<commit_before>// SystemInfo-Win32.cpp
//
// Copyright 2013 tomas <tomasp@videotron.ca>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.

#include <orion/SystemInfo.h>

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif

#include <windows.h>
#include <lmcons.h>   /* For UNLEN */
#include <process.h>

#if 0 //ndef __MINGW64__
#include <ddk/ntifs.h>

typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
LARGE_INTEGER IdleTime;
   LARGE_INTEGER KernelTime;
   LARGE_INTEGER UserTime;
   LARGE_INTEGER DpcTime;
   LARGE_INTEGER InterruptTime;
   ULONG InterruptCount;
} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;
#else
#include <winternl.h>
#endif

#include <psapi.h>

#include <orion/StringUtils.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))

namespace orion
{
namespace systeminfo
{

//--------------------------------------------------------------------
void get_loaded_modules(unsigned long process_id, ModuleList& modules)
{
   DWORD cbNeeded;

   // Get a list of all the modules in this process.
   HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION |
                                       PROCESS_VM_READ,
                                       FALSE,
                                       process_id);
   if (process_handle == nullptr)
       return;

   HMODULE module_handles[1024];

   if (EnumProcessModulesEx(process_handle, module_handles, sizeof(module_handles), &cbNeeded, LIST_MODULES_ALL))
   {
      for (int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
      {
         wchar_t module_name[MAX_PATH];

         // Get the full path to the module's file.
         if (GetModuleFileNameExW(process_handle, module_handles[i], module_name, sizeof(module_name)))
         {
            // Print the module name and handle value.
            modules.push_back(wstring_to_utf8(module_name));
         }
      }
   }
   CloseHandle(process_handle);
}

std::string get_cpu_model()
{
   const uint32_t max_length = 4096;

   DWORD   type = REG_SZ;
   HKEY    hKey = nullptr;
   DWORD   length = max_length;
   wchar_t value[max_length];

   ZeroMemory(value, max_length);

   const wchar_t* keyToOpen = L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0";
   const wchar_t* valueToFind = L"ProcessorNameString";

   RegOpenKeyExW(HKEY_LOCAL_MACHINE, keyToOpen, 0, KEY_READ, &hKey);
   RegQueryValueExW(hKey, valueToFind, nullptr, &type, (LPBYTE)&value, &length);
   RegCloseKey(hKey);

   std::string cpuName = wstring_to_utf8(value);

   SYSTEM_INFO sysinfo;
   ZeroMemory(&sysinfo, sizeof(SYSTEM_INFO));
   GetSystemInfo(&sysinfo);

   const uint64_t cpuThreadCount = sysinfo.dwNumberOfProcessors;
   std::string cpuInfo = cpuName + " (" + std::to_string(cpuThreadCount);

   if (cpuThreadCount == 1)
      cpuInfo.append(" thread)");
   else
      cpuInfo.append(" threads)");

   return cpuInfo;
}

std::vector<CpuInfo> get_cpu_info()
{
   std::vector<CpuInfo> cpu_infos;

   SYSTEM_INFO system_info;
   ZeroMemory(&system_info, sizeof(SYSTEM_INFO));

   GetSystemInfo(&system_info);

   int32_t cpu_count = system_info.dwNumberOfProcessors;

   SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* sppi = nullptr;
   ULONG result_size;

   DWORD sppi_size = cpu_count * sizeof(*sppi);
   sppi = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION*)malloc(sppi_size);

   NTSTATUS status = NtQuerySystemInformation(SystemProcessorPerformanceInformation,
                                              sppi,
                                              sppi_size,
                                              &result_size);

   if (not NT_SUCCESS(status))
   {
      // err = RtlNtStatusToDosError(status);
      RtlNtStatusToDosError(status);
      free(sppi);
      return cpu_infos;
   }

   for (int32_t i = 0; i < cpu_count; i++)
   {
      WCHAR key_name[128];
      HKEY processor_key;

      int len = _snwprintf(key_name,
                           ARRAY_SIZE(key_name),
                           L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d", i);

      DWORD ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key_name, 0, KEY_QUERY_VALUE, &processor_key);

      if (ret != ERROR_SUCCESS)
      {
         // err = GetLastError();
         // free(sppi);
      }

      DWORD cpu_speed;
      DWORD cpu_speed_size = sizeof(cpu_speed);

      ret = RegQueryValueExW(processor_key, L"~MHz", NULL, NULL, (BYTE*) &cpu_speed, &cpu_speed_size);

      if (ret != ERROR_SUCCESS)
      {
         // err = GetLastError();
         // free(sppi);
         // RegCloseKey(processor_key);
      }

      WCHAR cpu_brand[256];
      DWORD cpu_brand_size = sizeof(cpu_brand);

      ret = RegQueryValueExW(processor_key, L"ProcessorNameString", NULL, NULL, (BYTE*) &cpu_brand, &cpu_brand_size);

      if (ret != ERROR_SUCCESS)
      {
         // err = GetLastError();
         // free(sppi);
         // RegCloseKey(processor_key);
      }

      RegCloseKey(processor_key);

      CpuTimes cpu_times;

      cpu_times.user = sppi[i].UserTime.QuadPart / 10000;
      cpu_times.nice = 0;
      cpu_times.sys  = (sppi[i].KernelTime.QuadPart - sppi[i].IdleTime.QuadPart) / 10000;
      cpu_times.idle = sppi[i].IdleTime.QuadPart / 10000;
#if 0 //ndef __MINGW64__
      cpu_times.irq  = sppi[i].InterruptTime.QuadPart / 10000;
#else
      cpu_times.irq  = sppi[i].Reserved1[0].QuadPart / 10000;
#endif

      len = WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), NULL, 0, NULL, NULL);

      if (len == 0)
      {
         // err = GetLastError();
         // free(sppi);
      }

      char* model = new char[len];

      len = WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), model, len, NULL, NULL);

      if (len == 0)
      {
         // err = GetLastError();
         // free(sppi);
      }

      CpuInfo cpu_info(model, cpu_speed, cpu_times);

      cpu_infos.push_back(cpu_info);

      delete [] model;
   }

   free(sppi);

   return cpu_infos;
}

std::string get_os_version()
{
   OSVERSIONINFOEX osvi;

   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

   // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
   // If that fails, try using the OSVERSIONINFO structure.
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

   bool os_version_info_ex = GetVersionExW((OSVERSIONINFO*) &osvi);

   if (not os_version_info_ex)
   {
      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
      if (not GetVersionEx((OSVERSIONINFO*) &osvi))
         return "";
   }

   if (osvi.dwMajorVersion    == 5 and
       osvi.dwMinorVersion    == 1 and
       osvi.wServicePackMajor == 2 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows XP, Service Pack 2";

   if (osvi.dwMajorVersion    == 5 and
       osvi.dwMinorVersion    == 1 and
       osvi.wServicePackMajor == 3 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows XP, Service Pack 3";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 0 and
       osvi.wServicePackMajor == 1 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows Vista, Service Pack 1";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 0 and
       osvi.wServicePackMajor == 2 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows Vista, Service Pack 2";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 0)
      return "Microsoft Windows Vista";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 1 and
       osvi.wServicePackMajor == 1 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows 7, Service Pack 1";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 1)
      return "Microsoft Windows 7";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 2)
      return "Microsoft Windows 8";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 3)
      return "Microsoft Windows 8.1";

   return "Microsoft Windows";
}

std::string get_host_name()
{
   wchar_t hostname[100];
   DWORD size = sizeof (hostname);
   bool hostname_fail = not GetComputerNameW(hostname, &size);

   return hostname_fail ? "localhost" : wstring_to_utf8(hostname);
}

std::string get_user_name()
{
   std::string user_name;

   uint32_t len = UNLEN + 1;
   wchar_t  buffer[UNLEN + 1];

   if (GetUserNameW(buffer, (LPDWORD) &len))
   {
      user_name = wstring_to_utf8(buffer);
   }
   return user_name;
}

int get_process_id()
{
   return GetCurrentProcessId();
}

std::string get_program_name()
{
   HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION |
                                       PROCESS_VM_READ,
                                       FALSE, get_process_id());
   if (process_handle == nullptr)
       return "";

   wchar_t module_name[MAX_PATH];

   GetModuleFileNameEx(process_handle,
                       nullptr,
                       module_name, sizeof(module_name));

   CloseHandle(process_handle);

   return wstring_to_utf8(module_name);
}

void get_loadavg(double avg[3])
{
   avg[0] = avg[1] = avg[2] = 0;
}

uint64_t get_free_memory()
{
   MEMORYSTATUSEX memory_status;
   memory_status.dwLength = sizeof(memory_status);

   if (not GlobalMemoryStatusEx(&memory_status))
   {
      return -1;
   }

   return static_cast<uint64_t>(memory_status.ullAvailPhys);

}

uint64_t get_total_memory()
{
   MEMORYSTATUSEX memory_status;
   memory_status.dwLength = sizeof(memory_status);

   if (not GlobalMemoryStatusEx(&memory_status))
   {
      return -1;
   }

  return static_cast<uint64_t>(memory_status.ullTotalPhys);

}

} // namespace systeminfo
} // namespace orion
<commit_msg>Fix compilation errors with gcc.<commit_after>// SystemInfo-Win32.cpp
//
// Copyright 2013 tomas <tomasp@videotron.ca>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.

#include <orion/SystemInfo.h>

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif

#include <windows.h>
#include <lmcons.h>   /* For UNLEN */
#include <process.h>

#if 0 //ndef __MINGW64__
#include <ddk/ntifs.h>

typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
LARGE_INTEGER IdleTime;
   LARGE_INTEGER KernelTime;
   LARGE_INTEGER UserTime;
   LARGE_INTEGER DpcTime;
   LARGE_INTEGER InterruptTime;
   ULONG InterruptCount;
} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;
#else
#include <winternl.h>
#endif

#include <psapi.h>

#include <orion/StringUtils.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))

namespace orion
{
namespace systeminfo
{

//--------------------------------------------------------------------
void get_loaded_modules(unsigned long process_id, ModuleList& modules)
{
   DWORD cbNeeded;

   // Get a list of all the modules in this process.
   HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION |
                                       PROCESS_VM_READ,
                                       FALSE,
                                       process_id);
   if (process_handle == nullptr)
       return;

   HMODULE module_handles[1024];

   if (EnumProcessModulesEx(process_handle, module_handles, sizeof(module_handles), &cbNeeded, LIST_MODULES_ALL))
   {
      for (int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
      {
         wchar_t module_name[MAX_PATH];

         // Get the full path to the module's file.
         if (GetModuleFileNameExW(process_handle, module_handles[i], module_name, sizeof(module_name)))
         {
            // Print the module name and handle value.
            modules.push_back(wstring_to_utf8(module_name));
         }
      }
   }
   CloseHandle(process_handle);
}

std::string get_cpu_model()
{
   const uint32_t max_length = 4096;

   DWORD   type = REG_SZ;
   HKEY    hKey = nullptr;
   DWORD   length = max_length;
   wchar_t value[max_length];

   ZeroMemory(value, max_length);

   const wchar_t* keyToOpen = L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0";
   const wchar_t* valueToFind = L"ProcessorNameString";

   RegOpenKeyExW(HKEY_LOCAL_MACHINE, keyToOpen, 0, KEY_READ, &hKey);
   RegQueryValueExW(hKey, valueToFind, nullptr, &type, (LPBYTE)&value, &length);
   RegCloseKey(hKey);

   std::string cpuName = wstring_to_utf8(value);

   SYSTEM_INFO sysinfo;
   ZeroMemory(&sysinfo, sizeof(SYSTEM_INFO));
   GetSystemInfo(&sysinfo);

   const uint64_t cpuThreadCount = sysinfo.dwNumberOfProcessors;
   std::string cpuInfo = cpuName + " (" + std::to_string(cpuThreadCount);

   if (cpuThreadCount == 1)
      cpuInfo.append(" thread)");
   else
      cpuInfo.append(" threads)");

   return cpuInfo;
}

std::vector<CpuInfo> get_cpu_info()
{
   std::vector<CpuInfo> cpu_infos;

   SYSTEM_INFO system_info;
   ZeroMemory(&system_info, sizeof(SYSTEM_INFO));

   GetSystemInfo(&system_info);

   int32_t cpu_count = system_info.dwNumberOfProcessors;

   SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* sppi = nullptr;
   ULONG result_size;

   DWORD sppi_size = cpu_count * sizeof(*sppi);
   sppi = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION*)malloc(sppi_size);

   NTSTATUS status = NtQuerySystemInformation(SystemProcessorPerformanceInformation,
                                              sppi,
                                              sppi_size,
                                              &result_size);

   if (not NT_SUCCESS(status))
   {
      // err = RtlNtStatusToDosError(status);
      RtlNtStatusToDosError(status);
      free(sppi);
      return cpu_infos;
   }

   for (int32_t i = 0; i < cpu_count; i++)
   {
      WCHAR key_name[128];
      HKEY processor_key;

      int len = _snwprintf(key_name,
                           ARRAY_SIZE(key_name),
                           L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d", i);

      DWORD ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key_name, 0, KEY_QUERY_VALUE, &processor_key);

      if (ret != ERROR_SUCCESS)
      {
         // err = GetLastError();
         // free(sppi);
      }

      DWORD cpu_speed;
      DWORD cpu_speed_size = sizeof(cpu_speed);

      ret = RegQueryValueExW(processor_key, L"~MHz", NULL, NULL, (BYTE*) &cpu_speed, &cpu_speed_size);

      if (ret != ERROR_SUCCESS)
      {
         // err = GetLastError();
         // free(sppi);
         // RegCloseKey(processor_key);
      }

      WCHAR cpu_brand[256];
      DWORD cpu_brand_size = sizeof(cpu_brand);

      ret = RegQueryValueExW(processor_key, L"ProcessorNameString", NULL, NULL, (BYTE*) &cpu_brand, &cpu_brand_size);

      if (ret != ERROR_SUCCESS)
      {
         // err = GetLastError();
         // free(sppi);
         // RegCloseKey(processor_key);
      }

      RegCloseKey(processor_key);

      CpuTimes cpu_times;

      cpu_times.user = sppi[i].UserTime.QuadPart / 10000;
      cpu_times.nice = 0;
      cpu_times.sys  = (sppi[i].KernelTime.QuadPart - sppi[i].IdleTime.QuadPart) / 10000;
      cpu_times.idle = sppi[i].IdleTime.QuadPart / 10000;
#if 0 //ndef __MINGW64__
      cpu_times.irq  = sppi[i].InterruptTime.QuadPart / 10000;
#else
      cpu_times.irq  = sppi[i].Reserved1[0].QuadPart / 10000;
#endif

      len = WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), NULL, 0, NULL, NULL);

      if (len == 0)
      {
         // err = GetLastError();
         // free(sppi);
      }

      char* model = new char[len];

      len = WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), model, len, NULL, NULL);

      if (len == 0)
      {
         // err = GetLastError();
         // free(sppi);
      }

      CpuInfo cpu_info(model, cpu_speed, cpu_times);

      cpu_infos.push_back(cpu_info);

      delete [] model;
   }

   free(sppi);

   return cpu_infos;
}

std::string get_os_version()
{
   OSVERSIONINFOEXW osvi;

   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXW));

   // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
   // If that fails, try using the OSVERSIONINFO structure.
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);

   bool os_version_info_ex = GetVersionExW((OSVERSIONINFOW*) &osvi);

   if (not os_version_info_ex)
   {
      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
      if (not GetVersionExW((OSVERSIONINFOW*) &osvi))
         return "";
   }

   if (osvi.dwMajorVersion    == 5 and
       osvi.dwMinorVersion    == 1 and
       osvi.wServicePackMajor == 2 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows XP, Service Pack 2";

   if (osvi.dwMajorVersion    == 5 and
       osvi.dwMinorVersion    == 1 and
       osvi.wServicePackMajor == 3 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows XP, Service Pack 3";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 0 and
       osvi.wServicePackMajor == 1 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows Vista, Service Pack 1";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 0 and
       osvi.wServicePackMajor == 2 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows Vista, Service Pack 2";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 0)
      return "Microsoft Windows Vista";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 1 and
       osvi.wServicePackMajor == 1 and
       osvi.wServicePackMinor == 0)
      return "Microsoft Windows 7, Service Pack 1";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 1)
      return "Microsoft Windows 7";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 2)
      return "Microsoft Windows 8";

   if (osvi.dwMajorVersion    == 6 and
       osvi.dwMinorVersion    == 3)
      return "Microsoft Windows 8.1";

   return "Microsoft Windows";
}

std::string get_host_name()
{
   wchar_t hostname[100];
   DWORD size = sizeof (hostname);
   bool hostname_fail = not GetComputerNameW(hostname, &size);

   return hostname_fail ? "localhost" : wstring_to_utf8(hostname);
}

std::string get_user_name()
{
   std::string user_name;

   uint32_t len = UNLEN + 1;
   wchar_t  buffer[UNLEN + 1];

   if (GetUserNameW(buffer, (LPDWORD) &len))
   {
      user_name = wstring_to_utf8(buffer);
   }
   return user_name;
}

int get_process_id()
{
   return GetCurrentProcessId();
}

std::string get_program_name()
{
   HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION |
                                       PROCESS_VM_READ,
                                       FALSE, get_process_id());
   if (process_handle == nullptr)
       return "";

   wchar_t module_name[MAX_PATH];

   GetModuleFileNameExW(process_handle,
                        nullptr,
                        module_name, sizeof(module_name));

   CloseHandle(process_handle);

   return wstring_to_utf8(module_name);
}

void get_loadavg(double avg[3])
{
   avg[0] = avg[1] = avg[2] = 0;
}

uint64_t get_free_memory()
{
   MEMORYSTATUSEX memory_status;
   memory_status.dwLength = sizeof(memory_status);

   if (not GlobalMemoryStatusEx(&memory_status))
   {
      return -1;
   }

   return static_cast<uint64_t>(memory_status.ullAvailPhys);

}

uint64_t get_total_memory()
{
   MEMORYSTATUSEX memory_status;
   memory_status.dwLength = sizeof(memory_status);

   if (not GlobalMemoryStatusEx(&memory_status))
   {
      return -1;
   }

  return static_cast<uint64_t>(memory_status.ullTotalPhys);

}

} // namespace systeminfo
} // namespace orion
<|endoftext|>


<commit_before>#include <cmath>

#include "ingameelements/weapons/hammer.h"
#include "renderer.h"
#include "ingameelements/heroes/reinhardt.h"
#include "ingameelements/projectiles/firestrike.h"

#include "engine.h"

void Hammer::init(uint64_t id_, Gamestate &state, EntityPtr owner_)
{
    Weapon::init(id_, state, owner_);

    barrierptr = state.make_entity<ReinhardtShield>(state, team, owner_);

    firestrikeanim.init(herofolder()+"firestrikebackarm/");
    firestrikeanim.active(false);
    firestrikedelay.init(firestrikeanim.timer.duration * 0.5,
                         std::bind(&Hammer::createfirestrike, this, std::placeholders::_1));
    firestrikedelay.active = false;
}

void Hammer::renderbehind(Renderer &renderer, Gamestate &state)
{
    std::string mainsprite;
    Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
    if (firestrikeanim.active())
    {
        mainsprite = firestrikeanim.getframepath();
    }
    else if (barrier(state).active)
    {
        mainsprite = herofolder()+"shield/back";

    }
    else
    {
        mainsprite = herofolder()+"arm/back";
    }
    ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
    double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
    double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
    double rel_x = (x - renderer.cam_x)*renderer.zoom;
    double rel_y = (y - renderer.cam_y)*renderer.zoom;
    double attachpt_x = getbackattachpoint_x(state)*renderer.zoom;
    double attachpt_y = getbackattachpoint_y(state)*renderer.zoom;

    ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
    ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);

    al_set_target_bitmap(renderer.midground);
    if (c.weaponvisible(state))
    {
        if (c.isflipped)
        {
            al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y,
                                          -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y,
                                                    -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
            }
        }
        else
        {
            al_draw_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y, aimdirection*barrier(state).active, 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, aimdirection*barrier(state).active, 0);
            }
        }
    }
}

void Hammer::render(Renderer &renderer, Gamestate &state)
{
    std::string mainsprite;
    Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
    if (firestrikeanim.active())
    {
        mainsprite = herofolder()+"firestrikefrontarm/"+std::to_string(firestrikeanim.getframe());
    }
    else if (barrier(state).active)
    {
        mainsprite = herofolder()+"shield/front";

    }
    else
    {
        mainsprite = herofolder()+"arm/front";
    }
    ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
    double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
    double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
    double rel_x = (x - renderer.cam_x)*renderer.zoom;
    double rel_y = (y - renderer.cam_y)*renderer.zoom;
    double attachpt_x = getattachpoint_x(state)*renderer.zoom;
    double attachpt_y = getattachpoint_y(state)*renderer.zoom;

    ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
    ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);

    al_set_target_bitmap(renderer.midground);
    if (c.weaponvisible(state))
    {
        if (c.isflipped)
        {
            al_draw_scaled_rotated_bitmap(sprite, -attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
            }
        }
        else
        {
            al_draw_bitmap(sprite, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_bitmap(outline, outlinecolor, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
            }
        }
    }

    barrier(state).render(renderer, state);
}

void Hammer::beginstep(Gamestate &state, double frametime)
{
    Weapon::beginstep(state, frametime);
    barrier(state).beginstep(state, frametime);
    firestrikeanim.update(state, frametime);
    firestrikedelay.update(state, frametime);
}

void Hammer::midstep(Gamestate &state, double frametime)
{
    Weapon::midstep(state, frametime);
    barrier(state).midstep(state, frametime);
}

void Hammer::endstep(Gamestate &state, double frametime)
{
    Weapon::endstep(state, frametime);
    barrier(state).endstep(state, frametime);
}

void Hammer::wantfireprimary(Gamestate &state)
{
    if (state.engine.isserver and not firinganim.active() and not firestrikeanim.active())
    {
        fireprimary(state);
        state.engine.sendbuffer.write<uint8_t>(PRIMARY_FIRED);
        state.engine.sendbuffer.write<uint8_t>(state.findplayerid(owner));
    }
}

void Hammer::fireprimary(Gamestate &state)
{
    firinganim.reset();
    firinganim.active(true);
}

void Hammer::wantfiresecondary(Gamestate &state)
{
    // Do nothing
}

void Hammer::firesecondary(Gamestate &state)
{
    // Do nothing
}

void Hammer::createfirestrike(Gamestate &state)
{
    Firestrike &firestrike = state.get<Firestrike&>(state.make_entity<Firestrike>(state, owner));
    firestrike.x = x + std::cos(aimdirection) * 40;
    firestrike.y = y + std::sin(aimdirection) * 40;
    firestrike.hspeed = firestrike.SPEED * std::cos(aimdirection);
    firestrike.vspeed = firestrike.SPEED * std::sin(aimdirection);
}

double Hammer::getattachpoint_x(Gamestate &state)
{
    return 0;
}

double Hammer::getattachpoint_y(Gamestate &state)
{
    return 8;
}

double Hammer::getbackattachpoint_x(Gamestate &state)
{
    if (barrier(state).active)
    {
        return 6 * (state.get<Player&>(owner).getcharacter(state).isflipped ? 1:-1);
    }
    else
    {
        return 0;
    }
}

double Hammer::getbackattachpoint_y(Gamestate &state)
{
    if (barrier(state).active)
    {
        return 10;
    }
    else
    {
        return 8;
    }
}

ReinhardtShield& Hammer::barrier(Gamestate &state)
{
    return state.get<ReinhardtShield>(barrierptr);
}

void Hammer::destroy(Gamestate &state)
{
    barrier(state).destroy(state);
    Weapon::destroy(state);
}

void Hammer::interpolate(Entity &prev_entity, Entity &next_entity, double alpha)
{
    Weapon::interpolate(prev_entity, next_entity, alpha);

    Hammer &prev_e = static_cast<Hammer&>(prev_entity);
    Hammer &next_e = static_cast<Hammer&>(next_entity);

    firestrikeanim.interpolate(prev_e.firestrikeanim, next_e.firestrikeanim, alpha);
    firestrikedelay.interpolate(prev_e.firestrikedelay, next_e.firestrikedelay, alpha);
}<commit_msg>Removed the ability to firestrike through walls.<commit_after>#include <cmath>

#include "ingameelements/weapons/hammer.h"
#include "renderer.h"
#include "ingameelements/heroes/reinhardt.h"
#include "ingameelements/projectiles/firestrike.h"

#include "engine.h"

void Hammer::init(uint64_t id_, Gamestate &state, EntityPtr owner_)
{
    Weapon::init(id_, state, owner_);

    barrierptr = state.make_entity<ReinhardtShield>(state, team, owner_);

    firestrikeanim.init(herofolder()+"firestrikebackarm/");
    firestrikeanim.active(false);
    firestrikedelay.init(firestrikeanim.timer.duration * 0.5,
                         std::bind(&Hammer::createfirestrike, this, std::placeholders::_1));
    firestrikedelay.active = false;
}

void Hammer::renderbehind(Renderer &renderer, Gamestate &state)
{
    std::string mainsprite;
    Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
    if (firestrikeanim.active())
    {
        mainsprite = firestrikeanim.getframepath();
    }
    else if (barrier(state).active)
    {
        mainsprite = herofolder()+"shield/back";

    }
    else
    {
        mainsprite = herofolder()+"arm/back";
    }
    ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
    double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
    double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
    double rel_x = (x - renderer.cam_x)*renderer.zoom;
    double rel_y = (y - renderer.cam_y)*renderer.zoom;
    double attachpt_x = getbackattachpoint_x(state)*renderer.zoom;
    double attachpt_y = getbackattachpoint_y(state)*renderer.zoom;

    ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
    ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);

    al_set_target_bitmap(renderer.midground);
    if (c.weaponvisible(state))
    {
        if (c.isflipped)
        {
            al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y,
                                          -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y,
                                                    -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
            }
        }
        else
        {
            al_draw_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y, aimdirection*barrier(state).active, 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, aimdirection*barrier(state).active, 0);
            }
        }
    }
}

void Hammer::render(Renderer &renderer, Gamestate &state)
{
    std::string mainsprite;
    Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
    if (firestrikeanim.active())
    {
        mainsprite = herofolder()+"firestrikefrontarm/"+std::to_string(firestrikeanim.getframe());
    }
    else if (barrier(state).active)
    {
        mainsprite = herofolder()+"shield/front";

    }
    else
    {
        mainsprite = herofolder()+"arm/front";
    }
    ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
    double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
    double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
    double rel_x = (x - renderer.cam_x)*renderer.zoom;
    double rel_y = (y - renderer.cam_y)*renderer.zoom;
    double attachpt_x = getattachpoint_x(state)*renderer.zoom;
    double attachpt_y = getattachpoint_y(state)*renderer.zoom;

    ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
    ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);

    al_set_target_bitmap(renderer.midground);
    if (c.weaponvisible(state))
    {
        if (c.isflipped)
        {
            al_draw_scaled_rotated_bitmap(sprite, -attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
            }
        }
        else
        {
            al_draw_bitmap(sprite, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
            if (state.get<Player>(renderer.myself).team != team)
            {
                // Draw enemy outline
                al_draw_tinted_bitmap(outline, outlinecolor, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
            }
        }
    }

    barrier(state).render(renderer, state);
}

void Hammer::beginstep(Gamestate &state, double frametime)
{
    Weapon::beginstep(state, frametime);
    barrier(state).beginstep(state, frametime);
    firestrikeanim.update(state, frametime);
    firestrikedelay.update(state, frametime);
}

void Hammer::midstep(Gamestate &state, double frametime)
{
    Weapon::midstep(state, frametime);
    barrier(state).midstep(state, frametime);
}

void Hammer::endstep(Gamestate &state, double frametime)
{
    Weapon::endstep(state, frametime);
    barrier(state).endstep(state, frametime);
}

void Hammer::wantfireprimary(Gamestate &state)
{
    if (state.engine.isserver and not firinganim.active() and not firestrikeanim.active())
    {
        fireprimary(state);
        state.engine.sendbuffer.write<uint8_t>(PRIMARY_FIRED);
        state.engine.sendbuffer.write<uint8_t>(state.findplayerid(owner));
    }
}

void Hammer::fireprimary(Gamestate &state)
{
    firinganim.reset();
    firinganim.active(true);
}

void Hammer::wantfiresecondary(Gamestate &state)
{
    // Do nothing
}

void Hammer::firesecondary(Gamestate &state)
{
    // Do nothing
}

void Hammer::createfirestrike(Gamestate &state)
{
    Firestrike &firestrike = state.get<Firestrike&>(state.make_entity<Firestrike>(state, owner));
    firestrike.x = x + std::cos(aimdirection) * 40;
    firestrike.y = y + std::sin(aimdirection) * 40;
    firestrike.hspeed = firestrike.SPEED * std::cos(aimdirection);
    firestrike.vspeed = firestrike.SPEED * std::sin(aimdirection);

    if (state.currentmap->collideline(x, y, firestrike.x, firestrike.y))
    {
        firestrike.destroy(state);
    }
}

double Hammer::getattachpoint_x(Gamestate &state)
{
    return 0;
}

double Hammer::getattachpoint_y(Gamestate &state)
{
    return 8;
}

double Hammer::getbackattachpoint_x(Gamestate &state)
{
    if (barrier(state).active)
    {
        return 6 * (state.get<Player&>(owner).getcharacter(state).isflipped ? 1:-1);
    }
    else
    {
        return 0;
    }
}

double Hammer::getbackattachpoint_y(Gamestate &state)
{
    if (barrier(state).active)
    {
        return 10;
    }
    else
    {
        return 8;
    }
}

ReinhardtShield& Hammer::barrier(Gamestate &state)
{
    return state.get<ReinhardtShield>(barrierptr);
}

void Hammer::destroy(Gamestate &state)
{
    barrier(state).destroy(state);
    Weapon::destroy(state);
}

void Hammer::interpolate(Entity &prev_entity, Entity &next_entity, double alpha)
{
    Weapon::interpolate(prev_entity, next_entity, alpha);

    Hammer &prev_e = static_cast<Hammer&>(prev_entity);
    Hammer &next_e = static_cast<Hammer&>(next_entity);

    firestrikeanim.interpolate(prev_e.firestrikeanim, next_e.firestrikeanim, alpha);
    firestrikedelay.interpolate(prev_e.firestrikedelay, next_e.firestrikedelay, alpha);
}<|endoftext|>


<commit_before>
#pragma once

#include "quantities/named_quantities.hpp"

namespace principia {
namespace numerics {
namespace internal_arrays {

using quantities::Quotient;
using quantities::SquareRoot;

template<typename T>
struct CholeskyGenerator;

template<typename Scalar, template<typename S> typename UpperTriangularMatrix>
struct CholeskyGenerator<UpperTriangularMatrix<Scalar>> {
  using type = UpperTriangularMatrix<SquareRoot<Scalar>>;
};

template<typename Scalar, int columns,
         template<typename S, int c> typename UpperTriangularMatrix>
struct CholeskyGenerator<UpperTriangularMatrix<Scalar, columns>> {
  using type = UpperTriangularMatrix<SquareRoot<Scalar>, columns>;
};

// If A is the upper half of a symmetric positive definite matrix, returns R so
// that A = ᵗR R.
template<typename UpperTriangularMatrix>
typename CholeskyGenerator<UpperTriangularMatrix>::type
CholeskyDecomposition(UpperTriangularMatrix const& A);

// If A is the upper half of a symmetric matrix, returns R and D so that
// A = ᵗR D R.  The diagonal matrix is represented as a vector.
template<typename Scalar,
         template<typename S> typename UpperTriangularMatrix,
         template<typename S> typename Vector>
void ᵗRDRDecomposition(UpperTriangularMatrix<Scalar> const& A,
                       UpperTriangularMatrix<double>& R,
                       Vector<Scalar>& D);

// Returns x such that U x = b.
template<typename LScalar, typename RScalar,
         template<typename S> typename UpperTriangularMatrix,
         template<typename S> typename Vector>
Vector<Quotient<RScalar, LScalar>> BackSubstitution(
    UpperTriangularMatrix<LScalar> const& U,
    Vector<RScalar> const& b);

// Return x such that L x = b.
template<typename LScalar, typename RScalar,
         template<typename S> typename LowerTriangularMatrix,
         template<typename S> typename Vector>
Vector<Quotient<RScalar, LScalar>> ForwardSubstitution(
    LowerTriangularMatrix<LScalar> const& L,
    Vector<RScalar> const& b);

}  // namespace internal_arrays

using internal_arrays::BackSubstitution;
using internal_arrays::CholeskyDecomposition;
using internal_arrays::ForwardSubstitution;
using internal_arrays::ᵗRDRDecomposition;

}  // namespace numerics
}  // namespace principia

#include "numerics/matrix_computations_body.hpp"
<commit_msg>RDR generator.<commit_after>
#pragma once

#include "quantities/named_quantities.hpp"

namespace principia {
namespace numerics {
namespace internal_arrays {

using quantities::Quotient;
using quantities::SquareRoot;

template<typename T>
struct CholeskyGenerator;

template<typename Scalar, template<typename S> typename UpperTriangularMatrix>
struct CholeskyGenerator<UpperTriangularMatrix<Scalar>> {
  using type = UpperTriangularMatrix<SquareRoot<Scalar>>;
};

template<typename Scalar, int columns,
         template<typename S, int c> typename UpperTriangularMatrix>
struct CholeskyGenerator<UpperTriangularMatrix<Scalar, columns>> {
  using type = UpperTriangularMatrix<SquareRoot<Scalar>, columns>;
};

template<typename T1, typename T2>
struct ᵗRDRGenerator;

template<typename Scalar,
         template<typename S> typename Vector,
         template<typename S> typename UpperTriangularMatrix>
struct ᵗRDRGenerator<UpperTriangularMatrix<Scalar>, Vector<Scalar>> {
  struct type {
    UpperTriangularMatrix<double> R;
    Vector<Scalar> D;
  };
};

template<typename Scalar, int columns,
         template<typename S, int c> typename Vector,
         template<typename S, int c> typename UpperTriangularMatrix>
struct ᵗRDRGenerator<UpperTriangularMatrix<Scalar, columns>,
                     Vector<Scalar, columns>> {
  struct type {
    UpperTriangularMatrix<double, columns> R;
    Vector<Scalar, columns>& D;
  };
};

// If A is the upper half of a symmetric positive definite matrix, returns R so
// that A = ᵗR R.
template<typename UpperTriangularMatrix>
typename CholeskyGenerator<UpperTriangularMatrix>::type
CholeskyDecomposition(UpperTriangularMatrix const& A);

// If A is the upper half of a symmetric matrix, returns R and D so that
// A = ᵗR D R.  The diagonal matrix is represented as a vector.
template<typename Vector, typename UpperTriangularMatrix>
typename ᵗRDRGenerator<Vector, UpperTriangularMatrix>::type
ᵗRDRDecomposition(UpperTriangularMatrix const& A);

// Returns x such that U x = b.
template<typename LScalar, typename RScalar,
         template<typename S> typename UpperTriangularMatrix,
         template<typename S> typename Vector>
Vector<Quotient<RScalar, LScalar>> BackSubstitution(
    UpperTriangularMatrix<LScalar> const& U,
    Vector<RScalar> const& b);

// Return x such that L x = b.
template<typename LScalar, typename RScalar,
         template<typename S> typename LowerTriangularMatrix,
         template<typename S> typename Vector>
Vector<Quotient<RScalar, LScalar>> ForwardSubstitution(
    LowerTriangularMatrix<LScalar> const& L,
    Vector<RScalar> const& b);

}  // namespace internal_arrays

using internal_arrays::BackSubstitution;
using internal_arrays::CholeskyDecomposition;
using internal_arrays::ForwardSubstitution;
using internal_arrays::ᵗRDRDecomposition;

}  // namespace numerics
}  // namespace principia

#include "numerics/matrix_computations_body.hpp"
<|endoftext|>


<commit_before>/**
 * @File:   FootTrajectoryGenerator.cpp
 *
 * @author Xu, Yuan
 * foot trajectory for walking
 */

#include "FootTrajectoryGenerator.h"

using namespace std;

Pose3D FootTrajectorGenerator::genTrajectory(
  const Pose3D& oldFoot, const Pose3D& targetFoot,
  double cycle, double samplesDoubleSupport, double samplesSingleSupport, double extendDoubleSupport,
  double stepHeight, double footPitchOffset, double footYawOffset, double footRollOffset, double curveFactor)
{
  double doubleSupportEnd = samplesDoubleSupport / 2 + extendDoubleSupport;
  double doubleSupportBegin = samplesDoubleSupport / 2 + samplesSingleSupport;
  samplesSingleSupport -= extendDoubleSupport;

  if (cycle <= doubleSupportEnd)
  {
    return oldFoot;
  }
  else if (cycle <= doubleSupportBegin)
  {
    //      cout<<"foot stat 1"<<endl;
    double t = 1 - (doubleSupportBegin - cycle) / samplesSingleSupport;
    //        double xp = 10*t*t*t - 15*t*t*t*t + 6*t*t*t*t*t;
    //double xp = 1 / (1 + exp(-(t - 0.5) * curveFactor)); // this one has jumps for some values of curveFactor
    double xp = (1 - cos(t*Math::pi))*0.5;
    //        double xp = exp( -1 * exp(-10*(t-0.5)) );
    //        double yp = 16*t*t - 32*t*t*t + 16*t*t*t*t;
    //        cout<<"t = "<<t<<endl;
    t = t * Math::pi - Math::pi_2;
    //        double xp = (1+sin(t))*0.5;
    double yp = (1 + cos(t * 2))*0.5; //cos(t);
    //    if (t < 0) yp = cos(t);
    //        cout<<"t= "<<t<<" yp="<<yp<<endl;

    Pose3D foot;
    foot.translation.z = targetFoot.translation.z + yp*stepHeight;

    foot.translation.x = (1.0 - xp) * oldFoot.translation.x + xp * targetFoot.translation.x;
    foot.translation.y = (1.0 - xp) * oldFoot.translation.y + xp * targetFoot.translation.y;

    foot.rotation = RotationMatrix::getRotationX(footRollOffset * yp);
    foot.rotation.rotateY(Math::sgn(targetFoot.translation.x - oldFoot.translation.x) * footPitchOffset * yp);
    RotationMatrix rot = RotationMatrix::interpolate(oldFoot.rotation, targetFoot.rotation, xp);
    foot.rotation *= rot;

    return foot;
  }
  else
  {
    return targetFoot;
  }
}

Pose3D FootTrajectorGenerator::stepControl(
  const Pose3D& oldFoot,
  const Pose3D& targetFoot,
  double cycle,
  double samplesDoubleSupport,
  double samplesSingleSupport,
  double extendDoubleSupport,
  double stepHeight,
  double footPitchOffset,
  double footYawOffset,
  double footRollOffset,
  double curveFactor,
  double speedDirection
  )
{
  double doubleSupportEnd = samplesDoubleSupport / 2 + extendDoubleSupport;
  double doubleSupportBegin = samplesDoubleSupport / 2 + samplesSingleSupport;
  samplesSingleSupport -= extendDoubleSupport;

  if (cycle <= doubleSupportEnd)
  {
    return oldFoot;
  }
  else if (cycle <= doubleSupportBegin)
  {
    double t = 1 - (doubleSupportBegin - cycle) / samplesSingleSupport;
    //double xp = 1 / (1 + exp(-(t - 0.5) * curveFactor));// this one has jumps for some values of curveFactor
    double xp = (1 - cos(t*Math::pi))*0.5;
    t = t * Math::pi - Math::pi_2;
    double zp = (1 + cos(t * 2))*0.5;

    // TODO: optmize
    Pose3D speedTarget = targetFoot;
    speedTarget.translate(cos(speedDirection)*30, sin(speedDirection)*30, 0);
    vector<Vector2<double> > vecX;
    vecX.push_back(Vector2<double>(0, oldFoot.translation.x));
    vecX.push_back(Vector2<double>(1, targetFoot.translation.x));
    vecX.push_back(Vector2<double>(1.1, speedTarget.translation.x));
    CubicSpline theCubicSplineX;
    theCubicSplineX.init(vecX);

    vector<Vector2<double> > vecY;
    vecY.push_back(Vector2<double>(0, oldFoot.translation.y));
    vecY.push_back(Vector2<double>(1, targetFoot.translation.y));
    vecY.push_back(Vector2<double>(1.1, speedTarget.translation.y));
    CubicSpline theCubicSplineY;
    theCubicSplineY.init(vecY);

    Pose3D foot;
    foot.translation.z = targetFoot.translation.z + zp*stepHeight;

    foot.translation.x = theCubicSplineX.y(xp);
    foot.translation.y = theCubicSplineY.y(xp);

    foot.rotation = RotationMatrix::getRotationX(footRollOffset * zp);
    foot.rotation.rotateY(Math::sgn(targetFoot.translation.x - oldFoot.translation.x) * footPitchOffset * zp);
    RotationMatrix rot = RotationMatrix::interpolate(oldFoot.rotation, targetFoot.rotation, xp);
    foot.rotation *= rot;

    return foot;
  }
  else
  {
    return targetFoot;
  }
}
<commit_msg>feature: first idea for a better trajectory for a kick<commit_after>/**
 * @File:   FootTrajectoryGenerator.cpp
 *
 * @author Xu, Yuan
 * foot trajectory for walking
 */

#include "FootTrajectoryGenerator.h"

using namespace std;

Pose3D FootTrajectorGenerator::genTrajectory(
  const Pose3D& oldFoot, const Pose3D& targetFoot,
  double cycle, double samplesDoubleSupport, double samplesSingleSupport, double extendDoubleSupport,
  double stepHeight, double footPitchOffset, double footYawOffset, double footRollOffset, double curveFactor)
{
  double doubleSupportEnd = samplesDoubleSupport / 2 + extendDoubleSupport;
  double doubleSupportBegin = samplesDoubleSupport / 2 + samplesSingleSupport;
  samplesSingleSupport -= extendDoubleSupport;

  if (cycle <= doubleSupportEnd)
  {
    return oldFoot;
  }
  else if (cycle <= doubleSupportBegin)
  {
    double t = 1 - (doubleSupportBegin - cycle) / samplesSingleSupport;

    // parameter for the step curve
    // NOTE: xp is used to interpolate the motion in x/y-plane, while
    //       yp is for the mition in the z-axis
    double xp = (1 - cos(t*Math::pi))*0.5;
    double yp = (1 - cos(t*Math::pi2))*0.5;

    Pose3D foot;
    foot.translation.z = targetFoot.translation.z + yp*stepHeight;

    foot.translation.x = (1.0 - xp) * oldFoot.translation.x + xp * targetFoot.translation.x;
    foot.translation.y = (1.0 - xp) * oldFoot.translation.y + xp * targetFoot.translation.y;

    foot.rotation = RotationMatrix::getRotationX(footRollOffset * yp);
    foot.rotation.rotateY(Math::sgn(targetFoot.translation.x - oldFoot.translation.x) * footPitchOffset * yp);
    RotationMatrix rot = RotationMatrix::interpolate(oldFoot.rotation, targetFoot.rotation, xp);
    foot.rotation *= rot;

    return foot;
  }
  else
  {
    return targetFoot;
  }
}

Pose3D FootTrajectorGenerator::stepControl(
  const Pose3D& oldFoot,
  const Pose3D& targetFoot,
  double cycle,
  double samplesDoubleSupport,
  double samplesSingleSupport,
  double extendDoubleSupport,
  double stepHeight,
  double footPitchOffset,
  double footYawOffset,
  double footRollOffset,
  double curveFactor,
  double speedDirection
  )
{
  double doubleSupportEnd = samplesDoubleSupport / 2 + extendDoubleSupport;
  double doubleSupportBegin = samplesDoubleSupport / 2 + samplesSingleSupport;
  samplesSingleSupport -= extendDoubleSupport;

  if (cycle <= doubleSupportEnd)
  {
    return oldFoot;
  }
  else if (cycle <= doubleSupportBegin)
  {
    double t = 1 - (doubleSupportBegin - cycle) / samplesSingleSupport;
    //double xp = 1 / (1 + exp(-(t - 0.5) * curveFactor));// this one has jumps for some values of curveFactor
    double xp = (1 - cos(t*Math::pi))*0.5;
    double zp = (1 - cos(t*Math::pi2))*0.5;

    double s = 0.7;

    if(t < s) {
      xp = (1 - cos(t/s*Math::pi))*0.5;
    } else {
      xp = 1.0;
    }

    // TODO: optmize
    Pose3D speedTarget = targetFoot;
    speedTarget.translate(cos(speedDirection)*30, sin(speedDirection)*30, 0);
    vector<Vector2<double> > vecX;
    vecX.push_back(Vector2<double>(0, oldFoot.translation.x));
    vecX.push_back(Vector2<double>(1, targetFoot.translation.x));
    vecX.push_back(Vector2<double>(1.1, speedTarget.translation.x));
    CubicSpline theCubicSplineX;
    theCubicSplineX.init(vecX);

    vector<Vector2<double> > vecY;
    vecY.push_back(Vector2<double>(0, oldFoot.translation.y));
    vecY.push_back(Vector2<double>(1, targetFoot.translation.y));
    vecY.push_back(Vector2<double>(1.1, speedTarget.translation.y));
    CubicSpline theCubicSplineY;
    theCubicSplineY.init(vecY);

    Pose3D foot;
    foot.translation.z = targetFoot.translation.z + zp*stepHeight;

    foot.translation.x = theCubicSplineX.y(xp);
    foot.translation.y = theCubicSplineY.y(xp);

    foot.rotation = RotationMatrix::getRotationX(footRollOffset * zp);
    foot.rotation.rotateY(Math::sgn(targetFoot.translation.x - oldFoot.translation.x) * footPitchOffset * zp);
    RotationMatrix rot = RotationMatrix::interpolate(oldFoot.rotation, targetFoot.rotation, xp);
    foot.rotation *= rot;

    return foot;
  }
  else
  {
    return targetFoot;
  }
}
<|endoftext|>


<commit_before>//===-- asan_globals.cc ---------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Handle globals.
//===----------------------------------------------------------------------===//
#include "asan_interceptors.h"
#include "asan_internal.h"
#include "asan_mapping.h"
#include "asan_poisoning.h"
#include "asan_report.h"
#include "asan_stack.h"
#include "asan_stats.h"
#include "asan_thread.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_mutex.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_stackdepot.h"

namespace __asan {

typedef __asan_global Global;

struct ListOfGlobals {
  const Global *g;
  ListOfGlobals *next;
};

static BlockingMutex mu_for_globals(LINKER_INITIALIZED);
static LowLevelAllocator allocator_for_globals;
static ListOfGlobals *list_of_all_globals;

static const int kDynamicInitGlobalsInitialCapacity = 512;
struct DynInitGlobal {
  Global g;
  bool initialized;
};
typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
// Lazy-initialized and never deleted.
static VectorOfGlobals *dynamic_init_globals;

// We want to remember where a certain range of globals was registered.
struct GlobalRegistrationSite {
  u32 stack_id;
  Global *g_first, *g_last;
};
typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
static GlobalRegistrationSiteVector *global_registration_site_vector;

ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
  FastPoisonShadow(g->beg, g->size_with_redzone, value);
}

ALWAYS_INLINE void PoisonRedZones(const Global &g) {
  uptr aligned_size = RoundUpTo(g.size, SHADOW_GRANULARITY);
  FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
                   kAsanGlobalRedzoneMagic);
  if (g.size != aligned_size) {
    FastPoisonShadowPartialRightRedzone(
        g.beg + RoundDownTo(g.size, SHADOW_GRANULARITY),
        g.size % SHADOW_GRANULARITY,
        SHADOW_GRANULARITY,
        kAsanGlobalRedzoneMagic);
  }
}

const uptr kMinimalDistanceFromAnotherGlobal = 64;

bool IsAddressNearGlobal(uptr addr, const __asan_global &g) {
  if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;
  if (addr >= g.beg + g.size_with_redzone) return false;
  return true;
}

static void ReportGlobal(const Global &g, const char *prefix) {
  Report("%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu\n",
         prefix, &g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
         g.module_name, g.has_dynamic_init);
  if (g.location) {
    Report("  location (%p): name=%s[%p], %d %d\n", g.location,
           g.location->filename, g.location->filename, g.location->line_no,
           g.location->column_no);
  }
}

static bool DescribeOrGetInfoIfGlobal(uptr addr, uptr size, bool print,
                                      Global *output_global) {
  if (!flags()->report_globals) return false;
  BlockingMutexLock lock(&mu_for_globals);
  bool res = false;
  for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
    const Global &g = *l->g;
    if (print) {
      if (flags()->report_globals >= 2)
        ReportGlobal(g, "Search");
      res |= DescribeAddressRelativeToGlobal(addr, size, g);
    } else {
      if (IsAddressNearGlobal(addr, g)) {
        CHECK(output_global);
        *output_global = g;
        return true;
      }
    }
  }
  return res;
}

bool DescribeAddressIfGlobal(uptr addr, uptr size) {
  return DescribeOrGetInfoIfGlobal(addr, size, /* print */ true,
                                   /* output_global */ nullptr);
}

bool GetInfoForAddressIfGlobal(uptr addr, AddressDescription *descr) {
  Global g = {};
  if (DescribeOrGetInfoIfGlobal(addr, /* size */ 1, /* print */ false, &g)) {
    internal_strncpy(descr->name, g.name, descr->name_size);
    descr->region_address = g.beg;
    descr->region_size = g.size;
    descr->region_kind = "global";
    return true;
  }
  return false;
}

u32 FindRegistrationSite(const Global *g) {
  CHECK(global_registration_site_vector);
  for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
    GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
    if (g >= grs.g_first && g <= grs.g_last)
      return grs.stack_id;
  }
  return 0;
}

// Register a global variable.
// This function may be called more than once for every global
// so we store the globals in a map.
static void RegisterGlobal(const Global *g) {
  CHECK(asan_inited);
  if (flags()->report_globals >= 2)
    ReportGlobal(*g, "Added");
  CHECK(flags()->report_globals);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  if (flags()->detect_odr_violation) {
    // Try detecting ODR (One Definition Rule) violation, i.e. the situation
    // where two globals with the same name are defined in different modules.
    if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
      // This check may not be enough: if the first global is much larger
      // the entire redzone of the second global may be within the first global.
      for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
        if (g->beg == l->g->beg &&
            (flags()->detect_odr_violation >= 2 || g->size != l->g->size))
          ReportODRViolation(g, FindRegistrationSite(g),
                             l->g, FindRegistrationSite(l->g));
      }
    }
  }
  if (CanPoisonMemory())
    PoisonRedZones(*g);
  ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
  l->g = g;
  l->next = list_of_all_globals;
  list_of_all_globals = l;
  if (g->has_dynamic_init) {
    if (dynamic_init_globals == 0) {
      dynamic_init_globals = new(allocator_for_globals)
          VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
    }
    DynInitGlobal dyn_global = { *g, false };
    dynamic_init_globals->push_back(dyn_global);
  }
}

static void UnregisterGlobal(const Global *g) {
  CHECK(asan_inited);
  CHECK(flags()->report_globals);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  if (CanPoisonMemory())
    PoisonShadowForGlobal(g, 0);
  // We unpoison the shadow memory for the global but we do not remove it from
  // the list because that would require O(n^2) time with the current list
  // implementation. It might not be worth doing anyway.
}

void StopInitOrderChecking() {
  BlockingMutexLock lock(&mu_for_globals);
  if (!flags()->check_initialization_order || !dynamic_init_globals)
    return;
  flags()->check_initialization_order = false;
  for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
    DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
    const Global *g = &dyn_g.g;
    // Unpoison the whole global.
    PoisonShadowForGlobal(g, 0);
    // Poison redzones back.
    PoisonRedZones(*g);
  }
}

}  // namespace __asan

// ---------------------- Interface ---------------- {{{1
using namespace __asan;  // NOLINT

// Register an array of globals.
void __asan_register_globals(__asan_global *globals, uptr n) {
  if (!flags()->report_globals) return;
  GET_STACK_TRACE_FATAL_HERE;
  u32 stack_id = StackDepotPut(stack);
  BlockingMutexLock lock(&mu_for_globals);
  if (!global_registration_site_vector)
    global_registration_site_vector =
        new(allocator_for_globals) GlobalRegistrationSiteVector(128);
  GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
  global_registration_site_vector->push_back(site);
  if (flags()->report_globals >= 2) {
    PRINT_CURRENT_STACK();
    Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
  }
  for (uptr i = 0; i < n; i++) {
    RegisterGlobal(&globals[i]);
  }
}

// Unregister an array of globals.
// We must do this when a shared objects gets dlclosed.
void __asan_unregister_globals(__asan_global *globals, uptr n) {
  if (!flags()->report_globals) return;
  BlockingMutexLock lock(&mu_for_globals);
  for (uptr i = 0; i < n; i++) {
    UnregisterGlobal(&globals[i]);
  }
}

// This method runs immediately prior to dynamic initialization in each TU,
// when all dynamically initialized globals are unpoisoned.  This method
// poisons all global variables not defined in this TU, so that a dynamic
// initializer can only touch global variables in the same TU.
void __asan_before_dynamic_init(const char *module_name) {
  if (!flags()->check_initialization_order ||
      !CanPoisonMemory())
    return;
  bool strict_init_order = flags()->strict_init_order;
  CHECK(dynamic_init_globals);
  CHECK(module_name);
  CHECK(asan_inited);
  BlockingMutexLock lock(&mu_for_globals);
  if (flags()->report_globals >= 3)
    Printf("DynInitPoison module: %s\n", module_name);
  for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
    DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
    const Global *g = &dyn_g.g;
    if (dyn_g.initialized)
      continue;
    if (g->module_name != module_name)
      PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
    else if (!strict_init_order)
      dyn_g.initialized = true;
  }
}

// This method runs immediately after dynamic initialization in each TU, when
// all dynamically initialized globals except for those defined in the current
// TU are poisoned.  It simply unpoisons all dynamically initialized globals.
void __asan_after_dynamic_init() {
  if (!flags()->check_initialization_order ||
      !CanPoisonMemory())
    return;
  CHECK(asan_inited);
  BlockingMutexLock lock(&mu_for_globals);
  // FIXME: Optionally report that we're unpoisoning globals from a module.
  for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
    DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
    const Global *g = &dyn_g.g;
    if (!dyn_g.initialized) {
      // Unpoison the whole global.
      PoisonShadowForGlobal(g, 0);
      // Poison redzones back.
      PoisonRedZones(*g);
    }
  }
}
<commit_msg>[ASan] Print out a diagnostic when a global is unregistered<commit_after>//===-- asan_globals.cc ---------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Handle globals.
//===----------------------------------------------------------------------===//
#include "asan_interceptors.h"
#include "asan_internal.h"
#include "asan_mapping.h"
#include "asan_poisoning.h"
#include "asan_report.h"
#include "asan_stack.h"
#include "asan_stats.h"
#include "asan_thread.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_mutex.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_stackdepot.h"

namespace __asan {

typedef __asan_global Global;

struct ListOfGlobals {
  const Global *g;
  ListOfGlobals *next;
};

static BlockingMutex mu_for_globals(LINKER_INITIALIZED);
static LowLevelAllocator allocator_for_globals;
static ListOfGlobals *list_of_all_globals;

static const int kDynamicInitGlobalsInitialCapacity = 512;
struct DynInitGlobal {
  Global g;
  bool initialized;
};
typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
// Lazy-initialized and never deleted.
static VectorOfGlobals *dynamic_init_globals;

// We want to remember where a certain range of globals was registered.
struct GlobalRegistrationSite {
  u32 stack_id;
  Global *g_first, *g_last;
};
typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
static GlobalRegistrationSiteVector *global_registration_site_vector;

ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
  FastPoisonShadow(g->beg, g->size_with_redzone, value);
}

ALWAYS_INLINE void PoisonRedZones(const Global &g) {
  uptr aligned_size = RoundUpTo(g.size, SHADOW_GRANULARITY);
  FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
                   kAsanGlobalRedzoneMagic);
  if (g.size != aligned_size) {
    FastPoisonShadowPartialRightRedzone(
        g.beg + RoundDownTo(g.size, SHADOW_GRANULARITY),
        g.size % SHADOW_GRANULARITY,
        SHADOW_GRANULARITY,
        kAsanGlobalRedzoneMagic);
  }
}

const uptr kMinimalDistanceFromAnotherGlobal = 64;

bool IsAddressNearGlobal(uptr addr, const __asan_global &g) {
  if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;
  if (addr >= g.beg + g.size_with_redzone) return false;
  return true;
}

static void ReportGlobal(const Global &g, const char *prefix) {
  Report("%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu\n",
         prefix, &g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
         g.module_name, g.has_dynamic_init);
  if (g.location) {
    Report("  location (%p): name=%s[%p], %d %d\n", g.location,
           g.location->filename, g.location->filename, g.location->line_no,
           g.location->column_no);
  }
}

static bool DescribeOrGetInfoIfGlobal(uptr addr, uptr size, bool print,
                                      Global *output_global) {
  if (!flags()->report_globals) return false;
  BlockingMutexLock lock(&mu_for_globals);
  bool res = false;
  for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
    const Global &g = *l->g;
    if (print) {
      if (flags()->report_globals >= 2)
        ReportGlobal(g, "Search");
      res |= DescribeAddressRelativeToGlobal(addr, size, g);
    } else {
      if (IsAddressNearGlobal(addr, g)) {
        CHECK(output_global);
        *output_global = g;
        return true;
      }
    }
  }
  return res;
}

bool DescribeAddressIfGlobal(uptr addr, uptr size) {
  return DescribeOrGetInfoIfGlobal(addr, size, /* print */ true,
                                   /* output_global */ nullptr);
}

bool GetInfoForAddressIfGlobal(uptr addr, AddressDescription *descr) {
  Global g = {};
  if (DescribeOrGetInfoIfGlobal(addr, /* size */ 1, /* print */ false, &g)) {
    internal_strncpy(descr->name, g.name, descr->name_size);
    descr->region_address = g.beg;
    descr->region_size = g.size;
    descr->region_kind = "global";
    return true;
  }
  return false;
}

u32 FindRegistrationSite(const Global *g) {
  CHECK(global_registration_site_vector);
  for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
    GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
    if (g >= grs.g_first && g <= grs.g_last)
      return grs.stack_id;
  }
  return 0;
}

// Register a global variable.
// This function may be called more than once for every global
// so we store the globals in a map.
static void RegisterGlobal(const Global *g) {
  CHECK(asan_inited);
  if (flags()->report_globals >= 2)
    ReportGlobal(*g, "Added");
  CHECK(flags()->report_globals);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  if (flags()->detect_odr_violation) {
    // Try detecting ODR (One Definition Rule) violation, i.e. the situation
    // where two globals with the same name are defined in different modules.
    if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
      // This check may not be enough: if the first global is much larger
      // the entire redzone of the second global may be within the first global.
      for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
        if (g->beg == l->g->beg &&
            (flags()->detect_odr_violation >= 2 || g->size != l->g->size))
          ReportODRViolation(g, FindRegistrationSite(g),
                             l->g, FindRegistrationSite(l->g));
      }
    }
  }
  if (CanPoisonMemory())
    PoisonRedZones(*g);
  ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
  l->g = g;
  l->next = list_of_all_globals;
  list_of_all_globals = l;
  if (g->has_dynamic_init) {
    if (dynamic_init_globals == 0) {
      dynamic_init_globals = new(allocator_for_globals)
          VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
    }
    DynInitGlobal dyn_global = { *g, false };
    dynamic_init_globals->push_back(dyn_global);
  }
}

static void UnregisterGlobal(const Global *g) {
  CHECK(asan_inited);
  if (flags()->report_globals >= 2)
    ReportGlobal(*g, "Removed");
  CHECK(flags()->report_globals);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  if (CanPoisonMemory())
    PoisonShadowForGlobal(g, 0);
  // We unpoison the shadow memory for the global but we do not remove it from
  // the list because that would require O(n^2) time with the current list
  // implementation. It might not be worth doing anyway.
}

void StopInitOrderChecking() {
  BlockingMutexLock lock(&mu_for_globals);
  if (!flags()->check_initialization_order || !dynamic_init_globals)
    return;
  flags()->check_initialization_order = false;
  for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
    DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
    const Global *g = &dyn_g.g;
    // Unpoison the whole global.
    PoisonShadowForGlobal(g, 0);
    // Poison redzones back.
    PoisonRedZones(*g);
  }
}

}  // namespace __asan

// ---------------------- Interface ---------------- {{{1
using namespace __asan;  // NOLINT

// Register an array of globals.
void __asan_register_globals(__asan_global *globals, uptr n) {
  if (!flags()->report_globals) return;
  GET_STACK_TRACE_FATAL_HERE;
  u32 stack_id = StackDepotPut(stack);
  BlockingMutexLock lock(&mu_for_globals);
  if (!global_registration_site_vector)
    global_registration_site_vector =
        new(allocator_for_globals) GlobalRegistrationSiteVector(128);
  GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
  global_registration_site_vector->push_back(site);
  if (flags()->report_globals >= 2) {
    PRINT_CURRENT_STACK();
    Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
  }
  for (uptr i = 0; i < n; i++) {
    RegisterGlobal(&globals[i]);
  }
}

// Unregister an array of globals.
// We must do this when a shared objects gets dlclosed.
void __asan_unregister_globals(__asan_global *globals, uptr n) {
  if (!flags()->report_globals) return;
  BlockingMutexLock lock(&mu_for_globals);
  for (uptr i = 0; i < n; i++) {
    UnregisterGlobal(&globals[i]);
  }
}

// This method runs immediately prior to dynamic initialization in each TU,
// when all dynamically initialized globals are unpoisoned.  This method
// poisons all global variables not defined in this TU, so that a dynamic
// initializer can only touch global variables in the same TU.
void __asan_before_dynamic_init(const char *module_name) {
  if (!flags()->check_initialization_order ||
      !CanPoisonMemory())
    return;
  bool strict_init_order = flags()->strict_init_order;
  CHECK(dynamic_init_globals);
  CHECK(module_name);
  CHECK(asan_inited);
  BlockingMutexLock lock(&mu_for_globals);
  if (flags()->report_globals >= 3)
    Printf("DynInitPoison module: %s\n", module_name);
  for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
    DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
    const Global *g = &dyn_g.g;
    if (dyn_g.initialized)
      continue;
    if (g->module_name != module_name)
      PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
    else if (!strict_init_order)
      dyn_g.initialized = true;
  }
}

// This method runs immediately after dynamic initialization in each TU, when
// all dynamically initialized globals except for those defined in the current
// TU are poisoned.  It simply unpoisons all dynamically initialized globals.
void __asan_after_dynamic_init() {
  if (!flags()->check_initialization_order ||
      !CanPoisonMemory())
    return;
  CHECK(asan_inited);
  BlockingMutexLock lock(&mu_for_globals);
  // FIXME: Optionally report that we're unpoisoning globals from a module.
  for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
    DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
    const Global *g = &dyn_g.g;
    if (!dyn_g.initialized) {
      // Unpoison the whole global.
      PoisonShadowForGlobal(g, 0);
      // Poison redzones back.
      PoisonRedZones(*g);
    }
  }
}
<|endoftext|>


<commit_before>/*
* RDRAND RNG
* (C) 2016,2019 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/rdrand_rng.h>
#include <botan/loadstor.h>
#include <botan/cpuid.h>

#if !defined(BOTAN_USE_GCC_INLINE_ASM)
  #include <immintrin.h>
#endif

namespace Botan {

namespace {

#if defined(BOTAN_TARGET_ARCH_IS_X86_64)
   typedef uint64_t rdrand_output;
#else
   typedef uint32_t rdrand_output;
#endif

BOTAN_FUNC_ISA("rdrnd")
rdrand_output read_rdrand()
   {
   /*
   * According to Intel, RDRAND is guaranteed to generate a random
   * number within 10 retries on a working CPU
   */
   const size_t RDRAND_RETRIES = 10;

   for(size_t i = 0; i < RDRAND_RETRIES; ++i)
      {
      rdrand_output r = 0;
      int cf = 0;

#if defined(BOTAN_USE_GCC_INLINE_ASM)
      // same asm seq works for 32 and 64 bit
      asm("rdrand %0; adcl $0,%1" :
          "=r" (r), "=r" (cf) : "0" (r), "1" (cf) : "cc");
#elif defined(BOTAN_TARGET_ARCH_IS_X86_64)
      cf = _rdrand64_step(&r);
#else
      cf = _rdrand32_step(&r);
#endif
      if(1 == cf)
         {
         return r;
         }
      }

   throw PRNG_Unseeded("RDRAND read failed");
   }

}

void RDRAND_RNG::randomize(uint8_t out[], size_t out_len)
   {
   while(out_len >= sizeof(rdrand_output))
      {
      const rdrand_output r = read_rdrand();
      store_le(r, out);
      out += sizeof(rdrand_output);
      out_len -= sizeof(rdrand_output);
      }

   if(out_len > 0) // at most sizeof(rdrand_output)-1
      {
      const rdrand_output r = read_rdrand();
      for(size_t i = 0; i != out_len; ++i)
         out[i] = get_byte(i, r);
      }
   }

RDRAND_RNG::RDRAND_RNG()
   {
   if(!RDRAND_RNG::available())
      throw Invalid_State("Current CPU does not support RDRAND instruction");
   }

//static
bool RDRAND_RNG::available()
   {
   return CPUID::has_rdrand();
   }

//static
uint32_t RDRAND_RNG::rdrand()
   {
   return static_cast<uint32_t>(read_rdrand());
   }

//static
BOTAN_FUNC_ISA("rdrnd")
uint32_t RDRAND_RNG::rdrand_status(bool& ok)
   {
   ok = false;

   try
      {
      const uint32_t r = static_cast<uint32_t>(read_rdrand());
      ok = true;
      return r;
      }
   catch(PRNG_Unseeded&) {}

   return 0;
   }

}
<commit_msg>Avoid using BOTAN_ISA_FUNC on rdrand function unless needed<commit_after>/*
* RDRAND RNG
* (C) 2016,2019 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/rdrand_rng.h>
#include <botan/loadstor.h>
#include <botan/cpuid.h>

#if !defined(BOTAN_USE_GCC_INLINE_ASM)
  #include <immintrin.h>
#endif

namespace Botan {

namespace {

#if defined(BOTAN_TARGET_ARCH_IS_X86_64)
   typedef uint64_t rdrand_output;
#else
   typedef uint32_t rdrand_output;
#endif

#if !defined(BOTAN_USE_GCC_INLINE_ASM)
BOTAN_FUNC_ISA("rdrnd")
#endif
rdrand_output read_rdrand()
   {
   /*
   * According to Intel, RDRAND is guaranteed to generate a random
   * number within 10 retries on a working CPU
   */
   const size_t RDRAND_RETRIES = 10;

   for(size_t i = 0; i < RDRAND_RETRIES; ++i)
      {
      rdrand_output r = 0;
      int cf = 0;

#if defined(BOTAN_USE_GCC_INLINE_ASM)
      // same asm seq works for 32 and 64 bit
      asm("rdrand %0; adcl $0,%1" :
          "=r" (r), "=r" (cf) : "0" (r), "1" (cf) : "cc");
#elif defined(BOTAN_TARGET_ARCH_IS_X86_64)
      cf = _rdrand64_step(&r);
#else
      cf = _rdrand32_step(&r);
#endif
      if(1 == cf)
         {
         return r;
         }
      }

   throw PRNG_Unseeded("RDRAND read failed");
   }

}

void RDRAND_RNG::randomize(uint8_t out[], size_t out_len)
   {
   while(out_len >= sizeof(rdrand_output))
      {
      const rdrand_output r = read_rdrand();
      store_le(r, out);
      out += sizeof(rdrand_output);
      out_len -= sizeof(rdrand_output);
      }

   if(out_len > 0) // at most sizeof(rdrand_output)-1
      {
      const rdrand_output r = read_rdrand();
      for(size_t i = 0; i != out_len; ++i)
         out[i] = get_byte(i, r);
      }
   }

RDRAND_RNG::RDRAND_RNG()
   {
   if(!RDRAND_RNG::available())
      throw Invalid_State("Current CPU does not support RDRAND instruction");
   }

//static
bool RDRAND_RNG::available()
   {
   return CPUID::has_rdrand();
   }

//static
uint32_t RDRAND_RNG::rdrand()
   {
   return static_cast<uint32_t>(read_rdrand());
   }

//static
BOTAN_FUNC_ISA("rdrnd")
uint32_t RDRAND_RNG::rdrand_status(bool& ok)
   {
   ok = false;

   try
      {
      const uint32_t r = static_cast<uint32_t>(read_rdrand());
      ok = true;
      return r;
      }
   catch(PRNG_Unseeded&) {}

   return 0;
   }

}
<|endoftext|>


<commit_before>#include "RoadWarrior.h"
#include "Backend.h"
#include "RequestNotes.h"
#include "HttpBackend.h"
#include "FastCgiBackend.h"
#include <x0/http/HttpRequest.h>

RoadWarrior::RoadWarrior(x0::HttpWorker* worker) :
    BackendManager(worker, "__roadwarrior__"),
    backendsLock_(),
    backends_()
{
}

RoadWarrior::~RoadWarrior()
{
}

Backend* RoadWarrior::acquireBackend(const x0::SocketSpec& spec, Type type)
{
    std::lock_guard<std::mutex> _l(backendsLock_);

    auto bi = backends_.find(spec);
    if (bi != backends_.end()) {
        return bi->second.get();
    }

    Backend* backend = nullptr;
    switch (type) {
        case HTTP:
            backends_[spec].reset(backend = new HttpBackend(this, spec.str(), spec, 0, false));
            break;
        case FCGI:
            backends_[spec].reset(backend = new FastCgiBackend(this, spec.str(), spec, 0, false));
            break;
    }
    return backend;
}

void RoadWarrior::handleRequest(RequestNotes* rn, const x0::SocketSpec& spec, Type type)
{
    Backend* backend = acquireBackend(spec, type);
    if (!backend) {
        rn->request->status = x0::HttpStatus::InternalServerError;
        rn->request->finish();
    }

    SchedulerStatus result = backend->tryProcess(rn);
    if (result != SchedulerStatus::Success) {
        rn->request->status = x0::HttpStatus::ServiceUnavailable;
        rn->request->finish();
    }
}

void RoadWarrior::reject(RequestNotes* rn)
{
    // this request couldn't be served by the backend, so finish it with a 503 (Service Unavailable).

    auto r = rn->request;

    if (!r->status)
        r->status = x0::HttpStatus::ServiceUnavailable;

    r->finish();
}

void RoadWarrior::release(RequestNotes* rn)
{
    // The passed backend just finished serving a request, so we might now pass it a queued request,
    // in case we would support queuing (do we want that?).
}

void RoadWarrior::writeJSON(x0::JsonWriter& json) const
{
    json.beginObject(name());
    json.beginArray("members");
    for (const auto& backend: backends_) {
        json.value(*backend.second);
    }
    json.endArray();
    json.endObject();
}
<commit_msg>[plugins] director: so let's do a little test...<commit_after>#include "RoadWarrior.h"
#include "Backend.h"
#include "RequestNotes.h"
#include "HttpBackend.h"
#include "FastCgiBackend.h"
#include <x0/http/HttpRequest.h>

RoadWarrior::RoadWarrior(x0::HttpWorker* worker) :
    BackendManager(worker, "__roadwarrior__"),
    backendsLock_(),
    backends_()
{
    // so let's do a little test
    setTransferMode(TransferMode::MemoryAccel);
}

RoadWarrior::~RoadWarrior()
{
}

Backend* RoadWarrior::acquireBackend(const x0::SocketSpec& spec, Type type)
{
    std::lock_guard<std::mutex> _l(backendsLock_);

    auto bi = backends_.find(spec);
    if (bi != backends_.end()) {
        return bi->second.get();
    }

    Backend* backend = nullptr;
    switch (type) {
        case HTTP:
            backends_[spec].reset(backend = new HttpBackend(this, spec.str(), spec, 0, false));
            break;
        case FCGI:
            backends_[spec].reset(backend = new FastCgiBackend(this, spec.str(), spec, 0, false));
            break;
    }
    return backend;
}

void RoadWarrior::handleRequest(RequestNotes* rn, const x0::SocketSpec& spec, Type type)
{
    Backend* backend = acquireBackend(spec, type);
    if (!backend) {
        rn->request->status = x0::HttpStatus::InternalServerError;
        rn->request->finish();
    }

    SchedulerStatus result = backend->tryProcess(rn);
    if (result != SchedulerStatus::Success) {
        rn->request->status = x0::HttpStatus::ServiceUnavailable;
        rn->request->finish();
    }
}

void RoadWarrior::reject(RequestNotes* rn)
{
    // this request couldn't be served by the backend, so finish it with a 503 (Service Unavailable).

    auto r = rn->request;

    if (!r->status)
        r->status = x0::HttpStatus::ServiceUnavailable;

    r->finish();
}

void RoadWarrior::release(RequestNotes* rn)
{
    // The passed backend just finished serving a request, so we might now pass it a queued request,
    // in case we would support queuing (do we want that?).
}

void RoadWarrior::writeJSON(x0::JsonWriter& json) const
{
    json.beginObject(name());
    json.beginArray("members");
    for (const auto& backend: backends_) {
        json.value(*backend.second);
    }
    json.endArray();
    json.endObject();
}
<|endoftext|>


<commit_before>/*
 * This file is part of crash-reporter
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 *
 * Contact: Ville Ilvonen <ville.p.ilvonen@nokia.com>
 * Author: Riku Halonen <riku.halonen@nokia.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

// System includes.

#include <sys/types.h> // for chmod()
#include <sys/stat.h>

#include <QDir>
#include <QDebug>
#include <QDirIterator>

// User includes.

#include "creportercoredir.h"
#include "creportercoredir_p.h"
#include "creporterutils.h"

// Local macros and definitions.

#define FILE_PERMISSION 	0777

// Local constants.

const char rcore_file_name_filter[] = "*.rcore";
const char rcore_lzo_file_name_filter[] = "*.rcore.lzo";

// ======== MEMBER FUNCTIONS ========

CReporterCoreDir::CReporterCoreDir(QString& mpoint, QObject* parent)
    : QObject(parent), d_ptr(new CReporterCoreDirPrivate())
{
	d_ptr->mountpoint = mpoint;
	qDebug() << __PRETTY_FUNCTION__ << "Mountpoint set to:" << d_ptr->mountpoint;
}

CReporterCoreDir::~CReporterCoreDir()
{
	delete d_ptr;
}

QString CReporterCoreDir::getDirectory() const
{
    return d_ptr->directory;
}

QString CReporterCoreDir::getMountpoint() const
{
    return d_ptr->mountpoint;
}

void CReporterCoreDir::setDirectory(const QString& dir)
{
    Q_D(CReporterCoreDir);

	d->directory = dir;
	qDebug() << __PRETTY_FUNCTION__ << "Directory set to:" << d->directory;
}

void CReporterCoreDir::setMountpoint(const QString& mpoint)
{
    Q_D(CReporterCoreDir);

	d->mountpoint = mpoint;
	qDebug() << __PRETTY_FUNCTION__ << "Mountpoint set to:" << d->mountpoint;
}

void CReporterCoreDir::collectAllCoreFilesAtLocation(QStringList& coreList)
{
    Q_D(CReporterCoreDir);

	qDebug() << __PRETTY_FUNCTION__ << "Collecting cores from:" << d->directory;

	QStringList filters;
    filters << QString(rcore_file_name_filter) << QString(rcore_lzo_file_name_filter);

	// Construct iterator for core-dumps directory.
    QDirIterator iter(d->directory, filters, QDir::Files | QDir::NoDotAndDotDot);

    while (iter.hasNext()) {
        QString filePath = iter.next();

        if (CReporterUtils::validateCore(filePath)) {
            coreList << filePath;
        }
    }
}

QString CReporterCoreDir::checkDirectoryForCores()
{
    Q_D(CReporterCoreDir);

	QFileInfo fi;
	QString coreFilePath;

	QStringList filters;
    filters << QString(rcore_file_name_filter) << QString(rcore_lzo_file_name_filter);

	// Construct iterator for core-dumps directory.
    QDirIterator iter(d->directory, filters, QDir::Files | QDir::NoDotAndDotDot);

	// Iterate over files in the core-dumps directory.
    while (iter.hasNext()) {

		iter.next();
		fi = iter.fileInfo();

        if (!d->coresAtDirectory.contains(fi.fileName()) &&
                CReporterUtils::validateCore(fi.fileName())) {
				// This is valid rich core file, which hasn't been processed before.
				d->coresAtDirectory << fi.fileName();
				coreFilePath = fi.absoluteFilePath();
				qDebug() << __PRETTY_FUNCTION__ << "New core file:" << fi.fileName();
				break;
		}
	}

    if (coreFilePath.isEmpty()) {
		// File was deleted by the user or client from the directory.
		// Refresh directory list.
		updateCoreList();
	}

	return coreFilePath;
}

void CReporterCoreDir::createCoreDirectory()
{
    Q_D(CReporterCoreDir);

    if (CReporterUtils::isMounted(d->mountpoint))
    {
        // Construct new QDir pointing to mount point.
        QDir coreRoot(d->mountpoint);

        if (!coreRoot.exists(d->directory))
        {
            // If core-dumps -directory doesn't exist.
            // Create new sub-directory.
            if (coreRoot.exists(d->directory.left(d->directory.lastIndexOf('/')))
                && coreRoot.mkdir(d->directory))
            {
                qDebug() << __PRETTY_FUNCTION__ << "Created directory:" << d->directory;
                chmod(CReporterUtils::qstringToChar(d->directory), FILE_PERMISSION);
            }
            else
            {
                qWarning() << __PRETTY_FUNCTION__ << "Error while creating directory:" << d->directory;
            }
            // Remove old entries from the list.
            d->coresAtDirectory.clear();
        }
        else
        {
            // There was a "core-dumps" directory already. Fetch possible core files.
            updateCoreList();
        }
    }
}

void CReporterCoreDir::updateCoreList()
{
    Q_D(CReporterCoreDir);

	qDebug() << __PRETTY_FUNCTION__ << "Refreshing core directory list.";

    QDir dir(d->directory);
    dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
    dir.setNameFilters(QStringList() << rcore_file_name_filter << rcore_lzo_file_name_filter);

	// Remove old entries.
	d->coresAtDirectory.clear();

    QDirIterator it(dir);
    while (it.hasNext()) {
        d->coresAtDirectory.append(it.next());
    }
}

// End of file
<commit_msg>[coredir] Fix CReporterCoreDir::updateCoreList()<commit_after>/*
 * This file is part of crash-reporter
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 *
 * Contact: Ville Ilvonen <ville.p.ilvonen@nokia.com>
 * Author: Riku Halonen <riku.halonen@nokia.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

// System includes.

#include <sys/types.h> // for chmod()
#include <sys/stat.h>

#include <QDir>
#include <QDebug>
#include <QDirIterator>

// User includes.

#include "creportercoredir.h"
#include "creportercoredir_p.h"
#include "creporterutils.h"

// Local macros and definitions.

#define FILE_PERMISSION 	0777

// Local constants.

const char rcore_file_name_filter[] = "*.rcore";
const char rcore_lzo_file_name_filter[] = "*.rcore.lzo";

// ======== MEMBER FUNCTIONS ========

CReporterCoreDir::CReporterCoreDir(QString& mpoint, QObject* parent)
    : QObject(parent), d_ptr(new CReporterCoreDirPrivate())
{
	d_ptr->mountpoint = mpoint;
	qDebug() << __PRETTY_FUNCTION__ << "Mountpoint set to:" << d_ptr->mountpoint;
}

CReporterCoreDir::~CReporterCoreDir()
{
	delete d_ptr;
}

QString CReporterCoreDir::getDirectory() const
{
    return d_ptr->directory;
}

QString CReporterCoreDir::getMountpoint() const
{
    return d_ptr->mountpoint;
}

void CReporterCoreDir::setDirectory(const QString& dir)
{
    Q_D(CReporterCoreDir);

	d->directory = dir;
	qDebug() << __PRETTY_FUNCTION__ << "Directory set to:" << d->directory;
}

void CReporterCoreDir::setMountpoint(const QString& mpoint)
{
    Q_D(CReporterCoreDir);

	d->mountpoint = mpoint;
	qDebug() << __PRETTY_FUNCTION__ << "Mountpoint set to:" << d->mountpoint;
}

void CReporterCoreDir::collectAllCoreFilesAtLocation(QStringList& coreList)
{
    Q_D(CReporterCoreDir);

	qDebug() << __PRETTY_FUNCTION__ << "Collecting cores from:" << d->directory;

	QStringList filters;
    filters << QString(rcore_file_name_filter) << QString(rcore_lzo_file_name_filter);

	// Construct iterator for core-dumps directory.
    QDirIterator iter(d->directory, filters, QDir::Files | QDir::NoDotAndDotDot);

    while (iter.hasNext()) {
        QString filePath = iter.next();

        if (CReporterUtils::validateCore(filePath)) {
            coreList << filePath;
        }
    }
}

QString CReporterCoreDir::checkDirectoryForCores()
{
    Q_D(CReporterCoreDir);

	QFileInfo fi;
	QString coreFilePath;

	QStringList filters;
    filters << QString(rcore_file_name_filter) << QString(rcore_lzo_file_name_filter);

	// Construct iterator for core-dumps directory.
    QDirIterator iter(d->directory, filters, QDir::Files | QDir::NoDotAndDotDot);

	// Iterate over files in the core-dumps directory.
    while (iter.hasNext()) {

		iter.next();
		fi = iter.fileInfo();

        if (!d->coresAtDirectory.contains(fi.fileName()) &&
                CReporterUtils::validateCore(fi.fileName())) {
				// This is valid rich core file, which hasn't been processed before.
				d->coresAtDirectory << fi.fileName();
				coreFilePath = fi.absoluteFilePath();
				qDebug() << __PRETTY_FUNCTION__ << "New core file:" << fi.fileName();
				break;
		}
	}

    if (coreFilePath.isEmpty()) {
		// File was deleted by the user or client from the directory.
		// Refresh directory list.
		updateCoreList();
	}

	return coreFilePath;
}

void CReporterCoreDir::createCoreDirectory()
{
    Q_D(CReporterCoreDir);

    if (CReporterUtils::isMounted(d->mountpoint))
    {
        // Construct new QDir pointing to mount point.
        QDir coreRoot(d->mountpoint);

        if (!coreRoot.exists(d->directory))
        {
            // If core-dumps -directory doesn't exist.
            // Create new sub-directory.
            if (coreRoot.exists(d->directory.left(d->directory.lastIndexOf('/')))
                && coreRoot.mkdir(d->directory))
            {
                qDebug() << __PRETTY_FUNCTION__ << "Created directory:" << d->directory;
                chmod(CReporterUtils::qstringToChar(d->directory), FILE_PERMISSION);
            }
            else
            {
                qWarning() << __PRETTY_FUNCTION__ << "Error while creating directory:" << d->directory;
            }
            // Remove old entries from the list.
            d->coresAtDirectory.clear();
        }
        else
        {
            // There was a "core-dumps" directory already. Fetch possible core files.
            updateCoreList();
        }
    }
}

void CReporterCoreDir::updateCoreList()
{
    Q_D(CReporterCoreDir);

	qDebug() << __PRETTY_FUNCTION__ << "Refreshing core directory list.";

    QDir dir(d->directory);
    dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
    dir.setNameFilters(QStringList() << rcore_file_name_filter << rcore_lzo_file_name_filter);

	// Remove old entries.
	d->coresAtDirectory.clear();

    QDirIterator it(dir);
    while (it.hasNext()) {
        it.next();
        d->coresAtDirectory.append(it.fileName());
    }
}

// End of file
<|endoftext|>