repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
jonbakerfish/kgraph | test.cpp | 4008 | /*
Copyright (C) 2010,2011 Wei Dong <[email protected]>. All Rights Reserved.
DISTRIBUTION OF THIS PROGRAM IN EITHER BINARY OR SOURCE CODE FORM MUST BE
PERMITTED BY THE AUTHOR.
*/
#ifndef KGRAPH_VALUE_TYPE
#define KGRAPH_VALUE_TYPE float
#endif
#include <cctype>
#include <type_traits>
#include <iostream>
#include <boost/timer/timer.hpp>
#include <boost/program_options.hpp>
#include <kgraph.h>
#include <kgraph-data.h>
using namespace std;
using namespace boost;
using namespace kgraph;
namespace po = boost::program_options;
typedef KGRAPH_VALUE_TYPE value_type;
int main (int argc, char *argv[]) {
string input_path;
string query_path;
string output_path;
string eval_path;
unsigned K, P;
po::options_description desc_visible("General options");
desc_visible.add_options()
("help,h", "produce help message.")
("data", po::value(&input_path), "input path")
("query", po::value(&query_path), "query path")
("eval", po::value(&eval_path), "eval path")
(",K", po::value(&K)->default_value(default_K), "")
(",P", po::value(&P)->default_value(default_P), "")
;
po::options_description desc("Allowed options");
desc.add(desc_visible);
po::positional_options_description p;
p.add("data", 1);
p.add("query", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || vm.count("data") == 0 || vm.count("query") == 0) {
cout << "search <data> <index> <query> [output]" << endl;
cout << desc_visible << endl;
return 0;
}
if (P < K) {
P = K;
}
Matrix<value_type> data;
Matrix<value_type> query;
Matrix<unsigned> result;
data.load_lshkit(input_path);
query.load_lshkit(query_path);
unsigned dim = data.dim();
VectorOracle<Matrix<value_type>, value_type const*> oracle(data,
[dim](value_type const *a, value_type const *b)
{
float r = 0;
for (unsigned i = 0; i < dim; ++i) {
float v = float(a[i]) - (b[i]);
r += v * v;
}
return r;
});
float recall = 0;
float cost = 0;
float time = 0;
result.resize(query.size(), K);
KGraph::SearchParams params;
params.K = K;
params.P = P;
KGraph *kgraph = KGraph::create();
{
KGraph::IndexParams params;
kgraph->build(oracle, params, NULL);
}
boost::timer::auto_cpu_timer timer;
cerr << "Searching..." << endl;
#pragma omp parallel for reduction(+:cost)
for (unsigned i = 0; i < query.size(); ++i) {
KGraph::SearchInfo info;
kgraph->search(oracle.query(query[i]), params, result[i], &info);
cost += info.cost;
}
cost /= query.size();
time = timer.elapsed().wall / 1e9;
delete kgraph;
if (eval_path.size()) {
Matrix<unsigned> gs;
gs.load_lshkit(eval_path);
BOOST_VERIFY(gs.dim() >= K);
BOOST_VERIFY(gs.size() >= query.size());
kgraph::Matrix<float> gs_dist(query.size(), K);
kgraph::Matrix<float> result_dist(query.size(), K);
#pragma omp parallel for
for (unsigned i = 0; i < query.size(); ++i) {
auto const Q = oracle.query(query[i]);
float *gs_dist_row = gs_dist[i];
float *result_dist_row = result_dist[i];
unsigned const *gs_row = gs[i];
unsigned const *result_row = result[i];
for (unsigned k = 0; k < K; ++k) {
gs_dist_row[k] = Q(gs_row[k]);
result_dist_row[k] = Q(result_row[k]);
}
sort(gs_dist_row, gs_dist_row + K);
sort(result_dist_row, result_dist_row + K);
}
recall = AverageRecall(gs_dist, result_dist, K);
}
cout << "Time: " << time << " Recall: " << recall << " Cost: " << cost << endl;
return 0;
}
| bsd-2-clause |
robohack/homebrew-core | Formula/speedtest-cli.rb | 577 | class SpeedtestCli < Formula
desc "Command-line interface for https://speedtest.net bandwidth tests"
homepage "https://github.com/sivel/speedtest-cli"
url "https://github.com/sivel/speedtest-cli/archive/v1.0.7.tar.gz"
sha256 "3853bb7a3d16f686441d0d10ebbfc1fd49e974ecf17248ce03456ad4ef2478b9"
head "https://github.com/sivel/speedtest-cli.git"
bottle :unneeded
def install
bin.install "speedtest.py" => "speedtest"
bin.install_symlink "speedtest" => "speedtest-cli"
man1.install "speedtest-cli.1"
end
test do
system bin/"speedtest"
end
end
| bsd-2-clause |
attilaz/bgfx | examples/common/entry/entry.cpp | 21992 | /*
* Copyright 2011-2019 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include <bx/bx.h>
#include <bx/file.h>
#include <bx/sort.h>
#include <bgfx/bgfx.h>
#include <time.h>
#if BX_PLATFORM_EMSCRIPTEN
# include <emscripten.h>
#endif // BX_PLATFORM_EMSCRIPTEN
#include "entry_p.h"
#include "cmd.h"
#include "input.h"
extern "C" int32_t _main_(int32_t _argc, char** _argv);
namespace entry
{
static uint32_t s_debug = BGFX_DEBUG_NONE;
static uint32_t s_reset = BGFX_RESET_NONE;
static uint32_t s_width = ENTRY_DEFAULT_WIDTH;
static uint32_t s_height = ENTRY_DEFAULT_HEIGHT;
static bool s_exit = false;
static bx::FileReaderI* s_fileReader = NULL;
static bx::FileWriterI* s_fileWriter = NULL;
extern bx::AllocatorI* getDefaultAllocator();
bx::AllocatorI* g_allocator = getDefaultAllocator();
typedef bx::StringT<&g_allocator> String;
static String s_currentDir;
class FileReader : public bx::FileReader
{
typedef bx::FileReader super;
public:
virtual bool open(const bx::FilePath& _filePath, bx::Error* _err) override
{
String filePath(s_currentDir);
filePath.append(_filePath);
return super::open(filePath.getPtr(), _err);
}
};
class FileWriter : public bx::FileWriter
{
typedef bx::FileWriter super;
public:
virtual bool open(const bx::FilePath& _filePath, bool _append, bx::Error* _err) override
{
String filePath(s_currentDir);
filePath.append(_filePath);
return super::open(filePath.getPtr(), _append, _err);
}
};
void setCurrentDir(const char* _dir)
{
s_currentDir.set(_dir);
}
#if ENTRY_CONFIG_IMPLEMENT_DEFAULT_ALLOCATOR
bx::AllocatorI* getDefaultAllocator()
{
BX_PRAGMA_DIAGNOSTIC_PUSH();
BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4459); // warning C4459: declaration of 's_allocator' hides global declaration
BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow");
static bx::DefaultAllocator s_allocator;
return &s_allocator;
BX_PRAGMA_DIAGNOSTIC_POP();
}
#endif // ENTRY_CONFIG_IMPLEMENT_DEFAULT_ALLOCATOR
static const char* s_keyName[] =
{
"None",
"Esc",
"Return",
"Tab",
"Space",
"Backspace",
"Up",
"Down",
"Left",
"Right",
"Insert",
"Delete",
"Home",
"End",
"PageUp",
"PageDown",
"Print",
"Plus",
"Minus",
"LeftBracket",
"RightBracket",
"Semicolon",
"Quote",
"Comma",
"Period",
"Slash",
"Backslash",
"Tilde",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"NumPad0",
"NumPad1",
"NumPad2",
"NumPad3",
"NumPad4",
"NumPad5",
"NumPad6",
"NumPad7",
"NumPad8",
"NumPad9",
"Key0",
"Key1",
"Key2",
"Key3",
"Key4",
"Key5",
"Key6",
"Key7",
"Key8",
"Key9",
"KeyA",
"KeyB",
"KeyC",
"KeyD",
"KeyE",
"KeyF",
"KeyG",
"KeyH",
"KeyI",
"KeyJ",
"KeyK",
"KeyL",
"KeyM",
"KeyN",
"KeyO",
"KeyP",
"KeyQ",
"KeyR",
"KeyS",
"KeyT",
"KeyU",
"KeyV",
"KeyW",
"KeyX",
"KeyY",
"KeyZ",
"GamepadA",
"GamepadB",
"GamepadX",
"GamepadY",
"GamepadThumbL",
"GamepadThumbR",
"GamepadShoulderL",
"GamepadShoulderR",
"GamepadUp",
"GamepadDown",
"GamepadLeft",
"GamepadRight",
"GamepadBack",
"GamepadStart",
"GamepadGuide",
};
BX_STATIC_ASSERT(Key::Count == BX_COUNTOF(s_keyName) );
const char* getName(Key::Enum _key)
{
BX_CHECK(_key < Key::Count, "Invalid key %d.", _key);
return s_keyName[_key];
}
char keyToAscii(Key::Enum _key, uint8_t _modifiers)
{
const bool isAscii = (Key::Key0 <= _key && _key <= Key::KeyZ)
|| (Key::Esc <= _key && _key <= Key::Minus);
if (!isAscii)
{
return '\0';
}
const bool isNumber = (Key::Key0 <= _key && _key <= Key::Key9);
if (isNumber)
{
return '0' + char(_key - Key::Key0);
}
const bool isChar = (Key::KeyA <= _key && _key <= Key::KeyZ);
if (isChar)
{
enum { ShiftMask = Modifier::LeftShift|Modifier::RightShift };
const bool shift = !!(_modifiers&ShiftMask);
return (shift ? 'A' : 'a') + char(_key - Key::KeyA);
}
switch (_key)
{
case Key::Esc: return 0x1b;
case Key::Return: return '\n';
case Key::Tab: return '\t';
case Key::Space: return ' ';
case Key::Backspace: return 0x08;
case Key::Plus: return '+';
case Key::Minus: return '-';
default: break;
}
return '\0';
}
bool setOrToggle(uint32_t& _flags, const char* _name, uint32_t _bit, int _first, int _argc, char const* const* _argv)
{
if (0 == bx::strCmp(_argv[_first], _name) )
{
int arg = _first+1;
if (_argc > arg)
{
_flags &= ~_bit;
bool set = false;
bx::fromString(&set, _argv[arg]);
_flags |= set ? _bit : 0;
}
else
{
_flags ^= _bit;
}
return true;
}
return false;
}
int cmdMouseLock(CmdContext* /*_context*/, void* /*_userData*/, int _argc, char const* const* _argv)
{
if (1 < _argc)
{
bool set = false;
if (2 < _argc)
{
bx::fromString(&set, _argv[1]);
inputSetMouseLock(set);
}
else
{
inputSetMouseLock(!inputIsMouseLocked() );
}
return bx::kExitSuccess;
}
return bx::kExitFailure;
}
int cmdGraphics(CmdContext* /*_context*/, void* /*_userData*/, int _argc, char const* const* _argv)
{
if (_argc > 1)
{
if (setOrToggle(s_reset, "vsync", BGFX_RESET_VSYNC, 1, _argc, _argv)
|| setOrToggle(s_reset, "maxaniso", BGFX_RESET_MAXANISOTROPY, 1, _argc, _argv)
|| setOrToggle(s_reset, "msaa", BGFX_RESET_MSAA_X16, 1, _argc, _argv)
|| setOrToggle(s_reset, "flush", BGFX_RESET_FLUSH_AFTER_RENDER, 1, _argc, _argv)
|| setOrToggle(s_reset, "flip", BGFX_RESET_FLIP_AFTER_RENDER, 1, _argc, _argv)
|| setOrToggle(s_reset, "hidpi", BGFX_RESET_HIDPI, 1, _argc, _argv)
|| setOrToggle(s_reset, "depthclamp", BGFX_RESET_DEPTH_CLAMP, 1, _argc, _argv)
)
{
return bx::kExitSuccess;
}
else if (setOrToggle(s_debug, "stats", BGFX_DEBUG_STATS, 1, _argc, _argv)
|| setOrToggle(s_debug, "ifh", BGFX_DEBUG_IFH, 1, _argc, _argv)
|| setOrToggle(s_debug, "text", BGFX_DEBUG_TEXT, 1, _argc, _argv)
|| setOrToggle(s_debug, "wireframe", BGFX_DEBUG_WIREFRAME, 1, _argc, _argv)
|| setOrToggle(s_debug, "profiler", BGFX_DEBUG_PROFILER, 1, _argc, _argv)
)
{
bgfx::setDebug(s_debug);
return bx::kExitSuccess;
}
else if (0 == bx::strCmp(_argv[1], "screenshot") )
{
bgfx::FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
if (_argc > 2)
{
bgfx::requestScreenShot(fbh, _argv[2]);
}
else
{
time_t tt;
time(&tt);
char filePath[256];
bx::snprintf(filePath, sizeof(filePath), "temp/screenshot-%d", tt);
bgfx::requestScreenShot(fbh, filePath);
}
return bx::kExitSuccess;
}
else if (0 == bx::strCmp(_argv[1], "fullscreen") )
{
WindowHandle window = { 0 };
toggleFullscreen(window);
return bx::kExitSuccess;
}
}
return bx::kExitFailure;
}
int cmdExit(CmdContext* /*_context*/, void* /*_userData*/, int /*_argc*/, char const* const* /*_argv*/)
{
s_exit = true;
return bx::kExitSuccess;
}
static const InputBinding s_bindings[] =
{
{ entry::Key::KeyQ, entry::Modifier::LeftCtrl, 1, NULL, "exit" },
{ entry::Key::KeyQ, entry::Modifier::RightCtrl, 1, NULL, "exit" },
{ entry::Key::KeyF, entry::Modifier::LeftCtrl, 1, NULL, "graphics fullscreen" },
{ entry::Key::KeyF, entry::Modifier::RightCtrl, 1, NULL, "graphics fullscreen" },
{ entry::Key::Return, entry::Modifier::RightAlt, 1, NULL, "graphics fullscreen" },
{ entry::Key::F1, entry::Modifier::None, 1, NULL, "graphics stats" },
{ entry::Key::F1, entry::Modifier::LeftCtrl, 1, NULL, "graphics ifh" },
{ entry::Key::GamepadStart, entry::Modifier::None, 1, NULL, "graphics stats" },
{ entry::Key::F1, entry::Modifier::LeftShift, 1, NULL, "graphics stats 0\ngraphics text 0" },
{ entry::Key::F3, entry::Modifier::None, 1, NULL, "graphics wireframe" },
{ entry::Key::F4, entry::Modifier::None, 1, NULL, "graphics hmd" },
{ entry::Key::F4, entry::Modifier::LeftShift, 1, NULL, "graphics hmdrecenter" },
{ entry::Key::F4, entry::Modifier::LeftCtrl, 1, NULL, "graphics hmddbg" },
{ entry::Key::F6, entry::Modifier::None, 1, NULL, "graphics profiler" },
{ entry::Key::F7, entry::Modifier::None, 1, NULL, "graphics vsync" },
{ entry::Key::F8, entry::Modifier::None, 1, NULL, "graphics msaa" },
{ entry::Key::F9, entry::Modifier::None, 1, NULL, "graphics flush" },
{ entry::Key::F10, entry::Modifier::None, 1, NULL, "graphics hidpi" },
{ entry::Key::Print, entry::Modifier::None, 1, NULL, "graphics screenshot" },
{ entry::Key::KeyP, entry::Modifier::LeftCtrl, 1, NULL, "graphics screenshot" },
INPUT_BINDING_END
};
#if BX_PLATFORM_EMSCRIPTEN
static AppI* s_app;
static void updateApp()
{
s_app->update();
}
#endif // BX_PLATFORM_EMSCRIPTEN
static AppI* s_currentApp = NULL;
static AppI* s_apps = NULL;
static uint32_t s_numApps = 0;
static char s_restartArgs[1024] = { '\0' };
static AppI* getCurrentApp(AppI* _set = NULL)
{
if (NULL != _set)
{
s_currentApp = _set;
}
else if (NULL == s_currentApp)
{
s_currentApp = getFirstApp();
}
return s_currentApp;
}
static AppI* getNextWrap(AppI* _app)
{
AppI* next = _app->getNext();
if (NULL != next)
{
return next;
}
return getFirstApp();
}
int cmdApp(CmdContext* /*_context*/, void* /*_userData*/, int _argc, char const* const* _argv)
{
if (0 == bx::strCmp(_argv[1], "restart") )
{
if (2 == _argc)
{
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), getCurrentApp()->getName() );
return bx::kExitSuccess;
}
if (0 == bx::strCmp(_argv[2], "next") )
{
AppI* next = getNextWrap(getCurrentApp() );
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), next->getName() );
return bx::kExitSuccess;
}
else if (0 == bx::strCmp(_argv[2], "prev") )
{
AppI* prev = getCurrentApp();
for (AppI* app = getNextWrap(prev); app != getCurrentApp(); app = getNextWrap(app) )
{
prev = app;
}
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), prev->getName() );
return bx::kExitSuccess;
}
for (AppI* app = getFirstApp(); NULL != app; app = app->getNext() )
{
if (0 == bx::strCmp(_argv[2], app->getName() ) )
{
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), app->getName() );
return bx::kExitSuccess;
}
}
}
return bx::kExitFailure;
}
AppI::AppI(const char* _name, const char* _description)
{
m_name = _name;
m_description = _description;
m_next = s_apps;
s_apps = this;
s_numApps++;
}
AppI::~AppI()
{
for (AppI* prev = NULL, *app = s_apps, *next = app->getNext()
; NULL != app
; prev = app, app = next, next = app->getNext() )
{
if (app == this)
{
if (NULL != prev)
{
prev->m_next = next;
}
else
{
s_apps = next;
}
--s_numApps;
break;
}
}
}
const char* AppI::getName() const
{
return m_name;
}
const char* AppI::getDescription() const
{
return m_description;
}
AppI* AppI::getNext()
{
return m_next;
}
AppI* getFirstApp()
{
return s_apps;
}
uint32_t getNumApps()
{
return s_numApps;
}
int runApp(AppI* _app, int _argc, const char* const* _argv)
{
_app->init(_argc, _argv, s_width, s_height);
bgfx::frame();
WindowHandle defaultWindow = { 0 };
setWindowSize(defaultWindow, s_width, s_height);
#if BX_PLATFORM_EMSCRIPTEN
s_app = _app;
emscripten_set_main_loop(&updateApp, -1, 1);
#else
while (_app->update() )
{
if (0 != bx::strLen(s_restartArgs) )
{
break;
}
}
#endif // BX_PLATFORM_EMSCRIPTEN
return _app->shutdown();
}
static int32_t sortApp(const void* _lhs, const void* _rhs)
{
const AppI* lhs = *(const AppI**)_lhs;
const AppI* rhs = *(const AppI**)_rhs;
return bx::strCmpI(lhs->getName(), rhs->getName() );
}
static void sortApps()
{
if (2 > s_numApps)
{
return;
}
AppI** apps = (AppI**)BX_ALLOC(g_allocator, s_numApps*sizeof(AppI*) );
uint32_t ii = 0;
for (AppI* app = getFirstApp(); NULL != app; app = app->getNext() )
{
apps[ii++] = app;
}
bx::quickSort(apps, s_numApps, sizeof(AppI*), sortApp);
s_apps = apps[0];
for (ii = 1; ii < s_numApps; ++ii)
{
AppI* app = apps[ii-1];
app->m_next = apps[ii];
}
apps[s_numApps-1]->m_next = NULL;
BX_FREE(g_allocator, apps);
}
int main(int _argc, const char* const* _argv)
{
//DBG(BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME);
s_fileReader = BX_NEW(g_allocator, FileReader);
s_fileWriter = BX_NEW(g_allocator, FileWriter);
cmdInit();
cmdAdd("mouselock", cmdMouseLock);
cmdAdd("graphics", cmdGraphics );
cmdAdd("exit", cmdExit );
cmdAdd("app", cmdApp );
inputInit();
inputAddBindings("bindings", s_bindings);
entry::WindowHandle defaultWindow = { 0 };
bx::FilePath fp(_argv[0]);
char title[bx::kMaxFilePath];
bx::strCopy(title, BX_COUNTOF(title), fp.getBaseName() );
entry::setWindowTitle(defaultWindow, title);
setWindowSize(defaultWindow, ENTRY_DEFAULT_WIDTH, ENTRY_DEFAULT_HEIGHT);
sortApps();
const char* find = "";
if (1 < _argc)
{
find = _argv[_argc-1];
}
restart:
AppI* selected = NULL;
for (AppI* app = getFirstApp(); NULL != app; app = app->getNext() )
{
if (NULL == selected
&& !bx::strFindI(app->getName(), find).isEmpty() )
{
selected = app;
}
#if 0
DBG("%c %s, %s"
, app == selected ? '>' : ' '
, app->getName()
, app->getDescription()
);
#endif // 0
}
int32_t result = bx::kExitSuccess;
s_restartArgs[0] = '\0';
if (0 == s_numApps)
{
result = ::_main_(_argc, (char**)_argv);
}
else
{
result = runApp(getCurrentApp(selected), _argc, _argv);
}
if (0 != bx::strLen(s_restartArgs) )
{
find = s_restartArgs;
goto restart;
}
setCurrentDir("");
inputRemoveBindings("bindings");
inputShutdown();
cmdShutdown();
BX_DELETE(g_allocator, s_fileReader);
s_fileReader = NULL;
BX_DELETE(g_allocator, s_fileWriter);
s_fileWriter = NULL;
return result;
}
WindowState s_window[ENTRY_CONFIG_MAX_WINDOWS];
bool processEvents(uint32_t& _width, uint32_t& _height, uint32_t& _debug, uint32_t& _reset, MouseState* _mouse)
{
s_debug = _debug;
s_reset = _reset;
WindowHandle handle = { UINT16_MAX };
bool mouseLock = inputIsMouseLocked();
const Event* ev;
do
{
struct SE { const Event* m_ev; SE() : m_ev(poll() ) {} ~SE() { if (NULL != m_ev) { release(m_ev); } } } scopeEvent;
ev = scopeEvent.m_ev;
if (NULL != ev)
{
switch (ev->m_type)
{
case Event::Axis:
{
const AxisEvent* axis = static_cast<const AxisEvent*>(ev);
inputSetGamepadAxis(axis->m_gamepad, axis->m_axis, axis->m_value);
}
break;
case Event::Char:
{
const CharEvent* chev = static_cast<const CharEvent*>(ev);
inputChar(chev->m_len, chev->m_char);
}
break;
case Event::Exit:
return true;
case Event::Gamepad:
{
// const GamepadEvent* gev = static_cast<const GamepadEvent*>(ev);
// DBG("gamepad %d, %d", gev->m_gamepad.idx, gev->m_connected);
}
break;
case Event::Mouse:
{
const MouseEvent* mouse = static_cast<const MouseEvent*>(ev);
handle = mouse->m_handle;
inputSetMousePos(mouse->m_mx, mouse->m_my, mouse->m_mz);
if (!mouse->m_move)
{
inputSetMouseButtonState(mouse->m_button, mouse->m_down);
}
if (NULL != _mouse
&& !mouseLock)
{
_mouse->m_mx = mouse->m_mx;
_mouse->m_my = mouse->m_my;
_mouse->m_mz = mouse->m_mz;
if (!mouse->m_move)
{
_mouse->m_buttons[mouse->m_button] = mouse->m_down;
}
}
}
break;
case Event::Key:
{
const KeyEvent* key = static_cast<const KeyEvent*>(ev);
handle = key->m_handle;
inputSetKeyState(key->m_key, key->m_modifiers, key->m_down);
}
break;
case Event::Size:
{
const SizeEvent* size = static_cast<const SizeEvent*>(ev);
WindowState& win = s_window[0];
win.m_handle = size->m_handle;
win.m_width = size->m_width;
win.m_height = size->m_height;
handle = size->m_handle;
_width = size->m_width;
_height = size->m_height;
_reset = !s_reset; // force reset
}
break;
case Event::Window:
break;
case Event::Suspend:
break;
case Event::DropFile:
{
const DropFileEvent* drop = static_cast<const DropFileEvent*>(ev);
DBG("%s", drop->m_filePath.getCPtr() );
}
break;
default:
break;
}
}
inputProcess();
} while (NULL != ev);
if (handle.idx == 0
&& _reset != s_reset)
{
_reset = s_reset;
bgfx::reset(_width, _height, _reset);
inputSetMouseResolution(uint16_t(_width), uint16_t(_height) );
}
_debug = s_debug;
s_width = _width;
s_height = _height;
return s_exit;
}
bool processWindowEvents(WindowState& _state, uint32_t& _debug, uint32_t& _reset)
{
s_debug = _debug;
s_reset = _reset;
WindowHandle handle = { UINT16_MAX };
bool mouseLock = inputIsMouseLocked();
bool clearDropFile = true;
const Event* ev;
do
{
struct SE
{
SE(WindowHandle _handle)
: m_ev(poll(_handle) )
{
}
~SE()
{
if (NULL != m_ev)
{
release(m_ev);
}
}
const Event* m_ev;
} scopeEvent(handle);
ev = scopeEvent.m_ev;
if (NULL != ev)
{
handle = ev->m_handle;
WindowState& win = s_window[handle.idx];
switch (ev->m_type)
{
case Event::Axis:
{
const AxisEvent* axis = static_cast<const AxisEvent*>(ev);
inputSetGamepadAxis(axis->m_gamepad, axis->m_axis, axis->m_value);
}
break;
case Event::Char:
{
const CharEvent* chev = static_cast<const CharEvent*>(ev);
win.m_handle = chev->m_handle;
inputChar(chev->m_len, chev->m_char);
}
break;
case Event::Exit:
return true;
case Event::Gamepad:
{
const GamepadEvent* gev = static_cast<const GamepadEvent*>(ev);
DBG("gamepad %d, %d", gev->m_gamepad.idx, gev->m_connected);
}
break;
case Event::Mouse:
{
const MouseEvent* mouse = static_cast<const MouseEvent*>(ev);
win.m_handle = mouse->m_handle;
if (mouse->m_move)
{
inputSetMousePos(mouse->m_mx, mouse->m_my, mouse->m_mz);
}
else
{
inputSetMouseButtonState(mouse->m_button, mouse->m_down);
}
if (!mouseLock)
{
if (mouse->m_move)
{
win.m_mouse.m_mx = mouse->m_mx;
win.m_mouse.m_my = mouse->m_my;
win.m_mouse.m_mz = mouse->m_mz;
}
else
{
win.m_mouse.m_buttons[mouse->m_button] = mouse->m_down;
}
}
}
break;
case Event::Key:
{
const KeyEvent* key = static_cast<const KeyEvent*>(ev);
win.m_handle = key->m_handle;
inputSetKeyState(key->m_key, key->m_modifiers, key->m_down);
}
break;
case Event::Size:
{
const SizeEvent* size = static_cast<const SizeEvent*>(ev);
win.m_handle = size->m_handle;
win.m_width = size->m_width;
win.m_height = size->m_height;
_reset = win.m_handle.idx == 0
? !s_reset
: _reset
; // force reset
}
break;
case Event::Window:
{
const WindowEvent* window = static_cast<const WindowEvent*>(ev);
win.m_handle = window->m_handle;
win.m_nwh = window->m_nwh;
ev = NULL;
}
break;
case Event::Suspend:
break;
case Event::DropFile:
{
const DropFileEvent* drop = static_cast<const DropFileEvent*>(ev);
win.m_dropFile = drop->m_filePath;
clearDropFile = false;
}
break;
default:
break;
}
}
inputProcess();
} while (NULL != ev);
if (isValid(handle) )
{
WindowState& win = s_window[handle.idx];
if (clearDropFile)
{
win.m_dropFile.clear();
}
_state = win;
if (handle.idx == 0)
{
inputSetMouseResolution(uint16_t(win.m_width), uint16_t(win.m_height) );
}
}
if (_reset != s_reset)
{
_reset = s_reset;
bgfx::reset(s_window[0].m_width, s_window[0].m_height, _reset);
inputSetMouseResolution(uint16_t(s_window[0].m_width), uint16_t(s_window[0].m_height) );
}
_debug = s_debug;
return s_exit;
}
bx::FileReaderI* getFileReader()
{
return s_fileReader;
}
bx::FileWriterI* getFileWriter()
{
return s_fileWriter;
}
bx::AllocatorI* getAllocator()
{
if (NULL == g_allocator)
{
g_allocator = getDefaultAllocator();
}
return g_allocator;
}
void* TinyStlAllocator::static_allocate(size_t _bytes)
{
return BX_ALLOC(getAllocator(), _bytes);
}
void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
{
if (NULL != _ptr)
{
BX_FREE(getAllocator(), _ptr);
}
}
} // namespace entry
extern "C" bool entry_process_events(uint32_t* _width, uint32_t* _height, uint32_t* _debug, uint32_t* _reset)
{
return entry::processEvents(*_width, *_height, *_debug, *_reset, NULL);
}
| bsd-2-clause |
DrItanium/electron-platform | sys/src/electron/msgcom.c | 40001 | /*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.24 06/02/06 */
/* */
/* OBJECT MESSAGE COMMANDS */
/*******************************************************/
/*************************************************************/
/* Purpose: */
/* */
/* Principal Programmer(s): */
/* Brian L. Dantes */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* 6.23: Changed name of variable log to logName */
/* because of Unix compiler warnings of shadowed */
/* definitions. */
/* */
/* 6.24: Removed IMPERATIVE_MESSAGE_HANDLERS */
/* compilation flag. */
/* */
/* Corrected code to remove run-time program */
/* compiler warnings. */
/* */
/*************************************************************/
/* =========================================
*****************************************
EXTERNAL DEFINITIONS
=========================================
***************************************** */
#include "setup.h"
#if OBJECT_SYSTEM
#include <string.h>
#include "argacces.h"
#include "classcom.h"
#include "classfun.h"
#include "classinf.h"
#include "envrnmnt.h"
#include "insfun.h"
#include "insmoddp.h"
#include "msgfun.h"
#include "msgpass.h"
#include "memalloc.h"
#include "prccode.h"
#include "router.h"
#if BLOAD || BLOAD_AND_BSAVE
#include "bload.h"
#endif
#if ! RUN_TIME
#include "extnfunc.h"
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
#include "constrct.h"
#include "msgpsr.h"
#endif
#if DEBUGGING_FUNCTIONS
#include "watch.h"
#endif
#define _MSGCOM_SOURCE_
#include "msgcom.h"
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTION HEADERS
=========================================
***************************************** */
#if ! RUN_TIME
static void CreateSystemHandlers(void *);
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
static int WildDeleteHandler(void *,DEFCLASS *,SYMBOL_HN *,char *);
#endif
#if DEBUGGING_FUNCTIONS
static unsigned DefmessageHandlerWatchAccess(void *,int,unsigned,EXPRESSION *);
static unsigned DefmessageHandlerWatchPrint(void *,char *,int,EXPRESSION *);
static unsigned DefmessageHandlerWatchSupport(void *,char *,char *,int,
void (*)(void *,char *,void *,int),
void (*)(void *,int,void *,int),
EXPRESSION *);
static unsigned WatchClassHandlers(void *,void *,char *,int,char *,int,int,
void (*)(void *,char *,void *,int),
void (*)(void *,int,void *,int));
static void PrintHandlerWatchFlag(void *,char *,void *,int);
#endif
static void DeallocateMessageHandlerData(void *);
/* =========================================
*****************************************
EXTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/***************************************************
NAME : SetupMessageHandlers
DESCRIPTION : Sets up internal symbols and
fucntion definitions pertaining to
message-handlers. Also creates
system handlers
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Functions and data structures
initialized
NOTES : Should be called before
SetupInstanceModDupCommands() in
INSMODDP.C
***************************************************/
globle void SetupMessageHandlers(
void *theEnv)
{
ENTITY_RECORD handlerGetInfo = { (char*)"HANDLER_GET", HANDLER_GET,0,1,1,
PrintHandlerSlotGetFunction,
PrintHandlerSlotGetFunction,NULL,
HandlerSlotGetFunction,
NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL },
handlerPutInfo = { (char*)"HANDLER_PUT", HANDLER_PUT,0,1,1,
PrintHandlerSlotPutFunction,
PrintHandlerSlotPutFunction,NULL,
HandlerSlotPutFunction,
NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL };
AllocateEnvironmentData(theEnv,MESSAGE_HANDLER_DATA,sizeof(struct messageHandlerData),DeallocateMessageHandlerData);
memcpy(&MessageHandlerData(theEnv)->HandlerGetInfo,&handlerGetInfo,sizeof(struct entityRecord));
memcpy(&MessageHandlerData(theEnv)->HandlerPutInfo,&handlerPutInfo,sizeof(struct entityRecord));
MessageHandlerData(theEnv)->hndquals[0] = (char*)"around";
MessageHandlerData(theEnv)->hndquals[1] = (char*)"before";
MessageHandlerData(theEnv)->hndquals[2] = (char*)"primary";
MessageHandlerData(theEnv)->hndquals[3] = (char*)"after";
InstallPrimitive(theEnv,&MessageHandlerData(theEnv)->HandlerGetInfo,HANDLER_GET);
InstallPrimitive(theEnv,&MessageHandlerData(theEnv)->HandlerPutInfo,HANDLER_PUT);
#if ! RUN_TIME
MessageHandlerData(theEnv)->INIT_SYMBOL = (SYMBOL_HN *) EnvAddSymbol(theEnv,INIT_STRING);
IncrementSymbolCount(MessageHandlerData(theEnv)->INIT_SYMBOL);
MessageHandlerData(theEnv)->DELETE_SYMBOL = (SYMBOL_HN *) EnvAddSymbol(theEnv,DELETE_STRING);
IncrementSymbolCount(MessageHandlerData(theEnv)->DELETE_SYMBOL);
MessageHandlerData(theEnv)->CREATE_SYMBOL = (SYMBOL_HN *) EnvAddSymbol(theEnv,CREATE_STRING);
IncrementSymbolCount(MessageHandlerData(theEnv)->CREATE_SYMBOL);
EnvAddClearFunction(theEnv,(char*)"defclass",CreateSystemHandlers,-100);
#if ! BLOAD_ONLY
MessageHandlerData(theEnv)->SELF_SYMBOL = (SYMBOL_HN *) EnvAddSymbol(theEnv,SELF_STRING);
IncrementSymbolCount(MessageHandlerData(theEnv)->SELF_SYMBOL);
AddConstruct(theEnv,(char*)"defmessage-handler",(char*)"defmessage-handlers",
ParseDefmessageHandler,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
EnvDefineFunction2(theEnv,(char*)"undefmessage-handler",'v',PTIEF UndefmessageHandlerCommand,
(char*)"UndefmessageHandlerCommand",(char*)"23w");
#endif
EnvDefineFunction2(theEnv,(char*)"send",'u',PTIEF SendCommand,(char*)"SendCommand",(char*)"2*uuw");
#if DEBUGGING_FUNCTIONS
EnvDefineFunction2(theEnv,(char*)"preview-send",'v',PTIEF PreviewSendCommand,(char*)"PreviewSendCommand",(char*)"22w");
EnvDefineFunction2(theEnv,(char*)"ppdefmessage-handler",'v',PTIEF PPDefmessageHandlerCommand,
(char*)"PPDefmessageHandlerCommand",(char*)"23w");
EnvDefineFunction2(theEnv,(char*)"list-defmessage-handlers",'v',PTIEF ListDefmessageHandlersCommand,
(char*)"ListDefmessageHandlersCommand",(char*)"02w");
#endif
EnvDefineFunction2(theEnv,(char*)"next-handlerp",'b',PTIEF NextHandlerAvailable,(char*)"NextHandlerAvailable",(char*)"00");
FuncSeqOvlFlags(theEnv,(char*)"next-handlerp",TRUE,FALSE);
EnvDefineFunction2(theEnv,(char*)"call-next-handler",'u',
PTIEF CallNextHandler,(char*)"CallNextHandler",(char*)"00");
FuncSeqOvlFlags(theEnv,(char*)"call-next-handler",TRUE,FALSE);
EnvDefineFunction2(theEnv,(char*)"override-next-handler",'u',
PTIEF CallNextHandler,(char*)"CallNextHandler",NULL);
FuncSeqOvlFlags(theEnv,(char*)"override-next-handler",TRUE,FALSE);
EnvDefineFunction2(theEnv,(char*)"dynamic-get",'u',PTIEF DynamicHandlerGetSlot,(char*)"DynamicHandlerGetSlot",(char*)"11w");
EnvDefineFunction2(theEnv,(char*)"dynamic-put",'u',PTIEF DynamicHandlerPutSlot,(char*)"DynamicHandlerPutSlot",(char*)"1**w");
EnvDefineFunction2(theEnv,(char*)"get",'u',PTIEF DynamicHandlerGetSlot,(char*)"DynamicHandlerGetSlot",(char*)"11w");
EnvDefineFunction2(theEnv,(char*)"put",'u',PTIEF DynamicHandlerPutSlot,(char*)"DynamicHandlerPutSlot",(char*)"1**w");
#endif
#if DEBUGGING_FUNCTIONS
AddWatchItem(theEnv,(char*)"messages",0,&MessageHandlerData(theEnv)->WatchMessages,36,NULL,NULL);
AddWatchItem(theEnv,(char*)"message-handlers",0,&MessageHandlerData(theEnv)->WatchHandlers,35,
DefmessageHandlerWatchAccess,DefmessageHandlerWatchPrint);
#endif
}
/*******************************************************/
/* DeallocateMessageHandlerData: Deallocates environment */
/* data for the message handler functionality. */
/******************************************************/
static void DeallocateMessageHandlerData(
void *theEnv)
{
HANDLER_LINK *tmp, *mhead, *chead;
mhead = MessageHandlerData(theEnv)->TopOfCore;
while (mhead != NULL)
{
tmp = mhead;
mhead = mhead->nxt;
rtn_struct(theEnv,messageHandlerLink,tmp);
}
chead = MessageHandlerData(theEnv)->OldCore;
while (chead != NULL)
{
mhead = chead;
chead = chead->nxtInStack;
while (mhead != NULL)
{
tmp = mhead;
mhead = mhead->nxt;
rtn_struct(theEnv,messageHandlerLink,tmp);
}
}
}
/*****************************************************
NAME : EnvGetDefmessageHandlerName
DESCRIPTION : Gets the name of a message-handler
INPUTS : 1) Pointer to a class
2) Array index of handler in class's
message-handler array (+1)
RETURNS : Name-string of message-handler
SIDE EFFECTS : None
NOTES : None
*****************************************************/
char *EnvGetDefmessageHandlerName(
void *theEnv,
void *ptr,
int theIndex)
{
return(ValueToString(((DEFCLASS *) ptr)->handlers[theIndex-1].name));
}
/*****************************************************
NAME : EnvGetDefmessageHandlerType
DESCRIPTION : Gets the type of a message-handler
INPUTS : 1) Pointer to a class
2) Array index of handler in class's
message-handler array (+1)
RETURNS : Type-string of message-handler
SIDE EFFECTS : None
NOTES : None
*****************************************************/
globle char *EnvGetDefmessageHandlerType(
void *theEnv,
void *ptr,
int theIndex)
{
return(MessageHandlerData(theEnv)->hndquals[((DEFCLASS *) ptr)->handlers[theIndex-1].type]);
}
/**************************************************************
NAME : EnvGetNextDefmessageHandler
DESCRIPTION : Finds first or next handler for a class
INPUTS : 1) The address of the handler's class
2) The array index of the current handler (+1)
RETURNS : The array index (+1) of the next handler, or 0
if there is none
SIDE EFFECTS : None
NOTES : If index == 0, the first handler array index
(i.e. 1) returned
**************************************************************/
globle int EnvGetNextDefmessageHandler(
void *theEnv,
void *ptr,
int theIndex)
{
DEFCLASS *cls;
cls = (DEFCLASS *) ptr;
if (theIndex == 0)
return((cls->handlers != NULL) ? 1 : 0);
if (theIndex == cls->handlerCount)
return(0);
return(theIndex+1);
}
/*****************************************************
NAME : GetDefmessageHandlerPointer
DESCRIPTION : Returns a pointer to a handler
INPUTS : 1) Pointer to a class
2) Array index of handler in class's
message-handler array (+1)
RETURNS : Pointer to the handler.
SIDE EFFECTS : None
NOTES : None
*****************************************************/
globle HANDLER *GetDefmessageHandlerPointer(
void *ptr,
int theIndex)
{
return(&((DEFCLASS *) ptr)->handlers[theIndex-1]);
}
#if DEBUGGING_FUNCTIONS
/*********************************************************
NAME : EnvGetDefmessageHandlerWatch
DESCRIPTION : Determines if trace messages for calls
to this handler will be generated or not
INPUTS : 1) A pointer to the class
2) The index of the handler
RETURNS : TRUE if a trace is active,
FALSE otherwise
SIDE EFFECTS : None
NOTES : None
*********************************************************/
globle unsigned EnvGetDefmessageHandlerWatch(
void *theEnv,
void *theClass,
int theIndex)
{
return(((DEFCLASS *) theClass)->handlers[theIndex-1].trace);
}
/*********************************************************
NAME : EnvSetDefmessageHandlerWatch
DESCRIPTION : Sets the trace to ON/OFF for the
calling of the handler
INPUTS : 1) TRUE to set the trace on,
FALSE to set it off
2) A pointer to the class
3) The index of the handler
RETURNS : Nothing useful
SIDE EFFECTS : Watch flag for the handler set
NOTES : None
*********************************************************/
globle void EnvSetDefmessageHandlerWatch(
void *theEnv,
int newState,
void *theClass,
int theIndex)
{
((DEFCLASS *) theClass)->handlers[theIndex-1].trace = newState;
}
#endif
/***************************************************
NAME : EnvFindDefmessageHandler
DESCRIPTION : Determines the index of a specfied
message-handler
INPUTS : 1) A pointer to the class
2) Name-string of the handler
3) Handler-type: "around","before",
"primary", or "after"
RETURNS : The index of the handler
(0 if not found)
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle unsigned EnvFindDefmessageHandler(
void *theEnv,
void *ptr,
char *hname,
char *htypestr)
{
unsigned htype;
SYMBOL_HN *hsym;
DEFCLASS *cls;
int theIndex;
htype = HandlerType(theEnv,(char*)"handler-lookup",htypestr);
if (htype == MERROR)
return(0);
hsym = FindSymbolHN(theEnv,hname);
if (hsym == NULL)
return(0);
cls = (DEFCLASS *) ptr;
theIndex = FindHandlerByIndex(cls,hsym,(unsigned) htype);
return((unsigned) (theIndex+1));
}
/***************************************************
NAME : EnvIsDefmessageHandlerDeletable
DESCRIPTION : Determines if a message-handler
can be deleted
INPUTS : 1) Address of the handler's class
2) Index of the handler
RETURNS : TRUE if deletable, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
***************************************************/
globle int EnvIsDefmessageHandlerDeletable(
void *theEnv,
void *ptr,
int theIndex)
{
DEFCLASS *cls;
if (! ConstructsDeletable(theEnv))
{ return FALSE; }
cls = (DEFCLASS *) ptr;
if (cls->handlers[theIndex-1].system == 1)
return(FALSE);
#if (! BLOAD_ONLY) && (! RUN_TIME)
return((HandlersExecuting(cls) == FALSE) ? TRUE : FALSE);
#else
return FALSE;
#endif
}
/******************************************************************************
NAME : UndefmessageHandlerCommand
DESCRIPTION : Deletes a handler from a class
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Handler deleted if possible
NOTES : H/L Syntax: (undefmessage-handler <class> <handler> [<type>])
******************************************************************************/
globle void UndefmessageHandlerCommand(
void *theEnv)
{
#if RUN_TIME || BLOAD_ONLY
PrintErrorID(theEnv,(char*)"MSGCOM",3,FALSE);
EnvPrintRouter(theEnv,WERROR,(char*)"Unable to delete message-handlers.\n");
#else
SYMBOL_HN *mname;
char *tname;
DATA_OBJECT tmp;
DEFCLASS *cls;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded(theEnv))
{
PrintErrorID(theEnv,(char*)"MSGCOM",3,FALSE);
EnvPrintRouter(theEnv,WERROR,(char*)"Unable to delete message-handlers.\n");
return;
}
#endif
if (EnvArgTypeCheck(theEnv,(char*)"undefmessage-handler",1,SYMBOL,&tmp) == FALSE)
return;
cls = LookupDefclassByMdlOrScope(theEnv,DOToString(tmp));
if ((cls == NULL) ? (strcmp(DOToString(tmp),"*") != 0) : FALSE)
{
ClassExistError(theEnv,(char*)"undefmessage-handler",DOToString(tmp));
return;
}
if (EnvArgTypeCheck(theEnv,(char*)"undefmessage-handler",2,SYMBOL,&tmp) == FALSE)
return;
mname = (SYMBOL_HN *) tmp.value;
if (EnvRtnArgCount(theEnv) == 3)
{
if (EnvArgTypeCheck(theEnv,(char*)"undefmessage-handler",3,SYMBOL,&tmp) == FALSE)
return;
tname = DOToString(tmp);
if (strcmp(tname,"*") == 0)
tname = NULL;
}
else
tname = MessageHandlerData(theEnv)->hndquals[MPRIMARY];
WildDeleteHandler(theEnv,cls,mname,tname);
#endif
}
/***********************************************************
NAME : EnvUndefmessageHandler
DESCRIPTION : Deletes a handler from a class
INPUTS : 1) Class address (Can be NULL)
2) Handler index (can be 0)
RETURNS : 1 if successful, 0 otherwise
SIDE EFFECTS : Handler deleted if possible
NOTES : None
***********************************************************/
globle int EnvUndefmessageHandler(
void *theEnv,
void *vptr,
int mhi)
{
#if RUN_TIME || BLOAD_ONLY
PrintErrorID(theEnv,(char*)"MSGCOM",3,FALSE);
EnvPrintRouter(theEnv,WERROR,(char*)"Unable to delete message-handlers.\n");
return(0);
#else
DEFCLASS *cls;
#if BLOAD || BLOAD_AND_BSAVE
if (Bloaded(theEnv))
{
PrintErrorID(theEnv,(char*)"MSGCOM",3,FALSE);
EnvPrintRouter(theEnv,WERROR,(char*)"Unable to delete message-handlers.\n");
return(0);
}
#endif
if (vptr == NULL)
{
if (mhi != 0)
{
PrintErrorID(theEnv,(char*)"MSGCOM",1,FALSE);
EnvPrintRouter(theEnv,WERROR,(char*)"Incomplete message-handler specification for deletion.\n");
return(0);
}
return(WildDeleteHandler(theEnv,NULL,NULL,NULL));
}
if (mhi == 0)
return(WildDeleteHandler(theEnv,(DEFCLASS *) vptr,NULL,NULL));
cls = (DEFCLASS *) vptr;
if (HandlersExecuting(cls))
{
HandlerDeleteError(theEnv,EnvGetDefclassName(theEnv,(void *) cls));
return(0);
}
cls->handlers[mhi-1].mark = 1;
DeallocateMarkedHandlers(theEnv,cls);
return(1);
#endif
}
#if DEBUGGING_FUNCTIONS
/*******************************************************************************
NAME : PPDefmessageHandlerCommand
DESCRIPTION : Displays the pretty-print form (if any) for a handler
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (ppdefmessage-handler <class> <message> [<type>])
*******************************************************************************/
globle void PPDefmessageHandlerCommand(
void *theEnv)
{
DATA_OBJECT temp;
SYMBOL_HN *csym,*msym;
char *tname;
DEFCLASS *cls = NULL;
unsigned mtype;
HANDLER *hnd;
if (EnvArgTypeCheck(theEnv,(char*)"ppdefmessage-handler",1,SYMBOL,&temp) == FALSE)
return;
csym = FindSymbolHN(theEnv,DOToString(temp));
if (EnvArgTypeCheck(theEnv,(char*)"ppdefmessage-handler",2,SYMBOL,&temp) == FALSE)
return;
msym = FindSymbolHN(theEnv,DOToString(temp));
if (EnvRtnArgCount(theEnv) == 3)
{
if (EnvArgTypeCheck(theEnv,(char*)"ppdefmessage-handler",3,SYMBOL,&temp) == FALSE)
return;
tname = DOToString(temp);
}
else
tname = MessageHandlerData(theEnv)->hndquals[MPRIMARY];
mtype = HandlerType(theEnv,(char*)"ppdefmessage-handler",tname);
if (mtype == MERROR)
{
SetEvaluationError(theEnv,TRUE);
return;
}
if (csym != NULL)
cls = LookupDefclassByMdlOrScope(theEnv,ValueToString(csym));
if (((cls == NULL) || (msym == NULL)) ? TRUE :
((hnd = FindHandlerByAddress(cls,msym,(unsigned) mtype)) == NULL))
{
PrintErrorID(theEnv,(char*)"MSGCOM",2,FALSE);
EnvPrintRouter(theEnv,WERROR,(char*)"Unable to find message-handler ");
EnvPrintRouter(theEnv,WERROR,ValueToString(msym));
EnvPrintRouter(theEnv,WERROR,(char*)" ");
EnvPrintRouter(theEnv,WERROR,tname);
EnvPrintRouter(theEnv,WERROR,(char*)" for class ");
EnvPrintRouter(theEnv,WERROR,ValueToString(csym));
EnvPrintRouter(theEnv,WERROR,(char*)" in function ppdefmessage-handler.\n");
SetEvaluationError(theEnv,TRUE);
return;
}
if (hnd->ppForm != NULL)
PrintInChunks(theEnv,WDISPLAY,hnd->ppForm);
}
/*****************************************************************************
NAME : ListDefmessageHandlersCommand
DESCRIPTION : Depending on arguments, does lists handlers which
match restrictions
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : H/L Syntax: (list-defmessage-handlers [<class> [inherit]]))
*****************************************************************************/
globle void ListDefmessageHandlersCommand(
void *theEnv)
{
int inhp;
void *clsptr;
if (EnvRtnArgCount(theEnv) == 0)
EnvListDefmessageHandlers(theEnv,WDISPLAY,NULL,0);
else
{
clsptr = ClassInfoFnxArgs(theEnv,(char*)"list-defmessage-handlers",&inhp);
if (clsptr == NULL)
return;
EnvListDefmessageHandlers(theEnv,WDISPLAY,clsptr,inhp);
}
}
/********************************************************************
NAME : PreviewSendCommand
DESCRIPTION : Displays a list of the core for a message describing
shadows,etc.
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Temporary core created and destroyed
NOTES : H/L Syntax: (preview-send <class> <msg>)
********************************************************************/
globle void PreviewSendCommand(
void *theEnv)
{
DEFCLASS *cls;
DATA_OBJECT temp;
/* =============================
Get the class for the message
============================= */
if (EnvArgTypeCheck(theEnv,(char*)"preview-send",1,SYMBOL,&temp) == FALSE)
return;
cls = LookupDefclassByMdlOrScope(theEnv,DOToString(temp));
if (cls == NULL)
{
ClassExistError(theEnv,(char*)"preview-send",ValueToString(temp.value));
return;
}
if (EnvArgTypeCheck(theEnv,(char*)"preview-send",2,SYMBOL,&temp) == FALSE)
return;
EnvPreviewSend(theEnv,WDISPLAY,(void *) cls,DOToString(temp));
}
/********************************************************
NAME : EnvGetDefmessageHandlerPPForm
DESCRIPTION : Gets a message-handler pretty print form
INPUTS : 1) Address of the handler's class
2) Index of the handler
RETURNS : TRUE if printable, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
********************************************************/
globle char *EnvGetDefmessageHandlerPPForm(
void *theEnv,
void *ptr,
int theIndex)
{
return(((DEFCLASS *) ptr)->handlers[theIndex-1].ppForm);
}
/*******************************************************************
NAME : EnvListDefmessageHandlers
DESCRIPTION : Lists message-handlers for a class
INPUTS : 1) The logical name of the output
2) Class name (NULL to display all handlers)
3) A flag indicating whether to list inherited
handlers or not
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
*******************************************************************/
globle void EnvListDefmessageHandlers(
void *theEnv,
char *logName,
void *vptr,
int inhp)
{
DEFCLASS *cls;
long cnt;
PACKED_CLASS_LINKS plinks;
if (vptr != NULL)
{
cls = (DEFCLASS *) vptr;
if (inhp)
cnt = DisplayHandlersInLinks(theEnv,logName,&cls->allSuperclasses,0);
else
{
plinks.classCount = 1;
plinks.classArray = &cls;
cnt = DisplayHandlersInLinks(theEnv,logName,&plinks,0);
}
}
else
{
plinks.classCount = 1;
cnt = 0L;
for (cls = (DEFCLASS *) EnvGetNextDefclass(theEnv,NULL) ;
cls != NULL ;
cls = (DEFCLASS *) EnvGetNextDefclass(theEnv,(void *) cls))
{
plinks.classArray = &cls;
cnt += DisplayHandlersInLinks(theEnv,logName,&plinks,0);
}
}
PrintTally(theEnv,logName,cnt,(char*)"message-handler",(char*)"message-handlers");
}
/********************************************************************
NAME : EnvPreviewSend
DESCRIPTION : Displays a list of the core for a message describing
shadows,etc.
INPUTS : 1) Logical name of output
2) Class pointer
3) Message name-string
RETURNS : Nothing useful
SIDE EFFECTS : Temporary core created and destroyed
NOTES : None
********************************************************************/
globle void EnvPreviewSend(
void *theEnv,
char *logicalName,
void *clsptr,
char *msgname)
{
HANDLER_LINK *core;
SYMBOL_HN *msym;
msym = FindSymbolHN(theEnv,msgname);
if (msym == NULL)
return;
core = FindPreviewApplicableHandlers(theEnv,(DEFCLASS *) clsptr,msym);
if (core != NULL)
{
DisplayCore(theEnv,logicalName,core,0);
DestroyHandlerLinks(theEnv,core);
}
}
/****************************************************
NAME : DisplayHandlersInLinks
DESCRIPTION : Recursively displays all handlers
for an array of classes
INPUTS : 1) The logical name of the output
2) The packed class links
3) The index to print from the links
RETURNS : The number of handlers printed
SIDE EFFECTS : None
NOTES : Used by DescribeClass()
****************************************************/
globle long DisplayHandlersInLinks(
void *theEnv,
char *logName,
PACKED_CLASS_LINKS *plinks,
int theIndex)
{
long i;
long cnt;
cnt = (long) plinks->classArray[theIndex]->handlerCount;
if (((int) theIndex) < (plinks->classCount - 1))
cnt += DisplayHandlersInLinks(theEnv,logName,plinks,theIndex + 1);
for (i = 0 ; i < plinks->classArray[theIndex]->handlerCount ; i++)
PrintHandler(theEnv,logName,&plinks->classArray[theIndex]->handlers[i],TRUE);
return(cnt);
}
#endif
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
#if ! RUN_TIME
/**********************************************************
NAME : CreateSystemHandlers
DESCRIPTION : Attachess the system message-handlers
after a (clear)
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : System handlers created
NOTES : Must be called after CreateSystemClasses()
**********************************************************/
static void CreateSystemHandlers(
void *theEnv)
{
NewSystemHandler(theEnv,USER_TYPE_NAME,INIT_STRING,(char*)"init-slots",0);
NewSystemHandler(theEnv,USER_TYPE_NAME,DELETE_STRING,(char*)"delete-instance",0);
NewSystemHandler(theEnv,USER_TYPE_NAME,CREATE_STRING,(char*)"(create-instance)",0);
#if DEBUGGING_FUNCTIONS
NewSystemHandler(theEnv,USER_TYPE_NAME,PRINT_STRING,(char*)"ppinstance",0);
#endif
NewSystemHandler(theEnv,USER_TYPE_NAME,DIRECT_MODIFY_STRING,(char*)"(direct-modify)",1);
NewSystemHandler(theEnv,USER_TYPE_NAME,MSG_MODIFY_STRING,(char*)"(message-modify)",1);
NewSystemHandler(theEnv,USER_TYPE_NAME,DIRECT_DUPLICATE_STRING,(char*)"(direct-duplicate)",2);
NewSystemHandler(theEnv,USER_TYPE_NAME,MSG_DUPLICATE_STRING,(char*)"(message-duplicate)",2);
}
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
/************************************************************
NAME : WildDeleteHandler
DESCRIPTION : Deletes a handler from a class
INPUTS : 1) Class address (Can be NULL)
2) Message Handler Name (Can be NULL)
3) Type name ("primary", etc.)
RETURNS : 1 if successful, 0 otherwise
SIDE EFFECTS : Handler deleted if possible
NOTES : None
************************************************************/
static int WildDeleteHandler(
void *theEnv,
DEFCLASS *cls,
SYMBOL_HN *msym,
char *tname)
{
int mtype;
if (msym == NULL)
msym = (SYMBOL_HN *) EnvAddSymbol(theEnv,(char*)"*");
if (tname != NULL)
{
mtype = (int) HandlerType(theEnv,(char*)"undefmessage-handler",tname);
if (mtype == MERROR)
return(0);
}
else
mtype = -1;
if (cls == NULL)
{
int success = 1;
for (cls = (DEFCLASS *) EnvGetNextDefclass(theEnv,NULL) ;
cls != NULL ;
cls = (DEFCLASS *) EnvGetNextDefclass(theEnv,(void *) cls))
if (DeleteHandler(theEnv,cls,msym,mtype,FALSE) == 0)
success = 0;
return(success);
}
return(DeleteHandler(theEnv,cls,msym,mtype,TRUE));
}
#endif
#if DEBUGGING_FUNCTIONS
/******************************************************************
NAME : DefmessageHandlerWatchAccess
DESCRIPTION : Parses a list of class names passed by
AddWatchItem() and sets the traces accordingly
INPUTS : 1) A code indicating which trace flag is to be set
0 - Watch instance creation/deletion
1 - Watch slot changes to instances
2) The value to which to set the trace flags
3) A list of expressions containing the names
of the classes for which to set traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags set in specified classes
NOTES : Accessory function for AddWatchItem()
******************************************************************/
static unsigned DefmessageHandlerWatchAccess(
void *theEnv,
int code,
unsigned newState,
EXPRESSION *argExprs)
{
if (newState)
return(DefmessageHandlerWatchSupport(theEnv,(char*)"watch",NULL,newState,
NULL,EnvSetDefmessageHandlerWatch,argExprs));
else
return(DefmessageHandlerWatchSupport(theEnv,(char*)"unwatch",NULL,newState,
NULL,EnvSetDefmessageHandlerWatch,argExprs));
}
/***********************************************************************
NAME : DefmessageHandlerWatchPrint
DESCRIPTION : Parses a list of class names passed by
AddWatchItem() and displays the traces accordingly
INPUTS : 1) The logical name of the output
2) A code indicating which trace flag is to be examined
0 - Watch instance creation/deletion
1 - Watch slot changes to instances
3) A list of expressions containing the names
of the classes for which to examine traces
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Watch flags displayed for specified classes
NOTES : Accessory function for AddWatchItem()
***********************************************************************/
static unsigned DefmessageHandlerWatchPrint(
void *theEnv,
char *logName,
int code,
EXPRESSION *argExprs)
{
return(DefmessageHandlerWatchSupport(theEnv,(char*)"list-watch-items",logName,-1,
PrintHandlerWatchFlag,NULL,argExprs));
}
/*******************************************************
NAME : DefmessageHandlerWatchSupport
DESCRIPTION : Sets or displays handlers specified
INPUTS : 1) The calling function name
2) The logical output name for displays
(can be NULL)
4) The new set state (can be -1)
5) The print function (can be NULL)
6) The trace function (can be NULL)
7) The handlers expression list
RETURNS : TRUE if all OK,
FALSE otherwise
SIDE EFFECTS : Handler trace flags set or displayed
NOTES : None
*******************************************************/
static unsigned DefmessageHandlerWatchSupport(
void *theEnv,
char *funcName,
char *logName,
int newState,
void (*printFunc)(void *,char *,void *,int),
void (*traceFunc)(void *,int,void *,int),
EXPRESSION *argExprs)
{
struct defmodule *theModule;
void *theClass;
char *theHandlerStr;
int theType;
int argIndex = 2;
DATA_OBJECT tmpData;
/* ===============================
If no handlers are specified,
show the trace for all handlers
in all handlers
=============================== */
if (argExprs == NULL)
{
SaveCurrentModule(theEnv);
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,NULL);
while (theModule != NULL)
{
EnvSetCurrentModule(theEnv,(void *) theModule);
if (traceFunc == NULL)
{
EnvPrintRouter(theEnv,logName,EnvGetDefmoduleName(theEnv,(void *) theModule));
EnvPrintRouter(theEnv,logName,(char*)":\n");
}
theClass = EnvGetNextDefclass(theEnv,NULL);
while (theClass != NULL)
{
if (WatchClassHandlers(theEnv,theClass,NULL,-1,logName,newState,
TRUE,printFunc,traceFunc) == FALSE)
return(FALSE);
theClass = EnvGetNextDefclass(theEnv,theClass);
}
theModule = (struct defmodule *) EnvGetNextDefmodule(theEnv,(void *) theModule);
}
RestoreCurrentModule(theEnv);
return(TRUE);
}
/* ================================================
Set or show the traces for the specified handler
================================================ */
while (argExprs != NULL)
{
if (EvaluateExpression(theEnv,argExprs,&tmpData))
return(FALSE);
if (tmpData.type != SYMBOL)
{
ExpectedTypeError1(theEnv,funcName,argIndex,(char*)"class name");
return(FALSE);
}
theClass = (void *) LookupDefclassByMdlOrScope(theEnv,DOToString(tmpData));
if (theClass == NULL)
{
ExpectedTypeError1(theEnv,funcName,argIndex,(char*)"class name");
return(FALSE);
}
if (GetNextArgument(argExprs) != NULL)
{
argExprs = GetNextArgument(argExprs);
argIndex++;
if (EvaluateExpression(theEnv,argExprs,&tmpData))
return(FALSE);
if (tmpData.type != SYMBOL)
{
ExpectedTypeError1(theEnv,funcName,argIndex,(char*)"handler name");
return(FALSE);
}
theHandlerStr = DOToString(tmpData);
if (GetNextArgument(argExprs) != NULL)
{
argExprs = GetNextArgument(argExprs);
argIndex++;
if (EvaluateExpression(theEnv,argExprs,&tmpData))
return(FALSE);
if (tmpData.type != SYMBOL)
{
ExpectedTypeError1(theEnv,funcName,argIndex,(char*)"handler type");
return(FALSE);
}
if ((theType = (int) HandlerType(theEnv,funcName,DOToString(tmpData))) == MERROR)
return(FALSE);
}
else
theType = -1;
}
else
{
theHandlerStr = NULL;
theType = -1;
}
if (WatchClassHandlers(theEnv,theClass,theHandlerStr,theType,logName,
newState,FALSE,printFunc,traceFunc) == FALSE)
{
ExpectedTypeError1(theEnv,funcName,argIndex,(char*)"handler");
return(FALSE);
}
argIndex++;
argExprs = GetNextArgument(argExprs);
}
return(TRUE);
}
/*******************************************************
NAME : WatchClassHandlers
DESCRIPTION : Sets or displays handlers specified
INPUTS : 1) The class
2) The handler name (or NULL wildcard)
3) The handler type (or -1 wildcard)
4) The logical output name for displays
(can be NULL)
5) The new set state (can be -1)
6) The print function (can be NULL)
7) The trace function (can be NULL)
RETURNS : TRUE if all OK,
FALSE otherwise
SIDE EFFECTS : Handler trace flags set or displayed
NOTES : None
*******************************************************/
static unsigned WatchClassHandlers(
void *theEnv,
void *theClass,
char *theHandlerStr,
int theType,
char *logName,
int newState,
int indentp,
void (*printFunc)(void *,char *,void *,int),
void (*traceFunc)(void *,int,void *,int))
{
unsigned theHandler;
int found = FALSE;
theHandler = EnvGetNextDefmessageHandler(theEnv,theClass,0);
while (theHandler != 0)
{
if ((theType == -1) ? TRUE :
(theType == (int) ((DEFCLASS *) theClass)->handlers[theHandler-1].type))
{
if ((theHandlerStr == NULL) ? TRUE :
(strcmp(theHandlerStr,EnvGetDefmessageHandlerName(theEnv,theClass,theHandler)) == 0))
{
if (traceFunc != NULL)
(*traceFunc)(theEnv,newState,theClass,theHandler);
else
{
if (indentp)
EnvPrintRouter(theEnv,logName,(char*)" ");
(*printFunc)(theEnv,logName,theClass,theHandler);
}
found = TRUE;
}
}
theHandler = EnvGetNextDefmessageHandler(theEnv,theClass,theHandler);
}
if ((theHandlerStr != NULL) && (theType != -1) && (found == FALSE))
return(FALSE);
return(TRUE);
}
/***************************************************
NAME : PrintHandlerWatchFlag
DESCRIPTION : Displays trace value for handler
INPUTS : 1) The logical name of the output
2) The class
3) The handler index
RETURNS : Nothing useful
SIDE EFFECTS : None
NOTES : None
***************************************************/
static void PrintHandlerWatchFlag(
void *theEnv,
char *logName,
void *theClass,
int theHandler)
{
EnvPrintRouter(theEnv,logName,EnvGetDefclassName(theEnv,theClass));
EnvPrintRouter(theEnv,logName,(char*)" ");
EnvPrintRouter(theEnv,logName,EnvGetDefmessageHandlerName(theEnv,theClass,theHandler));
EnvPrintRouter(theEnv,logName,(char*)" ");
EnvPrintRouter(theEnv,logName,EnvGetDefmessageHandlerType(theEnv,theClass,theHandler));
if (EnvGetDefmessageHandlerWatch(theEnv,theClass,theHandler))
EnvPrintRouter(theEnv,logName,(char*)" = on\n");
else
EnvPrintRouter(theEnv,logName,(char*)" = off\n");
}
#endif /* DEBUGGING_FUNCTIONS */
#endif
| bsd-2-clause |
kit-transue/software-emancipation-discover | psethome/lib/Learn/src/ttt/include/application.H | 2370 | /*************************************************************************
* Copyright (c) 2015, Synopsys, Inc. *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
*************************************************************************/
#ifndef _application_h_
#define _application_h_
// standard
#include <string.h>
class application {
public:
application(char* name = " ");
virtual ~application();
virtual void giveName(char* name);
virtual char* getName();
virtual void save(char* );
virtual void restore(char* );
protected:
char* name;
};
#endif
| bsd-2-clause |
eegeo/eegeo-example-app | src/SearchMenu/View/SearchWidgetController.cpp | 14669 | // Copyright WRLD Ltd (2018-), All Rights Reserved
#include "SearchWidgetController.h"
#include "SearchResultSectionItemSelectedMessage.h"
#include "SearchServicesResult.h"
#include "IMenuSectionViewModel.h"
#include "NavigateToMessage.h"
#include "IMenuView.h"
#include "IMenuOption.h"
#include "MenuItemModel.h"
#include "IMenuModel.h"
#include "ISearchResultsRepository.h"
#include "SearchNavigationData.h"
namespace ExampleApp
{
namespace SearchMenu
{
namespace View
{
SearchWidgetController::SearchWidgetController(ISearchWidgetView& view,
ISearchResultsRepository& resultsRepository,
Modality::View::IModalBackgroundView& modalBackgroundView,
Menu::View::IMenuViewModel& viewModel,
ExampleAppMessaging::TMessageBus& messageBus,
ISearchProvider& searchProvider)
: m_view(view)
, m_modalBackgroundView(modalBackgroundView)
, m_viewModel(viewModel)
, m_messageBus(messageBus)
, m_resultsRepository(resultsRepository)
, m_onSearchResultsClearedCallback(this, &SearchWidgetController::OnSearchResultsCleared)
, m_onSearchResultSelectedCallback(this, &SearchWidgetController::OnSearchResultSelected)
, m_onNavigationRequestedCallback(this, &SearchWidgetController::OnNavigationRequested)
, m_onSearchQueryClearRequestHandler(this, &SearchWidgetController::OnSearchQueryClearRequest)
, m_onSearchQueryRefreshedHandler(this, &SearchWidgetController::OnSearchQueryRefreshedMessage)
, m_onSearchQueryResultsLoadedHandler(this, &SearchWidgetController::OnSearchResultsLoaded)
, m_deepLinkRequestedHandler(this, &SearchWidgetController::OnSearchRequestedMessage)
, m_menuContentsChanged(true)
, m_inInteriorMode(false)
, m_onAppModeChanged(this, &SearchWidgetController::OnAppModeChanged)
, m_onItemSelectedCallback(this, &SearchWidgetController::OnItemSelected)
, m_onItemAddedCallback(this, &SearchWidgetController::OnItemAdded)
, m_onItemRemovedCallback(this, &SearchWidgetController::OnItemRemoved)
, m_onScreenStateChanged(this, &SearchWidgetController::OnScreenControlStateChanged)
, m_onOpenableStateChanged(this, &SearchWidgetController::OnOpenableStateChanged)
, m_onModalBackgroundTouchCallback(this, &SearchWidgetController::OnModalBackgroundTouch)
, m_onViewOpenedCallback(this, &SearchWidgetController::OnViewOpened)
, m_onViewClosedCallback(this, &SearchWidgetController::OnViewClosed)
, m_tagCollection(m_messageBus)
, m_previousVisibleTextFromTagSearch("")
, m_shouldSelectFirstResult(false)
{
m_view.InsertSearchClearedCallback(m_onSearchResultsClearedCallback);
m_view.InsertResultSelectedCallback(m_onSearchResultSelectedCallback);
m_view.InsertOnItemSelected(m_onItemSelectedCallback);
m_view.InsertOnViewClosed(m_onViewClosedCallback);
m_view.InsertOnViewOpened(m_onViewOpenedCallback);
m_view.InsertOnNavigationRequestedCallback(m_onNavigationRequestedCallback);
m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);
m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);
m_modalBackgroundView.InsertTouchCallback(m_onModalBackgroundTouchCallback);
m_messageBus.SubscribeUi(m_onSearchQueryRefreshedHandler);
m_messageBus.SubscribeUi(m_onSearchQueryResultsLoadedHandler);
m_messageBus.SubscribeUi(m_onSearchQueryClearRequestHandler);
m_messageBus.SubscribeUi(m_deepLinkRequestedHandler);
m_messageBus.SubscribeUi(m_onAppModeChanged);
for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)
{
Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(static_cast<int>(i)));
SetGroupStart(section);
Menu::View::IMenuModel& menuModel = section.GetModel();
menuModel.InsertItemAddedCallback(m_onItemAddedCallback);
menuModel.InsertItemRemovedCallback(m_onItemRemovedCallback);
}
searchProvider.InsertSearchPerformedCallback(m_modalBackgroundView.GetSearchPerformedCallback());
}
SearchWidgetController::~SearchWidgetController()
{
for(int i = static_cast<int>(m_viewModel.SectionsCount()); --i >= 0;)
{
Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));
Menu::View::IMenuModel& menuModel = section.GetModel();
menuModel.RemoveItemAddedCallback(m_onItemAddedCallback);
menuModel.RemoveItemRemovedCallback(m_onItemRemovedCallback);
}
m_messageBus.UnsubscribeUi(m_onAppModeChanged);
m_messageBus.UnsubscribeUi(m_onSearchQueryRefreshedHandler);
m_messageBus.UnsubscribeUi(m_onSearchQueryClearRequestHandler);
m_messageBus.UnsubscribeUi(m_onSearchQueryResultsLoadedHandler);
m_messageBus.UnsubscribeUi(m_deepLinkRequestedHandler);
m_modalBackgroundView.RemoveTouchCallback(m_onModalBackgroundTouchCallback);
m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);
m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);
m_view.RemoveOnNavigationRequestedCallback(m_onNavigationRequestedCallback);
m_view.RemoveOnViewClosed(m_onViewClosedCallback);
m_view.RemoveResultSelectedCallback(m_onSearchResultSelectedCallback);
m_view.RemoveSearchClearedCallback(m_onSearchResultsClearedCallback);
m_view.RemoveOnItemSelected(m_onItemSelectedCallback);
m_view.RemoveOnItemSelected(m_onItemSelectedCallback);
}
void SearchWidgetController::SetGroupStart(Menu::View::IMenuSectionViewModel& section)
{
if (section.Name() == "Find" ||
section.Name() == "Drop Pin" ||
section.Name() == "Weather")
{
section.SetGroupStart(true);
}
}
void SearchWidgetController::OnItemAdded(Menu::View::MenuItemModel& item) {
m_menuContentsChanged = true;
}
void SearchWidgetController::OnItemRemoved(Menu::View::MenuItemModel& item){
m_menuContentsChanged = true;
}
void SearchWidgetController::OnSearchResultsCleared()
{
m_messageBus.Publish(SearchResultSection::SearchResultViewClearedMessage());
}
void SearchWidgetController::OnSearchResultSelected(int& index)
{
const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_resultsRepository.GetSdkSearchResultByIndex(index);
m_messageBus.Publish(SearchResultSection::SearchResultSectionItemSelectedMessage(
sdkSearchResult.GetLocation().ToECEF(),
sdkSearchResult.IsInterior(),
sdkSearchResult.GetBuildingId(),
sdkSearchResult.GetFloor(),
m_resultsRepository.GetResultOriginalIndexFromCurrentIndex(index),
sdkSearchResult.GetIdentifier()));
}
void SearchWidgetController::OnNavigationRequested(const int& index)
{
const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_resultsRepository.GetSdkSearchResultByIndex(index);
const NavRouting::SearchNavigationData searchNavigationData(sdkSearchResult);
m_messageBus.Publish(NavRouting::NavigateToMessage(searchNavigationData));
}
void SearchWidgetController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)
{
if (m_shouldSelectFirstResult && message.GetResults().size() > 0){
int val = 0;
OnSearchResultSelected(val);
m_shouldSelectFirstResult = false;
}
}
void SearchWidgetController::OnSearchQueryRefreshedMessage(const Search::SearchQueryRefreshedMessage& message)
{
const Search::SdkModel::SearchQuery &query = message.Query();
std::string visibleText = query.Query();
std::string tagText = "";
if (query.IsTag())
{
tagText = visibleText;
visibleText = m_previousVisibleTextFromTagSearch;
}
m_view.PerformSearch(visibleText,
QueryContext(false,
query.IsTag(),
tagText,
query.ShouldTryInteriorSearch(),
message.Location(),
message.Radius()));
}
void SearchWidgetController::OnSearchQueryClearRequest(const Search::SearchQueryClearRequestMessage &message)
{
m_view.ClearSearchResults();
}
void SearchWidgetController::OnSearchRequestedMessage(const Search::SearchQueryRequestMessage& message)
{
// needed to avoid a reentrant call on the reactor logic on startup queries / deeplinks
m_view.CloseMenu();
auto query = message.Query();
auto clearPreviousResults = false;
std::string visibleText = query.Query();
std::string tagText = "";
if (query.IsTag())
{
tagText = visibleText;
if (m_tagCollection.HasText(tagText))
{
const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);
visibleText = tagInfo.VisibleText();
}
}
m_previousVisibleTextFromTagSearch = visibleText;
auto queryContext = QueryContext(clearPreviousResults,
query.IsTag(),
tagText,
query.ShouldTryInteriorSearch(),
query.Location(),
query.Radius());
m_shouldSelectFirstResult = query.SelectFirstResult();
m_view.PerformSearch(visibleText, queryContext);
}
void SearchWidgetController::UpdateUiThread(float dt)
{
RefreshPresentation();
}
void SearchWidgetController::OnAppModeChanged(const AppModes::AppModeChangedMessage &message)
{
m_menuContentsChanged = true;
m_inInteriorMode = message.GetAppMode() == AppModes::SdkModel::AppMode::InteriorMode;
RefreshPresentation();
}
void SearchWidgetController::OnItemSelected(const std::string& menuText, int& sectionIndex, int& itemIndex)
{
Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);
if (m_tagCollection.HasTag(menuText))
{
m_view.ClearSearchResults();
TagCollection::TagInfo tagInfo = m_tagCollection.GetInfoByText(menuText);
m_previousVisibleTextFromTagSearch = menuText;
m_view.PerformSearch(menuText,
QueryContext(true, true, tagInfo.Tag(),
tagInfo.ShouldTryInterior()));
}
else if(!section.IsExpandable() || section.GetTotalItemCount()>0)
{
section.GetItemAtIndex(itemIndex).MenuOption().Select();
}
}
void SearchWidgetController::RefreshPresentation()
{
if (!m_menuContentsChanged)
{
return;
}
m_menuContentsChanged = false;
const size_t numSections = m_viewModel.SectionsCount();
Menu::View::TSections sections;
sections.reserve(numSections);
for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)
{
Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(static_cast<int>(groupIndex));
if (section.Name() != "Discover" || !m_inInteriorMode)
{
sections.push_back(§ion);
}
}
m_view.UpdateMenuSectionViews(sections);
}
void SearchWidgetController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel)
{
if(m_viewModel.IsOnScreen())
{
if (m_viewModel.IsOpen())
{
m_view.SetOnScreen();
}
}
else
{
m_view.SetOffScreen();
}
}
void SearchWidgetController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel)
{
if (m_viewModel.IsOnScreen())
{
m_view.SetOnScreen();
}
else if (m_viewModel.IsOffScreen())
{
m_view.SetOffScreen();
}
}
void SearchWidgetController::OnViewOpened()
{
if(!m_viewModel.IsOpen())
{
m_viewModel.Open();
}
}
void SearchWidgetController::OnViewClosed()
{
if(!m_viewModel.IsClosed())
{
m_viewModel.Close();
}
}
void SearchWidgetController::OnModalBackgroundTouch()
{
// the modal background goes away after the first touch, so no need to throttle
m_view.CloseMenu();
}
}
}
}
| bsd-2-clause |
L2G/homebrew-cask | Casks/delivery-status.rb | 658 | cask :v1 => 'delivery-status' do
version '6.1.2'
sha256 'f39afd137c99df16baf149c60f1a982edb9485f6211f4aefb9cad19af7a51514'
url "http://junecloud.com/get/delivery-status-widget?#{version}"
homepage 'http://junecloud.com/software/mac/delivery-status.html'
license :oss
widget 'Delivery Status.wdgt'
caveats <<-EOS.undent
Currently, Dashboard Widgets such as '#{title}' do NOT work correctly
when installed via brew-cask. The bug is being tracked here:
https://github.com/caskroom/homebrew-cask/issues/2206
It is recommended that you do not install this Cask unless you are
a developer working on the problem.
EOS
end
| bsd-2-clause |
khmseu/asn1c | libasn1compiler/asn1compiler.h | 2584 | #ifndef ASN1_COMPILER_H
#define ASN1_COMPILER_H
#include <asn1parser.h>
enum asn1c_flags {
A1C_NOFLAGS,
/*
* Debug the compiler.
*/
A1C_DEBUG = 0x0001,
/*
* Do not split the target output in several files, just print it.
* (Note: the output is not likely to be compilable in this case).
*/
A1C_PRINT_COMPILED = 0x0002,
/*
* Generate only the tables for ASN.1 types,
* do not emit ASN.1 parsing support code.
*/
A1C_OMIT_SUPPORT_CODE = 0x0004,
/*
* Use wide types by default (INTEGER_t etc) instead of native/long.
*/
A1C_USE_WIDE_TYPES = 0x0008,
/*
* Do not use C99 extensions.
*/
A1C_NO_C99 = 0x0010,
/*
* Enable use of unnamed unions (non-portable feature).
*/
A1C_UNNAMED_UNIONS = 0x0020,
/*
* Don't make the asn1_DEF_'s of structure members "static".
*/
A1C_ALL_DEFS_GLOBAL = 0x0040,
/*
* Do not generate constraint checking code.
*/
A1C_NO_CONSTRAINTS = 0x0080,
/*
* Generate type_id_PR_member things identifiers of id_PR_member.
*/
A1C_COMPOUND_NAMES = 0x0100,
/*
* Do not generate courtesy #includes for external dependencies.
*/
A1C_NO_INCLUDE_DEPS = 0x0200,
/*
* Compile members of CHOICE as indirect pointers.
*/
A1C_INDIRECT_CHOICE = 0x0400,
/*
* -flink-skeletons
* Symlink support files rather than copy them.
*/
A1C_LINK_SKELETONS = 0x0800,
/*
* -pdu={all|auto|Type}
* Generate PDU table
*/
A1C_PDU_ALL = 0x2000,
A1C_PDU_AUTO = 0x4000,
A1C_PDU_TYPE = 0x8000,
/*
* -fincludes-quoted
* Avoid generating #include <foo>, generate "foo" instead.
*/
A1C_INCLUDES_QUOTED = 0x10000,
/*
* -fline-refs
* Include ASN.1 module's line numbers in comments.
*/
A1C_LINE_REFS = 0x20000,
/*
* -gen-OER
* Generate Octet Encoding Rules support code
*/
A1C_GEN_OER = 0x40000,
/*
* -gen-PER
* Generate Packed Encoding Rules support code
*/
A1C_GEN_PER = 0x80000,
/*
* Generate converter-example.c and converter-example.mk
*/
A1C_GEN_EXAMPLE = 0x100000,
/*
* Generate top-level configure.ac and Makefile.am
*/
A1C_GEN_AUTOTOOLS_EXAMPLE = 0x200000,
/*
* Print the source of generated lines.
* -debug-output-origin-lines
*/
A1C_DEBUG_OUTPUT_ORIGIN_LINES = 0x400000,
};
/*
* Compile the ASN.1 specification.
*/
int asn1_compile(asn1p_t *asn, const char *datadir, const char *destdir, enum asn1c_flags,
int argc, int optc, char **argv);
void asn1c_debug_type_naming(asn1p_t *asn, enum asn1c_flags,
char **asn_type_names);
void asn1c__add_pdu_type(const char *typename);
#endif /* ASN1_COMPILER_H */
| bsd-2-clause |
renegelinas/mi-instrument | mi/dataset/parser/metbk_a_dcl.py | 7536 | #!/usr/bin/env python
"""
@package mi.dataset.parser.metbk_a_dcl
@file marine-integrations/mi/dataset/parser/metbk_a_dcl.py
@author Ronald Ronquillo
@brief Parser for the metbk_a_dcl dataset driver
This file contains code for the metbk_a_dcl parsers and code to produce data particles.
For telemetered data, there is one parser which produces one type of data particle.
For recovered data, there is one parser which produces one type of data particle.
The input files and the content of the data particles are the same for both
recovered and telemetered.
Only the names of the output particle streams are different.
The input file is ASCII and contains 2 types of records.
Records are separated by a newline.
All records start with a timestamp.
Metadata records: timestamp [text] more text newline.
Sensor Data records: timestamp sensor_data newline.
Only sensor data records produce particles if properly formed.
Mal-formed sensor data records and all metadata records produce no particles.
Release notes:
Initial Release
"""
import re
from mi.core.log import get_logger
from mi.core.common import BaseEnum
from mi.dataset.parser.dcl_file_common import \
DclInstrumentDataParticle, \
DclFileCommonParser
from mi.core.instrument.dataset_data_particle import DataParticleKey
from mi.core.exceptions import UnexpectedDataException
log = get_logger()
__author__ = 'Phillip Tran'
__license__ = 'Apache 2.0'
# SENSOR_DATA_MATCHER produces the following groups.
# The following are indices into groups() produced by SENSOR_DATA_MATCHER
# incremented after common timestamp values.
# i.e, match.groups()[INDEX]
SENSOR_GROUP_BAROMETRIC_PRESSURE = 1
SENSOR_GROUP_RELATIVE_HUMIDITY = 2
SENSOR_GROUP_AIR_TEMPERATURE = 3
SENSOR_GROUP_LONGWAVE_IRRADIANCE = 4
SENSOR_GROUP_PRECIPITATION = 5
SENSOR_GROUP_SEA_SURFACE_TEMPERATURE = 6
SENSOR_GROUP_SEA_SURFACE_CONDUCTIVITY = 7
SENSOR_GROUP_SHORTWAVE_IRRADIANCE = 8
SENSOR_GROUP_EASTWARD_WIND_VELOCITY = 9
SENSOR_GROUP_NORTHWARD_WIND_VELOCITY = 10
# This table is used in the generation of the instrument data particle.
# This will be a list of tuples with the following columns.
# Column 1 - particle parameter name
# Column 2 - group number (index into raw_data)
# Column 3 - data encoding function (conversion required - int, float, etc)
INSTRUMENT_PARTICLE_MAP = [
('barometric_pressure', SENSOR_GROUP_BAROMETRIC_PRESSURE, float),
('relative_humidity', SENSOR_GROUP_RELATIVE_HUMIDITY, float),
('air_temperature', SENSOR_GROUP_AIR_TEMPERATURE, float),
('longwave_irradiance', SENSOR_GROUP_LONGWAVE_IRRADIANCE, float),
('precipitation', SENSOR_GROUP_PRECIPITATION, float),
('sea_surface_temperature', SENSOR_GROUP_SEA_SURFACE_TEMPERATURE, float),
('sea_surface_conductivity', SENSOR_GROUP_SEA_SURFACE_CONDUCTIVITY, float),
('shortwave_irradiance', SENSOR_GROUP_SHORTWAVE_IRRADIANCE, float),
('eastward_wind_velocity', SENSOR_GROUP_EASTWARD_WIND_VELOCITY, float),
('northward_wind_velocity', SENSOR_GROUP_NORTHWARD_WIND_VELOCITY, float)
]
class DataParticleType(BaseEnum):
REC_INSTRUMENT_PARTICLE = 'metbk_a_dcl_instrument_recovered'
TEL_INSTRUMENT_PARTICLE = 'metbk_a_dcl_instrument'
class MetbkADclInstrumentDataParticle(DclInstrumentDataParticle):
"""
Class for generating the Metbk_a instrument particle.
"""
def __init__(self, raw_data, *args, **kwargs):
super(MetbkADclInstrumentDataParticle, self).__init__(
raw_data,
INSTRUMENT_PARTICLE_MAP,
*args, **kwargs)
def _build_parsed_values(self):
"""
Build parsed values for Recovered and Telemetered Instrument Data Particle.
Will only append float values and ignore strings.
Returns the list.
"""
data_list = []
for name, group, func in INSTRUMENT_PARTICLE_MAP:
if isinstance(self.raw_data[group], func):
data_list.append(self._encode_value(name, self.raw_data[group], func))
return data_list
class MetbkADclRecoveredInstrumentDataParticle(MetbkADclInstrumentDataParticle):
"""
Class for generating Offset Data Particles from Recovered data.
"""
_data_particle_type = DataParticleType.REC_INSTRUMENT_PARTICLE
class MetbkADclTelemeteredInstrumentDataParticle(MetbkADclInstrumentDataParticle):
"""
Class for generating Offset Data Particles from Telemetered data.
"""
_data_particle_type = DataParticleType.TEL_INSTRUMENT_PARTICLE
class MetbkADclParser(DclFileCommonParser):
"""
This is the entry point for the Metbk_a_dcl parser.
"""
def __init__(self,
config,
stream_handle,
exception_callback):
super(MetbkADclParser, self).__init__(config,
stream_handle,
exception_callback,
'',
'')
self.particle_classes = None
self.instrument_particle_map = INSTRUMENT_PARTICLE_MAP
self.raw_data_length = 14
def parse_file(self):
"""
This method reads the file and parses the data within, and at
the end of this method self._record_buffer will be filled with all the particles in the file.
"""
# If not set from config & no InstrumentParameterException error from constructor
if self.particle_classes is None:
self.particle_classes = (self._particle_class,)
for particle_class in self.particle_classes:
for line in self._stream_handle:
if not re.findall(r'.*\[.*\]:\b[^\W\d_]+\b', line) and line is not None: # Disregard anything that has a word after [metbk2:DLOGP6]:
line = re.sub(r'\[.*\]:', '', line)
raw_data = line.split()
if len(raw_data) != self.raw_data_length: # The raw data should have a length of 14
self.handle_unknown_data(line)
continue
if re.findall(r'[a-zA-Z][0-9]|[0-9][a-zA-Z]', line):
self.handle_unknown_data(line)
continue
raw_data[0:2] = [' '.join(raw_data[0:2])] # Merge the first and second elements to form a timestamp
if raw_data is not None:
for i in range(1, len(raw_data)): # Ignore 0th element, because that is the timestamp
raw_data[i] = self.select_type(raw_data[i])
particle = self._extract_sample(particle_class,
None,
raw_data,
preferred_ts=DataParticleKey.PORT_TIMESTAMP)
self._record_buffer.append(particle)
def handle_unknown_data(self, line):
# Otherwise generate warning for unknown data.
error_message = 'Unknown data found in chunk %s' % line
log.warn(error_message)
self._exception_callback(UnexpectedDataException(error_message))
@staticmethod
def select_type(raw_list_element):
"""
This function will return the float value if possible
"""
try:
return float(raw_list_element)
except ValueError:
return None
| bsd-2-clause |
eegeo/eegeo-example-app | src/AboutPage/SdkModel/AboutPageMenuModule.h | 1027 | // Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#pragma once
#include <string>
#include <vector>
#include "IAboutPageMenuModule.h"
#include "AboutPage.h"
#include "BidirectionalBus.h"
#include "IIdentity.h"
#include "IMetricsService.h"
#include "Menu.h"
#include "Reaction.h"
#include "Search.h"
#include "Types.h"
namespace ExampleApp
{
namespace AboutPage
{
namespace SdkModel
{
class AboutPageMenuModule: public IAboutPageMenuModule, private Eegeo::NonCopyable
{
private:
Menu::View::IMenuModel* m_pAboutPageMenuModel;
Menu::View::IMenuOptionsModel* m_pAboutPageMenuOptionsModel;
public:
AboutPageMenuModule(Menu::View::IMenuViewModel& menuViewModel,
AboutPage::View::IAboutPageViewModel& aboutPageViewModel);
~AboutPageMenuModule();
Menu::View::IMenuModel& GetAboutPageMenuModel() const;
};
}
}
}
| bsd-2-clause |
rolandshoemaker/cfssl | csr/csr.go | 10628 | // Package csr implements certificate requests for CFSSL.
package csr
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"net"
"net/mail"
"strings"
cferr "github.com/cloudflare/cfssl/errors"
"github.com/cloudflare/cfssl/helpers"
"github.com/cloudflare/cfssl/log"
)
const (
curveP256 = 256
curveP384 = 384
curveP521 = 521
)
// A Name contains the SubjectInfo fields.
type Name struct {
C string // Country
ST string // State
L string // Locality
O string // OrganisationName
OU string // OrganisationalUnitName
}
// A KeyRequest is a generic request for a new key.
type KeyRequest interface {
Algo() string
Size() int
Generate() (crypto.PrivateKey, error)
SigAlgo() x509.SignatureAlgorithm
}
// A BasicKeyRequest contains the algorithm and key size for a new private key.
type BasicKeyRequest struct {
A string `json:"algo"`
S int `json:"size"`
}
// NewBasicKeyRequest returns a default BasicKeyRequest.
func NewBasicKeyRequest() *BasicKeyRequest {
return &BasicKeyRequest{"ecdsa", curveP256}
}
// Algo returns the requested key algorithm represented as a string.
func (kr *BasicKeyRequest) Algo() string {
return kr.A
}
// Size returns the requested key size.
func (kr *BasicKeyRequest) Size() int {
return kr.S
}
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) {
log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size())
switch kr.Algo() {
case "rsa":
if kr.Size() < 2048 {
return nil, errors.New("RSA key is too weak")
}
if kr.Size() > 8192 {
return nil, errors.New("RSA key size too large")
}
return rsa.GenerateKey(rand.Reader, kr.Size())
case "ecdsa":
var curve elliptic.Curve
switch kr.Size() {
case curveP256:
curve = elliptic.P256()
case curveP384:
curve = elliptic.P384()
case curveP521:
curve = elliptic.P521()
default:
return nil, errors.New("invalid curve")
}
return ecdsa.GenerateKey(curve, rand.Reader)
default:
return nil, errors.New("invalid algorithm")
}
}
// SigAlgo returns an appropriate X.509 signature algorithm given the
// key request's type and size.
func (kr *BasicKeyRequest) SigAlgo() x509.SignatureAlgorithm {
switch kr.Algo() {
case "rsa":
switch {
case kr.Size() >= 4096:
return x509.SHA512WithRSA
case kr.Size() >= 3072:
return x509.SHA384WithRSA
case kr.Size() >= 2048:
return x509.SHA256WithRSA
default:
return x509.SHA1WithRSA
}
case "ecdsa":
switch kr.Size() {
case curveP521:
return x509.ECDSAWithSHA512
case curveP384:
return x509.ECDSAWithSHA384
case curveP256:
return x509.ECDSAWithSHA256
default:
return x509.ECDSAWithSHA1
}
default:
return x509.UnknownSignatureAlgorithm
}
}
// CAConfig is a section used in the requests initialising a new CA.
type CAConfig struct {
PathLength int `json:"pathlen"`
Expiry string `json:"expiry"`
}
// A CertificateRequest encapsulates the API interface to the
// certificate request functionality.
type CertificateRequest struct {
CN string
Names []Name `json:"names"`
Hosts []string `json:"hosts"`
KeyRequest KeyRequest `json:"key,omitempty"`
CA *CAConfig `json:"ca,omitempty"`
}
// New returns a new, empty CertificateRequest with a
// BasicKeyRequest.
func New() *CertificateRequest {
return &CertificateRequest{
KeyRequest: NewBasicKeyRequest(),
}
}
// appendIf appends to a if s is not an empty string.
func appendIf(s string, a *[]string) {
if s != "" {
*a = append(*a, s)
}
}
// Name returns the PKIX name for the request.
func (cr *CertificateRequest) Name() pkix.Name {
var name pkix.Name
name.CommonName = cr.CN
for _, n := range cr.Names {
appendIf(n.C, &name.Country)
appendIf(n.ST, &name.Province)
appendIf(n.L, &name.Locality)
appendIf(n.O, &name.Organization)
appendIf(n.OU, &name.OrganizationalUnit)
}
return name
}
// ParseRequest takes a certificate request and generates a key and
// CSR from it. It does no validation -- caveat emptor. It will,
// however, fail if the key request is not valid (i.e., an unsupported
// curve or RSA key size). The lack of validation was specifically
// chosen to allow the end user to define a policy and validate the
// request appropriately before calling this function.
func ParseRequest(req *CertificateRequest) (csr, key []byte, err error) {
log.Info("received CSR")
if req.KeyRequest == nil {
req.KeyRequest = NewBasicKeyRequest()
}
log.Infof("generating key: %s-%d", req.KeyRequest.Algo(), req.KeyRequest.Size())
priv, err := req.KeyRequest.Generate()
if err != nil {
err = cferr.Wrap(cferr.PrivateKeyError, cferr.GenerationFailed, err)
return
}
switch priv := priv.(type) {
case *rsa.PrivateKey:
key = x509.MarshalPKCS1PrivateKey(priv)
block := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: key,
}
key = pem.EncodeToMemory(&block)
case *ecdsa.PrivateKey:
key, err = x509.MarshalECPrivateKey(priv)
if err != nil {
err = cferr.Wrap(cferr.PrivateKeyError, cferr.Unknown, err)
return
}
block := pem.Block{
Type: "EC PRIVATE KEY",
Bytes: key,
}
key = pem.EncodeToMemory(&block)
default:
panic("Generate should have failed to produce a valid key.")
}
var tpl = x509.CertificateRequest{
Subject: req.Name(),
SignatureAlgorithm: req.KeyRequest.SigAlgo(),
}
for i := range req.Hosts {
if ip := net.ParseIP(req.Hosts[i]); ip != nil {
tpl.IPAddresses = append(tpl.IPAddresses, ip)
} else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil {
tpl.EmailAddresses = append(tpl.EmailAddresses, req.Hosts[i])
} else {
tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i])
}
}
csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv)
if err != nil {
log.Errorf("failed to generate a CSR: %v", err)
err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err)
return
}
block := pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr,
}
log.Info("encoded CSR")
csr = pem.EncodeToMemory(&block)
return
}
// ExtractCertificateRequest extracts a CertificateRequest from
// x509.Certificate. It is aimed to used for generating a new certificate
// from an existing certificate. For a root certificate, the CA expiry
// length is calculated as the duration between cert.NotAfter and cert.NotBefore.
func ExtractCertificateRequest(cert *x509.Certificate) *CertificateRequest {
req := New()
req.CN = cert.Subject.CommonName
req.Names = getNames(cert.Subject)
req.Hosts = getHosts(cert)
if cert.IsCA {
req.CA = new(CAConfig)
// CA expiry length is calculated based on the input cert
// issue date and expiry date.
req.CA.Expiry = cert.NotAfter.Sub(cert.NotBefore).String()
req.CA.PathLength = cert.MaxPathLen
}
return req
}
func getHosts(cert *x509.Certificate) []string {
var hosts []string
for _, ip := range cert.IPAddresses {
hosts = append(hosts, ip.String())
}
for _, dns := range cert.DNSNames {
hosts = append(hosts, dns)
}
for _, email := range cert.EmailAddresses {
hosts = append(hosts, email)
}
return hosts
}
// getNames returns an array of Names from the certificate
// It onnly cares about Country, Organization, OrganizationalUnit, Locality, Province
func getNames(sub pkix.Name) []Name {
// anonymous func for finding the max of a list of interger
max := func(v1 int, vn ...int) (max int) {
max = v1
for i := 0; i < len(vn); i++ {
if vn[i] > max {
max = vn[i]
}
}
return max
}
nc := len(sub.Country)
norg := len(sub.Organization)
nou := len(sub.OrganizationalUnit)
nl := len(sub.Locality)
np := len(sub.Province)
n := max(nc, norg, nou, nl, np)
names := make([]Name, n)
for i := range names {
if i < nc {
names[i].C = sub.Country[i]
}
if i < norg {
names[i].O = sub.Organization[i]
}
if i < nou {
names[i].OU = sub.OrganizationalUnit[i]
}
if i < nl {
names[i].L = sub.Locality[i]
}
if i < np {
names[i].ST = sub.Province[i]
}
}
return names
}
// A Generator is responsible for validating certificate requests.
type Generator struct {
Validator func(*CertificateRequest) error
}
// ProcessRequest validates and processes the incoming request. It is
// a wrapper around a validator and the ParseRequest function.
func (g *Generator) ProcessRequest(req *CertificateRequest) (csr, key []byte, err error) {
log.Info("generate received request")
err = g.Validator(req)
if err != nil {
log.Warningf("invalid request: %v", err)
return
}
csr, key, err = ParseRequest(req)
if err != nil {
return nil, nil, err
}
return
}
// IsNameEmpty returns true if the name has no identifying information in it.
func IsNameEmpty(n Name) bool {
empty := func(s string) bool { return strings.TrimSpace(s) == "" }
if empty(n.C) && empty(n.ST) && empty(n.L) && empty(n.O) && empty(n.OU) {
return true
}
return false
}
// Regenerate uses the provided CSR as a template for signing a new
// CSR using priv.
func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) {
req, extra, err := helpers.ParseCSR(csr)
if err != nil {
return nil, err
} else if len(extra) > 0 {
return nil, errors.New("csr: trailing data in certificate request")
}
return x509.CreateCertificateRequest(rand.Reader, req, priv)
}
// Generate creates a new CSR from a CertificateRequest structure and
// an existing key. The KeyRequest field is ignored.
func Generate(priv crypto.Signer, req *CertificateRequest) (csr []byte, err error) {
sigAlgo := helpers.SignerAlgo(priv, crypto.SHA256)
if sigAlgo == x509.UnknownSignatureAlgorithm {
return nil, cferr.New(cferr.PrivateKeyError, cferr.Unavailable)
}
var tpl = x509.CertificateRequest{
Subject: req.Name(),
SignatureAlgorithm: sigAlgo,
}
for i := range req.Hosts {
if ip := net.ParseIP(req.Hosts[i]); ip != nil {
tpl.IPAddresses = append(tpl.IPAddresses, ip)
} else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil {
tpl.EmailAddresses = append(tpl.EmailAddresses, email.Address)
} else {
tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i])
}
}
csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv)
if err != nil {
log.Errorf("failed to generate a CSR: %v", err)
err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err)
return
}
block := pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr,
}
log.Info("encoded CSR")
csr = pem.EncodeToMemory(&block)
return
}
| bsd-2-clause |
troyxmccall/homebrew-cask | Casks/gitahead.rb | 404 | cask 'gitahead' do
version '2.6.1'
sha256 'a4dbbbd7c72c34acfdcad94d5217dfba00a16c64440d3a2f155a937a94d87fff'
url "https://github.com/gitahead/gitahead/releases/download/v#{version}/GitAhead-#{version}.dmg"
appcast 'https://github.com/gitahead/gitahead/releases.atom'
name 'GitAhead'
homepage 'https://github.com/gitahead/gitahead'
depends_on macos: '>= :sierra'
app 'GitAhead.app'
end
| bsd-2-clause |
forkch/scrabble_ar | examples/book_androidstudio/VuforiaJME/app/src/main/jni/QCAR/ImageTarget.h | 3422 | /*===============================================================================
Copyright (c) 2010-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of QUALCOMM Incorporated, registered in the United States
and other countries. Trademarks of QUALCOMM Incorporated are used with permission.
@file
ImageTarget.h
@brief
Header file for ImageTarget class.
===============================================================================*/
#ifndef _QCAR_IMAGETARGET_H_
#define _QCAR_IMAGETARGET_H_
// Include files
#include <QCAR/Trackable.h>
#include <QCAR/Vectors.h>
namespace QCAR
{
// Forward declarations
class Area;
class VirtualButton;
/// A flat natural feature target
/**
* Methods to modify an ImageTarget must not be called while the
* corresponding DataSet is active. The dataset must be deactivated first
* before reconfiguring an ImageTarget.
*/
class QCAR_API ImageTarget : public Trackable
{
public:
/// Returns the Trackable class' type
static Type getClassType();
/// Returns the system-wide unique id of the target.
/**
* The target id uniquely identifies an ImageTarget across multiple
* Vuforia sessions. The system wide unique id may be generated off-line.
* This is opposed to the function getId() which is a dynamically
* generated id and which uniquely identifies a Trackable within one run
* of Vuforia only.
*/
virtual const char* getUniqueTargetId() const = 0;
/// Returns the size (width and height) of the target (in 3D scene units).
virtual Vec2F getSize() const = 0;
/// Set the size (width and height) of the target (in 3D scene units).
/**
* The dataset this ImageTarget belongs to must not be active when calling
* this function or it will fail. Returns true if the size was set
* successfully, false otherwise.
*/
virtual bool setSize(const Vec2F& size) = 0;
/// Returns the number of virtual buttons defined for this ImageTarget.
virtual int getNumVirtualButtons() const = 0;
/// Provides write access to a specific virtual button.
virtual VirtualButton* getVirtualButton(int idx) = 0;
/// Provides read-only access to a specific virtual button.
virtual const VirtualButton* getVirtualButton(int idx) const = 0;
/// Returns a virtual button by its name
/**
* Returns NULL if no virtual button with that name
* exists in this ImageTarget
*/
virtual VirtualButton* getVirtualButton(const char* name) = 0;
/// Returns a virtual button by its name
/**
* Returns NULL if no virtual button with that name
* exists in this ImageTarget
*/
virtual const VirtualButton* getVirtualButton(const char* name) const = 0;
/// Creates a new virtual button and adds it to the ImageTarget
/**
* Returns NULL if the corresponding DataSet is currently active.
*/
virtual VirtualButton* createVirtualButton(const char* name, const Area& area) = 0;
/// Removes and destroys one of the ImageTarget's virtual buttons
/**
* Returns false if the corresponding DataSet is currently active.
*/
virtual bool destroyVirtualButton(VirtualButton* button) = 0;
/// Returns the meta data string for this ImageTarget.
virtual const char* getMetaData() const = 0;
};
} // namespace QCAR
#endif //_QCAR_IMAGETARGET_H_
| bsd-2-clause |
rogeriopradoj/frapi-without-vhost | tests/phpunit/PHPUnit/Tests/Extensions/Database/AllTests.php | 3257 | <?php
/**
* PHPUnit
*
* Copyright (c) 2002-2009, Sebastian Bergmann <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @category Testing
* @package PHPUnit
* @author Sebastian Bergmann <[email protected]>
* @copyright 2002-2009 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version SVN: $Id: AllTests.php 4404 2008-12-31 09:27:18Z sb $
* @link http://www.phpunit.de/
* @since File available since Release 3.2.0
*/
error_reporting(E_ALL | E_STRICT);
require_once 'PHPUnit/Util/Filter.php';
PHPUnit_Util_Filter::addFileToFilter(__FILE__);
require_once 'PHPUnit/Framework/TestSuite.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'DataSet' . DIRECTORY_SEPARATOR . 'AllTests.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Operation' . DIRECTORY_SEPARATOR . 'AllTests.php';
PHPUnit_Util_Filter::$filterPHPUnit = FALSE;
/**
*
*
* @category Testing
* @package PHPUnit
* @author Sebastian Bergmann <[email protected]>
* @copyright 2002-2009 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://www.phpunit.de/
* @since Class available since Release 3.2.0
*/
class Extensions_Database_AllTests
{
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('PHPUnit_Extensions_Database');
$suite->addTest(Extensions_Database_Operation_AllTests::suite());
$suite->addTest(Extensions_Database_DataSet_AllTests::suite());
return $suite;
}
}
?>
| bsd-2-clause |
DomT4/homebrew-core | Formula/amazon-ecs-cli.rb | 1127 | class AmazonEcsCli < Formula
desc "CLI for Amazon ECS to manage clusters and tasks for development"
homepage "https://aws.amazon.com/ecs"
url "https://github.com/aws/amazon-ecs-cli/archive/v1.7.0.tar.gz"
sha256 "b25d3defae2977aa696532b0e68afebd1e587f90eb4c39c64883a4c15906e19b"
bottle do
cellar :any_skip_relocation
sha256 "5a4783469233b2a9535b98b1b351f151deecdfe2d0bc30f8abb3002a73bc7145" => :mojave
sha256 "c84a85efdba3e5b6205dd13cf62c1c7c0a56ad9a6277c6009e52688d3c09c292" => :high_sierra
sha256 "658f4033ebda28ac671895dea8c132f62a96fe6dd4dd91de10b394b9dff8e245" => :sierra
sha256 "6f9d3c50e8fa4b59720ec701fd83831600526787c1e908bb9dc269f646907c58" => :el_capitan
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
(buildpath/"src/github.com/aws/amazon-ecs-cli").install buildpath.children
cd "src/github.com/aws/amazon-ecs-cli" do
system "make", "build"
system "make", "test"
bin.install "bin/local/ecs-cli"
prefix.install_metafiles
end
end
test do
assert_match version.to_s, shell_output("#{bin}/ecs-cli -v")
end
end
| bsd-2-clause |
01org/TPM2.0-TSS | src/tss2-sys/api/Tss2_Sys_SetDecryptParam.c | 2652 | /* SPDX-License-Identifier: BSD-2-Clause */
/***********************************************************************;
* Copyright (c) 2015 - 2018, Intel Corporation
* All rights reserved.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <string.h>
#include "tss2_tpm2_types.h"
#include "tss2_mu.h"
#include "sysapi_util.h"
#include "util/tss2_endian.h"
TSS2_RC Tss2_Sys_SetDecryptParam(
TSS2_SYS_CONTEXT *sysContext,
size_t param_size,
const uint8_t *param_buffer)
{
_TSS2_SYS_CONTEXT_BLOB *ctx = syscontext_cast(sysContext);
size_t curr_param_size;
const uint8_t *curr_param_buffer;
UINT32 command_size;
const UINT8 *src, *limit;
UINT8 *dst;
UINT32 len;
TSS2_RC rval;
if (!param_buffer || !ctx)
return TSS2_SYS_RC_BAD_REFERENCE;
if (ctx->previousStage != CMD_STAGE_PREPARE)
return TSS2_SYS_RC_BAD_SEQUENCE;
if (ctx->decryptAllowed == 0)
return TSS2_SYS_RC_NO_DECRYPT_PARAM;
if (param_size < 1)
return TSS2_SYS_RC_BAD_VALUE;
if (BE_TO_HOST_32(req_header_from_cxt(ctx)->commandSize) +
param_size > ctx->maxCmdSize)
return TSS2_SYS_RC_INSUFFICIENT_CONTEXT;
rval = Tss2_Sys_GetDecryptParam(sysContext, &curr_param_size,
&curr_param_buffer);
if (rval)
return rval;
if (curr_param_size == 0 && ctx->decryptNull) {
/* Move the current cpBuffer down to make room for the decrypt param */
src = ctx->cpBuffer + 2;
dst = ctx->cpBuffer + ctx->cpBufferUsedSize + 2;
len = ctx->cpBufferUsedSize - 2;
limit = ctx->cmdBuffer + ctx->maxCmdSize;
if (dst + len > limit)
return TSS2_SYS_RC_INSUFFICIENT_CONTEXT;
memmove(dst, src, len);
ctx->cpBufferUsedSize += param_size;
*(UINT16 *)ctx->cpBuffer = HOST_TO_BE_16(param_size);
/* Fixup the command size */
command_size = BE_TO_HOST_32(req_header_from_cxt(ctx)->commandSize);
command_size += param_size;
req_header_from_cxt(ctx)->commandSize = HOST_TO_BE_32(command_size);
} else if (curr_param_size != param_size) {
return TSS2_SYS_RC_BAD_SIZE;
}
/* Copy the encrypted param into the command buffer */
src = param_buffer;
dst = (UINT8 *)curr_param_buffer;
len = param_size;
limit = ctx->cmdBuffer + ctx->maxCmdSize;
*(UINT16 *)ctx->cpBuffer = HOST_TO_BE_16(param_size);
if (dst + len > limit)
return TSS2_SYS_RC_INSUFFICIENT_CONTEXT;
memmove(dst, src, len);
return rval;
}
| bsd-2-clause |
Aweary/relay | src/tools/__tests__/transformRelayQueryPayload-test.js | 4969 | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+relay
*/
'use strict';
require('configureForRelayOSS');
const Relay = require('Relay');
const RelayTestUtils = require('RelayTestUtils');
const generateRQLFieldAlias = require('generateRQLFieldAlias');
const transformRelayQueryPayload = require('transformRelayQueryPayload');
describe('transformClientPayload()', () => {
var {getNode} = RelayTestUtils;
it('transforms singular root payloads', () => {
var query = getNode(Relay.QL`
query {
node(id: "123") {
friends(first:"1") {
count,
edges {
node {
id,
... on User {
profilePicture(size: "32") {
uri,
},
},
},
},
},
}
}
`);
var payload = {
node: {
id: '123',
friends: {
count: 1,
edges: [
{
cursor: 'friend:cursor',
node: {
id: 'client:1',
profilePicture: {
uri: 'friend.jpg',
},
},
},
],
},
},
};
expect(transformRelayQueryPayload(query, payload)).toEqual({
node: {
__typename: undefined,
id: '123',
[generateRQLFieldAlias('friends.first(1)')]: {
count: 1,
edges: [
{
cursor: 'friend:cursor',
node: {
id: 'client:1',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: 'friend.jpg',
},
},
},
],
pageInfo: undefined,
},
},
});
});
it('transforms plural root payloads of arrays', () => {
var query = getNode(Relay.QL`
query {
nodes(ids: ["123", "456"]) {
... on User {
profilePicture(size: "32") {
uri,
},
},
},
}
`);
var payload = {
123: {
id: '123',
profilePicture: {
uri: '123.jpg',
},
},
456: {
id: '456',
profilePicture: {
uri: '456.jpg',
},
},
};
expect(transformRelayQueryPayload(query, payload)).toEqual({
123: {
__typename: undefined,
id: '123',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '123.jpg',
},
},
456: {
__typename: undefined,
id: '456',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '456.jpg',
},
},
});
});
it('transforms plural root payloads of objects (OSS)', () => {
var query = getNode(Relay.QL`
query {
nodes(ids: ["123", "456"]) {
... on User {
profilePicture(size: "32") {
uri,
},
},
},
}
`);
var payload = [
{
id: '123',
profilePicture: {
uri: '123.jpg',
},
},
{
id: '456',
profilePicture: {
uri: '456.jpg',
},
},
];
expect(transformRelayQueryPayload(query, payload)).toEqual([
{
__typename: undefined,
id: '123',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '123.jpg',
},
},
{
__typename: undefined,
id: '456',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '456.jpg',
},
},
]);
});
it('transforms plural root payloads of objects (FB)', () => {
var query = getNode(Relay.QL`
query {
nodes(ids: ["123", "456"]) {
... on User {
profilePicture(size: "32") {
uri,
},
},
},
}
`);
var payload = {
nodes: [
{
id: '123',
profilePicture: {
uri: '123.jpg',
},
},
{
id: '456',
profilePicture: {
uri: '456.jpg',
},
},
],
};
expect(transformRelayQueryPayload(query, payload)).toEqual({
nodes: [
{
__typename: undefined,
id: '123',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '123.jpg',
},
},
{
__typename: undefined,
id: '456',
[generateRQLFieldAlias('profilePicture.size(32)')]: {
uri: '456.jpg',
},
},
],
});
});
});
| bsd-3-clause |
CyberAnalyticDevTeam/SimpleRock | roles/kibana/files/profile.d-kibanapw.sh | 438 | # Set passwords
function kibanapw() { if [ $# -lt 2 ]; then echo -e "Usage: kibanapw USER PASSWORD\nUsers will be added to /etc/nginx/htpasswd.users"; else egrep "^${1}:" /etc/lighttpd/rock-htpasswd.user > /dev/null 2>&1; if [[ $? -eq 0 ]]; then sudo sed -i "/${1}\:/d" /etc/lighttpd/rock-htpasswd.user; fi; printf "${1}:$(echo ${2} | openssl passwd -apr1 -stdin)\n" | sudo tee -a /etc/lighttpd/rock-htpasswd.user > /dev/null 2>&1; fi; }
| bsd-3-clause |
flutter/engine | shell/platform/android/test/io/flutter/embedding/android/FlutterActivityAndFragmentDelegateTest.java | 49478 | package io.flutter.embedding.android;
import static android.content.ComponentCallbacks2.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNotNull;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import io.flutter.FlutterInjector;
import io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.Host;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.FlutterShellArgs;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.embedding.engine.plugins.activity.ActivityControlSurface;
import io.flutter.embedding.engine.renderer.FlutterRenderer;
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener;
import io.flutter.embedding.engine.systemchannels.AccessibilityChannel;
import io.flutter.embedding.engine.systemchannels.KeyEventChannel;
import io.flutter.embedding.engine.systemchannels.LifecycleChannel;
import io.flutter.embedding.engine.systemchannels.LocalizationChannel;
import io.flutter.embedding.engine.systemchannels.MouseCursorChannel;
import io.flutter.embedding.engine.systemchannels.NavigationChannel;
import io.flutter.embedding.engine.systemchannels.SettingsChannel;
import io.flutter.embedding.engine.systemchannels.SystemChannel;
import io.flutter.embedding.engine.systemchannels.TextInputChannel;
import io.flutter.plugin.localization.LocalizationPlugin;
import io.flutter.plugin.platform.PlatformViewsController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(AndroidJUnit4.class)
public class FlutterActivityAndFragmentDelegateTest {
private FlutterEngine mockFlutterEngine;
private FlutterActivityAndFragmentDelegate.Host mockHost;
@Before
public void setup() {
FlutterInjector.reset();
// Create a mocked FlutterEngine for the various interactions required by the delegate
// being tested.
mockFlutterEngine = mockFlutterEngine();
// Create a mocked Host, which is required by the delegate being tested.
mockHost = mock(FlutterActivityAndFragmentDelegate.Host.class);
when(mockHost.getContext()).thenReturn(RuntimeEnvironment.application);
when(mockHost.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class));
when(mockHost.getLifecycle()).thenReturn(mock(Lifecycle.class));
when(mockHost.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {}));
when(mockHost.getDartEntrypointFunctionName()).thenReturn("main");
when(mockHost.getAppBundlePath()).thenReturn("/fake/path");
when(mockHost.getInitialRoute()).thenReturn("/");
when(mockHost.getRenderMode()).thenReturn(RenderMode.surface);
when(mockHost.getTransparencyMode()).thenReturn(TransparencyMode.transparent);
when(mockHost.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine);
when(mockHost.shouldAttachEngineToActivity()).thenReturn(true);
when(mockHost.shouldHandleDeeplinking()).thenReturn(false);
when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true);
when(mockHost.shouldDispatchAppLifecycleState()).thenReturn(true);
}
@Test
public void itSendsLifecycleEventsToFlutter() {
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// We're testing lifecycle behaviors, which require/expect that certain methods have already
// been executed by the time they run. Therefore, we run those expected methods first.
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
// --- Execute the behavior under test ---
// By the time an Activity/Fragment is started, we don't expect any lifecycle messages
// to have been sent to Flutter.
delegate.onStart();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsResumed();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached();
// When the Activity/Fragment is resumed, a resumed message should have been sent to Flutter.
delegate.onResume();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached();
// When the Activity/Fragment is paused, an inactive message should have been sent to Flutter.
delegate.onPause();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached();
// When the Activity/Fragment is stopped, a paused message should have been sent to Flutter.
// Notice that Flutter uses the term "paused" in a different way, and at a different time
// than the Android OS.
delegate.onStop();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsPaused();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached();
// When activity detaches, a detached message should have been sent to Flutter.
delegate.onDetach();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsResumed();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsInactive();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsPaused();
verify(mockFlutterEngine.getLifecycleChannel(), times(1)).appIsDetached();
}
@Test
public void itDoesNotSendsLifecycleEventsToFlutter() {
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
when(mockHost.shouldDispatchAppLifecycleState()).thenReturn(false);
// We're testing lifecycle behaviors, which require/expect that certain methods have already
// been executed by the time they run. Therefore, we run those expected methods first.
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
delegate.onResume();
delegate.onPause();
delegate.onStop();
delegate.onDetach();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsResumed();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsPaused();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsInactive();
verify(mockFlutterEngine.getLifecycleChannel(), never()).appIsDetached();
}
@Test
public void itDefersToTheHostToProvideFlutterEngine() {
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is created in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Verify that the host was asked to provide a FlutterEngine.
verify(mockHost, times(1)).provideFlutterEngine(any(Context.class));
// Verify that the delegate's FlutterEngine is our mock FlutterEngine.
assertEquals(
"The delegate failed to use the host's FlutterEngine.",
mockFlutterEngine,
delegate.getFlutterEngine());
}
@Test
public void itUsesCachedEngineWhenProvided() {
// ---- Test setup ----
// Place a FlutterEngine in the static cache.
FlutterEngine cachedEngine = mockFlutterEngine();
FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine);
// Adjust fake host to request cached engine.
when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine");
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is obtained in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
delegate.onResume();
// --- Verify that the cached engine was used ---
// Verify that the non-cached engine was not used.
verify(mockFlutterEngine.getDartExecutor(), never())
.executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class));
// We should never instruct a cached engine to execute Dart code - it should already be
// executing it.
verify(cachedEngine.getDartExecutor(), never())
.executeDartEntrypoint(any(DartExecutor.DartEntrypoint.class));
// If the cached engine is being used, it should have sent a resumed lifecycle event.
verify(cachedEngine.getLifecycleChannel(), times(1)).appIsResumed();
}
@Test(expected = IllegalStateException.class)
public void itThrowsExceptionIfCachedEngineDoesNotExist() {
// ---- Test setup ----
// Adjust fake host to request cached engine that does not exist.
when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine");
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine existence is verified in onAttach()
delegate.onAttach(RuntimeEnvironment.application);
// Expect IllegalStateException.
}
@Test
public void itGivesHostAnOpportunityToConfigureFlutterEngine() {
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is created in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Verify that the host was asked to configure our FlutterEngine.
verify(mockHost, times(1)).configureFlutterEngine(mockFlutterEngine);
}
@Test
public void itGivesHostAnOpportunityToConfigureFlutterSurfaceView() {
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
// Verify that the host was asked to configure a FlutterSurfaceView.
verify(mockHost, times(1)).onFlutterSurfaceViewCreated(isNotNull());
}
@Test
public void itGivesHostAnOpportunityToConfigureFlutterTextureView() {
// ---- Test setup ----
Host customMockHost = mock(Host.class);
when(customMockHost.getContext()).thenReturn(RuntimeEnvironment.application);
when(customMockHost.getActivity()).thenReturn(Robolectric.setupActivity(Activity.class));
when(customMockHost.getLifecycle()).thenReturn(mock(Lifecycle.class));
when(customMockHost.getFlutterShellArgs()).thenReturn(new FlutterShellArgs(new String[] {}));
when(customMockHost.getDartEntrypointFunctionName()).thenReturn("main");
when(customMockHost.getAppBundlePath()).thenReturn("/fake/path");
when(customMockHost.getInitialRoute()).thenReturn("/");
when(customMockHost.getRenderMode()).thenReturn(RenderMode.texture);
when(customMockHost.getTransparencyMode()).thenReturn(TransparencyMode.transparent);
when(customMockHost.provideFlutterEngine(any(Context.class))).thenReturn(mockFlutterEngine);
when(customMockHost.shouldAttachEngineToActivity()).thenReturn(true);
when(customMockHost.shouldDestroyEngineWithHost()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate =
new FlutterActivityAndFragmentDelegate(customMockHost);
// --- Execute the behavior under test ---
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, false);
// Verify that the host was asked to configure a FlutterTextureView.
verify(customMockHost, times(1)).onFlutterTextureViewCreated(isNotNull());
}
@Test
public void itGivesHostAnOpportunityToCleanUpFlutterEngine() {
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is created in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onDetach();
// Verify that the host was asked to configure our FlutterEngine.
verify(mockHost, times(1)).cleanUpFlutterEngine(mockFlutterEngine);
}
@Test
public void itSendsInitialRouteToFlutter() {
// ---- Test setup ----
// Set initial route on our fake Host.
when(mockHost.getInitialRoute()).thenReturn("/my/route");
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The initial route is sent in onStart().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
// Verify that the navigation channel was given our initial route.
verify(mockFlutterEngine.getNavigationChannel(), times(1)).setInitialRoute("/my/route");
}
@Test
public void itExecutesDartEntrypointProvidedByHost() {
// ---- Test setup ----
// Set Dart entrypoint parameters on fake host.
when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path");
when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint");
// Create the DartEntrypoint that we expect to be executed.
DartExecutor.DartEntrypoint dartEntrypoint =
new DartExecutor.DartEntrypoint("/my/bundle/path", "myEntrypoint");
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Dart is executed in onStart().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
// Verify that the host's Dart entrypoint was used.
verify(mockFlutterEngine.getDartExecutor(), times(1)).executeDartEntrypoint(eq(dartEntrypoint));
}
@Test
public void itExecutesDartLibraryUriProvidedByHost() {
when(mockHost.getAppBundlePath()).thenReturn("/my/bundle/path");
when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint");
when(mockHost.getDartEntrypointLibraryUri()).thenReturn("package:foo/bar.dart");
DartExecutor.DartEntrypoint expectedEntrypoint =
new DartExecutor.DartEntrypoint("/my/bundle/path", "package:foo/bar.dart", "myEntrypoint");
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
verify(mockFlutterEngine.getDartExecutor(), times(1))
.executeDartEntrypoint(eq(expectedEntrypoint));
}
@Test
public void itUsesDefaultFlutterLoaderAppBundlePathWhenUnspecified() {
// ---- Test setup ----
FlutterLoader mockFlutterLoader = mock(FlutterLoader.class);
when(mockFlutterLoader.findAppBundlePath()).thenReturn("default_flutter_assets/path");
FlutterInjector.setInstance(
new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build());
// Set Dart entrypoint parameters on fake host.
when(mockHost.getAppBundlePath()).thenReturn(null);
when(mockHost.getDartEntrypointFunctionName()).thenReturn("myEntrypoint");
// Create the DartEntrypoint that we expect to be executed.
DartExecutor.DartEntrypoint dartEntrypoint =
new DartExecutor.DartEntrypoint("default_flutter_assets/path", "myEntrypoint");
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Dart is executed in onStart().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
// Verify that the host's Dart entrypoint was used.
verify(mockFlutterEngine.getDartExecutor(), times(1)).executeDartEntrypoint(eq(dartEntrypoint));
}
// "Attaching" to the surrounding Activity refers to Flutter being able to control
// system chrome and other Activity-level details. If Flutter is not attached to the
// surrounding Activity, it cannot control those details. This includes plugins.
@Test
public void itAttachesFlutterToTheActivityIfDesired() {
// ---- Test setup ----
// Declare that the host wants Flutter to attach to the surrounding Activity.
when(mockHost.shouldAttachEngineToActivity()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Flutter is attached to the surrounding Activity in onAttach.
delegate.onAttach(RuntimeEnvironment.application);
// Verify that the ActivityControlSurface was told to attach to an Activity.
verify(mockFlutterEngine.getActivityControlSurface(), times(1))
.attachToActivity(any(ExclusiveAppComponent.class), any(Lifecycle.class));
// Flutter is detached from the surrounding Activity in onDetach.
delegate.onDetach();
// Verify that the ActivityControlSurface was told to detach from the Activity.
verify(mockFlutterEngine.getActivityControlSurface(), times(1)).detachFromActivity();
}
// "Attaching" to the surrounding Activity refers to Flutter being able to control
// system chrome and other Activity-level details. If Flutter is not attached to the
// surrounding Activity, it cannot control those details. This includes plugins.
@Test
public void itDoesNotAttachFlutterToTheActivityIfNotDesired() {
// ---- Test setup ----
// Declare that the host does NOT want Flutter to attach to the surrounding Activity.
when(mockHost.shouldAttachEngineToActivity()).thenReturn(false);
// getActivity() returns null if the activity is not attached
when(mockHost.getActivity()).thenReturn(null);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Flutter is attached to the surrounding Activity in onAttach.
delegate.onAttach(RuntimeEnvironment.application);
// Make sure all of the other lifecycle methods can run safely as well
// without a valid Activity
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
delegate.onResume();
delegate.onPause();
delegate.onStop();
delegate.onDestroyView();
// Flutter is detached from the surrounding Activity in onDetach.
delegate.onDetach();
// Verify that the ActivityControlSurface was NOT told to attach or detach to an Activity.
verify(mockFlutterEngine.getActivityControlSurface(), never())
.attachToActivity(any(ExclusiveAppComponent.class), any(Lifecycle.class));
verify(mockFlutterEngine.getActivityControlSurface(), never()).detachFromActivity();
}
@Test
public void itSendsPopRouteMessageToFlutterWhenHardwareBackButtonIsPressed() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Emulate the host and inform our delegate that the back button was pressed.
delegate.onBackPressed();
// Verify that the navigation channel tried to send a message to Flutter.
verify(mockFlutterEngine.getNavigationChannel(), times(1)).popRoute();
}
@Test
public void itForwardsOnRequestPermissionsResultToFlutterEngine() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Emulate the host and call the method that we expect to be forwarded.
delegate.onRequestPermissionsResult(0, new String[] {}, new int[] {});
// Verify that the call was forwarded to the engine.
verify(mockFlutterEngine.getActivityControlSurface(), times(1))
.onRequestPermissionsResult(any(Integer.class), any(String[].class), any(int[].class));
}
@Test
public void
itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinking() {
Intent intent = FlutterActivity.createDefaultIntent(RuntimeEnvironment.application);
intent.setData(Uri.parse("http://myApp/custom/route?query=test"));
ActivityController<FlutterActivity> activityController =
Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
when(mockHost.getActivity()).thenReturn(flutterActivity);
when(mockHost.getInitialRoute()).thenReturn(null);
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
// Emulate app start.
delegate.onStart();
// Verify that the navigation channel was given the initial route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1))
.setInitialRoute("/custom/route?query=test");
}
@Test
public void
itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingWithQueryParameterAndFragment() {
Intent intent = FlutterActivity.createDefaultIntent(RuntimeEnvironment.application);
intent.setData(Uri.parse("http://myApp/custom/route?query=test#fragment"));
ActivityController<FlutterActivity> activityController =
Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
when(mockHost.getActivity()).thenReturn(flutterActivity);
when(mockHost.getInitialRoute()).thenReturn(null);
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
// Emulate app start.
delegate.onStart();
// Verify that the navigation channel was given the initial route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1))
.setInitialRoute("/custom/route?query=test#fragment");
}
@Test
public void
itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingWithFragmentNoQueryParameter() {
Intent intent = FlutterActivity.createDefaultIntent(RuntimeEnvironment.application);
intent.setData(Uri.parse("http://myApp/custom/route#fragment"));
ActivityController<FlutterActivity> activityController =
Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
when(mockHost.getActivity()).thenReturn(flutterActivity);
when(mockHost.getInitialRoute()).thenReturn(null);
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
// Emulate app start.
delegate.onStart();
// Verify that the navigation channel was given the initial route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1))
.setInitialRoute("/custom/route#fragment");
}
@Test
public void
itSendsInitialRouteFromIntentOnStartIfNoInitialRouteFromActivityAndShouldHandleDeeplinkingNoQueryParameter() {
Intent intent = FlutterActivity.createDefaultIntent(RuntimeEnvironment.application);
intent.setData(Uri.parse("http://myApp/custom/route"));
ActivityController<FlutterActivity> activityController =
Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
when(mockHost.getActivity()).thenReturn(flutterActivity);
when(mockHost.getInitialRoute()).thenReturn(null);
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
// Emulate app start.
delegate.onStart();
// Verify that the navigation channel was given the initial route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1)).setInitialRoute("/custom/route");
}
@Test
public void itSendsdefaultInitialRouteOnStartIfNotDeepLinkingFromIntent() {
// Creates an empty intent without launch uri.
Intent intent = FlutterActivity.createDefaultIntent(RuntimeEnvironment.application);
ActivityController<FlutterActivity> activityController =
Robolectric.buildActivity(FlutterActivity.class, intent);
FlutterActivity flutterActivity = activityController.get();
when(mockHost.getActivity()).thenReturn(flutterActivity);
when(mockHost.getInitialRoute()).thenReturn(null);
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
// Emulate app start.
delegate.onStart();
// Verify that the navigation channel was given the default initial route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1)).setInitialRoute("/");
}
@Test
public void itSendsPushRouteMessageWhenOnNewIntent() {
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
Intent mockIntent = mock(Intent.class);
when(mockIntent.getData()).thenReturn(Uri.parse("http://myApp/custom/route?query=test"));
// Emulate the host and call the method that we expect to be forwarded.
delegate.onNewIntent(mockIntent);
// Verify that the navigation channel was given the push route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1))
.pushRoute("/custom/route?query=test");
}
@Test
public void itDoesNotSendPushRouteMessageWhenOnNewIntentIsNonHierarchicalUri() {
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
Intent mockIntent = mock(Intent.class);
// mailto: URIs are non-hierarchical
when(mockIntent.getData()).thenReturn(Uri.parse("mailto:[email protected]"));
// Emulate the host and call the method
delegate.onNewIntent(mockIntent);
// Verify that the navigation channel was not given a push route message.
verify(mockFlutterEngine.getNavigationChannel(), times(0)).pushRoute("mailto:[email protected]");
}
@Test
public void itSendsPushRouteMessageWhenOnNewIntentWithQueryParameterAndFragment() {
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
Intent mockIntent = mock(Intent.class);
when(mockIntent.getData())
.thenReturn(Uri.parse("http://myApp/custom/route?query=test#fragment"));
// Emulate the host and call the method that we expect to be forwarded.
delegate.onNewIntent(mockIntent);
// Verify that the navigation channel was given the push route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1))
.pushRoute("/custom/route?query=test#fragment");
}
@Test
public void itSendsPushRouteMessageWhenOnNewIntentWithFragmentNoQueryParameter() {
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
Intent mockIntent = mock(Intent.class);
when(mockIntent.getData()).thenReturn(Uri.parse("http://myApp/custom/route#fragment"));
// Emulate the host and call the method that we expect to be forwarded.
delegate.onNewIntent(mockIntent);
// Verify that the navigation channel was given the push route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRoute("/custom/route#fragment");
}
@Test
public void itSendsPushRouteMessageWhenOnNewIntentNoQueryParameter() {
when(mockHost.shouldHandleDeeplinking()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
Intent mockIntent = mock(Intent.class);
when(mockIntent.getData()).thenReturn(Uri.parse("http://myApp/custom/route"));
// Emulate the host and call the method that we expect to be forwarded.
delegate.onNewIntent(mockIntent);
// Verify that the navigation channel was given the push route message.
verify(mockFlutterEngine.getNavigationChannel(), times(1)).pushRoute("/custom/route");
}
@Test
public void itForwardsOnNewIntentToFlutterEngine() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Emulate the host and call the method that we expect to be forwarded.
delegate.onNewIntent(mock(Intent.class));
// Verify that the call was forwarded to the engine.
verify(mockFlutterEngine.getActivityControlSurface(), times(1)).onNewIntent(any(Intent.class));
}
@Test
public void itForwardsOnActivityResultToFlutterEngine() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Emulate the host and call the method that we expect to be forwarded.
delegate.onActivityResult(0, 0, null);
// Verify that the call was forwarded to the engine.
verify(mockFlutterEngine.getActivityControlSurface(), times(1))
.onActivityResult(any(Integer.class), any(Integer.class), /*intent=*/ isNull());
}
@Test
public void itForwardsOnUserLeaveHintToFlutterEngine() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Emulate the host and call the method that we expect to be forwarded.
delegate.onUserLeaveHint();
// Verify that the call was forwarded to the engine.
verify(mockFlutterEngine.getActivityControlSurface(), times(1)).onUserLeaveHint();
}
@Test
public void itNotifiesDartExecutorAndSendsMessageOverSystemChannelWhenToldToTrimMemory() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Test assumes no frames have been displayed.
verify(mockHost, times(0)).onFlutterUiDisplayed();
// Emulate the host and call the method that we expect to be forwarded.
delegate.onTrimMemory(TRIM_MEMORY_RUNNING_MODERATE);
delegate.onTrimMemory(TRIM_MEMORY_RUNNING_LOW);
verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning();
verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning();
delegate.onTrimMemory(TRIM_MEMORY_RUNNING_CRITICAL);
delegate.onTrimMemory(TRIM_MEMORY_BACKGROUND);
delegate.onTrimMemory(TRIM_MEMORY_COMPLETE);
delegate.onTrimMemory(TRIM_MEMORY_MODERATE);
delegate.onTrimMemory(TRIM_MEMORY_UI_HIDDEN);
verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning();
verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning();
verify(mockHost, times(0)).onFlutterUiDisplayed();
delegate.onCreateView(null, null, null, 0, false);
final FlutterRenderer renderer = mockFlutterEngine.getRenderer();
ArgumentCaptor<FlutterUiDisplayListener> listenerCaptor =
ArgumentCaptor.forClass(FlutterUiDisplayListener.class);
// 2 times: once for engine attachment, once for view creation.
verify(renderer, times(2)).addIsDisplayingFlutterUiListener(listenerCaptor.capture());
listenerCaptor.getValue().onFlutterUiDisplayed();
verify(mockHost, times(1)).onFlutterUiDisplayed();
delegate.onTrimMemory(TRIM_MEMORY_RUNNING_MODERATE);
verify(mockFlutterEngine.getDartExecutor(), times(0)).notifyLowMemoryWarning();
verify(mockFlutterEngine.getSystemChannel(), times(0)).sendMemoryPressureWarning();
delegate.onTrimMemory(TRIM_MEMORY_RUNNING_LOW);
delegate.onTrimMemory(TRIM_MEMORY_RUNNING_CRITICAL);
delegate.onTrimMemory(TRIM_MEMORY_BACKGROUND);
delegate.onTrimMemory(TRIM_MEMORY_COMPLETE);
delegate.onTrimMemory(TRIM_MEMORY_MODERATE);
delegate.onTrimMemory(TRIM_MEMORY_UI_HIDDEN);
verify(mockFlutterEngine.getDartExecutor(), times(6)).notifyLowMemoryWarning();
verify(mockFlutterEngine.getSystemChannel(), times(6)).sendMemoryPressureWarning();
}
@Test
public void itNotifiesDartExecutorAndSendsMessageOverSystemChannelWhenInformedOfLowMemory() {
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// The FlutterEngine is set up in onAttach().
delegate.onAttach(RuntimeEnvironment.application);
// Emulate the host and call the method that we expect to be forwarded.
delegate.onLowMemory();
// Verify that the call was forwarded to the engine.
verify(mockFlutterEngine.getDartExecutor(), times(1)).notifyLowMemoryWarning();
verify(mockFlutterEngine.getSystemChannel(), times(1)).sendMemoryPressureWarning();
}
@Test
public void itDestroysItsOwnEngineIfHostRequestsIt() {
// ---- Test setup ----
// Adjust fake host to request engine destruction.
when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Push the delegate through all lifecycle methods all the way to destruction.
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
delegate.onResume();
delegate.onPause();
delegate.onStop();
delegate.onDestroyView();
delegate.onDetach();
// --- Verify that the cached engine was destroyed ---
verify(mockFlutterEngine, times(1)).destroy();
}
@Test
public void itDoesNotDestroyItsOwnEngineWhenHostSaysNotTo() {
// ---- Test setup ----
// Adjust fake host to request engine destruction.
when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Push the delegate through all lifecycle methods all the way to destruction.
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
delegate.onResume();
delegate.onPause();
delegate.onStop();
delegate.onDestroyView();
delegate.onDetach();
// --- Verify that the cached engine was destroyed ---
verify(mockFlutterEngine, never()).destroy();
}
@Test
public void itDestroysCachedEngineWhenHostRequestsIt() {
// ---- Test setup ----
// Place a FlutterEngine in the static cache.
FlutterEngine cachedEngine = mockFlutterEngine();
FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine);
// Adjust fake host to request cached engine.
when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine");
// Adjust fake host to request engine destruction.
when(mockHost.shouldDestroyEngineWithHost()).thenReturn(true);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Push the delegate through all lifecycle methods all the way to destruction.
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
delegate.onResume();
delegate.onPause();
delegate.onStop();
delegate.onDestroyView();
delegate.onDetach();
// --- Verify that the cached engine was destroyed ---
verify(cachedEngine, times(1)).destroy();
assertNull(FlutterEngineCache.getInstance().get("my_flutter_engine"));
}
@Test
public void itDoesNotDestroyCachedEngineWhenHostSaysNotTo() {
// ---- Test setup ----
// Place a FlutterEngine in the static cache.
FlutterEngine cachedEngine = mockFlutterEngine();
FlutterEngineCache.getInstance().put("my_flutter_engine", cachedEngine);
// Adjust fake host to request cached engine.
when(mockHost.getCachedEngineId()).thenReturn("my_flutter_engine");
// Adjust fake host to request engine retention.
when(mockHost.shouldDestroyEngineWithHost()).thenReturn(false);
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
// Push the delegate through all lifecycle methods all the way to destruction.
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
delegate.onResume();
delegate.onPause();
delegate.onStop();
delegate.onDestroyView();
delegate.onDetach();
// --- Verify that the cached engine was NOT destroyed ---
verify(cachedEngine, never()).destroy();
}
@Test
public void itDelaysFirstDrawWhenRequested() {
// ---- Test setup ----
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// We're testing lifecycle behaviors, which require/expect that certain methods have already
// been executed by the time they run. Therefore, we run those expected methods first.
delegate.onAttach(RuntimeEnvironment.application);
// --- Execute the behavior under test ---
boolean shouldDelayFirstAndroidViewDraw = true;
delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw);
assertNotNull(delegate.activePreDrawListener);
}
@Test
public void itDoesNotDelayFirstDrawWhenNotRequested() {
// ---- Test setup ----
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// We're testing lifecycle behaviors, which require/expect that certain methods have already
// been executed by the time they run. Therefore, we run those expected methods first.
delegate.onAttach(RuntimeEnvironment.application);
// --- Execute the behavior under test ---
boolean shouldDelayFirstAndroidViewDraw = false;
delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw);
assertNull(delegate.activePreDrawListener);
}
@Test
public void itThrowsWhenDelayingTheFirstDrawAndUsingATextureView() {
// ---- Test setup ----
when(mockHost.getRenderMode()).thenReturn(RenderMode.texture);
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// We're testing lifecycle behaviors, which require/expect that certain methods have already
// been executed by the time they run. Therefore, we run those expected methods first.
delegate.onAttach(RuntimeEnvironment.application);
// --- Execute the behavior under test ---
boolean shouldDelayFirstAndroidViewDraw = true;
assertThrows(
IllegalArgumentException.class,
() -> {
delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw);
});
}
@Test
public void itChangesFlutterViewVisibilityWhenOnStartAndOnStop() {
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// --- Execute the behavior under test ---
delegate.onAttach(RuntimeEnvironment.application);
delegate.onCreateView(null, null, null, 0, true);
delegate.onStart();
// Verify that the flutterView is visible.
assertEquals(View.VISIBLE, delegate.flutterView.getVisibility());
delegate.onStop();
// Verify that the flutterView is not visible.
assertEquals(View.GONE, delegate.flutterView.getVisibility());
delegate.onStart();
// Verify that the flutterView is visible.
assertEquals(View.VISIBLE, delegate.flutterView.getVisibility());
}
@Test
public void itDoesNotDelayTheFirstDrawWhenRequestedAndWithAProvidedSplashScreen() {
when(mockHost.provideSplashScreen())
.thenReturn(new DrawableSplashScreen(new ColorDrawable(Color.GRAY)));
// ---- Test setup ----
// Create the real object that we're testing.
FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(mockHost);
// We're testing lifecycle behaviors, which require/expect that certain methods have already
// been executed by the time they run. Therefore, we run those expected methods first.
delegate.onAttach(RuntimeEnvironment.application);
// --- Execute the behavior under test ---
boolean shouldDelayFirstAndroidViewDraw = true;
delegate.onCreateView(null, null, null, 0, shouldDelayFirstAndroidViewDraw);
assertNull(delegate.activePreDrawListener);
}
/**
* Creates a mock {@link io.flutter.embedding.engine.FlutterEngine}.
*
* <p>The heuristic for deciding what to mock in the given {@link
* io.flutter.embedding.engine.FlutterEngine} is that we should mock the minimum number of
* necessary methods and associated objects. Maintaining developers should add more mock behavior
* as required for tests, but should avoid mocking things that are not required for the correct
* execution of tests.
*/
@NonNull
private FlutterEngine mockFlutterEngine() {
// The use of SettingsChannel by the delegate requires some behavior of its own, so it is
// explicitly mocked with some internal behavior.
SettingsChannel fakeSettingsChannel = mock(SettingsChannel.class);
SettingsChannel.MessageBuilder fakeMessageBuilder = mock(SettingsChannel.MessageBuilder.class);
when(fakeMessageBuilder.setPlatformBrightness(any(SettingsChannel.PlatformBrightness.class)))
.thenReturn(fakeMessageBuilder);
when(fakeMessageBuilder.setTextScaleFactor(any(Float.class))).thenReturn(fakeMessageBuilder);
when(fakeMessageBuilder.setBrieflyShowPassword(any(Boolean.class)))
.thenReturn(fakeMessageBuilder);
when(fakeMessageBuilder.setUse24HourFormat(any(Boolean.class))).thenReturn(fakeMessageBuilder);
when(fakeSettingsChannel.startMessage()).thenReturn(fakeMessageBuilder);
// Mock FlutterEngine and all of its required direct calls.
FlutterEngine engine = mock(FlutterEngine.class);
when(engine.getAccessibilityChannel()).thenReturn(mock(AccessibilityChannel.class));
when(engine.getActivityControlSurface()).thenReturn(mock(ActivityControlSurface.class));
when(engine.getDartExecutor()).thenReturn(mock(DartExecutor.class));
when(engine.getKeyEventChannel()).thenReturn(mock(KeyEventChannel.class));
when(engine.getLifecycleChannel()).thenReturn(mock(LifecycleChannel.class));
when(engine.getLocalizationChannel()).thenReturn(mock(LocalizationChannel.class));
when(engine.getLocalizationPlugin()).thenReturn(mock(LocalizationPlugin.class));
when(engine.getMouseCursorChannel()).thenReturn(mock(MouseCursorChannel.class));
when(engine.getNavigationChannel()).thenReturn(mock(NavigationChannel.class));
when(engine.getPlatformViewsController()).thenReturn(mock(PlatformViewsController.class));
FlutterRenderer renderer = mock(FlutterRenderer.class);
when(engine.getRenderer()).thenReturn(renderer);
when(engine.getSettingsChannel()).thenReturn(fakeSettingsChannel);
when(engine.getSystemChannel()).thenReturn(mock(SystemChannel.class));
when(engine.getTextInputChannel()).thenReturn(mock(TextInputChannel.class));
return engine;
}
}
| bsd-3-clause |
tequa/ammisoft | ammimain/WinPython-64bit-2.7.13.1Zero/python-2.7.13.amd64/Lib/site-packages/jedi/evaluate/sys_path.py | 10686 | import glob
import os
import sys
from jedi.evaluate.site import addsitedir
from jedi._compatibility import exec_function, unicode
from jedi.parser import tree
from jedi.parser import ParserWithRecovery
from jedi.evaluate.cache import memoize_default
from jedi import debug
from jedi import common
from jedi.evaluate.compiled import CompiledObject
from jedi.parser.utils import load_parser, save_parser
def get_venv_path(venv):
"""Get sys.path for specified virtual environment."""
sys_path = _get_venv_path_dirs(venv)
with common.ignored(ValueError):
sys_path.remove('')
sys_path = _get_sys_path_with_egglinks(sys_path)
# As of now, get_venv_path_dirs does not scan built-in pythonpath and
# user-local site-packages, let's approximate them using path from Jedi
# interpreter.
return sys_path + sys.path
def _get_sys_path_with_egglinks(sys_path):
"""Find all paths including those referenced by egg-links.
Egg-link-referenced directories are inserted into path immediately before
the directory on which their links were found. Such directories are not
taken into consideration by normal import mechanism, but they are traversed
when doing pkg_resources.require.
"""
result = []
for p in sys_path:
# pkg_resources does not define a specific order for egg-link files
# using os.listdir to enumerate them, we're sorting them to have
# reproducible tests.
for egg_link in sorted(glob.glob(os.path.join(p, '*.egg-link'))):
with open(egg_link) as fd:
for line in fd:
line = line.strip()
if line:
result.append(os.path.join(p, line))
# pkg_resources package only interprets the first
# non-empty line in egg-link files.
break
result.append(p)
return result
def _get_venv_path_dirs(venv):
"""Get sys.path for venv without starting up the interpreter."""
venv = os.path.abspath(venv)
sitedir = _get_venv_sitepackages(venv)
sys_path = []
addsitedir(sys_path, sitedir)
return sys_path
def _get_venv_sitepackages(venv):
if os.name == 'nt':
p = os.path.join(venv, 'lib', 'site-packages')
else:
p = os.path.join(venv, 'lib', 'python%d.%d' % sys.version_info[:2],
'site-packages')
return p
def _execute_code(module_path, code):
c = "import os; from os.path import *; result=%s"
variables = {'__file__': module_path}
try:
exec_function(c % code, variables)
except Exception:
debug.warning('sys.path manipulation detected, but failed to evaluate.')
else:
try:
res = variables['result']
if isinstance(res, str):
return [os.path.abspath(res)]
except KeyError:
pass
return []
def _paths_from_assignment(module_context, expr_stmt):
"""
Extracts the assigned strings from an assignment that looks as follows::
>>> sys.path[0:0] = ['module/path', 'another/module/path']
This function is in general pretty tolerant (and therefore 'buggy').
However, it's not a big issue usually to add more paths to Jedi's sys_path,
because it will only affect Jedi in very random situations and by adding
more paths than necessary, it usually benefits the general user.
"""
for assignee, operator in zip(expr_stmt.children[::2], expr_stmt.children[1::2]):
try:
assert operator in ['=', '+=']
assert assignee.type in ('power', 'atom_expr') and \
len(assignee.children) > 1
c = assignee.children
assert c[0].type == 'name' and c[0].value == 'sys'
trailer = c[1]
assert trailer.children[0] == '.' and trailer.children[1].value == 'path'
# TODO Essentially we're not checking details on sys.path
# manipulation. Both assigment of the sys.path and changing/adding
# parts of the sys.path are the same: They get added to the current
# sys.path.
"""
execution = c[2]
assert execution.children[0] == '['
subscript = execution.children[1]
assert subscript.type == 'subscript'
assert ':' in subscript.children
"""
except AssertionError:
continue
from jedi.evaluate.iterable import py__iter__
from jedi.evaluate.precedence import is_string
types = module_context.create_context(expr_stmt).eval_node(expr_stmt)
for lazy_context in py__iter__(module_context.evaluator, types, expr_stmt):
for context in lazy_context.infer():
if is_string(context):
yield context.obj
def _paths_from_list_modifications(module_path, trailer1, trailer2):
""" extract the path from either "sys.path.append" or "sys.path.insert" """
# Guarantee that both are trailers, the first one a name and the second one
# a function execution with at least one param.
if not (trailer1.type == 'trailer' and trailer1.children[0] == '.'
and trailer2.type == 'trailer' and trailer2.children[0] == '('
and len(trailer2.children) == 3):
return []
name = trailer1.children[1].value
if name not in ['insert', 'append']:
return []
arg = trailer2.children[1]
if name == 'insert' and len(arg.children) in (3, 4): # Possible trailing comma.
arg = arg.children[2]
return _execute_code(module_path, arg.get_code())
def _check_module(module_context):
"""
Detect sys.path modifications within module.
"""
def get_sys_path_powers(names):
for name in names:
power = name.parent.parent
if power.type in ('power', 'atom_expr'):
c = power.children
if isinstance(c[0], tree.Name) and c[0].value == 'sys' \
and c[1].type == 'trailer':
n = c[1].children[1]
if isinstance(n, tree.Name) and n.value == 'path':
yield name, power
sys_path = list(module_context.evaluator.sys_path) # copy
if isinstance(module_context, CompiledObject):
return sys_path
try:
possible_names = module_context.tree_node.used_names['path']
except KeyError:
# module.used_names is MergedNamesDict whose getitem never throws
# keyerror, this is superfluous.
pass
else:
for name, power in get_sys_path_powers(possible_names):
stmt = name.get_definition()
if len(power.children) >= 4:
sys_path.extend(
_paths_from_list_modifications(
module_context.py__file__(), *power.children[2:4]
)
)
elif name.get_definition().type == 'expr_stmt':
sys_path.extend(_paths_from_assignment(module_context, stmt))
return sys_path
@memoize_default(evaluator_is_first_arg=True, default=[])
def sys_path_with_modifications(evaluator, module_context):
path = module_context.py__file__()
if path is None:
# Support for modules without a path is bad, therefore return the
# normal path.
return list(evaluator.sys_path)
curdir = os.path.abspath(os.curdir)
#TODO why do we need a chdir?
with common.ignored(OSError):
os.chdir(os.path.dirname(path))
buildout_script_paths = set()
result = _check_module(module_context)
result += _detect_django_path(path)
for buildout_script in _get_buildout_scripts(path):
for path in _get_paths_from_buildout_script(evaluator, buildout_script):
buildout_script_paths.add(path)
# cleanup, back to old directory
os.chdir(curdir)
return list(result) + list(buildout_script_paths)
def _get_paths_from_buildout_script(evaluator, buildout_script):
def load(buildout_script):
try:
with open(buildout_script, 'rb') as f:
source = common.source_to_unicode(f.read())
except IOError:
debug.dbg('Error trying to read buildout_script: %s', buildout_script)
return
p = ParserWithRecovery(evaluator.grammar, source, buildout_script)
save_parser(buildout_script, p)
return p.module
cached = load_parser(buildout_script)
module_node = cached and cached.module or load(buildout_script)
if module_node is None:
return
from jedi.evaluate.representation import ModuleContext
for path in _check_module(ModuleContext(evaluator, module_node)):
yield path
def traverse_parents(path):
while True:
new = os.path.dirname(path)
if new == path:
return
path = new
yield path
def _get_parent_dir_with_file(path, filename):
for parent in traverse_parents(path):
if os.path.isfile(os.path.join(parent, filename)):
return parent
return None
def _detect_django_path(module_path):
""" Detects the path of the very well known Django library (if used) """
result = []
for parent in traverse_parents(module_path):
with common.ignored(IOError):
with open(parent + os.path.sep + 'manage.py'):
debug.dbg('Found django path: %s', module_path)
result.append(parent)
return result
def _get_buildout_scripts(module_path):
"""
if there is a 'buildout.cfg' file in one of the parent directories of the
given module it will return a list of all files in the buildout bin
directory that look like python files.
:param module_path: absolute path to the module.
:type module_path: str
"""
project_root = _get_parent_dir_with_file(module_path, 'buildout.cfg')
if not project_root:
return []
bin_path = os.path.join(project_root, 'bin')
if not os.path.exists(bin_path):
return []
extra_module_paths = []
for filename in os.listdir(bin_path):
try:
filepath = os.path.join(bin_path, filename)
with open(filepath, 'r') as f:
firstline = f.readline()
if firstline.startswith('#!') and 'python' in firstline:
extra_module_paths.append(filepath)
except (UnicodeDecodeError, IOError) as e:
# Probably a binary file; permission error or race cond. because file got deleted
# ignore
debug.warning(unicode(e))
continue
return extra_module_paths
| bsd-3-clause |
pozdnyakov/chromium-crosswalk | ui/base/ui_base_switches.cc | 4544 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ui_base_switches.h"
namespace switches {
// Disables use of DWM composition for top level windows.
const char kDisableDwmComposition[] = "disable-dwm-composition";
// Disables the new visual style for application dialogs and controls.
const char kDisableNewDialogStyle[] = "disable-new-dialog-style";
// Disables touch adjustment.
const char kDisableTouchAdjustment[] = "disable-touch-adjustment";
// Disables touch event based drag and drop.
const char kDisableTouchDragDrop[] = "disable-touch-drag-drop";
// Disables controls that support touch base text editing.
const char kDisableTouchEditing[] = "disable-touch-editing";
// Disables the Views textfield on Windows.
const char kDisableViewsTextfield[] = "disable-views-textfield";
// Enables the new visual style for application dialogs and controls.
const char kEnableNewDialogStyle[] = "enable-new-dialog-style";
// Enable scroll prediction for scroll update events.
const char kEnableScrollPrediction[] = "enable-scroll-prediction";
// Enables touch event based drag and drop.
const char kEnableTouchDragDrop[] = "enable-touch-drag-drop";
// Enables controls that support touch base text editing.
const char kEnableTouchEditing[] = "enable-touch-editing";
// Enables the Views textfield on Windows.
const char kEnableViewsTextfield[] = "enable-views-textfield";
// Enables/Disables High DPI support (windows)
const char kHighDPISupport[] = "high-dpi-support";
// Overrides the device scale factor for the browser UI and the contents.
const char kForceDeviceScaleFactor[] = "force-device-scale-factor";
// If a resource is requested at a scale factor at which it is not available
// or the resource is the incorrect size (based on the size of the 1x resource),
// generates the missing resource and applies a red mask to the generated
// resource. Resources for which hidpi is not supported because of software
// reasons will show up pixelated.
const char kHighlightMissingScaledResources[] =
"highlight-missing-scaled-resources";
// The language file that we want to try to open. Of the form
// language[-country] where language is the 2 letter code from ISO-639.
const char kLang[] = "lang";
// Load the locale resources from the given path. When running on Mac/Unix the
// path should point to a locale.pak file.
const char kLocalePak[] = "locale_pak";
// Disable ui::MessageBox. This is useful when running as part of scripts that
// do not have a user interface.
const char kNoMessageBox[] = "no-message-box";
// Enable support for touch events.
const char kTouchEvents[] = "touch-events";
// The values the kTouchEvents switch may have, as in --touch-events=disabled.
// auto: enabled at startup when an attached touchscreen is present.
const char kTouchEventsAuto[] = "auto";
// enabled: touch events always enabled.
const char kTouchEventsEnabled[] = "enabled";
// disabled: touch events are disabled.
const char kTouchEventsDisabled[] = "disabled";
// Enables UI changes that make it easier to use with a touchscreen.
// WARNING: Do not check this flag directly when deciding what UI to draw,
// instead you must call ui::GetDisplayLayout
const char kTouchOptimizedUI[] = "touch-optimized-ui";
// The values the kTouchOptimizedUI switch may have, as in
// "--touch-optimized-ui=disabled".
// auto: Enabled on monitors which have touchscreen support (default).
const char kTouchOptimizedUIAuto[] = "auto";
// enabled: always optimized for touch (even if no touch support).
const char kTouchOptimizedUIEnabled[] = "enabled";
// disabled: never optimized for touch.
const char kTouchOptimizedUIDisabled[] = "disabled";
#if defined(USE_XI2_MT)
// The calibration factors given as "<left>,<right>,<top>,<bottom>".
const char kTouchCalibration[] = "touch-calibration";
#endif
#if defined(OS_MACOSX)
// Disables support for Core Animation plugins. This is triggered when
// accelerated compositing is disabled. See http://crbug.com/122430 .
const char kDisableCoreAnimationPlugins[] =
"disable-core-animation-plugins";
#endif
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX)
// Tells chrome to interpret events from these devices as touch events. Only
// available with XInput 2 (i.e. X server 1.8 or above). The id's of the
// devices can be retrieved from 'xinput list'.
const char kTouchDevices[] = "touch-devices";
#endif
} // namespace switches
| bsd-3-clause |
alexkolar/Wooey | wooey/urls.py | 3225 | from __future__ import absolute_import
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from . import views
from . import settings as wooey_settings
wooey_patterns = [
url(r'^jobs/command$', views.celery_task_command, name='celery_task_command'),
url(r'^jobs/queue/global/json$', views.global_queue_json, name='global_queue_json'),
url(r'^jobs/queue/user/json$', views.user_queue_json, name='user_queue_json'),
url(r'^jobs/results/user/json$', views.user_results_json, name='user_results_json'),
url(r'^jobs/queue/all/json', views.all_queues_json, name='all_queues_json'),
url(r'^jobs/queue/global', views.GlobalQueueView.as_view(), name='global_queue'),
url(r'^jobs/queue/user', views.UserQueueView.as_view(), name='user_queue'),
url(r'^jobs/results/user', views.UserResultsView.as_view(), name='user_results'),
url(r'^jobs/(?P<job_id>[0-9\-]+)/$', views.JobView.as_view(), name='celery_results'),
url(r'^jobs/(?P<job_id>[0-9\-]+)/json$', views.JobJSON.as_view(), name='celery_results_json'),
# Global public access via uuid
url(r'^jobs/(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12})/$', views.JobView.as_view(), name='celery_results_uuid'),
url(r'^jobs/(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12})/json$', views.JobJSON.as_view(), name='celery_results_json_uuid'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/$', views.WooeyScriptView.as_view(), name='wooey_script'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/version/(?P<script_version>[A-Za-z\.0-9]+)$', views.WooeyScriptView.as_view(), name='wooey_script'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/version/(?P<script_version>[A-Za-z\.0-9]+)/iteration/(?P<script_iteration>\d+)$', views.WooeyScriptView.as_view(), name='wooey_script'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/jobs/(?P<job_id>[a-zA-Z0-9\-]+)$', views.WooeyScriptView.as_view(), name='wooey_script_clone'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/$', views.WooeyScriptJSON.as_view(), name='wooey_script_json'),
url(r'^scripts/search/json$', views.WooeyScriptSearchJSON.as_view(), name='wooey_search_script_json'),
url(r'^scripts/search/jsonhtml$', views.WooeyScriptSearchJSONHTML.as_view(), name='wooey_search_script_jsonhtml'),
url(r'^profile/$', views.WooeyProfileView.as_view(), name='profile_home'),
url(r'^profile/(?P<username>[a-zA-Z0-9\-]+)$', views.WooeyProfileView.as_view(), name='profile'),
url(r'^$', views.WooeyHomeView.as_view(), name='wooey_home'),
url(r'^$', views.WooeyHomeView.as_view(), name='wooey_job_launcher'),
url('^{}'.format(wooey_settings.WOOEY_LOGIN_URL.lstrip('/')), views.wooey_login, name='wooey_login'),
url('^{}'.format(wooey_settings.WOOEY_REGISTER_URL.lstrip('/')), views.WooeyRegister.as_view(), name='wooey_register'),
url(r'^favorite/toggle$', views.toggle_favorite, name='toggle_favorite'),
url(r'^scrapbook$', views.WooeyScrapbookView.as_view(), name='scrapbook'),
]
urlpatterns = [
url('^', include(wooey_patterns, namespace='wooey')),
url('^', include('django.contrib.auth.urls')),
]
| bsd-3-clause |
piyushsh/choco3 | choco-solver/src/test/java/org/chocosolver/solver/search/ParetoTest.java | 6565 | /*
* Copyright (c) 1999-2015, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Ecole des Mines de Nantes nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.chocosolver.solver.search;
import org.chocosolver.memory.copy.EnvironmentCopying;
import org.chocosolver.solver.ResolutionPolicy;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.IntConstraintFactory;
import org.chocosolver.solver.search.loop.monitors.IMonitorSolution;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.VariableFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Created by cprudhom on 18/02/15.
* Project: choco.
*/
public class ParetoTest {
//******************************************************************
// CP VARIABLES
//******************************************************************
// --- CP Solver
private Solver s;
// --- Decision variables
private IntVar[] occurrences;
// --- Cumulated profit_1 of selected items
private IntVar totalProfit_1;
// --- Cumulated profit_2 of selected items
private IntVar totalProfit_2;
// --- Cumulated weight of selected items
private IntVar totalWeight;
//******************************************************************
// DATA
//******************************************************************
// --- Capacity of the knapsack
private final int capacity;
// --- Maximal profit_1 of the knapsack
private int maxProfit_1;
// --- Maximal profit_2 of the knapsack
private int maxProfit_2;
// --- Number of items in each category
private final int[] nbItems;
// --- Weight of items in each category
private final int[] weights;
// --- Profit_1 of items in each category
private final int[] profits_1;
// --- Profit_2 of items in each category
private final int[] profits_2;
//******************************************************************
// CONSTRUCTOR
//******************************************************************
public ParetoTest(final int capacity, final String... items) {
this.capacity = capacity;
this.nbItems = new int[items.length];
this.weights = new int[items.length];
this.profits_1 = new int[items.length];
this.profits_2 = new int[items.length];
this.maxProfit_1 = 0;
this.maxProfit_2 = 0;
for (int it = 0; it < items.length; it++) {
String item = items[it];
item = item.trim();
final String[] itemData = item.split(";");
this.nbItems[it] = Integer.parseInt(itemData[0]);
this.weights[it] = Integer.parseInt(itemData[1]);
this.profits_1[it] = Integer.parseInt(itemData[2]);
this.profits_2[it] = Integer.parseInt(itemData[3]);
this.maxProfit_1 += this.nbItems[it] * this.profits_1[it];
this.maxProfit_2 += this.nbItems[it] * this.profits_2[it];
}
}
//******************************************************************
// METHODS
//******************************************************************
private void createSolver() {
// --- Creates a solver
s = new Solver(new EnvironmentCopying(), "Knapsack");
}
private void buildModel() {
createVariables();
postConstraints();
}
private void createVariables() {
// --- Creates decision variables
occurrences = new IntVar[nbItems.length];
for (int i = 0; i < nbItems.length; i++) {
occurrences[i] = VariableFactory.bounded("occurrences_" + i, 0, nbItems[i], s);
}
totalWeight = VariableFactory.bounded("totalWeight", 0, capacity, s);
totalProfit_1 = VariableFactory.bounded("totalProfit_1", 0, maxProfit_1, s);
totalProfit_2 = VariableFactory.bounded("totalProfit_2", 0, maxProfit_2, s);
}
private void postConstraints() {
// --- Posts a knapsack constraint on profit_1
s.post(IntConstraintFactory.knapsack(occurrences, totalWeight, totalProfit_1, weights, profits_1));
// --- Posts a knapsack constraint on profit_2
s.post(IntConstraintFactory.knapsack(occurrences, totalWeight, totalProfit_2, weights, profits_2));
}
static int bestProfit1 = 0;
private void solve() {
// --- Solves the problem
s.plugMonitor((IMonitorSolution) () -> bestProfit1 = Math.max(bestProfit1, totalProfit_1.getValue()));
// Chatterbox.showSolutions(s);
s.findParetoFront(ResolutionPolicy.MAXIMIZE, totalProfit_1, totalProfit_2);
}
//******************************************************************
// MAIN
//******************************************************************
@Test
public static void main() {
ParetoTest instance = new ParetoTest(30, "10;1;2;5", "5;3;7;4", "2;5;11;3");
instance.createSolver();
instance.buildModel();
instance.solve();
Assert.assertTrue(bestProfit1 > 60);
}
}
| bsd-3-clause |
kore/Phake | src/Phake/Stubber/Answers/ExceptionAnswer.php | 2595 | <?php
/*
* Phake - Mocking Framework
*
* Copyright (c) 2010-2012, Mike Lively <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Mike Lively nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @category Testing
* @package Phake
* @author Mike Lively <[email protected]>
* @copyright 2010 Mike Lively <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://www.digitalsandwich.com/
*/
/**
* Allows providing an exception to throw to a stubbed method call.
*
* @author Brian Feaver <[email protected]>
*/
class Phake_Stubber_Answers_ExceptionAnswer implements Phake_Stubber_IAnswer
{
/**
* @var mixed
*/
private $answer;
/**
* @param mixed $answer
*/
public function __construct(Exception $answer)
{
$this->answer = $answer;
}
public function getAnswerCallback($context, $method)
{
$answer = $this->answer;
return function () use ($answer) {
throw $answer;
};
}
public function processAnswer($answer)
{
}
}
| bsd-3-clause |
NCIP/cagrid | cagrid/Software/core/caGrid/projects/opensaml/src/gov/nih/nci/cagrid/opensaml/artifact/SAMLArtifactType0002.java | 10727 | /*
* Copyright 2001-2005 Internet2
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* File: SAMLArtifactType0002.java
*
*/
package gov.nih.nci.cagrid.opensaml.artifact;
import gov.nih.nci.cagrid.opensaml.SAMLConfig;
import gov.nih.nci.cagrid.opensaml.artifact.Artifact;
import gov.nih.nci.cagrid.opensaml.artifact.ArtifactParseException;
import gov.nih.nci.cagrid.opensaml.artifact.SAMLArtifact;
import gov.nih.nci.cagrid.opensaml.artifact.Util;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
/**
* <p>This class implements a type 0x0002 artifact as
* specified by SAML V1.1.</p>
*
* <pre>TypeCode := 0x0002
*RemainingArtifact := AssertionHandle SourceLocation
*AssertionHandle := 20-byte_sequence
*SourceLocation := URI</pre>
*
* <p>Since the URI is arbitrary, a type 0x0002
* artifact is of indeterminate size.</p>
*
* <p>The <code>AssertionHandle</code> is a sequence
* of random bytes that points to an
* authentication assertion at the IdP.</p>
*
* <p>Before the artifact is base64-encoded, the URI
* is converted to a sequence of bytes based on UTF-8.
* While parsing an encoded artifact, this encoding
* process is reversed.</p>
*
* @author Tom Scavo
*/
public class SAMLArtifactType0002 extends SAMLArtifact {
/**
* The type code of this <code>Artifact</code> object.
*/
public static final Artifact.TypeCode TYPE_CODE =
new TypeCode( (byte) 0x00, (byte) 0x02 );
/**
* This constructor initializes the
* <code>remainingArtifact</code> property by calling
* the corresponding constructor of this implementation
* of <code>Artifact.RemainingArtifact</code>.
* <p>
* This constructor throws an (unchecked)
* <code>NullArgumentException</code> if its argument is null.
*
* @param sourceLocation the desired source location
* of this <code>SAMLArtifactType0002</code> object
*
* @see SAMLArtifactType0002.RemainingArtifact
* @see gov.nih.nci.cagrid.opensaml.artifact.NullArgumentException
*/
public SAMLArtifactType0002( URI sourceLocation ) {
checkNullArg( sourceLocation );
this.typeCode = TYPE_CODE;
this.remainingArtifact = new RemainingArtifact( sourceLocation );
}
/**
* This constructor initializes the
* <code>remainingArtifact</code> property by calling
* the corresponding constructor of this implementation
* of <code>Artifact.RemainingArtifact</code>.
* <p>
* This constructor throws a <code>NullArgumentException</code>
* or <code>InvalidArgumentException</code> if any of its
* arguments are null or invalid, respectively.
* These exceptions are unchecked.
*
* @param assertionHandle the desired assertion handle
* of this <code>SAMLArtifactType0002</code> object
*
* @param sourceLocation the desired source location
* of this <code>SAMLArtifactType0002</code> object
*
* @see SAMLArtifactType0002.RemainingArtifact
* @see gov.nih.nci.cagrid.opensaml.artifact.NullArgumentException
* @see gov.nih.nci.cagrid.opensaml.artifact.InvalidArgumentException
*/
public SAMLArtifactType0002( byte[] assertionHandle, URI sourceLocation ) {
checkHandleArg( assertionHandle );
checkNullArg( sourceLocation );
this.typeCode = TYPE_CODE;
this.remainingArtifact =
new RemainingArtifact( assertionHandle, sourceLocation );
}
/**
* This constructor initializes the
* <code>remainingArtifact</code> property to the
* given value.
* <p>
* This constructor throws an (unchecked)
* <code>NullArgumentException</code> if its argument is null.
*
* @param remainingArtifact the desired value of
* the <code>remainingArtifact</code> property
* of this <code>SAMLArtifactType0002</code> object
*
* @see SAMLArtifactType0002.RemainingArtifact
* @see gov.nih.nci.cagrid.opensaml.artifact.NullArgumentException
*/
public SAMLArtifactType0002( Artifact.RemainingArtifact remainingArtifact ) {
checkNullArg( remainingArtifact );
this.typeCode = TYPE_CODE;
this.remainingArtifact = remainingArtifact;
}
/**
* A convenience method that returns the
* <code>assertionHandle</code> property of this implementation
* of <code>Artifact.RemainingArtifact</code>.
*
* @return the <code>assertionHandle</code> property
*
* @see SAMLArtifactType0002.RemainingArtifact
*/
public byte[] getAssertionHandle() {
return ((RemainingArtifact) this.remainingArtifact).getAssertionHandle();
}
/**
* A convenience method that returns the
* <code>sourceLocation</code> property of this implementation
* of <code>Artifact.RemainingArtifact</code>.
*
* @return the <code>sourceLocation</code> property
*
* @see SAMLArtifactType0002.RemainingArtifact
*/
public URI getSourceLocation() {
return ((RemainingArtifact) this.remainingArtifact).getSourceLocation();
}
/**
* An implementation of <code>Artifact.RemainingArtifact</code>
* for type 0x0002 artifacts (via extension of
* <code>SAMLArtifact.RemainingArtifact</code>).
* This class defines two properties
* (<code>assertionHandle</code> and <code>sourceLocation</code>).
*/
public static final class RemainingArtifact
extends SAMLArtifact.RemainingArtifact {
private byte[] assertionHandle;
private URI sourceLocation;
private byte[] sourceLocationBytes;
/**
* This constructor initializes the <code>sourceLocation</code>
* property of this <code>RemainingArtifact</code>
* object to the given value. The <code>assertionHandle</code>
* property is initialized to a sequence of random bytes.
*
* @param sourceLocation a source location
*/
public RemainingArtifact( URI sourceLocation ) {
byte[] assertionHandle = SAMLConfig.instance().getDefaultIDProvider().generateRandomBytes( HANDLE_LENGTH );
RemainingArtifact ra;
ra = new RemainingArtifact( assertionHandle, sourceLocation );
this.assertionHandle = ra.assertionHandle;
this.sourceLocation = ra.sourceLocation;
this.sourceLocationBytes = ra.sourceLocationBytes;
}
/**
* This constructor initializes the properties
* of this <code>RemainingArtifact</code>
* object to the given values.
* <p>
* This constructor throws a <code>NullArgumentException</code>
* or <code>InvalidArgumentException</code> if any of its
* arguments are null or invalid, respectively.
* These exceptions are unchecked.
*
* @param assertionHandle an assertion handle
*
* @param sourceLocation a source location
*
* @see gov.nih.nci.cagrid.opensaml.artifact.NullArgumentException
* @see gov.nih.nci.cagrid.opensaml.artifact.InvalidArgumentException
*/
public RemainingArtifact( byte[] assertionHandle, URI sourceLocation ) {
checkHandleArg( assertionHandle );
checkNullArg( sourceLocation );
this.assertionHandle = assertionHandle;
this.sourceLocation = sourceLocation;
this.sourceLocationBytes = sourceLocation.toBytes();
}
/**
* Get the <code>assertionHandle</code> property of this
* <code>Artifact.RemainingArtifact</code> object.
*
* return the <code>assertionHandle</code> property
*/
public byte[] getAssertionHandle() { return this.assertionHandle; }
/**
* Get the <code>sourceLocation</code> property of this
* <code>Artifact.RemainingArtifact</code> object.
*
* return the <code>sourceLocation</code> property
*/
public URI getSourceLocation() { return this.sourceLocation; }
public int size() {
return this.assertionHandle.length + this.sourceLocationBytes.length;
}
public byte[] getBytes() {
byte[] bytes0 = this.assertionHandle;
byte[] bytes1 = this.sourceLocationBytes;
return Util.concat( bytes0, bytes1 );
}
public int hashCode() {
return this.assertionHandle.hashCode() &
this.sourceLocationBytes.hashCode();
}
}
/**
* An implementation of <code>Artifact.Parser</code>
* for type 0x0002 artifacts.
*/
public static final class Parser implements Artifact.Parser {
/**
* Parse the given encoded string.
*
* @param s the encoded string
*
* @return an artifact that may be cast to type
* <code>SAMLArtifactType0002</code>
*
* @exception gov.nih.nci.cagrid.opensaml.artifact.ArtifactParseException
* if the length of the decoded string is
* less than the minimum length, or the
* type code is incorrect, or
* the tail portion of the parsed string
* is not a valid URI
*
* @see org.apache.commons.codec.binary.Base64
*/
public Artifact parse( String s ) throws ArtifactParseException {
// check total length:
byte[] bytes = Base64.decodeBase64( s.getBytes() );
int minLength = 2 + HANDLE_LENGTH;
if ( bytes.length < minLength ) {
throw new ArtifactParseException( bytes.length, minLength );
}
// check type code:
TypeCode typeCode =
new TypeCode( bytes[0], bytes[1] );
if ( ! typeCode.equals( TYPE_CODE ) ) {
throw new ArtifactParseException( typeCode, TYPE_CODE );
}
// extract the assertion handle:
byte[] assertionHandle = new byte[ HANDLE_LENGTH ];
System.arraycopy( bytes, 2, assertionHandle, 0, HANDLE_LENGTH );
// extract the remaining bytes:
int length = bytes.length - minLength;
byte[] remainingBytes = new byte[ length ];
System.arraycopy( bytes, minLength, remainingBytes, 0, length );
// convert the remaining bytes to a string:
URI uri;
try {
uri = new URI( remainingBytes, "UTF-8" );
}
catch (UnsupportedEncodingException e) {
throw new ArtifactParseException("UTF-8 unsupported string format, can not create artifact URI");
}
return new SAMLArtifactType0002( assertionHandle, uri );
}
}
}
| bsd-3-clause |
g1o/trinityrnaseq | util/support_scripts/SAM_coordSorted_fragment_Read_coverage_writer.pl | 2050 | #!/usr/bin/env perl
use strict;
use warnings;
use FindBin;
use lib ("$FindBin::RealBin/../../PerlLib");
use SAM_reader;
use SAM_entry;
my $usage = "usage: $0 coordSorted.file.sam\n\n";
my $sam_file = $ARGV[0] or die $usage;
main: {
my %scaffold_to_coverage; # will retain all coverage information.
my $sam_reader = new SAM_reader($sam_file);
my $current_scaff = undef;
my $counter = 0;
while ($sam_reader->has_next()) {
$counter++;
if ($counter % 1000 == 0) {
print STDERR "\r[$counter] ";
}
my $sam_entry = $sam_reader->get_next();
if ($sam_entry->is_query_unmapped()) { next; }
if (%scaffold_to_coverage && $sam_entry->get_scaffold_name() ne $current_scaff) {
&report_coverage(\%scaffold_to_coverage);
%scaffold_to_coverage = ();
}
$current_scaff = $sam_entry->get_scaffold_name();
&add_coverage($sam_entry, \%scaffold_to_coverage);
}
if (%scaffold_to_coverage) {
&report_coverage(\%scaffold_to_coverage);
}
exit(0);
}
####
sub report_coverage {
my ($scaffold_to_coverage_href) = @_;
## output the coverage information:
foreach my $scaffold (sort keys %$scaffold_to_coverage_href) {
print "variableStep chrom=$scaffold\n";
my @coverage = @{$scaffold_to_coverage_href->{$scaffold}};
for (my $i = 1; $i <= $#coverage; $i++) {
my $cov = $coverage[$i] || 0;
print "$i\t$cov\n";
}
}
return;
}
####
sub add_coverage {
my ($sam_entry, $scaffold_to_coverage_href) = @_;
## If the entry is paired and the query alignment
## is less than the paired position, then fill in the gap.
my $scaffold = $sam_entry->get_scaffold_name();
my $scaff_pos = $sam_entry->get_scaffold_position();
my @genome_coords;
my ($genome_coords_aref, $query_coords_aref) = $sam_entry->get_alignment_coords();
foreach my $coordset (@$genome_coords_aref) {
my ($lend, $rend) = @$coordset;
## add coverage:
for (my $i = $lend; $i <= $rend; $i++) {
$scaffold_to_coverage_href->{$scaffold}->[$i]++;
}
}
return;
}
| bsd-3-clause |
trueos/pcdm | src-qt5/PCDM/i18n/PCDM_en_ZA.ts | 8374 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
<name>FancySwitcher</name>
<message>
<source>Alt+Left</source>
<translation>Alt+Left</translation>
</message>
<message>
<source>Alt+Right</source>
<translation>Alt+Right</translation>
</message>
<message>
<source>Alt+Up</source>
<translation>Alt+Up</translation>
</message>
<message>
<source>Alt+Down</source>
<translation>Alt+Down</translation>
</message>
</context>
<context>
<name>LoginWidget</name>
<message>
<source>Select</source>
<translation>Select</translation>
</message>
<message>
<source>Select an alternate user and clear the password field</source>
<translation>Select an alternate user and clear the password field</translation>
</message>
<message>
<source>Select this user</source>
<translation>Select this user</translation>
</message>
<message>
<source>Login</source>
<translation>Login</translation>
</message>
<message>
<source>Login to the system with the current user and password</source>
<translation>Login to the system with the current user and password</translation>
</message>
<message>
<source>Password</source>
<translation>Password</translation>
</message>
<message>
<source>Hold to view the currently entered password</source>
<translation>Hold to view the currently entered password</translation>
</message>
<message>
<source>Login password for the selected user</source>
<translation>Login password for the selected user</translation>
</message>
<message>
<source>Available users</source>
<translation>Available users</translation>
</message>
<message>
<source>Login to %1</source>
<translation>Login to %1</translation>
</message>
<message>
<source>Available desktop environments</source>
<translation>Available desktop environments</translation>
</message>
<message>
<source>Please connect your PersonaCrypt device to start login procedures.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Stealth Session</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Use a temporary home directory which is deleted on log out)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Refresh</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Refresh available users</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Device encryption key</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Device encryption key (personacrypt users only)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCDMgui</name>
<message>
<source>Virtual Keyboard</source>
<translation>Virtual Keyboard</translation>
</message>
<message>
<source>Locale</source>
<translation>Locale</translation>
</message>
<message>
<source>Keyboard Layout</source>
<translation>Keyboard Layout</translation>
</message>
<message>
<source>Change Keyboard Layout</source>
<translation>Change Keyboard Layout</translation>
</message>
<message>
<source>System</source>
<translation>System</translation>
</message>
<message>
<source>Tip: Make sure that caps-lock is turned off.</source>
<translation>Tip: Make sure that caps-lock is turned off.</translation>
</message>
<message>
<source>Restart</source>
<translation>Restart</translation>
</message>
<message>
<source>Shut Down</source>
<translation>Shut Down</translation>
</message>
<message>
<source>Close PCDM</source>
<translation>Close PCDM</translation>
</message>
<message>
<source>Shutdown the computer</source>
<translation>Shutdown the computer</translation>
</message>
<message>
<source>Invalid Username/Password</source>
<translation>Invalid Username/Password</translation>
</message>
<message>
<source>Username/Password combination is invalid, please try again.</source>
<translation>Username/Password combination is invalid, please try again.</translation>
</message>
<message>
<source>System Shutdown</source>
<translation>System Shutdown</translation>
</message>
<message>
<source>You are about to shut down the system.</source>
<translation>You are about to shut down the system.</translation>
</message>
<message>
<source>Are you sure?</source>
<translation>Are you sure?</translation>
</message>
<message>
<source>System Restart</source>
<translation>System Restart</translation>
</message>
<message>
<source>You are about to restart the system.</source>
<translation>You are about to restart the system.</translation>
</message>
<message>
<source>Change locale (%1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Change DPI</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>High (4K)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Standard</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Low </source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Refresh PCDM</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>loginDelay</name>
<message>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<source>%v/%m seconds</source>
<translation>%v/%m seconds</translation>
</message>
<message>
<source>Cancel Login</source>
<translation>Cancel Login</translation>
</message>
<message>
<source>Login Now</source>
<translation>Login Now</translation>
</message>
<message>
<source>PCDM Automatic Login</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>widgetKeyboard</name>
<message>
<source>Keyboard Settings</source>
<translation>Keyboard Settings</translation>
</message>
<message>
<source>Key Layout</source>
<translation>Key Layout</translation>
</message>
<message>
<source>Variant</source>
<translation>Variant</translation>
</message>
<message>
<source>Keyboard Model</source>
<translation>Keyboard Model</translation>
</message>
<message>
<source>( you may type into the space below to test your selected settings. )</source>
<translation>( you may type into the space below to test your selected settings. )</translation>
</message>
<message>
<source>&Apply</source>
<translation>&Apply</translation>
</message>
<message>
<source>&Close</source>
<translation>&Close</translation>
</message>
</context>
<context>
<name>widgetLocale</name>
<message>
<source>Select Locale</source>
<translation>Select Locale</translation>
</message>
<message>
<source>Current Locale</source>
<translation>Current Locale</translation>
</message>
<message>
<source>Apply</source>
<translation>Apply</translation>
</message>
<message>
<source>Cancel</source>
<translation>Cancel</translation>
</message>
</context>
</TS>
| bsd-3-clause |
programerjakarta/tokojaya | frontend/views/transaksi/view.php | 1021 | <?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model frontend\models\Penjualan */
$this->title = $model->idpenjualan;
$this->params['breadcrumbs'][] = ['label' => 'Penjualans', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="penjualan-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->idpenjualan], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->idpenjualan], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'idpenjualan',
'tglpenjualan',
'jmlbarang',
'ttlbayar',
'idpelanggan',
],
]) ?>
</div>
| bsd-3-clause |
ChromeDevTools/devtools-frontend | node_modules/@babel/runtime-corejs3/helpers/esm/objectSpread.js | 1330 | import _forEachInstanceProperty from "@babel/runtime-corejs3/core-js/instance/for-each";
import _Object$getOwnPropertyDescriptor from "@babel/runtime-corejs3/core-js/object/get-own-property-descriptor";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js/instance/filter";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js/instance/concat";
import _Object$getOwnPropertySymbols from "@babel/runtime-corejs3/core-js/object/get-own-property-symbols";
import _Object$keys from "@babel/runtime-corejs3/core-js/object/keys";
import defineProperty from "@babel/runtime-corejs3/helpers/esm/defineProperty";
export default function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? Object(arguments[i]) : {};
var ownKeys = _Object$keys(source);
if (typeof _Object$getOwnPropertySymbols === 'function') {
var _context;
ownKeys = _concatInstanceProperty(ownKeys).call(ownKeys, _filterInstanceProperty(_context = _Object$getOwnPropertySymbols(source)).call(_context, function (sym) {
return _Object$getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
_forEachInstanceProperty(ownKeys).call(ownKeys, function (key) {
defineProperty(target, key, source[key]);
});
}
return target;
} | bsd-3-clause |
ds-hwang/chromium-crosswalk | third_party/WebKit/Source/platform/TraceEvent.h | 27889 | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This header file defines implementation details of how the trace macros in
// TraceEventCommon.h collect and store trace events. Anything not
// implementation-specific should go in TraceEventCommon.h instead of here.
#ifndef TraceEvent_h
#define TraceEvent_h
#include "platform/EventTracer.h"
#include "platform/TraceEventCommon.h"
#include "platform/TracedValue.h"
#include "wtf/Allocator.h"
#include "wtf/DynamicAnnotations.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/CString.h"
////////////////////////////////////////////////////////////////////////////////
// Implementation specific tracing API definitions.
// By default, const char* argument values are assumed to have long-lived scope
// and will not be copied. Use this macro to force a const char* to be copied.
#define TRACE_STR_COPY(str) \
blink::TraceEvent::TraceStringWithCopy(str)
// By default, uint64 ID argument values are not mangled with the Process ID in
// TRACE_EVENT_ASYNC macros. Use this macro to force Process ID mangling.
#define TRACE_ID_MANGLE(id) \
blink::TraceEvent::TraceID::ForceMangle(id)
// By default, pointers are mangled with the Process ID in TRACE_EVENT_ASYNC
// macros. Use this macro to prevent Process ID mangling.
#define TRACE_ID_DONT_MANGLE(id) \
blink::TraceEvent::TraceID::DontMangle(id)
// By default, trace IDs are eventually converted to a single 64-bit number. Use
// this macro to add a scope string.
#define TRACE_ID_WITH_SCOPE(scope, id) \
blink::TraceEvent::TraceID::WithScope(scope, id)
// Creates a scope of a sampling state with the given category and name (both must
// be constant strings). These states are intended for a sampling profiler.
// Implementation note: we store category and name together because we don't
// want the inconsistency/expense of storing two pointers.
// |thread_bucket| is [0..2] and is used to statically isolate samples in one
// thread from others.
//
// { // The sampling state is set within this scope.
// TRACE_EVENT_SAMPLING_STATE_SCOPE_FOR_BUCKET(0, "category", "name");
// ...;
// }
#define TRACE_EVENT_SCOPED_SAMPLING_STATE_FOR_BUCKET(bucket_number, category, name) \
TraceEvent::SamplingStateScope<bucket_number> traceEventSamplingScope(category "\0" name);
// Returns a current sampling state of the given bucket.
// The format of the returned string is "category\0name".
#define TRACE_EVENT_GET_SAMPLING_STATE_FOR_BUCKET(bucket_number) \
TraceEvent::SamplingStateScope<bucket_number>::current()
// Sets a current sampling state of the given bucket.
// |category| and |name| have to be constant strings.
#define TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(bucket_number, category, name) \
TraceEvent::SamplingStateScope<bucket_number>::set(category "\0" name)
// Sets a current sampling state of the given bucket.
// |categoryAndName| doesn't need to be a constant string.
// The format of the string is "category\0name".
#define TRACE_EVENT_SET_NONCONST_SAMPLING_STATE_FOR_BUCKET(bucket_number, categoryAndName) \
TraceEvent::SamplingStateScope<bucket_number>::set(categoryAndName)
// Get a pointer to the enabled state of the given trace category. Only
// long-lived literal strings should be given as the category name. The returned
// pointer can be held permanently in a local static for example. If the
// unsigned char is non-zero, tracing is enabled. If tracing is enabled,
// TRACE_EVENT_API_ADD_TRACE_EVENT can be called. It's OK if tracing is disabled
// between the load of the tracing state and the call to
// TRACE_EVENT_API_ADD_TRACE_EVENT, because this flag only provides an early out
// for best performance when tracing is disabled.
// const unsigned char*
// TRACE_EVENT_API_GET_CATEGORY_ENABLED(const char* category_name)
#define TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED \
blink::EventTracer::getTraceCategoryEnabledFlag
// Add a trace event to the platform tracing system.
// blink::TraceEvent::TraceEventHandle TRACE_EVENT_API_ADD_TRACE_EVENT(
// const char* name,
// const char* scope,
// unsigned long long id,
// double timestamp,
// int num_args,
// const char** arg_names,
// const unsigned char* arg_types,
// const unsigned long long* arg_values,
// PassOwnPtr<TracedValue> tracedValues[],
// unsigned char flags)
#define TRACE_EVENT_API_ADD_TRACE_EVENT \
blink::EventTracer::addTraceEvent
// Set the duration field of a COMPLETE trace event.
// void TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(
// blink::TraceEvent::TraceEventHandle handle)
#define TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION \
blink::EventTracer::updateTraceEventDuration
////////////////////////////////////////////////////////////////////////////////
// Implementation detail: trace event macros create temporary variables
// to keep instrumentation overhead low. These macros give each temporary
// variable a unique name based on the line number to prevent name collissions.
#define INTERNAL_TRACE_EVENT_UID3(a, b) \
trace_event_unique_##a##b
#define INTERNAL_TRACE_EVENT_UID2(a, b) \
INTERNAL_TRACE_EVENT_UID3(a, b)
#define INTERNALTRACEEVENTUID(name_prefix) \
INTERNAL_TRACE_EVENT_UID2(name_prefix, __LINE__)
// Implementation detail: internal macro to create static category.
// - WTF_ANNOTATE_BENIGN_RACE, see Thread Safety above.
#define INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category) \
static const unsigned char* INTERNALTRACEEVENTUID(categoryGroupEnabled) = 0; \
WTF_ANNOTATE_BENIGN_RACE(&INTERNALTRACEEVENTUID(categoryGroupEnabled), \
"trace_event category"); \
if (!INTERNALTRACEEVENTUID(categoryGroupEnabled)) { \
INTERNALTRACEEVENTUID(categoryGroupEnabled) = \
TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(category); \
}
// Implementation detail: internal macro to create static category and add
// event if the category is enabled.
#define INTERNAL_TRACE_EVENT_ADD(phase, category, name, flags, ...) \
do { \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
if (INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE()) { \
blink::TraceEvent::addTraceEvent( \
phase, INTERNALTRACEEVENTUID(categoryGroupEnabled), name, \
blink::TraceEvent::kGlobalScope, blink::TraceEvent::noEventId, \
flags, ##__VA_ARGS__); \
} \
} while (0)
// Implementation detail: internal macro to create static category and add begin
// event if the category is enabled. Also adds the end event when the scope
// ends.
#define INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name, ...) \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
blink::TraceEvent::ScopedTracer INTERNALTRACEEVENTUID(scopedTracer); \
if (INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE()) { \
blink::TraceEvent::TraceEventHandle h = \
blink::TraceEvent::addTraceEvent( \
TRACE_EVENT_PHASE_COMPLETE, \
INTERNALTRACEEVENTUID(categoryGroupEnabled), name, \
blink::TraceEvent::kGlobalScope, blink::TraceEvent::noEventId, \
TRACE_EVENT_FLAG_NONE, ##__VA_ARGS__); \
INTERNALTRACEEVENTUID(scopedTracer).initialize( \
INTERNALTRACEEVENTUID(categoryGroupEnabled), name, h); \
}
#define INTERNAL_TRACE_EVENT_ADD_SCOPED_WITH_FLOW(category, name, bindId, flowFlags, ...) \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
blink::TraceEvent::ScopedTracer INTERNALTRACEEVENTUID(scopedTracer); \
if (INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE()) { \
unsigned traceEventFlags = flowFlags; \
blink::TraceEvent::TraceID traceEventBindId(bindId, &traceEventFlags); \
blink::TraceEvent::TraceEventHandle h = \
blink::TraceEvent::addTraceEvent( \
TRACE_EVENT_PHASE_COMPLETE, \
INTERNALTRACEEVENTUID(categoryGroupEnabled), name, \
blink::TraceEvent::kGlobalScope, blink::TraceEvent::noEventId, \
traceEventBindId.data(), \
EventTracer::systemTraceTime(), traceEventFlags, ##__VA_ARGS__); \
INTERNALTRACEEVENTUID(scopedTracer).initialize( \
INTERNALTRACEEVENTUID(categoryGroupEnabled), name, h); \
}
// Implementation detail: internal macro to create static category and add
// event if the category is enabled.
#define INTERNAL_TRACE_EVENT_ADD_WITH_ID(phase, category, name, id, flags, ...) \
do { \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
if (INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE()) { \
unsigned traceEventFlags = flags | TRACE_EVENT_FLAG_HAS_ID; \
blink::TraceEvent::TraceID traceEventTraceID( \
id, &traceEventFlags); \
blink::TraceEvent::addTraceEvent( \
phase, INTERNALTRACEEVENTUID(categoryGroupEnabled), name, \
traceEventTraceID.scope(), traceEventTraceID.data(), \
traceEventFlags, ##__VA_ARGS__); \
} \
} while (0)
// Implementation detail: internal macro to create static category and add event
// if the category is enabled.
#define INTERNAL_TRACE_EVENT_ADD_WITH_ID_AND_TIMESTAMP(phase, category, name, id, timestamp, flags, ...) \
do { \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
if (INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE()) { \
unsigned traceEventFlags = flags | TRACE_EVENT_FLAG_HAS_ID; \
blink::TraceEvent::TraceID traceEventTraceID( \
id, &traceEventFlags); \
blink::TraceEvent::addTraceEvent( \
phase, INTERNALTRACEEVENTUID(categoryGroupEnabled), name, \
traceEventTraceID.scope(), traceEventTraceID.data(), \
blink::TraceEvent::noBindId, \
timestamp, traceEventFlags, ##__VA_ARGS__); \
} \
} while (0)
// Implementation detail: internal macro to create static category and add
// event if the category is enabled.
#define INTERNAL_TRACE_EVENT_ADD_WITH_TIMESTAMP(phase, category, name, timestamp, flags, ...) \
do { \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
if (INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE()) { \
blink::TraceEvent::addTraceEvent( \
phase, INTERNALTRACEEVENTUID(categoryGroupEnabled), name, \
blink::TraceEvent::kGlobalScope, blink::TraceEvent::noEventId, \
blink::TraceEvent::noBindId, \
timestamp, flags, ##__VA_ARGS__); \
} \
} while (0)
// Implementation detail: internal macro to enter and leave a context based on
// the current scope.
#define INTERNAL_TRACE_EVENT_SCOPED_CONTEXT(categoryGroup, name, context) \
struct INTERNAL_TRACE_EVENT_UID(ScopedContext) { \
public: \
INTERNAL_TRACE_EVENT_UID(ScopedContext)(uint64_t cid) : m_cid(cid) { \
TRACE_EVENT_ENTER_CONTEXT(category_group, name, m_cid); \
} \
~INTERNAL_TRACE_EVENT_UID(ScopedContext)() { \
TRACE_EVENT_LEAVE_CONTEXT(category_group, name, m_cid); \
} \
private: \
uint64_t m_cid; \
INTERNAL_TRACE_EVENT_UID(ScopedContext) \
(const INTERNAL_TRACE_EVENT_UID(ScopedContext)&) {}; \
void operator=(const INTERNAL_TRACE_EVENT_UID(ScopedContext)&) {}; \
}; \
INTERNAL_TRACE_EVENT_UID(ScopedContext) \
INTERNAL_TRACE_EVENT_UID(scoped_context)(context.data());
// These values must be in sync with base::debug::TraceLog::CategoryGroupEnabledFlags.
#define ENABLED_FOR_RECORDING (1 << 0)
#define ENABLED_FOR_EVENT_CALLBACK (1 << 2)
#define INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE() \
(*INTERNALTRACEEVENTUID(categoryGroupEnabled) & (ENABLED_FOR_RECORDING | ENABLED_FOR_EVENT_CALLBACK))
#define INTERNAL_TRACE_MEMORY(category, name)
namespace blink {
namespace TraceEvent {
// Specify these values when the corresponding argument of addTraceEvent is not
// used.
const int zeroNumArgs = 0;
const std::nullptr_t kGlobalScope = nullptr;
const unsigned long long noEventId = 0;
const unsigned long long noBindId = 0;
// TraceID encapsulates an ID that can either be an integer or pointer;
// optionally, it can be paired with a scope string, too. Pointers are mangled
// with the Process ID so that they are unlikely to collide when the same
// pointer is used on different processes.
class TraceID final {
STACK_ALLOCATED();
WTF_MAKE_NONCOPYABLE(TraceID);
public:
class WithScope final {
STACK_ALLOCATED();
public:
template<typename T> WithScope(const char* scope, T id)
: m_scope(scope), m_data(reinterpret_cast<unsigned long long>(id)) { }
const char* scope() const { return m_scope; }
unsigned long long data() const { return m_data; }
private:
const char* m_scope = kGlobalScope;
unsigned long long m_data;
};
template<bool dummyMangle> class MangleBehavior final {
STACK_ALLOCATED();
public:
template<typename T> explicit MangleBehavior(T id) : m_data(reinterpret_cast<unsigned long long>(id)) { }
explicit MangleBehavior(WithScope scopedID) : m_scope(scopedID.scope()), m_data(scopedID.data()) { }
const char* scope() const { return m_scope; }
unsigned long long data() const { return m_data; }
private:
const char* m_scope = kGlobalScope;
unsigned long long m_data;
};
typedef MangleBehavior<false> DontMangle;
typedef MangleBehavior<true> ForceMangle;
TraceID(const void* id, unsigned* flags)
: m_data(static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(id)))
{
*flags |= TRACE_EVENT_FLAG_MANGLE_ID;
}
TraceID(ForceMangle id, unsigned* flags)
: m_scope(id.scope()), m_data(id.data())
{
*flags |= TRACE_EVENT_FLAG_MANGLE_ID;
}
TraceID(DontMangle id, unsigned*) : m_scope(id.scope()), m_data(id.data()) { }
TraceID(unsigned long long id, unsigned*) : m_data(id) { }
TraceID(unsigned long id, unsigned*) : m_data(id) { }
TraceID(unsigned id, unsigned*) : m_data(id) { }
TraceID(unsigned short id, unsigned*) : m_data(id) { }
TraceID(unsigned char id, unsigned*) : m_data(id) { }
TraceID(long long id, unsigned*) :
m_data(static_cast<unsigned long long>(id)) { }
TraceID(long id, unsigned*) :
m_data(static_cast<unsigned long long>(id)) { }
TraceID(int id, unsigned*) :
m_data(static_cast<unsigned long long>(id)) { }
TraceID(short id, unsigned*) :
m_data(static_cast<unsigned long long>(id)) { }
TraceID(signed char id, unsigned*) :
m_data(static_cast<unsigned long long>(id)) { }
TraceID(WithScope scopedID, unsigned*) :
m_scope(scopedID.scope()), m_data(scopedID.data()) { }
const char* scope() const { return m_scope; }
unsigned long long data() const { return m_data; }
private:
const char* m_scope = kGlobalScope;
unsigned long long m_data;
};
// Simple union to store various types as unsigned long long.
union TraceValueUnion {
bool m_bool;
unsigned long long m_uint;
long long m_int;
double m_double;
const void* m_pointer;
const char* m_string;
};
// Simple container for const char* that should be copied instead of retained.
class TraceStringWithCopy {
STACK_ALLOCATED();
public:
explicit TraceStringWithCopy(const char* str) : m_str(str) { }
const char* str() const { return m_str; }
private:
const char* m_str;
};
// Define setTraceValue for each allowed type. It stores the type and
// value in the return arguments. This allows this API to avoid declaring any
// structures so that it is portable to third_party libraries.
#define INTERNAL_DECLARE_SET_TRACE_VALUE(actualType, argExpression, unionMember, valueTypeId) \
static inline void setTraceValue(actualType arg, unsigned char* type, unsigned long long* value) { \
TraceValueUnion typeValue; \
typeValue.unionMember = argExpression; \
*type = valueTypeId; \
*value = typeValue.m_uint; \
}
// Simpler form for int types that can be safely casted.
#define INTERNAL_DECLARE_SET_TRACE_VALUE_INT(actualType, valueTypeId) \
static inline void setTraceValue(actualType arg, \
unsigned char* type, \
unsigned long long* value) { \
*type = valueTypeId; \
*value = static_cast<unsigned long long>(arg); \
}
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned long long, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned short, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned char, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(long long, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(int, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(short, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(signed char, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE(bool, arg, m_bool, TRACE_VALUE_TYPE_BOOL)
INTERNAL_DECLARE_SET_TRACE_VALUE(double, arg, m_double, TRACE_VALUE_TYPE_DOUBLE)
INTERNAL_DECLARE_SET_TRACE_VALUE(const void*, arg, m_pointer, TRACE_VALUE_TYPE_POINTER)
INTERNAL_DECLARE_SET_TRACE_VALUE(const char*, arg, m_string, TRACE_VALUE_TYPE_STRING)
INTERNAL_DECLARE_SET_TRACE_VALUE(const TraceStringWithCopy&, arg.str(), m_string, TRACE_VALUE_TYPE_COPY_STRING)
#undef INTERNAL_DECLARE_SET_TRACE_VALUE
#undef INTERNAL_DECLARE_SET_TRACE_VALUE_INT
// WTF::String version of setTraceValue so that trace arguments can be strings.
static inline void setTraceValue(const WTF::CString& arg, unsigned char* type, unsigned long long* value)
{
TraceValueUnion typeValue;
typeValue.m_string = arg.data();
*type = TRACE_VALUE_TYPE_COPY_STRING;
*value = typeValue.m_uint;
}
static inline void setTraceValue(TracedValue*, unsigned char* type, unsigned long long*)
{
*type = TRACE_VALUE_TYPE_CONVERTABLE;
}
template<typename T> static inline void setTraceValue(const PassOwnPtr<T>& ptr, unsigned char* type, unsigned long long* value)
{
setTraceValue(ptr.get(), type, value);
}
template<typename T> struct TracedValueTraits {
static const bool isTracedValue = false;
static PassOwnPtr<TracedValue> moveFromIfTracedValue(const T&)
{
return nullptr;
}
};
template<typename T> struct TracedValueTraits<PassOwnPtr<T>> {
static const bool isTracedValue = std::is_convertible<T*, TracedValue*>::value;
static PassOwnPtr<TracedValue> moveFromIfTracedValue(const PassOwnPtr<T>& tracedValue)
{
return tracedValue;
}
};
template<typename T> bool isTracedValue(const T&)
{
return TracedValueTraits<T>::isTracedValue;
}
template<typename T> PassOwnPtr<TracedValue> moveFromIfTracedValue(const T& value)
{
return TracedValueTraits<T>::moveFromIfTracedValue(value);
}
// These addTraceEvent template functions are defined here instead of in the
// macro, because the arg values could be temporary string objects. In order to
// store pointers to the internal c_str and pass through to the tracing API, the
// arg values must live throughout these procedures.
static inline TraceEventHandle addTraceEvent(
char phase,
const unsigned char* categoryEnabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned long long bindId,
double timestamp,
unsigned flags)
{
return TRACE_EVENT_API_ADD_TRACE_EVENT(
phase, categoryEnabled, name, scope, id, bindId, timestamp,
zeroNumArgs, 0, 0, 0,
flags);
}
template <typename ARG1_TYPE>
static inline TraceEventHandle addTraceEvent(
char phase,
const unsigned char* categoryEnabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned long long bindId,
double timestamp,
unsigned flags,
const char* arg1Name,
const ARG1_TYPE& arg1Val)
{
const int numArgs = 1;
unsigned char argTypes[1];
unsigned long long argValues[1];
setTraceValue(arg1Val, &argTypes[0], &argValues[0]);
if (isTracedValue(arg1Val)) {
return TRACE_EVENT_API_ADD_TRACE_EVENT(
phase, categoryEnabled, name, scope, id, bindId, timestamp,
numArgs, &arg1Name, argTypes, argValues,
moveFromIfTracedValue(arg1Val),
nullptr,
flags);
}
return TRACE_EVENT_API_ADD_TRACE_EVENT(
phase, categoryEnabled, name, scope, id, bindId, timestamp,
numArgs, &arg1Name, argTypes, argValues,
flags);
}
template<typename ARG1_TYPE, typename ARG2_TYPE>
static inline TraceEventHandle addTraceEvent(
char phase,
const unsigned char* categoryEnabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned long long bindId,
double timestamp,
unsigned flags,
const char* arg1Name,
const ARG1_TYPE& arg1Val,
const char* arg2Name,
const ARG2_TYPE& arg2Val)
{
const int numArgs = 2;
const char* argNames[2] = { arg1Name, arg2Name };
unsigned char argTypes[2];
unsigned long long argValues[2];
setTraceValue(arg1Val, &argTypes[0], &argValues[0]);
setTraceValue(arg2Val, &argTypes[1], &argValues[1]);
if (isTracedValue(arg1Val) || isTracedValue(arg2Val)) {
return TRACE_EVENT_API_ADD_TRACE_EVENT(
phase, categoryEnabled, name, scope, id, bindId, timestamp,
numArgs, argNames, argTypes, argValues,
moveFromIfTracedValue(arg1Val),
moveFromIfTracedValue(arg2Val),
flags);
}
return TRACE_EVENT_API_ADD_TRACE_EVENT(
phase, categoryEnabled, name, scope, id, bindId, timestamp,
numArgs, argNames, argTypes, argValues,
flags);
}
static inline TraceEventHandle addTraceEvent(
char phase,
const unsigned char* categoryEnabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned flags)
{
return addTraceEvent(phase, categoryEnabled, name, scope, id,
blink::TraceEvent::noBindId, EventTracer::systemTraceTime(), flags);
}
template<typename ARG1_TYPE>
static inline TraceEventHandle addTraceEvent(
char phase,
const unsigned char* categoryEnabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned flags,
const char* arg1Name,
const ARG1_TYPE& arg1Val)
{
return addTraceEvent(phase, categoryEnabled, name, scope, id,
blink::TraceEvent::noBindId, EventTracer::systemTraceTime(), flags,
arg1Name, arg1Val);
}
template<typename ARG1_TYPE, typename ARG2_TYPE>
static inline TraceEventHandle addTraceEvent(
char phase,
const unsigned char* categoryEnabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned flags,
const char* arg1Name,
const ARG1_TYPE& arg1Val,
const char* arg2Name,
const ARG2_TYPE& arg2Val)
{
return addTraceEvent(phase, categoryEnabled, name, scope, id,
blink::TraceEvent::noBindId, EventTracer::systemTraceTime(), flags,
arg1Name, arg1Val, arg2Name, arg2Val);
}
// Used by TRACE_EVENTx macro. Do not use directly.
class ScopedTracer final {
STACK_ALLOCATED();
WTF_MAKE_NONCOPYABLE(ScopedTracer);
public:
// Note: members of m_data intentionally left uninitialized. See initialize.
ScopedTracer() : m_pdata(0) { }
~ScopedTracer()
{
if (m_pdata && *m_pdata->categoryGroupEnabled)
TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(m_data.categoryGroupEnabled, m_data.name, m_data.eventHandle);
}
void initialize(const unsigned char* categoryGroupEnabled, const char* name, TraceEventHandle eventHandle)
{
m_data.categoryGroupEnabled = categoryGroupEnabled;
m_data.name = name;
m_data.eventHandle = eventHandle;
m_pdata = &m_data;
}
private:
// This Data struct workaround is to avoid initializing all the members
// in Data during construction of this object, since this object is always
// constructed, even when tracing is disabled. If the members of Data were
// members of this class instead, compiler warnings occur about potential
// uninitialized accesses.
struct Data {
DISALLOW_NEW();
const unsigned char* categoryGroupEnabled;
const char* name;
TraceEventHandle eventHandle;
};
Data* m_pdata;
Data m_data;
};
// TraceEventSamplingStateScope records the current sampling state
// and sets a new sampling state. When the scope exists, it restores
// the sampling state having recorded.
template<size_t BucketNumber>
class SamplingStateScope final {
STACK_ALLOCATED();
WTF_MAKE_NONCOPYABLE(SamplingStateScope);
public:
SamplingStateScope(const char* categoryAndName)
{
m_previousState = SamplingStateScope<BucketNumber>::current();
SamplingStateScope<BucketNumber>::set(categoryAndName);
}
~SamplingStateScope()
{
SamplingStateScope<BucketNumber>::set(m_previousState);
}
// FIXME: Make load/store to traceSamplingState[] thread-safe and atomic.
static const char* current()
{
return reinterpret_cast<const char*>(*blink::traceSamplingState[BucketNumber]);
}
static void set(const char* categoryAndName)
{
*blink::traceSamplingState[BucketNumber] = reinterpret_cast<TraceEventAPIAtomicWord>(categoryAndName);
}
private:
const char* m_previousState;
};
template<typename IDType> class TraceScopedTrackableObject {
STACK_ALLOCATED();
WTF_MAKE_NONCOPYABLE(TraceScopedTrackableObject);
public:
TraceScopedTrackableObject(const char* categoryGroup, const char* name, IDType id)
: m_categoryGroup(categoryGroup), m_name(name), m_id(id)
{
TRACE_EVENT_OBJECT_CREATED_WITH_ID(m_categoryGroup, m_name, m_id);
}
~TraceScopedTrackableObject()
{
TRACE_EVENT_OBJECT_DELETED_WITH_ID(m_categoryGroup, m_name, m_id);
}
private:
const char* m_categoryGroup;
const char* m_name;
IDType m_id;
};
} // namespace TraceEvent
} // namespace blink
#endif
| bsd-3-clause |
peskovsb/shopgit | widgets/views/categories.php | 404 | <?php
use yii\widgets\Menu;
/* @var $this yii\web\View */
/* @var $items array */
?>
<div class="panel panel-default">
<div class="panel-heading">Категории</div>
<?= Menu::widget([
'options' => ['class' => 'nav nav-pills nav-stacked'],
'items' => $items,
'submenuTemplate' => "\n<ul class='nav nav-pills nav-stacked'>\n{items}\n</ul>\n"
]); ?>
</div>
| bsd-3-clause |
bcroq/kansha | kansha/services/dummyassetsmanager/dummyassetsmanager.py | 1033 | # -*- coding:utf-8 -*-
#--
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
from nagare import log
import pkg_resources
from ..assetsmanager import AssetsManager
class DummyAssetsManager(AssetsManager):
def __init__(self):
super(DummyAssetsManager, self).__init__('', None)
def save(self, data, file_id=None, metadata={}):
log.debug("Save Image")
log.debug("%s" % metadata)
return 'mock_id'
def load(self, file_id):
log.debug("Load Image")
package = pkg_resources.Requirement.parse('kansha')
fname = pkg_resources.resource_filename(package, 'kansha/services/dummyassetsmanager/tie.jpg')
with open(fname, 'r') as f:
data = f.read()
return data, {}
def update_metadata(self, file_id, metadata):
pass
def get_metadata(self, file_id):
pass
| bsd-3-clause |
mvaled/sentry | src/sentry/api/endpoints/api_application_details.py | 4091 | from __future__ import absolute_import
import logging
from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from uuid import uuid4
from sentry.api.base import Endpoint, SessionAuthentication
from sentry.api.exceptions import ResourceDoesNotExist
from sentry.api.serializers import serialize
from sentry.api.serializers.rest_framework import ListField
from sentry.models import ApiApplication, ApiApplicationStatus
from sentry.tasks.deletion import delete_api_application
delete_logger = logging.getLogger("sentry.deletions.api")
class ApiApplicationSerializer(serializers.Serializer):
name = serializers.CharField(max_length=64)
redirectUris = ListField(child=serializers.URLField(max_length=255), required=False)
allowedOrigins = ListField(
# TODO(dcramer): make this validate origins
child=serializers.CharField(max_length=255),
required=False,
)
homepageUrl = serializers.URLField(
max_length=255, required=False, allow_null=True, allow_blank=True
)
termsUrl = serializers.URLField(
max_length=255, required=False, allow_null=True, allow_blank=True
)
privacyUrl = serializers.URLField(
max_length=255, required=False, allow_null=True, allow_blank=True
)
class ApiApplicationDetailsEndpoint(Endpoint):
authentication_classes = (SessionAuthentication,)
permission_classes = (IsAuthenticated,)
def get(self, request, app_id):
try:
instance = ApiApplication.objects.get(
owner=request.user, client_id=app_id, status=ApiApplicationStatus.active
)
except ApiApplication.DoesNotExist:
raise ResourceDoesNotExist
return Response(serialize(instance, request.user))
def put(self, request, app_id):
try:
instance = ApiApplication.objects.get(
owner=request.user, client_id=app_id, status=ApiApplicationStatus.active
)
except ApiApplication.DoesNotExist:
raise ResourceDoesNotExist
serializer = ApiApplicationSerializer(data=request.data, partial=True)
if serializer.is_valid():
result = serializer.validated_data
kwargs = {}
if "name" in result:
kwargs["name"] = result["name"]
if "allowedOrigins" in result:
kwargs["allowed_origins"] = "\n".join(result["allowedOrigins"])
if "redirectUris" in result:
kwargs["redirect_uris"] = "\n".join(result["redirectUris"])
if "homepageUrl" in result:
kwargs["homepage_url"] = result["homepageUrl"]
if "privacyUrl" in result:
kwargs["privacy_url"] = result["privacyUrl"]
if "termsUrl" in result:
kwargs["terms_url"] = result["termsUrl"]
if kwargs:
instance.update(**kwargs)
return Response(serialize(instance, request.user), status=200)
return Response(serializer.errors, status=400)
def delete(self, request, app_id):
try:
instance = ApiApplication.objects.get(
owner=request.user, client_id=app_id, status=ApiApplicationStatus.active
)
except ApiApplication.DoesNotExist:
raise ResourceDoesNotExist
updated = ApiApplication.objects.filter(id=instance.id).update(
status=ApiApplicationStatus.pending_deletion
)
if updated:
transaction_id = uuid4().hex
delete_api_application.apply_async(
kwargs={"object_id": instance.id, "transaction_id": transaction_id}, countdown=3600
)
delete_logger.info(
"object.delete.queued",
extra={
"object_id": instance.id,
"transaction_id": transaction_id,
"model": type(instance).__name__,
},
)
return Response(status=204)
| bsd-3-clause |
aeklant/scipy | scipy/signal/tests/test_ltisys.py | 46195 | import warnings
import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose,
assert_, suppress_warnings)
from pytest import raises as assert_raises
from scipy.signal import (ss2tf, tf2ss, lsim2, impulse2, step2, lti,
dlti, bode, freqresp, lsim, impulse, step,
abcd_normalize, place_poles,
TransferFunction, StateSpace, ZerosPolesGain)
from scipy.signal.filter_design import BadCoefficients
import scipy.linalg as linalg
from scipy.sparse.sputils import matrix
def _assert_poles_close(P1,P2, rtol=1e-8, atol=1e-8):
"""
Check each pole in P1 is close to a pole in P2 with a 1e-8
relative tolerance or 1e-8 absolute tolerance (useful for zero poles).
These tolerances are very strict but the systems tested are known to
accept these poles so we should not be far from what is requested.
"""
P2 = P2.copy()
for p1 in P1:
found = False
for p2_idx in range(P2.shape[0]):
if np.allclose([np.real(p1), np.imag(p1)],
[np.real(P2[p2_idx]), np.imag(P2[p2_idx])],
rtol, atol):
found = True
np.delete(P2, p2_idx)
break
if not found:
raise ValueError("Can't find pole " + str(p1) + " in " + str(P2))
class TestPlacePoles(object):
def _check(self, A, B, P, **kwargs):
"""
Perform the most common tests on the poles computed by place_poles
and return the Bunch object for further specific tests
"""
fsf = place_poles(A, B, P, **kwargs)
expected, _ = np.linalg.eig(A - np.dot(B, fsf.gain_matrix))
_assert_poles_close(expected,fsf.requested_poles)
_assert_poles_close(expected,fsf.computed_poles)
_assert_poles_close(P,fsf.requested_poles)
return fsf
def test_real(self):
# Test real pole placement using KNV and YT0 algorithm and example 1 in
# section 4 of the reference publication (see place_poles docstring)
A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0,
0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273,
1.343, -2.104]).reshape(4, 4)
B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146,0]).reshape(4, 2)
P = np.array([-0.2, -0.5, -5.0566, -8.6659])
# Check that both KNV and YT compute correct K matrix
self._check(A, B, P, method='KNV0')
self._check(A, B, P, method='YT')
# Try to reach the specific case in _YT_real where two singular
# values are almost equal. This is to improve code coverage but I
# have no way to be sure this code is really reached
# on some architectures this can lead to a RuntimeWarning invalid
# value in divide (see gh-7590), so suppress it for now
with np.errstate(invalid='ignore'):
self._check(A, B, (2,2,3,3))
def test_complex(self):
# Test complex pole placement on a linearized car model, taken from L.
# Jaulin, Automatique pour la robotique, Cours et Exercices, iSTE
# editions p 184/185
A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0]).reshape(4,4)
B = np.array([0,0,0,0,1,0,0,1]).reshape(4,2)
# Test complex poles on YT
P = np.array([-3, -1, -2-1j, -2+1j])
self._check(A, B, P)
# Try to reach the specific case in _YT_complex where two singular
# values are almost equal. This is to improve code coverage but I
# have no way to be sure this code is really reached
P = [0-1e-6j,0+1e-6j,-10,10]
self._check(A, B, P, maxiter=1000)
# Try to reach the specific case in _YT_complex where the rank two
# update yields two null vectors. This test was found via Monte Carlo.
A = np.array(
[-2148,-2902, -2267, -598, -1722, -1829, -165, -283, -2546,
-167, -754, -2285, -543, -1700, -584, -2978, -925, -1300,
-1583, -984, -386, -2650, -764, -897, -517, -1598, 2, -1709,
-291, -338, -153, -1804, -1106, -1168, -867, -2297]
).reshape(6,6)
B = np.array(
[-108, -374, -524, -1285, -1232, -161, -1204, -672, -637,
-15, -483, -23, -931, -780, -1245, -1129, -1290, -1502,
-952, -1374, -62, -964, -930, -939, -792, -756, -1437,
-491, -1543, -686]
).reshape(6,5)
P = [-25.-29.j, -25.+29.j, 31.-42.j, 31.+42.j, 33.-41.j, 33.+41.j]
self._check(A, B, P)
# Use a lot of poles to go through all cases for update_order
# in _YT_loop
big_A = np.ones((11,11))-np.eye(11)
big_B = np.ones((11,10))-np.diag([1]*10,1)[:,1:]
big_A[:6,:6] = A
big_B[:6,:5] = B
P = [-10,-20,-30,40,50,60,70,-20-5j,-20+5j,5+3j,5-3j]
self._check(big_A, big_B, P)
#check with only complex poles and only real poles
P = [-10,-20,-30,-40,-50,-60,-70,-80,-90,-100]
self._check(big_A[:-1,:-1], big_B[:-1,:-1], P)
P = [-10+10j,-20+20j,-30+30j,-40+40j,-50+50j,
-10-10j,-20-20j,-30-30j,-40-40j,-50-50j]
self._check(big_A[:-1,:-1], big_B[:-1,:-1], P)
# need a 5x5 array to ensure YT handles properly when there
# is only one real pole and several complex
A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0,
0,0,0,5,0,0,0,0,9]).reshape(5,5)
B = np.array([0,0,0,0,1,0,0,1,2,3]).reshape(5,2)
P = np.array([-2, -3+1j, -3-1j, -1+1j, -1-1j])
place_poles(A, B, P)
# same test with an odd number of real poles > 1
# this is another specific case of YT
P = np.array([-2, -3, -4, -1+1j, -1-1j])
self._check(A, B, P)
def test_tricky_B(self):
# check we handle as we should the 1 column B matrices and
# n column B matrices (with n such as shape(A)=(n, n))
A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0,
0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273,
1.343, -2.104]).reshape(4, 4)
B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146, 0, 1, 2, 3, 4,
5, 6, 7, 8]).reshape(4, 4)
# KNV or YT are not called here, it's a specific case with only
# one unique solution
P = np.array([-0.2, -0.5, -5.0566, -8.6659])
fsf = self._check(A, B, P)
# rtol and nb_iter should be set to np.nan as the identity can be
# used as transfer matrix
assert_equal(fsf.rtol, np.nan)
assert_equal(fsf.nb_iter, np.nan)
# check with complex poles too as they trigger a specific case in
# the specific case :-)
P = np.array((-2+1j,-2-1j,-3,-2))
fsf = self._check(A, B, P)
assert_equal(fsf.rtol, np.nan)
assert_equal(fsf.nb_iter, np.nan)
#now test with a B matrix with only one column (no optimisation)
B = B[:,0].reshape(4,1)
P = np.array((-2+1j,-2-1j,-3,-2))
fsf = self._check(A, B, P)
# we can't optimize anything, check they are set to 0 as expected
assert_equal(fsf.rtol, 0)
assert_equal(fsf.nb_iter, 0)
def test_errors(self):
# Test input mistakes from user
A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0]).reshape(4,4)
B = np.array([0,0,0,0,1,0,0,1]).reshape(4,2)
#should fail as the method keyword is invalid
assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
method="foo")
#should fail as poles are not 1D array
assert_raises(ValueError, place_poles, A, B,
np.array((-2.1,-2.2,-2.3,-2.4)).reshape(4,1))
#should fail as A is not a 2D array
assert_raises(ValueError, place_poles, A[:,:,np.newaxis], B,
(-2.1,-2.2,-2.3,-2.4))
#should fail as B is not a 2D array
assert_raises(ValueError, place_poles, A, B[:,:,np.newaxis],
(-2.1,-2.2,-2.3,-2.4))
#should fail as there are too many poles
assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4,-3))
#should fail as there are not enough poles
assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3))
#should fail as the rtol is greater than 1
assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
rtol=42)
#should fail as maxiter is smaller than 1
assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
maxiter=-42)
# should fail as ndim(B) is two
assert_raises(ValueError, place_poles, A, B, (-2,-2,-2,-2))
#unctrollable system
assert_raises(ValueError, place_poles, np.ones((4,4)),
np.ones((4,2)), (1,2,3,4))
# Should not raise ValueError as the poles can be placed but should
# raise a warning as the convergence is not reached
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
fsf = place_poles(A, B, (-1,-2,-3,-4), rtol=1e-16, maxiter=42)
assert_(len(w) == 1)
assert_(issubclass(w[-1].category, UserWarning))
assert_("Convergence was not reached after maxiter iterations"
in str(w[-1].message))
assert_equal(fsf.nb_iter, 42)
# should fail as a complex misses its conjugate
assert_raises(ValueError, place_poles, A, B, (-2+1j,-2-1j,-2+3j,-2))
# should fail as A is not square
assert_raises(ValueError, place_poles, A[:,:3], B, (-2,-3,-4,-5))
# should fail as B has not the same number of lines as A
assert_raises(ValueError, place_poles, A, B[:3,:], (-2,-3,-4,-5))
# should fail as KNV0 does not support complex poles
assert_raises(ValueError, place_poles, A, B,
(-2+1j,-2-1j,-2+3j,-2-3j), method="KNV0")
class TestSS2TF:
def check_matrix_shapes(self, p, q, r):
ss2tf(np.zeros((p, p)),
np.zeros((p, q)),
np.zeros((r, p)),
np.zeros((r, q)), 0)
def test_shapes(self):
# Each tuple holds:
# number of states, number of inputs, number of outputs
for p, q, r in [(3, 3, 3), (1, 3, 3), (1, 1, 1)]:
self.check_matrix_shapes(p, q, r)
def test_basic(self):
# Test a round trip through tf2ss and ss2tf.
b = np.array([1.0, 3.0, 5.0])
a = np.array([1.0, 2.0, 3.0])
A, B, C, D = tf2ss(b, a)
assert_allclose(A, [[-2, -3], [1, 0]], rtol=1e-13)
assert_allclose(B, [[1], [0]], rtol=1e-13)
assert_allclose(C, [[1, 2]], rtol=1e-13)
assert_allclose(D, [[1]], rtol=1e-14)
bb, aa = ss2tf(A, B, C, D)
assert_allclose(bb[0], b, rtol=1e-13)
assert_allclose(aa, a, rtol=1e-13)
def test_zero_order_round_trip(self):
# See gh-5760
tf = (2, 1)
A, B, C, D = tf2ss(*tf)
assert_allclose(A, [[0]], rtol=1e-13)
assert_allclose(B, [[0]], rtol=1e-13)
assert_allclose(C, [[0]], rtol=1e-13)
assert_allclose(D, [[2]], rtol=1e-13)
num, den = ss2tf(A, B, C, D)
assert_allclose(num, [[2, 0]], rtol=1e-13)
assert_allclose(den, [1, 0], rtol=1e-13)
tf = ([[5], [2]], 1)
A, B, C, D = tf2ss(*tf)
assert_allclose(A, [[0]], rtol=1e-13)
assert_allclose(B, [[0]], rtol=1e-13)
assert_allclose(C, [[0], [0]], rtol=1e-13)
assert_allclose(D, [[5], [2]], rtol=1e-13)
num, den = ss2tf(A, B, C, D)
assert_allclose(num, [[5, 0], [2, 0]], rtol=1e-13)
assert_allclose(den, [1, 0], rtol=1e-13)
def test_simo_round_trip(self):
# See gh-5753
tf = ([[1, 2], [1, 1]], [1, 2])
A, B, C, D = tf2ss(*tf)
assert_allclose(A, [[-2]], rtol=1e-13)
assert_allclose(B, [[1]], rtol=1e-13)
assert_allclose(C, [[0], [-1]], rtol=1e-13)
assert_allclose(D, [[1], [1]], rtol=1e-13)
num, den = ss2tf(A, B, C, D)
assert_allclose(num, [[1, 2], [1, 1]], rtol=1e-13)
assert_allclose(den, [1, 2], rtol=1e-13)
tf = ([[1, 0, 1], [1, 1, 1]], [1, 1, 1])
A, B, C, D = tf2ss(*tf)
assert_allclose(A, [[-1, -1], [1, 0]], rtol=1e-13)
assert_allclose(B, [[1], [0]], rtol=1e-13)
assert_allclose(C, [[-1, 0], [0, 0]], rtol=1e-13)
assert_allclose(D, [[1], [1]], rtol=1e-13)
num, den = ss2tf(A, B, C, D)
assert_allclose(num, [[1, 0, 1], [1, 1, 1]], rtol=1e-13)
assert_allclose(den, [1, 1, 1], rtol=1e-13)
tf = ([[1, 2, 3], [1, 2, 3]], [1, 2, 3, 4])
A, B, C, D = tf2ss(*tf)
assert_allclose(A, [[-2, -3, -4], [1, 0, 0], [0, 1, 0]], rtol=1e-13)
assert_allclose(B, [[1], [0], [0]], rtol=1e-13)
assert_allclose(C, [[1, 2, 3], [1, 2, 3]], rtol=1e-13)
assert_allclose(D, [[0], [0]], rtol=1e-13)
num, den = ss2tf(A, B, C, D)
assert_allclose(num, [[0, 1, 2, 3], [0, 1, 2, 3]], rtol=1e-13)
assert_allclose(den, [1, 2, 3, 4], rtol=1e-13)
tf = (np.array([1, [2, 3]], dtype=object), [1, 6])
A, B, C, D = tf2ss(*tf)
assert_allclose(A, [[-6]], rtol=1e-31)
assert_allclose(B, [[1]], rtol=1e-31)
assert_allclose(C, [[1], [-9]], rtol=1e-31)
assert_allclose(D, [[0], [2]], rtol=1e-31)
num, den = ss2tf(A, B, C, D)
assert_allclose(num, [[0, 1], [2, 3]], rtol=1e-13)
assert_allclose(den, [1, 6], rtol=1e-13)
tf = (np.array([[1, -3], [1, 2, 3]], dtype=object), [1, 6, 5])
A, B, C, D = tf2ss(*tf)
assert_allclose(A, [[-6, -5], [1, 0]], rtol=1e-13)
assert_allclose(B, [[1], [0]], rtol=1e-13)
assert_allclose(C, [[1, -3], [-4, -2]], rtol=1e-13)
assert_allclose(D, [[0], [1]], rtol=1e-13)
num, den = ss2tf(A, B, C, D)
assert_allclose(num, [[0, 1, -3], [1, 2, 3]], rtol=1e-13)
assert_allclose(den, [1, 6, 5], rtol=1e-13)
def test_multioutput(self):
# Regression test for gh-2669.
# 4 states
A = np.array([[-1.0, 0.0, 1.0, 0.0],
[-1.0, 0.0, 2.0, 0.0],
[-4.0, 0.0, 3.0, 0.0],
[-8.0, 8.0, 0.0, 4.0]])
# 1 input
B = np.array([[0.3],
[0.0],
[7.0],
[0.0]])
# 3 outputs
C = np.array([[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
[8.0, 8.0, 0.0, 0.0]])
D = np.array([[0.0],
[0.0],
[1.0]])
# Get the transfer functions for all the outputs in one call.
b_all, a = ss2tf(A, B, C, D)
# Get the transfer functions for each output separately.
b0, a0 = ss2tf(A, B, C[0], D[0])
b1, a1 = ss2tf(A, B, C[1], D[1])
b2, a2 = ss2tf(A, B, C[2], D[2])
# Check that we got the same results.
assert_allclose(a0, a, rtol=1e-13)
assert_allclose(a1, a, rtol=1e-13)
assert_allclose(a2, a, rtol=1e-13)
assert_allclose(b_all, np.vstack((b0, b1, b2)), rtol=1e-13, atol=1e-14)
class TestLsim(object):
def lti_nowarn(self, *args):
with suppress_warnings() as sup:
sup.filter(BadCoefficients)
system = lti(*args)
return system
def test_first_order(self):
# y' = -y
# exact solution is y(t) = exp(-t)
system = self.lti_nowarn(-1.,1.,1.,0.)
t = np.linspace(0,5)
u = np.zeros_like(t)
tout, y, x = lsim(system, u, t, X0=[1.0])
expected_x = np.exp(-tout)
assert_almost_equal(x, expected_x)
assert_almost_equal(y, expected_x)
def test_integrator(self):
# integrator: y' = u
system = self.lti_nowarn(0., 1., 1., 0.)
t = np.linspace(0,5)
u = t
tout, y, x = lsim(system, u, t)
expected_x = 0.5 * tout**2
assert_almost_equal(x, expected_x)
assert_almost_equal(y, expected_x)
def test_double_integrator(self):
# double integrator: y'' = 2u
A = matrix("0. 1.; 0. 0.")
B = matrix("0.; 1.")
C = matrix("2. 0.")
system = self.lti_nowarn(A, B, C, 0.)
t = np.linspace(0,5)
u = np.ones_like(t)
tout, y, x = lsim(system, u, t)
expected_x = np.transpose(np.array([0.5 * tout**2, tout]))
expected_y = tout**2
assert_almost_equal(x, expected_x)
assert_almost_equal(y, expected_y)
def test_jordan_block(self):
# Non-diagonalizable A matrix
# x1' + x1 = x2
# x2' + x2 = u
# y = x1
# Exact solution with u = 0 is y(t) = t exp(-t)
A = matrix("-1. 1.; 0. -1.")
B = matrix("0.; 1.")
C = matrix("1. 0.")
system = self.lti_nowarn(A, B, C, 0.)
t = np.linspace(0,5)
u = np.zeros_like(t)
tout, y, x = lsim(system, u, t, X0=[0.0, 1.0])
expected_y = tout * np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_miso(self):
# A system with two state variables, two inputs, and one output.
A = np.array([[-1.0, 0.0], [0.0, -2.0]])
B = np.array([[1.0, 0.0], [0.0, 1.0]])
C = np.array([1.0, 0.0])
D = np.zeros((1,2))
system = self.lti_nowarn(A, B, C, D)
t = np.linspace(0, 5.0, 101)
u = np.zeros_like(t)
tout, y, x = lsim(system, u, t, X0=[1.0, 1.0])
expected_y = np.exp(-tout)
expected_x0 = np.exp(-tout)
expected_x1 = np.exp(-2.0*tout)
assert_almost_equal(y, expected_y)
assert_almost_equal(x[:,0], expected_x0)
assert_almost_equal(x[:,1], expected_x1)
def test_nonzero_initial_time(self):
system = self.lti_nowarn(-1.,1.,1.,0.)
t = np.linspace(1,2)
u = np.zeros_like(t)
tout, y, x = lsim(system, u, t, X0=[1.0])
expected_y = np.exp(-tout)
assert_almost_equal(y, expected_y)
class Test_lsim2(object):
def test_01(self):
t = np.linspace(0,10,1001)
u = np.zeros_like(t)
# First order system: x'(t) + x(t) = u(t), x(0) = 1.
# Exact solution is x(t) = exp(-t).
system = ([1.0],[1.0,1.0])
tout, y, x = lsim2(system, u, t, X0=[1.0])
expected_x = np.exp(-tout)
assert_almost_equal(x[:,0], expected_x)
def test_02(self):
t = np.array([0.0, 1.0, 1.0, 3.0])
u = np.array([0.0, 0.0, 1.0, 1.0])
# Simple integrator: x'(t) = u(t)
system = ([1.0],[1.0,0.0])
tout, y, x = lsim2(system, u, t, X0=[1.0])
expected_x = np.maximum(1.0, tout)
assert_almost_equal(x[:,0], expected_x)
def test_03(self):
t = np.array([0.0, 1.0, 1.0, 1.1, 1.1, 2.0])
u = np.array([0.0, 0.0, 1.0, 1.0, 0.0, 0.0])
# Simple integrator: x'(t) = u(t)
system = ([1.0],[1.0, 0.0])
tout, y, x = lsim2(system, u, t, hmax=0.01)
expected_x = np.array([0.0, 0.0, 0.0, 0.1, 0.1, 0.1])
assert_almost_equal(x[:,0], expected_x)
def test_04(self):
t = np.linspace(0, 10, 1001)
u = np.zeros_like(t)
# Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0.
# With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution
# is (1-t)*exp(-t).
system = ([1.0], [1.0, 2.0, 1.0])
tout, y, x = lsim2(system, u, t, X0=[1.0, 0.0])
expected_x = (1.0 - tout) * np.exp(-tout)
assert_almost_equal(x[:,0], expected_x)
def test_05(self):
# The call to lsim2 triggers a "BadCoefficients" warning from
# scipy.signal.filter_design, but the test passes. I think the warning
# is related to the incomplete handling of multi-input systems in
# scipy.signal.
# A system with two state variables, two inputs, and one output.
A = np.array([[-1.0, 0.0], [0.0, -2.0]])
B = np.array([[1.0, 0.0], [0.0, 1.0]])
C = np.array([1.0, 0.0])
D = np.zeros((1, 2))
t = np.linspace(0, 10.0, 101)
with suppress_warnings() as sup:
sup.filter(BadCoefficients)
tout, y, x = lsim2((A,B,C,D), T=t, X0=[1.0, 1.0])
expected_y = np.exp(-tout)
expected_x0 = np.exp(-tout)
expected_x1 = np.exp(-2.0 * tout)
assert_almost_equal(y, expected_y)
assert_almost_equal(x[:,0], expected_x0)
assert_almost_equal(x[:,1], expected_x1)
def test_06(self):
# Test use of the default values of the arguments `T` and `U`.
# Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0.
# With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution
# is (1-t)*exp(-t).
system = ([1.0], [1.0, 2.0, 1.0])
tout, y, x = lsim2(system, X0=[1.0, 0.0])
expected_x = (1.0 - tout) * np.exp(-tout)
assert_almost_equal(x[:,0], expected_x)
class _TestImpulseFuncs(object):
# Common tests for impulse/impulse2 (= self.func)
def test_01(self):
# First order system: x'(t) + x(t) = u(t)
# Exact impulse response is x(t) = exp(-t).
system = ([1.0], [1.0,1.0])
tout, y = self.func(system)
expected_y = np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_02(self):
# Specify the desired time values for the output.
# First order system: x'(t) + x(t) = u(t)
# Exact impulse response is x(t) = exp(-t).
system = ([1.0], [1.0,1.0])
n = 21
t = np.linspace(0, 2.0, n)
tout, y = self.func(system, T=t)
assert_equal(tout.shape, (n,))
assert_almost_equal(tout, t)
expected_y = np.exp(-t)
assert_almost_equal(y, expected_y)
def test_03(self):
# Specify an initial condition as a scalar.
# First order system: x'(t) + x(t) = u(t), x(0)=3.0
# Exact impulse response is x(t) = 4*exp(-t).
system = ([1.0], [1.0,1.0])
tout, y = self.func(system, X0=3.0)
expected_y = 4.0 * np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_04(self):
# Specify an initial condition as a list.
# First order system: x'(t) + x(t) = u(t), x(0)=3.0
# Exact impulse response is x(t) = 4*exp(-t).
system = ([1.0], [1.0,1.0])
tout, y = self.func(system, X0=[3.0])
expected_y = 4.0 * np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_05(self):
# Simple integrator: x'(t) = u(t)
system = ([1.0], [1.0,0.0])
tout, y = self.func(system)
expected_y = np.ones_like(tout)
assert_almost_equal(y, expected_y)
def test_06(self):
# Second order system with a repeated root:
# x''(t) + 2*x(t) + x(t) = u(t)
# The exact impulse response is t*exp(-t).
system = ([1.0], [1.0, 2.0, 1.0])
tout, y = self.func(system)
expected_y = tout * np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_array_like(self):
# Test that function can accept sequences, scalars.
system = ([1.0], [1.0, 2.0, 1.0])
# TODO: add meaningful test where X0 is a list
tout, y = self.func(system, X0=[3], T=[5, 6])
tout, y = self.func(system, X0=[3], T=[5])
def test_array_like2(self):
system = ([1.0], [1.0, 2.0, 1.0])
tout, y = self.func(system, X0=3, T=5)
class TestImpulse2(_TestImpulseFuncs):
def setup_method(self):
self.func = impulse2
class TestImpulse(_TestImpulseFuncs):
def setup_method(self):
self.func = impulse
class _TestStepFuncs(object):
def test_01(self):
# First order system: x'(t) + x(t) = u(t)
# Exact step response is x(t) = 1 - exp(-t).
system = ([1.0], [1.0,1.0])
tout, y = self.func(system)
expected_y = 1.0 - np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_02(self):
# Specify the desired time values for the output.
# First order system: x'(t) + x(t) = u(t)
# Exact step response is x(t) = 1 - exp(-t).
system = ([1.0], [1.0,1.0])
n = 21
t = np.linspace(0, 2.0, n)
tout, y = self.func(system, T=t)
assert_equal(tout.shape, (n,))
assert_almost_equal(tout, t)
expected_y = 1 - np.exp(-t)
assert_almost_equal(y, expected_y)
def test_03(self):
# Specify an initial condition as a scalar.
# First order system: x'(t) + x(t) = u(t), x(0)=3.0
# Exact step response is x(t) = 1 + 2*exp(-t).
system = ([1.0], [1.0,1.0])
tout, y = self.func(system, X0=3.0)
expected_y = 1 + 2.0*np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_04(self):
# Specify an initial condition as a list.
# First order system: x'(t) + x(t) = u(t), x(0)=3.0
# Exact step response is x(t) = 1 + 2*exp(-t).
system = ([1.0], [1.0,1.0])
tout, y = self.func(system, X0=[3.0])
expected_y = 1 + 2.0*np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_05(self):
# Simple integrator: x'(t) = u(t)
# Exact step response is x(t) = t.
system = ([1.0],[1.0,0.0])
tout, y = self.func(system)
expected_y = tout
assert_almost_equal(y, expected_y)
def test_06(self):
# Second order system with a repeated root:
# x''(t) + 2*x(t) + x(t) = u(t)
# The exact step response is 1 - (1 + t)*exp(-t).
system = ([1.0], [1.0, 2.0, 1.0])
tout, y = self.func(system)
expected_y = 1 - (1 + tout) * np.exp(-tout)
assert_almost_equal(y, expected_y)
def test_array_like(self):
# Test that function can accept sequences, scalars.
system = ([1.0], [1.0, 2.0, 1.0])
# TODO: add meaningful test where X0 is a list
tout, y = self.func(system, T=[5, 6])
class TestStep2(_TestStepFuncs):
def setup_method(self):
self.func = step2
def test_05(self):
# This test is almost the same as the one it overwrites in the base
# class. The only difference is the tolerances passed to step2:
# the default tolerances are not accurate enough for this test
# Simple integrator: x'(t) = u(t)
# Exact step response is x(t) = t.
system = ([1.0], [1.0,0.0])
tout, y = self.func(system, atol=1e-10, rtol=1e-8)
expected_y = tout
assert_almost_equal(y, expected_y)
class TestStep(_TestStepFuncs):
def setup_method(self):
self.func = step
def test_complex_input(self):
# Test that complex input doesn't raise an error.
# `step` doesn't seem to have been designed for complex input, but this
# works and may be used, so add regression test. See gh-2654.
step(([], [-1], 1+0j))
class TestLti(object):
def test_lti_instantiation(self):
# Test that lti can be instantiated with sequences, scalars.
# See PR-225.
# TransferFunction
s = lti([1], [-1])
assert_(isinstance(s, TransferFunction))
assert_(isinstance(s, lti))
assert_(not isinstance(s, dlti))
assert_(s.dt is None)
# ZerosPolesGain
s = lti(np.array([]), np.array([-1]), 1)
assert_(isinstance(s, ZerosPolesGain))
assert_(isinstance(s, lti))
assert_(not isinstance(s, dlti))
assert_(s.dt is None)
# StateSpace
s = lti([], [-1], 1)
s = lti([1], [-1], 1, 3)
assert_(isinstance(s, StateSpace))
assert_(isinstance(s, lti))
assert_(not isinstance(s, dlti))
assert_(s.dt is None)
class TestStateSpace(object):
def test_initialization(self):
# Check that all initializations work
StateSpace(1, 1, 1, 1)
StateSpace([1], [2], [3], [4])
StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]),
np.array([[1, 0]]), np.array([[0]]))
def test_conversion(self):
# Check the conversion functions
s = StateSpace(1, 2, 3, 4)
assert_(isinstance(s.to_ss(), StateSpace))
assert_(isinstance(s.to_tf(), TransferFunction))
assert_(isinstance(s.to_zpk(), ZerosPolesGain))
# Make sure copies work
assert_(StateSpace(s) is not s)
assert_(s.to_ss() is not s)
def test_properties(self):
# Test setters/getters for cross class properties.
# This implicitly tests to_tf() and to_zpk()
# Getters
s = StateSpace(1, 1, 1, 1)
assert_equal(s.poles, [1])
assert_equal(s.zeros, [0])
assert_(s.dt is None)
def test_operators(self):
# Test +/-/* operators on systems
class BadType(object):
pass
s1 = StateSpace(np.array([[-0.5, 0.7], [0.3, -0.8]]),
np.array([[1], [0]]),
np.array([[1, 0]]),
np.array([[0]]),
)
s2 = StateSpace(np.array([[-0.2, -0.1], [0.4, -0.1]]),
np.array([[1], [0]]),
np.array([[1, 0]]),
np.array([[0]])
)
s_discrete = s1.to_discrete(0.1)
s2_discrete = s2.to_discrete(0.2)
# Impulse response
t = np.linspace(0, 1, 100)
u = np.zeros_like(t)
u[0] = 1
# Test multiplication
for typ in (int, float, complex, np.float32, np.complex128, np.array):
assert_allclose(lsim(typ(2) * s1, U=u, T=t)[1],
typ(2) * lsim(s1, U=u, T=t)[1])
assert_allclose(lsim(s1 * typ(2), U=u, T=t)[1],
lsim(s1, U=u, T=t)[1] * typ(2))
assert_allclose(lsim(s1 / typ(2), U=u, T=t)[1],
lsim(s1, U=u, T=t)[1] / typ(2))
with assert_raises(TypeError):
typ(2) / s1
assert_allclose(lsim(s1 * 2, U=u, T=t)[1],
lsim(s1, U=2 * u, T=t)[1])
assert_allclose(lsim(s1 * s2, U=u, T=t)[1],
lsim(s1, U=lsim(s2, U=u, T=t)[1], T=t)[1],
atol=1e-5)
with assert_raises(TypeError):
s1 / s1
with assert_raises(TypeError):
s1 * s_discrete
with assert_raises(TypeError):
# Check different discretization constants
s_discrete * s2_discrete
with assert_raises(TypeError):
s1 * BadType()
with assert_raises(TypeError):
BadType() * s1
with assert_raises(TypeError):
s1 / BadType()
with assert_raises(TypeError):
BadType() / s1
# Test addition
assert_allclose(lsim(s1 + 2, U=u, T=t)[1],
2 * u + lsim(s1, U=u, T=t)[1])
# Check for dimension mismatch
with assert_raises(ValueError):
s1 + np.array([1, 2])
with assert_raises(ValueError):
np.array([1, 2]) + s1
with assert_raises(TypeError):
s1 + s_discrete
with assert_raises(ValueError):
s1 / np.array([[1, 2], [3, 4]])
with assert_raises(TypeError):
# Check different discretization constants
s_discrete + s2_discrete
with assert_raises(TypeError):
s1 + BadType()
with assert_raises(TypeError):
BadType() + s1
assert_allclose(lsim(s1 + s2, U=u, T=t)[1],
lsim(s1, U=u, T=t)[1] + lsim(s2, U=u, T=t)[1])
# Test subtraction
assert_allclose(lsim(s1 - 2, U=u, T=t)[1],
-2 * u + lsim(s1, U=u, T=t)[1])
assert_allclose(lsim(2 - s1, U=u, T=t)[1],
2 * u + lsim(-s1, U=u, T=t)[1])
assert_allclose(lsim(s1 - s2, U=u, T=t)[1],
lsim(s1, U=u, T=t)[1] - lsim(s2, U=u, T=t)[1])
with assert_raises(TypeError):
s1 - BadType()
with assert_raises(TypeError):
BadType() - s1
class TestTransferFunction(object):
def test_initialization(self):
# Check that all initializations work
TransferFunction(1, 1)
TransferFunction([1], [2])
TransferFunction(np.array([1]), np.array([2]))
def test_conversion(self):
# Check the conversion functions
s = TransferFunction([1, 0], [1, -1])
assert_(isinstance(s.to_ss(), StateSpace))
assert_(isinstance(s.to_tf(), TransferFunction))
assert_(isinstance(s.to_zpk(), ZerosPolesGain))
# Make sure copies work
assert_(TransferFunction(s) is not s)
assert_(s.to_tf() is not s)
def test_properties(self):
# Test setters/getters for cross class properties.
# This implicitly tests to_ss() and to_zpk()
# Getters
s = TransferFunction([1, 0], [1, -1])
assert_equal(s.poles, [1])
assert_equal(s.zeros, [0])
class TestZerosPolesGain(object):
def test_initialization(self):
# Check that all initializations work
ZerosPolesGain(1, 1, 1)
ZerosPolesGain([1], [2], 1)
ZerosPolesGain(np.array([1]), np.array([2]), 1)
def test_conversion(self):
#Check the conversion functions
s = ZerosPolesGain(1, 2, 3)
assert_(isinstance(s.to_ss(), StateSpace))
assert_(isinstance(s.to_tf(), TransferFunction))
assert_(isinstance(s.to_zpk(), ZerosPolesGain))
# Make sure copies work
assert_(ZerosPolesGain(s) is not s)
assert_(s.to_zpk() is not s)
class Test_abcd_normalize(object):
def setup_method(self):
self.A = np.array([[1.0, 2.0], [3.0, 4.0]])
self.B = np.array([[-1.0], [5.0]])
self.C = np.array([[4.0, 5.0]])
self.D = np.array([[2.5]])
def test_no_matrix_fails(self):
assert_raises(ValueError, abcd_normalize)
def test_A_nosquare_fails(self):
assert_raises(ValueError, abcd_normalize, [1, -1],
self.B, self.C, self.D)
def test_AB_mismatch_fails(self):
assert_raises(ValueError, abcd_normalize, self.A, [-1, 5],
self.C, self.D)
def test_AC_mismatch_fails(self):
assert_raises(ValueError, abcd_normalize, self.A, self.B,
[[4.0], [5.0]], self.D)
def test_CD_mismatch_fails(self):
assert_raises(ValueError, abcd_normalize, self.A, self.B,
self.C, [2.5, 0])
def test_BD_mismatch_fails(self):
assert_raises(ValueError, abcd_normalize, self.A, [-1, 5],
self.C, self.D)
def test_normalized_matrices_unchanged(self):
A, B, C, D = abcd_normalize(self.A, self.B, self.C, self.D)
assert_equal(A, self.A)
assert_equal(B, self.B)
assert_equal(C, self.C)
assert_equal(D, self.D)
def test_shapes(self):
A, B, C, D = abcd_normalize(self.A, self.B, [1, 0], 0)
assert_equal(A.shape[0], A.shape[1])
assert_equal(A.shape[0], B.shape[0])
assert_equal(A.shape[0], C.shape[1])
assert_equal(C.shape[0], D.shape[0])
assert_equal(B.shape[1], D.shape[1])
def test_zero_dimension_is_not_none1(self):
B_ = np.zeros((2, 0))
D_ = np.zeros((0, 0))
A, B, C, D = abcd_normalize(A=self.A, B=B_, D=D_)
assert_equal(A, self.A)
assert_equal(B, B_)
assert_equal(D, D_)
assert_equal(C.shape[0], D_.shape[0])
assert_equal(C.shape[1], self.A.shape[0])
def test_zero_dimension_is_not_none2(self):
B_ = np.zeros((2, 0))
C_ = np.zeros((0, 2))
A, B, C, D = abcd_normalize(A=self.A, B=B_, C=C_)
assert_equal(A, self.A)
assert_equal(B, B_)
assert_equal(C, C_)
assert_equal(D.shape[0], C_.shape[0])
assert_equal(D.shape[1], B_.shape[1])
def test_missing_A(self):
A, B, C, D = abcd_normalize(B=self.B, C=self.C, D=self.D)
assert_equal(A.shape[0], A.shape[1])
assert_equal(A.shape[0], B.shape[0])
assert_equal(A.shape, (self.B.shape[0], self.B.shape[0]))
def test_missing_B(self):
A, B, C, D = abcd_normalize(A=self.A, C=self.C, D=self.D)
assert_equal(B.shape[0], A.shape[0])
assert_equal(B.shape[1], D.shape[1])
assert_equal(B.shape, (self.A.shape[0], self.D.shape[1]))
def test_missing_C(self):
A, B, C, D = abcd_normalize(A=self.A, B=self.B, D=self.D)
assert_equal(C.shape[0], D.shape[0])
assert_equal(C.shape[1], A.shape[0])
assert_equal(C.shape, (self.D.shape[0], self.A.shape[0]))
def test_missing_D(self):
A, B, C, D = abcd_normalize(A=self.A, B=self.B, C=self.C)
assert_equal(D.shape[0], C.shape[0])
assert_equal(D.shape[1], B.shape[1])
assert_equal(D.shape, (self.C.shape[0], self.B.shape[1]))
def test_missing_AB(self):
A, B, C, D = abcd_normalize(C=self.C, D=self.D)
assert_equal(A.shape[0], A.shape[1])
assert_equal(A.shape[0], B.shape[0])
assert_equal(B.shape[1], D.shape[1])
assert_equal(A.shape, (self.C.shape[1], self.C.shape[1]))
assert_equal(B.shape, (self.C.shape[1], self.D.shape[1]))
def test_missing_AC(self):
A, B, C, D = abcd_normalize(B=self.B, D=self.D)
assert_equal(A.shape[0], A.shape[1])
assert_equal(A.shape[0], B.shape[0])
assert_equal(C.shape[0], D.shape[0])
assert_equal(C.shape[1], A.shape[0])
assert_equal(A.shape, (self.B.shape[0], self.B.shape[0]))
assert_equal(C.shape, (self.D.shape[0], self.B.shape[0]))
def test_missing_AD(self):
A, B, C, D = abcd_normalize(B=self.B, C=self.C)
assert_equal(A.shape[0], A.shape[1])
assert_equal(A.shape[0], B.shape[0])
assert_equal(D.shape[0], C.shape[0])
assert_equal(D.shape[1], B.shape[1])
assert_equal(A.shape, (self.B.shape[0], self.B.shape[0]))
assert_equal(D.shape, (self.C.shape[0], self.B.shape[1]))
def test_missing_BC(self):
A, B, C, D = abcd_normalize(A=self.A, D=self.D)
assert_equal(B.shape[0], A.shape[0])
assert_equal(B.shape[1], D.shape[1])
assert_equal(C.shape[0], D.shape[0])
assert_equal(C.shape[1], A.shape[0])
assert_equal(B.shape, (self.A.shape[0], self.D.shape[1]))
assert_equal(C.shape, (self.D.shape[0], self.A.shape[0]))
def test_missing_ABC_fails(self):
assert_raises(ValueError, abcd_normalize, D=self.D)
def test_missing_BD_fails(self):
assert_raises(ValueError, abcd_normalize, A=self.A, C=self.C)
def test_missing_CD_fails(self):
assert_raises(ValueError, abcd_normalize, A=self.A, B=self.B)
class Test_bode(object):
def test_01(self):
# Test bode() magnitude calculation (manual sanity check).
# 1st order low-pass filter: H(s) = 1 / (s + 1),
# cutoff: 1 rad/s, slope: -20 dB/decade
# H(s=0.1) ~= 0 dB
# H(s=1) ~= -3 dB
# H(s=10) ~= -20 dB
# H(s=100) ~= -40 dB
system = lti([1], [1, 1])
w = [0.1, 1, 10, 100]
w, mag, phase = bode(system, w=w)
expected_mag = [0, -3, -20, -40]
assert_almost_equal(mag, expected_mag, decimal=1)
def test_02(self):
# Test bode() phase calculation (manual sanity check).
# 1st order low-pass filter: H(s) = 1 / (s + 1),
# angle(H(s=0.1)) ~= -5.7 deg
# angle(H(s=1)) ~= -45 deg
# angle(H(s=10)) ~= -84.3 deg
system = lti([1], [1, 1])
w = [0.1, 1, 10]
w, mag, phase = bode(system, w=w)
expected_phase = [-5.7, -45, -84.3]
assert_almost_equal(phase, expected_phase, decimal=1)
def test_03(self):
# Test bode() magnitude calculation.
# 1st order low-pass filter: H(s) = 1 / (s + 1)
system = lti([1], [1, 1])
w = [0.1, 1, 10, 100]
w, mag, phase = bode(system, w=w)
jw = w * 1j
y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
expected_mag = 20.0 * np.log10(abs(y))
assert_almost_equal(mag, expected_mag)
def test_04(self):
# Test bode() phase calculation.
# 1st order low-pass filter: H(s) = 1 / (s + 1)
system = lti([1], [1, 1])
w = [0.1, 1, 10, 100]
w, mag, phase = bode(system, w=w)
jw = w * 1j
y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
expected_phase = np.arctan2(y.imag, y.real) * 180.0 / np.pi
assert_almost_equal(phase, expected_phase)
def test_05(self):
# Test that bode() finds a reasonable frequency range.
# 1st order low-pass filter: H(s) = 1 / (s + 1)
system = lti([1], [1, 1])
n = 10
# Expected range is from 0.01 to 10.
expected_w = np.logspace(-2, 1, n)
w, mag, phase = bode(system, n=n)
assert_almost_equal(w, expected_w)
def test_06(self):
# Test that bode() doesn't fail on a system with a pole at 0.
# integrator, pole at zero: H(s) = 1 / s
system = lti([1], [1, 0])
w, mag, phase = bode(system, n=2)
assert_equal(w[0], 0.01) # a fail would give not-a-number
def test_07(self):
# bode() should not fail on a system with pure imaginary poles.
# The test passes if bode doesn't raise an exception.
system = lti([1], [1, 0, 100])
w, mag, phase = bode(system, n=2)
def test_08(self):
# Test that bode() return continuous phase, issues/2331.
system = lti([], [-10, -30, -40, -60, -70], 1)
w, mag, phase = system.bode(w=np.logspace(-3, 40, 100))
assert_almost_equal(min(phase), -450, decimal=15)
def test_from_state_space(self):
# Ensure that bode works with a system that was created from the
# state space representation matrices A, B, C, D. In this case,
# system.num will be a 2-D array with shape (1, n+1), where (n,n)
# is the shape of A.
# A Butterworth lowpass filter is used, so we know the exact
# frequency response.
a = np.array([1.0, 2.0, 2.0, 1.0])
A = linalg.companion(a).T
B = np.array([[0.0], [0.0], [1.0]])
C = np.array([[1.0, 0.0, 0.0]])
D = np.array([[0.0]])
with suppress_warnings() as sup:
sup.filter(BadCoefficients)
system = lti(A, B, C, D)
w, mag, phase = bode(system, n=100)
expected_magnitude = 20 * np.log10(np.sqrt(1.0 / (1.0 + w**6)))
assert_almost_equal(mag, expected_magnitude)
class Test_freqresp(object):
def test_output_manual(self):
# Test freqresp() output calculation (manual sanity check).
# 1st order low-pass filter: H(s) = 1 / (s + 1),
# re(H(s=0.1)) ~= 0.99
# re(H(s=1)) ~= 0.5
# re(H(s=10)) ~= 0.0099
system = lti([1], [1, 1])
w = [0.1, 1, 10]
w, H = freqresp(system, w=w)
expected_re = [0.99, 0.5, 0.0099]
expected_im = [-0.099, -0.5, -0.099]
assert_almost_equal(H.real, expected_re, decimal=1)
assert_almost_equal(H.imag, expected_im, decimal=1)
def test_output(self):
# Test freqresp() output calculation.
# 1st order low-pass filter: H(s) = 1 / (s + 1)
system = lti([1], [1, 1])
w = [0.1, 1, 10, 100]
w, H = freqresp(system, w=w)
s = w * 1j
expected = np.polyval(system.num, s) / np.polyval(system.den, s)
assert_almost_equal(H.real, expected.real)
assert_almost_equal(H.imag, expected.imag)
def test_freq_range(self):
# Test that freqresp() finds a reasonable frequency range.
# 1st order low-pass filter: H(s) = 1 / (s + 1)
# Expected range is from 0.01 to 10.
system = lti([1], [1, 1])
n = 10
expected_w = np.logspace(-2, 1, n)
w, H = freqresp(system, n=n)
assert_almost_equal(w, expected_w)
def test_pole_zero(self):
# Test that freqresp() doesn't fail on a system with a pole at 0.
# integrator, pole at zero: H(s) = 1 / s
system = lti([1], [1, 0])
w, H = freqresp(system, n=2)
assert_equal(w[0], 0.01) # a fail would give not-a-number
def test_from_state_space(self):
# Ensure that freqresp works with a system that was created from the
# state space representation matrices A, B, C, D. In this case,
# system.num will be a 2-D array with shape (1, n+1), where (n,n) is
# the shape of A.
# A Butterworth lowpass filter is used, so we know the exact
# frequency response.
a = np.array([1.0, 2.0, 2.0, 1.0])
A = linalg.companion(a).T
B = np.array([[0.0],[0.0],[1.0]])
C = np.array([[1.0, 0.0, 0.0]])
D = np.array([[0.0]])
with suppress_warnings() as sup:
sup.filter(BadCoefficients)
system = lti(A, B, C, D)
w, H = freqresp(system, n=100)
s = w * 1j
expected = (1.0 / (1.0 + 2*s + 2*s**2 + s**3))
assert_almost_equal(H.real, expected.real)
assert_almost_equal(H.imag, expected.imag)
def test_from_zpk(self):
# 4th order low-pass filter: H(s) = 1 / (s + 1)
system = lti([],[-1]*4,[1])
w = [0.1, 1, 10, 100]
w, H = freqresp(system, w=w)
s = w * 1j
expected = 1 / (s + 1)**4
assert_almost_equal(H.real, expected.real)
assert_almost_equal(H.imag, expected.imag)
| bsd-3-clause |
ixc/plata | plata/reporting/views.py | 1080 | from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
@staff_member_required
def product_xls(request):
"""
Returns an XLS containing product information
"""
return plata.reporting.product.product_xls().to_response('products.xlsx')
@staff_member_required
def invoice_pdf(request, order_id):
"""
Returns the invoice PDF
"""
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
pdf, response = pdf_response('invoice-%09d' % order.id)
plata.reporting.order.invoice_pdf(pdf, order)
return response
@staff_member_required
def packing_slip_pdf(request, order_id):
"""
Returns the packing slip PDF
"""
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
pdf, response = pdf_response('packing-slip-%09d' % order.id)
plata.reporting.order.packing_slip_pdf(pdf, order)
return response
| bsd-3-clause |
axinging/chromium-crosswalk | third_party/WebKit/Source/bindings/core/v8/custom/V8CSSStyleDeclarationCustom.cpp | 8762 | /*
* Copyright (C) 2007-2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "bindings/core/v8/V8CSSStyleDeclaration.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8Binding.h"
#include "core/CSSPropertyNames.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSPropertyMetadata.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/css/CSSValue.h"
#include "core/css/parser/CSSParser.h"
#include "core/events/EventTarget.h"
#include "wtf/ASCIICType.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/StringConcatenate.h"
#include <algorithm>
using namespace WTF;
namespace blink {
// Check for a CSS prefix.
// Passed prefix is all lowercase.
// First character of the prefix within the property name may be upper or lowercase.
// Other characters in the prefix within the property name must be lowercase.
// The prefix within the property name must be followed by a capital letter.
static bool hasCSSPropertyNamePrefix(const String& propertyName, const char* prefix)
{
#if ENABLE(ASSERT)
ASSERT(*prefix);
for (const char* p = prefix; *p; ++p)
ASSERT(isASCIILower(*p));
ASSERT(propertyName.length());
#endif
if (toASCIILower(propertyName[0]) != prefix[0])
return false;
unsigned length = propertyName.length();
for (unsigned i = 1; i < length; ++i) {
if (!prefix[i])
return isASCIIUpper(propertyName[i]);
if (propertyName[i] != prefix[i])
return false;
}
return false;
}
static CSSPropertyID parseCSSPropertyID(const String& propertyName)
{
unsigned length = propertyName.length();
if (!length)
return CSSPropertyInvalid;
StringBuilder builder;
builder.reserveCapacity(length);
unsigned i = 0;
bool hasSeenDash = false;
if (hasCSSPropertyNamePrefix(propertyName, "webkit"))
builder.append('-');
else if (isASCIIUpper(propertyName[0]))
return CSSPropertyInvalid;
bool hasSeenUpper = isASCIIUpper(propertyName[i]);
builder.append(toASCIILower(propertyName[i++]));
for (; i < length; ++i) {
UChar c = propertyName[i];
if (!isASCIIUpper(c)) {
if (c == '-')
hasSeenDash = true;
builder.append(c);
} else {
hasSeenUpper = true;
builder.append('-');
builder.append(toASCIILower(c));
}
}
// Reject names containing both dashes and upper-case characters, such as "border-rightColor".
if (hasSeenDash && hasSeenUpper)
return CSSPropertyInvalid;
String propName = builder.toString();
return unresolvedCSSPropertyID(propName);
}
// When getting properties on CSSStyleDeclarations, the name used from
// Javascript and the actual name of the property are not the same, so
// we have to do the following translation. The translation turns upper
// case characters into lower case characters and inserts dashes to
// separate words.
//
// Example: 'backgroundPositionY' -> 'background-position-y'
//
// Also, certain prefixes such as 'css-' are stripped.
static CSSPropertyID cssPropertyInfo(v8::Local<v8::String> v8PropertyName)
{
String propertyName = toCoreString(v8PropertyName);
typedef HashMap<String, CSSPropertyID> CSSPropertyIDMap;
DEFINE_STATIC_LOCAL(CSSPropertyIDMap, map, ());
CSSPropertyIDMap::iterator iter = map.find(propertyName);
if (iter != map.end())
return iter->value;
CSSPropertyID unresolvedProperty = parseCSSPropertyID(propertyName);
map.add(propertyName, unresolvedProperty);
ASSERT(!unresolvedProperty || CSSPropertyMetadata::isEnabledProperty(unresolvedProperty));
return unresolvedProperty;
}
void V8CSSStyleDeclaration::namedPropertyEnumeratorCustom(const v8::PropertyCallbackInfo<v8::Array>& info)
{
typedef Vector<String, numCSSProperties - 1> PreAllocatedPropertyVector;
DEFINE_STATIC_LOCAL(PreAllocatedPropertyVector, propertyNames, ());
static unsigned propertyNamesLength = 0;
if (propertyNames.isEmpty()) {
for (int id = firstCSSProperty; id <= lastCSSProperty; ++id) {
CSSPropertyID propertyId = static_cast<CSSPropertyID>(id);
if (CSSPropertyMetadata::isEnabledProperty(propertyId))
propertyNames.append(getJSPropertyName(propertyId));
}
std::sort(propertyNames.begin(), propertyNames.end(), codePointCompareLessThan);
propertyNamesLength = propertyNames.size();
}
v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
v8::Local<v8::Array> properties = v8::Array::New(info.GetIsolate(), propertyNamesLength);
for (unsigned i = 0; i < propertyNamesLength; ++i) {
String key = propertyNames.at(i);
ASSERT(!key.isNull());
if (!v8CallBoolean(properties->CreateDataProperty(context, i, v8String(info.GetIsolate(), key))))
return;
}
v8SetReturnValue(info, properties);
}
void V8CSSStyleDeclaration::namedPropertyQueryCustom(v8::Local<v8::Name> v8Name, const v8::PropertyCallbackInfo<v8::Integer>& info)
{
// NOTE: cssPropertyInfo lookups incur several mallocs.
// Successful lookups have the same cost the first time, but are cached.
if (cssPropertyInfo(v8Name.As<v8::String>())) {
v8SetReturnValueInt(info, 0);
return;
}
}
void V8CSSStyleDeclaration::namedPropertyGetterCustom(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
// Search the style declaration.
CSSPropertyID unresolvedProperty = cssPropertyInfo(name.As<v8::String>());
// Do not handle non-property names.
if (!unresolvedProperty)
return;
CSSPropertyID resolvedProperty = resolveCSSPropertyID(unresolvedProperty);
CSSStyleDeclaration* impl = V8CSSStyleDeclaration::toImpl(info.Holder());
// TODO(leviw): This API doesn't support custom properties.
CSSValue* cssValue = impl->getPropertyCSSValueInternal(resolvedProperty);
if (cssValue) {
v8SetReturnValueStringOrNull(info, cssValue->cssText(), info.GetIsolate());
return;
}
String result = impl->getPropertyValueInternal(resolvedProperty);
v8SetReturnValueString(info, result, info.GetIsolate());
}
void V8CSSStyleDeclaration::namedPropertySetterCustom(v8::Local<v8::Name> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
CSSStyleDeclaration* impl = V8CSSStyleDeclaration::toImpl(info.Holder());
CSSPropertyID unresolvedProperty = cssPropertyInfo(name.As<v8::String>());
if (!unresolvedProperty)
return;
TOSTRING_VOID(V8StringResource<TreatNullAsNullString>, propertyValue, value);
ExceptionState exceptionState(ExceptionState::SetterContext, getPropertyName(resolveCSSPropertyID(unresolvedProperty)), "CSSStyleDeclaration", info.Holder(), info.GetIsolate());
// TODO(leviw): This API doesn't support custom properties.
impl->setPropertyInternal(unresolvedProperty, String(), propertyValue, false, exceptionState);
if (exceptionState.throwIfNeeded())
return;
v8SetReturnValue(info, value);
}
} // namespace blink
| bsd-3-clause |
Crystalnix/BitPop | content/renderer/media/video_capture_message_filter_unittest.cc | 6977 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/shared_memory.h"
#include "content/common/media/video_capture_messages.h"
#include "content/renderer/media/video_capture_message_filter.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class MockVideoCaptureDelegate : public VideoCaptureMessageFilter::Delegate {
public:
MockVideoCaptureDelegate() {
Reset();
device_id_received_ = false;
device_id_ = 0;
}
virtual void OnBufferCreated(base::SharedMemoryHandle handle,
int length, int buffer_id) {
buffer_created_ = true;
handle_ = handle;
}
// Called when a video frame buffer is received from the browser process.
virtual void OnBufferReceived(int buffer_id, base::Time timestamp) {
buffer_received_ = true;
buffer_id_ = buffer_id;
timestamp_ = timestamp;
}
virtual void OnStateChanged(video_capture::State state) {
state_changed_received_ = true;
state_ = state;
}
virtual void OnDeviceInfoReceived(const media::VideoCaptureParams& params) {
device_info_received_ = true;
params_.width = params.width;
params_.height = params.height;
params_.frame_per_second = params.frame_per_second;
}
virtual void OnDelegateAdded(int32 device_id) {
device_id_received_ = true;
device_id_ = device_id;
}
void Reset() {
buffer_created_ = false;
handle_ = base::SharedMemory::NULLHandle();
buffer_received_ = false;
buffer_id_ = -1;
timestamp_ = base::Time();
state_changed_received_ = false;
state_ = video_capture::kError;
device_info_received_ = false;
params_.width = 0;
params_.height = 0;
params_.frame_per_second = 0;
}
bool buffer_created() { return buffer_created_; }
base::SharedMemoryHandle received_buffer_handle() { return handle_; }
bool buffer_received() { return buffer_received_; }
int received_buffer_id() { return buffer_id_; }
base::Time received_buffer_ts() { return timestamp_; }
bool state_changed_received() { return state_changed_received_; }
video_capture::State state() { return state_; }
bool device_info_receive() { return device_info_received_; }
const media::VideoCaptureParams& received_device_info() { return params_; }
int32 device_id() { return device_id_; }
private:
bool buffer_created_;
base::SharedMemoryHandle handle_;
bool buffer_received_;
int buffer_id_;
base::Time timestamp_;
bool state_changed_received_;
video_capture::State state_;
bool device_info_received_;
media::VideoCaptureParams params_;
bool device_id_received_;
int32 device_id_;
DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureDelegate);
};
} // namespace
TEST(VideoCaptureMessageFilterTest, Basic) {
MessageLoop message_loop(MessageLoop::TYPE_IO);
scoped_refptr<VideoCaptureMessageFilter> filter(
new VideoCaptureMessageFilter());
filter->channel_ = reinterpret_cast<IPC::Channel*>(1);
MockVideoCaptureDelegate delegate;
filter->AddDelegate(&delegate);
// VideoCaptureMsg_StateChanged
EXPECT_FALSE(delegate.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate.device_id(),
video_capture::kStarted));
EXPECT_TRUE(delegate.state_changed_received());
EXPECT_TRUE(video_capture::kStarted == delegate.state());
delegate.Reset();
// VideoCaptureMsg_NewBuffer
const base::SharedMemoryHandle handle =
#if defined(OS_WIN)
reinterpret_cast<base::SharedMemoryHandle>(10);
#else
base::SharedMemoryHandle(10, true);
#endif
EXPECT_FALSE(delegate.buffer_created());
filter->OnMessageReceived(VideoCaptureMsg_NewBuffer(
delegate.device_id(), handle, 1, 1));
EXPECT_TRUE(delegate.buffer_created());
EXPECT_EQ(handle, delegate.received_buffer_handle());
delegate.Reset();
// VideoCaptureMsg_BufferReady
int buffer_id = 1;
base::Time timestamp = base::Time::FromInternalValue(1);
EXPECT_FALSE(delegate.buffer_received());
filter->OnMessageReceived(VideoCaptureMsg_BufferReady(
delegate.device_id(), buffer_id, timestamp));
EXPECT_TRUE(delegate.buffer_received());
EXPECT_EQ(buffer_id, delegate.received_buffer_id());
EXPECT_TRUE(timestamp == delegate.received_buffer_ts());
delegate.Reset();
// VideoCaptureMsg_DeviceInfo
media::VideoCaptureParams params;
params.width = 320;
params.height = 240;
params.frame_per_second = 30;
EXPECT_FALSE(delegate.device_info_receive());
filter->OnMessageReceived(VideoCaptureMsg_DeviceInfo(
delegate.device_id(), params));
EXPECT_TRUE(delegate.device_info_receive());
EXPECT_EQ(params.width, delegate.received_device_info().width);
EXPECT_EQ(params.height, delegate.received_device_info().height);
EXPECT_EQ(params.frame_per_second,
delegate.received_device_info().frame_per_second);
delegate.Reset();
message_loop.RunAllPending();
}
TEST(VideoCaptureMessageFilterTest, Delegates) {
MessageLoop message_loop(MessageLoop::TYPE_IO);
scoped_refptr<VideoCaptureMessageFilter> filter(
new VideoCaptureMessageFilter());
filter->channel_ = reinterpret_cast<IPC::Channel*>(1);
MockVideoCaptureDelegate delegate1;
MockVideoCaptureDelegate delegate2;
filter->AddDelegate(&delegate1);
filter->AddDelegate(&delegate2);
// Send an IPC message. Make sure the correct delegate gets called.
EXPECT_FALSE(delegate1.state_changed_received());
EXPECT_FALSE(delegate2.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate1.device_id(),
video_capture::kStarted));
EXPECT_TRUE(delegate1.state_changed_received());
EXPECT_FALSE(delegate2.state_changed_received());
delegate1.Reset();
EXPECT_FALSE(delegate1.state_changed_received());
EXPECT_FALSE(delegate2.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate2.device_id(),
video_capture::kStarted));
EXPECT_FALSE(delegate1.state_changed_received());
EXPECT_TRUE(delegate2.state_changed_received());
delegate2.Reset();
// Remove the delegates. Make sure they won't get called.
filter->RemoveDelegate(&delegate1);
EXPECT_FALSE(delegate1.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate1.device_id(),
video_capture::kStarted));
EXPECT_FALSE(delegate1.state_changed_received());
filter->RemoveDelegate(&delegate2);
EXPECT_FALSE(delegate2.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate2.device_id(),
video_capture::kStarted));
EXPECT_FALSE(delegate2.state_changed_received());
message_loop.RunAllPending();
}
| bsd-3-clause |
daejunpark/jsaf | tests/bug_detector_tests/urierror1.js | 100 | // d. ii. If k + 2 is greater than or equal to strLen, throw a URIError exception.
decodeURI('%1');
| bsd-3-clause |
chrismayer/geoext2 | examples/layeropacityslider/layeropacityslider.js | 3626 | /*
* Copyright (c) 2008-present The Open Source Geospatial Foundation
*
* Published under the BSD license.
* See https://github.com/geoext/geoext2/blob/master/license.txt for the full
* text of the license.
*/
/** api: example[layeropacityslider]
* Layer Opacity Slider
* --------------------
* Use a slider to control layer opacity.
*/
var panel1, panel2, wms, slider;
Ext.require([
'Ext.container.Viewport',
'Ext.layout.container.Border',
'GeoExt.panel.Map',
'GeoExt.slider.LayerOpacity',
'GeoExt.slider.Tip'
]);
Ext.application({
name: 'LayerOpacitySlider GeoExt2',
launch: function() {
wms = new OpenLayers.Layer.WMS(
"Global Imagery",
"http://maps.opengeo.org/geowebcache/service/wms",
{layers: "bluemarble"}
);
// create a map panel with an embedded slider
panel1 = Ext.create('GeoExt.panel.Map', {
title: "Map 1",
renderTo: "map1-container",
height: 300,
width: 400,
map: {
controls: [new OpenLayers.Control.Navigation()]
},
layers: [wms],
extent: [-5, 35, 15, 55],
items: [{
xtype: "gx_opacityslider",
layer: wms,
vertical: true,
height: 120,
x: 10,
y: 10,
plugins: Ext.create("GeoExt.slider.Tip", {
getText: function(thumb) {
return Ext.String.format('Opacity: {0}%', thumb.value);
}
})
}]
});
// create a separate slider bound to the map but displayed elsewhere
slider = Ext.create('GeoExt.slider.LayerOpacity', {
layer: wms,
aggressive: true,
width: 200,
isFormField: true,
inverse: true,
fieldLabel: "opacity",
renderTo: "slider",
plugins: Ext.create("GeoExt.slider.Tip", {
getText: function(thumb) {
return Ext.String.format('Transparency: {0}%', thumb.value);
}
})
});
var clone = wms.clone();
var wms2 = new OpenLayers.Layer.WMS(
"OpenStreetMap WMS",
"http://ows.terrestris.de/osm/service?",
{layers: 'OSM-WMS'},
{
attribution: '© terrestris GmbH & Co. KG <br>' +
'Data © OpenStreetMap ' +
'<a href="http://www.openstreetmap.org/copyright/en"' +
'target="_blank">contributors<a>'
}
);
panel2 = Ext.create('GeoExt.panel.Map', {
title: "Map 2",
renderTo: "map2-container",
height: 300,
width: 400,
map: {
controls: [new OpenLayers.Control.Navigation()]
},
layers: [wms2, clone],
extent: [-5, 35, 15, 55],
items: [{
xtype: "gx_opacityslider",
layer: clone,
complementaryLayer: wms2,
changeVisibility: true,
aggressive: true,
vertical: true,
height: 120,
x: 10,
y: 10,
plugins: Ext.create("GeoExt.slider.Tip", {
getText: function(thumb) {
return Ext.String.format('{0}%', thumb.value);
}
})
}]
});
}
});
| bsd-3-clause |
jmock-developers/jmock-library | jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/MockeryFinalizationAcceptanceTests.java | 3971 | package org.jmock.test.acceptance;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import org.jmock.Mockery;
import org.jmock.api.Imposteriser;
import org.jmock.lib.concurrent.Synchroniser;
import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
/**
* Nasty test to show GitHub #36 is fixed.
*/
public class MockeryFinalizationAcceptanceTests
{
private static final int FINALIZE_COUNT = 10; // consistently shows a problem before GitHub #36 was fixed
private final Mockery mockery = new Mockery() {{
setThreadingPolicy(new Synchroniser());
}};
private final ErrorStream capturingErr = new ErrorStream();
@BeforeAll
public static void clearAnyOutstandingMessages() {
ErrorStream localErr = new ErrorStream();
localErr.install();
String error = null;
try {
finalizeUntilMessageOrCount(localErr, FINALIZE_COUNT);
error = localErr.output();
} finally {
localErr.uninstall();
}
if (error != null)
System.err.println("WARNING - a previous test left output in finalization [" + error + "]");
}
@BeforeEach
public void captureSysErr() {
capturingErr.install();
}
@AfterEach
public void replaceSysErr() {
capturingErr.uninstall();
}
@ParameterizedTest
@ArgumentsSource(ImposteriserParameterResolver.class)
public void mockedInterfaceDoesntWarnOnFinalize(Imposteriser imposterImpl) {
mockery.setImposteriser(imposterImpl);
checkNoFinalizationMessage(mockery, CharSequence.class);
}
@ParameterizedTest
@ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class)
public void mockedClassDoesntWarnOnFinalize(Imposteriser imposterImpl) {
mockery.setImposteriser(imposterImpl);
checkNoFinalizationMessage(mockery, Object.class);
}
public interface TypeThatMakesFinalizePublic {
public void finalize();
}
@ParameterizedTest
@ArgumentsSource(ImposteriserParameterResolver.class)
public void mockedTypeThatMakesFinalizePublicDoesntWarnOnFinalize(Imposteriser imposterImpl) {
mockery.setImposteriser(imposterImpl);
checkNoFinalizationMessage(mockery, TypeThatMakesFinalizePublic.class);
}
private void checkNoFinalizationMessage(Mockery mockery, Class<?> typeToMock) {
WeakReference<Object> mockHolder = new WeakReference<Object>(mockery.mock(typeToMock));
while (mockHolder.get() != null) {
System.gc();
System.runFinalization();
}
finalizeUntilMessageOrCount(capturingErr, FINALIZE_COUNT);
assertThat(capturingErr.output(), isEmptyOrNullString());
}
private static void finalizeUntilMessageOrCount(ErrorStream capturingErr, int count) {
for (int i = 0; i < count && capturingErr.output().isEmpty(); i++) {
System.gc();
System.runFinalization();
}
}
private static class ErrorStream extends PrintStream {
private PrintStream oldSysErr;
public ErrorStream() {
super(new ByteArrayOutputStream());
}
public void install() {
oldSysErr = System.err;
System.setErr(this);
}
public void uninstall() {
System.setErr(oldSysErr);
}
public String output() {
return new String(((ByteArrayOutputStream) out).toByteArray());
}
}
} | bsd-3-clause |
leiferikb/bitpop-private | chrome/browser/media_transfer_protocol/media_transfer_protocol_daemon_client.h | 7976 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Client code to talk to the Media Transfer Protocol daemon. The MTP daemon is
// responsible for communicating with PTP / MTP capable devices like cameras
// and smartphones.
#ifndef CHROME_BROWSER_MEDIA_TRANSFER_PROTOCOL_MEDIA_TRANSFER_PROTOCOL_DAEMON_CLIENT_H_
#define CHROME_BROWSER_MEDIA_TRANSFER_PROTOCOL_MEDIA_TRANSFER_PROTOCOL_DAEMON_CLIENT_H_
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/callback.h"
#include "build/build_config.h"
#if !defined(OS_LINUX)
#error "Only used on Linux and ChromeOS"
#endif
class MtpFileEntry;
class MtpStorageInfo;
namespace dbus {
class Bus;
}
namespace chrome {
// A class to make the actual DBus calls for mtpd service.
// This class only makes calls, result/error handling should be done
// by callbacks.
class MediaTransferProtocolDaemonClient {
public:
// A callback to be called when DBus method call fails.
typedef base::Callback<void()> ErrorCallback;
// A callback to handle the result of EnumerateAutoMountableDevices.
// The argument is the enumerated storage names.
typedef base::Callback<void(const std::vector<std::string>& storage_names)
> EnumerateStoragesCallback;
// A callback to handle the result of GetStorageInfo.
// The argument is the information about the specified storage.
typedef base::Callback<void(const MtpStorageInfo& storage_info)
> GetStorageInfoCallback;
// A callback to handle the result of OpenStorage.
// The argument is the returned handle.
typedef base::Callback<void(const std::string& handle)> OpenStorageCallback;
// A callback to handle the result of CloseStorage.
typedef base::Callback<void()> CloseStorageCallback;
// A callback to handle the result of ReadDirectoryByPath/Id.
// The argument is a vector of file entries.
typedef base::Callback<void(const std::vector<MtpFileEntry>& file_entries)
> ReadDirectoryCallback;
// A callback to handle the result of ReadFileChunkByPath/Id.
// The argument is a string containing the file data.
typedef base::Callback<void(const std::string& data)> ReadFileCallback;
// A callback to handle the result of GetFileInfoByPath/Id.
// The argument is a file entry.
typedef base::Callback<void(const MtpFileEntry& file_entry)
> GetFileInfoCallback;
// A callback to handle storage attach/detach events.
// The first argument is true for attach, false for detach.
// The second argument is the storage name.
typedef base::Callback<void(bool is_attach,
const std::string& storage_name)
> MTPStorageEventHandler;
virtual ~MediaTransferProtocolDaemonClient();
// Calls EnumerateStorages method. |callback| is called after the
// method call succeeds, otherwise, |error_callback| is called.
virtual void EnumerateStorages(
const EnumerateStoragesCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls GetStorageInfo method. |callback| is called after the method call
// succeeds, otherwise, |error_callback| is called.
virtual void GetStorageInfo(const std::string& storage_name,
const GetStorageInfoCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls OpenStorage method. |callback| is called after the method call
// succeeds, otherwise, |error_callback| is called.
// OpenStorage returns a handle in |callback|.
virtual void OpenStorage(const std::string& storage_name,
const std::string& mode,
const OpenStorageCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls CloseStorage method. |callback| is called after the method call
// succeeds, otherwise, |error_callback| is called.
// |handle| comes from a OpenStorageCallback.
virtual void CloseStorage(const std::string& handle,
const CloseStorageCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls ReadDirectoryByPath method. |callback| is called after the method
// call succeeds, otherwise, |error_callback| is called.
virtual void ReadDirectoryByPath(const std::string& handle,
const std::string& path,
const ReadDirectoryCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls ReadDirectoryById method. |callback| is called after the method
// call succeeds, otherwise, |error_callback| is called.
// |file_id| is a MTP-device specific id for a file.
virtual void ReadDirectoryById(const std::string& handle,
uint32 file_id,
const ReadDirectoryCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls ReadFileChunkByPath method. |callback| is called after the method
// call succeeds, otherwise, |error_callback| is called.
// |bytes_to_read| cannot exceed 1 MiB.
virtual void ReadFileChunkByPath(const std::string& handle,
const std::string& path,
uint32 offset,
uint32 bytes_to_read,
const ReadFileCallback& callback,
const ErrorCallback& error_callback) = 0;
// TODO(thestig) Remove this in the near future if we don't see anyone using
// it.
// Calls ReadFilePathById method. |callback| is called after the method call
// succeeds, otherwise, |error_callback| is called.
// |file_id| is a MTP-device specific id for a file.
// |bytes_to_read| cannot exceed 1 MiB.
virtual void ReadFileChunkById(const std::string& handle,
uint32 file_id,
uint32 offset,
uint32 bytes_to_read,
const ReadFileCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls GetFileInfoByPath method. |callback| is called after the method
// call succeeds, otherwise, |error_callback| is called.
virtual void GetFileInfoByPath(const std::string& handle,
const std::string& path,
const GetFileInfoCallback& callback,
const ErrorCallback& error_callback) = 0;
// Calls GetFileInfoById method. |callback| is called after the method
// call succeeds, otherwise, |error_callback| is called.
// |file_id| is a MTP-device specific id for a file.
virtual void GetFileInfoById(const std::string& handle,
uint32 file_id,
const GetFileInfoCallback& callback,
const ErrorCallback& error_callback) = 0;
// Registers given callback for events.
// |storage_event_handler| is called when a mtp storage attach or detach
// signal is received.
virtual void SetUpConnections(const MTPStorageEventHandler& handler) = 0;
// Factory function, creates a new instance and returns ownership.
// For normal usage, set |is_stub| to false.
static MediaTransferProtocolDaemonClient* Create(dbus::Bus* bus,
bool is_stub);
protected:
// Create() should be used instead.
MediaTransferProtocolDaemonClient();
private:
DISALLOW_COPY_AND_ASSIGN(MediaTransferProtocolDaemonClient);
};
} // namespace chrome
#endif // CHROME_BROWSER_MEDIA_TRANSFER_PROTOCOL_MEDIA_TRANSFER_PROTOCOL_DAEMON_CLIENT_H_
| bsd-3-clause |
darkenk/vixl | test/traces/a64/sim-pmull2-8h-trace-a64.h | 25857 | // Copyright 2015, ARM Limited
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ARM Limited nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---------------------------------------------------------------------
// This file is auto generated using tools/generate_simulator_traces.py.
//
// PLEASE DO NOT EDIT.
// ---------------------------------------------------------------------
#ifndef VIXL_SIM_PMULL2_8H_TRACE_A64_H_
#define VIXL_SIM_PMULL2_8H_TRACE_A64_H_
const uint16_t kExpected_NEON_pmull2_8H[] = {
0x4005, 0x4444, 0x5050, 0x5540, 0x5551, 0x5554, 0x5555, 0x0000,
0x54fe, 0x7878, 0x4620, 0x5658, 0x5456, 0x55aa, 0x0000, 0x0000,
0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000,
0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000,
0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000,
0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000,
0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000,
0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000,
0x0083, 0x0154, 0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000,
0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000,
0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000,
0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000,
0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000,
0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000,
0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000,
0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000,
0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000,
0x4103, 0x5454, 0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000,
0x4086, 0x54fe, 0x7878, 0x4620, 0x5658, 0x5456, 0x55aa, 0x0000,
0x54fe, 0x7878, 0x4620, 0x5658, 0x5456, 0x55aa, 0x0000, 0x0000,
0x4444, 0x5050, 0x5540, 0x5551, 0x5554, 0x5555, 0x0000, 0x0001,
0x7878, 0x4620, 0x5658, 0x5456, 0x55aa, 0x0000, 0x0000, 0x0002,
0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008,
0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033,
0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055,
0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d,
0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000, 0x007e,
0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f,
0x0154, 0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080,
0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081,
0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082,
0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083,
0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa,
0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc,
0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8,
0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd,
0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe,
0x5454, 0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff,
0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000,
0x7878, 0x4620, 0x5658, 0x5456, 0x55aa, 0x0000, 0x0000, 0x0002,
0x5050, 0x5540, 0x5551, 0x5554, 0x5555, 0x0000, 0x0001, 0x0004,
0x4620, 0x5658, 0x5456, 0x55aa, 0x0000, 0x0000, 0x0002, 0x0010,
0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008, 0x0066,
0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa,
0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa,
0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc,
0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000, 0x007e, 0x00fe,
0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100,
0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102,
0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104,
0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106,
0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154,
0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198,
0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0,
0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa,
0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc,
0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe,
0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000,
0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008,
0x4620, 0x5658, 0x5456, 0x55aa, 0x0000, 0x0000, 0x0002, 0x0010,
0x5540, 0x5551, 0x5554, 0x5555, 0x0000, 0x0001, 0x0004, 0x0040,
0x5658, 0x5456, 0x55aa, 0x0000, 0x0000, 0x0002, 0x0010, 0x0198,
0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8,
0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8,
0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0,
0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8,
0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000, 0x007e, 0x00fe, 0x0400,
0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408,
0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410,
0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418,
0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106, 0x0550,
0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660,
0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0,
0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8,
0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0,
0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8,
0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000,
0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033,
0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008, 0x0066,
0x5658, 0x5456, 0x55aa, 0x0000, 0x0000, 0x0002, 0x0010, 0x0198,
0x5551, 0x5554, 0x5555, 0x0000, 0x0001, 0x0004, 0x0040, 0x0505,
0x5456, 0x55aa, 0x0000, 0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f,
0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7,
0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2,
0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891,
0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980,
0x07e8, 0x1122, 0x3333, 0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3,
0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408, 0x19e6,
0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410, 0x19d5,
0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e,
0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106, 0x0550, 0x1414,
0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660, 0x1188,
0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177,
0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122,
0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111,
0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000,
0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055,
0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa,
0x5750, 0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8,
0x5456, 0x55aa, 0x0000, 0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f,
0x5554, 0x5555, 0x0000, 0x0001, 0x0004, 0x0040, 0x0505, 0x1111,
0x55aa, 0x0000, 0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919,
0x0000, 0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6,
0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3,
0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80,
0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5,
0x1122, 0x3333, 0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a,
0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f,
0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410, 0x19d5, 0x2222,
0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c,
0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106, 0x0550, 0x1414, 0x3298,
0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660, 0x1188, 0x3399,
0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366,
0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333,
0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000,
0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d,
0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa,
0x57a8, 0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8,
0x54ab, 0x0000, 0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7,
0x55aa, 0x0000, 0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919,
0x5555, 0x0000, 0x0001, 0x0004, 0x0040, 0x0505, 0x1111, 0x1551,
0x0000, 0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6,
0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab,
0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80,
0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd,
0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a,
0x3333, 0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07,
0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232,
0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc,
0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58,
0x7f80, 0x0000, 0x0082, 0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1,
0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660, 0x1188, 0x3399, 0x2b56,
0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b,
0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000,
0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000, 0x007e,
0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc,
0x0000, 0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0,
0x0000, 0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2,
0x0000, 0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6,
0x0000, 0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6,
0x0000, 0x0001, 0x0004, 0x0040, 0x0505, 0x1111, 0x1551, 0x1554,
0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a,
0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00,
0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e,
0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc,
0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82,
0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc,
0x0000, 0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288,
0x0000, 0x0080, 0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50,
0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6,
0x0000, 0x0082, 0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54,
0x0000, 0x0083, 0x0154, 0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a,
0x0083, 0x0154, 0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000,
0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f,
0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000, 0x007e, 0x00fe,
0x00f8, 0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8,
0x00fd, 0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891,
0x00fe, 0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3,
0x00ff, 0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab,
0x0000, 0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a,
0x0001, 0x0004, 0x0040, 0x0505, 0x1111, 0x1551, 0x1554, 0x1555,
0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80,
0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff,
0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e,
0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01,
0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366,
0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244,
0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8,
0x0080, 0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b,
0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa,
0x0082, 0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5,
0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000,
0x0154, 0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080,
0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100,
0x01f0, 0x07e8, 0x1122, 0x3333, 0x0000, 0x007e, 0x00fe, 0x0400,
0x01fa, 0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980,
0x01fc, 0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80,
0x01fe, 0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80,
0x0000, 0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00,
0x0002, 0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80,
0x0004, 0x0040, 0x0505, 0x1111, 0x1551, 0x1554, 0x1555, 0x4000,
0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080,
0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100,
0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180,
0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500,
0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600,
0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00,
0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80,
0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00,
0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80,
0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000,
0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081,
0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102,
0x07c0, 0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408,
0x07e8, 0x1122, 0x3333, 0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3,
0x07f0, 0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5,
0x07f8, 0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd,
0x0000, 0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e,
0x0008, 0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff,
0x0010, 0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080,
0x0040, 0x0505, 0x1111, 0x1551, 0x1554, 0x1555, 0x4000, 0x4001,
0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182,
0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103,
0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa,
0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc,
0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8,
0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d,
0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe,
0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f,
0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000,
0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082,
0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104,
0x1188, 0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410,
0x1177, 0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408, 0x19e6,
0x1122, 0x3333, 0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a,
0x1111, 0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a,
0x0000, 0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc,
0x0033, 0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e,
0x0066, 0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100,
0x0198, 0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182,
0x0505, 0x1111, 0x1551, 0x1554, 0x1555, 0x4000, 0x4001, 0x4004,
0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182, 0x4086,
0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454,
0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798,
0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0,
0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a,
0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc,
0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e,
0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000,
0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083,
0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106,
0x3298, 0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418,
0x3399, 0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410, 0x19d5,
0x3366, 0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f,
0x3333, 0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07,
0x0000, 0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82,
0x0055, 0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01,
0x00aa, 0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180,
0x02a8, 0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103,
0x0f0f, 0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182, 0x4086,
0x1111, 0x1551, 0x1554, 0x1555, 0x4000, 0x4001, 0x4004, 0x4005,
0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe,
0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454, 0x6754,
0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08,
0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87,
0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02,
0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81,
0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000,
0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa,
0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154,
0x2a58, 0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106, 0x0550,
0x2bd1, 0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e,
0x2b56, 0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410, 0x19d5, 0x2222,
0x2b2b, 0x0000, 0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232,
0x0000, 0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc,
0x007d, 0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366,
0x00fa, 0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500,
0x03e8, 0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa,
0x08f7, 0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454,
0x1919, 0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe,
0x1551, 0x1554, 0x1555, 0x4000, 0x4001, 0x4004, 0x4005, 0x4444,
0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe, 0x7878,
0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454, 0x6754, 0x6530,
0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732,
0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc,
0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666,
0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000,
0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc,
0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198,
0x2b50, 0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660,
0x2ad6, 0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106, 0x0550, 0x1414,
0x2a54, 0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c,
0x2a2a, 0x0000, 0x0080, 0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc,
0x0000, 0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288,
0x007e, 0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244,
0x00fc, 0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600,
0x03f0, 0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc,
0x08a2, 0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798,
0x19e6, 0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454, 0x6754,
0x15d6, 0x152a, 0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe, 0x7878,
0x1554, 0x1555, 0x4000, 0x4001, 0x4004, 0x4005, 0x4444, 0x5050,
0x152a, 0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe, 0x7878, 0x4620,
0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454, 0x6754, 0x6530, 0x45dc,
0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488,
0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444,
0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000,
0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8,
0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0,
0x2ba8, 0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0,
0x2a2b, 0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660, 0x1188,
0x2aaa, 0x7f80, 0x0000, 0x0082, 0x0106, 0x0550, 0x1414, 0x3298,
0x2ad5, 0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58,
0x0000, 0x0080, 0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50,
0x007f, 0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8,
0x00fe, 0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00,
0x03f8, 0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8,
0x0891, 0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0,
0x19b3, 0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08,
0x15ab, 0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454, 0x6754, 0x6530,
0x152a, 0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe, 0x7878, 0x4620,
0x1555, 0x4000, 0x4001, 0x4004, 0x4005, 0x4444, 0x5050, 0x5540,
0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe, 0x7878, 0x4620, 0x5658,
0x3fff, 0x4100, 0x4103, 0x5454, 0x6754, 0x6530, 0x45dc, 0x5750,
0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8,
0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000,
0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd,
0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa,
0x7c00, 0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8,
0x7e80, 0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177,
0x7f00, 0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660, 0x1188, 0x3399,
0x7f80, 0x0000, 0x0082, 0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1,
0x0000, 0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6,
0x0080, 0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b,
0x0100, 0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80,
0x0400, 0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d,
0x1980, 0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a,
0x2a80, 0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87,
0x3e80, 0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732,
0x3f00, 0x3fff, 0x4100, 0x4103, 0x5454, 0x6754, 0x6530, 0x45dc,
0x3f80, 0x4080, 0x4182, 0x4086, 0x54fe, 0x7878, 0x4620, 0x5658,
0x4000, 0x4001, 0x4004, 0x4005, 0x4444, 0x5050, 0x5540, 0x5551,
0x4080, 0x4182, 0x4086, 0x54fe, 0x7878, 0x4620, 0x5658, 0x5456,
0x4100, 0x4103, 0x5454, 0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab,
0x4103, 0x5454, 0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000,
0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe,
0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc,
0x7cf8, 0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0,
0x7e7d, 0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122,
0x7ffe, 0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366,
0x7f7f, 0x0000, 0x0083, 0x0154, 0x0660, 0x1188, 0x3399, 0x2b56,
0x0000, 0x0082, 0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54,
0x0081, 0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa,
0x0102, 0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00,
0x0408, 0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe,
0x19b3, 0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc,
0x2ad5, 0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02,
0x3efd, 0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc,
0x3f7e, 0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488,
0x3fff, 0x4100, 0x4103, 0x5454, 0x6754, 0x6530, 0x45dc, 0x5750,
0x4080, 0x4182, 0x4086, 0x54fe, 0x7878, 0x4620, 0x5658, 0x5456,
0x4001, 0x4004, 0x4005, 0x4444, 0x5050, 0x5540, 0x5551, 0x5554,
0x4182, 0x4086, 0x54fe, 0x7878, 0x4620, 0x5658, 0x5456, 0x55aa,
0x4086, 0x54fe, 0x7878, 0x4620, 0x5658, 0x5456, 0x55aa, 0x0000,
0x5454, 0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab, 0x0000, 0x00ff,
0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8, 0x0000, 0x00fe, 0x01fe,
0x7df0, 0x7f87, 0x66cc, 0x4444, 0x0000, 0x00fd, 0x01fc, 0x07f8,
0x7f7a, 0x7e02, 0x6666, 0x0000, 0x00f8, 0x01fa, 0x07f0, 0x1111,
0x7efc, 0x7e81, 0x0000, 0x00cc, 0x01f0, 0x07e8, 0x1122, 0x3333,
0x7e7e, 0x0000, 0x00aa, 0x0198, 0x07c0, 0x1177, 0x3366, 0x2b2b,
0x0000, 0x0083, 0x0154, 0x0660, 0x1188, 0x3399, 0x2b56, 0x2a2a,
0x0082, 0x0106, 0x0550, 0x1414, 0x3298, 0x2bd1, 0x2a54, 0x2ad5,
0x0104, 0x0418, 0x1e1e, 0x3c3c, 0x2a58, 0x2ad6, 0x2aaa, 0x7f80,
0x0410, 0x19d5, 0x2222, 0x23dc, 0x2b50, 0x2a2b, 0x7f00, 0x7f7f,
0x19e6, 0x2a7f, 0x3232, 0x2288, 0x2ba8, 0x7e80, 0x7ffe, 0x7e7e,
0x2a2a, 0x3e07, 0x33cc, 0x2244, 0x7c00, 0x7e7d, 0x7efc, 0x7e81,
0x3e7a, 0x3f82, 0x3366, 0x6600, 0x7cf8, 0x7f7a, 0x7e02, 0x6666,
0x3ffc, 0x3f01, 0x5500, 0x66cc, 0x7df0, 0x7f87, 0x66cc, 0x4444,
0x3f7e, 0x4180, 0x55aa, 0x6798, 0x7d08, 0x6732, 0x4488, 0x57a8,
0x4100, 0x4103, 0x5454, 0x6754, 0x6530, 0x45dc, 0x5750, 0x54ab,
0x4182, 0x4086, 0x54fe, 0x7878, 0x4620, 0x5658, 0x5456, 0x55aa,
0x4004, 0x4005, 0x4444, 0x5050, 0x5540, 0x5551, 0x5554, 0x5555,
};
const unsigned kExpectedCount_NEON_pmull2_8H = 361;
#endif // VIXL_SIM_PMULL2_8H_TRACE_A64_H_
| bsd-3-clause |
beni55/LambdaHack | GameDefinition/Content/ItemKindTemporary.hs | 2960 | -- | Temporary aspect pseudo-item definitions.
module Content.ItemKindTemporary ( temporaries ) where
import Data.Text (Text)
import Game.LambdaHack.Common.Color
import Game.LambdaHack.Common.Dice
import Game.LambdaHack.Common.Flavour
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.Msg
import Game.LambdaHack.Content.ItemKind
temporaries :: [ItemKind]
temporaries =
[tmpStrengthened, tmpWeakened, tmpProtected, tmpVulnerable, tmpFast20, tmpSlow10, tmpFarSighted, tmpKeenSmelling, tmpDrunk, tmpRegenerating, tmpPoisoned, tmpSlow10Resistant, tmpPoisonResistant]
tmpStrengthened, tmpWeakened, tmpProtected, tmpVulnerable, tmpFast20, tmpSlow10, tmpFarSighted, tmpKeenSmelling, tmpDrunk, tmpRegenerating, tmpPoisoned, tmpSlow10Resistant, tmpPoisonResistant :: ItemKind
-- The @name@ is be used in item description, so it should be an adjective
-- describing the temporary set of aspects.
tmpAs :: Text -> [Aspect Dice] -> ItemKind
tmpAs name aspects = ItemKind
{ isymbol = '+'
, iname = name
, ifreq = [(toGroupName name, 1), ("temporary conditions", 1)]
, iflavour = zipPlain [BrWhite]
, icount = 1
, irarity = [(1, 1)]
, iverbHit = "affect"
, iweight = 0
, iaspects = [Periodic, Timeout 0] -- activates and vanishes soon,
-- depending on initial timer setting
++ aspects
, ieffects = let tmp = Temporary $ "be no longer" <+> name
in [Recharging tmp, OnSmash tmp]
, ifeature = [Identified]
, idesc = ""
, ikit = []
}
tmpStrengthened = tmpAs "strengthened" [AddHurtMelee 20]
tmpWeakened = tmpAs "weakened" [AddHurtMelee (-20)]
tmpProtected = tmpAs "protected" [ AddArmorMelee 30
, AddArmorRanged 30 ]
tmpVulnerable = tmpAs "defenseless" [ AddArmorMelee (-30)
, AddArmorRanged (-30) ]
tmpFast20 = tmpAs "fast 20" [AddSpeed 20]
tmpSlow10 = tmpAs "slow 10" [AddSpeed (-10)]
tmpFarSighted = tmpAs "far-sighted" [AddSight 5]
tmpKeenSmelling = tmpAs "keen-smelling" [AddSmell 2]
tmpDrunk = tmpAs "drunk" [ AddHurtMelee 30 -- fury
, AddArmorMelee (-20)
, AddArmorRanged (-20)
, AddSight (-7)
]
tmpRegenerating =
let tmp = tmpAs "regenerating" []
in tmp { icount = 7 + d 5
, ieffects = Recharging (RefillHP 1) : ieffects tmp
}
tmpPoisoned =
let tmp = tmpAs "poisoned" []
in tmp { icount = 7 + d 5
, ieffects = Recharging (RefillHP (-1)) : ieffects tmp
}
tmpSlow10Resistant =
let tmp = tmpAs "slow resistant" []
in tmp { icount = 7 + d 5
, ieffects = Recharging (DropItem COrgan "slow 10" True) : ieffects tmp
}
tmpPoisonResistant =
let tmp = tmpAs "poison resistant" []
in tmp { icount = 7 + d 5
, ieffects = Recharging (DropItem COrgan "poisoned" True) : ieffects tmp
}
| bsd-3-clause |
cdcarter/Cumulus | scripts/make_clean_slds_resource.sh | 1830 | #!/usr/bin/env bash
clean_slds_files() {
rm -fv $1/assets/fonts/License-for-font.txt
rm -fv $1/assets/fonts/*.ttf
rm -fv $1/assets/fonts/webfonts/*.eot
rm -fv $1/assets/fonts/webfonts/*.svg
rm -fv $1/assets/fonts/webfonts/SalesforceSans-Thin.woff
rm -fv $1/assets/fonts/webfonts/SalesforceSans-Thin.woff2
rm -fv $1/assets/fonts/webfonts/SalesforceSans-ThinItalic.woff
rm -fv $1/assets/fonts/webfonts/SalesforceSans-ThinItalic.woff2
rm -fv $1/assets/icons/action/*.png
rm -fv $1/assets/icons/action-sprite/symbols.html
rm -fv $1/assets/icons/custom/*.png
rm -fv $1/assets/icons/custom-sprite/symbols.html
rm -fv $1/assets/icons/doctype/*.png
rm -fv $1/assets/icons/doctype-sprite/symbols.html
rm -fv $1/assets/icons/standard/*.png
rm -fv $1/assets/icons/standard-sprite/symbols.html
rm -fv $1/assets/icons/utility/*.png
rm -fv $1/assets/icons/utility-sprite/symbols.html
rm -fv $1/assets/icons/README
rm -fv $1/assets/icons/License-for-icons.txt
rm -fv $1/assets/images/License-for-images.txt
rm -fv $1/assets/styles/salesforce-lightning-design-system-ltng.css
rm -fv $1/assets/styles/salesforce-lightning-design-system-scoped.css
rm -fv $1/assets/styles/salesforce-lightning-design-system-vf.css
rm -fv $1/assets/styles/salesforce-lightning-design-system.css
rm -fv $1/README.md
rm -rfv $1/scss
rm -rfv $1/swatches
}
SLDS_TMPDIR=`mktemp -d -t sldsclean.XXXXXXXX`
unzip -d $SLDS_TMPDIR/0_12_2 salesforce-lightning-design-system-0.12.2.zip
unzip -d $SLDS_TMPDIR/1_0_3 salesforce-lightning-design-system-1.0.3.zip
clean_slds_files $SLDS_TMPDIR/0_12_2
clean_slds_files $SLDS_TMPDIR/1_0_3
rm -fv $SLDS_TMPDIR/1_0_3/package.json
SLDS_OUTDIR=`pwd`
pushd $SLDS_TMPDIR
zip -r $SLDS_OUTDIR/SLDS.resource 0_12_2 1_0_3
popd
| bsd-3-clause |
tsheasha/rocksdb | db/merge_helper.cc | 12636 | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "db/merge_helper.h"
#include <stdio.h>
#include <string>
#include "db/dbformat.h"
#include "rocksdb/comparator.h"
#include "rocksdb/db.h"
#include "rocksdb/merge_operator.h"
#include "table/internal_iterator.h"
#include "util/perf_context_imp.h"
#include "util/statistics.h"
namespace rocksdb {
Status MergeHelper::TimedFullMerge(const MergeOperator* merge_operator,
const Slice& key, const Slice* value,
const std::vector<Slice>& operands,
std::string* result, Logger* logger,
Statistics* statistics, Env* env,
Slice* result_operand) {
assert(merge_operator != nullptr);
if (operands.size() == 0) {
assert(value != nullptr && result != nullptr);
result->assign(value->data(), value->size());
return Status::OK();
}
bool success;
Slice tmp_result_operand(nullptr, 0);
const MergeOperator::MergeOperationInput merge_in(key, value, operands,
logger);
MergeOperator::MergeOperationOutput merge_out(*result, tmp_result_operand);
{
// Setup to time the merge
StopWatchNano timer(env, statistics != nullptr);
PERF_TIMER_GUARD(merge_operator_time_nanos);
// Do the merge
success = merge_operator->FullMergeV2(merge_in, &merge_out);
if (tmp_result_operand.data()) {
// FullMergeV2 result is an existing operand
if (result_operand != nullptr) {
*result_operand = tmp_result_operand;
} else {
result->assign(tmp_result_operand.data(), tmp_result_operand.size());
}
} else if (result_operand) {
*result_operand = Slice(nullptr, 0);
}
RecordTick(statistics, MERGE_OPERATION_TOTAL_TIME,
statistics ? timer.ElapsedNanos() : 0);
}
if (!success) {
RecordTick(statistics, NUMBER_MERGE_FAILURES);
return Status::Corruption("Error: Could not perform merge.");
}
return Status::OK();
}
// PRE: iter points to the first merge type entry
// POST: iter points to the first entry beyond the merge process (or the end)
// keys_, operands_ are updated to reflect the merge result.
// keys_ stores the list of keys encountered while merging.
// operands_ stores the list of merge operands encountered while merging.
// keys_[i] corresponds to operands_[i] for each i.
Status MergeHelper::MergeUntil(InternalIterator* iter,
RangeDelAggregator* range_del_agg,
const SequenceNumber stop_before,
const bool at_bottom) {
// Get a copy of the internal key, before it's invalidated by iter->Next()
// Also maintain the list of merge operands seen.
assert(HasOperator());
keys_.clear();
merge_context_.Clear();
assert(user_merge_operator_);
bool first_key = true;
// We need to parse the internal key again as the parsed key is
// backed by the internal key!
// Assume no internal key corruption as it has been successfully parsed
// by the caller.
// original_key_is_iter variable is just caching the information:
// original_key_is_iter == (iter->key().ToString() == original_key)
bool original_key_is_iter = true;
std::string original_key = iter->key().ToString();
// Important:
// orig_ikey is backed by original_key if keys_.empty()
// orig_ikey is backed by keys_.back() if !keys_.empty()
ParsedInternalKey orig_ikey;
ParseInternalKey(original_key, &orig_ikey);
Status s;
bool hit_the_next_user_key = false;
for (; iter->Valid(); iter->Next(), original_key_is_iter = false) {
ParsedInternalKey ikey;
assert(keys_.size() == merge_context_.GetNumOperands());
if (!ParseInternalKey(iter->key(), &ikey)) {
// stop at corrupted key
if (assert_valid_internal_key_) {
assert(!"Corrupted internal key not expected.");
return Status::Corruption("Corrupted internal key not expected.");
}
break;
} else if (first_key) {
assert(user_comparator_->Equal(ikey.user_key, orig_ikey.user_key));
first_key = false;
} else if (!user_comparator_->Equal(ikey.user_key, orig_ikey.user_key)) {
// hit a different user key, stop right here
hit_the_next_user_key = true;
break;
} else if (stop_before && ikey.sequence <= stop_before) {
// hit an entry that's visible by the previous snapshot, can't touch that
break;
}
// At this point we are guaranteed that we need to process this key.
assert(IsValueType(ikey.type));
if (ikey.type != kTypeMerge) {
// hit a put/delete/single delete
// => merge the put value or a nullptr with operands_
// => store result in operands_.back() (and update keys_.back())
// => change the entry type to kTypeValue for keys_.back()
// We are done! Success!
// If there are no operands, just return the Status::OK(). That will cause
// the compaction iterator to write out the key we're currently at, which
// is the put/delete we just encountered.
if (keys_.empty()) {
return Status::OK();
}
// TODO(noetzli) If the merge operator returns false, we are currently
// (almost) silently dropping the put/delete. That's probably not what we
// want.
const Slice val = iter->value();
const Slice* val_ptr = (kTypeValue == ikey.type) ? &val : nullptr;
std::string merge_result;
s = TimedFullMerge(user_merge_operator_, ikey.user_key, val_ptr,
merge_context_.GetOperands(), &merge_result, logger_,
stats_, env_);
// We store the result in keys_.back() and operands_.back()
// if nothing went wrong (i.e.: no operand corruption on disk)
if (s.ok()) {
// The original key encountered
original_key = std::move(keys_.back());
orig_ikey.type = kTypeValue;
UpdateInternalKey(&original_key, orig_ikey.sequence, orig_ikey.type);
keys_.clear();
merge_context_.Clear();
keys_.emplace_front(std::move(original_key));
merge_context_.PushOperand(merge_result);
}
// move iter to the next entry
iter->Next();
return s;
} else {
// hit a merge
// => if there is a compaction filter, apply it.
// => check for range tombstones covering the operand
// => merge the operand into the front of the operands_ list
// if not filtered
// => then continue because we haven't yet seen a Put/Delete.
//
// Keep queuing keys and operands until we either meet a put / delete
// request or later did a partial merge.
Slice value_slice = iter->value();
// add an operand to the list if:
// 1) it's included in one of the snapshots. in that case we *must* write
// it out, no matter what compaction filter says
// 2) it's not filtered by a compaction filter
if ((ikey.sequence <= latest_snapshot_ ||
!FilterMerge(orig_ikey.user_key, value_slice)) &&
(range_del_agg == nullptr ||
!range_del_agg->ShouldDelete(iter->key()))) {
if (original_key_is_iter) {
// this is just an optimization that saves us one memcpy
keys_.push_front(std::move(original_key));
} else {
keys_.push_front(iter->key().ToString());
}
if (keys_.size() == 1) {
// we need to re-anchor the orig_ikey because it was anchored by
// original_key before
ParseInternalKey(keys_.back(), &orig_ikey);
}
merge_context_.PushOperand(value_slice,
iter->IsValuePinned() /* operand_pinned */);
}
}
}
if (merge_context_.GetNumOperands() == 0) {
// we filtered out all the merge operands
return Status::OK();
}
// We are sure we have seen this key's entire history if we are at the
// last level and exhausted all internal keys of this user key.
// NOTE: !iter->Valid() does not necessarily mean we hit the
// beginning of a user key, as versions of a user key might be
// split into multiple files (even files on the same level)
// and some files might not be included in the compaction/merge.
//
// There are also cases where we have seen the root of history of this
// key without being sure of it. Then, we simply miss the opportunity
// to combine the keys. Since VersionSet::SetupOtherInputs() always makes
// sure that all merge-operands on the same level get compacted together,
// this will simply lead to these merge operands moving to the next level.
//
// So, we only perform the following logic (to merge all operands together
// without a Put/Delete) if we are certain that we have seen the end of key.
bool surely_seen_the_beginning = hit_the_next_user_key && at_bottom;
if (surely_seen_the_beginning) {
// do a final merge with nullptr as the existing value and say
// bye to the merge type (it's now converted to a Put)
assert(kTypeMerge == orig_ikey.type);
assert(merge_context_.GetNumOperands() >= 1);
assert(merge_context_.GetNumOperands() == keys_.size());
std::string merge_result;
s = TimedFullMerge(user_merge_operator_, orig_ikey.user_key, nullptr,
merge_context_.GetOperands(), &merge_result, logger_,
stats_, env_);
if (s.ok()) {
// The original key encountered
// We are certain that keys_ is not empty here (see assertions couple of
// lines before).
original_key = std::move(keys_.back());
orig_ikey.type = kTypeValue;
UpdateInternalKey(&original_key, orig_ikey.sequence, orig_ikey.type);
keys_.clear();
merge_context_.Clear();
keys_.emplace_front(std::move(original_key));
merge_context_.PushOperand(merge_result);
}
} else {
// We haven't seen the beginning of the key nor a Put/Delete.
// Attempt to use the user's associative merge function to
// merge the stacked merge operands into a single operand.
//
// TODO(noetzli) The docblock of MergeUntil suggests that a successful
// partial merge returns Status::OK(). Should we change the status code
// after a successful partial merge?
s = Status::MergeInProgress();
if (merge_context_.GetNumOperands() >= 2 &&
merge_context_.GetNumOperands() >= min_partial_merge_operands_) {
bool merge_success = false;
std::string merge_result;
{
StopWatchNano timer(env_, stats_ != nullptr);
PERF_TIMER_GUARD(merge_operator_time_nanos);
merge_success = user_merge_operator_->PartialMergeMulti(
orig_ikey.user_key,
std::deque<Slice>(merge_context_.GetOperands().begin(),
merge_context_.GetOperands().end()),
&merge_result, logger_);
RecordTick(stats_, MERGE_OPERATION_TOTAL_TIME,
stats_ ? timer.ElapsedNanosSafe() : 0);
}
if (merge_success) {
// Merging of operands (associative merge) was successful.
// Replace operands with the merge result
merge_context_.Clear();
merge_context_.PushOperand(merge_result);
keys_.erase(keys_.begin(), keys_.end() - 1);
}
}
}
return s;
}
MergeOutputIterator::MergeOutputIterator(const MergeHelper* merge_helper)
: merge_helper_(merge_helper) {
it_keys_ = merge_helper_->keys().rend();
it_values_ = merge_helper_->values().rend();
}
void MergeOutputIterator::SeekToFirst() {
const auto& keys = merge_helper_->keys();
const auto& values = merge_helper_->values();
assert(keys.size() == values.size());
it_keys_ = keys.rbegin();
it_values_ = values.rbegin();
}
void MergeOutputIterator::Next() {
++it_keys_;
++it_values_;
}
bool MergeHelper::FilterMerge(const Slice& user_key, const Slice& value_slice) {
if (compaction_filter_ == nullptr) {
return false;
}
if (stats_ != nullptr) {
filter_timer_.Start();
}
bool to_delete =
compaction_filter_->FilterMergeOperand(level_, user_key, value_slice);
total_filter_time_ += filter_timer_.ElapsedNanosSafe();
return to_delete;
}
} // namespace rocksdb
| bsd-3-clause |
scheib/chromium | content/browser/interest_group/storage_interest_group.cc | 966 | // Copyright 2021 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 "content/browser/interest_group/storage_interest_group.h"
#include "content/services/auction_worklet/public/mojom/bidder_worklet.mojom.h"
namespace content {
StorageInterestGroup::StorageInterestGroup() = default;
StorageInterestGroup::StorageInterestGroup(
auction_worklet::mojom::BiddingInterestGroupPtr group) {
this->bidding_group = std::move(group);
}
StorageInterestGroup::StorageInterestGroup(StorageInterestGroup&&) = default;
StorageInterestGroup::~StorageInterestGroup() = default;
std::ostream& operator<<(std::ostream& out,
const StorageInterestGroup::KAnonymityData& kanon) {
return out << "KAnonymityData[key=`" << kanon.key << "`, k=" << kanon.k
<< ", last_updated=`" << kanon.last_updated << "`]";
}
} // namespace content
| bsd-3-clause |
UITools/saleor | saleor/product/migrations/0038_auto_20171129_0616.py | 383 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-29 12:16
from __future__ import unicode_literals
from django.contrib.postgres.operations import BtreeGinExtension
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0037_auto_20171124_0847'),
]
operations = [
BtreeGinExtension()
]
| bsd-3-clause |
hainm/pythran | third_party/boost/simd/include/functions/simd/insert.hpp | 196 | #ifndef BOOST_SIMD_INCLUDE_FUNCTIONS_SIMD_INSERT_HPP_INCLUDED
#define BOOST_SIMD_INCLUDE_FUNCTIONS_SIMD_INSERT_HPP_INCLUDED
#include <boost/simd/memory/include/functions/simd/insert.hpp>
#endif
| bsd-3-clause |
iamciera/IBAMR | ibtk/include/ibtk/private/LDataManager-inl.h | 9603 | // Filename: LDataManager-inl.h
// Created on 10 Dec 2009 by Boyce Griffith
//
// Copyright (c) 2002-2014, Boyce Griffith
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of The University of North Carolina nor the names of
// its contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef included_LDataManager_inl_h
#define included_LDataManager_inl_h
/////////////////////////////// INCLUDES /////////////////////////////////////
#include "ibtk/LDataManager.h"
#include "ibtk/LMesh.h"
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBTK
{
/////////////////////////////// PUBLIC ///////////////////////////////////////
inline const SAMRAI::hier::IntVector<NDIM>& LDataManager::getGhostCellWidth() const
{
return d_ghost_width;
} // getGhostCellWidth
inline const std::string& LDataManager::getDefaultInterpKernelFunction() const
{
return d_default_interp_kernel_fcn;
} // getDefaultInterpKernelFunction
inline const std::string& LDataManager::getDefaultSpreadKernelFunction() const
{
return d_default_spread_kernel_fcn;
} // getDefaultSpreadKernelFunction
inline bool LDataManager::levelContainsLagrangianData(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(level_number >= 0);
#endif
if (!(d_coarsest_ln <= level_number && d_finest_ln >= level_number))
{
return false;
}
else
{
return d_level_contains_lag_data[level_number];
}
} // levelContainsLagrangianData
inline unsigned int LDataManager::getNumberOfNodes(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(level_number >= 0);
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
return d_num_nodes[level_number];
} // getNumberOfNodes
inline unsigned int LDataManager::getNumberOfLocalNodes(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(level_number >= 0);
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
return static_cast<unsigned int>(d_local_lag_indices[level_number].size());
} // getNumberOfLocalNodes
inline unsigned int LDataManager::getNumberOfGhostNodes(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(level_number >= 0);
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
return static_cast<unsigned int>(d_nonlocal_lag_indices[level_number].size());
} // getNumberOfGhostNodes
inline unsigned int LDataManager::getGlobalNodeOffset(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(level_number >= 0);
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
return d_node_offset[level_number];
} // getGlobalNodeOffset
inline SAMRAI::tbox::Pointer<LMesh> LDataManager::getLMesh(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(level_number >= 0);
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
return d_lag_mesh[level_number];
} // getLMesh
inline SAMRAI::tbox::Pointer<LData> LDataManager::getLData(const std::string& quantity_name,
const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_lag_mesh_data[level_number].find(quantity_name) != d_lag_mesh_data[level_number].end());
TBOX_ASSERT(level_number >= 0);
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
TBOX_ASSERT(d_lag_mesh_data[level_number].count(quantity_name) > 0);
#endif
return d_lag_mesh_data[level_number].find(quantity_name)->second;
} // getLData
inline int LDataManager::getLNodePatchDescriptorIndex() const
{
return d_lag_node_index_current_idx;
} // getLNodePatchDescriptorIndex
inline int LDataManager::getWorkloadPatchDescriptorIndex() const
{
return d_workload_idx;
} // getWorkloadPatchDescriptorIndex
inline int LDataManager::getNodeCountPatchDescriptorIndex() const
{
return d_node_count_idx;
} // getNodeCountPatchDescriptorIndex
inline std::vector<std::string> LDataManager::getLagrangianStructureNames(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
std::vector<std::string> ret_val;
for (std::map<int, std::string>::const_iterator cit(d_strct_id_to_strct_name_map[level_number].begin());
cit != d_strct_id_to_strct_name_map[level_number].end();
++cit)
{
ret_val.push_back(cit->second);
}
return ret_val;
} // getLagrangianStructureNames
inline std::vector<int> LDataManager::getLagrangianStructureIDs(const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
std::vector<int> ret_val;
for (std::map<std::string, int>::const_iterator cit(d_strct_name_to_strct_id_map[level_number].begin());
cit != d_strct_name_to_strct_id_map[level_number].end();
++cit)
{
ret_val.push_back(cit->second);
}
return ret_val;
} // getLagrangianStructureIDs
inline int LDataManager::getLagrangianStructureID(const int lagrangian_index, const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
std::map<int, int>::const_iterator cit = d_last_lag_idx_to_strct_id_map[level_number].lower_bound(lagrangian_index);
if (UNLIKELY(cit == d_last_lag_idx_to_strct_id_map[level_number].end())) return -1;
const int strct_id = cit->second;
#if !defined(NDEBUG)
const std::pair<int, int>& idx_range = getLagrangianStructureIndexRange(strct_id, level_number);
TBOX_ASSERT(idx_range.first <= lagrangian_index && lagrangian_index < idx_range.second);
#endif
return strct_id;
} // getLagrangianStructureID
inline int LDataManager::getLagrangianStructureID(const std::string& structure_name, const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
std::map<std::string, int>::const_iterator cit = d_strct_name_to_strct_id_map[level_number].find(structure_name);
if (UNLIKELY(cit == d_strct_name_to_strct_id_map[level_number].end())) return -1;
return cit->second;
} // getLagrangianStructureID
inline std::string LDataManager::getLagrangianStructureName(const int structure_id, const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
std::map<int, std::string>::const_iterator cit = d_strct_id_to_strct_name_map[level_number].find(structure_id);
if (UNLIKELY(cit == d_strct_id_to_strct_name_map[level_number].end())) return std::string("UNKNOWN");
return cit->second;
} // getLagrangianStructureName
inline std::pair<int, int> LDataManager::getLagrangianStructureIndexRange(const int structure_id,
const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
std::map<int, std::pair<int, int> >::const_iterator cit =
d_strct_id_to_lag_idx_range_map[level_number].find(structure_id);
if (UNLIKELY(cit == d_strct_id_to_lag_idx_range_map[level_number].end())) return std::make_pair(-1, -1);
return cit->second;
} // getLagrangianStructureIndexRange
inline bool LDataManager::getLagrangianStructureIsActivated(const int structure_id, const int level_number) const
{
#if !defined(NDEBUG)
TBOX_ASSERT(d_coarsest_ln <= level_number && d_finest_ln >= level_number);
#endif
std::set<int>::const_iterator cit = d_inactive_strcts[level_number].getSet().find(structure_id);
return (cit == d_inactive_strcts[level_number].getSet().end());
} // getLagrangianStructureIsActivated
/////////////////////////////// PRIVATE //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
} // namespace IBTK
//////////////////////////////////////////////////////////////////////////////
#endif //#ifndef included_LDataManager_inl_h
| bsd-3-clause |
staranjeet/fjord | vendor/packages/translate-toolkit/translate/lang/af.py | 3846 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""This module represents the Afrikaans language.
.. seealso:: http://en.wikipedia.org/wiki/Afrikaans_language
"""
import re
from translate.lang import common
articlere = re.compile(r"'n\b")
class af(common.Common):
"""This class represents Afrikaans."""
validdoublewords = [u"u"]
punctuation = u"".join([common.Common.commonpunc, common.Common.quotes,
common.Common.miscpunc])
sentenceend = u".!?…"
sentencere = re.compile(r"""
(?s) # make . also match newlines
.*? # anything, but match non-greedy
[%s] # the puntuation for sentence ending
\s+ # the spacing after the puntuation
(?='n\s[A-Z]|[^'a-z\d]|'[^n])
# lookahead that next part starts with caps or 'n followed by caps
""" % sentenceend, re.VERBOSE
)
specialchars = u"ëïêôûáéíóúý"
def capsstart(cls, text):
"""Modify this for the indefinite article ('n)."""
match = articlere.search(text, 0, 20)
if match:
#construct a list of non-apostrophe punctuation:
nonapos = u"".join(cls.punctuation.split(u"'"))
stripped = text.lstrip().lstrip(nonapos)
match = articlere.match(stripped)
if match:
return common.Common.capsstart(stripped[match.end():])
return common.Common.capsstart(text)
capsstart = classmethod(capsstart)
cyr2lat = {
u"А": "A", u"а": "a",
u"Б": "B", u"б": "b",
u"В": "W", u"в": "w", # Different if at the end of a syllable see rule 2.
u"Г": "G", u"г": "g", # see rule 3 and 4
u"Д": "D", u"д": "d",
u"ДЖ": "Dj", u"дж": "dj",
u"Е": "Je", u"е": "je", # Sometimes e need to check when/why see rule 5.
u"Ё": "Jo", u"ё": "jo", # see rule 6
u"ЕЙ": "Ei", u"ей": "ei",
u"Ж": "Zj", u"ж": "zj",
u"З": "Z", u"з": "z",
u"И": "I", u"и": "i",
u"Й": "J", u"й": "j", # see rule 9 and 10
u"К": "K", u"к": "k", # see note 11
u"Л": "L", u"л": "l",
u"М": "M", u"м": "m",
u"Н": "N", u"н": "n",
u"О": "O", u"о": "o",
u"П": "P", u"п": "p",
u"Р": "R", u"р": "r",
u"С": "S", u"с": "s", # see note 12
u"Т": "T", u"т": "t",
u"У": "Oe", u"у": "oe",
u"Ф": "F", u"ф": "f",
u"Х": "Ch", u"х": "ch", # see rule 12
u"Ц": "Ts", u"ц": "ts",
u"Ч": "Tj", u"ч": "tj",
u"Ш": "Sj", u"ш": "sj",
u"Щ": "Sjtsj", u"щ": "sjtsj",
u"Ы": "I", u"ы": "i", # see note 13
u"Ъ": "", u"ъ": "", # See note 14
u"Ь": "", u"ь": "", # this letter is not in the AWS we assume it is left out as in the previous letter
u"Э": "E", u"э": "e",
u"Ю": "Joe", u"ю": "joe",
u"Я": "Ja", u"я": "ja",
}
"""Mapping of Cyrillic to Latin letters for transliteration in Afrikaans"""
cyr_vowels = u"аеёиоуыэюя"
def tranliterate_cyrillic(text):
"""Convert Cyrillic text to Latin according to the AWS transliteration rules."""
trans = u""
for i in text:
trans += cyr2lat.get(i, i)
return trans
| bsd-3-clause |
MarshedOut/android_external_pdfium | core/include/fpdfapi/fpdf_resource.h | 22806 | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef CORE_INCLUDE_FPDFAPI_FPDF_RESOURCE_H_
#define CORE_INCLUDE_FPDFAPI_FPDF_RESOURCE_H_
#include "../fxge/fx_font.h"
#include "fpdf_parser.h"
class CPDF_Font;
class CPDF_Type1Font;
class CPDF_TrueTypeFont;
class CPDF_CIDFont;
class CPDF_Type3Font;
class CPDF_FontEncoding;
class CPDF_CMap;
class CPDF_CID2UnicodeMap;
class CPDF_ColorSpace;
class CPDF_Color;
class CPDF_Function;
class CPDF_Pattern;
class CPDF_TilingPattern;
class CPDF_ShadingPattern;
class CPDF_Image;
class CPDF_Face;
class CPDF_ToUnicodeMap;
class CFX_SubstFont;
class CFX_Font;
class CPDF_RenderContext;
class CPDF_Form;
class CPDF_ImageObject;
class CFX_DIBitmap;
typedef struct FT_FaceRec_* FXFT_Face;
class CFX_CTTGSUBTable;
class CPDF_Page;
template <class ObjClass> class CPDF_CountedObject
{
public:
ObjClass m_Obj;
FX_DWORD m_nCount;
};
typedef CPDF_CountedObject<CPDF_Font*> CPDF_CountedFont;
typedef CPDF_CountedObject<CPDF_ColorSpace*> CPDF_CountedColorSpace;
typedef CPDF_CountedObject<CPDF_Pattern*> CPDF_CountedPattern;
typedef CPDF_CountedObject<CPDF_Image*> CPDF_CountedImage;
typedef CPDF_CountedObject<CPDF_IccProfile*> CPDF_CountedICCProfile;
typedef CPDF_CountedObject<CPDF_StreamAcc*> CPDF_CountedStreamAcc;
typedef CFX_MapPtrTemplate<CPDF_Dictionary*, CPDF_CountedFont*> CPDF_FontMap;
typedef CFX_MapPtrTemplate<CPDF_Object*, CPDF_CountedColorSpace*> CPDF_ColorSpaceMap;
typedef CFX_MapPtrTemplate<CPDF_Object*, CPDF_CountedPattern*> CPDF_PatternMap;
typedef CFX_MapPtrTemplate<FX_DWORD, CPDF_CountedImage*> CPDF_ImageMap;
typedef CFX_MapPtrTemplate<CPDF_Stream*, CPDF_CountedICCProfile*> CPDF_IccProfileMap;
typedef CFX_MapPtrTemplate<CPDF_Stream*, CPDF_CountedStreamAcc*> CPDF_FontFileMap;
#define PDFFONT_TYPE1 1
#define PDFFONT_TRUETYPE 2
#define PDFFONT_TYPE3 3
#define PDFFONT_CIDFONT 4
#define PDFFONT_FIXEDPITCH 1
#define PDFFONT_SERIF 2
#define PDFFONT_SYMBOLIC 4
#define PDFFONT_SCRIPT 8
#define PDFFONT_NONSYMBOLIC 32
#define PDFFONT_ITALIC 64
#define PDFFONT_ALLCAP 0x10000
#define PDFFONT_SMALLCAP 0x20000
#define PDFFONT_FORCEBOLD 0x40000
#define PDFFONT_USEEXTERNATTR 0x80000
FX_WCHAR PDF_UnicodeFromAdobeName(const FX_CHAR* name);
CFX_ByteString PDF_AdobeNameFromUnicode(FX_WCHAR unicode);
class CPDF_Font
{
public:
static CPDF_Font* CreateFontF(CPDF_Document* pDoc, CPDF_Dictionary* pFontDict);
static CPDF_Font* GetStockFont(CPDF_Document* pDoc, FX_BSTR fontname);
virtual ~CPDF_Font();
bool IsFontType(int fonttype) const { return fonttype == m_FontType; }
int GetFontType() const { return m_FontType; }
CFX_ByteString GetFontTypeName() const;
const CFX_ByteString& GetBaseFont() const
{
return m_BaseFont;
}
const CFX_SubstFont* GetSubstFont() const
{
return m_Font.GetSubstFont();
}
FX_DWORD GetFlags() const
{
return m_Flags;
}
virtual FX_BOOL IsVertWriting()const;
CPDF_Type1Font* GetType1Font() const
{
return m_FontType == PDFFONT_TYPE1 ? (CPDF_Type1Font*)(void*)this : NULL;
}
CPDF_TrueTypeFont* GetTrueTypeFont() const
{
return m_FontType == PDFFONT_TRUETYPE ? (CPDF_TrueTypeFont*)(void*)this : NULL;
}
CPDF_CIDFont* GetCIDFont() const
{
return (m_FontType == PDFFONT_CIDFONT) ? (CPDF_CIDFont*)(void*)this : NULL;
}
CPDF_Type3Font* GetType3Font() const
{
return (m_FontType == PDFFONT_TYPE3) ? (CPDF_Type3Font*)(void*)this : NULL;
}
FX_BOOL IsEmbedded() const
{
return m_FontType == PDFFONT_TYPE3 || m_pFontFile != NULL;
}
virtual FX_BOOL IsUnicodeCompatible() const
{
return FALSE;
}
CPDF_StreamAcc* GetFontFile() const
{
return m_pFontFile;
}
CPDF_Dictionary* GetFontDict() const
{
return m_pFontDict;
}
FX_BOOL IsStandardFont() const;
FXFT_Face GetFace() const
{
return m_Font.GetFace();
}
virtual FX_DWORD GetNextChar(FX_LPCSTR pString, int nStrLen, int& offset) const
{
if (offset < 0 || nStrLen < 1) {
return 0;
}
FX_BYTE ch = offset < nStrLen ? pString[offset++] : pString[nStrLen-1];
return static_cast<FX_DWORD>(ch);
}
virtual int CountChar(FX_LPCSTR pString, int size) const
{
return size;
}
void AppendChar(CFX_ByteString& str, FX_DWORD charcode) const;
virtual int AppendChar(FX_LPSTR buf, FX_DWORD charcode) const
{
*buf = (FX_CHAR)charcode;
return 1;
}
virtual int GetCharSize(FX_DWORD charcode) const
{
return 1;
}
virtual int GlyphFromCharCode(FX_DWORD charcode, FX_BOOL *pVertGlyph = NULL) = 0;
virtual int GlyphFromCharCodeExt(FX_DWORD charcode)
{
return GlyphFromCharCode(charcode);
}
CFX_WideString UnicodeFromCharCode(FX_DWORD charcode) const;
FX_DWORD CharCodeFromUnicode(FX_WCHAR Unicode) const;
CFX_CharMap* GetCharMap()
{
return m_pCharMap;
}
CFX_ByteString EncodeString(const CFX_WideString& str) const;
CFX_WideString DecodeString(const CFX_ByteString& str) const;
void GetFontBBox(FX_RECT& rect) const
{
rect = m_FontBBox;
}
int GetTypeAscent() const
{
return m_Ascent;
}
int GetTypeDescent() const
{
return m_Descent;
}
int GetItalicAngle() const
{
return m_ItalicAngle;
}
int GetStemV() const
{
return m_StemV;
}
int GetStringWidth(const FX_CHAR* pString, int size);
virtual int GetCharWidthF(FX_DWORD charcode, int level = 0) = 0;
virtual int GetCharTypeWidth(FX_DWORD charcode);
virtual void GetCharBBox(FX_DWORD charcode, FX_RECT& rect, int level = 0) = 0;
CPDF_Document* m_pDocument;
class CFX_PathData* LoadGlyphPath(FX_DWORD charcode, int dest_width = 0);
CFX_Font m_Font;
protected:
explicit CPDF_Font(int fonttype);
FX_BOOL Initialize();
FX_BOOL Load();
virtual FX_BOOL _Load() = 0;
virtual FX_WCHAR _UnicodeFromCharCode(FX_DWORD charcode) const = 0;
virtual FX_DWORD _CharCodeFromUnicode(FX_WCHAR Unicode) const = 0;
void LoadUnicodeMap();
void LoadPDFEncoding(CPDF_Object* pEncoding, int& iBaseEncoding,
CFX_ByteString*& pCharNames, FX_BOOL bEmbedded, FX_BOOL bTrueType);
void LoadFontDescriptor(CPDF_Dictionary*);
void LoadCharWidths(FX_WORD* pWidths);
void CheckFontMetrics();
CFX_CharMap* m_pCharMap;
CFX_ByteString m_BaseFont;
CPDF_StreamAcc* m_pFontFile;
CPDF_Dictionary* m_pFontDict;
CPDF_ToUnicodeMap* m_pToUnicodeMap;
FX_BOOL m_bToUnicodeLoaded;
int m_Flags;
FX_RECT m_FontBBox;
int m_StemV;
int m_Ascent;
int m_Descent;
int m_ItalicAngle;
private:
const int m_FontType;
};
#define PDFFONT_ENCODING_BUILTIN 0
#define PDFFONT_ENCODING_WINANSI 1
#define PDFFONT_ENCODING_MACROMAN 2
#define PDFFONT_ENCODING_MACEXPERT 3
#define PDFFONT_ENCODING_STANDARD 4
#define PDFFONT_ENCODING_ADOBE_SYMBOL 5
#define PDFFONT_ENCODING_ZAPFDINGBATS 6
#define PDFFONT_ENCODING_PDFDOC 7
#define PDFFONT_ENCODING_MS_SYMBOL 8
#define PDFFONT_ENCODING_UNICODE 9
class CPDF_FontEncoding
{
public:
CPDF_FontEncoding();
CPDF_FontEncoding(int PredefinedEncoding);
void LoadEncoding(CPDF_Object* pEncoding);
FX_BOOL IsIdentical(CPDF_FontEncoding* pAnother) const;
FX_WCHAR UnicodeFromCharCode(FX_BYTE charcode) const
{
return m_Unicodes[charcode];
}
int CharCodeFromUnicode(FX_WCHAR unicode) const;
void SetUnicode(FX_BYTE charcode, FX_WCHAR unicode)
{
m_Unicodes[charcode] = unicode;
}
CPDF_Object* Realize();
public:
FX_WCHAR m_Unicodes[256];
};
class CPDF_SimpleFont : public CPDF_Font
{
public:
explicit CPDF_SimpleFont(int fonttype);
~CPDF_SimpleFont() override;
CPDF_FontEncoding* GetEncoding()
{
return &m_Encoding;
}
virtual int GetCharWidthF(FX_DWORD charcode, int level = 0);
virtual void GetCharBBox(FX_DWORD charcode, FX_RECT& rect, int level = 0);
virtual int GlyphFromCharCode(FX_DWORD charcode, FX_BOOL *pVertGlyph = NULL);
virtual FX_BOOL IsUnicodeCompatible() const;
protected:
FX_BOOL LoadCommon();
void LoadSubstFont();
void LoadFaceMetrics();
virtual void LoadGlyphMap() = 0;
virtual FX_WCHAR _UnicodeFromCharCode(FX_DWORD charcode) const
{
return m_Encoding.UnicodeFromCharCode((FX_BYTE)charcode);
}
virtual FX_DWORD _CharCodeFromUnicode(FX_WCHAR Unicode) const
{
return m_Encoding.CharCodeFromUnicode(Unicode);
}
CPDF_FontEncoding m_Encoding;
FX_WORD m_GlyphIndex[256];
FX_WORD m_ExtGID[256];
CFX_ByteString* m_pCharNames;
int m_BaseEncoding;
FX_WORD m_CharWidth[256];
FX_SMALL_RECT m_CharBBox[256];
FX_BOOL m_bUseFontWidth;
void LoadCharMetrics(int charcode);
};
class CPDF_Type1Font : public CPDF_SimpleFont
{
public:
CPDF_Type1Font();
int GetBase14Font()
{
return m_Base14Font;
}
virtual int GlyphFromCharCodeExt(FX_DWORD charcode);
protected:
virtual FX_BOOL _Load();
int m_Base14Font;
virtual void LoadGlyphMap();
};
class CPDF_TrueTypeFont : public CPDF_SimpleFont
{
public:
CPDF_TrueTypeFont();
protected:
virtual FX_BOOL _Load();
virtual void LoadGlyphMap();
};
class CPDF_Type3Char
{
public:
CPDF_Type3Char();
~CPDF_Type3Char();
FX_BOOL LoadBitmap(CPDF_RenderContext* pContext);
FX_BOOL m_bColored;
FX_BOOL m_bPageRequired;
CPDF_Form* m_pForm;
CFX_AffineMatrix m_ImageMatrix;
CFX_DIBitmap* m_pBitmap;
int m_Width;
FX_RECT m_BBox;
};
class CPDF_Type3Font : public CPDF_SimpleFont
{
public:
CPDF_Type3Font();
~CPDF_Type3Font() override;
void SetPageResources(CPDF_Dictionary* pResources)
{
m_pPageResources = pResources;
}
CPDF_Type3Char* LoadChar(FX_DWORD charcode, int level = 0);
virtual int GetCharWidthF(FX_DWORD charcode, int level = 0);
virtual int GetCharTypeWidth(FX_DWORD charcode)
{
return GetCharWidthF(charcode);
}
virtual void GetCharBBox(FX_DWORD charcode, FX_RECT& rect, int level = 0);
CFX_AffineMatrix& GetFontMatrix()
{
return m_FontMatrix;
}
void CheckType3FontMetrics();
private:
virtual FX_BOOL _Load();
virtual void LoadGlyphMap() {}
int m_CharWidthL[256];
CPDF_Dictionary* m_pCharProcs;
CPDF_Dictionary* m_pPageResources;
CPDF_Dictionary* m_pFontResources;
CFX_MapPtrToPtr m_CacheMap;
CFX_MapPtrToPtr m_DeletedMap;
protected:
CFX_AffineMatrix m_FontMatrix;
};
#define CIDSET_UNKNOWN 0
#define CIDSET_GB1 1
#define CIDSET_CNS1 2
#define CIDSET_JAPAN1 3
#define CIDSET_KOREA1 4
#define CIDSET_UNICODE 5
#define NUMBER_OF_CIDSETS 6
class CPDF_CIDFont : public CPDF_Font
{
public:
CPDF_CIDFont();
virtual ~CPDF_CIDFont();
FX_BOOL LoadGB2312();
virtual int GlyphFromCharCode(FX_DWORD charcode, FX_BOOL *pVertGlyph = NULL);
virtual int GetCharWidthF(FX_DWORD charcode, int level = 0);
virtual void GetCharBBox(FX_DWORD charcode, FX_RECT& rect, int level = 0);
FX_WORD CIDFromCharCode(FX_DWORD charcode) const;
FX_BOOL IsTrueType()
{
return !m_bType1;
}
virtual FX_DWORD GetNextChar(FX_LPCSTR pString, int nStrLen, int& offset) const override;
virtual int CountChar(FX_LPCSTR pString, int size) const;
virtual int AppendChar(FX_LPSTR str, FX_DWORD charcode) const;
virtual int GetCharSize(FX_DWORD charcode) const;
int GetCharset() const
{
return m_Charset;
}
FX_LPCBYTE GetCIDTransform(FX_WORD CID) const;
virtual FX_BOOL IsVertWriting() const;
short GetVertWidth(FX_WORD CID) const;
void GetVertOrigin(FX_WORD CID, short& vx, short& vy) const;
virtual FX_BOOL IsUnicodeCompatible() const;
virtual FX_BOOL IsFontStyleFromCharCode(FX_DWORD charcode) const;
protected:
friend class CPDF_Font;
virtual FX_BOOL _Load();
virtual FX_WCHAR _UnicodeFromCharCode(FX_DWORD charcode) const;
virtual FX_DWORD _CharCodeFromUnicode(FX_WCHAR Unicode) const;
int GetGlyphIndex(FX_DWORD unicodeb, FX_BOOL *pVertGlyph);
CPDF_CMap* m_pCMap;
CPDF_CMap* m_pAllocatedCMap;
CPDF_CID2UnicodeMap* m_pCID2UnicodeMap;
int m_Charset;
FX_BOOL m_bType1;
CPDF_StreamAcc* m_pCIDToGIDMap;
FX_BOOL m_bCIDIsGID;
FX_WORD m_DefaultWidth;
FX_WORD* m_pAnsiWidths;
FX_SMALL_RECT m_CharBBox[256];
CFX_DWordArray m_WidthList;
short m_DefaultVY;
short m_DefaultW1;
CFX_DWordArray m_VertMetrics;
void LoadMetricsArray(CPDF_Array* pArray, CFX_DWordArray& result, int nElements);
void LoadSubstFont();
FX_BOOL m_bAdobeCourierStd;
CFX_CTTGSUBTable* m_pTTGSUBTable;
};
#define PDFCS_DEVICEGRAY 1
#define PDFCS_DEVICERGB 2
#define PDFCS_DEVICECMYK 3
#define PDFCS_CALGRAY 4
#define PDFCS_CALRGB 5
#define PDFCS_LAB 6
#define PDFCS_ICCBASED 7
#define PDFCS_SEPARATION 8
#define PDFCS_DEVICEN 9
#define PDFCS_INDEXED 10
#define PDFCS_PATTERN 11
class CPDF_ColorSpace
{
public:
static CPDF_ColorSpace* GetStockCS(int Family);
static CPDF_ColorSpace* Load(CPDF_Document* pDoc, CPDF_Object* pCSObj);
void ReleaseCS();
int GetBufSize() const;
FX_FLOAT* CreateBuf();
void GetDefaultColor(FX_FLOAT* buf) const;
int CountComponents() const
{
return m_nComponents;
}
int GetFamily() const
{
return m_Family;
}
virtual void GetDefaultValue(int iComponent, FX_FLOAT& value, FX_FLOAT& min, FX_FLOAT& max) const
{
value = 0;
min = 0;
max = 1.0f;
}
FX_BOOL sRGB() const;
virtual FX_BOOL GetRGB(FX_FLOAT* pBuf, FX_FLOAT& R, FX_FLOAT& G, FX_FLOAT& B) const = 0;
virtual FX_BOOL SetRGB(FX_FLOAT* pBuf, FX_FLOAT R, FX_FLOAT G, FX_FLOAT B) const
{
return FALSE;
}
FX_BOOL GetCMYK(FX_FLOAT* pBuf, FX_FLOAT& c, FX_FLOAT& m, FX_FLOAT& y, FX_FLOAT& k) const;
FX_BOOL SetCMYK(FX_FLOAT* pBuf, FX_FLOAT c, FX_FLOAT m, FX_FLOAT y, FX_FLOAT k) const;
virtual void TranslateImageLine(FX_LPBYTE dest_buf, FX_LPCBYTE src_buf, int pixels,
int image_width, int image_height, FX_BOOL bTransMask = FALSE) const;
CPDF_Array*& GetArray()
{
return m_pArray;
}
int GetMaxIndex() const;
virtual CPDF_ColorSpace* GetBaseCS() const
{
return NULL;
}
virtual void EnableStdConversion(FX_BOOL bEnabled);
CPDF_Document* m_pDocument;
protected:
CPDF_ColorSpace();
virtual ~CPDF_ColorSpace() {}
virtual FX_BOOL v_Load(CPDF_Document* pDoc, CPDF_Array* pArray)
{
return TRUE;
}
virtual FX_BOOL v_GetCMYK(FX_FLOAT* pBuf, FX_FLOAT& c, FX_FLOAT& m, FX_FLOAT& y, FX_FLOAT& k) const
{
return FALSE;
}
virtual FX_BOOL v_SetCMYK(FX_FLOAT* pBuf, FX_FLOAT c, FX_FLOAT m, FX_FLOAT y, FX_FLOAT k) const
{
return FALSE;
}
int m_Family;
int m_nComponents;
CPDF_Array* m_pArray;
FX_DWORD m_dwStdConversion;
};
class CPDF_Color
{
public:
CPDF_Color() :m_pCS(NULL), m_pBuffer(NULL)
{
}
CPDF_Color(int family);
~CPDF_Color();
FX_BOOL IsNull() const
{
return m_pBuffer == NULL;
}
FX_BOOL IsEqual(const CPDF_Color& other) const;
FX_BOOL IsPattern() const
{
return m_pCS && m_pCS->GetFamily() == PDFCS_PATTERN;
}
void Copy(const CPDF_Color* pSrc);
void SetColorSpace(CPDF_ColorSpace* pCS);
void SetValue(FX_FLOAT* comp);
void SetValue(CPDF_Pattern* pPattern, FX_FLOAT* comp, int ncomps);
FX_BOOL GetRGB(int& R, int& G, int& B) const;
CPDF_Pattern* GetPattern() const;
CPDF_ColorSpace* GetPatternCS() const;
FX_FLOAT* GetPatternColor() const;
CPDF_ColorSpace* m_pCS;
protected:
void ReleaseBuffer();
void ReleaseColorSpace();
FX_FLOAT* m_pBuffer;
};
#define PATTERN_TILING 1
#define PATTERN_SHADING 2
class CPDF_Pattern
{
public:
virtual ~CPDF_Pattern();
void SetForceClear(FX_BOOL bForceClear) { m_bForceClear = bForceClear; }
CPDF_Object* m_pPatternObj;
int m_PatternType;
CFX_AffineMatrix m_Pattern2Form;
CFX_AffineMatrix m_ParentMatrix;
CPDF_Document* m_pDocument;
protected:
CPDF_Pattern(const CFX_AffineMatrix* pParentMatrix);
FX_BOOL m_bForceClear;
};
class CPDF_TilingPattern : public CPDF_Pattern
{
public:
CPDF_TilingPattern(CPDF_Document* pDoc, CPDF_Object* pPatternObj, const CFX_AffineMatrix* parentMatrix);
virtual ~CPDF_TilingPattern();
FX_BOOL Load();
FX_BOOL m_bColored;
CFX_FloatRect m_BBox;
FX_FLOAT m_XStep;
FX_FLOAT m_YStep;
CPDF_Form* m_pForm;
};
class CPDF_ShadingPattern : public CPDF_Pattern
{
public:
CPDF_ShadingPattern(CPDF_Document* pDoc, CPDF_Object* pPatternObj, FX_BOOL bShading, const CFX_AffineMatrix* parentMatrix);
virtual ~CPDF_ShadingPattern();
CPDF_Object* m_pShadingObj;
FX_BOOL m_bShadingObj;
FX_BOOL Load();
FX_BOOL Reload();
int m_ShadingType;
CPDF_ColorSpace* m_pCS; // Still keep m_pCS as some CPDF_ColorSpace (name object) are not managed as counted objects. Refer to CPDF_DocPageData::GetColorSpace.
CPDF_CountedColorSpace* m_pCountedCS;
CPDF_Function* m_pFunctions[4];
int m_nFuncs;
protected:
void Clear();
};
struct CPDF_MeshVertex {
FX_FLOAT x, y;
FX_FLOAT r, g, b;
};
class CPDF_MeshStream
{
public:
FX_BOOL Load(CPDF_Stream* pShadingStream, CPDF_Function** pFuncs, int nFuncs, CPDF_ColorSpace* pCS);
FX_DWORD GetFlag();
void GetCoords(FX_FLOAT& x, FX_FLOAT& y);
void GetColor(FX_FLOAT& r, FX_FLOAT& g, FX_FLOAT& b);
FX_DWORD GetVertex(CPDF_MeshVertex& vertex, CFX_AffineMatrix* pObject2Bitmap);
FX_BOOL GetVertexRow(CPDF_MeshVertex* vertex, int count, CFX_AffineMatrix* pObject2Bitmap);
CPDF_Function** m_pFuncs;
CPDF_ColorSpace* m_pCS;
FX_DWORD m_nFuncs, m_nCoordBits, m_nCompBits, m_nFlagBits, m_nComps;
FX_DWORD m_CoordMax, m_CompMax;
FX_FLOAT m_xmin, m_xmax, m_ymin, m_ymax;
FX_FLOAT m_ColorMin[8], m_ColorMax[8];
CPDF_StreamAcc m_Stream;
CFX_BitStream m_BitStream;
};
#define PDF_IMAGE_NO_COMPRESS 0x0000
#define PDF_IMAGE_LOSSY_COMPRESS 0x0001
#define PDF_IMAGE_LOSSLESS_COMPRESS 0x0002
#define PDF_IMAGE_MASK_LOSSY_COMPRESS 0x0004
#define PDF_IMAGE_MASK_LOSSLESS_COMPRESS 0x0008
class CPDF_ImageSetParam
{
public:
CPDF_ImageSetParam()
: pMatteColor(NULL)
, nQuality(80)
{
}
FX_ARGB* pMatteColor;
FX_INT32 nQuality;
};
class CPDF_Image
{
public:
CPDF_Image(CPDF_Document* pDoc);
~CPDF_Image();
FX_BOOL LoadImageF(CPDF_Stream* pImageStream, FX_BOOL bInline);
void Release();
CPDF_Image* Clone();
FX_BOOL IsInline()
{
return m_bInline;
}
void SetInlineDict(CPDF_Dictionary* pDict)
{
m_pInlineDict = pDict;
}
CPDF_Dictionary* GetInlineDict() const
{
return m_pInlineDict;
}
CPDF_Stream* GetStream() const
{
return m_pStream;
}
CPDF_Dictionary* GetDict() const
{
return m_pStream? m_pStream->GetDict(): NULL;
}
CPDF_Dictionary* GetOC() const
{
return m_pOC;
}
CPDF_Document* GetDocument() const
{
return m_pDocument;
}
FX_INT32 GetPixelHeight() const
{
return m_Height;
}
FX_INT32 GetPixelWidth() const
{
return m_Width;
}
FX_BOOL IsMask() const
{
return m_bIsMask;
}
FX_BOOL IsInterpol() const
{
return m_bInterpolate;
}
CFX_DIBSource* LoadDIBSource(CFX_DIBSource** ppMask = NULL, FX_DWORD* pMatteColor = NULL, FX_BOOL bStdCS = FALSE, FX_DWORD GroupFamily = 0, FX_BOOL bLoadMask = FALSE) const;
void SetImage(const CFX_DIBitmap* pDIBitmap, FX_INT32 iCompress, IFX_FileWrite *pFileWrite = NULL, IFX_FileRead *pFileRead = NULL, const CFX_DIBitmap* pMask = NULL, const CPDF_ImageSetParam* pParam = NULL);
void SetJpegImage(FX_BYTE* pImageData, FX_DWORD size);
void SetJpegImage(IFX_FileRead *pFile);
void ResetCache(CPDF_Page* pPage, const CFX_DIBitmap* pDIBitmap);
public:
FX_BOOL StartLoadDIBSource(CPDF_Dictionary* pFormResource, CPDF_Dictionary* pPageResource, FX_BOOL bStdCS = FALSE, FX_DWORD GroupFamily = 0, FX_BOOL bLoadMask = FALSE);
FX_BOOL Continue(IFX_Pause* pPause);
CFX_DIBSource* DetachBitmap();
CFX_DIBSource* DetachMask();
CFX_DIBSource* m_pDIBSource;
CFX_DIBSource* m_pMask;
FX_DWORD m_MatteColor;
private:
CPDF_Stream* m_pStream;
FX_BOOL m_bInline;
CPDF_Dictionary* m_pInlineDict;
FX_INT32 m_Height;
FX_INT32 m_Width;
FX_BOOL m_bIsMask;
FX_BOOL m_bInterpolate;
CPDF_Document* m_pDocument;
CPDF_Dictionary* m_pOC;
CPDF_Dictionary* InitJPEG(FX_LPBYTE pData, FX_DWORD size);
};
#endif // CORE_INCLUDE_FPDFAPI_FPDF_RESOURCE_H_
| bsd-3-clause |
sudounlv/ircbot-php | Tests/Phergie/Event/HandlerTest.php | 10066 | <?php
/**
* Phergie
*
* PHP version 5
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://phergie.org/license
*
* @category Phergie
* @package Phergie_Tests
* @author Phergie Development Team <[email protected]>
* @copyright 2008-2012 Phergie Development Team (http://phergie.org)
* @license http://phergie.org/license New BSD License
* @link http://pear.phergie.org/package/Phergie_Tests
*/
/**
* Unit test suite for Phergie_Event_Handler.
*
* @category Phergie
* @package Phergie_Tests
* @author Phergie Development Team <[email protected]>
* @license http://phergie.org/license New BSD License
* @link http://pear.phergie.org/package/Phergie_Tests
*/
class Phergie_Event_HandlerTest extends PHPUnit_Framework_TestCase
{
/**
* Instance of the class to test
*
* @var Phergie_Event_Handler
*/
private $events;
/**
* Plugin associated with an event added to the handler
*
* @var Phergie_Plugin_Abstract
*/
private $plugin;
/**
* Type of event added to the handler
*
* @var string
*/
private $type = 'privmsg';
/**
* Arguments for an event added to the handler
*
* @var array
*/
private $args = array('#channel', 'text');
/**
* Instantiates the class to test.
*
* @return void
*/
public function setUp()
{
$this->events = new Phergie_Event_Handler;
$this->plugin = $this->getMockForAbstractClass('Phergie_Plugin_Abstract');
}
/**
* Tests that the handler contains no events by default.
*
* @return void
*/
public function testGetEvents()
{
$expected = array();
$actual = $this->events->getEvents();
$this->assertEquals($expected, $actual);
}
/**
* Adds a mock event to the handler.
*
* @return void
*/
private function addMockEvent($type = null, $args = null)
{
if (!$type) {
$type = $this->type;
$args = $this->args;
}
$this->events->addEvent($this->plugin, $type, $args);
}
/**
* Data provider for methods requiring a valid event type and a
* corresponding set of arguments.
*
* @return array Enumerated array of enumerated arrays each containing
* a string for an event type and an enumerated array of
* arguments for that event type
*/
public function dataProviderEventTypesAndArguments()
{
return array(
array('nick', array('nickname')),
array('oper', array('username', 'password')),
array('quit', array()),
array('quit', array('message')),
array('join', array('#channel1,#channel2')),
array('join', array('#channel1,#channel2', 'key1,key2')),
array('part', array('#channel1,#channel2')),
array('mode', array('#channel', '-l', '20')),
array('topic', array('#channel', 'message')),
array('names', array('#channel1,#channel2')),
array('list', array('#channel1,#channel2')),
array('invite', array('nickname', '#channel')),
array('kick', array('#channel', 'username1,username2')),
array('kick', array('#channel', 'username', 'comment')),
array('version', array('nick_or_server')),
array('version', array('nick', 'reply')),
array('stats', array('c')),
array('stats', array('c', 'server')),
array('links', array('mask')),
array('links', array('server', 'mask')),
array('time', array('nick_or_server')),
array('time', array('nick', 'reply')),
array('connect', array('server')),
array('connect', array('server', '6667')),
array('connect', array('target', '6667', 'remote')),
array('trace', array()),
array('trace', array('server')),
array('admin', array()),
array('admin', array('server')),
array('info', array()),
array('info', array('server')),
array('privmsg', array('receiver1,receiver2', 'text')),
array('notice', array('nickname', 'text')),
array('who', array('name')),
array('who', array('name', 'o')),
array('whois', array('mask1,mask2')),
array('whois', array('server', 'mask')),
array('whowas', array('nickname')),
array('whowas', array('nickname', '9')),
array('whowas', array('nickname', '9', 'server')),
array('kill', array('nickname', 'comment')),
array('ping', array('server1')),
array('ping', array('server1', 'server2')),
array('pong', array('daemon')),
array('pong', array('daemon', 'daemon2')),
array('finger', array('nick')),
array('finger', array('nick', 'reply')),
array('error', array('message')),
);
}
/**
* Tests that the handler can receive a new event.
*
* @param string $type Event type
* @param array $args Event arguments
* @dataProvider dataProviderEventTypesAndArguments
* @return void
*/
public function testAddEventWithValidData($type, array $args)
{
$this->addMockEvent($type, $args);
$events = $this->events->getEvents();
$event = array_shift($events);
$this->assertInstanceOf('Phergie_Event_Command', $event);
$this->assertSame($this->plugin, $event->getPlugin());
$this->assertSame($type, $event->getType());
$this->assertSame($args, $event->getArguments());
}
/**
* Tests that attempting to add an event to the handler with an invalid
* type results in an exception.
*
* @return void
*/
public function testAddEventWithInvalidType()
{
$type = 'foo';
try {
$this->events->addEvent($this->plugin, $type);
$this->fail('Expected exception was not thrown');
} catch (Phergie_Event_Exception $e) {
if ($e->getCode() != Phergie_Event_Exception::ERR_UNKNOWN_EVENT_TYPE) {
$this->fail('Unexpected exception code ' . $e->getCode());
}
}
}
/**
* Tests that the events contained within the handler can be
* collectively removed.
*
* @return void
* @depends testGetEvents
* @depends testAddEventWithValidData
*/
public function testClearEvents()
{
$this->addMockEvent();
$this->events->clearEvents();
$expected = array();
$actual = $this->events->getEvents();
$this->assertSame($expected, $actual);
}
/**
* Tests that the events contained within the handler can be replaced
* with a different set of events.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testReplaceEvents()
{
$this->addMockEvent();
$expected = array();
$this->events->replaceEvents($expected);
$actual = $this->events->getEvents();
$this->assertSame($expected, $actual);
}
/**
* Tests that the handler can accurately identify whether it has an
* event of a specified type.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testHasEventOfType()
{
$this->assertFalse($this->events->hasEventOfType($this->type));
$this->addMockEvent();
$this->assertTrue($this->events->hasEventOfType($this->type));
}
/**
* Tests that the handler can return events it contains that are of a
* specified type.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testGetEventsOfType()
{
$expected = array();
$actual = $this->events->getEventsOfType($this->type);
$this->assertSame($expected, $actual);
$this->addMockEvent();
$expected = $this->events->getEvents();
$actual = $this->events->getEventsOfType($this->type);
$this->assertSame($expected, $actual);
}
/**
* Tests that an event can be removed from the handler.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testRemoveEvent()
{
$this->addMockEvent();
$events = $this->events->getEvents();
$event = array_shift($events);
$this->events->removeEvent($event);
$expected = array();
$actual = $this->events->getEvents();
$this->assertSame($expected, $actual);
}
/**
* Tests that the handler supports iteration of the events it contains.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testImplementsGetIterator()
{
$reflector = new ReflectionClass('Phergie_Event_Handler');
$this->assertTrue($reflector->implementsInterface('IteratorAggregate'));
$this->addMockEvent();
$events = $this->events->getEvents();
$expected = array_shift($events);
foreach ($this->events as $actual) {
$this->assertSame($expected, $actual);
}
}
/**
* Tests that the handler supports returning a count of the events it
* contains.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testImplementsCountable()
{
$reflector = new ReflectionClass('Phergie_Event_Handler');
$this->assertTrue($reflector->implementsInterface('Countable'));
$expected = 0;
$actual = count($this->events);
$this->assertSame($expected, $actual);
$this->addMockEvent();
$expected = 1;
$actual = count($this->events);
$this->assertSame($expected, $actual);
}
}
| bsd-3-clause |
nyeholt/silverstripe-queuedjobs | src/Services/DefaultQueueHandler.php | 497 | <?php
namespace Symbiote\QueuedJobs\Services;
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
/**
* Default method for handling items run via the cron
*
* @author [email protected]
* @license BSD License http://silverstripe.org/bsd-license/
*/
class DefaultQueueHandler
{
public function startJobOnQueue(QueuedJobDescriptor $job)
{
$job->activateOnQueue();
}
public function scheduleJob(QueuedJobDescriptor $job, $date)
{
// noop
}
}
| bsd-3-clause |
Brother-Simon/eva-engine | module/Payment/src/Payment/Controller/ResponseController.php | 4610 | <?php
namespace Payment\Controller;
use Eva\Mvc\Controller\ActionController,
Payment\Service\Exception,
Eva\View\Model\ViewModel;
class ResponseController extends ActionController
{
protected $addResources = array(
);
public function indexAction()
{
$adapter = $this->params()->fromQuery('adapter');
$callback = $this->params()->fromQuery('callback');
$amount = $this->params()->fromQuery('amount');
$secretKey = $this->params()->fromQuery('secretKey');
$requestTime = $this->params()->fromQuery('time');
$signed = $this->params()->fromQuery('signed');
$responseData = $this->params()->fromQuery();
if (!$responseData) {
$responseData = $this->params()->fromPost();
}
if (isset($responseData['notify_id']) && isset($responseData['trade_status'])) {
return $this->alipayResponse();
}
if(!$amount){
throw new Exception\InvalidArgumentException(sprintf(
'No payment amount found'
));
}
if(!$adapter){
throw new Exception\InvalidArgumentException(sprintf(
'No payment adapter key found'
));
}
if(!$callback){
throw new Exception\InvalidArgumentException(sprintf(
'No payment callback found'
));
}
if(!$secretKey){
throw new Exception\InvalidArgumentException(sprintf(
'No payment secretKey found'
));
}
if(!$requestTime){
throw new Exception\InvalidArgumentException(sprintf(
'No payment request time found'
));
}
if(!$signed){
throw new Exception\InvalidArgumentException(sprintf(
'No payment signed time found'
));
}
if (!$this->authenticate($this->params()->fromQuery())) {
throw new Exception\InvalidArgumentException(sprintf(
'Signed not match'
));
return;
}
$adapter = $adapter == 'paypalec' ? 'PaypalEc' : 'AlipayEc';
$pay = new \Payment\Service\Payment($adapter);
$pay->setServiceLocator($this->getServiceLocator());
$pay->setStep('response');
$pay->saveResponseLog($secretKey, $responseData);
if ($callback == 'notify') {
return;
}
if($callback){
return $this->redirect()->toUrl($callback);
}
}
public function authenticate($params)
{
$adapter = $params['adapter'];
$callback = $params['callback'];
$amount = $params['amount'];
$secretKey = $params['secretKey'];
$requestTime = $params['time'];
$signed = $params['signed'];
$itemModel = \Eva\Api::_()->getModel('Payment\Model\Log');
$log = $itemModel->getLog($secretKey, array(
'self' => array(
'*',
'unserializeRequestData()',
'unserializeResponseData()',
),
));
if (!$log) {
return false;
}
$adapter = $adapter == 'paypalec' ? 'PaypalEc' : 'AlipayEc';
$pay = new \Payment\Service\Payment($adapter);
$pay->setServiceLocator($this->getServiceLocator());
$authenticate = $pay->setAmount($amount)
->setRequestTime($requestTime)
->setlogData($log['requestData'])
->setStep('response')
->getSigned();
if ($authenticate !== $signed) {
return false;
}
return true;
}
public function alipayResponse()
{
$callback = $this->params()->fromQuery('callback');
$responseData = $this->params()->fromQuery();
if (!isset($responseData['notify_id'])) {
$responseData = $this->params()->fromPost();
$method = 'notify';
}
$config = \Eva\Api::_()->getModuleConfig('Payment');
$options = $config['payment']['alipay'];
$pay = new \Payment\Service\Payment('AlipayEc', false ,$options);
$verify_result = $pay->verify();
if ($verify_result) {
$pay->setStep('response');
$pay->saveResponseLog($responseData['out_trade_no'], $responseData);
}
if ($callback == 'notify') {
return;
}
if($callback){
return $this->redirect()->toUrl($callback);
}
}
}
| bsd-3-clause |
scheib/chromium | components/update_client/updater_state.cc | 3368 |
// Copyright (c) 2016 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 "components/update_client/updater_state.h"
#include <string>
#include <utility>
#include "base/enterprise_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
namespace update_client {
// The value of this constant does not reflect its name (i.e. "domainjoined"
// vs something like "isenterprisemanaged") because it is used with omaha.
// After discussion with omaha team it was decided to leave the value as is to
// keep continuity with previous chrome versions.
const char UpdaterState::kIsEnterpriseManaged[] = "domainjoined";
UpdaterState::UpdaterState(bool is_machine) : is_machine_(is_machine) {}
UpdaterState::~UpdaterState() = default;
std::unique_ptr<UpdaterState::Attributes> UpdaterState::GetState(
bool is_machine) {
#if defined(OS_WIN) || defined(OS_MAC)
UpdaterState updater_state(is_machine);
updater_state.ReadState();
return std::make_unique<Attributes>(updater_state.BuildAttributes());
#else
return nullptr;
#endif // OS_WIN or Mac
}
#if defined(OS_WIN) || defined(OS_MAC)
void UpdaterState::ReadState() {
is_enterprise_managed_ = base::IsMachineExternallyManaged();
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
updater_name_ = GetUpdaterName();
updater_version_ = GetUpdaterVersion(is_machine_);
last_autoupdate_started_ = GetUpdaterLastStartedAU(is_machine_);
last_checked_ = GetUpdaterLastChecked(is_machine_);
is_autoupdate_check_enabled_ = IsAutoupdateCheckEnabled();
update_policy_ = GetUpdatePolicy();
#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
}
#endif // OS_WIN or Mac
UpdaterState::Attributes UpdaterState::BuildAttributes() const {
Attributes attributes;
#if defined(OS_WIN)
// Only Windows implements this attribute in a meaningful way.
attributes["ismachine"] = is_machine_ ? "1" : "0";
#endif // OS_WIN
attributes[kIsEnterpriseManaged] = is_enterprise_managed_ ? "1" : "0";
attributes["name"] = updater_name_;
if (updater_version_.IsValid())
attributes["version"] = updater_version_.GetString();
const base::Time now = base::Time::NowFromSystemTime();
if (!last_autoupdate_started_.is_null())
attributes["laststarted"] =
NormalizeTimeDelta(now - last_autoupdate_started_);
if (!last_checked_.is_null())
attributes["lastchecked"] = NormalizeTimeDelta(now - last_checked_);
attributes["autoupdatecheckenabled"] =
is_autoupdate_check_enabled_ ? "1" : "0";
DCHECK((update_policy_ >= 0 && update_policy_ <= 3) || update_policy_ == -1);
attributes["updatepolicy"] = base::NumberToString(update_policy_);
return attributes;
}
std::string UpdaterState::NormalizeTimeDelta(const base::TimeDelta& delta) {
const base::TimeDelta two_weeks = base::Days(14);
const base::TimeDelta two_months = base::Days(56);
std::string val; // Contains the value to return in hours.
if (delta <= two_weeks) {
val = "0";
} else if (two_weeks < delta && delta <= two_months) {
val = "336"; // 2 weeks in hours.
} else {
val = "1344"; // 2*28 days in hours.
}
DCHECK(!val.empty());
return val;
}
} // namespace update_client
| bsd-3-clause |
davizucon/ChatterBot | tests/corpus_tests/test_corpus.py | 3023 | from unittest import TestCase
from chatterbot.corpus import Corpus
import os
class CorpusUtilsTestCase(TestCase):
def setUp(self):
self.corpus = Corpus()
def test_get_file_path(self):
"""
Test that a dotted path is properly converted to a file address.
"""
path = self.corpus.get_file_path('chatterbot.corpus.english')
self.assertIn(
os.path.join('chatterbot_corpus', 'data', 'english'),
path
)
def test_read_english_corpus(self):
corpus_path = os.path.join(
self.corpus.data_directory,
'english', 'conversations.corpus.json'
)
data = self.corpus.read_corpus(corpus_path)
self.assertIn('conversations', data)
def test_list_english_corpus_files(self):
data_files = self.corpus.list_corpus_files('chatterbot.corpus.english')
self.assertIn('.json', data_files[0])
def test_load_corpus(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.english.greetings')
self.assertEqual(len(corpus), 1)
self.assertIn(['Hi', 'Hello'], corpus[0])
class CorpusLoadingTestCase(TestCase):
def setUp(self):
self.corpus = Corpus()
def test_load_corpus_chinese(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.chinese')
self.assertTrue(len(corpus))
def test_load_corpus_english(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.english')
self.assertTrue(len(corpus))
def test_load_corpus_french(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.french')
self.assertTrue(len(corpus))
def test_load_corpus_german(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.german')
self.assertTrue(len(corpus))
def test_load_corpus_hindi(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.hindi')
self.assertTrue(len(corpus))
def test_load_corpus_indonesia(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.indonesia')
self.assertTrue(len(corpus))
def test_load_corpus_italian(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.italian')
self.assertTrue(len(corpus))
def test_load_corpus_marathi(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.marathi')
self.assertTrue(len(corpus))
def test_load_corpus_portuguese(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.portuguese')
self.assertTrue(len(corpus))
def test_load_corpus_russian(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.russian')
self.assertTrue(len(corpus))
def test_load_corpus_spanish(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.spanish')
self.assertTrue(len(corpus))
def test_load_corpus_telugu(self):
corpus = self.corpus.load_corpus('chatterbot.corpus.telugu')
self.assertTrue(len(corpus))
| bsd-3-clause |
shrtcww/pymel | maintenance/docs.py | 3694 | import sys
import os
import glob
import shutil
import datetime
assert 'pymel' not in sys.modules or 'PYMEL_INCLUDE_EXAMPLES' in os.environ, "to generate docs PYMEL_INCLUDE_EXAMPLES env var must be set before pymel is imported"
# remember, the processed command examples are not version specific. you must
# run cmdcache.fixCodeExamples() to bring processed examples in from the raw
# version-specific example caches
os.environ['PYMEL_INCLUDE_EXAMPLES'] = 'True'
pymel_root = os.path.dirname(os.path.dirname(sys.modules[__name__].__file__))
docsdir = os.path.join(pymel_root, 'docs')
stubdir = os.path.join(pymel_root, 'extras', 'completion', 'py')
useStubs = False
if useStubs:
sys.path.insert(0, stubdir)
import pymel
print pymel.__file__
else:
import pymel
# make sure dynamic modules are fully loaded
from pymel.core.uitypes import *
from pymel.core.nodetypes import *
version = pymel.__version__.rsplit('.',1)[0]
SOURCE = 'source'
BUILD_ROOT = 'build'
BUILD = os.path.join(BUILD_ROOT, version)
sourcedir = os.path.join(docsdir, SOURCE)
gendir = os.path.join(sourcedir, 'generated')
buildrootdir = os.path.join(docsdir, BUILD_ROOT)
builddir = os.path.join(docsdir, BUILD)
from pymel.internal.cmdcache import fixCodeExamples
def generate(clean=True):
"delete build and generated directories and generate a top-level documentation source file for each module."
print "generating %s - %s" % (docsdir, datetime.datetime.now())
from sphinx.ext.autosummary.generate import main as sphinx_autogen
if clean:
clean_build()
clean_generated()
os.chdir(sourcedir)
sphinx_autogen( [''] + '--templates ../templates modules.rst'.split() )
sphinx_autogen( [''] + '--templates ../templates'.split() + glob.glob('generated/pymel.*.rst') )
print "...done generating %s - %s" % (docsdir, datetime.datetime.now())
def clean_build():
"delete existing build directory"
if os.path.exists(buildrootdir):
print "removing %s - %s" % (buildrootdir, datetime.datetime.now())
shutil.rmtree(buildrootdir)
def clean_generated():
"delete existing generated directory"
if os.path.exists(gendir):
print "removing %s - %s" % (gendir, datetime.datetime.now())
shutil.rmtree(gendir)
def find_dot():
if os.name == 'posix':
dot_bin = 'dot'
else:
dot_bin = 'dot.exe'
for p in os.environ['PATH'].split(os.pathsep):
d = os.path.join(p, dot_bin)
if os.path.exists(d):
return d
raise TypeError('cannot find graphiz dot executable in the path (%s)' % os.environ['PATH'])
def copy_changelog():
changelog = os.path.join(pymel_root, 'CHANGELOG.rst')
whatsnew = os.path.join(pymel_root, 'docs', 'source', 'whats_new.rst')
shutil.copy2(changelog, whatsnew)
def build(clean=True, **kwargs):
from sphinx import main as sphinx_build
print "building %s - %s" % (docsdir, datetime.datetime.now())
if not os.path.isdir(gendir):
generate()
os.chdir( docsdir )
if clean:
clean_build()
copy_changelog()
#mkdir -p build/html build/doctrees
#import pymel.internal.cmdcache as cmdcache
#cmdcache.fixCodeExamples()
opts = ['']
opts += '-b html -d build/doctrees'.split()
# set some defaults
if not kwargs.get('graphviz_dot', None):
kwargs['graphviz_dot'] = find_dot()
for key, value in kwargs.iteritems():
opts.append('-D')
opts.append( key.strip() + '=' + value.strip() )
opts.append('-P')
opts.append(SOURCE)
opts.append(BUILD)
sphinx_build(opts)
print "...done building %s - %s" % (docsdir, datetime.datetime.now())
| bsd-3-clause |
lucadelu/PDAL | vendor/pdalboost/boost/test/utils/basic_cstring/basic_cstring.hpp | 21254 | // (C) Copyright Gennadiy Rozental 2001.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : class basic_cstring wraps C string and provide std_string like
// interface
// ***************************************************************************
#ifndef BOOST_TEST_UTILS_BASIC_CSTRING_HPP
#define BOOST_TEST_UTILS_BASIC_CSTRING_HPP
// Boost.Test
#include <boost/test/utils/basic_cstring/basic_cstring_fwd.hpp>
#include <boost/test/utils/basic_cstring/bcs_char_traits.hpp>
// Boost
#include <boost/type_traits/remove_cv.hpp>
// STL
#include <string>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace pdalboost {
namespace unit_test {
// ************************************************************************** //
// ************** basic_cstring ************** //
// ************************************************************************** //
template<typename CharT>
class basic_cstring {
typedef basic_cstring<CharT> self_type;
public:
// Subtypes
typedef ut_detail::bcs_char_traits<CharT> traits_type;
typedef typename ut_detail::bcs_char_traits<CharT>::std_string std_string;
typedef CharT value_type;
typedef typename remove_cv<value_type>::type value_ret_type;
typedef value_type* pointer;
typedef value_type const* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef value_type const* const_iterator;
typedef value_type* iterator;
// !! should also present reverse_iterator, const_reverse_iterator
#if !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600))
enum npos_type { npos = static_cast<size_type>(-1) };
#else
// IBM/VisualAge version 6 is not able to handle enums larger than 4 bytes.
// But size_type is 8 bytes in 64bit mode.
static const size_type npos = -1 ;
#endif
static pointer null_str();
// Constructors; default copy constructor is generated by compiler
basic_cstring();
basic_cstring( std_string const& s );
basic_cstring( pointer s );
template<typename LenType>
basic_cstring( pointer s, LenType len ) : m_begin( s ), m_end( m_begin + len ) {}
basic_cstring( pointer first, pointer last );
// data access methods
value_ret_type operator[]( size_type index ) const;
value_ret_type at( size_type index ) const;
// size operators
size_type size() const;
bool is_empty() const;
void clear();
void resize( size_type new_len );
// !! only for STL container conformance use is_empty instead
bool empty() const;
// Trimming
self_type& trim_right( size_type trim_size );
self_type& trim_left( size_type trim_size );
self_type& trim_right( iterator it );
self_type& trim_left( iterator it );
#if !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(800))
self_type& trim_left( self_type exclusions = self_type() ) ;
self_type& trim_right( self_type exclusions = self_type() ) ;
self_type& trim( self_type exclusions = self_type() ) ;
#else
// VA C++/XL C++ v6 and v8 has in this case a problem with the default arguments.
self_type& trim_left( self_type exclusions );
self_type& trim_right( self_type exclusions );
self_type& trim( self_type exclusions );
self_type& trim_left() { return trim_left( self_type() ); }
self_type& trim_right() { return trim_right( self_type() ); }
self_type& trim() { return trim( self_type() ); }
#endif
// Assignment operators
basic_cstring& operator=( self_type const& s );
basic_cstring& operator=( std_string const& s );
basic_cstring& operator=( pointer s );
template<typename CharT2>
basic_cstring& assign( basic_cstring<CharT2> const& s )
{
return *this = basic_cstring<CharT>( s.begin(), s.end() );
}
template<typename PosType, typename LenType>
basic_cstring& assign( self_type const& s, PosType pos, LenType len )
{
return *this = self_type( s.m_begin + pos, len );
}
basic_cstring& assign( std_string const& s );
template<typename PosType, typename LenType>
basic_cstring& assign( std_string const& s, PosType pos, LenType len )
{
return *this = self_type( s.c_str() + pos, len );
}
basic_cstring& assign( pointer s );
template<typename LenType>
basic_cstring& assign( pointer s, LenType len )
{
return *this = self_type( s, len );
}
basic_cstring& assign( pointer f, pointer l );
// swapping
void swap( self_type& s );
// Iterators
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
// !! should have rbegin, rend
// substring search operation
size_type find( basic_cstring ) const;
size_type rfind( basic_cstring ) const;
self_type substr( size_type beg_index, size_type end_index = npos ) const;
private:
static self_type default_trim_ex();
// Data members
iterator m_begin;
iterator m_end;
};
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::pointer
basic_cstring<CharT>::null_str()
{
static CharT null = 0;
return &null;
}
//____________________________________________________________________________//
template<typename CharT>
inline
basic_cstring<CharT>::basic_cstring()
: m_begin( null_str() )
, m_end( m_begin )
{
}
//____________________________________________________________________________//
template<typename CharT>
inline
basic_cstring<CharT>::basic_cstring( std_string const& s )
: m_begin( s.c_str() )
, m_end( m_begin + s.size() )
{
}
//____________________________________________________________________________//
template<typename CharT>
inline
basic_cstring<CharT>::basic_cstring( pointer s )
: m_begin( s ? s : null_str() )
, m_end ( m_begin + (s ? traits_type::length( s ) : 0 ) )
{
}
//____________________________________________________________________________//
template<typename CharT>
inline
basic_cstring<CharT>::basic_cstring( pointer first, pointer last )
: m_begin( first )
, m_end( last )
{
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::value_ret_type
basic_cstring<CharT>::operator[]( size_type index ) const
{
return m_begin[index];
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::value_ret_type
basic_cstring<CharT>::at( size_type index ) const
{
if( m_begin + index >= m_end )
return static_cast<value_type>(0);
return m_begin[index];
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::size_type
basic_cstring<CharT>::size() const
{
return static_cast<size_type>(m_end - m_begin);
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
basic_cstring<CharT>::is_empty() const
{
return m_end == m_begin;
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
basic_cstring<CharT>::empty() const
{
return is_empty();
}
//____________________________________________________________________________//
template<typename CharT>
inline void
basic_cstring<CharT>::clear()
{
m_begin = m_end;
}
//____________________________________________________________________________//
template<typename CharT>
inline void
basic_cstring<CharT>::resize( size_type new_len )
{
if( m_begin + new_len < m_end )
m_end = m_begin + new_len;
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::trim_left( size_type trim_size )
{
m_begin += trim_size;
if( m_end <= m_begin )
clear();
return *this;
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::trim_left( iterator it )
{
m_begin = it;
if( m_end <= m_begin )
clear();
return *this;
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::trim_left( basic_cstring exclusions )
{
if( exclusions.is_empty() )
exclusions = default_trim_ex();
iterator it;
for( it = begin(); it != end(); ++it ) {
if( traits_type::find( exclusions.begin(), exclusions.size(), *it ) == reinterpret_cast<pointer>(0) )
break;
}
return trim_left( it );
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::trim_right( size_type trim_size )
{
m_end -= trim_size;
if( m_end <= m_begin )
clear();
return *this;
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::trim_right( iterator it )
{
m_end = it;
if( m_end <= m_begin )
clear();
return *this;
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::trim_right( basic_cstring exclusions )
{
if( exclusions.is_empty() )
exclusions = default_trim_ex();
iterator it;
for( it = end()-1; it != begin()-1; --it ) {
if( self_type::traits_type::find( exclusions.begin(), exclusions.size(), *it ) == reinterpret_cast<pointer>(0) )
break;
}
return trim_right( it+1 );
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::trim( basic_cstring exclusions )
{
trim_left( exclusions );
trim_right( exclusions );
return *this;
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::operator=( basic_cstring<CharT> const& s )
{
m_begin = s.m_begin;
m_end = s.m_end;
return *this;
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::operator=( std_string const& s )
{
return *this = self_type( s );
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::operator=( pointer s )
{
return *this = self_type( s );
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::assign( std_string const& s )
{
return *this = self_type( s );
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::assign( pointer s )
{
return *this = self_type( s );
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>&
basic_cstring<CharT>::assign( pointer f, pointer l )
{
return *this = self_type( f, l );
}
//____________________________________________________________________________//
template<typename CharT>
inline void
basic_cstring<CharT>::swap( basic_cstring<CharT>& s )
{
// do not want to include alogrithm
pointer tmp1 = m_begin;
pointer tmp2 = m_end;
m_begin = s.m_begin;
m_end = s.m_end;
s.m_begin = tmp1;
s.m_end = tmp2;
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::iterator
basic_cstring<CharT>::begin()
{
return m_begin;
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::const_iterator
basic_cstring<CharT>::begin() const
{
return m_begin;
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::iterator
basic_cstring<CharT>::end()
{
return m_end;
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::const_iterator
basic_cstring<CharT>::end() const
{
return m_end;
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::size_type
basic_cstring<CharT>::find( basic_cstring<CharT> str ) const
{
if( str.is_empty() || str.size() > size() )
return static_cast<size_type>(npos);
const_iterator it = begin();
const_iterator last = end() - str.size() + 1;
while( it != last ) {
if( traits_type::compare( it, str.begin(), str.size() ) == 0 )
break;
++it;
}
return it == last ? npos : static_cast<size_type>(it - begin());
}
//____________________________________________________________________________//
template<typename CharT>
inline typename basic_cstring<CharT>::size_type
basic_cstring<CharT>::rfind( basic_cstring<CharT> str ) const
{
if( str.is_empty() || str.size() > size() )
return static_cast<size_type>(npos);
const_iterator it = end() - str.size();
const_iterator last = begin()-1;
while( it != last ) {
if( traits_type::compare( it, str.begin(), str.size() ) == 0 )
break;
--it;
}
return it == last ? static_cast<size_type>(npos) : static_cast<size_type>(it - begin());
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>
basic_cstring<CharT>::substr( size_type beg_index, size_type end_index ) const
{
return beg_index > size()
? self_type()
: end_index > size()
? self_type( m_begin + beg_index, m_end )
: self_type( m_begin + beg_index, m_begin + end_index );
}
//____________________________________________________________________________//
template<typename CharT>
inline basic_cstring<CharT>
basic_cstring<CharT>::default_trim_ex()
{
static CharT ws[3] = { CharT(' '), CharT('\t'), CharT('\n') }; // !! wide case
return self_type( ws, 3 );
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** comparison operators ************** //
// ************************************************************************** //
template<typename CharT1,typename CharT2>
inline bool
operator==( basic_cstring<CharT1> const& s1, basic_cstring<CharT2> const& s2 )
{
typedef typename basic_cstring<CharT1>::traits_type traits_type;
return s1.size() == s2.size() &&
traits_type::compare( s1.begin(), s2.begin(), s1.size() ) == 0;
}
//____________________________________________________________________________//
template<typename CharT1,typename CharT2>
inline bool
operator==( basic_cstring<CharT1> const& s1, CharT2* s2 )
{
#if !defined(__DMC__)
return s1 == basic_cstring<CharT2>( s2 );
#else
return s1 == basic_cstring<CharT2 const>( s2 );
#endif
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
operator==( basic_cstring<CharT> const& s1, typename basic_cstring<CharT>::std_string const& s2 )
{
return s1 == basic_cstring<CharT>( s2 );
}
//____________________________________________________________________________//
template<typename CharT1,typename CharT2>
inline bool
operator==( CharT1* s2, basic_cstring<CharT2> const& s1 )
{
return s1 == s2;
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
operator==( typename basic_cstring<CharT>::std_string const& s2, basic_cstring<CharT> const& s1 )
{
return s1 == s2;
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
operator!=( basic_cstring<CharT> const& s1, CharT* s2 )
{
return !(s1 == s2);
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
operator!=( CharT* s2, basic_cstring<CharT> const& s1 )
{
return !(s1 == s2);
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
operator!=( basic_cstring<CharT> const& s1, basic_cstring<CharT> const& s2 )
{
return !(s1 == s2);
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
operator!=( basic_cstring<CharT> const& s1, typename basic_cstring<CharT>::std_string const& s2 )
{
return !(s1 == s2);
}
//____________________________________________________________________________//
template<typename CharT>
inline bool
operator!=( typename basic_cstring<CharT>::std_string const& s2, basic_cstring<CharT> const& s1 )
{
return !(s1 == s2);
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** first_char ************** //
// ************************************************************************** //
template<typename CharT>
inline typename basic_cstring<CharT>::value_ret_type
first_char( basic_cstring<CharT> source )
{
typedef typename basic_cstring<CharT>::value_ret_type res_type;
return source.is_empty() ? static_cast<res_type>(0) : *source.begin();
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** last_char ************** //
// ************************************************************************** //
template<typename CharT>
inline typename basic_cstring<CharT>::value_ret_type
last_char( basic_cstring<CharT> source )
{
typedef typename basic_cstring<CharT>::value_ret_type res_type;
return source.is_empty() ? static_cast<res_type>(0) : *(source.end()-1);
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** assign_op ************** //
// ************************************************************************** //
template<typename CharT1, typename CharT2>
inline void
assign_op( std::basic_string<CharT1>& target, basic_cstring<CharT2> src, int )
{
target.assign( src.begin(), src.size() );
}
//____________________________________________________________________________//
template<typename CharT1, typename CharT2>
inline std::basic_string<CharT1>&
operator+=( std::basic_string<CharT1>& target, basic_cstring<CharT2> const& str )
{
target.append( str.begin(), str.end() );
return target;
}
//____________________________________________________________________________//
template<typename CharT1, typename CharT2>
inline std::basic_string<CharT1>
operator+( std::basic_string<CharT1> const& lhs, basic_cstring<CharT2> const& rhs )
{
std::basic_string<CharT1> res( lhs );
res.append( rhs.begin(), rhs.end() );
return res;
}
//____________________________________________________________________________//
} // namespace unit_test
} // namespace pdalboost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_UTILS_BASIC_CSTRING_HPP
| bsd-3-clause |
gtcasl/gpuocelot | tests/parboil/benchmarks/mm/src/cuda/Makefile | 399 | # (c) 2010 The Board of Trustees of the University of Illinois.
include $(PARBOIL_ROOT)/common/mk/common.mk
include $(PARBOIL_ROOT)/common/mk/cuda.mk
SRCDIR_OBJS=main.o io.o #compute_gold.o
EXTRA_LIBS=-lm -lstdc++
EXTRA_CFLAGS=-ffast-math -g3
EXTRA_CXXFLAGS=-ffast-math -g3
LINK_MODE=CUDA
all : $(BIN)
include $(PARBOIL_ROOT)/common/mk/rules.mk
include $(PARBOIL_ROOT)/common/mk/cuda_rules.mk
| bsd-3-clause |
guorendong/iridium-browser-ubuntu | chrome/test/base/tracing.cc | 5907 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/base/tracing.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/singleton.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_util.h"
#include "base/timer/timer.h"
#include "base/trace_event/trace_event.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/tracing_controller.h"
#include "content/public/test/test_utils.h"
namespace {
using content::BrowserThread;
class StringTraceSink : public content::TracingController::TraceDataSink {
public:
StringTraceSink(std::string* result, const base::Closure& callback)
: result_(result), completion_callback_(callback) {}
void AddTraceChunk(const std::string& chunk) override {
*result_ += result_->empty() ? "[" : ",";
*result_ += chunk;
}
void Close() override {
if (!result_->empty())
*result_ += "]";
completion_callback_.Run();
}
private:
~StringTraceSink() override {}
std::string* result_;
base::Closure completion_callback_;
DISALLOW_COPY_AND_ASSIGN(StringTraceSink);
};
class InProcessTraceController {
public:
static InProcessTraceController* GetInstance() {
return Singleton<InProcessTraceController>::get();
}
InProcessTraceController()
: is_waiting_on_watch_(false),
watch_notification_count_(0) {}
virtual ~InProcessTraceController() {}
bool BeginTracing(const std::string& category_patterns) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return content::TracingController::GetInstance()->EnableRecording(
base::trace_event::CategoryFilter(category_patterns),
base::trace_event::TraceOptions(),
content::TracingController::EnableRecordingDoneCallback());
}
bool BeginTracingWithWatch(const std::string& category_patterns,
const std::string& category_name,
const std::string& event_name,
int num_occurrences) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(num_occurrences > 0);
watch_notification_count_ = num_occurrences;
if (!content::TracingController::GetInstance()->SetWatchEvent(
category_name, event_name,
base::Bind(&InProcessTraceController::OnWatchEventMatched,
base::Unretained(this)))) {
return false;
}
if (!content::TracingController::GetInstance()->EnableRecording(
base::trace_event::CategoryFilter(category_patterns),
base::trace_event::TraceOptions(),
base::Bind(&InProcessTraceController::OnEnableTracingComplete,
base::Unretained(this)))) {
return false;
}
message_loop_runner_ = new content::MessageLoopRunner;
message_loop_runner_->Run();
return true;
}
bool WaitForWatchEvent(base::TimeDelta timeout) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (watch_notification_count_ == 0)
return true;
if (timeout != base::TimeDelta()) {
timer_.Start(FROM_HERE, timeout, this,
&InProcessTraceController::Timeout);
}
is_waiting_on_watch_ = true;
message_loop_runner_ = new content::MessageLoopRunner;
message_loop_runner_->Run();
is_waiting_on_watch_ = false;
return watch_notification_count_ == 0;
}
bool EndTracing(std::string* json_trace_output) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
using namespace base::debug;
if (!content::TracingController::GetInstance()->DisableRecording(
new StringTraceSink(
json_trace_output,
base::Bind(&InProcessTraceController::OnTracingComplete,
base::Unretained(this))))) {
return false;
}
// Wait for OnEndTracingComplete() to quit the message loop.
message_loop_runner_ = new content::MessageLoopRunner;
message_loop_runner_->Run();
// Watch notifications can occur during this method's message loop run, but
// not after, so clear them here.
watch_notification_count_ = 0;
return true;
}
private:
friend struct DefaultSingletonTraits<InProcessTraceController>;
void OnEnableTracingComplete() {
message_loop_runner_->Quit();
}
void OnTracingComplete() { message_loop_runner_->Quit(); }
void OnWatchEventMatched() {
if (watch_notification_count_ == 0)
return;
if (--watch_notification_count_ == 0) {
timer_.Stop();
if (is_waiting_on_watch_)
message_loop_runner_->Quit();
}
}
void Timeout() {
DCHECK(is_waiting_on_watch_);
message_loop_runner_->Quit();
}
scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
base::OneShotTimer<InProcessTraceController> timer_;
bool is_waiting_on_watch_;
int watch_notification_count_;
DISALLOW_COPY_AND_ASSIGN(InProcessTraceController);
};
} // namespace
namespace tracing {
bool BeginTracing(const std::string& category_patterns) {
return InProcessTraceController::GetInstance()->BeginTracing(
category_patterns);
}
bool BeginTracingWithWatch(const std::string& category_patterns,
const std::string& category_name,
const std::string& event_name,
int num_occurrences) {
return InProcessTraceController::GetInstance()->BeginTracingWithWatch(
category_patterns, category_name, event_name, num_occurrences);
}
bool WaitForWatchEvent(base::TimeDelta timeout) {
return InProcessTraceController::GetInstance()->WaitForWatchEvent(timeout);
}
bool EndTracing(std::string* json_trace_output) {
return InProcessTraceController::GetInstance()->EndTracing(json_trace_output);
}
} // namespace tracing
| bsd-3-clause |
scheib/chromium | third_party/blink/renderer/modules/webcodecs/codec_logger.cc | 2677 | // Copyright 2020 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 "third_party/blink/renderer/modules/webcodecs/codec_logger.h"
#include <string>
#include "media/base/media_util.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/inspector/inspector_media_context_impl.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
CodecLogger::CodecLogger(
ExecutionContext* context,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
DCHECK(context);
// Owners of |this| should be ExecutionLifeCycleObservers, and should call
// Neuter() if |context| is destroyed. The MediaInspectorContextImpl must
// outlive |parent_media_log_|. If |context| is already destroyed, owners
// might never call Neuter(), and MediaInspectorContextImpl* could be garbage
// collected before |parent_media_log_| is destroyed.
if (!context->IsContextDestroyed()) {
parent_media_log_ = Platform::Current()->GetMediaLog(
MediaInspectorContextImpl::From(*context), task_runner,
/*is_on_worker=*/!IsMainThread());
}
// NullMediaLog silently and safely does nothing.
if (!parent_media_log_)
parent_media_log_ = std::make_unique<media::NullMediaLog>();
// This allows us to destroy |parent_media_log_| and stop logging,
// without causing problems to |media_log_| users.
media_log_ = parent_media_log_->Clone();
}
DOMException* CodecLogger::MakeException(std::string error_msg,
media::Status status) {
media_log_->NotifyError(status);
if (status_code_ == media::StatusCode::kOk) {
DCHECK(!status.is_ok());
status_code_ = status.code();
}
return MakeGarbageCollected<DOMException>(DOMExceptionCode::kOperationError,
error_msg.c_str());
}
DOMException* CodecLogger::MakeException(std::string error_msg,
media::StatusCode code,
const base::Location& location) {
if (status_code_ == media::StatusCode::kOk) {
DCHECK_NE(code, media::StatusCode::kOk);
status_code_ = code;
}
return MakeException(error_msg, media::Status(code, error_msg, location));
}
CodecLogger::~CodecLogger() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
void CodecLogger::Neuter() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
parent_media_log_ = nullptr;
}
} // namespace blink
| bsd-3-clause |
broadinstitute/hellbender | src/test/java/org/broadinstitute/hellbender/utils/dragstr/DoubleSequenceTest.java | 2666 | package org.broadinstitute.hellbender.utils.dragstr;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.IntStream;
/**
* Unit tests for {@link DoubleSequence}
*/
public class DoubleSequenceTest {
@Test(dataProvider = "correctSequenceData")
public void testCorrectSequence(final String spec, final double[] expectedValues, final double epsilon) {
final DoubleSequence subject = new DoubleSequence(spec);
Assert.assertEquals(subject.size(), expectedValues.length);
// check single value access:
for (int i = 0; i < expectedValues.length; i++) {
Assert.assertEquals(subject.get(i), expectedValues[i], epsilon);
}
// check array access:
final double[] actualValues = subject.toDoubleArray();
Assert.assertNotNull(actualValues);
Assert.assertEquals(actualValues, expectedValues, epsilon);
}
@Test(dataProvider = "badSpecsData", expectedExceptions = RuntimeException.class)
public void testBadSpecs(final String spec) {
new DoubleSequence(spec);
}
@DataProvider(name = "badSpecsData")
public Iterator<Object[]> badSpecsData() {
return Arrays.stream(new String[] {null, "", "::", "1:2", "2:2:2:2:2", "2,2", "4;5;100", "10:-1:100"})
.map(s -> new Object[] { s }).iterator();
}
@DataProvider(name = "correctSequenceData")
public Iterator<Object[]> correctSequenceData() {
final String STD_EPSILON = "0.001";
final String[] testCases = {
"0:1:10", "0,1,2,3,4,5,6,7,8,9,10", STD_EPSILON,
"-1:2.5:5", "-1,1.5,4", STD_EPSILON,
"1:1e-1:2.3", "1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3", STD_EPSILON,
"5:-1:1", "5,4,3,2,1", STD_EPSILON,
"1:0.00001:1", "1", STD_EPSILON,
"5:-123:5", "5", STD_EPSILON,
"8:1:10.00001", "8,9,10.00001", "0.0000000001",
};
return IntStream.range(0, testCases.length / 3)
.map(i -> 3 * i)
.mapToObj(i -> {
final String spec = testCases[i++];
final String strValues = testCases[i++];
final double epsilon = Double.parseDouble(testCases[i]);
final double[] dblValues = Arrays.stream(strValues.split("\\s*,\\s*")).mapToDouble(Double::parseDouble).toArray();
return new Object[]{spec, dblValues, epsilon};
}).iterator();
}
}
| bsd-3-clause |
kitsonk/expo | src/dojox/mobile/IconMenu.js | 3265 | define([
"dojo/_base/declare",
"dojo/_base/sniff",
"dojo/dom-class",
"dojo/dom-construct",
"dojo/dom-style",
"dijit/_Contained",
"dijit/_Container",
"dijit/_WidgetBase",
"./IconMenuItem"
], function(declare, has, domClass, domConstruct, domStyle, Contained, Container, WidgetBase){
// module:
// dojox/mobile/IconMenu
return declare("dojox.mobile.IconMenu", [WidgetBase, Container, Contained], {
// summary:
// A pop-up menu.
// description:
// The dojox/mobile/IconMenu widget displays a pop-up menu just
// like iPhone's call options menu that is shown while you are on a
// call. Each menu item must be dojox/mobile/IconMenuItem.
// transition: String
// The default animated transition effect for child items.
transition: "slide",
// iconBase: String
// The default icon path for child items.
iconBase: "",
// iconPos: String
// The default icon position for child items.
iconPos: "",
// cols: Number
// The number of child items in a row.
cols: 3,
// tag: String
// A name of html tag to create as domNode.
tag: "ul",
/* internal properties */
selectOne: false,
// baseClass: String
// The name of the CSS class of this widget.
baseClass: "mblIconMenu",
// childItemClass: String
// The name of the CSS class of menu items.
childItemClass: "mblIconMenuItem",
// _createTerminator: [private] Boolean
_createTerminator: false,
buildRendering: function(){
this.domNode = this.containerNode = this.srcNodeRef || domConstruct.create(this.tag);
this.inherited(arguments);
if(this._createTerminator){
var t = this._terminator = domConstruct.create("br");
t.className = this.childItemClass + "Terminator";
this.domNode.appendChild(t);
}
},
startup: function(){
if(this._started){ return; }
this.refresh();
this.inherited(arguments);
},
refresh: function(){
var p = this.getParent();
if(p){
domClass.remove(p.domNode, "mblSimpleDialogDecoration");
}
var children = this.getChildren();
if(this.cols){
var nRows = Math.ceil(children.length / this.cols);
var w = Math.floor(100/this.cols);
var _w = 100 - w*this.cols;
var h = Math.floor(100 / nRows);
var _h = 100 - h*nRows;
if(has("ie")){
_w--;
_h--;
}
}
for(var i = 0; i < children.length; i++){
var item = children[i];
if(this.cols){
var first = ((i % this.cols) === 0); // first column
var last = (((i + 1) % this.cols) === 0); // last column
var rowIdx = Math.floor(i / this.cols);
domStyle.set(item.domNode, {
width: w + (last ? _w : 0) + "%",
height: h + ((rowIdx + 1 === nRows) ? _h : 0) + "%"
});
domClass.toggle(item.domNode, this.childItemClass + "FirstColumn", first);
domClass.toggle(item.domNode, this.childItemClass + "LastColumn", last);
domClass.toggle(item.domNode, this.childItemClass + "FirstRow", rowIdx === 0);
domClass.toggle(item.domNode, this.childItemClass + "LastRow", rowIdx + 1 === nRows);
}
};
},
addChild: function(widget, /*Number?*/insertIndex){
this.inherited(arguments);
this.refresh();
},
hide: function(){
var p = this.getParent();
if(p && p.hide){
p.hide();
}
}
});
});
| bsd-3-clause |
zcth428/hpctoolkit111 | src/tool/hpcserver/LRUList.hpp | 5239 | // -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2015, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
#ifndef LRULIST_H_
#define LRULIST_H_
#include <vector>
#include <list>
using std::list;
using std::vector;
namespace TraceviewerServer {
template <typename T>
class LRUList {
private:
int totalPages;
int usedPages;
int currentFront;
list<T*> useOrder;
list<T*> removed;
vector<typename list<T*>::iterator> iters;
public:
/**
* It's a special data structure that uses a little extra memory in exchange
* for all operations running in constant time. Objects are added to the
* data structure and given an index that identifies them.
* Once added, objects are not deleted; they are either on the "in use" list,
* which for VersatileMemoryPage corresponds to being mapped, or they are on
* the "not in use" list, which corresponds to not being mapped. An object
* must only be added with addNew() once. If it is removed from the list
* with remove(), it must be added with reAdd(). It is not necessary to call
* putOnTop() after adding an element as it will already be on top.
*/
LRUList(int expectedMaxSize)//Up to linear time
{
iters.reserve(expectedMaxSize);
totalPages = 0;
usedPages = 0;
currentFront = -1;
}
int addNew(T* toAdd)//constant time
{
useOrder.push_front(toAdd);
int index = totalPages++;
currentFront = index;
iters.push_back(useOrder.begin());
usedPages++;
return index;
}
int addNewUnused(T* toAdd)//constant time
{
removed.push_front(toAdd);
int index = totalPages++;
iters.push_back(removed.begin());
return index;
}
void putOnTop(int index)//Constant time
{
if (index == currentFront) return;
typename list<T*>::iterator it;
it = iters[index];
useOrder.splice(useOrder.begin(), useOrder, it);
currentFront = index;
}
T* getLast()
{
return useOrder.back();
}
void removeLast()//Constant time
{
removed.splice(removed.end(), useOrder, --useOrder.end());
usedPages--;
}
void reAdd(int index)//Constant time
{
typename list<T*>::iterator it = iters[index];
useOrder.splice(useOrder.begin(), removed, it);
currentFront = index;
usedPages++;
}
int getTotalPageCount()//Constant time
{
return totalPages;
}
int getUsedPageCount()
{
return usedPages;
}
virtual ~LRUList()
{
}
/*int dump()
{
int x = 0;
puts("Objects \"in use\" from most recently used to least recently used");
typename list<T*>::iterator it = useOrder.begin();
for(; it != useOrder.end(); ++it){
printf("%d\n", ((TestData*)*it)->index);
x++;
}
puts("Objects \"not in use\" from most recently used to least recently used");
it = removed.begin();
for(; it != removed.end(); ++it){
printf("%d\n", ((TestData*)*it)->index);
}
cout << "Used count: " << usedPages <<" supposed to be " << x<<endl;
return x;
}*/
};
} /* namespace TraceviewerServer */
#endif /* LRULIST_H_ */
| bsd-3-clause |
youtube/cobalt | third_party/llvm-project/clang/test/OpenMP/target_teams_distribute_codegen_registration.cpp | 28706 | // Test host codegen.
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// Test target teams distribute codegen - host bc file has to be created first.
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s -check-prefix=TCHECK
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=TCHECK
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s -check-prefix=TCHECK
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=TCHECK
// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc
// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc
// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// SIMD-ONLY1-NOT: {{__kmpc|__tgt}}
// Check that no target code is emitted if no omptests flag was provided.
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK-NTARGET
// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY2 %s
// SIMD-ONLY2-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
// CHECK-DAG: [[SA:%.+]] = type { [4 x i32] }
// CHECK-DAG: [[SB:%.+]] = type { [8 x i32] }
// CHECK-DAG: [[SC:%.+]] = type { [16 x i32] }
// CHECK-DAG: [[SD:%.+]] = type { [32 x i32] }
// CHECK-DAG: [[SE:%.+]] = type { [64 x i32] }
// CHECK-DAG: [[ST1:%.+]] = type { [228 x i32] }
// CHECK-DAG: [[ST2:%.+]] = type { [1128 x i32] }
// CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 }
// CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* }
// CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* }
// TCHECK: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 }
// CHECK-DAG: $[[REGFN:\.omp_offloading\..+]] = comdat
// CHECK-DAG: [[A1:@.+]] = internal global [[SA]]
// CHECK-DAG: [[A2:@.+]] = global [[SA]]
// CHECK-DAG: [[B1:@.+]] = global [[SB]]
// CHECK-DAG: [[B2:@.+]] = global [[SB]]
// CHECK-DAG: [[C1:@.+]] = internal global [[SC]]
// CHECK-DAG: [[D1:@.+]] = global [[SD]]
// CHECK-DAG: [[E1:@.+]] = global [[SE]]
// CHECK-DAG: [[T1:@.+]] = global [[ST1]]
// CHECK-DAG: [[T2:@.+]] = global [[ST2]]
// CHECK-NTARGET-DAG: [[SA:%.+]] = type { [4 x i32] }
// CHECK-NTARGET-DAG: [[SB:%.+]] = type { [8 x i32] }
// CHECK-NTARGET-DAG: [[SC:%.+]] = type { [16 x i32] }
// CHECK-NTARGET-DAG: [[SD:%.+]] = type { [32 x i32] }
// CHECK-NTARGET-DAG: [[SE:%.+]] = type { [64 x i32] }
// CHECK-NTARGET-DAG: [[ST1:%.+]] = type { [228 x i32] }
// CHECK-NTARGET-DAG: [[ST2:%.+]] = type { [1128 x i32] }
// CHECK-NTARGET-NOT: type { i8*, i8*, %
// CHECK-NTARGET-NOT: type { i32, %
// We have 7 target regions
// CHECK-DAG: {{@.+}} = weak constant i8 0
// TCHECK-NOT: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-DAG: {{@.+}} = weak constant i8 0
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4]
// CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i64] [i64 800]
// CHECK-NTARGET-NOT: weak constant i8 0
// CHECK-NTARGET-NOT: private unnamed_addr constant [1 x i
// CHECK-DAG: [[NAMEPTR1:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME1:__omp_offloading_[0-9a-f]+_[0-9a-f]+__Z.+_l[0-9]+]]\00"
// CHECK-DAG: [[ENTRY1:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR1]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR2:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME2:.+]]\00"
// CHECK-DAG: [[ENTRY2:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR2]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR3:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME3:.+]]\00"
// CHECK-DAG: [[ENTRY3:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR3]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR4:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME4:.+]]\00"
// CHECK-DAG: [[ENTRY4:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR4]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR5:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME5:.+]]\00"
// CHECK-DAG: [[ENTRY5:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR5]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR6:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME6:.+]]\00"
// CHECK-DAG: [[ENTRY6:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR6]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR7:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME7:.+]]\00"
// CHECK-DAG: [[ENTRY7:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR7]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR8:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME8:.+]]\00"
// CHECK-DAG: [[ENTRY8:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR8]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR9:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME9:.+]]\00"
// CHECK-DAG: [[ENTRY9:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR9]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR10:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME10:.+]]\00"
// CHECK-DAG: [[ENTRY10:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR10]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR11:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME11:.+]]\00"
// CHECK-DAG: [[ENTRY11:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR11]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK-DAG: [[NAMEPTR12:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME12:.+]]\00"
// CHECK-DAG: [[ENTRY12:@.+]] = weak constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR12]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR1:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME1:__omp_offloading_[0-9a-f]+_[0-9a-f]+__Z.+_l[0-9]+]]\00"
// TCHECK-DAG: [[ENTRY1:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR1]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR2:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME2:.+]]\00"
// TCHECK-DAG: [[ENTRY2:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR2]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR3:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME3:.+]]\00"
// TCHECK-DAG: [[ENTRY3:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR3]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR4:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME4:.+]]\00"
// TCHECK-DAG: [[ENTRY4:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR4]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR5:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME5:.+]]\00"
// TCHECK-DAG: [[ENTRY5:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR5]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR6:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME6:.+]]\00"
// TCHECK-DAG: [[ENTRY6:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR6]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR7:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME7:.+]]\00"
// TCHECK-DAG: [[ENTRY7:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR7]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR8:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME8:.+]]\00"
// TCHECK-DAG: [[ENTRY8:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR8]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR9:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME9:.+]]\00"
// TCHECK-DAG: [[ENTRY9:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR9]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR10:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME10:.+]]\00"
// TCHECK-DAG: [[ENTRY10:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR10]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR11:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME11:.+]]\00"
// TCHECK-DAG: [[ENTRY11:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR11]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// TCHECK-DAG: [[NAMEPTR12:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME12:.+]]\00"
// TCHECK-DAG: [[ENTRY12:@.+]] = weak constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR12]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1
// CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]]
// CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]]
// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8
// CHECK: [[DEVEND:@.+]] = extern_weak constant i8
// CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]])
// CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]])
// We have 4 initializers, one for the 500 priority, another one for 501, or more for the default priority, and the last one for the offloading registration function.
// CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] [
// CHECK-SAME: { i32, void ()*, i8* } { i32 500, void ()* [[P500:@[^,]+]], i8* null },
// CHECK-SAME: { i32, void ()*, i8* } { i32 501, void ()* [[P501:@[^,]+]], i8* null },
// CHECK-SAME: { i32, void ()*, i8* } { i32 65535, void ()* [[PMAX:@[^,]+]], i8* null },
// CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
// CHECK-NTARGET: @llvm.global_ctors = appending global [3 x { i32, void ()*, i8* }] [
extern int *R;
struct SA {
int arr[4];
void foo() {
int a = *R;
a += 1;
*R = a;
}
SA() {
int a = *R;
a += 2;
*R = a;
}
~SA() {
int a = *R;
a += 3;
*R = a;
}
};
struct SB {
int arr[8];
void foo() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 4;
*R = a;
}
SB() {
int a = *R;
a += 5;
*R = a;
}
~SB() {
int a = *R;
a += 6;
*R = a;
}
};
struct SC {
int arr[16];
void foo() {
int a = *R;
a += 7;
*R = a;
}
SC() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 8;
*R = a;
}
~SC() {
int a = *R;
a += 9;
*R = a;
}
};
struct SD {
int arr[32];
void foo() {
int a = *R;
a += 10;
*R = a;
}
SD() {
int a = *R;
a += 11;
*R = a;
}
~SD() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 12;
*R = a;
}
};
struct SE {
int arr[64];
void foo() {
int a = *R;
#pragma omp target teams distribute if(target: 0)
for (int i = 0; i < 10; ++i)
a += 13;
*R = a;
}
SE() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 14;
*R = a;
}
~SE() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 15;
*R = a;
}
};
template <int x>
struct ST {
int arr[128 + x];
void foo() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 16 + x;
*R = a;
}
ST() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 17 + x;
*R = a;
}
~ST() {
int a = *R;
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
a += 18 + x;
*R = a;
}
};
// We have to make sure we us all the target regions:
//CHECK-DAG: define internal void @[[NAME1]](
//CHECK-DAG: call void @[[NAME1]](
//CHECK-DAG: define internal void @[[NAME2]](
//CHECK-DAG: call void @[[NAME2]](
//CHECK-DAG: define internal void @[[NAME3]](
//CHECK-DAG: call void @[[NAME3]](
//CHECK-DAG: define internal void @[[NAME4]](
//CHECK-DAG: call void @[[NAME4]](
//CHECK-DAG: define internal void @[[NAME5]](
//CHECK-DAG: call void @[[NAME5]](
//CHECK-DAG: define internal void @[[NAME6]](
//CHECK-DAG: call void @[[NAME6]](
//CHECK-DAG: define internal void @[[NAME7]](
//CHECK-DAG: call void @[[NAME7]](
//CHECK-DAG: define internal void @[[NAME8]](
//CHECK-DAG: call void @[[NAME8]](
//CHECK-DAG: define internal void @[[NAME9]](
//CHECK-DAG: call void @[[NAME9]](
//CHECK-DAG: define internal void @[[NAME10]](
//CHECK-DAG: call void @[[NAME10]](
//CHECK-DAG: define internal void @[[NAME11]](
//CHECK-DAG: call void @[[NAME11]](
//CHECK-DAG: define internal void @[[NAME12]](
//CHECK-DAG: call void @[[NAME12]](
//TCHECK-DAG: define weak void @[[NAME1]](
//TCHECK-DAG: define weak void @[[NAME2]](
//TCHECK-DAG: define weak void @[[NAME3]](
//TCHECK-DAG: define weak void @[[NAME4]](
//TCHECK-DAG: define weak void @[[NAME5]](
//TCHECK-DAG: define weak void @[[NAME6]](
//TCHECK-DAG: define weak void @[[NAME7]](
//TCHECK-DAG: define weak void @[[NAME8]](
//TCHECK-DAG: define weak void @[[NAME9]](
//TCHECK-DAG: define weak void @[[NAME10]](
//TCHECK-DAG: define weak void @[[NAME11]](
//TCHECK-DAG: define weak void @[[NAME12]](
// CHECK-NTARGET-NOT: __tgt_target
// CHECK-NTARGET-NOT: __tgt_register_lib
// CHECK-NTARGET-NOT: __tgt_unregister_lib
// TCHECK-NOT: __tgt_target
// TCHECK-NOT: __tgt_register_lib
// TCHECK-NOT: __tgt_unregister_lib
// We have 2 initializers with priority 500
//CHECK: define internal void [[P500]](
//CHECK: call void @{{.+}}()
//CHECK: call void @{{.+}}()
//CHECK-NOT: call void @{{.+}}()
//CHECK: ret void
// We have 1 initializers with priority 501
//CHECK: define internal void [[P501]](
//CHECK: call void @{{.+}}()
//CHECK-NOT: call void @{{.+}}()
//CHECK: ret void
// We have 6 initializers with default priority
//CHECK: define internal void [[PMAX]](
//CHECK: call void @{{.+}}()
//CHECK: call void @{{.+}}()
//CHECK: call void @{{.+}}()
//CHECK: call void @{{.+}}()
//CHECK: call void @{{.+}}()
//CHECK: call void @{{.+}}()
//CHECK-NOT: call void @{{.+}}()
//CHECK: ret void
// Check registration and unregistration
//CHECK: define internal void @[[UNREGFN:.+]](i8*)
//CHECK-SAME: comdat($[[REGFN]]) {
//CHECK: call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]])
//CHECK: ret void
//CHECK: declare i32 @__tgt_unregister_lib([[DSCTY]]*)
//CHECK: define linkonce hidden void @[[REGFN]]()
//CHECK-SAME: comdat {
//CHECK: call i32 @__tgt_register_lib([[DSCTY]]* [[DESC]])
//CHECK: call i32 @__cxa_atexit(void (i8*)* @[[UNREGFN]], i8* bitcast ([[DSCTY]]* [[DESC]] to i8*),
//CHECK: ret void
//CHECK: declare i32 @__tgt_register_lib([[DSCTY]]*)
static __attribute__((init_priority(500))) SA a1;
SA a2;
SB __attribute__((init_priority(500))) b1;
SB __attribute__((init_priority(501))) b2;
static SC c1;
SD d1;
SE e1;
ST<100> t1;
ST<1000> t2;
int bar(int a){
int r = a;
a1.foo();
a2.foo();
b1.foo();
b2.foo();
c1.foo();
d1.foo();
e1.foo();
t1.foo();
t2.foo();
#pragma omp target teams distribute
for (int i = 0; i < 10; ++i)
++r;
return r + *R;
}
// Check metadata is properly generated:
// CHECK: !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 216, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 268, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 286, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 293, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 305, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 312, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 436, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 319, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 312, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 319, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 305, i32 {{[0-9]+}}}
// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 242, i32 {{[0-9]+}}}
// TCHECK: !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 216, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 268, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 286, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 293, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 305, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 312, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 436, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 319, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 312, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 319, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 305, i32 {{[0-9]+}}}
// TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 242, i32 {{[0-9]+}}}
#endif
| bsd-3-clause |
nwjs/chromium.src | ui/platform_window/stub/stub_window.cc | 2654 | // Copyright 2015 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 "ui/platform_window/stub/stub_window.h"
#include "base/memory/scoped_refptr.h"
#include "base/notreached.h"
#include "ui/base/cursor/platform_cursor.h"
#include "ui/platform_window/platform_window_delegate.h"
namespace ui {
StubWindow::StubWindow(PlatformWindowDelegate* delegate,
bool use_default_accelerated_widget,
const gfx::Rect& bounds)
: delegate_(delegate), bounds_(bounds) {
DCHECK(delegate);
if (use_default_accelerated_widget)
delegate_->OnAcceleratedWidgetAvailable(gfx::kNullAcceleratedWidget);
}
StubWindow::~StubWindow() {}
void StubWindow::Show(bool inactive) {}
void StubWindow::Hide() {}
void StubWindow::Close() {
delegate_->OnClosed();
}
bool StubWindow::IsVisible() const {
NOTIMPLEMENTED_LOG_ONCE();
return true;
}
void StubWindow::PrepareForShutdown() {}
void StubWindow::SetBounds(const gfx::Rect& bounds) {
// Even if the pixel bounds didn't change this call to the delegate should
// still happen. The device scale factor may have changed which effectively
// changes the bounds.
bounds_ = bounds;
delegate_->OnBoundsChanged(bounds);
}
gfx::Rect StubWindow::GetBounds() const {
return bounds_;
}
void StubWindow::SetTitle(const std::u16string& title) {}
void StubWindow::SetCapture() {}
void StubWindow::ReleaseCapture() {}
bool StubWindow::HasCapture() const {
return false;
}
void StubWindow::ToggleFullscreen() {}
void StubWindow::Maximize() {}
void StubWindow::Minimize() {}
void StubWindow::Restore() {}
PlatformWindowState StubWindow::GetPlatformWindowState() const {
return PlatformWindowState::kUnknown;
}
void StubWindow::Activate() {
NOTIMPLEMENTED_LOG_ONCE();
}
void StubWindow::Deactivate() {
NOTIMPLEMENTED_LOG_ONCE();
}
void StubWindow::SetUseNativeFrame(bool use_native_frame) {}
bool StubWindow::ShouldUseNativeFrame() const {
NOTIMPLEMENTED_LOG_ONCE();
return false;
}
void StubWindow::SetCursor(scoped_refptr<PlatformCursor> cursor) {}
void StubWindow::MoveCursorTo(const gfx::Point& location) {}
void StubWindow::ConfineCursorToBounds(const gfx::Rect& bounds) {}
void StubWindow::SetRestoredBoundsInPixels(const gfx::Rect& bounds) {}
gfx::Rect StubWindow::GetRestoredBoundsInPixels() const {
return gfx::Rect();
}
void StubWindow::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {}
void StubWindow::SizeConstraintsChanged() {}
} // namespace ui
| bsd-3-clause |
scheib/chromium | third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc | 22622 | // Copyright 2017 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 "third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h"
#include <sstream>
#include "third_party/blink/renderer/core/dom/tag_collection.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
namespace blink {
namespace {
const NGPhysicalLineBoxFragment* FindBlockInInlineLineBoxFragment(
Element* container) {
NGInlineCursor cursor(*To<LayoutBlockFlow>(container->GetLayoutObject()));
for (cursor.MoveToFirstLine(); cursor; cursor.MoveToNextLine()) {
const NGPhysicalLineBoxFragment* fragment =
cursor.Current()->LineBoxFragment();
DCHECK(fragment);
if (fragment->IsBlockInInline())
return fragment;
}
return nullptr;
}
class NGInlineLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
protected:
static std::string AsFragmentItemsString(const LayoutBlockFlow& root) {
std::ostringstream ostream;
ostream << std::endl;
for (NGInlineCursor cursor(root); cursor; cursor.MoveToNext()) {
const auto& item = *cursor.CurrentItem();
ostream << item << " " << item.RectInContainerFragment() << std::endl;
}
return ostream.str();
}
};
TEST_F(NGInlineLayoutAlgorithmTest, Types) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<div id="normal">normal</div>
<div id="empty"><span></span></div>
)HTML");
NGInlineCursor normal(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("normal")));
normal.MoveToFirstLine();
EXPECT_FALSE(normal.Current()->LineBoxFragment()->IsEmptyLineBox());
NGInlineCursor empty(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("empty")));
empty.MoveToFirstLine();
EXPECT_TRUE(empty.Current()->LineBoxFragment()->IsEmptyLineBox());
}
TEST_F(NGInlineLayoutAlgorithmTest, TypesForBlockInInline) {
ScopedLayoutNGBlockInInlineForTest block_in_inline_scope(true);
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<div id="block-in-inline">
<span><div>normal</div></span>
</div>
<div id="block-in-inline-empty">
<span><div></div></span>
</div>
<div id="block-in-inline-height">
<span><div style="height: 100px"></div></span>
</div>
)HTML");
// Regular block-in-inline.
NGInlineCursor block_in_inline(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("block-in-inline")));
block_in_inline.MoveToFirstLine();
EXPECT_TRUE(block_in_inline.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_FALSE(block_in_inline.Current()->LineBoxFragment()->IsBlockInInline());
block_in_inline.MoveToNextLine();
EXPECT_FALSE(block_in_inline.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_TRUE(block_in_inline.Current()->LineBoxFragment()->IsBlockInInline());
int block_count = 0;
for (NGInlineCursor children = block_in_inline.CursorForDescendants();
children; children.MoveToNext()) {
if (children.Current()->BoxFragment() &&
children.Current()->BoxFragment()->IsBlockInInline())
++block_count;
}
EXPECT_EQ(block_count, 1);
block_in_inline.MoveToNextLine();
EXPECT_TRUE(block_in_inline.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_FALSE(block_in_inline.Current()->LineBoxFragment()->IsBlockInInline());
// If the block is empty and self-collapsing, |IsEmptyLineBox| should be set.
NGInlineCursor block_in_inline_empty(*To<LayoutBlockFlow>(
GetLayoutObjectByElementId("block-in-inline-empty")));
block_in_inline_empty.MoveToFirstLine();
block_in_inline_empty.MoveToNextLine();
EXPECT_TRUE(
block_in_inline_empty.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_TRUE(
block_in_inline_empty.Current()->LineBoxFragment()->IsBlockInInline());
// Test empty but non-self-collapsing block in an inline box.
NGInlineCursor block_in_inline_height(*To<LayoutBlockFlow>(
GetLayoutObjectByElementId("block-in-inline-height")));
block_in_inline_height.MoveToFirstLine();
block_in_inline_height.MoveToNextLine();
EXPECT_FALSE(
block_in_inline_height.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_TRUE(
block_in_inline_height.Current()->LineBoxFragment()->IsBlockInInline());
}
TEST_F(NGInlineLayoutAlgorithmTest, BreakToken) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html {
font: 10px/1 Ahem;
}
#container {
width: 50px; height: 20px;
}
</style>
<div id=container>123 456 789</div>
)HTML");
// Perform 1st Layout.
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGInlineNode inline_node(block_flow);
LogicalSize size(LayoutUnit(50), LayoutUnit(20));
NGConstraintSpaceBuilder builder(
WritingMode::kHorizontalTb,
{WritingMode::kHorizontalTb, TextDirection::kLtr},
/* is_new_fc */ false);
builder.SetAvailableSize(size);
NGConstraintSpace constraint_space = builder.ToConstraintSpace();
NGInlineChildLayoutContext context;
NGBoxFragmentBuilder container_builder(
block_flow, block_flow->Style(),
block_flow->Style()->GetWritingDirection());
NGFragmentItemsBuilder items_builder(inline_node,
container_builder.GetWritingDirection());
container_builder.SetItemsBuilder(&items_builder);
context.SetItemsBuilder(&items_builder);
scoped_refptr<const NGLayoutResult> layout_result =
inline_node.Layout(constraint_space, nullptr, &context);
const auto& line1 = layout_result->PhysicalFragment();
EXPECT_TRUE(line1.BreakToken());
// Perform 2nd layout with the break token from the 1st line.
scoped_refptr<const NGLayoutResult> layout_result2 =
inline_node.Layout(constraint_space, line1.BreakToken(), &context);
const auto& line2 = layout_result2->PhysicalFragment();
EXPECT_TRUE(line2.BreakToken());
// Perform 3rd layout with the break token from the 2nd line.
scoped_refptr<const NGLayoutResult> layout_result3 =
inline_node.Layout(constraint_space, line2.BreakToken(), &context);
const auto& line3 = layout_result3->PhysicalFragment();
EXPECT_FALSE(line3.BreakToken());
}
// This test ensures box fragments are generated when necessary, even when the
// line is empty. One such case is when the line contains a containing box of an
// out-of-flow object.
TEST_F(NGInlineLayoutAlgorithmTest,
EmptyLineWithOutOfFlowInInlineContainingBlock) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
oof-container {
position: relative;
}
oof {
position: absolute;
width: 100px;
height: 100px;
}
html, body { margin: 0; }
html {
font-size: 10px;
}
</style>
<div id=container>
<oof-container id=target>
<oof></oof>
</oof-container>
</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
const NGPhysicalBoxFragment* container = block_flow->GetPhysicalFragment(0);
ASSERT_TRUE(container);
EXPECT_EQ(LayoutUnit(), container->Size().height);
NGInlineCursor line_box(*block_flow);
ASSERT_TRUE(line_box);
ASSERT_TRUE(line_box.Current().IsLineBox());
EXPECT_EQ(PhysicalSize(), line_box.Current().Size());
NGInlineCursor off_container(line_box);
off_container.MoveToNext();
ASSERT_TRUE(off_container);
ASSERT_EQ(GetLayoutObjectByElementId("target"),
off_container.Current().GetLayoutObject());
EXPECT_EQ(PhysicalSize(), off_container.Current().Size());
}
// This test ensures that if an inline box generates (or does not generate) box
// fragments for a wrapped line, it should consistently do so for other lines
// too, when the inline box is fragmented to multiple lines.
TEST_F(NGInlineLayoutAlgorithmTest, BoxForEndMargin) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html, body { margin: 0; }
#container {
font: 10px/1 Ahem;
width: 50px;
}
span {
border-right: 10px solid blue;
}
</style>
<!-- This line wraps, and only 2nd line has a border. -->
<div id=container>12 <span id=span>3 45</span> 6</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGInlineCursor line_box(*block_flow);
ASSERT_TRUE(line_box) << "line_box is at start of first line.";
ASSERT_TRUE(line_box.Current().IsLineBox());
line_box.MoveToNextLine();
ASSERT_TRUE(line_box) << "line_box is at start of second line.";
NGInlineCursor cursor(line_box);
ASSERT_TRUE(line_box.Current().IsLineBox());
cursor.MoveToNext();
ASSERT_TRUE(cursor);
EXPECT_EQ(GetLayoutObjectByElementId("span"),
cursor.Current().GetLayoutObject());
// The <span> generates a box fragment for the 2nd line because it has a
// right border. It should also generate a box fragment for the 1st line even
// though there's no borders on the 1st line.
const NGPhysicalBoxFragment* box_fragment = cursor.Current().BoxFragment();
ASSERT_TRUE(box_fragment);
EXPECT_EQ(NGPhysicalFragment::kFragmentBox, box_fragment->Type());
line_box.MoveToNextLine();
ASSERT_FALSE(line_box) << "block_flow has two lines.";
}
// A block with inline children generates fragment tree as follows:
// - A box fragment created by NGBlockNode
// - A wrapper box fragment created by NGInlineNode
// - Line box fragments.
// This test verifies that borders/paddings are applied to the wrapper box.
TEST_F(NGInlineLayoutAlgorithmTest, ContainerBorderPadding) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html, body { margin: 0; }
div {
padding-left: 5px;
padding-top: 10px;
display: flow-root;
}
</style>
<div id=container>test</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGBlockNode block_node(block_flow);
NGConstraintSpace space =
NGConstraintSpace::CreateFromLayoutObject(*block_flow);
scoped_refptr<const NGLayoutResult> layout_result = block_node.Layout(space);
EXPECT_TRUE(layout_result->BfcBlockOffset().has_value());
EXPECT_EQ(0, *layout_result->BfcBlockOffset());
EXPECT_EQ(0, layout_result->BfcLineOffset());
PhysicalOffset line_offset =
layout_result->PhysicalFragment().Children()[0].Offset();
EXPECT_EQ(5, line_offset.left);
EXPECT_EQ(10, line_offset.top);
}
// The test leaks memory. crbug.com/721932
#if defined(ADDRESS_SANITIZER)
#define MAYBE_VerticalAlignBottomReplaced DISABLED_VerticalAlignBottomReplaced
#else
#define MAYBE_VerticalAlignBottomReplaced VerticalAlignBottomReplaced
#endif
TEST_F(NGInlineLayoutAlgorithmTest, MAYBE_VerticalAlignBottomReplaced) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html { font-size: 10px; }
img { vertical-align: bottom; }
#container { display: flow-root; }
</style>
<div id=container><img src="#" width="96" height="96"></div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGInlineCursor cursor(*block_flow);
ASSERT_TRUE(cursor);
EXPECT_EQ(LayoutUnit(96), cursor.Current().Size().height);
cursor.MoveToNext();
ASSERT_TRUE(cursor);
EXPECT_EQ(LayoutUnit(0), cursor.Current().OffsetInContainerFragment().top)
<< "Offset top of <img> should be zero.";
}
// Verifies that text can flow correctly around floats that were positioned
// before the inline block.
TEST_F(NGInlineLayoutAlgorithmTest, TextFloatsAroundFloatsBefore) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 20px;
}
#container {
height: 200px; width: 200px; outline: solid blue;
}
#left-float1 {
float: left; width: 30px; height: 30px; background-color: blue;
}
#left-float2 {
float: left; width: 10px; height: 10px;
background-color: purple;
}
#right-float {
float: right; width: 40px; height: 40px; background-color: yellow;
}
</style>
<div id="container">
<div id="left-float1"></div>
<div id="left-float2"></div>
<div id="right-float"></div>
<span id="text">The quick brown fox jumps over the lazy dog</span>
</div>
)HTML");
// ** Run LayoutNG algorithm **
NGConstraintSpace space;
scoped_refptr<const NGPhysicalBoxFragment> html_fragment;
std::tie(html_fragment, space) = RunBlockLayoutAlgorithmForElement(
GetDocument().getElementsByTagName("html")->item(0));
auto* body_fragment =
To<NGPhysicalBoxFragment>(html_fragment->Children()[0].get());
auto* container_fragment =
To<NGPhysicalBoxFragment>(body_fragment->Children()[0].get());
Vector<PhysicalOffset> line_offsets;
for (const auto& child : container_fragment->Children()) {
if (!child->IsLineBox())
continue;
line_offsets.push_back(child.Offset());
}
// Line break points may vary by minor differences in fonts.
// The test is valid as long as we have 3 or more lines and their positions
// are correct.
EXPECT_GE(line_offsets.size(), 3UL);
// 40 = #left-float1' width 30 + #left-float2 10
EXPECT_EQ(LayoutUnit(40), line_offsets[0].left);
// 40 = #left-float1' width 30
EXPECT_EQ(LayoutUnit(30), line_offsets[1].left);
EXPECT_EQ(LayoutUnit(), line_offsets[2].left);
}
// Verifies that text correctly flows around the inline float that fits on
// the same text line.
TEST_F(NGInlineLayoutAlgorithmTest, TextFloatsAroundInlineFloatThatFitsOnLine) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 18px;
}
#container {
height: 200px; width: 200px; outline: solid orange;
}
#narrow-float {
float: left; width: 30px; height: 30px; background-color: blue;
}
</style>
<div id="container">
<span id="text">
The quick <div id="narrow-float"></div> brown fox jumps over the lazy
</span>
</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
const NGPhysicalBoxFragment* block_box = block_flow->GetPhysicalFragment(0);
ASSERT_TRUE(block_box);
// Two lines.
ASSERT_EQ(2u, block_box->Children().size());
PhysicalOffset first_line_offset = block_box->Children()[1].Offset();
// 30 == narrow-float's width.
EXPECT_EQ(LayoutUnit(30), first_line_offset.left);
Element* span = GetDocument().getElementById("text");
// 38 == narrow-float's width + body's margin.
EXPECT_EQ(LayoutUnit(38), span->OffsetLeft());
Element* narrow_float = GetDocument().getElementById("narrow-float");
// 8 == body's margin.
EXPECT_EQ(8, narrow_float->OffsetLeft());
EXPECT_EQ(8, narrow_float->OffsetTop());
}
// Verifies that the inline float got pushed to the next line if it doesn't
// fit the current line.
TEST_F(NGInlineLayoutAlgorithmTest,
TextFloatsAroundInlineFloatThatDoesNotFitOnLine) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 19px;
}
#container {
height: 200px; width: 200px; outline: solid orange;
}
#wide-float {
float: left; width: 160px; height: 30px; background-color: red;
}
</style>
<div id="container">
<span id="text">
The quick <div id="wide-float"></div> brown fox jumps over the lazy dog
</span>
</div>
)HTML");
Element* wide_float = GetDocument().getElementById("wide-float");
// 8 == body's margin.
EXPECT_EQ(8, wide_float->OffsetLeft());
}
// Verifies that if an inline float pushed to the next line then all others
// following inline floats positioned with respect to the float's top edge
// alignment rule.
TEST_F(NGInlineLayoutAlgorithmTest,
FloatsArePositionedWithRespectToTopEdgeAlignmentRule) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 19px;
}
#container {
height: 200px; width: 200px; outline: solid orange;
}
#left-narrow {
float: left; width: 5px; height: 30px; background-color: blue;
}
#left-wide {
float: left; width: 160px; height: 30px; background-color: red;
}
</style>
<div id="container">
<span id="text">
The quick <div id="left-wide"></div> brown <div id="left-narrow"></div>
fox jumps over the lazy dog
</span>
</div>
)HTML");
Element* wide_float = GetDocument().getElementById("left-wide");
// 8 == body's margin.
EXPECT_EQ(8, wide_float->OffsetLeft());
Element* narrow_float = GetDocument().getElementById("left-narrow");
// 160 float-wide's width + 8 body's margin.
EXPECT_EQ(160 + 8, narrow_float->OffsetLeft());
// On the same line.
EXPECT_EQ(wide_float->OffsetTop(), narrow_float->OffsetTop());
}
// Block-in-inline is not reusable. See |EndOfReusableItems|.
TEST_F(NGInlineLayoutAlgorithmTest, BlockInInlineAppend) {
ScopedLayoutNGBlockInInlineForTest scoped_for_test(true);
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
:root {
font-size: 10px;
}
#container {
width: 10ch;
}
</style>
<div id="container">
<span id="span">
12345678
<div>block</div>
12345678
</span>
12345678
</div>
)HTML");
Element* container_element = GetElementById("container");
scoped_refptr<const NGPhysicalLineBoxFragment> before_append =
FindBlockInInlineLineBoxFragment(container_element);
ASSERT_TRUE(before_append);
Document& doc = GetDocument();
container_element->appendChild(doc.createTextNode("12345678"));
UpdateAllLifecyclePhasesForTest();
scoped_refptr<const NGPhysicalLineBoxFragment> after_append =
FindBlockInInlineLineBoxFragment(container_element);
EXPECT_NE(before_append, after_append);
}
// Verifies that InlineLayoutAlgorithm positions floats with respect to their
// margins.
TEST_F(NGInlineLayoutAlgorithmTest, PositionFloatsWithMargins) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
#container {
height: 200px; width: 200px; outline: solid orange;
}
#left {
float: left; width: 5px; height: 30px; background-color: blue;
margin: 10%;
}
</style>
<div id="container">
<span id="text">
The quick <div id="left"></div> brown fox jumps over the lazy dog
</span>
</div>
)HTML");
Element* span = GetElementById("text");
// 53 = sum of left's inline margins: 40 + left's width: 5 + body's margin: 8
EXPECT_EQ(LayoutUnit(53), span->OffsetLeft());
}
// Test glyph bounding box causes ink overflow.
TEST_F(NGInlineLayoutAlgorithmTest, InkOverflow) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
#container {
font: 20px/.5 Ahem;
display: flow-root;
}
</style>
<div id="container">Hello</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
const NGPhysicalBoxFragment& box_fragment =
*block_flow->GetPhysicalFragment(0);
EXPECT_EQ(LayoutUnit(10), box_fragment.Size().height);
NGInlineCursor cursor(*block_flow);
PhysicalRect ink_overflow = cursor.Current().InkOverflow();
EXPECT_EQ(LayoutUnit(-5), ink_overflow.offset.top);
EXPECT_EQ(LayoutUnit(20), ink_overflow.size.height);
}
// See also NGInlineLayoutAlgorithmTest.TextCombineFake
TEST_F(NGInlineLayoutAlgorithmTest, TextCombineBasic) {
ScopedLayoutNGTextCombineForTest enable_layout_ng_text_combine(true);
LoadAhem();
InsertStyleElement(
"body { margin: 0px; font: 100px/110px Ahem; }"
"c { text-combine-upright: all; }"
"div { writing-mode: vertical-rl; }");
SetBodyInnerHTML("<div id=root>a<c id=target>01234</c>b</div>");
EXPECT_EQ(R"DUMP(
{Line #descendants=5 LTR Standard} "0,0 110x300"
{Text 0-1 LTR Standard} "5,0 100x100"
{Box #descendants=2 Standard} "5,100 100x100"
{Box #descendants=1 AtomicInlineLTR Standard} "5,100 100x100"
{Text 2-3 LTR Standard} "5,200 100x100"
)DUMP",
AsFragmentItemsString(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("root"))));
EXPECT_EQ(R"DUMP(
{Line #descendants=2 LTR Standard} "0,0 100x100"
{Text 0-5 LTR Standard} "0,0 500x100"
)DUMP",
AsFragmentItemsString(*To<LayoutBlockFlow>(
GetLayoutObjectByElementId("target")->SlowFirstChild())));
}
// See also NGInlineLayoutAlgorithmTest.TextCombineBasic
TEST_F(NGInlineLayoutAlgorithmTest, TextCombineFake) {
ScopedLayoutNGTextCombineForTest enable_layout_ng_text_combine(true);
LoadAhem();
InsertStyleElement(
"body { margin: 0px; font: 100px/110px Ahem; }"
"c {"
" display: inline-block;"
" width: 1em; height: 1em;"
" writing-mode: horizontal-tb;"
"}"
"div { writing-mode: vertical-rl; }");
SetBodyInnerHTML("<div id=root>a<c id=target>0</c>b</div>");
EXPECT_EQ(R"DUMP(
{Line #descendants=4 LTR Standard} "0,0 110x300"
{Text 0-1 LTR Standard} "5,0 100x100"
{Box #descendants=1 AtomicInlineLTR Standard} "5,100 100x100"
{Text 2-3 LTR Standard} "5,200 100x100"
)DUMP",
AsFragmentItemsString(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("root"))));
EXPECT_EQ(R"DUMP(
{Line #descendants=2 LTR Standard} "0,0 100x110"
{Text 0-1 LTR Standard} "0,5 100x100"
)DUMP",
AsFragmentItemsString(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("target"))));
}
#undef MAYBE_VerticalAlignBottomReplaced
} // namespace
} // namespace blink
| bsd-3-clause |
arthurgwatidzo/dhis2-android-sdk | app/src/main/java/org/hisp/dhis/android/sdk/persistence/models/ImportCount.java | 3317 | /*
* Copyright (c) 2015, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.sdk.persistence.models;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
import org.hisp.dhis.android.sdk.persistence.Dhis2Database;
/**
* @author Simen Skogly Russnes on 24.02.15.
*/
@Table(databaseName = Dhis2Database.NAME)
public class ImportCount extends BaseModel{
@Column
@PrimaryKey(autoincrement = true)
protected int id;
@JsonProperty("imported")
@Column
private int imported;
@JsonProperty("updated")
@Column
private int updated;
@JsonProperty("ignored")
@Column
private int ignored;
@JsonProperty("deleted")
@Column
private int deleted;
@JsonAnySetter
public void handleUnknown(String key, Object value) {
// do something: put to a Map; log a warning, whatever
}
public int getId() {
return id;
}
public int getImported() {
return imported;
}
public int getUpdated() {
return updated;
}
public int getIgnored() {
return ignored;
}
public int getDeleted() {
return deleted;
}
public void setDeleted(int deleted) {
this.deleted = deleted;
}
public void setIgnored(int ignored) {
this.ignored = ignored;
}
public void setUpdated(int updated) {
this.updated = updated;
}
public void setImported(int imported) {
this.imported = imported;
}
public void setId(int id) {
this.id = id;
}
}
| bsd-3-clause |
leighpauls/k2cro4 | third_party/libjingle/source/talk/app/webrtc/jsep.h | 11642 | /*
* libjingle
* Copyright 2012, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Interfaces matching the draft-ietf-rtcweb-jsep-00.
// TODO(ronghuawu): Remove all the jsep-00 APIs (marked as deprecated) once
// chromium (WebKit and glue code) is ready. And update the comment above to
// jsep-01.
#ifndef TALK_APP_WEBRTC_JSEP_H_
#define TALK_APP_WEBRTC_JSEP_H_
#include <string>
#include <vector>
#include "talk/base/basictypes.h"
#include "talk/base/refcount.h"
namespace cricket {
class SessionDescription;
class Candidate;
} // namespace cricket
namespace webrtc {
class MediaConstraintsInterface;
class SessionDescriptionOptions {
public:
SessionDescriptionOptions() : has_audio_(true), has_video_(true) {}
SessionDescriptionOptions(bool receive_audio, bool receive_video)
: has_audio_(receive_audio),
has_video_(receive_video) {
}
// The peer wants to receive audio.
bool has_audio() const { return has_audio_; }
// The peer wants to receive video.
bool has_video() const { return has_video_; }
private:
bool has_audio_;
bool has_video_;
};
// Class used for describing what media a PeerConnection can receive.
class MediaHints { // Deprecated (jsep00)
public:
MediaHints() : has_audio_(true), has_video_(true) {}
MediaHints(bool receive_audio, bool receive_video)
: has_audio_(receive_audio),
has_video_(receive_video) {
}
// The peer wants to receive audio.
bool has_audio() const { return has_audio_; }
// The peer wants to receive video.
bool has_video() const { return has_video_; }
private:
bool has_audio_;
bool has_video_;
};
// Class representation of an ICE candidate.
// An instance of this interface is supposed to be owned by one class at
// a time and is therefore not expected to be thread safe.
class IceCandidateInterface {
public:
virtual ~IceCandidateInterface() {}
/// If present, this contains the identierfier of the "media stream
// identification" as defined in [RFC 3388] for m-line this candidate is
// assocated with.
virtual std::string sdp_mid() const = 0;
// This indeicates the index (starting at zero) of m-line in the SDP this
// candidate is assocated with.
virtual int sdp_mline_index() const = 0;
virtual const cricket::Candidate& candidate() const = 0;
// Creates a SDP-ized form of this candidate.
virtual bool ToString(std::string* out) const = 0;
};
// Creates a IceCandidateInterface based on SDP string.
// Returns NULL if the sdp string can't be parsed.
IceCandidateInterface* CreateIceCandidate(const std::string& sdp_mid,
int sdp_mline_index,
const std::string& sdp);
// This class represents a collection of candidates for a specific m-line.
// This class is used in SessionDescriptionInterface to represent all known
// candidates for a certain m-line.
class IceCandidateCollection {
public:
virtual ~IceCandidateCollection() {}
virtual size_t count() const = 0;
// Returns true if an equivalent |candidate| exist in the collection.
virtual bool HasCandidate(const IceCandidateInterface* candidate) const = 0;
virtual const IceCandidateInterface* at(size_t index) const = 0;
};
// Class representation of a Session description.
// An instance of this interface is supposed to be owned by one class at
// a time and is therefore not expected to be thread safe.
class SessionDescriptionInterface {
public:
// Supported types:
static const char kOffer[];
static const char kPrAnswer[];
static const char kAnswer[];
virtual ~SessionDescriptionInterface() {}
virtual cricket::SessionDescription* description() = 0;
virtual const cricket::SessionDescription* description() const = 0;
// Get the session id and session version, which are defined based on
// RFC 4566 for the SDP o= line.
virtual std::string session_id() const = 0;
virtual std::string session_version() const = 0;
virtual std::string type() const = 0;
// Adds the specified candidate to the description.
// Ownership is not transferred.
// Returns false if the session description does not have a media section that
// corresponds to the |candidate| label.
virtual bool AddCandidate(const IceCandidateInterface* candidate) = 0;
// Returns the number of m- lines in the session description.
virtual size_t number_of_mediasections() const = 0;
// Returns a collection of all candidates that belong to a certain m-line
virtual const IceCandidateCollection* candidates(
size_t mediasection_index) const = 0;
// Serializes the description to SDP.
virtual bool ToString(std::string* out) const = 0;
};
// Deprecated (jsep00)
SessionDescriptionInterface* CreateSessionDescription(const std::string& sdp);
// Creates a SessionDescriptionInterface based on SDP string and the type.
// Returns NULL if the sdp string can't be parsed or the type is unsupported.
SessionDescriptionInterface* CreateSessionDescription(const std::string& type,
const std::string& sdp);
// Jsep Ice candidate callback interface. An application should implement these
// methods to be notified of new local candidates.
class IceCandidateObserver {
public:
// TODO(ronghuawu): Implement OnIceChange.
// Called any time the iceState changes.
virtual void OnIceChange() {}
// New Ice candidate have been found.
virtual void OnIceCandidate(const IceCandidateInterface* candidate) = 0;
// All Ice candidates have been found.
// Deprecated (jsep00)
virtual void OnIceComplete() {}
protected:
~IceCandidateObserver() {}
};
// Jsep CreateOffer and CreateAnswer callback interface.
class CreateSessionDescriptionObserver : public talk_base::RefCountInterface {
public:
// The implementation of the CreateSessionDescriptionObserver takes
// the ownership of the |desc|.
virtual void OnSuccess(SessionDescriptionInterface* desc) = 0;
virtual void OnFailure(const std::string& error) = 0;
protected:
~CreateSessionDescriptionObserver() {}
};
// Jsep SetLocalDescription and SetRemoteDescription callback interface.
class SetSessionDescriptionObserver : public talk_base::RefCountInterface {
public:
virtual void OnSuccess() = 0;
virtual void OnFailure(const std::string& error) = 0;
protected:
~SetSessionDescriptionObserver() {}
};
// Interface for implementing Jsep. PeerConnection implements these functions.
class JsepInterface {
public:
// Indicates the type of SessionDescription in a call to SetLocalDescription
// and SetRemoteDescription.
// Deprecated (jsep00)
enum Action {
kOffer,
kPrAnswer,
kAnswer,
};
// Indicates what types of local candidates should be used.
// Deprecated (jsep00)
enum IceOptions {
kUseAll,
kNoRelay,
kOnlyRelay
};
struct IceServer {
std::string uri;
std::string password;
};
typedef std::vector<IceServer> IceServers;
// Deprecated (jsep00)
virtual SessionDescriptionInterface* CreateOffer(const MediaHints& hints) = 0;
// Deprecated (jsep00)
// Create an answer to an offer. Returns NULL if an answer can't be created.
virtual SessionDescriptionInterface* CreateAnswer(
const MediaHints& hints,
const SessionDescriptionInterface* offer) = 0;
// Deprecated (jsep00)
// Starts or updates the ICE Agent process of
// gathering local candidates and pinging remote candidates.
// SetLocalDescription must be called before calling this method.
virtual bool StartIce(IceOptions options) = 0;
// Deprecated (jsep00)
// Sets the local session description.
// JsepInterface take ownership of |desc|.
virtual bool SetLocalDescription(Action action,
SessionDescriptionInterface* desc) = 0;
// Deprecated (jsep00)
// Sets the remote session description.
// JsepInterface take ownership of |desc|.
virtual bool SetRemoteDescription(Action action,
SessionDescriptionInterface* desc) = 0;
// Deprecated (jsep00)
// Processes received ICE information.
virtual bool ProcessIceMessage(
const IceCandidateInterface* ice_candidate) = 0;
virtual const SessionDescriptionInterface* local_description() const = 0;
virtual const SessionDescriptionInterface* remote_description() const = 0;
// JSEP01
// Create a new offer.
// The CreateSessionDescriptionObserver callback will be called when done.
virtual void CreateOffer(CreateSessionDescriptionObserver* observer,
const MediaConstraintsInterface* constraints) = 0;
// Create an answer to an offer.
// The CreateSessionDescriptionObserver callback will be called when done.
virtual void CreateAnswer(CreateSessionDescriptionObserver* observer,
const MediaConstraintsInterface* constraints) = 0;
// Sets the local session description.
// JsepInterface takes the ownership of |desc| even if it fails.
// The |observer| callback will be called when done.
virtual void SetLocalDescription(SetSessionDescriptionObserver* observer,
SessionDescriptionInterface* desc) = 0;
// Sets the remote session description.
// JsepInterface takes the ownership of |desc| even if it fails.
// The |observer| callback will be called when done.
virtual void SetRemoteDescription(SetSessionDescriptionObserver* observer,
SessionDescriptionInterface* desc) = 0;
// Restarts or updates the ICE Agent process of gathering local candidates
// and pinging remote candidates.
virtual bool UpdateIce(const IceServers& configuration,
const MediaConstraintsInterface* constraints) = 0;
// Provides a remote candidate to the ICE Agent.
// A copy of the |candidate| will be created and added to the remote
// description. So the caller of this method still has the ownership of the
// |candidate|.
// TODO(ronghuawu): Consider to change this so that the AddIceCandidate will
// take the ownership of the |candidate|.
virtual bool AddIceCandidate(const IceCandidateInterface* candidate) = 0;
protected:
virtual ~JsepInterface() {}
};
} // namespace webrtc
#endif // TALK_APP_WEBRTC_JSEP_H_
| bsd-3-clause |
endlessm/chromium-browser | third_party/protobuf/java/core/src/main/java/com/google/protobuf/LongArrayList.java | 7711 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.google.protobuf;
import static com.google.protobuf.Internal.checkNotNull;
import com.google.protobuf.Internal.LongList;
import java.util.Arrays;
import java.util.Collection;
import java.util.RandomAccess;
/**
* An implementation of {@link LongList} on top of a primitive array.
*
* @author [email protected] (Daniel Weis)
*/
final class LongArrayList extends AbstractProtobufList<Long>
implements LongList, RandomAccess, PrimitiveNonBoxingCollection {
private static final LongArrayList EMPTY_LIST = new LongArrayList(new long[0], 0);
static {
EMPTY_LIST.makeImmutable();
}
public static LongArrayList emptyList() {
return EMPTY_LIST;
}
/** The backing store for the list. */
private long[] array;
/**
* The size of the list distinct from the length of the array. That is, it is the number of
* elements set in the list.
*/
private int size;
/** Constructs a new mutable {@code LongArrayList} with default capacity. */
LongArrayList() {
this(new long[DEFAULT_CAPACITY], 0);
}
/**
* Constructs a new mutable {@code LongArrayList} containing the same elements as {@code other}.
*/
private LongArrayList(long[] other, int size) {
array = other;
this.size = size;
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
ensureIsMutable();
if (toIndex < fromIndex) {
throw new IndexOutOfBoundsException("toIndex < fromIndex");
}
System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
size -= (toIndex - fromIndex);
modCount++;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof LongArrayList)) {
return super.equals(o);
}
LongArrayList other = (LongArrayList) o;
if (size != other.size) {
return false;
}
final long[] arr = other.array;
for (int i = 0; i < size; i++) {
if (array[i] != arr[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int result = 1;
for (int i = 0; i < size; i++) {
result = (31 * result) + Internal.hashLong(array[i]);
}
return result;
}
@Override
public LongList mutableCopyWithCapacity(int capacity) {
if (capacity < size) {
throw new IllegalArgumentException();
}
return new LongArrayList(Arrays.copyOf(array, capacity), size);
}
@Override
public Long get(int index) {
return getLong(index);
}
@Override
public long getLong(int index) {
ensureIndexInRange(index);
return array[index];
}
@Override
public int size() {
return size;
}
@Override
public Long set(int index, Long element) {
return setLong(index, element);
}
@Override
public long setLong(int index, long element) {
ensureIsMutable();
ensureIndexInRange(index);
long previousValue = array[index];
array[index] = element;
return previousValue;
}
@Override
public void add(int index, Long element) {
addLong(index, element);
}
/** Like {@link #add(Long)} but more efficient in that it doesn't box the element. */
@Override
public void addLong(long element) {
addLong(size, element);
}
/** Like {@link #add(int, Long)} but more efficient in that it doesn't box the element. */
private void addLong(int index, long element) {
ensureIsMutable();
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index));
}
if (size < array.length) {
// Shift everything over to make room
System.arraycopy(array, index, array, index + 1, size - index);
} else {
// Resize to 1.5x the size
int length = ((size * 3) / 2) + 1;
long[] newArray = new long[length];
// Copy the first part directly
System.arraycopy(array, 0, newArray, 0, index);
// Copy the rest shifted over by one to make room
System.arraycopy(array, index, newArray, index + 1, size - index);
array = newArray;
}
array[index] = element;
size++;
modCount++;
}
@Override
public boolean addAll(Collection<? extends Long> collection) {
ensureIsMutable();
checkNotNull(collection);
// We specialize when adding another LongArrayList to avoid boxing elements.
if (!(collection instanceof LongArrayList)) {
return super.addAll(collection);
}
LongArrayList list = (LongArrayList) collection;
if (list.size == 0) {
return false;
}
int overflow = Integer.MAX_VALUE - size;
if (overflow < list.size) {
// We can't actually represent a list this large.
throw new OutOfMemoryError();
}
int newSize = size + list.size;
if (newSize > array.length) {
array = Arrays.copyOf(array, newSize);
}
System.arraycopy(list.array, 0, array, size, list.size);
size = newSize;
modCount++;
return true;
}
@Override
public boolean remove(Object o) {
ensureIsMutable();
for (int i = 0; i < size; i++) {
if (o.equals(array[i])) {
System.arraycopy(array, i + 1, array, i, size - i - 1);
size--;
modCount++;
return true;
}
}
return false;
}
@Override
public Long remove(int index) {
ensureIsMutable();
ensureIndexInRange(index);
long value = array[index];
if (index < size - 1) {
System.arraycopy(array, index + 1, array, index, size - index - 1);
}
size--;
modCount++;
return value;
}
/**
* Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an
* {@link IndexOutOfBoundsException} if it is not.
*
* @param index the index to verify is in range
*/
private void ensureIndexInRange(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index));
}
}
private String makeOutOfBoundsExceptionMessage(int index) {
return "Index:" + index + ", Size:" + size;
}
}
| bsd-3-clause |
Crystalnix/house-of-life-chromium | content/common/gpu/media/mft_angle_video_device.cc | 1786 | // Copyright (c) 2011 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 "content/common/gpu/media/mft_angle_video_device.h"
#include <d3d9.h>
#include "media/base/video_frame.h"
#include "third_party/angle/src/libGLESv2/main.h"
MftAngleVideoDevice::MftAngleVideoDevice()
: device_(reinterpret_cast<egl::Display*>(
eglGetCurrentDisplay())->getDevice()) {
}
void* MftAngleVideoDevice::GetDevice() {
return device_;
}
bool MftAngleVideoDevice::CreateVideoFrameFromGlTextures(
size_t width, size_t height, media::VideoFrame::Format format,
const std::vector<media::VideoFrame::GlTexture>& textures,
scoped_refptr<media::VideoFrame>* frame) {
media::VideoFrame::GlTexture texture_array[media::VideoFrame::kMaxPlanes];
memset(texture_array, 0, sizeof(texture_array));
for (size_t i = 0; i < textures.size(); ++i) {
texture_array[i] = textures[i];
}
media::VideoFrame::CreateFrameGlTexture(format,
width,
height,
texture_array,
frame);
return *frame != NULL;
}
void MftAngleVideoDevice::ReleaseVideoFrame(
const scoped_refptr<media::VideoFrame>& frame) {
// We didn't need to anything here because we didn't allocate any resources
// for the VideoFrame(s) generated.
}
bool MftAngleVideoDevice::ConvertToVideoFrame(
void* buffer, scoped_refptr<media::VideoFrame> frame) {
gl::Context* context = (gl::Context*)eglGetCurrentContext();
// TODO(hclam): Connect ANGLE to upload the surface to texture when changes
// to ANGLE is done.
return true;
}
| bsd-3-clause |
codeaudit/Foundry | Components/CommonCore/Test/gov/sandia/cognition/evaluator/AbstractStatefulEvaluatorTest.java | 5498 | /*
* File: AbstractStatefulEvaluatorTest.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright Jul 7, 2009, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government.
* Export of this program may require a license from the United States
* Government. See CopyrightHistory.txt for complete details.
*
*/
package gov.sandia.cognition.evaluator;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.math.matrix.mtj.Vector3;
import gov.sandia.cognition.util.ObjectUtil;
import junit.framework.TestCase;
import java.util.Random;
/**
* Unit tests for AbstractStatefulEvaluatorTest.
*
* @author krdixon
*/
public class AbstractStatefulEvaluatorTest
extends TestCase
{
/**
* Random number generator to use for a fixed random seed.
*/
public final Random RANDOM = new Random( 1 );
/**
* Default tolerance of the regression tests, {@value}.
*/
public final double TOLERANCE = 1e-5;
/**
* Tests for class AbstractStatefulEvaluatorTest.
* @param testName Name of the test.
*/
public AbstractStatefulEvaluatorTest(
String testName)
{
super(testName);
}
public static class StatefulFunction
extends AbstractStatefulEvaluator<Vector,Vector,Vector>
{
public StatefulFunction()
{
super();
}
public StatefulFunction(
Vector state )
{
super( state );
}
public Vector createDefaultState()
{
return new Vector3(1.0,2.0,3.0);
}
public Vector evaluate(
Vector input)
{
this.getState().plusEquals(input);
return this.getState();
}
}
public Vector createRandomInput()
{
return Vector3.createRandom(RANDOM);
}
public StatefulFunction createInstance()
{
return new StatefulFunction(this.createRandomInput());
}
/**
* Tests the constructors of class AbstractStatefulEvaluatorTest.
*/
public void testConstructors()
{
System.out.println( "Constructors" );
StatefulFunction f = new StatefulFunction();
assertEquals( f.createDefaultState(), f.getState() );
Vector x = this.createRandomInput();
f = new StatefulFunction( x );
assertSame( x, f.getState() );
}
/**
* Test of clone method, of class AbstractStatefulEvaluator.
*/
public void testClone()
{
System.out.println("clone");
StatefulFunction f = this.createInstance();
StatefulFunction clone = (StatefulFunction) f.clone();
System.out.println( "f:\n" + ObjectUtil.toString(f) );
System.out.println( "clone:\n" + ObjectUtil.toString(clone) );
assertNotNull( clone );
assertNotSame( f, clone );
assertNotNull( clone.getState() );
assertNotSame( f.getState(), clone.getState() );
assertEquals( f.getState(), clone.getState() );
assertFalse( clone.getState().equals( clone.createDefaultState() ) );
Vector originalState = f.getState().clone();
assertEquals( originalState, f.getState() );
assertEquals( originalState, clone.getState() );
clone.getState().scaleEquals(RANDOM.nextDouble());
assertEquals( originalState, f.getState() );
assertFalse( originalState.equals( clone.getState() ) );
}
/**
* evaluate(state)
*/
public void testEvaluateState()
{
System.out.println( "evaluate(State)" );
StatefulFunction f = this.createInstance();
Vector defaultState = f.createDefaultState();
f.resetState();
Vector input = this.createRandomInput();
Vector o1 = f.evaluate(input);
Vector o2 = f.evaluate(input, defaultState );
assertNotSame( o1, o2 );
assertEquals( o1, o2 );
}
/**
* Test of evaluate method, of class AbstractStatefulEvaluator.
*/
public void testEvaluate()
{
System.out.println("evaluate");
StatefulFunction f = this.createInstance();
Vector originalState = f.getState().clone();
f.evaluate(this.createRandomInput());
assertFalse( originalState.equals( f.getState() ) );
}
/**
* Test of getState method, of class AbstractStatefulEvaluator.
*/
public void testGetState()
{
System.out.println("getState");
StatefulFunction f = this.createInstance();
assertNotNull( f.getState() );
}
/**
* Test of setState method, of class AbstractStatefulEvaluator.
*/
public void testSetState()
{
System.out.println("setState");
StatefulFunction f = this.createInstance();
Vector s = this.createRandomInput();
f.setState(s);
assertSame( s, f.getState() );
}
/**
* Test of resetState method, of class AbstractStatefulEvaluator.
*/
public void testResetState()
{
System.out.println("resetState");
StatefulFunction f = this.createInstance();
Vector v = f.createDefaultState();
assertFalse( v.equals( f.getState() ) );
f.resetState();
assertEquals( v, f.getState() );
}
}
| bsd-3-clause |
pawelmhm/splash | splash/response_middleware.py | 2510 | # -*- coding: utf-8 -*-
"""
Classes that process (and maybe abort) responses based on
various conditions. They should be used with
:class:`splash.network_manager.SplashQNetworkAccessManager`.
"""
from __future__ import absolute_import
from PyQt5.QtNetwork import QNetworkRequest
from splash.qtutils import request_repr
from twisted.python import log
import fnmatch
class ContentTypeMiddleware(object):
"""
Response middleware, aborts responses depending on the content type.
A response will be aborted (and the underlying connection closed) after
receiving the response headers if the content type of the response is not
in the whitelist or it's in the blacklist. Both lists support wildcards.
"""
def __init__(self, verbosity=0):
self.verbosity = verbosity
@staticmethod
def contains(mime_set, mime):
"""
>>> ContentTypeMiddleware.contains({'*/*'}, 'any/thing')
True
>>> ContentTypeMiddleware.contains(set(), 'any/thing')
False
>>> ContentTypeMiddleware.contains({'text/css', 'image/*'}, 'image/png')
True
>>> ContentTypeMiddleware.contains({'*'}, 'any-thing')
True
"""
for pattern in mime_set:
if fnmatch.fnmatch(mime, pattern):
return True
return False
@staticmethod
def clean_mime(mime):
"""
Remove attributes from a mime string:
>>> ContentTypeMiddleware.clean_mime(' text/html; charset=utf-8\t ')
'text/html'
"""
separator = mime.find(';')
if separator > 0:
mime = mime[:separator]
return mime.strip()
def process(self, reply, render_options):
content_type = reply.header(QNetworkRequest.ContentTypeHeader)
if content_type is None:
return
mimetype = self.clean_mime(content_type)
allowed = render_options.get_allowed_content_types()
forbidden = render_options.get_forbidden_content_types()
whitelist = set(map(ContentTypeMiddleware.clean_mime, allowed))
blacklist = set(map(ContentTypeMiddleware.clean_mime, forbidden))
if self.contains(blacklist, mimetype) or not self.contains(whitelist, mimetype):
if self.verbosity >= 2:
request_str = request_repr(reply, reply.operation())
msg = "Dropping %s because of Content Type" % request_str
log.msg(msg, system='response_middleware')
reply.abort()
| bsd-3-clause |
darkrsw/safe | tests/typing_tests/TAJS_micro/test2.js | 68 | //2
var __result1 = 2; // for SAFE
var __expect1 = 2; // for SAFE
| bsd-3-clause |
ychen820/microblog | src/application/templates/base.html | 2403 | <!DOCTYPE html>
<html lang="en" class="no-js">
{% set bootstrap_version = '3.0.0' %}
{% set modernizer_version = '2.6.2' %}
{% set jquery_version = '1.9.1' %}
{% set parsley_version = '1.1.16' %}
{% set awesome_version = '4.0.1' %}
{% set bootswatch_version = '3.0.0' %}
{% set bootswatch_theme = 'cyborg' %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>{% block title%}Flask on App Engine{% endblock %}</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/{{ bootstrap_version }}/css/bootstrap.min.css" rel="stylesheet" />
<link href="//netdna.bootstrapcdn.com/font-awesome/{{ awesome_version }}/css/font-awesome.min.css" rel="stylesheet" >
<link href="//netdna.bootstrapcdn.com/bootswatch/{{ bootswatch_version }}/{{ bootswatch_theme }}/bootstrap.min.css" rel="stylesheet" >
<style> </style> <!-- Bootstrap -->
<link href="/static/css/main.css" rel="stylesheet" />
<link rel="shortcut icon" href="/static/img/favicon.ico" />
{% block style_block %}{# page-specific CSS #}{% endblock %}
<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/{{ modernizer_version }}/modernizr.min.js"></script>{# Modernizr must be here, above body tag. #}
{% block head_script %}{# defer-incapable JS block #}{% endblock %}
</head>
<body>
{% include 'includes/nav.html' %} {# pull in navbar #}
<div class="container" id="maincontent">
{% include 'includes/flash_message.html' %} {# page-level feedback notices #}
<div id="body_content">
{% block content %}{# main content area #}{% endblock %}
</div>
</div><!-- /container -->
<footer>
<div id="footer" class="container">
{% block footer %}{% endblock %}
</div><!-- /footer -->
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/{{ jquery_version }}/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/{{ bootstrap_version }}/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/parsley.js/{{ parsley_version }}/parsley-standalone.min.js"></script>
<script src="/static/js/main.js"></script>
{% block tail_script %}{# defer-capable JS block #}{% endblock %}
{{ profiler_includes|safe }}
</body>
</html>
| bsd-3-clause |
ric2b/Vivaldi-browser | chromium/chrome/browser/resources/settings/chromeos/os_a11y_page/manage_a11y_page.js | 23701 | // Copyright 2016 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.
/** @const {number} */
const DEFAULT_BLACK_CURSOR_COLOR = 0;
/**
* @fileoverview
* 'settings-manage-a11y-page' is the subpage with the accessibility
* settings.
*/
import {afterNextRender, Polymer, html, flush, Templatizer, TemplateInstanceBase} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import '//resources/cr_elements/cr_link_row/cr_link_row.js';
import '//resources/cr_elements/icons.m.js';
import '//resources/cr_elements/shared_vars_css.m.js';
import {WebUIListenerBehavior} from '//resources/js/web_ui_listener_behavior.m.js';
import {I18nBehavior} from '//resources/js/i18n_behavior.m.js';
import {loadTimeData} from '//resources/js/load_time_data.m.js';
import '../../controls/settings_slider.js';
import '../../controls/settings_toggle_button.js';
import {DeepLinkingBehavior} from '../deep_linking_behavior.m.js';
import {routes} from '../os_route.m.js';
import {Router, Route} from '../../router.js';
import {RouteObserverBehavior} from '../route_observer_behavior.js';
import '../../settings_shared_css.js';
import {BatteryStatus, DevicePageBrowserProxy, DevicePageBrowserProxyImpl, ExternalStorage, IdleBehavior, LidClosedBehavior, NoteAppInfo, NoteAppLockScreenSupport, PowerManagementSettings, PowerSource, getDisplayApi, StorageSpaceState} from '../device_page/device_page_browser_proxy.js';
import '//resources/cr_components/chromeos/localized_link/localized_link.js';
import {RouteOriginBehaviorImpl, RouteOriginBehavior} from '../route_origin_behavior.m.js';
import {ManageA11yPageBrowserProxyImpl, ManageA11yPageBrowserProxy} from './manage_a11y_page_browser_proxy.js';
Polymer({
_template: html`{__html_template__}`,
is: 'settings-manage-a11y-page',
behaviors: [
DeepLinkingBehavior,
I18nBehavior,
RouteObserverBehavior,
RouteOriginBehavior,
WebUIListenerBehavior,
],
properties: {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* Enum values for the 'settings.a11y.screen_magnifier_mouse_following_mode'
* preference. These values map to
* AccessibilityController::MagnifierMouseFollowingMode, and are written to
* prefs and metrics, so order should not be changed.
* @private {!Object<string, number>}
*/
screenMagnifierMouseFollowingModePrefValues_: {
readOnly: true,
type: Object,
value: {
CONTINUOUS: 0,
CENTERED: 1,
EDGE: 2,
},
},
screenMagnifierZoomOptions_: {
readOnly: true,
type: Array,
value() {
// These values correspond to the i18n values in settings_strings.grdp.
// If these values get changed then those strings need to be changed as
// well.
return [
{value: 2, name: loadTimeData.getString('screenMagnifierZoom2x')},
{value: 4, name: loadTimeData.getString('screenMagnifierZoom4x')},
{value: 6, name: loadTimeData.getString('screenMagnifierZoom6x')},
{value: 8, name: loadTimeData.getString('screenMagnifierZoom8x')},
{value: 10, name: loadTimeData.getString('screenMagnifierZoom10x')},
{value: 12, name: loadTimeData.getString('screenMagnifierZoom12x')},
{value: 14, name: loadTimeData.getString('screenMagnifierZoom14x')},
{value: 16, name: loadTimeData.getString('screenMagnifierZoom16x')},
{value: 18, name: loadTimeData.getString('screenMagnifierZoom18x')},
{value: 20, name: loadTimeData.getString('screenMagnifierZoom20x')},
];
},
},
autoClickDelayOptions_: {
readOnly: true,
type: Array,
value() {
// These values correspond to the i18n values in settings_strings.grdp.
// If these values get changed then those strings need to be changed as
// well.
return [
{
value: 600,
name: loadTimeData.getString('delayBeforeClickExtremelyShort')
},
{
value: 800,
name: loadTimeData.getString('delayBeforeClickVeryShort')
},
{value: 1000, name: loadTimeData.getString('delayBeforeClickShort')},
{value: 2000, name: loadTimeData.getString('delayBeforeClickLong')},
{
value: 4000,
name: loadTimeData.getString('delayBeforeClickVeryLong')
},
];
},
},
autoClickMovementThresholdOptions_: {
readOnly: true,
type: Array,
value() {
return [
{
value: 5,
name: loadTimeData.getString('autoclickMovementThresholdExtraSmall')
},
{
value: 10,
name: loadTimeData.getString('autoclickMovementThresholdSmall')
},
{
value: 20,
name: loadTimeData.getString('autoclickMovementThresholdDefault')
},
{
value: 30,
name: loadTimeData.getString('autoclickMovementThresholdLarge')
},
{
value: 40,
name: loadTimeData.getString('autoclickMovementThresholdExtraLarge')
},
];
},
},
/** @private {!Array<{name: string, value: number}>} */
cursorColorOptions_: {
readOnly: true,
type: Array,
value() {
return [
{
value: DEFAULT_BLACK_CURSOR_COLOR,
name: loadTimeData.getString('cursorColorBlack'),
},
{
value: 0xd93025, // Red 600
name: loadTimeData.getString('cursorColorRed'),
},
{
value: 0xf29900, // Yellow 700
name: loadTimeData.getString('cursorColorYellow'),
},
{
value: 0x1e8e3e, // Green 600
name: loadTimeData.getString('cursorColorGreen'),
},
{
value: 0x03b6be, // Cyan 600
name: loadTimeData.getString('cursorColorCyan'),
},
{
value: 0x1a73e8, // Blue 600
name: loadTimeData.getString('cursorColorBlue'),
},
{
value: 0xc61ad9, // Magenta 600
name: loadTimeData.getString('cursorColorMagenta'),
},
{
value: 0xf50057, // Pink A400
name: loadTimeData.getString('cursorColorPink'),
},
];
},
},
/** @private */
isMagnifierContinuousMouseFollowingModeSettingEnabled_: {
type: Boolean,
value() {
return loadTimeData.getBoolean(
'isMagnifierContinuousMouseFollowingModeSettingEnabled');
},
},
/**
* Whether the user is in kiosk mode.
* @private
*/
isKioskModeActive_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('isKioskModeActive');
}
},
/**
* Whether a setting for enabling shelf navigation buttons in tablet mode
* should be displayed in the accessibility settings.
* @private
*/
showShelfNavigationButtonsSettings_: {
type: Boolean,
computed:
'computeShowShelfNavigationButtonsSettings_(isKioskModeActive_)',
},
/** @private */
isGuest_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('isGuest');
}
},
/** @private */
screenMagnifierHintLabel_: {
type: String,
value() {
return this.i18n(
'screenMagnifierHintLabel',
this.i18n('screenMagnifierHintSearchKey'));
}
},
/** @private */
dictationSubtitle_: {
type: String,
value() {
return loadTimeData.getString('dictationDescription');
}
},
/** @private */
dictationLocaleSubtitleOverride_: {
type: String,
value: '',
},
/** @private */
useDictationLocaleSubtitleOverride_: {
type: Boolean,
value: false,
},
/** @private */
dictationLocaleMenuSubtitle_: {
type: String,
computed: 'computeDictationLocaleSubtitle_(' +
'dictationLocaleOptions_, ' +
'prefs.settings.a11y.dictation_locale.value, ' +
'dictationLocaleSubtitleOverride_)',
},
/** @private */
areDictationLocalePrefsAllowed_: {
type: Boolean,
readOnly: true,
value() {
return loadTimeData.getBoolean('areDictationLocalePrefsAllowed');
}
},
/** @private */
dictationLocaleOptions_: {
type: Array,
value() {
return [];
}
},
/** @private */
dictationLocalesList_: {
type: Array,
value() {
return [];
}
},
/** @private */
showDictationLocaleMenu_: {
type: Boolean,
value: false,
},
/**
* |hasKeyboard_|, |hasMouse_|, |hasPointingStick_|, and |hasTouchpad_|
* start undefined so observers don't trigger until they have been
* populated.
* @private
*/
hasKeyboard_: Boolean,
/** @private */
hasMouse_: Boolean,
/** @private */
hasPointingStick_: Boolean,
/** @private */
hasTouchpad_: Boolean,
/**
* Boolean indicating whether shelf navigation buttons should implicitly be
* enabled in tablet mode - the navigation buttons are implicitly enabled
* when spoken feedback, automatic clicks, or switch access are enabled.
* The buttons can also be explicitly enabled by a designated a11y setting.
* @private
*/
shelfNavigationButtonsImplicitlyEnabled_: {
type: Boolean,
computed: 'computeShelfNavigationButtonsImplicitlyEnabled_(' +
'prefs.settings.accessibility.value,' +
'prefs.settings.a11y.autoclick.value,' +
'prefs.settings.a11y.switch_access.enabled.value)',
},
/**
* The effective pref value that indicates whether shelf navigation buttons
* are enabled in tablet mode.
* @type {chrome.settingsPrivate.PrefObject}
* @private
*/
shelfNavigationButtonsPref_: {
type: Object,
computed: 'getShelfNavigationButtonsEnabledPref_(' +
'shelfNavigationButtonsImplicitlyEnabled_,' +
'prefs.settings.a11y.tablet_mode_shelf_nav_buttons_enabled)',
},
/**
* Used by DeepLinkingBehavior to focus this page's deep links.
* @type {!Set<!chromeos.settings.mojom.Setting>}
*/
supportedSettingIds: {
type: Object,
value: () => new Set([
chromeos.settings.mojom.Setting.kChromeVox,
chromeos.settings.mojom.Setting.kSelectToSpeak,
chromeos.settings.mojom.Setting.kHighContrastMode,
chromeos.settings.mojom.Setting.kFullscreenMagnifier,
chromeos.settings.mojom.Setting.kFullscreenMagnifierMouseFollowingMode,
chromeos.settings.mojom.Setting.kFullscreenMagnifierFocusFollowing,
chromeos.settings.mojom.Setting.kDockedMagnifier,
chromeos.settings.mojom.Setting.kStickyKeys,
chromeos.settings.mojom.Setting.kOnScreenKeyboard,
chromeos.settings.mojom.Setting.kDictation,
chromeos.settings.mojom.Setting.kHighlightKeyboardFocus,
chromeos.settings.mojom.Setting.kHighlightTextCaret,
chromeos.settings.mojom.Setting.kAutoClickWhenCursorStops,
chromeos.settings.mojom.Setting.kLargeCursor,
chromeos.settings.mojom.Setting.kHighlightCursorWhileMoving,
chromeos.settings.mojom.Setting.kTabletNavigationButtons,
chromeos.settings.mojom.Setting.kMonoAudio,
chromeos.settings.mojom.Setting.kStartupSound,
chromeos.settings.mojom.Setting.kEnableSwitchAccess,
chromeos.settings.mojom.Setting.kEnableCursorColor,
]),
},
},
observers: [
'pointersChanged_(hasMouse_, hasPointingStick_, hasTouchpad_, ' +
'isKioskModeActive_)',
],
/** RouteOriginBehavior override */
route_: routes.MANAGE_ACCESSIBILITY,
/** @private {?ManageA11yPageBrowserProxy} */
manageBrowserProxy_: null,
/** @private {?DevicePageBrowserProxy} */
deviceBrowserProxy_: null,
/** @override */
created() {
this.manageBrowserProxy_ = ManageA11yPageBrowserProxyImpl.getInstance();
this.deviceBrowserProxy_ = DevicePageBrowserProxyImpl.getInstance();
},
/** @override */
attached() {
this.addWebUIListener(
'has-mouse-changed', (exists) => this.set('hasMouse_', exists));
this.addWebUIListener(
'has-pointing-stick-changed',
(exists) => this.set('hasPointingStick_', exists));
this.addWebUIListener(
'has-touchpad-changed', (exists) => this.set('hasTouchpad_', exists));
this.deviceBrowserProxy_.initializePointers();
this.addWebUIListener(
'has-hardware-keyboard',
(hasKeyboard) => this.set('hasKeyboard_', hasKeyboard));
this.deviceBrowserProxy_.initializeKeyboardWatcher();
},
/** @override */
ready() {
this.addWebUIListener(
'initial-data-ready',
(startup_sound_enabled) =>
this.onManageAllyPageReady_(startup_sound_enabled));
this.addWebUIListener(
'dictation-locale-menu-subtitle-changed',
(result) => this.onDictationLocaleMenuSubtitleChanged_(result));
this.addWebUIListener(
'dictation-locales-set',
(locales) => this.onDictationLocalesSet_(locales));
this.manageBrowserProxy_.manageA11yPageReady();
const r = routes;
this.addFocusConfig_(r.MANAGE_TTS_SETTINGS, '#ttsSubpageButton');
this.addFocusConfig_(r.MANAGE_CAPTION_SETTINGS, '#captionsSubpageButton');
this.addFocusConfig_(
r.MANAGE_SWITCH_ACCESS_SETTINGS, '#switchAccessSubpageButton');
this.addFocusConfig_(r.DISPLAY, '#displaySubpageButton');
this.addFocusConfig_(r.KEYBOARD, '#keyboardSubpageButton');
this.addFocusConfig_(r.POINTERS, '#pointerSubpageButton');
},
/**
* @param {!Route} route
* @param {!Route} oldRoute
*/
currentRouteChanged(route, oldRoute) {
// Does not apply to this page.
if (route !== routes.MANAGE_ACCESSIBILITY) {
return;
}
this.attemptDeepLink();
},
/**
* @param {boolean} hasMouse
* @param {boolean} hasPointingStick
* @param {boolean} hasTouchpad
* @private
*/
pointersChanged_(hasMouse, hasTouchpad, hasPointingStick, isKioskModeActive) {
this.$.pointerSubpageButton.hidden =
(!hasMouse && !hasPointingStick && !hasTouchpad) || isKioskModeActive;
},
/**
* Updates the Select-to-Speak description text based on:
* 1. Whether Select-to-Speak is enabled.
* 2. If it is enabled, whether a physical keyboard is present.
* @param {boolean} enabled
* @param {boolean} hasKeyboard
* @param {string} disabledString String to show when Select-to-Speak is
* disabled.
* @param {string} keyboardString String to show when there is a physical
* keyboard
* @param {string} noKeyboardString String to show when there is no keyboard
* @private
*/
getSelectToSpeakDescription_(
enabled, hasKeyboard, disabledString, keyboardString, noKeyboardString) {
return !enabled ? disabledString :
hasKeyboard ? keyboardString : noKeyboardString;
},
/**
* @param {!CustomEvent<boolean>} e
* @private
*/
toggleStartupSoundEnabled_(e) {
this.manageBrowserProxy_.setStartupSoundEnabled(e.detail);
},
/** @private */
onManageTtsSettingsTap_() {
Router.getInstance().navigateTo(routes.MANAGE_TTS_SETTINGS);
},
/** @private */
onChromeVoxSettingsTap_() {
this.manageBrowserProxy_.showChromeVoxSettings();
},
/** @private */
onChromeVoxTutorialTap_() {
this.manageBrowserProxy_.showChromeVoxTutorial();
},
/** @private */
onCaptionsClick_() {
Router.getInstance().navigateTo(routes.MANAGE_CAPTION_SETTINGS);
},
/** @private */
onSelectToSpeakSettingsTap_() {
this.manageBrowserProxy_.showSelectToSpeakSettings();
},
/** @private */
onSwitchAccessSettingsTap_() {
Router.getInstance().navigateTo(routes.MANAGE_SWITCH_ACCESS_SETTINGS);
},
/** @private */
onDisplayTap_() {
Router.getInstance().navigateTo(
routes.DISPLAY,
/* dynamicParams */ null, /* removeSearch */ true);
},
/** @private */
onAppearanceTap_() {
// Open browser appearance section in a new browser tab.
window.open('chrome://settings/appearance');
},
/** @private */
onKeyboardTap_() {
Router.getInstance().navigateTo(
routes.KEYBOARD,
/* dynamicParams */ null, /* removeSearch */ true);
},
/**
* @param {!Event} event
* @private
*/
onA11yCaretBrowsingChange_(event) {
if (event.target.checked) {
chrome.metricsPrivate.recordUserAction(
'Accessibility.CaretBrowsing.EnableWithSettings');
} else {
chrome.metricsPrivate.recordUserAction(
'Accessibility.CaretBrowsing.DisableWithSettings');
}
},
/**
* @return {boolean}
* @private
*/
computeShowShelfNavigationButtonsSettings_() {
return !this.isKioskModeActive_ &&
loadTimeData.getBoolean('showTabletModeShelfNavigationButtonsSettings');
},
/**
* @return {boolean} Whether shelf navigation buttons should implicitly be
* enabled in tablet mode (due to accessibility settings different than
* shelf_navigation_buttons_enabled_in_tablet_mode).
* @private
*/
computeShelfNavigationButtonsImplicitlyEnabled_() {
/**
* Gets the bool pref value for the provided pref key.
* @param {string} key
* @return {boolean}
*/
const getBoolPrefValue = (key) => {
const pref = /** @type {chrome.settingsPrivate.PrefObject} */ (
this.get(key, this.prefs));
return pref && !!pref.value;
};
return getBoolPrefValue('settings.accessibility') ||
getBoolPrefValue('settings.a11y.autoclick') ||
getBoolPrefValue('settings.a11y.switch_access.enabled');
},
/**
* Calculates the effective value for "shelf navigation buttons enabled in
* tablet mode" setting - if the setting is implicitly enabled (by other a11y
* settings), this will return a stub pref value.
* @private
* @return {chrome.settingsPrivate.PrefObject}
*/
getShelfNavigationButtonsEnabledPref_() {
if (this.shelfNavigationButtonsImplicitlyEnabled_) {
return /** @type {!chrome.settingsPrivate.PrefObject}*/ ({
value: true,
type: chrome.settingsPrivate.PrefType.BOOLEAN,
key: ''
});
}
return /** @type {chrome.settingsPrivate.PrefObject} */ (this.get(
'settings.a11y.tablet_mode_shelf_nav_buttons_enabled', this.prefs));
},
/** @private */
onShelfNavigationButtonsLearnMoreClicked_() {
chrome.metricsPrivate.recordUserAction(
'Settings_A11y_ShelfNavigationButtonsLearnMoreClicked');
},
/**
* Handles the <code>tablet_mode_shelf_nav_buttons_enabled</code> setting's
* toggle changes. It updates the backing pref value, unless the setting is
* implicitly enabled.
* @private
*/
updateShelfNavigationButtonsEnabledPref_() {
if (this.shelfNavigationButtonsImplicitlyEnabled_) {
return;
}
const enabled = this.$$('#shelfNavigationButtonsEnabledControl').checked;
this.set(
'prefs.settings.a11y.tablet_mode_shelf_nav_buttons_enabled.value',
enabled);
this.manageBrowserProxy_.recordSelectedShowShelfNavigationButtonValue(
enabled);
},
/** @private */
onA11yCursorColorChange_() {
// Custom cursor color is enabled when the color is not set to black.
const a11yCursorColorOn =
this.get('prefs.settings.a11y.cursor_color.value') !==
DEFAULT_BLACK_CURSOR_COLOR;
this.set(
'prefs.settings.a11y.cursor_color_enabled.value', a11yCursorColorOn);
},
/** @private */
onMouseTap_() {
Router.getInstance().navigateTo(
routes.POINTERS,
/* dynamicParams */ null, /* removeSearch */ true);
},
/**
* Handles updating the visibility of the shelf navigation buttons setting
* and updating whether startupSoundEnabled is checked.
* @param {boolean} startup_sound_enabled Whether startup sound is enabled.
* @private
*/
onManageAllyPageReady_(startup_sound_enabled) {
this.$.startupSoundEnabled.checked = startup_sound_enabled;
},
/**
* Whether additional features link should be shown.
* @param {boolean} isKiosk
* @param {boolean} isGuest
* @return {boolean}
* @private
*/
shouldShowAdditionalFeaturesLink_(isKiosk, isGuest) {
return !isKiosk && !isGuest;
},
/**
* @param {string} subtitle
* @private
*/
onDictationLocaleMenuSubtitleChanged_(subtitle) {
this.useDictationLocaleSubtitleOverride_ = true;
this.dictationLocaleSubtitleOverride_ = subtitle;
},
/**
* Saves a list of locales and updates the UI to reflect the list.
* @param {!Array<!Array<string>>} locales
* @private
*/
onDictationLocalesSet_(locales) {
this.dictationLocalesList_ = locales;
this.onDictationLocalesChanged_();
},
/**
* Converts an array of locales and their human-readable equivalents to
* an array of menu options.
* TODO(crbug.com/1195916): Use 'offline' to indicate to the user which
* locales work offline with an icon in the select options.
* @private
*/
onDictationLocalesChanged_() {
const currentLocale =
this.get('prefs.settings.a11y.dictation_locale.value');
this.dictationLocaleOptions_ =
this.dictationLocalesList_.map((localeInfo) => {
return {
name: localeInfo.name,
value: localeInfo.value,
worksOffline: localeInfo.worksOffline,
installed: localeInfo.installed,
recommended:
localeInfo.recommended || localeInfo.value === currentLocale,
};
});
},
/**
* Calculates the Dictation locale subtitle based on the current
* locale from prefs and the offline availability of that locale.
* @return {string}
* @private
*/
computeDictationLocaleSubtitle_() {
if (this.useDictationLocaleSubtitleOverride_) {
// Only use the subtitle override once, since we still want the subtitle
// to repsond to changes to the dictation locale.
this.useDictationLocaleSubtitleOverride_ = false;
return this.dictationLocaleSubtitleOverride_;
}
const currentLocale =
this.get('prefs.settings.a11y.dictation_locale.value');
const locale = this.dictationLocaleOptions_.find(
(element) => element.value === currentLocale);
if (!locale) {
return '';
}
if (!locale.worksOffline) {
// If a locale is not supported offline, then use the network subtitle.
return this.i18n('dictationLocaleSubLabelNetwork', locale.name);
}
if (!locale.installed) {
// If a locale is supported offline, but isn't installed, then use the
// temporary network subtitle.
return this.i18n(
'dictationLocaleSubLabelNetworkTemporarily', locale.name);
}
// If we get here, we know a locale is both supported offline and installed.
return this.i18n('dictationLocaleSubLabelOffline', locale.name);
},
/** @private */
onChangeDictationLocaleButtonClicked_() {
if (this.areDictationLocalePrefsAllowed_) {
this.showDictationLocaleMenu_ = true;
}
},
/** @private */
onChangeDictationLocalesDialogClosed_() {
this.showDictationLocaleMenu_ = false;
},
});
| bsd-3-clause |
robixnai/xinu-arm | shell/xsh_snoop.c | 9885 | /**
* @file xsh_snoop.c
* @provides xsh_snoop
*
* $Id: xsh_snoop.c 2121 2009-11-06 00:28:33Z kthurow $
*/
/* Embedded Xinu, Copyright (C) 2009. All rights reserved. */
#include <stddef.h>
#include <conf.h>
#include <ipv4.h>
#include <shell.h>
#include <snoop.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void usage(char *command)
{
printf("Usage:\n");
printf("\t%s [--help]\n", command);
printf("\t%s [-c COUNT] [-i NETIF] [-s CAPLEN]\n", command);
printf("\t [-d] [-dd] [-v] [-vv] [-t TYPE]\n");
printf("\t [-da ADDR] [-dp PORT] [-sa ADDR] [-sp PORT]\n");
printf("Description:\n");
printf
("\tSnoop prints out a description and contents of packets on\n");
printf
("\ta network interface. By default it lists all all inbound\n");
printf
("\tand outbound traffic on all active network interfaces. It\n");
printf("\tcan also be used to read a PCAP trace file.\n");
printf("Output Options:\n");
printf("\t-d\tDump the packet in hex.\n");
printf("\t-dd\tDump the packet in hex and ASCII.\n");
printf("\t--help\tDisplay this help and exit.\n");
printf("\t-v\tPrint details on the network and transport layer\n");
printf("\t\theader in each packet.\n");
printf("\t-vv\tPrint details on the link layer header and more\n");
printf("\t\tdetails on the network and transport layer headers.\n");
printf("Capture Options:\n");
printf("\t-c\tExit after capturing COUNT packets.\n");
printf("\t-i\tCapture only from the network interface NETIF\n");
printf("\t-s\tCapture only CAPLEN bytes of each packet. Default\n");
printf("\t\tcaplen is 65535 bytes.\n");
printf("Filter Options:\n");
printf
("\t-da\tCapture only packets whose destination IPv4 address\n");
printf("\t\tis ADDR.\n");
printf
("\t-dp\tCapture only packets whose destination port is PORT.\n");
printf("\t\tThis is ignored if -t UDP or TCP is not specified.\n");
printf("\t-sa\tCapture only packets whose source IPv4 address\n");
printf("\t\tis ADDR.\n");
printf("\t-sp\tCapture only packets whose source port is PORT.\n");
printf("\t\tThis is ignored if -t UDP or TCP is not specified.\n");
printf
("\t-t\tCapture only packets of type TYPE. Valid values for\n");
printf("\t\ttype are: ARP, ICMP, IPv4, TCP, UDP.\n");
}
static void error(char *arg)
{
fprintf(stderr, "Invalid argument '%s', try snoop --help\n", arg);
}
static thread snoop(struct snoop *cap, uint count, char dump,
char verbose)
{
bool forever = FALSE;
struct packet *pkt = NULL;
if (0 == count)
{
forever = TRUE;
}
while (forever || count > 0)
{
pkt = snoopRead(cap);
if ((SYSERR == (int)pkt) || (NULL == pkt))
{
continue;
}
snoopPrint(pkt, dump, verbose);
netFreebuf(pkt);
count--;
}
return OK;
}
/**
* Shell command (snoop).
* @param nargs number of arguments in args array
* @param args array of arguments
* @return OK for success, SYSERR for syntax error
*/
shellcmd xsh_snoop(int nargs, char *args[])
{
int a;
uint count = 0;
uint caplen = 65535;
char dump = SNOOP_DUMP_NONE;
char verbose = SNOOP_VERBOSE_NONE;
char *type = NULL;
char *dstaddr = NULL;
ushort dstport = 0;
char *srcaddr = NULL;
ushort srcport = 0;
struct snoop cap;
char devname[DEVMAXNAME];
tid_typ tid;
strncpy(devname, "ALL", DEVMAXNAME);
/* Output help, if '--help' argument was supplied */
if (nargs == 2 && strncmp(args[1], "--help", 7) == 0)
{
usage(args[0]);
return 0;
}
/* Parse arguments */
for (a = 1; a < nargs; a++)
{
if (args[a][0] != '-')
{
error(args[a]);
return 1;
}
switch (args[a][1])
{
/* Capture count */
case 'c':
a++;
if (a >= nargs)
{
error(args[a - 1]);
return 1;
}
count = atoi(args[a]);
break;
/* Output dump OR Filter dst addr OR Filter dst port */
case 'd':
switch (args[a][2])
{
/* Output dump hex and char */
case 'd':
dump = SNOOP_DUMP_CHAR;
break;
/* Filter destination address */
case 'a':
a++;
if (a >= nargs)
{
error(args[a - 1]);
return 1;
}
dstaddr = args[a];
break;
/* Filter destination port */
case 'p':
a++;
if (a >= nargs)
{
error(args[a - 1]);
return 1;
}
dstport = atoi(args[a]);
break;
/* Output dump hex */
case '\0':
dump = SNOOP_DUMP_HEX;
break;
default:
error(args[a]);
return 1;
}
break;
/* Capture interface */
case 'i':
a++;
if (a >= nargs)
{
error(args[a - 1]);
return 1;
}
strncpy(devname, args[a], DEVMAXNAME);
break;
/* Capture size OR Filter src addr OR Filter dst addr */
case 's':
switch (args[a][2])
{
/* Filter source address */
case 'a':
a++;
if (a >= nargs)
{
error(args[a - 1]);
return 1;
}
srcaddr = args[a];
break;
/* Filter source port */
case 'p':
a++;
if (a >= nargs)
{
error(args[a - 1]);
return 1;
}
srcport = atoi(args[a]);
break;
/* Capture size */
case '\0':
a++;
if (a >= nargs)
{
error(args[a - 1]);
return 1;
}
caplen = atoi(args[a]);
break;
default:
error(args[a]);
return 1;
}
break;
/* Select type */
case 't':
a++;
if (a >= nargs)
{
error(args[a - 1]);
}
type = args[a];
break;
/* Output verbose */
case 'v':
if (args[a][2] == 'v')
{
verbose = SNOOP_VERBOSE_TWO;
}
else
{
verbose = SNOOP_VERBOSE_ONE;
}
break;
default:
error(args[a]);
return 1;
}
}
/* Set filter */
cap.caplen = caplen;
cap.promisc = FALSE;
if (NULL == type)
{
cap.type = SNOOP_FILTER_ALL;
}
else
{
if (0 == strncmp(type, "ARP", 4))
{
cap.type = SNOOP_FILTER_ARP;
}
else if (0 == strncmp(type, "IPv4", 5))
{
cap.type = SNOOP_FILTER_IPv4;
}
else if (0 == strncmp(type, "UDP", 4))
{
cap.type = SNOOP_FILTER_UDP;
}
else if (0 == strncmp(type, "TCP", 4))
{
cap.type = SNOOP_FILTER_TCP;
}
else if (0 == strncmp(type, "ICMP", 5))
{
cap.type = SNOOP_FILTER_ICMP;
}
else
{
fprintf(stderr, "Invalid type '%s', try usage --help\n",
type);
return 1;
}
}
if (NULL == srcaddr)
{
cap.srcaddr.type = NULL;
}
else
{
dot2ipv4(srcaddr, &cap.srcaddr);
}
cap.srcport = srcport;
if (NULL == dstaddr)
{
cap.dstaddr.type = NULL;
}
else
{
dot2ipv4(dstaddr, &cap.dstaddr);
}
cap.dstport = dstport;
/* Open snoop */
if (SYSERR == snoopOpen(&cap, devname))
{
fprintf(stderr, "Failed to open capture on network device '%s'\n",
devname);
return 1;
}
/* Spawn output thread */
tid = create((void *)snoop, SHELL_CMDSTK, SHELL_CMDPRIO, "snoop",
4, &cap, count, dump, verbose);
if (SYSERR == tid)
{
snoopClose(&cap);
fprintf(stderr, "Failed to start capture\n");
return 1;
}
/* Use same stdin, stdout, and sterr as this thread */
thrtab[tid].fdesc[0] = thrtab[gettid()].fdesc[0];
thrtab[tid].fdesc[1] = thrtab[gettid()].fdesc[1];
thrtab[tid].fdesc[2] = thrtab[gettid()].fdesc[2];
/* Start output thread */
recvclr();
ready(tid, RESCHED_NO);
/* Close at proper event */
if (0 == count)
{
/* Stop snooping when enter is hit */
fprintf(stdout, "Snooping... Press <Enter> to stop.\n");
getchar();
kill(tid);
}
else
{
/* Stop snooping when thread dies */
fprintf(stdout, "Snooping %d packets...\n", count);
while (receive() != tid);
}
/* Print out statistics */
printf("%d packets captured\n", cap.ncap);
printf("%d packets matched filter\n", cap.nmatch);
printf("%d packets printed\n", cap.nprint);
printf("%d packets overrun\n", cap.novrn);
/* Close interface */
if (SYSERR == snoopClose(&cap))
{
fprintf(stderr, "Failed to stop capture\n");
return 1;
}
return 0;
}
| bsd-3-clause |
ruriwo/ErgoThumb072_firmware | tmk_core/tool/mbed/mbed-sdk/libraries/mbed/targets/cmsis/TARGET_RENESAS/TARGET_RZ_A1H/inc/iobitmasks/mtu2_iobitmask.h | 18495 | /*******************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only
* intended for use with Renesas products. No other uses are authorized. This
* software is owned by Renesas Electronics Corporation and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software
* and to discontinue the availability of this software. By using this software,
* you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved.
*******************************************************************************/
/*******************************************************************************
* File Name : mtu2_iobitmask.h
* $Rev: 1138 $
* $Date:: 2014-08-08 11:03:56 +0900#$
* Description : MTU2 register define header
*******************************************************************************/
#ifndef MTU2_IOBITMASK_H
#define MTU2_IOBITMASK_H
/* ==== Mask values for IO registers ==== */
#define MTU2_TCR_n_TPSC (0x07u)
#define MTU2_TCR_n_CKEG (0x18u)
#define MTU2_TCR_n_CCLR (0xE0u)
#define MTU2_TMDR_n_MD (0x0Fu)
#define MTU2_TIOR_2_IOA (0x0Fu)
#define MTU2_TIOR_2_IOB (0xF0u)
#define MTU2_TIER_n_TGIEA (0x01u)
#define MTU2_TIER_n_TGIEB (0x02u)
#define MTU2_TIER_n_TCIEV (0x10u)
#define MTU2_TIER_2_TCIEU (0x20u)
#define MTU2_TIER_n_TTGE (0x80u)
#define MTU2_TSR_n_TGFA (0x01u)
#define MTU2_TSR_n_TGFB (0x02u)
#define MTU2_TSR_n_TCFV (0x10u)
#define MTU2_TSR_2_TCFU (0x20u)
#define MTU2_TSR_2_TCFD (0x80u)
#define MTU2_TCNT_n_D (0xFFFFu)
#define MTU2_TGRA_n_D (0xFFFFu)
#define MTU2_TGRB_n_D (0xFFFFu)
#define MTU2_TMDR_3_BFA (0x10u)
#define MTU2_TMDR_3_BFB (0x20u)
#define MTU2_TMDR_4_BFA (0x10u)
#define MTU2_TMDR_4_BFB (0x20u)
#define MTU2_TIORH_3_IOA (0x0Fu)
#define MTU2_TIORH_3_IOB (0xF0u)
#define MTU2_TIORL_3_IOC (0x0Fu)
#define MTU2_TIORL_3_IOD (0xF0u)
#define MTU2_TIORH_4_IOA (0x0Fu)
#define MTU2_TIORH_4_IOB (0xF0u)
#define MTU2_TIORL_4_IOC (0x0Fu)
#define MTU2_TIORL_4_IOD (0xF0u)
#define MTU2_TIER_3_TGIEC (0x04u)
#define MTU2_TIER_3_TGIED (0x08u)
#define MTU2_TIER_4_TGIEC (0x04u)
#define MTU2_TIER_4_TGIED (0x08u)
#define MTU2_TIER_4_TTGE2 (0x40u)
#define MTU2_TOER_OE3B (0x01u)
#define MTU2_TOER_OE4A (0x02u)
#define MTU2_TOER_OE4B (0x04u)
#define MTU2_TOER_OE3D (0x08u)
#define MTU2_TOER_OE4C (0x10u)
#define MTU2_TOER_OE4D (0x20u)
#define MTU2_TGCR_UF (0x01u)
#define MTU2_TGCR_VF (0x02u)
#define MTU2_TGCR_WF (0x04u)
#define MTU2_TGCR_FB (0x08u)
#define MTU2_TGCR_P (0x10u)
#define MTU2_TGCR_N (0x20u)
#define MTU2_TGCR_BDC (0x40u)
#define MTU2_TOCR1_OLSP (0x01u)
#define MTU2_TOCR1_OLSN (0x02u)
#define MTU2_TOCR1_TOCS (0x04u)
#define MTU2_TOCR1_TOCL (0x08u)
#define MTU2_TOCR1_PSYE (0x40u)
#define MTU2_TOCR2_OLS1P (0x01u)
#define MTU2_TOCR2_OLS1N (0x02u)
#define MTU2_TOCR2_OLS2P (0x04u)
#define MTU2_TOCR2_OLS2N (0x08u)
#define MTU2_TOCR2_OLS3P (0x10u)
#define MTU2_TOCR2_OLS3N (0x20u)
#define MTU2_TOCR2_BF (0xC0u)
#define MTU2_TCDR_D (0xFFFFu)
#define MTU2_TDDR_D (0xFFFFu)
#define MTU2_TCNTS_D (0xFFFFu)
#define MTU2_TCBR_D (0xFFFFu)
#define MTU2_TGRC_3_D (0xFFFFu)
#define MTU2_TGRD_3_D (0xFFFFu)
#define MTU2_TGRC_4_D (0xFFFFu)
#define MTU2_TGRD_4_D (0xFFFFu)
#define MTU2_TSR_3_TGFC (0x04u)
#define MTU2_TSR_3_TGFD (0x08u)
#define MTU2_TSR_3_TCFD (0x80u)
#define MTU2_TSR_4_TGFC (0x04u)
#define MTU2_TSR_4_TGFD (0x08u)
#define MTU2_TSR_4_TCFD (0x80u)
#define MTU2_TITCR_4VCOR (0x07u)
#define MTU2_TITCR_T4VEN (0x08u)
#define MTU2_TITCR_3ACOR (0x70u)
#define MTU2_TITCR_T3AEN (0x80u)
#define MTU2_TITCNT_4VCNT (0x07u)
#define MTU2_TITCNT_3ACNT (0x70u)
#define MTU2_TBTER_BTE (0x03u)
#define MTU2_TDER_TDER (0x01u)
#define MTU2_TOLBR_OLS1P (0x01u)
#define MTU2_TOLBR_OLS1N (0x02u)
#define MTU2_TOLBR_OLS2P (0x04u)
#define MTU2_TOLBR_OLS2N (0x08u)
#define MTU2_TOLBR_OLS3P (0x10u)
#define MTU2_TOLBR_OLS3N (0x20u)
#define MTU2_TBTM_3_TTSA (0x01u)
#define MTU2_TBTM_3_TTSB (0x02u)
#define MTU2_TBTM_4_TTSA (0x01u)
#define MTU2_TBTM_4_TTSB (0x02u)
#define MTU2_TADCR_ITB4VE (0x0001u)
#define MTU2_TADCR_ITB3AE (0x0002u)
#define MTU2_TADCR_ITA4VE (0x0004u)
#define MTU2_TADCR_ITA3AE (0x0008u)
#define MTU2_TADCR_DT4BE (0x0010u)
#define MTU2_TADCR_UT4BE (0x0020u)
#define MTU2_TADCR_DT4AE (0x0040u)
#define MTU2_TADCR_UT4AE (0x0080u)
#define MTU2_TADCR_BF (0xC000u)
#define MTU2_TADCORA_4_D (0xFFFFu)
#define MTU2_TADCORB_4_D (0xFFFFu)
#define MTU2_TADCOBRA_4_D (0xFFFFu)
#define MTU2_TADCOBRB_4_D (0xFFFFu)
#define MTU2_TWCR_WRE (0x01u)
#define MTU2_TWCR_CCE (0x80u)
#define MTU2_TSTR_CST0 (0x01u)
#define MTU2_TSTR_CST1 (0x02u)
#define MTU2_TSTR_CST2 (0x04u)
#define MTU2_TSTR_CST3 (0x40u)
#define MTU2_TSTR_CST4 (0x80u)
#define MTU2_TSYR_SYNC0 (0x01u)
#define MTU2_TSYR_SYNC1 (0x02u)
#define MTU2_TSYR_SYNC2 (0x04u)
#define MTU2_TSYR_SYNC3 (0x40u)
#define MTU2_TSYR_SYNC4 (0x80u)
#define MTU2_TRWER_RWE (0x01u)
#define MTU2_TMDR_0_BFA (0x10u)
#define MTU2_TMDR_0_BFB (0x20u)
#define MTU2_TMDR_0_BFE (0x40u)
#define MTU2_TIORH_0_IOA (0x0Fu)
#define MTU2_TIORH_0_IOB (0xF0u)
#define MTU2_TIORL_0_IOC (0x0Fu)
#define MTU2_TIORL_0_IOD (0xF0u)
#define MTU2_TIER_0_TGIEC (0x04u)
#define MTU2_TIER_0_TGIED (0x08u)
#define MTU2_TSR_0_TGFC (0x04u)
#define MTU2_TSR_0_TGFD (0x08u)
#define MTU2_TGRC_0_D (0xFFFFu)
#define MTU2_TGRD_0_D (0xFFFFu)
#define MTU2_TGRE_0_D (0xFFFFu)
#define MTU2_TGRF_0_D (0xFFFFu)
#define MTU2_TIER2_0_TGIEE (0x01u)
#define MTU2_TIER2_0_TGIEF (0x02u)
#define MTU2_TSR2_0_TGFE (0x01u)
#define MTU2_TSR2_0_TGFF (0x02u)
#define MTU2_TBTM_0_TTSA (0x01u)
#define MTU2_TBTM_0_TTSB (0x02u)
#define MTU2_TBTM_0_TTSE (0x04u)
#define MTU2_TIOR_1_IOA (0x0Fu)
#define MTU2_TIOR_1_IOB (0xF0u)
#define MTU2_TIER_1_TCIEU (0x20u)
#define MTU2_TSR_1_TCFU (0x20u)
#define MTU2_TSR_1_TCFD (0x80u)
#define MTU2_TICCR_I1AE (0x01u)
#define MTU2_TICCR_I1BE (0x02u)
#define MTU2_TICCR_I2AE (0x04u)
#define MTU2_TICCR_I2BE (0x08u)
/* ==== Shift values for IO registers ==== */
#define MTU2_TCR_n_TPSC_SHIFT (0u)
#define MTU2_TCR_n_CKEG_SHIFT (3u)
#define MTU2_TCR_n_CCLR_SHIFT (5u)
#define MTU2_TMDR_n_MD_SHIFT (0u)
#define MTU2_TIOR_2_IOA_SHIFT (0u)
#define MTU2_TIOR_2_IOB_SHIFT (4u)
#define MTU2_TIER_n_TGIEA_SHIFT (0u)
#define MTU2_TIER_n_TGIEB_SHIFT (1u)
#define MTU2_TIER_n_TCIEV_SHIFT (4u)
#define MTU2_TIER_2_TCIEU_SHIFT (5u)
#define MTU2_TIER_n_TTGE_SHIFT (7u)
#define MTU2_TSR_n_TGFA_SHIFT (0u)
#define MTU2_TSR_n_TGFB_SHIFT (1u)
#define MTU2_TSR_n_TCFV_SHIFT (4u)
#define MTU2_TSR_2_TCFU_SHIFT (5u)
#define MTU2_TSR_2_TCFD_SHIFT (7u)
#define MTU2_TCNT_n_D_SHIFT (0u)
#define MTU2_TGRA_n_D_SHIFT (0u)
#define MTU2_TGRB_n_D_SHIFT (0u)
#define MTU2_TMDR_3_BFA_SHIFT (4u)
#define MTU2_TMDR_3_BFB_SHIFT (5u)
#define MTU2_TMDR_4_BFA_SHIFT (4u)
#define MTU2_TMDR_4_BFB_SHIFT (5u)
#define MTU2_TIORH_3_IOA_SHIFT (0u)
#define MTU2_TIORH_3_IOB_SHIFT (4u)
#define MTU2_TIORL_3_IOC_SHIFT (0u)
#define MTU2_TIORL_3_IOD_SHIFT (4u)
#define MTU2_TIORH_4_IOA_SHIFT (0u)
#define MTU2_TIORH_4_IOB_SHIFT (4u)
#define MTU2_TIORL_4_IOC_SHIFT (0u)
#define MTU2_TIORL_4_IOD_SHIFT (4u)
#define MTU2_TIER_3_TGIEC_SHIFT (2u)
#define MTU2_TIER_3_TGIED_SHIFT (3u)
#define MTU2_TIER_4_TGIEC_SHIFT (2u)
#define MTU2_TIER_4_TGIED_SHIFT (3u)
#define MTU2_TIER_4_TTGE2_SHIFT (6u)
#define MTU2_TOER_OE3B_SHIFT (0u)
#define MTU2_TOER_OE4A_SHIFT (1u)
#define MTU2_TOER_OE4B_SHIFT (2u)
#define MTU2_TOER_OE3D_SHIFT (3u)
#define MTU2_TOER_OE4C_SHIFT (4u)
#define MTU2_TOER_OE4D_SHIFT (5u)
#define MTU2_TGCR_UF_SHIFT (0u)
#define MTU2_TGCR_VF_SHIFT (1u)
#define MTU2_TGCR_WF_SHIFT (2u)
#define MTU2_TGCR_FB_SHIFT (3u)
#define MTU2_TGCR_P_SHIFT (4u)
#define MTU2_TGCR_N_SHIFT (5u)
#define MTU2_TGCR_BDC_SHIFT (6u)
#define MTU2_TOCR1_OLSP_SHIFT (0u)
#define MTU2_TOCR1_OLSN_SHIFT (1u)
#define MTU2_TOCR1_TOCS_SHIFT (2u)
#define MTU2_TOCR1_TOCL_SHIFT (3u)
#define MTU2_TOCR1_PSYE_SHIFT (6u)
#define MTU2_TOCR2_OLS1P_SHIFT (0u)
#define MTU2_TOCR2_OLS1N_SHIFT (1u)
#define MTU2_TOCR2_OLS2P_SHIFT (2u)
#define MTU2_TOCR2_OLS2N_SHIFT (3u)
#define MTU2_TOCR2_OLS3P_SHIFT (4u)
#define MTU2_TOCR2_OLS3N_SHIFT (5u)
#define MTU2_TOCR2_BF_SHIFT (6u)
#define MTU2_TCDR_D_SHIFT (0u)
#define MTU2_TDDR_D_SHIFT (0u)
#define MTU2_TCNTS_D_SHIFT (0u)
#define MTU2_TCBR_D_SHIFT (0u)
#define MTU2_TGRC_3_D_SHIFT (0u)
#define MTU2_TGRD_3_D_SHIFT (0u)
#define MTU2_TGRC_4_D_SHIFT (0u)
#define MTU2_TGRD_4_D_SHIFT (0u)
#define MTU2_TSR_3_TGFC_SHIFT (2u)
#define MTU2_TSR_3_TGFD_SHIFT (3u)
#define MTU2_TSR_3_TCFD_SHIFT (7u)
#define MTU2_TSR_4_TGFC_SHIFT (2u)
#define MTU2_TSR_4_TGFD_SHIFT (3u)
#define MTU2_TSR_4_TCFD_SHIFT (7u)
#define MTU2_TITCR_4VCOR_SHIFT (0u)
#define MTU2_TITCR_T4VEN_SHIFT (3u)
#define MTU2_TITCR_3ACOR_SHIFT (4u)
#define MTU2_TITCR_T3AEN_SHIFT (7u)
#define MTU2_TITCNT_4VCNT_SHIFT (0u)
#define MTU2_TITCNT_3ACNT_SHIFT (4u)
#define MTU2_TBTER_BTE_SHIFT (0u)
#define MTU2_TDER_TDER_SHIFT (0u)
#define MTU2_TOLBR_OLS1P_SHIFT (0u)
#define MTU2_TOLBR_OLS1N_SHIFT (1u)
#define MTU2_TOLBR_OLS2P_SHIFT (2u)
#define MTU2_TOLBR_OLS2N_SHIFT (3u)
#define MTU2_TOLBR_OLS3P_SHIFT (4u)
#define MTU2_TOLBR_OLS3N_SHIFT (5u)
#define MTU2_TBTM_3_TTSA_SHIFT (0u)
#define MTU2_TBTM_3_TTSB_SHIFT (1u)
#define MTU2_TBTM_4_TTSA_SHIFT (0u)
#define MTU2_TBTM_4_TTSB_SHIFT (1u)
#define MTU2_TADCR_ITB4VE_SHIFT (0u)
#define MTU2_TADCR_ITB3AE_SHIFT (1u)
#define MTU2_TADCR_ITA4VE_SHIFT (2u)
#define MTU2_TADCR_ITA3AE_SHIFT (3u)
#define MTU2_TADCR_DT4BE_SHIFT (4u)
#define MTU2_TADCR_UT4BE_SHIFT (5u)
#define MTU2_TADCR_DT4AE_SHIFT (6u)
#define MTU2_TADCR_UT4AE_SHIFT (7u)
#define MTU2_TADCR_BF_SHIFT (14u)
#define MTU2_TADCORA_4_D_SHIFT (0u)
#define MTU2_TADCORB_4_D_SHIFT (0u)
#define MTU2_TADCOBRA_4_D_SHIFT (0u)
#define MTU2_TADCOBRB_4_D_SHIFT (0u)
#define MTU2_TWCR_WRE_SHIFT (0u)
#define MTU2_TWCR_CCE_SHIFT (7u)
#define MTU2_TSTR_CST0_SHIFT (0u)
#define MTU2_TSTR_CST1_SHIFT (1u)
#define MTU2_TSTR_CST2_SHIFT (2u)
#define MTU2_TSTR_CST3_SHIFT (6u)
#define MTU2_TSTR_CST4_SHIFT (7u)
#define MTU2_TSYR_SYNC0_SHIFT (0u)
#define MTU2_TSYR_SYNC1_SHIFT (1u)
#define MTU2_TSYR_SYNC2_SHIFT (2u)
#define MTU2_TSYR_SYNC3_SHIFT (6u)
#define MTU2_TSYR_SYNC4_SHIFT (7u)
#define MTU2_TRWER_RWE_SHIFT (0u)
#define MTU2_TMDR_0_BFA_SHIFT (4u)
#define MTU2_TMDR_0_BFB_SHIFT (5u)
#define MTU2_TMDR_0_BFE_SHIFT (6u)
#define MTU2_TIORH_0_IOA_SHIFT (0u)
#define MTU2_TIORH_0_IOB_SHIFT (4u)
#define MTU2_TIORL_0_IOC_SHIFT (0u)
#define MTU2_TIORL_0_IOD_SHIFT (4u)
#define MTU2_TIER_0_TGIEC_SHIFT (2u)
#define MTU2_TIER_0_TGIED_SHIFT (3u)
#define MTU2_TSR_0_TGFC_SHIFT (2u)
#define MTU2_TSR_0_TGFD_SHIFT (3u)
#define MTU2_TGRC_0_D_SHIFT (0u)
#define MTU2_TGRD_0_D_SHIFT (0u)
#define MTU2_TGRE_0_D_SHIFT (0u)
#define MTU2_TGRF_0_D_SHIFT (0u)
#define MTU2_TIER2_0_TGIEE_SHIFT (0u)
#define MTU2_TIER2_0_TGIEF_SHIFT (1u)
#define MTU2_TSR2_0_TGFE_SHIFT (0u)
#define MTU2_TSR2_0_TGFF_SHIFT (1u)
#define MTU2_TBTM_0_TTSA_SHIFT (0u)
#define MTU2_TBTM_0_TTSB_SHIFT (1u)
#define MTU2_TBTM_0_TTSE_SHIFT (2u)
#define MTU2_TIOR_1_IOA_SHIFT (0u)
#define MTU2_TIOR_1_IOB_SHIFT (4u)
#define MTU2_TIER_1_TCIEU_SHIFT (5u)
#define MTU2_TSR_1_TCFU_SHIFT (5u)
#define MTU2_TSR_1_TCFD_SHIFT (7u)
#define MTU2_TICCR_I1AE_SHIFT (0u)
#define MTU2_TICCR_I1BE_SHIFT (1u)
#define MTU2_TICCR_I2AE_SHIFT (2u)
#define MTU2_TICCR_I2BE_SHIFT (3u)
#endif /* MTU2_IOBITMASK_H */
/* End of File */
| gpl-2.0 |
ayeletshpigelman/azure-sdk-for-net | sdk/core/Azure.Core/src/SyncAsyncEventHandler.cs | 11132 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
namespace Azure.Core
{
/// <summary>
/// Represents a method that can handle an event and execute either
/// synchronously or asynchronously.
/// </summary>
/// <typeparam name="T">
/// Type of the event arguments deriving or equal to
/// <see cref="SyncAsyncEventArgs"/>.
/// </typeparam>
/// <param name="e">
/// An <see cref="SyncAsyncEventArgs"/> instance that contains the event
/// data.
/// </param>
/// <returns>
/// A task that represents the handler. You can return
/// <see cref="Task.CompletedTask"/> if implementing a sync handler.
/// Please see the Remarks section for more details.
/// </returns>
/// <example>
/// <para>
/// If you're using the synchronous, blocking methods of a client (i.e.,
/// methods without an Async suffix), they will raise events that require
/// handlers to execute synchronously as well. Even though the signature
/// of your handler returns a <see cref="Task"/>, you should write regular
/// sync code that blocks and return <see cref="Task.CompletedTask"/> when
/// finished.
/// <code snippet="Snippet:Azure_Core_Samples_EventSamples_SyncHandler">
/// var client = new AlarmClient();
/// client.Ring += (SyncAsyncEventArgs e) =>
/// {
/// Console.WriteLine("Wake up!");
/// return Task.CompletedTask;
/// };
///
/// client.Snooze();
/// </code>
/// If you need to call an async method from a synchronous event handler,
/// you have two options. You can use <see cref="Task.Run(Action)"/> to
/// queue a task for execution on the ThreadPool without waiting on it to
/// complete. This "fire and forget" approach may not run before your
/// handler finishes executing. Be sure to understand
/// <see href="https://docs.microsoft.com/dotnet/standard/parallel-programming/exception-handling-task-parallel-library">
/// exception handling in the Task Parallel Library</see> to avoid
/// unhandled exceptions tearing down your process. If you absolutely need
/// the async method to execute before returning from your handler, you can
/// call <c>myAsyncTask.GetAwaiter().GetResult()</c>. Please be aware
/// this may cause ThreadPool starvation. See the sync-over-async note in
/// Remarks for more details.
/// </para>
/// <para>
/// If you're using the asynchronous, non-blocking methods of a client
/// (i.e., methods with an Async suffix), they will raise events that
/// expect handlers to execute asynchronously.
/// <code snippet="Snippet:Azure_Core_Samples_EventSamples_AsyncHandler">
/// var client = new AlarmClient();
/// client.Ring += async (SyncAsyncEventArgs e) =>
/// {
/// await Console.Out.WriteLineAsync("Wake up!");
/// };
///
/// await client.SnoozeAsync();
/// </code>
/// </para>
/// <para>
/// The same event can be raised from both synchronous and asynchronous
/// code paths depending on whether you're calling sync or async methods
/// on a client. If you write an async handler but raise it from a sync
/// method, the handler will be doing sync-over-async and may cause
/// ThreadPool starvation. See the note in Remarks for more details. You
/// should use the <see cref="SyncAsyncEventArgs.IsRunningSynchronously"/>
/// property to check how the event is being raised and implement your
/// handler accordingly. Here's an example handler that's safe to invoke
/// from both sync and async code paths.
/// <code snippet="Snippet:Azure_Core_Samples_EventSamples_CombinedHandler">
/// var client = new AlarmClient();
/// client.Ring += async (SyncAsyncEventArgs e) =>
/// {
/// if (e.IsRunningSynchronously)
/// {
/// Console.WriteLine("Wake up!");
/// }
/// else
/// {
/// await Console.Out.WriteLineAsync("Wake up!");
/// }
/// };
///
/// client.Snooze(); // sync call that blocks
/// await client.SnoozeAsync(); // async call that doesn't block
/// </code>
/// </para>
/// </example>
/// <example>
/// </example>
/// <exception cref="AggregateException">
/// Any exceptions thrown by an event handler will be wrapped in a single
/// AggregateException and thrown from the code that raised the event. You
/// can check the <see cref="AggregateException.InnerExceptions"/> property
/// to see the original exceptions thrown by your event handlers.
/// AggregateException also provides
/// <see href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/brownfield/aggregating-exceptions">
/// a number of helpful methods</see> like
/// <see cref="AggregateException.Flatten"/> and
/// <see cref="AggregateException.Handle(Func{Exception, bool})"/> to make
/// complex failures easier to work with.
/// <code snippet="Snippet:Azure_Core_Samples_EventSamples_Exceptions">
/// var client = new AlarmClient();
/// client.Ring += (SyncAsyncEventArgs e) =>
/// throw new InvalidOperationException("Alarm unplugged.");
///
/// try
/// {
/// client.Snooze();
/// }
/// catch (AggregateException ex)
/// {
/// ex.Handle(e => e is InvalidOperationException);
/// Console.WriteLine("Please switch to your backup alarm.");
/// }
/// </code>
/// </exception>
/// <remarks>
/// <para>
/// Most Azure client libraries for .NET offer both synchronous and
/// asynchronous methods for calling Azure services. You can distinguish
/// the asynchronous methods by their Async suffix. For example,
/// BlobClient.Download and BlobClient.DownloadAsync make the same
/// underlying REST call and only differ in whether they block. We
/// recommend using our async methods for new applications, but there are
/// perfectly valid cases for using sync methods as well. These dual
/// method invocation semantics allow for flexibility, but require a little
/// extra care when writing event handlers.
/// </para>
/// <para>
/// The SyncAsyncEventHandler is a delegate used by events in Azure client
/// libraries to represent an event handler that can be invoked from either
/// sync or async code paths. It takes event arguments deriving from
/// <see cref="SyncAsyncEventArgs"/> that contain important information for
/// writing your event handler:
/// <list type="bullet">
/// <item>
/// <description>
/// <see cref="SyncAsyncEventArgs.CancellationToken"/> is a cancellation
/// token related to the original operation that raised the event. It's
/// important for your handler to pass this token along to any asynchronous
/// or long-running synchronous operations that take a token so cancellation
/// (via something like
/// <c>new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token</c>,
/// for example) will correctly propagate.
/// </description>
/// </item>
/// <item>
/// <description>
/// <see cref="SyncAsyncEventArgs.IsRunningSynchronously"/> is a flag indicating
/// whether your handler was invoked synchronously or asynchronously. If
/// you're calling sync methods on your client, you should use sync methods
/// to implement your event handler (you can return
/// <see cref="Task.CompletedTask"/>). If you're calling async methods on
/// your client, you should use async methods where possible to implement
/// your event handler. If you're not in control of how the client will be
/// used or want to write safer code, you should check the
/// <see cref="SyncAsyncEventArgs.IsRunningSynchronously"/> property and call
/// either sync or async methods as directed.
/// </description>
/// </item>
/// <item>
/// <description>
/// Most events will customize the event data by deriving from
/// <see cref="SyncAsyncEventArgs"/> and including details about what
/// triggered the event or providing options to react. Many times this
/// will include a reference to the client that raised the event in case
/// you need it for additional processing.
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// When an event using SyncAsyncEventHandler is raised, the handlers will
/// be executed sequentially to avoid introducing any unintended
/// parallelism. The event handlers will finish before returning control
/// to the code path raising the event. This means blocking for events
/// raised synchronously and waiting for the returned <see cref="Task"/> to
/// complete for events raised asynchronously.
/// </para>
/// <para>
/// Any exceptions thrown from a handler will be wrapped in a single
/// <see cref="AggregateException"/>. If one handler throws an exception,
/// it will not prevent other handlers from running. This is also relevant
/// for cancellation because all handlers are still raised if cancellation
/// occurs. You should both pass <see cref="SyncAsyncEventArgs.CancellationToken"/>
/// to asynchronous or long-running synchronous operations and consider
/// calling <see cref="System.Threading.CancellationToken.ThrowIfCancellationRequested"/>
/// in compute heavy handlers.
/// </para>
/// <para>
/// A <see href="https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/core/Azure.Core/samples/Diagnostics.md#distributed-tracing">
/// distributed tracing span</see> is wrapped around your handlers using
/// the event name so you can see how long your handlers took to run,
/// whether they made other calls to Azure services, and details about any
/// exceptions that were thrown.
/// </para>
/// <para>
/// Executing asynchronous code from a sync code path is commonly referred
/// to as sync-over-async because you're getting sync behavior but still
/// invoking all the async machinery. See
/// <see href="https://docs.microsoft.com/archive/blogs/vancem/diagnosing-net-core-threadpool-starvation-with-perfview-why-my-service-is-not-saturating-all-cores-or-seems-to-stall">
/// Diagnosing.NET Core ThreadPool Starvation with PerfView</see>
/// for a detailed explanation of how that can cause serious performance
/// problems. We recommend you use the
/// <see cref="SyncAsyncEventArgs.IsRunningSynchronously"/> flag to avoid
/// ThreadPool starvation.
/// </para>
/// </remarks>
public delegate Task SyncAsyncEventHandler<T>(T e)
where T : SyncAsyncEventArgs;
// NOTE: You should always use SyncAsyncEventHandlerExtensions.RaiseAsync
// in Azure.Core's shared source to ensure consistent event handling
// semantics.
}
| mit |
mandino/www.bloggingshakespeare.com | wp-content/plugins/wordpress-seo/src/models/primary-term.php | 750 | <?php
/**
* Model for the Primary Term table.
*
* @package Yoast\YoastSEO\Models
*/
namespace Yoast\WP\SEO\Models;
use Yoast\WP\Lib\Model;
/**
* Primary Term model definition.
*
* @property int $id Identifier.
* @property int $post_id Post ID.
* @property int $term_id Term ID.
* @property string $taxonomy Taxonomy.
* @property int $blog_id Blog ID.
*
* @property string $created_at
* @property string $updated_at
*/
class Primary_Term extends Model {
/**
* Whether nor this model uses timestamps.
*
* @var bool
*/
protected $uses_timestamps = true;
/**
* Which columns contain int values.
*
* @var array
*/
protected $int_columns = [
'id',
'post_id',
'term_id',
'blog_id',
];
}
| mit |
belzeba/VR | Assets/VRTK/Scripts/VRTK_ControllerActions.cs | 27336 | // Controller Actions|Scripts|0020
namespace VRTK
{
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Highlighters;
[System.Serializable]
public class VRTK_ControllerModelElementPaths
{
public string bodyModelPath = "";
public string triggerModelPath = "";
public string leftGripModelPath = "";
public string rightGripModelPath = "";
public string touchpadModelPath = "";
public string appMenuModelPath = "";
public string systemMenuModelPath = "";
}
[System.Serializable]
public struct VRTK_ControllerElementHighlighers
{
public VRTK_BaseHighlighter body;
public VRTK_BaseHighlighter trigger;
public VRTK_BaseHighlighter gripLeft;
public VRTK_BaseHighlighter gripRight;
public VRTK_BaseHighlighter touchpad;
public VRTK_BaseHighlighter appMenu;
public VRTK_BaseHighlighter systemMenu;
}
/// <summary>
/// Event Payload
/// </summary>
/// <param name="controllerIndex">The index of the controller that was used.</param>
public struct ControllerActionsEventArgs
{
public uint controllerIndex;
}
/// <summary>
/// Event Payload
/// </summary>
/// <param name="sender">this object</param>
/// <param name="e"><see cref="ControllerActionsEventArgs"/></param>
public delegate void ControllerActionsEventHandler(object sender, ControllerActionsEventArgs e);
/// <summary>
/// The Controller Actions script provides helper methods to deal with common controller actions. It deals with actions that can be done to the controller.
/// </summary>
/// <remarks>
/// The highlighting of the controller is defaulted to use the `VRTK_MaterialColorSwapHighlighter` if no other highlighter is applied to the Object.
/// </remarks>
/// <example>
/// `VRTK/Examples/016_Controller_HapticRumble` demonstrates the ability to hide a controller model and make the controller vibrate for a given length of time at a given intensity.
///
/// `VRTK/Examples/035_Controller_OpacityAndHighlighting` demonstrates the ability to change the opacity of a controller model and to highlight specific elements of a controller such as the buttons or even the entire controller model.
/// </example>
public class VRTK_ControllerActions : MonoBehaviour
{
[Tooltip("A collection of strings that determine the path to the controller model sub elements for identifying the model parts at runtime. If the paths are left empty they will default to the model element paths of the selected SDK Bridge.\n\n"
+ "* The available model sub elements are:\n\n"
+ " * `Body Model Path`: The overall shape of the controller.\n"
+ " * `Trigger Model Path`: The model that represents the trigger button.\n"
+ " * `Grip Left Model Path`: The model that represents the left grip button.\n"
+ " * `Grip Right Model Path`: The model that represents the right grip button.\n"
+ " * `Touchpad Model Path`: The model that represents the touchpad.\n"
+ " * `App Menu Model Path`: The model that represents the application menu button.\n"
+ " * `System Menu Model Path`: The model that represents the system menu button.")]
public VRTK_ControllerModelElementPaths modelElementPaths;
[Tooltip("A collection of highlighter overrides for each controller model sub element. If no highlighter override is given then highlighter on the Controller game object is used.\n\n"
+ "* The available model sub elements are:\n\n"
+ " * `Body`: The highlighter to use on the overall shape of the controller.\n"
+ " * `Trigger`: The highlighter to use on the trigger button.\n"
+ " * `Grip Left`: The highlighter to use on the left grip button.\n"
+ " * `Grip Right`: The highlighter to use on the right grip button.\n"
+ " * `Touchpad`: The highlighter to use on the touchpad.\n"
+ " * `App Menu`: The highlighter to use on the application menu button.\n"
+ " * `System Menu`: The highlighter to use on the system menu button.")]
public VRTK_ControllerElementHighlighers elementHighlighterOverrides;
/// <summary>
/// Emitted when the controller model is toggled to be visible.
/// </summary>
public event ControllerActionsEventHandler ControllerModelVisible;
/// <summary>
/// Emitted when the controller model is toggled to be invisible.
/// </summary>
public event ControllerActionsEventHandler ControllerModelInvisible;
private bool controllerVisible = true;
private ushort hapticPulseStrength;
private uint controllerIndex;
private ushort maxHapticVibration = 3999;
private bool controllerHighlighted = false;
private Dictionary<string, Transform> cachedElements;
private Dictionary<string, object> highlighterOptions;
public virtual void OnControllerModelVisible(ControllerActionsEventArgs e)
{
if (ControllerModelVisible != null)
{
ControllerModelVisible(this, e);
}
}
public virtual void OnControllerModelInvisible(ControllerActionsEventArgs e)
{
if (ControllerModelInvisible != null)
{
ControllerModelInvisible(this, e);
}
}
/// <summary>
/// The IsControllerVisible method returns true if the controller is currently visible by whether the renderers on the controller are enabled.
/// </summary>
/// <returns>Is true if the controller model has the renderers that are attached to it are enabled.</returns>
public bool IsControllerVisible()
{
return controllerVisible;
}
/// <summary>
/// The ToggleControllerModel method is used to turn on or off the controller model by enabling or disabling the renderers on the object. It will also work for any custom controllers. It should also not disable any objects being held by the controller if they are a child of the controller object.
/// </summary>
/// <param name="state">The visibility state to toggle the controller to, `true` will make the controller visible - `false` will hide the controller model.</param>
/// <param name="grabbedChildObject">If an object is being held by the controller then this can be passed through to prevent hiding the grabbed game object as well.</param>
public void ToggleControllerModel(bool state, GameObject grabbedChildObject)
{
if (!enabled)
{
return;
}
foreach (MeshRenderer renderer in GetComponentsInChildren<MeshRenderer>())
{
if (renderer.gameObject != grabbedChildObject && (grabbedChildObject == null || !renderer.transform.IsChildOf(grabbedChildObject.transform)))
{
renderer.enabled = state;
}
}
foreach (SkinnedMeshRenderer renderer in GetComponentsInChildren<SkinnedMeshRenderer>())
{
if (renderer.gameObject != grabbedChildObject && (grabbedChildObject == null || !renderer.transform.IsChildOf(grabbedChildObject.transform)))
{
renderer.enabled = state;
}
}
controllerVisible = state;
if (state)
{
OnControllerModelVisible(SetActionEvent(controllerIndex));
}
else
{
OnControllerModelInvisible(SetActionEvent(controllerIndex));
}
}
/// <summary>
/// The SetControllerOpacity method allows the opacity of the controller model to be changed to make the controller more transparent. A lower alpha value will make the object more transparent, such as `0.5f` will make the controller partially transparent where as `0f` will make the controller completely transparent.
/// </summary>
/// <param name="alpha">The alpha level to apply to opacity of the controller object. `0f` to `1f`.</param>
public void SetControllerOpacity(float alpha)
{
if (!enabled)
{
return;
}
alpha = Mathf.Clamp(alpha, 0f, 1f);
foreach (var renderer in gameObject.GetComponentsInChildren<Renderer>())
{
if (alpha < 1f)
{
renderer.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
renderer.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
renderer.material.SetInt("_ZWrite", 0);
renderer.material.DisableKeyword("_ALPHATEST_ON");
renderer.material.DisableKeyword("_ALPHABLEND_ON");
renderer.material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
renderer.material.renderQueue = 3000;
}
else
{
renderer.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
renderer.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
renderer.material.SetInt("_ZWrite", 1);
renderer.material.DisableKeyword("_ALPHATEST_ON");
renderer.material.DisableKeyword("_ALPHABLEND_ON");
renderer.material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
renderer.material.renderQueue = -1;
}
if (renderer.material.HasProperty("_Color"))
{
renderer.material.color = new Color(renderer.material.color.r, renderer.material.color.g, renderer.material.color.b, alpha);
}
}
}
/// <summary>
/// The HighlightControllerElement method allows for an element of the controller to have its colour changed to simulate a highlighting effect of that element on the controller. It's useful for being able to draw a user's attention to a specific button on the controller.
/// </summary>
/// <param name="element">The element of the controller to apply the highlight to.</param>
/// <param name="highlight">The colour of the highlight.</param>
/// <param name="fadeDuration">The duration of fade from white to the highlight colour. Optional parameter defaults to `0f`.</param>
public void HighlightControllerElement(GameObject element, Color? highlight, float fadeDuration = 0f)
{
if (!enabled)
{
return;
}
var highlighter = element.GetComponent<VRTK_BaseHighlighter>();
if (highlighter)
{
highlighter.Highlight(highlight ?? Color.white, fadeDuration);
}
}
/// <summary>
/// The UnhighlightControllerElement method is the inverse of the HighlightControllerElement method and resets the controller element to its original colour.
/// </summary>
/// <param name="element">The element of the controller to remove the highlight from.</param>
public void UnhighlightControllerElement(GameObject element)
{
if (!enabled)
{
return;
}
var highlighter = element.GetComponent<VRTK_BaseHighlighter>();
if (highlighter)
{
highlighter.Unhighlight();
}
}
/// <summary>
/// The ToggleHighlightControllerElement method is a shortcut method that makes it easier to highlight and unhighlight a controller element in a single method rather than using the HighlightControllerElement and UnhighlightControllerElement methods separately.
/// </summary>
/// <param name="state">The highlight colour state, `true` will enable the highlight on the given element and `false` will remove the highlight from the given element.</param>
/// <param name="element">The element of the controller to apply the highlight to.</param>
/// <param name="highlight">The colour of the highlight.</param>
/// <param name="duration">The duration of fade from white to the highlight colour.</param>
public void ToggleHighlightControllerElement(bool state, GameObject element, Color? highlight = null, float duration = 0f)
{
if (element)
{
if (state)
{
HighlightControllerElement(element.gameObject, highlight ?? Color.white, duration);
}
else
{
UnhighlightControllerElement(element.gameObject);
}
}
}
/// <summary>
/// The ToggleHighlightTrigger method is a shortcut method that makes it easier to toggle the highlight state of the controller trigger element.
/// </summary>
/// <param name="state">The highlight colour state, `true` will enable the highlight on the trigger and `false` will remove the highlight from the trigger.</param>
/// <param name="highlight">The colour to highlight the trigger with.</param>
/// <param name="duration">The duration of fade from white to the highlight colour.</param>
public void ToggleHighlightTrigger(bool state, Color? highlight = null, float duration = 0f)
{
if (!state && controllerHighlighted)
{
return;
}
ToggleHighlightAlias(state, modelElementPaths.triggerModelPath, highlight, duration);
}
/// <summary>
/// The ToggleHighlightGrip method is a shortcut method that makes it easier to toggle the highlight state of the controller grip element.
/// </summary>
/// <param name="state">The highlight colour state, `true` will enable the highlight on the grip and `false` will remove the highlight from the grip.</param>
/// <param name="highlight">The colour to highlight the grip with.</param>
/// <param name="duration">The duration of fade from white to the highlight colour.</param>
public void ToggleHighlightGrip(bool state, Color? highlight = null, float duration = 0f)
{
if (!state && controllerHighlighted)
{
return;
}
ToggleHighlightAlias(state, modelElementPaths.leftGripModelPath, highlight, duration);
ToggleHighlightAlias(state, modelElementPaths.rightGripModelPath, highlight, duration);
}
/// <summary>
/// The ToggleHighlightTouchpad method is a shortcut method that makes it easier to toggle the highlight state of the controller touchpad element.
/// </summary>
/// <param name="state">The highlight colour state, `true` will enable the highlight on the touchpad and `false` will remove the highlight from the touchpad.</param>
/// <param name="highlight">The colour to highlight the touchpad with.</param>
/// <param name="duration">The duration of fade from white to the highlight colour.</param>
public void ToggleHighlightTouchpad(bool state, Color? highlight = null, float duration = 0f)
{
if (!state && controllerHighlighted)
{
return;
}
ToggleHighlightAlias(state, modelElementPaths.touchpadModelPath, highlight, duration);
}
/// <summary>
/// The ToggleHighlightApplicationMenu method is a shortcut method that makes it easier to toggle the highlight state of the controller application menu element.
/// </summary>
/// <param name="state">The highlight colour state, `true` will enable the highlight on the application menu and `false` will remove the highlight from the application menu.</param>
/// <param name="highlight">The colour to highlight the application menu with.</param>
/// <param name="duration">The duration of fade from white to the highlight colour.</param>
public void ToggleHighlightApplicationMenu(bool state, Color? highlight = null, float duration = 0f)
{
if (!state && controllerHighlighted)
{
return;
}
ToggleHighlightAlias(state, modelElementPaths.appMenuModelPath, highlight, duration);
}
/// <summary>
/// The ToggleHighlighBody method is a shortcut method that makes it easier to toggle the highlight state of the controller body element.
/// </summary>
/// <param name="state">The highlight colour state, `true` will enable the highlight on the body and `false` will remove the highlight from the body.</param>
/// <param name="highlight">The colour to highlight the body with.</param>
/// <param name="duration">The duration of fade from white to the highlight colour.</param>
public void ToggleHighlighBody(bool state, Color? highlight = null, float duration = 0f)
{
if (!state && controllerHighlighted)
{
return;
}
ToggleHighlightAlias(state, modelElementPaths.bodyModelPath, highlight, duration);
}
/// <summary>
/// The ToggleHighlightController method is a shortcut method that makes it easier to toggle the highlight state of the entire controller.
/// </summary>
/// <param name="state">The highlight colour state, `true` will enable the highlight on the entire controller `false` will remove the highlight from the entire controller.</param>
/// <param name="highlight">The colour to highlight the entire controller with.</param>
/// <param name="duration">The duration of fade from white to the highlight colour.</param>
public void ToggleHighlightController(bool state, Color? highlight = null, float duration = 0f)
{
controllerHighlighted = state;
ToggleHighlightTrigger(state, highlight, duration);
ToggleHighlightGrip(state, highlight, duration);
ToggleHighlightTouchpad(state, highlight, duration);
ToggleHighlightApplicationMenu(state, highlight, duration);
ToggleHighlightAlias(state, modelElementPaths.systemMenuModelPath, highlight, duration);
ToggleHighlightAlias(state, modelElementPaths.bodyModelPath, highlight, duration);
}
/// <summary>
/// The TriggerHapticPulse/1 method calls a single haptic pulse call on the controller for a single tick.
/// </summary>
/// <param name="strength">The intensity of the rumble of the controller motor. `0` to `3999`.</param>
public void TriggerHapticPulse(ushort strength)
{
if (!enabled)
{
return;
}
hapticPulseStrength = (strength <= maxHapticVibration ? strength : maxHapticVibration);
VRTK_SDK_Bridge.HapticPulseOnIndex(controllerIndex, hapticPulseStrength);
}
/// <summary>
/// The TriggerHapticPulse/3 method calls a haptic pulse for a specified amount of time rather than just a single tick. Each pulse can be separated by providing a `pulseInterval` to pause between each haptic pulse.
/// </summary>
/// <param name="strength">The intensity of the rumble of the controller motor. `0` to `3999`.</param>
/// <param name="duration">The length of time the rumble should continue for.</param>
/// <param name="pulseInterval">The interval to wait between each haptic pulse.</param>
public void TriggerHapticPulse(ushort strength, float duration, float pulseInterval)
{
if (!enabled)
{
return;
}
hapticPulseStrength = (strength <= maxHapticVibration ? strength : maxHapticVibration);
StartCoroutine(HapticPulse(duration, hapticPulseStrength, pulseInterval));
}
/// <summary>
/// The InitaliseHighlighters method sets up the highlighters on the controller model.
/// </summary>
public void InitaliseHighlighters()
{
highlighterOptions = new Dictionary<string, object>();
highlighterOptions.Add("resetMainTexture", true);
VRTK_BaseHighlighter objectHighlighter = Utilities.GetActiveHighlighter(gameObject);
if (objectHighlighter == null)
{
objectHighlighter = gameObject.AddComponent<VRTK_MaterialColorSwapHighlighter>();
}
objectHighlighter.Initialise(null, highlighterOptions);
AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.ApplicationMenu)), objectHighlighter, elementHighlighterOverrides.appMenu);
AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Body)), objectHighlighter, elementHighlighterOverrides.body);
AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripLeft)), objectHighlighter, elementHighlighterOverrides.gripLeft);
AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripRight)), objectHighlighter, elementHighlighterOverrides.gripRight);
AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.SystemMenu)), objectHighlighter, elementHighlighterOverrides.systemMenu);
AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Touchpad)), objectHighlighter, elementHighlighterOverrides.touchpad);
AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Trigger)), objectHighlighter, elementHighlighterOverrides.trigger);
}
private void Awake()
{
gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
cachedElements = new Dictionary<string, Transform>();
var controllerHand = VRTK_DeviceFinder.GetControllerHand(gameObject);
if (modelElementPaths.bodyModelPath.Trim() == "")
{
modelElementPaths.bodyModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Body, controllerHand);
}
if (modelElementPaths.triggerModelPath.Trim() == "")
{
modelElementPaths.triggerModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Trigger, controllerHand);
}
if (modelElementPaths.leftGripModelPath.Trim() == "")
{
modelElementPaths.leftGripModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripLeft, controllerHand);
}
if (modelElementPaths.rightGripModelPath.Trim() == "")
{
modelElementPaths.rightGripModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripRight, controllerHand);
}
if (modelElementPaths.touchpadModelPath.Trim() == "")
{
modelElementPaths.touchpadModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Touchpad, controllerHand);
}
if (modelElementPaths.appMenuModelPath.Trim() == "")
{
modelElementPaths.appMenuModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.ApplicationMenu, controllerHand);
}
if (modelElementPaths.systemMenuModelPath.Trim() == "")
{
modelElementPaths.systemMenuModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.SystemMenu, controllerHand);
}
}
private void OnEnable()
{
StartCoroutine(WaitForModel());
}
private void Update()
{
controllerIndex = VRTK_DeviceFinder.GetControllerIndex(gameObject);
}
private IEnumerator WaitForModel()
{
while (GetElementTransform(modelElementPaths.bodyModelPath) == null)
{
yield return null;
}
InitaliseHighlighters();
}
private void AddHighlighterToElement(Transform element, VRTK_BaseHighlighter parentHighlighter, VRTK_BaseHighlighter overrideHighlighter)
{
if (element)
{
var highlighter = (overrideHighlighter != null ? overrideHighlighter : parentHighlighter);
VRTK_BaseHighlighter clonedHighlighter = (VRTK_BaseHighlighter)Utilities.CloneComponent(highlighter, element.gameObject);
clonedHighlighter.Initialise(null, highlighterOptions);
}
}
private IEnumerator HapticPulse(float duration, ushort hapticPulseStrength, float pulseInterval)
{
if (pulseInterval <= 0)
{
yield break;
}
while (duration > 0)
{
VRTK_SDK_Bridge.HapticPulseOnIndex(controllerIndex, hapticPulseStrength);
yield return new WaitForSeconds(pulseInterval);
duration -= pulseInterval;
}
}
private IEnumerator CycleColor(Material material, Color startColor, Color endColor, float duration)
{
var elapsedTime = 0f;
while (elapsedTime <= duration)
{
elapsedTime += Time.deltaTime;
if (material.HasProperty("_Color"))
{
material.color = Color.Lerp(startColor, endColor, (elapsedTime / duration));
}
yield return null;
}
}
private Transform GetElementTransform(string path)
{
if (cachedElements == null)
{
return null;
}
if (!cachedElements.ContainsKey(path) || cachedElements[path] == null)
{
cachedElements[path] = transform.Find(path);
}
return cachedElements[path];
}
private void ToggleHighlightAlias(bool state, string transformPath, Color? highlight, float duration = 0f)
{
var element = GetElementTransform(transformPath);
if (element)
{
ToggleHighlightControllerElement(state, element.gameObject, highlight, duration);
}
}
private ControllerActionsEventArgs SetActionEvent(uint index)
{
ControllerActionsEventArgs e;
e.controllerIndex = index;
return e;
}
}
} | mit |
TracklistMe/client-web | static/fonts/Basic-picto/ie7/ie7.css | 17763 | .basic-pictohome {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '_');
}
.basic-pictofilecross {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '“');
}
.basic-pictofiledownload {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '‘');
}
.basic-pictofileupload {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '{');
}
.basic-pictofilecheck {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '¶');
}
.basic-pictopin {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'π');
}
.basic-pictotext {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '@');
}
.basic-pictobold {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '1');
}
.basic-pictoitalic {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '2');
}
.basic-pictounderline {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '3');
}
.basic-pictostrike {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Á');
}
.basic-pictosymbol {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '•');
}
.basic-pictosuperior {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '°');
}
.basic-pictoindent-more {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '»');
}
.basic-pictoindent-less {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Û');
}
.basic-pictoliste {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '≠');
}
.basic-pictocalendar {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'A');
}
.basic-pictoverticalcircle {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'I');
}
.basic-pictopen2 {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'k');
}
.basic-pictosimply-down {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '¨');
}
.basic-pictosimply-left {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '<');
}
.basic-pictosimply-right {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '>');
}
.basic-pictosimply-up {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '^');
}
.basic-pictobag {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ß');
}
.basic-pictoshop {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '€');
}
.basic-pictosmarthphone {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '‰');
}
.basic-pictogoout {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Ï');
}
.basic-pictogoin {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Í');
}
.basic-pictocode {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '*');
}
.basic-pictoarrange {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '®');
}
.basic-pictochrono {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '™');
}
.basic-pictotel {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = ')');
}
.basic-pictocreditcard {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '¥');
}
.basic-pictoFilter {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '·');
}
.basic-pictofemme {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '‹');
}
.basic-pictohomme {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'µ');
}
.basic-pictosquare_help {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '∞');
}
.basic-pictointerdict {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'n');
}
.basic-pictomouse {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '~');
}
.basic-pictofilter {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ı');
}
.basic-pictocar {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '¿');
}
.basic-pictoeye {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'e');
}
.basic-pictopaper-clip {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '∏');
}
.basic-pictomail {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'm');
}
.basic-pictotoggle {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'y');
}
.basic-pictolayout {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = ':');
}
.basic-pictolink {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'l');
}
.basic-pictobell {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'E');
}
.basic-pictolock {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'L');
}
.basic-pictounlock {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '|');
}
.basic-pictoribbon {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '/');
}
.basic-pictoimage {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'i');
}
.basic-pictosignal {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'R');
}
.basic-pictotarget {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'œ');
}
.basic-pictoclipboard {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '∫');
}
.basic-pictoclock {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'C');
}
.basic-pictowatch {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'w');
}
.basic-pictocamera {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'p');
}
.basic-pictovideo {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'v');
}
.basic-pictoair-play {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Y');
}
.basic-pictoprinter {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'P');
}
.basic-pictomonitor {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Ù');
}
.basic-pictocog {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'g');
}
.basic-pictoheart {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'h');
}
.basic-pictoheartfull {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'H');
}
.basic-pictostar {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 's');
}
.basic-pictostarfull {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'S');
}
.basic-pictoalign-justify {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '4');
}
.basic-pictoalign-left {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '5');
}
.basic-pictoalign-center {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '6');
}
.basic-pictoalign-right {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '7');
}
.basic-pictolayers {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'O');
}
.basic-pictostack {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '√');
}
.basic-pictostack-2 {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'V');
}
.basic-pictopaper {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'o');
}
.basic-pictopaper-stack {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '◊');
}
.basic-pictosearch {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'z');
}
.basic-pictozoom-in {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Z');
}
.basic-pictozoom-out {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Å');
}
.basic-pictorearward {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'B');
}
.basic-pictoforward {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'N');
}
.basic-pictocircle-plus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '±');
}
.basic-pictocircle-minus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '–');
}
.basic-pictocircle-check {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '¢');
}
.basic-pictocircle-cross {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '⁄');
}
.basic-pictosquare-plus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '«');
}
.basic-pictosquare-minus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '¡');
}
.basic-pictosquare-check {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Ç');
}
.basic-pictosquare-cross {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '}');
}
.basic-pictomicrophone {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '`');
}
.basic-pictorecord {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '&');
}
.basic-pictoskip-back {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'é');
}
.basic-pictorewind {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '"');
}
.basic-pictoplay {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = ''');
}
.basic-pictopause {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '(');
}
.basic-pictostop {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '§');
}
.basic-pictofast-forward {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'è');
}
.basic-pictoskip-forward {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '!');
}
.basic-pictoshuffle {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ç');
}
.basic-pictorepeat {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'à');
}
.basic-pictofolder {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'f');
}
.basic-pictoumbrella {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '´');
}
.basic-pictomoon {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '„');
}
.basic-pictothermometer {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '”');
}
.basic-pictodrop {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '’');
}
.basic-pictosun {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '[');
}
.basic-pictocloud {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'å');
}
.basic-pictocloud-upload {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ª');
}
.basic-pictocloud-download {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '∆');
}
.basic-pictoupload {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'U');
}
.basic-pictodownload {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'D');
}
.basic-pictolocation {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Ó');
}
.basic-pictolocation-2 {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'M');
}
.basic-pictomap {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '%');
}
.basic-pictobattery {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '.');
}
.basic-pictohead {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'j');
}
.basic-pictobriefcase {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '$');
}
.basic-pictospeech-bubble {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'b');
}
.basic-pictoanchor {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'æ');
}
.basic-pictoglobe {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'W');
}
.basic-pictoreload {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'r');
}
.basic-pictoshare {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'a');
}
.basic-pictotag {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '†');
}
.basic-pictopower {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'q');
}
.basic-pictocommand {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '#');
}
.basic-pictoalt {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Æ');
}
.basic-pictobar-graph {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'G');
}
.basic-pictobar-graph-2 {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'fl');
}
.basic-pictopie-graph {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '©');
}
.basic-pictoarrow-left {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '≤');
}
.basic-pictoarrow-right {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '≥');
}
.basic-pictoarrow-up {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ô');
}
.basic-pictoarrow-down {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Ô');
}
.basic-pictovolume {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Ò');
}
.basic-pictomute {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '∑');
}
.basic-pictogrid-2 {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'fi');
}
.basic-pictoloader {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '¬');
}
.basic-pictoban {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '\');
}
.basic-pictoflag {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ƒ');
}
.basic-pictotrash {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 't');
}
.basic-pictoexpand {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'î');
}
.basic-pictocontract {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ï');
}
.basic-pictomaximize {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '?');
}
.basic-pictominimize {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = ',');
}
.basic-pictoplus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '+');
}
.basic-pictominus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '-');
}
.basic-pictocheck {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'c');
}
.basic-pictocross {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'x');
}
.basic-pictomove {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ù');
}
.basic-pictodelete {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'T');
}
.basic-pictomenu {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '=');
}
.basic-pictoarchive {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Â');
}
.basic-pictoinbox {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'd');
}
.basic-pictooutbox {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'u');
}
.basic-pictofile {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'F');
}
.basic-pictofile-add {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '');
}
.basic-pictofile-subtract {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ë');
}
.basic-pictohelp {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Ì');
}
.basic-pictoopen {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Œ');
}
.basic-pictoellipsis {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '…');
}
.basic-pictobox {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = ';');
}
.basic-pictobook {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ø');
}
.basic-pictomarquee-plus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '÷');
}
.basic-pictomarquee-minus {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '—');
}
.basic-pictocolumns {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = ']');
}
.basic-pictocontent-right {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '8');
}
.basic-pictocontent-left {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '9');
}
.basic-pictogrid {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '0');
}
.basic-pictodisc {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'Q');
}
.basic-pictoserver {
*zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'È');
}
| mit |
erikdstock/force | src/v2/DevTools/MockRouter.tsx | 1901 | import { RouterConfig } from "v2/Artsy/Router"
import { buildClientApp } from "v2/Artsy/Router/buildClientApp"
import {
createMockNetworkLayer,
createMockNetworkLayer2,
} from "v2/DevTools/createMockNetworkLayer"
import { HistoryOptions } from "farce"
import { RouteConfig } from "found"
import { IMocks } from "graphql-tools/dist/Interfaces"
import React from "react"
import { getUser } from "v2/Utils/user"
interface Props {
routes: RouteConfig[]
initialRoute?: string
initialState?: object
historyOptions?: HistoryOptions
mockResolvers?: IMocks
mockData?: object
mockMutationResults?: object
context?: RouterConfig["context"]
}
export class MockRouter extends React.Component<Props> {
state = {
ClientApp: null,
}
static defaultProps = {
initialRoute: "/",
}
async componentDidMount() {
const {
routes,
initialRoute,
historyOptions,
mockResolvers,
mockData,
mockMutationResults,
context,
} = this.props
try {
const user = getUser(context && context.user)
const relayEnvironment = mockResolvers
? createMockNetworkLayer(mockResolvers)
: mockData || mockMutationResults
? createMockNetworkLayer2({ mockData, mockMutationResults })
: undefined
const { ClientApp } = await buildClientApp({
routes,
initialRoute,
history: {
protocol: "memory",
options: historyOptions,
},
context: {
...context,
user,
relayEnvironment,
} as any,
})
this.setState({
ClientApp,
})
} catch (error) {
console.error("MockRouter", error)
}
}
render() {
const { ClientApp } = this.state
return (
<React.Fragment>
{ClientApp && <ClientApp {...this.props.initialState} />}
</React.Fragment>
)
}
}
| mit |
dbrumley/recfi | llvm-3.3/lib/CodeGen/AsmPrinter/DwarfDebug.h | 23578 | //===-- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework ------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing dwarf debug info into asm files.
//
//===----------------------------------------------------------------------===//
#ifndef CODEGEN_ASMPRINTER_DWARFDEBUG_H__
#define CODEGEN_ASMPRINTER_DWARFDEBUG_H__
#include "DIE.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/DebugInfo.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/DebugLoc.h"
namespace llvm {
class CompileUnit;
class ConstantInt;
class ConstantFP;
class DbgVariable;
class MachineFrameInfo;
class MachineModuleInfo;
class MachineOperand;
class MCAsmInfo;
class DIEAbbrev;
class DIE;
class DIEBlock;
class DIEEntry;
class DwarfDebug;
//===----------------------------------------------------------------------===//
/// \brief This class is used to record source line correspondence.
class SrcLineInfo {
unsigned Line; // Source line number.
unsigned Column; // Source column.
unsigned SourceID; // Source ID number.
MCSymbol *Label; // Label in code ID number.
public:
SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
: Line(L), Column(C), SourceID(S), Label(label) {}
// Accessors
unsigned getLine() const { return Line; }
unsigned getColumn() const { return Column; }
unsigned getSourceID() const { return SourceID; }
MCSymbol *getLabel() const { return Label; }
};
/// \brief This struct describes location entries emitted in the .debug_loc
/// section.
typedef struct DotDebugLocEntry {
const MCSymbol *Begin;
const MCSymbol *End;
MachineLocation Loc;
const MDNode *Variable;
bool Merged;
bool Constant;
enum EntryType {
E_Location,
E_Integer,
E_ConstantFP,
E_ConstantInt
};
enum EntryType EntryKind;
union {
int64_t Int;
const ConstantFP *CFP;
const ConstantInt *CIP;
} Constants;
DotDebugLocEntry()
: Begin(0), End(0), Variable(0), Merged(false),
Constant(false) { Constants.Int = 0;}
DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, MachineLocation &L,
const MDNode *V)
: Begin(B), End(E), Loc(L), Variable(V), Merged(false),
Constant(false) { Constants.Int = 0; EntryKind = E_Location; }
DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, int64_t i)
: Begin(B), End(E), Variable(0), Merged(false),
Constant(true) { Constants.Int = i; EntryKind = E_Integer; }
DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, const ConstantFP *FPtr)
: Begin(B), End(E), Variable(0), Merged(false),
Constant(true) { Constants.CFP = FPtr; EntryKind = E_ConstantFP; }
DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E,
const ConstantInt *IPtr)
: Begin(B), End(E), Variable(0), Merged(false),
Constant(true) { Constants.CIP = IPtr; EntryKind = E_ConstantInt; }
/// \brief Empty entries are also used as a trigger to emit temp label. Such
/// labels are referenced is used to find debug_loc offset for a given DIE.
bool isEmpty() { return Begin == 0 && End == 0; }
bool isMerged() { return Merged; }
void Merge(DotDebugLocEntry *Next) {
if (!(Begin && Loc == Next->Loc && End == Next->Begin))
return;
Next->Begin = Begin;
Merged = true;
}
bool isLocation() const { return EntryKind == E_Location; }
bool isInt() const { return EntryKind == E_Integer; }
bool isConstantFP() const { return EntryKind == E_ConstantFP; }
bool isConstantInt() const { return EntryKind == E_ConstantInt; }
int64_t getInt() { return Constants.Int; }
const ConstantFP *getConstantFP() { return Constants.CFP; }
const ConstantInt *getConstantInt() { return Constants.CIP; }
} DotDebugLocEntry;
//===----------------------------------------------------------------------===//
/// \brief This class is used to track local variable information.
class DbgVariable {
DIVariable Var; // Variable Descriptor.
DIE *TheDIE; // Variable DIE.
unsigned DotDebugLocOffset; // Offset in DotDebugLocEntries.
DbgVariable *AbsVar; // Corresponding Abstract variable, if any.
const MachineInstr *MInsn; // DBG_VALUE instruction of the variable.
int FrameIndex;
public:
// AbsVar may be NULL.
DbgVariable(DIVariable V, DbgVariable *AV)
: Var(V), TheDIE(0), DotDebugLocOffset(~0U), AbsVar(AV), MInsn(0),
FrameIndex(~0) {}
// Accessors.
DIVariable getVariable() const { return Var; }
void setDIE(DIE *D) { TheDIE = D; }
DIE *getDIE() const { return TheDIE; }
void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
StringRef getName() const { return Var.getName(); }
DbgVariable *getAbstractVariable() const { return AbsVar; }
const MachineInstr *getMInsn() const { return MInsn; }
void setMInsn(const MachineInstr *M) { MInsn = M; }
int getFrameIndex() const { return FrameIndex; }
void setFrameIndex(int FI) { FrameIndex = FI; }
// Translate tag to proper Dwarf tag.
unsigned getTag() const {
if (Var.getTag() == dwarf::DW_TAG_arg_variable)
return dwarf::DW_TAG_formal_parameter;
return dwarf::DW_TAG_variable;
}
/// \brief Return true if DbgVariable is artificial.
bool isArtificial() const {
if (Var.isArtificial())
return true;
if (getType().isArtificial())
return true;
return false;
}
bool isObjectPointer() const {
if (Var.isObjectPointer())
return true;
if (getType().isObjectPointer())
return true;
return false;
}
bool variableHasComplexAddress() const {
assert(Var.Verify() && "Invalid complex DbgVariable!");
return Var.hasComplexAddress();
}
bool isBlockByrefVariable() const {
assert(Var.Verify() && "Invalid complex DbgVariable!");
return Var.isBlockByrefVariable();
}
unsigned getNumAddrElements() const {
assert(Var.Verify() && "Invalid complex DbgVariable!");
return Var.getNumAddrElements();
}
uint64_t getAddrElement(unsigned i) const {
return Var.getAddrElement(i);
}
DIType getType() const;
};
// A String->Symbol mapping of strings used by indirect
// references.
typedef StringMap<std::pair<MCSymbol*, unsigned>,
BumpPtrAllocator&> StrPool;
// A Symbol->pair<Symbol, unsigned> mapping of addresses used by indirect
// references.
typedef DenseMap<MCSymbol *, std::pair<MCSymbol *, unsigned> > AddrPool;
/// \brief Collects and handles information specific to a particular
/// collection of units.
class DwarfUnits {
// Target of Dwarf emission, used for sizing of abbreviations.
AsmPrinter *Asm;
// Used to uniquely define abbreviations.
FoldingSet<DIEAbbrev> *AbbreviationsSet;
// A list of all the unique abbreviations in use.
std::vector<DIEAbbrev *> *Abbreviations;
// A pointer to all units in the section.
SmallVector<CompileUnit *, 1> CUs;
// Collection of strings for this unit and assorted symbols.
StrPool StringPool;
unsigned NextStringPoolNumber;
std::string StringPref;
// Collection of addresses for this unit and assorted labels.
AddrPool AddressPool;
unsigned NextAddrPoolNumber;
public:
DwarfUnits(AsmPrinter *AP, FoldingSet<DIEAbbrev> *AS,
std::vector<DIEAbbrev *> *A, const char *Pref,
BumpPtrAllocator &DA) :
Asm(AP), AbbreviationsSet(AS), Abbreviations(A),
StringPool(DA), NextStringPoolNumber(0), StringPref(Pref),
AddressPool(), NextAddrPoolNumber(0) {}
/// \brief Compute the size and offset of a DIE given an incoming Offset.
unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
/// \brief Compute the size and offset of all the DIEs.
void computeSizeAndOffsets();
/// \brief Define a unique number for the abbreviation.
void assignAbbrevNumber(DIEAbbrev &Abbrev);
/// \brief Add a unit to the list of CUs.
void addUnit(CompileUnit *CU) { CUs.push_back(CU); }
/// \brief Emit all of the units to the section listed with the given
/// abbreviation section.
void emitUnits(DwarfDebug *, const MCSection *, const MCSection *,
const MCSymbol *);
/// \brief Emit all of the strings to the section given.
void emitStrings(const MCSection *, const MCSection *, const MCSymbol *);
/// \brief Emit all of the addresses to the section given.
void emitAddresses(const MCSection *);
/// \brief Returns the entry into the start of the pool.
MCSymbol *getStringPoolSym();
/// \brief Returns an entry into the string pool with the given
/// string text.
MCSymbol *getStringPoolEntry(StringRef Str);
/// \brief Returns the index into the string pool with the given
/// string text.
unsigned getStringPoolIndex(StringRef Str);
/// \brief Returns the string pool.
StrPool *getStringPool() { return &StringPool; }
/// \brief Returns the index into the address pool with the given
/// label/symbol.
unsigned getAddrPoolIndex(MCSymbol *);
/// \brief Returns the address pool.
AddrPool *getAddrPool() { return &AddressPool; }
/// \brief for a given compile unit DIE, returns offset from beginning of
/// debug info.
unsigned getCUOffset(DIE *Die);
};
/// \brief Collects and handles dwarf debug information.
class DwarfDebug {
// Target of Dwarf emission.
AsmPrinter *Asm;
// Collected machine module information.
MachineModuleInfo *MMI;
// All DIEValues are allocated through this allocator.
BumpPtrAllocator DIEValueAllocator;
//===--------------------------------------------------------------------===//
// Attribute used to construct specific Dwarf sections.
//
CompileUnit *FirstCU;
// Maps MDNode with its corresponding CompileUnit.
DenseMap <const MDNode *, CompileUnit *> CUMap;
// Maps subprogram MDNode with its corresponding CompileUnit.
DenseMap <const MDNode *, CompileUnit *> SPMap;
// Used to uniquely define abbreviations.
FoldingSet<DIEAbbrev> AbbreviationsSet;
// A list of all the unique abbreviations in use.
std::vector<DIEAbbrev *> Abbreviations;
// Stores the current file ID for a given compile unit.
DenseMap <unsigned, unsigned> FileIDCUMap;
// Source id map, i.e. CUID, source filename and directory,
// separated by a zero byte, mapped to a unique id.
StringMap<unsigned, BumpPtrAllocator&> SourceIdMap;
// Provides a unique id per text section.
SetVector<const MCSection*> SectionMap;
// List of Arguments (DbgValues) for current function.
SmallVector<DbgVariable *, 8> CurrentFnArguments;
LexicalScopes LScopes;
// Collection of abstract subprogram DIEs.
DenseMap<const MDNode *, DIE *> AbstractSPDies;
// Collection of dbg variables of a scope.
DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> > ScopeVariables;
// Collection of abstract variables.
DenseMap<const MDNode *, DbgVariable *> AbstractVariables;
// Collection of DotDebugLocEntry.
SmallVector<DotDebugLocEntry, 4> DotDebugLocEntries;
// Collection of subprogram DIEs that are marked (at the end of the module)
// as DW_AT_inline.
SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
// Keep track of inlined functions and their location. This
// information is used to populate the debug_inlined section.
typedef std::pair<const MCSymbol *, DIE *> InlineInfoLabels;
DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> > InlineInfo;
SmallVector<const MDNode *, 4> InlinedSPNodes;
// This is a collection of subprogram MDNodes that are processed to
// create DIEs.
SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
// Maps instruction with label emitted before instruction.
DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
// Maps instruction with label emitted after instruction.
DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
// Every user variable mentioned by a DBG_VALUE instruction in order of
// appearance.
SmallVector<const MDNode*, 8> UserVariables;
// For each user variable, keep a list of DBG_VALUE instructions in order.
// The list can also contain normal instructions that clobber the previous
// DBG_VALUE.
typedef DenseMap<const MDNode*, SmallVector<const MachineInstr*, 4> >
DbgValueHistoryMap;
DbgValueHistoryMap DbgValues;
SmallVector<const MCSymbol *, 8> DebugRangeSymbols;
// Previous instruction's location information. This is used to determine
// label location to indicate scope boundries in dwarf debug info.
DebugLoc PrevInstLoc;
MCSymbol *PrevLabel;
// This location indicates end of function prologue and beginning of function
// body.
DebugLoc PrologEndLoc;
struct FunctionDebugFrameInfo {
unsigned Number;
std::vector<MachineMove> Moves;
FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M)
: Number(Num), Moves(M) {}
};
std::vector<FunctionDebugFrameInfo> DebugFrames;
// Section Symbols: these are assembler temporary labels that are emitted at
// the beginning of each supported dwarf section. These are used to form
// section offsets and are created by EmitSectionLabels.
MCSymbol *DwarfInfoSectionSym, *DwarfAbbrevSectionSym;
MCSymbol *DwarfStrSectionSym, *TextSectionSym, *DwarfDebugRangeSectionSym;
MCSymbol *DwarfDebugLocSectionSym, *DwarfLineSectionSym, *DwarfAddrSectionSym;
MCSymbol *FunctionBeginSym, *FunctionEndSym;
MCSymbol *DwarfAbbrevDWOSectionSym, *DwarfStrDWOSectionSym;
// As an optimization, there is no need to emit an entry in the directory
// table for the same directory as DW_at_comp_dir.
StringRef CompilationDir;
// Counter for assigning globally unique IDs for CUs.
unsigned GlobalCUIndexCount;
// Holder for the file specific debug information.
DwarfUnits InfoHolder;
// Holders for the various debug information flags that we might need to
// have exposed. See accessor functions below for description.
// Whether or not we're emitting info for older versions of gdb on darwin.
bool IsDarwinGDBCompat;
// DWARF5 Experimental Options
bool HasDwarfAccelTables;
bool HasSplitDwarf;
// Separated Dwarf Variables
// In general these will all be for bits that are left in the
// original object file, rather than things that are meant
// to be in the .dwo sections.
// The CUs left in the original object file for separated debug info.
SmallVector<CompileUnit *, 1> SkeletonCUs;
// Used to uniquely define abbreviations for the skeleton emission.
FoldingSet<DIEAbbrev> SkeletonAbbrevSet;
// A list of all the unique abbreviations in use.
std::vector<DIEAbbrev *> SkeletonAbbrevs;
// Holder for the skeleton information.
DwarfUnits SkeletonHolder;
typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
ImportedEntityMap;
ImportedEntityMap ScopesWithImportedEntities;
private:
void addScopeVariable(LexicalScope *LS, DbgVariable *Var);
/// \brief Find abstract variable associated with Var.
DbgVariable *findAbstractVariable(DIVariable &Var, DebugLoc Loc);
/// \brief Find DIE for the given subprogram and attach appropriate
/// DW_AT_low_pc and DW_AT_high_pc attributes. If there are global
/// variables in this scope then create and insert DIEs for these
/// variables.
DIE *updateSubprogramScopeDIE(CompileUnit *SPCU, const MDNode *SPNode);
/// \brief Construct new DW_TAG_lexical_block for this scope and
/// attach DW_AT_low_pc/DW_AT_high_pc labels.
DIE *constructLexicalScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
/// \brief This scope represents inlined body of a function. Construct
/// DIE to represent this concrete inlined copy of the function.
DIE *constructInlinedScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
/// \brief Construct a DIE for this scope.
DIE *constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
/// \brief Emit initial Dwarf sections with a label at the start of each one.
void emitSectionLabels();
/// \brief Compute the size and offset of a DIE given an incoming Offset.
unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
/// \brief Compute the size and offset of all the DIEs.
void computeSizeAndOffsets();
/// \brief Attach DW_AT_inline attribute with inlined subprogram DIEs.
void computeInlinedDIEs();
/// \brief Collect info for variables that were optimized out.
void collectDeadVariables();
/// \brief Finish off debug information after all functions have been
/// processed.
void finalizeModuleInfo();
/// \brief Emit labels to close any remaining sections that have been left
/// open.
void endSections();
/// \brief Emit a set of abbreviations to the specific section.
void emitAbbrevs(const MCSection *, std::vector<DIEAbbrev*> *);
/// \brief Emit the debug info section.
void emitDebugInfo();
/// \brief Emit the abbreviation section.
void emitAbbreviations();
/// \brief Emit the last address of the section and the end of
/// the line matrix.
void emitEndOfLineMatrix(unsigned SectionEnd);
/// \brief Emit visible names into a hashed accelerator table section.
void emitAccelNames();
/// \brief Emit objective C classes and categories into a hashed
/// accelerator table section.
void emitAccelObjC();
/// \brief Emit namespace dies into a hashed accelerator table.
void emitAccelNamespaces();
/// \brief Emit type dies into a hashed accelerator table.
void emitAccelTypes();
/// \brief Emit visible names into a debug pubnames section.
void emitDebugPubnames();
/// \brief Emit visible types into a debug pubtypes section.
void emitDebugPubTypes();
/// \brief Emit visible names into a debug str section.
void emitDebugStr();
/// \brief Emit visible names into a debug loc section.
void emitDebugLoc();
/// \brief Emit visible names into a debug aranges section.
void emitDebugARanges();
/// \brief Emit visible names into a debug ranges section.
void emitDebugRanges();
/// \brief Emit visible names into a debug macinfo section.
void emitDebugMacInfo();
/// \brief Emit inline info using custom format.
void emitDebugInlineInfo();
/// DWARF 5 Experimental Split Dwarf Emitters
/// \brief Construct the split debug info compile unit for the debug info
/// section.
CompileUnit *constructSkeletonCU(const MDNode *);
/// \brief Emit the local split abbreviations.
void emitSkeletonAbbrevs(const MCSection *);
/// \brief Emit the debug info dwo section.
void emitDebugInfoDWO();
/// \brief Emit the debug abbrev dwo section.
void emitDebugAbbrevDWO();
/// \brief Emit the debug str dwo section.
void emitDebugStrDWO();
/// \brief Create new CompileUnit for the given metadata node with tag
/// DW_TAG_compile_unit.
CompileUnit *constructCompileUnit(const MDNode *N);
/// \brief Construct subprogram DIE.
void constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N);
/// \brief Construct import_module DIE.
void constructImportedModuleDIE(CompileUnit *TheCU, const MDNode *N);
/// \brief Construct import_module DIE.
void constructImportedModuleDIE(CompileUnit *TheCU, const MDNode *N,
DIE *Context);
/// \brief Construct import_module DIE.
void constructImportedModuleDIE(CompileUnit *TheCU,
const DIImportedModule &Module,
DIE *Context);
/// \brief Register a source line with debug info. Returns the unique
/// label that was emitted and which provides correspondence to the
/// source line list.
void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
unsigned Flags);
/// \brief Indentify instructions that are marking the beginning of or
/// ending of a scope.
void identifyScopeMarkers();
/// \brief If Var is an current function argument that add it in
/// CurrentFnArguments list.
bool addCurrentFnArgument(const MachineFunction *MF,
DbgVariable *Var, LexicalScope *Scope);
/// \brief Populate LexicalScope entries with variables' info.
void collectVariableInfo(const MachineFunction *,
SmallPtrSet<const MDNode *, 16> &ProcessedVars);
/// \brief Collect variable information from the side table maintained
/// by MMI.
void collectVariableInfoFromMMITable(const MachineFunction * MF,
SmallPtrSet<const MDNode *, 16> &P);
/// \brief Ensure that a label will be emitted before MI.
void requestLabelBeforeInsn(const MachineInstr *MI) {
LabelsBeforeInsn.insert(std::make_pair(MI, (MCSymbol*)0));
}
/// \brief Return Label preceding the instruction.
MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
/// \brief Ensure that a label will be emitted after MI.
void requestLabelAfterInsn(const MachineInstr *MI) {
LabelsAfterInsn.insert(std::make_pair(MI, (MCSymbol*)0));
}
/// \brief Return Label immediately following the instruction.
MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
public:
//===--------------------------------------------------------------------===//
// Main entry points.
//
DwarfDebug(AsmPrinter *A, Module *M);
~DwarfDebug();
/// \brief Emit all Dwarf sections that should come prior to the
/// content.
void beginModule();
/// \brief Emit all Dwarf sections that should come after the content.
void endModule();
/// \brief Gather pre-function debug information.
void beginFunction(const MachineFunction *MF);
/// \brief Gather and emit post-function debug information.
void endFunction(const MachineFunction *MF);
/// \brief Process beginning of an instruction.
void beginInstruction(const MachineInstr *MI);
/// \brief Process end of an instruction.
void endInstruction(const MachineInstr *MI);
/// \brief Look up the source id with the given directory and source file
/// names. If none currently exists, create a new id and insert it in the
/// SourceIds map.
unsigned getOrCreateSourceID(StringRef DirName, StringRef FullName,
unsigned CUID);
/// \brief Recursively Emits a debug information entry.
void emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs);
/// \brief Returns whether or not to limit some of our debug
/// output to the limitations of darwin gdb.
bool useDarwinGDBCompat() { return IsDarwinGDBCompat; }
// Experimental DWARF5 features.
/// \brief Returns whether or not to emit tables that dwarf consumers can
/// use to accelerate lookup.
bool useDwarfAccelTables() { return HasDwarfAccelTables; }
/// \brief Returns whether or not to change the current debug info for the
/// split dwarf proposal support.
bool useSplitDwarf() { return HasSplitDwarf; }
};
} // End of namespace llvm
#endif
| mit |
mwoynarski/KunstmaanBundlesCMS | src/Kunstmaan/TaggingBundle/Tests/unit/DependencyInjection/ConfigurationTest.php | 696 | <?php
namespace Kunstmaan\TaggingBundle\Tests\DependencyInjection;
use Kunstmaan\TaggingBundle\DependencyInjection\Configuration;
use Matthias\SymfonyConfigTest\PhpUnit\ConfigurationTestCaseTrait;
use PHPUnit\Framework\TestCase;
/**
* Class ConfigurationTest
*/
class ConfigurationTest extends TestCase
{
use ConfigurationTestCaseTrait;
/**
* @return \Symfony\Component\Config\Definition\ConfigurationInterface
*/
protected function getConfiguration()
{
return new Configuration();
}
public function testProcessedValueContainsRequiredValue()
{
$array = [];
$this->assertProcessedConfigurationEquals([$array], $array);
}
}
| mit |
minhnguyen-balance/oro_platform | vendor/oro/platform/src/Oro/Bundle/NavigationBundle/Tests/Unit/Event/ResponseHistoryListenerTest.php | 8766 | <?php
namespace Oro\Bundle\NavigationBundle\Tests\Unit\Event;
use Oro\Bundle\UserBundle\Entity\User;
use Oro\Bundle\NavigationBundle\Entity\NavigationHistoryItem;
use Oro\Bundle\NavigationBundle\Event\ResponseHistoryListener;
use Oro\Bundle\NavigationBundle\Provider\TitleService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class ResponseHistoryListenerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $em;
/**
* @var \Symfony\Component\Security\Core\SecurityContextInterface
*/
protected $securityContext;
/**
* @var ResponseHistoryListener
*/
protected $listener;
/**
* @var NavigationHistoryItem
*/
protected $item;
/**
* @var \Oro\Bundle\NavigationBundle\Entity\Builder\ItemFactory
*/
protected $factory;
/**
* @var Request
*/
protected $request;
/**
* @var TitleService
*/
protected $titleService;
/**
* @var string
*/
protected $serializedTitle;
public function setUp()
{
$this->factory = $this->getMock('Oro\Bundle\NavigationBundle\Entity\Builder\ItemFactory');
$this->securityContext = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
$user = new User();
$user->setEmail('[email protected]');
$token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$token->expects($this->exactly(2))
->method('getUser')
->will($this->returnValue($user));
$this->securityContext->expects($this->any())
->method('getToken')
->will($this->returnValue($token));
$this->item = $this->getMock('Oro\Bundle\NavigationBundle\Entity\NavigationHistoryItem');
$this->serializedTitle = json_encode(array('titleTemplate' => 'Test title template'));
}
public function testOnResponse()
{
$response = $this->getResponse();
$repository = $this->getDefaultRepositoryMock($this->item);
$em = $this->getEntityManager($repository);
$listener = $this->getListener($this->factory, $this->securityContext, $em);
$listener->onResponse($this->getEventMock($this->getRequest(), $response));
}
public function testTitle()
{
$this->item->expects($this->once())
->method('setTitle')
->with($this->equalTo($this->serializedTitle));
$response = $this->getResponse();
$repository = $this->getDefaultRepositoryMock($this->item);
$em = $this->getEntityManager($repository);
$listener = $this->getListener($this->factory, $this->securityContext, $em);
$listener->onResponse($this->getEventMock($this->getRequest(), $response));
}
public function testNewItem()
{
$user = new User();
$user->setEmail('[email protected]');
$this->factory->expects($this->once())
->method('createItem')
->will($this->returnValue($this->item));
$repository = $this->getDefaultRepositoryMock(null);
$em = $this->getEntityManager($repository);
$listener = $this->getListener($this->factory, $this->securityContext, $em);
$response = $this->getResponse();
$listener->onResponse($this->getEventMock($this->getRequest(), $response));
}
public function testNotMasterRequest()
{
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent')
->disableOriginalConstructor()
->getMock();
$event->expects($this->never())
->method('getRequest');
$event->expects($this->never())
->method('getResponse');
$event->expects($this->once())
->method('getRequestType')
->will($this->returnValue(HttpKernelInterface::SUB_REQUEST));
$em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$em->expects($this->never())
->method('getRepository');
$titleService = $this->getMock('Oro\Bundle\NavigationBundle\Provider\TitleServiceInterface');
$listener = new ResponseHistoryListener($this->factory, $this->securityContext, $em, $titleService);
$listener->onResponse($event);
}
/**
* Get the mock of the GetResponseEvent and FilterResponseEvent.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param null|\Symfony\Component\HttpFoundation\Response $response
* @param string $type
*
* @return mixed
*/
private function getEventMock($request, $response, $type = 'Symfony\Component\HttpKernel\Event\FilterResponseEvent')
{
$event = $this->getMockBuilder($type)
->disableOriginalConstructor()
->getMock();
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
$event->expects($this->any())
->method('getRequestType')
->will($this->returnValue(HttpKernelInterface::MASTER_REQUEST));
$event->expects($this->any())
->method('getResponse')
->will($this->returnValue($response));
return $event;
}
/**
* Creates request mock object
*
* @return Request
*/
private function getRequest()
{
$this->request = $this->getMock('Symfony\Component\HttpFoundation\Request');
$this->request->expects($this->once())
->method('getRequestFormat')
->will($this->returnValue('html'));
$this->request->expects($this->once())
->method('getMethod')
->will($this->returnValue('GET'));
$this->request->expects($this->once())
->method('get')
->with('_route')
->will($this->returnValue('test_route'));
return $this->request;
}
/**
* Creates response object mock
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getResponse()
{
$response = $this->getMock('Symfony\Component\HttpFoundation\Response');
$response->expects($this->once())
->method('getStatusCode')
->will($this->returnValue(200));
return $response;
}
public function getTitleService()
{
$this->titleService = $this->getMock('Oro\Bundle\NavigationBundle\Provider\TitleServiceInterface');
$this->titleService->expects($this->once())
->method('getSerialized')
->will($this->returnValue($this->serializedTitle));
return $this->titleService;
}
/**
* @param \Oro\Bundle\NavigationBundle\Entity\Builder\ItemFactory $factory
* @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext
* @param \Doctrine\ORM\EntityManager $entityManager
* @return ResponseHistoryListener
*/
private function getListener($factory, $securityContext, $entityManager)
{
return new ResponseHistoryListener($factory, $securityContext, $entityManager, $this->getTitleService());
}
/**
* Returns EntityManager
*
* @param \Oro\Bundle\NavigationBundle\Entity\Repository\HistoryItemRepository $repositoryMock
* @return \Doctrine\ORM\EntityManager $entityManager
*/
private function getEntityManager($repositoryMock)
{
$this->em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$this->em->expects($this->once())
->method('getRepository')
->with($this->equalTo('Oro\Bundle\NavigationBundle\Entity\NavigationHistoryItem'))
->will($this->returnValue($repositoryMock));
return $this->em;
}
/**
* Prepare repository mock
*
* @param mixed $returnValue
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getDefaultRepositoryMock($returnValue)
{
$repository = $this->getMockBuilder('Oro\Bundle\NavigationBundle\Entity\Repository\HistoryItemRepository')
->disableOriginalConstructor()
->getMock();
$repository->expects($this->once())
->method('findOneBy')
->will($this->returnValue($returnValue));
return $repository;
}
}
| mit |
jonahpelfrey/Badgerloop_Competition_Dashboard | log/client/js/angular/docs/examples/example-ngAnimateChildren/index-production.html | 948 | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-ngAnimateChildren-production</title>
<link href="animations.css" rel="stylesheet" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-animate.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="ngAnimateChildren">
<div ng-controller="MainController as main">
<label>Show container? <input type="checkbox" ng-model="main.enterElement" /></label>
<label>Animate children? <input type="checkbox" ng-model="main.animateChildren" /></label>
<hr>
<div ng-animate-children="{{main.animateChildren}}">
<div ng-if="main.enterElement" class="container">
List of items:
<div ng-repeat="item in [0, 1, 2, 3]" class="item">Item {{item}}</div>
</div>
</div>
</div>
</body>
</html> | mit |
pierredup/CSBill | src/CoreBundle/Form/Type/ImageUploadType.php | 1863 | <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) Pierre du Plessis <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ImageUploadType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer(new class() implements DataTransformerInterface {
private $file;
public function transform($value)
{
if (null !== $value) {
$this->file = $value;
}
return new File('', false);
}
public function reverseTransform($value)
{
if (null === $value && null !== $this->file) {
return $this->file;
}
if (!$value instanceof UploadedFile) {
return;
}
if (!$value->isValid()) {
throw new TransformationFailedException();
}
return $value->guessExtension().'|'.base64_encode(file_get_contents($value->getPathname()));
}
});
}
public function getParent(): string
{
return FileType::class;
}
public function getBlockPrefix()
{
return 'image_upload';
}
}
| mit |
zouzou73/medicme | src/medicme/ClientApp/app/components/controls/todo-demo.component.css | 715 |
.navbar .nav > li.toolbaritem > a {
font-weight: bold;
}
input.form-control {
border-left-width: 5px;
}
.control-box {
margin-bottom: 5px;
}
.search-box {
margin: 0;
}
.action-box {
margin: 0 15px 0 0;
min-height: 0;
}
.action-box .toolbaritem a {
padding-top: 5px;
padding-bottom: 5px;
min-width: 100px;
}
.completed {
text-decoration: line-through;
}
.checkbox {
margin: 0;
}
.inline-editor {
width: 100%;
}
.description-form-group {
margin-bottom: 5px;
}
.actionBtn-form-group {
margin: 0;
}
.edit-last-separator-hr {
margin: 10px 0;
}
@media (max-width: 768px) {
.action-box {
margin: 0 14px;
}
}
| mit |
lucasa/Politicos | src/main/java/org/politicos/config/JacksonConfiguration.java | 1060 | package org.politicos.config;
import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
@Configuration
public class JacksonConfiguration {
public static final DateTimeFormatter ISO_FIXED_FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
jackson2ObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
}
};
}
}
| mit |
qiudesong/coreclr | src/vm/interpreter.cpp | 418371 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
#include "common.h"
#ifdef FEATURE_INTERPRETER
#include "interpreter.h"
#include "interpreter.hpp"
#include "cgencpu.h"
#include "stublink.h"
#include "openum.h"
#include "fcall.h"
#include "frames.h"
#include "gcheaputilities.h"
#include <float.h>
#include "jitinterface.h"
#include "safemath.h"
#include "exceptmacros.h"
#include "runtimeexceptionkind.h"
#include "runtimehandles.h"
#include "vars.hpp"
#include "cycletimer.h"
inline CORINFO_CALLINFO_FLAGS combine(CORINFO_CALLINFO_FLAGS flag1, CORINFO_CALLINFO_FLAGS flag2)
{
return (CORINFO_CALLINFO_FLAGS) (flag1 | flag2);
}
static CorInfoType asCorInfoType(CORINFO_CLASS_HANDLE clsHnd)
{
TypeHandle typeHnd(clsHnd);
return CEEInfo::asCorInfoType(typeHnd.GetInternalCorElementType(), typeHnd, NULL);
}
InterpreterMethodInfo::InterpreterMethodInfo(CEEInfo* comp, CORINFO_METHOD_INFO* methInfo)
: m_method(methInfo->ftn),
m_module(methInfo->scope),
m_jittedCode(0),
m_ILCode(methInfo->ILCode),
m_ILCodeEnd(methInfo->ILCode + methInfo->ILCodeSize),
m_maxStack(methInfo->maxStack),
#if INTERP_PROFILE
m_totIlInstructionsExeced(0),
m_maxIlInstructionsExeced(0),
#endif
m_ehClauseCount(methInfo->EHcount),
m_varArgHandleArgNum(NO_VA_ARGNUM),
m_numArgs(methInfo->args.numArgs),
m_numLocals(methInfo->locals.numArgs),
m_flags(0),
m_argDescs(NULL),
m_returnType(methInfo->args.retType),
m_invocations(0),
m_methodCache(NULL)
{
// Overflow sanity check. (Can ILCodeSize ever be zero?)
assert(m_ILCode <= m_ILCodeEnd);
// Does the calling convention indicate an implicit "this" (first arg) or generic type context arg (last arg)?
SetFlag<Flag_hasThisArg>((methInfo->args.callConv & CORINFO_CALLCONV_HASTHIS) != 0);
if (GetFlag<Flag_hasThisArg>())
{
GCX_PREEMP();
CORINFO_CLASS_HANDLE methClass = comp->getMethodClass(methInfo->ftn);
DWORD attribs = comp->getClassAttribs(methClass);
SetFlag<Flag_thisArgIsObjPtr>((attribs & CORINFO_FLG_VALUECLASS) == 0);
}
#if INTERP_PROFILE || defined(_DEBUG)
{
const char* clsName;
#if defined(_DEBUG)
m_methName = ::eeGetMethodFullName(comp, methInfo->ftn, &clsName);
#else
m_methName = comp->getMethodName(methInfo->ftn, &clsName);
#endif
char* myClsName = new char[strlen(clsName) + 1];
strcpy(myClsName, clsName);
m_clsName = myClsName;
}
#endif // INTERP_PROFILE
// Do we have a ret buff? If its a struct or refany, then *maybe*, depending on architecture...
bool hasRetBuff = (methInfo->args.retType == CORINFO_TYPE_VALUECLASS || methInfo->args.retType == CORINFO_TYPE_REFANY);
#if defined(FEATURE_HFA)
// ... unless its an HFA type (and not varargs)...
if (hasRetBuff && CorInfoTypeIsFloatingPoint(comp->getHFAType(methInfo->args.retTypeClass)) && methInfo->args.getCallConv() != CORINFO_CALLCONV_VARARG)
{
hasRetBuff = false;
}
#endif
#if defined(_ARM_) || defined(_AMD64_)|| defined(_ARM64_)
// ...or it fits into one register.
if (hasRetBuff && getClassSize(methInfo->args.retTypeClass) <= sizeof(void*))
{
hasRetBuff = false;
}
#endif
SetFlag<Flag_hasRetBuffArg>(hasRetBuff);
MetaSig sig(reinterpret_cast<MethodDesc*>(methInfo->ftn));
SetFlag<Flag_hasGenericsContextArg>((methInfo->args.callConv & CORINFO_CALLCONV_PARAMTYPE) != 0);
SetFlag<Flag_isVarArg>((methInfo->args.callConv & CORINFO_CALLCONV_VARARG) != 0);
SetFlag<Flag_typeHasGenericArgs>(methInfo->args.sigInst.classInstCount > 0);
SetFlag<Flag_methHasGenericArgs>(methInfo->args.sigInst.methInstCount > 0);
_ASSERTE_MSG(!GetFlag<Flag_hasGenericsContextArg>()
|| ((GetFlag<Flag_typeHasGenericArgs>() & !(GetFlag<Flag_hasThisArg>() && GetFlag<Flag_thisArgIsObjPtr>())) || GetFlag<Flag_methHasGenericArgs>()),
"If the method takes a generic parameter, is a static method of generic class (or meth of a value class), and/or itself takes generic parameters");
if (GetFlag<Flag_hasThisArg>())
{
m_numArgs++;
}
if (GetFlag<Flag_hasRetBuffArg>())
{
m_numArgs++;
}
if (GetFlag<Flag_isVarArg>())
{
m_numArgs++;
}
if (GetFlag<Flag_hasGenericsContextArg>())
{
m_numArgs++;
}
if (m_numArgs == 0)
{
m_argDescs = NULL;
}
else
{
m_argDescs = new ArgDesc[m_numArgs];
}
// Now we'll do the locals.
m_localDescs = new LocalDesc[m_numLocals];
// Allocate space for the pinning reference bits (lazily).
m_localIsPinningRefBits = NULL;
// Now look at each local.
CORINFO_ARG_LIST_HANDLE localsPtr = methInfo->locals.args;
CORINFO_CLASS_HANDLE vcTypeRet;
unsigned curLargeStructOffset = 0;
for (unsigned k = 0; k < methInfo->locals.numArgs; k++)
{
// TODO: if this optimization succeeds, the switch below on localType
// can become much simpler.
m_localDescs[k].m_offset = 0;
#ifdef _DEBUG
vcTypeRet = NULL;
#endif
CorInfoTypeWithMod localTypWithMod = comp->getArgType(&methInfo->locals, localsPtr, &vcTypeRet);
// If the local vars is a pinning reference, set the bit to indicate this.
if ((localTypWithMod & CORINFO_TYPE_MOD_PINNED) != 0)
{
SetPinningBit(k);
}
CorInfoType localType = strip(localTypWithMod);
switch (localType)
{
case CORINFO_TYPE_VALUECLASS:
case CORINFO_TYPE_REFANY: // Just a special case: vcTypeRet is handle for TypedReference in this case...
{
InterpreterType tp = InterpreterType(comp, vcTypeRet);
unsigned size = static_cast<unsigned>(tp.Size(comp));
size = max(size, sizeof(void*));
m_localDescs[k].m_type = tp;
if (tp.IsLargeStruct(comp))
{
m_localDescs[k].m_offset = curLargeStructOffset;
curLargeStructOffset += size;
}
}
break;
case CORINFO_TYPE_VAR:
NYI_INTERP("argument of generic parameter type"); // Should not happen;
break;
default:
m_localDescs[k].m_type = InterpreterType(localType);
break;
}
m_localDescs[k].m_typeStackNormal = m_localDescs[k].m_type.StackNormalize();
localsPtr = comp->getArgNext(localsPtr);
}
m_largeStructLocalSize = curLargeStructOffset;
}
void InterpreterMethodInfo::InitArgInfo(CEEInfo* comp, CORINFO_METHOD_INFO* methInfo, short* argOffsets_)
{
unsigned numSigArgsPlusThis = methInfo->args.numArgs;
if (GetFlag<Flag_hasThisArg>())
{
numSigArgsPlusThis++;
}
// The m_argDescs array is constructed in the following "canonical" order:
// 1. 'this' pointer
// 2. signature arguments
// 3. return buffer
// 4. type parameter -or- vararg cookie
//
// argOffsets_ is passed in this order, and serves to establish the offsets to arguments
// when the interpreter is invoked using the native calling convention (i.e., not directly).
//
// When the interpreter is invoked directly, the arguments will appear in the same order
// and form as arguments passed to MethodDesc::CallDescr(). This ordering is as follows:
// 1. 'this' pointer
// 2. return buffer
// 3. signature arguments
//
// MethodDesc::CallDescr() does not support generic parameters or varargs functions.
_ASSERTE_MSG((methInfo->args.callConv & (CORINFO_CALLCONV_EXPLICITTHIS)) == 0,
"Don't yet handle EXPLICITTHIS calling convention modifier.");
switch (methInfo->args.callConv & CORINFO_CALLCONV_MASK)
{
case CORINFO_CALLCONV_DEFAULT:
case CORINFO_CALLCONV_VARARG:
{
unsigned k = 0;
ARG_SLOT* directOffset = NULL;
short directRetBuffOffset = 0;
short directVarArgOffset = 0;
short directTypeParamOffset = 0;
// If there's a "this" argument, handle it.
if (GetFlag<Flag_hasThisArg>())
{
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_UNDEF);
#ifdef FEATURE_STUBS_AS_IL
MethodDesc *pMD = reinterpret_cast<MethodDesc*>(methInfo->ftn);
// The signature of the ILStubs may be misleading.
// If a StubTarget is ever set, we'll find the correct type by inspecting the
// target, rather than the stub.
if (pMD->IsILStub())
{
if (pMD->AsDynamicMethodDesc()->IsUnboxingILStub())
{
// This is an unboxing stub where the thisptr is passed as a boxed VT.
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_CLASS);
}
else
{
MethodDesc *pTargetMD = pMD->AsDynamicMethodDesc()->GetILStubResolver()->GetStubTargetMethodDesc();
if (pTargetMD != NULL)
{
if (pTargetMD->GetMethodTable()->IsValueType())
{
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_BYREF);
}
else
{
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_CLASS);
}
}
}
}
#endif // FEATURE_STUBS_AS_IL
if (m_argDescs[k].m_type == InterpreterType(CORINFO_TYPE_UNDEF))
{
CORINFO_CLASS_HANDLE cls = comp->getMethodClass(methInfo->ftn);
DWORD attribs = comp->getClassAttribs(cls);
if (attribs & CORINFO_FLG_VALUECLASS)
{
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_BYREF);
}
else
{
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_CLASS);
}
}
m_argDescs[k].m_typeStackNormal = m_argDescs[k].m_type;
m_argDescs[k].m_nativeOffset = argOffsets_[k];
m_argDescs[k].m_directOffset = reinterpret_cast<short>(ArgSlotEndianessFixup(directOffset, sizeof(void*)));
directOffset++;
k++;
}
// If there is a return buffer, it will appear next in the arguments list for a direct call.
// Reserve its offset now, for use after the explicit arguments.
#if defined(_ARM_)
// On ARM, for direct calls we always treat HFA return types as having ret buffs.
// So figure out if we have an HFA return type.
bool hasHFARetType =
methInfo->args.retType == CORINFO_TYPE_VALUECLASS
&& CorInfoTypeIsFloatingPoint(comp->getHFAType(methInfo->args.retTypeClass))
&& methInfo->args.getCallConv() != CORINFO_CALLCONV_VARARG;
#endif // defined(_ARM_)
if (GetFlag<Flag_hasRetBuffArg>()
#if defined(_ARM_)
// On ARM, for direct calls we always treat HFA return types as having ret buffs.
|| hasHFARetType
#endif // defined(_ARM_)
)
{
directRetBuffOffset = reinterpret_cast<short>(ArgSlotEndianessFixup(directOffset, sizeof(void*)));
directOffset++;
}
#if defined(_AMD64_)
if (GetFlag<Flag_isVarArg>())
{
directVarArgOffset = reinterpret_cast<short>(ArgSlotEndianessFixup(directOffset, sizeof(void*)));
directOffset++;
}
if (GetFlag<Flag_hasGenericsContextArg>())
{
directTypeParamOffset = reinterpret_cast<short>(ArgSlotEndianessFixup(directOffset, sizeof(void*)));
directOffset++;
}
#endif
// Now record the argument types for the rest of the arguments.
InterpreterType it;
CORINFO_CLASS_HANDLE vcTypeRet;
CORINFO_ARG_LIST_HANDLE argPtr = methInfo->args.args;
for (; k < numSigArgsPlusThis; k++)
{
CorInfoTypeWithMod argTypWithMod = comp->getArgType(&methInfo->args, argPtr, &vcTypeRet);
CorInfoType argType = strip(argTypWithMod);
switch (argType)
{
case CORINFO_TYPE_VALUECLASS:
case CORINFO_TYPE_REFANY: // Just a special case: vcTypeRet is handle for TypedReference in this case...
it = InterpreterType(comp, vcTypeRet);
break;
default:
// Everything else is just encoded as a shifted CorInfoType.
it = InterpreterType(argType);
break;
}
m_argDescs[k].m_type = it;
m_argDescs[k].m_typeStackNormal = it.StackNormalize();
m_argDescs[k].m_nativeOffset = argOffsets_[k];
// When invoking the interpreter directly, large value types are always passed by reference.
if (it.IsLargeStruct(comp))
{
m_argDescs[k].m_directOffset = reinterpret_cast<short>(ArgSlotEndianessFixup(directOffset, sizeof(void*)));
}
else
{
m_argDescs[k].m_directOffset = reinterpret_cast<short>(ArgSlotEndianessFixup(directOffset, it.Size(comp)));
}
argPtr = comp->getArgNext(argPtr);
directOffset++;
}
if (GetFlag<Flag_hasRetBuffArg>())
{
// The generic type context is an unmanaged pointer (native int).
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_BYREF);
m_argDescs[k].m_typeStackNormal = m_argDescs[k].m_type;
m_argDescs[k].m_nativeOffset = argOffsets_[k];
m_argDescs[k].m_directOffset = directRetBuffOffset;
k++;
}
if (GetFlag<Flag_hasGenericsContextArg>())
{
// The vararg cookie is an unmanaged pointer (native int).
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_NATIVEINT);
m_argDescs[k].m_typeStackNormal = m_argDescs[k].m_type;
m_argDescs[k].m_nativeOffset = argOffsets_[k];
m_argDescs[k].m_directOffset = directTypeParamOffset;
directOffset++;
k++;
}
if (GetFlag<Flag_isVarArg>())
{
// The generic type context is an unmanaged pointer (native int).
m_argDescs[k].m_type = InterpreterType(CORINFO_TYPE_NATIVEINT);
m_argDescs[k].m_typeStackNormal = m_argDescs[k].m_type;
m_argDescs[k].m_nativeOffset = argOffsets_[k];
m_argDescs[k].m_directOffset = directVarArgOffset;
k++;
}
}
break;
case CORINFO_CALLCONV_C:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_C");
break;
case CORINFO_CALLCONV_STDCALL:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_STDCALL");
break;
case CORINFO_CALLCONV_THISCALL:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_THISCALL");
break;
case CORINFO_CALLCONV_FASTCALL:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_FASTCALL");
break;
case CORINFO_CALLCONV_FIELD:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_FIELD");
break;
case CORINFO_CALLCONV_LOCAL_SIG:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_LOCAL_SIG");
break;
case CORINFO_CALLCONV_PROPERTY:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_PROPERTY");
break;
case CORINFO_CALLCONV_NATIVEVARARG:
NYI_INTERP("InterpreterMethodInfo::InitArgInfo -- CORINFO_CALLCONV_NATIVEVARARG");
break;
default:
_ASSERTE_ALL_BUILDS(__FILE__, false); // shouldn't get here
}
}
InterpreterMethodInfo::~InterpreterMethodInfo()
{
if (m_methodCache != NULL)
{
delete reinterpret_cast<ILOffsetToItemCache*>(m_methodCache);
}
}
void InterpreterMethodInfo::AllocPinningBitsIfNeeded()
{
if (m_localIsPinningRefBits != NULL)
return;
unsigned numChars = (m_numLocals + 7) / 8;
m_localIsPinningRefBits = new char[numChars];
for (unsigned i = 0; i < numChars; i++)
{
m_localIsPinningRefBits[i] = char(0);
}
}
void InterpreterMethodInfo::SetPinningBit(unsigned locNum)
{
_ASSERTE_MSG(locNum < m_numLocals, "Precondition");
AllocPinningBitsIfNeeded();
unsigned ind = locNum / 8;
unsigned bitNum = locNum - (ind * 8);
m_localIsPinningRefBits[ind] |= (1 << bitNum);
}
bool InterpreterMethodInfo::GetPinningBit(unsigned locNum)
{
_ASSERTE_MSG(locNum < m_numLocals, "Precondition");
if (m_localIsPinningRefBits == NULL)
return false;
unsigned ind = locNum / 8;
unsigned bitNum = locNum - (ind * 8);
return (m_localIsPinningRefBits[ind] & (1 << bitNum)) != 0;
}
void Interpreter::ArgState::AddArg(unsigned canonIndex, short numSlots, bool noReg, bool twoSlotAlign)
{
#if defined(_AMD64_)
assert(!noReg);
assert(!twoSlotAlign);
AddArgAmd64(canonIndex, numSlots, /*isFloatingType*/false);
#else // !_AMD64_
#if defined(_X86_) || defined(_ARM64_)
assert(!twoSlotAlign); // Shouldn't use this flag on x86 (it wouldn't work right in the stack, at least).
#endif
// If the argument requires two-slot alignment, make sure we have it. This is the
// ARM model: both in regs and on the stack.
if (twoSlotAlign)
{
if (!noReg && numRegArgs < NumberOfIntegerRegArgs())
{
if ((numRegArgs % 2) != 0)
{
numRegArgs++;
}
}
else
{
if ((callerArgStackSlots % 2) != 0)
{
callerArgStackSlots++;
}
}
}
#if defined(_ARM64_)
// On ARM64 we're not going to place an argument 'partially' on the stack
// if all slots fits into registers, they go into registers, otherwise they go into stack.
if (!noReg && numRegArgs+numSlots <= NumberOfIntegerRegArgs())
#else
if (!noReg && numRegArgs < NumberOfIntegerRegArgs())
#endif
{
argIsReg[canonIndex] = ARS_IntReg;
argOffsets[canonIndex] = numRegArgs * sizeof(void*);
numRegArgs += numSlots;
// If we overflowed the regs, we consume some stack arg space.
if (numRegArgs > NumberOfIntegerRegArgs())
{
callerArgStackSlots += (numRegArgs - NumberOfIntegerRegArgs());
}
}
else
{
#if defined(_X86_)
// On X86, stack args are pushed in order. We will add the total size of the arguments to this offset,
// so we set this to a negative number relative to the SP before the first arg push.
callerArgStackSlots += numSlots;
ClrSafeInt<short> offset(-callerArgStackSlots);
#elif defined(_ARM_) || defined(_ARM64_)
// On ARM, args are pushed in *reverse* order. So we will create an offset relative to the address
// of the first stack arg; later, we will add the size of the non-stack arguments.
ClrSafeInt<short> offset(callerArgStackSlots);
#endif
offset *= static_cast<short>(sizeof(void*));
assert(!offset.IsOverflow());
argOffsets[canonIndex] = offset.Value();
#if defined(_ARM_) || defined(_ARM64_)
callerArgStackSlots += numSlots;
#endif
}
#endif // !_AMD64_
}
#if defined(_AMD64_)
// AMD64 calling convention allows any type that can be contained in 64 bits to be passed in registers,
// if not contained or they are of a size not a power of 2, then they are passed by reference on the stack.
// RCX, RDX, R8, R9 are the int arg registers. XMM0-3 overlap with the integer registers and are used
// for floating point arguments.
void Interpreter::ArgState::AddArgAmd64(unsigned canonIndex, unsigned short numSlots, bool isFloatingType)
{
// If floating type and there are slots use a float reg slot.
if (isFloatingType && (numFPRegArgSlots < MaxNumFPRegArgSlots))
{
assert(numSlots == 1);
argIsReg[canonIndex] = ARS_FloatReg;
argOffsets[canonIndex] = numFPRegArgSlots * sizeof(void*);
fpArgsUsed |= (0x1 << (numFPRegArgSlots + 1));
numFPRegArgSlots += 1;
numRegArgs += 1; // Increment int reg count due to shadowing.
return;
}
// If we have an integer/aligned-struct arg or a reference of a struct that got copied on
// to the stack, it would go into a register or a stack slot.
if (numRegArgs != NumberOfIntegerRegArgs())
{
argIsReg[canonIndex] = ARS_IntReg;
argOffsets[canonIndex] = numRegArgs * sizeof(void*);
numRegArgs += 1;
numFPRegArgSlots += 1; // Increment FP reg count due to shadowing.
}
else
{
argIsReg[canonIndex] = ARS_NotReg;
ClrSafeInt<short> offset(callerArgStackSlots * sizeof(void*));
assert(!offset.IsOverflow());
argOffsets[canonIndex] = offset.Value();
callerArgStackSlots += 1;
}
}
#endif
void Interpreter::ArgState::AddFPArg(unsigned canonIndex, unsigned short numSlots, bool twoSlotAlign)
{
#if defined(_AMD64_)
assert(!twoSlotAlign);
assert(numSlots == 1);
AddArgAmd64(canonIndex, numSlots, /*isFloatingType*/ true);
#elif defined(_X86_)
assert(false); // Don't call this on x86; we pass all FP on the stack.
#elif defined(_ARM_)
// We require "numSlots" alignment.
assert(numFPRegArgSlots + numSlots <= MaxNumFPRegArgSlots);
argIsReg[canonIndex] = ARS_FloatReg;
if (twoSlotAlign)
{
// If we require two slot alignment, the number of slots must be a multiple of two.
assert((numSlots % 2) == 0);
// Skip a slot if necessary.
if ((numFPRegArgSlots % 2) != 0)
{
numFPRegArgSlots++;
}
// We always use new slots for two slot aligned args precision...
argOffsets[canonIndex] = numFPRegArgSlots * sizeof(void*);
for (unsigned short i = 0; i < numSlots/2; i++)
{
fpArgsUsed |= (0x3 << (numFPRegArgSlots + i));
}
numFPRegArgSlots += numSlots;
}
else
{
if (numSlots == 1)
{
// A single-precision (float) argument. We must do "back-filling" where possible, searching
// for previous unused registers.
unsigned slot = 0;
while (slot < 32 && (fpArgsUsed & (1 << slot))) slot++;
assert(slot < 32); // Search succeeded.
assert(slot <= numFPRegArgSlots); // No bits at or above numFPRegArgSlots are set (regs used).
argOffsets[canonIndex] = slot * sizeof(void*);
fpArgsUsed |= (0x1 << slot);
if (slot == numFPRegArgSlots)
numFPRegArgSlots += numSlots;
}
else
{
// We can always allocate at after the last used slot.
argOffsets[numFPRegArgSlots] = numFPRegArgSlots * sizeof(void*);
for (unsigned i = 0; i < numSlots; i++)
{
fpArgsUsed |= (0x1 << (numFPRegArgSlots + i));
}
numFPRegArgSlots += numSlots;
}
}
#elif defined(_ARM64_)
assert(numFPRegArgSlots + numSlots <= MaxNumFPRegArgSlots);
assert(!twoSlotAlign);
argIsReg[canonIndex] = ARS_FloatReg;
argOffsets[canonIndex] = numFPRegArgSlots * sizeof(void*);
for (unsigned i = 0; i < numSlots; i++)
{
fpArgsUsed |= (0x1 << (numFPRegArgSlots + i));
}
numFPRegArgSlots += numSlots;
#else
#error "Unsupported architecture"
#endif
}
// static
CorJitResult Interpreter::GenerateInterpreterStub(CEEInfo* comp,
CORINFO_METHOD_INFO* info,
/*OUT*/ BYTE **nativeEntry,
/*OUT*/ ULONG *nativeSizeOfCode,
InterpreterMethodInfo** ppInterpMethodInfo,
bool jmpCall)
{
//
// First, ensure that the compiler-specific statics are initialized.
//
InitializeCompilerStatics(comp);
//
// Next, use switches and IL scanning to determine whether to interpret this method.
//
#if INTERP_TRACING
#define TRACE_SKIPPED(cls, meth, reason) \
if (s_DumpInterpreterStubsFlag.val(CLRConfig::INTERNAL_DumpInterpreterStubs)) { \
fprintf(GetLogFile(), "Skipping %s:%s (%s).\n", cls, meth, reason); \
}
#else
#define TRACE_SKIPPED(cls, meth, reason)
#endif
// If jmpCall, we only need to do computations involving method info.
if (!jmpCall)
{
const char* clsName;
const char* methName = comp->getMethodName(info->ftn, &clsName);
if ( !s_InterpretMeths.contains(methName, clsName, info->args.pSig)
|| s_InterpretMethsExclude.contains(methName, clsName, info->args.pSig))
{
TRACE_SKIPPED(clsName, methName, "not in set of methods to interpret");
return CORJIT_SKIPPED;
}
unsigned methHash = comp->getMethodHash(info->ftn);
if ( methHash < s_InterpretMethHashMin.val(CLRConfig::INTERNAL_InterpreterMethHashMin)
|| methHash > s_InterpretMethHashMax.val(CLRConfig::INTERNAL_InterpreterMethHashMax))
{
TRACE_SKIPPED(clsName, methName, "hash not within range to interpret");
return CORJIT_SKIPPED;
}
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(info->ftn);
#if !INTERP_ILSTUBS
if (pMD->IsILStub())
{
TRACE_SKIPPED(clsName, methName, "interop stubs not supported");
return CORJIT_SKIPPED;
}
else
#endif // !INTERP_ILSTUBS
if (!s_InterpreterDoLoopMethods && MethodMayHaveLoop(info->ILCode, info->ILCodeSize))
{
TRACE_SKIPPED(clsName, methName, "has loop, not interpreting loop methods.");
return CORJIT_SKIPPED;
}
s_interpreterStubNum++;
#if INTERP_TRACING
if (s_interpreterStubNum < s_InterpreterStubMin.val(CLRConfig::INTERNAL_InterpreterStubMin)
|| s_interpreterStubNum > s_InterpreterStubMax.val(CLRConfig::INTERNAL_InterpreterStubMax))
{
TRACE_SKIPPED(clsName, methName, "stub num not in range, not interpreting.");
return CORJIT_SKIPPED;
}
if (s_DumpInterpreterStubsFlag.val(CLRConfig::INTERNAL_DumpInterpreterStubs))
{
unsigned hash = comp->getMethodHash(info->ftn);
fprintf(GetLogFile(), "Generating interpretation stub (# %d = 0x%x, hash = 0x%x) for %s:%s.\n",
s_interpreterStubNum, s_interpreterStubNum, hash, clsName, methName);
fflush(GetLogFile());
}
#endif
}
//
// Finally, generate an interpreter entry-point stub.
//
// @TODO: this structure clearly needs some sort of lifetime management. It is the moral equivalent
// of compiled code, and should be associated with an app domain. In addition, when I get to it, we should
// delete it when/if we actually compile the method. (Actually, that's complicated, since there may be
// VSD stubs still bound to the interpreter stub. The check there will get to the jitted code, but we want
// to eventually clean those up at some safe point...)
InterpreterMethodInfo* interpMethInfo = new InterpreterMethodInfo(comp, info);
if (ppInterpMethodInfo != nullptr)
{
*ppInterpMethodInfo = interpMethInfo;
}
interpMethInfo->m_stubNum = s_interpreterStubNum;
MethodDesc* methodDesc = reinterpret_cast<MethodDesc*>(info->ftn);
if (!jmpCall)
{
interpMethInfo = RecordInterpreterMethodInfoForMethodHandle(info->ftn, interpMethInfo);
}
#if FEATURE_INTERPRETER_DEADSIMPLE_OPT
unsigned offsetOfLd;
if (IsDeadSimpleGetter(comp, methodDesc, &offsetOfLd))
{
interpMethInfo->SetFlag<InterpreterMethodInfo::Flag_methIsDeadSimpleGetter>(true);
if (offsetOfLd == ILOffsetOfLdFldInDeadSimpleInstanceGetterDbg)
{
interpMethInfo->SetFlag<InterpreterMethodInfo::Flag_methIsDeadSimpleGetterIsDbgForm>(true);
}
else
{
assert(offsetOfLd == ILOffsetOfLdFldInDeadSimpleInstanceGetterOpt);
}
}
#endif // FEATURE_INTERPRETER_DEADSIMPLE_OPT
// Used to initialize the arg offset information.
Stub* stub = NULL;
// We assume that the stack contains (with addresses growing upwards, assuming a downwards-growing stack):
//
// [Non-reg arg N-1]
// ...
// [Non-reg arg <# of reg args>]
// [return PC]
//
// Then push the register args to get:
//
// [Non-reg arg N-1]
// ...
// [Non-reg arg <# of reg args>]
// [return PC]
// [reg arg <# of reg args>-1]
// ...
// [reg arg 0]
//
// Pass the address of this argument array, and the MethodDesc pointer for the method, as arguments to
// Interpret.
//
// So the structure of the code will look like this (in the non-ILstub case):
//
#if defined(_X86_) || defined(_AMD64_)
// First do "short-circuiting" if the method has JITted code, and we couldn't find/update the call site:
// eax = &interpMethInfo
// eax = [eax + offsetof(m_jittedCode)]
// if (eax == zero) goto doInterpret:
// /*else*/ jmp [eax]
// doInterpret:
// push ebp
// mov ebp, esp
// [if there are register arguments in ecx or edx, push them]
// ecx := addr of InterpretMethodInfo for the method to be intepreted.
// edx = esp /*pointer to argument structure*/
// call to Interpreter::InterpretMethod
// [if we pushed register arguments, increment esp by the right amount.]
// pop ebp
// ret <n> ; where <n> is the number of argument stack slots in the call to the stub.
#elif defined (_ARM_)
// TODO.
#endif
// The IL stub case is hard. The portion of the interpreter stub that short-circuits
// to JITted code requires an extra "scratch" volatile register, not an argument register;
// in the IL stub case, it too is using such a register, as an extra argument, to hold the stub context.
// On x86 and ARM, there is only one such extra volatile register, and we've got a conundrum.
// The cases where this short-circuiting is important is when the address of an interpreter stub
// becomes "embedded" in other code. The examples I know of are VSD stubs and delegates.
// The first of these is not a problem for IL stubs -- methods invoked via p/Invoke (the ones that
// [I think!] use IL stubs) are static, and cannot be invoked via VSD stubs. Delegates, on the other
// remain a problem [I believe].
// For the short term, we'll ignore this issue, and never do short-circuiting for IL stubs.
// So interpreter stubs embedded in delegates will continue to interpret the IL stub, even after
// the stub has been JITted.
// The long-term intention is that when we JIT a method with an interpreter stub, we keep a mapping
// from interpreter stub address to corresponding native code address. If this mapping is non-empty,
// at GC time we would visit the locations in which interpreter stub addresses might be located, like
// VSD stubs and delegate objects, and update them to point to new addresses. This would be a necessary
// part of any scheme to GC interpreter stubs, and InterpreterMethodInfos.
// If we *really* wanted to make short-circuiting work for the IL stub case, we would have to
// (in the x86 case, which should be sufficiently illustrative):
// push eax
// <get the address of JITted code, if any, into eax>
// if there is JITted code in eax, we'd have to
// push 2 non-volatile registers, say esi and edi.
// copy the JITted code address from eax into esi.
// copy the method arguments (without the return address) down the stack, using edi
// as a scratch register.
// restore the original stub context value into eax from the stack
// call (not jmp) to the JITted code address in esi
// pop esi and edi from the stack.
// now the stack has original args, followed by original return address. Do a "ret"
// that returns to the return address, and also pops the original args from the stack.
// If we did this, we'd have to give this portion of the stub proper unwind info.
// Also, we'd have to adjust the rest of the stub to pop eax from the stack.
// TODO: much of the interpreter stub code should be is shareable. In the non-IL stub case,
// at least, we could have a small per-method stub that puts the address of the method-specific
// InterpreterMethodInfo into eax, and then branches to a shared part. Probably we would want to
// always push all integer args on x86, as we do already on ARM. On ARM, we'd need several versions
// of the shared stub, for different numbers of floating point register args, cross different kinds of
// HFA return values. But these could still be shared, and the per-method stub would decide which of
// these to target.
//
// In the IL stub case, which uses eax, it would be problematic to do this sharing.
StubLinkerCPU sl;
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(info->ftn);
if (!jmpCall)
{
sl.Init();
#if defined(_X86_) || defined(_AMD64_)
// First we do "short-circuiting" if the method has JITted code.
#if INTERP_ILSTUBS
if (!pMD->IsILStub()) // As discussed above, we don't do short-circuiting for IL stubs.
#endif
{
// First read the m_jittedCode field.
sl.X86EmitRegLoad(kEAX, UINT_PTR(interpMethInfo));
sl.X86EmitOffsetModRM(0x8b, kEAX, kEAX, offsetof(InterpreterMethodInfo, m_jittedCode));
// If it is still zero, then go on to do the interpretation.
sl.X86EmitCmpRegImm32(kEAX, 0);
CodeLabel* doInterpret = sl.NewCodeLabel();
sl.X86EmitCondJump(doInterpret, X86CondCode::kJE);
// Otherwise...
sl.X86EmitJumpReg(kEAX); // tail call to JITted code.
sl.EmitLabel(doInterpret);
}
#if defined(_X86_)
// Start regular interpretation
sl.X86EmitPushReg(kEBP);
sl.X86EmitMovRegReg(kEBP, static_cast<X86Reg>(kESP_Unsafe));
#endif
#elif defined(_ARM_)
// On ARM we use R12 as a "scratch" register -- callee-trashed, not used
// for arguments.
ThumbReg r11 = ThumbReg(11);
ThumbReg r12 = ThumbReg(12);
#if INTERP_ILSTUBS
if (!pMD->IsILStub()) // As discussed above, we don't do short-circuiting for IL stubs.
#endif
{
// But we also have to use r4, because ThumbEmitCondRegJump below requires a low register.
sl.ThumbEmitMovConstant(r11, 0);
sl.ThumbEmitMovConstant(r12, UINT_PTR(interpMethInfo));
sl.ThumbEmitLoadRegIndirect(r12, r12, offsetof(InterpreterMethodInfo, m_jittedCode));
sl.ThumbEmitCmpReg(r12, r11); // Set condition codes.
// If r12 is zero, then go on to do the interpretation.
CodeLabel* doInterpret = sl.NewCodeLabel();
sl.ThumbEmitCondFlagJump(doInterpret, thumbCondEq.cond);
sl.ThumbEmitJumpRegister(r12); // If non-zero, tail call to JITted code.
sl.EmitLabel(doInterpret);
}
// Start regular interpretation
#elif defined(_ARM64_)
// x8 through x15 are scratch registers on ARM64.
IntReg x8 = IntReg(8);
IntReg x9 = IntReg(9);
#if INTERP_ILSTUBS
if (!pMD->IsILStub()) // As discussed above, we don't do short-circuiting for IL stubs.
#endif
{
sl.EmitMovConstant(x8, UINT64(interpMethInfo));
sl.EmitLoadStoreRegImm(StubLinkerCPU::eLOAD, x9, x8, offsetof(InterpreterMethodInfo, m_jittedCode));
sl.EmitCmpImm(x9, 0);
CodeLabel* doInterpret = sl.NewCodeLabel();
sl.EmitCondFlagJump(doInterpret, CondEq.cond);
sl.EmitJumpRegister(x9);
sl.EmitLabel(doInterpret);
}
// Start regular interpretation
#else
#error unsupported platform
#endif
}
MetaSig sig(methodDesc);
unsigned totalArgs = info->args.numArgs;
unsigned sigArgsPlusThis = totalArgs;
bool hasThis = false;
bool hasRetBuff = false;
bool isVarArg = false;
bool hasGenericsContextArg = false;
// Below, we will increment "totalArgs" for any of the "this" argument,
// a ret buff argument, and/or a generics context argument.
//
// There will be four arrays allocated below, each with this increased "totalArgs" elements:
// argOffsets, argIsReg, argPerm, and, later, m_argDescs.
//
// They will be indexed in the order (0-based, [] indicating optional)
//
// [this] sigArgs [retBuff] [VASigCookie] [genCtxt]
//
// We will call this "canonical order". It is architecture-independent, and
// does not necessarily correspond to the architecture-dependent physical order
// in which the registers are actually passed. (That's actually the purpose of
// "argPerm": to record the correspondence between canonical order and physical
// order.) We could have chosen any order for the first three of these, but it's
// simplest to let m_argDescs have all the passed IL arguments passed contiguously
// at the beginning, allowing it to be indexed by IL argument number.
int genericsContextArgIndex = 0;
int retBuffArgIndex = 0;
int vaSigCookieIndex = 0;
if (sig.HasThis())
{
assert(info->args.callConv & CORINFO_CALLCONV_HASTHIS);
hasThis = true;
totalArgs++; sigArgsPlusThis++;
}
if (methodDesc->HasRetBuffArg())
{
hasRetBuff = true;
retBuffArgIndex = totalArgs;
totalArgs++;
}
if (sig.GetCallingConventionInfo() & CORINFO_CALLCONV_VARARG)
{
isVarArg = true;
vaSigCookieIndex = totalArgs;
totalArgs++;
}
if (sig.GetCallingConventionInfo() & CORINFO_CALLCONV_PARAMTYPE)
{
assert(info->args.callConv & CORINFO_CALLCONV_PARAMTYPE);
hasGenericsContextArg = true;
genericsContextArgIndex = totalArgs;
totalArgs++;
}
// The non-this sig args have indices starting after these.
// We will first encode the arg offsets as *negative* offsets from the address above the first
// stack arg, and later add in the total size of the stack args to get a positive offset.
// The first sigArgsPlusThis elements are the offsets of the IL-addressable arguments. After that,
// there may be up to two more: generics context arg, if present, and return buff pointer, if present.
// (Note that the latter is actually passed after the "this" pointer, or else first if no "this" pointer
// is present. We re-arrange to preserve the easy IL-addressability.)
ArgState argState(totalArgs);
// This is the permutation that translates from an index in the argOffsets/argIsReg arrays to
// the platform-specific order in which the arguments are passed.
unsigned* argPerm = new unsigned[totalArgs];
// The number of register argument slots we end up pushing.
unsigned short regArgsFound = 0;
unsigned physArgIndex = 0;
#if defined(_ARM_)
// The stub linker has a weird little limitation: all stubs it's used
// for on ARM push some callee-saved register, so the unwind info
// code was written assuming at least one would be pushed. I don't know how to
// fix it, so I'm meeting this requirement, by pushing one callee-save.
#define STUB_LINK_EMIT_PROLOG_REQUIRES_CALLEE_SAVE_PUSH 1
#if STUB_LINK_EMIT_PROLOG_REQUIRES_CALLEE_SAVE_PUSH
const int NumberOfCalleeSaveRegsToPush = 1;
#else
const int NumberOfCalleeSaveRegsToPush = 0;
#endif
// The "1" here is for the return address.
const int NumberOfFixedPushes = 1 + NumberOfCalleeSaveRegsToPush;
#elif defined(_ARM64_)
// FP, LR
const int NumberOfFixedPushes = 2;
#endif
#if defined(FEATURE_HFA)
#if defined(_ARM_) || defined(_ARM64_)
// On ARM, a non-retBuffArg method that returns a struct type might be an HFA return. Figure
// that out.
unsigned HFARetTypeSize = 0;
#endif
#if defined(_ARM64_)
unsigned cHFAVars = 0;
#endif
if (info->args.retType == CORINFO_TYPE_VALUECLASS
&& CorInfoTypeIsFloatingPoint(comp->getHFAType(info->args.retTypeClass))
&& info->args.getCallConv() != CORINFO_CALLCONV_VARARG)
{
HFARetTypeSize = getClassSize(info->args.retTypeClass);
#if defined(_ARM_)
// Round up to a double boundary;
HFARetTypeSize = ((HFARetTypeSize+ sizeof(double) - 1) / sizeof(double)) * sizeof(double);
#elif defined(_ARM64_)
// We don't need to round it up to double. Unlike ARM, whether it's a float or a double each field will
// occupy one slot. We'll handle the stack alignment in the prolog where we have all the information about
// what is going to be pushed on the stack.
// Instead on ARM64 we'll need to know how many slots we'll need.
// for instance a VT with two float fields will have the same size as a VT with 1 double field. (ARM64TODO: Verify it)
// It works on ARM because the overlapping layout of the floating point registers
// but it won't work on ARM64.
cHFAVars = (comp->getHFAType(info->args.retTypeClass) == CORINFO_TYPE_FLOAT) ? HFARetTypeSize/sizeof(float) : HFARetTypeSize/sizeof(double);
#endif
}
#endif // defined(FEATURE_HFA)
_ASSERTE_MSG((info->args.callConv & (CORINFO_CALLCONV_EXPLICITTHIS)) == 0,
"Don't yet handle EXPLICITTHIS calling convention modifier.");
switch (info->args.callConv & CORINFO_CALLCONV_MASK)
{
case CORINFO_CALLCONV_DEFAULT:
case CORINFO_CALLCONV_VARARG:
{
unsigned firstSigArgIndex = 0;
if (hasThis)
{
argPerm[0] = physArgIndex; physArgIndex++;
argState.AddArg(0);
firstSigArgIndex++;
}
if (hasRetBuff)
{
argPerm[retBuffArgIndex] = physArgIndex; physArgIndex++;
argState.AddArg(retBuffArgIndex);
}
if (isVarArg)
{
argPerm[vaSigCookieIndex] = physArgIndex; physArgIndex++;
interpMethInfo->m_varArgHandleArgNum = vaSigCookieIndex;
argState.AddArg(vaSigCookieIndex);
}
#if defined(_ARM_) || defined(_AMD64_) || defined(_ARM64_)
// Generics context comes before args on ARM. Would be better if I factored this out as a call,
// to avoid large swatches of duplicate code.
if (hasGenericsContextArg)
{
argPerm[genericsContextArgIndex] = physArgIndex; physArgIndex++;
argState.AddArg(genericsContextArgIndex);
}
#endif // _ARM_ || _AMD64_ || _ARM64_
CORINFO_ARG_LIST_HANDLE argPtr = info->args.args;
// Some arguments are have been passed in registers, some in memory. We must generate code that
// moves the register arguments to memory, and determines a pointer into the stack from which all
// the arguments can be accessed, according to the offsets in "argOffsets."
//
// In the first pass over the arguments, we will label and count the register arguments, and
// initialize entries in "argOffsets" for the non-register arguments -- relative to the SP at the
// time of the call. Then when we have counted the number of register arguments, we will adjust
// the offsets for the non-register arguments to account for those. Then, in the second pass, we
// will push the register arguments on the stack, and capture the final stack pointer value as
// the argument vector pointer.
CORINFO_CLASS_HANDLE vcTypeRet;
// This iteration starts at the first signature argument, and iterates over all the
// canonical indices for the signature arguments.
for (unsigned k = firstSigArgIndex; k < sigArgsPlusThis; k++)
{
argPerm[k] = physArgIndex; physArgIndex++;
CorInfoTypeWithMod argTypWithMod = comp->getArgType(&info->args, argPtr, &vcTypeRet);
CorInfoType argType = strip(argTypWithMod);
switch (argType)
{
case CORINFO_TYPE_UNDEF:
case CORINFO_TYPE_VOID:
case CORINFO_TYPE_VAR:
_ASSERTE_ALL_BUILDS(__FILE__, false); // Should not happen;
break;
// One integer slot arguments:
case CORINFO_TYPE_BOOL:
case CORINFO_TYPE_CHAR:
case CORINFO_TYPE_BYTE:
case CORINFO_TYPE_UBYTE:
case CORINFO_TYPE_SHORT:
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_INT:
case CORINFO_TYPE_UINT:
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_STRING:
case CORINFO_TYPE_PTR:
argState.AddArg(k);
break;
// Two integer slot arguments.
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_ULONG:
#if defined(_X86_)
// Longs are always passed on the stack -- with no obvious alignment.
argState.AddArg(k, 2, /*noReg*/true);
#elif defined(_ARM_)
// LONGS have 2-reg alignment; inc reg if necessary.
argState.AddArg(k, 2, /*noReg*/false, /*twoSlotAlign*/true);
#elif defined(_AMD64_) || defined(_ARM64_)
argState.AddArg(k);
#else
#error unknown platform
#endif
break;
// One float slot args:
case CORINFO_TYPE_FLOAT:
#if defined(_X86_)
argState.AddArg(k, 1, /*noReg*/true);
#elif defined(_ARM_)
argState.AddFPArg(k, 1, /*twoSlotAlign*/false);
#elif defined(_AMD64_) || defined(_ARM64_)
argState.AddFPArg(k, 1, false);
#else
#error unknown platform
#endif
break;
// Two float slot args
case CORINFO_TYPE_DOUBLE:
#if defined(_X86_)
argState.AddArg(k, 2, /*noReg*/true);
#elif defined(_ARM_)
argState.AddFPArg(k, 2, /*twoSlotAlign*/true);
#elif defined(_AMD64_) || defined(_ARM64_)
argState.AddFPArg(k, 1, false);
#else
#error unknown platform
#endif
break;
// Value class args:
case CORINFO_TYPE_VALUECLASS:
case CORINFO_TYPE_REFANY:
{
unsigned sz = getClassSize(vcTypeRet);
unsigned szSlots = max(1, sz / sizeof(void*));
#if defined(_X86_)
argState.AddArg(k, static_cast<short>(szSlots), /*noReg*/true);
#elif defined(_AMD64_)
argState.AddArg(k, static_cast<short>(szSlots));
#elif defined(_ARM_) || defined(_ARM64_)
CorInfoType hfaType = comp->getHFAType(vcTypeRet);
if (CorInfoTypeIsFloatingPoint(hfaType))
{
argState.AddFPArg(k, szSlots,
#if defined(_ARM_)
/*twoSlotAlign*/ (hfaType == CORINFO_TYPE_DOUBLE)
#elif defined(_ARM64_)
/*twoSlotAlign*/ false // unlike ARM32 FP args always consume 1 slot on ARM64
#endif
);
}
else
{
unsigned align = comp->getClassAlignmentRequirement(vcTypeRet, FALSE);
argState.AddArg(k, static_cast<short>(szSlots), /*noReg*/false,
#if defined(_ARM_)
/*twoSlotAlign*/ (align == 8)
#elif defined(_ARM64_)
/*twoSlotAlign*/ false
#endif
);
}
#else
#error unknown platform
#endif
}
break;
default:
_ASSERTE_MSG(false, "should not reach here, unknown arg type");
}
argPtr = comp->getArgNext(argPtr);
}
#if defined(_X86_)
// Generics context comes last on _X86_. Would be better if I factored this out as a call,
// to avoid large swatches of duplicate code.
if (hasGenericsContextArg)
{
argPerm[genericsContextArgIndex] = physArgIndex; physArgIndex++;
argState.AddArg(genericsContextArgIndex);
}
// Now we have counted the number of register arguments, so we can update the offsets for the
// non-register arguments. "+ 2" below is to account for the return address from the call, and
// pushing of EBP.
unsigned short stackArgBaseOffset = (argState.numRegArgs + 2 + argState.callerArgStackSlots) * sizeof(void*);
unsigned intRegArgBaseOffset = 0;
#elif defined(_ARM_)
// We're choosing to always push all arg regs on ARM -- this is the only option
// that ThumbEmitProlog currently gives.
argState.numRegArgs = 4;
// On ARM, we push the (integer) arg regs before we push the return address, so we don't add an
// extra constant. And the offset is the address of the last pushed argument, which is the first
// stack argument in signature order.
// Round up to a double boundary...
unsigned fpStackSlots = ((argState.numFPRegArgSlots + 1) / 2) * 2;
unsigned intRegArgBaseOffset = (fpStackSlots + NumberOfFixedPushes) * sizeof(void*);
unsigned short stackArgBaseOffset = intRegArgBaseOffset + (argState.numRegArgs) * sizeof(void*);
#elif defined(_ARM64_)
// See StubLinkerCPU::EmitProlog for the layout of the stack
unsigned intRegArgBaseOffset = (argState.numFPRegArgSlots) * sizeof(void*);
unsigned short stackArgBaseOffset = (unsigned short) ((argState.numRegArgs + argState.numFPRegArgSlots) * sizeof(void*));
#elif defined(_AMD64_)
unsigned short stackArgBaseOffset = (argState.numRegArgs) * sizeof(void*);
#else
#error unsupported platform
#endif
#if defined(_ARM_)
WORD regArgMask = 0;
#endif // defined(_ARM_)
// argPerm maps from an index into the argOffsets/argIsReg arrays to
// the order that the arguments are passed.
unsigned* argPermInverse = new unsigned[totalArgs];
for (unsigned t = 0; t < totalArgs; t++)
{
argPermInverse[argPerm[t]] = t;
}
for (unsigned kk = 0; kk < totalArgs; kk++)
{
// Let "k" be the index of the kk'th input in the argOffsets and argIsReg arrays.
// To compute "k" we need to invert argPerm permutation -- determine the "k" such
// that argPerm[k] == kk.
unsigned k = argPermInverse[kk];
assert(k < totalArgs);
if (argState.argIsReg[k] == ArgState::ARS_IntReg)
{
regArgsFound++;
// If any int reg args are used on ARM, we push them all (in ThumbEmitProlog)
#if defined(_X86_)
if (regArgsFound == 1)
{
if (!jmpCall) { sl.X86EmitPushReg(kECX); }
argState.argOffsets[k] = (argState.numRegArgs - regArgsFound)*sizeof(void*); // General form, good for general # of reg args.
}
else
{
assert(regArgsFound == 2);
if (!jmpCall) { sl.X86EmitPushReg(kEDX); }
argState.argOffsets[k] = (argState.numRegArgs - regArgsFound)*sizeof(void*);
}
#elif defined(_ARM_) || defined(_ARM64_)
argState.argOffsets[k] += intRegArgBaseOffset;
#elif defined(_AMD64_)
// First home the register arguments in the stack space allocated by the caller.
// Refer to Stack Allocation on x64 [http://msdn.microsoft.com/en-US/library/ew5tede7(v=vs.80).aspx]
X86Reg argRegs[] = { kECX, kEDX, kR8, kR9 };
if (!jmpCall) { sl.X86EmitIndexRegStoreRSP(regArgsFound * sizeof(void*), argRegs[regArgsFound - 1]); }
argState.argOffsets[k] = (regArgsFound - 1) * sizeof(void*);
#else
#error unsupported platform
#endif
}
#if defined(_AMD64_)
else if (argState.argIsReg[k] == ArgState::ARS_FloatReg)
{
// Increment regArgsFound since float/int arguments have overlapping registers.
regArgsFound++;
// Home the float arguments.
X86Reg argRegs[] = { kXMM0, kXMM1, kXMM2, kXMM3 };
if (!jmpCall) { sl.X64EmitMovSDToMem(argRegs[regArgsFound - 1], static_cast<X86Reg>(kESP_Unsafe), regArgsFound * sizeof(void*)); }
argState.argOffsets[k] = (regArgsFound - 1) * sizeof(void*);
}
#endif
else if (argState.argIsReg[k] == ArgState::ARS_NotReg)
{
argState.argOffsets[k] += stackArgBaseOffset;
}
// So far, x86 doesn't have any FP reg args, and ARM and ARM64 puts them at offset 0, so no
// adjustment is necessary (yet) for arguments passed in those registers.
}
delete[] argPermInverse;
}
break;
case CORINFO_CALLCONV_C:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_C");
break;
case CORINFO_CALLCONV_STDCALL:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_STDCALL");
break;
case CORINFO_CALLCONV_THISCALL:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_THISCALL");
break;
case CORINFO_CALLCONV_FASTCALL:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_FASTCALL");
break;
case CORINFO_CALLCONV_FIELD:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_FIELD");
break;
case CORINFO_CALLCONV_LOCAL_SIG:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_LOCAL_SIG");
break;
case CORINFO_CALLCONV_PROPERTY:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_PROPERTY");
break;
case CORINFO_CALLCONV_NATIVEVARARG:
NYI_INTERP("GenerateInterpreterStub -- CORINFO_CALLCONV_NATIVEVARARG");
break;
default:
_ASSERTE_ALL_BUILDS(__FILE__, false); // shouldn't get here
}
delete[] argPerm;
PCODE interpretMethodFunc;
if (!jmpCall)
{
switch (info->args.retType)
{
case CORINFO_TYPE_FLOAT:
interpretMethodFunc = reinterpret_cast<PCODE>(&InterpretMethodFloat);
break;
case CORINFO_TYPE_DOUBLE:
interpretMethodFunc = reinterpret_cast<PCODE>(&InterpretMethodDouble);
break;
default:
interpretMethodFunc = reinterpret_cast<PCODE>(&InterpretMethod);
break;
}
// The argument registers have been pushed by now, so we can use them.
#if defined(_X86_)
// First arg is pointer to the base of the ILargs arr -- i.e., the current stack value.
sl.X86EmitMovRegReg(kEDX, static_cast<X86Reg>(kESP_Unsafe));
// InterpretMethod uses F_CALL_CONV == __fastcall; pass 2 args in regs.
#if INTERP_ILSTUBS
if (pMD->IsILStub())
{
// Third argument is stubcontext, in eax.
sl.X86EmitPushReg(kEAX);
}
else
#endif
{
// For a non-ILStub method, push NULL as the StubContext argument.
sl.X86EmitZeroOutReg(kECX);
sl.X86EmitPushReg(kECX);
}
// sl.X86EmitAddReg(kECX, reinterpret_cast<UINT>(interpMethInfo));
sl.X86EmitRegLoad(kECX, reinterpret_cast<UINT>(interpMethInfo));
sl.X86EmitCall(sl.NewExternalCodeLabel(interpretMethodFunc), 0);
// Now we will deallocate the stack slots we pushed to hold register arguments.
if (argState.numRegArgs > 0)
{
sl.X86EmitAddEsp(argState.numRegArgs * sizeof(void*));
}
sl.X86EmitPopReg(kEBP);
sl.X86EmitReturn(static_cast<WORD>(argState.callerArgStackSlots * sizeof(void*)));
#elif defined(_AMD64_)
// Pass "ilArgs", i.e. just the point where registers have been homed, as 2nd arg
sl.X86EmitIndexLeaRSP(ARGUMENT_kREG2, static_cast<X86Reg>(kESP_Unsafe), 8);
// Allocate space for homing callee's (InterpretMethod's) arguments.
// Calling convention requires a default allocation space of 4,
// but to double align the stack frame, we'd allocate 5.
int interpMethodArgSize = 5 * sizeof(void*);
sl.X86EmitSubEsp(interpMethodArgSize);
// If we have IL stubs pass the stub context in R10 or else pass NULL.
#if INTERP_ILSTUBS
if (pMD->IsILStub())
{
sl.X86EmitMovRegReg(kR8, kR10);
}
else
#endif
{
// For a non-ILStub method, push NULL as the StubContext argument.
sl.X86EmitZeroOutReg(ARGUMENT_kREG1);
sl.X86EmitMovRegReg(kR8, ARGUMENT_kREG1);
}
sl.X86EmitRegLoad(ARGUMENT_kREG1, reinterpret_cast<UINT_PTR>(interpMethInfo));
sl.X86EmitCall(sl.NewExternalCodeLabel(interpretMethodFunc), 0);
sl.X86EmitAddEsp(interpMethodArgSize);
sl.X86EmitReturn(0);
#elif defined(_ARM_)
// We have to maintain 8-byte stack alignment. So if the number of
// slots we would normally push is not a multiple of two, add a random
// register. (We will not pop this register, but rather, increment
// sp by an amount that includes it.)
bool oddPushes = (((argState.numRegArgs + NumberOfFixedPushes) % 2) != 0);
UINT stackFrameSize = 0;
if (oddPushes) stackFrameSize = sizeof(void*);
// Now, if any FP regs are used as arguments, we will copy those to the stack; reserve space for that here.
// (We push doubles to keep the stack aligned...)
unsigned short doublesToPush = (argState.numFPRegArgSlots + 1)/2;
stackFrameSize += (doublesToPush*2*sizeof(void*));
// The last argument here causes this to generate code to push all int arg regs.
sl.ThumbEmitProlog(/*cCalleeSavedRegs*/NumberOfCalleeSaveRegsToPush, /*cbStackFrame*/stackFrameSize, /*fPushArgRegs*/TRUE);
// Now we will generate code to copy the floating point registers to the stack frame.
if (doublesToPush > 0)
{
sl.ThumbEmitStoreMultipleVFPDoubleReg(ThumbVFPDoubleReg(0), thumbRegSp, doublesToPush*2);
}
#if INTERP_ILSTUBS
if (pMD->IsILStub())
{
// Third argument is stubcontext, in r12.
sl.ThumbEmitMovRegReg(ThumbReg(2), ThumbReg(12));
}
else
#endif
{
// For a non-ILStub method, push NULL as the third StubContext argument.
sl.ThumbEmitMovConstant(ThumbReg(2), 0);
}
// Second arg is pointer to the base of the ILargs arr -- i.e., the current stack value.
sl.ThumbEmitMovRegReg(ThumbReg(1), thumbRegSp);
// First arg is the pointer to the interpMethInfo structure.
sl.ThumbEmitMovConstant(ThumbReg(0), reinterpret_cast<int>(interpMethInfo));
// If there's an HFA return, add space for that.
if (HFARetTypeSize > 0)
{
sl.ThumbEmitSubSp(HFARetTypeSize);
}
// Now we can call the right method.
// No "direct call" instruction, so load into register first. Can use R3.
sl.ThumbEmitMovConstant(ThumbReg(3), static_cast<int>(interpretMethodFunc));
sl.ThumbEmitCallRegister(ThumbReg(3));
// If there's an HFA return, copy to FP regs, and deallocate the stack space.
if (HFARetTypeSize > 0)
{
sl.ThumbEmitLoadMultipleVFPDoubleReg(ThumbVFPDoubleReg(0), thumbRegSp, HFARetTypeSize/sizeof(void*));
sl.ThumbEmitAddSp(HFARetTypeSize);
}
sl.ThumbEmitEpilog();
#elif defined(_ARM64_)
UINT stackFrameSize = argState.numFPRegArgSlots;
sl.EmitProlog(argState.numRegArgs, argState.numFPRegArgSlots, 0 /*cCalleeSavedRegs*/, static_cast<unsigned short>(cHFAVars*sizeof(void*)));
#if INTERP_ILSTUBS
if (pMD->IsILStub())
{
// Third argument is stubcontext, in x12 (METHODDESC_REGISTER)
sl.EmitMovReg(IntReg(2), IntReg(12));
}
else
#endif
{
// For a non-ILStub method, push NULL as the third stubContext argument
sl.EmitMovConstant(IntReg(2), 0);
}
// Second arg is pointer to the basei of the ILArgs -- i.e., the current stack value
sl.EmitAddImm(IntReg(1), RegSp, sl.GetSavedRegArgsOffset());
// First arg is the pointer to the interpMethodInfo structure
#if INTERP_ILSTUBS
if (!pMD->IsILStub())
#endif
{
// interpMethodInfo is already in x8, so copy it from x8
sl.EmitMovReg(IntReg(0), IntReg(8));
}
#if INTERP_ILSTUBS
else
{
// We didn't do the short-circuiting, therefore interpMethInfo is
// not stored in a register (x8) before. so do it now.
sl.EmitMovConstant(IntReg(0), reinterpret_cast<UINT64>(interpMethInfo));
}
#endif
sl.EmitCallLabel(sl.NewExternalCodeLabel((LPVOID)interpretMethodFunc), FALSE, FALSE);
// If there's an HFA return, copy to FP regs
if (cHFAVars > 0)
{
for (unsigned i=0; i<=(cHFAVars/2)*2;i+=2)
sl.EmitLoadStoreRegPairImm(StubLinkerCPU::eLOAD, VecReg(i), VecReg(i+1), RegSp, i*sizeof(void*));
if ((cHFAVars % 2) == 1)
sl.EmitLoadStoreRegImm(StubLinkerCPU::eLOAD,VecReg(cHFAVars-1), RegSp, cHFAVars*sizeof(void*));
}
sl.EmitEpilog();
#else
#error unsupported platform
#endif
stub = sl.Link(SystemDomain::GetGlobalLoaderAllocator()->GetStubHeap());
*nativeSizeOfCode = static_cast<ULONG>(stub->GetNumCodeBytes());
// TODO: manage reference count of interpreter stubs. Look for examples...
*nativeEntry = dac_cast<BYTE*>(stub->GetEntryPoint());
}
// Initialize the arg offset information.
interpMethInfo->InitArgInfo(comp, info, argState.argOffsets);
#ifdef _DEBUG
AddInterpMethInfo(interpMethInfo);
#endif // _DEBUG
if (!jmpCall)
{
// Remember the mapping between code address and MethodDesc*.
RecordInterpreterStubForMethodDesc(info->ftn, *nativeEntry);
}
return CORJIT_OK;
#undef TRACE_SKIPPED
}
size_t Interpreter::GetFrameSize(InterpreterMethodInfo* interpMethInfo)
{
size_t sz = interpMethInfo->LocalMemSize();
#if COMBINE_OPSTACK_VAL_TYPE
sz += (interpMethInfo->m_maxStack * sizeof(OpStackValAndType));
#else
sz += (interpMethInfo->m_maxStack * (sizeof(INT64) + sizeof(InterpreterType*)));
#endif
return sz;
}
// static
ARG_SLOT Interpreter::ExecuteMethodWrapper(struct InterpreterMethodInfo* interpMethInfo, bool directCall, BYTE* ilArgs, void* stubContext, __out bool* pDoJmpCall, CORINFO_RESOLVED_TOKEN* pResolvedToken)
{
#define INTERP_DYNAMIC_CONTRACTS 1
#if INTERP_DYNAMIC_CONTRACTS
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#else
// Dynamic contract occupies too much stack.
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
#endif
size_t sizeWithGS = GetFrameSize(interpMethInfo) + sizeof(GSCookie);
BYTE* frameMemoryGS = static_cast<BYTE*>(_alloca(sizeWithGS));
ARG_SLOT retVal = 0;
unsigned jmpCallToken = 0;
Interpreter interp(interpMethInfo, directCall, ilArgs, stubContext, frameMemoryGS);
// Make sure we can do a GC Scan properly.
FrameWithCookie<InterpreterFrame> interpFrame(&interp);
// Update the interpretation count.
InterlockedIncrement(reinterpret_cast<LONG *>(&interpMethInfo->m_invocations));
// Need to wait until this point to do this JITting, since it may trigger a GC.
JitMethodIfAppropriate(interpMethInfo);
// Pass buffers to get jmpCall flag and the token, if necessary.
interp.ExecuteMethod(&retVal, pDoJmpCall, &jmpCallToken);
if (*pDoJmpCall)
{
GCX_PREEMP();
interp.ResolveToken(pResolvedToken, jmpCallToken, CORINFO_TOKENKIND_Method InterpTracingArg(RTK_Call));
}
interpFrame.Pop();
return retVal;
}
// TODO: Add GSCookie checks
// static
inline ARG_SLOT Interpreter::InterpretMethodBody(struct InterpreterMethodInfo* interpMethInfo, bool directCall, BYTE* ilArgs, void* stubContext)
{
#if INTERP_DYNAMIC_CONTRACTS
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#else
// Dynamic contract occupies too much stack.
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
#endif
CEEInfo* jitInfo = NULL;
for (bool doJmpCall = true; doJmpCall; )
{
unsigned jmpCallToken = 0;
CORINFO_RESOLVED_TOKEN methTokPtr;
ARG_SLOT retVal = ExecuteMethodWrapper(interpMethInfo, directCall, ilArgs, stubContext, &doJmpCall, &methTokPtr);
// Clear any allocated jitInfo.
delete jitInfo;
// Nothing to do if the recent method asks not to do a jmpCall.
if (!doJmpCall)
{
return retVal;
}
// The recently executed method wants us to perform a jmpCall.
MethodDesc* pMD = GetMethod(methTokPtr.hMethod);
interpMethInfo = MethodHandleToInterpreterMethInfoPtr(CORINFO_METHOD_HANDLE(pMD));
// Allocate a new jitInfo and also a new interpMethInfo.
if (interpMethInfo == NULL)
{
assert(doJmpCall);
jitInfo = new CEEInfo(pMD, true);
CORINFO_METHOD_INFO methInfo;
GCX_PREEMP();
jitInfo->getMethodInfo(CORINFO_METHOD_HANDLE(pMD), &methInfo);
GenerateInterpreterStub(jitInfo, &methInfo, NULL, 0, &interpMethInfo, true);
}
}
UNREACHABLE();
}
void Interpreter::JitMethodIfAppropriate(InterpreterMethodInfo* interpMethInfo, bool force)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
unsigned int MaxInterpretCount = s_InterpreterJITThreshold.val(CLRConfig::INTERNAL_InterpreterJITThreshold);
if (force || interpMethInfo->m_invocations > MaxInterpretCount)
{
GCX_PREEMP();
MethodDesc *md = reinterpret_cast<MethodDesc *>(interpMethInfo->m_method);
PCODE stub = md->GetNativeCode();
if (InterpretationStubToMethodInfo(stub) == md)
{
#ifdef _DEBUG
if (s_TraceInterpreterJITTransitionFlag.val(CLRConfig::INTERNAL_TraceInterpreterJITTransition))
{
fprintf(GetLogFile(), "JITting method %s:%s.\n", md->m_pszDebugClassName, md->m_pszDebugMethodName);
}
#endif // _DEBUG
CORJIT_FLAGS jitFlags(CORJIT_FLAGS::CORJIT_FLAG_MAKEFINALCODE);
NewHolder<COR_ILMETHOD_DECODER> pDecoder(NULL);
// Dynamic methods (e.g., IL stubs) do not have an IL decoder but may
// require additional flags. Ordinary methods require the opposite.
if (md->IsDynamicMethod())
{
jitFlags.Add(md->AsDynamicMethodDesc()->GetILStubResolver()->GetJitFlags());
}
else
{
COR_ILMETHOD_DECODER::DecoderStatus status;
pDecoder = new COR_ILMETHOD_DECODER(md->GetILHeader(TRUE),
md->GetMDImport(),
&status);
}
PCODE res = md->MakeJitWorker(pDecoder, jitFlags);
interpMethInfo->m_jittedCode = res;
}
}
}
// static
HCIMPL3(float, InterpretMethodFloat, struct InterpreterMethodInfo* interpMethInfo, BYTE* ilArgs, void* stubContext)
{
FCALL_CONTRACT;
ARG_SLOT retVal = 0;
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2);
retVal = (ARG_SLOT)Interpreter::InterpretMethodBody(interpMethInfo, false, ilArgs, stubContext);
HELPER_METHOD_FRAME_END();
return *reinterpret_cast<float*>(ArgSlotEndianessFixup(&retVal, sizeof(float)));
}
HCIMPLEND
// static
HCIMPL3(double, InterpretMethodDouble, struct InterpreterMethodInfo* interpMethInfo, BYTE* ilArgs, void* stubContext)
{
FCALL_CONTRACT;
ARG_SLOT retVal = 0;
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2);
retVal = Interpreter::InterpretMethodBody(interpMethInfo, false, ilArgs, stubContext);
HELPER_METHOD_FRAME_END();
return *reinterpret_cast<double*>(ArgSlotEndianessFixup(&retVal, sizeof(double)));
}
HCIMPLEND
// static
HCIMPL3(INT64, InterpretMethod, struct InterpreterMethodInfo* interpMethInfo, BYTE* ilArgs, void* stubContext)
{
FCALL_CONTRACT;
ARG_SLOT retVal = 0;
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2);
retVal = Interpreter::InterpretMethodBody(interpMethInfo, false, ilArgs, stubContext);
HELPER_METHOD_FRAME_END();
return static_cast<INT64>(retVal);
}
HCIMPLEND
bool Interpreter::IsInCalleesFrames(void* stackPtr)
{
// We assume a downwards_growing stack.
return stackPtr < (m_localVarMemory - sizeof(GSCookie));
}
// I want an enumeration with values for the second byte of 2-byte opcodes.
enum OPCODE_2BYTE {
#define OPDEF(c,s,pop,push,args,type,l,s1,s2,ctrl) TWOBYTE_##c = unsigned(s2),
#include "opcode.def"
#undef OPDEF
};
// Optimize the interpreter loop for speed.
#ifdef _MSC_VER
#pragma optimize("t", on)
#endif
// Duplicating code from JitHelpers for MonEnter,MonExit,MonEnter_Static,
// MonExit_Static because it sets up helper frame for the JIT.
static void MonitorEnter(Object* obj, BYTE* pbLockTaken)
{
OBJECTREF objRef = ObjectToOBJECTREF(obj);
if (objRef == NULL)
COMPlusThrow(kArgumentNullException);
GCPROTECT_BEGININTERIOR(pbLockTaken);
#ifdef _DEBUG
Thread *pThread = GetThread();
DWORD lockCount = pThread->m_dwLockCount;
#endif
if (GET_THREAD()->CatchAtSafePointOpportunistic())
{
GET_THREAD()->PulseGCMode();
}
objRef->EnterObjMonitor();
_ASSERTE ((objRef->GetSyncBlock()->GetMonitor()->m_Recursion == 1 && pThread->m_dwLockCount == lockCount + 1) ||
pThread->m_dwLockCount == lockCount);
if (pbLockTaken != 0) *pbLockTaken = 1;
GCPROTECT_END();
}
static void MonitorExit(Object* obj, BYTE* pbLockTaken)
{
OBJECTREF objRef = ObjectToOBJECTREF(obj);
if (objRef == NULL)
COMPlusThrow(kArgumentNullException);
if (!objRef->LeaveObjMonitor())
COMPlusThrow(kSynchronizationLockException);
if (pbLockTaken != 0) *pbLockTaken = 0;
TESTHOOKCALL(AppDomainCanBeUnloaded(GET_THREAD()->GetDomain()->GetId().m_dwId,FALSE));
if (GET_THREAD()->IsAbortRequested()) {
GET_THREAD()->HandleThreadAbort();
}
}
static void MonitorEnterStatic(AwareLock *lock, BYTE* pbLockTaken)
{
lock->Enter();
MONHELPER_STATE(*pbLockTaken = 1;)
}
static void MonitorExitStatic(AwareLock *lock, BYTE* pbLockTaken)
{
// Error, yield or contention
if (!lock->Leave())
COMPlusThrow(kSynchronizationLockException);
TESTHOOKCALL(AppDomainCanBeUnloaded(GET_THREAD()->GetDomain()->GetId().m_dwId,FALSE));
if (GET_THREAD()->IsAbortRequested()) {
GET_THREAD()->HandleThreadAbort();
}
}
AwareLock* Interpreter::GetMonitorForStaticMethod()
{
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(m_methInfo->m_method);
CORINFO_LOOKUP_KIND kind;
{
GCX_PREEMP();
kind = m_interpCeeInfo.getLocationOfThisType(m_methInfo->m_method);
}
if (!kind.needsRuntimeLookup)
{
OBJECTREF ref = pMD->GetMethodTable()->GetManagedClassObject();
return (AwareLock*) ref->GetSyncBlock()->GetMonitor();
}
else
{
CORINFO_CLASS_HANDLE classHnd = nullptr;
switch (kind.runtimeLookupKind)
{
case CORINFO_LOOKUP_CLASSPARAM:
{
classHnd = (CORINFO_CLASS_HANDLE) GetPreciseGenericsContext();
}
break;
case CORINFO_LOOKUP_METHODPARAM:
{
MethodDesc* pMD = (MethodDesc*) GetPreciseGenericsContext();
classHnd = (CORINFO_CLASS_HANDLE) pMD->GetMethodTable();
}
break;
default:
NYI_INTERP("Unknown lookup for synchronized methods");
break;
}
MethodTable* pMT = GetMethodTableFromClsHnd(classHnd);
OBJECTREF ref = pMT->GetManagedClassObject();
ASSERT(ref);
return (AwareLock*) ref->GetSyncBlock()->GetMonitor();
}
}
void Interpreter::DoMonitorEnterWork()
{
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(m_methInfo->m_method);
if (pMD->IsSynchronized())
{
if (pMD->IsStatic())
{
AwareLock* lock = GetMonitorForStaticMethod();
MonitorEnterStatic(lock, &m_monAcquired);
}
else
{
MonitorEnter((Object*) m_thisArg, &m_monAcquired);
}
}
}
void Interpreter::DoMonitorExitWork()
{
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(m_methInfo->m_method);
if (pMD->IsSynchronized())
{
if (pMD->IsStatic())
{
AwareLock* lock = GetMonitorForStaticMethod();
MonitorExitStatic(lock, &m_monAcquired);
}
else
{
MonitorExit((Object*) m_thisArg, &m_monAcquired);
}
}
}
void Interpreter::ExecuteMethod(ARG_SLOT* retVal, __out bool* pDoJmpCall, __out unsigned* pJmpCallToken)
{
#if INTERP_DYNAMIC_CONTRACTS
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#else
// Dynamic contract occupies too much stack.
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
#endif
*pDoJmpCall = false;
// Normally I'd prefer to declare these in small case-block scopes, but most C++ compilers
// do not realize that their lifetimes do not overlap, so that makes for a large stack frame.
// So I avoid that by outside declarations (sigh).
char offsetc, valc;
unsigned char argNumc;
unsigned short argNums;
INT32 vali;
INT64 vall;
InterpreterType it;
size_t sz;
unsigned short ops;
// Make sure that the .cctor for the current method's class has been run.
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(m_methInfo->m_method);
EnsureClassInit(pMD->GetMethodTable());
#if INTERP_TRACING
const char* methName = eeGetMethodFullName(m_methInfo->m_method);
unsigned ilOffset = 0;
unsigned curInvocation = InterlockedIncrement(&s_totalInvocations);
if (s_TraceInterpreterEntriesFlag.val(CLRConfig::INTERNAL_TraceInterpreterEntries))
{
fprintf(GetLogFile(), "Entering method #%d (= 0x%x): %s.\n", curInvocation, curInvocation, methName);
fprintf(GetLogFile(), " arguments:\n");
PrintArgs();
}
#endif // INTERP_TRACING
#if LOOPS_VIA_INSTRS
unsigned instrs = 0;
#else
#if INTERP_PROFILE
unsigned instrs = 0;
#endif
#endif
EvalLoop:
GCX_ASSERT_COOP();
// Catch any exceptions raised.
EX_TRY {
// Optional features...
#define INTERPRETER_CHECK_LARGE_STRUCT_STACK_HEIGHT 1
#if INTERP_ILCYCLE_PROFILE
m_instr = CEE_COUNT; // Flag to indicate first instruction.
m_exemptCycles = 0;
#endif // INTERP_ILCYCLE_PROFILE
DoMonitorEnterWork();
INTERPLOG("START %d, %s\n", m_methInfo->m_stubNum, methName);
for (;;)
{
// TODO: verify that m_ILCodePtr is legal, and we haven't walked off the end of the IL array? (i.e., bad IL).
// Note that ExecuteBranch() should be called for every branch. That checks that we aren't either before or
// after the IL range. Here, we would only need to check that we haven't gone past the end (not before the beginning)
// because everything that doesn't call ExecuteBranch() should only add to m_ILCodePtr.
#if INTERP_TRACING
ilOffset = CurOffset();
#endif // _DEBUG
#if INTERP_TRACING
if (s_TraceInterpreterOstackFlag.val(CLRConfig::INTERNAL_TraceInterpreterOstack))
{
PrintOStack();
}
#if INTERPRETER_CHECK_LARGE_STRUCT_STACK_HEIGHT
_ASSERTE_MSG(LargeStructStackHeightIsValid(), "Large structure stack height invariant violated."); // Check the large struct stack invariant.
#endif
if (s_TraceInterpreterILFlag.val(CLRConfig::INTERNAL_TraceInterpreterIL))
{
fprintf(GetLogFile(), " %#4x: %s\n", ilOffset, ILOp(m_ILCodePtr));
fflush(GetLogFile());
}
#endif // INTERP_TRACING
#if LOOPS_VIA_INSTRS
instrs++;
#else
#if INTERP_PROFILE
instrs++;
#endif
#endif
#if INTERP_ILINSTR_PROFILE
#if INTERP_ILCYCLE_PROFILE
UpdateCycleCount();
#endif // INTERP_ILCYCLE_PROFILE
InterlockedIncrement(&s_ILInstrExecs[*m_ILCodePtr]);
#endif // INTERP_ILINSTR_PROFILE
switch (*m_ILCodePtr)
{
case CEE_NOP:
m_ILCodePtr++;
continue;
case CEE_BREAK: // TODO: interact with the debugger?
m_ILCodePtr++;
continue;
case CEE_LDARG_0:
LdArg(0);
break;
case CEE_LDARG_1:
LdArg(1);
break;
case CEE_LDARG_2:
LdArg(2);
break;
case CEE_LDARG_3:
LdArg(3);
break;
case CEE_LDLOC_0:
LdLoc(0);
m_ILCodePtr++;
continue;
case CEE_LDLOC_1:
LdLoc(1);
break;
case CEE_LDLOC_2:
LdLoc(2);
break;
case CEE_LDLOC_3:
LdLoc(3);
break;
case CEE_STLOC_0:
StLoc(0);
break;
case CEE_STLOC_1:
StLoc(1);
break;
case CEE_STLOC_2:
StLoc(2);
break;
case CEE_STLOC_3:
StLoc(3);
break;
case CEE_LDARG_S:
m_ILCodePtr++;
argNumc = *m_ILCodePtr;
LdArg(argNumc);
break;
case CEE_LDARGA_S:
m_ILCodePtr++;
argNumc = *m_ILCodePtr;
LdArgA(argNumc);
break;
case CEE_STARG_S:
m_ILCodePtr++;
argNumc = *m_ILCodePtr;
StArg(argNumc);
break;
case CEE_LDLOC_S:
argNumc = *(m_ILCodePtr + 1);
LdLoc(argNumc);
m_ILCodePtr += 2;
continue;
case CEE_LDLOCA_S:
m_ILCodePtr++;
argNumc = *m_ILCodePtr;
LdLocA(argNumc);
break;
case CEE_STLOC_S:
argNumc = *(m_ILCodePtr + 1);
StLoc(argNumc);
m_ILCodePtr += 2;
continue;
case CEE_LDNULL:
LdNull();
break;
case CEE_LDC_I4_M1:
LdIcon(-1);
break;
case CEE_LDC_I4_0:
LdIcon(0);
break;
case CEE_LDC_I4_1:
LdIcon(1);
m_ILCodePtr++;
continue;
case CEE_LDC_I4_2:
LdIcon(2);
break;
case CEE_LDC_I4_3:
LdIcon(3);
break;
case CEE_LDC_I4_4:
LdIcon(4);
break;
case CEE_LDC_I4_5:
LdIcon(5);
break;
case CEE_LDC_I4_6:
LdIcon(6);
break;
case CEE_LDC_I4_7:
LdIcon(7);
break;
case CEE_LDC_I4_8:
LdIcon(8);
break;
case CEE_LDC_I4_S:
valc = getI1(m_ILCodePtr + 1);
LdIcon(valc);
m_ILCodePtr += 2;
continue;
case CEE_LDC_I4:
vali = getI4LittleEndian(m_ILCodePtr + 1);
LdIcon(vali);
m_ILCodePtr += 5;
continue;
case CEE_LDC_I8:
vall = getI8LittleEndian(m_ILCodePtr + 1);
LdLcon(vall);
m_ILCodePtr += 9;
continue;
case CEE_LDC_R4:
// We use I4 here because we just care about the bit pattern.
// LdR4Con will push the right InterpreterType.
vali = getI4LittleEndian(m_ILCodePtr + 1);
LdR4con(vali);
m_ILCodePtr += 5;
continue;
case CEE_LDC_R8:
// We use I4 here because we just care about the bit pattern.
// LdR8Con will push the right InterpreterType.
vall = getI8LittleEndian(m_ILCodePtr + 1);
LdR8con(vall);
m_ILCodePtr += 9;
continue;
case CEE_DUP:
assert(m_curStackHt > 0);
it = OpStackTypeGet(m_curStackHt - 1);
OpStackTypeSet(m_curStackHt, it);
if (it.IsLargeStruct(&m_interpCeeInfo))
{
sz = it.Size(&m_interpCeeInfo);
void* dest = LargeStructOperandStackPush(sz);
memcpy(dest, OpStackGet<void*>(m_curStackHt - 1), sz);
OpStackSet<void*>(m_curStackHt, dest);
}
else
{
OpStackSet<INT64>(m_curStackHt, OpStackGet<INT64>(m_curStackHt - 1));
}
m_curStackHt++;
break;
case CEE_POP:
assert(m_curStackHt > 0);
m_curStackHt--;
it = OpStackTypeGet(m_curStackHt);
if (it.IsLargeStruct(&m_interpCeeInfo))
{
LargeStructOperandStackPop(it.Size(&m_interpCeeInfo), OpStackGet<void*>(m_curStackHt));
}
break;
case CEE_JMP:
*pJmpCallToken = getU4LittleEndian(m_ILCodePtr + sizeof(BYTE));
*pDoJmpCall = true;
goto ExitEvalLoop;
case CEE_CALL:
DoCall(/*virtualCall*/false);
#ifdef _DEBUG
if (s_TraceInterpreterILFlag.val(CLRConfig::INTERNAL_TraceInterpreterIL))
{
fprintf(GetLogFile(), " Returning to method %s, stub num %d.\n", methName, m_methInfo->m_stubNum);
}
#endif // _DEBUG
continue;
case CEE_CALLVIRT:
DoCall(/*virtualCall*/true);
#ifdef _DEBUG
if (s_TraceInterpreterILFlag.val(CLRConfig::INTERNAL_TraceInterpreterIL))
{
fprintf(GetLogFile(), " Returning to method %s, stub num %d.\n", methName, m_methInfo->m_stubNum);
}
#endif // _DEBUG
continue;
// HARD
case CEE_CALLI:
CallI();
continue;
case CEE_RET:
if (m_methInfo->m_returnType == CORINFO_TYPE_VOID)
{
assert(m_curStackHt == 0);
}
else
{
assert(m_curStackHt == 1);
InterpreterType retValIt = OpStackTypeGet(0);
bool looseInt = s_InterpreterLooseRules &&
CorInfoTypeIsIntegral(m_methInfo->m_returnType) &&
(CorInfoTypeIsIntegral(retValIt.ToCorInfoType()) || CorInfoTypeIsPointer(retValIt.ToCorInfoType())) &&
(m_methInfo->m_returnType != retValIt.ToCorInfoType());
bool looseFloat = s_InterpreterLooseRules &&
CorInfoTypeIsFloatingPoint(m_methInfo->m_returnType) &&
CorInfoTypeIsFloatingPoint(retValIt.ToCorInfoType()) &&
(m_methInfo->m_returnType != retValIt.ToCorInfoType());
// Make sure that the return value "matches" (which allows certain relaxations) the declared return type.
assert((m_methInfo->m_returnType == CORINFO_TYPE_VALUECLASS && retValIt.ToCorInfoType() == CORINFO_TYPE_VALUECLASS) ||
(m_methInfo->m_returnType == CORINFO_TYPE_REFANY && retValIt.ToCorInfoType() == CORINFO_TYPE_VALUECLASS) ||
(m_methInfo->m_returnType == CORINFO_TYPE_REFANY && retValIt.ToCorInfoType() == CORINFO_TYPE_REFANY) ||
(looseInt || looseFloat) ||
InterpreterType(m_methInfo->m_returnType).StackNormalize().Matches(retValIt, &m_interpCeeInfo));
size_t sz = retValIt.Size(&m_interpCeeInfo);
#if defined(FEATURE_HFA)
CorInfoType cit = CORINFO_TYPE_UNDEF;
{
GCX_PREEMP();
if(m_methInfo->m_returnType == CORINFO_TYPE_VALUECLASS)
cit = m_interpCeeInfo.getHFAType(retValIt.ToClassHandle());
}
#endif
if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasRetBuffArg>())
{
assert((m_methInfo->m_returnType == CORINFO_TYPE_VALUECLASS && retValIt.ToCorInfoType() == CORINFO_TYPE_VALUECLASS) ||
(m_methInfo->m_returnType == CORINFO_TYPE_REFANY && retValIt.ToCorInfoType() == CORINFO_TYPE_VALUECLASS) ||
(m_methInfo->m_returnType == CORINFO_TYPE_REFANY && retValIt.ToCorInfoType() == CORINFO_TYPE_REFANY));
if (retValIt.ToCorInfoType() == CORINFO_TYPE_REFANY)
{
InterpreterType typedRefIT = GetTypedRefIT(&m_interpCeeInfo);
TypedByRef* ptr = OpStackGet<TypedByRef*>(0);
*((TypedByRef*) m_retBufArg) = *ptr;
}
else if (retValIt.IsLargeStruct(&m_interpCeeInfo))
{
MethodTable* clsMt = GetMethodTableFromClsHnd(retValIt.ToClassHandle());
// The ostack value is a pointer to the struct value.
CopyValueClassUnchecked(m_retBufArg, OpStackGet<void*>(0), clsMt);
}
else
{
MethodTable* clsMt = GetMethodTableFromClsHnd(retValIt.ToClassHandle());
// The ostack value *is* the struct value.
CopyValueClassUnchecked(m_retBufArg, OpStackGetAddr(0, sz), clsMt);
}
}
#if defined(FEATURE_HFA)
// Is it an HFA?
else if (m_methInfo->m_returnType == CORINFO_TYPE_VALUECLASS
&& CorInfoTypeIsFloatingPoint(cit)
&& (MetaSig(reinterpret_cast<MethodDesc*>(m_methInfo->m_method)).GetCallingConventionInfo() & CORINFO_CALLCONV_VARARG) == 0)
{
if (retValIt.IsLargeStruct(&m_interpCeeInfo))
{
// The ostack value is a pointer to the struct value.
memcpy(GetHFARetBuffAddr(static_cast<unsigned>(sz)), OpStackGet<void*>(0), sz);
}
else
{
// The ostack value *is* the struct value.
memcpy(GetHFARetBuffAddr(static_cast<unsigned>(sz)), OpStackGetAddr(0, sz), sz);
}
}
#endif
else if (CorInfoTypeIsFloatingPoint(m_methInfo->m_returnType) &&
CorInfoTypeIsFloatingPoint(retValIt.ToCorInfoType()))
{
double val = (sz <= sizeof(INT32)) ? OpStackGet<float>(0) : OpStackGet<double>(0);
if (m_methInfo->m_returnType == CORINFO_TYPE_DOUBLE)
{
memcpy(retVal, &val, sizeof(double));
}
else
{
float val2 = (float) val;
memcpy(retVal, &val2, sizeof(float));
}
}
else
{
if (sz <= sizeof(INT32))
{
*retVal = OpStackGet<INT32>(0);
}
else
{
// If looseInt is true, we are relying on auto-downcast in case *retVal
// is small (but this is guaranteed not to happen by def'n of ARG_SLOT.)
assert(sz == sizeof(INT64));
*retVal = OpStackGet<INT64>(0);
}
}
}
#if INTERP_PROFILE
// We're not capturing instructions executed in a method that terminates via exception,
// but that's OK...
m_methInfo->RecordExecInstrs(instrs);
#endif
#if INTERP_TRACING
// We keep this live until we leave.
delete methName;
#endif // INTERP_TRACING
#if INTERP_ILCYCLE_PROFILE
// Finish off accounting for the "RET" before we return
UpdateCycleCount();
#endif // INTERP_ILCYCLE_PROFILE
goto ExitEvalLoop;
case CEE_BR_S:
m_ILCodePtr++;
offsetc = *m_ILCodePtr;
// The offset is wrt the beginning of the following instruction, so the +1 is to get to that
// m_ILCodePtr value before adding the offset.
ExecuteBranch(m_ILCodePtr + offsetc + 1);
continue; // Skip the default m_ILCodePtr++ at bottom of loop.
case CEE_LEAVE_S:
// LEAVE empties the operand stack.
m_curStackHt = 0;
m_largeStructOperandStackHt = 0;
offsetc = getI1(m_ILCodePtr + 1);
{
// The offset is wrt the beginning of the following instruction, so the +2 is to get to that
// m_ILCodePtr value before adding the offset.
BYTE* leaveTarget = m_ILCodePtr + offsetc + 2;
unsigned leaveOffset = CurOffset();
m_leaveInfoStack.Push(LeaveInfo(leaveOffset, leaveTarget));
if (!SearchForCoveringFinally())
{
m_leaveInfoStack.Pop();
ExecuteBranch(leaveTarget);
}
}
continue; // Skip the default m_ILCodePtr++ at bottom of loop.
// Abstract the next pair out to something common with templates.
case CEE_BRFALSE_S:
BrOnValue<false, 1>();
continue;
case CEE_BRTRUE_S:
BrOnValue<true, 1>();
continue;
case CEE_BEQ_S:
BrOnComparison<CO_EQ, false, 1>();
continue;
case CEE_BGE_S:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_LT_UN, true, 1>();
break;
default:
BrOnComparison<CO_LT, true, 1>();
break;
}
continue;
case CEE_BGT_S:
BrOnComparison<CO_GT, false, 1>();
continue;
case CEE_BLE_S:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_GT_UN, true, 1>();
break;
default:
BrOnComparison<CO_GT, true, 1>();
break;
}
continue;
case CEE_BLT_S:
BrOnComparison<CO_LT, false, 1>();
continue;
case CEE_BNE_UN_S:
BrOnComparison<CO_EQ, true, 1>();
continue;
case CEE_BGE_UN_S:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_LT, true, 1>();
break;
default:
BrOnComparison<CO_LT_UN, true, 1>();
break;
}
continue;
case CEE_BGT_UN_S:
BrOnComparison<CO_GT_UN, false, 1>();
continue;
case CEE_BLE_UN_S:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_GT, true, 1>();
break;
default:
BrOnComparison<CO_GT_UN, true, 1>();
break;
}
continue;
case CEE_BLT_UN_S:
BrOnComparison<CO_LT_UN, false, 1>();
continue;
case CEE_BR:
m_ILCodePtr++;
vali = getI4LittleEndian(m_ILCodePtr);
vali += 4; // +4 for the length of the offset.
ExecuteBranch(m_ILCodePtr + vali);
if (vali < 0)
{
// Backwards branch -- enable caching.
BackwardsBranchActions(vali);
}
continue;
case CEE_LEAVE:
// LEAVE empties the operand stack.
m_curStackHt = 0;
m_largeStructOperandStackHt = 0;
vali = getI4LittleEndian(m_ILCodePtr + 1);
{
// The offset is wrt the beginning of the following instruction, so the +5 is to get to that
// m_ILCodePtr value before adding the offset.
BYTE* leaveTarget = m_ILCodePtr + (vali + 5);
unsigned leaveOffset = CurOffset();
m_leaveInfoStack.Push(LeaveInfo(leaveOffset, leaveTarget));
if (!SearchForCoveringFinally())
{
(void)m_leaveInfoStack.Pop();
if (vali < 0)
{
// Backwards branch -- enable caching.
BackwardsBranchActions(vali);
}
ExecuteBranch(leaveTarget);
}
}
continue; // Skip the default m_ILCodePtr++ at bottom of loop.
case CEE_BRFALSE:
BrOnValue<false, 4>();
continue;
case CEE_BRTRUE:
BrOnValue<true, 4>();
continue;
case CEE_BEQ:
BrOnComparison<CO_EQ, false, 4>();
continue;
case CEE_BGE:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_LT_UN, true, 4>();
break;
default:
BrOnComparison<CO_LT, true, 4>();
break;
}
continue;
case CEE_BGT:
BrOnComparison<CO_GT, false, 4>();
continue;
case CEE_BLE:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_GT_UN, true, 4>();
break;
default:
BrOnComparison<CO_GT, true, 4>();
break;
}
continue;
case CEE_BLT:
BrOnComparison<CO_LT, false, 4>();
continue;
case CEE_BNE_UN:
BrOnComparison<CO_EQ, true, 4>();
continue;
case CEE_BGE_UN:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_LT, true, 4>();
break;
default:
BrOnComparison<CO_LT_UN, true, 4>();
break;
}
continue;
case CEE_BGT_UN:
BrOnComparison<CO_GT_UN, false, 4>();
continue;
case CEE_BLE_UN:
assert(m_curStackHt >= 2);
// ECMA spec gives different semantics for different operand types:
switch (OpStackTypeGet(m_curStackHt-1).ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
BrOnComparison<CO_GT, true, 4>();
break;
default:
BrOnComparison<CO_GT_UN, true, 4>();
break;
}
continue;
case CEE_BLT_UN:
BrOnComparison<CO_LT_UN, false, 4>();
continue;
case CEE_SWITCH:
{
assert(m_curStackHt > 0);
m_curStackHt--;
#if defined(_DEBUG) || defined(_AMD64_)
CorInfoType cit = OpStackTypeGet(m_curStackHt).ToCorInfoType();
#endif // _DEBUG || _AMD64_
#ifdef _DEBUG
assert(cit == CORINFO_TYPE_INT || cit == CORINFO_TYPE_UINT || cit == CORINFO_TYPE_NATIVEINT);
#endif // _DEBUG
#if defined(_AMD64_)
UINT32 val = (cit == CORINFO_TYPE_NATIVEINT) ? (INT32) OpStackGet<NativeInt>(m_curStackHt)
: OpStackGet<INT32>(m_curStackHt);
#else
UINT32 val = OpStackGet<INT32>(m_curStackHt);
#endif
UINT32 n = getU4LittleEndian(m_ILCodePtr + 1);
UINT32 instrSize = 1 + (n + 1)*4;
if (val < n)
{
vali = getI4LittleEndian(m_ILCodePtr + (5 + val * 4));
ExecuteBranch(m_ILCodePtr + instrSize + vali);
}
else
{
m_ILCodePtr += instrSize;
}
}
continue;
case CEE_LDIND_I1:
LdIndShort<INT8, /*isUnsigned*/false>();
break;
case CEE_LDIND_U1:
LdIndShort<UINT8, /*isUnsigned*/true>();
break;
case CEE_LDIND_I2:
LdIndShort<INT16, /*isUnsigned*/false>();
break;
case CEE_LDIND_U2:
LdIndShort<UINT16, /*isUnsigned*/true>();
break;
case CEE_LDIND_I4:
LdInd<INT32, CORINFO_TYPE_INT>();
break;
case CEE_LDIND_U4:
LdInd<UINT32, CORINFO_TYPE_INT>();
break;
case CEE_LDIND_I8:
LdInd<INT64, CORINFO_TYPE_LONG>();
break;
case CEE_LDIND_I:
LdInd<NativeInt, CORINFO_TYPE_NATIVEINT>();
break;
case CEE_LDIND_R4:
LdInd<float, CORINFO_TYPE_FLOAT>();
break;
case CEE_LDIND_R8:
LdInd<double, CORINFO_TYPE_DOUBLE>();
break;
case CEE_LDIND_REF:
LdInd<Object*, CORINFO_TYPE_CLASS>();
break;
case CEE_STIND_REF:
StInd_Ref();
break;
case CEE_STIND_I1:
StInd<INT8>();
break;
case CEE_STIND_I2:
StInd<INT16>();
break;
case CEE_STIND_I4:
StInd<INT32>();
break;
case CEE_STIND_I8:
StInd<INT64>();
break;
case CEE_STIND_R4:
StInd<float>();
break;
case CEE_STIND_R8:
StInd<double>();
break;
case CEE_ADD:
BinaryArithOp<BA_Add>();
m_ILCodePtr++;
continue;
case CEE_SUB:
BinaryArithOp<BA_Sub>();
break;
case CEE_MUL:
BinaryArithOp<BA_Mul>();
break;
case CEE_DIV:
BinaryArithOp<BA_Div>();
break;
case CEE_DIV_UN:
BinaryIntOp<BIO_DivUn>();
break;
case CEE_REM:
BinaryArithOp<BA_Rem>();
break;
case CEE_REM_UN:
BinaryIntOp<BIO_RemUn>();
break;
case CEE_AND:
BinaryIntOp<BIO_And>();
break;
case CEE_OR:
BinaryIntOp<BIO_Or>();
break;
case CEE_XOR:
BinaryIntOp<BIO_Xor>();
break;
case CEE_SHL:
ShiftOp<CEE_SHL>();
break;
case CEE_SHR:
ShiftOp<CEE_SHR>();
break;
case CEE_SHR_UN:
ShiftOp<CEE_SHR_UN>();
break;
case CEE_NEG:
Neg();
break;
case CEE_NOT:
Not();
break;
case CEE_CONV_I1:
Conv<INT8, /*TIsUnsigned*/false, /*TCanHoldPtr*/false, /*TIsShort*/true, CORINFO_TYPE_INT>();
break;
case CEE_CONV_I2:
Conv<INT16, /*TIsUnsigned*/false, /*TCanHoldPtr*/false, /*TIsShort*/true, CORINFO_TYPE_INT>();
break;
case CEE_CONV_I4:
Conv<INT32, /*TIsUnsigned*/false, /*TCanHoldPtr*/false, /*TIsShort*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_I8:
Conv<INT64, /*TIsUnsigned*/false, /*TCanHoldPtr*/true, /*TIsShort*/false, CORINFO_TYPE_LONG>();
break;
case CEE_CONV_R4:
Conv<float, /*TIsUnsigned*/false, /*TCanHoldPtr*/false, /*TIsShort*/false, CORINFO_TYPE_FLOAT>();
break;
case CEE_CONV_R8:
Conv<double, /*TIsUnsigned*/false, /*TCanHoldPtr*/false, /*TIsShort*/false, CORINFO_TYPE_DOUBLE>();
break;
case CEE_CONV_U4:
Conv<UINT32, /*TIsUnsigned*/true, /*TCanHoldPtr*/false, /*TIsShort*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_U8:
Conv<UINT64, /*TIsUnsigned*/true, /*TCanHoldPtr*/true, /*TIsShort*/false, CORINFO_TYPE_LONG>();
break;
case CEE_CPOBJ:
CpObj();
continue;
case CEE_LDOBJ:
LdObj();
continue;
case CEE_LDSTR:
LdStr();
continue;
case CEE_NEWOBJ:
NewObj();
#ifdef _DEBUG
if (s_TraceInterpreterILFlag.val(CLRConfig::INTERNAL_TraceInterpreterIL))
{
fprintf(GetLogFile(), " Returning to method %s, stub num %d.\n", methName, m_methInfo->m_stubNum);
}
#endif // _DEBUG
continue;
case CEE_CASTCLASS:
CastClass();
continue;
case CEE_ISINST:
IsInst();
continue;
case CEE_CONV_R_UN:
ConvRUn();
break;
case CEE_UNBOX:
Unbox();
continue;
case CEE_THROW:
Throw();
break;
case CEE_LDFLD:
LdFld();
continue;
case CEE_LDFLDA:
LdFldA();
continue;
case CEE_STFLD:
StFld();
continue;
case CEE_LDSFLD:
LdSFld();
continue;
case CEE_LDSFLDA:
LdSFldA();
continue;
case CEE_STSFLD:
StSFld();
continue;
case CEE_STOBJ:
StObj();
continue;
case CEE_CONV_OVF_I1_UN:
ConvOvfUn<INT8, SCHAR_MIN, SCHAR_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_I2_UN:
ConvOvfUn<INT16, SHRT_MIN, SHRT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_I4_UN:
ConvOvfUn<INT32, INT_MIN, INT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_I8_UN:
ConvOvfUn<INT64, _I64_MIN, _I64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_LONG>();
break;
case CEE_CONV_OVF_U1_UN:
ConvOvfUn<UINT8, 0, UCHAR_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_U2_UN:
ConvOvfUn<UINT16, 0, USHRT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_U4_UN:
ConvOvfUn<UINT32, 0, UINT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_U8_UN:
ConvOvfUn<UINT64, 0, _UI64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_LONG>();
break;
case CEE_CONV_OVF_I_UN:
if (sizeof(NativeInt) == 4)
{
ConvOvfUn<NativeInt, INT_MIN, INT_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
else
{
assert(sizeof(NativeInt) == 8);
ConvOvfUn<NativeInt, _I64_MIN, _I64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
break;
case CEE_CONV_OVF_U_UN:
if (sizeof(NativeUInt) == 4)
{
ConvOvfUn<NativeUInt, 0, UINT_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
else
{
assert(sizeof(NativeUInt) == 8);
ConvOvfUn<NativeUInt, 0, _UI64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
break;
case CEE_BOX:
Box();
continue;
case CEE_NEWARR:
NewArr();
continue;
case CEE_LDLEN:
LdLen();
break;
case CEE_LDELEMA:
LdElem</*takeAddr*/true>();
continue;
case CEE_LDELEM_I1:
LdElemWithType<INT8, false, CORINFO_TYPE_INT>();
break;
case CEE_LDELEM_U1:
LdElemWithType<UINT8, false, CORINFO_TYPE_INT>();
break;
case CEE_LDELEM_I2:
LdElemWithType<INT16, false, CORINFO_TYPE_INT>();
break;
case CEE_LDELEM_U2:
LdElemWithType<UINT16, false, CORINFO_TYPE_INT>();
break;
case CEE_LDELEM_I4:
LdElemWithType<INT32, false, CORINFO_TYPE_INT>();
break;
case CEE_LDELEM_U4:
LdElemWithType<UINT32, false, CORINFO_TYPE_INT>();
break;
case CEE_LDELEM_I8:
LdElemWithType<INT64, false, CORINFO_TYPE_LONG>();
break;
// Note that the ECMA spec defines a "LDELEM_U8", but it is the same instruction number as LDELEM_I8 (since
// when loading to the widest width, signed/unsigned doesn't matter).
case CEE_LDELEM_I:
LdElemWithType<NativeInt, false, CORINFO_TYPE_NATIVEINT>();
break;
case CEE_LDELEM_R4:
LdElemWithType<float, false, CORINFO_TYPE_FLOAT>();
break;
case CEE_LDELEM_R8:
LdElemWithType<double, false, CORINFO_TYPE_DOUBLE>();
break;
case CEE_LDELEM_REF:
LdElemWithType<Object*, true, CORINFO_TYPE_CLASS>();
break;
case CEE_STELEM_I:
StElemWithType<NativeInt, false>();
break;
case CEE_STELEM_I1:
StElemWithType<INT8, false>();
break;
case CEE_STELEM_I2:
StElemWithType<INT16, false>();
break;
case CEE_STELEM_I4:
StElemWithType<INT32, false>();
break;
case CEE_STELEM_I8:
StElemWithType<INT64, false>();
break;
case CEE_STELEM_R4:
StElemWithType<float, false>();
break;
case CEE_STELEM_R8:
StElemWithType<double, false>();
break;
case CEE_STELEM_REF:
StElemWithType<Object*, true>();
break;
case CEE_LDELEM:
LdElem</*takeAddr*/false>();
continue;
case CEE_STELEM:
StElem();
continue;
case CEE_UNBOX_ANY:
UnboxAny();
continue;
case CEE_CONV_OVF_I1:
ConvOvf<INT8, SCHAR_MIN, SCHAR_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_U1:
ConvOvf<UINT8, 0, UCHAR_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_I2:
ConvOvf<INT16, SHRT_MIN, SHRT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_U2:
ConvOvf<UINT16, 0, USHRT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_I4:
ConvOvf<INT32, INT_MIN, INT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_U4:
ConvOvf<UINT32, 0, UINT_MAX, /*TCanHoldPtr*/false, CORINFO_TYPE_INT>();
break;
case CEE_CONV_OVF_I8:
ConvOvf<INT64, _I64_MIN, _I64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_LONG>();
break;
case CEE_CONV_OVF_U8:
ConvOvf<UINT64, 0, _UI64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_LONG>();
break;
case CEE_REFANYVAL:
RefanyVal();
continue;
case CEE_CKFINITE:
CkFinite();
break;
case CEE_MKREFANY:
MkRefany();
continue;
case CEE_LDTOKEN:
LdToken();
continue;
case CEE_CONV_U2:
Conv<UINT16, /*TIsUnsigned*/true, /*TCanHoldPtr*/false, /*TIsShort*/true, CORINFO_TYPE_INT>();
break;
case CEE_CONV_U1:
Conv<UINT8, /*TIsUnsigned*/true, /*TCanHoldPtr*/false, /*TIsShort*/true, CORINFO_TYPE_INT>();
break;
case CEE_CONV_I:
Conv<NativeInt, /*TIsUnsigned*/false, /*TCanHoldPtr*/true, /*TIsShort*/false, CORINFO_TYPE_NATIVEINT>();
break;
case CEE_CONV_OVF_I:
if (sizeof(NativeInt) == 4)
{
ConvOvf<NativeInt, INT_MIN, INT_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
else
{
assert(sizeof(NativeInt) == 8);
ConvOvf<NativeInt, _I64_MIN, _I64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
break;
case CEE_CONV_OVF_U:
if (sizeof(NativeUInt) == 4)
{
ConvOvf<NativeUInt, 0, UINT_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
else
{
assert(sizeof(NativeUInt) == 8);
ConvOvf<NativeUInt, 0, _UI64_MAX, /*TCanHoldPtr*/true, CORINFO_TYPE_NATIVEINT>();
}
break;
case CEE_ADD_OVF:
BinaryArithOvfOp<BA_Add, /*asUnsigned*/false>();
break;
case CEE_ADD_OVF_UN:
BinaryArithOvfOp<BA_Add, /*asUnsigned*/true>();
break;
case CEE_MUL_OVF:
BinaryArithOvfOp<BA_Mul, /*asUnsigned*/false>();
break;
case CEE_MUL_OVF_UN:
BinaryArithOvfOp<BA_Mul, /*asUnsigned*/true>();
break;
case CEE_SUB_OVF:
BinaryArithOvfOp<BA_Sub, /*asUnsigned*/false>();
break;
case CEE_SUB_OVF_UN:
BinaryArithOvfOp<BA_Sub, /*asUnsigned*/true>();
break;
case CEE_ENDFINALLY:
// We have just ended a finally.
// If we were called during exception dispatch,
// rethrow the exception on our way out.
if (m_leaveInfoStack.IsEmpty())
{
Object* finallyException = NULL;
{
GCX_FORBID();
assert(m_inFlightException != NULL);
finallyException = m_inFlightException;
INTERPLOG("endfinally handling for %s, %p, %p\n", methName, m_methInfo, finallyException);
m_inFlightException = NULL;
}
COMPlusThrow(ObjectToOBJECTREF(finallyException));
UNREACHABLE();
}
// Otherwise, see if there's another finally block to
// execute as part of processing the current LEAVE...
else if (!SearchForCoveringFinally())
{
// No, there isn't -- go to the leave target.
assert(!m_leaveInfoStack.IsEmpty());
LeaveInfo li = m_leaveInfoStack.Pop();
ExecuteBranch(li.m_target);
}
// Yes, there, is, and SearchForCoveringFinally set us up to start executing it.
continue; // Skip the default m_ILCodePtr++ at bottom of loop.
case CEE_STIND_I:
StInd<NativeInt>();
break;
case CEE_CONV_U:
Conv<NativeUInt, /*TIsUnsigned*/true, /*TCanHoldPtr*/true, /*TIsShort*/false, CORINFO_TYPE_NATIVEINT>();
break;
case CEE_PREFIX7:
NYI_INTERP("Unimplemented opcode: CEE_PREFIX7");
break;
case CEE_PREFIX6:
NYI_INTERP("Unimplemented opcode: CEE_PREFIX6");
break;
case CEE_PREFIX5:
NYI_INTERP("Unimplemented opcode: CEE_PREFIX5");
break;
case CEE_PREFIX4:
NYI_INTERP("Unimplemented opcode: CEE_PREFIX4");
break;
case CEE_PREFIX3:
NYI_INTERP("Unimplemented opcode: CEE_PREFIX3");
break;
case CEE_PREFIX2:
NYI_INTERP("Unimplemented opcode: CEE_PREFIX2");
break;
case CEE_PREFIX1:
// This is the prefix for all the 2-byte opcodes.
// Figure out the second byte of the 2-byte opcode.
ops = *(m_ILCodePtr + 1);
#if INTERP_ILINSTR_PROFILE
// Take one away from PREFIX1, which we won't count.
InterlockedDecrement(&s_ILInstrExecs[CEE_PREFIX1]);
// Credit instead to the 2-byte instruction index.
InterlockedIncrement(&s_ILInstr2ByteExecs[ops]);
#endif // INTERP_ILINSTR_PROFILE
switch (ops)
{
case TWOBYTE_CEE_ARGLIST:
// NYI_INTERP("Unimplemented opcode: TWOBYTE_CEE_ARGLIST");
assert(m_methInfo->m_varArgHandleArgNum != NO_VA_ARGNUM);
LdArgA(m_methInfo->m_varArgHandleArgNum);
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_CEQ:
CompareOp<CO_EQ>();
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_CGT:
CompareOp<CO_GT>();
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_CGT_UN:
CompareOp<CO_GT_UN>();
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_CLT:
CompareOp<CO_LT>();
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_CLT_UN:
CompareOp<CO_LT_UN>();
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_LDARG:
m_ILCodePtr += 2;
argNums = getU2LittleEndian(m_ILCodePtr);
LdArg(argNums);
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_LDARGA:
m_ILCodePtr += 2;
argNums = getU2LittleEndian(m_ILCodePtr);
LdArgA(argNums);
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_STARG:
m_ILCodePtr += 2;
argNums = getU2LittleEndian(m_ILCodePtr);
StArg(argNums);
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_LDLOC:
m_ILCodePtr += 2;
argNums = getU2LittleEndian(m_ILCodePtr);
LdLoc(argNums);
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_LDLOCA:
m_ILCodePtr += 2;
argNums = getU2LittleEndian(m_ILCodePtr);
LdLocA(argNums);
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_STLOC:
m_ILCodePtr += 2;
argNums = getU2LittleEndian(m_ILCodePtr);
StLoc(argNums);
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_CONSTRAINED:
RecordConstrainedCall();
break;
case TWOBYTE_CEE_VOLATILE:
// Set a flag that causes a memory barrier to be associated with the next load or store.
m_volatileFlag = true;
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_LDFTN:
LdFtn();
break;
case TWOBYTE_CEE_INITOBJ:
InitObj();
break;
case TWOBYTE_CEE_LOCALLOC:
LocAlloc();
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_LDVIRTFTN:
LdVirtFtn();
break;
case TWOBYTE_CEE_SIZEOF:
Sizeof();
break;
case TWOBYTE_CEE_RETHROW:
Rethrow();
break;
case TWOBYTE_CEE_READONLY:
m_readonlyFlag = true;
m_ILCodePtr += 2;
// A comment in importer.cpp indicates that READONLY may also apply to calls. We'll see.
_ASSERTE_MSG(*m_ILCodePtr == CEE_LDELEMA, "According to the ECMA spec, READONLY may only precede LDELEMA");
break;
case TWOBYTE_CEE_INITBLK:
InitBlk();
break;
case TWOBYTE_CEE_CPBLK:
CpBlk();
break;
case TWOBYTE_CEE_ENDFILTER:
EndFilter();
break;
case TWOBYTE_CEE_UNALIGNED:
// Nothing to do here.
m_ILCodePtr += 3;
break;
case TWOBYTE_CEE_TAILCALL:
// TODO: Needs revisiting when implementing tail call.
// NYI_INTERP("Unimplemented opcode: TWOBYTE_CEE_TAILCALL");
m_ILCodePtr += 2;
break;
case TWOBYTE_CEE_REFANYTYPE:
RefanyType();
break;
default:
UNREACHABLE();
break;
}
continue;
case CEE_PREFIXREF:
NYI_INTERP("Unimplemented opcode: CEE_PREFIXREF");
m_ILCodePtr++;
continue;
default:
UNREACHABLE();
continue;
}
m_ILCodePtr++;
}
ExitEvalLoop:;
INTERPLOG("DONE %d, %s\n", m_methInfo->m_stubNum, m_methInfo->m_methName);
}
EX_CATCH
{
INTERPLOG("EXCEPTION %d (throw), %s\n", m_methInfo->m_stubNum, m_methInfo->m_methName);
bool handleException = false;
OBJECTREF orThrowable = NULL;
GCX_COOP_NO_DTOR();
orThrowable = GET_THROWABLE();
if (m_filterNextScan != 0)
{
// We are in the middle of a filter scan and an exception is thrown inside
// a filter. We are supposed to swallow it and assume the filter did not
// handle the exception.
m_curStackHt = 0;
m_largeStructOperandStackHt = 0;
LdIcon(0);
EndFilter();
handleException = true;
}
else
{
// orThrowable must be protected. MethodHandlesException() will place orThrowable
// into the operand stack (a permanently protected area) if it returns true.
GCPROTECT_BEGIN(orThrowable);
handleException = MethodHandlesException(orThrowable);
GCPROTECT_END();
}
if (handleException)
{
GetThread()->SafeSetThrowables(orThrowable
DEBUG_ARG(ThreadExceptionState::STEC_CurrentTrackerEqualNullOkForInterpreter));
goto EvalLoop;
}
else
{
INTERPLOG("EXCEPTION %d (rethrow), %s\n", m_methInfo->m_stubNum, m_methInfo->m_methName);
EX_RETHROW;
}
}
EX_END_CATCH(RethrowTransientExceptions)
}
#ifdef _MSC_VER
#pragma optimize("", on)
#endif
void Interpreter::EndFilter()
{
unsigned handles = OpStackGet<unsigned>(0);
// If the filter decides to handle the exception, then go to the handler offset.
if (handles)
{
// We decided to handle the exception, so give all EH entries a chance to
// handle future exceptions. Clear scan.
m_filterNextScan = 0;
ExecuteBranch(m_methInfo->m_ILCode + m_filterHandlerOffset);
}
// The filter decided not to handle the exception, ask if there is some other filter
// lined up to try to handle it or some other catch/finally handlers will handle it.
// If no one handles the exception, rethrow and be done with it.
else
{
bool handlesEx = false;
{
OBJECTREF orThrowable = ObjectToOBJECTREF(m_inFlightException);
GCPROTECT_BEGIN(orThrowable);
handlesEx = MethodHandlesException(orThrowable);
GCPROTECT_END();
}
if (!handlesEx)
{
// Just clear scan before rethrowing to give any EH entry a chance to handle
// the "rethrow".
m_filterNextScan = 0;
Object* filterException = NULL;
{
GCX_FORBID();
assert(m_inFlightException != NULL);
filterException = m_inFlightException;
INTERPLOG("endfilter handling for %s, %p, %p\n", m_methInfo->m_methName, m_methInfo, filterException);
m_inFlightException = NULL;
}
COMPlusThrow(ObjectToOBJECTREF(filterException));
UNREACHABLE();
}
else
{
// Let it do another round of filter:end-filter or handler block.
// During the next end filter, we will reuse m_filterNextScan and
// continue searching where we left off. Note however, while searching,
// any of the filters could throw an exception. But this is supposed to
// be swallowed and endfilter should be called with a value of 0 on the
// stack.
}
}
}
bool Interpreter::MethodHandlesException(OBJECTREF orThrowable)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
bool handlesEx = false;
if (orThrowable != NULL)
{
PTR_Thread pCurThread = GetThread();
// Don't catch ThreadAbort and other uncatchable exceptions
if (!IsUncatchable(&orThrowable))
{
// Does the current method catch this? The clauses are defined by offsets, so get that.
// However, if we are in the middle of a filter scan, make sure we get the offset of the
// excepting code, rather than the offset of the filter body.
DWORD curOffset = (m_filterNextScan != 0) ? m_filterExcILOffset : CurOffset();
TypeHandle orThrowableTH = TypeHandle(orThrowable->GetMethodTable());
GCPROTECT_BEGIN(orThrowable);
GCX_PREEMP();
// Perform a filter scan or regular walk of the EH Table. Filter scan is performed when
// we are evaluating a series of filters to handle the exception until the first handler
// (filter's or otherwise) that will handle the exception.
for (unsigned XTnum = m_filterNextScan; XTnum < m_methInfo->m_ehClauseCount; XTnum++)
{
CORINFO_EH_CLAUSE clause;
m_interpCeeInfo.getEHinfo(m_methInfo->m_method, XTnum, &clause);
assert(clause.HandlerLength != (unsigned)-1); // @DEPRECATED
// First, is the current offset in the try block?
if (clause.TryOffset <= curOffset && curOffset < clause.TryOffset + clause.TryLength)
{
unsigned handlerOffset = 0;
// CORINFO_EH_CLAUSE_NONE represents 'catch' blocks
if (clause.Flags == CORINFO_EH_CLAUSE_NONE)
{
// Now, does the catch block handle the thrown exception type?
CORINFO_CLASS_HANDLE excType = FindClass(clause.ClassToken InterpTracingArg(RTK_CheckHandlesException));
if (ExceptionIsOfRightType(TypeHandle::FromPtr(excType), orThrowableTH))
{
GCX_COOP();
// Push the exception object onto the operand stack.
OpStackSet<OBJECTREF>(0, orThrowable);
OpStackTypeSet(0, InterpreterType(CORINFO_TYPE_CLASS));
m_curStackHt = 1;
m_largeStructOperandStackHt = 0;
handlerOffset = clause.HandlerOffset;
handlesEx = true;
m_filterNextScan = 0;
}
else
{
GCX_COOP();
// Handle a wrapped exception.
OBJECTREF orUnwrapped = PossiblyUnwrapThrowable(orThrowable, GetMethodDesc()->GetAssembly());
if (ExceptionIsOfRightType(TypeHandle::FromPtr(excType), orUnwrapped->GetTrueTypeHandle()))
{
// Push the exception object onto the operand stack.
OpStackSet<OBJECTREF>(0, orUnwrapped);
OpStackTypeSet(0, InterpreterType(CORINFO_TYPE_CLASS));
m_curStackHt = 1;
m_largeStructOperandStackHt = 0;
handlerOffset = clause.HandlerOffset;
handlesEx = true;
m_filterNextScan = 0;
}
}
}
else if (clause.Flags == CORINFO_EH_CLAUSE_FILTER)
{
GCX_COOP();
// Push the exception object onto the operand stack.
OpStackSet<OBJECTREF>(0, orThrowable);
OpStackTypeSet(0, InterpreterType(CORINFO_TYPE_CLASS));
m_curStackHt = 1;
m_largeStructOperandStackHt = 0;
handlerOffset = clause.FilterOffset;
m_inFlightException = OBJECTREFToObject(orThrowable);
handlesEx = true;
m_filterHandlerOffset = clause.HandlerOffset;
m_filterNextScan = XTnum + 1;
m_filterExcILOffset = curOffset;
}
else if (clause.Flags == CORINFO_EH_CLAUSE_FAULT ||
clause.Flags == CORINFO_EH_CLAUSE_FINALLY)
{
GCX_COOP();
// Save the exception object to rethrow.
m_inFlightException = OBJECTREFToObject(orThrowable);
// Empty the operand stack.
m_curStackHt = 0;
m_largeStructOperandStackHt = 0;
handlerOffset = clause.HandlerOffset;
handlesEx = true;
m_filterNextScan = 0;
}
// Reset the interpreter loop in preparation of calling the handler.
if (handlesEx)
{
// Set the IL offset of the handler.
ExecuteBranch(m_methInfo->m_ILCode + handlerOffset);
// If an exception occurs while attempting to leave a protected scope,
// we empty the 'leave' info stack upon entering the handler.
while (!m_leaveInfoStack.IsEmpty())
{
m_leaveInfoStack.Pop();
}
// Some things are set up before a call, and must be cleared on an exception caught be the caller.
// A method that returns a struct allocates local space for the return value, and "registers" that
// space and the type so that it's scanned if a GC happens. "Unregister" it if we throw an exception
// in the call, and handle it in the caller. (If it's not handled by the caller, the Interpreter is
// deallocated, so it's value doesn't matter.)
m_structRetValITPtr = NULL;
m_callThisArg = NULL;
m_argsSize = 0;
break;
}
}
}
GCPROTECT_END();
}
if (!handlesEx)
{
DoMonitorExitWork();
}
}
return handlesEx;
}
static unsigned OpFormatExtraSize(opcode_format_t format) {
switch (format)
{
case InlineNone:
return 0;
case InlineVar:
return 2;
case InlineI:
case InlineBrTarget:
case InlineMethod:
case InlineField:
case InlineType:
case InlineString:
case InlineSig:
case InlineRVA:
case InlineTok:
case ShortInlineR:
return 4;
case InlineR:
case InlineI8:
return 8;
case InlineSwitch:
return 0; // We'll handle this specially.
case ShortInlineVar:
case ShortInlineI:
case ShortInlineBrTarget:
return 1;
default:
assert(false);
return 0;
}
}
static unsigned opSizes1Byte[CEE_COUNT];
static bool opSizes1ByteInit = false;
static void OpSizes1ByteInit()
{
if (opSizes1ByteInit) return;
#define OPDEF(name, stringname, stackpop, stackpush, params, kind, len, byte1, byte2, ctrl) \
opSizes1Byte[name] = len + OpFormatExtraSize(params);
#include "opcode.def"
#undef OPDEF
opSizes1ByteInit = true;
};
// static
bool Interpreter::MethodMayHaveLoop(BYTE* ilCode, unsigned codeSize)
{
OpSizes1ByteInit();
int delta;
BYTE* ilCodeLim = ilCode + codeSize;
while (ilCode < ilCodeLim)
{
unsigned op = *ilCode;
switch (op)
{
case CEE_BR_S: case CEE_BRFALSE_S: case CEE_BRTRUE_S:
case CEE_BEQ_S: case CEE_BGE_S: case CEE_BGT_S: case CEE_BLE_S: case CEE_BLT_S:
case CEE_BNE_UN_S: case CEE_BGE_UN_S: case CEE_BGT_UN_S: case CEE_BLE_UN_S: case CEE_BLT_UN_S:
case CEE_LEAVE_S:
delta = getI1(ilCode + 1);
if (delta < 0) return true;
ilCode += 2;
break;
case CEE_BR: case CEE_BRFALSE: case CEE_BRTRUE:
case CEE_BEQ: case CEE_BGE: case CEE_BGT: case CEE_BLE: case CEE_BLT:
case CEE_BNE_UN: case CEE_BGE_UN: case CEE_BGT_UN: case CEE_BLE_UN: case CEE_BLT_UN:
case CEE_LEAVE:
delta = getI4LittleEndian(ilCode + 1);
if (delta < 0) return true;
ilCode += 5;
break;
case CEE_SWITCH:
{
UINT32 n = getU4LittleEndian(ilCode + 1);
UINT32 instrSize = 1 + (n + 1)*4;
for (unsigned i = 0; i < n; i++) {
delta = getI4LittleEndian(ilCode + (5 + i * 4));
if (delta < 0) return true;
}
ilCode += instrSize;
break;
}
case CEE_PREFIX1:
op = *(ilCode + 1) + 0x100;
assert(op < CEE_COUNT); // Bounds check for below.
// deliberate fall-through here.
default:
// For the rest of the 1-byte instructions, we'll use a table-driven approach.
ilCode += opSizes1Byte[op];
break;
}
}
return false;
}
void Interpreter::BackwardsBranchActions(int offset)
{
// TODO: Figure out how to do a GC poll.
}
bool Interpreter::SearchForCoveringFinally()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_ANY;
} CONTRACTL_END;
_ASSERTE_MSG(!m_leaveInfoStack.IsEmpty(), "precondition");
LeaveInfo& li = m_leaveInfoStack.PeekRef();
GCX_PREEMP();
for (unsigned XTnum = li.m_nextEHIndex; XTnum < m_methInfo->m_ehClauseCount; XTnum++)
{
CORINFO_EH_CLAUSE clause;
m_interpCeeInfo.getEHinfo(m_methInfo->m_method, XTnum, &clause);
assert(clause.HandlerLength != (unsigned)-1); // @DEPRECATED
// First, is the offset of the leave instruction in the try block?
unsigned tryEndOffset = clause.TryOffset + clause.TryLength;
if (clause.TryOffset <= li.m_offset && li.m_offset < tryEndOffset)
{
// Yes: is it a finally, and is its target outside the try block?
size_t targOffset = (li.m_target - m_methInfo->m_ILCode);
if (clause.Flags == CORINFO_EH_CLAUSE_FINALLY
&& !(clause.TryOffset <= targOffset && targOffset < tryEndOffset))
{
m_ILCodePtr = m_methInfo->m_ILCode + clause.HandlerOffset;
li.m_nextEHIndex = XTnum + 1;
return true;
}
}
}
// Caller will handle popping the leave info stack.
return false;
}
// static
void Interpreter::GCScanRoots(promote_func* pf, ScanContext* sc, void* interp0)
{
Interpreter* interp = reinterpret_cast<Interpreter*>(interp0);
interp->GCScanRoots(pf, sc);
}
void Interpreter::GCScanRoots(promote_func* pf, ScanContext* sc)
{
// Report inbound arguments, if the interpreter has not been invoked directly.
// (In the latter case, the arguments are reported by the calling method.)
if (!m_directCall)
{
for (unsigned i = 0; i < m_methInfo->m_numArgs; i++)
{
GCScanRootAtLoc(reinterpret_cast<Object**>(GetArgAddr(i)), GetArgType(i), pf, sc);
}
}
if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_hasThisArg>())
{
if (m_methInfo->GetFlag<InterpreterMethodInfo::Flag_thisArgIsObjPtr>())
{
GCScanRootAtLoc(&m_thisArg, InterpreterType(CORINFO_TYPE_CLASS), pf, sc);
}
else
{
GCScanRootAtLoc(&m_thisArg, InterpreterType(CORINFO_TYPE_BYREF), pf, sc);
}
}
// This is the "this" argument passed in to DoCallWork. (Note that we treat this as a byref; it
// might be, for a struct instance method, and this covers the object pointer case as well.)
GCScanRootAtLoc(reinterpret_cast<Object**>(&m_callThisArg), InterpreterType(CORINFO_TYPE_BYREF), pf, sc);
// Scan the exception object that we'll rethrow at the end of the finally block.
GCScanRootAtLoc(reinterpret_cast<Object**>(&m_inFlightException), InterpreterType(CORINFO_TYPE_CLASS), pf, sc);
// A retBufArg, may, in some cases, be a byref into the heap.
if (m_retBufArg != NULL)
{
GCScanRootAtLoc(reinterpret_cast<Object**>(&m_retBufArg), InterpreterType(CORINFO_TYPE_BYREF), pf, sc);
}
if (m_structRetValITPtr != NULL)
{
GCScanRootAtLoc(reinterpret_cast<Object**>(m_structRetValTempSpace), *m_structRetValITPtr, pf, sc);
}
// We'll conservatively assume that we might have a security object.
GCScanRootAtLoc(reinterpret_cast<Object**>(&m_securityObject), InterpreterType(CORINFO_TYPE_CLASS), pf, sc);
// Do locals.
for (unsigned i = 0; i < m_methInfo->m_numLocals; i++)
{
InterpreterType it = m_methInfo->m_localDescs[i].m_type;
void* localPtr = NULL;
if (it.IsLargeStruct(&m_interpCeeInfo))
{
void* structPtr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(i)), sizeof(void**));
localPtr = *reinterpret_cast<void**>(structPtr);
}
else
{
localPtr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(i)), it.Size(&m_interpCeeInfo));
}
GCScanRootAtLoc(reinterpret_cast<Object**>(localPtr), it, pf, sc, m_methInfo->GetPinningBit(i));
}
// Do current ostack.
for (unsigned i = 0; i < m_curStackHt; i++)
{
InterpreterType it = OpStackTypeGet(i);
if (it.IsLargeStruct(&m_interpCeeInfo))
{
Object** structPtr = reinterpret_cast<Object**>(OpStackGet<void*>(i));
// If the ostack value is a pointer to a local var value, don't scan, since we already
// scanned the variable value above.
if (!IsInLargeStructLocalArea(structPtr))
{
GCScanRootAtLoc(structPtr, it, pf, sc);
}
}
else
{
void* stackPtr = OpStackGetAddr(i, it.Size(&m_interpCeeInfo));
GCScanRootAtLoc(reinterpret_cast<Object**>(stackPtr), it, pf, sc);
}
}
// Any outgoing arguments for a call in progress.
for (unsigned i = 0; i < m_argsSize; i++)
{
// If a call has a large struct argument, we'll have pushed a pointer to the entry for that argument on the
// largeStructStack of the current Interpreter. That will be scanned by the code above, so just skip it.
InterpreterType undef(CORINFO_TYPE_UNDEF);
InterpreterType it = m_argTypes[i];
if (it != undef && !it.IsLargeStruct(&m_interpCeeInfo))
{
BYTE* argPtr = ArgSlotEndianessFixup(&m_args[i], it.Size(&m_interpCeeInfo));
GCScanRootAtLoc(reinterpret_cast<Object**>(argPtr), it, pf, sc);
}
}
}
void Interpreter::GCScanRootAtLoc(Object** loc, InterpreterType it, promote_func* pf, ScanContext* sc, bool pinningRef)
{
switch (it.ToCorInfoType())
{
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_STRING:
{
DWORD flags = 0;
if (pinningRef) flags |= GC_CALL_PINNED;
(*pf)(loc, sc, flags);
}
break;
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_REFANY:
{
DWORD flags = GC_CALL_INTERIOR;
if (pinningRef) flags |= GC_CALL_PINNED;
(*pf)(loc, sc, flags);
}
break;
case CORINFO_TYPE_VALUECLASS:
assert(!pinningRef);
GCScanValueClassRootAtLoc(loc, it.ToClassHandle(), pf, sc);
break;
default:
assert(!pinningRef);
break;
}
}
void Interpreter::GCScanValueClassRootAtLoc(Object** loc, CORINFO_CLASS_HANDLE valueClsHnd, promote_func* pf, ScanContext* sc)
{
MethodTable* valClsMT = GetMethodTableFromClsHnd(valueClsHnd);
ReportPointersFromValueType(pf, sc, valClsMT, loc);
}
// Returns "true" iff "cit" is "stack-normal": all integer types with byte size less than 4
// are folded to CORINFO_TYPE_INT; all remaining unsigned types are folded to their signed counterparts.
bool IsStackNormalType(CorInfoType cit)
{
LIMITED_METHOD_CONTRACT;
switch (cit)
{
case CORINFO_TYPE_UNDEF:
case CORINFO_TYPE_VOID:
case CORINFO_TYPE_BOOL:
case CORINFO_TYPE_CHAR:
case CORINFO_TYPE_BYTE:
case CORINFO_TYPE_UBYTE:
case CORINFO_TYPE_SHORT:
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_UINT:
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_ULONG:
case CORINFO_TYPE_VAR:
case CORINFO_TYPE_STRING:
case CORINFO_TYPE_PTR:
return false;
case CORINFO_TYPE_INT:
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_VALUECLASS:
case CORINFO_TYPE_REFANY:
// I chose to consider both float and double stack-normal; together these comprise
// the "F" type of the ECMA spec. This means I have to consider these to freely
// interconvert.
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
return true;
default:
UNREACHABLE();
}
}
CorInfoType CorInfoTypeStackNormalize(CorInfoType cit)
{
LIMITED_METHOD_CONTRACT;
switch (cit)
{
case CORINFO_TYPE_UNDEF:
return CORINFO_TYPE_UNDEF;
case CORINFO_TYPE_VOID:
case CORINFO_TYPE_VAR:
_ASSERTE_MSG(false, "Type that cannot be on the ostack.");
return CORINFO_TYPE_UNDEF;
case CORINFO_TYPE_BOOL:
case CORINFO_TYPE_CHAR:
case CORINFO_TYPE_BYTE:
case CORINFO_TYPE_UBYTE:
case CORINFO_TYPE_SHORT:
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_UINT:
return CORINFO_TYPE_INT;
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_PTR:
return CORINFO_TYPE_NATIVEINT;
case CORINFO_TYPE_ULONG:
return CORINFO_TYPE_LONG;
case CORINFO_TYPE_STRING:
return CORINFO_TYPE_CLASS;
case CORINFO_TYPE_INT:
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_VALUECLASS:
case CORINFO_TYPE_REFANY:
// I chose to consider both float and double stack-normal; together these comprise
// the "F" type of the ECMA spec. This means I have to consider these to freely
// interconvert.
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
assert(IsStackNormalType(cit));
return cit;
default:
UNREACHABLE();
}
}
InterpreterType InterpreterType::StackNormalize() const
{
LIMITED_METHOD_CONTRACT;
switch (ToCorInfoType())
{
case CORINFO_TYPE_BOOL:
case CORINFO_TYPE_CHAR:
case CORINFO_TYPE_BYTE:
case CORINFO_TYPE_UBYTE:
case CORINFO_TYPE_SHORT:
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_UINT:
return InterpreterType(CORINFO_TYPE_INT);
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_PTR:
return InterpreterType(CORINFO_TYPE_NATIVEINT);
case CORINFO_TYPE_ULONG:
return InterpreterType(CORINFO_TYPE_LONG);
case CORINFO_TYPE_STRING:
return InterpreterType(CORINFO_TYPE_CLASS);
case CORINFO_TYPE_INT:
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_VALUECLASS:
case CORINFO_TYPE_REFANY:
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
return *const_cast<InterpreterType*>(this);
case CORINFO_TYPE_UNDEF:
case CORINFO_TYPE_VOID:
case CORINFO_TYPE_VAR:
default:
_ASSERTE_MSG(false, "should not reach here");
return *const_cast<InterpreterType*>(this);
}
}
#ifdef _DEBUG
bool InterpreterType::MatchesWork(const InterpreterType it2, CEEInfo* info) const
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
if (*this == it2) return true;
// Otherwise...
CorInfoType cit1 = ToCorInfoType();
CorInfoType cit2 = it2.ToCorInfoType();
GCX_PREEMP();
// An approximation: valueclasses of the same size match.
if (cit1 == CORINFO_TYPE_VALUECLASS &&
cit2 == CORINFO_TYPE_VALUECLASS &&
Size(info) == it2.Size(info))
{
return true;
}
// NativeInt matches byref. (In unsafe code).
if ((cit1 == CORINFO_TYPE_BYREF && cit2 == CORINFO_TYPE_NATIVEINT))
return true;
// apparently the VM may do the optimization of reporting the return type of a method that
// returns a struct of a single nativeint field *as* nativeint; and similarly with at least some other primitive types.
// So weaken this check to allow that.
// (The check is actually a little weaker still, since I don't want to crack the return type and make sure
// that it has only a single nativeint member -- so I just ensure that the total size is correct).
switch (cit1)
{
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_NATIVEUINT:
assert(sizeof(NativeInt) == sizeof(NativeUInt));
if (it2.Size(info) == sizeof(NativeInt))
return true;
break;
case CORINFO_TYPE_INT:
case CORINFO_TYPE_UINT:
assert(sizeof(INT32) == sizeof(UINT32));
if (it2.Size(info) == sizeof(INT32))
return true;
break;
default:
break;
}
// See if the second is a value type synonym for a primitive.
if (cit2 == CORINFO_TYPE_VALUECLASS)
{
CorInfoType cit2prim = info->getTypeForPrimitiveValueClass(it2.ToClassHandle());
if (cit2prim != CORINFO_TYPE_UNDEF)
{
InterpreterType it2prim(cit2prim);
if (*this == it2prim.StackNormalize())
return true;
}
}
// Otherwise...
return false;
}
#endif // _DEBUG
// Static
size_t CorInfoTypeSizeArray[] =
{
/*CORINFO_TYPE_UNDEF = 0x0*/0,
/*CORINFO_TYPE_VOID = 0x1*/0,
/*CORINFO_TYPE_BOOL = 0x2*/1,
/*CORINFO_TYPE_CHAR = 0x3*/2,
/*CORINFO_TYPE_BYTE = 0x4*/1,
/*CORINFO_TYPE_UBYTE = 0x5*/1,
/*CORINFO_TYPE_SHORT = 0x6*/2,
/*CORINFO_TYPE_USHORT = 0x7*/2,
/*CORINFO_TYPE_INT = 0x8*/4,
/*CORINFO_TYPE_UINT = 0x9*/4,
/*CORINFO_TYPE_LONG = 0xa*/8,
/*CORINFO_TYPE_ULONG = 0xb*/8,
/*CORINFO_TYPE_NATIVEINT = 0xc*/sizeof(void*),
/*CORINFO_TYPE_NATIVEUINT = 0xd*/sizeof(void*),
/*CORINFO_TYPE_FLOAT = 0xe*/4,
/*CORINFO_TYPE_DOUBLE = 0xf*/8,
/*CORINFO_TYPE_STRING = 0x10*/sizeof(void*),
/*CORINFO_TYPE_PTR = 0x11*/sizeof(void*),
/*CORINFO_TYPE_BYREF = 0x12*/sizeof(void*),
/*CORINFO_TYPE_VALUECLASS = 0x13*/0,
/*CORINFO_TYPE_CLASS = 0x14*/sizeof(void*),
/*CORINFO_TYPE_REFANY = 0x15*/sizeof(void*)*2,
/*CORINFO_TYPE_VAR = 0x16*/0,
};
bool CorInfoTypeIsUnsigned(CorInfoType cit)
{
LIMITED_METHOD_CONTRACT;
switch (cit)
{
case CORINFO_TYPE_UINT:
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_ULONG:
case CORINFO_TYPE_UBYTE:
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_CHAR:
return true;
default:
return false;
}
}
bool CorInfoTypeIsIntegral(CorInfoType cit)
{
LIMITED_METHOD_CONTRACT;
switch (cit)
{
case CORINFO_TYPE_UINT:
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_ULONG:
case CORINFO_TYPE_UBYTE:
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_INT:
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_BYTE:
case CORINFO_TYPE_BOOL:
case CORINFO_TYPE_SHORT:
return true;
default:
return false;
}
}
bool CorInfoTypeIsFloatingPoint(CorInfoType cit)
{
return cit == CORINFO_TYPE_FLOAT || cit == CORINFO_TYPE_DOUBLE;
}
bool CorElemTypeIsUnsigned(CorElementType cet)
{
LIMITED_METHOD_CONTRACT;
switch (cet)
{
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_U2:
case ELEMENT_TYPE_U4:
case ELEMENT_TYPE_U8:
case ELEMENT_TYPE_U:
return true;
default:
return false;
}
}
bool CorInfoTypeIsPointer(CorInfoType cit)
{
LIMITED_METHOD_CONTRACT;
switch (cit)
{
case CORINFO_TYPE_PTR:
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_NATIVEUINT:
return true;
// It seems like the ECMA spec doesn't allow this, but (at least) the managed C++
// compiler expects the explicitly-sized pointer type of the platform pointer size to work:
case CORINFO_TYPE_INT:
case CORINFO_TYPE_UINT:
return sizeof(NativeInt) == sizeof(INT32);
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_ULONG:
return sizeof(NativeInt) == sizeof(INT64);
default:
return false;
}
}
void Interpreter::LdArg(int argNum)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
LdFromMemAddr(GetArgAddr(argNum), GetArgType(argNum));
}
void Interpreter::LdArgA(int argNum)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_BYREF));
OpStackSet<void*>(m_curStackHt, reinterpret_cast<void*>(GetArgAddr(argNum)));
m_curStackHt++;
}
void Interpreter::StArg(int argNum)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
StToLocalMemAddr(GetArgAddr(argNum), GetArgType(argNum));
}
void Interpreter::LdLocA(int locNum)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
InterpreterType tp = m_methInfo->m_localDescs[locNum].m_type;
void* addr;
if (tp.IsLargeStruct(&m_interpCeeInfo))
{
void* structPtr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(locNum)), sizeof(void**));
addr = *reinterpret_cast<void**>(structPtr);
}
else
{
addr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(locNum)), tp.Size(&m_interpCeeInfo));
}
// The "addr" above, while a byref, is never a heap pointer, so we're robust if
// any of these were to cause a GC.
OpStackSet<void*>(m_curStackHt, addr);
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_BYREF));
m_curStackHt++;
}
void Interpreter::LdIcon(INT32 c)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_INT));
OpStackSet<INT32>(m_curStackHt, c);
m_curStackHt++;
}
void Interpreter::LdR4con(INT32 c)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_FLOAT));
OpStackSet<INT32>(m_curStackHt, c);
m_curStackHt++;
}
void Interpreter::LdLcon(INT64 c)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_LONG));
OpStackSet<INT64>(m_curStackHt, c);
m_curStackHt++;
}
void Interpreter::LdR8con(INT64 c)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_DOUBLE));
OpStackSet<INT64>(m_curStackHt, c);
m_curStackHt++;
}
void Interpreter::LdNull()
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_CLASS));
OpStackSet<void*>(m_curStackHt, NULL);
m_curStackHt++;
}
template<typename T, CorInfoType cit>
void Interpreter::LdInd()
{
assert(TOSIsPtr());
assert(IsStackNormalType(cit));
unsigned curStackInd = m_curStackHt-1;
T* ptr = OpStackGet<T*>(curStackInd);
ThrowOnInvalidPointer(ptr);
OpStackSet<T>(curStackInd, *ptr);
OpStackTypeSet(curStackInd, InterpreterType(cit));
BarrierIfVolatile();
}
template<typename T, bool isUnsigned>
void Interpreter::LdIndShort()
{
assert(TOSIsPtr());
assert(sizeof(T) < 4);
unsigned curStackInd = m_curStackHt-1;
T* ptr = OpStackGet<T*>(curStackInd);
ThrowOnInvalidPointer(ptr);
if (isUnsigned)
{
OpStackSet<UINT32>(curStackInd, *ptr);
}
else
{
OpStackSet<INT32>(curStackInd, *ptr);
}
// All short integers are normalized to INT as their stack type.
OpStackTypeSet(curStackInd, InterpreterType(CORINFO_TYPE_INT));
BarrierIfVolatile();
}
template<typename T>
void Interpreter::StInd()
{
assert(m_curStackHt >= 2);
assert(CorInfoTypeIsPointer(OpStackTypeGet(m_curStackHt-2).ToCorInfoType()));
BarrierIfVolatile();
unsigned stackInd0 = m_curStackHt-2;
unsigned stackInd1 = m_curStackHt-1;
T val = OpStackGet<T>(stackInd1);
T* ptr = OpStackGet<T*>(stackInd0);
ThrowOnInvalidPointer(ptr);
*ptr = val;
m_curStackHt -= 2;
#ifdef _DEBUG
if (s_TraceInterpreterILFlag.val(CLRConfig::INTERNAL_TraceInterpreterIL) &&
IsInLocalArea(ptr))
{
PrintLocals();
}
#endif // _DEBUG
}
void Interpreter::StInd_Ref()
{
assert(m_curStackHt >= 2);
assert(CorInfoTypeIsPointer(OpStackTypeGet(m_curStackHt-2).ToCorInfoType()));
BarrierIfVolatile();
unsigned stackInd0 = m_curStackHt-2;
unsigned stackInd1 = m_curStackHt-1;
OBJECTREF val = ObjectToOBJECTREF(OpStackGet<Object*>(stackInd1));
OBJECTREF* ptr = OpStackGet<OBJECTREF*>(stackInd0);
ThrowOnInvalidPointer(ptr);
SetObjectReferenceUnchecked(ptr, val);
m_curStackHt -= 2;
#ifdef _DEBUG
if (s_TraceInterpreterILFlag.val(CLRConfig::INTERNAL_TraceInterpreterIL) &&
IsInLocalArea(ptr))
{
PrintLocals();
}
#endif // _DEBUG
}
template<int op>
void Interpreter::BinaryArithOp()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned op1idx = m_curStackHt - 2;
unsigned op2idx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(op1idx);
assert(IsStackNormalType(t1.ToCorInfoType()));
// Looking at the generated code, it does seem to save some instructions to use the "shifted
// types," though the effect on end-to-end time is variable. So I'll leave it set.
InterpreterType t2 = OpStackTypeGet(op2idx);
assert(IsStackNormalType(t2.ToCorInfoType()));
// In all cases belows, since "op" is compile-time constant, "if" chains on it should fold away.
switch (t1.ToCorInfoTypeShifted())
{
case CORINFO_TYPE_SHIFTED_INT:
if (t1 == t2)
{
// Int op Int = Int
INT32 val1 = OpStackGet<INT32>(op1idx);
INT32 val2 = OpStackGet<INT32>(op2idx);
BinaryArithOpWork<op, INT32, /*IsIntType*/true, CORINFO_TYPE_INT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
CorInfoTypeShifted cits2 = t2.ToCorInfoTypeShifted();
if (cits2 == CORINFO_TYPE_SHIFTED_NATIVEINT)
{
// Int op NativeInt = NativeInt
NativeInt val1 = static_cast<NativeInt>(OpStackGet<INT32>(op1idx));
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/false>(val1, val2);
}
else if (s_InterpreterLooseRules && cits2 == CORINFO_TYPE_SHIFTED_LONG)
{
// Int op Long = Long
INT64 val1 = static_cast<INT64>(OpStackGet<INT32>(op1idx));
INT64 val2 = OpStackGet<INT64>(op2idx);
BinaryArithOpWork<op, INT64, /*IsIntType*/true, CORINFO_TYPE_LONG, /*TypeIsUnchanged*/false>(val1, val2);
}
else if (cits2 == CORINFO_TYPE_SHIFTED_BYREF)
{
if (op == BA_Add || (s_InterpreterLooseRules && op == BA_Sub))
{
// Int + ByRef = ByRef
NativeInt val1 = static_cast<NativeInt>(OpStackGet<INT32>(op1idx));
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("Operation not permitted on int and managed pointer.");
}
}
else
{
VerificationError("Binary arithmetic operation type mismatch (int and ?)");
}
}
break;
case CORINFO_TYPE_SHIFTED_NATIVEINT:
{
NativeInt val1 = OpStackGet<NativeInt>(op1idx);
if (t1 == t2)
{
// NativeInt op NativeInt = NativeInt
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
CorInfoTypeShifted cits2 = t2.ToCorInfoTypeShifted();
if (cits2 == CORINFO_TYPE_SHIFTED_INT)
{
// NativeInt op Int = NativeInt
NativeInt val2 = static_cast<NativeInt>(OpStackGet<INT32>(op2idx));
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
// CLI spec does not allow adding a native int and an int64. So use loose rules.
else if (s_InterpreterLooseRules && cits2 == CORINFO_TYPE_SHIFTED_LONG)
{
// NativeInt op Int = NativeInt
NativeInt val2 = static_cast<NativeInt>(OpStackGet<INT64>(op2idx));
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
else if (cits2 == CORINFO_TYPE_SHIFTED_BYREF)
{
if (op == BA_Add || (s_InterpreterLooseRules && op == BA_Sub))
{
// NativeInt + ByRef = ByRef
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("Operation not permitted on native int and managed pointer.");
}
}
else
{
VerificationError("Binary arithmetic operation type mismatch (native int and ?)");
}
}
}
break;
case CORINFO_TYPE_SHIFTED_LONG:
{
bool looseLong = false;
#if defined(_AMD64_)
looseLong = (s_InterpreterLooseRules && (t2.ToCorInfoType() == CORINFO_TYPE_NATIVEINT ||
t2.ToCorInfoType() == CORINFO_TYPE_BYREF));
#endif
if (t1 == t2 || looseLong)
{
// Long op Long = Long
INT64 val1 = OpStackGet<INT64>(op1idx);
INT64 val2 = OpStackGet<INT64>(op2idx);
BinaryArithOpWork<op, INT64, /*IsIntType*/true, CORINFO_TYPE_LONG, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
VerificationError("Binary arithmetic operation type mismatch (long and ?)");
}
}
break;
case CORINFO_TYPE_SHIFTED_FLOAT:
{
if (t1 == t2)
{
// Float op Float = Float
float val1 = OpStackGet<float>(op1idx);
float val2 = OpStackGet<float>(op2idx);
BinaryArithOpWork<op, float, /*IsIntType*/false, CORINFO_TYPE_FLOAT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
CorInfoTypeShifted cits2 = t2.ToCorInfoTypeShifted();
if (cits2 == CORINFO_TYPE_SHIFTED_DOUBLE)
{
// Float op Double = Double
double val1 = static_cast<double>(OpStackGet<float>(op1idx));
double val2 = OpStackGet<double>(op2idx);
BinaryArithOpWork<op, double, /*IsIntType*/false, CORINFO_TYPE_DOUBLE, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("Binary arithmetic operation type mismatch (float and ?)");
}
}
}
break;
case CORINFO_TYPE_SHIFTED_DOUBLE:
{
if (t1 == t2)
{
// Double op Double = Double
double val1 = OpStackGet<double>(op1idx);
double val2 = OpStackGet<double>(op2idx);
BinaryArithOpWork<op, double, /*IsIntType*/false, CORINFO_TYPE_DOUBLE, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
CorInfoTypeShifted cits2 = t2.ToCorInfoTypeShifted();
if (cits2 == CORINFO_TYPE_SHIFTED_FLOAT)
{
// Double op Float = Double
double val1 = OpStackGet<double>(op1idx);
double val2 = static_cast<double>(OpStackGet<float>(op2idx));
BinaryArithOpWork<op, double, /*IsIntType*/false, CORINFO_TYPE_DOUBLE, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
VerificationError("Binary arithmetic operation type mismatch (double and ?)");
}
}
}
break;
case CORINFO_TYPE_SHIFTED_BYREF:
{
NativeInt val1 = OpStackGet<NativeInt>(op1idx);
CorInfoTypeShifted cits2 = t2.ToCorInfoTypeShifted();
if (cits2 == CORINFO_TYPE_SHIFTED_INT)
{
if (op == BA_Add || op == BA_Sub)
{
// ByRef +- Int = ByRef
NativeInt val2 = static_cast<NativeInt>(OpStackGet<INT32>(op2idx));
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
VerificationError("May only add/subtract managed pointer and integral value.");
}
}
else if (cits2 == CORINFO_TYPE_SHIFTED_NATIVEINT)
{
if (op == BA_Add || op == BA_Sub)
{
// ByRef +- NativeInt = ByRef
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
VerificationError("May only add/subtract managed pointer and integral value.");
}
}
else if (cits2 == CORINFO_TYPE_SHIFTED_BYREF)
{
if (op == BA_Sub)
{
// ByRef - ByRef = NativeInt
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("May only subtract managed pointer values.");
}
}
// CLI spec does not allow adding a native int and an int64. So use loose rules.
else if (s_InterpreterLooseRules && cits2 == CORINFO_TYPE_SHIFTED_LONG)
{
// NativeInt op Int = NativeInt
NativeInt val2 = static_cast<NativeInt>(OpStackGet<INT64>(op2idx));
BinaryArithOpWork<op, NativeInt, /*IsIntType*/true, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
VerificationError("Binary arithmetic operation not permitted on byref");
}
}
break;
case CORINFO_TYPE_SHIFTED_CLASS:
VerificationError("Can't do binary arithmetic on object references.");
break;
default:
_ASSERTE_MSG(false, "Non-stack-normal type on stack.");
}
// In all cases:
m_curStackHt--;
}
template<int op, bool asUnsigned>
void Interpreter::BinaryArithOvfOp()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned op1idx = m_curStackHt - 2;
unsigned op2idx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(op1idx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
InterpreterType t2 = OpStackTypeGet(op2idx);
CorInfoType cit2 = t2.ToCorInfoType();
assert(IsStackNormalType(cit2));
// In all cases belows, since "op" is compile-time constant, "if" chains on it should fold away.
switch (cit1)
{
case CORINFO_TYPE_INT:
if (cit2 == CORINFO_TYPE_INT)
{
if (asUnsigned)
{
// UnsignedInt op UnsignedInt = UnsignedInt
UINT32 val1 = OpStackGet<UINT32>(op1idx);
UINT32 val2 = OpStackGet<UINT32>(op2idx);
BinaryArithOvfOpWork<op, UINT32, CORINFO_TYPE_INT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
// Int op Int = Int
INT32 val1 = OpStackGet<INT32>(op1idx);
INT32 val2 = OpStackGet<INT32>(op2idx);
BinaryArithOvfOpWork<op, INT32, CORINFO_TYPE_INT, /*TypeIsUnchanged*/true>(val1, val2);
}
}
else if (cit2 == CORINFO_TYPE_NATIVEINT)
{
if (asUnsigned)
{
// UnsignedInt op UnsignedNativeInt = UnsignedNativeInt
NativeUInt val1 = static_cast<NativeUInt>(OpStackGet<UINT32>(op1idx));
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
// Int op NativeInt = NativeInt
NativeInt val1 = static_cast<NativeInt>(OpStackGet<INT32>(op1idx));
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOvfOpWork<op, NativeInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/false>(val1, val2);
}
}
else if (cit2 == CORINFO_TYPE_BYREF)
{
if (asUnsigned && op == BA_Add)
{
// UnsignedInt + ByRef = ByRef
NativeUInt val1 = static_cast<NativeUInt>(OpStackGet<UINT32>(op1idx));
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("Illegal arithmetic overflow operation for int and byref.");
}
}
else
{
VerificationError("Binary arithmetic overflow operation type mismatch (int and ?)");
}
break;
case CORINFO_TYPE_NATIVEINT:
if (cit2 == CORINFO_TYPE_INT)
{
if (asUnsigned)
{
// UnsignedNativeInt op UnsignedInt = UnsignedNativeInt
NativeUInt val1 = OpStackGet<NativeUInt>(op1idx);
NativeUInt val2 = static_cast<NativeUInt>(OpStackGet<UINT32>(op2idx));
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
// NativeInt op Int = NativeInt
NativeInt val1 = OpStackGet<NativeInt>(op1idx);
NativeInt val2 = static_cast<NativeInt>(OpStackGet<INT32>(op2idx));
BinaryArithOvfOpWork<op, NativeInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
}
else if (cit2 == CORINFO_TYPE_NATIVEINT)
{
if (asUnsigned)
{
// UnsignedNativeInt op UnsignedNativeInt = UnsignedNativeInt
NativeUInt val1 = OpStackGet<NativeUInt>(op1idx);
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
// NativeInt op NativeInt = NativeInt
NativeInt val1 = OpStackGet<NativeInt>(op1idx);
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
BinaryArithOvfOpWork<op, NativeInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
}
else if (cit2 == CORINFO_TYPE_BYREF)
{
if (asUnsigned && op == BA_Add)
{
// UnsignedNativeInt op ByRef = ByRef
NativeUInt val1 = OpStackGet<UINT32>(op1idx);
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("Illegal arithmetic overflow operation for native int and byref.");
}
}
else
{
VerificationError("Binary arithmetic overflow operation type mismatch (native int and ?)");
}
break;
case CORINFO_TYPE_LONG:
if (cit2 == CORINFO_TYPE_LONG || (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_NATIVEINT))
{
if (asUnsigned)
{
// UnsignedLong op UnsignedLong = UnsignedLong
UINT64 val1 = OpStackGet<UINT64>(op1idx);
UINT64 val2 = OpStackGet<UINT64>(op2idx);
BinaryArithOvfOpWork<op, UINT64, CORINFO_TYPE_LONG, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
// Long op Long = Long
INT64 val1 = OpStackGet<INT64>(op1idx);
INT64 val2 = OpStackGet<INT64>(op2idx);
BinaryArithOvfOpWork<op, INT64, CORINFO_TYPE_LONG, /*TypeIsUnchanged*/true>(val1, val2);
}
}
else
{
VerificationError("Binary arithmetic overflow operation type mismatch (long and ?)");
}
break;
case CORINFO_TYPE_BYREF:
if (asUnsigned && (op == BA_Add || op == BA_Sub))
{
NativeUInt val1 = OpStackGet<NativeUInt>(op1idx);
if (cit2 == CORINFO_TYPE_INT)
{
// ByRef +- UnsignedInt = ByRef
NativeUInt val2 = static_cast<NativeUInt>(OpStackGet<INT32>(op2idx));
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/true>(val1, val2);
}
else if (cit2 == CORINFO_TYPE_NATIVEINT)
{
// ByRef +- UnsignedNativeInt = ByRef
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/true>(val1, val2);
}
else if (cit2 == CORINFO_TYPE_BYREF)
{
if (op == BA_Sub)
{
// ByRef - ByRef = UnsignedNativeInt
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryArithOvfOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("Illegal arithmetic overflow operation for byref and byref: may only subtract managed pointer values.");
}
}
else
{
VerificationError("Binary arithmetic overflow operation not permitted on byref");
}
}
else
{
if (!asUnsigned)
{
VerificationError("Signed binary arithmetic overflow operation not permitted on managed pointer values.");
}
else
{
_ASSERTE_MSG(op == BA_Mul, "Must be an overflow operation; tested for Add || Sub above.");
VerificationError("Cannot multiply managed pointer values.");
}
}
break;
default:
_ASSERTE_MSG(false, "Non-stack-normal type on stack.");
}
// In all cases:
m_curStackHt--;
}
template<int op, typename T, CorInfoType cit, bool TypeIsUnchanged>
void Interpreter::BinaryArithOvfOpWork(T val1, T val2)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
ClrSafeInt<T> res;
ClrSafeInt<T> safeV1(val1);
ClrSafeInt<T> safeV2(val2);
if (op == BA_Add)
{
res = safeV1 + safeV2;
}
else if (op == BA_Sub)
{
res = safeV1 - safeV2;
}
else if (op == BA_Mul)
{
res = safeV1 * safeV2;
}
else
{
_ASSERTE_MSG(false, "op should be one of the overflow ops...");
}
if (res.IsOverflow())
{
ThrowOverflowException();
}
unsigned residx = m_curStackHt - 2;
OpStackSet<T>(residx, res.Value());
if (!TypeIsUnchanged)
{
OpStackTypeSet(residx, InterpreterType(cit));
}
}
template<int op>
void Interpreter::BinaryIntOp()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned op1idx = m_curStackHt - 2;
unsigned op2idx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(op1idx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
InterpreterType t2 = OpStackTypeGet(op2idx);
CorInfoType cit2 = t2.ToCorInfoType();
assert(IsStackNormalType(cit2));
// In all cases belows, since "op" is compile-time constant, "if" chains on it should fold away.
switch (cit1)
{
case CORINFO_TYPE_INT:
if (cit2 == CORINFO_TYPE_INT)
{
// Int op Int = Int
UINT32 val1 = OpStackGet<UINT32>(op1idx);
UINT32 val2 = OpStackGet<UINT32>(op2idx);
BinaryIntOpWork<op, UINT32, CORINFO_TYPE_INT, /*TypeIsUnchanged*/true>(val1, val2);
}
else if (cit2 == CORINFO_TYPE_NATIVEINT)
{
// Int op NativeInt = NativeInt
NativeUInt val1 = static_cast<NativeUInt>(OpStackGet<INT32>(op1idx));
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryIntOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/false>(val1, val2);
}
else if (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_BYREF)
{
// Int op NativeUInt = NativeUInt
NativeUInt val1 = static_cast<NativeUInt>(OpStackGet<INT32>(op1idx));
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryIntOpWork<op, NativeUInt, CORINFO_TYPE_BYREF, /*TypeIsUnchanged*/false>(val1, val2);
}
else
{
VerificationError("Binary arithmetic operation type mismatch (int and ?)");
}
break;
case CORINFO_TYPE_NATIVEINT:
if (cit2 == CORINFO_TYPE_NATIVEINT)
{
// NativeInt op NativeInt = NativeInt
NativeUInt val1 = OpStackGet<NativeUInt>(op1idx);
NativeUInt val2 = OpStackGet<NativeUInt>(op2idx);
BinaryIntOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
else if (cit2 == CORINFO_TYPE_INT)
{
// NativeInt op Int = NativeInt
NativeUInt val1 = OpStackGet<NativeUInt>(op1idx);
NativeUInt val2 = static_cast<NativeUInt>(OpStackGet<INT32>(op2idx));
BinaryIntOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
// CLI spec does not allow adding a native int and an int64. So use loose rules.
else if (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_LONG)
{
// NativeInt op Int = NativeInt
NativeUInt val1 = OpStackGet<NativeUInt>(op1idx);
NativeUInt val2 = static_cast<NativeUInt>(OpStackGet<INT64>(op2idx));
BinaryIntOpWork<op, NativeUInt, CORINFO_TYPE_NATIVEINT, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
VerificationError("Binary arithmetic operation type mismatch (native int and ?)");
}
break;
case CORINFO_TYPE_LONG:
if (cit2 == CORINFO_TYPE_LONG || (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_NATIVEINT))
{
// Long op Long = Long
UINT64 val1 = OpStackGet<UINT64>(op1idx);
UINT64 val2 = OpStackGet<UINT64>(op2idx);
BinaryIntOpWork<op, UINT64, CORINFO_TYPE_LONG, /*TypeIsUnchanged*/true>(val1, val2);
}
else
{
VerificationError("Binary arithmetic operation type mismatch (long and ?)");
}
break;
default:
VerificationError("Illegal operation for non-integral data type.");
}
// In all cases:
m_curStackHt--;
}
template<int op, typename T, CorInfoType cit, bool TypeIsUnchanged>
void Interpreter::BinaryIntOpWork(T val1, T val2)
{
T res;
if (op == BIO_And)
{
res = val1 & val2;
}
else if (op == BIO_Or)
{
res = val1 | val2;
}
else if (op == BIO_Xor)
{
res = val1 ^ val2;
}
else
{
assert(op == BIO_DivUn || op == BIO_RemUn);
if (val2 == 0)
{
ThrowDivideByZero();
}
else if (val2 == -1 && val1 == static_cast<T>(((UINT64)1) << (sizeof(T)*8 - 1))) // min int / -1 is not representable.
{
ThrowSysArithException();
}
// Otherwise...
if (op == BIO_DivUn)
{
res = val1 / val2;
}
else
{
res = val1 % val2;
}
}
unsigned residx = m_curStackHt - 2;
OpStackSet<T>(residx, res);
if (!TypeIsUnchanged)
{
OpStackTypeSet(residx, InterpreterType(cit));
}
}
template<int op>
void Interpreter::ShiftOp()
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned op1idx = m_curStackHt - 2;
unsigned op2idx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(op1idx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
InterpreterType t2 = OpStackTypeGet(op2idx);
CorInfoType cit2 = t2.ToCorInfoType();
assert(IsStackNormalType(cit2));
// In all cases belows, since "op" is compile-time constant, "if" chains on it should fold away.
switch (cit1)
{
case CORINFO_TYPE_INT:
ShiftOpWork<op, INT32, UINT32>(op1idx, cit2);
break;
case CORINFO_TYPE_NATIVEINT:
ShiftOpWork<op, NativeInt, NativeUInt>(op1idx, cit2);
break;
case CORINFO_TYPE_LONG:
ShiftOpWork<op, INT64, UINT64>(op1idx, cit2);
break;
default:
VerificationError("Illegal value type for shift operation.");
break;
}
m_curStackHt--;
}
template<int op, typename T, typename UT>
void Interpreter::ShiftOpWork(unsigned op1idx, CorInfoType cit2)
{
T val = OpStackGet<T>(op1idx);
unsigned op2idx = op1idx + 1;
T res = 0;
if (cit2 == CORINFO_TYPE_INT)
{
INT32 shiftAmt = OpStackGet<INT32>(op2idx);
if (op == CEE_SHL)
{
res = val << shiftAmt; // TODO: Check that C++ semantics matches IL.
}
else if (op == CEE_SHR)
{
res = val >> shiftAmt;
}
else
{
assert(op == CEE_SHR_UN);
res = (static_cast<UT>(val)) >> shiftAmt;
}
}
else if (cit2 == CORINFO_TYPE_NATIVEINT)
{
NativeInt shiftAmt = OpStackGet<NativeInt>(op2idx);
if (op == CEE_SHL)
{
res = val << shiftAmt; // TODO: Check that C++ semantics matches IL.
}
else if (op == CEE_SHR)
{
res = val >> shiftAmt;
}
else
{
assert(op == CEE_SHR_UN);
res = (static_cast<UT>(val)) >> shiftAmt;
}
}
else
{
VerificationError("Operand type mismatch for shift operator.");
}
OpStackSet<T>(op1idx, res);
}
void Interpreter::Neg()
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned opidx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(opidx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
switch (cit1)
{
case CORINFO_TYPE_INT:
OpStackSet<INT32>(opidx, -OpStackGet<INT32>(opidx));
break;
case CORINFO_TYPE_NATIVEINT:
OpStackSet<NativeInt>(opidx, -OpStackGet<NativeInt>(opidx));
break;
case CORINFO_TYPE_LONG:
OpStackSet<INT64>(opidx, -OpStackGet<INT64>(opidx));
break;
case CORINFO_TYPE_FLOAT:
OpStackSet<float>(opidx, -OpStackGet<float>(opidx));
break;
case CORINFO_TYPE_DOUBLE:
OpStackSet<double>(opidx, -OpStackGet<double>(opidx));
break;
default:
VerificationError("Illegal operand type for Neg operation.");
}
}
void Interpreter::Not()
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned opidx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(opidx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
switch (cit1)
{
case CORINFO_TYPE_INT:
OpStackSet<INT32>(opidx, ~OpStackGet<INT32>(opidx));
break;
case CORINFO_TYPE_NATIVEINT:
OpStackSet<NativeInt>(opidx, ~OpStackGet<NativeInt>(opidx));
break;
case CORINFO_TYPE_LONG:
OpStackSet<INT64>(opidx, ~OpStackGet<INT64>(opidx));
break;
default:
VerificationError("Illegal operand type for Not operation.");
}
}
template<typename T, bool TIsUnsigned, bool TCanHoldPtr, bool TIsShort, CorInfoType cit>
void Interpreter::Conv()
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned opidx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(opidx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
T val;
switch (cit1)
{
case CORINFO_TYPE_INT:
if (TIsUnsigned)
{
// Must convert the 32 bit value to unsigned first, so that we zero-extend if necessary.
val = static_cast<T>(static_cast<UINT32>(OpStackGet<INT32>(opidx)));
}
else
{
val = static_cast<T>(OpStackGet<INT32>(opidx));
}
break;
case CORINFO_TYPE_NATIVEINT:
if (TIsUnsigned)
{
// NativeInt might be 32 bits, so convert to unsigned before possibly widening.
val = static_cast<T>(static_cast<NativeUInt>(OpStackGet<NativeInt>(opidx)));
}
else
{
val = static_cast<T>(OpStackGet<NativeInt>(opidx));
}
break;
case CORINFO_TYPE_LONG:
val = static_cast<T>(OpStackGet<INT64>(opidx));
break;
// TODO: Make sure that the C++ conversions do the right thing (truncate to zero...)
case CORINFO_TYPE_FLOAT:
val = static_cast<T>(OpStackGet<float>(opidx));
break;
case CORINFO_TYPE_DOUBLE:
val = static_cast<T>(OpStackGet<double>(opidx));
break;
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_STRING:
if (!TCanHoldPtr && !s_InterpreterLooseRules)
{
VerificationError("Conversion of pointer value to type that can't hold its value.");
}
// Otherwise...
// (Must first convert to NativeInt, because the compiler believes this might be applied for T =
// float or double. It won't, by the test above, and the extra cast shouldn't generate any code...)
val = static_cast<T>(reinterpret_cast<NativeInt>(OpStackGet<void*>(opidx)));
break;
default:
VerificationError("Illegal operand type for conv.* operation.");
UNREACHABLE();
}
if (TIsShort)
{
OpStackSet<INT32>(opidx, static_cast<INT32>(val));
}
else
{
OpStackSet<T>(opidx, val);
}
OpStackTypeSet(opidx, InterpreterType(cit));
}
void Interpreter::ConvRUn()
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned opidx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(opidx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
switch (cit1)
{
case CORINFO_TYPE_INT:
OpStackSet<double>(opidx, static_cast<double>(OpStackGet<UINT32>(opidx)));
break;
case CORINFO_TYPE_NATIVEINT:
OpStackSet<double>(opidx, static_cast<double>(OpStackGet<NativeUInt>(opidx)));
break;
case CORINFO_TYPE_LONG:
OpStackSet<double>(opidx, static_cast<double>(OpStackGet<UINT64>(opidx)));
break;
case CORINFO_TYPE_DOUBLE:
return;
default:
VerificationError("Illegal operand type for conv.r.un operation.");
}
OpStackTypeSet(opidx, InterpreterType(CORINFO_TYPE_DOUBLE));
}
template<typename T, INT64 TMin, UINT64 TMax, bool TCanHoldPtr, CorInfoType cit>
void Interpreter::ConvOvf()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned opidx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(opidx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
switch (cit1)
{
case CORINFO_TYPE_INT:
{
INT32 i4 = OpStackGet<INT32>(opidx);
if (!FitsIn<T>(i4))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(i4));
}
break;
case CORINFO_TYPE_NATIVEINT:
{
NativeInt i = OpStackGet<NativeInt>(opidx);
if (!FitsIn<T>(i))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(i));
}
break;
case CORINFO_TYPE_LONG:
{
INT64 i8 = OpStackGet<INT64>(opidx);
if (!FitsIn<T>(i8))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(i8));
}
break;
// Make sure that the C++ conversions do the right thing (truncate to zero...)
case CORINFO_TYPE_FLOAT:
{
float f = OpStackGet<float>(opidx);
if (!FloatFitsInIntType<TMin, TMax>(f))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(f));
}
break;
case CORINFO_TYPE_DOUBLE:
{
double d = OpStackGet<double>(opidx);
if (!DoubleFitsInIntType<TMin, TMax>(d))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(d));
}
break;
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_STRING:
if (!TCanHoldPtr)
{
VerificationError("Conversion of pointer value to type that can't hold its value.");
}
// Otherwise...
// (Must first convert to NativeInt, because the compiler believes this might be applied for T =
// float or double. It won't, by the test above, and the extra cast shouldn't generate any code...
OpStackSet<T>(opidx, static_cast<T>(reinterpret_cast<NativeInt>(OpStackGet<void*>(opidx))));
break;
default:
VerificationError("Illegal operand type for conv.ovf.* operation.");
}
_ASSERTE_MSG(IsStackNormalType(cit), "Precondition.");
OpStackTypeSet(opidx, InterpreterType(cit));
}
template<typename T, INT64 TMin, UINT64 TMax, bool TCanHoldPtr, CorInfoType cit>
void Interpreter::ConvOvfUn()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned opidx = m_curStackHt - 1;
InterpreterType t1 = OpStackTypeGet(opidx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
switch (cit1)
{
case CORINFO_TYPE_INT:
{
UINT32 ui4 = OpStackGet<UINT32>(opidx);
if (!FitsIn<T>(ui4))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(ui4));
}
break;
case CORINFO_TYPE_NATIVEINT:
{
NativeUInt ui = OpStackGet<NativeUInt>(opidx);
if (!FitsIn<T>(ui))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(ui));
}
break;
case CORINFO_TYPE_LONG:
{
UINT64 ui8 = OpStackGet<UINT64>(opidx);
if (!FitsIn<T>(ui8))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(ui8));
}
break;
// Make sure that the C++ conversions do the right thing (truncate to zero...)
case CORINFO_TYPE_FLOAT:
{
float f = OpStackGet<float>(opidx);
if (!FloatFitsInIntType<TMin, TMax>(f))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(f));
}
break;
case CORINFO_TYPE_DOUBLE:
{
double d = OpStackGet<double>(opidx);
if (!DoubleFitsInIntType<TMin, TMax>(d))
{
ThrowOverflowException();
}
OpStackSet<T>(opidx, static_cast<T>(d));
}
break;
case CORINFO_TYPE_BYREF:
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_STRING:
if (!TCanHoldPtr)
{
VerificationError("Conversion of pointer value to type that can't hold its value.");
}
// Otherwise...
// (Must first convert to NativeInt, because the compiler believes this might be applied for T =
// float or double. It won't, by the test above, and the extra cast shouldn't generate any code...
OpStackSet<T>(opidx, static_cast<T>(reinterpret_cast<NativeInt>(OpStackGet<void*>(opidx))));
break;
default:
VerificationError("Illegal operand type for conv.ovf.*.un operation.");
}
_ASSERTE_MSG(IsStackNormalType(cit), "Precondition.");
OpStackTypeSet(opidx, InterpreterType(cit));
}
void Interpreter::LdObj()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
BarrierIfVolatile();
assert(m_curStackHt > 0);
unsigned ind = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType cit = OpStackTypeGet(ind).ToCorInfoType();
_ASSERTE_MSG(IsValidPointerType(cit), "Expect pointer on stack");
#endif // _DEBUG
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_LdObj]);
#endif // INTERP_TRACING
// TODO: GetTypeFromToken also uses GCX_PREEMP(); can we merge it with the getClassAttribs() block below, and do it just once?
CORINFO_CLASS_HANDLE clsHnd = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_LdObj));
DWORD clsAttribs;
{
GCX_PREEMP();
clsAttribs = m_interpCeeInfo.getClassAttribs(clsHnd);
}
void* src = OpStackGet<void*>(ind);
ThrowOnInvalidPointer(src);
if (clsAttribs & CORINFO_FLG_VALUECLASS)
{
LdObjValueClassWork(clsHnd, ind, src);
}
else
{
OpStackSet<void*>(ind, *reinterpret_cast<void**>(src));
OpStackTypeSet(ind, InterpreterType(CORINFO_TYPE_CLASS));
}
m_ILCodePtr += 5;
}
void Interpreter::LdObjValueClassWork(CORINFO_CLASS_HANDLE valueClsHnd, unsigned ind, void* src)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
// "src" is a byref, which may be into an object. GCPROTECT for the call below.
GCPROTECT_BEGININTERIOR(src);
InterpreterType it = InterpreterType(&m_interpCeeInfo, valueClsHnd);
size_t sz = it.Size(&m_interpCeeInfo);
// Note that the memcpy's below are permissible because the destination is in the operand stack.
if (sz > sizeof(INT64))
{
void* dest = LargeStructOperandStackPush(sz);
memcpy(dest, src, sz);
OpStackSet<void*>(ind, dest);
}
else
{
OpStackSet<INT64>(ind, GetSmallStructValue(src, sz));
}
OpStackTypeSet(ind, it.StackNormalize());
GCPROTECT_END();
}
CORINFO_CLASS_HANDLE Interpreter::GetTypeFromToken(BYTE* codePtr, CorInfoTokenKind tokKind InterpTracingArg(ResolveTokenKind rtk))
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
GCX_PREEMP();
CORINFO_GENERICHANDLE_RESULT embedInfo;
CORINFO_RESOLVED_TOKEN typeTok;
ResolveToken(&typeTok, getU4LittleEndian(codePtr), tokKind InterpTracingArg(rtk));
return typeTok.hClass;
}
bool Interpreter::IsValidPointerType(CorInfoType cit)
{
bool isValid = (cit == CORINFO_TYPE_NATIVEINT || cit == CORINFO_TYPE_BYREF);
#if defined(_AMD64_)
isValid = isValid || (s_InterpreterLooseRules && cit == CORINFO_TYPE_LONG);
#endif
return isValid;
}
void Interpreter::CpObj()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned destInd = m_curStackHt - 2;
unsigned srcInd = m_curStackHt - 1;
#ifdef _DEBUG
// Check that src and dest are both pointer types.
CorInfoType cit = OpStackTypeGet(destInd).ToCorInfoType();
_ASSERTE_MSG(IsValidPointerType(cit), "Expect pointer on stack for dest of cpobj");
cit = OpStackTypeGet(srcInd).ToCorInfoType();
_ASSERTE_MSG(IsValidPointerType(cit), "Expect pointer on stack for src of cpobj");
#endif // _DEBUG
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_CpObj]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE clsHnd = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_CpObj));
DWORD clsAttribs;
{
GCX_PREEMP();
clsAttribs = m_interpCeeInfo.getClassAttribs(clsHnd);
}
void* dest = OpStackGet<void*>(destInd);
void* src = OpStackGet<void*>(srcInd);
ThrowOnInvalidPointer(dest);
ThrowOnInvalidPointer(src);
// dest and src are vulnerable byrefs.
GCX_FORBID();
if (clsAttribs & CORINFO_FLG_VALUECLASS)
{
CopyValueClassUnchecked(dest, src, GetMethodTableFromClsHnd(clsHnd));
}
else
{
OBJECTREF val = *reinterpret_cast<OBJECTREF*>(src);
SetObjectReferenceUnchecked(reinterpret_cast<OBJECTREF*>(dest), val);
}
m_curStackHt -= 2;
m_ILCodePtr += 5;
}
void Interpreter::StObj()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned destInd = m_curStackHt - 2;
unsigned valInd = m_curStackHt - 1;
#ifdef _DEBUG
// Check that dest is a pointer type.
CorInfoType cit = OpStackTypeGet(destInd).ToCorInfoType();
_ASSERTE_MSG(IsValidPointerType(cit), "Expect pointer on stack for dest of stobj");
#endif // _DEBUG
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_StObj]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE clsHnd = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_StObj));
DWORD clsAttribs;
{
GCX_PREEMP();
clsAttribs = m_interpCeeInfo.getClassAttribs(clsHnd);
}
if (clsAttribs & CORINFO_FLG_VALUECLASS)
{
MethodTable* clsMT = GetMethodTableFromClsHnd(clsHnd);
size_t sz;
{
GCX_PREEMP();
sz = getClassSize(clsHnd);
}
// Note that "dest" might be a pointer into the heap. It is therefore important
// to calculate it *after* any PREEMP transitions at which we might do a GC.
void* dest = OpStackGet<void*>(destInd);
ThrowOnInvalidPointer(dest);
assert( (OpStackTypeGet(valInd).ToCorInfoType() == CORINFO_TYPE_VALUECLASS &&
OpStackTypeGet(valInd).ToClassHandle() == clsHnd)
||
(OpStackTypeGet(valInd).ToCorInfoType() ==
CorInfoTypeStackNormalize(GetTypeForPrimitiveValueClass(clsHnd)))
|| (s_InterpreterLooseRules && sz <= sizeof(dest)));
GCX_FORBID();
if (sz > sizeof(INT64))
{
// Large struct case -- ostack entry is pointer.
void* src = OpStackGet<void*>(valInd);
CopyValueClassUnchecked(dest, src, clsMT);
LargeStructOperandStackPop(sz, src);
}
else
{
// The ostack entry contains the struct value.
CopyValueClassUnchecked(dest, OpStackGetAddr(valInd, sz), clsMT);
}
}
else
{
// The ostack entry is an object reference.
assert(OpStackTypeGet(valInd).ToCorInfoType() == CORINFO_TYPE_CLASS);
// Note that "dest" might be a pointer into the heap. It is therefore important
// to calculate it *after* any PREEMP transitions at which we might do a GC. (Thus,
// we have to duplicate this code with the case above.
void* dest = OpStackGet<void*>(destInd);
ThrowOnInvalidPointer(dest);
GCX_FORBID();
OBJECTREF val = ObjectToOBJECTREF(OpStackGet<Object*>(valInd));
SetObjectReferenceUnchecked(reinterpret_cast<OBJECTREF*>(dest), val);
}
m_curStackHt -= 2;
m_ILCodePtr += 5;
BarrierIfVolatile();
}
void Interpreter::InitObj()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned destInd = m_curStackHt - 1;
#ifdef _DEBUG
// Check that src and dest are both pointer types.
CorInfoType cit = OpStackTypeGet(destInd).ToCorInfoType();
_ASSERTE_MSG(IsValidPointerType(cit), "Expect pointer on stack");
#endif // _DEBUG
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_InitObj]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE clsHnd = GetTypeFromToken(m_ILCodePtr + 2, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_InitObj));
size_t valueClassSz = 0;
DWORD clsAttribs;
{
GCX_PREEMP();
clsAttribs = m_interpCeeInfo.getClassAttribs(clsHnd);
if (clsAttribs & CORINFO_FLG_VALUECLASS)
{
valueClassSz = getClassSize(clsHnd);
}
}
void* dest = OpStackGet<void*>(destInd);
ThrowOnInvalidPointer(dest);
// dest is a vulnerable byref.
GCX_FORBID();
if (clsAttribs & CORINFO_FLG_VALUECLASS)
{
memset(dest, 0, valueClassSz);
}
else
{
// The ostack entry is an object reference.
SetObjectReferenceUnchecked(reinterpret_cast<OBJECTREF*>(dest), NULL);
}
m_curStackHt -= 1;
m_ILCodePtr += 6;
}
void Interpreter::LdStr()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
OBJECTHANDLE res = ConstructStringLiteral(m_methInfo->m_module, getU4LittleEndian(m_ILCodePtr + 1));
{
GCX_FORBID();
OpStackSet<Object*>(m_curStackHt, *reinterpret_cast<Object**>(res));
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_CLASS)); // Stack-normal type for "string"
m_curStackHt++;
}
m_ILCodePtr += 5;
}
void Interpreter::NewObj()
{
#if INTERP_DYNAMIC_CONTRACTS
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#else
// Dynamic contract occupies too much stack.
STATIC_CONTRACT_SO_TOLERANT;
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
#endif
unsigned ctorTok = getU4LittleEndian(m_ILCodePtr + 1);
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_NewObj]);
#endif // INTERP_TRACING
CORINFO_CALL_INFO callInfo;
CORINFO_RESOLVED_TOKEN methTok;
{
GCX_PREEMP();
ResolveToken(&methTok, ctorTok, CORINFO_TOKENKIND_Ldtoken InterpTracingArg(RTK_NewObj));
m_interpCeeInfo.getCallInfo(&methTok, NULL,
m_methInfo->m_method,
CORINFO_CALLINFO_FLAGS(0),
&callInfo);
}
unsigned mflags = callInfo.methodFlags;
if ((mflags & (CORINFO_FLG_STATIC|CORINFO_FLG_ABSTRACT)) != 0)
{
VerificationError("newobj on static or abstract method");
}
unsigned clsFlags = callInfo.classFlags;
#ifdef _DEBUG
// What class are we allocating?
const char* clsName;
{
GCX_PREEMP();
clsName = m_interpCeeInfo.getClassName(methTok.hClass);
}
#endif // _DEBUG
// There are four cases:
// 1) Value types (ordinary constructor, resulting VALUECLASS pushed)
// 2) String (var-args constructor, result automatically pushed)
// 3) MDArray (var-args constructor, resulting OBJECTREF pushed)
// 4) Reference types (ordinary constructor, resulting OBJECTREF pushed)
if (clsFlags & CORINFO_FLG_VALUECLASS)
{
void* tempDest;
INT64 smallTempDest = 0;
size_t sz = 0;
{
GCX_PREEMP();
sz = getClassSize(methTok.hClass);
}
if (sz > sizeof(INT64))
{
// TODO: Make sure this is deleted in the face of exceptions.
tempDest = new BYTE[sz];
}
else
{
tempDest = &smallTempDest;
}
memset(tempDest, 0, sz);
InterpreterType structValRetIT(&m_interpCeeInfo, methTok.hClass);
m_structRetValITPtr = &structValRetIT;
m_structRetValTempSpace = tempDest;
DoCallWork(/*virtCall*/false, tempDest, &methTok, &callInfo);
if (sz > sizeof(INT64))
{
void* dest = LargeStructOperandStackPush(sz);
memcpy(dest, tempDest, sz);
delete[] reinterpret_cast<BYTE*>(tempDest);
OpStackSet<void*>(m_curStackHt, dest);
}
else
{
OpStackSet<INT64>(m_curStackHt, GetSmallStructValue(tempDest, sz));
}
if (m_structRetValITPtr->IsStruct())
{
OpStackTypeSet(m_curStackHt, *m_structRetValITPtr);
}
else
{
// Must stack-normalize primitive types.
OpStackTypeSet(m_curStackHt, m_structRetValITPtr->StackNormalize());
}
// "Unregister" the temp space for GC scanning...
m_structRetValITPtr = NULL;
m_curStackHt++;
}
else if ((clsFlags & CORINFO_FLG_VAROBJSIZE) && !(clsFlags & CORINFO_FLG_ARRAY))
{
// For a VAROBJSIZE class (currently == String), pass NULL as this to "pseudo-constructor."
void* specialFlagArg = reinterpret_cast<void*>(0x1); // Special value for "thisArg" argument of "DoCallWork": push NULL that's not on op stack.
DoCallWork(/*virtCall*/false, specialFlagArg, &methTok, &callInfo); // pushes result automatically
}
else
{
OBJECTREF thisArgObj = NULL;
GCPROTECT_BEGIN(thisArgObj);
if (clsFlags & CORINFO_FLG_ARRAY)
{
assert(clsFlags & CORINFO_FLG_VAROBJSIZE);
MethodDesc* methDesc = GetMethod(methTok.hMethod);
PCCOR_SIGNATURE pSig;
DWORD cbSigSize;
methDesc->GetSig(&pSig, &cbSigSize);
MetaSig msig(pSig, cbSigSize, methDesc->GetModule(), NULL);
unsigned dwNumArgs = msig.NumFixedArgs();
assert(m_curStackHt >= dwNumArgs);
m_curStackHt -= dwNumArgs;
INT32* args = (INT32*)_alloca(dwNumArgs * sizeof(INT32));
unsigned dwArg;
for (dwArg = 0; dwArg < dwNumArgs; dwArg++)
{
unsigned stkInd = m_curStackHt + dwArg;
bool loose = s_InterpreterLooseRules && (OpStackTypeGet(stkInd).ToCorInfoType() == CORINFO_TYPE_NATIVEINT);
if (OpStackTypeGet(stkInd).ToCorInfoType() != CORINFO_TYPE_INT && !loose)
{
VerificationError("MD array dimension bounds and sizes must be int.");
}
args[dwArg] = loose ? (INT32) OpStackGet<NativeInt>(stkInd) : OpStackGet<INT32>(stkInd);
}
thisArgObj = AllocateArrayEx(TypeHandle(methTok.hClass), args, dwNumArgs);
}
else
{
CorInfoHelpFunc newHelper;
{
GCX_PREEMP();
newHelper = m_interpCeeInfo.getNewHelper(&methTok, m_methInfo->m_method);
}
MethodTable * pNewObjMT = GetMethodTableFromClsHnd(methTok.hClass);
switch (newHelper)
{
case CORINFO_HELP_NEWFAST:
default:
thisArgObj = AllocateObject(pNewObjMT);
break;
}
DoCallWork(/*virtCall*/false, OBJECTREFToObject(thisArgObj), &methTok, &callInfo);
}
{
GCX_FORBID();
OpStackSet<Object*>(m_curStackHt, OBJECTREFToObject(thisArgObj));
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_CLASS));
m_curStackHt++;
}
GCPROTECT_END(); // For "thisArgObj"
}
m_ILCodePtr += 5;
}
void Interpreter::NewArr()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt > 0);
unsigned stkInd = m_curStackHt-1;
CorInfoType cit = OpStackTypeGet(stkInd).ToCorInfoType();
NativeInt sz = 0;
switch (cit)
{
case CORINFO_TYPE_INT:
sz = static_cast<NativeInt>(OpStackGet<INT32>(stkInd));
break;
case CORINFO_TYPE_NATIVEINT:
sz = OpStackGet<NativeInt>(stkInd);
break;
default:
VerificationError("Size operand of 'newarr' must be int or native int.");
}
unsigned elemTypeTok = getU4LittleEndian(m_ILCodePtr + 1);
CORINFO_CLASS_HANDLE elemClsHnd;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_NewArr]);
#endif // INTERP_TRACING
CORINFO_RESOLVED_TOKEN elemTypeResolvedTok;
{
GCX_PREEMP();
ResolveToken(&elemTypeResolvedTok, elemTypeTok, CORINFO_TOKENKIND_Newarr InterpTracingArg(RTK_NewArr));
elemClsHnd = elemTypeResolvedTok.hClass;
}
{
if (sz < 0)
{
COMPlusThrow(kOverflowException);
}
#ifdef _WIN64
// Even though ECMA allows using a native int as the argument to newarr instruction
// (therefore size is INT_PTR), ArrayBase::m_NumComponents is 32-bit, so even on 64-bit
// platforms we can't create an array whose size exceeds 32 bits.
if (sz > INT_MAX)
{
EX_THROW(EEMessageException, (kOverflowException, IDS_EE_ARRAY_DIMENSIONS_EXCEEDED));
}
#endif
TypeHandle typeHnd(elemClsHnd);
ArrayTypeDesc* pArrayClassRef = typeHnd.AsArray();
pArrayClassRef->GetMethodTable()->CheckRunClassInitThrowing();
INT32 size32 = (INT32)sz;
Object* newarray = OBJECTREFToObject(AllocateArrayEx(typeHnd, &size32, 1));
GCX_FORBID();
OpStackTypeSet(stkInd, InterpreterType(CORINFO_TYPE_CLASS));
OpStackSet<Object*>(stkInd, newarray);
}
m_ILCodePtr += 5;
}
void Interpreter::IsInst()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_IsInst]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE cls = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Casting InterpTracingArg(RTK_IsInst));
assert(m_curStackHt >= 1);
unsigned idx = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType cit = OpStackTypeGet(idx).ToCorInfoType();
assert(cit == CORINFO_TYPE_CLASS || cit == CORINFO_TYPE_STRING);
#endif // DEBUG
Object * pObj = OpStackGet<Object*>(idx);
if (pObj != NULL)
{
if (!ObjIsInstanceOf(pObj, TypeHandle(cls)))
OpStackSet<Object*>(idx, NULL);
}
// Type stack stays unmodified.
m_ILCodePtr += 5;
}
void Interpreter::CastClass()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_CastClass]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE cls = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Casting InterpTracingArg(RTK_CastClass));
assert(m_curStackHt >= 1);
unsigned idx = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType cit = OpStackTypeGet(idx).ToCorInfoType();
assert(cit == CORINFO_TYPE_CLASS || cit == CORINFO_TYPE_STRING);
#endif // _DEBUG
Object * pObj = OpStackGet<Object*>(idx);
if (pObj != NULL)
{
if (!ObjIsInstanceOf(pObj, TypeHandle(cls), TRUE))
{
UNREACHABLE(); //ObjIsInstanceOf will throw if cast can't be done
}
}
// Type stack stays unmodified.
m_ILCodePtr += 5;
}
void Interpreter::LocAlloc()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned idx = m_curStackHt - 1;
CorInfoType cit = OpStackTypeGet(idx).ToCorInfoType();
NativeUInt sz = 0;
if (cit == CORINFO_TYPE_INT || cit == CORINFO_TYPE_UINT)
{
sz = static_cast<NativeUInt>(OpStackGet<UINT32>(idx));
}
else if (cit == CORINFO_TYPE_NATIVEINT || cit == CORINFO_TYPE_NATIVEUINT)
{
sz = OpStackGet<NativeUInt>(idx);
}
else if (s_InterpreterLooseRules && cit == CORINFO_TYPE_LONG)
{
sz = (NativeUInt) OpStackGet<INT64>(idx);
}
else
{
VerificationError("localloc requires int or nativeint argument.");
}
if (sz == 0)
{
OpStackSet<void*>(idx, NULL);
}
else
{
void* res = GetLocAllocData()->Alloc(sz);
if (res == NULL) ThrowStackOverflow();
OpStackSet<void*>(idx, res);
}
OpStackTypeSet(idx, InterpreterType(CORINFO_TYPE_NATIVEINT));
}
void Interpreter::MkRefany()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_MkRefAny]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE cls = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_MkRefAny));
assert(m_curStackHt >= 1);
unsigned idx = m_curStackHt - 1;
CorInfoType cit = OpStackTypeGet(idx).ToCorInfoType();
if (!(cit == CORINFO_TYPE_BYREF || cit == CORINFO_TYPE_NATIVEINT))
VerificationError("MkRefany requires byref or native int (pointer) on the stack.");
void* ptr = OpStackGet<void*>(idx);
InterpreterType typedRefIT = GetTypedRefIT(&m_interpCeeInfo);
TypedByRef* tbr;
#if defined(_AMD64_)
assert(typedRefIT.IsLargeStruct(&m_interpCeeInfo));
tbr = (TypedByRef*) LargeStructOperandStackPush(GetTypedRefSize(&m_interpCeeInfo));
OpStackSet<void*>(idx, tbr);
#elif defined(_X86_) || defined(_ARM_)
assert(!typedRefIT.IsLargeStruct(&m_interpCeeInfo));
tbr = OpStackGetAddr<TypedByRef>(idx);
#elif defined(_ARM64_)
tbr = NULL;
NYI_INTERP("Unimplemented code: MkRefAny");
#else
#error "unsupported platform"
#endif
tbr->data = ptr;
tbr->type = TypeHandle(cls);
OpStackTypeSet(idx, typedRefIT);
m_ILCodePtr += 5;
}
void Interpreter::RefanyType()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt > 0);
unsigned idx = m_curStackHt - 1;
if (OpStackTypeGet(idx) != GetTypedRefIT(&m_interpCeeInfo))
VerificationError("RefAnyVal requires a TypedRef on the stack.");
TypedByRef* ptbr = OpStackGet<TypedByRef*>(idx);
LargeStructOperandStackPop(sizeof(TypedByRef), ptbr);
TypeHandle* pth = &ptbr->type;
{
OBJECTREF classobj = TypeHandleToTypeRef(pth);
GCX_FORBID();
OpStackSet<Object*>(idx, OBJECTREFToObject(classobj));
OpStackTypeSet(idx, InterpreterType(CORINFO_TYPE_CLASS));
}
m_ILCodePtr += 2;
}
// This (unfortunately) duplicates code in JIT_GetRuntimeTypeHandle, which
// isn't callable because it sets up a Helper Method Frame.
OBJECTREF Interpreter::TypeHandleToTypeRef(TypeHandle* pth)
{
OBJECTREF typePtr = NULL;
if (!pth->IsTypeDesc())
{
// Most common... and fastest case
typePtr = pth->AsMethodTable()->GetManagedClassObjectIfExists();
if (typePtr == NULL)
{
typePtr = pth->GetManagedClassObject();
}
}
else
{
typePtr = pth->GetManagedClassObject();
}
return typePtr;
}
CorInfoType Interpreter::GetTypeForPrimitiveValueClass(CORINFO_CLASS_HANDLE clsHnd)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
GCX_PREEMP();
return m_interpCeeInfo.getTypeForPrimitiveValueClass(clsHnd);
}
void Interpreter::RefanyVal()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt > 0);
unsigned idx = m_curStackHt - 1;
if (OpStackTypeGet(idx) != GetTypedRefIT(&m_interpCeeInfo))
VerificationError("RefAnyVal requires a TypedRef on the stack.");
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_RefAnyVal]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE cls = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_RefAnyVal));
TypeHandle expected(cls);
TypedByRef* ptbr = OpStackGet<TypedByRef*>(idx);
LargeStructOperandStackPop(sizeof(TypedByRef), ptbr);
if (expected != ptbr->type) ThrowInvalidCastException();
OpStackSet<void*>(idx, static_cast<void*>(ptbr->data));
OpStackTypeSet(idx, InterpreterType(CORINFO_TYPE_BYREF));
m_ILCodePtr += 5;
}
void Interpreter::CkFinite()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt > 0);
unsigned idx = m_curStackHt - 1;
CorInfoType cit = OpStackTypeGet(idx).ToCorInfoType();
double val = 0.0;
switch (cit)
{
case CORINFO_TYPE_FLOAT:
val = (double)OpStackGet<float>(idx);
break;
case CORINFO_TYPE_DOUBLE:
val = OpStackGet<double>(idx);
break;
default:
VerificationError("CkFinite requires a floating-point value on the stack.");
break;
}
if (!_finite(val))
ThrowSysArithException();
}
void Interpreter::LdToken()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
unsigned tokVal = getU4LittleEndian(m_ILCodePtr + 1);
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_LdToken]);
#endif // INTERP_TRACING
CORINFO_RESOLVED_TOKEN tok;
{
GCX_PREEMP();
ResolveToken(&tok, tokVal, CORINFO_TOKENKIND_Ldtoken InterpTracingArg(RTK_LdToken));
}
// To save duplication of the factored code at the bottom, I don't do GCX_FORBID for
// these Object* values, but this comment documents the intent.
if (tok.hMethod != NULL)
{
MethodDesc* pMethod = (MethodDesc*)tok.hMethod;
Object* objPtr = OBJECTREFToObject((OBJECTREF)pMethod->GetStubMethodInfo());
OpStackSet<Object*>(m_curStackHt, objPtr);
}
else if (tok.hField != NULL)
{
FieldDesc * pField = (FieldDesc *)tok.hField;
Object* objPtr = OBJECTREFToObject((OBJECTREF)pField->GetStubFieldInfo());
OpStackSet<Object*>(m_curStackHt, objPtr);
}
else
{
TypeHandle th(tok.hClass);
Object* objPtr = OBJECTREFToObject(th.GetManagedClassObject());
OpStackSet<Object*>(m_curStackHt, objPtr);
}
{
GCX_FORBID();
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_CLASS));
m_curStackHt++;
}
m_ILCodePtr += 5;
}
void Interpreter::LdFtn()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
unsigned tokVal = getU4LittleEndian(m_ILCodePtr + 2);
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_LdFtn]);
#endif // INTERP_TRACING
CORINFO_RESOLVED_TOKEN tok;
CORINFO_CALL_INFO callInfo;
{
GCX_PREEMP();
ResolveToken(&tok, tokVal, CORINFO_TOKENKIND_Method InterpTracingArg(RTK_LdFtn));
m_interpCeeInfo.getCallInfo(&tok, NULL, m_methInfo->m_method,
combine(CORINFO_CALLINFO_SECURITYCHECKS,CORINFO_CALLINFO_LDFTN),
&callInfo);
}
switch (callInfo.kind)
{
case CORINFO_CALL:
{
PCODE pCode = ((MethodDesc *)callInfo.hMethod)->GetMultiCallableAddrOfCode();
OpStackSet<void*>(m_curStackHt, (void *)pCode);
GetFunctionPointerStack()[m_curStackHt] = callInfo.hMethod;
}
break;
case CORINFO_CALL_CODE_POINTER:
NYI_INTERP("Indirect code pointer.");
break;
default:
_ASSERTE_MSG(false, "Should not reach here: unknown call kind.");
break;
}
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_NATIVEINT));
m_curStackHt++;
m_ILCodePtr += 6;
}
void Interpreter::LdVirtFtn()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned ind = m_curStackHt - 1;
unsigned tokVal = getU4LittleEndian(m_ILCodePtr + 2);
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_LdVirtFtn]);
#endif // INTERP_TRACING
CORINFO_RESOLVED_TOKEN tok;
CORINFO_CALL_INFO callInfo;
CORINFO_CLASS_HANDLE classHnd;
CORINFO_METHOD_HANDLE methodHnd;
{
GCX_PREEMP();
ResolveToken(&tok, tokVal, CORINFO_TOKENKIND_Method InterpTracingArg(RTK_LdVirtFtn));
m_interpCeeInfo.getCallInfo(&tok, NULL, m_methInfo->m_method,
combine(CORINFO_CALLINFO_SECURITYCHECKS,CORINFO_CALLINFO_LDFTN),
&callInfo);
classHnd = tok.hClass;
methodHnd = tok.hMethod;
}
MethodDesc * pMD = (MethodDesc *)methodHnd;
PCODE pCode;
if (pMD->IsVtableMethod())
{
Object* obj = OpStackGet<Object*>(ind);
ThrowOnInvalidPointer(obj);
OBJECTREF objRef = ObjectToOBJECTREF(obj);
GCPROTECT_BEGIN(objRef);
pCode = pMD->GetMultiCallableAddrOfVirtualizedCode(&objRef, TypeHandle(classHnd));
GCPROTECT_END();
pMD = Entry2MethodDesc(pCode, TypeHandle(classHnd).GetMethodTable());
}
else
{
pCode = pMD->GetMultiCallableAddrOfCode();
}
OpStackSet<void*>(ind, (void *)pCode);
GetFunctionPointerStack()[ind] = (CORINFO_METHOD_HANDLE)pMD;
OpStackTypeSet(ind, InterpreterType(CORINFO_TYPE_NATIVEINT));
m_ILCodePtr += 6;
}
void Interpreter::Sizeof()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_Sizeof]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE cls = GetTypeFromToken(m_ILCodePtr + 2, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_Sizeof));
unsigned sz;
{
GCX_PREEMP();
CorInfoType cit = ::asCorInfoType(cls);
// For class types, the ECMA spec says to return the size of the object reference, not the referent
// object. Everything else should be a value type, for which we can just return the size as reported
// by the EE.
switch (cit)
{
case CORINFO_TYPE_CLASS:
sz = sizeof(Object*);
break;
default:
sz = getClassSize(cls);
break;
}
}
OpStackSet<UINT32>(m_curStackHt, sz);
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_INT));
m_curStackHt++;
m_ILCodePtr += 6;
}
// static:
bool Interpreter::s_initialized = false;
bool Interpreter::s_compilerStaticsInitialized = false;
size_t Interpreter::s_TypedRefSize;
CORINFO_CLASS_HANDLE Interpreter::s_TypedRefClsHnd;
InterpreterType Interpreter::s_TypedRefIT;
// Must call GetTypedRefIT
size_t Interpreter::GetTypedRefSize(CEEInfo* info)
{
_ASSERTE_MSG(s_compilerStaticsInitialized, "Precondition");
return s_TypedRefSize;
}
InterpreterType Interpreter::GetTypedRefIT(CEEInfo* info)
{
_ASSERTE_MSG(s_compilerStaticsInitialized, "Precondition");
return s_TypedRefIT;
}
CORINFO_CLASS_HANDLE Interpreter::GetTypedRefClsHnd(CEEInfo* info)
{
_ASSERTE_MSG(s_compilerStaticsInitialized, "Precondition");
return s_TypedRefClsHnd;
}
void Interpreter::Initialize()
{
assert(!s_initialized);
s_InterpretMeths.ensureInit(CLRConfig::INTERNAL_Interpret);
s_InterpretMethsExclude.ensureInit(CLRConfig::INTERNAL_InterpretExclude);
s_InterpreterUseCaching = (s_InterpreterUseCachingFlag.val(CLRConfig::INTERNAL_InterpreterUseCaching) != 0);
s_InterpreterLooseRules = (s_InterpreterLooseRulesFlag.val(CLRConfig::INTERNAL_InterpreterLooseRules) != 0);
s_InterpreterDoLoopMethods = (s_InterpreterDoLoopMethodsFlag.val(CLRConfig::INTERNAL_InterpreterDoLoopMethods) != 0);
// Initialize the lock used to protect method locks.
// TODO: it would be better if this were a reader/writer lock.
s_methodCacheLock.Init(CrstLeafLock, CRST_DEFAULT);
// Similarly, initialize the lock used to protect the map from
// interpreter stub addresses to their method descs.
s_interpStubToMDMapLock.Init(CrstLeafLock, CRST_DEFAULT);
s_initialized = true;
#if INTERP_ILINSTR_PROFILE
SetILInstrCategories();
#endif // INTERP_ILINSTR_PROFILE
}
void Interpreter::InitializeCompilerStatics(CEEInfo* info)
{
if (!s_compilerStaticsInitialized)
{
// TODO: I believe I need no synchronization around this on x86, but I do
// on more permissive memory models. (Why it's OK on x86: each thread executes this
// before any access to the initialized static variables; if several threads do
// so, they perform idempotent initializing writes to the statics.
GCX_PREEMP();
s_TypedRefClsHnd = info->getBuiltinClass(CLASSID_TYPED_BYREF);
s_TypedRefIT = InterpreterType(info, s_TypedRefClsHnd);
s_TypedRefSize = getClassSize(s_TypedRefClsHnd);
s_compilerStaticsInitialized = true;
// TODO: Need store-store memory barrier here.
}
}
void Interpreter::Terminate()
{
if (s_initialized)
{
s_methodCacheLock.Destroy();
s_interpStubToMDMapLock.Destroy();
s_initialized = false;
}
}
#if INTERP_ILINSTR_PROFILE
void Interpreter::SetILInstrCategories()
{
// Start with the indentity maps
for (unsigned short instr = 0; instr < 512; instr++) s_ILInstrCategories[instr] = instr;
// Now make exceptions.
for (unsigned instr = CEE_LDARG_0; instr <= CEE_LDARG_3; instr++) s_ILInstrCategories[instr] = CEE_LDARG;
s_ILInstrCategories[CEE_LDARG_S] = CEE_LDARG;
for (unsigned instr = CEE_LDLOC_0; instr <= CEE_LDLOC_3; instr++) s_ILInstrCategories[instr] = CEE_LDLOC;
s_ILInstrCategories[CEE_LDLOC_S] = CEE_LDLOC;
for (unsigned instr = CEE_STLOC_0; instr <= CEE_STLOC_3; instr++) s_ILInstrCategories[instr] = CEE_STLOC;
s_ILInstrCategories[CEE_STLOC_S] = CEE_STLOC;
s_ILInstrCategories[CEE_LDLOCA_S] = CEE_LDLOCA;
for (unsigned instr = CEE_LDC_I4_M1; instr <= CEE_LDC_I4_S; instr++) s_ILInstrCategories[instr] = CEE_LDC_I4;
for (unsigned instr = CEE_BR_S; instr <= CEE_BLT_UN; instr++) s_ILInstrCategories[instr] = CEE_BR;
for (unsigned instr = CEE_LDIND_I1; instr <= CEE_LDIND_REF; instr++) s_ILInstrCategories[instr] = CEE_LDIND_I;
for (unsigned instr = CEE_STIND_REF; instr <= CEE_STIND_R8; instr++) s_ILInstrCategories[instr] = CEE_STIND_I;
for (unsigned instr = CEE_ADD; instr <= CEE_REM_UN; instr++) s_ILInstrCategories[instr] = CEE_ADD;
for (unsigned instr = CEE_AND; instr <= CEE_NOT; instr++) s_ILInstrCategories[instr] = CEE_AND;
for (unsigned instr = CEE_CONV_I1; instr <= CEE_CONV_U8; instr++) s_ILInstrCategories[instr] = CEE_CONV_I;
for (unsigned instr = CEE_CONV_OVF_I1_UN; instr <= CEE_CONV_OVF_U_UN; instr++) s_ILInstrCategories[instr] = CEE_CONV_I;
for (unsigned instr = CEE_LDELEM_I1; instr <= CEE_LDELEM_REF; instr++) s_ILInstrCategories[instr] = CEE_LDELEM;
for (unsigned instr = CEE_STELEM_I; instr <= CEE_STELEM_REF; instr++) s_ILInstrCategories[instr] = CEE_STELEM;
for (unsigned instr = CEE_CONV_OVF_I1; instr <= CEE_CONV_OVF_U8; instr++) s_ILInstrCategories[instr] = CEE_CONV_I;
for (unsigned instr = CEE_CONV_U2; instr <= CEE_CONV_U1; instr++) s_ILInstrCategories[instr] = CEE_CONV_I;
for (unsigned instr = CEE_CONV_OVF_I; instr <= CEE_CONV_OVF_U; instr++) s_ILInstrCategories[instr] = CEE_CONV_I;
for (unsigned instr = CEE_ADD_OVF; instr <= CEE_SUB_OVF; instr++) s_ILInstrCategories[instr] = CEE_ADD_OVF;
s_ILInstrCategories[CEE_LEAVE_S] = CEE_LEAVE;
s_ILInstrCategories[CEE_CONV_U] = CEE_CONV_I;
}
#endif // INTERP_ILINSTR_PROFILE
template<int op>
void Interpreter::CompareOp()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned op1idx = m_curStackHt - 2;
INT32 res = CompareOpRes<op>(op1idx);
OpStackSet<INT32>(op1idx, res);
OpStackTypeSet(op1idx, InterpreterType(CORINFO_TYPE_INT));
m_curStackHt--;
}
template<int op>
INT32 Interpreter::CompareOpRes(unsigned op1idx)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= op1idx + 2);
unsigned op2idx = op1idx + 1;
InterpreterType t1 = OpStackTypeGet(op1idx);
CorInfoType cit1 = t1.ToCorInfoType();
assert(IsStackNormalType(cit1));
InterpreterType t2 = OpStackTypeGet(op2idx);
CorInfoType cit2 = t2.ToCorInfoType();
assert(IsStackNormalType(cit2));
INT32 res = 0;
switch (cit1)
{
case CORINFO_TYPE_INT:
if (cit2 == CORINFO_TYPE_INT)
{
INT32 val1 = OpStackGet<INT32>(op1idx);
INT32 val2 = OpStackGet<INT32>(op2idx);
if (op == CO_EQ)
{
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
if (static_cast<UINT32>(val1) > static_cast<UINT32>(val2)) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
if (static_cast<UINT32>(val1) < static_cast<UINT32>(val2)) res = 1;
}
}
else if (cit2 == CORINFO_TYPE_NATIVEINT ||
(s_InterpreterLooseRules && cit2 == CORINFO_TYPE_BYREF) ||
(cit2 == CORINFO_TYPE_VALUECLASS
&& CorInfoTypeStackNormalize(GetTypeForPrimitiveValueClass(t2.ToClassHandle())) == CORINFO_TYPE_NATIVEINT))
{
NativeInt val1 = OpStackGet<NativeInt>(op1idx);
NativeInt val2 = OpStackGet<NativeInt>(op2idx);
if (op == CO_EQ)
{
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
if (static_cast<NativeUInt>(val1) > static_cast<NativeUInt>(val2)) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
if (static_cast<NativeUInt>(val1) < static_cast<NativeUInt>(val2)) res = 1;
}
}
else if (cit2 == CORINFO_TYPE_VALUECLASS)
{
cit2 = GetTypeForPrimitiveValueClass(t2.ToClassHandle());
INT32 val1 = OpStackGet<INT32>(op1idx);
INT32 val2 = 0;
if (CorInfoTypeStackNormalize(cit2) == CORINFO_TYPE_INT)
{
size_t sz = t2.Size(&m_interpCeeInfo);
switch (sz)
{
case 1:
if (CorInfoTypeIsUnsigned(cit2))
{
val2 = OpStackGet<UINT8>(op2idx);
}
else
{
val2 = OpStackGet<INT8>(op2idx);
}
break;
case 2:
if (CorInfoTypeIsUnsigned(cit2))
{
val2 = OpStackGet<UINT16>(op2idx);
}
else
{
val2 = OpStackGet<INT16>(op2idx);
}
break;
case 4:
val2 = OpStackGet<INT32>(op2idx);
break;
default:
UNREACHABLE();
}
}
else
{
VerificationError("Can't compare with struct type.");
}
if (op == CO_EQ)
{
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
if (static_cast<UINT32>(val1) > static_cast<UINT32>(val2)) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
if (static_cast<UINT32>(val1) < static_cast<UINT32>(val2)) res = 1;
}
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
break;
case CORINFO_TYPE_NATIVEINT:
if (cit2 == CORINFO_TYPE_NATIVEINT || cit2 == CORINFO_TYPE_INT
|| (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_LONG)
|| (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_BYREF)
|| (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_CLASS && OpStackGet<void*>(op2idx) == 0))
{
NativeInt val1 = OpStackGet<NativeInt>(op1idx);
NativeInt val2;
if (cit2 == CORINFO_TYPE_NATIVEINT)
{
val2 = OpStackGet<NativeInt>(op2idx);
}
else if (cit2 == CORINFO_TYPE_INT)
{
val2 = static_cast<NativeInt>(OpStackGet<INT32>(op2idx));
}
else if (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_LONG)
{
val2 = static_cast<NativeInt>(OpStackGet<INT64>(op2idx));
}
else if (cit2 == CORINFO_TYPE_CLASS)
{
assert(OpStackGet<void*>(op2idx) == 0);
val2 = 0;
}
else
{
assert(s_InterpreterLooseRules && cit2 == CORINFO_TYPE_BYREF);
val2 = reinterpret_cast<NativeInt>(OpStackGet<void*>(op2idx));
}
if (op == CO_EQ)
{
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
if (static_cast<NativeUInt>(val1) > static_cast<NativeUInt>(val2)) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
if (static_cast<NativeUInt>(val1) < static_cast<NativeUInt>(val2)) res = 1;
}
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
break;
case CORINFO_TYPE_LONG:
{
bool looseLong = false;
#if defined(_AMD64_)
looseLong = s_InterpreterLooseRules && (cit2 == CORINFO_TYPE_NATIVEINT || cit2 == CORINFO_TYPE_BYREF);
#endif
if (cit2 == CORINFO_TYPE_LONG || looseLong)
{
INT64 val1 = OpStackGet<INT64>(op1idx);
INT64 val2 = OpStackGet<INT64>(op2idx);
if (op == CO_EQ)
{
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
if (static_cast<UINT64>(val1) > static_cast<UINT64>(val2)) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
if (static_cast<UINT64>(val1) < static_cast<UINT64>(val2)) res = 1;
}
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
}
break;
case CORINFO_TYPE_CLASS:
case CORINFO_TYPE_STRING:
if (cit2 == CORINFO_TYPE_CLASS || cit2 == CORINFO_TYPE_STRING)
{
GCX_FORBID();
Object* val1 = OpStackGet<Object*>(op1idx);
Object* val2 = OpStackGet<Object*>(op2idx);
if (op == CO_EQ)
{
if (val1 == val2) res = 1;
}
else if (op == CO_GT_UN)
{
if (val1 != val2) res = 1;
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
break;
case CORINFO_TYPE_FLOAT:
{
bool isDouble = (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_DOUBLE);
if (cit2 == CORINFO_TYPE_FLOAT || isDouble)
{
float val1 = OpStackGet<float>(op1idx);
float val2 = (isDouble) ? (float) OpStackGet<double>(op2idx) : OpStackGet<float>(op2idx);
if (op == CO_EQ)
{
// I'm assuming IEEE math here, so that if at least one is a NAN, the comparison will fail...
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
// I'm assuming that C++ arithmetic does the right thing here with infinities and NANs.
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
// Check for NAN's here: if either is a NAN, they're unordered, so this comparison returns true.
if (_isnan(val1) || _isnan(val2)) res = 1;
else if (val1 > val2) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
// Check for NAN's here: if either is a NAN, they're unordered, so this comparison returns true.
if (_isnan(val1) || _isnan(val2)) res = 1;
else if (val1 < val2) res = 1;
}
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
}
break;
case CORINFO_TYPE_DOUBLE:
{
bool isFloat = (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_FLOAT);
if (cit2 == CORINFO_TYPE_DOUBLE || isFloat)
{
double val1 = OpStackGet<double>(op1idx);
double val2 = (isFloat) ? (double) OpStackGet<float>(op2idx) : OpStackGet<double>(op2idx);
if (op == CO_EQ)
{
// I'm assuming IEEE math here, so that if at least one is a NAN, the comparison will fail...
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
// I'm assuming that C++ arithmetic does the right thing here with infinities and NANs.
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
// Check for NAN's here: if either is a NAN, they're unordered, so this comparison returns true.
if (_isnan(val1) || _isnan(val2)) res = 1;
else if (val1 > val2) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
// Check for NAN's here: if either is a NAN, they're unordered, so this comparison returns true.
if (_isnan(val1) || _isnan(val2)) res = 1;
else if (val1 < val2) res = 1;
}
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
}
break;
case CORINFO_TYPE_BYREF:
if (cit2 == CORINFO_TYPE_BYREF || (s_InterpreterLooseRules && cit2 == CORINFO_TYPE_NATIVEINT))
{
NativeInt val1 = reinterpret_cast<NativeInt>(OpStackGet<void*>(op1idx));
NativeInt val2;
if (cit2 == CORINFO_TYPE_BYREF)
{
val2 = reinterpret_cast<NativeInt>(OpStackGet<void*>(op2idx));
}
else
{
assert(s_InterpreterLooseRules && cit2 == CORINFO_TYPE_NATIVEINT);
val2 = OpStackGet<NativeInt>(op2idx);
}
if (op == CO_EQ)
{
if (val1 == val2) res = 1;
}
else if (op == CO_GT)
{
if (val1 > val2) res = 1;
}
else if (op == CO_GT_UN)
{
if (static_cast<NativeUInt>(val1) > static_cast<NativeUInt>(val2)) res = 1;
}
else if (op == CO_LT)
{
if (val1 < val2) res = 1;
}
else
{
assert(op == CO_LT_UN);
if (static_cast<NativeUInt>(val1) < static_cast<NativeUInt>(val2)) res = 1;
}
}
else
{
VerificationError("Binary comparision operation: type mismatch.");
}
break;
case CORINFO_TYPE_VALUECLASS:
{
CorInfoType newCit1 = GetTypeForPrimitiveValueClass(t1.ToClassHandle());
if (newCit1 == CORINFO_TYPE_UNDEF)
{
VerificationError("Can't compare a value class.");
}
else
{
NYI_INTERP("Must eliminate 'punning' value classes from the ostack.");
}
}
break;
default:
assert(false); // Should not be here if the type is stack-normal.
}
return res;
}
template<bool val, int targetLen>
void Interpreter::BrOnValue()
{
assert(targetLen == 1 || targetLen == 4);
assert(m_curStackHt > 0);
unsigned stackInd = m_curStackHt - 1;
InterpreterType it = OpStackTypeGet(stackInd);
// It shouldn't be a value class, unless it's a punning name for a primitive integral type.
if (it.ToCorInfoType() == CORINFO_TYPE_VALUECLASS)
{
GCX_PREEMP();
CorInfoType cit = m_interpCeeInfo.getTypeForPrimitiveValueClass(it.ToClassHandle());
if (CorInfoTypeIsIntegral(cit))
{
it = InterpreterType(cit);
}
else
{
VerificationError("Can't branch on the value of a value type that is not a primitive type.");
}
}
#ifdef _DEBUG
switch (it.ToCorInfoType())
{
case CORINFO_TYPE_FLOAT:
case CORINFO_TYPE_DOUBLE:
VerificationError("Can't branch on the value of a float or double.");
break;
default:
break;
}
#endif // _DEBUG
switch (it.SizeNotStruct())
{
case 4:
{
INT32 branchVal = OpStackGet<INT32>(stackInd);
BrOnValueTakeBranch((branchVal != 0) == val, targetLen);
}
break;
case 8:
{
INT64 branchVal = OpStackGet<INT64>(stackInd);
BrOnValueTakeBranch((branchVal != 0) == val, targetLen);
}
break;
// The value-class case handled above makes sizes 1 and 2 possible.
case 1:
{
INT8 branchVal = OpStackGet<INT8>(stackInd);
BrOnValueTakeBranch((branchVal != 0) == val, targetLen);
}
break;
case 2:
{
INT16 branchVal = OpStackGet<INT16>(stackInd);
BrOnValueTakeBranch((branchVal != 0) == val, targetLen);
}
break;
default:
UNREACHABLE();
break;
}
m_curStackHt = stackInd;
}
// compOp is a member of the BranchComparisonOp enumeration.
template<int compOp, bool reverse, int targetLen>
void Interpreter::BrOnComparison()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(targetLen == 1 || targetLen == 4);
assert(m_curStackHt >= 2);
unsigned v1Ind = m_curStackHt - 2;
INT32 res = CompareOpRes<compOp>(v1Ind);
if (reverse)
{
res = (res == 0) ? 1 : 0;
}
if (res)
{
int offset;
if (targetLen == 1)
{
// BYTE is unsigned...
offset = getI1(m_ILCodePtr + 1);
}
else
{
offset = getI4LittleEndian(m_ILCodePtr + 1);
}
// 1 is the size of the current instruction; offset is relative to start of next.
if (offset < 0)
{
// Backwards branch; enable caching.
BackwardsBranchActions(offset);
}
ExecuteBranch(m_ILCodePtr + 1 + targetLen + offset);
}
else
{
m_ILCodePtr += targetLen + 1;
}
m_curStackHt -= 2;
}
void Interpreter::LdFld(FieldDesc* fldIn)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
BarrierIfVolatile();
FieldDesc* fld = fldIn;
CORINFO_CLASS_HANDLE valClsHnd = NULL;
DWORD fldOffset;
{
GCX_PREEMP();
unsigned ilOffset = CurOffset();
if (fld == NULL && s_InterpreterUseCaching)
{
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_LdFld]);
#endif // INTERP_TRACING
fld = GetCachedInstanceField(ilOffset);
}
if (fld == NULL)
{
unsigned tok = getU4LittleEndian(m_ILCodePtr + sizeof(BYTE));
fld = FindField(tok InterpTracingArg(RTK_LdFld));
assert(fld != NULL);
fldOffset = fld->GetOffset();
if (s_InterpreterUseCaching && fldOffset < FIELD_OFFSET_LAST_REAL_OFFSET)
CacheInstanceField(ilOffset, fld);
}
else
{
fldOffset = fld->GetOffset();
}
}
CorInfoType valCit = CEEInfo::asCorInfoType(fld->GetFieldType());
// If "fldIn" is non-NULL, it's not a "real" LdFld -- the caller should handle updating the instruction pointer.
if (fldIn == NULL)
m_ILCodePtr += 5; // Last use above, so update now.
// We need to construct the interpreter type for a struct type before we try to do coordinated
// pushes of the value and type on the opstacks -- these must be atomic wrt GC, and constructing
// a struct InterpreterType transitions to preemptive mode.
InterpreterType structValIT;
if (valCit == CORINFO_TYPE_VALUECLASS)
{
GCX_PREEMP();
valCit = m_interpCeeInfo.getFieldType(CORINFO_FIELD_HANDLE(fld), &valClsHnd);
structValIT = InterpreterType(&m_interpCeeInfo, valClsHnd);
}
UINT sz = fld->GetSize();
// Live vars: valCit, structValIt
assert(m_curStackHt > 0);
unsigned stackInd = m_curStackHt - 1;
InterpreterType addrIt = OpStackTypeGet(stackInd);
CorInfoType addrCit = addrIt.ToCorInfoType();
bool isUnsigned;
if (addrCit == CORINFO_TYPE_CLASS)
{
OBJECTREF obj = OBJECTREF(OpStackGet<Object*>(stackInd));
ThrowOnInvalidPointer(OBJECTREFToObject(obj));
if (valCit == CORINFO_TYPE_VALUECLASS)
{
void* srcPtr = fld->GetInstanceAddress(obj);
// srcPtr is now vulnerable.
GCX_FORBID();
MethodTable* valClsMT = GetMethodTableFromClsHnd(valClsHnd);
if (sz > sizeof(INT64))
{
// Large struct case: allocate space on the large struct operand stack.
void* destPtr = LargeStructOperandStackPush(sz);
OpStackSet<void*>(stackInd, destPtr);
CopyValueClass(destPtr, srcPtr, valClsMT, obj->GetAppDomain());
}
else
{
// Small struct case -- is inline in operand stack.
OpStackSet<INT64>(stackInd, GetSmallStructValue(srcPtr, sz));
}
}
else
{
BYTE* fldStart = dac_cast<PTR_BYTE>(OBJECTREFToObject(obj)) + sizeof(Object) + fldOffset;
// fldStart is now a vulnerable byref
GCX_FORBID();
switch (sz)
{
case 1:
isUnsigned = CorInfoTypeIsUnsigned(valCit);
if (isUnsigned)
{
OpStackSet<UINT32>(stackInd, *reinterpret_cast<UINT8*>(fldStart));
}
else
{
OpStackSet<INT32>(stackInd, *reinterpret_cast<INT8*>(fldStart));
}
break;
case 2:
isUnsigned = CorInfoTypeIsUnsigned(valCit);
if (isUnsigned)
{
OpStackSet<UINT32>(stackInd, *reinterpret_cast<UINT16*>(fldStart));
}
else
{
OpStackSet<INT32>(stackInd, *reinterpret_cast<INT16*>(fldStart));
}
break;
case 4:
OpStackSet<INT32>(stackInd, *reinterpret_cast<INT32*>(fldStart));
break;
case 8:
OpStackSet<INT64>(stackInd, *reinterpret_cast<INT64*>(fldStart));
break;
default:
_ASSERTE_MSG(false, "Should not reach here.");
break;
}
}
}
else
{
INT8* ptr = NULL;
if (addrCit == CORINFO_TYPE_VALUECLASS)
{
size_t addrSize = addrIt.Size(&m_interpCeeInfo);
// The ECMA spec allows ldfld to be applied to "an instance of a value type."
// We will take the address of the ostack entry.
if (addrIt.IsLargeStruct(&m_interpCeeInfo))
{
ptr = reinterpret_cast<INT8*>(OpStackGet<void*>(stackInd));
// This is delicate. I'm going to pop the large struct off the large-struct stack
// now, even though the field value we push may go back on the large object stack.
// We rely on the fact that this instruction doesn't do any other pushing, and
// we assume that LargeStructOperandStackPop does not actually deallocate any memory,
// and we rely on memcpy properly handling possibly-overlapping regions being copied.
// Finally (wow, this really *is* delicate), we rely on the property that the large-struct
// stack pop operation doesn't deallocate memory (the size of the allocated memory for the
// large-struct stack only grows in a method execution), and that if we push the field value
// on the large struct stack below, the size of the pushed item is at most the size of the
// popped item, so the stack won't grow (which would allow a dealloc/realloc).
// (All in all, maybe it would be better to just copy the value elsewhere then pop...but
// that wouldn't be very aggressive.)
LargeStructOperandStackPop(addrSize, ptr);
}
else
{
ptr = reinterpret_cast<INT8*>(OpStackGetAddr(stackInd, addrSize));
}
}
else
{
assert(CorInfoTypeIsPointer(addrCit));
ptr = OpStackGet<INT8*>(stackInd);
ThrowOnInvalidPointer(ptr);
}
assert(ptr != NULL);
ptr += fldOffset;
if (valCit == CORINFO_TYPE_VALUECLASS)
{
if (sz > sizeof(INT64))
{
// Large struct case.
void* dstPtr = LargeStructOperandStackPush(sz);
memcpy(dstPtr, ptr, sz);
OpStackSet<void*>(stackInd, dstPtr);
}
else
{
// Small struct case -- is inline in operand stack.
OpStackSet<INT64>(stackInd, GetSmallStructValue(ptr, sz));
}
OpStackTypeSet(stackInd, structValIT.StackNormalize());
return;
}
// Otherwise...
switch (sz)
{
case 1:
isUnsigned = CorInfoTypeIsUnsigned(valCit);
if (isUnsigned)
{
OpStackSet<UINT32>(stackInd, *reinterpret_cast<UINT8*>(ptr));
}
else
{
OpStackSet<INT32>(stackInd, *reinterpret_cast<INT8*>(ptr));
}
break;
case 2:
isUnsigned = CorInfoTypeIsUnsigned(valCit);
if (isUnsigned)
{
OpStackSet<UINT32>(stackInd, *reinterpret_cast<UINT16*>(ptr));
}
else
{
OpStackSet<INT32>(stackInd, *reinterpret_cast<INT16*>(ptr));
}
break;
case 4:
OpStackSet<INT32>(stackInd, *reinterpret_cast<INT32*>(ptr));
break;
case 8:
OpStackSet<INT64>(stackInd, *reinterpret_cast<INT64*>(ptr));
break;
}
}
if (valCit == CORINFO_TYPE_VALUECLASS)
{
OpStackTypeSet(stackInd, structValIT.StackNormalize());
}
else
{
OpStackTypeSet(stackInd, InterpreterType(valCit).StackNormalize());
}
}
void Interpreter::LdFldA()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
unsigned tok = getU4LittleEndian(m_ILCodePtr + sizeof(BYTE));
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_LdFldA]);
#endif // INTERP_TRACING
unsigned offset = CurOffset();
m_ILCodePtr += 5; // Last use above, so update now.
FieldDesc* fld = NULL;
if (s_InterpreterUseCaching) fld = GetCachedInstanceField(offset);
if (fld == NULL)
{
GCX_PREEMP();
fld = FindField(tok InterpTracingArg(RTK_LdFldA));
if (s_InterpreterUseCaching) CacheInstanceField(offset, fld);
}
assert(m_curStackHt > 0);
unsigned stackInd = m_curStackHt - 1;
CorInfoType addrCit = OpStackTypeGet(stackInd).ToCorInfoType();
if (addrCit == CORINFO_TYPE_BYREF || addrCit == CORINFO_TYPE_CLASS || addrCit == CORINFO_TYPE_NATIVEINT)
{
NativeInt ptr = OpStackGet<NativeInt>(stackInd);
ThrowOnInvalidPointer((void*)ptr);
// The "offset" below does not include the Object (i.e., the MethodTable pointer) for object pointers, so add that in first.
if (addrCit == CORINFO_TYPE_CLASS) ptr += sizeof(Object);
// Now add the offset.
ptr += fld->GetOffset();
OpStackSet<NativeInt>(stackInd, ptr);
if (addrCit == CORINFO_TYPE_NATIVEINT)
{
OpStackTypeSet(stackInd, InterpreterType(CORINFO_TYPE_NATIVEINT));
}
else
{
OpStackTypeSet(stackInd, InterpreterType(CORINFO_TYPE_BYREF));
}
}
else
{
VerificationError("LdfldA requires object reference, managed or unmanaged pointer type.");
}
}
void Interpreter::StFld()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_StFld]);
#endif // INTERP_TRACING
FieldDesc* fld = NULL;
DWORD fldOffset;
{
unsigned ilOffset = CurOffset();
if (s_InterpreterUseCaching) fld = GetCachedInstanceField(ilOffset);
if (fld == NULL)
{
unsigned tok = getU4LittleEndian(m_ILCodePtr + sizeof(BYTE));
GCX_PREEMP();
fld = FindField(tok InterpTracingArg(RTK_StFld));
assert(fld != NULL);
fldOffset = fld->GetOffset();
if (s_InterpreterUseCaching && fldOffset < FIELD_OFFSET_LAST_REAL_OFFSET)
CacheInstanceField(ilOffset, fld);
}
else
{
fldOffset = fld->GetOffset();
}
}
m_ILCodePtr += 5; // Last use above, so update now.
UINT sz = fld->GetSize();
assert(m_curStackHt >= 2);
unsigned addrInd = m_curStackHt - 2;
CorInfoType addrCit = OpStackTypeGet(addrInd).ToCorInfoType();
unsigned valInd = m_curStackHt - 1;
CorInfoType valCit = OpStackTypeGet(valInd).ToCorInfoType();
assert(IsStackNormalType(addrCit) && IsStackNormalType(valCit));
m_curStackHt -= 2;
if (addrCit == CORINFO_TYPE_CLASS)
{
OBJECTREF obj = OBJECTREF(OpStackGet<Object*>(addrInd));
ThrowOnInvalidPointer(OBJECTREFToObject(obj));
if (valCit == CORINFO_TYPE_CLASS)
{
fld->SetRefValue(obj, ObjectToOBJECTREF(OpStackGet<Object*>(valInd)));
}
else if (valCit == CORINFO_TYPE_VALUECLASS)
{
MethodTable* valClsMT = GetMethodTableFromClsHnd(OpStackTypeGet(valInd).ToClassHandle());
void* destPtr = fld->GetInstanceAddress(obj);
// destPtr is now a vulnerable byref, so can't do GC.
GCX_FORBID();
// I use GCSafeMemCpy below to ensure that write barriers happen for the case in which
// the value class contains GC pointers. We could do better...
if (sz > sizeof(INT64))
{
// Large struct case: stack slot contains pointer...
void* srcPtr = OpStackGet<void*>(valInd);
CopyValueClassUnchecked(destPtr, srcPtr, valClsMT);
LargeStructOperandStackPop(sz, srcPtr);
}
else
{
// Small struct case -- is inline in operand stack.
CopyValueClassUnchecked(destPtr, OpStackGetAddr(valInd, sz), valClsMT);
}
BarrierIfVolatile();
return;
}
else
{
#ifdef _DEBUG
if (obj->IsTransparentProxy()) NYI_INTERP("Stores to thunking objects.");
#endif
BYTE* fldStart = dac_cast<PTR_BYTE>(OBJECTREFToObject(obj)) + sizeof(Object) + fldOffset;
// fldStart is now a vulnerable byref
GCX_FORBID();
switch (sz)
{
case 1:
*reinterpret_cast<INT8*>(fldStart) = OpStackGet<INT8>(valInd);
break;
case 2:
*reinterpret_cast<INT16*>(fldStart) = OpStackGet<INT16>(valInd);
break;
case 4:
*reinterpret_cast<INT32*>(fldStart) = OpStackGet<INT32>(valInd);
break;
case 8:
*reinterpret_cast<INT64*>(fldStart) = OpStackGet<INT64>(valInd);
break;
}
}
}
else
{
assert(addrCit == CORINFO_TYPE_BYREF || addrCit == CORINFO_TYPE_NATIVEINT);
INT8* destPtr = OpStackGet<INT8*>(addrInd);
ThrowOnInvalidPointer(destPtr);
destPtr += fldOffset;
if (valCit == CORINFO_TYPE_VALUECLASS)
{
MethodTable* valClsMT = GetMethodTableFromClsHnd(OpStackTypeGet(valInd).ToClassHandle());
// I use GCSafeMemCpy below to ensure that write barriers happen for the case in which
// the value class contains GC pointers. We could do better...
if (sz > sizeof(INT64))
{
// Large struct case: stack slot contains pointer...
void* srcPtr = OpStackGet<void*>(valInd);
CopyValueClassUnchecked(destPtr, srcPtr, valClsMT);
LargeStructOperandStackPop(sz, srcPtr);
}
else
{
// Small struct case -- is inline in operand stack.
CopyValueClassUnchecked(destPtr, OpStackGetAddr(valInd, sz), valClsMT);
}
BarrierIfVolatile();
return;
}
else if (valCit == CORINFO_TYPE_CLASS)
{
OBJECTREF val = ObjectToOBJECTREF(OpStackGet<Object*>(valInd));
SetObjectReferenceUnchecked(reinterpret_cast<OBJECTREF*>(destPtr), val);
}
else
{
switch (sz)
{
case 1:
*reinterpret_cast<INT8*>(destPtr) = OpStackGet<INT8>(valInd);
break;
case 2:
*reinterpret_cast<INT16*>(destPtr) = OpStackGet<INT16>(valInd);
break;
case 4:
*reinterpret_cast<INT32*>(destPtr) = OpStackGet<INT32>(valInd);
break;
case 8:
*reinterpret_cast<INT64*>(destPtr) = OpStackGet<INT64>(valInd);
break;
}
}
}
BarrierIfVolatile();
}
bool Interpreter::StaticFldAddrWork(CORINFO_ACCESS_FLAGS accessFlgs, /*out (byref)*/void** pStaticFieldAddr, /*out*/InterpreterType* pit, /*out*/UINT* pFldSize, /*out*/bool* pManagedMem)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
bool isCacheable = true;
*pManagedMem = true; // Default result.
unsigned tok = getU4LittleEndian(m_ILCodePtr + sizeof(BYTE));
m_ILCodePtr += 5; // Above is last use of m_ILCodePtr in this method, so update now.
FieldDesc* fld;
CORINFO_FIELD_INFO fldInfo;
CORINFO_RESOLVED_TOKEN fldTok;
void* pFldAddr = NULL;
{
{
GCX_PREEMP();
ResolveToken(&fldTok, tok, CORINFO_TOKENKIND_Field InterpTracingArg(RTK_SFldAddr));
fld = reinterpret_cast<FieldDesc*>(fldTok.hField);
m_interpCeeInfo.getFieldInfo(&fldTok, m_methInfo->m_method, accessFlgs, &fldInfo);
}
EnsureClassInit(GetMethodTableFromClsHnd(fldTok.hClass));
if (fldInfo.fieldAccessor == CORINFO_FIELD_STATIC_TLS)
{
NYI_INTERP("Thread-local static.");
}
else if (fldInfo.fieldAccessor == CORINFO_FIELD_STATIC_SHARED_STATIC_HELPER
|| fldInfo.fieldAccessor == CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER)
{
*pStaticFieldAddr = fld->GetCurrentStaticAddress();
isCacheable = false;
}
else
{
*pStaticFieldAddr = fld->GetCurrentStaticAddress();
}
}
if (fldInfo.structType != NULL && fldInfo.fieldType != CORINFO_TYPE_CLASS && fldInfo.fieldType != CORINFO_TYPE_PTR)
{
*pit = InterpreterType(&m_interpCeeInfo, fldInfo.structType);
if ((fldInfo.fieldFlags & CORINFO_FLG_FIELD_UNMANAGED) == 0)
{
// For valuetypes in managed memory, the address returned contains a pointer into the heap, to a boxed version of the
// static variable; return a pointer to the boxed struct.
isCacheable = false;
}
else
{
*pManagedMem = false;
}
}
else
{
*pit = InterpreterType(fldInfo.fieldType);
}
*pFldSize = fld->GetSize();
return isCacheable;
}
void Interpreter::LdSFld()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
InterpreterType fldIt;
UINT sz;
bool managedMem;
void* srcPtr = NULL;
BarrierIfVolatile();
GCPROTECT_BEGININTERIOR(srcPtr);
StaticFldAddr(CORINFO_ACCESS_GET, &srcPtr, &fldIt, &sz, &managedMem);
bool isUnsigned;
if (fldIt.IsStruct())
{
// Large struct case.
CORINFO_CLASS_HANDLE sh = fldIt.ToClassHandle();
// This call is GC_TRIGGERS, so do it before we copy the value: no GC after this,
// until the op stacks and ht are consistent.
OpStackTypeSet(m_curStackHt, InterpreterType(&m_interpCeeInfo, sh).StackNormalize());
if (fldIt.IsLargeStruct(&m_interpCeeInfo))
{
void* dstPtr = LargeStructOperandStackPush(sz);
memcpy(dstPtr, srcPtr, sz);
OpStackSet<void*>(m_curStackHt, dstPtr);
}
else
{
OpStackSet<INT64>(m_curStackHt, GetSmallStructValue(srcPtr, sz));
}
}
else
{
CorInfoType valCit = fldIt.ToCorInfoType();
switch (sz)
{
case 1:
isUnsigned = CorInfoTypeIsUnsigned(valCit);
if (isUnsigned)
{
OpStackSet<UINT32>(m_curStackHt, *reinterpret_cast<UINT8*>(srcPtr));
}
else
{
OpStackSet<INT32>(m_curStackHt, *reinterpret_cast<INT8*>(srcPtr));
}
break;
case 2:
isUnsigned = CorInfoTypeIsUnsigned(valCit);
if (isUnsigned)
{
OpStackSet<UINT32>(m_curStackHt, *reinterpret_cast<UINT16*>(srcPtr));
}
else
{
OpStackSet<INT32>(m_curStackHt, *reinterpret_cast<INT16*>(srcPtr));
}
break;
case 4:
OpStackSet<INT32>(m_curStackHt, *reinterpret_cast<INT32*>(srcPtr));
break;
case 8:
OpStackSet<INT64>(m_curStackHt, *reinterpret_cast<INT64*>(srcPtr));
break;
default:
_ASSERTE_MSG(false, "LdSFld: this should have exhausted all the possible sizes.");
break;
}
OpStackTypeSet(m_curStackHt, fldIt.StackNormalize());
}
m_curStackHt++;
GCPROTECT_END();
}
void Interpreter::EnsureClassInit(MethodTable* pMT)
{
if (!pMT->IsClassInited())
{
pMT->CheckRestore();
// This is tantamount to a call, so exempt it from the cycle count.
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 startCycles;
bool b = CycleTimer::GetThreadCyclesS(&startCycles); assert(b);
#endif // INTERP_ILCYCLE_PROFILE
pMT->CheckRunClassInitThrowing();
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 endCycles;
b = CycleTimer::GetThreadCyclesS(&endCycles); assert(b);
m_exemptCycles += (endCycles - startCycles);
#endif // INTERP_ILCYCLE_PROFILE
}
}
void Interpreter::LdSFldA()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
InterpreterType fldIt;
UINT fldSz;
bool managedMem;
void* srcPtr = NULL;
GCPROTECT_BEGININTERIOR(srcPtr);
StaticFldAddr(CORINFO_ACCESS_ADDRESS, &srcPtr, &fldIt, &fldSz, &managedMem);
OpStackSet<void*>(m_curStackHt, srcPtr);
if (managedMem)
{
// Static variable in managed memory...
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_BYREF));
}
else
{
// RVA is in unmanaged memory.
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_NATIVEINT));
}
m_curStackHt++;
GCPROTECT_END();
}
void Interpreter::StSFld()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
InterpreterType fldIt;
UINT sz;
bool managedMem;
void* dstPtr = NULL;
GCPROTECT_BEGININTERIOR(dstPtr);
StaticFldAddr(CORINFO_ACCESS_SET, &dstPtr, &fldIt, &sz, &managedMem);
m_curStackHt--;
InterpreterType valIt = OpStackTypeGet(m_curStackHt);
CorInfoType valCit = valIt.ToCorInfoType();
if (valCit == CORINFO_TYPE_VALUECLASS)
{
MethodTable* valClsMT = GetMethodTableFromClsHnd(valIt.ToClassHandle());
if (sz > sizeof(INT64))
{
// Large struct case: value in operand stack is indirect pointer.
void* srcPtr = OpStackGet<void*>(m_curStackHt);
CopyValueClassUnchecked(dstPtr, srcPtr, valClsMT);
LargeStructOperandStackPop(sz, srcPtr);
}
else
{
// Struct value is inline in the operand stack.
CopyValueClassUnchecked(dstPtr, OpStackGetAddr(m_curStackHt, sz), valClsMT);
}
}
else if (valCit == CORINFO_TYPE_CLASS)
{
SetObjectReferenceUnchecked(reinterpret_cast<OBJECTREF*>(dstPtr), ObjectToOBJECTREF(OpStackGet<Object*>(m_curStackHt)));
}
else
{
switch (sz)
{
case 1:
*reinterpret_cast<UINT8*>(dstPtr) = OpStackGet<UINT8>(m_curStackHt);
break;
case 2:
*reinterpret_cast<UINT16*>(dstPtr) = OpStackGet<UINT16>(m_curStackHt);
break;
case 4:
*reinterpret_cast<UINT32*>(dstPtr) = OpStackGet<UINT32>(m_curStackHt);
break;
case 8:
*reinterpret_cast<UINT64*>(dstPtr) = OpStackGet<UINT64>(m_curStackHt);
break;
default:
_ASSERTE_MSG(false, "This should have exhausted all the possible sizes.");
break;
}
}
GCPROTECT_END();
BarrierIfVolatile();
}
template<typename T, bool IsObjType, CorInfoType cit>
void Interpreter::LdElemWithType()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned arrInd = m_curStackHt - 2;
unsigned indexInd = m_curStackHt - 1;
assert(OpStackTypeGet(arrInd).ToCorInfoType() == CORINFO_TYPE_CLASS);
ArrayBase* a = OpStackGet<ArrayBase*>(arrInd);
ThrowOnInvalidPointer(a);
int len = a->GetNumComponents();
CorInfoType indexCit = OpStackTypeGet(indexInd).ToCorInfoType();
if (indexCit == CORINFO_TYPE_INT)
{
int index = OpStackGet<INT32>(indexInd);
if (index < 0 || index >= len) ThrowArrayBoundsException();
GCX_FORBID();
if (IsObjType)
{
OBJECTREF res = reinterpret_cast<PtrArray*>(a)->GetAt(index);
OpStackSet<OBJECTREF>(arrInd, res);
}
else
{
T res = reinterpret_cast<Array<T>*>(a)->GetDirectConstPointerToNonObjectElements()[index];
if (cit == CORINFO_TYPE_INT)
{
// Widen narrow types.
int ires = (int)res;
OpStackSet<int>(arrInd, ires);
}
else
{
OpStackSet<T>(arrInd, res);
}
}
}
else
{
assert(indexCit == CORINFO_TYPE_NATIVEINT);
NativeInt index = OpStackGet<NativeInt>(indexInd);
if (index < 0 || index >= NativeInt(len)) ThrowArrayBoundsException();
GCX_FORBID();
if (IsObjType)
{
OBJECTREF res = reinterpret_cast<PtrArray*>(a)->GetAt(index);
OpStackSet<OBJECTREF>(arrInd, res);
}
else
{
T res = reinterpret_cast<Array<T>*>(a)->GetDirectConstPointerToNonObjectElements()[index];
OpStackSet<T>(arrInd, res);
}
}
OpStackTypeSet(arrInd, InterpreterType(cit));
m_curStackHt--;
}
template<typename T, bool IsObjType>
void Interpreter::StElemWithType()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 3);
unsigned arrInd = m_curStackHt - 3;
unsigned indexInd = m_curStackHt - 2;
unsigned valInd = m_curStackHt - 1;
assert(OpStackTypeGet(arrInd).ToCorInfoType() == CORINFO_TYPE_CLASS);
ArrayBase* a = OpStackGet<ArrayBase*>(arrInd);
ThrowOnInvalidPointer(a);
int len = a->GetNumComponents();
CorInfoType indexCit = OpStackTypeGet(indexInd).ToCorInfoType();
if (indexCit == CORINFO_TYPE_INT)
{
int index = OpStackGet<INT32>(indexInd);
if (index < 0 || index >= len) ThrowArrayBoundsException();
if (IsObjType)
{
struct _gc {
OBJECTREF val;
OBJECTREF a;
} gc;
gc.val = ObjectToOBJECTREF(OpStackGet<Object*>(valInd));
gc.a = ObjectToOBJECTREF(a);
GCPROTECT_BEGIN(gc);
if (gc.val != NULL &&
!ObjIsInstanceOf(OBJECTREFToObject(gc.val), reinterpret_cast<PtrArray*>(a)->GetArrayElementTypeHandle()))
COMPlusThrow(kArrayTypeMismatchException);
reinterpret_cast<PtrArray*>(OBJECTREFToObject(gc.a))->SetAt(index, gc.val);
GCPROTECT_END();
}
else
{
GCX_FORBID();
T val = OpStackGet<T>(valInd);
reinterpret_cast<Array<T>*>(a)->GetDirectPointerToNonObjectElements()[index] = val;
}
}
else
{
assert(indexCit == CORINFO_TYPE_NATIVEINT);
NativeInt index = OpStackGet<NativeInt>(indexInd);
if (index < 0 || index >= NativeInt(len)) ThrowArrayBoundsException();
if (IsObjType)
{
struct _gc {
OBJECTREF val;
OBJECTREF a;
} gc;
gc.val = ObjectToOBJECTREF(OpStackGet<Object*>(valInd));
gc.a = ObjectToOBJECTREF(a);
GCPROTECT_BEGIN(gc);
if (gc.val != NULL &&
!ObjIsInstanceOf(OBJECTREFToObject(gc.val), reinterpret_cast<PtrArray*>(a)->GetArrayElementTypeHandle()))
COMPlusThrow(kArrayTypeMismatchException);
reinterpret_cast<PtrArray*>(OBJECTREFToObject(gc.a))->SetAt(index, gc.val);
GCPROTECT_END();
}
else
{
GCX_FORBID();
T val = OpStackGet<T>(valInd);
reinterpret_cast<Array<T>*>(a)->GetDirectPointerToNonObjectElements()[index] = val;
}
}
m_curStackHt -= 3;
}
template<bool takeAddress>
void Interpreter::LdElem()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned arrInd = m_curStackHt - 2;
unsigned indexInd = m_curStackHt - 1;
unsigned elemTypeTok = getU4LittleEndian(m_ILCodePtr + 1);
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_LdElem]);
#endif // INTERP_TRACING
unsigned ilOffset = CurOffset();
CORINFO_CLASS_HANDLE clsHnd = NULL;
if (s_InterpreterUseCaching) clsHnd = GetCachedClassHandle(ilOffset);
if (clsHnd == NULL)
{
CORINFO_RESOLVED_TOKEN elemTypeResolvedTok;
{
GCX_PREEMP();
ResolveToken(&elemTypeResolvedTok, elemTypeTok, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_LdElem));
clsHnd = elemTypeResolvedTok.hClass;
}
if (s_InterpreterUseCaching) CacheClassHandle(ilOffset, clsHnd);
}
CorInfoType elemCit = ::asCorInfoType(clsHnd);
m_ILCodePtr += 5;
InterpreterType elemIt;
if (elemCit == CORINFO_TYPE_VALUECLASS)
{
elemIt = InterpreterType(&m_interpCeeInfo, clsHnd);
}
else
{
elemIt = InterpreterType(elemCit);
}
assert(OpStackTypeGet(arrInd).ToCorInfoType() == CORINFO_TYPE_CLASS);
ArrayBase* a = OpStackGet<ArrayBase*>(arrInd);
ThrowOnInvalidPointer(a);
int len = a->GetNumComponents();
NativeInt index;
{
GCX_FORBID();
CorInfoType indexCit = OpStackTypeGet(indexInd).ToCorInfoType();
if (indexCit == CORINFO_TYPE_INT)
{
index = static_cast<NativeInt>(OpStackGet<INT32>(indexInd));
}
else
{
assert(indexCit == CORINFO_TYPE_NATIVEINT);
index = OpStackGet<NativeInt>(indexInd);
}
}
if (index < 0 || index >= len) ThrowArrayBoundsException();
bool throwTypeMismatch = NULL;
{
void* elemPtr = a->GetDataPtr() + a->GetComponentSize() * index;
// elemPtr is now a vulnerable byref.
GCX_FORBID();
if (takeAddress)
{
// If the element type is a class type, may have to do a type check.
if (elemCit == CORINFO_TYPE_CLASS)
{
// Unless there was a readonly prefix, which removes the need to
// do the (dynamic) type check.
if (m_readonlyFlag)
{
// Consume the readonly prefix, and don't do the type check below.
m_readonlyFlag = false;
}
else
{
PtrArray* pa = reinterpret_cast<PtrArray*>(a);
// The element array type must be exactly the referent type of the managed
// pointer we'll be creating.
if (pa->GetArrayElementTypeHandle() != TypeHandle(clsHnd))
{
throwTypeMismatch = true;
}
}
}
if (!throwTypeMismatch)
{
// If we're not going to throw the exception, we can take the address.
OpStackSet<void*>(arrInd, elemPtr);
OpStackTypeSet(arrInd, InterpreterType(CORINFO_TYPE_BYREF));
m_curStackHt--;
}
}
else
{
m_curStackHt -= 2;
LdFromMemAddr(elemPtr, elemIt);
return;
}
}
// If we're going to throw, we do the throw outside the GCX_FORBID region above, since it requires GC_TRIGGERS.
if (throwTypeMismatch)
{
COMPlusThrow(kArrayTypeMismatchException);
}
}
void Interpreter::StElem()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 3);
unsigned arrInd = m_curStackHt - 3;
unsigned indexInd = m_curStackHt - 2;
unsigned valInd = m_curStackHt - 1;
CorInfoType valCit = OpStackTypeGet(valInd).ToCorInfoType();
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_StElem]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE typeFromTok = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_StElem));
m_ILCodePtr += 5;
CorInfoType typeFromTokCit;
{
GCX_PREEMP();
typeFromTokCit = ::asCorInfoType(typeFromTok);
}
size_t sz;
#ifdef _DEBUG
InterpreterType typeFromTokIt;
#endif // _DEBUG
if (typeFromTokCit == CORINFO_TYPE_VALUECLASS)
{
GCX_PREEMP();
sz = getClassSize(typeFromTok);
#ifdef _DEBUG
typeFromTokIt = InterpreterType(&m_interpCeeInfo, typeFromTok);
#endif // _DEBUG
}
else
{
sz = CorInfoTypeSize(typeFromTokCit);
#ifdef _DEBUG
typeFromTokIt = InterpreterType(typeFromTokCit);
#endif // _DEBUG
}
#ifdef _DEBUG
// Instead of debug, I need to parameterize the interpreter at the top level over whether
// to do checks corresponding to verification.
if (typeFromTokIt.StackNormalize().ToCorInfoType() != valCit)
{
// This is obviously only a partial test of the required condition.
VerificationError("Value in stelem does not have the required type.");
}
#endif // _DEBUG
assert(OpStackTypeGet(arrInd).ToCorInfoType() == CORINFO_TYPE_CLASS);
ArrayBase* a = OpStackGet<ArrayBase*>(arrInd);
ThrowOnInvalidPointer(a);
int len = a->GetNumComponents();
CorInfoType indexCit = OpStackTypeGet(indexInd).ToCorInfoType();
NativeInt index = 0;
if (indexCit == CORINFO_TYPE_INT)
{
index = static_cast<NativeInt>(OpStackGet<INT32>(indexInd));
}
else
{
index = OpStackGet<NativeInt>(indexInd);
}
if (index < 0 || index >= len) ThrowArrayBoundsException();
if (typeFromTokCit == CORINFO_TYPE_CLASS)
{
struct _gc {
OBJECTREF val;
OBJECTREF a;
} gc;
gc.val = ObjectToOBJECTREF(OpStackGet<Object*>(valInd));
gc.a = ObjectToOBJECTREF(a);
GCPROTECT_BEGIN(gc);
if (gc.val != NULL &&
!ObjIsInstanceOf(OBJECTREFToObject(gc.val), reinterpret_cast<PtrArray*>(a)->GetArrayElementTypeHandle()))
COMPlusThrow(kArrayTypeMismatchException);
reinterpret_cast<PtrArray*>(OBJECTREFToObject(gc.a))->SetAt(index, gc.val);
GCPROTECT_END();
}
else
{
GCX_FORBID();
void* destPtr = a->GetDataPtr() + index * sz;;
if (typeFromTokCit == CORINFO_TYPE_VALUECLASS)
{
MethodTable* valClsMT = GetMethodTableFromClsHnd(OpStackTypeGet(valInd).ToClassHandle());
// I use GCSafeMemCpy below to ensure that write barriers happen for the case in which
// the value class contains GC pointers. We could do better...
if (sz > sizeof(UINT64))
{
// Large struct case: stack slot contains pointer...
void* src = OpStackGet<void*>(valInd);
CopyValueClassUnchecked(destPtr, src, valClsMT);
LargeStructOperandStackPop(sz, src);
}
else
{
// Small struct case -- is inline in operand stack.
CopyValueClassUnchecked(destPtr, OpStackGetAddr(valInd, sz), valClsMT);
}
}
else
{
switch (sz)
{
case 1:
*reinterpret_cast<INT8*>(destPtr) = OpStackGet<INT8>(valInd);
break;
case 2:
*reinterpret_cast<INT16*>(destPtr) = OpStackGet<INT16>(valInd);
break;
case 4:
*reinterpret_cast<INT32*>(destPtr) = OpStackGet<INT32>(valInd);
break;
case 8:
*reinterpret_cast<INT64*>(destPtr) = OpStackGet<INT64>(valInd);
break;
}
}
}
m_curStackHt -= 3;
}
void Interpreter::InitBlk()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 3);
unsigned addrInd = m_curStackHt - 3;
unsigned valInd = m_curStackHt - 2;
unsigned sizeInd = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType addrCIT = OpStackTypeGet(addrInd).ToCorInfoType();
bool addrValidType = (addrCIT == CORINFO_TYPE_NATIVEINT || addrCIT == CORINFO_TYPE_BYREF);
#if defined(_AMD64_)
if (s_InterpreterLooseRules && addrCIT == CORINFO_TYPE_LONG)
addrValidType = true;
#endif
if (!addrValidType)
VerificationError("Addr of InitBlk must be native int or &.");
CorInfoType valCIT = OpStackTypeGet(valInd).ToCorInfoType();
if (valCIT != CORINFO_TYPE_INT)
VerificationError("Value of InitBlk must be int");
#endif // _DEBUG
CorInfoType sizeCIT = OpStackTypeGet(sizeInd).ToCorInfoType();
bool isLong = s_InterpreterLooseRules && (sizeCIT == CORINFO_TYPE_LONG);
#ifdef _DEBUG
if (sizeCIT != CORINFO_TYPE_INT && !isLong)
VerificationError("Size of InitBlk must be int");
#endif // _DEBUG
void* addr = OpStackGet<void*>(addrInd);
ThrowOnInvalidPointer(addr);
GCX_FORBID(); // addr is a potentially vulnerable byref.
INT8 val = OpStackGet<INT8>(valInd);
size_t size = (size_t) ((isLong) ? OpStackGet<UINT64>(sizeInd) : OpStackGet<UINT32>(sizeInd));
memset(addr, val, size);
m_curStackHt = addrInd;
m_ILCodePtr += 2;
BarrierIfVolatile();
}
void Interpreter::CpBlk()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 3);
unsigned destInd = m_curStackHt - 3;
unsigned srcInd = m_curStackHt - 2;
unsigned sizeInd = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType destCIT = OpStackTypeGet(destInd).ToCorInfoType();
bool destValidType = (destCIT == CORINFO_TYPE_NATIVEINT || destCIT == CORINFO_TYPE_BYREF);
#if defined(_AMD64_)
if (s_InterpreterLooseRules && destCIT == CORINFO_TYPE_LONG)
destValidType = true;
#endif
if (!destValidType)
{
VerificationError("Dest addr of CpBlk must be native int or &.");
}
CorInfoType srcCIT = OpStackTypeGet(srcInd).ToCorInfoType();
bool srcValidType = (srcCIT == CORINFO_TYPE_NATIVEINT || srcCIT == CORINFO_TYPE_BYREF);
#if defined(_AMD64_)
if (s_InterpreterLooseRules && srcCIT == CORINFO_TYPE_LONG)
srcValidType = true;
#endif
if (!srcValidType)
VerificationError("Src addr of CpBlk must be native int or &.");
#endif // _DEBUG
CorInfoType sizeCIT = OpStackTypeGet(sizeInd).ToCorInfoType();
bool isLong = s_InterpreterLooseRules && (sizeCIT == CORINFO_TYPE_LONG);
#ifdef _DEBUG
if (sizeCIT != CORINFO_TYPE_INT && !isLong)
VerificationError("Size of CpBlk must be int");
#endif // _DEBUG
void* destAddr = OpStackGet<void*>(destInd);
void* srcAddr = OpStackGet<void*>(srcInd);
ThrowOnInvalidPointer(destAddr);
ThrowOnInvalidPointer(srcAddr);
GCX_FORBID(); // destAddr & srcAddr are potentially vulnerable byrefs.
size_t size = (size_t)((isLong) ? OpStackGet<UINT64>(sizeInd) : OpStackGet<UINT32>(sizeInd));
memcpyNoGCRefs(destAddr, srcAddr, size);
m_curStackHt = destInd;
m_ILCodePtr += 2;
BarrierIfVolatile();
}
void Interpreter::Box()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned ind = m_curStackHt - 1;
DWORD boxTypeAttribs = 0;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_Box]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE boxTypeClsHnd = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_Box));
{
GCX_PREEMP();
boxTypeAttribs = m_interpCeeInfo.getClassAttribs(boxTypeClsHnd);
}
m_ILCodePtr += 5;
if (boxTypeAttribs & CORINFO_FLG_VALUECLASS)
{
InterpreterType valIt = OpStackTypeGet(ind);
void* valPtr;
if (valIt.IsLargeStruct(&m_interpCeeInfo))
{
// Operand stack entry is pointer to the data.
valPtr = OpStackGet<void*>(ind);
}
else
{
// Operand stack entry *is* the data.
size_t classSize = getClassSize(boxTypeClsHnd);
valPtr = OpStackGetAddr(ind, classSize);
}
TypeHandle th(boxTypeClsHnd);
if (th.IsTypeDesc())
{
COMPlusThrow(kInvalidOperationException, W("InvalidOperation_TypeCannotBeBoxed"));
}
MethodTable* pMT = th.AsMethodTable();
{
Object* res = OBJECTREFToObject(pMT->Box(valPtr));
GCX_FORBID();
// If we're popping a large struct off the operand stack, make sure we clean up.
if (valIt.IsLargeStruct(&m_interpCeeInfo))
{
LargeStructOperandStackPop(valIt.Size(&m_interpCeeInfo), valPtr);
}
OpStackSet<Object*>(ind, res);
OpStackTypeSet(ind, InterpreterType(CORINFO_TYPE_CLASS));
}
}
}
void Interpreter::BoxStructRefAt(unsigned ind, CORINFO_CLASS_HANDLE valCls)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
_ASSERTE_MSG(ind < m_curStackHt, "Precondition");
{
GCX_PREEMP();
_ASSERTE_MSG(m_interpCeeInfo.getClassAttribs(valCls) & CORINFO_FLG_VALUECLASS, "Precondition");
}
_ASSERTE_MSG(OpStackTypeGet(ind).ToCorInfoType() == CORINFO_TYPE_BYREF, "Precondition");
InterpreterType valIt = InterpreterType(&m_interpCeeInfo, valCls);
void* valPtr = OpStackGet<void*>(ind);
TypeHandle th(valCls);
if (th.IsTypeDesc())
COMPlusThrow(kInvalidOperationException,W("InvalidOperation_TypeCannotBeBoxed"));
MethodTable* pMT = th.AsMethodTable();
{
Object* res = OBJECTREFToObject(pMT->Box(valPtr));
GCX_FORBID();
OpStackSet<Object*>(ind, res);
OpStackTypeSet(ind, InterpreterType(CORINFO_TYPE_CLASS));
}
}
void Interpreter::Unbox()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END
assert(m_curStackHt > 0);
unsigned tos = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType tosCIT = OpStackTypeGet(tos).ToCorInfoType();
if (tosCIT != CORINFO_TYPE_CLASS)
VerificationError("Unbox requires that TOS is an object pointer.");
#endif // _DEBUG
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_Unbox]);
#endif // INTERP_TRACING
CORINFO_CLASS_HANDLE boxTypeClsHnd = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_Unbox));
CorInfoHelpFunc unboxHelper;
{
GCX_PREEMP();
unboxHelper = m_interpCeeInfo.getUnBoxHelper(boxTypeClsHnd);
}
void* res = NULL;
Object* obj = OpStackGet<Object*>(tos);
switch (unboxHelper)
{
case CORINFO_HELP_UNBOX:
{
ThrowOnInvalidPointer(obj);
MethodTable* pMT1 = (MethodTable*)boxTypeClsHnd;
MethodTable* pMT2 = obj->GetMethodTable();
if (pMT1->IsEquivalentTo(pMT2))
{
res = OpStackGet<Object*>(tos)->UnBox();
}
else
{
CorElementType type1 = pMT1->GetInternalCorElementType();
CorElementType type2 = pMT2->GetInternalCorElementType();
// we allow enums and their primtive type to be interchangable
if (type1 == type2)
{
if ((pMT1->IsEnum() || pMT1->IsTruePrimitive()) &&
(pMT2->IsEnum() || pMT2->IsTruePrimitive()))
{
res = OpStackGet<Object*>(tos)->UnBox();
}
}
}
if (res == NULL)
{
COMPlusThrow(kInvalidCastException);
}
}
break;
case CORINFO_HELP_UNBOX_NULLABLE:
{
// For "unbox Nullable<T>", we need to create a new object (maybe in some temporary local
// space (that we reuse every time we hit this IL instruction?), that gets reported to the GC,
// maybe in the GC heap itself). That object will contain an embedded Nullable<T>. Then, we need to
// get a byref to the data within the object.
NYI_INTERP("Unhandled 'unbox' of Nullable<T>.");
}
break;
default:
NYI_INTERP("Unhandled 'unbox' helper.");
}
{
GCX_FORBID();
OpStackSet<void*>(tos, res);
OpStackTypeSet(tos, InterpreterType(CORINFO_TYPE_BYREF));
}
m_ILCodePtr += 5;
}
void Interpreter::Throw()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END
assert(m_curStackHt >= 1);
// Note that we can't decrement the stack height here, since the operand stack
// protects the thrown object. Nor do we need to, since the ostack will be cleared on
// any catch within this method.
unsigned exInd = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType exCIT = OpStackTypeGet(exInd).ToCorInfoType();
if (exCIT != CORINFO_TYPE_CLASS)
{
VerificationError("Can only throw an object.");
}
#endif // _DEBUG
Object* obj = OpStackGet<Object*>(exInd);
ThrowOnInvalidPointer(obj);
OBJECTREF oref = ObjectToOBJECTREF(obj);
if (!IsException(oref->GetMethodTable()))
{
GCPROTECT_BEGIN(oref);
WrapNonCompliantException(&oref);
GCPROTECT_END();
}
COMPlusThrow(oref);
}
void Interpreter::Rethrow()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END
OBJECTREF throwable = GetThread()->LastThrownObject();
COMPlusThrow(throwable);
}
void Interpreter::UnboxAny()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt > 0);
unsigned tos = m_curStackHt - 1;
unsigned boxTypeTok = getU4LittleEndian(m_ILCodePtr + 1);
m_ILCodePtr += 5;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_UnboxAny]);
#endif // INTERP_TRACING
CORINFO_RESOLVED_TOKEN boxTypeResolvedTok;
CORINFO_CLASS_HANDLE boxTypeClsHnd;
DWORD boxTypeAttribs = 0;
{
GCX_PREEMP();
ResolveToken(&boxTypeResolvedTok, boxTypeTok, CORINFO_TOKENKIND_Class InterpTracingArg(RTK_UnboxAny));
boxTypeClsHnd = boxTypeResolvedTok.hClass;
boxTypeAttribs = m_interpCeeInfo.getClassAttribs(boxTypeClsHnd);
}
CorInfoType unboxCIT = OpStackTypeGet(tos).ToCorInfoType();
if (unboxCIT != CORINFO_TYPE_CLASS)
VerificationError("Type mismatch in UNBOXANY.");
if ((boxTypeAttribs & CORINFO_FLG_VALUECLASS) == 0)
{
Object* obj = OpStackGet<Object*>(tos);
if (obj != NULL && !ObjIsInstanceOf(obj, TypeHandle(boxTypeClsHnd), TRUE))
{
UNREACHABLE(); //ObjIsInstanceOf will throw if cast can't be done
}
}
else
{
CorInfoHelpFunc unboxHelper;
{
GCX_PREEMP();
unboxHelper = m_interpCeeInfo.getUnBoxHelper(boxTypeClsHnd);
}
// Important that this *not* be factored out with the identical statement in the "if" branch:
// delay read from GC-protected operand stack until after COOP-->PREEMP transition above.
Object* obj = OpStackGet<Object*>(tos);
switch (unboxHelper)
{
case CORINFO_HELP_UNBOX:
{
ThrowOnInvalidPointer(obj);
MethodTable* pMT1 = (MethodTable*)boxTypeClsHnd;
MethodTable* pMT2 = obj->GetMethodTable();
void* res = NULL;
if (pMT1->IsEquivalentTo(pMT2))
{
res = OpStackGet<Object*>(tos)->UnBox();
}
else
{
CorElementType type1 = pMT1->GetInternalCorElementType();
CorElementType type2 = pMT2->GetInternalCorElementType();
// we allow enums and their primtive type to be interchangable
if (type1 == type2)
{
if ((pMT1->IsEnum() || pMT1->IsTruePrimitive()) &&
(pMT2->IsEnum() || pMT2->IsTruePrimitive()))
{
res = OpStackGet<Object*>(tos)->UnBox();
}
}
}
if (res == NULL)
{
COMPlusThrow(kInvalidCastException);
}
// As the ECMA spec says, the rest is like a "ldobj".
LdObjValueClassWork(boxTypeClsHnd, tos, res);
}
break;
case CORINFO_HELP_UNBOX_NULLABLE:
{
InterpreterType it = InterpreterType(&m_interpCeeInfo, boxTypeClsHnd);
size_t sz = it.Size(&m_interpCeeInfo);
if (sz > sizeof(INT64))
{
void* destPtr = LargeStructOperandStackPush(sz);
if (!Nullable::UnBox(destPtr, ObjectToOBJECTREF(obj), (MethodTable*)boxTypeClsHnd))
{
COMPlusThrow(kInvalidCastException);
}
OpStackSet<void*>(tos, destPtr);
}
else
{
INT64 dest = 0;
if (!Nullable::UnBox(&dest, ObjectToOBJECTREF(obj), (MethodTable*)boxTypeClsHnd))
{
COMPlusThrow(kInvalidCastException);
}
OpStackSet<INT64>(tos, dest);
}
OpStackTypeSet(tos, it.StackNormalize());
}
break;
default:
NYI_INTERP("Unhandled 'unbox.any' helper.");
}
}
}
void Interpreter::LdLen()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 1);
unsigned arrInd = m_curStackHt - 1;
assert(OpStackTypeGet(arrInd).ToCorInfoType() == CORINFO_TYPE_CLASS);
GCX_FORBID();
ArrayBase* a = OpStackGet<ArrayBase*>(arrInd);
ThrowOnInvalidPointer(a);
int len = a->GetNumComponents();
OpStackSet<NativeUInt>(arrInd, NativeUInt(len));
// The ECMA spec says that the type of the length value is NATIVEUINT, but this
// doesn't make any sense -- unsigned types are not stack-normalized. So I'm
// using NATIVEINT, to get the width right.
OpStackTypeSet(arrInd, InterpreterType(CORINFO_TYPE_NATIVEINT));
}
void Interpreter::DoCall(bool virtualCall)
{
#if INTERP_DYNAMIC_CONTRACTS
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#else
// Dynamic contract occupies too much stack.
STATIC_CONTRACT_SO_TOLERANT;
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
#endif
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_Call]);
#endif // INTERP_TRACING
DoCallWork(virtualCall);
m_ILCodePtr += 5;
}
CORINFO_CONTEXT_HANDLE InterpreterMethodInfo::GetPreciseGenericsContext(Object* thisArg, void* genericsCtxtArg)
{
// If the caller has a generic argument, then we need to get the exact methodContext.
// There are several possibilities that lead to a generic argument:
// 1) Static method of generic class: generic argument is the method table of the class.
// 2) generic method of a class: generic argument is the precise MethodDesc* of the method.
if (GetFlag<InterpreterMethodInfo::Flag_hasGenericsContextArg>())
{
assert(GetFlag<InterpreterMethodInfo::Flag_methHasGenericArgs>() || GetFlag<InterpreterMethodInfo::Flag_typeHasGenericArgs>());
if (GetFlag<InterpreterMethodInfo::Flag_methHasGenericArgs>())
{
return MAKE_METHODCONTEXT(reinterpret_cast<CORINFO_METHOD_HANDLE>(genericsCtxtArg));
}
else
{
MethodTable* methodClass = reinterpret_cast<MethodDesc*>(m_method)->GetMethodTable();
MethodTable* contextClass = reinterpret_cast<MethodTable*>(genericsCtxtArg)->GetMethodTableMatchingParentClass(methodClass);
return MAKE_CLASSCONTEXT(contextClass);
}
}
// TODO: This condition isn't quite right. If the actual class is a subtype of the declaring type of the method,
// then it might be in another module, the scope and context won't agree.
else if (GetFlag<InterpreterMethodInfo::Flag_typeHasGenericArgs>()
&& !GetFlag<InterpreterMethodInfo::Flag_methHasGenericArgs>()
&& GetFlag<InterpreterMethodInfo::Flag_hasThisArg>()
&& GetFlag<InterpreterMethodInfo::Flag_thisArgIsObjPtr>() && thisArg != NULL)
{
MethodTable* methodClass = reinterpret_cast<MethodDesc*>(m_method)->GetMethodTable();
MethodTable* contextClass = thisArg->GetMethodTable()->GetMethodTableMatchingParentClass(methodClass);
return MAKE_CLASSCONTEXT(contextClass);
}
else
{
return MAKE_METHODCONTEXT(m_method);
}
}
void Interpreter::DoCallWork(bool virtualCall, void* thisArg, CORINFO_RESOLVED_TOKEN* methTokPtr, CORINFO_CALL_INFO* callInfoPtr)
{
#if INTERP_DYNAMIC_CONTRACTS
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#else
// Dynamic contract occupies too much stack.
STATIC_CONTRACT_SO_TOLERANT;
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
#endif
#if INTERP_ILCYCLE_PROFILE
#if 0
// XXX
unsigned __int64 callStartCycles;
bool b = CycleTimer::GetThreadCyclesS(&callStartCycles); assert(b);
unsigned __int64 callStartExemptCycles = m_exemptCycles;
#endif
#endif // INTERP_ILCYCLE_PROFILE
#if INTERP_TRACING
InterlockedIncrement(&s_totalInterpCalls);
#endif // INTERP_TRACING
unsigned tok = getU4LittleEndian(m_ILCodePtr + sizeof(BYTE));
// It's possible for an IL method to push a capital-F Frame. If so, we pop it and save it;
// we'll push it back on after our GCPROTECT frame is popped.
Frame* ilPushedFrame = NULL;
// We can't protect "thisArg" with a GCPROTECT, because this pushes a Frame, and there
// exist managed methods that push (and pop) Frames -- so that the Frame chain does not return
// to its original state after a call. Therefore, we can't have a Frame on the stack over the duration
// of a call. (I assume that any method that calls a Frame-pushing IL method performs a matching
// call to pop that Frame before the caller method completes. If this were not true, if one method could push
// a Frame, but defer the pop to its caller, then we could *never* use a Frame in the interpreter, and
// our implementation plan would be doomed.)
assert(m_callThisArg == NULL);
m_callThisArg = thisArg;
// Have we already cached a MethodDescCallSite for this call? (We do this only in loops
// in the current execution).
unsigned iloffset = CurOffset();
CallSiteCacheData* pCscd = NULL;
if (s_InterpreterUseCaching) pCscd = GetCachedCallInfo(iloffset);
// If this is true, then we should not cache this call site.
bool doNotCache;
CORINFO_RESOLVED_TOKEN methTok;
CORINFO_CALL_INFO callInfo;
MethodDesc* methToCall = NULL;
CORINFO_CLASS_HANDLE exactClass = NULL;
CORINFO_SIG_INFO_SMALL sigInfo;
if (pCscd != NULL)
{
GCX_PREEMP();
methToCall = pCscd->m_pMD;
sigInfo = pCscd->m_sigInfo;
doNotCache = true; // We already have a cache entry.
}
else
{
doNotCache = false; // Until we determine otherwise.
if (callInfoPtr == NULL)
{
GCX_PREEMP();
// callInfoPtr and methTokPtr must either both be NULL, or neither.
assert(methTokPtr == NULL);
methTokPtr = &methTok;
ResolveToken(methTokPtr, tok, CORINFO_TOKENKIND_Method InterpTracingArg(RTK_Call));
OPCODE opcode = (OPCODE)(*m_ILCodePtr);
m_interpCeeInfo.getCallInfo(methTokPtr,
m_constrainedFlag ? & m_constrainedResolvedToken : NULL,
m_methInfo->m_method,
//this is how impImportCall invokes getCallInfo
combine(combine(CORINFO_CALLINFO_ALLOWINSTPARAM,
CORINFO_CALLINFO_SECURITYCHECKS),
(opcode == CEE_CALLVIRT) ? CORINFO_CALLINFO_CALLVIRT
: CORINFO_CALLINFO_NONE),
&callInfo);
#if INTERP_ILCYCLE_PROFILE
#if 0
if (virtualCall)
{
unsigned __int64 callEndCycles;
b = CycleTimer::GetThreadCyclesS(&callEndCycles); assert(b);
unsigned __int64 delta = (callEndCycles - callStartCycles);
delta -= (m_exemptCycles - callStartExemptCycles);
s_callCycles += delta;
s_calls++;
}
#endif
#endif // INTERP_ILCYCLE_PROFILE
callInfoPtr = &callInfo;
assert(!callInfoPtr->exactContextNeedsRuntimeLookup);
methToCall = reinterpret_cast<MethodDesc*>(methTok.hMethod);
exactClass = methTok.hClass;
}
else
{
// callInfoPtr and methTokPtr must either both be NULL, or neither.
assert(methTokPtr != NULL);
assert(!callInfoPtr->exactContextNeedsRuntimeLookup);
methToCall = reinterpret_cast<MethodDesc*>(callInfoPtr->hMethod);
exactClass = methTokPtr->hClass;
}
// We used to take the sigInfo from the callInfo here, but that isn't precise, since
// we may have made "methToCall" more precise wrt generics than the method handle in
// the callinfo. So look up th emore precise signature.
GCX_PREEMP();
CORINFO_SIG_INFO sigInfoFull;
m_interpCeeInfo.getMethodSig(CORINFO_METHOD_HANDLE(methToCall), &sigInfoFull);
sigInfo.retTypeClass = sigInfoFull.retTypeClass;
sigInfo.numArgs = sigInfoFull.numArgs;
sigInfo.callConv = sigInfoFull.callConv;
sigInfo.retType = sigInfoFull.retType;
}
// Point A in our cycle count.
// Is the method an intrinsic? If so, and if it's one we've written special-case code for
// handle intrinsically.
CorInfoIntrinsics intrinsicId;
{
GCX_PREEMP();
intrinsicId = m_interpCeeInfo.getIntrinsicID(CORINFO_METHOD_HANDLE(methToCall));
}
#if INTERP_TRACING
if (intrinsicId != CORINFO_INTRINSIC_Illegal)
InterlockedIncrement(&s_totalInterpCallsToIntrinsics);
#endif // INTERP_TRACING
bool didIntrinsic = false;
if (!m_constrainedFlag)
{
switch (intrinsicId)
{
case CORINFO_INTRINSIC_StringLength:
DoStringLength(); didIntrinsic = true;
break;
case CORINFO_INTRINSIC_StringGetChar:
DoStringGetChar(); didIntrinsic = true;
break;
case CORINFO_INTRINSIC_GetTypeFromHandle:
// This is an identity transformation. (At least until I change LdToken to
// return a RuntimeTypeHandle struct...which is a TODO.)
DoGetTypeFromHandle();
didIntrinsic = true;
break;
#if INTERP_ILSTUBS
case CORINFO_INTRINSIC_StubHelpers_GetStubContext:
OpStackSet<void*>(m_curStackHt, GetStubContext());
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_NATIVEINT));
m_curStackHt++; didIntrinsic = true;
break;
case CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr:
OpStackSet<void*>(m_curStackHt, GetStubContextAddr());
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_NATIVEINT));
m_curStackHt++; didIntrinsic = true;
break;
#endif // INTERP_ILSTUBS
default:
#if INTERP_TRACING
InterlockedIncrement(&s_totalInterpCallsToIntrinsicsUnhandled);
#endif // INTERP_TRACING
break;
}
// Plus some other calls that we're going to treat "like" intrinsics...
if (methToCall == MscorlibBinder::GetMethod(METHOD__STUBHELPERS__SET_LAST_ERROR))
{
// If we're interpreting a method that calls "SetLastError", it's very likely that the call(i) whose
// error we're trying to capture was performed with MethodDescCallSite machinery that itself trashes
// the last error. We solve this by saving the last error in a special interpreter-specific field of
// "Thread" in that case, and essentially implement SetLastError here, taking that field as the
// source for the last error.
Thread* thrd = GetThread();
thrd->m_dwLastError = thrd->m_dwLastErrorInterp;
didIntrinsic = true;
}
}
if (didIntrinsic)
{
if (s_InterpreterUseCaching && !doNotCache)
{
// Cache the token resolution result...
pCscd = new CallSiteCacheData(methToCall, sigInfo);
CacheCallInfo(iloffset, pCscd);
}
// Now we can return.
return;
}
// Handle other simple special cases:
#if FEATURE_INTERPRETER_DEADSIMPLE_OPT
#ifndef DACCESS_COMPILE
// Dead simple static getters.
InterpreterMethodInfo* calleeInterpMethInfo;
if (GetMethodHandleToInterpMethInfoPtrMap()->Lookup(CORINFO_METHOD_HANDLE(methToCall), &calleeInterpMethInfo))
{
if (calleeInterpMethInfo->GetFlag<InterpreterMethodInfo::Flag_methIsDeadSimpleGetter>())
{
if (methToCall->IsStatic())
{
// TODO
}
else
{
ILOffsetToItemCache* calleeCache;
{
Object* thisArg = OpStackGet<Object*>(m_curStackHt-1);
GCX_FORBID();
// We pass NULL for the generic context arg, because a dead simple getter takes none, by definition.
calleeCache = calleeInterpMethInfo->GetCacheForCall(thisArg, /*genericsContextArg*/NULL);
}
// We've interpreted the getter at least once, so the cache for *some* generics context is populated -- but maybe not
// this one. We're hoping that it usually is.
if (calleeCache != NULL)
{
CachedItem cachedItem;
unsigned offsetOfLd;
if (calleeInterpMethInfo->GetFlag<InterpreterMethodInfo::Flag_methIsDeadSimpleGetterIsDbgForm>())
offsetOfLd = ILOffsetOfLdFldInDeadSimpleInstanceGetterOpt;
else
offsetOfLd = ILOffsetOfLdFldInDeadSimpleInstanceGetterOpt;
bool b = calleeCache->GetItem(offsetOfLd, cachedItem);
_ASSERTE_MSG(b, "If the cache exists for this generic context, it should an entry for the LdFld.");
_ASSERTE_MSG(cachedItem.m_tag == CIK_InstanceField, "If it's there, it should be an instance field cache.");
LdFld(cachedItem.m_value.m_instanceField);
#if INTERP_TRACING
InterlockedIncrement(&s_totalInterpCallsToDeadSimpleGetters);
InterlockedIncrement(&s_totalInterpCallsToDeadSimpleGettersShortCircuited);
#endif // INTERP_TRACING
return;
}
}
}
}
#endif // DACCESS_COMPILE
#endif // FEATURE_INTERPRETER_DEADSIMPLE_OPT
unsigned totalSigArgs;
CORINFO_VARARGS_HANDLE vaSigCookie = nullptr;
if ((sigInfo.callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG ||
(sigInfo.callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_NATIVEVARARG)
{
GCX_PREEMP();
CORINFO_SIG_INFO sig;
m_interpCeeInfo.findCallSiteSig(m_methInfo->m_module, methTokPtr->token, MAKE_METHODCONTEXT(m_methInfo->m_method), &sig);
sigInfo.retTypeClass = sig.retTypeClass;
sigInfo.numArgs = sig.numArgs;
sigInfo.callConv = sig.callConv;
sigInfo.retType = sig.retType;
// Adding 'this' pointer because, numArgs doesn't include the this pointer.
totalSigArgs = sigInfo.numArgs + sigInfo.hasThis();
if ((sigInfo.callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG)
{
Module* module = GetModule(sig.scope);
vaSigCookie = CORINFO_VARARGS_HANDLE(module->GetVASigCookie(Signature(sig.pSig, sig.cbSig)));
}
doNotCache = true;
}
else
{
totalSigArgs = sigInfo.totalILArgs();
}
// Note that "totalNativeArgs()" includes space for ret buff arg.
unsigned nSlots = totalSigArgs + 1;
if (sigInfo.hasTypeArg()) nSlots++;
if (sigInfo.isVarArg()) nSlots++;
DelegateCtorArgs ctorData;
// If any of these are non-null, they will be pushed as extra arguments (see the code below).
ctorData.pArg3 = NULL;
ctorData.pArg4 = NULL;
ctorData.pArg5 = NULL;
// Since we make "doNotCache" true below, well never have a non-null "pCscd" for a delegate
// constructor. But we have to check for a cached method first, since callInfoPtr may be null in the cached case.
if (pCscd == NULL && callInfoPtr->classFlags & CORINFO_FLG_DELEGATE && callInfoPtr->methodFlags & CORINFO_FLG_CONSTRUCTOR)
{
// We won't cache this case.
doNotCache = true;
_ASSERTE_MSG(!sigInfo.hasTypeArg(), "I assume that this isn't possible.");
GCX_PREEMP();
ctorData.pMethod = methToCall;
// Second argument to delegate constructor will be code address of the function the delegate wraps.
assert(TOSIsPtr() && OpStackTypeGet(m_curStackHt-1).ToCorInfoType() != CORINFO_TYPE_BYREF);
CORINFO_METHOD_HANDLE targetMethodHnd = GetFunctionPointerStack()[m_curStackHt-1];
assert(targetMethodHnd != NULL);
CORINFO_METHOD_HANDLE alternateCtorHnd = m_interpCeeInfo.GetDelegateCtor(reinterpret_cast<CORINFO_METHOD_HANDLE>(methToCall), methTokPtr->hClass, targetMethodHnd, &ctorData);
MethodDesc* alternateCtor = reinterpret_cast<MethodDesc*>(alternateCtorHnd);
if (alternateCtor != methToCall)
{
methToCall = alternateCtor;
// Translate the method address argument from a method handle to the actual callable code address.
void* val = (void *)((MethodDesc *)targetMethodHnd)->GetMultiCallableAddrOfCode();
// Change the method argument to the code pointer.
OpStackSet<void*>(m_curStackHt-1, val);
// Now if there are extra arguments, add them to the number of slots; we'll push them on the
// arg list later.
if (ctorData.pArg3) nSlots++;
if (ctorData.pArg4) nSlots++;
if (ctorData.pArg5) nSlots++;
}
}
// Make sure that the operand stack has the required number of arguments.
// (Note that this is IL args, not native.)
//
// The total number of arguments on the IL stack. Initially we assume that all the IL arguments
// the callee expects are on the stack, but may be adjusted downwards if the "this" argument
// is provided by an allocation (the call is to a constructor).
unsigned totalArgsOnILStack = totalSigArgs;
if (m_callThisArg != NULL)
{
assert(totalArgsOnILStack > 0);
totalArgsOnILStack--;
}
#if defined(FEATURE_HFA)
// Does the callee have an HFA return type?
unsigned HFAReturnArgSlots = 0;
{
GCX_PREEMP();
if (sigInfo.retType == CORINFO_TYPE_VALUECLASS
&& CorInfoTypeIsFloatingPoint(m_interpCeeInfo.getHFAType(sigInfo.retTypeClass))
&& (sigInfo.getCallConv() & CORINFO_CALLCONV_VARARG) == 0)
{
HFAReturnArgSlots = getClassSize(sigInfo.retTypeClass);
// Round up to a multiple of double size.
HFAReturnArgSlots = (HFAReturnArgSlots + sizeof(ARG_SLOT) - 1) / sizeof(ARG_SLOT);
}
}
#endif
// Point B
const unsigned LOCAL_ARG_SLOTS = 8;
ARG_SLOT localArgs[LOCAL_ARG_SLOTS];
InterpreterType localArgTypes[LOCAL_ARG_SLOTS];
ARG_SLOT* args;
InterpreterType* argTypes;
#if defined(_X86_)
unsigned totalArgSlots = nSlots;
#elif defined(_ARM_) || defined(_ARM64_)
// ARM64TODO: Verify that the following statement is correct for ARM64.
unsigned totalArgSlots = nSlots + HFAReturnArgSlots;
#elif defined(_AMD64_)
unsigned totalArgSlots = nSlots;
#else
#error "unsupported platform"
#endif
if (totalArgSlots <= LOCAL_ARG_SLOTS)
{
args = &localArgs[0];
argTypes = &localArgTypes[0];
}
else
{
args = (ARG_SLOT*)_alloca(totalArgSlots * sizeof(ARG_SLOT));
#if defined(_ARM_)
// The HFA return buffer, if any, is assumed to be at a negative
// offset from the IL arg pointer, so adjust that pointer upward.
args = args + HFAReturnArgSlots;
#endif // defined(_ARM_)
argTypes = (InterpreterType*)_alloca(nSlots * sizeof(InterpreterType));
}
// Make sure that we don't scan any of these until we overwrite them with
// the real types of the arguments.
InterpreterType undefIt(CORINFO_TYPE_UNDEF);
for (unsigned i = 0; i < nSlots; i++) argTypes[i] = undefIt;
// GC-protect the argument array (as byrefs).
m_args = args; m_argsSize = nSlots; m_argTypes = argTypes;
// This is the index into the "args" array (where we copy the value to).
int curArgSlot = 0;
// The operand stack index of the first IL argument.
assert(m_curStackHt >= totalArgsOnILStack);
int argsBase = m_curStackHt - totalArgsOnILStack;
// Current on-stack argument index.
unsigned arg = 0;
// We do "this" -- in the case of a constructor, we "shuffle" the "m_callThisArg" argument in as the first
// argument -- it isn't on the IL operand stack.
if (m_constrainedFlag)
{
_ASSERT(m_callThisArg == NULL); // "m_callThisArg" non-null only for .ctor, which are not callvirts.
CorInfoType argCIT = OpStackTypeGet(argsBase + arg).ToCorInfoType();
if (argCIT != CORINFO_TYPE_BYREF)
VerificationError("This arg of constrained call must be managed pointer.");
// We only cache for the CORINFO_NO_THIS_TRANSFORM case, so we may assume that if we have a cached call site,
// there's no thisTransform to perform.
if (pCscd == NULL)
{
switch (callInfoPtr->thisTransform)
{
case CORINFO_NO_THIS_TRANSFORM:
// It is a constrained call on a method implemented by a value type; this is already the proper managed pointer.
break;
case CORINFO_DEREF_THIS:
#ifdef _DEBUG
{
GCX_PREEMP();
DWORD clsAttribs = m_interpCeeInfo.getClassAttribs(m_constrainedResolvedToken.hClass);
assert((clsAttribs & CORINFO_FLG_VALUECLASS) == 0);
}
#endif // _DEBUG
{
// As per the spec, dereference the byref to the "this" pointer, and substitute it as the new "this" pointer.
GCX_FORBID();
Object** objPtrPtr = OpStackGet<Object**>(argsBase + arg);
OpStackSet<Object*>(argsBase + arg, *objPtrPtr);
OpStackTypeSet(argsBase + arg, InterpreterType(CORINFO_TYPE_CLASS));
}
doNotCache = true;
break;
case CORINFO_BOX_THIS:
// This is the case where the call is to a virtual method of Object the given
// struct class does not override -- the struct must be boxed, so that the
// method can be invoked as a virtual.
BoxStructRefAt(argsBase + arg, m_constrainedResolvedToken.hClass);
doNotCache = true;
break;
}
exactClass = m_constrainedResolvedToken.hClass;
{
GCX_PREEMP();
DWORD exactClassAttribs = m_interpCeeInfo.getClassAttribs(exactClass);
// If the constraint type is a value class, then it is the exact class (which will be the
// "owner type" in the MDCS below.) If it is not, leave it as the (precise) interface method.
if (exactClassAttribs & CORINFO_FLG_VALUECLASS)
{
MethodTable* exactClassMT = GetMethodTableFromClsHnd(exactClass);
// Find the method on exactClass corresponding to methToCall.
methToCall = MethodDesc::FindOrCreateAssociatedMethodDesc(
reinterpret_cast<MethodDesc*>(callInfoPtr->hMethod), // pPrimaryMD
exactClassMT, // pExactMT
FALSE, // forceBoxedEntryPoint
methToCall->GetMethodInstantiation(), // methodInst
FALSE); // allowInstParam
}
else
{
exactClass = methTokPtr->hClass;
}
}
}
// We've consumed the constraint, so reset the flag.
m_constrainedFlag = false;
}
if (pCscd == NULL)
{
if (callInfoPtr->methodFlags & CORINFO_FLG_STATIC)
{
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(callInfoPtr->hMethod);
EnsureClassInit(pMD->GetMethodTable());
}
}
// Point C
// We must do anything that might make a COOP->PREEMP transition before copying arguments out of the
// operand stack (where they are GC-protected) into the args array (where they are not).
#ifdef _DEBUG
const char* clsOfMethToCallName;;
const char* methToCallName = NULL;
{
GCX_PREEMP();
methToCallName = m_interpCeeInfo.getMethodName(CORINFO_METHOD_HANDLE(methToCall), &clsOfMethToCallName);
}
#if INTERP_TRACING
if (strncmp(methToCallName, "get_", 4) == 0)
{
InterlockedIncrement(&s_totalInterpCallsToGetters);
size_t offsetOfLd;
if (IsDeadSimpleGetter(&m_interpCeeInfo, methToCall, &offsetOfLd))
{
InterlockedIncrement(&s_totalInterpCallsToDeadSimpleGetters);
}
}
else if (strncmp(methToCallName, "set_", 4) == 0)
{
InterlockedIncrement(&s_totalInterpCallsToSetters);
}
#endif // INTERP_TRACING
// Only do this check on the first call, since it should be the same each time.
if (pCscd == NULL)
{
// Ensure that any value types used as argument types are loaded. This property is checked
// by the MethodDescCall site mechanisms. Since enums are freely convertible with their underlying
// integer type, this is at least one case where a caller may push a value convertible to a value type
// without any code having caused the value type to be loaded. This is DEBUG-only because if the callee
// the integer-type value as the enum value type, it will have loaded the value type.
MetaSig ms(methToCall);
CorElementType argType;
while ((argType = ms.NextArg()) != ELEMENT_TYPE_END)
{
if (argType == ELEMENT_TYPE_VALUETYPE)
{
TypeHandle th = ms.GetLastTypeHandleThrowing(ClassLoader::LoadTypes);
CONSISTENCY_CHECK(th.CheckFullyLoaded());
CONSISTENCY_CHECK(th.IsRestored_NoLogging());
}
}
}
#endif
// CYCLE PROFILE: BEFORE ARG PROCESSING.
if (sigInfo.hasThis())
{
if (m_callThisArg != NULL)
{
if (size_t(m_callThisArg) == 0x1)
{
args[curArgSlot] = NULL;
}
else
{
args[curArgSlot] = PtrToArgSlot(m_callThisArg);
}
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_BYREF);
}
else
{
args[curArgSlot] = PtrToArgSlot(OpStackGet<void*>(argsBase + arg));
argTypes[curArgSlot] = OpStackTypeGet(argsBase + arg);
arg++;
}
// AV -> NullRef translation is NYI for the interpreter,
// so we should manually check and throw the correct exception.
if (args[curArgSlot] == NULL)
{
// If we're calling a constructor, we bypass this check since the runtime
// should have thrown OOM if it was unable to allocate an instance.
if (m_callThisArg == NULL)
{
assert(!methToCall->IsStatic());
ThrowNullPointerException();
}
// ...except in the case of strings, which are both
// allocated and initialized by their special constructor.
else
{
assert(methToCall->IsCtor() && methToCall->GetMethodTable()->IsString());
}
}
curArgSlot++;
}
// This is the argument slot that will be used to hold the return value.
ARG_SLOT retVal = 0;
#if !defined(_ARM_) && !defined(UNIX_AMD64_ABI)
_ASSERTE (NUMBER_RETURNVALUE_SLOTS == 1);
#endif
// If the return type is a structure, then these will be initialized.
CORINFO_CLASS_HANDLE retTypeClsHnd = NULL;
InterpreterType retTypeIt;
size_t retTypeSz = 0;
// If non-null, space allocated to hold a large struct return value. Should be deleted later.
// (I could probably optimize this pop all the arguments first, then allocate space for the return value
// on the large structure operand stack, and pass a pointer directly to that space, avoiding the extra
// copy we have below. But this seemed more expedient, and this should be a pretty rare case.)
BYTE* pLargeStructRetVal = NULL;
// If there's a "GetFlag<Flag_hasRetBuffArg>()" struct return value, it will be stored in this variable if it fits,
// otherwise, we'll dynamically allocate memory for it.
ARG_SLOT smallStructRetVal = 0;
// We should have no return buffer temp space registered here...unless this is a constructor, in which
// case it will return void. In particular, if the return type VALUE_CLASS, then this should be NULL.
_ASSERTE_MSG((pCscd != NULL) || sigInfo.retType == CORINFO_TYPE_VOID || m_structRetValITPtr == NULL, "Invariant.");
// Is it the return value a struct with a ret buff?
_ASSERTE_MSG(methToCall != NULL, "assumption");
bool hasRetBuffArg = false;
if (sigInfo.retType == CORINFO_TYPE_VALUECLASS || sigInfo.retType == CORINFO_TYPE_REFANY)
{
hasRetBuffArg = !!methToCall->HasRetBuffArg();
retTypeClsHnd = sigInfo.retTypeClass;
MetaSig ms(methToCall);
// On ARM, if there's an HFA return type, we must also allocate a return buffer, since the
// MDCS calling convention requires it.
if (hasRetBuffArg
#if defined(_ARM_)
|| HFAReturnArgSlots > 0
#endif // defined(_ARM_)
)
{
assert(retTypeClsHnd != NULL);
retTypeIt = InterpreterType(&m_interpCeeInfo, retTypeClsHnd);
retTypeSz = retTypeIt.Size(&m_interpCeeInfo);
#if defined(_ARM_)
if (HFAReturnArgSlots > 0)
{
args[curArgSlot] = PtrToArgSlot(args - HFAReturnArgSlots);
}
else
#endif // defined(_ARM_)
if (retTypeIt.IsLargeStruct(&m_interpCeeInfo))
{
size_t retBuffSize = retTypeSz;
// If the target architecture can sometimes return a struct in several registers,
// MethodDescCallSite will reserve a return value array big enough to hold the maximum.
// It will then copy *all* of this into the return buffer area we allocate. So make sure
// we allocate at least that much.
#ifdef ENREGISTERED_RETURNTYPE_MAXSIZE
retBuffSize = max(retTypeSz, ENREGISTERED_RETURNTYPE_MAXSIZE);
#endif // ENREGISTERED_RETURNTYPE_MAXSIZE
pLargeStructRetVal = (BYTE*)_alloca(retBuffSize);
// Clear this in case a GC happens.
for (unsigned i = 0; i < retTypeSz; i++) pLargeStructRetVal[i] = 0;
// Register this as location needing GC.
m_structRetValTempSpace = pLargeStructRetVal;
// Set it as the return buffer.
args[curArgSlot] = PtrToArgSlot(pLargeStructRetVal);
}
else
{
// Clear this in case a GC happens.
smallStructRetVal = 0;
// Register this as location needing GC.
m_structRetValTempSpace = &smallStructRetVal;
// Set it as the return buffer.
args[curArgSlot] = PtrToArgSlot(&smallStructRetVal);
}
m_structRetValITPtr = &retTypeIt;
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
else
{
// The struct type might "normalize" to a primitive type.
if (retTypeClsHnd == NULL)
{
retTypeIt = InterpreterType(CEEInfo::asCorInfoType(ms.GetReturnTypeNormalized()));
}
else
{
retTypeIt = InterpreterType(&m_interpCeeInfo, retTypeClsHnd);
}
}
}
if (((sigInfo.callConv & CORINFO_CALLCONV_VARARG) != 0) && sigInfo.isVarArg())
{
assert(vaSigCookie != nullptr);
args[curArgSlot] = PtrToArgSlot(vaSigCookie);
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
if (pCscd == NULL)
{
if (sigInfo.hasTypeArg())
{
GCX_PREEMP();
// We will find the instantiating stub for the method, and call that instead.
CORINFO_SIG_INFO sigInfoFull;
Instantiation methodInst = methToCall->GetMethodInstantiation();
BOOL fNeedUnboxingStub = virtualCall && TypeHandle(exactClass).IsValueType() && methToCall->IsVirtual();
methToCall = MethodDesc::FindOrCreateAssociatedMethodDesc(methToCall,
TypeHandle(exactClass).GetMethodTable(), fNeedUnboxingStub, methodInst, FALSE, TRUE);
m_interpCeeInfo.getMethodSig(CORINFO_METHOD_HANDLE(methToCall), &sigInfoFull);
sigInfo.retTypeClass = sigInfoFull.retTypeClass;
sigInfo.numArgs = sigInfoFull.numArgs;
sigInfo.callConv = sigInfoFull.callConv;
sigInfo.retType = sigInfoFull.retType;
}
if (sigInfo.hasTypeArg())
{
// If we still have a type argument, we're calling an ArrayOpStub and need to pass the array TypeHandle.
assert(methToCall->IsArray());
doNotCache = true;
args[curArgSlot] = PtrToArgSlot(exactClass);
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
}
// Now we do the non-this arguments.
size_t largeStructSpaceToPop = 0;
for (; arg < totalArgsOnILStack; arg++)
{
InterpreterType argIt = OpStackTypeGet(argsBase + arg);
size_t sz = OpStackTypeGet(argsBase + arg).Size(&m_interpCeeInfo);
switch (sz)
{
case 1:
args[curArgSlot] = OpStackGet<INT8>(argsBase + arg);
break;
case 2:
args[curArgSlot] = OpStackGet<INT16>(argsBase + arg);
break;
case 4:
args[curArgSlot] = OpStackGet<INT32>(argsBase + arg);
break;
case 8:
default:
if (sz > 8)
{
void* srcPtr = OpStackGet<void*>(argsBase + arg);
args[curArgSlot] = PtrToArgSlot(srcPtr);
if (!IsInLargeStructLocalArea(srcPtr))
largeStructSpaceToPop += sz;
}
else
{
args[curArgSlot] = OpStackGet<INT64>(argsBase + arg);
}
break;
}
argTypes[curArgSlot] = argIt;
curArgSlot++;
}
if (ctorData.pArg3)
{
args[curArgSlot] = PtrToArgSlot(ctorData.pArg3);
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
if (ctorData.pArg4)
{
args[curArgSlot] = PtrToArgSlot(ctorData.pArg4);
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
if (ctorData.pArg5)
{
args[curArgSlot] = PtrToArgSlot(ctorData.pArg5);
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
// CYCLE PROFILE: AFTER ARG PROCESSING.
{
Thread* thr = GetThread();
Object** thisArgHnd = NULL;
ARG_SLOT nullThisArg = NULL;
if (sigInfo.hasThis())
{
if (m_callThisArg != NULL)
{
if (size_t(m_callThisArg) == 0x1)
{
thisArgHnd = reinterpret_cast<Object**>(&nullThisArg);
}
else
{
thisArgHnd = reinterpret_cast<Object**>(&m_callThisArg);
}
}
else
{
thisArgHnd = OpStackGetAddr<Object*>(argsBase);
}
}
Frame* topFrameBefore = thr->GetFrame();
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 startCycles;
#endif // INTERP_ILCYCLE_PROFILE
// CYCLE PROFILE: BEFORE MDCS CREATION.
PCODE target = NULL;
MethodDesc *exactMethToCall = methToCall;
// Determine the target of virtual calls.
if (virtualCall && methToCall->IsVtableMethod())
{
PCODE pCode;
assert(thisArgHnd != NULL);
OBJECTREF objRef = ObjectToOBJECTREF(*thisArgHnd);
GCPROTECT_BEGIN(objRef);
pCode = methToCall->GetMultiCallableAddrOfVirtualizedCode(&objRef, methToCall->GetMethodTable());
GCPROTECT_END();
exactMethToCall = Entry2MethodDesc(pCode, objRef->GetTrueMethodTable());
}
// Compile the target in advance of calling.
if (exactMethToCall->IsPointingToPrestub())
{
MethodTable* dispatchingMT = NULL;
if (exactMethToCall->IsVtableMethod())
{
assert(thisArgHnd != NULL);
dispatchingMT = (*thisArgHnd)->GetMethodTable();
}
GCX_PREEMP();
target = exactMethToCall->DoPrestub(dispatchingMT);
}
else
{
target = exactMethToCall->GetMethodEntryPoint();
}
// If we're interpreting the method, simply call it directly.
if (InterpretationStubToMethodInfo(target) == exactMethToCall)
{
assert(!exactMethToCall->IsILStub());
InterpreterMethodInfo* methInfo = MethodHandleToInterpreterMethInfoPtr(CORINFO_METHOD_HANDLE(exactMethToCall));
assert(methInfo != NULL);
#if INTERP_ILCYCLE_PROFILE
bool b = CycleTimer::GetThreadCyclesS(&startCycles); assert(b);
#endif // INTERP_ILCYCLE_PROFILE
retVal = InterpretMethodBody(methInfo, true, reinterpret_cast<BYTE*>(args), NULL);
pCscd = NULL; // Nothing to cache.
}
else
{
MetaSig msig(exactMethToCall);
// We've already resolved the virtual call target above, so there is no need to do it again.
MethodDescCallSite mdcs(exactMethToCall, &msig, target);
#if INTERP_ILCYCLE_PROFILE
bool b = CycleTimer::GetThreadCyclesS(&startCycles); assert(b);
#endif // INTERP_ILCYCLE_PROFILE
mdcs.CallTargetWorker(args, &retVal, sizeof(retVal));
if (pCscd != NULL)
{
// We will do a check at the end to determine whether to cache pCscd, to set
// to NULL here to make sure we don't.
pCscd = NULL;
}
else
{
// For now, we won't cache virtual calls to virtual methods.
// TODO: fix this somehow.
if (virtualCall && (callInfoPtr->methodFlags & CORINFO_FLG_VIRTUAL)) doNotCache = true;
if (s_InterpreterUseCaching && !doNotCache)
{
// We will add this to the cache later; the locking provokes a GC,
// and "retVal" is vulnerable.
pCscd = new CallSiteCacheData(exactMethToCall, sigInfo);
}
}
}
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 endCycles;
bool b = CycleTimer::GetThreadCyclesS(&endCycles); assert(b);
m_exemptCycles += (endCycles - startCycles);
#endif // INTERP_ILCYCLE_PROFILE
// retVal is now vulnerable.
GCX_FORBID();
// Some managed methods, believe it or not, can push capital-F Frames on the Frame chain.
// If this happens, executing the EX_CATCH below will pop it, which is bad.
// So detect that case, pop the explicitly-pushed frame, and push it again after the EX_CATCH.
// (Asserting that there is only 1 such frame!)
if (thr->GetFrame() != topFrameBefore)
{
ilPushedFrame = thr->GetFrame();
if (ilPushedFrame != NULL)
{
ilPushedFrame->Pop(thr);
if (thr->GetFrame() != topFrameBefore)
{
// This wasn't an IL-pushed frame, so restore.
ilPushedFrame->Push(thr);
ilPushedFrame = NULL;
}
}
}
}
// retVal is still vulnerable.
{
GCX_FORBID();
m_argsSize = 0;
// At this point, the call has happened successfully. We can delete the arguments from the operand stack.
m_curStackHt -= totalArgsOnILStack;
// We've already checked that "largeStructSpaceToPop
LargeStructOperandStackPop(largeStructSpaceToPop, NULL);
if (size_t(m_callThisArg) == 0x1)
{
_ASSERTE_MSG(sigInfo.retType == CORINFO_TYPE_VOID, "Constructor for var-sized object becomes factory method that returns result.");
OpStackSet<Object*>(m_curStackHt, reinterpret_cast<Object*>(retVal));
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_CLASS));
m_curStackHt++;
}
else if (sigInfo.retType != CORINFO_TYPE_VOID)
{
switch (sigInfo.retType)
{
case CORINFO_TYPE_BOOL:
case CORINFO_TYPE_BYTE:
OpStackSet<INT32>(m_curStackHt, static_cast<INT8>(retVal));
break;
case CORINFO_TYPE_UBYTE:
OpStackSet<UINT32>(m_curStackHt, static_cast<UINT8>(retVal));
break;
case CORINFO_TYPE_SHORT:
OpStackSet<INT32>(m_curStackHt, static_cast<INT16>(retVal));
break;
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_CHAR:
OpStackSet<UINT32>(m_curStackHt, static_cast<UINT16>(retVal));
break;
case CORINFO_TYPE_INT:
case CORINFO_TYPE_UINT:
case CORINFO_TYPE_FLOAT:
OpStackSet<INT32>(m_curStackHt, static_cast<INT32>(retVal));
break;
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_ULONG:
case CORINFO_TYPE_DOUBLE:
OpStackSet<INT64>(m_curStackHt, static_cast<INT64>(retVal));
break;
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_PTR:
OpStackSet<NativeInt>(m_curStackHt, static_cast<NativeInt>(retVal));
break;
case CORINFO_TYPE_CLASS:
OpStackSet<Object*>(m_curStackHt, reinterpret_cast<Object*>(retVal));
break;
case CORINFO_TYPE_BYREF:
OpStackSet<void*>(m_curStackHt, reinterpret_cast<void*>(retVal));
break;
case CORINFO_TYPE_VALUECLASS:
case CORINFO_TYPE_REFANY:
{
// We must be careful here to write the value, the type, and update the stack height in one
// sequence that has no COOP->PREEMP transitions in it, so no GC's happen until the value
// is protected by being fully "on" the operandStack.
#if defined(_ARM_)
// Is the return type an HFA?
if (HFAReturnArgSlots > 0)
{
ARG_SLOT* hfaRetBuff = args - HFAReturnArgSlots;
if (retTypeIt.IsLargeStruct(&m_interpCeeInfo))
{
void* dst = LargeStructOperandStackPush(retTypeSz);
memcpy(dst, hfaRetBuff, retTypeSz);
OpStackSet<void*>(m_curStackHt, dst);
}
else
{
memcpy(OpStackGetAddr<UINT64>(m_curStackHt), hfaRetBuff, retTypeSz);
}
}
else
#endif // defined(_ARM_)
if (pLargeStructRetVal != NULL)
{
assert(hasRetBuffArg);
void* dst = LargeStructOperandStackPush(retTypeSz);
CopyValueClassUnchecked(dst, pLargeStructRetVal, GetMethodTableFromClsHnd(retTypeClsHnd));
OpStackSet<void*>(m_curStackHt, dst);
}
else if (hasRetBuffArg)
{
OpStackSet<INT64>(m_curStackHt, GetSmallStructValue(&smallStructRetVal, retTypeSz));
}
else
{
OpStackSet<UINT64>(m_curStackHt, retVal);
}
// We already created this interpreter type, so use it.
OpStackTypeSet(m_curStackHt, retTypeIt.StackNormalize());
m_curStackHt++;
// In the value-class case, the call might have used a ret buff, which we would have registered for GC scanning.
// Make sure it's unregistered.
m_structRetValITPtr = NULL;
}
break;
default:
NYI_INTERP("Unhandled return type");
break;
}
_ASSERTE_MSG(m_structRetValITPtr == NULL, "Invariant.");
// The valueclass case is handled fully in the switch above.
if (sigInfo.retType != CORINFO_TYPE_VALUECLASS &&
sigInfo.retType != CORINFO_TYPE_REFANY)
{
OpStackTypeSet(m_curStackHt, InterpreterType(sigInfo.retType).StackNormalize());
m_curStackHt++;
}
}
}
// Originally, this assertion was in the ValueClass case above, but it does a COOP->PREEMP
// transition, and therefore causes a GC, and we're GCX_FORBIDden from doing a GC while retVal
// is vulnerable. So, for completeness, do it here.
assert(sigInfo.retType != CORINFO_TYPE_VALUECLASS || retTypeIt == InterpreterType(&m_interpCeeInfo, retTypeClsHnd));
// If we created a cached call site, cache it now (when it's safe to take a GC).
if (pCscd != NULL && !doNotCache)
{
CacheCallInfo(iloffset, pCscd);
}
m_callThisArg = NULL;
// If the call we just made pushed a Frame, we popped it above, so re-push it.
if (ilPushedFrame != NULL) ilPushedFrame->Push();
}
#include "metadata.h"
void Interpreter::CallI()
{
#if INTERP_DYNAMIC_CONTRACTS
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#else
// Dynamic contract occupies too much stack.
STATIC_CONTRACT_SO_TOLERANT;
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
#endif
#if INTERP_TRACING
InterlockedIncrement(&s_totalInterpCalls);
#endif // INTERP_TRACING
unsigned tok = getU4LittleEndian(m_ILCodePtr + sizeof(BYTE));
CORINFO_SIG_INFO sigInfo;
{
GCX_PREEMP();
m_interpCeeInfo.findSig(m_methInfo->m_module, tok, GetPreciseGenericsContext(), &sigInfo);
}
// I'm assuming that a calli can't depend on the generics context, so the simple form of type
// context should suffice?
MethodDesc* pMD = reinterpret_cast<MethodDesc*>(m_methInfo->m_method);
SigTypeContext sigTypeCtxt(pMD);
MetaSig mSig(sigInfo.pSig, sigInfo.cbSig, GetModule(sigInfo.scope), &sigTypeCtxt);
unsigned totalSigArgs = sigInfo.totalILArgs();
// Note that "totalNativeArgs()" includes space for ret buff arg.
unsigned nSlots = totalSigArgs + 1;
if ((sigInfo.callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG)
{
nSlots++;
}
// Make sure that the operand stack has the required number of arguments.
// (Note that this is IL args, not native.)
//
// The total number of arguments on the IL stack. Initially we assume that all the IL arguments
// the callee expects are on the stack, but may be adjusted downwards if the "this" argument
// is provided by an allocation (the call is to a constructor).
unsigned totalArgsOnILStack = totalSigArgs;
const unsigned LOCAL_ARG_SLOTS = 8;
ARG_SLOT localArgs[LOCAL_ARG_SLOTS];
InterpreterType localArgTypes[LOCAL_ARG_SLOTS];
ARG_SLOT* args;
InterpreterType* argTypes;
if (nSlots <= LOCAL_ARG_SLOTS)
{
args = &localArgs[0];
argTypes = &localArgTypes[0];
}
else
{
args = (ARG_SLOT*)_alloca(nSlots * sizeof(ARG_SLOT));
argTypes = (InterpreterType*)_alloca(nSlots * sizeof(InterpreterType));
}
// Make sure that we don't scan any of these until we overwrite them with
// the real types of the arguments.
InterpreterType undefIt(CORINFO_TYPE_UNDEF);
for (unsigned i = 0; i < nSlots; i++)
{
argTypes[i] = undefIt;
}
// GC-protect the argument array (as byrefs).
m_args = args;
m_argsSize = nSlots;
m_argTypes = argTypes;
// This is the index into the "args" array (where we copy the value to).
int curArgSlot = 0;
// The operand stack index of the first IL argument.
unsigned totalArgPositions = totalArgsOnILStack + 1; // + 1 for the ftn argument.
assert(m_curStackHt >= totalArgPositions);
int argsBase = m_curStackHt - totalArgPositions;
// Current on-stack argument index.
unsigned arg = 0;
if (sigInfo.hasThis())
{
args[curArgSlot] = PtrToArgSlot(OpStackGet<void*>(argsBase + arg));
argTypes[curArgSlot] = OpStackTypeGet(argsBase + arg);
// AV -> NullRef translation is NYI for the interpreter,
// so we should manually check and throw the correct exception.
ThrowOnInvalidPointer((void*)args[curArgSlot]);
arg++;
curArgSlot++;
}
// This is the argument slot that will be used to hold the return value.
ARG_SLOT retVal = 0;
// If the return type is a structure, then these will be initialized.
CORINFO_CLASS_HANDLE retTypeClsHnd = NULL;
InterpreterType retTypeIt;
size_t retTypeSz = 0;
// If non-null, space allocated to hold a large struct return value. Should be deleted later.
// (I could probably optimize this pop all the arguments first, then allocate space for the return value
// on the large structure operand stack, and pass a pointer directly to that space, avoiding the extra
// copy we have below. But this seemed more expedient, and this should be a pretty rare case.)
BYTE* pLargeStructRetVal = NULL;
// If there's a "GetFlag<Flag_hasRetBuffArg>()" struct return value, it will be stored in this variable if it fits,
// otherwise, we'll dynamically allocate memory for it.
ARG_SLOT smallStructRetVal = 0;
// We should have no return buffer temp space registered here...unless this is a constructor, in which
// case it will return void. In particular, if the return type VALUE_CLASS, then this should be NULL.
_ASSERTE_MSG(sigInfo.retType == CORINFO_TYPE_VOID || m_structRetValITPtr == NULL, "Invariant.");
// Is it the return value a struct with a ret buff?
bool hasRetBuffArg = false;
if (sigInfo.retType == CORINFO_TYPE_VALUECLASS)
{
retTypeClsHnd = sigInfo.retTypeClass;
retTypeIt = InterpreterType(&m_interpCeeInfo, retTypeClsHnd);
retTypeSz = retTypeIt.Size(&m_interpCeeInfo);
#if defined(_AMD64_)
// TODO: Investigate why HasRetBuffArg can't be used. pMD is a hacked up MD for the
// calli because it belongs to the current method. Doing what the JIT does.
hasRetBuffArg = (retTypeSz > sizeof(void*)) || ((retTypeSz & (retTypeSz - 1)) != 0);
#else
hasRetBuffArg = !!pMD->HasRetBuffArg();
#endif
if (hasRetBuffArg)
{
if (retTypeIt.IsLargeStruct(&m_interpCeeInfo))
{
size_t retBuffSize = retTypeSz;
// If the target architecture can sometimes return a struct in several registers,
// MethodDescCallSite will reserve a return value array big enough to hold the maximum.
// It will then copy *all* of this into the return buffer area we allocate. So make sure
// we allocate at least that much.
#ifdef ENREGISTERED_RETURNTYPE_MAXSIZE
retBuffSize = max(retTypeSz, ENREGISTERED_RETURNTYPE_MAXSIZE);
#endif // ENREGISTERED_RETURNTYPE_MAXSIZE
pLargeStructRetVal = (BYTE*)_alloca(retBuffSize);
// Clear this in case a GC happens.
for (unsigned i = 0; i < retTypeSz; i++)
{
pLargeStructRetVal[i] = 0;
}
// Register this as location needing GC.
m_structRetValTempSpace = pLargeStructRetVal;
// Set it as the return buffer.
args[curArgSlot] = PtrToArgSlot(pLargeStructRetVal);
}
else
{
// Clear this in case a GC happens.
smallStructRetVal = 0;
// Register this as location needing GC.
m_structRetValTempSpace = &smallStructRetVal;
// Set it as the return buffer.
args[curArgSlot] = PtrToArgSlot(&smallStructRetVal);
}
m_structRetValITPtr = &retTypeIt;
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
}
if ((sigInfo.callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG)
{
Module* module = GetModule(sigInfo.scope);
CORINFO_VARARGS_HANDLE handle = CORINFO_VARARGS_HANDLE(module->GetVASigCookie(Signature(sigInfo.pSig, sigInfo.cbSig)));
args[curArgSlot] = PtrToArgSlot(handle);
argTypes[curArgSlot] = InterpreterType(CORINFO_TYPE_NATIVEINT);
curArgSlot++;
}
// Now we do the non-this arguments.
size_t largeStructSpaceToPop = 0;
for (; arg < totalArgsOnILStack; arg++)
{
InterpreterType argIt = OpStackTypeGet(argsBase + arg);
size_t sz = OpStackTypeGet(argsBase + arg).Size(&m_interpCeeInfo);
switch (sz)
{
case 1:
args[curArgSlot] = OpStackGet<INT8>(argsBase + arg);
break;
case 2:
args[curArgSlot] = OpStackGet<INT16>(argsBase + arg);
break;
case 4:
args[curArgSlot] = OpStackGet<INT32>(argsBase + arg);
break;
case 8:
default:
if (sz > 8)
{
void* srcPtr = OpStackGet<void*>(argsBase + arg);
args[curArgSlot] = PtrToArgSlot(srcPtr);
if (!IsInLargeStructLocalArea(srcPtr))
{
largeStructSpaceToPop += sz;
}
}
else
{
args[curArgSlot] = OpStackGet<INT64>(argsBase + arg);
}
break;
}
argTypes[curArgSlot] = argIt;
curArgSlot++;
}
// Finally, we get the code pointer.
unsigned ftnInd = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType ftnType = OpStackTypeGet(ftnInd).ToCorInfoType();
assert(ftnType == CORINFO_TYPE_NATIVEINT
|| ftnType == CORINFO_TYPE_INT
|| ftnType == CORINFO_TYPE_LONG);
#endif // DEBUG
PCODE ftnPtr = OpStackGet<PCODE>(ftnInd);
{
MethodDesc* methToCall;
// If we're interpreting the target, simply call it directly.
if ((methToCall = InterpretationStubToMethodInfo((PCODE)ftnPtr)) != NULL)
{
InterpreterMethodInfo* methInfo = MethodHandleToInterpreterMethInfoPtr(CORINFO_METHOD_HANDLE(methToCall));
assert(methInfo != NULL);
#if INTERP_ILCYCLE_PROFILE
bool b = CycleTimer::GetThreadCyclesS(&startCycles); assert(b);
#endif // INTERP_ILCYCLE_PROFILE
retVal = InterpretMethodBody(methInfo, true, reinterpret_cast<BYTE*>(args), NULL);
}
else
{
// This is not a great workaround. For the most part, we really don't care what method desc we're using, since
// we're providing the signature and function pointer -- other than that it's well-formed and "activated."
// And also, one more thing: whether it is static or not. Which is actually determined by the signature.
// So we query the signature we have to determine whether we need a static or instance MethodDesc, and then
// use one of the appropriate staticness that happens to be sitting around in global variables. For static
// we use "RuntimeHelpers.PrepareConstrainedRegions", for instance we use the default constructor of "Object."
// TODO: make this cleaner -- maybe invent a couple of empty methods with instructive names, just for this purpose.
MethodDesc* pMD;
if (mSig.HasThis())
{
pMD = g_pObjectCtorMD;
}
else
{
pMD = g_pExecuteBackoutCodeHelperMethod; // A random static method.
}
MethodDescCallSite mdcs(pMD, &mSig, ftnPtr);
#if 0
// If the current method being interpreted is an IL stub, we're calling native code, so
// change the GC mode. (We'll only do this at the call if the calling convention turns out
// to be a managed calling convention.)
MethodDesc* pStubContextMD = reinterpret_cast<MethodDesc*>(m_stubContext);
bool transitionToPreemptive = (pStubContextMD != NULL && !pStubContextMD->IsIL());
mdcs.CallTargetWorker(args, &retVal, sizeof(retVal), transitionToPreemptive);
#else
// TODO The code above triggers assertion at threads.cpp:6861:
// _ASSERTE(thread->PreemptiveGCDisabled()); // Should have been in managed code
// The workaround will likely break more things than what it is fixing:
// just do not make transition to preemptive GC for now.
mdcs.CallTargetWorker(args, &retVal, sizeof(retVal));
#endif
}
// retVal is now vulnerable.
GCX_FORBID();
}
// retVal is still vulnerable.
{
GCX_FORBID();
m_argsSize = 0;
// At this point, the call has happened successfully. We can delete the arguments from the operand stack.
m_curStackHt -= totalArgPositions;
// We've already checked that "largeStructSpaceToPop
LargeStructOperandStackPop(largeStructSpaceToPop, NULL);
if (size_t(m_callThisArg) == 0x1)
{
_ASSERTE_MSG(sigInfo.retType == CORINFO_TYPE_VOID, "Constructor for var-sized object becomes factory method that returns result.");
OpStackSet<Object*>(m_curStackHt, reinterpret_cast<Object*>(retVal));
OpStackTypeSet(m_curStackHt, InterpreterType(CORINFO_TYPE_CLASS));
m_curStackHt++;
}
else if (sigInfo.retType != CORINFO_TYPE_VOID)
{
switch (sigInfo.retType)
{
case CORINFO_TYPE_BOOL:
case CORINFO_TYPE_BYTE:
OpStackSet<INT32>(m_curStackHt, static_cast<INT8>(retVal));
break;
case CORINFO_TYPE_UBYTE:
OpStackSet<UINT32>(m_curStackHt, static_cast<UINT8>(retVal));
break;
case CORINFO_TYPE_SHORT:
OpStackSet<INT32>(m_curStackHt, static_cast<INT16>(retVal));
break;
case CORINFO_TYPE_USHORT:
case CORINFO_TYPE_CHAR:
OpStackSet<UINT32>(m_curStackHt, static_cast<UINT16>(retVal));
break;
case CORINFO_TYPE_INT:
case CORINFO_TYPE_UINT:
case CORINFO_TYPE_FLOAT:
OpStackSet<INT32>(m_curStackHt, static_cast<INT32>(retVal));
break;
case CORINFO_TYPE_LONG:
case CORINFO_TYPE_ULONG:
case CORINFO_TYPE_DOUBLE:
OpStackSet<INT64>(m_curStackHt, static_cast<INT64>(retVal));
break;
case CORINFO_TYPE_NATIVEINT:
case CORINFO_TYPE_NATIVEUINT:
case CORINFO_TYPE_PTR:
OpStackSet<NativeInt>(m_curStackHt, static_cast<NativeInt>(retVal));
break;
case CORINFO_TYPE_CLASS:
OpStackSet<Object*>(m_curStackHt, reinterpret_cast<Object*>(retVal));
break;
case CORINFO_TYPE_VALUECLASS:
{
// We must be careful here to write the value, the type, and update the stack height in one
// sequence that has no COOP->PREEMP transitions in it, so no GC's happen until the value
// is protected by being fully "on" the operandStack.
if (pLargeStructRetVal != NULL)
{
assert(hasRetBuffArg);
void* dst = LargeStructOperandStackPush(retTypeSz);
CopyValueClassUnchecked(dst, pLargeStructRetVal, GetMethodTableFromClsHnd(retTypeClsHnd));
OpStackSet<void*>(m_curStackHt, dst);
}
else if (hasRetBuffArg)
{
OpStackSet<INT64>(m_curStackHt, GetSmallStructValue(&smallStructRetVal, retTypeSz));
}
else
{
OpStackSet<UINT64>(m_curStackHt, retVal);
}
// We already created this interpreter type, so use it.
OpStackTypeSet(m_curStackHt, retTypeIt.StackNormalize());
m_curStackHt++;
// In the value-class case, the call might have used a ret buff, which we would have registered for GC scanning.
// Make sure it's unregistered.
m_structRetValITPtr = NULL;
}
break;
default:
NYI_INTERP("Unhandled return type");
break;
}
_ASSERTE_MSG(m_structRetValITPtr == NULL, "Invariant.");
// The valueclass case is handled fully in the switch above.
if (sigInfo.retType != CORINFO_TYPE_VALUECLASS)
{
OpStackTypeSet(m_curStackHt, InterpreterType(sigInfo.retType).StackNormalize());
m_curStackHt++;
}
}
}
// Originally, this assertion was in the ValueClass case above, but it does a COOP->PREEMP
// transition, and therefore causes a GC, and we're GCX_FORBIDden from doing a GC while retVal
// is vulnerable. So, for completeness, do it here.
assert(sigInfo.retType != CORINFO_TYPE_VALUECLASS || retTypeIt == InterpreterType(&m_interpCeeInfo, retTypeClsHnd));
m_ILCodePtr += 5;
}
// static
bool Interpreter::IsDeadSimpleGetter(CEEInfo* info, MethodDesc* pMD, size_t* offsetOfLd)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_ANY;
} CONTRACTL_END;
DWORD flags = pMD->GetAttrs();
CORINFO_METHOD_INFO methInfo;
{
GCX_PREEMP();
bool b = info->getMethodInfo(CORINFO_METHOD_HANDLE(pMD), &methInfo);
if (!b) return false;
}
// If the method takes a generic type argument, it's not dead simple...
if (methInfo.args.callConv & CORINFO_CALLCONV_PARAMTYPE) return false;
BYTE* codePtr = methInfo.ILCode;
if (flags & CORINFO_FLG_STATIC)
{
if (methInfo.ILCodeSize != 6)
return false;
if (*codePtr != CEE_LDSFLD)
return false;
assert(ILOffsetOfLdSFldInDeadSimpleStaticGetter == 0);
*offsetOfLd = 0;
codePtr += 5;
return (*codePtr == CEE_RET);
}
else
{
// We handle two forms, one for DBG IL, and one for OPT IL.
bool dbg = false;
if (methInfo.ILCodeSize == 0xc)
dbg = true;
else if (methInfo.ILCodeSize != 7)
return false;
if (dbg)
{
if (*codePtr != CEE_NOP)
return false;
codePtr += 1;
}
if (*codePtr != CEE_LDARG_0)
return false;
codePtr += 1;
if (*codePtr != CEE_LDFLD)
return false;
*offsetOfLd = codePtr - methInfo.ILCode;
assert((dbg && ILOffsetOfLdFldInDeadSimpleInstanceGetterDbg == *offsetOfLd)
|| (!dbg && ILOffsetOfLdFldInDeadSimpleInstanceGetterOpt == *offsetOfLd));
codePtr += 5;
if (dbg)
{
if (*codePtr != CEE_STLOC_0)
return false;
codePtr += 1;
if (*codePtr != CEE_BR)
return false;
if (getU4LittleEndian(codePtr + 1) != 0)
return false;
codePtr += 5;
if (*codePtr != CEE_LDLOC_0)
return false;
}
return (*codePtr == CEE_RET);
}
}
void Interpreter::DoStringLength()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt > 0);
unsigned ind = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType stringCIT = OpStackTypeGet(ind).ToCorInfoType();
if (stringCIT != CORINFO_TYPE_CLASS)
{
VerificationError("StringLength called on non-string.");
}
#endif // _DEBUG
Object* obj = OpStackGet<Object*>(ind);
#ifdef _DEBUG
if (obj->GetMethodTable() != g_pStringClass)
{
VerificationError("StringLength called on non-string.");
}
#endif // _DEBUG
StringObject* str = reinterpret_cast<StringObject*>(obj);
INT32 len = str->GetStringLength();
OpStackSet<INT32>(ind, len);
OpStackTypeSet(ind, InterpreterType(CORINFO_TYPE_INT));
}
void Interpreter::DoStringGetChar()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt >= 2);
unsigned strInd = m_curStackHt - 2;
unsigned indexInd = strInd + 1;
#ifdef _DEBUG
CorInfoType stringCIT = OpStackTypeGet(strInd).ToCorInfoType();
if (stringCIT != CORINFO_TYPE_CLASS)
{
VerificationError("StringGetChar called on non-string.");
}
#endif // _DEBUG
Object* obj = OpStackGet<Object*>(strInd);
#ifdef _DEBUG
if (obj->GetMethodTable() != g_pStringClass)
{
VerificationError("StringGetChar called on non-string.");
}
#endif // _DEBUG
StringObject* str = reinterpret_cast<StringObject*>(obj);
#ifdef _DEBUG
CorInfoType indexCIT = OpStackTypeGet(indexInd).ToCorInfoType();
if (indexCIT != CORINFO_TYPE_INT)
{
VerificationError("StringGetChar needs integer index.");
}
#endif // _DEBUG
INT32 ind = OpStackGet<INT32>(indexInd);
if (ind < 0)
ThrowArrayBoundsException();
UINT32 uind = static_cast<UINT32>(ind);
if (uind >= str->GetStringLength())
ThrowArrayBoundsException();
// Otherwise...
GCX_FORBID(); // str is vulnerable.
UINT16* dataPtr = reinterpret_cast<UINT16*>(reinterpret_cast<INT8*>(str) + StringObject::GetBufferOffset());
UINT32 filledChar = dataPtr[ind];
OpStackSet<UINT32>(strInd, filledChar);
OpStackTypeSet(strInd, InterpreterType(CORINFO_TYPE_INT));
m_curStackHt = indexInd;
}
void Interpreter::DoGetTypeFromHandle()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
assert(m_curStackHt > 0);
unsigned ind = m_curStackHt - 1;
#ifdef _DEBUG
CorInfoType handleCIT = OpStackTypeGet(ind).ToCorInfoType();
if (handleCIT != CORINFO_TYPE_VALUECLASS && handleCIT != CORINFO_TYPE_CLASS)
{
VerificationError("HandleGetTypeFromHandle called on non-RuntimeTypeHandle/non-RuntimeType.");
}
Object* obj = OpStackGet<Object*>(ind);
if (obj->GetMethodTable() != g_pRuntimeTypeClass)
{
VerificationError("HandleGetTypeFromHandle called on non-RuntimeTypeHandle/non-RuntimeType.");
}
#endif // _DEBUG
OpStackTypeSet(ind, InterpreterType(CORINFO_TYPE_CLASS));
}
void Interpreter::RecordConstrainedCall()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
#if INTERP_TRACING
InterlockedIncrement(&s_tokenResolutionOpportunities[RTK_Constrained]);
#endif // INTERP_TRACING
{
GCX_PREEMP();
ResolveToken(&m_constrainedResolvedToken, getU4LittleEndian(m_ILCodePtr + 2), CORINFO_TOKENKIND_Constrained InterpTracingArg(RTK_Constrained));
}
m_constrainedFlag = true;
m_ILCodePtr += 6;
}
void Interpreter::LargeStructOperandStackEnsureCanPush(size_t sz)
{
size_t remaining = m_largeStructOperandStackAllocSize - m_largeStructOperandStackHt;
if (remaining < sz)
{
size_t newAllocSize = max(m_largeStructOperandStackAllocSize + sz * 4, m_largeStructOperandStackAllocSize * 2);
BYTE* newStack = new BYTE[newAllocSize];
m_largeStructOperandStackAllocSize = newAllocSize;
if (m_largeStructOperandStack != NULL)
{
memcpy(newStack, m_largeStructOperandStack, m_largeStructOperandStackHt);
delete[] m_largeStructOperandStack;
}
m_largeStructOperandStack = newStack;
}
}
void* Interpreter::LargeStructOperandStackPush(size_t sz)
{
LargeStructOperandStackEnsureCanPush(sz);
assert(m_largeStructOperandStackAllocSize >= m_largeStructOperandStackHt + sz);
void* res = &m_largeStructOperandStack[m_largeStructOperandStackHt];
m_largeStructOperandStackHt += sz;
return res;
}
void Interpreter::LargeStructOperandStackPop(size_t sz, void* fromAddr)
{
if (!IsInLargeStructLocalArea(fromAddr))
{
assert(m_largeStructOperandStackHt >= sz);
m_largeStructOperandStackHt -= sz;
}
}
#ifdef _DEBUG
bool Interpreter::LargeStructStackHeightIsValid()
{
size_t sz2 = 0;
for (unsigned k = 0; k < m_curStackHt; k++)
{
if (OpStackTypeGet(k).IsLargeStruct(&m_interpCeeInfo) && !IsInLargeStructLocalArea(OpStackGet<void*>(k)))
{
sz2 += OpStackTypeGet(k).Size(&m_interpCeeInfo);
}
}
assert(sz2 == m_largeStructOperandStackHt);
return sz2 == m_largeStructOperandStackHt;
}
#endif // _DEBUG
void Interpreter::VerificationError(const char* msg)
{
// TODO: Should raise an exception eventually; for now:
const char* const msgPrefix = "Verification Error: ";
size_t len = strlen(msgPrefix) + strlen(msg) + 1;
char* msgFinal = (char*)_alloca(len);
strcpy_s(msgFinal, len, msgPrefix);
strcat_s(msgFinal, len, msg);
_ASSERTE_MSG(false, msgFinal);
}
void Interpreter::ThrowDivideByZero()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
COMPlusThrow(kDivideByZeroException);
}
void Interpreter::ThrowSysArithException()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
// According to the ECMA spec, this should be an ArithmeticException; however,
// the JITs throw an OverflowException and consistency is top priority...
COMPlusThrow(kOverflowException);
}
void Interpreter::ThrowNullPointerException()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
COMPlusThrow(kNullReferenceException);
}
void Interpreter::ThrowOverflowException()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
COMPlusThrow(kOverflowException);
}
void Interpreter::ThrowArrayBoundsException()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
COMPlusThrow(kIndexOutOfRangeException);
}
void Interpreter::ThrowInvalidCastException()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
COMPlusThrow(kInvalidCastException);
}
void Interpreter::ThrowStackOverflow()
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
COMPlusThrow(kStackOverflowException);
}
float Interpreter::RemFunc(float v1, float v2)
{
return fmodf(v1, v2);
}
double Interpreter::RemFunc(double v1, double v2)
{
return fmod(v1, v2);
}
// Static members and methods.
Interpreter::AddrToMDMap* Interpreter::s_addrToMDMap = NULL;
unsigned Interpreter::s_interpreterStubNum = 0;
// TODO: contracts and synchronization for the AddrToMDMap methods.
// Requires caller to hold "s_interpStubToMDMapLock".
Interpreter::AddrToMDMap* Interpreter::GetAddrToMdMap()
{
#if 0
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
#endif
if (s_addrToMDMap == NULL)
{
s_addrToMDMap = new AddrToMDMap();
}
return s_addrToMDMap;
}
void Interpreter::RecordInterpreterStubForMethodDesc(CORINFO_METHOD_HANDLE md, void* addr)
{
#if 0
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#endif
CrstHolder ch(&s_interpStubToMDMapLock);
AddrToMDMap* map = Interpreter::GetAddrToMdMap();
#ifdef _DEBUG
CORINFO_METHOD_HANDLE dummy;
assert(!map->Lookup(addr, &dummy));
#endif // DEBUG
map->AddOrReplace(KeyValuePair<void*,CORINFO_METHOD_HANDLE>(addr, md));
}
MethodDesc* Interpreter::InterpretationStubToMethodInfo(PCODE addr)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
// This query function will never allocate the table...
if (s_addrToMDMap == NULL)
return NULL;
// Otherwise...if we observe s_addrToMdMap non-null, the lock below must be initialized.
// CrstHolder ch(&s_interpStubToMDMapLock);
AddrToMDMap* map = Interpreter::GetAddrToMdMap();
CORINFO_METHOD_HANDLE result = NULL;
(void)map->Lookup((void*)addr, &result);
return (MethodDesc*)result;
}
Interpreter::MethodHandleToInterpMethInfoPtrMap* Interpreter::s_methodHandleToInterpMethInfoPtrMap = NULL;
// Requires caller to hold "s_interpStubToMDMapLock".
Interpreter::MethodHandleToInterpMethInfoPtrMap* Interpreter::GetMethodHandleToInterpMethInfoPtrMap()
{
#if 0
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
#endif
if (s_methodHandleToInterpMethInfoPtrMap == NULL)
{
s_methodHandleToInterpMethInfoPtrMap = new MethodHandleToInterpMethInfoPtrMap();
}
return s_methodHandleToInterpMethInfoPtrMap;
}
InterpreterMethodInfo* Interpreter::RecordInterpreterMethodInfoForMethodHandle(CORINFO_METHOD_HANDLE md, InterpreterMethodInfo* methInfo)
{
#if 0
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#endif
CrstHolder ch(&s_interpStubToMDMapLock);
MethodHandleToInterpMethInfoPtrMap* map = Interpreter::GetMethodHandleToInterpMethInfoPtrMap();
MethInfo mi;
if (map->Lookup(md, &mi))
{
// If there's already an entry, make sure it was created by another thread -- the same thread shouldn't create two
// of these.
_ASSERTE_MSG(mi.m_thread != GetThread(), "Two InterpMethInfo's for same meth by same thread.");
// If we were creating an interpreter stub at the same time as another thread, and we lost the race to
// insert it, use the already-existing one, and delete this one.
delete methInfo;
return mi.m_info;
}
mi.m_info = methInfo;
#ifdef _DEBUG
mi.m_thread = GetThread();
#endif
_ASSERTE_MSG(map->LookupPtr(md) == NULL, "Multiple InterpMethInfos for method desc.");
map->Add(md, mi);
return methInfo;
}
InterpreterMethodInfo* Interpreter::MethodHandleToInterpreterMethInfoPtr(CORINFO_METHOD_HANDLE md)
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_TRIGGERS;
} CONTRACTL_END;
// This query function will never allocate the table...
if (s_methodHandleToInterpMethInfoPtrMap == NULL)
return NULL;
// Otherwise...if we observe s_addrToMdMap non-null, the lock below must be initialized.
CrstHolder ch(&s_interpStubToMDMapLock);
MethodHandleToInterpMethInfoPtrMap* map = Interpreter::GetMethodHandleToInterpMethInfoPtrMap();
MethInfo mi;
mi.m_info = NULL;
(void)map->Lookup(md, &mi);
return mi.m_info;
}
#ifndef DACCESS_COMPILE
// Requires that the current thread holds "s_methodCacheLock."
ILOffsetToItemCache* InterpreterMethodInfo::GetCacheForCall(Object* thisArg, void* genericsCtxtArg, bool alloc)
{
// First, does the current method have dynamic generic information, and, if so,
// what kind?
CORINFO_CONTEXT_HANDLE context = GetPreciseGenericsContext(thisArg, genericsCtxtArg);
if (context == MAKE_METHODCONTEXT(m_method))
{
// No dynamic generics context information. The caching field in "m_methInfo" is the
// ILoffset->Item cache directly.
// First, ensure that it's allocated.
if (m_methodCache == NULL && alloc)
{
// Lazy init via compare-exchange.
ILOffsetToItemCache* cache = new ILOffsetToItemCache();
void* prev = InterlockedCompareExchangeT<void*>(&m_methodCache, cache, NULL);
if (prev != NULL) delete cache;
}
return reinterpret_cast<ILOffsetToItemCache*>(m_methodCache);
}
else
{
// Otherwise, it does have generic info, so find the right cache.
// First ensure that the top-level generics-context --> cache cache exists.
GenericContextToInnerCache* outerCache = reinterpret_cast<GenericContextToInnerCache*>(m_methodCache);
if (outerCache == NULL)
{
if (alloc)
{
// Lazy init via compare-exchange.
outerCache = new GenericContextToInnerCache();
void* prev = InterlockedCompareExchangeT<void*>(&m_methodCache, outerCache, NULL);
if (prev != NULL)
{
delete outerCache;
outerCache = reinterpret_cast<GenericContextToInnerCache*>(prev);
}
}
else
{
return NULL;
}
}
// Does the outerCache already have an entry for this instantiation?
ILOffsetToItemCache* innerCache = NULL;
if (!outerCache->GetItem(size_t(context), innerCache) && alloc)
{
innerCache = new ILOffsetToItemCache();
outerCache->AddItem(size_t(context), innerCache);
}
return innerCache;
}
}
void Interpreter::CacheCallInfo(unsigned iloffset, CallSiteCacheData* callInfo)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(true);
// Insert, but if the item is already there, delete "mdcs" (which would have been owned
// by the cache).
// (Duplicate entries can happen because of recursive calls -- F makes a recursive call to F, and when it
// returns wants to cache it, but the recursive call makes a furher recursive call, and caches that, so the
// first call finds the iloffset already occupied.)
if (!cache->AddItem(iloffset, CachedItem(callInfo)))
{
delete callInfo;
}
}
CallSiteCacheData* Interpreter::GetCachedCallInfo(unsigned iloffset)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(false);
if (cache == NULL) return NULL;
// Otherwise...
CachedItem item;
if (cache->GetItem(iloffset, item))
{
_ASSERTE_MSG(item.m_tag == CIK_CallSite, "Wrong cached item tag.");
return item.m_value.m_callSiteInfo;
}
else
{
return NULL;
}
}
void Interpreter::CacheInstanceField(unsigned iloffset, FieldDesc* fld)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(true);
cache->AddItem(iloffset, CachedItem(fld));
}
FieldDesc* Interpreter::GetCachedInstanceField(unsigned iloffset)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(false);
if (cache == NULL) return NULL;
// Otherwise...
CachedItem item;
if (cache->GetItem(iloffset, item))
{
_ASSERTE_MSG(item.m_tag == CIK_InstanceField, "Wrong cached item tag.");
return item.m_value.m_instanceField;
}
else
{
return NULL;
}
}
void Interpreter::CacheStaticField(unsigned iloffset, StaticFieldCacheEntry* pEntry)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(true);
// If (say) a concurrent thread has beaten us to this, delete the entry (which otherwise would have
// been owned by the cache).
if (!cache->AddItem(iloffset, CachedItem(pEntry)))
{
delete pEntry;
}
}
StaticFieldCacheEntry* Interpreter::GetCachedStaticField(unsigned iloffset)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(false);
if (cache == NULL)
return NULL;
// Otherwise...
CachedItem item;
if (cache->GetItem(iloffset, item))
{
_ASSERTE_MSG(item.m_tag == CIK_StaticField, "Wrong cached item tag.");
return item.m_value.m_staticFieldAddr;
}
else
{
return NULL;
}
}
void Interpreter::CacheClassHandle(unsigned iloffset, CORINFO_CLASS_HANDLE clsHnd)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(true);
cache->AddItem(iloffset, CachedItem(clsHnd));
}
CORINFO_CLASS_HANDLE Interpreter::GetCachedClassHandle(unsigned iloffset)
{
CrstHolder ch(&s_methodCacheLock);
ILOffsetToItemCache* cache = GetThisExecCache(false);
if (cache == NULL)
return NULL;
// Otherwise...
CachedItem item;
if (cache->GetItem(iloffset, item))
{
_ASSERTE_MSG(item.m_tag == CIK_ClassHandle, "Wrong cached item tag.");
return item.m_value.m_clsHnd;
}
else
{
return NULL;
}
}
#endif // DACCESS_COMPILE
// Statics
// Theses are not debug-only.
ConfigMethodSet Interpreter::s_InterpretMeths;
ConfigMethodSet Interpreter::s_InterpretMethsExclude;
ConfigDWORD Interpreter::s_InterpretMethHashMin;
ConfigDWORD Interpreter::s_InterpretMethHashMax;
ConfigDWORD Interpreter::s_InterpreterJITThreshold;
ConfigDWORD Interpreter::s_InterpreterDoLoopMethodsFlag;
ConfigDWORD Interpreter::s_InterpreterUseCachingFlag;
ConfigDWORD Interpreter::s_InterpreterLooseRulesFlag;
bool Interpreter::s_InterpreterDoLoopMethods;
bool Interpreter::s_InterpreterUseCaching;
bool Interpreter::s_InterpreterLooseRules;
CrstExplicitInit Interpreter::s_methodCacheLock;
CrstExplicitInit Interpreter::s_interpStubToMDMapLock;
// The static variables below are debug-only.
#if INTERP_TRACING
LONG Interpreter::s_totalInvocations = 0;
LONG Interpreter::s_totalInterpCalls = 0;
LONG Interpreter::s_totalInterpCallsToGetters = 0;
LONG Interpreter::s_totalInterpCallsToDeadSimpleGetters = 0;
LONG Interpreter::s_totalInterpCallsToDeadSimpleGettersShortCircuited = 0;
LONG Interpreter::s_totalInterpCallsToSetters = 0;
LONG Interpreter::s_totalInterpCallsToIntrinsics = 0;
LONG Interpreter::s_totalInterpCallsToIntrinsicsUnhandled = 0;
LONG Interpreter::s_tokenResolutionOpportunities[RTK_Count] = {0, };
LONG Interpreter::s_tokenResolutionCalls[RTK_Count] = {0, };
const char* Interpreter::s_tokenResolutionKindNames[RTK_Count] =
{
"Undefined",
"Constrained",
"NewObj",
"NewArr",
"LdToken",
"LdFtn",
"LdVirtFtn",
"SFldAddr",
"LdElem",
"Call",
"LdObj",
"StObj",
"CpObj",
"InitObj",
"IsInst",
"CastClass",
"MkRefAny",
"RefAnyVal",
"Sizeof",
"StElem",
"Box",
"Unbox",
"UnboxAny",
"LdFld",
"LdFldA",
"StFld",
"FindClass",
"Exception",
};
FILE* Interpreter::s_InterpreterLogFile = NULL;
ConfigDWORD Interpreter::s_DumpInterpreterStubsFlag;
ConfigDWORD Interpreter::s_TraceInterpreterEntriesFlag;
ConfigDWORD Interpreter::s_TraceInterpreterILFlag;
ConfigDWORD Interpreter::s_TraceInterpreterOstackFlag;
ConfigDWORD Interpreter::s_TraceInterpreterVerboseFlag;
ConfigDWORD Interpreter::s_TraceInterpreterJITTransitionFlag;
ConfigDWORD Interpreter::s_InterpreterStubMin;
ConfigDWORD Interpreter::s_InterpreterStubMax;
#endif // INTERP_TRACING
#if INTERP_ILINSTR_PROFILE
unsigned short Interpreter::s_ILInstrCategories[512];
int Interpreter::s_ILInstrExecs[256] = {0, };
int Interpreter::s_ILInstrExecsByCategory[512] = {0, };
int Interpreter::s_ILInstr2ByteExecs[Interpreter::CountIlInstr2Byte] = {0, };
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 Interpreter::s_ILInstrCycles[512] = { 0, };
unsigned __int64 Interpreter::s_ILInstrCyclesByCategory[512] = { 0, };
// XXX
unsigned __int64 Interpreter::s_callCycles = 0;
unsigned Interpreter::s_calls = 0;
void Interpreter::UpdateCycleCount()
{
unsigned __int64 endCycles;
bool b = CycleTimer::GetThreadCyclesS(&endCycles); assert(b);
if (m_instr != CEE_COUNT)
{
unsigned __int64 delta = (endCycles - m_startCycles);
if (m_exemptCycles > 0)
{
delta = delta - m_exemptCycles;
m_exemptCycles = 0;
}
CycleTimer::InterlockedAddU64(&s_ILInstrCycles[m_instr], delta);
}
// In any case, set the instruction to the current one, and record it's start time.
m_instr = (*m_ILCodePtr);
if (m_instr == CEE_PREFIX1) {
m_instr = *(m_ILCodePtr + 1) + 0x100;
}
b = CycleTimer::GetThreadCyclesS(&m_startCycles); assert(b);
}
#endif // INTERP_ILCYCLE_PROFILE
#endif // INTERP_ILINSTR_PROFILE
#ifdef _DEBUG
InterpreterMethodInfo** Interpreter::s_interpMethInfos = NULL;
unsigned Interpreter::s_interpMethInfosAllocSize = 0;
unsigned Interpreter::s_interpMethInfosCount = 0;
bool Interpreter::TOSIsPtr()
{
if (m_curStackHt == 0)
return false;
return CorInfoTypeIsPointer(OpStackTypeGet(m_curStackHt - 1).ToCorInfoType());
}
#endif // DEBUG
ConfigDWORD Interpreter::s_PrintPostMortemFlag;
// InterpreterCache.
template<typename Key, typename Val>
InterpreterCache<Key,Val>::InterpreterCache() : m_pairs(NULL), m_allocSize(0), m_count(0)
{
#ifdef _DEBUG
AddAllocBytes(sizeof(*this));
#endif
}
#ifdef _DEBUG
// static
static unsigned InterpreterCacheAllocBytes = 0;
const unsigned KBYTE = 1024;
const unsigned MBYTE = KBYTE*KBYTE;
const unsigned InterpreterCacheAllocBytesIncrement = 16*KBYTE;
static unsigned InterpreterCacheAllocBytesNextTarget = InterpreterCacheAllocBytesIncrement;
template<typename Key, typename Val>
void InterpreterCache<Key,Val>::AddAllocBytes(unsigned bytes)
{
// Reinstate this code if you want to track bytes attributable to caching.
#if 0
InterpreterCacheAllocBytes += bytes;
if (InterpreterCacheAllocBytes > InterpreterCacheAllocBytesNextTarget)
{
printf("Total cache alloc = %d bytes.\n", InterpreterCacheAllocBytes);
fflush(stdout);
InterpreterCacheAllocBytesNextTarget += InterpreterCacheAllocBytesIncrement;
}
#endif
}
#endif // _DEBUG
template<typename Key, typename Val>
void InterpreterCache<Key,Val>::EnsureCanInsert()
{
if (m_count < m_allocSize)
return;
// Otherwise, must make room.
if (m_allocSize == 0)
{
assert(m_count == 0);
m_pairs = new KeyValPair[InitSize];
m_allocSize = InitSize;
#ifdef _DEBUG
AddAllocBytes(m_allocSize * sizeof(KeyValPair));
#endif
}
else
{
unsigned short newSize = min(m_allocSize * 2, USHRT_MAX);
KeyValPair* newPairs = new KeyValPair[newSize];
memcpy(newPairs, m_pairs, m_count * sizeof(KeyValPair));
delete[] m_pairs;
m_pairs = newPairs;
#ifdef _DEBUG
AddAllocBytes((newSize - m_allocSize) * sizeof(KeyValPair));
#endif
m_allocSize = newSize;
}
}
template<typename Key, typename Val>
bool InterpreterCache<Key,Val>::AddItem(Key key, Val val)
{
EnsureCanInsert();
// Find the index to insert before.
unsigned firstGreaterOrEqual = 0;
for (; firstGreaterOrEqual < m_count; firstGreaterOrEqual++)
{
if (m_pairs[firstGreaterOrEqual].m_key >= key)
break;
}
if (firstGreaterOrEqual < m_count && m_pairs[firstGreaterOrEqual].m_key == key)
{
assert(m_pairs[firstGreaterOrEqual].m_val == val);
return false;
}
// Move everything starting at firstGreater up one index (if necessary)
if (m_count > 0)
{
for (unsigned k = m_count-1; k >= firstGreaterOrEqual; k--)
{
m_pairs[k + 1] = m_pairs[k];
if (k == 0)
break;
}
}
// Now we can insert the new element.
m_pairs[firstGreaterOrEqual].m_key = key;
m_pairs[firstGreaterOrEqual].m_val = val;
m_count++;
return true;
}
template<typename Key, typename Val>
bool InterpreterCache<Key,Val>::GetItem(Key key, Val& v)
{
unsigned lo = 0;
unsigned hi = m_count;
// Invariant: we've determined that the pair for "iloffset", if present,
// is in the index interval [lo, hi).
while (lo < hi)
{
unsigned mid = (hi + lo)/2;
Key midKey = m_pairs[mid].m_key;
if (key == midKey)
{
v = m_pairs[mid].m_val;
return true;
}
else if (key < midKey)
{
hi = mid;
}
else
{
assert(key > midKey);
lo = mid + 1;
}
}
// If we reach here without returning, it's not here.
return false;
}
// TODO: add a header comment here describing this function.
void Interpreter::OpStackNormalize()
{
size_t largeStructStackOffset = 0;
// Yes, I've written a quadratic algorithm here. I don't think it will matter in practice.
for (unsigned i = 0; i < m_curStackHt; i++)
{
InterpreterType tp = OpStackTypeGet(i);
if (tp.IsLargeStruct(&m_interpCeeInfo))
{
size_t sz = tp.Size(&m_interpCeeInfo);
void* addr = OpStackGet<void*>(i);
if (IsInLargeStructLocalArea(addr))
{
// We're going to allocate space at the top for the new value, then copy everything above the current slot
// up into that new space, then copy the value into the vacated space.
// How much will we have to copy?
size_t toCopy = m_largeStructOperandStackHt - largeStructStackOffset;
// Allocate space for the new value.
void* dummy = LargeStructOperandStackPush(sz);
// Remember where we're going to write to.
BYTE* fromAddr = m_largeStructOperandStack + largeStructStackOffset;
BYTE* toAddr = fromAddr + sz;
memcpy(toAddr, fromAddr, toCopy);
// Now copy the local variable value.
memcpy(fromAddr, addr, sz);
OpStackSet<void*>(i, fromAddr);
}
largeStructStackOffset += sz;
}
}
// When we've normalized the stack, it contains no pointers to locals.
m_orOfPushedInterpreterTypes = 0;
}
#if INTERP_TRACING
// Code copied from eeinterface.cpp in "compiler". Should be common...
static const char* CorInfoTypeNames[] = {
"undef",
"void",
"bool",
"char",
"byte",
"ubyte",
"short",
"ushort",
"int",
"uint",
"long",
"ulong",
"nativeint",
"nativeuint",
"float",
"double",
"string",
"ptr",
"byref",
"valueclass",
"class",
"refany",
"var"
};
const char* eeGetMethodFullName(CEEInfo* info, CORINFO_METHOD_HANDLE hnd, const char** clsName)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
GC_TRIGGERS;
MODE_ANY;
} CONTRACTL_END;
GCX_PREEMP();
const char* returnType = NULL;
const char* className;
const char* methodName = info->getMethodName(hnd, &className);
if (clsName != NULL)
{
*clsName = className;
}
size_t length = 0;
unsigned i;
/* Generating the full signature is a two-pass process. First we have to walk
the components in order to assess the total size, then we allocate the buffer
and copy the elements into it.
*/
/* Right now there is a race-condition in the EE, className can be NULL */
/* initialize length with length of className and '.' */
if (className)
{
length = strlen(className) + 1;
}
else
{
assert(strlen("<NULL>.") == 7);
length = 7;
}
/* add length of methodName and opening bracket */
length += strlen(methodName) + 1;
CORINFO_SIG_INFO sig;
info->getMethodSig(hnd, &sig);
CORINFO_ARG_LIST_HANDLE argLst = sig.args;
CORINFO_CLASS_HANDLE dummyCls;
for (i = 0; i < sig.numArgs; i++)
{
CorInfoType type = strip(info->getArgType(&sig, argLst, &dummyCls));
length += strlen(CorInfoTypeNames[type]);
argLst = info->getArgNext(argLst);
}
/* add ',' if there is more than one argument */
if (sig.numArgs > 1)
{
length += (sig.numArgs - 1);
}
if (sig.retType != CORINFO_TYPE_VOID)
{
returnType = CorInfoTypeNames[sig.retType];
length += strlen(returnType) + 1; // don't forget the delimiter ':'
}
/* add closing bracket and null terminator */
length += 2;
char* retName = new char[length];
/* Now generate the full signature string in the allocated buffer */
if (className)
{
strcpy_s(retName, length, className);
strcat_s(retName, length, ":");
}
else
{
strcpy_s(retName, length, "<NULL>.");
}
strcat_s(retName, length, methodName);
// append the signature
strcat_s(retName, length, "(");
argLst = sig.args;
for (i = 0; i < sig.numArgs; i++)
{
CorInfoType type = strip(info->getArgType(&sig, argLst, &dummyCls));
strcat_s(retName, length, CorInfoTypeNames[type]);
argLst = info->getArgNext(argLst);
if (i + 1 < sig.numArgs)
{
strcat_s(retName, length, ",");
}
}
strcat_s(retName, length, ")");
if (returnType)
{
strcat_s(retName, length, ":");
strcat_s(retName, length, returnType);
}
assert(strlen(retName) == length - 1);
return(retName);
}
const char* Interpreter::eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd)
{
return ::eeGetMethodFullName(&m_interpCeeInfo, hnd);
}
const char* ILOpNames[256*2];
bool ILOpNamesInited = false;
void InitILOpNames()
{
if (!ILOpNamesInited)
{
// Initialize the array.
#define OPDEF(c,s,pop,push,args,type,l,s1,s2,ctrl) if (s1 == 0xfe || s1 == 0xff) { int ind ((unsigned(s1) << 8) + unsigned(s2)); ind -= 0xfe00; ILOpNames[ind] = s; }
#include "opcode.def"
#undef OPDEF
ILOpNamesInited = true;
}
};
const char* Interpreter::ILOp(BYTE* m_ILCodePtr)
{
InitILOpNames();
BYTE b = *m_ILCodePtr;
if (b == 0xfe)
{
return ILOpNames[*(m_ILCodePtr + 1)];
}
else
{
return ILOpNames[(0x1 << 8) + b];
}
}
const char* Interpreter::ILOp1Byte(unsigned short ilInstrVal)
{
InitILOpNames();
return ILOpNames[(0x1 << 8) + ilInstrVal];
}
const char* Interpreter::ILOp2Byte(unsigned short ilInstrVal)
{
InitILOpNames();
return ILOpNames[ilInstrVal];
}
void Interpreter::PrintOStack()
{
if (m_curStackHt == 0)
{
fprintf(GetLogFile(), " <empty>\n");
}
else
{
for (unsigned k = 0; k < m_curStackHt; k++)
{
CorInfoType cit = OpStackTypeGet(k).ToCorInfoType();
assert(IsStackNormalType(cit));
fprintf(GetLogFile(), " %4d: %10s: ", k, CorInfoTypeNames[cit]);
PrintOStackValue(k);
fprintf(GetLogFile(), "\n");
}
}
fflush(GetLogFile());
}
void Interpreter::PrintOStackValue(unsigned index)
{
_ASSERTE_MSG(index < m_curStackHt, "precondition");
InterpreterType it = OpStackTypeGet(index);
if (it.IsLargeStruct(&m_interpCeeInfo))
{
PrintValue(it, OpStackGet<BYTE*>(index));
}
else
{
PrintValue(it, reinterpret_cast<BYTE*>(OpStackGetAddr(index, it.Size(&m_interpCeeInfo))));
}
}
void Interpreter::PrintLocals()
{
if (m_methInfo->m_numLocals == 0)
{
fprintf(GetLogFile(), " <no locals>\n");
}
else
{
for (unsigned i = 0; i < m_methInfo->m_numLocals; i++)
{
InterpreterType it = m_methInfo->m_localDescs[i].m_type;
CorInfoType cit = it.ToCorInfoType();
void* localPtr = NULL;
if (it.IsLargeStruct(&m_interpCeeInfo))
{
void* structPtr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(i)), sizeof(void**));
localPtr = *reinterpret_cast<void**>(structPtr);
}
else
{
localPtr = ArgSlotEndianessFixup(reinterpret_cast<ARG_SLOT*>(FixedSizeLocalSlot(i)), it.Size(&m_interpCeeInfo));
}
fprintf(GetLogFile(), " loc%-4d: %10s: ", i, CorInfoTypeNames[cit]);
PrintValue(it, reinterpret_cast<BYTE*>(localPtr));
fprintf(GetLogFile(), "\n");
}
}
fflush(GetLogFile());
}
void Interpreter::PrintArgs()
{
for (unsigned k = 0; k < m_methInfo->m_numArgs; k++)
{
CorInfoType cit = GetArgType(k).ToCorInfoType();
fprintf(GetLogFile(), " %4d: %10s: ", k, CorInfoTypeNames[cit]);
PrintArgValue(k);
fprintf(GetLogFile(), "\n");
}
fprintf(GetLogFile(), "\n");
fflush(GetLogFile());
}
void Interpreter::PrintArgValue(unsigned argNum)
{
_ASSERTE_MSG(argNum < m_methInfo->m_numArgs, "precondition");
InterpreterType it = GetArgType(argNum);
PrintValue(it, GetArgAddr(argNum));
}
// Note that this is used to print non-stack-normal values, so
// it must handle all cases.
void Interpreter::PrintValue(InterpreterType it, BYTE* valAddr)
{
switch (it.ToCorInfoType())
{
case CORINFO_TYPE_BOOL:
fprintf(GetLogFile(), "%s", ((*reinterpret_cast<INT8*>(valAddr)) ? "true" : "false"));
break;
case CORINFO_TYPE_BYTE:
fprintf(GetLogFile(), "%d", *reinterpret_cast<INT8*>(valAddr));
break;
case CORINFO_TYPE_UBYTE:
fprintf(GetLogFile(), "%u", *reinterpret_cast<UINT8*>(valAddr));
break;
case CORINFO_TYPE_SHORT:
fprintf(GetLogFile(), "%d", *reinterpret_cast<INT16*>(valAddr));
break;
case CORINFO_TYPE_USHORT: case CORINFO_TYPE_CHAR:
fprintf(GetLogFile(), "%u", *reinterpret_cast<UINT16*>(valAddr));
break;
case CORINFO_TYPE_INT:
fprintf(GetLogFile(), "%d", *reinterpret_cast<INT32*>(valAddr));
break;
case CORINFO_TYPE_UINT:
fprintf(GetLogFile(), "%u", *reinterpret_cast<UINT32*>(valAddr));
break;
case CORINFO_TYPE_NATIVEINT:
{
INT64 val = static_cast<INT64>(*reinterpret_cast<NativeInt*>(valAddr));
fprintf(GetLogFile(), "%lld (= 0x%llx)", val, val);
}
break;
case CORINFO_TYPE_NATIVEUINT:
{
UINT64 val = static_cast<UINT64>(*reinterpret_cast<NativeUInt*>(valAddr));
fprintf(GetLogFile(), "%lld (= 0x%llx)", val, val);
}
break;
case CORINFO_TYPE_BYREF:
fprintf(GetLogFile(), "0x%p", *reinterpret_cast<void**>(valAddr));
break;
case CORINFO_TYPE_LONG:
{
INT64 val = *reinterpret_cast<INT64*>(valAddr);
fprintf(GetLogFile(), "%lld (= 0x%llx)", val, val);
}
break;
case CORINFO_TYPE_ULONG:
fprintf(GetLogFile(), "%lld", *reinterpret_cast<UINT64*>(valAddr));
break;
case CORINFO_TYPE_CLASS:
{
Object* obj = *reinterpret_cast<Object**>(valAddr);
if (obj == NULL)
{
fprintf(GetLogFile(), "null");
}
else
{
#ifdef _DEBUG
fprintf(GetLogFile(), "0x%p (%s) [", obj, obj->GetMethodTable()->GetDebugClassName());
#else
fprintf(GetLogFile(), "0x%p (MT=0x%p) [", obj, obj->GetMethodTable());
#endif
unsigned sz = obj->GetMethodTable()->GetBaseSize();
BYTE* objBytes = reinterpret_cast<BYTE*>(obj);
for (unsigned i = 0; i < sz; i++)
{
if (i > 0)
{
fprintf(GetLogFile(), " ");
}
fprintf(GetLogFile(), "0x%x", objBytes[i]);
}
fprintf(GetLogFile(), "]");
}
}
break;
case CORINFO_TYPE_VALUECLASS:
{
GCX_PREEMP();
fprintf(GetLogFile(), "<%s>: [", m_interpCeeInfo.getClassName(it.ToClassHandle()));
unsigned sz = getClassSize(it.ToClassHandle());
for (unsigned i = 0; i < sz; i++)
{
if (i > 0)
{
fprintf(GetLogFile(), " ");
}
fprintf(GetLogFile(), "0x%02x", valAddr[i]);
}
fprintf(GetLogFile(), "]");
}
break;
case CORINFO_TYPE_REFANY:
fprintf(GetLogFile(), "<refany>");
break;
case CORINFO_TYPE_FLOAT:
fprintf(GetLogFile(), "%f", *reinterpret_cast<float*>(valAddr));
break;
case CORINFO_TYPE_DOUBLE:
fprintf(GetLogFile(), "%g", *reinterpret_cast<double*>(valAddr));
break;
case CORINFO_TYPE_PTR:
fprintf(GetLogFile(), "0x%p", *reinterpret_cast<void**>(valAddr));
break;
default:
_ASSERTE_MSG(false, "Unknown type in PrintValue.");
break;
}
}
#endif // INTERP_TRACING
#ifdef _DEBUG
void Interpreter::AddInterpMethInfo(InterpreterMethodInfo* methInfo)
{
typedef InterpreterMethodInfo* InterpreterMethodInfoPtr;
// TODO: this requires synchronization.
const unsigned InitSize = 128;
if (s_interpMethInfos == NULL)
{
s_interpMethInfos = new InterpreterMethodInfoPtr[InitSize];
s_interpMethInfosAllocSize = InitSize;
}
if (s_interpMethInfosAllocSize == s_interpMethInfosCount)
{
unsigned newSize = s_interpMethInfosAllocSize * 2;
InterpreterMethodInfoPtr* tmp = new InterpreterMethodInfoPtr[newSize];
memcpy(tmp, s_interpMethInfos, s_interpMethInfosCount * sizeof(InterpreterMethodInfoPtr));
delete[] s_interpMethInfos;
s_interpMethInfos = tmp;
s_interpMethInfosAllocSize = newSize;
}
s_interpMethInfos[s_interpMethInfosCount] = methInfo;
s_interpMethInfosCount++;
}
int _cdecl Interpreter::CompareMethInfosByInvocations(const void* mi0in, const void* mi1in)
{
const InterpreterMethodInfo* mi0 = *((const InterpreterMethodInfo**)mi0in);
const InterpreterMethodInfo* mi1 = *((const InterpreterMethodInfo**)mi1in);
if (mi0->m_invocations < mi1->m_invocations)
{
return -1;
}
else if (mi0->m_invocations == mi1->m_invocations)
{
return 0;
}
else
{
assert(mi0->m_invocations > mi1->m_invocations);
return 1;
}
}
#if INTERP_PROFILE
int _cdecl Interpreter::CompareMethInfosByILInstrs(const void* mi0in, const void* mi1in)
{
const InterpreterMethodInfo* mi0 = *((const InterpreterMethodInfo**)mi0in);
const InterpreterMethodInfo* mi1 = *((const InterpreterMethodInfo**)mi1in);
if (mi0->m_totIlInstructionsExeced < mi1->m_totIlInstructionsExeced) return 1;
else if (mi0->m_totIlInstructionsExeced == mi1->m_totIlInstructionsExeced) return 0;
else
{
assert(mi0->m_totIlInstructionsExeced > mi1->m_totIlInstructionsExeced);
return -1;
}
}
#endif // INTERP_PROFILE
#endif // _DEBUG
const int MIL = 1000000;
// Leaving this disabled for now.
#if 0
unsigned __int64 ForceSigWalkCycles = 0;
#endif
void Interpreter::PrintPostMortemData()
{
if (s_PrintPostMortemFlag.val(CLRConfig::INTERNAL_InterpreterPrintPostMortem) == 0)
return;
// Otherwise...
#ifdef _DEBUG
// Let's print two things: the number of methods that are 0-10, or more, and
// For each 10% of methods, cumulative % of invocations they represent. By 1% for last 10%.
// First one doesn't require any sorting.
const unsigned HistoMax = 11;
unsigned histo[HistoMax];
unsigned numExecs[HistoMax];
for (unsigned k = 0; k < HistoMax; k++)
{
histo[k] = 0; numExecs[k] = 0;
}
for (unsigned k = 0; k < s_interpMethInfosCount; k++)
{
unsigned invokes = s_interpMethInfos[k]->m_invocations;
if (invokes > HistoMax - 1)
{
invokes = HistoMax - 1;
}
histo[invokes]++;
numExecs[invokes] += s_interpMethInfos[k]->m_invocations;
}
fprintf(GetLogFile(), "Histogram of method executions:\n");
fprintf(GetLogFile(), " # of execs | # meths (%%) | cum %% | %% cum execs\n");
fprintf(GetLogFile(), " -------------------------------------------------------\n");
float fTotMeths = float(s_interpMethInfosCount);
float fTotExecs = float(s_totalInvocations);
float numPct = 0.0f;
float numExecPct = 0.0f;
for (unsigned k = 0; k < HistoMax; k++)
{
fprintf(GetLogFile(), " %10d", k);
if (k == HistoMax)
{
fprintf(GetLogFile(), "+ ");
}
else
{
fprintf(GetLogFile(), " ");
}
float pct = float(histo[k])*100.0f/fTotMeths;
numPct += pct;
float execPct = float(numExecs[k])*100.0f/fTotExecs;
numExecPct += execPct;
fprintf(GetLogFile(), "| %7d (%5.2f%%) | %6.2f%% | %6.2f%%\n", histo[k], pct, numPct, numExecPct);
}
// This sorts them in ascending order of number of invocations.
qsort(&s_interpMethInfos[0], s_interpMethInfosCount, sizeof(InterpreterMethodInfo*), &CompareMethInfosByInvocations);
fprintf(GetLogFile(), "\nFor methods sorted in ascending # of executions order, cumulative %% of executions:\n");
if (s_totalInvocations > 0)
{
fprintf(GetLogFile(), " %% of methods | max execs | cum %% of execs\n");
fprintf(GetLogFile(), " ------------------------------------------\n");
unsigned methNum = 0;
unsigned nNumExecs = 0;
float totExecsF = float(s_totalInvocations);
for (unsigned k = 10; k < 100; k += 10)
{
unsigned targ = unsigned((float(k)/100.0f)*float(s_interpMethInfosCount));
unsigned targLess1 = (targ > 0 ? targ - 1 : 0);
while (methNum < targ)
{
nNumExecs += s_interpMethInfos[methNum]->m_invocations;
methNum++;
}
float pctExecs = float(nNumExecs) * 100.0f / totExecsF;
fprintf(GetLogFile(), " %8d%% | %9d | %8.2f%%\n", k, s_interpMethInfos[targLess1]->m_invocations, pctExecs);
if (k == 90)
{
k++;
for (; k < 100; k++)
{
unsigned targ = unsigned((float(k)/100.0f)*float(s_interpMethInfosCount));
while (methNum < targ)
{
nNumExecs += s_interpMethInfos[methNum]->m_invocations;
methNum++;
}
pctExecs = float(nNumExecs) * 100.0f / totExecsF;
fprintf(GetLogFile(), " %8d%% | %9d | %8.2f%%\n", k, s_interpMethInfos[targLess1]->m_invocations, pctExecs);
}
// Now do 100%.
targ = s_interpMethInfosCount;
while (methNum < targ)
{
nNumExecs += s_interpMethInfos[methNum]->m_invocations;
methNum++;
}
pctExecs = float(nNumExecs) * 100.0f / totExecsF;
fprintf(GetLogFile(), " %8d%% | %9d | %8.2f%%\n", k, s_interpMethInfos[targLess1]->m_invocations, pctExecs);
}
}
}
fprintf(GetLogFile(), "\nTotal number of calls from interpreted code: %d.\n", s_totalInterpCalls);
fprintf(GetLogFile(), " Also, %d are intrinsics; %d of these are not currently handled intrinsically.\n",
s_totalInterpCallsToIntrinsics, s_totalInterpCallsToIntrinsicsUnhandled);
fprintf(GetLogFile(), " Of these, %d to potential property getters (%d of these dead simple), %d to setters.\n",
s_totalInterpCallsToGetters, s_totalInterpCallsToDeadSimpleGetters, s_totalInterpCallsToSetters);
fprintf(GetLogFile(), " Of the dead simple getter calls, %d have been short-circuited.\n",
s_totalInterpCallsToDeadSimpleGettersShortCircuited);
fprintf(GetLogFile(), "\nToken resolutions by category:\n");
fprintf(GetLogFile(), "Category | opportunities | calls | %%\n");
fprintf(GetLogFile(), "---------------------------------------------------\n");
for (unsigned i = RTK_Undefined; i < RTK_Count; i++)
{
float pct = 0.0;
if (s_tokenResolutionOpportunities[i] > 0)
pct = 100.0f * float(s_tokenResolutionCalls[i]) / float(s_tokenResolutionOpportunities[i]);
fprintf(GetLogFile(), "%12s | %15d | %9d | %6.2f%%\n",
s_tokenResolutionKindNames[i], s_tokenResolutionOpportunities[i], s_tokenResolutionCalls[i], pct);
}
#if INTERP_PROFILE
fprintf(GetLogFile(), "Information on num of execs:\n");
UINT64 totILInstrs = 0;
for (unsigned i = 0; i < s_interpMethInfosCount; i++) totILInstrs += s_interpMethInfos[i]->m_totIlInstructionsExeced;
float totILInstrsF = float(totILInstrs);
fprintf(GetLogFile(), "\nTotal instructions = %lld.\n", totILInstrs);
fprintf(GetLogFile(), "\nTop <=10 methods by # of IL instructions executed.\n");
fprintf(GetLogFile(), "%10s | %9s | %10s | %10s | %8s | %s\n", "tot execs", "# invokes", "code size", "ratio", "% of tot", "Method");
fprintf(GetLogFile(), "----------------------------------------------------------------------------\n");
qsort(&s_interpMethInfos[0], s_interpMethInfosCount, sizeof(InterpreterMethodInfo*), &CompareMethInfosByILInstrs);
for (unsigned i = 0; i < min(10, s_interpMethInfosCount); i++)
{
unsigned ilCodeSize = unsigned(s_interpMethInfos[i]->m_ILCodeEnd - s_interpMethInfos[i]->m_ILCode);
fprintf(GetLogFile(), "%10lld | %9d | %10d | %10.2f | %8.2f%% | %s:%s\n",
s_interpMethInfos[i]->m_totIlInstructionsExeced,
s_interpMethInfos[i]->m_invocations,
ilCodeSize,
float(s_interpMethInfos[i]->m_totIlInstructionsExeced) / float(ilCodeSize),
float(s_interpMethInfos[i]->m_totIlInstructionsExeced) * 100.0f / totILInstrsF,
s_interpMethInfos[i]->m_clsName,
s_interpMethInfos[i]->m_methName);
}
#endif // INTERP_PROFILE
#endif // _DEBUG
#if INTERP_ILINSTR_PROFILE
fprintf(GetLogFile(), "\nIL instruction profiling:\n");
// First, classify by categories.
unsigned totInstrs = 0;
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 totCycles = 0;
unsigned __int64 perMeasurementOverhead = CycleTimer::QueryOverhead();
#endif // INTERP_ILCYCLE_PROFILE
for (unsigned i = 0; i < 256; i++)
{
s_ILInstrExecsByCategory[s_ILInstrCategories[i]] += s_ILInstrExecs[i];
totInstrs += s_ILInstrExecs[i];
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 cycles = s_ILInstrCycles[i];
if (cycles > s_ILInstrExecs[i] * perMeasurementOverhead) cycles -= s_ILInstrExecs[i] * perMeasurementOverhead;
else cycles = 0;
s_ILInstrCycles[i] = cycles;
s_ILInstrCyclesByCategory[s_ILInstrCategories[i]] += cycles;
totCycles += cycles;
#endif // INTERP_ILCYCLE_PROFILE
}
unsigned totInstrs2Byte = 0;
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 totCycles2Byte = 0;
#endif // INTERP_ILCYCLE_PROFILE
for (unsigned i = 0; i < CountIlInstr2Byte; i++)
{
unsigned ind = 0x100 + i;
s_ILInstrExecsByCategory[s_ILInstrCategories[ind]] += s_ILInstr2ByteExecs[i];
totInstrs += s_ILInstr2ByteExecs[i];
totInstrs2Byte += s_ILInstr2ByteExecs[i];
#if INTERP_ILCYCLE_PROFILE
unsigned __int64 cycles = s_ILInstrCycles[ind];
if (cycles > s_ILInstrExecs[ind] * perMeasurementOverhead) cycles -= s_ILInstrExecs[ind] * perMeasurementOverhead;
else cycles = 0;
s_ILInstrCycles[i] = cycles;
s_ILInstrCyclesByCategory[s_ILInstrCategories[ind]] += cycles;
totCycles += cycles;
totCycles2Byte += cycles;
#endif // INTERP_ILCYCLE_PROFILE
}
// Now sort the categories by # of occurrences.
InstrExecRecord ieps[256 + CountIlInstr2Byte];
for (unsigned short i = 0; i < 256; i++)
{
ieps[i].m_instr = i; ieps[i].m_is2byte = false; ieps[i].m_execs = s_ILInstrExecs[i];
#if INTERP_ILCYCLE_PROFILE
if (i == CEE_BREAK)
{
ieps[i].m_cycles = 0;
continue; // Don't count these if they occur...
}
ieps[i].m_cycles = s_ILInstrCycles[i];
assert((ieps[i].m_execs != 0) || (ieps[i].m_cycles == 0)); // Cycles can be zero for non-zero execs because of measurement correction.
#endif // INTERP_ILCYCLE_PROFILE
}
for (unsigned short i = 0; i < CountIlInstr2Byte; i++)
{
int ind = 256 + i;
ieps[ind].m_instr = i; ieps[ind].m_is2byte = true; ieps[ind].m_execs = s_ILInstr2ByteExecs[i];
#if INTERP_ILCYCLE_PROFILE
ieps[ind].m_cycles = s_ILInstrCycles[ind];
assert((ieps[i].m_execs != 0) || (ieps[i].m_cycles == 0)); // Cycles can be zero for non-zero execs because of measurement correction.
#endif // INTERP_ILCYCLE_PROFILE
}
qsort(&ieps[0], 256 + CountIlInstr2Byte, sizeof(InstrExecRecord), &InstrExecRecord::Compare);
fprintf(GetLogFile(), "\nInstructions (%d total, %d 1-byte):\n", totInstrs, totInstrs - totInstrs2Byte);
#if INTERP_ILCYCLE_PROFILE
if (s_callCycles > s_calls * perMeasurementOverhead) s_callCycles -= s_calls * perMeasurementOverhead;
else s_callCycles = 0;
fprintf(GetLogFile(), " MCycles (%lld total, %lld 1-byte, %lld calls (%d calls, %10.2f cyc/call):\n",
totCycles/MIL, (totCycles - totCycles2Byte)/MIL, s_callCycles/MIL, s_calls, float(s_callCycles)/float(s_calls));
#if 0
extern unsigned __int64 MetaSigCtor1Cycles;
fprintf(GetLogFile(), " MetaSig(MethodDesc, TypeHandle) ctor: %lld MCycles.\n",
MetaSigCtor1Cycles/MIL);
fprintf(GetLogFile(), " ForceSigWalk: %lld MCycles.\n",
ForceSigWalkCycles/MIL);
#endif
#endif // INTERP_ILCYCLE_PROFILE
PrintILProfile(&ieps[0], totInstrs
#if INTERP_ILCYCLE_PROFILE
, totCycles
#endif // INTERP_ILCYCLE_PROFILE
);
fprintf(GetLogFile(), "\nInstructions grouped by category: (%d total, %d 1-byte):\n", totInstrs, totInstrs - totInstrs2Byte);
#if INTERP_ILCYCLE_PROFILE
fprintf(GetLogFile(), " MCycles (%lld total, %lld 1-byte):\n",
totCycles/MIL, (totCycles - totCycles2Byte)/MIL);
#endif // INTERP_ILCYCLE_PROFILE
for (unsigned short i = 0; i < 256 + CountIlInstr2Byte; i++)
{
if (i < 256)
{
ieps[i].m_instr = i; ieps[i].m_is2byte = false;
}
else
{
ieps[i].m_instr = i - 256; ieps[i].m_is2byte = true;
}
ieps[i].m_execs = s_ILInstrExecsByCategory[i];
#if INTERP_ILCYCLE_PROFILE
ieps[i].m_cycles = s_ILInstrCyclesByCategory[i];
#endif // INTERP_ILCYCLE_PROFILE
}
qsort(&ieps[0], 256 + CountIlInstr2Byte, sizeof(InstrExecRecord), &InstrExecRecord::Compare);
PrintILProfile(&ieps[0], totInstrs
#if INTERP_ILCYCLE_PROFILE
, totCycles
#endif // INTERP_ILCYCLE_PROFILE
);
#if 0
// Early debugging code.
fprintf(GetLogFile(), "\nInstructions grouped category mapping:\n", totInstrs, totInstrs - totInstrs2Byte);
for (unsigned short i = 0; i < 256; i++)
{
unsigned short cat = s_ILInstrCategories[i];
if (cat < 256) {
fprintf(GetLogFile(), "Instr: %12s ==> %12s.\n", ILOp1Byte(i), ILOp1Byte(cat));
} else {
fprintf(GetLogFile(), "Instr: %12s ==> %12s.\n", ILOp1Byte(i), ILOp2Byte(cat - 256));
}
}
for (unsigned short i = 0; i < CountIlInstr2Byte; i++)
{
unsigned ind = 256 + i;
unsigned short cat = s_ILInstrCategories[ind];
if (cat < 256) {
fprintf(GetLogFile(), "Instr: %12s ==> %12s.\n", ILOp2Byte(i), ILOp1Byte(cat));
} else {
fprintf(GetLogFile(), "Instr: %12s ==> %12s.\n", ILOp2Byte(i), ILOp2Byte(cat - 256));
}
}
#endif
#endif // INTERP_ILINSTR_PROFILE
}
#if INTERP_ILINSTR_PROFILE
const int K = 1000;
// static
void Interpreter::PrintILProfile(Interpreter::InstrExecRecord *recs, unsigned int totInstrs
#if INTERP_ILCYCLE_PROFILE
, unsigned __int64 totCycles
#endif // INTERP_ILCYCLE_PROFILE
)
{
float fTotInstrs = float(totInstrs);
fprintf(GetLogFile(), "Instruction | execs | %% | cum %%");
#if INTERP_ILCYCLE_PROFILE
float fTotCycles = float(totCycles);
fprintf(GetLogFile(), "| KCycles | %% | cum %% | cyc/inst\n");
fprintf(GetLogFile(), "--------------------------------------------------"
"-----------------------------------------\n");
#else
fprintf(GetLogFile(), "\n-------------------------------------------\n");
#endif
float numPct = 0.0f;
#if INTERP_ILCYCLE_PROFILE
float numCyclePct = 0.0f;
#endif // INTERP_ILCYCLE_PROFILE
for (unsigned i = 0; i < 256 + CountIlInstr2Byte; i++)
{
float pct = 0.0f;
if (totInstrs > 0) pct = float(recs[i].m_execs) * 100.0f / fTotInstrs;
numPct += pct;
if (recs[i].m_execs > 0)
{
fprintf(GetLogFile(), "%12s | %9d | %6.2f%% | %6.2f%%",
(recs[i].m_is2byte ? ILOp2Byte(recs[i].m_instr) : ILOp1Byte(recs[i].m_instr)), recs[i].m_execs,
pct, numPct);
#if INTERP_ILCYCLE_PROFILE
pct = 0.0f;
if (totCycles > 0) pct = float(recs[i].m_cycles) * 100.0f / fTotCycles;
numCyclePct += pct;
float cyclesPerInst = float(recs[i].m_cycles) / float(recs[i].m_execs);
fprintf(GetLogFile(), "| %12llu | %6.2f%% | %6.2f%% | %11.2f",
recs[i].m_cycles/K, pct, numCyclePct, cyclesPerInst);
#endif // INTERP_ILCYCLE_PROFILE
fprintf(GetLogFile(), "\n");
}
}
}
#endif // INTERP_ILINSTR_PROFILE
#endif // FEATURE_INTERPRETER
| mit |
luberda-molinet/FFImageLoading | samples/ImageLoading.MvvmCross.Sample/FFImageLoading.MvvmCross.Sample.Core/ViewModels/Image.cs | 476 | using System;
using System.Collections.Generic;
using FFImageLoading.Transformations;
using FFImageLoading.Work;
namespace FFImageLoading.MvvmCross.Sample.Core
{
public class Image
{
public string Url { get; }
public double DownsampleWidth => 200d;
public List<ITransformation> Transformations => new List<ITransformation> { new CircleTransformation() };
public Image(string url)
{
Url = url;
}
}
}
| mit |
Azure/azure-sdk-for-python | sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_generated/_configuration.py | 2179 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from ._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any
class KeyVaultClientConfiguration(Configuration):
"""Configuration for KeyVaultClient.
Note that all parameters used to create this instance are saved as instance
attributes.
"""
def __init__(
self,
**kwargs # type: Any
):
# type: (...) -> None
super(KeyVaultClientConfiguration, self).__init__(**kwargs)
kwargs.setdefault('sdk_moniker', 'azure-keyvault/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
| mit |
MSOpenTech/Vipr | src/Core/Vipr.Core/CodeModel/OdcmClass.cs | 1000 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
namespace Vipr.Core.CodeModel
{
public abstract class OdcmClass : OdcmType
{
public bool IsAbstract { get; set; }
public bool IsOpen { get; set; }
public OdcmClass Base { get; set; }
public IList<OdcmClass> Derived { get; private set; }
public OdcmClassKind Kind { get; set; }
public List<OdcmProperty> Properties { get; private set; }
public List<OdcmMethod> Methods { get; private set; }
public OdcmClass(string name, OdcmNamespace @namespace, OdcmClassKind kind)
: base(name, @namespace)
{
Kind = kind;
Properties = new List<OdcmProperty>();
Methods = new List<OdcmMethod>();
Derived = new List<OdcmClass>();
}
}
}
| mit |
appium/node-jscs | test/rules/require-space-after-prefix-unary-operators.js | 2695 | var Checker = require('../../lib/checker');
var assert = require('assert');
var operators = require('../../lib/utils').unaryOperators;
describe('rules/require-space-after-prefix-unary-operators', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
});
operators.forEach(function(operator) {
var sticked = 'var test;' + operator + 'test';
var stickedWithParenthesis = 'var test;' + operator + '(test)';
var notSticked = 'var test;' + operator + ' test';
var notStickedWithParenthesis = 'var test;' + operator + ' (test)';
[[operator], true].forEach(function(value) {
it('should report sticky operator for ' + sticked + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(sticked).getErrorCount() === 1);
}
);
it('should not report sticky operator for ' + notSticked + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(notSticked).isEmpty());
}
);
it('should report sticky operator for ' + stickedWithParenthesis + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(stickedWithParenthesis).getErrorCount() === 1);
}
);
it('should not report sticky operator for ' + notStickedWithParenthesis + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(notStickedWithParenthesis).isEmpty());
}
);
});
});
it('should report sticky operator if operand in parentheses', function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: ['-', '~', '!', '++'] });
assert(checker.checkString('var x = ~(0); ++(((x))); -( x ); !(++( x ));').getErrorCount() === 5);
});
it('should not report consecutive operators (#405)', function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: ['!'] });
assert(checker.checkString('!~test;').isEmpty());
assert(checker.checkString('!~test;').isEmpty());
assert(checker.checkString('!++test;').isEmpty());
});
});
| mit |
pvskand/addictionRemoval | tinymce/src/ui/src/test/js/browser/content/LinkTargetsTest.js | 4977 | asynctest(
'browser.tinymce.ui.content.LinkTargetsTest',
[
'ephox.mcagar.api.LegacyUnit',
'ephox.agar.api.Pipeline',
'tinymce.ui.content.LinkTargets',
'tinymce.core.util.Arr',
'global!document'
],
function (LegacyUnit, Pipeline, LinkTargets, Arr, document) {
var success = arguments[arguments.length - 2];
var failure = arguments[arguments.length - 1];
var suite = LegacyUnit.createSuite();
var createFromHtml = function (html) {
var elm = document.createElement('div');
elm.contentEditable = true;
elm.innerHTML = html;
return elm;
};
var targetsIn = function (html) {
return LinkTargets.find(createFromHtml(html));
};
var equalTargets = function (actualTargets, expectedTargets, message) {
var nonAttachedTargets = Arr.map(actualTargets, function (target) {
return {
level: target.level,
title: target.title,
type: target.type,
url: target.url
};
});
LegacyUnit.deepEqual(nonAttachedTargets, expectedTargets, message);
};
suite.test('Non link targets', function () {
LegacyUnit.equal(targetsIn('a').length, 0, 'Text has no targets');
LegacyUnit.equal(targetsIn('<p>a</p>').length, 0, 'Paragraph has no targets');
LegacyUnit.equal(targetsIn('<a href="#1">a</a>').length, 0, 'Link has no targets');
});
suite.test('Anchor targets', function () {
equalTargets(targetsIn('<a id="a"></a>'), [{ level: 0, title: '#a', type: 'anchor', url: '#a' }], 'Anchor with id');
equalTargets(targetsIn('<a name="a"></a>'), [{ level: 0, title: '#a', type: 'anchor', url: '#a' }], 'Anchor with name');
equalTargets(targetsIn('<a name="a" contentEditable="false"></a>'), [], 'cE=false anchor');
equalTargets(targetsIn('<div contentEditable="false"><a name="a"></a></div>'), [], 'Anchor in cE=false');
equalTargets(targetsIn('<a name=""></a>'), [], 'Empty anchor name should not produce a target');
equalTargets(targetsIn('<a id=""></a>'), [], 'Empty anchor id should not produce a target');
});
suite.test('Header targets', function () {
equalTargets(targetsIn('<h1 id="a">a</h1>'), [{ level: 1, title: 'a', type: 'header', url: '#a' }], 'Header 1 with id');
equalTargets(targetsIn('<h2 id="a">a</h2>'), [{ level: 2, title: 'a', type: 'header', url: '#a' }], 'Header 2 with id');
equalTargets(targetsIn('<h3 id="a">a</h3>'), [{ level: 3, title: 'a', type: 'header', url: '#a' }], 'Header 3 with id');
equalTargets(targetsIn('<h4 id="a">a</h4>'), [{ level: 4, title: 'a', type: 'header', url: '#a' }], 'Header 4 with id');
equalTargets(targetsIn('<h5 id="a">a</h5>'), [{ level: 5, title: 'a', type: 'header', url: '#a' }], 'Header 5 with id');
equalTargets(targetsIn('<h6 id="a">a</h6>'), [{ level: 6, title: 'a', type: 'header', url: '#a' }], 'Header 6 with id');
equalTargets(targetsIn('<h1 id="a"></h1>'), [], 'Empty header should not produce a target');
equalTargets(targetsIn('<div contentEditable="false"><h1 id="a">a</h1></div>'), [], 'Header in cE=false');
equalTargets(targetsIn('<h1 id="a" contentEditable="false">a</h1>'), [], 'cE=false header');
});
suite.test('Mixed targets', function () {
equalTargets(
targetsIn('<h1 id="a">a</h1><a id="b"></a>'),
[
{ level: 1, title: 'a', type: 'header', url: '#a' },
{ level: 0, title: '#b', type: 'anchor', url: '#b' }
],
'Header 1 with id and anchor with id'
);
});
suite.test('Anchor attach', function () {
var elm = createFromHtml('<a id="a"></a>');
var targets = LinkTargets.find(elm);
targets[0].attach();
LegacyUnit.equal(elm.innerHTML, '<a id="a"></a>', 'Should remain the same as before attach');
});
suite.test('Header attach on header with id', function () {
var elm = createFromHtml('<h1 id="a">a</h1>');
var targets = LinkTargets.find(elm);
targets[0].attach();
LegacyUnit.equal(elm.innerHTML, '<h1 id="a">a</h1>', 'Should remain the same as before attach');
});
suite.test('Header attach on headers without ids', function () {
var elm = createFromHtml('<h1>a</h1><h2>b</h2>');
var targets = LinkTargets.find(elm);
targets[0].attach();
targets[1].attach();
var idA = elm.firstChild.id;
var idB = elm.lastChild.id;
var afterAttachHtml = elm.innerHTML;
LegacyUnit.equal(afterAttachHtml, '<h1 id="' + idA + '">a</h1><h2 id="' + idB + '">b</h2>', 'Should have unique id:s');
LegacyUnit.equal(idA === idB, false, 'Should not be equal id:s');
targets[0].attach();
targets[1].attach();
LegacyUnit.equal(elm.innerHTML, afterAttachHtml, 'Should be the same id:s regardless of how many times you attach');
});
Pipeline.async({}, suite.toSteps({}), function () {
success();
}, failure);
}
);
| mit |
hyonholee/azure-rest-api-specs | specification/datalake-analytics/resource-manager/readme.md | 5739 | # DataLakeAnalytics
> see https://aka.ms/autorest
This is the AutoRest configuration file for DataLakeAnalytics.
---
## Getting Started
To build the SDK for DataLakeAnalytics, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:
> `autorest`
To see additional help and options, run:
> `autorest --help`
---
## Configuration
### Basic Information
These are the global settings for the DataLakeAnalytics API.
``` yaml
openapi-type: arm
tag: package-2016-11
```
### Tag: package-2016-11
These settings apply only when `--tag=package-2016-11` is specified on the command line.
``` yaml $(tag) == 'package-2016-11'
input-file:
- Microsoft.DataLakeAnalytics/stable/2016-11-01/account.json
```
### Tag: package-2015-10-preview
These settings apply only when `--tag=package-2015-10-preview` is specified on the command line.
``` yaml $(tag) == 'package-2015-10-preview'
input-file:
- Microsoft.DataLakeAnalytics/preview/2015-10-01-preview/account.json
```
## Suppression
``` yaml
directive:
- suppress: TrackedResourceGetOperation
reason: This is by design in that we return DataLakeAnalyticsAccountBasic only for Account_List
#where:
# - $.definitions.DataLakeAnalyticsAccountBasic
- suppress: TrackedResourcePatchOperation
reason: DataLakeAnalyticsAccountBasic is not independent and its purpose is for Account_List only. PATCH is for DataLakeAnalyticsAccount, which will effectively update DataLakeAnalyticsAccountBasic
#where:
# - $.definitions.DataLakeAnalyticsAccountBasic
```
---
# Code Generation
## Swagger to SDK
This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.
``` yaml $(swagger-to-sdk)
swagger-to-sdk:
- repo: azure-sdk-for-net
- repo: azure-sdk-for-python
- repo: azure-sdk-for-java
- repo: azure-sdk-for-go
- repo: azure-sdk-for-node
- repo: azure-sdk-for-ruby
after_scripts:
- bundle install && rake arm:regen_all_profiles['azure_mgmt_datalake_analytics']
```
## C#
These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.
``` yaml $(csharp)
csharp:
azure-arm: true
license-header: MICROSOFT_MIT_NO_VERSION
namespace: Microsoft.Azure.Management.DataLake.Analytics
output-folder: $(csharp-sdks-folder)/datalake-analytics/Microsoft.Azure.Management.DataLake.Analytics/src/Generated
clear-output-folder: true
```
## Python
These settings apply only when `--python` is specified on the command line.
Please also specify `--python-sdks-folder=<path to the root directory of your azure-sdk-for-python clone>`.
```yaml $(python)
python:
azure-arm: true
license-header: MICROSOFT_MIT_NO_VERSION
payload-flattening-threshold: 2
package-name: azure-mgmt-datalake-analytics
clear-output-folder: true
no-namespace-folders: true
namespace: azure.mgmt.datalake.analytics.account
output-folder: $(python-sdks-folder)/datalake/azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/account
```
## Go
See configuration in [readme.go.md](./readme.go.md)
## Java
These settings apply only when `--java` is specified on the command line.
Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`.
``` yaml $(java)
azure-arm: true
fluent: true
namespace: com.microsoft.azure.management.datalake.analytics
license-header: MICROSOFT_MIT_NO_CODEGEN
output-folder: $(azure-libraries-for-java-folder)/azure-mgmt-datalake/analytics
```
### Java multi-api
``` yaml $(java) && $(multiapi)
batch:
- tag: package-2015-10-preview
- tag: package-2016-11
```
### Tag: package-2015-10-preview and java
These settings apply only when `--tag=package-2015-10-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.
``` yaml $(tag) == 'package-2015-10-preview' && $(java) && $(multiapi)
java:
namespace: com.microsoft.azure.management.datalakeanalytics.v2015_10_01_preview
output-folder: $(azure-libraries-for-java-folder)/sdk/datalakeanalytics/mgmt-v2015_10_01_preview
regenerate-manager: true
generate-interface: true
```
### Tag: package-2016-11 and java
These settings apply only when `--tag=package-2016-11 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.
``` yaml $(tag) == 'package-2016-11' && $(java) && $(multiapi)
java:
namespace: com.microsoft.azure.management.datalakeanalytics.v2016_11_01
output-folder: $(azure-libraries-for-java-folder)/sdk/datalakeanalytics/mgmt-v2016_11_01
regenerate-manager: true
generate-interface: true
```
## Multi-API/Profile support for AutoRest v3 generators
AutoRest V3 generators require the use of `--tag=all-api-versions` to select api files.
This block is updated by an automatic script. Edits may be lost!
``` yaml $(tag) == 'all-api-versions' /* autogenerated */
# include the azure profile definitions from the standard location
require: $(this-folder)/../../../profiles/readme.md
# all the input files across all versions
input-file:
- $(this-folder)/Microsoft.DataLakeAnalytics/stable/2016-11-01/account.json
- $(this-folder)/Microsoft.DataLakeAnalytics/preview/2015-10-01-preview/account.json
```
If there are files that should not be in the `all-api-versions` set,
uncomment the `exclude-file` section below and add the file paths.
``` yaml $(tag) == 'all-api-versions'
#exclude-file:
# - $(this-folder)/Microsoft.Example/stable/2010-01-01/somefile.json
```
| mit |
nmizoguchi/pfg-r-osgi | ch.ethz.iks.r_osgi.remote/src/main/java/ch/ethz/iks/util/ScheduleListener.java | 2191 | /* Copyright (c) 2006-2009 Jan S. Rellermeyer
* Systems Group,
* Department of Computer Science, ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of ETH Zurich nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.ethz.iks.util;
/**
* Interface for listeners of the Scheduler utility.
*
* @author Jan S. Rellermeyer, ETH Zurich
*/
public interface ScheduleListener {
/**
* called, when a scheduled object is due.
*
* @param scheduler
* the scheduler that has scheduled the object.
* @param timestamp
* the timestamp for which the object was scheduled.
* @param object
* the scheduled object.
*/
void due(final Scheduler scheduler, final long timestamp,
final Object object);
}
| mit |
RJFreund/OpenDSA | Exercises/Development/edit-KA.html | 2667 | <!DOCTYPE html>
<!--
Edit Distance, Khan Academy Page
Erich Brungraber
-->
<html data-require="math">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit Distance - Khan Academy</title>
<script src="../../ODSAkhan-exercises/khan-exercise.js"></script>
<script src="../../JSAV/build/JSAV-min.js"></script>
<link rel="stylesheet" href="../../JSAV/css/JSAV.css" type="text/css" />
<script src="../../AV/edit.js"></script>
<style>
.jsavcontainer {
border: 0px;
height: 300px}
.jsavarray { margin: 0; height: 40px; min-height: 40px; }
.jsavarray li { border-radius: 0 !important; height: 40px; width: 40px; font-size: 14px; line-height: 40px;}
</style>
<body>
<script>
var av, arr, myGuess;
var c1, c2, c3, c4;
//debugging function
var select = function(choice) {
alert("Hey y'all, this is your choice: " + arr[choice]);
myGuess = arr[choice];
}
/**
initJSAV
Initializes the JSAV.
*/
initJSAV = function() {
myGuess = -1;
av = new JSAV("jsav", {"animationMode": "none"});
var s1 = randString(3,5);
var s2 = randString(3,5);
arr = initKA(s1, s2);
for (var i = 0; i < arr.length; i++) {
console.log("" + i + ": " + arr[i]);
}
//set the labels
document.getElementById('a').innerHTML = arr[0];
document.getElementById('b').innerHTML = arr[1];
document.getElementById('c').innerHTML = arr[2];
document.getElementById('d').innerHTML = arr[3];
}
getAns = function(num) {
return arr[num];
} //end initJSAV func
/**
randString
Creates random string for use in proficiency testing.
@params:
base = minimum char count
max = max char count
*/
var randString = function(base, max) {
var count = Math.floor((max - base + 1) * Math.random() + base);
var str = "";
for (var i = 0; i < count; i++) {
str += String.fromCharCode(26 * Math.random() + 97);
}
return str;
} //end randString func
genAnswer = function() {
return arr[4];
}
</script>
<div class="exercise">
<div class="vars">
<var id="JSAV">initJSAV()</var>
<var id="CorrectAnswer">genAnswer()</var>
</div> <!-- vars -->
<div class="problems">
<div>
<div class="question">
Select the correct cell value from the list.
<div id="jsav"></div>
</div> <!-- question -->
<div class="solution"><var>genAnswer()</var></div>
<ul class="choices" data-category="true">
<li><var id="a"></var></li>
<li><var id="b"></var></li>
<li><var id="c"></var></li>
<li><var id="d"></var></li>
</ul>
</div>
</div> <!-- problems -->
<div class="hints">
<p><var>CorrectAnswer</var></p>
</div>
</div> <!--exercises-->
</body>
</html>
| mit |
kaicataldo/babel | packages/babel-generator/test/fixtures/types/LogicalExpression/output.js | 215 | foo || bar;
(x => x) || bar;
(function a(x) {
return x;
}) || 2;
0 || function () {
return alpha;
};
a && b && c;
a && b && c;
a || b || c;
a || b || c;
a || b && c;
a && (b || c);
(a || b) && c;
a && b || c; | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.