<commit_before>/**
 * Copyright (c) 2020, Timothy Stack
 *
 * 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
 */

#ifndef lnav_time_util_hh
#define lnav_time_util_hh

#include <inttypes.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>

#include "config.h"

namespace lnav {

using time64_t = uint64_t;

}

struct tm* secs2tm(lnav::time64_t tim, struct tm* res);
/**
 * Convert the time stored in a 'tm' struct into epoch time.
 *
 * @param t The 'tm' structure to convert to epoch time.
 * @return The given time in seconds since the epoch.
 */
time_t tm2sec(const struct tm* t);
void secs2wday(const struct timeval& tv, struct tm* res);

inline time_t
convert_log_time_to_local(time_t value)
{
    struct tm tm;

    localtime_r(&value, &tm);
#ifdef HAVE_STRUCT_TM_TM_ZONE
    tm.tm_zone = NULL;
#endif
    tm.tm_isdst = 0;
    return tm2sec(&tm);
}

constexpr lnav::time64_t MAX_TIME_T = 4000000000LL;

enum exttm_bits_t {
    ETB_YEAR_SET,
    ETB_MONTH_SET,
    ETB_DAY_SET,
    ETB_MACHINE_ORIENTED,
    ETB_EPOCH_TIME,
    ETB_MILLIS_SET,
    ETB_MICROS_SET,
    ETB_NANOS_SET,
};

enum exttm_flags_t {
    ETF_YEAR_SET = (1UL << ETB_YEAR_SET),
    ETF_MONTH_SET = (1UL << ETB_MONTH_SET),
    ETF_DAY_SET = (1UL << ETB_DAY_SET),
    ETF_MACHINE_ORIENTED = (1UL << ETB_MACHINE_ORIENTED),
    ETF_EPOCH_TIME = (1UL << ETB_EPOCH_TIME),
    ETF_MILLIS_SET = (1UL << ETB_MILLIS_SET),
    ETF_MICROS_SET = (1UL << ETB_MICROS_SET),
    ETF_NANOS_SET = (1UL << ETB_NANOS_SET),
};

struct exttm {
    struct tm et_tm;
    int32_t et_nsec;
    unsigned int et_flags;
    long et_gmtoff;

    bool operator==(const exttm& other) const
    {
        return memcmp(this, &other, sizeof(exttm)) == 0;
    };

    struct timeval to_timeval() const;
};

inline bool
operator<(const struct timeval& left, time_t right)
{
    return left.tv_sec < right;
}

inline bool
operator<(time_t left, const struct timeval& right)
{
    return left < right.tv_sec;
}

inline bool
operator<(const struct timeval& left, const struct timeval& right)
{
    return left.tv_sec < right.tv_sec
        || ((left.tv_sec == right.tv_sec) && (left.tv_usec < right.tv_usec));
}

inline bool
operator!=(const struct timeval& left, const struct timeval& right)
{
    return left.tv_sec != right.tv_sec || left.tv_usec != right.tv_usec;
}

inline struct timeval
operator-(const struct timeval& lhs, const struct timeval& rhs)
{
    struct timeval diff;

    timersub(&lhs, &rhs, &diff);
    return diff;
}

typedef int64_t mstime_t;

inline mstime_t
getmstime()
{
    struct timeval tv;

    gettimeofday(&tv, nullptr);

    return tv.tv_sec * 1000ULL + tv.tv_usec / 1000ULL;
}

inline struct timeval
current_timeval()
{
    struct timeval retval;

    gettimeofday(&retval, nullptr);

    return retval;
}

inline struct timespec
current_timespec()
{
    struct timespec retval;

    clock_gettime(CLOCK_REALTIME, &retval);

    return retval;
}

inline time_t
day_num(time_t ti)
{
    return ti / (24 * 60 * 60);
}

inline time_t
hour_num(time_t ti)
{
    return ti / (60 * 60);
}

#endif
<commit_msg>[exttm] missed an initialization<commit_after>/**
 * Copyright (c) 2020, Timothy Stack
 *
 * 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
 */

#ifndef lnav_time_util_hh
#define lnav_time_util_hh

#include <inttypes.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>

#include "config.h"

namespace lnav {

using time64_t = uint64_t;

}

struct tm* secs2tm(lnav::time64_t tim, struct tm* res);
/**
 * Convert the time stored in a 'tm' struct into epoch time.
 *
 * @param t The 'tm' structure to convert to epoch time.
 * @return The given time in seconds since the epoch.
 */
time_t tm2sec(const struct tm* t);
void secs2wday(const struct timeval& tv, struct tm* res);

inline time_t
convert_log_time_to_local(time_t value)
{
    struct tm tm;

    localtime_r(&value, &tm);
#ifdef HAVE_STRUCT_TM_TM_ZONE
    tm.tm_zone = NULL;
#endif
    tm.tm_isdst = 0;
    return tm2sec(&tm);
}

constexpr lnav::time64_t MAX_TIME_T = 4000000000LL;

enum exttm_bits_t {
    ETB_YEAR_SET,
    ETB_MONTH_SET,
    ETB_DAY_SET,
    ETB_MACHINE_ORIENTED,
    ETB_EPOCH_TIME,
    ETB_MILLIS_SET,
    ETB_MICROS_SET,
    ETB_NANOS_SET,
};

enum exttm_flags_t {
    ETF_YEAR_SET = (1UL << ETB_YEAR_SET),
    ETF_MONTH_SET = (1UL << ETB_MONTH_SET),
    ETF_DAY_SET = (1UL << ETB_DAY_SET),
    ETF_MACHINE_ORIENTED = (1UL << ETB_MACHINE_ORIENTED),
    ETF_EPOCH_TIME = (1UL << ETB_EPOCH_TIME),
    ETF_MILLIS_SET = (1UL << ETB_MILLIS_SET),
    ETF_MICROS_SET = (1UL << ETB_MICROS_SET),
    ETF_NANOS_SET = (1UL << ETB_NANOS_SET),
};

struct exttm {
    struct tm et_tm;
    int32_t et_nsec{0};
    unsigned int et_flags{0};
    long et_gmtoff{0};

    bool operator==(const exttm& other) const
    {
        return memcmp(this, &other, sizeof(exttm)) == 0;
    };

    struct timeval to_timeval() const;
};

inline bool
operator<(const struct timeval& left, time_t right)
{
    return left.tv_sec < right;
}

inline bool
operator<(time_t left, const struct timeval& right)
{
    return left < right.tv_sec;
}

inline bool
operator<(const struct timeval& left, const struct timeval& right)
{
    return left.tv_sec < right.tv_sec
        || ((left.tv_sec == right.tv_sec) && (left.tv_usec < right.tv_usec));
}

inline bool
operator!=(const struct timeval& left, const struct timeval& right)
{
    return left.tv_sec != right.tv_sec || left.tv_usec != right.tv_usec;
}

inline struct timeval
operator-(const struct timeval& lhs, const struct timeval& rhs)
{
    struct timeval diff;

    timersub(&lhs, &rhs, &diff);
    return diff;
}

typedef int64_t mstime_t;

inline mstime_t
getmstime()
{
    struct timeval tv;

    gettimeofday(&tv, nullptr);

    return tv.tv_sec * 1000ULL + tv.tv_usec / 1000ULL;
}

inline struct timeval
current_timeval()
{
    struct timeval retval;

    gettimeofday(&retval, nullptr);

    return retval;
}

inline struct timespec
current_timespec()
{
    struct timespec retval;

    clock_gettime(CLOCK_REALTIME, &retval);

    return retval;
}

inline time_t
day_num(time_t ti)
{
    return ti / (24 * 60 * 60);
}

inline time_t
hour_num(time_t ti)
{
    return ti / (60 * 60);
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
Main - Fichier principal de l'application content le main
-------------------
dbut                :	20/05/17
copyright            :	(C) 2017 par VOGEL
e-mail               :	hugues.vogel@insa-lyon.fr
*************************************************************************/

//--------------- Ralisation du Main (fichier Main.cpp) ---------------//

//---------------------------------------------------------------- INCLUDE

//-------------------------------------------------------- Include systme

#include <string>
#include <iostream>

//------------------------------------------------------ Include personnel

#include "Communication.h"
#include "Dictionnaire.h"

//------------------------------------------------------------------- MAIN

using namespace std;

const int DEFAULT_PORT = 8282;
const string DEFAULT_DICTIONNAIR_FILE = "./dictionnaire.dico";

void afficherUsage() {
	cout << "Usage :" << endl
		<< "./DNAnalyserServer [-dico <fileName>] [-port <serverPort>]" << endl
		<< "./DNAnalyserServer help" << endl;
}
void afficherSyntaxError(string erreurText) {
	cout << "Commande non valide : " << erreurText << endl;
	afficherUsage();
}
void afficherAide() {
	afficherUsage();
	cout << "Aide : " << endl
		<< "  Parametre       Alias                   Commentaire" << endl
		<< "" << endl
		<< "  -port <Port>    -p <Port>               Permet de changer le port d'ecoute du server, le port" << endl
		<< "                                          d'ecoute par default est "<< to_string(DEFAULT_PORT) << endl
		<< "" << endl
		<< "  -dico <file>    -d <file>               Permet de changer le fichier de dictionnaire charger" << endl
		<< "                  -dictionnaire <file>    laur du demarage du server, le fichier charger par" << endl
		<< "                                          defaut est \""+ DEFAULT_DICTIONNAIR_FILE +"\"" << endl;

}

int main(int argc, char** argv)
{
	unsigned int portNumber = 8282;
	string dicoFile = "./dictionnaire.dico";

	for (int i = 1; i < argc; i++) {
		string arg(argv[i]);
		if (!arg.empty()) {
			if (arg[0] == '-') {
				if (arg == "-d" || arg == "-dico" || arg == "-dictionnaire") {
					i++;
					if (i == argc) {
						afficherSyntaxError("nom de fichier requis aprs " + arg);
						exit(0);
					}
					dicoFile = argv[i];
				}
				if (arg == "-p" || arg == "-port") {
					i++;
					if (i == argc) {
						afficherSyntaxError("numero de port requis aprs " + arg);
						exit(0);
					}
					try {
						size_t st;
						string arg_port(argv[i]);
						portNumber = stoi(arg_port, &st);
						if (st != arg_port.length()|| portNumber<1|| portNumber>65535) {
							afficherSyntaxError("le numero de port requis aprs " + arg + " doit tre un nombre entre 1 et 65536");
						}
					}
					catch (const invalid_argument &e) {
						afficherSyntaxError("le numero de port requis aprs " + arg + " doit tre un nombre entre 1 et 65536");
						exit(0);
					}

				}
				else {
					afficherSyntaxError("argument " + arg + " inconu");
					exit(0);
				}
			}
			else {//pour les paramtres obligatoir (aucun pour nous)
				if (arg == "help" && i == 0) {
					afficherAide();
					exit(0);
				}
				afficherSyntaxError("argument " + arg + " inconu");
				exit(0);
			}
		}
	}

	std::cout << "Chargement du Dictionnaire :  " << dicoFile << std::endl;
	try {
		Dictionnaire::ObtenirInstance().ChargerFichier(dicoFile);
	}
	catch (const exception &e) {
		std::cout << "Erreur lors du chargement di dictionnaire"<<endl;
		std::cout << "ERREUR : " << e.what() << endl;
		exit(0);
	}
	std::cout << "Dictionnaire Charger (" << to_string(Dictionnaire::ObtenirInstance().ObtenirNomsMaladies().size()) <<" maladies charger)"<< std::endl;
	std::cout << "Demarage du server sur le port " << to_string(portNumber) << std::endl;
	try {
		Communication::ObtenirInstance().Ecouter(portNumber);
	}
	catch (const exception &e) {
		std::cout << "Erreur lors du demarage du server" << endl;
		std::cout << "ERREUR : " << e.what() << endl;
		exit(0);
	}
	std::cout << "Server sart" << std::endl;

	return 0;
}

<commit_msg>correction du main n°1<commit_after>/*************************************************************************
Main - Fichier principal de l'application content le main
-------------------
dbut                :	20/05/17
copyright            :	(C) 2017 par VOGEL
e-mail               :	hugues.vogel@insa-lyon.fr
*************************************************************************/

//--------------- Ralisation du Main (fichier Main.cpp) ---------------//

//---------------------------------------------------------------- INCLUDE

//-------------------------------------------------------- Include systme

#include <string>
#include <iostream>

//------------------------------------------------------ Include personnel

#include "Communication.h"
#include "Dictionnaire.h"

//------------------------------------------------------------------- MAIN

using namespace std;

const int DEFAULT_PORT = 8282;
const string DEFAULT_DICTIONNAIR_FILE = "./dictionnaire.dico";

void afficherUsage() {
	cout << "Usage :" << endl
		<< "./DNAnalyserServer [-dico <fileName>] [-port <serverPort>]" << endl
		<< "./DNAnalyserServer help" << endl;
}
void afficherSyntaxError(string erreurText) {
	cout << "Commande non valide : " << erreurText << endl;
	afficherUsage();
}
void afficherAide() {
	afficherUsage();
	cout << "Aide : " << endl
		<< "  Parametre       Alias                   Commentaire" << endl
		<< "" << endl
		<< "  -port <Port>    -p <Port>               Permet de changer le port d'ecoute du server, le port" << endl
		<< "                                          d'ecoute par default est "<< to_string(DEFAULT_PORT) << endl
		<< "" << endl
		<< "  -dico <file>    -d <file>               Permet de changer le fichier de dictionnaire charger" << endl
		<< "                  -dictionnaire <file>    laur du demarage du server, le fichier charger par" << endl
		<< "                                          defaut est \""+ DEFAULT_DICTIONNAIR_FILE +"\"" << endl;

}

int main(int argc, char** argv)
{
	unsigned int portNumber = 8282;
	string dicoFile = "./dictionnaire.dico";

	for (int i = 1; i < argc; i++) {
		string arg(argv[i]);
		if (!arg.empty()) {
			if (arg[0] == '-') {
				if (arg == "-d" || arg == "-dico" || arg == "-dictionnaire") {
					i++;
					if (i == argc) {
						afficherSyntaxError("nom de fichier requis aprs " + arg);
						exit(0);
					}
					dicoFile = argv[i];
				}
				if (arg == "-p" || arg == "-port") {
					i++;
					if (i == argc) {
						afficherSyntaxError("numero de port requis aprs " + arg);
						exit(0);
					}
					try {
						size_t st;
						string arg_port(argv[i]);
						portNumber = stoi(arg_port, &st);
						if (st != arg_port.length()|| portNumber<1|| portNumber>65535) {
							afficherSyntaxError("le numero de port requis aprs " + arg + " doit tre un nombre entre 1 et 65536");
						}
					}
					catch (const invalid_argument &e) {
						afficherSyntaxError("le numero de port requis aprs " + arg + " doit tre un nombre entre 1 et 65536");
						exit(0);
					}

				}
				else {
					afficherSyntaxError("argument " + arg + " inconu");
					exit(0);
				}
			}
			else {//pour les paramtres obligatoir (aucun pour nous)
				if (arg == "help" && i == 1) {
					afficherAide();
					exit(0);
				}
				afficherSyntaxError("argument " + arg + " inconu");
				exit(0);
			}
		}
	}

	std::cout << "Chargement du Dictionnaire :  " << dicoFile << std::endl;
	try {
		Dictionnaire::ObtenirInstance().ChargerFichier(dicoFile);
	}
	catch (const exception &e) {
		std::cout << "Erreur lors du chargement di dictionnaire"<<endl;
		std::cout << "ERREUR : " << e.what() << endl;
		exit(0);
	}
	std::cout << "Dictionnaire Charger (" << to_string(Dictionnaire::ObtenirInstance().ObtenirNomsMaladies().size()) <<" maladies charger)"<< std::endl;
	std::cout << "Demarage du server sur le port " << to_string(portNumber) << std::endl;
	try {
		Communication::ObtenirInstance().Ecouter(portNumber);
	}
	catch (const exception &e) {
		std::cout << "Erreur lors du demarage du server" << endl;
		std::cout << "ERREUR : " << e.what() << endl;
		exit(0);
	}
	std::cout << "Server sart" << std::endl;

	return 0;
}

<|endoftext|>


<commit_before>#include "vm_manager.h"
#include "simulator.h"
#include <boost/lexical_cast.hpp>

#include "log.h"

VMManager *VMManager::m_singleton = NULL;

void VMManager::allocate()
{
   assert (m_singleton == NULL);
   m_singleton = new VMManager();
}

void VMManager::release()
{
   delete m_singleton;
   m_singleton = NULL;
}

VMManager *VMManager::getSingleton()
{
   return m_singleton;
}

VMManager::VMManager()
{
   // FIXME: Figure out a way to get the end of the static data
   m_start_data_segment = (IntPtr) sbrk(0);
   m_end_data_segment = m_start_data_segment;

   UInt32 total_cores = Sim()->getConfig()->getTotalCores();

   UInt32 stack_size_per_core;
   try
   {
      m_start_stack_segment = (IntPtr) boost::lexical_cast <unsigned long int> (Sim()->getCfg()->get("stack/stack_base"));
      stack_size_per_core = (UInt32) boost::lexical_cast <unsigned long int> (Sim()->getCfg()->get("stack/stack_size_per_core"));
   }
   catch (boost::bad_lexical_cast &)
   {
      LOG_PRINT_ERROR("Error reading stack parameters from the config file");
      return;
   }

   // FIXME: MCP does not have a stack. Do something about this
   m_end_stack_segment = m_start_stack_segment + total_cores * stack_size_per_core;

   LOG_ASSERT_ERROR(m_end_stack_segment > m_start_stack_segment,
       "Problem with Application Stack: start_stack_segment(0x%x), end_stack_segment(0x%x)",
       m_start_stack_segment, m_end_stack_segment);

   LOG_ASSERT_ERROR(m_start_stack_segment > m_start_data_segment,
       "Problem with Application Stack: start_data_segment(0x%x), start_stack_segment(0x%x)",
       m_start_data_segment, m_start_stack_segment);

#ifdef TARGET_IA32
   m_start_dynamic_segment = 0xb0000000;
#endif

#ifdef TARGET_X86_64
   m_start_dynamic_segment = 0xf000000000;
#endif

   m_end_dynamic_segment = m_start_dynamic_segment;

   LOG_ASSERT_ERROR(m_start_dynamic_segment > m_end_stack_segment,
       "Problem with Application Stack: end_stack_segment(0x%x), start_dynamic_segment(0x%x)",
       m_end_stack_segment, m_start_dynamic_segment);
}

VMManager::~VMManager()
{
}

void *VMManager::brk(void *end_data_segment)
{
   LOG_PRINT ("VMManager: brk(%p)", end_data_segment);

   if (end_data_segment == (void*) 0)
   {
      LOG_PRINT ("VMManager: brk(%p) returned %p", end_data_segment, m_end_data_segment);
      return (void*) m_end_data_segment;
   }

   LOG_ASSERT_ERROR((IntPtr) end_data_segment > m_start_data_segment,
       "Problem with brk() system call: start_data_segment(0x%x), end_data_segment(0x%x)",
       m_start_data_segment, (IntPtr) end_data_segment);

   LOG_ASSERT_ERROR((IntPtr) end_data_segment < m_start_stack_segment,
       "Problem with brk() system call: No more memory to allocate! end_data_segment(0x%x), start_stack_segment(0x%x)",
       (IntPtr) end_data_segment, m_start_stack_segment);

   m_end_data_segment = (IntPtr) end_data_segment;

   LOG_PRINT ("VMManager: brk(%p) returned %p", end_data_segment, m_end_data_segment);
   return ((void*) m_end_data_segment);
}

void *VMManager::mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset)
{
   LOG_PRINT("VMManager: mmap(start = %p, length = 0x%x, flags = 0x%x, fd = %i, offset = %u)",
         start, length, flags, fd, flags);

   LOG_ASSERT_ERROR(fd == -1,
         "Mmap() system call, received valid file descriptor. Not currently supported");
   LOG_ASSERT_ERROR((flags & MAP_ANONYMOUS) == MAP_ANONYMOUS,
         "Mmap() system call, MAP_ANONYMOUS should be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_FIXED) == 0,
         "Mmap() system call, MAP_FIXED should NOT be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_PRIVATE) == MAP_PRIVATE,
         "Mmap() system call, MAP_PRIVATE should be set in flags");

   LOG_ASSERT_ERROR((m_start_dynamic_segment - length) > m_end_stack_segment,
         "Mmap() system call: No more memory to allocate! end_stack_segment(0x%x), start_dynamic_segment(0x%x)",
         m_end_stack_segment, m_start_dynamic_segment - length);

   m_start_dynamic_segment -= length;

   LOG_PRINT("VMManager: mmap() returned 0x%x", m_start_dynamic_segment);
   return ((void*) m_start_dynamic_segment);
}

void *VMManager::mmap2(void *start, size_t length, int prot, int flags, int fd, off_t offset)
{
   LOG_PRINT("VMManager: mmap2(start = %p, length = 0x%x, flags = 0x%x)",
         start, length, (unsigned) flags);

   LOG_ASSERT_ERROR(fd == -1,
         "Mmap2() system call, received valid file descriptor. Not currently supported");
   LOG_ASSERT_ERROR((flags & MAP_ANONYMOUS) == MAP_ANONYMOUS,
         "Mmap2() system call, MAP_ANONYMOUS should be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_FIXED) == 0,
         "Mmap2() system call, MAP_FIXED should NOT be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_PRIVATE) == MAP_PRIVATE,
         "Mmap2() system call, MAP_PRIVATE should be set in flags");

   LOG_ASSERT_ERROR((m_start_dynamic_segment - length) > m_end_stack_segment,
         "Mmap2() system call: No more memory to allocate! end_stack_segment(0x%x), start_dynamic_segment(0x%x)",
         m_end_stack_segment, m_start_dynamic_segment - length);

   m_start_dynamic_segment -= length;

   LOG_PRINT("VMManager: mmap2() returned 0x%x", m_start_dynamic_segment);
   return ((void*) m_start_dynamic_segment);
}

int VMManager::munmap(void *start, size_t length)
{
   LOG_PRINT("VMManager: munmap(start = %p, length = 0x%x",
         start, length);

   // Ignore for now
   LOG_ASSERT_ERROR((((IntPtr) start) >= m_start_dynamic_segment),
         "Munmap() system call, start(0x%x), start_dynamic_segment(0x%x)",
         (IntPtr) start, m_start_dynamic_segment);

   LOG_PRINT("VMManager: munmap() returned 0");
   return 0;
}
<commit_msg>[vm_manager] Small changes to vm_manager.cc<commit_after>#include "vm_manager.h"
#include "simulator.h"
#include <boost/lexical_cast.hpp>

#include "log.h"

VMManager *VMManager::m_singleton = NULL;

void VMManager::allocate()
{
   assert (m_singleton == NULL);
   m_singleton = new VMManager();
}

void VMManager::release()
{
   delete m_singleton;
   m_singleton = NULL;
}

VMManager *VMManager::getSingleton()
{
   return m_singleton;
}

VMManager::VMManager()
{
   // FIXME: Figure out a way to get the end of the static data
   m_start_data_segment = (IntPtr) sbrk(0);
   m_end_data_segment = m_start_data_segment;

   UInt32 total_cores = Sim()->getConfig()->getTotalCores();

   UInt32 stack_size_per_core;
   try
   {
      m_start_stack_segment = (IntPtr) boost::lexical_cast <unsigned long int> (Sim()->getCfg()->get("stack/stack_base"));
      stack_size_per_core = (UInt32) boost::lexical_cast <unsigned long int> (Sim()->getCfg()->get("stack/stack_size_per_core"));
   }
   catch (boost::bad_lexical_cast &)
   {
      LOG_PRINT_ERROR("Error reading stack parameters from the config file");
      return;
   }

   // FIXME: MCP does not have a stack. Do something about this
   m_end_stack_segment = m_start_stack_segment + total_cores * stack_size_per_core;

   LOG_ASSERT_ERROR(m_end_stack_segment > m_start_stack_segment,
       "Problem with Application Stack: start_stack_segment(0x%x), end_stack_segment(0x%x)",
       m_start_stack_segment, m_end_stack_segment);

   LOG_ASSERT_ERROR(m_start_stack_segment > m_start_data_segment,
       "Problem with Application Stack: start_data_segment(0x%x), start_stack_segment(0x%x)",
       m_start_data_segment, m_start_stack_segment);

#ifdef TARGET_IA32
   m_start_dynamic_segment = 0xb0000000;
#endif

#ifdef TARGET_X86_64
   m_start_dynamic_segment = 0xf000000000;
#endif

   m_end_dynamic_segment = m_start_dynamic_segment;

   LOG_ASSERT_ERROR(m_start_dynamic_segment > m_end_stack_segment,
       "Problem with Application Stack: end_stack_segment(0x%x), start_dynamic_segment(0x%x)",
       m_end_stack_segment, m_start_dynamic_segment);
}

VMManager::~VMManager()
{
}

void *VMManager::brk(void *end_data_segment)
{
   LOG_PRINT ("VMManager: brk(%p)", end_data_segment);

   if (end_data_segment == (void*) 0)
   {
      LOG_PRINT ("VMManager: brk(%p) returned %p", end_data_segment, m_end_data_segment);
      return (void*) m_end_data_segment;
   }

   LOG_ASSERT_ERROR(m_start_data_segment < ((IntPtr) end_data_segment),
       "Problem with brk() system call: start_data_segment(0x%x), end_data_segment(0x%x)",
       m_start_data_segment, (IntPtr) end_data_segment);

   LOG_ASSERT_ERROR(m_start_stack_segment > ((IntPtr) end_data_segment),
       "Problem with brk() system call: No more memory to allocate! end_data_segment(0x%x), start_stack_segment(0x%x)",
       (IntPtr) end_data_segment, m_start_stack_segment);

   m_end_data_segment = (IntPtr) end_data_segment;

   LOG_PRINT ("VMManager: brk(%p) returned %p", end_data_segment, m_end_data_segment);
   return ((void*) m_end_data_segment);
}

void *VMManager::mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset)
{
   LOG_PRINT("VMManager: mmap(start = %p, length = 0x%x, flags = 0x%x, fd = %i, offset = %u)",
         start, length, flags, fd, flags);

   LOG_ASSERT_ERROR(fd == -1,
         "Mmap() system call, received valid file descriptor. Not currently supported");
   LOG_ASSERT_ERROR((flags & MAP_ANONYMOUS) == MAP_ANONYMOUS,
         "Mmap() system call, MAP_ANONYMOUS should be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_FIXED) == 0,
         "Mmap() system call, MAP_FIXED should NOT be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_PRIVATE) == MAP_PRIVATE,
         "Mmap() system call, MAP_PRIVATE should be set in flags");

   LOG_ASSERT_ERROR((m_end_stack_segment < m_start_dynamic_segment - length),
         "Mmap() system call: No more memory to allocate! end_stack_segment(0x%x), start_dynamic_segment(0x%x)",
         m_end_stack_segment, m_start_dynamic_segment - length);

   m_start_dynamic_segment -= length;

   LOG_PRINT("VMManager: mmap() returned %p", (void*) m_start_dynamic_segment);
   return ((void*) m_start_dynamic_segment);
}

void *VMManager::mmap2(void *start, size_t length, int prot, int flags, int fd, off_t offset)
{
   LOG_PRINT("VMManager: mmap2(start = %p, length = 0x%x, flags = 0x%x)",
         start, length, (unsigned) flags);

   LOG_ASSERT_ERROR(fd == -1,
         "Mmap2() system call, received valid file descriptor. Not currently supported");
   LOG_ASSERT_ERROR((flags & MAP_ANONYMOUS) == MAP_ANONYMOUS,
         "Mmap2() system call, MAP_ANONYMOUS should be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_FIXED) == 0,
         "Mmap2() system call, MAP_FIXED should NOT be set in flags");
   LOG_ASSERT_ERROR((flags & MAP_PRIVATE) == MAP_PRIVATE,
         "Mmap2() system call, MAP_PRIVATE should be set in flags");

   LOG_ASSERT_ERROR(m_end_stack_segment < (m_start_dynamic_segment - length),
         "Mmap2() system call: No more memory to allocate! end_stack_segment(0x%x), start_dynamic_segment(0x%x)",
         m_end_stack_segment, m_start_dynamic_segment - length);

   m_start_dynamic_segment -= length;

   LOG_PRINT("VMManager: mmap2() returned %p", (void*) m_start_dynamic_segment);
   return ((void*) m_start_dynamic_segment);
}

int VMManager::munmap(void *start, size_t length)
{
   LOG_PRINT("VMManager: munmap(start = %p, length = 0x%x",
         start, length);

   // Ignore for now
   LOG_ASSERT_ERROR(m_start_dynamic_segment <= ((IntPtr) start),
         "Munmap() system call, start(0x%x), start_dynamic_segment(0x%x)",
         (IntPtr) start, m_start_dynamic_segment);

   LOG_PRINT("VMManager: munmap() returned 0");
   return 0;
}
<|endoftext|>


<commit_before>#include "hittop/parser/force.h"
#include "hittop/parser/force.h"

#include "gtest/gtest.h"

#include <string>

#include "hittop/parser/literal.h"
#include "hittop/parser/parser.h"
#include "hittop/parser/repeat.h"

using hittop::parser::Force;
using hittop::parser::Literal;
using hittop::parser::Parse;
using hittop::parser::Repeat;

TEST(ParseForce, OkRepeatEmpty) {
  const std::string input = "";
  auto result = Parse<Force<Repeat<Literal<'a'>>>>(input);
  EXPECT_FALSE(result.error()) << "Actual error: " << result.error().message();
}
<commit_msg>Fallible => ParseResult<commit_after>#include "hittop/parser/force.h"
#include "hittop/parser/force.h"

#include "gtest/gtest.h"

#include <string>

#include "hittop/parser/literal.h"
#include "hittop/parser/parser.h"
#include "hittop/parser/repeat.h"

using hittop::parser::Force;
using hittop::parser::Literal;
using hittop::parser::Parse;
using hittop::parser::Repeat;

TEST(ParseForce, OkRepeatEmpty) {
  const std::string input = "";
  auto result = Parse<Force<Repeat<Literal<'a'>>>>(input);
  EXPECT_FALSE(result.error())
      << "Actual error: " << make_error_condition(result.error()).message();
}
<|endoftext|>


<commit_before>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <limits>

//#ifdef WITH_PLANARMAXCUT
#include <opengm/inference/auxiliary/planar_maxcut.hxx>
//#endif

int main()
{
   std::cout << "Planar MaxCut Test ... "<<std::endl;

   {
      opengm::external::PlanarMaxCut pmc(4,12);
      std::vector<int> l;

      pmc.addEdge(0,1,-2.0);
      pmc.addEdge(0,2, 2.0);
      pmc.addEdge(1,3, 2.0);
      pmc.addEdge(2,3,-2.0);
      pmc.calculateCut(l);

      OPENGM_ASSERT(l[0]==l[1]);
      OPENGM_ASSERT(l[2]==l[3]);
      OPENGM_ASSERT(l[0]!=l[2]);
      OPENGM_ASSERT(l[1]!=l[3]);

      for(size_t i=0; i<4; ++i)
         std::cout <<l[i]<<", ";
      std::cout<<std::endl;
   }

   {
      opengm::external::PlanarMaxCut pmc(5,12);
      std::vector<int> l;

      pmc.addEdge(0,1, -2.0);
      pmc.addEdge(0,2, -2.0);
      pmc.addEdge(1,3, -2.0);
      pmc.addEdge(2,3, -2.0);
      pmc.addEdge(3,4, -2.0);
      pmc.calculateCut(l);

      OPENGM_ASSERT(l[0]==l[1]);
      OPENGM_ASSERT(l[1]==l[2]);
      OPENGM_ASSERT(l[2]==l[3]);
      OPENGM_ASSERT(l[3]==l[4]);

      for(size_t i=0; i<5; ++i)
         std::cout <<l[i]<<", ";
      std::cout<<std::endl;
   }
   {
      opengm::external::PlanarMaxCut pmc(5,12);
      std::vector<int> l;

      pmc.addEdge(0,1, -2.0);
      pmc.addEdge(0,2, -2.0);
      pmc.addEdge(1,3, -2.0);
      pmc.addEdge(2,3, -2.0);
      pmc.addEdge(3,4, 2.0);
      pmc.calculateCut(l);

      OPENGM_ASSERT(l[0]==l[1]);
      OPENGM_ASSERT(l[1]==l[2]);
      OPENGM_ASSERT(l[2]==l[3]);
      OPENGM_ASSERT(l[3]!=l[4]);

      for(size_t i=0; i<5; ++i)
         std::cout <<l[i]<<", ";
      std::cout<<std::endl;
   }

   std::cout << " OK!" << std::endl;

}
<commit_msg>update test for planar max cut<commit_after>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <limits>

//#ifdef WITH_PLANARMAXCUT
#include <opengm/inference/auxiliary/planar_maxcut.hxx>
//#endif

int main()
{
   std::cout << "Planar MaxCut Test ... "<<std::endl;
   {
      opengm::external::PlanarMaxCut pmc(4,12);
      std::vector<int> l;
      std::vector<bool> cut;

      pmc.addEdge(0,1,-2.0);
      pmc.addEdge(0,2, 2.0);
      pmc.addEdge(1,3, 2.0);
      pmc.addEdge(2,3,-2.0);
      pmc.calculateCut();
      pmc.getLabeling(l);
      pmc.getCut(cut);

      for(size_t i=0; i<4; ++i)
         std::cout <<l[i]<<", ";
      std::cout<<std::endl;

      OPENGM_ASSERT(l[0]==l[1]);
      OPENGM_ASSERT(l[2]==l[3]);
      OPENGM_ASSERT(l[0]!=l[2]);
      OPENGM_ASSERT(l[1]!=l[3]);

      OPENGM_ASSERT(cut[0]==0);
      OPENGM_ASSERT(cut[1]==1);
      OPENGM_ASSERT(cut[2]==1);
      OPENGM_ASSERT(cut[3]==0);

   }
   {
      opengm::external::PlanarMaxCut pmc(5,12);
      std::vector<int> l;
      std::vector<bool> cut;

      pmc.addEdge(0,1, -2.0);
      pmc.addEdge(0,2, -2.0);
      pmc.addEdge(1,3, -2.0);
      pmc.addEdge(2,3, -2.0);
      pmc.addEdge(3,4, -2.0);
      pmc.calculateCut();
      pmc.getLabeling(l);
      pmc.getCut(cut);

      for(size_t i=0; i<cut.size(); ++i)
         std::cout <<cut[i]<<", ";
      std::cout<<std::endl;

      for(size_t i=0; i<5; ++i)
         std::cout <<l[i]<<", ";
      std::cout<<std::endl;

      OPENGM_ASSERT(l[0]==l[1]);
      OPENGM_ASSERT(l[1]==l[2]);
      OPENGM_ASSERT(l[2]==l[3]);
      OPENGM_ASSERT(l[3]==l[4]);

      OPENGM_ASSERT(cut[0]==0);
      OPENGM_ASSERT(cut[1]==0);
      OPENGM_ASSERT(cut[2]==0);
      OPENGM_ASSERT(cut[3]==0);
      OPENGM_ASSERT(cut[4]==0);

   }
   {
      opengm::external::PlanarMaxCut pmc(5,12);
      std::vector<int> l;
      std::vector<bool> cut;

      pmc.addEdge(0,1, -2.0);
      pmc.addEdge(0,2, -2.0);
      pmc.addEdge(1,3, -2.0);
      pmc.addEdge(2,3, -2.0);
      pmc.addEdge(3,4, 2.0);
      pmc.calculateCut();
      pmc.getLabeling(l);
      pmc.getCut(cut);

      for(size_t i=0; i<5; ++i)
         std::cout <<l[i]<<", ";
      std::cout<<std::endl;

      OPENGM_ASSERT(l[0]==l[1]);
      OPENGM_ASSERT(l[1]==l[2]);
      OPENGM_ASSERT(l[2]==l[3]);
      OPENGM_ASSERT(l[3]!=l[4]);

      OPENGM_ASSERT(cut[0]==0);
      OPENGM_ASSERT(cut[1]==0);
      OPENGM_ASSERT(cut[2]==0);
      OPENGM_ASSERT(cut[3]==0);
      OPENGM_ASSERT(cut[4]==1);

   }
   {
      opengm::external::PlanarMaxCut pmc(4,12);
      std::vector<int> l;
      std::vector<bool> cut;

      pmc.addEdge(0,1, 2.0);
      pmc.addEdge(1,2, 2.0);
      pmc.addEdge(2,3, 2.0);
      pmc.addEdge(0,3, 2.0);
      pmc.calculateCut();
      pmc.getLabeling(l);
      pmc.getCut(cut);

      for(size_t i=0; i<4; ++i)
         std::cout <<l[i]<<", ";
      std::cout<<std::endl;

      OPENGM_ASSERT(l[0]!=l[1]);
      OPENGM_ASSERT(l[1]!=l[2]);
      OPENGM_ASSERT(l[2]!=l[3]);

      OPENGM_ASSERT(cut[0]==1);
      OPENGM_ASSERT(cut[1]==1);
      OPENGM_ASSERT(cut[2]==1);
      OPENGM_ASSERT(cut[3]==1);
   }

   std::cout << " OK!" << std::endl;

}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/plat/prdfPlatServices_ipl.C $               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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  prdfPlatServices_ipl.C
 * @brief Wrapper code for external interfaces used by PRD (IPL only).
 *
 * This file contains code that is strictly specific to Hostboot. All code that
 * is common between FSP and Hostboot should be in the respective common file.
 */

#include <prdfPlatServices.H>

#include <prdfGlobal.H>
#include <prdfErrlUtil.H>
#include <prdfTrace.H>

//#include <prdfCenDqBitmap.H> TODO RTC 164707
#include <prdfMemScrubUtils.H>

#include <diag/mdia/mdia.H>
#include <config.h>

using namespace TARGETING;

namespace PRDF
{

namespace PlatServices
{

//##############################################################################
//##                        Memory specific functions
//##############################################################################

bool isInMdiaMode()
{
    bool o_isInMdiaMode = false;
#ifndef CONFIG_VPO_COMPILE
    MDIA::waitingForMaintCmdEvents(o_isInMdiaMode);
#endif
    return o_isInMdiaMode;
}

//------------------------------------------------------------------------------

int32_t mdiaSendEventMsg( TargetHandle_t i_trgt,
                          MDIA::MaintCommandEventType i_eventType )
{
    #define PRDF_FUNC "[PlatServices::mdiaSendEventMsg] "

    int32_t o_rc = SUCCESS;

#ifndef CONFIG_VPO_COMPILE

    PRDF_ASSERT( nullptr != i_trgt );

    // Only MCBIST and MBA supported.
    TYPE trgtType = getTargetType( i_trgt );
    PRDF_ASSERT( TYPE_MCBIST == trgtType || TYPE_MBA == trgtType );

    // MDIA must be running.
    PRDF_ASSERT( isInMdiaMode() );

    // Send command complete to MDIA.
    MDIA::MaintCommandEvent mdiaEvent;
    mdiaEvent.target = i_trgt;
    mdiaEvent.type   = i_eventType;

    errlHndl_t errl = MDIA::processEvent( mdiaEvent );
    if ( NULL != errl )
    {
        PRDF_ERR( PRDF_FUNC "MDIA::processEvent() failed: i_target=0x%08x "
                  "i_eventType=%d", getHuid(i_trgt), i_eventType );
        PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
        o_rc = FAIL;
    }

#endif

    return o_rc;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

bool rcdParityErrorReconfigLoop()
{
    TargetHandle_t top = getSystemTarget();

    // Check the current reconfig count.
    uint8_t allowed = top->getAttr<ATTR_RCD_PARITY_RECONFIG_LOOPS_ALLOWED>();
    uint8_t count   = top->getAttr<ATTR_RCD_PARITY_RECONFIG_LOOP_COUNT>();

    if ( count <= allowed )
    {
        // Set the RCD parity error flag in the reconfig loop attribute. This
        // will trigger a reconfig loop at the end of the current istep.
        ATTR_RECONFIGURE_LOOP_type attr = top->getAttr<ATTR_RECONFIGURE_LOOP>();
        if ( 0 == (attr & RECONFIGURE_LOOP_RCD_PARITY_ERROR) )
        {
            attr |= RECONFIGURE_LOOP_RCD_PARITY_ERROR;
            top->setAttr<ATTR_RECONFIGURE_LOOP>(attr);
        }

        // Increment the count.
        top->setAttr<ATTR_RCD_PARITY_RECONFIG_LOOP_COUNT>(++count);

        return false;
    }

    return true;
}

//------------------------------------------------------------------------------

/* TODO RTC 164707
int32_t mssRestoreDramRepairs( TargetHandle_t i_mbaTarget,
                               uint8_t & o_repairedRankMask,
                               uint8_t & o_badDimmMask )
{
    int32_t o_rc = SUCCESS;

    errlHndl_t errl = NULL;

    FAPI_INVOKE_HWP( errl, mss_restore_DRAM_repairs,
                     fapi::Target(fapi::TARGET_TYPE_MBA_CHIPLET, i_mbaTarget),
                     o_repairedRankMask, o_badDimmMask );

    if ( NULL != errl )
    {
        PRDF_ERR( "[PlatServices::mssRestoreDramRepairs] "
                  "mss_restore_dram_repairs() failed. HUID: 0x%08x",
                  getHuid(i_mbaTarget) );
        PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
        o_rc = FAIL;
    }

    return o_rc;
}
*/

//------------------------------------------------------------------------------

/* TODO RTC 157888
int32_t mssIplUeIsolation( TargetHandle_t i_mba, const CenRank & i_rank,
                           CenDqBitmap & o_bitmap )
{
    #define PRDF_FUNC "[PlatServices::mssIplUeIsolation] "

    int32_t o_rc = SUCCESS;

    uint8_t data[MBA_DIMMS_PER_RANK][DIMM_DQ_RANK_BITMAP_SIZE];

    errlHndl_t errl = NULL;
    FAPI_INVOKE_HWP( errl, mss_IPL_UE_isolation, getFapiTarget(i_mba),
                     i_rank.getMaster(), data );
    if ( NULL != errl )
    {
        PRDF_ERR( PRDF_FUNC "mss_IPL_UE_isolation() failed: MBA=0x%08x "
                  "rank=%d", getHuid(i_mba), i_rank.getMaster() );
        PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
        o_rc = FAIL;
    }
    else
    {
        o_bitmap = CenDqBitmap ( i_mba, i_rank, data );
    }

    return o_rc;

    #undef PRDF_FUNC
}
*/

//##############################################################################
//##                    Nimbus Maintenance Command wrappers
//##############################################################################

template<>
uint32_t startSfRead<TYPE_MCA>( ExtensibleChip * i_mcaChip,
                                const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startSfRead<TYPE_MCA>] "

    PRDF_ASSERT( isInMdiaMode() ); // MDIA must be running.

    PRDF_ASSERT( nullptr != i_mcaChip );
    PRDF_ASSERT( TYPE_MCA == i_mcaChip->getType() );

    uint32_t o_rc = SUCCESS;

    // Get the MCBIST fapi target
    ExtensibleChip * mcbChip = getConnectedParent( i_mcaChip, TYPE_MCBIST );
    fapi2::Target<fapi2::TARGET_TYPE_MCBIST> fapiTrgt ( mcbChip->getTrgt() );

    // Get the stop conditions.
    mss::mcbist::stop_conditions stopCond;
    stopCond.set_pause_on_mpe(mss::ON)
            .set_pause_on_ue(mss::ON)
            .set_nce_inter_symbol_count_enable(mss::ON)
            .set_nce_soft_symbol_count_enable( mss::ON)
            .set_nce_hard_symbol_count_enable( mss::ON);

    // Stop on hard CEs if MNFG CE checking is enable.
    if ( isMfgCeCheckingEnabled() ) stopCond.set_pause_on_nce_hard(mss::ON);

    // Get the first address of the given rank.
    uint32_t port = i_mcaChip->getPos() % MAX_MCA_PER_MCBIST;
    mss::mcbist::address saddr, eaddr;
    mss::mcbist::address::get_srank_range( port,
                                           i_rank.getDimmSlct(),
                                           i_rank.getRankSlct(),
                                           i_rank.getSlave(),
                                           saddr,
                                           eaddr );

    do
    {
        // Clear all of the counters and maintenance ECC attentions.
        o_rc = prepareNextCmd<TYPE_MCBIST>( mcbChip );
        if ( SUCCESS != o_rc )
        {
            PRDF_ERR( PRDF_FUNC "prepareNextCmd(0x%08x) failed",
                      mcbChip->getHuid() );
            break;
        }

        // Start the super fast read command.
        errlHndl_t errl;
        FAPI_INVOKE_HWP( errl, memdiags::sf_read, fapiTrgt, stopCond, saddr );

        if ( nullptr != errl )
        {
            PRDF_ERR( PRDF_FUNC "memdiags::sf_read(0x%08x,%d) failed",
                      mcbChip->getHuid(), i_rank.getMaster() );
            PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
            o_rc = FAIL; break;
        }

    } while (0);

    return o_rc;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

// This specialization only exists to avoid a lot of extra code in some classes.
// The input chip must still be an MCA chip.
template<>
uint32_t startSfRead<TYPE_MCBIST>( ExtensibleChip * i_mcaChip,
                                   const MemRank & i_rank )
{
    return startSfRead<TYPE_MCA>( i_mcaChip, i_rank );
}

//##############################################################################
//##                   Centaur Maintenance Command wrappers
//##############################################################################

template<>
uint32_t startSfRead<TYPE_MBA>( ExtensibleChip * i_mbaChip,
                                const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startSfRead<TYPE_MBA>] "

    PRDF_ASSERT( nullptr != i_mbaChip );
    PRDF_ASSERT( TYPE_MBA == i_mbaChip->getType() );

    uint32_t o_rc = SUCCESS;

    do
    {
        // Clear all of the counters and maintenance ECC attentions.
        o_rc = prepareNextCmd<TYPE_MBA>( i_mbaChip );
        if ( SUCCESS != o_rc )
        {
            PRDF_ERR( PRDF_FUNC "prepareNextCmd(0x%08x) failed",
                      i_mbaChip->getHuid() );
            break;
        }

        // Start the background scrub command.
        PRDF_ERR( PRDF_FUNC "function not implemented yet" ); // TODO RTC 157888

    } while (0);

    return o_rc;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

template<>
uint32_t startVcmPhase1<TYPE_MBA>( ExtensibleChip * i_chip,
                                   const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startVcmPhase1<TYPE_MBA>] "

    PRDF_ASSERT( nullptr != i_chip );
    PRDF_ASSERT( TYPE_MBA == i_chip->getType() );

    // TODO RTC 157888
    //  - Start a targeted steer cleanup.
    //  - Stop on RCE ETE (threshold 1).
    //  - The command should always stop at the end of the master rank.

    PRDF_ERR( PRDF_FUNC "function not implemented yet" );

    return SUCCESS;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

template<>
uint32_t startVcmPhase2<TYPE_MBA>( ExtensibleChip * i_chip,
                                   const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startVcmPhase2<TYPE_MBA>] "

    PRDF_ASSERT( nullptr != i_chip );
    PRDF_ASSERT( TYPE_MBA == i_chip->getType() );

    // TODO RTC 157888
    //  - Start a targeted super fast read.
    //  - No stop-on-error conditions. Note that RCEs will report as UEs during
    //    read operations. You can still set stop-on-RCE-ETE to be consistent
    //    with phase 1, but it will not have any effect and is not required.
    //  - The command should always stop at the end of the master rank.

    PRDF_ERR( PRDF_FUNC "function not implemented yet" );

    return SUCCESS;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

} // end namespace PlatServices

} // end namespace PRDF

<commit_msg>PRD: set stop-on-AUE during memdiags after TD procedure<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/plat/prdfPlatServices_ipl.C $               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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  prdfPlatServices_ipl.C
 * @brief Wrapper code for external interfaces used by PRD (IPL only).
 *
 * This file contains code that is strictly specific to Hostboot. All code that
 * is common between FSP and Hostboot should be in the respective common file.
 */

#include <prdfPlatServices.H>

#include <prdfGlobal.H>
#include <prdfErrlUtil.H>
#include <prdfTrace.H>

//#include <prdfCenDqBitmap.H> TODO RTC 164707
#include <prdfMemScrubUtils.H>

#include <diag/mdia/mdia.H>
#include <config.h>

using namespace TARGETING;

namespace PRDF
{

namespace PlatServices
{

//##############################################################################
//##                        Memory specific functions
//##############################################################################

bool isInMdiaMode()
{
    bool o_isInMdiaMode = false;
#ifndef CONFIG_VPO_COMPILE
    MDIA::waitingForMaintCmdEvents(o_isInMdiaMode);
#endif
    return o_isInMdiaMode;
}

//------------------------------------------------------------------------------

int32_t mdiaSendEventMsg( TargetHandle_t i_trgt,
                          MDIA::MaintCommandEventType i_eventType )
{
    #define PRDF_FUNC "[PlatServices::mdiaSendEventMsg] "

    int32_t o_rc = SUCCESS;

#ifndef CONFIG_VPO_COMPILE

    PRDF_ASSERT( nullptr != i_trgt );

    // Only MCBIST and MBA supported.
    TYPE trgtType = getTargetType( i_trgt );
    PRDF_ASSERT( TYPE_MCBIST == trgtType || TYPE_MBA == trgtType );

    // MDIA must be running.
    PRDF_ASSERT( isInMdiaMode() );

    // Send command complete to MDIA.
    MDIA::MaintCommandEvent mdiaEvent;
    mdiaEvent.target = i_trgt;
    mdiaEvent.type   = i_eventType;

    errlHndl_t errl = MDIA::processEvent( mdiaEvent );
    if ( NULL != errl )
    {
        PRDF_ERR( PRDF_FUNC "MDIA::processEvent() failed: i_target=0x%08x "
                  "i_eventType=%d", getHuid(i_trgt), i_eventType );
        PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
        o_rc = FAIL;
    }

#endif

    return o_rc;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

bool rcdParityErrorReconfigLoop()
{
    TargetHandle_t top = getSystemTarget();

    // Check the current reconfig count.
    uint8_t allowed = top->getAttr<ATTR_RCD_PARITY_RECONFIG_LOOPS_ALLOWED>();
    uint8_t count   = top->getAttr<ATTR_RCD_PARITY_RECONFIG_LOOP_COUNT>();

    if ( count <= allowed )
    {
        // Set the RCD parity error flag in the reconfig loop attribute. This
        // will trigger a reconfig loop at the end of the current istep.
        ATTR_RECONFIGURE_LOOP_type attr = top->getAttr<ATTR_RECONFIGURE_LOOP>();
        if ( 0 == (attr & RECONFIGURE_LOOP_RCD_PARITY_ERROR) )
        {
            attr |= RECONFIGURE_LOOP_RCD_PARITY_ERROR;
            top->setAttr<ATTR_RECONFIGURE_LOOP>(attr);
        }

        // Increment the count.
        top->setAttr<ATTR_RCD_PARITY_RECONFIG_LOOP_COUNT>(++count);

        return false;
    }

    return true;
}

//------------------------------------------------------------------------------

/* TODO RTC 164707
int32_t mssRestoreDramRepairs( TargetHandle_t i_mbaTarget,
                               uint8_t & o_repairedRankMask,
                               uint8_t & o_badDimmMask )
{
    int32_t o_rc = SUCCESS;

    errlHndl_t errl = NULL;

    FAPI_INVOKE_HWP( errl, mss_restore_DRAM_repairs,
                     fapi::Target(fapi::TARGET_TYPE_MBA_CHIPLET, i_mbaTarget),
                     o_repairedRankMask, o_badDimmMask );

    if ( NULL != errl )
    {
        PRDF_ERR( "[PlatServices::mssRestoreDramRepairs] "
                  "mss_restore_dram_repairs() failed. HUID: 0x%08x",
                  getHuid(i_mbaTarget) );
        PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
        o_rc = FAIL;
    }

    return o_rc;
}
*/

//------------------------------------------------------------------------------

/* TODO RTC 157888
int32_t mssIplUeIsolation( TargetHandle_t i_mba, const CenRank & i_rank,
                           CenDqBitmap & o_bitmap )
{
    #define PRDF_FUNC "[PlatServices::mssIplUeIsolation] "

    int32_t o_rc = SUCCESS;

    uint8_t data[MBA_DIMMS_PER_RANK][DIMM_DQ_RANK_BITMAP_SIZE];

    errlHndl_t errl = NULL;
    FAPI_INVOKE_HWP( errl, mss_IPL_UE_isolation, getFapiTarget(i_mba),
                     i_rank.getMaster(), data );
    if ( NULL != errl )
    {
        PRDF_ERR( PRDF_FUNC "mss_IPL_UE_isolation() failed: MBA=0x%08x "
                  "rank=%d", getHuid(i_mba), i_rank.getMaster() );
        PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
        o_rc = FAIL;
    }
    else
    {
        o_bitmap = CenDqBitmap ( i_mba, i_rank, data );
    }

    return o_rc;

    #undef PRDF_FUNC
}
*/

//##############################################################################
//##                    Nimbus Maintenance Command wrappers
//##############################################################################

template<>
uint32_t startSfRead<TYPE_MCA>( ExtensibleChip * i_mcaChip,
                                const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startSfRead<TYPE_MCA>] "

    PRDF_ASSERT( isInMdiaMode() ); // MDIA must be running.

    PRDF_ASSERT( nullptr != i_mcaChip );
    PRDF_ASSERT( TYPE_MCA == i_mcaChip->getType() );

    uint32_t o_rc = SUCCESS;

    // Get the MCBIST fapi target
    ExtensibleChip * mcbChip = getConnectedParent( i_mcaChip, TYPE_MCBIST );
    fapi2::Target<fapi2::TARGET_TYPE_MCBIST> fapiTrgt ( mcbChip->getTrgt() );

    // Get the stop conditions.
    mss::mcbist::stop_conditions stopCond;
    stopCond.set_pause_on_mpe(mss::ON)
            .set_pause_on_ue(mss::ON)
            .set_pause_on_aue(mss::ON)
            .set_nce_inter_symbol_count_enable(mss::ON)
            .set_nce_soft_symbol_count_enable( mss::ON)
            .set_nce_hard_symbol_count_enable( mss::ON);

    // Stop on hard CEs if MNFG CE checking is enable.
    if ( isMfgCeCheckingEnabled() ) stopCond.set_pause_on_nce_hard(mss::ON);

    // Get the first address of the given rank.
    uint32_t port = i_mcaChip->getPos() % MAX_MCA_PER_MCBIST;
    mss::mcbist::address saddr, eaddr;
    mss::mcbist::address::get_srank_range( port,
                                           i_rank.getDimmSlct(),
                                           i_rank.getRankSlct(),
                                           i_rank.getSlave(),
                                           saddr,
                                           eaddr );

    do
    {
        // Clear all of the counters and maintenance ECC attentions.
        o_rc = prepareNextCmd<TYPE_MCBIST>( mcbChip );
        if ( SUCCESS != o_rc )
        {
            PRDF_ERR( PRDF_FUNC "prepareNextCmd(0x%08x) failed",
                      mcbChip->getHuid() );
            break;
        }

        // Start the super fast read command.
        errlHndl_t errl;
        FAPI_INVOKE_HWP( errl, memdiags::sf_read, fapiTrgt, stopCond, saddr );

        if ( nullptr != errl )
        {
            PRDF_ERR( PRDF_FUNC "memdiags::sf_read(0x%08x,%d) failed",
                      mcbChip->getHuid(), i_rank.getMaster() );
            PRDF_COMMIT_ERRL( errl, ERRL_ACTION_REPORT );
            o_rc = FAIL; break;
        }

    } while (0);

    return o_rc;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

// This specialization only exists to avoid a lot of extra code in some classes.
// The input chip must still be an MCA chip.
template<>
uint32_t startSfRead<TYPE_MCBIST>( ExtensibleChip * i_mcaChip,
                                   const MemRank & i_rank )
{
    return startSfRead<TYPE_MCA>( i_mcaChip, i_rank );
}

//##############################################################################
//##                   Centaur Maintenance Command wrappers
//##############################################################################

template<>
uint32_t startSfRead<TYPE_MBA>( ExtensibleChip * i_mbaChip,
                                const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startSfRead<TYPE_MBA>] "

    PRDF_ASSERT( nullptr != i_mbaChip );
    PRDF_ASSERT( TYPE_MBA == i_mbaChip->getType() );

    uint32_t o_rc = SUCCESS;

    do
    {
        // Clear all of the counters and maintenance ECC attentions.
        o_rc = prepareNextCmd<TYPE_MBA>( i_mbaChip );
        if ( SUCCESS != o_rc )
        {
            PRDF_ERR( PRDF_FUNC "prepareNextCmd(0x%08x) failed",
                      i_mbaChip->getHuid() );
            break;
        }

        // Start the background scrub command.
        PRDF_ERR( PRDF_FUNC "function not implemented yet" ); // TODO RTC 157888

    } while (0);

    return o_rc;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

template<>
uint32_t startVcmPhase1<TYPE_MBA>( ExtensibleChip * i_chip,
                                   const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startVcmPhase1<TYPE_MBA>] "

    PRDF_ASSERT( nullptr != i_chip );
    PRDF_ASSERT( TYPE_MBA == i_chip->getType() );

    // TODO RTC 157888
    //  - Start a targeted steer cleanup.
    //  - Stop on RCE ETE (threshold 1).
    //  - The command should always stop at the end of the master rank.

    PRDF_ERR( PRDF_FUNC "function not implemented yet" );

    return SUCCESS;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

template<>
uint32_t startVcmPhase2<TYPE_MBA>( ExtensibleChip * i_chip,
                                   const MemRank & i_rank )
{
    #define PRDF_FUNC "[PlatServices::startVcmPhase2<TYPE_MBA>] "

    PRDF_ASSERT( nullptr != i_chip );
    PRDF_ASSERT( TYPE_MBA == i_chip->getType() );

    // TODO RTC 157888
    //  - Start a targeted super fast read.
    //  - No stop-on-error conditions. Note that RCEs will report as UEs during
    //    read operations. You can still set stop-on-RCE-ETE to be consistent
    //    with phase 1, but it will not have any effect and is not required.
    //  - The command should always stop at the end of the master rank.

    PRDF_ERR( PRDF_FUNC "function not implemented yet" );

    return SUCCESS;

    #undef PRDF_FUNC
}

//------------------------------------------------------------------------------

} // end namespace PlatServices

} // end namespace PRDF

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep13/call_mss_draminit_mc.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                                                     */

//Error handling and tracing
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>

//  targeting support
#include <targeting/common/commontargeting.H>
#include <targeting/common/util.H>
#include <targeting/common/utilFilter.H>

// Istep 13 framework
#include "istep13consts.H"

// fapi2 HWP invoker
#include  <fapi2/plat_hwp_invoker.H>

//From Import Directory (EKB Repository)
#include  <config.h>
#include  <fapi2.H>
#include  <p9_mss_draminit_mc.H>

using namespace ERRORLOG;
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace TARGETING;

namespace ISTEP_13
{
void* call_mss_draminit_mc (void *io_pArgs)
{
    errlHndl_t l_err = NULL;

    IStepError l_stepError;

    TARGETING::Target * sys = NULL;
    TARGETING::targetService().getTopLevelTarget( sys );

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"call_mss_draminit_mc entry" );

    // Get all MCBIST
    TARGETING::TargetHandleList l_mcbistTargetList;
    getAllChiplets(l_mcbistTargetList, TYPE_MCBIST);

    for (const auto & l_mcbist_target : l_mcbistTargetList)
    {
        // Dump current run on target
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "Running p9_mss_draminit_mc HWP on "
                "target HUID %.8X", TARGETING::get_huid(l_mcbist_target));

        fapi2::Target<fapi2::TARGET_TYPE_MCBIST> l_fapi_mcbist_target
            (l_mcbist_target);
        FAPI_INVOKE_HWP(l_err, p9_mss_draminit_mc, l_fapi_mcbist_target);

        if (l_err)
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                    "ERROR 0x%.8X : p9_mss_draminit_mc HWP returns error",
                    l_err->reasonCode());

            // capture the target data in the elog
            ErrlUserDetailsTarget(l_mcbist_target).addToLog( l_err );

            // Create IStep error log and cross reference to error that occurred
            l_stepError.addErrorDetails( l_err );

            // Commit Error
            errlCommit( l_err, HWPF_COMP_ID );
        }
        else
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                       "SUCCESS running p9_mss_draminit_mc HWP on "
                       "target HUID %.8X", TARGETING::get_huid(l_mcbist_target));
        }

    } // End; memBuf loop

    //TODO RTC:167292 Remove this workaround that is clearing this scom register
    fapi2::buffer<uint64_t> l_data64;
    l_data64.flush<0>();
    // Get all MCAs
    TARGETING::TargetHandleList l_mcaTargetList;
    getAllChiplets(l_mcaTargetList, TYPE_MCA);

    //Clear out the MBA_FARB3Q reg(0x7010916) on all MCAs
    for (const auto & l_mca_target : l_mcaTargetList)
    {
        fapi2::Target<fapi2::TARGET_TYPE_MCA> l_fapi_mca_target
        (l_mca_target);
        fapi2::putScom(l_fapi_mca_target, 0x7010916, l_data64);
    }

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_draminit_mc exit" );

    return l_stepError.getErrorHandle();
}

};
<commit_msg>Clean up FAR3BQ workaround so that fails will be committed properly<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep13/call_mss_draminit_mc.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                                                     */

//Error handling and tracing
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>

//  targeting support
#include <targeting/common/commontargeting.H>
#include <targeting/common/util.H>
#include <targeting/common/utilFilter.H>

// Istep 13 framework
#include "istep13consts.H"

// fapi2 HWP invoker
#include  <fapi2/plat_hwp_invoker.H>

//From Import Directory (EKB Repository)
#include  <config.h>
#include  <fapi2.H>
#include  <p9_mss_draminit_mc.H>

using namespace ERRORLOG;
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace TARGETING;

namespace ISTEP_13
{
void* call_mss_draminit_mc (void *io_pArgs)
{
    errlHndl_t l_err = NULL;

    IStepError l_stepError;

    TARGETING::Target * sys = NULL;
    TARGETING::targetService().getTopLevelTarget( sys );

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"call_mss_draminit_mc entry" );

    // Get all MCBIST
    TARGETING::TargetHandleList l_mcbistTargetList;
    getAllChiplets(l_mcbistTargetList, TYPE_MCBIST);

    for (const auto & l_mcbist_target : l_mcbistTargetList)
    {
        // Dump current run on target
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "Running p9_mss_draminit_mc HWP on "
                "target HUID %.8X", TARGETING::get_huid(l_mcbist_target));

        fapi2::Target<fapi2::TARGET_TYPE_MCBIST> l_fapi_mcbist_target
            (l_mcbist_target);
        FAPI_INVOKE_HWP(l_err, p9_mss_draminit_mc, l_fapi_mcbist_target);

        if (l_err)
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                    "ERROR 0x%.8X : p9_mss_draminit_mc HWP returns error",
                    l_err->reasonCode());

            // capture the target data in the elog
            ErrlUserDetailsTarget(l_mcbist_target).addToLog( l_err );

            // Create IStep error log and cross reference to error that occurred
            l_stepError.addErrorDetails( l_err );

            // Commit Error
            errlCommit( l_err, HWPF_COMP_ID );
        }
        else
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                       "SUCCESS running p9_mss_draminit_mc HWP on "
                       "target HUID %.8X", TARGETING::get_huid(l_mcbist_target));
        }

    } // End; memBuf loop

    //TODO RTC:167292 Remove this workaround that is clearing this scom register
    uint64_t l_data64 = 0x0;
    size_t l_size = sizeof(uint64_t);
    // Get all MCAs
    TARGETING::TargetHandleList l_mcaTargetList;
    getAllChiplets(l_mcaTargetList, TYPE_MCA);

    //Clear out the MBA_FARB3Q reg(0x7010916) on all MCAs
    for (const auto & l_mca_target : l_mcaTargetList)
    {
        l_err = deviceOp( DeviceFW::WRITE,
                          l_mca_target,
                          &l_data64,
                          l_size,
                          DEVICE_SCOM_ADDRESS(0x7010916));
        if (l_err)
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                      "Failed clearing MBA_FARB3Q register on MCA %d",
                      l_mca_target->getAttr<TARGETING::ATTR_CHIPLET_ID>());
            errlCommit(l_err, HWPF_COMP_ID);
        }
    }

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_draminit_mc exit" );

    return l_stepError.getErrorHandle();
}

};
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <string>

#include <osquery/core.h>
#include <osquery/tables.h>

#include "osquery/tables/system/windows/registry.h"

namespace osquery {
namespace tables {

struct sdb {
  std::string description;
  unsigned long long installTimestamp;
  std::string path;
  std::string type;
};

QueryData genShims(QueryContext& context) {
  QueryData results;
  QueryData sdbResults;
  QueryData shimResults;
  std::map<std::string, sdb> sdbs;

  queryKey(
      "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows "
      "NT\\CurrentVersion\\AppCompatFlags\\InstalledSDB",
      sdbResults);
  for (const auto& rKey : sdbResults) {
    if (rKey.at("type") != "subkey") {
      continue;
    }
    QueryData regResults;
    sdb sdb;
    std::string subkey = rKey.at("path");
    auto start = subkey.find("{");
    if (start == std::string::npos) {
      continue;
    }
    std::string sdbId = subkey.substr(start, subkey.length());
    // make sure it's a sane uninstall key
    queryKey(subkey, regResults);
    for (const auto& aKey : regResults) {
      if (aKey.at("name") == "DatabaseDescription") {
        sdb.description = aKey.at("data");
      }
      if (aKey.at("name") == "DatabaseInstallTimeStamp") {
        // take this crazy windows timestamp to a unix timestamp
        sdb.installTimestamp = std::stoull(aKey.at("data"));
        sdb.installTimestamp = (sdb.installTimestamp / 10000000) - 11644473600;
      }
      if (aKey.at("name") == "DatabasePath") {
        sdb.path = aKey.at("data");
      }
      if (aKey.at("name") == "DatabaseType") {
        sdb.type = aKey.at("data");
      }
    }
    sdbs[sdbId] = sdb;
  }

  queryKey(
      "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\"
      "CurrentVersion\\AppCompatFlags\\Custom",
      shimResults);
  for (const auto& rKey : shimResults) {
    QueryData regResults;
    if (rKey.at("type") != "subkey") {
      continue;
    }
    std::string subkey = rKey.at("path");
    auto start = rKey.at("path").rfind("\\");
    if (start == std::string::npos) {
      continue;
    }
    std::string executable =
        rKey.at("path").substr(start + 1, rKey.at("subkey").length());
    // make sure it's a sane uninstall key
    queryKey(subkey, regResults);
    for (const auto& aKey : regResults) {
      Row r;
      std::string sdbId;
      if (aKey.at("name").length() > 4) {
        sdbId = aKey.at("name").substr(0, aKey.at("name").length() - 4);
      }
      if (sdbs.count(sdbId) == 0) {
        continue;
      }
      r["executable"] = executable;
      r["path"] = sdbs.at(sdbId).path;
      r["description"] = sdbs.at(sdbId).description;
      r["install_time"] = INTEGER(sdbs.at(sdbId).installTimestamp);
      r["type"] = sdbs.at(sdbId).type;
      r["sdb_id"] = sdbId;
      results.push_back(r);
    }
  }

  return results;
}
}
}
<commit_msg>Adding bounds checks and key checks for appcompat shims table (#3169)<commit_after>/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <string>

#include <osquery/core.h>
#include <osquery/tables.h>

#include "osquery/core/conversions.h"
#include "osquery/tables/system/windows/registry.h"

namespace osquery {
namespace tables {

struct sdb {
  std::string description;
  unsigned long long installTimestamp;
  std::string path;
  std::string type;
};

QueryData genShims(QueryContext& context) {
  QueryData results;
  QueryData sdbResults;
  QueryData shimResults;
  std::map<std::string, sdb> sdbs;

  queryKey(
      "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows "
      "NT\\CurrentVersion\\AppCompatFlags\\InstalledSDB",
      sdbResults);
  for (const auto& rKey : sdbResults) {
    if (rKey.count("type") == 0 || rKey.count("path") == 0) {
      continue;
    }
    QueryData regResults;
    sdb sdb;
    std::string subkey = rKey.at("path");
    auto start = subkey.find("{");
    if (start == std::string::npos) {
      continue;
    }
    if (start > subkey.size()) {
      continue;
    }
    std::string sdbId = subkey.substr(start, subkey.length());
    // make sure it's a sane uninstall key
    queryKey(subkey, regResults);
    for (const auto& aKey : regResults) {
      if (aKey.count("name") == 0 || aKey.count("data") == 0) {
        continue;
      }
      if (aKey.at("name") == "DatabaseDescription") {
        sdb.description = aKey.at("data");
      }
      if (aKey.at("name") == "DatabaseInstallTimeStamp") {
        // take this crazy windows timestamp to a unix timestamp
        sdb.installTimestamp = std::stoull(aKey.at("data"));
        sdb.installTimestamp = (sdb.installTimestamp / 10000000) - 11644473600;
      }
      if (aKey.at("name") == "DatabasePath") {
        sdb.path = aKey.at("data");
      }
      if (aKey.at("name") == "DatabaseType") {
        sdb.type = aKey.at("data");
      }
    }
    sdbs[sdbId] = sdb;
  }

  queryKey(
      "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\"
      "CurrentVersion\\AppCompatFlags\\Custom",
      shimResults);
  for (const auto& rKey : shimResults) {
    if (rKey.count("type") == 0 || rKey.count("path") == 0 ||
        rKey.at("type") != "subkey") {
      continue;
    }

    QueryData regResults;
    std::string subkey = rKey.at("path");
    auto toks = split(rKey.at("path"), "\\");
    auto executable = toks[toks.size() - 1];
    queryKey(subkey, regResults);
    for (const auto& aKey : regResults) {
      Row r;
      std::string sdbId;
      if (aKey.at("name").length() > 4) {
        sdbId = aKey.at("name").substr(0, aKey.at("name").length() - 4);
      }
      if (sdbs.count(sdbId) == 0) {
        continue;
      }
      r["executable"] = executable;
      r["path"] = sdbs.at(sdbId).path;
      r["description"] = sdbs.at(sdbId).description;
      r["install_time"] = INTEGER(sdbs.at(sdbId).installTimestamp);
      r["type"] = sdbs.at(sdbId).type;
      r["sdb_id"] = sdbId;
      results.push_back(r);
    }
  }

  return results;
}
} // namespace tables
} // namespace osquery
<|endoftext|>


<commit_before>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "greenworks_utils.h"
#include "steam_id.h"
#include "v8.h"

namespace greenworks {

v8::Local<v8::Object> SteamID::Create(CSteamID steam_id) {
  Nan::EscapableHandleScope scope;
  v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>();
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  SetPrototypeMethod(tpl, "isAnonymous", IsAnonymous);
  SetPrototypeMethod(tpl, "isAnonymousGameServer", IsAnonymousGameServer);
  SetPrototypeMethod(tpl, "isAnonymousGameServerLogin",
                     IsAnonymousGameServerLogin);
  SetPrototypeMethod(tpl, "isAnonymousUser", IsAnonymousUser);
  SetPrototypeMethod(tpl, "isChatAccount", IsChatAccount);
  SetPrototypeMethod(tpl, "isClanAccount", IsClanAccount);
  SetPrototypeMethod(tpl, "isConsoleUserAccount", IsConsoleUserAccount);
  SetPrototypeMethod(tpl, "isContentServerAccount", IsContentServerAccount);
  SetPrototypeMethod(tpl, "isGameServerAccount", IsGameServerAccount);
  SetPrototypeMethod(tpl, "isIndividualAccount", IsIndividualAccount);
  SetPrototypeMethod(tpl, "isPersistentGameServerAccount",
                     IsPersistentGameServerAccount);
  SetPrototypeMethod(tpl, "isLobby", IsLobby);
  SetPrototypeMethod(tpl, "getAccountID", GetAccountID);
  SetPrototypeMethod(tpl, "getRawSteamID", GetRawSteamID);
  SetPrototypeMethod(tpl, "getAccountType", GetAccountType);
  SetPrototypeMethod(tpl, "isValid", IsValid);
  SetPrototypeMethod(tpl, "getStaticAccountKey", GetStaticAccountKey);
  SetPrototypeMethod(tpl, "getPersonaName", GetPersonaName);
  SetPrototypeMethod(tpl, "getNickname", GetNickname);
  SetPrototypeMethod(tpl, "getRelationship", GetRelationship);
  SetPrototypeMethod(tpl, "getSteamLevel", GetSteamLevel);

  SteamID* obj = new SteamID(steam_id);
  v8::Local<v8::Object> instance =
      Nan::NewInstance(tpl->GetFunction()).ToLocalChecked();
  Nan::SetInternalFieldPointer(instance, 0, obj);
  return scope.Escape(instance);
}

NAN_METHOD(SteamID::IsAnonymous) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(obj->steam_id_.BAnonAccount());
}

NAN_METHOD(SteamID::IsAnonymousGameServer) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(obj->steam_id_.BAnonGameServerAccount());
}

NAN_METHOD(SteamID::IsAnonymousGameServerLogin) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BBlankAnonAccount()));
}

NAN_METHOD(SteamID::IsAnonymousUser) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BAnonUserAccount()));
}

NAN_METHOD(SteamID::IsChatAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BChatAccount()));
}

NAN_METHOD(SteamID::IsClanAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BClanAccount()));
}

NAN_METHOD(SteamID::IsConsoleUserAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BConsoleUserAccount()));
}

NAN_METHOD(SteamID::IsContentServerAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BContentServerAccount()));
}

NAN_METHOD(SteamID::IsGameServerAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BGameServerAccount()));
}

NAN_METHOD(SteamID::IsIndividualAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BIndividualAccount()));
}

NAN_METHOD(SteamID::IsPersistentGameServerAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(obj->steam_id_.BPersistentGameServerAccount()));
}

NAN_METHOD(SteamID::IsLobby) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsLobby()));
}

NAN_METHOD(SteamID::GetAccountID) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New<v8::Integer>(obj->steam_id_.GetAccountID()));
}

NAN_METHOD(SteamID::GetRawSteamID) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(utils::uint64ToString(obj->steam_id_.ConvertToUint64()))
          .ToLocalChecked());
}

NAN_METHOD(SteamID::GetAccountType) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.GetEAccountType()));
}

NAN_METHOD(SteamID::IsValid) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsValid()));
}

NAN_METHOD(SteamID::GetStaticAccountKey) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(utils::uint64ToString(
          obj->steam_id_.GetStaticAccountKey())).ToLocalChecked());
}

NAN_METHOD(SteamID::GetPersonaName) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(SteamFriends()->GetFriendPersonaName(obj->steam_id_))
          .ToLocalChecked());
}

NAN_METHOD(SteamID::GetNickname) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  const char* nick_name = SteamFriends()->GetPlayerNickname(obj->steam_id_);
  if (!nick_name) {
    info.GetReturnValue().Set(Nan::New(nick_name).ToLocalChecked());
    return;
  }
  info.GetReturnValue().Set(Nan::EmptyString());
}

NAN_METHOD(SteamID::GetRelationship) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(SteamFriends()->GetFriendRelationship(obj->steam_id_)));
}

NAN_METHOD(SteamID::GetSteamLevel) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(SteamFriends()->GetFriendSteamLevel(obj->steam_id_)));
}

}  // namespace greenworks
<commit_msg>fix crash<commit_after>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "greenworks_utils.h"
#include "steam_id.h"
#include "v8.h"

namespace greenworks {

v8::Local<v8::Object> SteamID::Create(CSteamID steam_id) {
  Nan::EscapableHandleScope scope;
  v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>();
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  SetPrototypeMethod(tpl, "isAnonymous", IsAnonymous);
  SetPrototypeMethod(tpl, "isAnonymousGameServer", IsAnonymousGameServer);
  SetPrototypeMethod(tpl, "isAnonymousGameServerLogin",
                     IsAnonymousGameServerLogin);
  SetPrototypeMethod(tpl, "isAnonymousUser", IsAnonymousUser);
  SetPrototypeMethod(tpl, "isChatAccount", IsChatAccount);
  SetPrototypeMethod(tpl, "isClanAccount", IsClanAccount);
  SetPrototypeMethod(tpl, "isConsoleUserAccount", IsConsoleUserAccount);
  SetPrototypeMethod(tpl, "isContentServerAccount", IsContentServerAccount);
  SetPrototypeMethod(tpl, "isGameServerAccount", IsGameServerAccount);
  SetPrototypeMethod(tpl, "isIndividualAccount", IsIndividualAccount);
  SetPrototypeMethod(tpl, "isPersistentGameServerAccount",
                     IsPersistentGameServerAccount);
  SetPrototypeMethod(tpl, "isLobby", IsLobby);
  SetPrototypeMethod(tpl, "getAccountID", GetAccountID);
  SetPrototypeMethod(tpl, "getRawSteamID", GetRawSteamID);
  SetPrototypeMethod(tpl, "getAccountType", GetAccountType);
  SetPrototypeMethod(tpl, "isValid", IsValid);
  SetPrototypeMethod(tpl, "getStaticAccountKey", GetStaticAccountKey);
  SetPrototypeMethod(tpl, "getPersonaName", GetPersonaName);
  SetPrototypeMethod(tpl, "getNickname", GetNickname);
  SetPrototypeMethod(tpl, "getRelationship", GetRelationship);
  SetPrototypeMethod(tpl, "getSteamLevel", GetSteamLevel);

  SteamID* obj = new SteamID(steam_id);
  v8::Local<v8::Object> instance =
      Nan::NewInstance(tpl->GetFunction()).ToLocalChecked();
  Nan::SetInternalFieldPointer(instance, 0, obj);
  return scope.Escape(instance);
}

NAN_METHOD(SteamID::IsAnonymous) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(obj->steam_id_.BAnonAccount());
}

NAN_METHOD(SteamID::IsAnonymousGameServer) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(obj->steam_id_.BAnonGameServerAccount());
}

NAN_METHOD(SteamID::IsAnonymousGameServerLogin) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BBlankAnonAccount()));
}

NAN_METHOD(SteamID::IsAnonymousUser) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BAnonUserAccount()));
}

NAN_METHOD(SteamID::IsChatAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BChatAccount()));
}

NAN_METHOD(SteamID::IsClanAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BClanAccount()));
}

NAN_METHOD(SteamID::IsConsoleUserAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BConsoleUserAccount()));
}

NAN_METHOD(SteamID::IsContentServerAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BContentServerAccount()));
}

NAN_METHOD(SteamID::IsGameServerAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BGameServerAccount()));
}

NAN_METHOD(SteamID::IsIndividualAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.BIndividualAccount()));
}

NAN_METHOD(SteamID::IsPersistentGameServerAccount) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(obj->steam_id_.BPersistentGameServerAccount()));
}

NAN_METHOD(SteamID::IsLobby) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsLobby()));
}

NAN_METHOD(SteamID::GetAccountID) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New<v8::Integer>(obj->steam_id_.GetAccountID()));
}

NAN_METHOD(SteamID::GetRawSteamID) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(utils::uint64ToString(obj->steam_id_.ConvertToUint64()))
          .ToLocalChecked());
}

NAN_METHOD(SteamID::GetAccountType) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.GetEAccountType()));
}

NAN_METHOD(SteamID::IsValid) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsValid()));
}

NAN_METHOD(SteamID::GetStaticAccountKey) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(utils::uint64ToString(
          obj->steam_id_.GetStaticAccountKey())).ToLocalChecked());
}

NAN_METHOD(SteamID::GetPersonaName) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(SteamFriends()->GetFriendPersonaName(obj->steam_id_))
          .ToLocalChecked());
}

NAN_METHOD(SteamID::GetNickname) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  const char* nick_name = SteamFriends()->GetPlayerNickname(obj->steam_id_);
  if (nick_name != NULL) {
    info.GetReturnValue().Set(Nan::New(nick_name).ToLocalChecked());
    return;
  }
  info.GetReturnValue().Set(Nan::EmptyString());
}

NAN_METHOD(SteamID::GetRelationship) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(SteamFriends()->GetFriendRelationship(obj->steam_id_)));
}

NAN_METHOD(SteamID::GetSteamLevel) {
  SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder());
  info.GetReturnValue().Set(
      Nan::New(SteamFriends()->GetFriendSteamLevel(obj->steam_id_)));
}

}  // namespace greenworks
<|endoftext|>


<commit_before>#include <iostream>
#include <unordered_map>
#include <vector>
#include <stack>
#include <queue>

using namespace std;

class Solution {

    void help(vector<int> v, vector<vector<int>>& result, int n, vector<int> &num)
    {
        if(v.size() == n) {
            result.push_back(v);
            return;
        }

        for(int i = 0;i < num.size();i++)
        {
            int tmp = num[i];
            v.push_back(num[i]);
            num.erase(num.begin()+i);
            help(v, result, n, num);
            num.insert(num.begin()+i, tmp);
            v.pop_back();
        }
    }

public:
    vector<vector<int> > permute(vector<int> &num) {

        vector<int> v;
        vector<vector<int>> result;
        help(v, result, num.size(), num);
        return result;
    }

};

int main()
{
    Solution s;
    int a[] = {1,2,3};

    return 0;
}<commit_msg>46. Permutations<commit_after>class Solution {

    void help(vector<vector<int>>& result, int begin, vector<int> &num)
    {
        if(begin == num.size()) {
            result.push_back(num);
            return;
        }

        for(int i = begin; i < num.size();i++)
        {
            swap(num[begin], num[i]);
            help(result, begin+1, num);
            swap(num[begin], num[i]);
        }
    }

public:
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int>> result;
        help(result, 0, num);
        return result;
    }
};
<|endoftext|>