<commit_before>//IBM_PROLOG_BEGIN_TAG
/*
 * Copyright 2003,2016 IBM International Business Machines Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//IBM_PROLOG_END_TAG

#ifndef ecmdReturnCodes_h
#define ecmdReturnCodes_h

/**
 * @file ecmdReturnCodes.H
 * @brief All Return Codes for the eCmd Capi
*/

#include <ecmdDefines.H>

/* These are the prefixs that the plugins will use to specify their specific errors as well as eCMD errors itself */
#define ECMD_ERR_UNKNOWN                        0x00000000 ///< This error code wasn't flagged to which plugin it came from
#define ECMD_ERR_ECMD                           0x01000000 ///< Error came from eCMD
#define ECMD_ERR_CRONUS                         0x02000000 ///< Error came from Cronus
#define ECMD_ERR_IP                             0x04000000 ///< Error came from IP GFW
#define ECMD_ERR_Z                              0x08000000 ///< Error came from Z GFW
#define ECMD_ERR_SCAND                          0x10000000 ///< Error came from Z GFW
#define ECMD_ERR_LHT                            0x20000000 ///< Error came from Linux Host Tool

#define ECMD_SUCCESS                            0x0    ///< API Returned Successfully

/* For now let's define all return codes in the 0x1000-0x1FFF range */
#define ECMD_INVALID_DLL_VERSION                (ECMD_ERR_ECMD | 0x1001) ///< Dll Version didn't match the Client version detected
#define ECMD_INVALID_DLL_FILENAME               (ECMD_ERR_ECMD | 0x1003) ///< Unable to find filename to load or file doesn't exist
#define ECMD_DLL_LOAD_FAILURE                   (ECMD_ERR_ECMD | 0x1005) ///< Error occured on call to dlopen
#define ECMD_DLL_UNLOAD_FAILURE                 (ECMD_ERR_ECMD | 0x1007) ///< Error occurred on call to dlclose
#define ECMD_DLL_UNINITIALIZED                  (ECMD_ERR_ECMD | 0x1009) ///< A function was called before ecmdLoadDll was called
#define ECMD_DLL_INVALID                        (ECMD_ERR_ECMD | 0x100B) ///< If we are unable to lookup a function in the Dll
#define ECMD_FAILURE                            (ECMD_ERR_ECMD | 0x100D) ///< General Failure occurred in eCMD
#define ECMD_TARGET_NOT_CONFIGURED              (ECMD_ERR_ECMD | 0x100F) ///< Chip target provided was not configured in the system
#define ECMD_FUNCTION_NOT_SUPPORTED             (ECMD_ERR_ECMD | 0x1011) ///< Returned if a specific Dll instance doesn't support the function you called
#define ECMD_UNKNOWN_FILE                       (ECMD_ERR_ECMD | 0x1013) ///< ecmdQueryFileLocation was unable to find the file you requested
#define ECMD_UNKNOWN_HELP_FILE                  (ECMD_ERR_ECMD | 0x1014) ///< Helpfile could not be read
#define ECMD_INVALID_ARGS                       (ECMD_ERR_ECMD | 0x1015) ///< Not enough arguments provided to the function
#define ECMD_INVALID_SPY_ENUM                   (ECMD_ERR_ECMD | 0x1017) ///< getSpyEnum or putSpyEnum used an invalid enum
#define ECMD_SPY_FAILED_ECC_CHECK               (ECMD_ERR_ECMD | 0x1019) ///< getSpy or getSpyEnum failed with invalid ECC detected in the hardware
#define ECMD_SPY_NOT_ENUMERATED                 (ECMD_ERR_ECMD | 0x101B) ///< getSpyEnum or putSpyEnum was called on a non-enumerated spy
#define ECMD_SPY_IS_EDIAL                       (ECMD_ERR_ECMD | 0x101D) ///< getSpy or Putspy was called on an edial
#define ECMD_INVALID_SPY                        (ECMD_ERR_ECMD | 0x101F) ///< Spy functions found an invalid Spy name or type
#define ECMD_DATA_OVERFLOW                      (ECMD_ERR_ECMD | 0x1021) ///< Too much data was provided to a write function
#define ECMD_DATA_UNDERFLOW                     (ECMD_ERR_ECMD | 0x1023) ///< Too little data was provided to a write function
#define ECMD_INVALID_RING                       (ECMD_ERR_ECMD | 0x1025) ///< Invalid ring name was provided
#define ECMD_INVALID_ARRAY                      (ECMD_ERR_ECMD | 0x1027) ///< Invalid array name was provided
#define ECMD_INVALID_CONFIG                     (ECMD_ERR_ECMD | 0x1029) ///< There was an error processing the configuration information
#define ECMD_CLOCKS_IN_INVALID_STATE            (ECMD_ERR_ECMD | 0x102B) ///< Chip Clocks were in an invalid state to perform the operation
#define ECMD_NON_JTAG_CHIP                      (ECMD_ERR_ECMD | 0x102D) ///< JTag function called  on non-jtag attached chip
#define ECMD_NON_FSI_CHIP                       (ECMD_ERR_ECMD | 0x102F) ///< Fsi function called on non-fsi attached chip
#define ECMD_INVALID_SPR                        (ECMD_ERR_ECMD | 0x1031) ///< Invalid SPR was specified to get/put spr functions
#define ECMD_INVALID_GPR                        (ECMD_ERR_ECMD | 0x1033) ///< Invalid GPR number was specified to get/put gpr functions
#define ECMD_INVALID_FPR                        (ECMD_ERR_ECMD | 0x1035) ///< Invalid FPR number was specified to get/put fpr functions
#define ECMD_RING_CACHE_ENABLED                 (ECMD_ERR_ECMD | 0x1037) ///< Ring Cache enabled during call non-cache enabled function
#define ECMD_INVALID_CONFIG_NAME                (ECMD_ERR_ECMD | 0x1039) ///< An Invalid name was used to set/get a configuation setting
#define ECMD_INVALID_CONFIG_DATA                (ECMD_ERR_ECMD | 0x103B) ///< An Invalid data type was used to set/get a configuation setting
#define ECMD_SPY_GROUP_MISMATCH                 (ECMD_ERR_ECMD | 0x103D) ///< A mismatch was found reading a group spy not all groups set the same
#define ECMD_INVALID_CLOCK_DOMAIN               (ECMD_ERR_ECMD | 0x103F) ///< An invalid clock domain name was specified
#define ECMD_CLOCKS_ALREADY_OFF                 (ECMD_ERR_ECMD | 0x1041) ///< A stopclocks was requested when clocks are already off
#define ECMD_CLOCKS_ALREADY_ON                  (ECMD_ERR_ECMD | 0x1043) ///< A startclocks was requested when clocks are already on
#define ECMD_UNABLE_TO_OPEN_SCANDEF             (ECMD_ERR_ECMD | 0x1045) ///< eCMD was unable to open the scandef
#define ECMD_INVALID_LATCHNAME                  (ECMD_ERR_ECMD | 0x1047) ///< eCMD was unable to find the specified latch in the scandef
#define ECMD_POLLING_FAILURE                    (ECMD_ERR_ECMD | 0x1049) ///< eCMD failed waiting for a poll to match expected value
#define ECMD_TARGET_INVALID_TYPE                (ECMD_ERR_ECMD | 0x104B) ///< Target specified an object that was inappropriate for the function
#define ECMD_EXTENSION_NOT_SUPPORTED            (ECMD_ERR_ECMD | 0x104D) ///< The current plugin does not supported the requested extension
#define ECMD_ISTEPS_INVALID_STEP                (ECMD_ERR_ECMD | 0x104F) ///< An invalid step name was provided
#define ECMD_UNABLE_TO_OPEN_SCANDEFHASH         (ECMD_ERR_ECMD | 0x1051) ///< eCMD was unable to open the scandefhash
#define ECMD_SCANDEFHASH_MULT_RINGS             (ECMD_ERR_ECMD | 0x1053) ///< Multiple ring keys matching the same latchname found
#define ECMD_UNABLE_TO_OPEN_SCOMDEF             (ECMD_ERR_ECMD | 0x1055) ///< eCMD was unable to open scomdef file
#define ECMD_SCOMADDRESS_NOT_FOUND              (ECMD_ERR_ECMD | 0x1057) ///< Scom Address not found in the ScomDef file
#define ECMD_INVALID_ENTRY_REQUESTED            (ECMD_ERR_ECMD | 0x1059) ///< An invalid entry was requested
#define ECMD_INSTRUCTIONS_IN_INVALID_STATE      (ECMD_ERR_ECMD | 0x105B) ///< Instructions were in an invalid state for operation
#define ECMD_INVALID_MEMORY_ADDRESS             (ECMD_ERR_ECMD | 0x105D) ///< Memory Address was not on a proper byte boundary
#define ECMD_RETRY_WITH_VIRTUAL_ADDR            (ECMD_ERR_IP   | 0x105F) ///< Requests that the user retries operation with returned Virtual Address
#define ECMD_UNABLE_TO_MAP_HASHID		(ECMD_ERR_IP   | 0x1061) ///< Mapping function was unable to match the hashid given by the user
#define ECMD_UNABLE_TO_OPEN_ARRAYDEF            (ECMD_ERR_ECMD | 0x1063) ///< eCMD was unable to open arraydef file
#define ECMD_INVALID_RETURN_DATA                (ECMD_ERR_ECMD | 0x1065) ///< Data returned (if any) is incomplete or invalid... caller beware
#define ECMD_CHIP_UNKNOWN_FOR_MAPPING           (ECMD_ERR_ECMD | 0x1067) ///< Chip type did not map to a known EDC table
#define ECMD_INVALID_GP_REGISTER                (ECMD_ERR_ECMD | 0x1069) ///< Invalid GP Register was provided
#define ECMD_INVALID_SCOM                       (ECMD_ERR_ECMD | 0x106B) ///< Invalid SCOM Register was provided
#define ECMD_RING_NOT_FOUND                     (ECMD_ERR_ECMD | 0x106D) ///< Ring requested was not found
#define ECMD_SCOM_NOT_FOUND                     (ECMD_ERR_ECMD | 0x106F) ///< Scom requested was not found
#define ECMD_ARRAY_NOT_FOUND                    (ECMD_ERR_ECMD | 0x1071) ///< Array requested was not found
#define ECMD_ARRAY_INVALID_OBJECT               (ECMD_ERR_ECMD | 0x1072) ///< No array table available for this chip
#define ECMD_TRACEARRAY_NOT_FOUND               (ECMD_ERR_ECMD | 0x1073) ///< Trace Array requested was not found
#define ECMD_CFAMREG_NOT_FOUND                  (ECMD_ERR_ECMD | 0x1075) ///< Cfam Register requested was not found
#define ECMD_CFAMADDRESS_OUT_OF_RANGE           (ECMD_ERR_ECMD | 0x1076) ///< Cfam Address requested was out of scom and scan range
#define ECMD_GPREG_NOT_FOUND                    (ECMD_ERR_ECMD | 0x1077) ///< GP Register requested was not found
#define ECMD_SPY_NOT_FOUND                      (ECMD_ERR_ECMD | 0x1079) ///< Spy requested was not found
#define ECMD_IRSTAT_NOT_FOUND                   (ECMD_ERR_ECMD | 0x107B) ///< IRSTAT requested was not found
#define ECMD_WRITING_TO_READ_ONLY_REG           (ECMD_ERR_ECMD | 0x107D) ///< Writing to Read-Only Register
#define ECMD_READING_FROM_WRITE_ONLY_REG        (ECMD_ERR_ECMD | 0x107F) ///< Reading from Write-Only Register
#define ECMD_INVALID_INIT_ID                    (ECMD_ERR_ECMD | 0x1081) ///< Initialization ID  not found in eng data
#define ECMD_INVALID_INIT_FILE                  (ECMD_ERR_ECMD | 0x1083) ///< File not found
#define ECMD_INVALID_INIT_MODE                  (ECMD_ERR_ECMD | 0x1085) ///< Initialization mode not supported
#define ECMD_NOT_CHIPUNIT_0                     (ECMD_ERR_ECMD | 0x108A) ///< The item passed in wasn't for chipUnit 0
#define ECMD_ARRAY_SCANRING_ERROR               (ECMD_ERR_ECMD | 0x108B) ///< Failed to create scanring object during array access
#define ECMD_ARRAY_SETUP_CONTROLS_ERROR         (ECMD_ERR_ECMD | 0x108D) ///< Failed to setup array controls
#define ECMD_ARRAY_CACHE_NOT_OFF_ERROR          (ECMD_ERR_ECMD | 0x108F) ///< Cache must be turned off before accessing an array
#define ECMD_ARRAY_SCOM_RETRY_ERROR             (ECMD_ERR_ECMD | 0x1091) ///< Read/write done indicator not set after 10 retries during scom 1 or 2 array access
#define ECMD_SCANRING_ILLEGAL_OPER              (ECMD_ERR_ECMD | 0x1093) ///< Scan/scom access with wrong mode or hw scanring access with cache on
#define ECMD_SCANRING_INVALID_OBJECT            (ECMD_ERR_ECMD | 0x1095) ///< No proper scan/scom init or wrong ringtype requested
#define ECMD_SCANRING_ACCESS_FAIL               (ECMD_ERR_ECMD | 0x1097) ///< Scanring access failed with bad return code from i390
#define ECMD_SCANRING_INVALID_STATE             (ECMD_ERR_ECMD | 0x1099) ///< Scanring shift mode error - selftest still running or clocks running
#define ECMD_SCANRING_SCAN_PROTECT              (ECMD_ERR_ECMD | 0x109B) ///< Attempt to access scanring although clocks were running
#define ECMD_SPYDEF_INVALID                     (ECMD_ERR_ECMD | 0x109D) ///< The (binary) spy definition is corrupt
#define ECMD_SPY_NO_RING_FOUND                  (ECMD_ERR_ECMD | 0x109F) ///< Failed to create scanring object
#define ECMD_SPY_EXTRACT_DATA_FAIL              (ECMD_ERR_ECMD | 0x10A1) ///< The (binary) spy definition is corrupt
#define ECMD_SPY_INSERT_DATA_FAIL               (ECMD_ERR_ECMD | 0x10A3) ///< The (binary) spy definition is corrupt
#define ECMD_SPY_FLIP_BITS_FAIL                 (ECMD_ERR_ECMD | 0x10A5) ///< The (binary) spy definition is corrupt
#define ECMD_SPY_WRITE_FAIL                     (ECMD_ERR_ECMD | 0x10A7) ///< Spy size vs buffer mismatch or unknown enum
#define ECMD_SPY_INVALID_READ_OPER              (ECMD_ERR_ECMD | 0x10A9) ///< Spy enum read operation on non-enum or vice versa
#define ECMD_SPY_INVALID_WRITE_OPER             (ECMD_ERR_ECMD | 0x10AB) ///< Spy enum write op on non-enum or vice versa or write op to non-defined enum for this spy
#define ECMD_SPY_INVALID_OBJECT                 (ECMD_ERR_ECMD | 0x10AD) ///< Spy not properly initialized
#define ECMD_SCOM_INVALID_OBJECT                (ECMD_ERR_ECMD | 0x10AF) ///< Scom not properly initialized
#define ECMD_HREG_ECMDDATABUFFER_ERROR          (ECMD_ERR_ECMD | 0x10B1) ///< Scanring buffer op failed or corrupt scanring binary or memory mgmt issue
#define ECMD_HREG_ADDRESS_INVALID_PARAM         (ECMD_ERR_ECMD | 0x10B3) ///< Address translation failed due to invalied combination of parameters
#define ECMD_SENSOR_HUMIDITY_NOT_AVAILABLE       (ECMD_ERR_ECMD | 0x10C1) ///< Humidity Sensor data not available
#define ECMD_SENSOR_AIR_DENSITY_NOT_AVAILABLE   (ECMD_ERR_ECMD | 0x10C3) ///< Air Density Sensor data not available
#define ECMD_SENSOR_UNIT_NOT_SUPPORTED          (ECMD_ERR_ECMD | 0x10C5) ///< Unit not supported for sensor
#define ECMD_SENSOR_ID_NOT_SUPPORTED            (ECMD_ERR_ECMD | 0x10C7) ///< Sensor Id not supported for sensor
#define ECMD_SENSOR_THERMAL_NOT_SUPPORTED       (ECMD_ERR_ECMD | 0x10C9) ///< Thermal Sensor data not available
#define ECMD_FATAL_FAILURE                      (ECMD_ERR_ECMD | 0x10CB) ///< Fatal error during plugin load due to library versions mismatch
#define ECMD_WILDCARD_CHAR_NOT_SUPPORTED        (ECMD_ERR_ECMD | 0x10CD) ///< Wildcard 'x' was used with a command that doesn't support it
#define ECMD_WILDCARD_MISUSE                    (ECMD_ERR_ECMD | 0x10CF) ///< Wildcard 'x' was used incorrectly - i.e. as a chipunit
#define ECMD_UNABLE_TO_OPEN_SPYDEF              (ECMD_ERR_ECMD | 0x10D1) ///< eCMD was unable to open the spydef

/* Return codes for command interpreter */
#define ECMD_INT_UNKNOWN_COMMAND                (ECMD_ERR_ECMD | 0x1901)  ///< Command interpreter didn't understand command
#define ECMD_EXPECT_FAILURE                     (ECMD_ERR_ECMD | 0x1903)  ///< An expect was performed and a miscompare was found
#define ECMD_SCANDEF_LOOKUP_FAILURE             (ECMD_ERR_ECMD | 0x1905)  ///< An Error occurred trying to process the scandef file
#define ECMD_DATA_BOUNDS_OVERFLOW               (ECMD_ERR_ECMD | 0x1907)  ///< The user specified to get/put data that was larger then ECMD_MAX_DATA_BITS
#define ECMD_SPYDEF_LOOKUP_FAILURE              (ECMD_ERR_ECMD | 0x1909)  ///< An Error occurred trying to process the scandef file

/* dataBuffer specific return codes */
#ifndef ECMD_DBUF_SUCCESS
 #define ECMD_DBUF_SUCCESS                       0x0    ///< DataBuffer returned successfully
 #define ECMD_DBUF_INIT_FAIL                     (ECMD_ERR_ECMD | 0x2001) ///< Initialization of the DataBuffer failed
 #define ECMD_DBUF_BUFFER_OVERFLOW               (ECMD_ERR_ECMD | 0x2011) ///< Attempt to read/write data beyond the length of the DataBuffer
 #define ECMD_DBUF_XSTATE_ERROR                  (ECMD_ERR_ECMD | 0x2021) ///< An 'X' character occured where it was not expected
 #define ECMD_DBUF_UNDEFINED_FUNCTION            (ECMD_ERR_ECMD | 0x2031) ///< Function not included in this version of DataBuffer
 #define ECMD_DBUF_INVALID_ARGS                  (ECMD_ERR_ECMD | 0x2041) ///< Args provided to dataBuffer were invalid
 #define ECMD_DBUF_INVALID_DATA_FORMAT           (ECMD_ERR_ECMD | 0x2043) ///< String data didn't match expected input format
 #define ECMD_DBUF_FOPEN_FAIL                    (ECMD_ERR_ECMD | 0x2051) ///< File open on file for reading or writing the data buffer failed
 #define ECMD_DBUF_FILE_FORMAT_MISMATCH          (ECMD_ERR_ECMD | 0x2053) ///< In readFile specified format not found in the data file
 #define ECMD_DBUF_DATANUMBER_NOT_FOUND          (ECMD_ERR_ECMD | 0x2055) ///< In readFileMultiple specified data number  not found in file
 #define ECMD_DBUF_FILE_OPERATION_FAIL           (ECMD_ERR_ECMD | 0x2057) ///< File operation failed
 #define ECMD_DBUF_NOT_OWNER                     (ECMD_ERR_ECMD | 0x2061) ///< Don't own this buffer so can't do this operation
 #define ECMD_DBUF_XSTATE_NOT_ENABLED            (ECMD_ERR_ECMD | 0x2063) ///< Xstate function called on a buffer that doesn't have xstates enabled
 #define ECMD_DBUF_MISMATCH                      (ECMD_ERR_ECMD | 0x2065) ///< There was a mismatch between a comparision operation in the buffer
 #define ECMD_DBUF_NULL_POINTER                  (ECMD_ERR_ECMD | 0x2067) ///< Null pointer passed
#endif

#define ECMD_GET_ALL_REMAINING_ERRORS            (ECMD_ERR_ECMD | 0xFFFF) ///< Retrieve all errors from getErrorMsg.  Not to be used.

#endif /* ecmdReturnCodes_h */
<commit_msg>removal of duplicate file<commit_after><|endoftext|>


<commit_before>#include "Notfredo.h"
#include "Camera.h"
#include "StageState.h"
#include "Gallahad.h"
#include "Lancelot.h"
#include "Vec2.h"
#include "Rect.h"
#include "Attack.h"
#include "Melee.h"
#include "Projectile.h"
#include "IAComponent.h"
#include "Room.h"

typedef struct Node node;

struct Node{
  int x,y,z;
  float graph_distance;
  float physical_distance;
  float combined_distance;
  bool discovered;
  node* going_through;
  node* next;
};

Notfredo::Notfredo(int x, int y,Type type):
	Character(x,y),
	radius(),
	looking(1500),
	idle(1500)
{
	inputComponent = new IAComponent();
    if(type == GROUND)
    {
        graphicsComponent = new NotfredoGraphicsComponent("EnemyGallahad");
    }
    if(type == FLYING)
    {
        graphicsComponent = new NotfredoGraphicsComponent("Drone inimigo Idle Sprite");

    }
	name = "Notfredo";
	box.SetWH(graphicsComponent->GetSize());
	idle.Start();
    this->type = type;
}

Notfredo::~Notfredo()
{

}

void Notfredo::Attack()
{
	//Starts attack timer
	attacking.Start();
	//Generates attack object
	StageState::AddObject(new Melee("Melee.png", 2, 0, this, 500, 1));
}

void Notfredo::NotifyTileCollision(int tile, Face face)
{
	if(tile >= SOLID_TILE && (face == LEFT || face == RIGHT))
	{
		if(physicsComponent.velocity.y >= 0.6)
		{
			physicsComponent.velocity.y = -0.5;
		}
	}
}

void Notfredo::UpdateTimers(float dt)
{
	invincibilityTimer.Update(dt);
	attacking.Update(dt);
	if(looking.IsRunning())
	{
		looking.Update(dt);
		if(!looking.IsRunning())
			idle.Start();
	}
	else if(idle.IsRunning())
	{
		idle.Update(dt);
		if(!idle.IsRunning())
			looking.Start();
	}
}

node* Notfredo::New(int x,int y,int z,float physical_distance)
{
    node* aux = new node;
    aux->x = x;
    aux->y = y;
    aux->z = z;
    aux->combined_distance = MAX_VALUE;
    aux->discovered = false;
    aux->going_through = nullptr;
    aux->graph_distance = 0;
    aux->next = nullptr;
    aux->physical_distance = physical_distance;

    return aux;
}

node* Notfredo::Pop(node* stack)
{
    node* aux = stack;

    stack = stack->next;

    return aux;
}

void Notfredo::Push(int x,int y,int z,node* stack,float physical_distance)
{
    node* aux = stack;

    while(aux->next != nullptr){
        aux = aux->next;
    }

    aux->next = New(x,y,z,physical_distance);
}

void Notfredo::CopyNode(node* source,node* target){

    target->combined_distance = source->combined_distance;
    target->discovered = source->discovered;
    target->going_through = source->going_through;
    target->graph_distance = source->graph_distance;
    target->next = source->next;
    target->physical_distance = source->physical_distance;
    target->x = source->x;
    target->y = source->y;
    target->z = source->z;

}

void Notfredo::QuickSort(node* tileStack, int start, int end)
{

    int pivot, i, j, half;

    node* aux;

    i = start;
    j = end;

    half = (int) ((i + j) / 2);
    pivot = tileStack[half].combined_distance;

    do
    {
      while (tileStack[i].combined_distance < pivot) i = i + 1;
      while (tileStack[j].combined_distance > pivot) j = j - 1;

      if(i <= j)
      {
         CopyNode(&tileStack[i],aux);

         CopyNode(&tileStack[j],&tileStack[i]);

         CopyNode(aux,&tileStack[j]);

         i = i + 1;
         j = j - 1;
      }
    }while(j > i);

    if(start < j) QuickSort(tileStack, start, j);
    if(i < end) QuickSort(tileStack, i, end);
}

node* Notfredo::Find(node* tileStack,int x,int y)
    {
       node* aux = tileStack;
       while(aux->x != x || aux->y != y) aux = aux->next;
       return aux;

    }

node* Notfredo::PathFind()
{

     int mapWidth = StageState::GetCurrentRoom()->GetMap()->GetWidth();

     int mapHeight =  StageState::GetCurrentRoom()->GetMap()->GetHeight();

     int x,y,pathStackSize = 1;

    node tileStack,startTile,endTile;
    node* aux;
    node* currentNode;
    node* pathStack;

    //for all tiles in current tilemap
        //push new node with tile coordinates,
        //combined distance of MAX_VALUE(to be determined),
        //and physical_distance as the distance between the
        //tile and the target(player)

    for(x = 0;x < mapWidth; x++)
    {
        for(y = 0;y < mapHeight; y++)
        {
           Push(x,y,0,&tileStack,StageState::GetCurrentRoom()->GetMap()->GetTileBox(x,y).GetCenter().distance(StageState::GetPlayer()->box.GetCenter()));
        }
    }

    //starting with start tile(fredo's tile)

    this->CurrentTile(&startTile.x,&startTile.y,&startTile.z);

    if(StageState::GetPlayer()->Is("Gallahad"))
    {
        //Gallahad::CurrentTile(&endTile.x,&endTile.y,&endTile.z);
    }
    else if(StageState::GetPlayer()->Is("Lancelot"))
         {
            //Lancelot::CurrentTile(&endTile.x,&endTile.y,&endTile.z);
         }

    currentNode = Find(&tileStack,startTile.x,startTile.y);
    currentNode->combined_distance = currentNode->physical_distance+currentNode->graph_distance;
    Push(currentNode->x,currentNode->y,currentNode->z,pathStack,currentNode->physical_distance);

    while(pathStack->x != endTile.x && pathStack->y != endTile.y)
    {

        aux = currentNode;

        for(int i = 0;i < 4;i++)
        {
            if(i == 0 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x+1,currentNode->y,0) != SOLID_TILE)
            {

                aux->x+=1;
            }

            if(i == 1 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x-1,currentNode->y,0) != SOLID_TILE)
            {

                aux->x-=1;
            }
            if(i == 2 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x,currentNode->y+1,0) != SOLID_TILE)
            {

                aux->y+=1;
            }
            if(i == 3 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x,currentNode->y-1,0) != SOLID_TILE)
            {

                aux->y-=1;
            }

            if(!aux->discovered)
            {
                aux->graph_distance+=1;

                aux->combined_distance = aux->graph_distance + aux->physical_distance;

                aux->going_through = currentNode;

                Push(aux->x,aux->y,aux->z,pathStack,aux->physical_distance);

                pathStackSize++;

                aux->discovered = true;

            }

        }

        QuickSort(pathStack,0,pathStackSize-1);

        currentNode = Pop(pathStack);

    }

    aux = pathStack;

    while(aux->going_through != nullptr){
        aux = aux->going_through;
    }

    return aux;

    //while top of stack is not the target's tile
        //pop top of stack. That is the current node

        //for all nodes adjacent to current node
            //if node is undiscovered(discovered == false)
                //tile's graph distance is current node's graph distance plus distance
                //between current node and adjacent node

                //tile's combined distance is it's graph distance plus its physical distance

            //else if tile's graph distance is lower than current tile's graph distance plus
            //distance between current node and adjacent node
                //replace graph distance in tile and update combined distance
                //else, do nothing
        //order stack by total distance

    //return sequence of tiles to target

}

void Notfredo::UpdateAI(float dt)
{
    if(type == GROUND)
    {
        radius = Rect(box.x-200, box.y-200, box.w+400, box.h+400);
        if(StageState::GetPlayer())
        {
            Rect player = StageState::GetPlayer()->box;
            bool visible = true;
            if(StageState::GetPlayer()->Is("Gallahad"))
            {
                Gallahad* p = (Gallahad*) StageState::GetPlayer();
                if(p->Hiding())
                {
                    visible = false;
                }
            }
            if(player.OverlapsWith(radius) && visible)
            {
                if(player.x < box.x )
                {
                    physicsComponent.velocity.x -= 0.003*dt;
                    if(box.x - physicsComponent.velocity.x*dt < player.x)
                    {
                        box.x = player.x;
                        physicsComponent.velocity.x = 0;
                    }
                    facing = LEFT;
                }
                else
                {
                    physicsComponent.velocity.x += 0.003*dt;
                    if(box.x + physicsComponent.velocity.x*dt > player.x)
                    {
                        box.x = player.x;
                        physicsComponent.velocity.x = 0;
                    }
                    facing = RIGHT;
                }
                clamp(physicsComponent.velocity.x,-0.4f,0.4f);

                if(!Attacking())
                {
                    Attack();
                }
            }
            else if(looking.IsRunning() && looking.GetElapsed() == 0)
            {
                if(facing == LEFT)
                    physicsComponent.velocity.x = -0.2;
                else
                    physicsComponent.velocity.x = 0.2;
            }
            else
            {
                if(idle.IsRunning() && idle.GetElapsed() == 0)
                {
                    physicsComponent.velocity.x = 0;
                    if(facing == LEFT)
                    {
                        facing = RIGHT;
                    }
                    else
                    {
                        facing = LEFT;
                    }
                }
            }
        }
    }
    if(type == FLYING)
    {
        node* aux = PathFind();
        box.x = aux->x;
        box.y = aux->y;
    }
}

void Notfredo::Update(TileMap* world, float dt)
{
	UpdateTimers(dt);
	UpdateAI(dt);
	inputComponent->Update(this,dt);
	physicsComponent.Update(this,world,dt);
	graphicsComponent->Update(this,dt);
}

bool Notfredo::Is(std::string type)
{
	return (type=="Enemy");
}
<commit_msg>Conserto<commit_after>#include "Notfredo.h"
#include "Camera.h"
#include "StageState.h"
#include "Gallahad.h"
#include "Lancelot.h"
#include "Vec2.h"
#include "Rect.h"
#include "Attack.h"
#include "Melee.h"
#include "Projectile.h"
#include "IAComponent.h"
#include "Room.h"

typedef struct Node node;

struct Node{
  int x,y,z;
  float graph_distance;
  float physical_distance;
  float combined_distance;
  bool discovered;
  node* going_through;
  node* next;
};

Notfredo::Notfredo(int x, int y,Type type):
	Character(x,y),
	radius(),
	looking(1500),
	idle(1500)
{
	inputComponent = new IAComponent();
    if(type == GROUND)
    {
        graphicsComponent = new NotfredoGraphicsComponent("EnemyGallahad");
    }
    if(type == FLYING)
    {
        graphicsComponent = new NotfredoGraphicsComponent("DroneInimigoSprite");

    }
	name = "Notfredo";
	box.SetWH(graphicsComponent->GetSize());
	idle.Start();
    this->type = type;
}

Notfredo::~Notfredo()
{

}

void Notfredo::Attack()
{
	//Starts attack timer
	attacking.Start();
	//Generates attack object
	StageState::AddObject(new Melee("Melee.png", 2, 0, this, 500, 1));
}

void Notfredo::NotifyTileCollision(int tile, Face face)
{
	if(tile >= SOLID_TILE && (face == LEFT || face == RIGHT))
	{
		if(physicsComponent.velocity.y >= 0.6)
		{
			physicsComponent.velocity.y = -0.5;
		}
	}
}

void Notfredo::UpdateTimers(float dt)
{
	invincibilityTimer.Update(dt);
	attacking.Update(dt);
	if(looking.IsRunning())
	{
		looking.Update(dt);
		if(!looking.IsRunning())
			idle.Start();
	}
	else if(idle.IsRunning())
	{
		idle.Update(dt);
		if(!idle.IsRunning())
			looking.Start();
	}
}

node* Notfredo::New(int x,int y,int z,float physical_distance)
{
    node* aux = new node;
    aux->x = x;
    aux->y = y;
    aux->z = z;
    aux->combined_distance = MAX_VALUE;
    aux->discovered = false;
    aux->going_through = nullptr;
    aux->graph_distance = 0;
    aux->next = nullptr;
    aux->physical_distance = physical_distance;

    return aux;
}

node* Notfredo::Pop(node* stack)
{
    node* aux = stack;

    stack = stack->next;

    return aux;
}

void Notfredo::Push(int x,int y,int z,node* stack,float physical_distance)
{
    node* aux = stack;

    while(aux->next != nullptr){
        aux = aux->next;
    }

    aux->next = New(x,y,z,physical_distance);
}

void Notfredo::CopyNode(node* source,node* target){

    target->combined_distance = source->combined_distance;
    target->discovered = source->discovered;
    target->going_through = source->going_through;
    target->graph_distance = source->graph_distance;
    target->next = source->next;
    target->physical_distance = source->physical_distance;
    target->x = source->x;
    target->y = source->y;
    target->z = source->z;

}

void Notfredo::QuickSort(node* tileStack, int start, int end)
{

    int pivot, i, j, half;

    node* aux;

    i = start;
    j = end;

    half = (int) ((i + j) / 2);
    pivot = tileStack[half].combined_distance;

    do
    {
      while (tileStack[i].combined_distance < pivot) i = i + 1;
      while (tileStack[j].combined_distance > pivot) j = j - 1;

      if(i <= j)
      {
         CopyNode(&tileStack[i],aux);

         CopyNode(&tileStack[j],&tileStack[i]);

         CopyNode(aux,&tileStack[j]);

         i = i + 1;
         j = j - 1;
      }
    }while(j > i);

    if(start < j) QuickSort(tileStack, start, j);
    if(i < end) QuickSort(tileStack, i, end);
}

node* Notfredo::Find(node* tileStack,int x,int y)
    {
       node* aux = tileStack;
       while(aux->x != x || aux->y != y) aux = aux->next;
       return aux;

    }

node* Notfredo::PathFind()
{

     int mapWidth = StageState::GetCurrentRoom()->GetMap()->GetWidth();

     int mapHeight =  StageState::GetCurrentRoom()->GetMap()->GetHeight();

     int x,y,pathStackSize = 1;

    node tileStack,startTile,endTile;
    node* aux;
    node* currentNode;
    node* pathStack;

    //for all tiles in current tilemap
        //push new node with tile coordinates,
        //combined distance of MAX_VALUE(to be determined),
        //and physical_distance as the distance between the
        //tile and the target(player)

    for(x = 0;x < mapWidth; x++)
    {
        for(y = 0;y < mapHeight; y++)
        {
           Push(x,y,0,&tileStack,StageState::GetCurrentRoom()->GetMap()->GetTileBox(x,y).GetCenter().distance(StageState::GetPlayer()->box.GetCenter()));
        }
    }

    //starting with start tile(fredo's tile)

    this->CurrentTile(&startTile.x,&startTile.y,&startTile.z);

    if(StageState::GetPlayer()->Is("Gallahad"))
    {
        //Gallahad::CurrentTile(&endTile.x,&endTile.y,&endTile.z);
    }
    else if(StageState::GetPlayer()->Is("Lancelot"))
         {
            //Lancelot::CurrentTile(&endTile.x,&endTile.y,&endTile.z);
         }

    currentNode = Find(&tileStack,startTile.x,startTile.y);
    currentNode->combined_distance = currentNode->physical_distance+currentNode->graph_distance;
    Push(currentNode->x,currentNode->y,currentNode->z,pathStack,currentNode->physical_distance);

    while(pathStack->x != endTile.x && pathStack->y != endTile.y)
    {

        aux = currentNode;

        for(int i = 0;i < 4;i++)
        {
            if(i == 0 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x+1,currentNode->y,0) != SOLID_TILE)
            {

                aux->x+=1;
            }

            if(i == 1 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x-1,currentNode->y,0) != SOLID_TILE)
            {

                aux->x-=1;
            }
            if(i == 2 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x,currentNode->y+1,0) != SOLID_TILE)
            {

                aux->y+=1;
            }
            if(i == 3 && StageState::GetCurrentRoom()->GetMap()->At(currentNode->x,currentNode->y-1,0) != SOLID_TILE)
            {

                aux->y-=1;
            }

            if(!aux->discovered)
            {
                aux->graph_distance+=1;

                aux->combined_distance = aux->graph_distance + aux->physical_distance;

                aux->going_through = currentNode;

                Push(aux->x,aux->y,aux->z,pathStack,aux->physical_distance);

                pathStackSize++;

                aux->discovered = true;

            }

        }

        QuickSort(pathStack,0,pathStackSize-1);

        currentNode = Pop(pathStack);

    }

    aux = pathStack;

    while(aux->going_through != nullptr){
        aux = aux->going_through;
    }

    return aux;

    //while top of stack is not the target's tile
        //pop top of stack. That is the current node

        //for all nodes adjacent to current node
            //if node is undiscovered(discovered == false)
                //tile's graph distance is current node's graph distance plus distance
                //between current node and adjacent node

                //tile's combined distance is it's graph distance plus its physical distance

            //else if tile's graph distance is lower than current tile's graph distance plus
            //distance between current node and adjacent node
                //replace graph distance in tile and update combined distance
                //else, do nothing
        //order stack by total distance

    //return sequence of tiles to target

}

void Notfredo::UpdateAI(float dt)
{
    if(type == GROUND)
    {
        radius = Rect(box.x-200, box.y-200, box.w+400, box.h+400);
        if(StageState::GetPlayer())
        {
            Rect player = StageState::GetPlayer()->box;
            bool visible = true;
            if(StageState::GetPlayer()->Is("Gallahad"))
            {
                Gallahad* p = (Gallahad*) StageState::GetPlayer();
                if(p->Hiding())
                {
                    visible = false;
                }
            }
            if(player.OverlapsWith(radius) && visible)
            {
                if(player.x < box.x )
                {
                    physicsComponent.velocity.x -= 0.003*dt;
                    if(box.x - physicsComponent.velocity.x*dt < player.x)
                    {
                        box.x = player.x;
                        physicsComponent.velocity.x = 0;
                    }
                    facing = LEFT;
                }
                else
                {
                    physicsComponent.velocity.x += 0.003*dt;
                    if(box.x + physicsComponent.velocity.x*dt > player.x)
                    {
                        box.x = player.x;
                        physicsComponent.velocity.x = 0;
                    }
                    facing = RIGHT;
                }
                clamp(physicsComponent.velocity.x,-0.4f,0.4f);

                if(!Attacking())
                {
                    Attack();
                }
            }
            else if(looking.IsRunning() && looking.GetElapsed() == 0)
            {
                if(facing == LEFT)
                    physicsComponent.velocity.x = -0.2;
                else
                    physicsComponent.velocity.x = 0.2;
            }
            else
            {
                if(idle.IsRunning() && idle.GetElapsed() == 0)
                {
                    physicsComponent.velocity.x = 0;
                    if(facing == LEFT)
                    {
                        facing = RIGHT;
                    }
                    else
                    {
                        facing = LEFT;
                    }
                }
            }
        }
    }
    if(type == FLYING)
    {
        node* aux = PathFind();
        box.x = aux->x;
        box.y = aux->y;
    }
}

void Notfredo::Update(TileMap* world, float dt)
{
	UpdateTimers(dt);
	UpdateAI(dt);
	inputComponent->Update(this,dt);
	physicsComponent.Update(this,world,dt);
	graphicsComponent->Update(this,dt);
}

bool Notfredo::Is(std::string type)
{
	return (type=="Enemy");
}
<|endoftext|>


<commit_before>/*
This file is part of WME Lite.
http://dead-code.org/redir.php?target=wmelite

Copyright (c) 2011 Jan Nedoma

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "dcgf.h"
#include <algorithm>
#include <fstream>
#include "PathUtil.h"
#include "StringUtil.h"

#ifdef __WIN32__
#	include <shlobj.h>
#	include <io.h>
#else
#   include <dirent.h>
#endif

#ifdef __MACOSX__
#	include <CoreServices/CoreServices.h>
#endif

#ifdef __IPHONEOS__
#	include "ios_utils.h"
#endif

#ifdef __ANDROID__
#	include "android.h"
#endif

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::UnifySeparators(const AnsiString& path)
{
	AnsiString newPath = path;

	std::replace(newPath.begin(), newPath.end(), L'\\', L'/');
	return newPath;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::NormalizeFileName(const AnsiString& path)
{
	AnsiString newPath = UnifySeparators(path);
	StringUtil::ToLowerCase(newPath);
	return newPath;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::Combine(const AnsiString& path1, const AnsiString& path2)
{
	AnsiString newPath1 = UnifySeparators(path1);
	AnsiString newPath2 = UnifySeparators(path2);

	if (!StringUtil::EndsWith(newPath1, "/", true) && !StringUtil::StartsWith(newPath2, "/", true))
		newPath1 += "/";

	return newPath1 + newPath2;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetDirectoryName(const AnsiString& path)
{
	AnsiString newPath = UnifySeparators(path);

	size_t pos = newPath.find_last_of(L'/');

	if (pos == AnsiString::npos) return "";
	else return newPath.substr(0, pos + 1);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetFileName(const AnsiString& path)
{
	AnsiString newPath = UnifySeparators(path);

	size_t pos = newPath.find_last_of(L'/');

	if (pos == AnsiString::npos) return path;
	else return newPath.substr(pos + 1);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetFileNameWithoutExtension(const AnsiString& path)
{
	AnsiString fileName = GetFileName(path);

	size_t pos = fileName.find_last_of('.');

	if (pos == AnsiString::npos) return fileName;
	else return fileName.substr(0, pos);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetExtension(const AnsiString& path)
{
	AnsiString fileName = GetFileName(path);

	size_t pos = fileName.find_last_of('.');

	if (pos == AnsiString::npos) return "";
	else return fileName.substr(pos);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetSafeLogFileName()
{
#ifndef __ANDROID__

	AnsiString logFileName = GetUserDirectory();

#ifdef __WIN32__
	char moduleName[MAX_PATH];
	::GetModuleFileName(NULL, moduleName, MAX_PATH);

	AnsiString fileName = GetFileNameWithoutExtension(moduleName) + ".log";
	fileName = Combine("/Wintermute Engine/Logs/", fileName);
	logFileName = Combine(logFileName, fileName);

#else
	// !PORTME
	logFileName = Combine(logFileName, "/Wintermute Engine/wme.log");
#endif

#else
	char androidPath[1024];
	android_getLogFileDirectory(androidPath, 1024);
	// use a storage path in Android that is easily available
	// typically that would be the external storage path
	AnsiString logFileName = Combine(androidPath, "/wme.log");

#endif

	CreateDirectory(GetDirectoryName(logFileName));
	return logFileName;
}

//////////////////////////////////////////////////////////////////////////
bool PathUtil::CreateDirectory(const AnsiString& path)
{
	return false;
}

//////////////////////////////////////////////////////////////////////////
bool PathUtil::MatchesMask(const AnsiString& fileName, const AnsiString& mask)
{
	return false;
}

//////////////////////////////////////////////////////////////////////////
bool PathUtil::FileExists(const AnsiString& fileName)
{
	std::ifstream stream;

	stream.open(fileName.c_str());
	bool ret = stream.is_open();
	stream.close();

	return ret;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetUserDirectory()
{
	AnsiString userDir = "./";

#ifdef __WIN32__
	char buffer[MAX_PATH];
	buffer[0] = '\0';
	LPITEMIDLIST pidl = NULL;
	LPMALLOC pMalloc;
	if(SUCCEEDED(SHGetMalloc(&pMalloc)))
	{
		SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA, &pidl);
		if(pidl)
		{
			SHGetPathFromIDList(pidl, buffer);
		}
		pMalloc->Free(pidl);
		userDir = AnsiString(buffer);
	}
#elif __MACOSX__
	FSRef fileRef;
	OSStatus error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, true, &fileRef);
	if (error == noErr)
	{
		char buffer[MAX_PATH];
		error = FSRefMakePath(&fileRef, (UInt8*)buffer, sizeof(buffer));
		if (error == noErr)
			userDir = buffer;

	}
#elif __IPHONEOS__
	char path[MAX_PATH];
	IOS_GetDataDir(path);
	userDir = AnsiString(path);
#elif __ANDROID__
	char androidPath[1024];
	android_getPrivateFilesPath(androidPath, 1024);
	userDir = AnsiString(androidPath);

#endif

	return userDir;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetAbsolutePath(const AnsiString& path)
{
	char fullPath[MAX_PATH];
#ifdef _WIN32
	_fullpath(fullPath, path.c_str(), MAX_PATH);
#else
	realpath(path.c_str(), fullPath);
#endif
	return AnsiString(fullPath);
}

//////////////////////////////////////////////////////////////////////////
void PathUtil::GetFilesInDirectory(const AnsiString& path, const AnsiString& mask, AnsiStringList& files)
{
	AnsiString fileSpec = PathUtil::Combine(path, mask);

#ifdef _WIN32
	struct _finddata_t c_file;
	intptr_t hFile;

	if ((hFile = _findfirst(fileSpec.c_str(), &c_file)) == -1L) return;
	else
	{
		do
		{
			if (!(c_file.attrib & _A_SUBDIR))
			{
				files.push_back(c_file.name);
			}
		} while (_findnext(hFile, &c_file ) == 0);
		_findclose(hFile);
	}
#else
    DIR* dir;
    struct dirent* entry;

    dir = opendir(path.c_str());
    if (dir)
    {
        while ((entry = readdir(dir)) != NULL)
        {
            if (CBUtils::MatchesPattern(mask.c_str(), entry->d_name))
            {
                files.push_back(entry->d_name);
            }
        }
        closedir(dir);
    }
#endif
}
<commit_msg>increase buffer for unix absolute paths to avoid buffer overflow observed in Linux<commit_after>/*
This file is part of WME Lite.
http://dead-code.org/redir.php?target=wmelite

Copyright (c) 2011 Jan Nedoma

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "dcgf.h"
#include <algorithm>
#include <fstream>
#include "PathUtil.h"
#include "StringUtil.h"

#ifdef __WIN32__
#	include <shlobj.h>
#	include <io.h>
#else
#   include <dirent.h>
#endif

#ifdef __MACOSX__
#	include <CoreServices/CoreServices.h>
#endif

#ifdef __IPHONEOS__
#	include "ios_utils.h"
#endif

#ifdef __ANDROID__
#	include "android.h"
#endif

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::UnifySeparators(const AnsiString& path)
{
	AnsiString newPath = path;

	std::replace(newPath.begin(), newPath.end(), L'\\', L'/');
	return newPath;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::NormalizeFileName(const AnsiString& path)
{
	AnsiString newPath = UnifySeparators(path);
	StringUtil::ToLowerCase(newPath);
	return newPath;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::Combine(const AnsiString& path1, const AnsiString& path2)
{
	AnsiString newPath1 = UnifySeparators(path1);
	AnsiString newPath2 = UnifySeparators(path2);

	if (!StringUtil::EndsWith(newPath1, "/", true) && !StringUtil::StartsWith(newPath2, "/", true))
		newPath1 += "/";

	return newPath1 + newPath2;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetDirectoryName(const AnsiString& path)
{
	AnsiString newPath = UnifySeparators(path);

	size_t pos = newPath.find_last_of(L'/');

	if (pos == AnsiString::npos) return "";
	else return newPath.substr(0, pos + 1);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetFileName(const AnsiString& path)
{
	AnsiString newPath = UnifySeparators(path);

	size_t pos = newPath.find_last_of(L'/');

	if (pos == AnsiString::npos) return path;
	else return newPath.substr(pos + 1);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetFileNameWithoutExtension(const AnsiString& path)
{
	AnsiString fileName = GetFileName(path);

	size_t pos = fileName.find_last_of('.');

	if (pos == AnsiString::npos) return fileName;
	else return fileName.substr(0, pos);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetExtension(const AnsiString& path)
{
	AnsiString fileName = GetFileName(path);

	size_t pos = fileName.find_last_of('.');

	if (pos == AnsiString::npos) return "";
	else return fileName.substr(pos);
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetSafeLogFileName()
{
#ifndef __ANDROID__

	AnsiString logFileName = GetUserDirectory();

#ifdef __WIN32__
	char moduleName[MAX_PATH];
	::GetModuleFileName(NULL, moduleName, MAX_PATH);

	AnsiString fileName = GetFileNameWithoutExtension(moduleName) + ".log";
	fileName = Combine("/Wintermute Engine/Logs/", fileName);
	logFileName = Combine(logFileName, fileName);

#else
	// !PORTME
	logFileName = Combine(logFileName, "/Wintermute Engine/wme.log");
#endif

#else
	char androidPath[1024];
	android_getLogFileDirectory(androidPath, 1024);
	// use a storage path in Android that is easily available
	// typically that would be the external storage path
	AnsiString logFileName = Combine(androidPath, "/wme.log");

#endif

	CreateDirectory(GetDirectoryName(logFileName));
	return logFileName;
}

//////////////////////////////////////////////////////////////////////////
bool PathUtil::CreateDirectory(const AnsiString& path)
{
	return false;
}

//////////////////////////////////////////////////////////////////////////
bool PathUtil::MatchesMask(const AnsiString& fileName, const AnsiString& mask)
{
	return false;
}

//////////////////////////////////////////////////////////////////////////
bool PathUtil::FileExists(const AnsiString& fileName)
{
	std::ifstream stream;

	stream.open(fileName.c_str());
	bool ret = stream.is_open();
	stream.close();

	return ret;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetUserDirectory()
{
	AnsiString userDir = "./";

#ifdef __WIN32__
	char buffer[MAX_PATH];
	buffer[0] = '\0';
	LPITEMIDLIST pidl = NULL;
	LPMALLOC pMalloc;
	if(SUCCEEDED(SHGetMalloc(&pMalloc)))
	{
		SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA, &pidl);
		if(pidl)
		{
			SHGetPathFromIDList(pidl, buffer);
		}
		pMalloc->Free(pidl);
		userDir = AnsiString(buffer);
	}
#elif __MACOSX__
	FSRef fileRef;
	OSStatus error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, true, &fileRef);
	if (error == noErr)
	{
		char buffer[MAX_PATH];
		error = FSRefMakePath(&fileRef, (UInt8*)buffer, sizeof(buffer));
		if (error == noErr)
			userDir = buffer;

	}
#elif __IPHONEOS__
	char path[MAX_PATH];
	IOS_GetDataDir(path);
	userDir = AnsiString(path);
#elif __ANDROID__
	char androidPath[1024];
	android_getPrivateFilesPath(androidPath, 1024);
	userDir = AnsiString(androidPath);

#endif

	return userDir;
}

//////////////////////////////////////////////////////////////////////////
AnsiString PathUtil::GetAbsolutePath(const AnsiString& path)
{
#ifdef _WIN32
	char fullPath[MAX_PATH];
	_fullpath(fullPath, path.c_str(), MAX_PATH);
#else
	char fullPath[32768]; // UNIX paths can be longer
	realpath(path.c_str(), fullPath);
#endif
	return AnsiString(fullPath);
}

//////////////////////////////////////////////////////////////////////////
void PathUtil::GetFilesInDirectory(const AnsiString& path, const AnsiString& mask, AnsiStringList& files)
{
	AnsiString fileSpec = PathUtil::Combine(path, mask);

#ifdef _WIN32
	struct _finddata_t c_file;
	intptr_t hFile;

	if ((hFile = _findfirst(fileSpec.c_str(), &c_file)) == -1L) return;
	else
	{
		do
		{
			if (!(c_file.attrib & _A_SUBDIR))
			{
				files.push_back(c_file.name);
			}
		} while (_findnext(hFile, &c_file ) == 0);
		_findclose(hFile);
	}
#else
    DIR* dir;
    struct dirent* entry;

    dir = opendir(path.c_str());
    if (dir)
    {
        while ((entry = readdir(dir)) != NULL)
        {
            if (CBUtils::MatchesPattern(mask.c_str(), entry->d_name))
            {
                files.push_back(entry->d_name);
            }
        }
        closedir(dir);
    }
#endif
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_revert_sbe_mcs_setup.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_revert_sbe_mcs_setup.C
/// @brief Revert MC configuration applied by SBE (FAPI2)

///
/// @author Joe McGill <jmcgill@us.ibm.com>
///

//
// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB
//

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_revert_sbe_mcs_setup.H>
#include <p9_perv_scom_addresses.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------

// MCS target type constants
const uint8_t NUM_MCS_TARGETS = 4;

const uint64_t MCS_CPLT_CTRL1_ARR[NUM_MCS_TARGETS] =
{
    PERV_N3_CPLT_CTRL1,
    PERV_N3_CPLT_CTRL1,
    PERV_N1_CPLT_CTRL1,
    PERV_N1_CPLT_CTRL1
};

const uint64_t MCS_CPLT_CTRL1_BIT_ARR[NUM_MCS_TARGETS] =
{
    10,
    10,
    9,
    9
};

const uint64_t MCS_MCFGP_ARR[NUM_MCS_TARGETS] =
{
    MCS_0_MCFGP,
    MCS_1_MCFGP,
    MCS_2_MCFGP,
    MCS_3_MCFGP
};
const uint64_t MCS_MCMODE1_ARR[NUM_MCS_TARGETS] =
{
    MCS_0_MCMODE1,
    MCS_1_MCMODE1,
    MCS_2_MCMODE1,
    MCS_3_MCMODE1
};
const uint64_t MCS_MCFIRMASK_OR_ARR[NUM_MCS_TARGETS] =
{
    MCS_0_MCFIRMASK_OR,
    MCS_1_MCFIRMASK_OR,
    MCS_2_MCFIRMASK_OR,
    MCS_3_MCFIRMASK_OR
};

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

// helper function for MCS target type
fapi2::ReturnCode
revert_mcs_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
                          const uint8_t i_mcs)
{
    FAPI_DBG("Start");
    fapi2::buffer<uint64_t> l_cplt_ctrl1;
    fapi2::buffer<uint64_t> l_mcfgp;
    fapi2::buffer<uint64_t> l_mcmode1;
    fapi2::buffer<uint64_t> l_mcfirmask;

    FAPI_TRY(fapi2::getScom(i_target, MCS_CPLT_CTRL1_ARR[i_mcs], l_cplt_ctrl1),
             "Error from getscom (CPLT_CTRL1)");

    if (!l_cplt_ctrl1.getBit(MCS_CPLT_CTRL1_BIT_ARR[i_mcs]))
    {
        // MCFGP -- mark BAR invalid & reset grouping configuration fields
        FAPI_TRY(fapi2::getScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),
                 "Error from getScom (MCS%d_MCFGP)", i_mcs);
        l_mcfgp.clearBit<MCS_MCFGP_VALID>();
        l_mcfgp.clearBit<MCS_MCFGP_MC_CHANNELS_PER_GROUP,
                         MCS_MCFGP_MC_CHANNELS_PER_GROUP_LEN>();
        l_mcfgp.clearBit<MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION,
                         MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION_LEN>();
        l_mcfgp.clearBit<MCS_MCFGP_GROUP_SIZE, MCS_MCFGP_GROUP_SIZE_LEN>();
        FAPI_TRY(fapi2::putScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),
                 "Error from putScom (MCS%d_MCFGP)", i_mcs);

        // MCMODE1 -- enable speculation
        FAPI_TRY(fapi2::getScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),
                 "Error from getScom (MCS%d_MCMODE1)", i_mcs);
        l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_ALL_SPEC_OPS>();
        l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_SPEC_OP,
                           MCS_MCMODE1_DISABLE_SPEC_OP_LEN>();
        FAPI_TRY(fapi2::putScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),
                 "Error from putScom (MCS%d_MCMODE1)", i_mcs);

        // Re-mask MCFIR. We want to ensure all MCSs are masked
        // until the BARs are opened later during IPL.
        l_mcfirmask.flush<1>();
        FAPI_TRY(fapi2::putScom(i_target, MCS_MCFIRMASK_OR_ARR[i_mcs], l_mcfirmask),
                 "Error from putScom (MCS%d_MCFIRMASK_OR)", i_mcs);
    }

fapi_try_exit:
    FAPI_DBG("End");
    return fapi2::current_err;
}

// helper function for MI target type
fapi2::ReturnCode
revert_mi_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_DBG("Start");

    // TODO: implement for Cumulus/MI target type
    (void) i_target;
    goto fapi_try_exit;

fapi_try_exit:
    FAPI_DBG("End");
    return fapi2::current_err;
}

// HWP entry point
fapi2::ReturnCode
p9_revert_sbe_mcs_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_INF("Start");

    fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
    fapi2::ATTR_SYSTEM_IPL_PHASE_Type l_ipl_phase;
    auto l_mcs_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>(fapi2::TARGET_STATE_PRESENT);

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_ipl_phase),
             "Error from FAPI_ATTR_GET (ATTR_SYSTEM_IPL_PHASE)");

    if (l_ipl_phase == fapi2::ENUM_ATTR_SYSTEM_IPL_PHASE_CHIP_CONTAINED)
    {
        FAPI_INF("Leaving MC BAR configured for chip contained execution");
        goto fapi_try_exit;
    }

    if (l_mcs_chiplets.size())
    {
        for (uint8_t l_mcs = 0; l_mcs < NUM_MCS_TARGETS; l_mcs++)
        {
            FAPI_TRY(revert_mcs_hb_dcbz_config(i_target, l_mcs),
                     "Error from revert_mcs_hb_dcbz_config");
        }
    }
    else
    {
        FAPI_TRY(revert_mi_hb_dcbz_config(i_target),
                 "Error from revert_mi_hb_dcbz_config");
    }

fapi_try_exit:
    FAPI_INF("End");
    return fapi2::current_err;
}
<commit_msg>Need to disable fast path and cmd bypass for HB load<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_revert_sbe_mcs_setup.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_revert_sbe_mcs_setup.C
/// @brief Revert MC configuration applied by SBE (FAPI2)

///
/// @author Joe McGill <jmcgill@us.ibm.com>
///

//
// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB
//

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_revert_sbe_mcs_setup.H>
#include <p9_perv_scom_addresses.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------

// MCS target type constants
const uint8_t NUM_MCS_TARGETS = 4;

const uint64_t MCS_CPLT_CTRL1_ARR[NUM_MCS_TARGETS] =
{
    PERV_N3_CPLT_CTRL1,
    PERV_N3_CPLT_CTRL1,
    PERV_N1_CPLT_CTRL1,
    PERV_N1_CPLT_CTRL1
};

const uint64_t MCS_CPLT_CTRL1_BIT_ARR[NUM_MCS_TARGETS] =
{
    10,
    10,
    9,
    9
};

const uint64_t MCS_MCFGP_ARR[NUM_MCS_TARGETS] =
{
    MCS_0_MCFGP,
    MCS_1_MCFGP,
    MCS_2_MCFGP,
    MCS_3_MCFGP
};
const uint64_t MCS_MCMODE1_ARR[NUM_MCS_TARGETS] =
{
    MCS_0_MCMODE1,
    MCS_1_MCMODE1,
    MCS_2_MCMODE1,
    MCS_3_MCMODE1
};
const uint64_t MCS_MCPERF1_ARR[NUM_MCS_TARGETS] =
{
    MCS_0_MCPERF1,
    MCS_1_MCPERF1,
    MCS_2_MCPERF1,
    MCS_3_MCPERF1
};
const uint64_t MCS_MCFIRMASK_OR_ARR[NUM_MCS_TARGETS] =
{
    MCS_0_MCFIRMASK_OR,
    MCS_1_MCFIRMASK_OR,
    MCS_2_MCFIRMASK_OR,
    MCS_3_MCFIRMASK_OR
};

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

// helper function for MCS target type
fapi2::ReturnCode
revert_mcs_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
                          const uint8_t i_mcs)
{
    FAPI_DBG("Start");
    fapi2::buffer<uint64_t> l_cplt_ctrl1;
    fapi2::buffer<uint64_t> l_mcfgp;
    fapi2::buffer<uint64_t> l_mcmode1;
    fapi2::buffer<uint64_t> l_mcperf1;
    fapi2::buffer<uint64_t> l_mcfirmask;

    FAPI_TRY(fapi2::getScom(i_target, MCS_CPLT_CTRL1_ARR[i_mcs], l_cplt_ctrl1),
             "Error from getscom (CPLT_CTRL1)");

    if (!l_cplt_ctrl1.getBit(MCS_CPLT_CTRL1_BIT_ARR[i_mcs]))
    {
        // MCFGP -- mark BAR invalid & reset grouping configuration fields
        FAPI_TRY(fapi2::getScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),
                 "Error from getScom (MCS%d_MCFGP)", i_mcs);
        l_mcfgp.clearBit<MCS_MCFGP_VALID>();
        l_mcfgp.clearBit<MCS_MCFGP_MC_CHANNELS_PER_GROUP,
                         MCS_MCFGP_MC_CHANNELS_PER_GROUP_LEN>();
        l_mcfgp.clearBit<MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION,
                         MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION_LEN>();
        l_mcfgp.clearBit<MCS_MCFGP_GROUP_SIZE, MCS_MCFGP_GROUP_SIZE_LEN>();
        FAPI_TRY(fapi2::putScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),
                 "Error from putScom (MCS%d_MCFGP)", i_mcs);

        // MCMODE1 -- enable speculation, cmd bypass, fp command bypass
        FAPI_TRY(fapi2::getScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),
                 "Error from getScom (MCS%d_MCMODE1)", i_mcs);
        l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_ALL_SPEC_OPS>();
        l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_SPEC_OP,
                           MCS_MCMODE1_DISABLE_SPEC_OP_LEN>();
        l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_COMMAND_BYPASS,
                           MCS_MCMODE1_DISABLE_COMMAND_BYPASS_LEN>();
        l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_FP_COMMAND_BYPASS>();
        FAPI_TRY(fapi2::putScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),
                 "Error from putScom (MCS%d_MCMODE1)", i_mcs);

        // MCS_MCPERF1 -- enable fast path
        FAPI_TRY(fapi2::getScom(i_target, MCS_MCPERF1_ARR[i_mcs], l_mcperf1),
                 "Error from getScom (MCS%d_MCPERF1)", i_mcs);
        l_mcperf1.clearBit<MCS_MCPERF1_DISABLE_FASTPATH>();
        FAPI_TRY(fapi2::putScom(i_target, MCS_MCPERF1, l_mcperf1),
                 "Error from putScom (MCS%d_MCPERF1)", i_mcs);

        // Re-mask MCFIR. We want to ensure all MCSs are masked
        // until the BARs are opened later during IPL.
        l_mcfirmask.flush<1>();
        FAPI_TRY(fapi2::putScom(i_target, MCS_MCFIRMASK_OR_ARR[i_mcs], l_mcfirmask),
                 "Error from putScom (MCS % d_MCFIRMASK_OR)", i_mcs);
    }

fapi_try_exit:
    FAPI_DBG("End");
    return fapi2::current_err;
}

// helper function for MI target type
fapi2::ReturnCode
revert_mi_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_DBG("Start");

    // TODO: implement for Cumulus/MI target type
    (void) i_target;
    goto fapi_try_exit;

fapi_try_exit:
    FAPI_DBG("End");
    return fapi2::current_err;
}

// HWP entry point
fapi2::ReturnCode
p9_revert_sbe_mcs_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_INF("Start");

    fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
    fapi2::ATTR_SYSTEM_IPL_PHASE_Type l_ipl_phase;
    auto l_mcs_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>(fapi2::TARGET_STATE_PRESENT);

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_ipl_phase),
             "Error from FAPI_ATTR_GET (ATTR_SYSTEM_IPL_PHASE)");

    if (l_ipl_phase == fapi2::ENUM_ATTR_SYSTEM_IPL_PHASE_CHIP_CONTAINED)
    {

        FAPI_INF("Leaving MC BAR configured for chip contained execution");
        goto fapi_try_exit;
    }

    if (l_mcs_chiplets.size())
    {
        for (uint8_t l_mcs = 0; l_mcs < NUM_MCS_TARGETS; l_mcs++)
        {
            FAPI_TRY(revert_mcs_hb_dcbz_config(i_target, l_mcs),
                     "Error from revert_mcs_hb_dcbz_config");
        }
    }
    else
    {
        FAPI_TRY(revert_mi_hb_dcbz_config(i_target),
                 "Error from revert_mi_hb_dcbz_config");
    }

fapi_try_exit:
    FAPI_INF("End");
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the Apache License 2.0.
*/

#include <triton/config.hpp>
#include <triton/pythonBindings.hpp>
#include <triton/pythonUtils.hpp>
#include <triton/pythonXFunctions.hpp>
#include <triton/version.hpp>

/*! \page py_VERSION_page VERSION
    \brief [**python api**] All information about the VERSION Python namespace.

\tableofcontents

\section VERSION_py_description Description

The VERSION namespace contains all version numbers.

\section VERSION_py_api Python API - Items of the VERSION namespace

- **VERSION.BUILD**
- **VERSION.MAJOR**
- **VERSION.MINOR**
- **VERSION.BITWUZLA_INTERFACE**
- **VERSION.LLVM_INTERFACE**
- **VERSION.Z3_INTERFACE**

*/

namespace triton {
  namespace bindings {
    namespace python {

      void initVersionNamespace(PyObject* versionDict) {
        xPyDict_SetItemString(versionDict, "MAJOR", PyLong_FromUint32(triton::MAJOR));
        xPyDict_SetItemString(versionDict, "MINOR", PyLong_FromUint32(triton::MINOR));
        xPyDict_SetItemString(versionDict, "BUILD", PyLong_FromUint32(triton::BUILD));

        #ifdef TRITON_Z3_INTERFACE
          xPyDict_SetItemString(versionDict, "Z3_INTERFACE", Py_True);
        #else
          xPyDict_SetItemString(versionDict, "Z3_INTERFACE", Py_False);
        #endif

        #ifdef TRITON_BITWUZLA_INTERFACE
          xPyDict_SetItemString(versionDict, "BITWUZLA_INTERFACE", Py_True);
        #else
          xPyDict_SetItemString(versionDict, "BITWUZLA_INTERFACE", Py_False);
        #endif

        #ifdef TRITON_LLVM_INTERFACE
          xPyDict_SetItemString(versionDict, "LLVM_INTERFACE", Py_True);
        #else
          xPyDict_SetItemString(versionDict, "LLVM_INTERFACE", Py_False);
        #endif
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */
<commit_msg>Fix reference count of Py_True/Py_False<commit_after>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the Apache License 2.0.
*/

#include <triton/config.hpp>
#include <triton/pythonBindings.hpp>
#include <triton/pythonUtils.hpp>
#include <triton/pythonXFunctions.hpp>
#include <triton/version.hpp>

/*! \page py_VERSION_page VERSION
    \brief [**python api**] All information about the VERSION Python namespace.

\tableofcontents

\section VERSION_py_description Description

The VERSION namespace contains all version numbers.

\section VERSION_py_api Python API - Items of the VERSION namespace

- **VERSION.BUILD**
- **VERSION.MAJOR**
- **VERSION.MINOR**
- **VERSION.BITWUZLA_INTERFACE**
- **VERSION.LLVM_INTERFACE**
- **VERSION.Z3_INTERFACE**

*/

namespace triton {
  namespace bindings {
    namespace python {

      void initVersionNamespace(PyObject* versionDict) {
        xPyDict_SetItemString(versionDict, "MAJOR", PyLong_FromUint32(triton::MAJOR));
        xPyDict_SetItemString(versionDict, "MINOR", PyLong_FromUint32(triton::MINOR));
        xPyDict_SetItemString(versionDict, "BUILD", PyLong_FromUint32(triton::BUILD));

        #ifdef TRITON_Z3_INTERFACE
          Py_INCREF(Py_True);
          xPyDict_SetItemString(versionDict, "Z3_INTERFACE", Py_True);
        #else
          Py_INCREF(Py_False);
          xPyDict_SetItemString(versionDict, "Z3_INTERFACE", Py_False);
        #endif

        #ifdef TRITON_BITWUZLA_INTERFACE
          Py_INCREF(Py_True);
          xPyDict_SetItemString(versionDict, "BITWUZLA_INTERFACE", Py_True);
        #else
          Py_INCREF(Py_False);
          xPyDict_SetItemString(versionDict, "BITWUZLA_INTERFACE", Py_False);
        #endif

        #ifdef TRITON_LLVM_INTERFACE
          Py_INCREF(Py_True);
          xPyDict_SetItemString(versionDict, "LLVM_INTERFACE", Py_True);
        #else
          Py_INCREF(Py_False);
          xPyDict_SetItemString(versionDict, "LLVM_INTERFACE", Py_False);
        #endif
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "LRUCache.hxx"

TEST(LRUCache, InsertPair)
{
    LRUCache<int, std::string, 3> cache;

    auto pairResult = cache.insert(std::make_pair<int, std::string>(1, "1"));
    EXPECT_EQ(std::string("1"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(1, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(2, "2"));
    EXPECT_EQ(std::string("2"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(2, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(3, "3"));
    EXPECT_EQ(std::string("3"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(3, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(4, "4"));
    EXPECT_EQ(std::string("4"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(3, cache.size());
}

TEST(LRUCache, BracketOperator)
{
    LRUCache<int, std::string, 5> cache;

    cache.insert(std::make_pair<int, std::string>(1, "1"));
    auto& value = cache[1];
    EXPECT_EQ(std::string("1"), value);
}<commit_msg>Add a test for non existing value<commit_after>#include <gtest/gtest.h>
#include "LRUCache.hxx"

TEST(LRUCache, InsertPair)
{
    LRUCache<int, std::string, 3> cache;

    auto pairResult = cache.insert(std::make_pair<int, std::string>(1, "1"));
    EXPECT_EQ(std::string("1"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(1, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(2, "2"));
    EXPECT_EQ(std::string("2"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(2, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(3, "3"));
    EXPECT_EQ(std::string("3"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(3, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(4, "4"));
    EXPECT_EQ(std::string("4"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(3, cache.size());
}

TEST(LRUCache, BracketOperator)
{
    LRUCache<int, std::string, 5> cache;

    // Element does exist
    cache.insert(std::make_pair<int, std::string>(1, "1"));
    auto& value = cache[1];
    EXPECT_EQ(std::string("1"), value);

    // Element that does not exist
    auto& defaultValue = cache[42];
    EXPECT_EQ(std::string(), defaultValue);
}<|endoftext|>


<commit_before>/*
Copyright (c) 2009-2019, Intel Corporation
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// written by Roman Dementiev,
//            Patrick Konsor
//

#include <iostream>
#include <string.h>
#ifndef _MSC_VER
#include <sys/types.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include "pci.h"
#include "mmio.h"

#ifndef _MSC_VER
#include <sys/mman.h>
#include <errno.h>
#endif

#ifdef _MSC_VER

#include <windows.h>

class PCMPmem : public WinPmem {
protected:
    virtual int load_driver_()
    {
        SYSTEM_INFO sys_info;
        ZeroMemory(&sys_info, sizeof(sys_info));

        GetCurrentDirectory(MAX_PATH - 10, driver_filename);

        GetNativeSystemInfo(&sys_info);
        switch (sys_info.wProcessorArchitecture)
        {
        case PROCESSOR_ARCHITECTURE_AMD64:
            wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x64.sys");
            if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES)
            {
                std::cout << "ERROR: winpmem_x64.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x64.sys ." << std::endl;
                std::cout << "ERROR: Memory bandwidth statistics will not be available." << std::endl;
            }
            break;
        case PROCESSOR_ARCHITECTURE_INTEL:
            wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x86.sys");
            if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES)
            {
                std::cout << "ERROR: winpmem_x86.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x86.sys ." << std::endl;
                std::cout << "ERROR: Memory bandwidth statistics will not be available." << std::endl;
            }
            break;
        default:
            return -1;
        }
        return 1;
    }
    virtual int write_crashdump_header_(struct PmemMemoryInfo * info)
    {
        return -1;
    }
};

std::shared_ptr<WinPmem> MMIORange::pmem;
PCM_Util::Mutex MMIORange::mutex;
bool MMIORange::writeSupported;

MMIORange::MMIORange(uint64 baseAddr_, uint64 /* size_ */, bool readonly_) : startAddr(baseAddr_), readonly(readonly_)
{
    mutex.lock();
    if (pmem.get() == NULL)
    {
        pmem = std::make_shared<PCMPmem>();
        pmem->install_driver(false);
        pmem->set_acquisition_mode(PMEM_MODE_IOSPACE);
        writeSupported = pmem->toggle_write_mode() >= 0; // since it is a global object enable write mode just in case someone needs it
    }
    mutex.unlock();
}

#elif __APPLE__

#include "PCIDriverInterface.h"

MMIORange::MMIORange(uint64 physical_address, uint64 size_, bool readonly_) : mmapAddr(NULL), readonly(readonly_)
{
    if (size_ > 4096)
    {
        std::cerr << "PCM Error: the driver does not support mapping of regions > 4KB" << std::endl;
        return;
    }
    if (physical_address) {
        PCIDriver_mapMemory((uint32_t)physical_address, (uint8_t **)&mmapAddr);
    }
}

uint32 MMIORange::read32(uint64 offset)
{
    uint32 val = 0;
    PCIDriver_readMemory32((uint8_t *)mmapAddr + offset, &val);
    return val;
}

uint64 MMIORange::read64(uint64 offset)
{
    uint64 val = 0;
    PCIDriver_readMemory64((uint8_t *)mmapAddr + offset, &val);
    return val;
}

void MMIORange::write32(uint64 offset, uint32 val)
{
    std::cerr << "PCM Error: the driver does not support writing to MMIORange" << std::endl;
}
void MMIORange::write64(uint64 offset, uint64 val)
{
    std::cerr << "PCM Error: the driver does not support writing to MMIORange" << std::endl;
}

MMIORange::~MMIORange()
{
    if(mmapAddr) PCIDriver_unmapMemory((uint8_t *)mmapAddr);
}

#elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__)

MMIORange::MMIORange(uint64 baseAddr_, uint64 size_, bool readonly_) :
    fd(-1),
    mmapAddr(NULL),
    size(size_),
    readonly(readonly_)
{
    const int oflag = readonly ? O_RDONLY : O_RDWR;
    int handle = ::open("/dev/mem", oflag);
    if (handle < 0)
    {
       std::cout << "opening /dev/mem failed: errno is " << errno << " (" << strerror(errno) << ")" << std::endl;
       throw std::exception();
    }
    fd = handle;

    const int prot = readonly ? PROT_READ : (PROT_READ | PROT_WRITE);
    mmapAddr = (char *)mmap(NULL, size, prot, MAP_SHARED, fd, baseAddr_);

    if (mmapAddr == MAP_FAILED)
    {
        std::cout << "mmap failed: errno is " << errno << " (" << strerror(errno) << ")" << std::endl;
        throw std::exception();
    }
}

uint32 MMIORange::read32(uint64 offset)
{
    return *((uint32 *)(mmapAddr + offset));
}

uint64 MMIORange::read64(uint64 offset)
{
    return *((uint64 *)(mmapAddr + offset));
}

void MMIORange::write32(uint64 offset, uint32 val)
{
    if (readonly)
    {
        std::cerr << "PCM Error: attempting to write to a read-only MMIORange" << std::endl;
        return;
    }
    *((uint32 *)(mmapAddr + offset)) = val;
}
void MMIORange::write64(uint64 offset, uint64 val)
{
    if (readonly)
    {
        std::cerr << "PCM Error: attempting to write to a read-only MMIORange" << std::endl;
        return;
    }
    *((uint64 *)(mmapAddr + offset)) = val;
}

MMIORange::~MMIORange()
{
    if (mmapAddr) munmap(mmapAddr, size);
    if (fd >= 0) ::close(fd);
}

#endif

<commit_msg>fix compilation on OSX<commit_after>/*
Copyright (c) 2009-2019, Intel Corporation
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// written by Roman Dementiev,
//            Patrick Konsor
//

#include <iostream>
#include <string.h>
#ifndef _MSC_VER
#include <sys/types.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include "pci.h"
#include "mmio.h"

#ifndef _MSC_VER
#include <sys/mman.h>
#include <errno.h>
#endif

#ifdef _MSC_VER

#include <windows.h>

class PCMPmem : public WinPmem {
protected:
    virtual int load_driver_()
    {
        SYSTEM_INFO sys_info;
        ZeroMemory(&sys_info, sizeof(sys_info));

        GetCurrentDirectory(MAX_PATH - 10, driver_filename);

        GetNativeSystemInfo(&sys_info);
        switch (sys_info.wProcessorArchitecture)
        {
        case PROCESSOR_ARCHITECTURE_AMD64:
            wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x64.sys");
            if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES)
            {
                std::cout << "ERROR: winpmem_x64.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x64.sys ." << std::endl;
                std::cout << "ERROR: Memory bandwidth statistics will not be available." << std::endl;
            }
            break;
        case PROCESSOR_ARCHITECTURE_INTEL:
            wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x86.sys");
            if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES)
            {
                std::cout << "ERROR: winpmem_x86.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x86.sys ." << std::endl;
                std::cout << "ERROR: Memory bandwidth statistics will not be available." << std::endl;
            }
            break;
        default:
            return -1;
        }
        return 1;
    }
    virtual int write_crashdump_header_(struct PmemMemoryInfo * info)
    {
        return -1;
    }
};

std::shared_ptr<WinPmem> MMIORange::pmem;
PCM_Util::Mutex MMIORange::mutex;
bool MMIORange::writeSupported;

MMIORange::MMIORange(uint64 baseAddr_, uint64 /* size_ */, bool readonly_) : startAddr(baseAddr_), readonly(readonly_)
{
    mutex.lock();
    if (pmem.get() == NULL)
    {
        pmem = std::make_shared<PCMPmem>();
        pmem->install_driver(false);
        pmem->set_acquisition_mode(PMEM_MODE_IOSPACE);
        writeSupported = pmem->toggle_write_mode() >= 0; // since it is a global object enable write mode just in case someone needs it
    }
    mutex.unlock();
}

#elif __APPLE__

#include "PCIDriverInterface.h"

MMIORange::MMIORange(uint64 physical_address, uint64 size_, bool readonly_) :
    mmapAddr(NULL),
    size(size_),
    readonly(readonly_)
{
    if (size > 4096)
    {
        std::cerr << "PCM Error: the driver does not support mapping of regions > 4KB" << std::endl;
        return;
    }
    if (physical_address) {
        PCIDriver_mapMemory((uint32_t)physical_address, (uint8_t **)&mmapAddr);
    }
}

uint32 MMIORange::read32(uint64 offset)
{
    uint32 val = 0;
    PCIDriver_readMemory32((uint8_t *)mmapAddr + offset, &val);
    return val;
}

uint64 MMIORange::read64(uint64 offset)
{
    uint64 val = 0;
    PCIDriver_readMemory64((uint8_t *)mmapAddr + offset, &val);
    return val;
}

void MMIORange::write32(uint64 offset, uint32 val)
{
    std::cerr << "PCM Error: the driver does not support writing to MMIORange" << std::endl;
}
void MMIORange::write64(uint64 offset, uint64 val)
{
    std::cerr << "PCM Error: the driver does not support writing to MMIORange" << std::endl;
}

MMIORange::~MMIORange()
{
    if(mmapAddr) PCIDriver_unmapMemory((uint8_t *)mmapAddr);
}

#elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__)

MMIORange::MMIORange(uint64 baseAddr_, uint64 size_, bool readonly_) :
    fd(-1),
    mmapAddr(NULL),
    size(size_),
    readonly(readonly_)
{
    const int oflag = readonly ? O_RDONLY : O_RDWR;
    int handle = ::open("/dev/mem", oflag);
    if (handle < 0)
    {
       std::cout << "opening /dev/mem failed: errno is " << errno << " (" << strerror(errno) << ")" << std::endl;
       throw std::exception();
    }
    fd = handle;

    const int prot = readonly ? PROT_READ : (PROT_READ | PROT_WRITE);
    mmapAddr = (char *)mmap(NULL, size, prot, MAP_SHARED, fd, baseAddr_);

    if (mmapAddr == MAP_FAILED)
    {
        std::cout << "mmap failed: errno is " << errno << " (" << strerror(errno) << ")" << std::endl;
        throw std::exception();
    }
}

uint32 MMIORange::read32(uint64 offset)
{
    return *((uint32 *)(mmapAddr + offset));
}

uint64 MMIORange::read64(uint64 offset)
{
    return *((uint64 *)(mmapAddr + offset));
}

void MMIORange::write32(uint64 offset, uint32 val)
{
    if (readonly)
    {
        std::cerr << "PCM Error: attempting to write to a read-only MMIORange" << std::endl;
        return;
    }
    *((uint32 *)(mmapAddr + offset)) = val;
}
void MMIORange::write64(uint64 offset, uint64 val)
{
    if (readonly)
    {
        std::cerr << "PCM Error: attempting to write to a read-only MMIORange" << std::endl;
        return;
    }
    *((uint64 *)(mmapAddr + offset)) = val;
}

MMIORange::~MMIORange()
{
    if (mmapAddr) munmap(mmapAddr, size);
    if (fd >= 0) ::close(fd);
}

#endif

<|endoftext|>