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

// This file is meant to override chrome_extensions_dispatch_delegate to provide
// alternate functionality for Brave. It is not a copy and there are significant
// change from Chrome
#include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"

#include <set>
#include <string>
#include "atom/common/javascript_bindings.h"
#include "atom/grit/atom_resources.h"  // NOLINT: This file is generated
#include "atom/grit/electron_api_resources.h"  // NOLINT: This file is generated
#include "base/win/windows_version.h"
#include "brave/common/extensions/crash_reporter_bindings.h"
#include "brave/common/extensions/shared_memory_bindings.h"
#include "brave/common/extensions/url_bindings.h"
#include "brave/grit/brave_resources.h"  // NOLINT: This file is generated
#include "brave/renderer/extensions/content_settings_bindings.h"
#include "brave/renderer/extensions/web_frame_bindings.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/grit/renderer_resources.h"  // NOLINT: This file is generated
#include "content/public/common/bindings_policy.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "extensions/common/extension.h"
#include "extensions/renderer/css_native_handler.h"
#include "extensions/renderer/i18n_custom_bindings.h"
#include "extensions/renderer/lazy_background_page_native_handler.h"
#include "extensions/renderer/resource_bundle_source_map.h"
#include "extensions/renderer/v8_helpers.h"
#include "gin/converter.h"
#include "vendor/node/src/node_version.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

using extensions::Manifest;
using extensions::NativeHandler;
using extensions::ScriptContext;
using extensions::v8_helpers::ToV8StringUnsafe;

namespace {

#if defined(OS_MACOSX)
const char* kPlatform = "darwin";
#elif defined(OS_LINUX)
const char* kPlatform = "linux";
#elif defined(OS_WIN)
const char* kPlatform = "win32";
#else
const char* kPlatform = "unknown";
#endif

v8::Local<v8::Value> GetOrCreateProcess(ScriptContext* context) {
  v8::Local<v8::String> process_string(
      v8::String::NewFromUtf8(context->isolate(), "process"));
  v8::Local<v8::Object> global(context->v8_context()->Global());
  v8::Local<v8::Value> process(global->Get(process_string));
  if (process->IsUndefined()) {
    process = v8::Object::New(context->isolate());
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "type"),
        ToV8StringUnsafe(context->isolate(), "renderer"));
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "version"),
        ToV8StringUnsafe(context->isolate(), NODE_VERSION_STRING));
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "platform"),
        ToV8StringUnsafe(context->isolate(), kPlatform));
#if defined(OS_WIN)
    switch (base::win::GetVersion()) {
      case base::win::VERSION_WIN7:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win7"));
          break;
      case base::win::VERSION_WIN8:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win8"));
          break;
      case base::win::VERSION_WIN8_1:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win8_1"));
          break;
      case base::win::VERSION_WIN10:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win10"));
          break;
      case base::win::VERSION_WIN10_TH2:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win10_th2"));
          break;
      default:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), ""));
        break;
    }
#else
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "platformVersion"),
        ToV8StringUnsafe(context->isolate(), ""));
#endif
    // TODO(bridiver) - add a function to return env vars
    // std::unique_ptr<base::Environment> env(base::Environment::Create());
    // gin::SetProperty(context->isolate(), process.As<v8::Object>(),
    //     ToV8StringUnsafe(context->isolate(), "env"),
    //     ToV8StringUnsafe(context->isolate(), "TODO"));
    global->Set(process_string, process);
  }

  return process;
}

// Returns |value| cast to an object if possible, else an empty handle.
v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
  return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
}

}

ChromeExtensionsDispatcherDelegate::ChromeExtensionsDispatcherDelegate() {
}

ChromeExtensionsDispatcherDelegate::~ChromeExtensionsDispatcherDelegate() {
}

void ChromeExtensionsDispatcherDelegate::InitOriginPermissions(
    const extensions::Extension* extension,
    bool is_extension_active) {
}

void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
    extensions::Dispatcher* dispatcher,
    extensions::ModuleSystem* module_system,
    extensions::ExtensionBindingsSystem* bindings_system,
    extensions::ScriptContext* context) {
  module_system->RegisterNativeHandler(
      "atom",
      std::unique_ptr<NativeHandler>(
          new atom::JavascriptBindings(
              context->GetRenderFrame()->GetRenderView(), context)));
  module_system->RegisterNativeHandler(
      "contentSettings",
      std::unique_ptr<NativeHandler>(
          new brave::ContentSettingsBindings(context)));
  module_system->RegisterNativeHandler(
      "webFrame",
      std::unique_ptr<NativeHandler>(
          new brave::WebFrameBindings(context)));

  // The following are native handlers that are defined in //extensions, but
  // are only used for APIs defined in Chrome.
  // See chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
  module_system->RegisterNativeHandler(
      "i18n", std::unique_ptr<NativeHandler>(
                  new extensions::I18NCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "lazy_background_page",
      std::unique_ptr<NativeHandler>(
          new extensions::LazyBackgroundPageNativeHandler(context)));
  module_system->RegisterNativeHandler(
      "css_natives", std::unique_ptr<NativeHandler>(
                         new extensions::CssNativeHandler(context)));

}

void ChromeExtensionsDispatcherDelegate::PopulateSourceMap(
    extensions::ResourceBundleSourceMap* source_map) {
  // TODO(bridiver) - add a permission for these
  // so only component extensions can use
  // blessed extension??
  source_map->RegisterSource("event_emitter", IDR_ATOM_EVENT_EMITTER_JS);
  source_map->RegisterSource("ipcRenderer", IDR_BRAVE_IPC_RENDERER_JS);
  source_map->RegisterSource("ipc_utils", IDR_ATOM_IPC_INTERNAL_JS);
  source_map->RegisterSource("webFrame",
                             IDR_ATOM_WEB_FRAME_BINDINGS_JS);
  source_map->RegisterSource("remote",
                              IDR_ELECTRON_REMOTE_BINDINGS_JS);
  source_map->RegisterSource("base64-js",
                              IDR_ELECTRON_BASE64_JS_BINDINGS_JS);
  source_map->RegisterSource("buffer",
                              IDR_ELECTRON_BUFFER_BINDINGS_JS);
  source_map->RegisterSource("ieee754",
                              IDR_ELECTRON_IEEE754_BINDINGS_JS);
  source_map->RegisterSource("is-promise",
                              IDR_ELECTRON_IS_PROMISE_BINDINGS_JS);
  source_map->RegisterSource("callbacks-registry",
                              IDR_ELECTRON_CALLBACKS_REGISTRY_BINDINGS_JS);
  source_map->RegisterSource("guest-view-internal",
                              IDR_ELECTRON_GUEST_VIEW_INTERNAL_BINDINGS_JS);
  source_map->RegisterSource("browserAction",
                             IDR_ATOM_BROWSER_ACTION_BINDINGS_JS);
  source_map->RegisterSource("permissions", IDR_ATOM_PERMISSIONS_BINDINGS_JS);
  source_map->RegisterSource("privacy", IDR_ATOM_PRIVACY_BINDINGS_JS);
  source_map->RegisterSource("tabs",
                             IDR_ATOM_TABS_BINDINGS_JS);
  source_map->RegisterSource("contextMenus",
                             IDR_ATOM_CONTEXT_MENUS_BINDINGS_JS);
  source_map->RegisterSource("contentSettings",
                             IDR_ATOM_CONTENT_SETTINGS_BINDINGS_JS);
  source_map->RegisterSource("windows",
                             IDR_ATOM_WINDOWS_BINDINGS_JS);
  source_map->RegisterSource("cookies",
                             IDR_ATOM_COOKIES_BINDINGS_JS);
  source_map->RegisterSource("protocol",
                             IDR_ATOM_PROTOCOL_BINDINGS_JS);
  source_map->RegisterSource("ChromeSetting", IDR_CHROME_SETTING_JS);
  source_map->RegisterSource("ContentSetting", IDR_CONTENT_SETTING_JS);
  source_map->RegisterSource("ChromeDirectSetting",
                             IDR_CHROME_DIRECT_SETTING_JS);
  source_map->RegisterSource("webViewInternal",
      IDR_ATOM_WEB_VIEW_INTERNAL_BINDINGS_JS);
  source_map->RegisterSource("tabViewInternal",
      IDR_ATOM_TAB_VIEW_INTERNAL_BINDINGS_JS);
  source_map->RegisterSource("webViewApiMethods",
      IDR_ATOM_WEB_VIEW_API_BINDINGS_JS);
  source_map->RegisterSource("webViewEventsApiMethods",
      IDR_ATOM_WEB_VIEW_EVENTS_API_BINDINGS_JS);
  source_map->RegisterSource("guestViewApiMethods",
      IDR_ATOM_GUEST_VIEW_API_BINDINGS_JS);
}

void ChromeExtensionsDispatcherDelegate::RequireAdditionalModules(
    extensions::ScriptContext* context) {
  extensions::ModuleSystem* module_system = context->module_system();
  extensions::Feature::Context context_type = context->context_type();

  if (context_type == extensions::Feature::WEBUI_CONTEXT) {
    module_system->Require("webView");
    module_system->Require("tabViewInternal");
    module_system->Require("webViewInternal");
    module_system->Require("webViewApiMethods");
    module_system->Require("webViewAttributes");
    module_system->Require("webViewEventsApiMethods");
    module_system->Require("guestViewApiMethods");
  }

  if (context_type == extensions::Feature::WEBUI_CONTEXT ||
      (context->extension() && context->extension()->is_extension() &&
        Manifest::IsComponentLocation(context->extension()->location()))) {
    v8::Local<v8::Object> process =
        AsObjectOrEmpty(GetOrCreateProcess(context));
    v8::Local<v8::Object> global = context->v8_context()->Global();
    v8::Local<v8::Object> muon = v8::Object::New(context->isolate());
    global->Set(v8::String::NewFromUtf8(context->isolate(), "muon"), muon);

    v8::Local<v8::Object> url =
        brave::URLBindings::API(context);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "url"), url);

    v8::Local<v8::Object> shared_memory =
        brave::SharedMemoryBindings::API(context);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "shared_memory"),
        shared_memory);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "sharedMemory"),
        shared_memory);

    v8::Local<v8::Object> crash_reporter =
        brave::CrashReporterBindings::API(context);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "crashReporter"),
        crash_reporter);
  }
}

void ChromeExtensionsDispatcherDelegate::OnActiveExtensionsUpdated(
    const std::set<std::string>& extension_ids) {
  crash_keys::SetActiveExtensions(extension_ids);
}

void ChromeExtensionsDispatcherDelegate::InitializeBindingsSystem(
    extensions::Dispatcher* dispatcher,
    extensions::APIBindingsSystem* bindings_system) {}
<commit_msg>ChromeDirectSettings was removed<commit_after>// Copyright 2016 The Brave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file is meant to override chrome_extensions_dispatch_delegate to provide
// alternate functionality for Brave. It is not a copy and there are significant
// change from Chrome
#include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"

#include <set>
#include <string>
#include "atom/common/javascript_bindings.h"
#include "atom/grit/atom_resources.h"  // NOLINT: This file is generated
#include "atom/grit/electron_api_resources.h"  // NOLINT: This file is generated
#include "base/win/windows_version.h"
#include "brave/common/extensions/crash_reporter_bindings.h"
#include "brave/common/extensions/shared_memory_bindings.h"
#include "brave/common/extensions/url_bindings.h"
#include "brave/grit/brave_resources.h"  // NOLINT: This file is generated
#include "brave/renderer/extensions/content_settings_bindings.h"
#include "brave/renderer/extensions/web_frame_bindings.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/grit/renderer_resources.h"  // NOLINT: This file is generated
#include "content/public/common/bindings_policy.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "extensions/common/extension.h"
#include "extensions/renderer/css_native_handler.h"
#include "extensions/renderer/i18n_custom_bindings.h"
#include "extensions/renderer/lazy_background_page_native_handler.h"
#include "extensions/renderer/resource_bundle_source_map.h"
#include "extensions/renderer/v8_helpers.h"
#include "gin/converter.h"
#include "vendor/node/src/node_version.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

using extensions::Manifest;
using extensions::NativeHandler;
using extensions::ScriptContext;
using extensions::v8_helpers::ToV8StringUnsafe;

namespace {

#if defined(OS_MACOSX)
const char* kPlatform = "darwin";
#elif defined(OS_LINUX)
const char* kPlatform = "linux";
#elif defined(OS_WIN)
const char* kPlatform = "win32";
#else
const char* kPlatform = "unknown";
#endif

v8::Local<v8::Value> GetOrCreateProcess(ScriptContext* context) {
  v8::Local<v8::String> process_string(
      v8::String::NewFromUtf8(context->isolate(), "process"));
  v8::Local<v8::Object> global(context->v8_context()->Global());
  v8::Local<v8::Value> process(global->Get(process_string));
  if (process->IsUndefined()) {
    process = v8::Object::New(context->isolate());
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "type"),
        ToV8StringUnsafe(context->isolate(), "renderer"));
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "version"),
        ToV8StringUnsafe(context->isolate(), NODE_VERSION_STRING));
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "platform"),
        ToV8StringUnsafe(context->isolate(), kPlatform));
#if defined(OS_WIN)
    switch (base::win::GetVersion()) {
      case base::win::VERSION_WIN7:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win7"));
          break;
      case base::win::VERSION_WIN8:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win8"));
          break;
      case base::win::VERSION_WIN8_1:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win8_1"));
          break;
      case base::win::VERSION_WIN10:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win10"));
          break;
      case base::win::VERSION_WIN10_TH2:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), "win10_th2"));
          break;
      default:
        gin::SetProperty(context->isolate(), process.As<v8::Object>(),
          ToV8StringUnsafe(context->isolate(), "platformVersion"),
          ToV8StringUnsafe(context->isolate(), ""));
        break;
    }
#else
    gin::SetProperty(context->isolate(), process.As<v8::Object>(),
        ToV8StringUnsafe(context->isolate(), "platformVersion"),
        ToV8StringUnsafe(context->isolate(), ""));
#endif
    // TODO(bridiver) - add a function to return env vars
    // std::unique_ptr<base::Environment> env(base::Environment::Create());
    // gin::SetProperty(context->isolate(), process.As<v8::Object>(),
    //     ToV8StringUnsafe(context->isolate(), "env"),
    //     ToV8StringUnsafe(context->isolate(), "TODO"));
    global->Set(process_string, process);
  }

  return process;
}

// Returns |value| cast to an object if possible, else an empty handle.
v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
  return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
}

}

ChromeExtensionsDispatcherDelegate::ChromeExtensionsDispatcherDelegate() {
}

ChromeExtensionsDispatcherDelegate::~ChromeExtensionsDispatcherDelegate() {
}

void ChromeExtensionsDispatcherDelegate::InitOriginPermissions(
    const extensions::Extension* extension,
    bool is_extension_active) {
}

void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
    extensions::Dispatcher* dispatcher,
    extensions::ModuleSystem* module_system,
    extensions::ExtensionBindingsSystem* bindings_system,
    extensions::ScriptContext* context) {
  module_system->RegisterNativeHandler(
      "atom",
      std::unique_ptr<NativeHandler>(
          new atom::JavascriptBindings(
              context->GetRenderFrame()->GetRenderView(), context)));
  module_system->RegisterNativeHandler(
      "contentSettings",
      std::unique_ptr<NativeHandler>(
          new brave::ContentSettingsBindings(context)));
  module_system->RegisterNativeHandler(
      "webFrame",
      std::unique_ptr<NativeHandler>(
          new brave::WebFrameBindings(context)));

  // The following are native handlers that are defined in //extensions, but
  // are only used for APIs defined in Chrome.
  // See chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
  module_system->RegisterNativeHandler(
      "i18n", std::unique_ptr<NativeHandler>(
                  new extensions::I18NCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "lazy_background_page",
      std::unique_ptr<NativeHandler>(
          new extensions::LazyBackgroundPageNativeHandler(context)));
  module_system->RegisterNativeHandler(
      "css_natives", std::unique_ptr<NativeHandler>(
                         new extensions::CssNativeHandler(context)));

}

void ChromeExtensionsDispatcherDelegate::PopulateSourceMap(
    extensions::ResourceBundleSourceMap* source_map) {
  // TODO(bridiver) - add a permission for these
  // so only component extensions can use
  // blessed extension??
  source_map->RegisterSource("event_emitter", IDR_ATOM_EVENT_EMITTER_JS);
  source_map->RegisterSource("ipcRenderer", IDR_BRAVE_IPC_RENDERER_JS);
  source_map->RegisterSource("ipc_utils", IDR_ATOM_IPC_INTERNAL_JS);
  source_map->RegisterSource("webFrame",
                             IDR_ATOM_WEB_FRAME_BINDINGS_JS);
  source_map->RegisterSource("remote",
                              IDR_ELECTRON_REMOTE_BINDINGS_JS);
  source_map->RegisterSource("base64-js",
                              IDR_ELECTRON_BASE64_JS_BINDINGS_JS);
  source_map->RegisterSource("buffer",
                              IDR_ELECTRON_BUFFER_BINDINGS_JS);
  source_map->RegisterSource("ieee754",
                              IDR_ELECTRON_IEEE754_BINDINGS_JS);
  source_map->RegisterSource("is-promise",
                              IDR_ELECTRON_IS_PROMISE_BINDINGS_JS);
  source_map->RegisterSource("callbacks-registry",
                              IDR_ELECTRON_CALLBACKS_REGISTRY_BINDINGS_JS);
  source_map->RegisterSource("guest-view-internal",
                              IDR_ELECTRON_GUEST_VIEW_INTERNAL_BINDINGS_JS);
  source_map->RegisterSource("browserAction",
                             IDR_ATOM_BROWSER_ACTION_BINDINGS_JS);
  source_map->RegisterSource("permissions", IDR_ATOM_PERMISSIONS_BINDINGS_JS);
  source_map->RegisterSource("privacy", IDR_ATOM_PRIVACY_BINDINGS_JS);
  source_map->RegisterSource("tabs",
                             IDR_ATOM_TABS_BINDINGS_JS);
  source_map->RegisterSource("contextMenus",
                             IDR_ATOM_CONTEXT_MENUS_BINDINGS_JS);
  source_map->RegisterSource("contentSettings",
                             IDR_ATOM_CONTENT_SETTINGS_BINDINGS_JS);
  source_map->RegisterSource("windows",
                             IDR_ATOM_WINDOWS_BINDINGS_JS);
  source_map->RegisterSource("cookies",
                             IDR_ATOM_COOKIES_BINDINGS_JS);
  source_map->RegisterSource("protocol",
                             IDR_ATOM_PROTOCOL_BINDINGS_JS);
  source_map->RegisterSource("ChromeSetting", IDR_CHROME_SETTING_JS);
  source_map->RegisterSource("ContentSetting", IDR_CONTENT_SETTING_JS);
  source_map->RegisterSource("EasyUnlockProximityRequired",
                             IDR_EASY_UNLOCK_PROXIMITY_REQUIRED_JS);
  source_map->RegisterSource("webViewInternal",
      IDR_ATOM_WEB_VIEW_INTERNAL_BINDINGS_JS);
  source_map->RegisterSource("tabViewInternal",
      IDR_ATOM_TAB_VIEW_INTERNAL_BINDINGS_JS);
  source_map->RegisterSource("webViewApiMethods",
      IDR_ATOM_WEB_VIEW_API_BINDINGS_JS);
  source_map->RegisterSource("webViewEventsApiMethods",
      IDR_ATOM_WEB_VIEW_EVENTS_API_BINDINGS_JS);
  source_map->RegisterSource("guestViewApiMethods",
      IDR_ATOM_GUEST_VIEW_API_BINDINGS_JS);
}

void ChromeExtensionsDispatcherDelegate::RequireAdditionalModules(
    extensions::ScriptContext* context) {
  extensions::ModuleSystem* module_system = context->module_system();
  extensions::Feature::Context context_type = context->context_type();

  if (context_type == extensions::Feature::WEBUI_CONTEXT) {
    module_system->Require("webView");
    module_system->Require("tabViewInternal");
    module_system->Require("webViewInternal");
    module_system->Require("webViewApiMethods");
    module_system->Require("webViewAttributes");
    module_system->Require("webViewEventsApiMethods");
    module_system->Require("guestViewApiMethods");
  }

  if (context_type == extensions::Feature::WEBUI_CONTEXT ||
      (context->extension() && context->extension()->is_extension() &&
        Manifest::IsComponentLocation(context->extension()->location()))) {
    v8::Local<v8::Object> process =
        AsObjectOrEmpty(GetOrCreateProcess(context));
    v8::Local<v8::Object> global = context->v8_context()->Global();
    v8::Local<v8::Object> muon = v8::Object::New(context->isolate());
    global->Set(v8::String::NewFromUtf8(context->isolate(), "muon"), muon);

    v8::Local<v8::Object> url =
        brave::URLBindings::API(context);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "url"), url);

    v8::Local<v8::Object> shared_memory =
        brave::SharedMemoryBindings::API(context);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "shared_memory"),
        shared_memory);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "sharedMemory"),
        shared_memory);

    v8::Local<v8::Object> crash_reporter =
        brave::CrashReporterBindings::API(context);
    muon->Set(v8::String::NewFromUtf8(context->isolate(), "crashReporter"),
        crash_reporter);
  }
}

void ChromeExtensionsDispatcherDelegate::OnActiveExtensionsUpdated(
    const std::set<std::string>& extension_ids) {
  crash_keys::SetActiveExtensions(extension_ids);
}

void ChromeExtensionsDispatcherDelegate::InitializeBindingsSystem(
    extensions::Dispatcher* dispatcher,
    extensions::APIBindingsSystem* bindings_system) {}
<|endoftext|>


<commit_before>//This is undocumented  COM magic.  Including this here should be sufficient for most of the library, but maybe not.
#include <initguid.h>
#include "wasapi.hpp"
#include <audio_io/private/audio_outputs.hpp>
#include <audio_io/private/single_threaded_apartment.hpp>
#include <windows.h>
#include <audioclient.h>
#include <mmdeviceapi.h>
#include <functiondiscoverykeys_devpkey.h>

namespace audio_io {
namespace implementation {

WasapiOutputDeviceFactory::WasapiOutputDeviceFactory() {
	APARTMENTCALL(CoCreateInstance, CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&enumerator);
	//todo: errors.
	rescan();
}

WasapiOutputDeviceFactory::~WasapiOutputDeviceFactory() {
	if(enumerator) enumerator->Release();
}

std::vector<std::string> WasapiOutputDeviceFactory::getOutputNames() {
	return names;
}

std::vector<int> WasapiOutputDeviceFactory::getOutputMaxChannels() {
	return max_channels;
}

std::shared_ptr<OutputDevice> WasapiOutputDeviceFactory::createDevice(std::function<void(float*, int)> callback, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) {
	HRESULT res;
	IMMDevice* dev;
	if(index == -1) res = APARTMENTCALL(enumerator->GetDefaultAudioEndpoint, eRender, eMultimedia, &dev);
	else res = APARTMENTCALL(enumerator->GetDevice, ids_to_id_strings[index].c_str(), &dev);
	//Proper error handling!
	if(res != S_OK) return nullptr;
	return std::make_shared<WasapiOutputDevice>(callback, dev, blockSize, channels, sr, mixAhead);
}

unsigned int WasapiOutputDeviceFactory::getOutputCount() {
	return names.size();
}

std::string WasapiOutputDeviceFactory::getName() {
	return "Wasapi";
}

void WasapiOutputDeviceFactory::rescan() {
	names.clear();
	max_channels.clear();
	ids_to_id_strings.clear();
	IMMDeviceCollection *collection;
	enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection);
	UINT count;
	collection->GetCount(&count);
	for(UINT i = 0; i < count; i++) {
		std::wstring identifierString;
		int channels;
		IMMDevice *device;
		collection->Item(i, &device);
		//We have to open the property store and use it to get the informationh.
		IPropertyStore *properties;
		device->OpenPropertyStore(STGM_READ, &properties);
		PROPVARIANT prop;
		properties->GetValue(PKEY_AudioEngine_DeviceFormat, &prop);
		WAVEFORMATEX *format = (WAVEFORMATEX*)prop.blob.pBlobData;
		channels = format->nChannels;
		//Easy string is the identifier.
		LPWSTR identifier;
		device->GetId(&identifier);
		identifierString = std::wstring(identifier);
		CoTaskMemFree(identifier);
		properties->GetValue(PKEY_DeviceInterface_FriendlyName, &prop);
		LPWSTR rawname = prop.pwszVal;
		char* utf8Name;
		int length = WideCharToMultiByte(CP_UTF8, 0, rawname, -1, NULL, 0, NULL, NULL);
		//MSDN is unclear if we get a null, so we make sure to add one.
		utf8Name = new char[length]();
		length = WideCharToMultiByte(CP_UTF8, 0, rawname, -1, utf8Name, length, NULL, NULL);
		utf8Name[length] = '\0';
		auto name = std::string(utf8Name);
		this->max_channels.push_back(channels);
		names.push_back(name);
		ids_to_id_strings[i] = identifierString;
	}
}

OutputDeviceFactory* createWasapiOutputDeviceFactory() {
	//In order to determine if we have Wasapi, we attempt to open and close the default output device without error.
	try {
		SingleThreadedApartment sta;
		IMMDeviceEnumerator* enumerator = nullptr;
		IMMDevice *default_device = nullptr;
		IAudioClient* client = nullptr;
		auto res = sta.callInApartment(CoCreateInstance, CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&enumerator);
		if(IS_ERROR(res)) return nullptr;
		//Attempt to get the default device.
		res = APARTMENTCALL(enumerator->GetDefaultAudioEndpoint, eRender, eMultimedia, &default_device);
		if(IS_ERROR(res)) {
			enumerator->Release();
			return nullptr;
		}
		res = APARTMENTCALL(default_device->Activate, IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&client);
		if(IS_ERROR(res)) {
			default_device->Release();
			enumerator->Release();
			return nullptr;
		}
		//We now have an IAudioClient.  We can attempt to initialize it with the default mixer format in shared mode, which is supposed to always be accepted.
		WAVEFORMATEX *format = nullptr;
		res = APARTMENTCALL(client->GetMixFormat, &format);
		if(IS_ERROR(res)) {
			client->Release();
			default_device->Release();
			enumerator->Release();
			return nullptr;
		}
		//1e6 nanoseconds in a millisecond.
		//We don't request a specific buffer length, we just want to know if we can open and otherwise don't care.
		res = APARTMENTCALL(client->Initialize, AUDCLNT_SHAREMODE_SHARED, 0, 0, 0, format, NULL);
		if(IS_ERROR(res)) {
			client->Release();
			default_device->Release();
			enumerator->Release();
			return nullptr;
		}
		client->Release();
		default_device->Release();
		enumerator->Release();
		return new WasapiOutputDeviceFactory();
	}
	catch(...) {
		return nullptr;
	}
	return nullptr;
}

}
}<commit_msg>Register wasapi devices with their factory.<commit_after>//This is undocumented  COM magic.  Including this here should be sufficient for most of the library, but maybe not.
#include <initguid.h>
#include "wasapi.hpp"
#include <audio_io/private/audio_outputs.hpp>
#include <audio_io/private/single_threaded_apartment.hpp>
#include <windows.h>
#include <audioclient.h>
#include <mmdeviceapi.h>
#include <functiondiscoverykeys_devpkey.h>

namespace audio_io {
namespace implementation {

WasapiOutputDeviceFactory::WasapiOutputDeviceFactory() {
	APARTMENTCALL(CoCreateInstance, CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&enumerator);
	//todo: errors.
	rescan();
}

WasapiOutputDeviceFactory::~WasapiOutputDeviceFactory() {
	if(enumerator) enumerator->Release();
}

std::vector<std::string> WasapiOutputDeviceFactory::getOutputNames() {
	return names;
}

std::vector<int> WasapiOutputDeviceFactory::getOutputMaxChannels() {
	return max_channels;
}

std::shared_ptr<OutputDevice> WasapiOutputDeviceFactory::createDevice(std::function<void(float*, int)> callback, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) {
	HRESULT res;
	IMMDevice* dev;
	if(index == -1) res = APARTMENTCALL(enumerator->GetDefaultAudioEndpoint, eRender, eMultimedia, &dev);
	else res = APARTMENTCALL(enumerator->GetDevice, ids_to_id_strings[index].c_str(), &dev);
	//Proper error handling!
	if(res != S_OK) return nullptr;
	auto ret = std::make_shared<WasapiOutputDevice>(callback, dev, blockSize, channels, sr, mixAhead);
	created_devices.push_back(ret);
	return ret;
}

unsigned int WasapiOutputDeviceFactory::getOutputCount() {
	return names.size();
}

std::string WasapiOutputDeviceFactory::getName() {
	return "Wasapi";
}

void WasapiOutputDeviceFactory::rescan() {
	names.clear();
	max_channels.clear();
	ids_to_id_strings.clear();
	IMMDeviceCollection *collection;
	enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection);
	UINT count;
	collection->GetCount(&count);
	for(UINT i = 0; i < count; i++) {
		std::wstring identifierString;
		int channels;
		IMMDevice *device;
		collection->Item(i, &device);
		//We have to open the property store and use it to get the informationh.
		IPropertyStore *properties;
		device->OpenPropertyStore(STGM_READ, &properties);
		PROPVARIANT prop;
		properties->GetValue(PKEY_AudioEngine_DeviceFormat, &prop);
		WAVEFORMATEX *format = (WAVEFORMATEX*)prop.blob.pBlobData;
		channels = format->nChannels;
		//Easy string is the identifier.
		LPWSTR identifier;
		device->GetId(&identifier);
		identifierString = std::wstring(identifier);
		CoTaskMemFree(identifier);
		properties->GetValue(PKEY_DeviceInterface_FriendlyName, &prop);
		LPWSTR rawname = prop.pwszVal;
		char* utf8Name;
		int length = WideCharToMultiByte(CP_UTF8, 0, rawname, -1, NULL, 0, NULL, NULL);
		//MSDN is unclear if we get a null, so we make sure to add one.
		utf8Name = new char[length]();
		length = WideCharToMultiByte(CP_UTF8, 0, rawname, -1, utf8Name, length, NULL, NULL);
		utf8Name[length] = '\0';
		auto name = std::string(utf8Name);
		this->max_channels.push_back(channels);
		names.push_back(name);
		ids_to_id_strings[i] = identifierString;
	}
}

OutputDeviceFactory* createWasapiOutputDeviceFactory() {
	//In order to determine if we have Wasapi, we attempt to open and close the default output device without error.
	try {
		SingleThreadedApartment sta;
		IMMDeviceEnumerator* enumerator = nullptr;
		IMMDevice *default_device = nullptr;
		IAudioClient* client = nullptr;
		auto res = sta.callInApartment(CoCreateInstance, CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&enumerator);
		if(IS_ERROR(res)) return nullptr;
		//Attempt to get the default device.
		res = APARTMENTCALL(enumerator->GetDefaultAudioEndpoint, eRender, eMultimedia, &default_device);
		if(IS_ERROR(res)) {
			enumerator->Release();
			return nullptr;
		}
		res = APARTMENTCALL(default_device->Activate, IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&client);
		if(IS_ERROR(res)) {
			default_device->Release();
			enumerator->Release();
			return nullptr;
		}
		//We now have an IAudioClient.  We can attempt to initialize it with the default mixer format in shared mode, which is supposed to always be accepted.
		WAVEFORMATEX *format = nullptr;
		res = APARTMENTCALL(client->GetMixFormat, &format);
		if(IS_ERROR(res)) {
			client->Release();
			default_device->Release();
			enumerator->Release();
			return nullptr;
		}
		//1e6 nanoseconds in a millisecond.
		//We don't request a specific buffer length, we just want to know if we can open and otherwise don't care.
		res = APARTMENTCALL(client->Initialize, AUDCLNT_SHAREMODE_SHARED, 0, 0, 0, format, NULL);
		if(IS_ERROR(res)) {
			client->Release();
			default_device->Release();
			enumerator->Release();
			return nullptr;
		}
		client->Release();
		default_device->Release();
		enumerator->Release();
		return new WasapiOutputDeviceFactory();
	}
	catch(...) {
		return nullptr;
	}
	return nullptr;
}

}
}<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_jvmfwk.hxx"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sal/main.h"
#include "sal/types.h"
#include "osl/thread.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "jvmfwk/framework.h"

using ::rtl::OUString;
using ::rtl::OUStringToOString;
using ::rtl::OString;
#define OUSTR(x) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))

static sal_Bool hasOption(char const * szOption, int argc, char** argv);
static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData);
static bool findAndSelect(JavaInfo**);

#define HELP_TEXT    \
"\njavaldx is necessary to make Java work on some UNIX platforms." \
"It prints a string to std out that consists of directories which " \
"have to be included into the LD_LIBRARY_PATH variable.The setting of " \
"the variable usually occurs in a shell script that runs javaldx.\n" \
"The directories are from the chosen java installation. \n" \
"Options are: \n"\
"--help or -h\n"

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv))
    {
        fprintf(stdout, HELP_TEXT);// default
        return 0;
    }
    javaFrameworkError errcode = JFW_E_NONE;
    sal_Bool bEnabled = sal_False;
    errcode = jfw_getEnabled( & bEnabled);
    if (errcode == JFW_E_NONE && bEnabled == sal_False)
    {
            //Do not do any preparation because that may only slow startup time.
        return 0;
    }
    else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE)
    {
        fprintf(stderr,"javaldx failed! \n");
        return -1;
    }

    JavaInfo * pInfo = NULL;
    errcode = jfw_getSelectedJRE( & pInfo);

    if (errcode == JFW_E_INVALID_SETTINGS)
    {
        fprintf(stderr,"javaldx failed. User must select a JRE from options dialog!");
        return -1;
    }
    else if (errcode != JFW_E_NONE)
    {
        fprintf(stderr,"javaldx failed! \n");
        return -1;
    }

    if (pInfo == NULL)
    {
        if (false == findAndSelect(&pInfo))
            return -1;
    }
    else
    {
        //check if the JRE was not uninstalled
        sal_Bool bExist = sal_False;
        errcode = jfw_existJRE(pInfo, &bExist);
        if (errcode == JFW_E_NONE)
        {
            if (!bExist && !findAndSelect(&pInfo))
                return -1;
        }
        else
        {
            fprintf(stderr, "javaldx: Could not determine if JRE still exist\n");
            return -1;
        }
    }

    //Only do something if the sunjavaplugin created this JavaInfo
    rtl::OUString sVendor1(RTL_CONSTASCII_USTRINGPARAM("Sun Microsystems Inc."));
    rtl::OUString sVendor2(RTL_CONSTASCII_USTRINGPARAM("IBM Corporation"));
    rtl::OUString sVendor3(RTL_CONSTASCII_USTRINGPARAM("Blackdown Java-Linux Team"));
    rtl::OUString sVendor4(RTL_CONSTASCII_USTRINGPARAM("Apple Inc."));
    rtl::OUString sVendor5(RTL_CONSTASCII_USTRINGPARAM("Apple Computer, Inc."));
    rtl::OUString sVendor6(RTL_CONSTASCII_USTRINGPARAM("BEA Systems, Inc."));
    rtl::OUString sVendor7(RTL_CONSTASCII_USTRINGPARAM("Free Software Foundation, Inc."));
    rtl::OUString sVendor8(RTL_CONSTASCII_USTRINGPARAM("The FreeBSD Foundation"));
    if ( ! (sVendor1.equals(pInfo->sVendor) == sal_True
            || sVendor2.equals(pInfo->sVendor) == sal_True
            || sVendor3.equals(pInfo->sVendor) == sal_True
            || sVendor4.equals(pInfo->sVendor) == sal_True
            || sVendor5.equals(pInfo->sVendor) == sal_True
            || sVendor6.equals(pInfo->sVendor) == sal_True
            || sVendor7.equals(pInfo->sVendor) == sal_True
            || sVendor8.equals(pInfo->sVendor) == sal_True))
        return 0;

    rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData);
    fprintf(stdout, "%s\n", sPaths.getStr());
    jfw_freeJavaInfo(pInfo);

    return 0;
}

rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData)
{
    const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray();
    sal_Int32 len = vendorData.getLength();
    rtl::OUString sData(chars, len / 2);
    //the runtime lib is on the first line
    sal_Int32 index = 0;
    rtl::OUString aToken = sData.getToken( 1, '\n', index);

    rtl::OString paths =
        rtl::OUStringToOString(aToken, osl_getThreadTextEncoding());
    return paths;
}

static sal_Bool hasOption(char const * szOption, int argc, char** argv)
{
    sal_Bool retVal= sal_False;
    for(sal_Int16 i= 1; i < argc; i++)
    {
        if( ! strcmp(argv[i], szOption))
        {
            retVal= sal_True;
            break;
        }
    }
    return retVal;
}

static bool findAndSelect(JavaInfo ** ppInfo)
{
    javaFrameworkError errcode = jfw_findAndSelectJRE(ppInfo);
    if (errcode == JFW_E_NO_JAVA_FOUND)
    {
        fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n");
        return false;
    }
    else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE)
    {
        fprintf(stderr,"javaldx failed!\n");
        return false;
    }
    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>jvmfwk-modified-javavendors-xml.diff: autodetect java (i#99619)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_jvmfwk.hxx"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sal/main.h"
#include "sal/types.h"
#include "osl/thread.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "jvmfwk/framework.h"

using ::rtl::OUString;
using ::rtl::OUStringToOString;
using ::rtl::OString;
#define OUSTR(x) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))

static sal_Bool hasOption(char const * szOption, int argc, char** argv);
static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData);
static bool findAndSelect(JavaInfo**);

#define HELP_TEXT    \
"\njavaldx is necessary to make Java work on some UNIX platforms." \
"It prints a string to std out that consists of directories which " \
"have to be included into the LD_LIBRARY_PATH variable.The setting of " \
"the variable usually occurs in a shell script that runs javaldx.\n" \
"The directories are from the chosen java installation. \n" \
"Options are: \n"\
"--help or -h\n"

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv))
    {
        fprintf(stdout, HELP_TEXT);// default
        return 0;
    }
    javaFrameworkError errcode = JFW_E_NONE;
    sal_Bool bEnabled = sal_False;
    errcode = jfw_getEnabled( & bEnabled);
    if (errcode == JFW_E_NONE && bEnabled == sal_False)
    {
            //Do not do any preparation because that may only slow startup time.
        return 0;
    }
    else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE)
    {
        fprintf(stderr,"javaldx failed! \n");
        return -1;
    }

    JavaInfo * pInfo = NULL;
    errcode = jfw_getSelectedJRE( & pInfo);

    if (errcode != JFW_E_NONE && errcode != JFW_E_INVALID_SETTINGS)
    {
        fprintf(stderr,"javaldx failed! \n");
        return -1;
    }

    if (pInfo == NULL)
    {
        if (false == findAndSelect(&pInfo))
            return -1;
    }
    else
    {
        //check if the JRE was not uninstalled
        sal_Bool bExist = sal_False;
        errcode = jfw_existJRE(pInfo, &bExist);
        if (errcode == JFW_E_NONE)
        {
            if (!bExist && !findAndSelect(&pInfo))
                return -1;
        }
        else
        {
            fprintf(stderr, "javaldx: Could not determine if JRE still exist\n");
            return -1;
        }
    }

    //Only do something if the sunjavaplugin created this JavaInfo
    rtl::OUString sVendor1(RTL_CONSTASCII_USTRINGPARAM("Sun Microsystems Inc."));
    rtl::OUString sVendor2(RTL_CONSTASCII_USTRINGPARAM("IBM Corporation"));
    rtl::OUString sVendor3(RTL_CONSTASCII_USTRINGPARAM("Blackdown Java-Linux Team"));
    rtl::OUString sVendor4(RTL_CONSTASCII_USTRINGPARAM("Apple Inc."));
    rtl::OUString sVendor5(RTL_CONSTASCII_USTRINGPARAM("Apple Computer, Inc."));
    rtl::OUString sVendor6(RTL_CONSTASCII_USTRINGPARAM("BEA Systems, Inc."));
    rtl::OUString sVendor7(RTL_CONSTASCII_USTRINGPARAM("Free Software Foundation, Inc."));
    rtl::OUString sVendor8(RTL_CONSTASCII_USTRINGPARAM("The FreeBSD Foundation"));
    if ( ! (sVendor1.equals(pInfo->sVendor) == sal_True
            || sVendor2.equals(pInfo->sVendor) == sal_True
            || sVendor3.equals(pInfo->sVendor) == sal_True
            || sVendor4.equals(pInfo->sVendor) == sal_True
            || sVendor5.equals(pInfo->sVendor) == sal_True
            || sVendor6.equals(pInfo->sVendor) == sal_True
            || sVendor7.equals(pInfo->sVendor) == sal_True
            || sVendor8.equals(pInfo->sVendor) == sal_True))
        return 0;

    rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData);
    fprintf(stdout, "%s\n", sPaths.getStr());
    jfw_freeJavaInfo(pInfo);

    return 0;
}

rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData)
{
    const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray();
    sal_Int32 len = vendorData.getLength();
    rtl::OUString sData(chars, len / 2);
    //the runtime lib is on the first line
    sal_Int32 index = 0;
    rtl::OUString aToken = sData.getToken( 1, '\n', index);

    rtl::OString paths =
        rtl::OUStringToOString(aToken, osl_getThreadTextEncoding());
    return paths;
}

static sal_Bool hasOption(char const * szOption, int argc, char** argv)
{
    sal_Bool retVal= sal_False;
    for(sal_Int16 i= 1; i < argc; i++)
    {
        if( ! strcmp(argv[i], szOption))
        {
            retVal= sal_True;
            break;
        }
    }
    return retVal;
}

static bool findAndSelect(JavaInfo ** ppInfo)
{
    javaFrameworkError errcode = jfw_findAndSelectJRE(ppInfo);
    if (errcode == JFW_E_NO_JAVA_FOUND)
    {
        fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n");
        return false;
    }
    else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE)
    {
        fprintf(stderr,"javaldx failed!\n");
        return false;
    }
    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sunversion.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 18:41:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#if !defined INCLUDED_JVMACCESS_SUNVERSION_HXX
#define INCLUDED_JVMACCESS_SUNVERSION_HXX

#include "rtl/ustring.hxx"

namespace stoc_javadetect {
// Define SUNVERSION_SELFTEST to run a test when this lib is loaded
//#define SUNVERSION_SELFTEST

/* SunVersion is used to compare java versions based on a string, as taken
   from the registry. The strings look like "1.3", "1.3.1", "1.3.1_02" etc.
   Versions such as "1.4.1_01a" are allowed although this is not specified.
   1.4.1_01 < 1.4.1_01a < 1.4.1_01b < 1.4.1_02
   Pre - release versions, such as 1.4.1-ea, 1.4.1-beta, 1.4.1-rc are recognized,
   but are treated as minor to release versions:
   1.4.0 > 1.4.2-beta
   Pre releases relate this way
   1.4.1-ea < 1.4.1-beta < 1.4.1-rc1

   An object acts as holder for the version string. That string may be present
   even if the version could not be parsed. Then the version may not be compatible
   to a SUN Java version.

   An invalid object, that is, operator bool returns false, will always be
   the lower version in a comparison. If two invalid objects are compared
   then they are considered equal.

   To test if the version is ok, that is this object can be compared to others,
   use the bool conversion operator.
 */
class SunVersion
{
protected:

    enum PreRelease
    {
        Rel_NONE,
        Rel_EA,
        Rel_EA1,
        Rel_EA2,
        Rel_EA3,
        Rel_BETA,
        Rel_BETA1,
        Rel_BETA2,
        Rel_BETA3,
        Rel_RC,
        Rel_RC1,
        Rel_RC2,
        Rel_RC3
    };

    //contains major,minor,micro,update
    int m_arVersionParts[4];
    // The update can be followed by a char, e.g. 1.4.1_01a
    char m_nUpdateSpecial;

    PreRelease m_preRelease;
public:
    SunVersion();
    SunVersion(const char * szVer);
    SunVersion(const rtl::OUString& usVer);
    ~SunVersion();

    /**
       Pre-release versions are taken into account.
       1.5.0-beta > 1.5.0-ea > 1.4.2
     */
    bool operator > (const SunVersion& ver) const;
    bool operator < (const SunVersion& ver) const;
    bool operator == (const SunVersion& ver) const;

    /** Test if the version is compatible tu SUN's versioning scheme
     */
    operator bool ();

    /** Will always contain a value if the object has been constructed with
        a version string.
     */
    rtl::OUString usVersion;

protected:
    bool init(const char * szVer);

    bool m_bValid;
};

/**
    @param usJavaHome
    File URL of the java installation directory.
*/
SunVersion initVersion(const rtl::OUString& usJavaHome);

SunVersion extractVersion(const rtl::OString & sVersionLine);

}

#endif // INCLUDED_JVMACCESS_SUNVERSION_HXX
<commit_msg>INTEGRATION: CWS jl8 (1.2.4); FILE MERGED 2004/07/07 13:28:51 jl 1.2.4.3: #i30342# 2004/07/07 10:47:37 jl 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2004/06/23 12:31:35 jl 1.2.4.1: #i30342# refactorizing plugin<commit_after>/*************************************************************************
 *
 *  $RCSfile: sunversion.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2004-07-23 11:52:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#if !defined INCLUDED_JVMACCESS_SUNVERSION_HXX
#define INCLUDED_JVMACCESS_SUNVERSION_HXX

#include "rtl/ustring.hxx"

namespace jfw_plugin {
// Define SUNVERSION_SELFTEST to run a test when this lib is loaded
//#define SUNVERSION_SELFTEST

/* SunVersion is used to compare java versions based on a string, as taken
   from the registry. The strings look like "1.3", "1.3.1", "1.3.1_02" etc.
   Versions such as "1.4.1_01a" are allowed although this is not specified.
   1.4.1_01 < 1.4.1_01a < 1.4.1_01b < 1.4.1_02
   Pre - release versions, such as 1.4.1-ea, 1.4.1-beta, 1.4.1-rc are recognized,
   but are treated as minor to release versions:
   1.4.0 > 1.4.2-beta
   Pre releases relate this way
   1.4.1-ea < 1.4.1-beta < 1.4.1-rc1

   An object acts as holder for the version string. That string may be present
   even if the version could not be parsed. Then the version may not be compatible
   to a SUN Java version.

   An invalid object, that is, operator bool returns false, will always be
   the lower version in a comparison. If two invalid objects are compared
   then they are considered equal.

   To test if the version is ok, that is this object can be compared to others,
   use the bool conversion operator.
 */
class SunVersion
{
protected:

    enum PreRelease
    {
        Rel_NONE,
        Rel_EA,
        Rel_EA1,
        Rel_EA2,
        Rel_EA3,
        Rel_BETA,
        Rel_BETA1,
        Rel_BETA2,
        Rel_BETA3,
        Rel_RC,
        Rel_RC1,
        Rel_RC2,
        Rel_RC3
    };

    //contains major,minor,micro,update
    int m_arVersionParts[4];
    // The update can be followed by a char, e.g. 1.4.1_01a
    char m_nUpdateSpecial;

    PreRelease m_preRelease;
public:
    SunVersion();
    SunVersion(const char * szVer);
    SunVersion(const rtl::OUString& usVer);
    ~SunVersion();

    /**
       Pre-release versions are taken into account.
       1.5.0-beta > 1.5.0-ea > 1.4.2
     */
    bool operator > (const SunVersion& ver) const;
    bool operator < (const SunVersion& ver) const;
    bool operator == (const SunVersion& ver) const;

    /** Test if the version is compatible tu SUN's versioning scheme
     */
    operator bool ();

    /** Will always contain a value if the object has been constructed with
        a version string.
     */
    rtl::OUString usVersion;

protected:
    bool init(const char * szVer);

    bool m_bValid;
};

}

#endif // INCLUDED_JVMACCESS_SUNVERSION_HXX
<|endoftext|>


<commit_before>//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012 Esteban Tovagliari.
//
// 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.
//

// Has to be first, to avoid redifinition warnings.
#include "bind_auto_release_ptr.h"

#include "renderer/modeling/scene/assembly.h"
#include "renderer/modeling/scene/assemblyinstance.h"

#include "bind_typed_entity_containers.h"
#include "dict2dict.h"

namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;

namespace detail
{
    auto_release_ptr<Assembly> create_assembly(const std::string& name)
    {
        return AssemblyFactory::create(name.c_str(), ParamArray());
    }

    auto_release_ptr<Assembly> create_assembly_with_params(
        const std::string&  name,
        const bpy::dict&    params)
    {
        return AssemblyFactory::create(name.c_str(), bpy_dict_to_param_array(params));
    }

    auto_release_ptr<AssemblyInstance> create_assembly_instance(
        const std::string&  name,
        const bpy::dict&    params,
        const std::string&  assembly_name)
    {
        return
            AssemblyInstanceFactory::create(
                name.c_str(),
                bpy_dict_to_param_array(params),
                assembly_name.c_str());
    }

    TransformSequence& get_transform_sequence(AssemblyInstance* instance)
    {
        return instance->transform_sequence();
    }
}

void bind_assembly()
{
    bpy::class_<BaseGroup, boost::noncopyable>("BaseGroup")
        .def("colors", &BaseGroup::colors, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("textures", &BaseGroup::textures, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("texture_instances", &BaseGroup::texture_instances, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("assemblies", &BaseGroup::assemblies, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("assembly_instances", &BaseGroup::assembly_instances, bpy::return_value_policy<bpy::reference_existing_object>())
        ;

    bpy::class_<Assembly, auto_release_ptr<Assembly>, bpy::bases<Entity, BaseGroup>, boost::noncopyable>("Assembly", bpy::no_init)
        .def("__init__", bpy::make_constructor(detail::create_assembly))
        .def("__init__", bpy::make_constructor(detail::create_assembly_with_params))
        .def("bsdfs", &Assembly::bsdfs, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("edfs", &Assembly::edfs, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("surface_shaders", &Assembly::surface_shaders, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("materials", &Assembly::materials, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("lights", &Assembly::lights, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("objects", &Assembly::objects, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("object_instances", &Assembly::object_instances, bpy::return_value_policy<bpy::reference_existing_object>())
        ;

    bind_typed_entity_map<Assembly>("AssemblyContainer");

    bpy::class_<AssemblyInstance, auto_release_ptr<AssemblyInstance>, bpy::bases<Entity>, boost::noncopyable>("AssemblyInstance", bpy::no_init)
        .def("__init__", bpy::make_constructor(detail::create_assembly_instance))
        .def("get_assembly", &AssemblyInstance::get_assembly, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("transform_sequence", detail::get_transform_sequence, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("compute_local_bbox", &AssemblyInstance::compute_local_bbox)
        .def("compute_parent_bbox", &AssemblyInstance::compute_parent_bbox)
        ;

    bind_typed_entity_map<AssemblyInstance>("AssemblyInstanceContainer");
}
<commit_msg>changed the order of #include statements. the rule is: from most specific to most generic.<commit_after>//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012 Esteban Tovagliari.
//
// 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.
//

// Has to be first, to avoid redifinition warnings.
#include "bind_auto_release_ptr.h"

#include "bind_typed_entity_containers.h"
#include "dict2dict.h"

#include "renderer/modeling/scene/assembly.h"
#include "renderer/modeling/scene/assemblyinstance.h"

namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;

namespace detail
{
    auto_release_ptr<Assembly> create_assembly(const std::string& name)
    {
        return AssemblyFactory::create(name.c_str(), ParamArray());
    }

    auto_release_ptr<Assembly> create_assembly_with_params(
        const std::string&  name,
        const bpy::dict&    params)
    {
        return AssemblyFactory::create(name.c_str(), bpy_dict_to_param_array(params));
    }

    auto_release_ptr<AssemblyInstance> create_assembly_instance(
        const std::string&  name,
        const bpy::dict&    params,
        const std::string&  assembly_name)
    {
        return
            AssemblyInstanceFactory::create(
                name.c_str(),
                bpy_dict_to_param_array(params),
                assembly_name.c_str());
    }

    TransformSequence& get_transform_sequence(AssemblyInstance* instance)
    {
        return instance->transform_sequence();
    }
}

void bind_assembly()
{
    bpy::class_<BaseGroup, boost::noncopyable>("BaseGroup")
        .def("colors", &BaseGroup::colors, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("textures", &BaseGroup::textures, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("texture_instances", &BaseGroup::texture_instances, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("assemblies", &BaseGroup::assemblies, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("assembly_instances", &BaseGroup::assembly_instances, bpy::return_value_policy<bpy::reference_existing_object>())
        ;

    bpy::class_<Assembly, auto_release_ptr<Assembly>, bpy::bases<Entity, BaseGroup>, boost::noncopyable>("Assembly", bpy::no_init)
        .def("__init__", bpy::make_constructor(detail::create_assembly))
        .def("__init__", bpy::make_constructor(detail::create_assembly_with_params))
        .def("bsdfs", &Assembly::bsdfs, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("edfs", &Assembly::edfs, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("surface_shaders", &Assembly::surface_shaders, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("materials", &Assembly::materials, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("lights", &Assembly::lights, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("objects", &Assembly::objects, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("object_instances", &Assembly::object_instances, bpy::return_value_policy<bpy::reference_existing_object>())
        ;

    bind_typed_entity_map<Assembly>("AssemblyContainer");

    bpy::class_<AssemblyInstance, auto_release_ptr<AssemblyInstance>, bpy::bases<Entity>, boost::noncopyable>("AssemblyInstance", bpy::no_init)
        .def("__init__", bpy::make_constructor(detail::create_assembly_instance))
        .def("get_assembly", &AssemblyInstance::get_assembly, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("transform_sequence", detail::get_transform_sequence, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("compute_local_bbox", &AssemblyInstance::compute_local_bbox)
        .def("compute_parent_bbox", &AssemblyInstance::compute_parent_bbox)
        ;

    bind_typed_entity_map<AssemblyInstance>("AssemblyInstanceContainer");
}
<|endoftext|>


<commit_before>#pragma once

#include "compiler.hpp"

#if (defined(BLACKHOLE_HAS_CLANG) && defined(TARGET_OS_MAC)) || defined(BLACKHOLE_HAS_AT_LEAST_GCC46)
    #define BLACKHOLE_HAS_FEATURE_ATOMIC
#endif
<commit_msg>[Common] Clang support on non OS X targets.<commit_after>#pragma once

#include "compiler.hpp"

#if defined(BLACKHOLE_HAS_CLANG) || defined(BLACKHOLE_HAS_AT_LEAST_GCC46)
    #define BLACKHOLE_HAS_FEATURE_ATOMIC
#endif
<|endoftext|>


<commit_before>#include "For.hpp"

#include "../Context.hpp"

namespace liquidpp {
For::For(Tag&& tag)
   : Block(std::move(tag)) {
   auto tokens = Expression::splitTokens(value);

   loopVariable = tokens[0].to_string();
   if (tokens[1] != "in")
      throw Exception("Second token in 'for' tag has to be the 'in' keyword!", tokens[1]);
   rangeVariable = tokens[2].to_string();

   auto cnt = tokens.size();
   for (size_t i=3; i < cnt; i++)
   {
      auto& key = tokens[i];

      if (key == "limit")
      {
         if (i+2 < cnt)
         {
            if (tokens[i+1] != ":")
               throw Exception("Expected operator ':' after parameter name!", tokens[i+1]);
            limitToken = Expression::toToken(tokens[i+2]);
            i += 2;
         }
         else
            throw Exception("Not enough arguments for this parameter!", key);
      }
      else if (key == "offset")
      {
         if (i+2 < cnt)
         {
            if (tokens[i+1] != ":")
               throw Exception("Expected operator ':' after parameter name!", tokens[i+1]);
            offsetToken = Expression::toToken(tokens[i+2]);
            i += 2;
         }
         else
            throw Exception("Not enough arguments for this parameter!", key);
      }
      else if (key == "reversed")
         reversed = true;
      else
         throw Exception("Unknown parameter on 'for' tag!", key);
   }
}

boost::optional<For::RangeExpression> For::toRangeDefinition(string_view sv)
{
   if (sv.front() == '(')
   {
      if (sv.back() != ')')
         throw Exception("Unterminated range expression!", sv);

      sv.remove_prefix(1);
      sv.remove_suffix(1);

      RangeExpression res;
      auto idx = sv.find("..");
      if (idx == std::string::npos)
         throw Exception("Range expression misses '..'!", sv);
      res.startIdxToken = Expression::toToken(sv.substr(0, idx));
      res.endIdxToken = Expression::toToken(sv.substr(idx+2));

      return res;
   }

   return boost::none;
}

Value For::LoopData::get(OptIndex requIdx, string_view path) const
{
   if (requIdx)
      return ValueTag::Object;

   if (path == "first")
      return toValue(idx == 0);
   if (path == "index")
      return toValue(idx + 1);
   if (path == "index0")
      return toValue(idx);
   if (path == "last")
      return toValue(idx + 1 == size);
   if (path == "length")
      return toValue(size);
   if (path == "rindex")
      return toValue(size - idx);
   if (path == "rindex0")
      return toValue(size - idx - 1);

   return ValueTag::Null;
}

void For::render(Context& context, std::string& res) const {
   auto rangeExpr = toRangeDefinition(rangeVariable);
   size_t rangeExprStart = 0;
   size_t rangeExprEnd = 0;
   Value val;

   if (rangeExpr)
   {
      rangeExprStart = Expression::value(context, rangeExpr->startIdxToken).integralValue();
      rangeExprEnd = Expression::value(context, rangeExpr->endIdxToken).integralValue();
   }
   else
      val = context.get(rangeVariable);

   size_t size = 0;
   if (rangeExpr)
      size = rangeExprEnd - rangeExprStart + 1;
   else if (val.isRange())
      size = val.size();
   else if (val.isSimpleValue())
      size = 1;

   auto getValue = [&](size_t i) mutable {
      if (rangeExpr)
         return std::make_tuple(toValue(rangeExprStart + i), std::string{});
      else if (val.isSimpleValue())
         return std::make_tuple(val, std::string{});
      else if (val.isRange())
         return Expression::value(context, val.range(), i, rangeVariable);

      return std::make_tuple(Value{ValueTag::OutOfRange}, std::string{});
   };

   size_t offset = 0;
   if (offsetToken)
      offset = Expression::value(context, *offsetToken).integralValue();

   size_t limit = size - offset;
   if (limitToken)
   {
      auto l = static_cast<size_t>(Expression::value(context, *limitToken).integralValue());
      if (l < limit)
         limit = l;
   }

   if (limit == 0)
   {
      bool elseFound = false;
      for (auto&& node : body.nodeList)
      {
         if (isSpecificTag(node, "else"))
            elseFound = true;
         else if (elseFound)
            renderNode(context, node, res);
      }
      return;
   }

   for (size_t i = 0; i < limit; i++) {
      size_t idx = i + offset;
      if (reversed)
         idx = size - offset - i - 1;

      auto itm = getValue(idx);
      if (!renderElement(context, res, std::get<0>(itm), std::get<1>(itm), LoopData{i, limit}))
         break;
   }
}

template<>
struct ValueConverter<For::LoopData> : public std::true_type {
   template<typename T>
   static auto get(T&& loopData) {
      return [loopData = std::forward<T>(loopData)](OptIndex
      idx, string_view
      path) -> Value
      {
         return loopData.get(idx, path);
      };
   }
};

bool For::renderElement(Context& context, std::string& res, const Value& currentVal, string_view idxPath, LoopData forLoop) const {
   Context loopVarContext{context};
   loopVarContext.set("forloop", forLoop);

   if (currentVal.isSimpleValue())
      loopVarContext.setLiquidValue(loopVariable, currentVal);
   else if (currentVal != ValueTag::OutOfRange)
      loopVarContext.setLink(loopVariable, idxPath);
   else
      return false;

   try {
      for (auto&& node : body.nodeList)
      {
         if (isSpecificTag(node, "else"))
            break;
         renderNode(loopVarContext, node, res);
      }

      return true;
   }
   catch (DoContinue&) { return true; }
   catch (DoBreak&) { return false; }
}
}
<commit_msg>libFuzzer: Add missing token count check<commit_after>#include "For.hpp"

#include "../Context.hpp"

namespace liquidpp {
For::For(Tag&& tag)
   : Block(std::move(tag)) {
   auto tokens = Expression::splitTokens(value);
   if (tokens.size() < 3)
      throw Exception("Not enough parameters in 'for' tag!", value);

   loopVariable = tokens[0].to_string();
   if (tokens[1] != "in")
      throw Exception("Second token in 'for' tag has to be the 'in' keyword!", tokens[1]);
   rangeVariable = tokens[2].to_string();

   auto cnt = tokens.size();
   for (size_t i=3; i < cnt; i++)
   {
      auto& key = tokens[i];

      if (key == "limit")
      {
         if (i+2 < cnt)
         {
            if (tokens[i+1] != ":")
               throw Exception("Expected operator ':' after parameter name!", tokens[i+1]);
            limitToken = Expression::toToken(tokens[i+2]);
            i += 2;
         }
         else
            throw Exception("Not enough arguments for this parameter!", key);
      }
      else if (key == "offset")
      {
         if (i+2 < cnt)
         {
            if (tokens[i+1] != ":")
               throw Exception("Expected operator ':' after parameter name!", tokens[i+1]);
            offsetToken = Expression::toToken(tokens[i+2]);
            i += 2;
         }
         else
            throw Exception("Not enough arguments for this parameter!", key);
      }
      else if (key == "reversed")
         reversed = true;
      else
         throw Exception("Unknown parameter on 'for' tag!", key);
   }
}

boost::optional<For::RangeExpression> For::toRangeDefinition(string_view sv)
{
   if (sv.front() == '(')
   {
      if (sv.back() != ')')
         throw Exception("Unterminated range expression!", sv);

      sv.remove_prefix(1);
      sv.remove_suffix(1);

      RangeExpression res;
      auto idx = sv.find("..");
      if (idx == std::string::npos)
         throw Exception("Range expression misses '..'!", sv);
      res.startIdxToken = Expression::toToken(sv.substr(0, idx));
      res.endIdxToken = Expression::toToken(sv.substr(idx+2));

      return res;
   }

   return boost::none;
}

Value For::LoopData::get(OptIndex requIdx, string_view path) const
{
   if (requIdx)
      return ValueTag::Object;

   if (path == "first")
      return toValue(idx == 0);
   if (path == "index")
      return toValue(idx + 1);
   if (path == "index0")
      return toValue(idx);
   if (path == "last")
      return toValue(idx + 1 == size);
   if (path == "length")
      return toValue(size);
   if (path == "rindex")
      return toValue(size - idx);
   if (path == "rindex0")
      return toValue(size - idx - 1);

   return ValueTag::Null;
}

void For::render(Context& context, std::string& res) const {
   auto rangeExpr = toRangeDefinition(rangeVariable);
   size_t rangeExprStart = 0;
   size_t rangeExprEnd = 0;
   Value val;

   if (rangeExpr)
   {
      rangeExprStart = Expression::value(context, rangeExpr->startIdxToken).integralValue();
      rangeExprEnd = Expression::value(context, rangeExpr->endIdxToken).integralValue();
   }
   else
      val = context.get(rangeVariable);

   size_t size = 0;
   if (rangeExpr)
      size = rangeExprEnd - rangeExprStart + 1;
   else if (val.isRange())
      size = val.size();
   else if (val.isSimpleValue())
      size = 1;

   auto getValue = [&](size_t i) mutable {
      if (rangeExpr)
         return std::make_tuple(toValue(rangeExprStart + i), std::string{});
      else if (val.isSimpleValue())
         return std::make_tuple(val, std::string{});
      else if (val.isRange())
         return Expression::value(context, val.range(), i, rangeVariable);

      return std::make_tuple(Value{ValueTag::OutOfRange}, std::string{});
   };

   size_t offset = 0;
   if (offsetToken)
      offset = Expression::value(context, *offsetToken).integralValue();

   size_t limit = size - offset;
   if (limitToken)
   {
      auto l = static_cast<size_t>(Expression::value(context, *limitToken).integralValue());
      if (l < limit)
         limit = l;
   }

   if (limit == 0)
   {
      bool elseFound = false;
      for (auto&& node : body.nodeList)
      {
         if (isSpecificTag(node, "else"))
            elseFound = true;
         else if (elseFound)
            renderNode(context, node, res);
      }
      return;
   }

   for (size_t i = 0; i < limit; i++) {
      size_t idx = i + offset;
      if (reversed)
         idx = size - offset - i - 1;

      auto itm = getValue(idx);
      if (!renderElement(context, res, std::get<0>(itm), std::get<1>(itm), LoopData{i, limit}))
         break;
   }
}

template<>
struct ValueConverter<For::LoopData> : public std::true_type {
   template<typename T>
   static auto get(T&& loopData) {
      return [loopData = std::forward<T>(loopData)](OptIndex
      idx, string_view
      path) -> Value
      {
         return loopData.get(idx, path);
      };
   }
};

bool For::renderElement(Context& context, std::string& res, const Value& currentVal, string_view idxPath, LoopData forLoop) const {
   Context loopVarContext{context};
   loopVarContext.set("forloop", forLoop);

   if (currentVal.isSimpleValue())
      loopVarContext.setLiquidValue(loopVariable, currentVal);
   else if (currentVal != ValueTag::OutOfRange)
      loopVarContext.setLink(loopVariable, idxPath);
   else
      return false;

   try {
      for (auto&& node : body.nodeList)
      {
         if (isSpecificTag(node, "else"))
            break;
         renderNode(loopVarContext, node, res);
      }

      return true;
   }
   catch (DoContinue&) { return true; }
   catch (DoBreak&) { return false; }
}
}
<|endoftext|>


<commit_before>#include <pwd.h>
#include <grp.h>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = directoryName;
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isL) {

		cout << 78 << endl;
		struct stat current;

		struct passwd *x;
		struct group *y;
		while ((direntp = readdir(dirp))) {

			//cout << "direntp: " << direntp << endl;
			if (-1 == (stat(direntp->d_name, &current))) {

				perror("stat failed");
				return -1;
			}
			if (direntp->d_name[0] == '.' && !isA)
				continue;
			else {

				if (current.st_mode & S_IFDIR)
					cout << "d";

				if (current.st_mode & S_IFLNK)
					cout << "l";

				if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
					cout << "-";

				if (current.st_mode & S_IRUSR)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWUSR)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXUSR)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IRGRP)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWGRP)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXGRP)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IROTH)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWOTH)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXOTH)
					cout << "x";
				else
					cout << "-";

				cout << " ";

				cout << current.st_nlink << " ";

				if ((x = getpwuid(current.st_uid)) != NULL)
					cout << x->pw_name << " ";
				else {
					cerr << "error: " << errno << endl;
					exit(0);
				}

				if ((y = getgrgid(current.st_gid)) != NULL)
					cout << y->gr_name << " ";
				else {
					cerr << "error: " << errno << endl;
					exit(0);
				}
				cout << current.st_size << " ";

				char buff[20];
				struct tm * timeinfo;
				timeinfo = localtime(&(current.st_mtime));
				strftime(buff, 20, "%b %d %H:%M", timeinfo);
				printf("%s",buff);

				cout << " " << direntp->d_name;
			}
			cout << endl;

		}
		closedir(dirp);

	}

	else if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
		closedir(dirp);
	}
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directories.push_back(argv[i]);

			}
			else if (argv[i][0] == '-') {

				flags.push_back(argv[i]);
			}
		}
		if (flags.size() == 0) {

			for (unsigned i = 0; i < directories.size(); ++i) {

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				ls(directoryName);

				delete [] directoryName;
			}
		}
		else {
			//cout << "directories: ";
			//for (unsigned i = 0; i < directories.size(); ++i)
				//cout << directories.at(i) << " ";
			//cout << endl;

			if (directories.size() == 1) {

				char* directoryName = new char[directories.at(0).size() + 1];
				strcpy(directoryName, directories.at(0).c_str());

				lsWithFlags(directoryName, flags);

				delete [] directoryName;
			}

			else {
				for (unsigned int i = 0; i < directories.size(); ++i) {
					//cout << 145 << endl;

					char* directoryName = new char[directories.at(i).size() + 1];
					strcpy(directoryName, directories.at(i).c_str());

					lsWithFlags(directoryName, flags);
					delete [] directoryName;
				}
			}
		}
	}

}

<commit_msg>added -l protection functionality<commit_after>#include <pwd.h>
#include <grp.h>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = directoryName;
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isL) {

		cout << 78 << endl;
		struct stat current;

		struct passwd *x;
		struct group *y;
		while ((direntp = readdir(dirp))) {

			//cout << "direntp: " << direntp << endl;
			if (-1 == (stat(direntp->d_name, &current))) {

				perror("stat failed");
				return -1;
			}
			if (direntp->d_name[0] == '.' && !isA)
				continue;
			else {

				if (current.st_mode & S_IFDIR)
					cout << "d";

				if (current.st_mode & S_IFLNK)
					cout << "l";

				if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
					cout << "-";

				if (current.st_mode & S_IRUSR)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWUSR)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXUSR)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IRGRP)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWGRP)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXGRP)
					cout << "x";
				else
					cout << "-";

				if (current.st_mode & S_IROTH)
					cout << "r";
				else
					cout << "-";

				if (current.st_mode & S_IWOTH)
					cout << "w";
				else
					cout << "-";

				if (current.st_mode & S_IXOTH)
					cout << "x";
				else
					cout << "-";

				cout << " ";

				cout << current.st_nlink << " ";

				if ((x = getpwuid(current.st_uid)) != NULL)
					cout << x->pw_name << " ";
				else {
					cerr << "error: " << errno << endl;
					exit(0);
				}

				if ((y = getgrgid(current.st_gid)) != NULL)
					cout << y->gr_name << " ";
				else {
					cerr << "error: " << errno << endl;
					exit(0);
				}
				cout << current.st_size << " ";

				char buff[20];
				struct tm * timeinfo;
				timeinfo = localtime(&(current.st_mtime));
				strftime(buff, 20, "%b %d %H:%M", timeinfo);
				printf("%s",buff);

				cout << " " << direntp->d_name;
			}
			cout << endl;

		}
		closedir(dirp);

	}

	else if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
		closedir(dirp);
	}
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directories.push_back(argv[i]);

			}
			else if (argv[i][0] == '-') {

				flags.push_back(argv[i]);
			}
		}
		if (flags.size() == 0) {

			for (unsigned i = 0; i < directories.size(); ++i) {

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				ls(directoryName);

				delete [] directoryName;
			}
		}
		else if (directories.size() == 0) {

			lsWithFlags(".", flags);
		}
		else {
			//cout << "directories: ";
			//for (unsigned i = 0; i < directories.size(); ++i)
				//cout << directories.at(i) << " ";
			//cout << endl;

			if (directories.size() == 1) {

				char* directoryName = new char[directories.at(0).size() + 1];
				strcpy(directoryName, directories.at(0).c_str());

				lsWithFlags(directoryName, flags);

				delete [] directoryName;
			}

			else {
				for (unsigned int i = 0; i < directories.size(); ++i) {
					//cout << 145 << endl;

					char* directoryName = new char[directories.at(i).size() + 1];
					strcpy(directoryName, directories.at(i).c_str());

					lsWithFlags(directoryName, flags);
					delete [] directoryName;
				}
			}
		}
	}

}

<|endoftext|>