<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_about_handler.h"

#include <string>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"

namespace {

// Add paths here to be included in chrome://chrome-urls (about:about).
// These paths will also be suggested by BuiltinProvider.
const char* const kChromePaths[] = {
  chrome::kChromeUIAppCacheInternalsHost,
  chrome::kChromeUIBlobInternalsHost,
  chrome::kChromeUIBookmarksHost,
  chrome::kChromeUICacheHost,
  chrome::kChromeUIChromeURLsHost,
  chrome::kChromeUICrashesHost,
  chrome::kChromeUICreditsHost,
  chrome::kChromeUIDNSHost,
  chrome::kChromeUIDownloadsHost,
  chrome::kChromeUIExtensionsHost,
  chrome::kChromeUIFlagsHost,
  chrome::kChromeUIFlashHost,
  chrome::kChromeUIGpuInternalsHost,
  chrome::kChromeUIHistogramsHost,
  chrome::kChromeUIHistoryHost,
  chrome::kChromeUIIPCHost,
  chrome::kChromeUIInspectHost,
  chrome::kChromeUIMediaInternalsHost,
  chrome::kChromeUIMemoryHost,
  chrome::kChromeUINetInternalsHost,
  chrome::kChromeUINetworkViewCacheHost,
  chrome::kChromeUINewTabHost,
  chrome::kChromeUIOmniboxHost,
  chrome::kChromeUIPluginsHost,
  chrome::kChromeUIPolicyHost,
  chrome::kChromeUIPredictorsHost,
  chrome::kChromeUIProfilerHost,
  chrome::kChromeUIQuotaInternalsHost,
  chrome::kChromeUISettingsHost,
  chrome::kChromeUIStatsHost,
  chrome::kChromeUISyncInternalsHost,
  chrome::kChromeUITaskManagerHost,
  chrome::kChromeUITermsHost,
  chrome::kChromeUITracingHost,
  chrome::kChromeUIVersionHost,
#if defined(OS_WIN)
  chrome::kChromeUIConflictsHost,
#endif
#if defined(OS_LINUX) || defined(OS_OPENBSD)
  chrome::kChromeUILinuxProxyConfigHost,
  chrome::kChromeUISandboxHost,
#endif
#if defined(OS_CHROMEOS)
  chrome::kChromeUIChooseMobileNetworkHost,
  chrome::kChromeUICryptohomeHost,
  chrome::kChromeUIDiscardsHost,
  chrome::kChromeUIImageBurnerHost,
  chrome::kChromeUIKeyboardOverlayHost,
  chrome::kChromeUILoginHost,
  chrome::kChromeUINetworkHost,
  chrome::kChromeUIOobeHost,
  chrome::kChromeUIOSCreditsHost,
  chrome::kChromeUIProxySettingsHost,
  chrome::kChromeUISystemInfoHost,
  chrome::kChromeUIWallpaperHost,
#endif
#if defined(ENABLE_PRINTING)
  chrome::kChromeUIPrintHost,
#endif
};

}  // namespace

bool WillHandleBrowserAboutURL(GURL* url,
                               content::BrowserContext* browser_context) {
  // TODO(msw): Eliminate "about:*" constants and literals from code and tests,
  //            then hopefully we can remove this forced fixup.
  *url = URLFixerUpper::FixupURL(url->possibly_invalid_spec(), std::string());

  // Check that about: URLs are fixed up to chrome: by URLFixerUpper::FixupURL.
  DCHECK((*url == GURL(chrome::kAboutBlankURL)) ||
         !url->SchemeIs(chrome::kAboutScheme));

  // Only handle chrome://foo/, URLFixerUpper::FixupURL translates about:foo.
  if (!url->SchemeIs(chrome::kChromeUIScheme))
    return false;

  std::string host(url->host());
  std::string path;
  // Replace about with chrome-urls.
  if (host == chrome::kChromeUIAboutHost)
    host = chrome::kChromeUIChromeURLsHost;
  // Replace cache with view-http-cache.
  if (host == chrome::kChromeUICacheHost) {
    host = chrome::kChromeUINetworkViewCacheHost;
  // Replace gpu with gpu-internals.
  } else if (host == chrome::kChromeUIGpuHost) {
    host = chrome::kChromeUIGpuInternalsHost;
  // Replace sync with sync-internals (for legacy reasons).
  } else if (host == chrome::kChromeUISyncHost) {
    host = chrome::kChromeUISyncInternalsHost;
  // Redirect chrome://extensions.
  } else if (host == chrome::kChromeUIExtensionsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost + url->path();
  // Redirect chrome://settings/extensions.
  // TODO(csilv): Remove this URL after M22 (legacy URL).
  } else if (host == chrome::kChromeUISettingsHost &&
      url->path() == std::string("/") + chrome::kExtensionsSubPage) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost;
  // Redirect chrome://history.
  } else if (host == chrome::kChromeUIHistoryHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIHistoryHost + url->path();
  // Redirect chrome://settings
  } else if (host == chrome::kChromeUISettingsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUISettingsHost + url->path();
  }
  GURL::Replacements replacements;
  replacements.SetHostStr(host);
  if (!path.empty())
    replacements.SetPathStr(path);
  *url = url->ReplaceComponents(replacements);

  // Having re-written the URL, make the chrome: handler process it.
  return false;
}

bool HandleNonNavigationAboutURL(const GURL& url) {
  std::string host(url.host());

  // chrome://ipc/ is currently buggy, so we disable it for official builds.
#if !defined(OFFICIAL_BUILD)

#if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED)
  if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) {
    // Run the dialog. This will re-use the existing one if it's already up.
    chrome::ShowAboutIPCDialog();
    return true;
  }
#endif

#endif  // OFFICIAL_BUILD

  return false;
}

std::vector<std::string> ChromePaths() {
  std::vector<std::string> paths;
  paths.reserve(arraysize(kChromePaths));
  for (size_t i = 0; i < arraysize(kChromePaths); i++)
    paths.push_back(kChromePaths[i]);
  return paths;
}
<commit_msg>Show about:tasks only on CrOs, it's a dead link elsewhere.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_about_handler.h"

#include <string>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"

namespace {

// Add paths here to be included in chrome://chrome-urls (about:about).
// These paths will also be suggested by BuiltinProvider.
const char* const kChromePaths[] = {
  chrome::kChromeUIAppCacheInternalsHost,
  chrome::kChromeUIBlobInternalsHost,
  chrome::kChromeUIBookmarksHost,
  chrome::kChromeUICacheHost,
  chrome::kChromeUIChromeURLsHost,
  chrome::kChromeUICrashesHost,
  chrome::kChromeUICreditsHost,
  chrome::kChromeUIDNSHost,
  chrome::kChromeUIDownloadsHost,
  chrome::kChromeUIExtensionsHost,
  chrome::kChromeUIFlagsHost,
  chrome::kChromeUIFlashHost,
  chrome::kChromeUIGpuInternalsHost,
  chrome::kChromeUIHistogramsHost,
  chrome::kChromeUIHistoryHost,
  chrome::kChromeUIIPCHost,
  chrome::kChromeUIInspectHost,
  chrome::kChromeUIMediaInternalsHost,
  chrome::kChromeUIMemoryHost,
  chrome::kChromeUINetInternalsHost,
  chrome::kChromeUINetworkViewCacheHost,
  chrome::kChromeUINewTabHost,
  chrome::kChromeUIOmniboxHost,
  chrome::kChromeUIPluginsHost,
  chrome::kChromeUIPolicyHost,
  chrome::kChromeUIPredictorsHost,
  chrome::kChromeUIProfilerHost,
  chrome::kChromeUIQuotaInternalsHost,
  chrome::kChromeUISettingsHost,
  chrome::kChromeUIStatsHost,
  chrome::kChromeUISyncInternalsHost,
#if defined(OS_CHROMEOS)
  chrome::kChromeUITaskManagerHost,
#endif
  chrome::kChromeUITermsHost,
  chrome::kChromeUITracingHost,
  chrome::kChromeUIVersionHost,
#if defined(OS_WIN)
  chrome::kChromeUIConflictsHost,
#endif
#if defined(OS_LINUX) || defined(OS_OPENBSD)
  chrome::kChromeUILinuxProxyConfigHost,
  chrome::kChromeUISandboxHost,
#endif
#if defined(OS_CHROMEOS)
  chrome::kChromeUIChooseMobileNetworkHost,
  chrome::kChromeUICryptohomeHost,
  chrome::kChromeUIDiscardsHost,
  chrome::kChromeUIImageBurnerHost,
  chrome::kChromeUIKeyboardOverlayHost,
  chrome::kChromeUILoginHost,
  chrome::kChromeUINetworkHost,
  chrome::kChromeUIOobeHost,
  chrome::kChromeUIOSCreditsHost,
  chrome::kChromeUIProxySettingsHost,
  chrome::kChromeUISystemInfoHost,
  chrome::kChromeUIWallpaperHost,
#endif
#if defined(ENABLE_PRINTING)
  chrome::kChromeUIPrintHost,
#endif
};

}  // namespace

bool WillHandleBrowserAboutURL(GURL* url,
                               content::BrowserContext* browser_context) {
  // TODO(msw): Eliminate "about:*" constants and literals from code and tests,
  //            then hopefully we can remove this forced fixup.
  *url = URLFixerUpper::FixupURL(url->possibly_invalid_spec(), std::string());

  // Check that about: URLs are fixed up to chrome: by URLFixerUpper::FixupURL.
  DCHECK((*url == GURL(chrome::kAboutBlankURL)) ||
         !url->SchemeIs(chrome::kAboutScheme));

  // Only handle chrome://foo/, URLFixerUpper::FixupURL translates about:foo.
  if (!url->SchemeIs(chrome::kChromeUIScheme))
    return false;

  std::string host(url->host());
  std::string path;
  // Replace about with chrome-urls.
  if (host == chrome::kChromeUIAboutHost)
    host = chrome::kChromeUIChromeURLsHost;
  // Replace cache with view-http-cache.
  if (host == chrome::kChromeUICacheHost) {
    host = chrome::kChromeUINetworkViewCacheHost;
  // Replace gpu with gpu-internals.
  } else if (host == chrome::kChromeUIGpuHost) {
    host = chrome::kChromeUIGpuInternalsHost;
  // Replace sync with sync-internals (for legacy reasons).
  } else if (host == chrome::kChromeUISyncHost) {
    host = chrome::kChromeUISyncInternalsHost;
  // Redirect chrome://extensions.
  } else if (host == chrome::kChromeUIExtensionsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost + url->path();
  // Redirect chrome://settings/extensions.
  // TODO(csilv): Remove this URL after M22 (legacy URL).
  } else if (host == chrome::kChromeUISettingsHost &&
      url->path() == std::string("/") + chrome::kExtensionsSubPage) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIExtensionsHost;
  // Redirect chrome://history.
  } else if (host == chrome::kChromeUIHistoryHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUIHistoryHost + url->path();
  // Redirect chrome://settings
  } else if (host == chrome::kChromeUISettingsHost) {
    host = chrome::kChromeUIUberHost;
    path = chrome::kChromeUISettingsHost + url->path();
  }
  GURL::Replacements replacements;
  replacements.SetHostStr(host);
  if (!path.empty())
    replacements.SetPathStr(path);
  *url = url->ReplaceComponents(replacements);

  // Having re-written the URL, make the chrome: handler process it.
  return false;
}

bool HandleNonNavigationAboutURL(const GURL& url) {
  std::string host(url.host());

  // chrome://ipc/ is currently buggy, so we disable it for official builds.
#if !defined(OFFICIAL_BUILD)

#if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED)
  if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) {
    // Run the dialog. This will re-use the existing one if it's already up.
    chrome::ShowAboutIPCDialog();
    return true;
  }
#endif

#endif  // OFFICIAL_BUILD

  return false;
}

std::vector<std::string> ChromePaths() {
  std::vector<std::string> paths;
  paths.reserve(arraysize(kChromePaths));
  for (size_t i = 0; i < arraysize(kChromePaths); i++)
    paths.push_back(kChromePaths[i]);
  return paths;
}
<|endoftext|>


<commit_before><commit_msg>If there is nothing to import, return.<commit_after><|endoftext|>


<commit_before><commit_msg>Marking test as flaky since it is failing in release >50% of the time now.<commit_after><|endoftext|>


<commit_before>
#include "ros/ros.h"
#include "geometry_msgs/PoseStamped"

#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <stdio.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <cstudio>
#include <ctime>

typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;

sensor_msgs::ImageConstPtr image;

struct my_pose {
    float x;
    float y;
} a, b, c, d;

/*
    a           b
        m
    c           d
*/

void callback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
    a.x = 59.9426460266;
    a.y = 5.25176143646;
    b.x = 60.0549316406;
    b.y = 9.36225509644;
    c.x = 61.6946525574;
    c.y = 5.01872062683;
    d.x = 61.9057197571;
    d.y = 9.26733779907;

    my_pose pose = msg->pose;

    am = (a.x - pose.Point.x) * (a.y - pose.Point.y);
    ab = (a.x - b.x) * (a.y - b.y);
    ad = (a.x - d.x) * (a.y - d.y);

    if (am*ab > 0 && am*ab < ab*ab && am*ad > 0 && am*ad < ad*ad)
    {
        std::time_t rawtime;
        std::tm* timeinfo;
        char buffer [80];

        std::time(&rawtime);
        timeinfo = std::localtime(&rawtime);
        std::strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
        std::puts(buffer);
        std::string str(buffer);

        ROS_INFO("People detected in frout of a white board, picture saved.");

        try
        {
            cv_bridge::CvImageConstPtr cv_ptr;
            cv::imwrite("/home/bwi/Desktop/write_board_" + str + ".jpg",
                        cv_ptr->image);
        }
        catch (cv_bridge::Exception& e)
        {
            ROS_ERROR("cv_bridge exception: %s", e.what());
            return;
        }
    }
}

// keep saving the most recent image
void callback_image_saver(const sensor_msgs::ImageConstPtr& msg)
{
  image = msg;
}

// main function of the node
int main(int argc, char ** argv)
{
    ros::init(argc, argv, "white_board");
    ros::NodeHandle nh;
    ros::Subscriber sub1 = nh.subscribe(
                    "/segbot_pcl_person_detector/human_poses", 100, callback);

    image_transport::ImageTransport it(nh);
    image_transport::Subscriber sub2 = it.subscribe(
                    "/nav_kinect/rgb/image_color", 1, callback_image_saver);

    ros::spin();

    return 0;
}

<commit_msg>fixed positioning problem<commit_after>
#include "ros/ros.h"
#include "geometry_msgs/PoseStamped.h"

#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <stdio.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <cstdio>
#include <ctime>

typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;

sensor_msgs::ImageConstPtr image;

struct my_pose {
    float x;
    float y;
} p1, p2;

/*
    a           b
       p1   p2
    c           d
*/

void callback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
    p1.x = 61.099;
    p1.y = 7.479;
    p2.x = 60.981;
    p2.y = 6.310;
    float range= 1.0;

    geometry_msgs::PoseStampedConstPtr poseStamped = msg;

    float x = poseStamped->pose.position.x;
    float y = poseStamped->pose.position.y;

    float dis_p1 = pow(pow(p1.x-x, 2.0) + pow(p1.y - y, 2.0), 0.5);
    float dis_p2 = pow(pow(p2.x-x, 2.0) + pow(p2.y - y, 2.0), 0.5);

    if (dis_p1 < 1.0 || dis_p2 < 1.0)
    {
        std::time_t rawtime;
        std::tm* timeinfo;
        char buffer [80];

        std::time(&rawtime);
        timeinfo = std::localtime(&rawtime);
        std::strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
        std::puts(buffer);
        std::string str(buffer);

        ROS_INFO("People detected in frout of a white board, picture saved.");

        cv_bridge::CvImageConstPtr cv_ptr;
        try
        {
            cv_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);
            cv::imwrite("/home/bwi/Desktop/write_board_" + str + ".jpg",
                        cv_ptr->image);
        }
        catch (cv_bridge::Exception& e)
        {
            ROS_ERROR("cv_bridge exception: %s", e.what());
            return;
        }
    }
}

// keep saving the most recent image
void callback_image_saver(const sensor_msgs::ImageConstPtr& msg)
{
  image = msg;
}

// main function of the node
int main(int argc, char ** argv)
{
    ros::init(argc, argv, "white_board");
    ros::NodeHandle nh;
    ros::Subscriber sub1 = nh.subscribe(
                    "/segbot_pcl_person_detector/human_poses", 100, callback);

    image_transport::ImageTransport it(nh);
    image_transport::Subscriber sub2 = it.subscribe(
                    "/nav_kinect/rgb/image_color", 1, callback_image_saver);

    ros::spin();

    return 0;
}

<|endoftext|>


<commit_before>#include "ScriptManager.hpp"

#include <angelscript.h>
#include <scriptbuilder/scriptbuilder.h>
#include <scriptstdstring/scriptstdstring.h>
#include "../Util/Log.hpp"
#include "../Util/FileSystem.hpp"
#include "../Hymn.hpp"
#include "../Scene/Scene.hpp"
#include "../Component/Script.hpp"
#include "../Entity/Entity.hpp"
#include "Managers.hpp"

void print(const std::string& message) {
    Log() << message;
}

Entity* GetEntity() {
    return Managers().scriptManager->currentEntity;
}

void RegisterUpdate() {
    Managers().scriptManager->RegisterUpdate(GetEntity());
}

ScriptManager::ScriptManager() {
    // Create the script engine
    engine = asCreateScriptEngine();

    // Set the message callback to receive information on errors in human readable form.
    engine->SetMessageCallback(asFUNCTION(AngelScriptMessageCallback), 0, asCALL_CDECL);

    // Register add-ons.
    RegisterStdString(engine);

    // Register GLM types.
    engine->RegisterObjectType("vec3", sizeof(glm::vec3), asOBJ_VALUE | asOBJ_POD);
    engine->RegisterObjectProperty("vec3", "float x", asOFFSET(glm::vec3, x));
    engine->RegisterObjectProperty("vec3", "float y", asOFFSET(glm::vec3, y));
    engine->RegisterObjectProperty("vec3", "float z", asOFFSET(glm::vec3, z));

    // Register Entity.
    engine->RegisterObjectType("Entity", 0, asOBJ_REF | asOBJ_NOCOUNT);
    engine->RegisterObjectProperty("Entity", "string name", asOFFSET(Entity, name));
    engine->RegisterObjectMethod("Entity", "void Kill()", asMETHOD(Entity, Kill), asCALL_THISCALL);
    engine->RegisterObjectMethod("Entity", "bool IsKilled()", asMETHOD(Entity, IsKilled), asCALL_THISCALL);

    // Register components.
    engine->SetDefaultNamespace("Component");
    engine->RegisterObjectType("Transform", 0, asOBJ_REF | asOBJ_NOCOUNT);
    engine->SetDefaultNamespace("");

    // Register functions.
    engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL);
    engine->RegisterGlobalFunction("Entity@ GetEntity()", asFUNCTION(GetEntity), asCALL_CDECL);
    engine->RegisterGlobalFunction("void RegisterUpdate()", asFUNCTION(::RegisterUpdate), asCALL_CDECL);
}

ScriptManager::~ScriptManager() {
    engine->ShutDownAndRelease();
}

void ScriptManager::BuildScript(const std::string& name) {
    std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + "Scripts" + FileSystem::DELIMITER + name + ".as";
    if (!FileSystem::FileExists(filename.c_str())) {
        Log() << "Script file does not exist: " << filename << "\n";
        return;
    }

    // Create and build script module.
    CScriptBuilder builder;
    int r = builder.StartNewModule(engine, name.c_str());
    if (r < 0)
        Log() << "Couldn't start new module: " << name << ".\n";

    r = builder.AddSectionFromFile(filename.c_str());
    if (r < 0)
        Log() << "File section could not be added: " << filename << ".\n";

    r = builder.BuildModule();
    if (r < 0)
        Log() << "Compile errors.\n";
}

void ScriptManager::Update(Scene& scene) {
    // Init.
    for (Component::Script* script : scene.GetComponents<Component::Script>()) {
        if (!script->initialized) {
            CallScript(script->entity, "void Init()");
            script->initialized = true;
        }
    }

    // Update.
    for (Entity* entity : updateEntities)
        CallScript(entity, "void Update()");
}

void ScriptManager::RegisterUpdate(Entity* entity) {
    updateEntities.push_back(entity);
}

void ScriptManager::CallScript(Entity* entity, const std::string& functionName) {
    currentEntity = entity;

    // Get script module.
    asIScriptModule* module = engine->GetModule(entity->name.c_str(), asGM_ONLY_IF_EXISTS);

    // Find function to call.
    asIScriptFunction* function = module->GetFunctionByDecl(functionName.c_str());
    if (function == nullptr)
        Log() << "Couldn't find \"" + functionName + "\" function.\n";

    // Create context, prepare it and execute.
    asIScriptContext* context = engine->CreateContext();
    context->Prepare(function);
    int r = context->Execute();
    if (r != asEXECUTION_FINISHED) {
        // The execution didn't complete as expected. Determine what happened.
        if (r == asEXECUTION_EXCEPTION) {
          // An exception occurred, let the script writer know what happened so it can be corrected.
          Log() << "An exception '" << context->GetExceptionString() << "' occurred. Please correct the code and try again.\n";
        }
    }

    // Clean up.
    context->Release();
}
<commit_msg>Register Entity::GetTransform<commit_after>#include "ScriptManager.hpp"

#include <angelscript.h>
#include <scriptbuilder/scriptbuilder.h>
#include <scriptstdstring/scriptstdstring.h>
#include "../Util/Log.hpp"
#include "../Util/FileSystem.hpp"
#include "../Hymn.hpp"
#include "../Scene/Scene.hpp"
#include "../Component/Script.hpp"
#include "../Component/Transform.hpp"
#include "../Entity/Entity.hpp"
#include "Managers.hpp"

void print(const std::string& message) {
    Log() << message;
}

Entity* GetEntity() {
    return Managers().scriptManager->currentEntity;
}

void RegisterUpdate() {
    Managers().scriptManager->RegisterUpdate(GetEntity());
}

ScriptManager::ScriptManager() {
    // Create the script engine
    engine = asCreateScriptEngine();

    // Set the message callback to receive information on errors in human readable form.
    engine->SetMessageCallback(asFUNCTION(AngelScriptMessageCallback), 0, asCALL_CDECL);

    // Register add-ons.
    RegisterStdString(engine);

    // Register GLM types.
    engine->RegisterObjectType("vec3", sizeof(glm::vec3), asOBJ_VALUE | asOBJ_POD);
    engine->RegisterObjectProperty("vec3", "float x", asOFFSET(glm::vec3, x));
    engine->RegisterObjectProperty("vec3", "float y", asOFFSET(glm::vec3, y));
    engine->RegisterObjectProperty("vec3", "float z", asOFFSET(glm::vec3, z));

    // Register Entity.
    engine->RegisterObjectType("Entity", 0, asOBJ_REF | asOBJ_NOCOUNT);
    engine->RegisterObjectProperty("Entity", "string name", asOFFSET(Entity, name));
    engine->RegisterObjectMethod("Entity", "void Kill()", asMETHOD(Entity, Kill), asCALL_THISCALL);
    engine->RegisterObjectMethod("Entity", "bool IsKilled() const", asMETHOD(Entity, IsKilled), asCALL_THISCALL);

    // Register components.
    engine->SetDefaultNamespace("Component");
    engine->RegisterObjectType("Transform", 0, asOBJ_REF | asOBJ_NOCOUNT);
    engine->SetDefaultNamespace("");

    // Register GetComponent.
    engine->RegisterObjectMethod("Entity", "Component::Transform@ GetTransform()", asMETHODPR(Entity, GetComponent<Component::Transform>, (), Component::Transform*), asCALL_THISCALL);

    // Register functions.
    engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL);
    engine->RegisterGlobalFunction("Entity@ GetEntity()", asFUNCTION(GetEntity), asCALL_CDECL);
    engine->RegisterGlobalFunction("void RegisterUpdate()", asFUNCTION(::RegisterUpdate), asCALL_CDECL);
}

ScriptManager::~ScriptManager() {
    engine->ShutDownAndRelease();
}

void ScriptManager::BuildScript(const std::string& name) {
    std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + "Scripts" + FileSystem::DELIMITER + name + ".as";
    if (!FileSystem::FileExists(filename.c_str())) {
        Log() << "Script file does not exist: " << filename << "\n";
        return;
    }

    // Create and build script module.
    CScriptBuilder builder;
    int r = builder.StartNewModule(engine, name.c_str());
    if (r < 0)
        Log() << "Couldn't start new module: " << name << ".\n";

    r = builder.AddSectionFromFile(filename.c_str());
    if (r < 0)
        Log() << "File section could not be added: " << filename << ".\n";

    r = builder.BuildModule();
    if (r < 0)
        Log() << "Compile errors.\n";
}

void ScriptManager::Update(Scene& scene) {
    // Init.
    for (Component::Script* script : scene.GetComponents<Component::Script>()) {
        if (!script->initialized) {
            CallScript(script->entity, "void Init()");
            script->initialized = true;
        }
    }

    // Update.
    for (Entity* entity : updateEntities)
        CallScript(entity, "void Update()");
}

void ScriptManager::RegisterUpdate(Entity* entity) {
    updateEntities.push_back(entity);
}

void ScriptManager::CallScript(Entity* entity, const std::string& functionName) {
    currentEntity = entity;

    // Get script module.
    asIScriptModule* module = engine->GetModule(entity->name.c_str(), asGM_ONLY_IF_EXISTS);

    // Find function to call.
    asIScriptFunction* function = module->GetFunctionByDecl(functionName.c_str());
    if (function == nullptr)
        Log() << "Couldn't find \"" + functionName + "\" function.\n";

    // Create context, prepare it and execute.
    asIScriptContext* context = engine->CreateContext();
    context->Prepare(function);
    int r = context->Execute();
    if (r != asEXECUTION_FINISHED) {
        // The execution didn't complete as expected. Determine what happened.
        if (r == asEXECUTION_EXCEPTION) {
          // An exception occurred, let the script writer know what happened so it can be corrected.
          Log() << "An exception '" << context->GetExceptionString() << "' occurred. Please correct the code and try again.\n";
        }
    }

    // Clean up.
    context->Release();
}
<|endoftext|>


<commit_before><commit_msg>fix invalid template argument in MDSimulator<commit_after><|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>

#include <iostream>

#include "Snake.h"
#include "Game.h"
#include "Fruit.h"
#include "SnakeNode.h"

using namespace sfSnake;

Snake::Snake() : direction_(Direction::Up)
{
	initNodes();
}

void Snake::initNodes()
{
	for (int i = 0; i < Snake::InitialSize; ++i)
	{
		nodes_.push_back(SnakeNode(sf::Vector2f(
			Game::Width / 2 - SnakeNode::Width / 2,
			Game::Height / 2 - (SnakeNode::Height / 2) + (SnakeNode::Height * i))));
	}
}

void Snake::handleInput()
{
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		direction_ = Direction::Up;
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		direction_ = Direction::Down;
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
		direction_ = Direction::Left;
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
		direction_ = Direction::Right;
}

void Snake::update(sf::Time delta)
{
	move();
	checkEdgeCollisions();
	checkSelfCollisions();
}

void Snake::checkFruitCollisions(std::vector<Fruit>& fruits)
{
	decltype(fruits.begin()) toRemove = fruits.end();

	for (auto& it = fruits.begin(); it != fruits.end(); ++it)
	{
		if (it->getBounds().intersects(nodes_[0].getBounds()))
			toRemove = it;
	}

	if (toRemove != fruits.end())
	{
		grow();
		fruits.erase(toRemove);
	}
}

void Snake::grow()
{
	switch (direction_)
	{
	case Direction::Up:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x,
			nodes_[nodes_.size() - 1].getPosition().y + SnakeNode::Height)));
		break;
	case Direction::Down:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x,
			nodes_[nodes_.size() - 1].getPosition().y - SnakeNode::Height)));
		break;
	case Direction::Left:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x + SnakeNode::Width,
			nodes_[nodes_.size() - 1].getPosition().y)));
		break;
	case Direction::Right:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x - SnakeNode::Width,
			nodes_[nodes_.size() - 1].getPosition().y)));
		break;
	}
}

void Snake::checkSelfCollisions()
{
	SnakeNode& headNode = nodes_[0];

	for (decltype(nodes_.size()) i = 1; i < nodes_.size(); ++i)
	{
		if (headNode.getBounds().intersects(nodes_[i].getBounds()))
			std::cout << "Collision with self!" << std::endl;
	}
}

void Snake::checkEdgeCollisions()
{
	SnakeNode& headNode = nodes_[0];

	if (headNode.getPosition().x <= 0)
		headNode.setPosition(Game::Width, headNode.getPosition().y);
	else if (headNode.getPosition().x >= Game::Width)
		headNode.setPosition(0, headNode.getPosition().y);
	else if (headNode.getPosition().y <= 0)
		headNode.setPosition(headNode.getPosition().x, Game::Height);
	else if (headNode.getPosition().y >= Game::Height)
		headNode.setPosition(headNode.getPosition().x, 0);
}

void Snake::move()
{
	for (decltype(nodes_.size()) i = nodes_.size() - 1; i > 0; --i)
	{
		nodes_[i].setPosition(nodes_.at(i - 1).getPosition());
	}

	switch (direction_)
	{
	case Direction::Up:
		nodes_[0].move(0, -SnakeNode::Height);
		break;
	case Direction::Down:
		nodes_[0].move(0, SnakeNode::Height);
		break;
	case Direction::Left:
		nodes_[0].move(-SnakeNode::Width, 0);
		break;
	case Direction::Right:
		nodes_[0].move(SnakeNode::Width, 0);
		break;
	}
}

void Snake::render(sf::RenderWindow& window)
{
	std::cout << nodes_.size() << std::endl;
	for (auto node : nodes_)
		node.render(window);
}<commit_msg>Removed debug print code<commit_after>#include <SFML/Graphics.hpp>

#include <iostream>

#include "Snake.h"
#include "Game.h"
#include "Fruit.h"
#include "SnakeNode.h"

using namespace sfSnake;

Snake::Snake() : direction_(Direction::Up)
{
	initNodes();
}

void Snake::initNodes()
{
	for (int i = 0; i < Snake::InitialSize; ++i)
	{
		nodes_.push_back(SnakeNode(sf::Vector2f(
			Game::Width / 2 - SnakeNode::Width / 2,
			Game::Height / 2 - (SnakeNode::Height / 2) + (SnakeNode::Height * i))));
	}
}

void Snake::handleInput()
{
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		direction_ = Direction::Up;
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		direction_ = Direction::Down;
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
		direction_ = Direction::Left;
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
		direction_ = Direction::Right;
}

void Snake::update(sf::Time delta)
{
	move();
	checkEdgeCollisions();
	checkSelfCollisions();
}

void Snake::checkFruitCollisions(std::vector<Fruit>& fruits)
{
	decltype(fruits.begin()) toRemove = fruits.end();

	for (auto& it = fruits.begin(); it != fruits.end(); ++it)
	{
		if (it->getBounds().intersects(nodes_[0].getBounds()))
			toRemove = it;
	}

	if (toRemove != fruits.end())
	{
		grow();
		fruits.erase(toRemove);
	}
}

void Snake::grow()
{
	switch (direction_)
	{
	case Direction::Up:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x,
			nodes_[nodes_.size() - 1].getPosition().y + SnakeNode::Height)));
		break;
	case Direction::Down:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x,
			nodes_[nodes_.size() - 1].getPosition().y - SnakeNode::Height)));
		break;
	case Direction::Left:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x + SnakeNode::Width,
			nodes_[nodes_.size() - 1].getPosition().y)));
		break;
	case Direction::Right:
		nodes_.push_back(SnakeNode(sf::Vector2f(nodes_[nodes_.size() - 1].getPosition().x - SnakeNode::Width,
			nodes_[nodes_.size() - 1].getPosition().y)));
		break;
	}
}

void Snake::checkSelfCollisions()
{
	SnakeNode& headNode = nodes_[0];

	for (decltype(nodes_.size()) i = 1; i < nodes_.size(); ++i)
	{
		if (headNode.getBounds().intersects(nodes_[i].getBounds()))
			std::cout << "Collision with self!" << std::endl;
	}
}

void Snake::checkEdgeCollisions()
{
	SnakeNode& headNode = nodes_[0];

	if (headNode.getPosition().x <= 0)
		headNode.setPosition(Game::Width, headNode.getPosition().y);
	else if (headNode.getPosition().x >= Game::Width)
		headNode.setPosition(0, headNode.getPosition().y);
	else if (headNode.getPosition().y <= 0)
		headNode.setPosition(headNode.getPosition().x, Game::Height);
	else if (headNode.getPosition().y >= Game::Height)
		headNode.setPosition(headNode.getPosition().x, 0);
}

void Snake::move()
{
	for (decltype(nodes_.size()) i = nodes_.size() - 1; i > 0; --i)
	{
		nodes_[i].setPosition(nodes_.at(i - 1).getPosition());
	}

	switch (direction_)
	{
	case Direction::Up:
		nodes_[0].move(0, -SnakeNode::Height);
		break;
	case Direction::Down:
		nodes_[0].move(0, SnakeNode::Height);
		break;
	case Direction::Left:
		nodes_[0].move(-SnakeNode::Width, 0);
		break;
	case Direction::Right:
		nodes_[0].move(SnakeNode::Width, 0);
		break;
	}
}

void Snake::render(sf::RenderWindow& window)
{
	for (auto node : nodes_)
		node.render(window);
}<|endoftext|>


<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station

(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

This file is part of the QGROUNDCONTROL project

    QGROUNDCONTROL is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    QGROUNDCONTROL is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Implementation of class MainWindow
 *   @author Your Name here
 */

#include "ArduPilotMegaMAV.h"

#ifdef QGC_USE_ARDUPILOTMEGA_MESSAGES
#ifndef MAVLINK_MSG_ID_MOUNT_CONFIGURE
#include "ardupilotmega/mavlink_msg_mount_configure.h"
#endif

#ifndef MAVLINK_MSG_ID_MOUNT_CONTROL
#include "ardupilotmega/mavlink_msg_mount_control.h"
#endif
#endif

ArduPilotMegaMAV::ArduPilotMegaMAV(MAVLinkProtocol* mavlink, int id) :
    UAS(mavlink, id)//,
    // place other initializers here
{
    //This does not seem to work. Manually request each stream type at a specified rate.
    // Ask for all streams at 4 Hz
    //enableAllDataTransmission(4);
    txReqTimer = new QTimer(this);
    connect(txReqTimer,SIGNAL(timeout()),this,SLOT(sendTxRequests()));

    QTimer::singleShot(5000,this,SLOT(sendTxRequests())); //Send an initial TX request in 5 seconds.

    txReqTimer->start(300000); //Resend the TX requests every 5 minutes.
}
void ArduPilotMegaMAV::sendTxRequests()
{
    enableExtendedSystemStatusTransmission(2);
    QGC::SLEEP::msleep(250);
    enablePositionTransmission(3);
    QGC::SLEEP::msleep(250);
    enableExtra1Transmission(10);
    QGC::SLEEP::msleep(250);
    enableExtra2Transmission(10);
    QGC::SLEEP::msleep(250);
    enableExtra3Transmission(2);
    QGC::SLEEP::msleep(250);
    enableRawSensorDataTransmission(2);
    QGC::SLEEP::msleep(250);
    enableRCChannelDataTransmission(2);
}

/**
 * This function is called by MAVLink once a complete, uncorrupted (CRC check valid)
 * mavlink packet is received.
 *
 * @param link Hardware link the message came from (e.g. /dev/ttyUSB0 or UDP port).
 *             messages can be sent back to the system via this link
 * @param message MAVLink message, as received from the MAVLink protocol stack
 */
void ArduPilotMegaMAV::receiveMessage(LinkInterface* link, mavlink_message_t message)
{
    // Let UAS handle the default message set
    UAS::receiveMessage(link, message);

    if (message.sysid == uasId) {
        // Handle your special messages
        switch (message.msgid) {
        case MAVLINK_MSG_ID_HEARTBEAT:
        {
            //qDebug() << "ARDUPILOT RECEIVED HEARTBEAT";
            break;
        }
        default:
            //qDebug() << "\nARDUPILOT RECEIVED MESSAGE WITH ID" << message.msgid;
            break;
        }
    }
}
void ArduPilotMegaMAV::setMountConfigure(unsigned char mode, bool stabilize_roll,bool stabilize_pitch,bool stabilize_yaw)
{
#ifdef QGC_USE_ARDUPILOTMEGA_MESSAGES
    //Only supported by APM
    mavlink_message_t msg;
    mavlink_msg_mount_configure_pack(255,1,&msg,this->uasId,1,mode,stabilize_roll,stabilize_pitch,stabilize_yaw);
    sendMessage(msg);
#endif
}
void ArduPilotMegaMAV::setMountControl(double pa,double pb,double pc,bool islatlong)
{
#ifdef QGC_USE_ARDUPILOTMEGA_MESSAGES
    mavlink_message_t msg;
    if (islatlong)
    {
        mavlink_msg_mount_control_pack(255,1,&msg,this->uasId,1,pa*10000000.0,pb*10000000.0,pc*10000000.0,0);
    }
    else
    {
        mavlink_msg_mount_control_pack(255,1,&msg,this->uasId,1,pa,pb,pc,0);
    }
    sendMessage(msg);
#endif
}
<commit_msg>Fix unused variables errors in Pixhawk build<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station

(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

This file is part of the QGROUNDCONTROL project

    QGROUNDCONTROL is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    QGROUNDCONTROL is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Implementation of class MainWindow
 *   @author Your Name here
 */

#include "ArduPilotMegaMAV.h"

#ifdef QGC_USE_ARDUPILOTMEGA_MESSAGES
#ifndef MAVLINK_MSG_ID_MOUNT_CONFIGURE
#include "ardupilotmega/mavlink_msg_mount_configure.h"
#endif

#ifndef MAVLINK_MSG_ID_MOUNT_CONTROL
#include "ardupilotmega/mavlink_msg_mount_control.h"
#endif
#endif

ArduPilotMegaMAV::ArduPilotMegaMAV(MAVLinkProtocol* mavlink, int id) :
    UAS(mavlink, id)//,
    // place other initializers here
{
    //This does not seem to work. Manually request each stream type at a specified rate.
    // Ask for all streams at 4 Hz
    //enableAllDataTransmission(4);
    txReqTimer = new QTimer(this);
    connect(txReqTimer,SIGNAL(timeout()),this,SLOT(sendTxRequests()));

    QTimer::singleShot(5000,this,SLOT(sendTxRequests())); //Send an initial TX request in 5 seconds.

    txReqTimer->start(300000); //Resend the TX requests every 5 minutes.
}
void ArduPilotMegaMAV::sendTxRequests()
{
    enableExtendedSystemStatusTransmission(2);
    QGC::SLEEP::msleep(250);
    enablePositionTransmission(3);
    QGC::SLEEP::msleep(250);
    enableExtra1Transmission(10);
    QGC::SLEEP::msleep(250);
    enableExtra2Transmission(10);
    QGC::SLEEP::msleep(250);
    enableExtra3Transmission(2);
    QGC::SLEEP::msleep(250);
    enableRawSensorDataTransmission(2);
    QGC::SLEEP::msleep(250);
    enableRCChannelDataTransmission(2);
}

/**
 * This function is called by MAVLink once a complete, uncorrupted (CRC check valid)
 * mavlink packet is received.
 *
 * @param link Hardware link the message came from (e.g. /dev/ttyUSB0 or UDP port).
 *             messages can be sent back to the system via this link
 * @param message MAVLink message, as received from the MAVLink protocol stack
 */
void ArduPilotMegaMAV::receiveMessage(LinkInterface* link, mavlink_message_t message)
{
    // Let UAS handle the default message set
    UAS::receiveMessage(link, message);

    if (message.sysid == uasId) {
        // Handle your special messages
        switch (message.msgid) {
        case MAVLINK_MSG_ID_HEARTBEAT:
        {
            //qDebug() << "ARDUPILOT RECEIVED HEARTBEAT";
            break;
        }
        default:
            //qDebug() << "\nARDUPILOT RECEIVED MESSAGE WITH ID" << message.msgid;
            break;
        }
    }
}
void ArduPilotMegaMAV::setMountConfigure(unsigned char mode, bool stabilize_roll,bool stabilize_pitch,bool stabilize_yaw)
{
#ifdef QGC_USE_ARDUPILOTMEGA_MESSAGES
    //Only supported by APM
    mavlink_message_t msg;
    mavlink_msg_mount_configure_pack(255,1,&msg,this->uasId,1,mode,stabilize_roll,stabilize_pitch,stabilize_yaw);
    sendMessage(msg);
#else
    Q_UNUSED(mode);
    Q_UNUSED(stabilize_roll);
    Q_UNUSED(stabilize_pitch);
    Q_UNUSED(stabilize_yaw);
#endif
}
void ArduPilotMegaMAV::setMountControl(double pa,double pb,double pc,bool islatlong)
{
#ifdef QGC_USE_ARDUPILOTMEGA_MESSAGES
    mavlink_message_t msg;
    if (islatlong)
    {
        mavlink_msg_mount_control_pack(255,1,&msg,this->uasId,1,pa*10000000.0,pb*10000000.0,pc*10000000.0,0);
    }
    else
    {
        mavlink_msg_mount_control_pack(255,1,&msg,this->uasId,1,pa,pb,pc,0);
    }
    sendMessage(msg);
#else
    Q_UNUSED(pa);
    Q_UNUSED(pb);
    Q_UNUSED(pc);
    Q_UNUSED(islatlong);
#endif
}
<|endoftext|>


<commit_before>/*
* Copyright (c) 2003-2013 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// \file AboutDlg.cpp
//-----------------------------------------------------------------------------

#include "stdafx.h"

#include "AboutDlg.h"
// following 2 includes to allow querying
// the current version details
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "GeneralMsgBox.h"
#include "RichEditCtrlExtn.h"
#include "PWSversion.h"
#include "DumpSelect.h"
#include "DboxMain.h"

#include "core/UTF8Conv.h"
#include "core/SysInfo.h"

#include "resource.h"
#include "resource3.h"

// for fetching xml file:
#include <afxinet.h>

using pws_os::CUUID;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

CAboutDlg::CAboutDlg(CWnd* pParent)
  : CPWDialog(CAboutDlg::IDD, pParent),
  m_nMajor(0), m_nMinor(0), m_nBuild(0)
{
  CString verstat;
  // Following since text in quotes is not to be translated
  verstat.Format(IDS_LATEST_VERSION, L"[check_version]");
  m_newVerStatus = verstat;
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
  CPWDialog::DoDataExchange(pDX);
  DDX_Control(pDX, IDC_NEWVER_STATUS, m_RECExNewVerStatus);
  DDX_Control(pDX, IDC_VISIT_WEBSITE, m_RECExWebSite);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CPWDialog)
  ON_BN_CLICKED(IDC_TAKETESTDUMP, OnTakeTestdump)
END_MESSAGE_MAP()

BOOL CAboutDlg::OnInitDialog()
{
  CPWDialog::OnInitDialog();

  const PWSversion *pPWSver = PWSversion::GetInstance();
  m_nMajor = pPWSver->GetMajor();
  m_nMinor = pPWSver->GetMinor();
  m_nBuild = pPWSver->GetBuild();
  CString Revision = pPWSver->GetRevision();
  CString SpecialBuild = pPWSver->GetSpecialBuild();

  m_appversion = pPWSver->GetAppVersion();

  const CString cs2go = SysInfo::IsUnderPw2go() ? L"2go " : L" ";
  if (m_nBuild == 0) { // hide build # if zero (formal release)
    m_appversion.Format(L"%s%sV%d.%02d (%s)%s", AfxGetAppName(), cs2go,
                        m_nMajor, m_nMinor, Revision, SpecialBuild);
  } else {
    m_appversion.Format(L"%s%sV%d.%02d.%02d (%s)%s", AfxGetAppName(), cs2go,
                        m_nMajor, m_nMinor, m_nBuild, Revision, SpecialBuild);
  }

#ifdef _DEBUG
  m_appversion += L" [Debug]";
#endif

#ifdef DEMO
  m_appversion += L" " + CString(MAKEINTRESOURCE(IDS_DEMO));
#endif

  CString builtOnPrefix;
  GetDlgItem(IDC_APPBUILTON)->GetWindowText(builtOnPrefix);
  const CString builtOn =  builtOnPrefix + pPWSver->GetBuiltOn();

  GetDlgItem(IDC_APPVERSION)->SetWindowText(m_appversion);
  GetDlgItem(IDC_APPBUILTON)->SetWindowText(builtOn);
  GetDlgItem(IDC_APPCOPYRIGHT)->SetWindowText(app.GetCopyrightString());

  m_RECExNewVerStatus.SetWindowText(m_newVerStatus);
  m_RECExNewVerStatus.RegisterOnLink(OnCheckVersion, (LPARAM)this);

  m_RECExWebSite.SetWindowText(CString(MAKEINTRESOURCE(IDS_VISIT_WEBSITE)));

  if (app.PermitTestdump()) {
    GetDlgItem(IDC_TAKETESTDUMP)->ShowWindow(SW_SHOW);
    GetDlgItem(IDC_TAKETESTDUMP)->EnableWindow();
  }

  return TRUE;
}

bool CAboutDlg::OnCheckVersion(const CString &URL, const CString & /* lpszFName */, LPARAM instance)
{
  if (URL == L"[check_version]") {
    CAboutDlg *self = (CAboutDlg *)instance;
    self->CheckNewVer();
    return true;
  } else
    return false;
}

void CAboutDlg::CheckNewVer()
{
  // Get the latest.xml file from our site, compare to version,
  // and notify the user
  // First, make sure database is closed: Sensitive data with an
  // open socket makes me uneasy...
  DboxMain *pDbx = static_cast<DboxMain *>(GetParent());
  CGeneralMsgBox gmb;

  if (pDbx->GetNumEntries() != 0) {
    const CString cs_txt(MAKEINTRESOURCE(IDS_CLOSE_B4_CHECK));
    const CString cs_title(MAKEINTRESOURCE(IDS_CONFIRM_CLOSE));
    INT_PTR rc = gmb.MessageBox(cs_txt, cs_title,
                        (MB_OKCANCEL | MB_ICONQUESTION));
    if (rc == IDCANCEL)
      return; // no hard feelings
    // Close database, prompt for save if changed
    pDbx->SendMessage(WM_COMMAND, ID_MENUITEM_CLOSE);
    // User could have cancelled save, need to check if really closed:
    if (pDbx->GetNumEntries() != 0)
      return;
  }
  pDbx->UpdateWindow(); // show user that we closed database
  ASSERT(pDbx->GetNumEntries() == 0);
  // safe to open external connection
  m_newVerStatus.LoadString(IDS_TRYING2CONTACT_SERVER);
  UpdateData(FALSE);
  std::wstring latest;
  wchar_t *html_redfont = L"";
  wchar_t *html_greenfont = L"";
  wchar_t *html_endfont = L"";
  switch (CheckLatestVersion(latest)) {
    case CheckVersion::CANT_CONNECT:
      m_newVerStatus.Format(IDS_CANT_CONTACT_SERVER, html_redfont, html_endfont);
      break;
    case CheckVersion::UP2DATE:
      m_newVerStatus.Format(IDS_UP2DATE, html_greenfont, html_endfont);
      break;
    case CheckVersion::NEWER_AVAILABLE:
      {
      CString newer;
      newer.Format(SysInfo::IsUnderU3() ? IDS_NEWER_AVAILABLE_U3 : IDS_NEWER_AVAILABLE,
                   m_appversion, latest.c_str());
      m_newVerStatus.Format(IDS_NEWER_AVAILABLE_SHORT, html_redfont, html_endfont);
      gmb.MessageBox(newer, CString(MAKEINTRESOURCE(IDS_NEWER_CAPTION)), MB_ICONEXCLAMATION);
      break;
      }
    case CheckVersion::CANT_READ:
      m_newVerStatus.Format(IDS_CANT_READ_VERINFO, html_redfont, html_endfont);
      break;
    default:
      break;
  }

  m_RECExNewVerStatus.SetFont(GetFont());
  m_RECExNewVerStatus.SetWindowText(m_newVerStatus);
  m_RECExNewVerStatus.Invalidate();
  UpdateData(FALSE);
  GetDlgItem(IDOK)->SetFocus();
}

CheckVersion::CheckStatus CAboutDlg::CheckLatestVersion(std::wstring &latest)
{
  CInternetSession session(L"PasswordSafe Version Check");
  CStdioFile *fh;

  // Put up hourglass...this might take a while
  CWaitCursor waitCursor;

  try {
    // Loading the file as binary since we're treating it as UTF-8
    fh = session.OpenURL(L"http://pwsafe.org/latest.xml",
                         1, (INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD));
  } catch (CInternetException *) {
    // throw;
    return CheckVersion::CANT_CONNECT;
  }

  ASSERT(fh != NULL);
  CString latest_xml;
  unsigned char buff[BUFSIZ + 1];
  StringX chunk;
  UINT nRead;
  CUTF8Conv conv;

  while ((nRead = fh->Read(buff, BUFSIZ)) != 0) {
    buff[nRead] = '\0';
    // change to widechar representation
    if (!conv.FromUTF8(buff, nRead, chunk)) {
      fh->Close();
      delete fh;
      session.Close();
      return CheckVersion::CANT_READ;
    } else
      latest_xml += chunk.c_str();
  }

  fh->Close();
  delete fh;

  session.Close();
  waitCursor.Restore(); // restore normal cursor

  CheckVersion vh(m_nMajor, m_nMinor, m_nBuild);
  return vh.CheckLatestVersion(LPCWSTR(latest_xml), latest);
}

// Take a test dump
void CAboutDlg::OnTakeTestdump()
{
  CDumpSelect dmpslct;
  dmpslct.DoModal();
}

<commit_msg>Version string now looks better when special build string set<commit_after>/*
* Copyright (c) 2003-2013 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// \file AboutDlg.cpp
//-----------------------------------------------------------------------------

#include "stdafx.h"

#include "AboutDlg.h"
// following 2 includes to allow querying
// the current version details
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "GeneralMsgBox.h"
#include "RichEditCtrlExtn.h"
#include "PWSversion.h"
#include "DumpSelect.h"
#include "DboxMain.h"

#include "core/UTF8Conv.h"
#include "core/SysInfo.h"

#include "resource.h"
#include "resource3.h"

// for fetching xml file:
#include <afxinet.h>

using pws_os::CUUID;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

CAboutDlg::CAboutDlg(CWnd* pParent)
  : CPWDialog(CAboutDlg::IDD, pParent),
  m_nMajor(0), m_nMinor(0), m_nBuild(0)
{
  CString verstat;
  // Following since text in quotes is not to be translated
  verstat.Format(IDS_LATEST_VERSION, L"[check_version]");
  m_newVerStatus = verstat;
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
  CPWDialog::DoDataExchange(pDX);
  DDX_Control(pDX, IDC_NEWVER_STATUS, m_RECExNewVerStatus);
  DDX_Control(pDX, IDC_VISIT_WEBSITE, m_RECExWebSite);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CPWDialog)
  ON_BN_CLICKED(IDC_TAKETESTDUMP, OnTakeTestdump)
END_MESSAGE_MAP()

BOOL CAboutDlg::OnInitDialog()
{
  CPWDialog::OnInitDialog();

  const PWSversion *pPWSver = PWSversion::GetInstance();
  m_nMajor = pPWSver->GetMajor();
  m_nMinor = pPWSver->GetMinor();
  m_nBuild = pPWSver->GetBuild();
  CString Revision = pPWSver->GetRevision();
  CString SpecialBuild = pPWSver->GetSpecialBuild();

  m_appversion = pPWSver->GetAppVersion();

  const CString cs2go = SysInfo::IsUnderPw2go() ? L"2go " : L" ";
  if (m_nBuild == 0) { // hide build # if zero (formal release)
    m_appversion.Format(L"%s%sV%d.%02d%s (%s)", AfxGetAppName(), cs2go,
                        m_nMajor, m_nMinor, SpecialBuild, Revision);
  } else {
    m_appversion.Format(L"%s%sV%d.%02d.%02d%s (%s)", AfxGetAppName(), cs2go,
                        m_nMajor, m_nMinor, m_nBuild, SpecialBuild, Revision);
  }

#ifdef _DEBUG
  m_appversion += L" [Debug]";
#endif

#ifdef DEMO
  m_appversion += L" " + CString(MAKEINTRESOURCE(IDS_DEMO));
#endif

  CString builtOnPrefix;
  GetDlgItem(IDC_APPBUILTON)->GetWindowText(builtOnPrefix);
  const CString builtOn =  builtOnPrefix + pPWSver->GetBuiltOn();

  GetDlgItem(IDC_APPVERSION)->SetWindowText(m_appversion);
  GetDlgItem(IDC_APPBUILTON)->SetWindowText(builtOn);
  GetDlgItem(IDC_APPCOPYRIGHT)->SetWindowText(app.GetCopyrightString());

  m_RECExNewVerStatus.SetWindowText(m_newVerStatus);
  m_RECExNewVerStatus.RegisterOnLink(OnCheckVersion, (LPARAM)this);

  m_RECExWebSite.SetWindowText(CString(MAKEINTRESOURCE(IDS_VISIT_WEBSITE)));

  if (app.PermitTestdump()) {
    GetDlgItem(IDC_TAKETESTDUMP)->ShowWindow(SW_SHOW);
    GetDlgItem(IDC_TAKETESTDUMP)->EnableWindow();
  }

  return TRUE;
}

bool CAboutDlg::OnCheckVersion(const CString &URL, const CString & /* lpszFName */, LPARAM instance)
{
  if (URL == L"[check_version]") {
    CAboutDlg *self = (CAboutDlg *)instance;
    self->CheckNewVer();
    return true;
  } else
    return false;
}

void CAboutDlg::CheckNewVer()
{
  // Get the latest.xml file from our site, compare to version,
  // and notify the user
  // First, make sure database is closed: Sensitive data with an
  // open socket makes me uneasy...
  DboxMain *pDbx = static_cast<DboxMain *>(GetParent());
  CGeneralMsgBox gmb;

  if (pDbx->GetNumEntries() != 0) {
    const CString cs_txt(MAKEINTRESOURCE(IDS_CLOSE_B4_CHECK));
    const CString cs_title(MAKEINTRESOURCE(IDS_CONFIRM_CLOSE));
    INT_PTR rc = gmb.MessageBox(cs_txt, cs_title,
                        (MB_OKCANCEL | MB_ICONQUESTION));
    if (rc == IDCANCEL)
      return; // no hard feelings
    // Close database, prompt for save if changed
    pDbx->SendMessage(WM_COMMAND, ID_MENUITEM_CLOSE);
    // User could have cancelled save, need to check if really closed:
    if (pDbx->GetNumEntries() != 0)
      return;
  }
  pDbx->UpdateWindow(); // show user that we closed database
  ASSERT(pDbx->GetNumEntries() == 0);
  // safe to open external connection
  m_newVerStatus.LoadString(IDS_TRYING2CONTACT_SERVER);
  UpdateData(FALSE);
  std::wstring latest;
  wchar_t *html_redfont = L"";
  wchar_t *html_greenfont = L"";
  wchar_t *html_endfont = L"";
  switch (CheckLatestVersion(latest)) {
    case CheckVersion::CANT_CONNECT:
      m_newVerStatus.Format(IDS_CANT_CONTACT_SERVER, html_redfont, html_endfont);
      break;
    case CheckVersion::UP2DATE:
      m_newVerStatus.Format(IDS_UP2DATE, html_greenfont, html_endfont);
      break;
    case CheckVersion::NEWER_AVAILABLE:
      {
      CString newer;
      newer.Format(SysInfo::IsUnderU3() ? IDS_NEWER_AVAILABLE_U3 : IDS_NEWER_AVAILABLE,
                   m_appversion, latest.c_str());
      m_newVerStatus.Format(IDS_NEWER_AVAILABLE_SHORT, html_redfont, html_endfont);
      gmb.MessageBox(newer, CString(MAKEINTRESOURCE(IDS_NEWER_CAPTION)), MB_ICONEXCLAMATION);
      break;
      }
    case CheckVersion::CANT_READ:
      m_newVerStatus.Format(IDS_CANT_READ_VERINFO, html_redfont, html_endfont);
      break;
    default:
      break;
  }

  m_RECExNewVerStatus.SetFont(GetFont());
  m_RECExNewVerStatus.SetWindowText(m_newVerStatus);
  m_RECExNewVerStatus.Invalidate();
  UpdateData(FALSE);
  GetDlgItem(IDOK)->SetFocus();
}

CheckVersion::CheckStatus CAboutDlg::CheckLatestVersion(std::wstring &latest)
{
  CInternetSession session(L"PasswordSafe Version Check");
  CStdioFile *fh;

  // Put up hourglass...this might take a while
  CWaitCursor waitCursor;

  try {
    // Loading the file as binary since we're treating it as UTF-8
    fh = session.OpenURL(L"http://pwsafe.org/latest.xml",
                         1, (INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD));
  } catch (CInternetException *) {
    // throw;
    return CheckVersion::CANT_CONNECT;
  }

  ASSERT(fh != NULL);
  CString latest_xml;
  unsigned char buff[BUFSIZ + 1];
  StringX chunk;
  UINT nRead;
  CUTF8Conv conv;

  while ((nRead = fh->Read(buff, BUFSIZ)) != 0) {
    buff[nRead] = '\0';
    // change to widechar representation
    if (!conv.FromUTF8(buff, nRead, chunk)) {
      fh->Close();
      delete fh;
      session.Close();
      return CheckVersion::CANT_READ;
    } else
      latest_xml += chunk.c_str();
  }

  fh->Close();
  delete fh;

  session.Close();
  waitCursor.Restore(); // restore normal cursor

  CheckVersion vh(m_nMajor, m_nMinor, m_nBuild);
  return vh.CheckLatestVersion(LPCWSTR(latest_xml), latest);
}

// Take a test dump
void CAboutDlg::OnTakeTestdump()
{
  CDumpSelect dmpslct;
  dmpslct.DoModal();
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/mdia/mdiamba.C $                                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,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 mdiamba.C
 * @brief mdia mba specific functions
 */

#include "mdiafwd.H"
#include "mdiaglobals.H"
#include "mdiasm.H"
#include "mdiatrace.H"
#include "targeting/common/utilFilter.H"

using namespace TARGETING;

namespace MDIA
{

errlHndl_t getDiagnosticMode(
        const Globals & i_globals,
        TargetHandle_t i_trgt,
        DiagMode & o_mode)
{
    o_mode = ONE_PATTERN;

    do
    {

        if(MNFG_FLAG_ENABLE_EXHAUSTIVE_PATTERN_TEST
           & i_globals.mfgPolicy)
        {
            o_mode = NINE_PATTERNS;
        }

        else if(MNFG_FLAG_ENABLE_STANDARD_PATTERN_TEST
                & i_globals.mfgPolicy)
        {
            o_mode = FOUR_PATTERNS;
        }

        else if(MNFG_FLAG_ENABLE_MINIMUM_PATTERN_TEST
                & i_globals.mfgPolicy)
        {
            o_mode = ONE_PATTERN;
        }

        else if(i_globals.simicsRunning)
        {
            o_mode = ONE_PATTERN;
        }

        // Only need to check hw changed state attributes
        // when not already set to exhaustive and not in simics
        if(( NINE_PATTERNS != o_mode ) &&
           ( ! i_globals.simicsRunning ))
        {
            if(isHWStateChanged(i_trgt))
            {
                o_mode = NINE_PATTERNS;
            }
        }

    } while(0);

    MDIA_FAST("getDiagnosticMode: trgt: %x, o_mode: 0x%x, "
              "simics: %d",
              get_huid(i_trgt), o_mode, i_globals.simicsRunning);

    return 0;
}

errlHndl_t getWorkFlow(
                DiagMode i_mode,
                WorkFlow & o_wf,
                const Globals & i_globals)
{
    // add the correct sequences for the mba based
    // on the mode

    // every mba does restore dram repairs

    o_wf.push_back(RESTORE_DRAM_REPAIRS);

    switch (i_mode)
    {
        case NINE_PATTERNS:

            o_wf.push_back(START_PATTERN_7);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_6);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_5);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_4);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_3);
            o_wf.push_back(START_SCRUB);

            // fall through

        case FOUR_PATTERNS:

            o_wf.push_back(START_RANDOM_PATTERN);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_2);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_1);
            o_wf.push_back(START_SCRUB);

            // fall through

        case ONE_PATTERN:

            o_wf.push_back(START_PATTERN_0); // 0's pattern, must be last
            o_wf.push_back(START_SCRUB);

            break;

        default:
            break;
    }

    if(MNFG_FLAG_IPL_MEMORY_CE_CHECKING
            & i_globals.mfgPolicy)
    {
        o_wf.push_back(ANALYZE_IPL_MNFG_CE_STATS);
    }

    o_wf.push_back(CLEAR_HW_CHANGED_STATE);

    return 0;
}

/*
 *  Local helper function to return a list of Centaur
 *  DIMMs, and MCS associated with the input MBA target
 *
 *  If i_queryOnly = true (Query)
 *    - Return a list of DIMMs, Centaur, and
 *      MCS connected to this MBA
 *
 *  Else (Clear)
 *   - Return a list of DIMMs and
 *     (Centaur + MCS) if all the DIMMs behind this
 *     Centaur have hwchangedState flags cleared
 *     or about to be cleared by this MBA
 */
TargetHandleList getMemTargetsForQueryOrClear(
                    TargetHandle_t i_trgt, bool i_queryOnly)
{
    #define FUNC "getMemTargetsForQueryOrClear: "
    TargetHandleList o_list;

    do
    {
        // add associated DIMMs
        TargetHandleList dimmList;
        getChildAffinityTargets(dimmList,
                                i_trgt,
                                CLASS_NA,
                                TYPE_DIMM);

        if( ! dimmList.empty() )
        {
            o_list.insert(o_list.begin(), dimmList.begin(), dimmList.end());
        }

        TYPE trgtType = i_trgt->getAttr<ATTR_TYPE>();

        // mcbist target
        if ( TYPE_MCBIST == trgtType )
        {
            // add associated MCBIST
            o_list.push_back( i_trgt );

            // add associated MCAs
            TargetHandleList mcaList;
            getChildAffinityTargets(mcaList, i_trgt, CLASS_UNIT, TYPE_MCA);

            if ( !mcaList.empty() )
            {
                o_list.insert( o_list.end(), mcaList.begin(), mcaList.end() );
            }

        }
        // MBA target
        else
        {
            // add associated Centaur
            TargetHandleList targetList;
            getParentAffinityTargets(targetList,
                    i_trgt,
                    CLASS_CHIP,
                    TYPE_MEMBUF);

            if( targetList.empty() )
            {
                MDIA_FAST(FUNC "no connected centaur "
                        "for mba: %x", get_huid(i_trgt));
                break;
            }

            TargetHandle_t centaur = targetList[0];

            // if query flag is not set, check to make sure
            // all of the dimms connected to this centaur
            // have cleared hw chagned state attributes
            // before adding this centaur/mcs to the list.
            // This is needed because we only clear
            // the centaur/mcs attribute when all of the
            // dimms' attributes from both mbas have cleared.
            if(false == i_queryOnly)
            {
                targetList.clear();
                getChildAffinityTargets(targetList,
                        centaur,
                        CLASS_NA,
                        TYPE_DIMM);

                if( ! targetList.empty() )
                {
                    TargetHandleList::iterator target;

                    for(target = targetList.begin();
                            target != targetList.end(); ++target)
                    {
                        // exclude dimms belong to the current mba
                        // because their attributes will be cleared
                        if(dimmList.end() !=
                                std::find(dimmList.begin(),
                                    dimmList.end(), *target))
                        {
                            continue;
                        }

                        ATTR_HWAS_STATE_CHANGED_FLAG_type hwChangeFlag;
                        hwChangeFlag =
                            (*target)->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>();

                        if(HWAS_CHANGED_BIT_MEMDIAG & hwChangeFlag)
                        {
                            MDIA_FAST(FUNC "hwChangedState is not cleared "
                                    "for dimm: %x", get_huid(*target));
                            centaur = NULL; // don't add centaur and mcs and mba
                            break;
                        }
                    }
                }
            }

            if(NULL == centaur)
            {
                break;
            }

            o_list.push_back(centaur);

            // get connected mcs target
            targetList.clear();

            getParentAffinityTargets(targetList,
                                     centaur,
                                     CLASS_UNIT,
                                     TYPE_MCS);

            if( !targetList.empty() )
            {
                o_list.push_back(targetList[0]);
            }

            // add associated MBAs
            targetList.clear();

            getChildAffinityTargets(targetList, i_trgt, CLASS_UNIT, TYPE_MBA);

            if ( !targetList.empty() )
            {
                o_list.insert( o_list.end(), targetList.begin(),
                               targetList.end() );
            }

        }

    } while(0);

    MDIA_DBG(FUNC "i_trgt HUID: %x, size: %d",
             get_huid(i_trgt), o_list.size());

    return o_list;

    #undef FUNC
}

bool isHWStateChanged(TargetHandle_t i_trgt)
{
    bool hwChanged = false;
    ATTR_HWAS_STATE_CHANGED_FLAG_type hwChangeFlag;

    // Get a list of associated targets for attribute query
    TargetHandleList targetList =
        getMemTargetsForQueryOrClear(i_trgt, true);

    for(TargetHandleList::iterator target = targetList.begin();
        target != targetList.end(); ++target )
    {
        hwChangeFlag =
            (*target)->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>();

        if(HWAS_CHANGED_BIT_MEMDIAG & hwChangeFlag)
        {
            MDIA_DBG("isHWStateChanged: set for target: %x",
                     get_huid(*target));
            hwChanged = true;
            break;
        }
    }

    return hwChanged;
}

void clearHWStateChanged(TargetHandle_t i_trgt)
{
    TargetHandleList targetList;

    // Get a list of associated targets for attribute clearing
    targetList = getMemTargetsForQueryOrClear(i_trgt, false);

    for(TargetHandleList::iterator target = targetList.begin();
        target != targetList.end(); ++target)
    {
        MDIA_DBG("clearHWStateChanged: mba: %x, target: %x",
                 get_huid(i_trgt), get_huid(*target));

        clear_hwas_changed_bit( *target,
                                HWAS_CHANGED_BIT_MEMDIAG);
    }
}

}
<commit_msg>MDIA: DD1 1-rank DIMM workaround<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/mdia/mdiamba.C $                                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,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 mdiamba.C
 * @brief mdia mba specific functions
 */

#include "mdiafwd.H"
#include "mdiaglobals.H"
#include "mdiasm.H"
#include "mdiatrace.H"
#include "targeting/common/utilFilter.H"

using namespace TARGETING;

namespace MDIA
{

bool __nimbusDD1Workaround( TargetHandle_t i_trgt )
{
    // In Nimbus DD1.x, 1-rank DIMMs must use a slow read as opposed to a super
    // fast read, as such, this causes mdia to run too slowly to complete nine
    // patterns before the istep times out. In this case, we will just do four
    // patterns instead. This function will return true if we need to apply the
    // Nimbus DD1 1-rank DIMM workaround or false if we don't.

    bool slowRead = false;

    ConstTargetHandle_t parent = getParentChip( i_trgt );

    // The workaround only applies to Nimbus
    if ( MODEL_NIMBUS == parent->getAttr<ATTR_MODEL>() )
    {
        // check if DD1.x
        if ( 0x20 > parent->getAttr<ATTR_EC>() )
        {
            // check if there is a 1-rank DIMM
            TargetHandleList mcsList;
            getChildAffinityTargets( mcsList, i_trgt, CLASS_UNIT, TYPE_MCS );

            for ( auto &mcs : mcsList )
            {
                ATTR_EFF_NUM_RANKS_PER_DIMM_type attr;
                if ( !mcs->tryGetAttr<ATTR_EFF_NUM_RANKS_PER_DIMM>(attr) )
                {
                    MDIA_FAST( "tryGetAttr<ATTR_EFF_NUM_RANKS_PER_DIMM> failed:"
                               " i_trgt=0x%08x", get_huid(i_trgt) );
                    break;
                }
                for ( uint8_t pos = 0; pos < mss::PORTS_PER_MCS; pos++ )
                {
                    for ( uint8_t ds = 0; ds < mss::MAX_DIMM_PER_PORT; ds++ )
                    {
                        // If there is a DIMM with only 1 rank we must apply the
                        // workaround.
                        if ( 1 == attr[pos][ds] )
                        {
                            slowRead = true;
                            break;
                        }
                    }
                    if ( slowRead ) break;
                }
                if ( slowRead ) break;
            }
        }
    }

    return slowRead;
}

errlHndl_t getDiagnosticMode(
        const Globals & i_globals,
        TargetHandle_t i_trgt,
        DiagMode & o_mode)
{
    o_mode = ONE_PATTERN;

    do
    {

        if(MNFG_FLAG_ENABLE_EXHAUSTIVE_PATTERN_TEST
           & i_globals.mfgPolicy)
        {
            o_mode = NINE_PATTERNS;
        }

        else if(MNFG_FLAG_ENABLE_STANDARD_PATTERN_TEST
                & i_globals.mfgPolicy)
        {
            o_mode = FOUR_PATTERNS;
        }

        else if(MNFG_FLAG_ENABLE_MINIMUM_PATTERN_TEST
                & i_globals.mfgPolicy)
        {
            o_mode = ONE_PATTERN;
        }

        else if(i_globals.simicsRunning)
        {
            o_mode = ONE_PATTERN;
        }

        // Only need to check hw changed state attributes
        // when not already set to exhaustive and not in simics
        if(( NINE_PATTERNS != o_mode ) &&
           ( ! i_globals.simicsRunning ))
        {
            if(isHWStateChanged(i_trgt))
            {
                o_mode = NINE_PATTERNS;
            }
        }

        // Check to see if we must apply the Nimbus DD1 1-rank DIMM workaround
        if ( (NINE_PATTERNS == o_mode) && __nimbusDD1Workaround(i_trgt) )
        {
            o_mode = FOUR_PATTERNS;
        }

    } while(0);

    MDIA_FAST("getDiagnosticMode: trgt: %x, o_mode: 0x%x, "
              "simics: %d",
              get_huid(i_trgt), o_mode, i_globals.simicsRunning);

    return 0;
}

errlHndl_t getWorkFlow(
                DiagMode i_mode,
                WorkFlow & o_wf,
                const Globals & i_globals)
{
    // add the correct sequences for the mba based
    // on the mode

    // every mba does restore dram repairs

    o_wf.push_back(RESTORE_DRAM_REPAIRS);

    switch (i_mode)
    {
        case NINE_PATTERNS:

            o_wf.push_back(START_PATTERN_7);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_6);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_5);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_4);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_3);
            o_wf.push_back(START_SCRUB);

            // fall through

        case FOUR_PATTERNS:

            o_wf.push_back(START_RANDOM_PATTERN);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_2);
            o_wf.push_back(START_SCRUB);
            o_wf.push_back(START_PATTERN_1);
            o_wf.push_back(START_SCRUB);

            // fall through

        case ONE_PATTERN:

            o_wf.push_back(START_PATTERN_0); // 0's pattern, must be last
            o_wf.push_back(START_SCRUB);

            break;

        default:
            break;
    }

    if(MNFG_FLAG_IPL_MEMORY_CE_CHECKING
            & i_globals.mfgPolicy)
    {
        o_wf.push_back(ANALYZE_IPL_MNFG_CE_STATS);
    }

    o_wf.push_back(CLEAR_HW_CHANGED_STATE);

    return 0;
}

/*
 *  Local helper function to return a list of Centaur
 *  DIMMs, and MCS associated with the input MBA target
 *
 *  If i_queryOnly = true (Query)
 *    - Return a list of DIMMs, Centaur, and
 *      MCS connected to this MBA
 *
 *  Else (Clear)
 *   - Return a list of DIMMs and
 *     (Centaur + MCS) if all the DIMMs behind this
 *     Centaur have hwchangedState flags cleared
 *     or about to be cleared by this MBA
 */
TargetHandleList getMemTargetsForQueryOrClear(
                    TargetHandle_t i_trgt, bool i_queryOnly)
{
    #define FUNC "getMemTargetsForQueryOrClear: "
    TargetHandleList o_list;

    do
    {
        // add associated DIMMs
        TargetHandleList dimmList;
        getChildAffinityTargets(dimmList,
                                i_trgt,
                                CLASS_NA,
                                TYPE_DIMM);

        if( ! dimmList.empty() )
        {
            o_list.insert(o_list.begin(), dimmList.begin(), dimmList.end());
        }

        TYPE trgtType = i_trgt->getAttr<ATTR_TYPE>();

        // mcbist target
        if ( TYPE_MCBIST == trgtType )
        {
            // add associated MCBIST
            o_list.push_back( i_trgt );

            // add associated MCAs
            TargetHandleList mcaList;
            getChildAffinityTargets(mcaList, i_trgt, CLASS_UNIT, TYPE_MCA);

            if ( !mcaList.empty() )
            {
                o_list.insert( o_list.end(), mcaList.begin(), mcaList.end() );
            }

        }
        // MBA target
        else
        {
            // add associated Centaur
            TargetHandleList targetList;
            getParentAffinityTargets(targetList,
                    i_trgt,
                    CLASS_CHIP,
                    TYPE_MEMBUF);

            if( targetList.empty() )
            {
                MDIA_FAST(FUNC "no connected centaur "
                        "for mba: %x", get_huid(i_trgt));
                break;
            }

            TargetHandle_t centaur = targetList[0];

            // if query flag is not set, check to make sure
            // all of the dimms connected to this centaur
            // have cleared hw chagned state attributes
            // before adding this centaur/mcs to the list.
            // This is needed because we only clear
            // the centaur/mcs attribute when all of the
            // dimms' attributes from both mbas have cleared.
            if(false == i_queryOnly)
            {
                targetList.clear();
                getChildAffinityTargets(targetList,
                        centaur,
                        CLASS_NA,
                        TYPE_DIMM);

                if( ! targetList.empty() )
                {
                    TargetHandleList::iterator target;

                    for(target = targetList.begin();
                            target != targetList.end(); ++target)
                    {
                        // exclude dimms belong to the current mba
                        // because their attributes will be cleared
                        if(dimmList.end() !=
                                std::find(dimmList.begin(),
                                    dimmList.end(), *target))
                        {
                            continue;
                        }

                        ATTR_HWAS_STATE_CHANGED_FLAG_type hwChangeFlag;
                        hwChangeFlag =
                            (*target)->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>();

                        if(HWAS_CHANGED_BIT_MEMDIAG & hwChangeFlag)
                        {
                            MDIA_FAST(FUNC "hwChangedState is not cleared "
                                    "for dimm: %x", get_huid(*target));
                            centaur = NULL; // don't add centaur and mcs and mba
                            break;
                        }
                    }
                }
            }

            if(NULL == centaur)
            {
                break;
            }

            o_list.push_back(centaur);

            // get connected mcs target
            targetList.clear();

            getParentAffinityTargets(targetList,
                                     centaur,
                                     CLASS_UNIT,
                                     TYPE_MCS);

            if( !targetList.empty() )
            {
                o_list.push_back(targetList[0]);
            }

            // add associated MBAs
            targetList.clear();

            getChildAffinityTargets(targetList, i_trgt, CLASS_UNIT, TYPE_MBA);

            if ( !targetList.empty() )
            {
                o_list.insert( o_list.end(), targetList.begin(),
                               targetList.end() );
            }

        }

    } while(0);

    MDIA_DBG(FUNC "i_trgt HUID: %x, size: %d",
             get_huid(i_trgt), o_list.size());

    return o_list;

    #undef FUNC
}

bool isHWStateChanged(TargetHandle_t i_trgt)
{
    bool hwChanged = false;
    ATTR_HWAS_STATE_CHANGED_FLAG_type hwChangeFlag;

    // Get a list of associated targets for attribute query
    TargetHandleList targetList =
        getMemTargetsForQueryOrClear(i_trgt, true);

    for(TargetHandleList::iterator target = targetList.begin();
        target != targetList.end(); ++target )
    {
        hwChangeFlag =
            (*target)->getAttr<ATTR_HWAS_STATE_CHANGED_FLAG>();

        if(HWAS_CHANGED_BIT_MEMDIAG & hwChangeFlag)
        {
            MDIA_DBG("isHWStateChanged: set for target: %x",
                     get_huid(*target));
            hwChanged = true;
            break;
        }
    }

    return hwChanged;
}

void clearHWStateChanged(TargetHandle_t i_trgt)
{
    TargetHandleList targetList;

    // Get a list of associated targets for attribute clearing
    targetList = getMemTargetsForQueryOrClear(i_trgt, false);

    for(TargetHandleList::iterator target = targetList.begin();
        target != targetList.end(); ++target)
    {
        MDIA_DBG("clearHWStateChanged: mba: %x, target: %x",
                 get_huid(i_trgt), get_huid(*target));

        clear_hwas_changed_bit( *target,
                                HWAS_CHANGED_BIT_MEMDIAG);
    }
}

}
<|endoftext|>


<commit_before>#include "naor-pinkas.h"

void NaorPinkas::Receiver(uint32_t nSndVals, uint32_t nOTs, CBitVector& choices,
		CSocket* socket, uint8_t* ret) {

	fe* PK0 = m_cPKCrypto->get_fe();
	fe** PK_sigma = (fe**) malloc(sizeof(fe*) * nOTs);
	fe** pDec = (fe**) malloc(sizeof(fe*) * nOTs);
	fe** pC = (fe**) malloc(sizeof(fe*) * nSndVals);
	fe* g = m_cPKCrypto->get_generator();

	num** pK = (num**) malloc(sizeof(num*) * nOTs);

	uint8_t* retPtr;
	uint32_t u, k, choice, hash_bytes, fe_bytes;
	hash_bytes = m_cCrypto->get_hash_bytes();
	fe_bytes = m_cPKCrypto->fe_byte_size();

	brickexp *bg, *bc;
	bg = m_cPKCrypto->get_brick(g);	//BrickInit(&bg, g, m_fParams);

	uint8_t* pBuf = (uint8_t*) malloc(sizeof(uint8_t) * nOTs * fe_bytes);
	uint32_t nBufSize = nSndVals * fe_bytes;

	//calculate the generator of the group
	for (k = 0; k < nOTs; k++)
	{
		PK_sigma[k] = m_cPKCrypto->get_fe();//	FieldElementInit(PK_sigma[k]);
		pK[k] = m_cPKCrypto->get_rnd_num(); //FieldElementInit(pK[k]);

		//pK[k]->//GetRandomNumber(pK[k], m_fParams.secparam, m_fParams);/
		bg->pow(PK_sigma[k], pK[k]);//BrickPowerMod(&bg, PK_sigma[k], pK[k]);
	}

	socket->Receive(pBuf, nBufSize);
	uint8_t* pBufIdx = pBuf;

	for (u = 0; u < nSndVals; u++) {
		pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]);
		pC[u]->import_from_bytes(pBufIdx);//ByteToFieldElement(pC + u, m_fParams.elebytelen, pBufIdx);
		pBufIdx += fe_bytes;
	}

	bc = m_cPKCrypto->get_brick(pC[0]);//BrickInit(&bc, pC[0], m_fParams);

	//====================================================
	// N-P receiver: send pk0
	pBufIdx = pBuf;
	for (k = 0; k < nOTs; k++)
	{
		choice = choices.GetBit((int32_t) k);
		if (choice != 0) {
			PK0->set_div(pC[choice], PK_sigma[k]);//FieldElementDiv(PK0, pC[choice], PK_sigma[k], m_fParams);//PK0 = pC[choice];
		} else {
			PK0->set(PK_sigma[k]);//FieldElementSet(PK0, PK_sigma[k]);//PK0 = PK_sigma[k];
		}
		//cout << "PK0: " << PK0 << ", PK_sigma: " << PK_sigma[k] << ", choice: " << choice << ", pC[choice: " << pC[choice] << endl;
		PK0->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0);
		pBufIdx += fe_bytes;//m_fParams.elebytelen;
	}

	socket->Send(pBuf, nOTs * m_cPKCrypto->fe_byte_size());

	free(pBuf);
	pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes);//new uint8_t[m_fParams.elebytelen];
	retPtr = ret;

	for (k = 0; k < nOTs; k++) {
		pDec[k] = m_cPKCrypto->get_fe();//FieldElementInit(pDec[k]);
		bc->pow(pDec[k], pK[k]);//BrickPowerMod(&bc, pDec[k], pK[k]);
		pDec[k]->export_to_bytes(pBuf);//FieldElementToByte(pBuf, m_fParams.elebytelen, pDec[k]);

		hashReturn(retPtr, hash_bytes, pBuf, fe_bytes, k);
		retPtr += hash_bytes;//SHA1_BYTES;
	}

	delete bc;//BrickDelete(&bc);
	delete bg;//BrickDelete(&bg);

	delete [] pBuf;
	free(PK_sigma);
	free(pDec);
	free(pC);
	free(pK);
}

void NaorPinkas::Sender(uint32_t nSndVals, uint32_t nOTs, CSocket* socket, uint8_t* ret)
{
	num *alpha, *PKr, *tmp;
	fe **pCr, **pC, *fetmp, *PK0r, *g, **pPK0;
	uint8_t* pBuf, *pBufIdx;
	uint32_t hash_bytes, fe_bytes, nBufSize, u, k;

	hash_bytes = m_cCrypto->get_hash_bytes();
	fe_bytes = m_cPKCrypto->fe_byte_size();

	alpha = m_cPKCrypto->get_rnd_num();
	PKr = m_cPKCrypto->get_num();

	pCr = (fe**) malloc(sizeof(fe*) * nSndVals);
	pC = (fe**) malloc(sizeof(fe*) * nSndVals);

	fetmp = m_cPKCrypto->get_fe();
	PK0r = m_cPKCrypto->get_fe();
	pC[0] = m_cPKCrypto->get_fe();
	g = m_cPKCrypto->get_generator();

	//random C1
	pC[0]->set_pow(g, alpha);//FieldElementPow(pC[0], g, alpha, m_fParams);

	//random C(i+1)
	for (u = 1; u < nSndVals; u++) {
		pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]);
		tmp = m_cPKCrypto->get_rnd_num();
		pC[u]->set_pow(g, tmp);//FieldElementPow(pC[u], g, tmp, m_fParams);
	}

	//====================================================
	// Export the generated C_1-C_nSndVals to a uint8_t vector and send them to the receiver
	nBufSize = nSndVals * fe_bytes;
	pBuf = (uint8_t*) malloc(nBufSize);
	pBufIdx = pBuf;
	for (u = 0; u < nSndVals; u++) {
		pC[u]->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, pC[u]);
		pBufIdx += fe_bytes;//m_fParams.elebytelen;
	}
	socket->Send(pBuf, nBufSize);

	//====================================================
	// compute C^R
	for (u = 1; u < nSndVals; u++) {
		pCr[u] = m_cPKCrypto->get_fe();//FieldElementInit(pCr[u]);
		pCr[u]->set_pow(pC[u], alpha);//FieldElementPow(pCr[u], pC[u], alpha, m_fParams);
	}
	//====================================================

	free(pBuf);
	// N-P sender: receive pk0
	nBufSize = fe_bytes * nOTs;
	pBuf = (uint8_t*) malloc(nBufSize);
	socket->Receive(pBuf, nBufSize);

	pBufIdx = pBuf;

	pPK0 = (fe**) malloc(sizeof(fe*) * nOTs);
	for (k = 0; k < nOTs; k++) {
		pPK0[k] = m_cPKCrypto->get_fe();
		//FieldElementInit(pPK0[k]);
		pPK0[k]->import_from_bytes(pBufIdx);
		//ByteToFieldElement(pPK0 + k, m_fParams.elebytelen, pBufIdx);
		pBufIdx += fe_bytes;
	}

	//====================================================
	// Write all nOTs * nSndVals possible values to ret
	//free(pBuf); TODO fix and uncomment
	pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes * nSndVals);
	uint8_t* retPtr = ret;
	fetmp = m_cPKCrypto->get_fe();

	for (k = 0; k < nOTs; k++)
	{
		pBufIdx = pBuf;
		for (u = 0; u < nSndVals; u++) {

			if (u == 0) {
				// pk0^r
				PK0r->set_pow(pPK0[k], alpha);//FieldElementPow(PK0r, pPK0[k], alpha, m_fParams);
				PK0r->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0r);

			} else {
				// pk^r
				fetmp->set_div(pCr[u], PK0r);//FieldElementDiv(fetmp, pCr[u], PK0r, m_fParams);
				fetmp->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, fetmp);
			}
			hashReturn(retPtr, hash_bytes, pBufIdx, fe_bytes, k);
			pBufIdx += fe_bytes;
			retPtr += hash_bytes;
		}

	}

	free(pBuf);
	free(pCr);
	free(pC);
}
<commit_msg>fix malloc/free mismatch<commit_after>#include "naor-pinkas.h"

void NaorPinkas::Receiver(uint32_t nSndVals, uint32_t nOTs, CBitVector& choices,
		CSocket* socket, uint8_t* ret) {

	fe* PK0 = m_cPKCrypto->get_fe();
	fe** PK_sigma = (fe**) malloc(sizeof(fe*) * nOTs);
	fe** pDec = (fe**) malloc(sizeof(fe*) * nOTs);
	fe** pC = (fe**) malloc(sizeof(fe*) * nSndVals);
	fe* g = m_cPKCrypto->get_generator();

	num** pK = (num**) malloc(sizeof(num*) * nOTs);

	uint8_t* retPtr;
	uint32_t u, k, choice, hash_bytes, fe_bytes;
	hash_bytes = m_cCrypto->get_hash_bytes();
	fe_bytes = m_cPKCrypto->fe_byte_size();

	brickexp *bg, *bc;
	bg = m_cPKCrypto->get_brick(g);	//BrickInit(&bg, g, m_fParams);

	uint8_t* pBuf = (uint8_t*) malloc(sizeof(uint8_t) * nOTs * fe_bytes);
	uint32_t nBufSize = nSndVals * fe_bytes;

	//calculate the generator of the group
	for (k = 0; k < nOTs; k++)
	{
		PK_sigma[k] = m_cPKCrypto->get_fe();//	FieldElementInit(PK_sigma[k]);
		pK[k] = m_cPKCrypto->get_rnd_num(); //FieldElementInit(pK[k]);

		//pK[k]->//GetRandomNumber(pK[k], m_fParams.secparam, m_fParams);/
		bg->pow(PK_sigma[k], pK[k]);//BrickPowerMod(&bg, PK_sigma[k], pK[k]);
	}

	socket->Receive(pBuf, nBufSize);
	uint8_t* pBufIdx = pBuf;

	for (u = 0; u < nSndVals; u++) {
		pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]);
		pC[u]->import_from_bytes(pBufIdx);//ByteToFieldElement(pC + u, m_fParams.elebytelen, pBufIdx);
		pBufIdx += fe_bytes;
	}

	bc = m_cPKCrypto->get_brick(pC[0]);//BrickInit(&bc, pC[0], m_fParams);

	//====================================================
	// N-P receiver: send pk0
	pBufIdx = pBuf;
	for (k = 0; k < nOTs; k++)
	{
		choice = choices.GetBit((int32_t) k);
		if (choice != 0) {
			PK0->set_div(pC[choice], PK_sigma[k]);//FieldElementDiv(PK0, pC[choice], PK_sigma[k], m_fParams);//PK0 = pC[choice];
		} else {
			PK0->set(PK_sigma[k]);//FieldElementSet(PK0, PK_sigma[k]);//PK0 = PK_sigma[k];
		}
		//cout << "PK0: " << PK0 << ", PK_sigma: " << PK_sigma[k] << ", choice: " << choice << ", pC[choice: " << pC[choice] << endl;
		PK0->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0);
		pBufIdx += fe_bytes;//m_fParams.elebytelen;
	}

	socket->Send(pBuf, nOTs * m_cPKCrypto->fe_byte_size());

	free(pBuf);
	pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes);//new uint8_t[m_fParams.elebytelen];
	retPtr = ret;

	for (k = 0; k < nOTs; k++) {
		pDec[k] = m_cPKCrypto->get_fe();//FieldElementInit(pDec[k]);
		bc->pow(pDec[k], pK[k]);//BrickPowerMod(&bc, pDec[k], pK[k]);
		pDec[k]->export_to_bytes(pBuf);//FieldElementToByte(pBuf, m_fParams.elebytelen, pDec[k]);

		hashReturn(retPtr, hash_bytes, pBuf, fe_bytes, k);
		retPtr += hash_bytes;//SHA1_BYTES;
	}

	delete bc;//BrickDelete(&bc);
	delete bg;//BrickDelete(&bg);

	free(pBuf);
	free(PK_sigma);
	free(pDec);
	free(pC);
	free(pK);
}

void NaorPinkas::Sender(uint32_t nSndVals, uint32_t nOTs, CSocket* socket, uint8_t* ret)
{
	num *alpha, *PKr, *tmp;
	fe **pCr, **pC, *fetmp, *PK0r, *g, **pPK0;
	uint8_t* pBuf, *pBufIdx;
	uint32_t hash_bytes, fe_bytes, nBufSize, u, k;

	hash_bytes = m_cCrypto->get_hash_bytes();
	fe_bytes = m_cPKCrypto->fe_byte_size();

	alpha = m_cPKCrypto->get_rnd_num();
	PKr = m_cPKCrypto->get_num();

	pCr = (fe**) malloc(sizeof(fe*) * nSndVals);
	pC = (fe**) malloc(sizeof(fe*) * nSndVals);

	fetmp = m_cPKCrypto->get_fe();
	PK0r = m_cPKCrypto->get_fe();
	pC[0] = m_cPKCrypto->get_fe();
	g = m_cPKCrypto->get_generator();

	//random C1
	pC[0]->set_pow(g, alpha);//FieldElementPow(pC[0], g, alpha, m_fParams);

	//random C(i+1)
	for (u = 1; u < nSndVals; u++) {
		pC[u] = m_cPKCrypto->get_fe();//FieldElementInit(pC[u]);
		tmp = m_cPKCrypto->get_rnd_num();
		pC[u]->set_pow(g, tmp);//FieldElementPow(pC[u], g, tmp, m_fParams);
	}

	//====================================================
	// Export the generated C_1-C_nSndVals to a uint8_t vector and send them to the receiver
	nBufSize = nSndVals * fe_bytes;
	pBuf = (uint8_t*) malloc(nBufSize);
	pBufIdx = pBuf;
	for (u = 0; u < nSndVals; u++) {
		pC[u]->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, pC[u]);
		pBufIdx += fe_bytes;//m_fParams.elebytelen;
	}
	socket->Send(pBuf, nBufSize);

	//====================================================
	// compute C^R
	for (u = 1; u < nSndVals; u++) {
		pCr[u] = m_cPKCrypto->get_fe();//FieldElementInit(pCr[u]);
		pCr[u]->set_pow(pC[u], alpha);//FieldElementPow(pCr[u], pC[u], alpha, m_fParams);
	}
	//====================================================

	free(pBuf);
	// N-P sender: receive pk0
	nBufSize = fe_bytes * nOTs;
	pBuf = (uint8_t*) malloc(nBufSize);
	socket->Receive(pBuf, nBufSize);

	pBufIdx = pBuf;

	pPK0 = (fe**) malloc(sizeof(fe*) * nOTs);
	for (k = 0; k < nOTs; k++) {
		pPK0[k] = m_cPKCrypto->get_fe();
		//FieldElementInit(pPK0[k]);
		pPK0[k]->import_from_bytes(pBufIdx);
		//ByteToFieldElement(pPK0 + k, m_fParams.elebytelen, pBufIdx);
		pBufIdx += fe_bytes;
	}

	//====================================================
	// Write all nOTs * nSndVals possible values to ret
	//free(pBuf); TODO fix and uncomment
	pBuf = (uint8_t*) malloc(sizeof(uint8_t) * fe_bytes * nSndVals);
	uint8_t* retPtr = ret;
	fetmp = m_cPKCrypto->get_fe();

	for (k = 0; k < nOTs; k++)
	{
		pBufIdx = pBuf;
		for (u = 0; u < nSndVals; u++) {

			if (u == 0) {
				// pk0^r
				PK0r->set_pow(pPK0[k], alpha);//FieldElementPow(PK0r, pPK0[k], alpha, m_fParams);
				PK0r->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, PK0r);

			} else {
				// pk^r
				fetmp->set_div(pCr[u], PK0r);//FieldElementDiv(fetmp, pCr[u], PK0r, m_fParams);
				fetmp->export_to_bytes(pBufIdx);//FieldElementToByte(pBufIdx, m_fParams.elebytelen, fetmp);
			}
			hashReturn(retPtr, hash_bytes, pBufIdx, fe_bytes, k);
			pBufIdx += fe_bytes;
			retPtr += hash_bytes;
		}

	}

	free(pBuf);
	free(pCr);
	free(pC);
}
<|endoftext|>