<commit_before>// Copyright (c) 2010 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/gpu_blacklist.h"

#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/common/gpu_info.h"

GpuBlacklist::VersionInfo::VersionInfo(const std::string& version_op,
                                       const std::string& version_string,
                                       const std::string& version_string2) {
  op_ = StringToOp(version_op);
  if (op_ == kUnknown || op_ == kAny)
    return;
  version_.reset(Version::GetVersionFromString(version_string));
  if (version_.get() == NULL) {
    op_ = kUnknown;
    return;
  }
  if (op_ == kBetween) {
    version2_.reset(Version::GetVersionFromString(version_string2));
    if (version2_.get() == NULL)
      op_ = kUnknown;
  }
}

GpuBlacklist::VersionInfo::~VersionInfo() {
}

bool GpuBlacklist::VersionInfo::Contains(const Version& version) const {
  if (op_ == kUnknown)
    return false;
  if (op_ == kAny)
    return true;
  if (op_ == kEQ) {
    // Handles cases where 10.6 is considered as containing 10.6.*.
    const std::vector<uint16>& components_reference = version_->components();
    const std::vector<uint16>& components = version.components();
    for (size_t i = 0; i < components_reference.size(); ++i) {
      if (i >= components.size() && components_reference[i] != 0)
        return false;
      if (components[i] != components_reference[i])
        return false;
    }
    return true;
  }
  int relation = version.CompareTo(*version_);
  if (op_ == kEQ)
    return (relation == 0);
  else if (op_ == kLT)
    return (relation < 0);
  else if (op_ == kLE)
    return (relation <= 0);
  else if (op_ == kGT)
    return (relation > 0);
  else if (op_ == kGE)
    return (relation >= 0);
  // op_ == kBetween
  if (relation < 0)
    return false;
  return version.CompareTo(*version2_) <= 0;
}

bool GpuBlacklist::VersionInfo::IsValid() const {
  return op_ != kUnknown;
}

GpuBlacklist::VersionInfo::Op GpuBlacklist::VersionInfo::StringToOp(
    const std::string& version_op) {
  if (version_op == "=")
    return kEQ;
  else if (version_op == "<")
    return kLT;
  else if (version_op == "<=")
    return kLE;
  else if (version_op == ">")
    return kGT;
  else if (version_op == ">=")
    return kGE;
  else if (version_op == "any")
    return kAny;
  else if (version_op == "between")
    return kBetween;
  return kUnknown;
}

GpuBlacklist::OsInfo::OsInfo(const std::string& os,
                             const std::string& version_op,
                             const std::string& version_string,
                             const std::string& version_string2) {
  type_ = StringToOsType(os);
  if (type_ != kOsUnknown) {
    version_info_.reset(
        new VersionInfo(version_op, version_string, version_string2));
  }
}

bool GpuBlacklist::OsInfo::Contains(OsType type,
                                    const Version& version) const {
  if (!IsValid())
    return false;
  if (type_ != type && type_ != kOsAny)
    return false;
  return version_info_->Contains(version);
}

bool GpuBlacklist::OsInfo::IsValid() const {
  return type_ != kOsUnknown && version_info_->IsValid();
}

GpuBlacklist::OsType GpuBlacklist::OsInfo::type() const {
  return type_;
}

GpuBlacklist::OsType GpuBlacklist::OsInfo::StringToOsType(
    const std::string& os) {
  if (os == "win")
    return kOsWin;
  else if (os == "macosx")
    return kOsMacosx;
  else if (os == "linux")
    return kOsLinux;
  else if (os == "any")
    return kOsAny;
  return kOsUnknown;
}

GpuBlacklist::GpuBlacklistEntry*
GpuBlacklist::GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(
    DictionaryValue* value) {
  if (value == NULL)
    return NULL;

  GpuBlacklistEntry* entry = new GpuBlacklistEntry();

  DictionaryValue* os_value = NULL;
  if (value->GetDictionary("os", &os_value)) {
    std::string os_type;
    std::string os_version_op = "any";
    std::string os_version_string;
    std::string os_version_string2;
    os_value->GetString("type", &os_type);
    DictionaryValue* os_version_value = NULL;
    if (os_value->GetDictionary("version", &os_version_value)) {
      os_version_value->GetString("op", &os_version_op);
      os_version_value->GetString("number", &os_version_string);
      os_version_value->GetString("number2", &os_version_string2);
    }
    if (!entry->SetOsInfo(os_type, os_version_op, os_version_string,
                          os_version_string2)) {
      delete entry;
      return NULL;
    }
  }

  std::string vendor_id;
  if (value->GetString("vendor_id", &vendor_id)) {
    if (!entry->SetVendorId(vendor_id)) {
      delete entry;
      return NULL;
    }
  }

  std::string device_id;
  if (value->GetString("device_id", &device_id)) {
    if (!entry->SetDeviceId(device_id)) {
      delete entry;
      return NULL;
    }
  }

  DictionaryValue* driver_version_value = NULL;
  if (value->GetDictionary("driver_version", &driver_version_value)) {
    std::string driver_version_op = "any";
    std::string driver_version_string;
    std::string driver_version_string2;
    driver_version_value->GetString("op", &driver_version_op);
    driver_version_value->GetString("number", &driver_version_string);
    driver_version_value->GetString("number2", &driver_version_string2);
    if (!entry->SetDriverVersionInfo(driver_version_op, driver_version_string,
                                     driver_version_string2)) {
      delete entry;
      return NULL;
    }
  }

  ListValue* blacklist_value = NULL;
  if (!value->GetList("blacklist", &blacklist_value)) {
    delete entry;
    return NULL;
  }
  std::vector<std::string> blacklist;
  for (size_t i = 0; i < blacklist_value->GetSize(); ++i) {
    std::string feature;
    if (blacklist_value->GetString(i, &feature)) {
      blacklist.push_back(feature);
    } else {
      delete entry;
      return NULL;
    }
  }
  if (!entry->SetBlacklistedFeatures(blacklist)) {
    delete entry;
    return NULL;
  }

  return entry;
}

GpuBlacklist::GpuBlacklistEntry::GpuBlacklistEntry()
    : vendor_id_(0),
      device_id_(0) {
}

bool GpuBlacklist::GpuBlacklistEntry::SetOsInfo(
    const std::string& os,
    const std::string& version_op,
    const std::string& version_string,
    const std::string& version_string2) {
  os_info_.reset(new OsInfo(os, version_op, version_string, version_string2));
  return os_info_->IsValid();
}

bool GpuBlacklist::GpuBlacklistEntry::SetVendorId(
    const std::string& vendor_id_string) {
  vendor_id_ = 0;
  return base::HexStringToInt(vendor_id_string,
                              reinterpret_cast<int*>(&vendor_id_));
}

bool GpuBlacklist::GpuBlacklistEntry::SetDeviceId(
    const std::string& device_id_string) {
  device_id_ = 0;
  return base::HexStringToInt(device_id_string,
                              reinterpret_cast<int*>(&device_id_));
}

bool GpuBlacklist::GpuBlacklistEntry::SetDriverVersionInfo(
    const std::string& version_op,
    const std::string& version_string,
    const std::string& version_string2) {
  driver_version_info_.reset(
      new VersionInfo(version_op, version_string, version_string2));
  return driver_version_info_->IsValid();
}

bool GpuBlacklist::GpuBlacklistEntry::SetBlacklistedFeatures(
    const std::vector<std::string>& blacklisted_features) {
  size_t size = blacklisted_features.size();
  if (size == 0)
    return false;
  uint32 flags = 0;
  for (size_t i = 0; i < size; ++i) {
    GpuFeatureFlags::GpuFeatureType type =
        GpuFeatureFlags::StringToGpuFeatureType(blacklisted_features[i]);
    switch (type) {
      case GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas:
      case GpuFeatureFlags::kGpuFeatureAcceleratedCompositing:
      case GpuFeatureFlags::kGpuFeatureWebgl:
      case GpuFeatureFlags::kGpuFeatureAll:
        flags |= type;
        break;
      case GpuFeatureFlags::kGpuFeatureUnknown:
        return false;
    }
  }
  feature_flags_.reset(new GpuFeatureFlags());
  feature_flags_->set_flags(flags);
  return true;
}

bool GpuBlacklist::GpuBlacklistEntry::Contains(
    OsType os_type, const Version& os_version,
    uint32 vendor_id, uint32 device_id,
    const Version& driver_version) const {
  DCHECK(os_type != kOsAny);
  if (os_info_.get() != NULL && !os_info_->Contains(os_type, os_version))
    return false;
  if (vendor_id_ != 0 && vendor_id_ != vendor_id)
    return false;
  if (device_id_ != 0 && device_id_ != device_id)
    return false;
  if (driver_version_info_.get() == NULL)
    return true;
  return driver_version_info_->Contains(driver_version);
}

GpuBlacklist::OsType GpuBlacklist::GpuBlacklistEntry::GetOsType() const {
  if (os_info_.get() == NULL)
    return kOsUnknown;
  return os_info_->type();
}

GpuFeatureFlags GpuBlacklist::GpuBlacklistEntry::GetGpuFeatureFlags() const {
  return *feature_flags_;
}

GpuBlacklist::GpuBlacklist() {
}

GpuBlacklist::~GpuBlacklist() {
  Clear();
}

bool GpuBlacklist::LoadGpuBlacklist(const std::string& json_context,
                                    bool current_os_only) {
  std::vector<GpuBlacklistEntry*> entries;
  scoped_ptr<Value> root;
  root.reset(base::JSONReader::Read(json_context, false));
  if (root.get() == NULL || !root->IsType(Value::TYPE_DICTIONARY))
    return false;

  ListValue* list = NULL;
  static_cast<DictionaryValue*>(root.get())->GetList("entries", &list);
  if (list == NULL)
    return false;

  for (size_t i = 0; i < list->GetSize(); ++i) {
    DictionaryValue* list_item = NULL;
    bool valid = list->GetDictionary(i, &list_item);
    if (!valid)
      break;
    GpuBlacklistEntry* entry =
        GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(list_item);
    if (entry == NULL)
      break;
    entries.push_back(entry);
  }

  if (entries.size() < list->GetSize()) {
    for (size_t i = 0; i < entries.size(); ++i)
      delete entries[i];
    return false;
  }

  Clear();
  // Don't apply GPU blacklist for a non-registered OS.
  OsType os_filter = GetOsType();
  if (os_filter != kOsUnknown) {
    for (size_t i = 0; i < entries.size(); ++i) {
      OsType entry_os = entries[i]->GetOsType();
      if (!current_os_only ||
          entry_os == kOsAny || entry_os == os_filter)
        blacklist_.push_back(entries[i]);
    }
  }
  return true;
}

GpuFeatureFlags GpuBlacklist::DetermineGpuFeatureFlags(
    GpuBlacklist::OsType os,
    Version* os_version,
    const GPUInfo& gpu_info) const {
  GpuFeatureFlags flags;
  // No need to go through blacklist entries if GPUInfo isn't available.
  if (gpu_info.progress() == GPUInfo::kUninitialized)
    return flags;
  scoped_ptr<Version> driver_version(
      Version::GetVersionFromString(gpu_info.driver_version()));
  if (driver_version.get() == NULL)
    return flags;

  if (os == kOsAny)
    os = GetOsType();
  scoped_ptr<Version> my_os_version;
  if (os_version == NULL) {
    std::string version_string;
#if defined(OS_MACOSX)
    // Seems like base::SysInfo::OperatingSystemVersion() returns the wrong
    // version in MacOsx.
    int32 version_major, version_minor, version_bugfix;
    base::SysInfo::OperatingSystemVersionNumbers(
        &version_major, &version_minor, &version_bugfix);
    version_string = base::StringPrintf("%d.%d.%d",
                                        version_major,
                                        version_minor,
                                        version_bugfix);
#else
    version_string = base::SysInfo::OperatingSystemVersion();
#endif
    my_os_version.reset(Version::GetVersionFromString(version_string));
    os_version = my_os_version.get();
  }
  DCHECK(os_version != NULL);

  for (size_t i = 0; i < blacklist_.size(); ++i) {
    if (blacklist_[i]->Contains(os, *os_version,
                                gpu_info.vendor_id(), gpu_info.device_id(),
                                *driver_version)) {
      flags.Combine(blacklist_[i]->GetGpuFeatureFlags());
    }
  }
  return flags;
}

GpuBlacklist::OsType GpuBlacklist::GetOsType() {
#if defined(OS_WIN)
  return kOsWin;
#elif defined(OS_LINUX)
  return kOsLinux;
#elif defined(OS_MACOSX)
  return kOsMacosx;
#else
  return kOsUnknown;
#endif
}

void GpuBlacklist::Clear() {
  for (size_t i = 0; i < blacklist_.size(); ++i)
    delete blacklist_[i];
  blacklist_.clear();
}

<commit_msg>Fix memory leak in gpu_blacklist.cc.<commit_after>// Copyright (c) 2010 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/gpu_blacklist.h"

#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/common/gpu_info.h"

GpuBlacklist::VersionInfo::VersionInfo(const std::string& version_op,
                                       const std::string& version_string,
                                       const std::string& version_string2) {
  op_ = StringToOp(version_op);
  if (op_ == kUnknown || op_ == kAny)
    return;
  version_.reset(Version::GetVersionFromString(version_string));
  if (version_.get() == NULL) {
    op_ = kUnknown;
    return;
  }
  if (op_ == kBetween) {
    version2_.reset(Version::GetVersionFromString(version_string2));
    if (version2_.get() == NULL)
      op_ = kUnknown;
  }
}

GpuBlacklist::VersionInfo::~VersionInfo() {
}

bool GpuBlacklist::VersionInfo::Contains(const Version& version) const {
  if (op_ == kUnknown)
    return false;
  if (op_ == kAny)
    return true;
  if (op_ == kEQ) {
    // Handles cases where 10.6 is considered as containing 10.6.*.
    const std::vector<uint16>& components_reference = version_->components();
    const std::vector<uint16>& components = version.components();
    for (size_t i = 0; i < components_reference.size(); ++i) {
      if (i >= components.size() && components_reference[i] != 0)
        return false;
      if (components[i] != components_reference[i])
        return false;
    }
    return true;
  }
  int relation = version.CompareTo(*version_);
  if (op_ == kEQ)
    return (relation == 0);
  else if (op_ == kLT)
    return (relation < 0);
  else if (op_ == kLE)
    return (relation <= 0);
  else if (op_ == kGT)
    return (relation > 0);
  else if (op_ == kGE)
    return (relation >= 0);
  // op_ == kBetween
  if (relation < 0)
    return false;
  return version.CompareTo(*version2_) <= 0;
}

bool GpuBlacklist::VersionInfo::IsValid() const {
  return op_ != kUnknown;
}

GpuBlacklist::VersionInfo::Op GpuBlacklist::VersionInfo::StringToOp(
    const std::string& version_op) {
  if (version_op == "=")
    return kEQ;
  else if (version_op == "<")
    return kLT;
  else if (version_op == "<=")
    return kLE;
  else if (version_op == ">")
    return kGT;
  else if (version_op == ">=")
    return kGE;
  else if (version_op == "any")
    return kAny;
  else if (version_op == "between")
    return kBetween;
  return kUnknown;
}

GpuBlacklist::OsInfo::OsInfo(const std::string& os,
                             const std::string& version_op,
                             const std::string& version_string,
                             const std::string& version_string2) {
  type_ = StringToOsType(os);
  if (type_ != kOsUnknown) {
    version_info_.reset(
        new VersionInfo(version_op, version_string, version_string2));
  }
}

bool GpuBlacklist::OsInfo::Contains(OsType type,
                                    const Version& version) const {
  if (!IsValid())
    return false;
  if (type_ != type && type_ != kOsAny)
    return false;
  return version_info_->Contains(version);
}

bool GpuBlacklist::OsInfo::IsValid() const {
  return type_ != kOsUnknown && version_info_->IsValid();
}

GpuBlacklist::OsType GpuBlacklist::OsInfo::type() const {
  return type_;
}

GpuBlacklist::OsType GpuBlacklist::OsInfo::StringToOsType(
    const std::string& os) {
  if (os == "win")
    return kOsWin;
  else if (os == "macosx")
    return kOsMacosx;
  else if (os == "linux")
    return kOsLinux;
  else if (os == "any")
    return kOsAny;
  return kOsUnknown;
}

GpuBlacklist::GpuBlacklistEntry*
GpuBlacklist::GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(
    DictionaryValue* value) {
  if (value == NULL)
    return NULL;

  GpuBlacklistEntry* entry = new GpuBlacklistEntry();

  DictionaryValue* os_value = NULL;
  if (value->GetDictionary("os", &os_value)) {
    std::string os_type;
    std::string os_version_op = "any";
    std::string os_version_string;
    std::string os_version_string2;
    os_value->GetString("type", &os_type);
    DictionaryValue* os_version_value = NULL;
    if (os_value->GetDictionary("version", &os_version_value)) {
      os_version_value->GetString("op", &os_version_op);
      os_version_value->GetString("number", &os_version_string);
      os_version_value->GetString("number2", &os_version_string2);
    }
    if (!entry->SetOsInfo(os_type, os_version_op, os_version_string,
                          os_version_string2)) {
      delete entry;
      return NULL;
    }
  }

  std::string vendor_id;
  if (value->GetString("vendor_id", &vendor_id)) {
    if (!entry->SetVendorId(vendor_id)) {
      delete entry;
      return NULL;
    }
  }

  std::string device_id;
  if (value->GetString("device_id", &device_id)) {
    if (!entry->SetDeviceId(device_id)) {
      delete entry;
      return NULL;
    }
  }

  DictionaryValue* driver_version_value = NULL;
  if (value->GetDictionary("driver_version", &driver_version_value)) {
    std::string driver_version_op = "any";
    std::string driver_version_string;
    std::string driver_version_string2;
    driver_version_value->GetString("op", &driver_version_op);
    driver_version_value->GetString("number", &driver_version_string);
    driver_version_value->GetString("number2", &driver_version_string2);
    if (!entry->SetDriverVersionInfo(driver_version_op, driver_version_string,
                                     driver_version_string2)) {
      delete entry;
      return NULL;
    }
  }

  ListValue* blacklist_value = NULL;
  if (!value->GetList("blacklist", &blacklist_value)) {
    delete entry;
    return NULL;
  }
  std::vector<std::string> blacklist;
  for (size_t i = 0; i < blacklist_value->GetSize(); ++i) {
    std::string feature;
    if (blacklist_value->GetString(i, &feature)) {
      blacklist.push_back(feature);
    } else {
      delete entry;
      return NULL;
    }
  }
  if (!entry->SetBlacklistedFeatures(blacklist)) {
    delete entry;
    return NULL;
  }

  return entry;
}

GpuBlacklist::GpuBlacklistEntry::GpuBlacklistEntry()
    : vendor_id_(0),
      device_id_(0) {
}

bool GpuBlacklist::GpuBlacklistEntry::SetOsInfo(
    const std::string& os,
    const std::string& version_op,
    const std::string& version_string,
    const std::string& version_string2) {
  os_info_.reset(new OsInfo(os, version_op, version_string, version_string2));
  return os_info_->IsValid();
}

bool GpuBlacklist::GpuBlacklistEntry::SetVendorId(
    const std::string& vendor_id_string) {
  vendor_id_ = 0;
  return base::HexStringToInt(vendor_id_string,
                              reinterpret_cast<int*>(&vendor_id_));
}

bool GpuBlacklist::GpuBlacklistEntry::SetDeviceId(
    const std::string& device_id_string) {
  device_id_ = 0;
  return base::HexStringToInt(device_id_string,
                              reinterpret_cast<int*>(&device_id_));
}

bool GpuBlacklist::GpuBlacklistEntry::SetDriverVersionInfo(
    const std::string& version_op,
    const std::string& version_string,
    const std::string& version_string2) {
  driver_version_info_.reset(
      new VersionInfo(version_op, version_string, version_string2));
  return driver_version_info_->IsValid();
}

bool GpuBlacklist::GpuBlacklistEntry::SetBlacklistedFeatures(
    const std::vector<std::string>& blacklisted_features) {
  size_t size = blacklisted_features.size();
  if (size == 0)
    return false;
  uint32 flags = 0;
  for (size_t i = 0; i < size; ++i) {
    GpuFeatureFlags::GpuFeatureType type =
        GpuFeatureFlags::StringToGpuFeatureType(blacklisted_features[i]);
    switch (type) {
      case GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas:
      case GpuFeatureFlags::kGpuFeatureAcceleratedCompositing:
      case GpuFeatureFlags::kGpuFeatureWebgl:
      case GpuFeatureFlags::kGpuFeatureAll:
        flags |= type;
        break;
      case GpuFeatureFlags::kGpuFeatureUnknown:
        return false;
    }
  }
  feature_flags_.reset(new GpuFeatureFlags());
  feature_flags_->set_flags(flags);
  return true;
}

bool GpuBlacklist::GpuBlacklistEntry::Contains(
    OsType os_type, const Version& os_version,
    uint32 vendor_id, uint32 device_id,
    const Version& driver_version) const {
  DCHECK(os_type != kOsAny);
  if (os_info_.get() != NULL && !os_info_->Contains(os_type, os_version))
    return false;
  if (vendor_id_ != 0 && vendor_id_ != vendor_id)
    return false;
  if (device_id_ != 0 && device_id_ != device_id)
    return false;
  if (driver_version_info_.get() == NULL)
    return true;
  return driver_version_info_->Contains(driver_version);
}

GpuBlacklist::OsType GpuBlacklist::GpuBlacklistEntry::GetOsType() const {
  if (os_info_.get() == NULL)
    return kOsUnknown;
  return os_info_->type();
}

GpuFeatureFlags GpuBlacklist::GpuBlacklistEntry::GetGpuFeatureFlags() const {
  return *feature_flags_;
}

GpuBlacklist::GpuBlacklist() {
}

GpuBlacklist::~GpuBlacklist() {
  Clear();
}

bool GpuBlacklist::LoadGpuBlacklist(const std::string& json_context,
                                    bool current_os_only) {
  std::vector<GpuBlacklistEntry*> entries;
  scoped_ptr<Value> root;
  root.reset(base::JSONReader::Read(json_context, false));
  if (root.get() == NULL || !root->IsType(Value::TYPE_DICTIONARY))
    return false;

  ListValue* list = NULL;
  static_cast<DictionaryValue*>(root.get())->GetList("entries", &list);
  if (list == NULL)
    return false;

  for (size_t i = 0; i < list->GetSize(); ++i) {
    DictionaryValue* list_item = NULL;
    bool valid = list->GetDictionary(i, &list_item);
    if (!valid)
      break;
    GpuBlacklistEntry* entry =
        GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(list_item);
    if (entry == NULL)
      break;
    entries.push_back(entry);
  }

  if (entries.size() < list->GetSize()) {
    for (size_t i = 0; i < entries.size(); ++i)
      delete entries[i];
    return false;
  }

  Clear();
  // Don't apply GPU blacklist for a non-registered OS.
  OsType os_filter = GetOsType();
  if (os_filter != kOsUnknown) {
    for (size_t i = 0; i < entries.size(); ++i) {
      OsType entry_os = entries[i]->GetOsType();
      if (!current_os_only ||
          entry_os == kOsAny || entry_os == os_filter)
        blacklist_.push_back(entries[i]);
      else
        delete entries[i];
    }
  }
  return true;
}

GpuFeatureFlags GpuBlacklist::DetermineGpuFeatureFlags(
    GpuBlacklist::OsType os,
    Version* os_version,
    const GPUInfo& gpu_info) const {
  GpuFeatureFlags flags;
  // No need to go through blacklist entries if GPUInfo isn't available.
  if (gpu_info.progress() == GPUInfo::kUninitialized)
    return flags;
  scoped_ptr<Version> driver_version(
      Version::GetVersionFromString(gpu_info.driver_version()));
  if (driver_version.get() == NULL)
    return flags;

  if (os == kOsAny)
    os = GetOsType();
  scoped_ptr<Version> my_os_version;
  if (os_version == NULL) {
    std::string version_string;
#if defined(OS_MACOSX)
    // Seems like base::SysInfo::OperatingSystemVersion() returns the wrong
    // version in MacOsx.
    int32 version_major, version_minor, version_bugfix;
    base::SysInfo::OperatingSystemVersionNumbers(
        &version_major, &version_minor, &version_bugfix);
    version_string = base::StringPrintf("%d.%d.%d",
                                        version_major,
                                        version_minor,
                                        version_bugfix);
#else
    version_string = base::SysInfo::OperatingSystemVersion();
#endif
    my_os_version.reset(Version::GetVersionFromString(version_string));
    os_version = my_os_version.get();
  }
  DCHECK(os_version != NULL);

  for (size_t i = 0; i < blacklist_.size(); ++i) {
    if (blacklist_[i]->Contains(os, *os_version,
                                gpu_info.vendor_id(), gpu_info.device_id(),
                                *driver_version)) {
      flags.Combine(blacklist_[i]->GetGpuFeatureFlags());
    }
  }
  return flags;
}

GpuBlacklist::OsType GpuBlacklist::GetOsType() {
#if defined(OS_WIN)
  return kOsWin;
#elif defined(OS_LINUX)
  return kOsLinux;
#elif defined(OS_MACOSX)
  return kOsMacosx;
#else
  return kOsUnknown;
#endif
}

void GpuBlacklist::Clear() {
  for (size_t i = 0; i < blacklist_.size(); ++i)
    delete blacklist_[i];
  blacklist_.clear();
}

<|endoftext|>


<commit_before>// Copyright (c) 2009 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/test/render_view_test.h"

#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_preferences.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/extension_process_bindings.h"
#include "chrome/renderer/extensions/js_only_v8_extensions.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "webkit/api/public/WebFrame.h"
#include "webkit/api/public/WebInputEvent.h"
#include "webkit/api/public/WebKit.h"
#include "webkit/api/public/WebScriptSource.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/webview.h"

using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;
using WebKit::WebURLRequest;

namespace {
const int32 kRouteId = 5;
const int32 kOpenerId = 7;
}

void RenderViewTest::ProcessPendingMessages() {
  msg_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask());
  msg_loop_.Run();
}

WebFrame* RenderViewTest::GetMainFrame() {
  return view_->webview()->GetMainFrame();
}

void RenderViewTest::ExecuteJavaScript(const char* js) {
  GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
}

void RenderViewTest::LoadHTML(const char* html) {
  std::string url_str = "data:text/html;charset=utf-8,";
  url_str.append(html);
  GURL url(url_str);

  GetMainFrame()->loadRequest(WebURLRequest(url));

  // The load actually happens asynchronously, so we pump messages to process
  // the pending continuation.
  ProcessPendingMessages();
}

void RenderViewTest::SetUp() {
  sandbox_init_wrapper_.reset(new SandboxInitWrapper());
#if defined(OS_WIN)
  command_line_.reset(new CommandLine(std::wstring()));
#elif defined(OS_POSIX)
  command_line_.reset(new CommandLine(std::vector<std::string>()));
#endif
  params_.reset(new MainFunctionParams(*command_line_, *sandbox_init_wrapper_,
                                       NULL));
  platform_.reset(new RendererMainPlatformDelegate(*params_));
  platform_->PlatformInitialize();

  WebKit::initialize(&webkitclient_);
  WebKit::registerExtension(BaseJsV8Extension::Get());
  WebKit::registerExtension(JsonSchemaJsV8Extension::Get());
  WebKit::registerExtension(EventBindings::Get());
  WebKit::registerExtension(ExtensionApiTestV8Extension::Get());
  WebKit::registerExtension(ExtensionProcessBindings::Get());
  WebKit::registerExtension(RendererExtensionBindings::Get());
  EventBindings::SetRenderThread(&render_thread_);

  // TODO(aa): Should some of this go to some other inheriting class?
  std::vector<std::string> names;
  ExtensionFunctionDispatcher::GetAllFunctionNames(&names);
  ExtensionProcessBindings::SetFunctionNames(names);

  std::vector<std::string> permissions(
      Extension::kPermissionNames,
      Extension::kPermissionNames + Extension::kNumPermissions);
  ExtensionProcessBindings::SetAPIPermissions("", permissions);

  mock_process_.reset(new MockProcess());

  render_thread_.set_routing_id(kRouteId);

  // This needs to pass the mock render thread to the view.
  view_ = RenderView::Create(&render_thread_, NULL, NULL, kOpenerId,
                             RendererPreferences(), WebPreferences(),
                             new SharedRenderViewCounter(0), kRouteId);

  // Attach a pseudo keyboard device to this object.
  mock_keyboard_.reset(new MockKeyboard());
}
void RenderViewTest::TearDown() {
  render_thread_.SendCloseMessage();

  // Run the loop so the release task from the renderwidget executes.
  ProcessPendingMessages();

  EventBindings::SetRenderThread(NULL);

  view_ = NULL;

  mock_process_.reset();
  WebKit::shutdown();

  msg_loop_.RunAllPending();

  mock_keyboard_.reset();

  platform_->PlatformUninitialize();
  platform_.reset();
  params_.reset();
  command_line_.reset();
  sandbox_init_wrapper_.reset();
}

int RenderViewTest::SendKeyEvent(MockKeyboard::Layout layout,
                                 int key_code,
                                 MockKeyboard::Modifiers modifiers,
                                 std::wstring* output) {
#if defined(OS_WIN)
  // Retrieve the Unicode character for the given tuple (keyboard-layout,
  // key-code, and modifiers).
  // Exit when a keyboard-layout driver cannot assign a Unicode character to
  // the tuple to prevent sending an invalid key code to the RenderView object.
  CHECK(mock_keyboard_.get());
  CHECK(output);
  int length = mock_keyboard_->GetCharacters(layout, key_code, modifiers,
                                             output);
  if (length != 1)
    return -1;

  // Create IPC messages from Windows messages and send them to our
  // back-end.
  // A keyboard event of Windows consists of three Windows messages:
  // WM_KEYDOWN, WM_CHAR, and WM_KEYUP.
  // WM_KEYDOWN and WM_KEYUP sends virtual-key codes. On the other hand,
  // WM_CHAR sends a composed Unicode character.
  NativeWebKeyboardEvent keydown_event(NULL, WM_KEYDOWN, key_code, 0);
  scoped_ptr<IPC::Message> keydown_message(new ViewMsg_HandleInputEvent(0));
  keydown_message->WriteData(reinterpret_cast<const char*>(&keydown_event),
                             sizeof(WebKit::WebKeyboardEvent));
  view_->OnHandleInputEvent(*keydown_message);

  NativeWebKeyboardEvent char_event(NULL, WM_CHAR, (*output)[0], 0);
  scoped_ptr<IPC::Message> char_message(new ViewMsg_HandleInputEvent(0));
  char_message->WriteData(reinterpret_cast<const char*>(&char_event),
                          sizeof(WebKit::WebKeyboardEvent));
  view_->OnHandleInputEvent(*char_message);

  NativeWebKeyboardEvent keyup_event(NULL, WM_KEYUP, key_code, 0);
  scoped_ptr<IPC::Message> keyup_message(new ViewMsg_HandleInputEvent(0));
  keyup_message->WriteData(reinterpret_cast<const char*>(&keyup_event),
                           sizeof(WebKit::WebKeyboardEvent));
  view_->OnHandleInputEvent(*keyup_message);

  return length;
#else
  NOTIMPLEMENTED();
  return L'\0';
#endif
}
<commit_msg>Hopefully fix flaky RenderViewTest<commit_after>// Copyright (c) 2009 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/test/render_view_test.h"

#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_preferences.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/extension_process_bindings.h"
#include "chrome/renderer/extensions/js_only_v8_extensions.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "webkit/api/public/WebFrame.h"
#include "webkit/api/public/WebInputEvent.h"
#include "webkit/api/public/WebKit.h"
#include "webkit/api/public/WebScriptSource.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/webview.h"

using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;
using WebKit::WebURLRequest;

namespace {
const int32 kRouteId = 5;
const int32 kOpenerId = 7;
}

void RenderViewTest::ProcessPendingMessages() {
  msg_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask());
  msg_loop_.Run();
}

WebFrame* RenderViewTest::GetMainFrame() {
  return view_->webview()->GetMainFrame();
}

void RenderViewTest::ExecuteJavaScript(const char* js) {
  GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
}

void RenderViewTest::LoadHTML(const char* html) {
  std::string url_str = "data:text/html;charset=utf-8,";
  url_str.append(html);
  GURL url(url_str);

  GetMainFrame()->loadRequest(WebURLRequest(url));

  // The load actually happens asynchronously, so we pump messages to process
  // the pending continuation.
  ProcessPendingMessages();
}

void RenderViewTest::SetUp() {
  sandbox_init_wrapper_.reset(new SandboxInitWrapper());
#if defined(OS_WIN)
  command_line_.reset(new CommandLine(std::wstring()));
#elif defined(OS_POSIX)
  command_line_.reset(new CommandLine(std::vector<std::string>()));
#endif
  params_.reset(new MainFunctionParams(*command_line_, *sandbox_init_wrapper_,
                                       NULL));
  platform_.reset(new RendererMainPlatformDelegate(*params_));
  platform_->PlatformInitialize();

  WebKit::initialize(&webkitclient_);
  WebKit::registerExtension(BaseJsV8Extension::Get());
  WebKit::registerExtension(JsonSchemaJsV8Extension::Get());
  WebKit::registerExtension(EventBindings::Get());
  WebKit::registerExtension(ExtensionApiTestV8Extension::Get());
  WebKit::registerExtension(ExtensionProcessBindings::Get());
  WebKit::registerExtension(RendererExtensionBindings::Get());
  EventBindings::SetRenderThread(&render_thread_);

  // TODO(aa): Should some of this go to some other inheriting class?
  std::vector<std::string> names;
  ExtensionFunctionDispatcher::GetAllFunctionNames(&names);
  ExtensionProcessBindings::SetFunctionNames(names);

  std::vector<std::string> permissions(
      Extension::kPermissionNames,
      Extension::kPermissionNames + Extension::kNumPermissions);
  ExtensionProcessBindings::SetAPIPermissions("", permissions);

  mock_process_.reset(new MockProcess());

  render_thread_.set_routing_id(kRouteId);

  // This needs to pass the mock render thread to the view.
  view_ = RenderView::Create(&render_thread_, NULL, NULL, kOpenerId,
                             RendererPreferences(), WebPreferences(),
                             new SharedRenderViewCounter(0), kRouteId);

  // Attach a pseudo keyboard device to this object.
  mock_keyboard_.reset(new MockKeyboard());
}
void RenderViewTest::TearDown() {
  render_thread_.SendCloseMessage();

  // Run the loop so the release task from the renderwidget executes.
  ProcessPendingMessages();

  EventBindings::SetRenderThread(NULL);

  view_ = NULL;

  mock_process_.reset();

  // After resetting the view_ and mock_process_ we may get some new tasks
  // which need to be processed before shutting down WebKit
  // (http://crbug.com/21508).
  msg_loop_.RunAllPending();

  WebKit::shutdown();

  mock_keyboard_.reset();

  platform_->PlatformUninitialize();
  platform_.reset();
  params_.reset();
  command_line_.reset();
  sandbox_init_wrapper_.reset();
}

int RenderViewTest::SendKeyEvent(MockKeyboard::Layout layout,
                                 int key_code,
                                 MockKeyboard::Modifiers modifiers,
                                 std::wstring* output) {
#if defined(OS_WIN)
  // Retrieve the Unicode character for the given tuple (keyboard-layout,
  // key-code, and modifiers).
  // Exit when a keyboard-layout driver cannot assign a Unicode character to
  // the tuple to prevent sending an invalid key code to the RenderView object.
  CHECK(mock_keyboard_.get());
  CHECK(output);
  int length = mock_keyboard_->GetCharacters(layout, key_code, modifiers,
                                             output);
  if (length != 1)
    return -1;

  // Create IPC messages from Windows messages and send them to our
  // back-end.
  // A keyboard event of Windows consists of three Windows messages:
  // WM_KEYDOWN, WM_CHAR, and WM_KEYUP.
  // WM_KEYDOWN and WM_KEYUP sends virtual-key codes. On the other hand,
  // WM_CHAR sends a composed Unicode character.
  NativeWebKeyboardEvent keydown_event(NULL, WM_KEYDOWN, key_code, 0);
  scoped_ptr<IPC::Message> keydown_message(new ViewMsg_HandleInputEvent(0));
  keydown_message->WriteData(reinterpret_cast<const char*>(&keydown_event),
                             sizeof(WebKit::WebKeyboardEvent));
  view_->OnHandleInputEvent(*keydown_message);

  NativeWebKeyboardEvent char_event(NULL, WM_CHAR, (*output)[0], 0);
  scoped_ptr<IPC::Message> char_message(new ViewMsg_HandleInputEvent(0));
  char_message->WriteData(reinterpret_cast<const char*>(&char_event),
                          sizeof(WebKit::WebKeyboardEvent));
  view_->OnHandleInputEvent(*char_message);

  NativeWebKeyboardEvent keyup_event(NULL, WM_KEYUP, key_code, 0);
  scoped_ptr<IPC::Message> keyup_message(new ViewMsg_HandleInputEvent(0));
  keyup_message->WriteData(reinterpret_cast<const char*>(&keyup_event),
                           sizeof(WebKit::WebKeyboardEvent));
  view_->OnHandleInputEvent(*keyup_message);

  return length;
#else
  NOTIMPLEMENTED();
  return L'\0';
#endif
}
<|endoftext|>


<commit_before>
#include "numerics/matrix_computations.hpp"

#include <tuple>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/fixed_arrays.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
#include "testing_utilities/almost_equals.hpp"

namespace principia {
namespace numerics {

using quantities::Sqrt;
using testing_utilities::AlmostEquals;

template<typename T>
class MatrixComputationsTest : public ::testing::Test {
 protected:
};

template<typename Scalar>
using FixedVector4 = FixedVector<Scalar, 4>;
template<typename Scalar>
using FixedLowerTriangularMatrix4 = FixedLowerTriangularMatrix<Scalar, 4>;
template<typename Scalar>
using FixedUpperTriangularMatrix4 = FixedUpperTriangularMatrix<Scalar, 4>;

using MatrixTypes =
    ::testing::Types<std::tuple<FixedVector4<double>,
                                FixedLowerTriangularMatrix4<double>,
                                FixedUpperTriangularMatrix4<double>>,
                     std::tuple<UnboundedVector<double>,
                                UnboundedLowerTriangularMatrix<double>,
                                UnboundedUpperTriangularMatrix<double>>>;

TYPED_TEST_SUITE(MatrixComputationsTest, MatrixTypes);

TYPED_TEST(MatrixComputationsTest, CholeskyDecomposition) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;

  UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
                                           1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
                                                      1.0 / 5.0, 1.0 / 6.0,
                                                                 1.0 / 7.0});
  UpperTriangularMatrix const r4_expected({
      1,        1.0 / 2.0,         1.0 / 3.0,          1.0 / 4.0,
         1.0 / Sqrt(12.0),  1.0 / Sqrt(12.0),  Sqrt(27.0) / 20.0,
                           1.0 / Sqrt(180.0),   1.0 / Sqrt(80.0),
                                              1.0 / Sqrt(2800.0)});

  auto const r4_actual = CholeskyDecomposition(hilbert4);
  EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 245));
}

TYPED_TEST(MatrixComputationsTest, ᵗRDRDecomposition) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;

  UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
                                           1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
                                                      1.0 / 5.0, 1.0 / 6.0,
                                                                 1.0 / 7.0});
  UpperTriangularMatrix const r4_expected({
      1, 1.0 / 2.0, 1.0 / 3.0,  1.0 / 4.0,
                 1,         1, 9.0 / 10.0,
                            1,  3.0 / 2.0,
                                        1});
  Vector d4_expected({1, 1.0 / 12.0, 1.0 / 180.0, 1.0 / 2800.0});

  UpperTriangularMatrix r4_actual(4);
  Vector d4_actual(4);
  ᵗRDRDecomposition(hilbert4, r4_actual, d4_actual);
  EXPECT_THAT(d4_actual, AlmostEquals(d4_expected, 1615));
  EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 23));
}

TYPED_TEST(MatrixComputationsTest, BackSubstitution) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;

  UpperTriangularMatrix const m4({1, 3, -2,  6,
                                     4,  7, -1,
                                         5,  3,
                                             2});
  Vector const b4({1, 1, -4, 4});
  Vector const x4_expected({-111.0 / 4.0, 17.0 / 4.0, -2.0, 2.0});

  auto const x4_actual = BackSubstitution(m4, b4);
  EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 1));
}

TYPED_TEST(MatrixComputationsTest, ForwardSubstitution) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using LowerTriangularMatrix = typename std::tuple_element<1, TypeParam>::type;

  LowerTriangularMatrix const m4({ 1,
                                   3, -2,
                                   4,  7, 5,
                                  -6,  9, 1, 2});
  Vector const b4({1, 1, -4, 4});
  Vector const x4_expected({1, 1, -3, 2});

  auto const x4_actual = ForwardSubstitution(m4, b4);
  EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 0));
}

}  // namespace numerics
}  // namespace principia
<commit_msg>The tests I'd like to have.<commit_after>
#include "numerics/matrix_computations.hpp"

#include <tuple>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/fixed_arrays.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
#include "testing_utilities/almost_equals.hpp"

namespace principia {
namespace numerics {

using quantities::Sqrt;
using testing_utilities::AlmostEquals;

template<typename T>
class MatrixComputationsTest : public ::testing::Test {
 protected:
};

using MatrixTypes =
    ::testing::Types<std::tuple<FixedVector<double, 4>,
                                FixedLowerTriangularMatrix<double, 4>,
                                FixedUpperTriangularMatrix<double, 4>>,
                     std::tuple<UnboundedVector<double>,
                                UnboundedLowerTriangularMatrix<double>,
                                UnboundedUpperTriangularMatrix<double>>>;

TYPED_TEST_SUITE(MatrixComputationsTest, MatrixTypes);

TYPED_TEST(MatrixComputationsTest, CholeskyDecomposition) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;

  UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
                                           1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
                                                      1.0 / 5.0, 1.0 / 6.0,
                                                                 1.0 / 7.0});
  UpperTriangularMatrix const r4_expected({
      1,        1.0 / 2.0,         1.0 / 3.0,          1.0 / 4.0,
         1.0 / Sqrt(12.0),  1.0 / Sqrt(12.0),  Sqrt(27.0) / 20.0,
                           1.0 / Sqrt(180.0),   1.0 / Sqrt(80.0),
                                              1.0 / Sqrt(2800.0)});

  auto const r4_actual = CholeskyDecomposition(hilbert4);
  EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 245));
}
#if 0
TYPED_TEST(MatrixComputationsTest, ᵗRDRDecomposition) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;

  UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
                                           1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
                                                      1.0 / 5.0, 1.0 / 6.0,
                                                                 1.0 / 7.0});
  UpperTriangularMatrix const r4_expected({
      1, 1.0 / 2.0, 1.0 / 3.0,  1.0 / 4.0,
                 1,         1, 9.0 / 10.0,
                            1,  3.0 / 2.0,
                                        1});
  Vector d4_expected({1, 1.0 / 12.0, 1.0 / 180.0, 1.0 / 2800.0});

  UpperTriangularMatrix r4_actual(4);
  Vector d4_actual(4);
  ᵗRDRDecomposition(hilbert4, r4_actual, d4_actual);
  EXPECT_THAT(d4_actual, AlmostEquals(d4_expected, 1615));
  EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 23));
}

TYPED_TEST(MatrixComputationsTest, BackSubstitution) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;

  UpperTriangularMatrix const m4({1, 3, -2,  6,
                                     4,  7, -1,
                                         5,  3,
                                             2});
  Vector const b4({1, 1, -4, 4});
  Vector const x4_expected({-111.0 / 4.0, 17.0 / 4.0, -2.0, 2.0});

  auto const x4_actual = BackSubstitution(m4, b4);
  EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 1));
}

TYPED_TEST(MatrixComputationsTest, ForwardSubstitution) {
  using Vector = typename std::tuple_element<0, TypeParam>::type;
  using LowerTriangularMatrix = typename std::tuple_element<1, TypeParam>::type;

  LowerTriangularMatrix const m4({ 1,
                                   3, -2,
                                   4,  7, 5,
                                  -6,  9, 1, 2});
  Vector const b4({1, 1, -4, 4});
  Vector const x4_expected({1, 1, -3, 2});

  auto const x4_actual = ForwardSubstitution(m4, b4);
  EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 0));
}
#endif
}  // namespace numerics
}  // namespace principia
<|endoftext|>


<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/renderer/shell_content_renderer_client.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "content/nw/src/api/dispatcher.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_version.h"
#include "content/nw/src/renderer/prerenderer/prerenderer_client.h"
#include "content/nw/src/renderer/shell_render_process_observer.h"
#include "content/nw/src/renderer/shell_render_view_observer.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/req_wrap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "v8/include/v8.h"

namespace content {

ShellContentRendererClient::ShellContentRendererClient() {
}

ShellContentRendererClient::~ShellContentRendererClient() {
}

void ShellContentRendererClient::RenderThreadStarted() {
  // Change working directory
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kWorkingDirectory)) {
    file_util::SetCurrentDirectory(
        command_line->GetSwitchValuePath(switches::kWorkingDirectory));
  }

  // Initialize node after render thread is started
  v8::V8::Initialize();
  v8::HandleScope scope;

  node::g_context = v8::Context::New();
  node::g_context->Enter();

  char* argv[] = { (char*)"node", NULL };
  node::SetupContext(1, argv, node::g_context->Global());

  // Start observers
  shell_observer_.reset(new ShellRenderProcessObserver());
  api_dispatcher_.reset(new api::Dispatcher());
}

void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) {
  new prerender::PrerendererClient(render_view);
  new ShellRenderViewObserver(render_view);
}

void ShellContentRendererClient::DidCreateScriptContext(
    WebKit::WebFrame* frame,
    v8::Handle<v8::Context> context,
    int extension_group,
    int world_id) {
  InstallNodeSymbols(context);

  api_dispatcher_->DidCreateScriptContext(
      frame, context, extension_group, world_id);
}

void ShellContentRendererClient::WillReleaseScriptContext(
    WebKit::WebFrame* frame,
    v8::Handle<v8::Context> context,
    int world_id) {
  api_dispatcher_->WillReleaseScriptContext(frame, context, world_id);
}

bool ShellContentRendererClient::WillSetSecurityToken(
    WebKit::WebFrame* frame,
    v8::Handle<v8::Context> context) {
  // Override context's security token
  context->SetSecurityToken(node::g_context->GetSecurityToken());

  return true;
}

void ShellContentRendererClient::InstallNodeSymbols(
    v8::Handle<v8::Context> context) {
  // Do we integrate node?
  bool use_node = CommandLine::ForCurrentProcess()->HasSwitch(switches::kmNodejs);

  // Test if protocol is file:
  v8::Local<v8::Script> protocol_script = v8::Script::New(v8::String::New(
      "(function(){ return window.location.protocol == 'file:' })();"
  ));
  bool is_file_protocol = protocol_script->Run()->BooleanValue();

  // Disable nodejs in no-file protocols
  use_node = is_file_protocol ? use_node : false;

  // Test if protocol is 'nw:'
  // test for 'about:blank' is also here becuase window.open would open 'about:blank' first
  protocol_script = v8::Script::New(v8::String::New(
      "(function(){ return window.location.protocol == 'nw:' || window.location == 'about:blank'; })();"
  ));
  bool is_nw_protocol = protocol_script->Run()->BooleanValue();

  if (use_node || is_nw_protocol) {
    // Don't use WebKit's timers in node
    v8::Local<v8::Object> disableMap = v8::Object::New();
    disableMap->Set(v8::String::New("setTimeout"), v8::Integer::New(1));
    disableMap->Set(v8::String::New("clearTimeout"), v8::Integer::New(1));
    disableMap->Set(v8::String::New("setInterval"), v8::Integer::New(1));
    disableMap->Set(v8::String::New("clearInterval"), v8::Integer::New(1));

    v8::Local<v8::Object> nodeGlobal = node::g_context->Global();
    v8::Local<v8::Object> v8Global = context->Global();
    v8::Local<v8::Array> symbols = nodeGlobal->GetPropertyNames();
    for (unsigned i = 0; i < symbols->Length(); ++i) {
      v8::Local<v8::Value> key = symbols->Get(i);
      if (disableMap->Has(key->ToString()))
        continue;
      v8Global->Set(key, nodeGlobal->Get(key));
    }
  }

  if (use_node) {
    v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
        // Make node's relative modules work
#if defined(OS_WIN)
        "process.mainModule.filename = decodeURIComponent(window.location.pathname.substr(1));"
#else
        "process.mainModule.filename = decodeURIComponent(window.location.pathname);"
#endif
        "process.mainModule.paths = require('module')._nodeModulePaths(process.cwd());"
    ));
    script->Run();
  }

  if (use_node || is_nw_protocol) {
    v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
        // Use WebKit's console globally
        "global.console = console;"

        // Don't exit on exception
        "process.on('uncaughtException', function (err) {"
          "console.log(err.stack);"
        "});"

        // Save node-webkit version
        "process.versions['node-webkit'] = '" NW_VERSION_STRING "';"
    ));
    script->Run();
  }
}

}  // namespace content
<commit_msg>Only transfer necessary objects from node to DOM.<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/renderer/shell_content_renderer_client.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "content/nw/src/api/dispatcher.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_version.h"
#include "content/nw/src/renderer/prerenderer/prerenderer_client.h"
#include "content/nw/src/renderer/shell_render_process_observer.h"
#include "content/nw/src/renderer/shell_render_view_observer.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/req_wrap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "v8/include/v8.h"

namespace content {

ShellContentRendererClient::ShellContentRendererClient() {
}

ShellContentRendererClient::~ShellContentRendererClient() {
}

void ShellContentRendererClient::RenderThreadStarted() {
  // Change working directory
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kWorkingDirectory)) {
    file_util::SetCurrentDirectory(
        command_line->GetSwitchValuePath(switches::kWorkingDirectory));
  }

  // Initialize node after render thread is started
  v8::V8::Initialize();
  v8::HandleScope scope;

  node::g_context = v8::Context::New();
  node::g_context->Enter();

  char* argv[] = { (char*)"node", NULL };
  node::SetupContext(1, argv, node::g_context->Global());

  // Start observers
  shell_observer_.reset(new ShellRenderProcessObserver());
  api_dispatcher_.reset(new api::Dispatcher());
}

void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) {
  new prerender::PrerendererClient(render_view);
  new ShellRenderViewObserver(render_view);
}

void ShellContentRendererClient::DidCreateScriptContext(
    WebKit::WebFrame* frame,
    v8::Handle<v8::Context> context,
    int extension_group,
    int world_id) {
  InstallNodeSymbols(context);

  api_dispatcher_->DidCreateScriptContext(
      frame, context, extension_group, world_id);
}

void ShellContentRendererClient::WillReleaseScriptContext(
    WebKit::WebFrame* frame,
    v8::Handle<v8::Context> context,
    int world_id) {
  api_dispatcher_->WillReleaseScriptContext(frame, context, world_id);
}

bool ShellContentRendererClient::WillSetSecurityToken(
    WebKit::WebFrame* frame,
    v8::Handle<v8::Context> context) {
  // Override context's security token
  context->SetSecurityToken(node::g_context->GetSecurityToken());

  return true;
}

void ShellContentRendererClient::InstallNodeSymbols(
    v8::Handle<v8::Context> context) {
  // Do we integrate node?
  bool use_node = CommandLine::ForCurrentProcess()->HasSwitch(switches::kmNodejs);

  // Test if protocol is file:
  v8::Local<v8::Script> protocol_script = v8::Script::New(v8::String::New(
      "(function(){ return window.location.protocol == 'file:' })();"
  ));
  bool is_file_protocol = protocol_script->Run()->BooleanValue();

  // Disable nodejs in no-file protocols
  use_node = is_file_protocol ? use_node : false;

  // Test if protocol is 'nw:'
  // test for 'about:blank' is also here becuase window.open would open 'about:blank' first
  protocol_script = v8::Script::New(v8::String::New(
      "(function(){ return window.location.protocol == 'nw:' || window.location == 'about:blank'; })();"
  ));
  bool is_nw_protocol = protocol_script->Run()->BooleanValue();

  if (use_node || is_nw_protocol) {
    v8::Local<v8::Array> symbols = v8::Array::New(5);
    symbols->Set(0, v8::String::New("require"));
    symbols->Set(1, v8::String::New("global"));
    symbols->Set(2, v8::String::New("process"));
    symbols->Set(3, v8::String::New("Buffer"));
    symbols->Set(4, v8::String::New("root"));

    v8::Local<v8::Object> nodeGlobal = node::g_context->Global();
    v8::Local<v8::Object> v8Global = context->Global();
    for (unsigned i = 0; i < symbols->Length(); ++i) {
      v8::Local<v8::Value> key = symbols->Get(i);
      v8Global->Set(key, nodeGlobal->Get(key));
    }
  }

  if (use_node) {
    v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
        // Make node's relative modules work
#if defined(OS_WIN)
        "process.mainModule.filename = decodeURIComponent(window.location.pathname.substr(1));"
#else
        "process.mainModule.filename = decodeURIComponent(window.location.pathname);"
#endif
        "process.mainModule.paths = require('module')._nodeModulePaths(process.cwd());"
    ));
    script->Run();
  }

  if (use_node || is_nw_protocol) {
    v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
        // Use WebKit's console globally
        "global.console = console;"

        // Don't exit on exception
        "process.on('uncaughtException', function (err) {"
          "console.log(err.stack);"
        "});"

        // Save node-webkit version
        "process.versions['node-webkit'] = '" NW_VERSION_STRING "';"
    ));
    script->Run();
  }
}

}  // namespace content
<|endoftext|>


<commit_before>#include <nan.h>
#include "prtscn_windows.h"
#include <stdlib.h>

using namespace v8;

void Method(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = args.GetIsolate();

	// Check number of arguments passed
	if (args.Length() < 5) {
		isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments")));
		return;
	}

	//Check the argument types
	if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber()) {
		isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments")));
		return;
	}

	int x = args[0]->NumberValue();
	int y = args[1]->NumberValue();
	int width =  args[2]->NumberValue();
	int height = args[3]->NumberValue();

	getScreen(x, y, width, height, *String::Utf8Value(args[4]));

	//Performe the operation
	Local<Function> cb = Local<Function>::Cast(args[5]);
	Local<Value> argv[1] = {Null(isolate)};
	cb->Call(Null(isolate), 1, argv);
}

void Init(Local<Object> exports, Local<Object> module) {
	NODE_SET_METHOD(module, "exports", Method);
}

NODE_MODULE(screenshot, Init)
<commit_msg>Adding node12 support<commit_after>#include <nan.h>
#include "prtscn_windows.h"
#include <stdlib.h>

using namespace v8;

void Method(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = args.GetIsolate();
	v8::Local<v8::Context> context = isolate->GetCurrentContext();

	// Check number of arguments passed
	if (args.Length() < 5) {
		isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments")));
		return;
	}

	//Check the argument types
	if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber()) {
		isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments")));
		return;
	}

	int x = args[0]->NumberValue(context).FromJust();
	int y = args[1]->NumberValue(context).FromJust();
	int width =  args[2]->NumberValue(context).FromJust();
	int height = args[3]->NumberValue(context).FromJust();;

	Nan::Utf8String param1(args[4]->ToString(context).ToLocalChecked());
    std::string value = std::string(*param1);

	getScreen(x, y, width, height, *String::Utf8Value(args[4]));

	//Performe the operation
	v8::Local<v8::Function> cb = Local<Function>::Cast(args[5]);
	Local<Value> argv[1] = {Null(isolate)};
	Nan::Callback callback(cb);
	callback.Call(1,argv);
}

void Init(Local<Object> exports, Local<Object> module) {
	NODE_SET_METHOD(module, "exports", Method);
}

NODE_MODULE(screenshot, Init)
<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

// TODO: clean me up!
SHIM_CALL DbgPrint_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t format_ptr = SHIM_GET_ARG_32(0);
  if (format_ptr == 0) {
    SHIM_SET_RETURN_64(-1);
    return;
  }

  const char* format = (const char*)SHIM_MEM_ADDR(format_ptr);

  int arg_index = 0;

  char buffer[512];  // TODO: ensure it never writes past the end of the
                     // buffer...
  char* b = buffer;
  for (; *format != '\0'; ++format) {
    const char* start = format;

    if (*format != '%') {
      *b++ = *format;
      continue;
    }

    ++format;
    if (*format == '\0') {
      break;
    }

    if (*format == '%') {
      *b++ = *format;
      continue;
    }

    const char* end;
    end = format;

    // skip flags
    while (*end == '-' || *end == '+' || *end == ' ' || *end == '#' ||
           *end == '0') {
      ++end;
    }

    if (*end == '\0') {
      break;
    }

    int arg_extras = 0;

    // skip width
    if (*end == '*') {
      ++end;
      arg_extras++;
    } else {
      while (*end >= '0' && *end <= '9') {
        ++end;
      }
    }

    if (*end == '\0') {
      break;
    }

    // skip precision
    if (*end == '.') {
      ++end;

      if (*end == '*') {
        ++end;
        ++arg_extras;
      } else {
        while (*end >= '0' && *end <= '9') {
          ++end;
        }
      }
    }

    if (*end == '\0') {
      break;
    }

    // get length
    int arg_size = 4;

    if (*end == 'h') {
      ++end;
      arg_size = 4;
      if (*end == 'h') {
        ++end;
      }
    } else if (*end == 'l') {
      ++end;
      arg_size = 4;
      if (*end == 'l') {
        ++end;
        arg_size = 8;
      }
    } else if (*end == 'j') {
      arg_size = 8;
      ++end;
    } else if (*end == 'z') {
      arg_size = 4;
      ++end;
    } else if (*end == 't') {
      arg_size = 8;
      ++end;
    } else if (*end == 'L') {
      arg_size = 8;
      ++end;
    }

    if (*end == '\0') {
      break;
    }

    if (*end == 'd' || *end == 'i' || *end == 'u' || *end == 'o' ||
        *end == 'x' || *end == 'X' || *end == 'f' || *end == 'F' ||
        *end == 'e' || *end == 'E' || *end == 'g' || *end == 'G' ||
        *end == 'a' || *end == 'A' || *end == 'c') {
      char local[512];
      local[0] = '\0';
      strncat(local, start, end + 1 - start);

      assert_true(arg_size == 8 || arg_size == 4);
      if (arg_size == 8) {
        if (arg_extras == 0) {
          uint64_t value =
              arg_index < 7
                  ? SHIM_GET_ARG_64(1 + arg_index)
                  : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
          int result = sprintf(b, local, value);
          b += result;
          arg_index++;
        } else {
          assert_true(false);
        }
      } else if (arg_size == 4) {
        if (arg_extras == 0) {
          uint64_t value =
              arg_index < 7
                  ? SHIM_GET_ARG_64(1 + arg_index)
                  : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
          int result = sprintf(b, local, (uint32_t)value);
          b += result;
          arg_index++;
        } else {
          assert_true(false);
        }
      }
    } else if (*end == 'n') {
      assert_true(arg_size == 4);
      if (arg_extras == 0) {
        uint32_t value = arg_index < 7
                             ? SHIM_GET_ARG_32(1 + arg_index)
                             : (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
                                                     ((1 + arg_index) * 8));
        SHIM_SET_MEM_32(value, (uint32_t)((b - buffer) / sizeof(char)));
        arg_index++;
      } else {
        assert_true(false);
      }
    } else if (*end == 's' || *end == 'p') {
      char local[512];
      local[0] = '\0';
      strncat(local, start, end + 1 - start);

      assert_true(arg_size == 4);
      if (arg_extras == 0) {
        uint32_t value = arg_index < 7
                             ? SHIM_GET_ARG_32(1 + arg_index)
                             : (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
                                                     ((1 + arg_index) * 8));
        const void* pointer = (const void*)SHIM_MEM_ADDR(value);
        int result = sprintf(b, local, pointer);
        b += result;
        arg_index++;
      } else {
        assert_true(false);
      }
    } else {
      assert_true(false);
      break;
    }

    format = end;
  }
  *b++ = '\0';

  XELOGD("(DbgPrint) %s", buffer);
}

SHIM_CALL DbgBreakPoint_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("DbgBreakPoint()");
  DebugBreak();
}

SHIM_CALL RtlRaiseException_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t record_ptr = SHIM_GET_ARG_32(0);

  uint32_t code = SHIM_MEM_32(record_ptr + 0);
  uint32_t flags = SHIM_MEM_32(record_ptr + 4);
  // ...
  uint32_t param_count = SHIM_MEM_32(record_ptr + 16);

  XELOGD("RtlRaiseException(%.8X(%.8X))", record_ptr, code);

  if (code == 0x406D1388) {
    // SetThreadName. FFS.
    uint32_t thread_info_ptr = record_ptr + 20;
    uint32_t type = SHIM_MEM_32(thread_info_ptr + 0);
    assert_true(type == 0x1000);
    uint32_t name_ptr = SHIM_MEM_32(thread_info_ptr + 4);
    uint32_t thread_id = SHIM_MEM_32(thread_info_ptr + 8);

    const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);

    XThread* thread = NULL;
    if (thread_id == -1) {
      // Current thread.
      thread = XThread::GetCurrentThread();
      thread->Retain();
    } else {
      // Lookup thread by ID.
      thread = state->GetThreadByID(thread_id);
    }

    if (thread) {
      XELOGD("SetThreadName(%d, %s)", thread->thread_id(), name);
      thread->set_name(name);
      thread->Release();
    }

    // TODO(benvanik): unwinding required here?
    return;
  }

  // TODO(benvanik): unwinding.
  // This is going to suck.
  DebugBreak();
}

void xeKeBugCheckEx(uint32_t code, uint32_t param1, uint32_t param2,
                    uint32_t param3, uint32_t param4) {
  XELOGD("*** STOP: 0x%.8X (0x%.8X, 0x%.8X, 0x%.8X, 0x%.8X)", code, param1,
         param2, param3, param4);
  fflush(stdout);
  DebugBreak();
  assert_always();
}

SHIM_CALL KeBugCheck_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t code = SHIM_GET_ARG_32(0);
  xeKeBugCheckEx(code, 0, 0, 0, 0);
}

SHIM_CALL KeBugCheckEx_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t code = SHIM_GET_ARG_32(0);
  uint32_t param1 = SHIM_GET_ARG_32(1);
  uint32_t param2 = SHIM_GET_ARG_32(2);
  uint32_t param3 = SHIM_GET_ARG_32(3);
  uint32_t param4 = SHIM_GET_ARG_32(4);
  xeKeBugCheckEx(code, param1, param2, param3, param4);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xboxkrnl::RegisterDebugExports(
    xe::cpu::ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xboxkrnl.exe", DbgPrint, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", DbgBreakPoint, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", RtlRaiseException, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheck, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheckEx, state);
}
<commit_msg>Cleaning up some stuff in RtlRaiseException, additional notes.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

// TODO: clean me up!
SHIM_CALL DbgPrint_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t format_ptr = SHIM_GET_ARG_32(0);
  if (format_ptr == 0) {
    SHIM_SET_RETURN_64(-1);
    return;
  }

  const char* format = (const char*)SHIM_MEM_ADDR(format_ptr);

  int arg_index = 0;

  char buffer[512];  // TODO: ensure it never writes past the end of the
                     // buffer...
  char* b = buffer;
  for (; *format != '\0'; ++format) {
    const char* start = format;

    if (*format != '%') {
      *b++ = *format;
      continue;
    }

    ++format;
    if (*format == '\0') {
      break;
    }

    if (*format == '%') {
      *b++ = *format;
      continue;
    }

    const char* end;
    end = format;

    // skip flags
    while (*end == '-' || *end == '+' || *end == ' ' || *end == '#' ||
           *end == '0') {
      ++end;
    }

    if (*end == '\0') {
      break;
    }

    int arg_extras = 0;

    // skip width
    if (*end == '*') {
      ++end;
      arg_extras++;
    } else {
      while (*end >= '0' && *end <= '9') {
        ++end;
      }
    }

    if (*end == '\0') {
      break;
    }

    // skip precision
    if (*end == '.') {
      ++end;

      if (*end == '*') {
        ++end;
        ++arg_extras;
      } else {
        while (*end >= '0' && *end <= '9') {
          ++end;
        }
      }
    }

    if (*end == '\0') {
      break;
    }

    // get length
    int arg_size = 4;

    if (*end == 'h') {
      ++end;
      arg_size = 4;
      if (*end == 'h') {
        ++end;
      }
    } else if (*end == 'l') {
      ++end;
      arg_size = 4;
      if (*end == 'l') {
        ++end;
        arg_size = 8;
      }
    } else if (*end == 'j') {
      arg_size = 8;
      ++end;
    } else if (*end == 'z') {
      arg_size = 4;
      ++end;
    } else if (*end == 't') {
      arg_size = 8;
      ++end;
    } else if (*end == 'L') {
      arg_size = 8;
      ++end;
    }

    if (*end == '\0') {
      break;
    }

    if (*end == 'd' || *end == 'i' || *end == 'u' || *end == 'o' ||
        *end == 'x' || *end == 'X' || *end == 'f' || *end == 'F' ||
        *end == 'e' || *end == 'E' || *end == 'g' || *end == 'G' ||
        *end == 'a' || *end == 'A' || *end == 'c') {
      char local[512];
      local[0] = '\0';
      strncat(local, start, end + 1 - start);

      assert_true(arg_size == 8 || arg_size == 4);
      if (arg_size == 8) {
        if (arg_extras == 0) {
          uint64_t value =
              arg_index < 7
                  ? SHIM_GET_ARG_64(1 + arg_index)
                  : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
          int result = sprintf(b, local, value);
          b += result;
          arg_index++;
        } else {
          assert_true(false);
        }
      } else if (arg_size == 4) {
        if (arg_extras == 0) {
          uint64_t value =
              arg_index < 7
                  ? SHIM_GET_ARG_64(1 + arg_index)
                  : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
          int result = sprintf(b, local, (uint32_t)value);
          b += result;
          arg_index++;
        } else {
          assert_true(false);
        }
      }
    } else if (*end == 'n') {
      assert_true(arg_size == 4);
      if (arg_extras == 0) {
        uint32_t value = arg_index < 7
                             ? SHIM_GET_ARG_32(1 + arg_index)
                             : (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
                                                     ((1 + arg_index) * 8));
        SHIM_SET_MEM_32(value, (uint32_t)((b - buffer) / sizeof(char)));
        arg_index++;
      } else {
        assert_true(false);
      }
    } else if (*end == 's' || *end == 'p') {
      char local[512];
      local[0] = '\0';
      strncat(local, start, end + 1 - start);

      assert_true(arg_size == 4);
      if (arg_extras == 0) {
        uint32_t value = arg_index < 7
                             ? SHIM_GET_ARG_32(1 + arg_index)
                             : (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
                                                     ((1 + arg_index) * 8));
        const void* pointer = (const void*)SHIM_MEM_ADDR(value);
        int result = sprintf(b, local, pointer);
        b += result;
        arg_index++;
      } else {
        assert_true(false);
      }
    } else {
      assert_true(false);
      break;
    }

    format = end;
  }
  *b++ = '\0';

  XELOGD("(DbgPrint) %s", buffer);
}

SHIM_CALL DbgBreakPoint_shim(PPCContext* ppc_state, KernelState* state) {
  XELOGD("DbgBreakPoint()");
  DebugBreak();
}

// https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
typedef struct {
    xe::be<uint32_t> type;
    xe::be<uint32_t> name_ptr;
    xe::be<uint32_t> thread_id;
    xe::be<uint32_t> flags;
} X_THREADNAME_INFO;
static_assert_size(X_THREADNAME_INFO, 0x10);

// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082.aspx
typedef struct {
  xe::be<uint32_t> exception_code;
  xe::be<uint32_t> exception_flags;
  xe::be<uint32_t> exception_record;
  xe::be<uint32_t> exception_address;
  xe::be<uint32_t> number_parameters;
  xe::be<uint32_t> exception_information[15];
} X_EXCEPTION_RECORD;
static_assert_size(X_EXCEPTION_RECORD, 0x50);

SHIM_CALL RtlRaiseException_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t record_ptr = SHIM_GET_ARG_32(0);

  auto record = reinterpret_cast<X_EXCEPTION_RECORD*>(SHIM_MEM_ADDR(record_ptr));

  XELOGD("RtlRaiseException(%.8X(%.8X))", record_ptr, record->exception_code);

  if (record->exception_code == 0x406D1388) {
    // SetThreadName. FFS.
    // https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx

    // TODO: check record->number_parameters to make sure it's a correct size
    auto thread_info = reinterpret_cast<X_THREADNAME_INFO*>(&record->exception_information[0]);

    assert_true(thread_info->type == 0x1000);
    const char* name = (const char*)SHIM_MEM_ADDR(thread_info->name_ptr);

    XThread* thread = NULL;
    if (thread_info->thread_id == -1) {
      // Current thread.
      thread = XThread::GetCurrentThread();
      thread->Retain();
    } else {
      // Lookup thread by ID.
      thread = state->GetThreadByID(thread_info->thread_id);
    }

    if (thread) {
      XELOGD("SetThreadName(%d, %s)", thread->thread_id(), name);
      thread->set_name(name);
      thread->Release();
    }

    // TODO(benvanik): unwinding required here?
    return;
  }

  if (record->exception_code == 0xE06D7363) {
    // C++ exception.
    // http://blogs.msdn.com/b/oldnewthing/archive/2010/07/30/10044061.aspx
    DebugBreak();
    return;
  }

  // TODO(benvanik): unwinding.
  // This is going to suck.
  DebugBreak();
}

void xeKeBugCheckEx(uint32_t code, uint32_t param1, uint32_t param2,
                    uint32_t param3, uint32_t param4) {
  XELOGD("*** STOP: 0x%.8X (0x%.8X, 0x%.8X, 0x%.8X, 0x%.8X)", code, param1,
         param2, param3, param4);
  fflush(stdout);
  DebugBreak();
  assert_always();
}

SHIM_CALL KeBugCheck_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t code = SHIM_GET_ARG_32(0);
  xeKeBugCheckEx(code, 0, 0, 0, 0);
}

SHIM_CALL KeBugCheckEx_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t code = SHIM_GET_ARG_32(0);
  uint32_t param1 = SHIM_GET_ARG_32(1);
  uint32_t param2 = SHIM_GET_ARG_32(2);
  uint32_t param3 = SHIM_GET_ARG_32(3);
  uint32_t param4 = SHIM_GET_ARG_32(4);
  xeKeBugCheckEx(code, param1, param2, param3, param4);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xboxkrnl::RegisterDebugExports(
    xe::cpu::ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xboxkrnl.exe", DbgPrint, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", DbgBreakPoint, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", RtlRaiseException, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheck, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheckEx, state);
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <map>

#include "sst/verbs.h"

using std::ofstream;
using std::map;
using std::cin;
using std::cout;
using std::endl;
using std::string;

using namespace sst;

// number of reruns
long long int num_reruns = 10000;

int main() {
    ofstream fout;
    fout.open("data_write_avg_time", ofstream::app);

    // input number of nodes and the local node id
    int num_nodes, node_rank;
    cin >> node_rank;
    cin >> num_nodes;

    // input the ip addresses
    map<uint32_t, string> ip_addrs;
    for(int i = 0; i < num_nodes; ++i) {
        cin >> ip_addrs[i];
    }

    // initialize the rdma resources
    verbs_initialize(ip_addrs, node_rank);

    int r_index = num_nodes - 1 - node_rank;
    for(int size = 1; size < 100000; ++size) {
        // create buffer for write and read
        char *write_buf, *read_buf;
        write_buf = (char *)malloc(size);
        read_buf = (char *)malloc(size);

        resources res(r_index, read_buf, write_buf, size, size);

        // start the timing experiment
        struct timespec start_time;
        struct timespec end_time;
        long long int nanoseconds_elapsed;

        if(node_rank == 0) {
            clock_gettime(CLOCK_REALTIME, &start_time);
            for(int i = 0; i < num_reruns; ++i) {
                // write the entire buffer
                res.post_remote_write(0, size);
                // poll for completion
                verbs_poll_completion();
            }
            clock_gettime(CLOCK_REALTIME, &end_time);
            nanoseconds_elapsed = (end_time.tv_sec - start_time.tv_sec) * 1000000000 + (end_time.tv_nsec - start_time.tv_nsec);
            fout << size << " " << (nanoseconds_elapsed + 0.0) / (1000 * num_reruns) << endl;
            free(write_buf);
            free(read_buf);
        }
	sync (r_index);
    }
    sync(r_index);
    fout.close();
    return 0;
}
<commit_msg>Carried out the experiments and got the results<commit_after>#include <fstream>
#include <iostream>
#include <map>

#include "sst/verbs.h"

using std::ofstream;
using std::map;
using std::cin;
using std::cout;
using std::endl;
using std::string;

using namespace sst;

// number of reruns
long long int num_reruns = 10000;

int main() {
    ofstream fout;
    fout.open("data_write_avg_time", ofstream::app);

    cout << "FOR THIS EXPERIMENT TO WORK, DO NOT START THE POLLING THREAD!!!" << endl;

    // input number of nodes and the local node id
    int num_nodes, node_rank;
    cin >> node_rank;
    cin >> num_nodes;

    // input the ip addresses
    map<uint32_t, string> ip_addrs;
    for(int i = 0; i < num_nodes; ++i) {
        cin >> ip_addrs[i];
    }

    // initialize the rdma resources
    verbs_initialize(ip_addrs, node_rank);

    int r_index = num_nodes - 1 - node_rank;
    for(int size = 1; size <= 10000; ++size) {
        // create buffer for write and read
        char *write_buf, *read_buf;
        write_buf = (char *)malloc(size);
        read_buf = (char *)malloc(size);

        resources res(r_index, read_buf, write_buf, size, size);

        // start the timing experiment
        struct timespec start_time;
        struct timespec end_time;
        long long int nanoseconds_elapsed;

        if(node_rank == 0) {
            clock_gettime(CLOCK_REALTIME, &start_time);
            for(int i = 0; i < num_reruns; ++i) {
                // write the entire buffer
                res.post_remote_write_with_completion(0, size);
                // poll for completion
                verbs_poll_completion();
            }
            clock_gettime(CLOCK_REALTIME, &end_time);
            nanoseconds_elapsed = (end_time.tv_sec - start_time.tv_sec) * 1000000000 + (end_time.tv_nsec - start_time.tv_nsec);
            fout << size << " " << (nanoseconds_elapsed + 0.0) / (1000 * num_reruns) << endl;
            free(write_buf);
            free(read_buf);
        }
	sync (r_index);
    }
    sync(r_index);
    fout.close();
    return 0;
}
<|endoftext|>


<commit_before>//
// MIT License
//
// Copyright (c) 2017 Thibault Martinez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//

#include <unordered_map>
#include "Keccak384.hpp"
#include "gtest/gtest.h"

static std::unordered_map<std::string, std::string> hashes = {
  { "Message",
    "0c8d6ff6e6a1cf18a0d55b20f0bca160d0d1c914"
    "a5e842f3707a25eeb20a279f6b4e83eda8e43a67"
    "697832c7f69f53ca" },
  { "Keccak-384",
    "924bd16d2ae40f6b93d58f488002de88f9288a75"
    "986c60944005e99b55fec03b1f55ff91186142c6"
    "4c2547de5a85815e" },
  { "IOTA",
    "7ea0e8132692844c737a527baedb3045900d8ef7"
    "102e4aaec87c47450717c0cfa7b23db6429e8359"
    "09ca4393c5a171d5" },
  { "Crypto",
    "29c016cf4476900cc2d17e3255137f45af2e4836"
    "ac8281bf6f6d76978dec2926c386723b7bf65e73"
    "01b5a062686bd227" },
  { "Input",
    "fad2b6d11d8b32a8554775321441091eecbe13fc"
    "3aa4f835eb81449303d8bd8f0407838bc265a4cf"
    "60261133e4da9a22" },
  { "Tangle",
    "5c7685f3c667c8a2c44d6d85174af11c57bbf9c7"
    "6260af885588e6bcd05b8e485de284e24c3614c0"
    "3f9072b5f67675bd" },
  { "Hash",
    "b6cea85560278fa023f1ceea13b434c45d223529e8c6760473c2f6f6a9f2c566aa0407d6ada26256945a595bfe07df"
    "c6" },
  { "b6cea85560278fa023f1ceea13b434c45d223529e8c6760473c2f6f6a9f2c566aa0407d6ada26256945a595bfe07df"
    "c6",
    "674d7600f0596b2074a19c6eb5ef785d5fc6a1e1b7af81cd776eb1296e1e10de7f11926be182509538f2eb5225e3d6"
    "2a" },
  { "674d7600f0596b2074a19c6eb5ef785d5fc6a1e1b7af81cd776eb1296e1e10de7f11926be182509538f2eb5225e3d6"
    "2a",
    "1d48d470066949b60ad2a0929be916f4e32743cbeba99bcb7178e5ee46f6ed6ee513e26c812a8a16ec8210cfa51556"
    "8f" },
  { "1d48d470066949b60ad2a0929be916f4e32743cbeba99bcb7178e5ee46f6ed6ee513e26c812a8a16ec8210cfa51556"
    "8f",
    "2ed08bff9d7d000275911940152c7f7ab5b05b36be1904004eef366f63febde86b0bf86de8ea4a8896f2fbb8427d35"
    "c1" },
  { "2ed08bff9d7d000275911940152c7f7ab5b05b36be1904004eef366f63febde86b0bf86de8ea4a8896f2fbb8427d35"
    "c1",
    "3fa3a52ad49e76a3545f7e8d19fa2a328637dc017357729f465a03d91e7e6d5a1cb923a737a76752eeecd5c4ad73f7"
    "49" }
};

TEST(Keccak384Test, Hash) {
  IOTA::Crypto::Keccak384 k;

  for (auto& input : hashes) {
    std::vector<int8_t> vinput(std::begin(input.first), std::end(input.first));
    k.update(vinput);
    EXPECT_EQ(input.second, k.digest());
    k.reset();
  }
}
<commit_msg>Keccak384 tests<commit_after>//
// MIT License
//
// Copyright (c) 2017 Thibault Martinez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//

#include <fstream>
#include "Keccak384.hpp"
#include "gtest/gtest.h"

TEST(Keccak384Test, digest) {
  std::ifstream file("/root/iota.lib.cpp/test/files/keccak384");
  std::string   line;
  ASSERT_TRUE(file.is_open());
  IOTA::Crypto::Keccak384 k;
  while (std::getline(file, line)) {
    auto                semicolon = line.find(';');
    auto                input     = line.substr(0, semicolon);
    auto                digest    = line.substr(semicolon + 1);
    std::vector<int8_t> vinput(std::begin(input), std::end(input));
    k.update(vinput);
    EXPECT_EQ(digest, k.digest());
    k.reset();
  }
}
<|endoftext|>


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

#include "xwalk/test/base/xwalk_test_suite.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/stats_table.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "xwalk/runtime/browser/xwalk_content_browser_client.h"
#include "xwalk/runtime/common/xwalk_content_client.h"
#include "xwalk/runtime/common/xwalk_paths.h"
#include "content/public/test/test_launcher.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/resource/resource_handle.h"

#if defined(OS_POSIX)
#include "base/memory/shared_memory.h"
#endif

namespace {

void RemoveSharedMemoryFile(const std::string& filename) {
  // Stats uses SharedMemory under the hood. On posix, this results in a file
  // on disk.
#if defined(OS_POSIX)
  base::SharedMemory memory;
  memory.Delete(filename);
#endif
}

class XWalkTestSuiteInitializer : public testing::EmptyTestEventListener {
 public:
  XWalkTestSuiteInitializer() {
  }

  virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE {
    content_client_.reset(new xwalk::XWalkContentClient);
    content::SetContentClient(content_client_.get());

    browser_content_client_.reset(new xwalk::XWalkContentBrowserClient());
    SetBrowserClientForTesting(browser_content_client_.get());
  }

  virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE {
    browser_content_client_.reset();
    content_client_.reset();
    content::SetContentClient(NULL);
  }

 private:
  scoped_ptr<xwalk::XWalkContentClient> content_client_;
  scoped_ptr<xwalk::XWalkContentBrowserClient> browser_content_client_;

  DISALLOW_COPY_AND_ASSIGN(XWalkTestSuiteInitializer);
};

}  // namespace

XWalkTestSuite::XWalkTestSuite(int argc, char** argv)
    : content::ContentTestSuiteBase(argc, argv) {
}

XWalkTestSuite::~XWalkTestSuite() {
}

void XWalkTestSuite::Initialize() {
  xwalk::RegisterPathProvider();

  // Initialize after overriding paths as some content paths depend on correct
  // values for DIR_EXE and DIR_MODULE.
  content::ContentTestSuiteBase::Initialize();

  base::FilePath pak_dir;
  PathService::Get(base::DIR_MODULE, &pak_dir);
  DCHECK(!pak_dir.empty());
  base::FilePath resources_pack_path;
  resources_pack_path = pak_dir.Append(FILE_PATH_LITERAL("xwalk.pak"));
  ui::ResourceBundle::InitSharedInstanceWithPakPath(resources_pack_path);

  stats_filename_ = base::StringPrintf("unit_tests-%d",
                                       ::base::GetCurrentProcId());
  RemoveSharedMemoryFile(stats_filename_);
  stats_table_.reset(new base::StatsTable(stats_filename_, 20, 200));
  base::StatsTable::set_current(stats_table_.get());

  testing::TestEventListeners& listeners =
      testing::UnitTest::GetInstance()->listeners();
  listeners.Append(new XWalkTestSuiteInitializer);
}

content::ContentClient* XWalkTestSuite::CreateClientForInitialization() {
  return new xwalk::XWalkContentClient();
}

void XWalkTestSuite::Shutdown() {
  ResourceBundle::CleanupSharedInstance();

  base::StatsTable::set_current(NULL);
  stats_table_.reset();
  RemoveSharedMemoryFile(stats_filename_);

  base::TestSuite::Shutdown();
}
<commit_msg>Fix build for Windows.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/test/base/xwalk_test_suite.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/stats_table.h"
#include "base/path_service.h"
#include "base/process/process_handle.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "xwalk/runtime/browser/xwalk_content_browser_client.h"
#include "xwalk/runtime/common/xwalk_content_client.h"
#include "xwalk/runtime/common/xwalk_paths.h"
#include "content/public/test/test_launcher.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/resource/resource_handle.h"

#if defined(OS_POSIX)
#include "base/memory/shared_memory.h"
#endif

namespace {

void RemoveSharedMemoryFile(const std::string& filename) {
  // Stats uses SharedMemory under the hood. On posix, this results in a file
  // on disk.
#if defined(OS_POSIX)
  base::SharedMemory memory;
  memory.Delete(filename);
#endif
}

class XWalkTestSuiteInitializer : public testing::EmptyTestEventListener {
 public:
  XWalkTestSuiteInitializer() {
  }

  virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE {
    content_client_.reset(new xwalk::XWalkContentClient);
    content::SetContentClient(content_client_.get());

    browser_content_client_.reset(new xwalk::XWalkContentBrowserClient());
    SetBrowserClientForTesting(browser_content_client_.get());
  }

  virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE {
    browser_content_client_.reset();
    content_client_.reset();
    content::SetContentClient(NULL);
  }

 private:
  scoped_ptr<xwalk::XWalkContentClient> content_client_;
  scoped_ptr<xwalk::XWalkContentBrowserClient> browser_content_client_;

  DISALLOW_COPY_AND_ASSIGN(XWalkTestSuiteInitializer);
};

}  // namespace

XWalkTestSuite::XWalkTestSuite(int argc, char** argv)
    : content::ContentTestSuiteBase(argc, argv) {
}

XWalkTestSuite::~XWalkTestSuite() {
}

void XWalkTestSuite::Initialize() {
  xwalk::RegisterPathProvider();

  // Initialize after overriding paths as some content paths depend on correct
  // values for DIR_EXE and DIR_MODULE.
  content::ContentTestSuiteBase::Initialize();

  base::FilePath pak_dir;
  PathService::Get(base::DIR_MODULE, &pak_dir);
  DCHECK(!pak_dir.empty());
  base::FilePath resources_pack_path;
  resources_pack_path = pak_dir.Append(FILE_PATH_LITERAL("xwalk.pak"));
  ui::ResourceBundle::InitSharedInstanceWithPakPath(resources_pack_path);

  stats_filename_ = base::StringPrintf("unit_tests-%d",
                                       base::GetCurrentProcId());
  RemoveSharedMemoryFile(stats_filename_);
  stats_table_.reset(new base::StatsTable(stats_filename_, 20, 200));
  base::StatsTable::set_current(stats_table_.get());

  testing::TestEventListeners& listeners =
      testing::UnitTest::GetInstance()->listeners();
  listeners.Append(new XWalkTestSuiteInitializer);
}

content::ContentClient* XWalkTestSuite::CreateClientForInitialization() {
  return new xwalk::XWalkContentClient();
}

void XWalkTestSuite::Shutdown() {
  ResourceBundle::CleanupSharedInstance();

  base::StatsTable::set_current(NULL);
  stats_table_.reset();
  RemoveSharedMemoryFile(stats_filename_);

  base::TestSuite::Shutdown();
}
<|endoftext|>