text
stringlengths 5
1.04M
|
|---|
#include <iostream>
using namespace std;
class Apple {
private:
static int nTotalNumber;
public:
static void PrintTotal() {
cout << nTotalNumber << endl;
}
Apple() {
++nTotalNumber;
}
~Apple() {
--nTotalNumber;
}
};
int Apple::nTotalNumber = 0;
Apple Fun(const Apple & a) {
a.PrintTotal();
return a;
}
int main()
{
Apple * p = new Apple[4];
Fun(p[2]);
Apple p1,p2;
Apple::PrintTotal ();
delete [] p;
p1.PrintTotal ();
return 0;
}
|
/* Copyright (c) 2020-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
/** \file Format string processing for printf based on hostcall messages.
*/
#include <assert.h>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <string>
static void checkPrintf(FILE* stream, int* outCount, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
int retval = vfprintf(stream, fmt, args);
*outCount = retval < 0 ? retval : *outCount + retval;
}
static int countStars(const std::string& spec) {
int stars = 0;
for (auto c : spec) {
if (c == '*') {
++stars;
}
}
return stars;
}
template <typename... Args>
static const uint64_t* consumeInteger(FILE* stream, int* outCount, const std::string& spec,
const uint64_t* ptr, Args... args) {
checkPrintf(stream, outCount, spec.c_str(), args..., ptr[0]);
return ptr + 1;
}
template <typename... Args>
static const uint64_t* consumeFloatingPoint(FILE* stream, int* outCount, const std::string& spec,
const uint64_t* ptr, Args... args) {
double d;
memcpy(&d, ptr, 8);
checkPrintf(stream, outCount, spec.c_str(), args..., d);
return ptr + 1;
}
template <typename... Args>
static const uint64_t* consumeCstring(FILE* stream, int* outCount, const std::string& spec,
const uint64_t* ptr, Args... args) {
auto str = reinterpret_cast<const char*>(ptr);
checkPrintf(stream, outCount, spec.c_str(), args..., str);
return ptr + (strlen(str) + 7) / 8;
}
template <typename... Args>
static const uint64_t* consumePointer(FILE* stream, int* outCount, const std::string& spec,
const uint64_t* ptr, Args... args) {
auto vptr = reinterpret_cast<void*>(*ptr);
checkPrintf(stream, outCount, spec.c_str(), args..., vptr);
return ptr + 1;
}
template <typename... Args>
static const uint64_t* consumeArgument(FILE* stream, int* outCount, const std::string& spec,
const uint64_t* ptr, const uint64_t* end, Args... args) {
switch (spec.back()) {
case 'd':
case 'i':
case 'o':
case 'u':
case 'x':
case 'X':
case 'c':
return consumeInteger(stream, outCount, spec, ptr, args...);
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
case 'a':
case 'A':
return consumeFloatingPoint(stream, outCount, spec, ptr, args...);
case 's':
return consumeCstring(stream, outCount, spec, ptr, args...);
case 'p':
return consumePointer(stream, outCount, spec, ptr, args...);
case 'n':
return ptr + 1;
}
// Undefined behaviour with an unknown flag
return end;
}
static const uint64_t* processSpec(FILE* stream, int* outCount, const std::string& spec,
const uint64_t* ptr, const uint64_t* end) {
auto stars = countStars(spec);
assert(stars < 3 && "cannot have more than two placeholders");
switch (stars) {
case 0:
return consumeArgument(stream, outCount, spec, ptr, end);
case 1:
// Undefined behaviour if there are not enough arguments.
if (end - ptr < 2) {
return end;
}
return consumeArgument(stream, outCount, spec, ptr + 1, end, ptr[0]);
case 2:
// Undefined behaviour if there are not enough arguments.
if (end - ptr < 3) {
return end;
}
return consumeArgument(stream, outCount, spec, ptr + 2, end, ptr[0], ptr[1]);
}
// Undefined behaviour if three are more than two stars.
return end;
}
/** \brief Process a printf message using the system printf function.
* \param begin Start of the uint64_t array containing the message.
* \param end One past the last element in the array.
* \return An integer that satisfies the POSIX return value for printf.
*
* The message has the following format:
* - uint64_t version, required to be zero.
* - Format string padded to an 8 byte boundary.
* - Sequence of arguments
* - Each int/float/pointer argument occupies one uint64_t location.
* - Each string argument is padded to an 8 byte boundary.
*
* The format() function extracts the format string, and then
* extracts further arguments based on the format string. It breaks
* up the format string at the format specifiers and invokes the
* system printf() function multiple times:
* - A format specifier and its corresponding arguments are passed to
* a separate printf() call.
* - Slices between the format specifiers are passed to additional
* printf() calls interleaved with the specifiers.
*
* Limitations:
* - Behaviour is undefined with wide characters and strings.
* - %n specifier is ignored and the corresponding argument is skipped.
*/
static int format(FILE* stream, const uint64_t* begin, const uint64_t* end) {
const char convSpecifiers[] = "diouxXfFeEgGaAcspn";
auto ptr = begin;
const std::string fmt(reinterpret_cast<const char*>(ptr));
ptr += (fmt.length() + 7 + 1) / 8; // the extra '1' is for the null
int outCount = 0;
size_t point = 0;
while (true) {
// Each segment of the format string delineated by [mark,
// point) is handled seprately.
auto mark = point;
point = fmt.find('%', point);
// Two different cases where a literal segment is printed out.
// 1. When the point reaches the end of the format string.
// 2. When the point is at the start of a format specifier.
if (point == std::string::npos) {
checkPrintf(stream, &outCount, "%s", &fmt[mark]);
return outCount;
}
checkPrintf(stream, &outCount, "%.*s", (int)(point - mark), &fmt[mark]);
if (outCount < 0) {
return outCount;
}
mark = point;
++point;
// Handle the simplest specifier, '%%'.
if (fmt[point] == '%') {
checkPrintf(stream, &outCount, "%%");
if (outCount < 0) {
return outCount;
}
++point;
continue;
}
// Before processing the specifier, check if we have run out
// of arguments.
if (ptr == end) {
return outCount;
}
// Undefined behaviour if we don't see a conversion specifier.
point = fmt.find_first_of(convSpecifiers, point);
if (point == std::string::npos) {
return outCount;
}
++point;
// [mark,point) now contains a complete specifier.
const std::string spec(fmt, mark, point - mark);
ptr = processSpec(stream, &outCount, spec, ptr, end);
if (outCount < 0) {
return outCount;
}
}
}
void handlePrintf(uint64_t* output, const uint64_t* input, uint64_t len) {
auto end = input + len;
auto control = *input++;
FILE* stream = stdout;
// Only the LSB in the control word is used.
uint64_t CTRL_MASK = 1;
if (control & ~CTRL_MASK) {
// Unknown control value.
*output = -1;
return;
}
// Output goes to stderr if LSB is set.
if (control & CTRL_MASK) {
stream = stderr;
}
*output = format(stream, input, end);
}
|
#include "aux2.hpp"
#include <iostream>
void aux2()
{
std::cout << "Hello from aux2\n";
}
|
/*
* Copyright 2015 Open Source Robotics Foundation
*
* 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.
*
*/
#include <locale>
#include <string>
#include <vector>
#include "sdf/Types.hh"
namespace sdf
{
inline namespace SDF_VERSION_NAMESPACE {
/////////////////////////////////////////////////
std::vector<std::string> split(const std::string &_str,
const std::string &_splitter)
{
std::vector<std::string> ret;
size_t next = 0;
size_t current = next;
if (_splitter.empty())
{
// If the splitter is blank, just return the original
ret.push_back(_str);
return ret;
}
while (next != std::string::npos)
{
next = _str.find(_splitter, current);
ret.push_back(_str.substr(current, next - current));
current = next + _splitter.length();
}
return ret;
}
//////////////////////////////////////////////////
std::string trim(const char *_in)
{
return sdf::trim(std::string(_in));
}
//////////////////////////////////////////////////
std::string trim(const std::string &_in)
{
const size_t strBegin = _in.find_first_not_of(" \t\n");
if (strBegin == std::string::npos)
{
return "";
}
const size_t strRange = _in.find_last_not_of(" \t\n") - strBegin + 1;
return _in.substr(strBegin, strRange);
}
/////////////////////////////////////////////////
std::string lowercase(const std::string &_in)
{
std::string out = _in;
for (size_t i = 0; i < out.size(); ++i)
out[i] = std::tolower(out[i], std::locale());
return out;
}
/////////////////////////////////////////////////
std::ostream &operator<<(std::ostream &_out, const sdf::Errors &_errs)
{
for (const auto &e : _errs)
{
_out << e << std::endl;
}
return _out;
}
}
}
|
#include "stdafx.h"
#include <string>
#include "resource.h"
#include "mainframe.h"
#include "childfrm.h"
#include "mainframedoc.h"
#include "mainframeview.h"
#include "utility\utilitymacro.h"
#include <interface/iviewlugin.h>
CMainFrame::CMainFrame()
{
m_pMainFrameWnd = NULL;
}
CMainFrame::~CMainFrame()
{
}
void CMainFrame::RegisterTemplates()
{
//CMultiDocTemplate* pTemplate = new CMultiDocTemplate(
// IDR_MAINFRAME,
// RUNTIME_CLASS(CMainframeDoc),
// RUNTIME_CLASS(CChildFrame),
// RUNTIME_CLASS(CMainframeView));
//AfxGetApp()->AddDocTemplate(pTemplate);
// TODO: load from config
x3::Object<IViewPlugin> viewPluginPtr;
if(!viewPluginPtr.create(_T("e2f969c0-2600-11e5-a15a-0021ccd9da8f")))
return;
CMultiDocTemplate* pTemplate = new CMultiDocTemplate(
IDR_MAINFRAME,
viewPluginPtr->GetDocRC(),
RUNTIME_CLASS(CChildFrame),
viewPluginPtr->GetViewRC());
AfxGetApp()->AddDocTemplate(pTemplate);
}
BOOL CMainFrame::CreateFrame()
{
if (m_pMainFrameWnd != NULL)
return TRUE;
CXTPWinDwmWrapper().SetProcessDPIAware();
CString strFile;
ENV_RESOURCE_PATH(strFile);
if (PathFileExists(strFile))
XTPResourceManager()->SetResourceFile(strFile);
else
TRACE1("Warning: no translation file '%s'\n", strFile);
// register template
RegisterTemplates();
m_pMainFrameWnd = new CMainFrameWnd();
BOOL bRt = m_pMainFrameWnd->LoadFrame(IDR_MAINFRAME);
AfxGetApp()->m_pMainWnd = m_pMainFrameWnd;
return bRt;
}
void CMainFrame::ShowWindow()
{
CCommandLineInfo cmdInfo;
AfxGetApp()->ParseCommandLine(cmdInfo);
if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew)
cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing;
if (!AfxGetApp()->ProcessShellCommand(cmdInfo))
return;
AfxGetMainWnd()->ShowWindow(SW_SHOWMAXIMIZED);
AfxGetMainWnd()->UpdateWindow();
}
CWnd* CMainFrame::GetHandle()
{
return m_pMainFrameWnd;
}
void CMainFrame::OnQuit()
{
}
BOOL CMainFrame::OnIdle(long)
{
bool more = false;
return more;
}
|
// license:BSD-3-Clause
// copyright-holders:Manuel Abadia, Ernesto Corvi, Nicola Salmoria
/***************************************************************************
gaplus.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "emu.h"
#include "includes/gaplus.h"
/***************************************************************************
Convert the color PROMs.
The palette PROMs are connected to the RGB output this way:
bit 3 -- 220 ohm resistor -- RED/GREEN/BLUE
-- 470 ohm resistor -- RED/GREEN/BLUE
-- 1 kohm resistor -- RED/GREEN/BLUE
bit 0 -- 2.2kohm resistor -- RED/GREEN/BLUE
***************************************************************************/
void gaplus_base_state::gaplus_palette(palette_device &palette) const
{
const uint8_t *color_prom = m_proms_region->base();
for (int i = 0; i < 256; i++)
{
int bit0, bit1, bit2, bit3;
// red component
bit0 = BIT(color_prom[i], 0);
bit1 = BIT(color_prom[i], 1);
bit2 = BIT(color_prom[i], 2);
bit3 = BIT(color_prom[i], 3);
int const r = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
// green component
bit0 = BIT(color_prom[i + 0x100], 0);
bit1 = BIT(color_prom[i + 0x100], 1);
bit2 = BIT(color_prom[i + 0x100], 2);
bit3 = BIT(color_prom[i + 0x100], 3);
int const g = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
// blue component
bit0 = BIT(color_prom[i + 0x200], 0);
bit1 = BIT(color_prom[i + 0x200], 1);
bit2 = BIT(color_prom[i + 0x200], 2);
bit3 = BIT(color_prom[i + 0x200], 3);
int const b = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
palette.set_indirect_color(i, rgb_t(r, g, b));
}
color_prom += 0x300;
// color_prom now points to the beginning of the lookup table
// characters use colors 0xf0-0xff
for (int i = 0; i < m_gfxdecode->gfx(0)->colors() * m_gfxdecode->gfx(0)->granularity(); i++)
palette.set_pen_indirect(m_gfxdecode->gfx(0)->colorbase() + i, 0xf0 + (*color_prom++ & 0x0f));
/* sprites */
for (int i = 0; i < m_gfxdecode->gfx(1)->colors() * m_gfxdecode->gfx(1)->granularity(); i++)
{
palette.set_pen_indirect(m_gfxdecode->gfx(1)->colorbase() + i, (color_prom[0] & 0x0f) + ((color_prom[0x200] & 0x0f) << 4));
color_prom++;
}
}
/***************************************************************************
Callbacks for the TileMap code
***************************************************************************/
/* convert from 32x32 to 36x28 */
TILEMAP_MAPPER_MEMBER(gaplus_base_state::tilemap_scan)
{
row += 2;
col -= 2;
if (col & 0x20)
return row + ((col & 0x1f) << 5);
return col + (row << 5);
}
TILE_GET_INFO_MEMBER(gaplus_base_state::get_tile_info)
{
const uint8_t attr = m_videoram[tile_index + 0x400];
tileinfo.category = (attr & 0x40) >> 6;
tileinfo.group = attr & 0x3f;
tileinfo.set(0,
m_videoram[tile_index] + ((attr & 0x80) << 1),
attr & 0x3f,
0);
}
/***************************************************************************
Starfield information
There's 3 sets of stars planes at different speeds.
a000 ---> (bit 0 = 1) enable starfield.
(bit 0 = 0) disable starfield.
a001 ---> starfield plane 0 control
a002 ---> starfield plane 1 control
a003 ---> starfield plane 2 control
***************************************************************************/
/* starfield speed constants (bigger = faster) */
#define SPEED_1 1.0f
#define SPEED_2 2.0f
#define SPEED_3 3.0f
/* starfield: top and bottom clipping size */
#define STARFIELD_CLIPPING_X 16
void gaplus_base_state::starfield_init()
{
int generator = 0;
int set = 0;
const int width = m_screen->width();
const int height = m_screen->height();
m_total_stars = 0;
m_starfield_framecount = 0;
/* precalculate the star background */
/* this comes from the Galaxian hardware, Gaplus is probably different */
for (int y = 0; y < height; y++)
{
for (int x = width - (STARFIELD_CLIPPING_X * 2) - 1; x >= 0; x--)
{
generator <<= 1;
const int bit1 = (~generator >> 17) & 1;
const int bit2 = (generator >> 5) & 1;
if (bit1 ^ bit2) generator |= 1;
if (BIT(~generator, 16) && (generator & 0xff) == 0xff)
{
const int color = (~(generator >> 8)) % 7 + 1;
int color_base = 0;
/* A guess based on comparison with PCB video output */
switch (set)
{
case 0:
color_base = 0x250;
break;
case 1:
color_base = 0x230;
break;
case 2:
color_base = 0x210;
break;
}
if (color && m_total_stars < MAX_STARS)
{
m_stars[m_total_stars].x = x + STARFIELD_CLIPPING_X;
m_stars[m_total_stars].y = y;
m_stars[m_total_stars].col = color_base + color;
m_stars[m_total_stars].set = set++;
if (set == 3)
set = 0;
m_total_stars++;
}
}
}
}
}
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
void gaplus_base_state::video_start()
{
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(gaplus_state::get_tile_info)), tilemap_mapper_delegate(*this, FUNC(gaplus_state::tilemap_scan)), 8,8,36,28);
m_bg_tilemap->configure_groups(*m_gfxdecode->gfx(0), 0xff);
starfield_init();
save_item(NAME(m_starfield_control));
save_item(NAME(m_starfield_framecount));
for (int i = 0; i < MAX_STARS; i++)
{
save_item(NAME(m_stars[i].x), i);
save_item(NAME(m_stars[i].y), i);
// col and set aren't changed after init
}
}
/***************************************************************************
Memory handlers
***************************************************************************/
void gaplus_base_state::videoram_w(offs_t offset, uint8_t data)
{
m_videoram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset & 0x3ff);
}
void gaplus_base_state::starfield_control_w(offs_t offset, uint8_t data)
{
m_starfield_control[offset & 3] = data;
}
/***************************************************************************
Display Refresh
***************************************************************************/
void gaplus_base_state::starfield_render(bitmap_ind16 &bitmap)
{
/* check if we're running */
if ((m_starfield_control[0] & 1) == 0)
return;
const int width = m_screen->width();
const int height = m_screen->height();
/* draw the starfields */
for (int i = 0; i < m_total_stars; i++)
{
int x = m_stars[i].x;
int y = m_stars[i].y;
/* Some stars in the second layer will flash erratically when changing their movements.
(It is when at reverse scrolling stage or get elephant head.)
This is based on a guess from the video output of the PCB.
https://www.youtube.com/watch?v=_1x5Oid3uPg (3:35-, 13:12-)
https://www.youtube.com/watch?v=vrmZAUJYXnI (3:14-, 12:40-) */
if (m_stars[i].set == 1 && m_starfield_control[2] != 0x85 && i % 2 == 0)
{
int bit = BIT(m_starfield_framecount + i, 3) ? 1 : 2;
if (BIT(m_starfield_framecount + i, bit)) { continue; }
}
if (x >= 0 && x < width && y >= 0 && y < height)
{
bitmap.pix(y, x) = m_stars[i].col;
}
}
}
void gaplus_base_state::draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect ) const
{
uint8_t *spriteram = m_spriteram + 0x780;
uint8_t *spriteram_2 = spriteram + 0x800;
uint8_t *spriteram_3 = spriteram_2 + 0x800;
for (int offs = 0;offs < 0x80;offs += 2)
{
/* is it on? */
if ((spriteram_3[offs+1] & 2) == 0)
{
static const int gfx_offs[2][2] =
{
{ 0, 1 },
{ 2, 3 }
};
const int sprite = spriteram[offs] | ((spriteram_3[offs] & 0x40) << 2);
const int color = spriteram[offs+1] & 0x3f;
const int sx = spriteram_2[offs+1] + 0x100 * (spriteram_3[offs+1] & 1) - 71;
int sy = 256 - spriteram_2[offs] - 8;
int flipx = BIT(spriteram_3[offs], 0);
int flipy = BIT(spriteram_3[offs], 1);
const int sizex = BIT(spriteram_3[offs], 3);
const int sizey = BIT(spriteram_3[offs], 5);
const int duplicate = spriteram_3[offs] & 0x80;
if (flip_screen())
{
flipx ^= 1;
flipy ^= 1;
}
sy -= 16 * sizey;
sy = (sy & 0xff) - 32; // fix wraparound
for (int y = 0;y <= sizey; y++)
{
for (int x = 0; x <= sizex; x++)
{
m_gfxdecode->gfx(1)->transmask(bitmap, cliprect,
sprite + (duplicate ? 0 : (gfx_offs[y ^ (sizey * flipy)][x ^ (sizex * flipx)])),
color,
flipx,flipy,
sx + 16 * x, sy + 16 * y,
m_palette->transpen_mask(*m_gfxdecode->gfx(1), color, 0xff));
}
}
}
}
}
uint32_t gaplus_base_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
/* flip screen control is embedded in RAM */
flip_screen_set(m_spriteram[0x1f7f - 0x800] & 1);
bitmap.fill(0, cliprect);
starfield_render(bitmap);
/* draw the low priority characters */
m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
draw_sprites(bitmap, cliprect);
/* draw the high priority characters */
/* (I don't know if this feature is used by Gaplus, but it's shown in the schematics) */
m_bg_tilemap->draw(screen, bitmap, cliprect, 1, 0);
return 0;
}
WRITE_LINE_MEMBER(gaplus_base_state::screen_vblank)/* update starfields */
{
// falling edge
if (!state)
{
struct star *stars = m_stars;
int i;
int width = m_screen->width();
int height = m_screen->height();
m_starfield_framecount ++;
/* check if we're running */
if ( ( m_starfield_control[0] & 1 ) == 0 )
return;
/* update the starfields */
for ( i = 0; i < m_total_stars; i++ ) {
switch( m_starfield_control[stars[i].set + 1] ) {
case 0x87:
/* stand still */
break;
case 0x85:
case 0x86:
/* scroll down (speed 1) */
stars[i].x += SPEED_1;
break;
case 0x06:
/* scroll down (speed 2) */
stars[i].x += SPEED_2;
break;
case 0x80:
/* scroll up (speed 1) */
stars[i].x -= SPEED_1;
break;
case 0x82:
/* scroll up (speed 2) */
stars[i].x -= SPEED_2;
break;
case 0x81:
/* scroll up (speed 3) */
stars[i].x -= SPEED_3;
break;
case 0x9f:
/* scroll left (speed 3) */
stars[i].y += SPEED_3;
break;
case 0xaf:
/* scroll right (speed 3) */
stars[i].y -= SPEED_3;
break;
}
/* wrap */
if ( stars[i].x < STARFIELD_CLIPPING_X )
stars[i].x = ( float )( width-STARFIELD_CLIPPING_X*2) + stars[i].x;
if ( stars[i].x >= ( float )( width-STARFIELD_CLIPPING_X) )
stars[i].x -= ( float )( width-STARFIELD_CLIPPING_X*2);
if ( stars[i].y < 0 )
stars[i].y = ( float )( height ) + stars[i].y;
if ( stars[i].y >= ( float )( height ) )
stars[i].y -= ( float )( height );
}
}
}
|
/**
* @file
* @copyright defined in aac/LICENSE.txt
*/
#pragma once
#include <aacio/chain/exceptions.hpp>
#include <aacio/chain/types.hpp>
#include <aacio/chain/symbol.hpp>
namespace aacio { namespace chain {
/**
asset includes amount and currency symbol
asset::from_string takes a string of the form "10.0000 CUR" and constructs an asset
with amount = 10 and symbol(4,"CUR")
*/
struct asset
{
static constexpr int64_t max_amount = (1LL << 62) - 1;
explicit asset(share_type a = 0, symbol id = symbol(CORE_SYMBOL)) :amount(a), sym(id) {
AAC_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
AAC_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
}
bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }
bool is_valid()const { return is_amount_within_range() && sym.valid(); }
double to_real()const { return static_cast<double>(amount) / precision(); }
uint8_t decimals()const;
string symbol_name()const;
int64_t precision()const;
const symbol& get_symbol() const { return sym; }
share_type get_amount()const { return amount; }
static asset from_string(const string& from);
string to_string()const;
asset& operator += (const asset& o)
{
AAC_ASSERT(get_symbol() == o.get_symbol(), asset_type_exception, "addition between two different asset is not allowed");
amount += o.amount;
return *this;
}
asset& operator -= (const asset& o)
{
AAC_ASSERT(get_symbol() == o.get_symbol(), asset_type_exception, "subtraction between two different asset is not allowed");
amount -= o.amount;
return *this;
}
asset operator -()const { return asset(-amount, get_symbol()); }
friend bool operator == (const asset& a, const asset& b)
{
return std::tie(a.get_symbol(), a.amount) == std::tie(b.get_symbol(), b.amount);
}
friend bool operator < (const asset& a, const asset& b)
{
AAC_ASSERT(a.get_symbol() == b.get_symbol(), asset_type_exception, "logical operation between two different asset is not allowed");
return std::tie(a.amount,a.get_symbol()) < std::tie(b.amount,b.get_symbol());
}
friend bool operator <= (const asset& a, const asset& b) { return (a == b) || (a < b); }
friend bool operator != (const asset& a, const asset& b) { return !(a == b); }
friend bool operator > (const asset& a, const asset& b) { return !(a <= b); }
friend bool operator >= (const asset& a, const asset& b) { return !(a < b); }
friend asset operator - (const asset& a, const asset& b) {
AAC_ASSERT(a.get_symbol() == b.get_symbol(), asset_type_exception, "subtraction between two different asset is not allowed");
return asset(a.amount - b.amount, a.get_symbol());
}
friend asset operator + (const asset& a, const asset& b) {
AAC_ASSERT(a.get_symbol() == b.get_symbol(), asset_type_exception, "addition between two different asset is not allowed");
return asset(a.amount + b.amount, a.get_symbol());
}
friend std::ostream& operator << (std::ostream& out, const asset& a) { return out << a.to_string(); }
friend struct fc::reflector<asset>;
void reflector_verify()const {
AAC_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
AAC_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
}
private:
share_type amount;
symbol sym;
};
struct extended_asset {
extended_asset(){}
extended_asset( asset a, name n ):quantity(a),contract(n){}
asset quantity;
name contract;
};
bool operator < (const asset& a, const asset& b);
bool operator <= (const asset& a, const asset& b);
}} // namespace aacio::chain
namespace fc {
inline void to_variant(const aacio::chain::asset& var, fc::variant& vo) { vo = var.to_string(); }
inline void from_variant(const fc::variant& var, aacio::chain::asset& vo) {
vo = aacio::chain::asset::from_string(var.get_string());
}
}
FC_REFLECT(aacio::chain::asset, (amount)(sym))
FC_REFLECT(aacio::chain::extended_asset, (quantity)(contract) )
|
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file SymbolicISAM.cpp
* @date July 29, 2013
* @author Frank Dellaert
* @author Richard Roberts
*/
#include <gtsam/symbolic/SymbolicISAM.h>
#include <gtsam/inference/ISAM-inst.h>
namespace gtsam {
// Instantiate base class
template class ISAM<SymbolicBayesTree>;
/* ************************************************************************* */
SymbolicISAM::SymbolicISAM() {}
/* ************************************************************************* */
SymbolicISAM::SymbolicISAM(const SymbolicBayesTree& bayesTree) :
Base(bayesTree) {}
}
|
#include "StreamingTextView.h"
#include <GroupLayout.h>
#include <ScrollBar.h>
#include <String.h>
#include <TextView.h>
#include <View.h>
StreamingTextView::StreamingTextView(const char* name)
:
BView(name,B_SUPPORTS_LAYOUT),
fText(new BTextView("text"))
{
BGroupLayout* hGroup = new BGroupLayout(B_HORIZONTAL, 0);
SetLayout(hGroup);
hGroup->SetInsets(0, -1, -1, -1); // hides scroll bar borders
BView* hView = new BView("hview", 0, hGroup);
fText->MakeEditable(false);
BLayoutItem* textView = hGroup->AddView(fText);
textView->SetExplicitAlignment(BAlignment(B_ALIGN_USE_FULL_WIDTH,
B_ALIGN_USE_FULL_HEIGHT));
fTextScroll = new BScrollBar("textscrollbar",
fText, 0, 100, B_VERTICAL);
fTextScroll->SetResizingMode(B_FOLLOW_RIGHT | B_FOLLOW_TOP);
BLayoutItem* liScrollBar = hGroup->AddView(fTextScroll);
liScrollBar->SetExplicitAlignment(BAlignment(B_ALIGN_RIGHT,
B_ALIGN_USE_FULL_HEIGHT));
}
StreamingTextView::~StreamingTextView()
{
}
void
StreamingTextView::Append(BString& text)
{
BString newText(fText->Text());
newText << text;
fText->SetText(newText);
float min, max;
fTextScroll->GetRange(&min,&max);
fTextScroll->SetValue(max);
}
|
#include "GAMER.h"
#include "TestProb.h"
// problem-specific global variables
// =======================================================================================
static bool var_bool;
static double var_double;
static int var_int;
static char var_str[MAX_STRING];
// =======================================================================================
//-------------------------------------------------------------------------------------------------------
// Function : Validate
// Description : Validate the compilation flags and runtime parameters for this test problem
//
// Note : None
//
// Parameter : None
//
// Return : None
//-------------------------------------------------------------------------------------------------------
void Validate()
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, " Validating test problem %d ...\n", TESTPROB_ID );
// examples
/*
// errors
# if ( MODEL != HYDRO )
Aux_Error( ERROR_INFO, "MODEL != HYDRO !!\n" );
# endif
# ifndef GRAVITY
Aux_Error( ERROR_INFO, "GRAVITY must be enabled !!\n" );
# endif
# ifdef PARTICLE
Aux_Error( ERROR_INFO, "PARTICLE must be disabled !!\n" );
# endif
# ifdef GRAVITY
if ( OPT__BC_FLU[0] == BC_FLU_PERIODIC || OPT__BC_POT == BC_POT_PERIODIC )
Aux_Error( ERROR_INFO, "do not use periodic BC for this test !!\n" );
# endif
// warnings
if ( MPI_Rank == 0 )
{
# ifndef DUAL_ENERGY
Aux_Message( stderr, "WARNING : it's recommended to enable DUAL_ENERGY for this test !!\n" );
# endif
if ( FLAG_BUFFER_SIZE < 5 )
Aux_Message( stderr, "WARNING : it's recommended to set FLAG_BUFFER_SIZE >= 5 for this test !!\n" );
} // if ( MPI_Rank == 0 )
*/
if ( MPI_Rank == 0 ) Aux_Message( stdout, " Validating test problem %d ... done\n", TESTPROB_ID );
} // FUNCTION : Validate
// replace HYDRO by the target model (e.g., MHD/ELBDM) and also check other compilation flags if necessary (e.g., GRAVITY/PARTICLE)
#if ( MODEL == HYDRO )
//-------------------------------------------------------------------------------------------------------
// Function : SetParameter
// Description : Load and set the problem-specific runtime parameters
//
// Note : 1. Filename is set to "Input__TestProb" by default
// 2. Major tasks in this function:
// (1) load the problem-specific runtime parameters
// (2) set the problem-specific derived parameters
// (3) reset other general-purpose parameters if necessary
// (4) make a note of the problem-specific parameters
// 3. Must call EoS_Init() before calling any other EoS routine
//
// Parameter : None
//
// Return : None
//-------------------------------------------------------------------------------------------------------
void SetParameter()
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, " Setting runtime parameters ...\n" );
// (1) load the problem-specific runtime parameters
const char FileName[] = "Input__TestProb";
ReadPara_t *ReadPara = new ReadPara_t;
// (1-1) add parameters in the following format:
// --> note that VARIABLE, DEFAULT, MIN, and MAX must have the same data type
// --> some handy constants (e.g., Useless_bool, Eps_double, NoMin_int, ...) are defined in "include/ReadPara.h"
// ********************************************************************************************************************************
// ReadPara->Add( "KEY_IN_THE_FILE", &VARIABLE, DEFAULT, MIN, MAX );
// ********************************************************************************************************************************
ReadPara->Add( "var_bool", &var_bool, true, Useless_bool, Useless_bool );
ReadPara->Add( "var_double", &var_double, 1.0, Eps_double, NoMax_double );
ReadPara->Add( "var_int", &var_int, 2, 0, 5 );
ReadPara->Add( "var_str", var_str, Useless_str, Useless_str, Useless_str );
ReadPara->Read( FileName );
delete ReadPara;
// (1-2) set the default values
// (1-3) check the runtime parameters
// (2) set the problem-specific derived parameters
// (3) reset other general-purpose parameters
// --> a helper macro PRINT_WARNING is defined in TestProb.h
const long End_Step_Default = __INT_MAX__;
const double End_T_Default = __FLT_MAX__;
if ( END_STEP < 0 ) {
END_STEP = End_Step_Default;
PRINT_WARNING( "END_STEP", END_STEP, FORMAT_LONG );
}
if ( END_T < 0.0 ) {
END_T = End_T_Default;
PRINT_WARNING( "END_T", END_T, FORMAT_REAL );
}
// (4) make a note
if ( MPI_Rank == 0 )
{
Aux_Message( stdout, "=============================================================================\n" );
Aux_Message( stdout, " test problem ID = %d\n", TESTPROB_ID );
Aux_Message( stdout, " var_bool = %d\n", var_bool );
Aux_Message( stdout, " var_double = %13.7e\n", var_double );
Aux_Message( stdout, " var_int = %d\n", var_int );
Aux_Message( stdout, " var_str = %s\n", var_str );
Aux_Message( stdout, "=============================================================================\n" );
}
if ( MPI_Rank == 0 ) Aux_Message( stdout, " Setting runtime parameters ... done\n" );
} // FUNCTION : SetParameter
//-------------------------------------------------------------------------------------------------------
// Function : SetGridIC
// Description : Set the problem-specific initial condition on grids
//
// Note : 1. This function may also be used to estimate the numerical errors when OPT__OUTPUT_USER is enabled
// --> In this case, it should provide the analytical solution at the given "Time"
// 2. This function will be invoked by multiple OpenMP threads when OPENMP is enabled
// (unless OPT__INIT_GRID_WITH_OMP is disabled)
// --> Please ensure that everything here is thread-safe
// 3. Even when DUAL_ENERGY is adopted for HYDRO, one does NOT need to set the dual-energy variable here
// --> It will be calculated automatically
// 4. For MHD, do NOT add magnetic energy (i.e., 0.5*B^2) to fluid[ENGY] here
// --> It will be added automatically later
//
// Parameter : fluid : Fluid field to be initialized
// x/y/z : Physical coordinates
// Time : Physical time
// lv : Target refinement level
// AuxArray : Auxiliary array
//
// Return : fluid
//-------------------------------------------------------------------------------------------------------
void SetGridIC( real fluid[], const double x, const double y, const double z, const double Time,
const int lv, double AuxArray[] )
{
// HYDRO example
double Dens, MomX, MomY, MomZ, Pres, Eint, Etot;
Dens = 1.0;
MomX = 0.0;
MomY = 0.0;
MomZ = 0.0;
Pres = 2.0;
Eint = EoS_DensPres2Eint_CPUPtr( Dens, Pres, NULL, EoS_AuxArray_Flt,
EoS_AuxArray_Int, h_EoS_Table, NULL ); // assuming EoS requires no passive scalars
Etot = Hydro_ConEint2Etot( Dens, MomX, MomY, MomZ, Eint, 0.0 ); // do NOT include magnetic energy here
// set the output array
fluid[DENS] = Dens;
fluid[MOMX] = MomX;
fluid[MOMY] = MomY;
fluid[MOMZ] = MomZ;
fluid[ENGY] = Etot;
} // FUNCTION : SetGridIC
#ifdef MHD
//-------------------------------------------------------------------------------------------------------
// Function : SetBFieldIC
// Description : Set the problem-specific initial condition of magnetic field
//
// Note : 1. This function will be invoked by multiple OpenMP threads when OPENMP is enabled
// (unless OPT__INIT_GRID_WITH_OMP is disabled)
// --> Please ensure that everything here is thread-safe
//
// Parameter : magnetic : Array to store the output magnetic field
// x/y/z : Target physical coordinates
// Time : Target physical time
// lv : Target refinement level
// AuxArray : Auxiliary array
//
// Return : magnetic
//-------------------------------------------------------------------------------------------------------
void SetBFieldIC( real magnetic[], const double x, const double y, const double z, const double Time,
const int lv, double AuxArray[] )
{
/*
// example
magnetic[MAGX] = 1.0;
magnetic[MAGY] = 2.0;
magnetic[MAGZ] = 3.0;
*/
} // FUNCTION : SetBFieldIC
#endif // #ifdef MHD
#endif // #if ( MODEL == HYDRO )
//-------------------------------------------------------------------------------------------------------
// Function : Init_TestProb_Template
// Description : Test problem initializer
//
// Note : None
//
// Parameter : None
//
// Return : None
//-------------------------------------------------------------------------------------------------------
void Init_TestProb_Template()
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s ...\n", __FUNCTION__ );
// validate the compilation flags and runtime parameters
Validate();
// replace HYDRO by the target model (e.g., MHD/ELBDM) and also check other compilation flags if necessary (e.g., GRAVITY/PARTICLE)
# if ( MODEL == HYDRO )
// set the problem-specific runtime parameters
SetParameter();
// procedure to enable a problem-specific function:
// 1. define a user-specified function (example functions are given below)
// 2. declare its function prototype on the top of this file
// 3. set the corresponding function pointer below to the new problem-specific function
// 4. enable the corresponding runtime option in "Input__Parameter"
// --> for instance, enable OPT__OUTPUT_USER for Output_User_Ptr
Init_Function_User_Ptr = SetGridIC;
# ifdef MHD
Init_Function_BField_User_Ptr = SetBFieldIC;
# endif
// comment out Init_ByFile_User_Ptr to use the default
// Init_ByFile_User_Ptr = NULL; // option: OPT__INIT=3; example: Init/Init_ByFile.cpp -> Init_ByFile_Default()
Init_Field_User_Ptr = NULL; // set NCOMP_PASSIVE_USER; example: TestProblem/Hydro/Plummer/Init_TestProb_Hydro_Plummer.cpp --> AddNewField()
Flag_User_Ptr = NULL; // option: OPT__FLAG_USER; example: Refine/Flag_User.cpp
Mis_GetTimeStep_User_Ptr = NULL; // option: OPT__DT_USER; example: Miscellaneous/Mis_GetTimeStep_User.cpp
BC_User_Ptr = NULL; // option: OPT__BC_FLU_*=4; example: TestProblem/ELBDM/ExtPot/Init_TestProb_ELBDM_ExtPot.cpp --> BC()
# ifdef MHD
BC_BField_User_Ptr = NULL; // option: OPT__BC_FLU_*=4;
# endif
Flu_ResetByUser_Func_Ptr = NULL; // option: OPT__RESET_FLUID; example: Fluid/Flu_ResetByUser.cpp
Init_DerivedField_User_Ptr = NULL; // option: OPT__OUTPUT_USER_FIELD; example: Fluid/Flu_DerivedField_User.cpp
Output_User_Ptr = NULL; // option: OPT__OUTPUT_USER; example: TestProblem/Hydro/AcousticWave/Init_TestProb_Hydro_AcousticWave.cpp --> OutputError()
Aux_Record_User_Ptr = NULL; // option: OPT__RECORD_USER; example: Auxiliary/Aux_Record_User.cpp
Init_User_Ptr = NULL; // option: none; example: none
End_User_Ptr = NULL; // option: none; example: TestProblem/Hydro/ClusterMerger_vs_Flash/Init_TestProb_ClusterMerger_vs_Flash.cpp --> End_ClusterMerger()
# ifdef GRAVITY
Init_ExtAcc_Ptr = NULL; // option: OPT__EXT_ACC; example: SelfGravity/CPU_Gravity/CPU_ExtAcc_PointMass.cpp
End_ExtAcc_Ptr = NULL;
Init_ExtPot_Ptr = NULL; // option: OPT__EXT_POT; example: SelfGravity/CPU_Poisson/CPU_ExtPot_PointMass.cpp
End_ExtPot_Ptr = NULL;
Poi_AddExtraMassForGravity_Ptr = NULL; // option: OPT__GRAVITY_EXTRA_MASS; example: none
Poi_UserWorkBeforePoisson_Ptr = NULL; // option: none; example: SelfGravity/Poi_UserWorkBeforePoisson.cpp
# endif
# ifdef PARTICLE
Par_Init_ByFunction_Ptr = NULL; // option: PAR_INIT=1; example: Particle/Par_Init_ByFunction.cpp
Par_Init_Attribute_User_Ptr = NULL; // set PAR_NATT_USER; example: TestProblem/Hydro/AGORA_IsolatedGalaxy/Init_TestProb_Hydro_AGORA_IsolatedGalaxy.cpp --> AddNewParticleAttribute()
# endif
# if ( EOS == EOS_USER )
EoS_Init_Ptr = NULL; // option: EOS in the Makefile; example: EoS/User_Template/CPU_EoS_User_Template.cpp
EoS_End_Ptr = NULL;
# endif
# endif // #if ( MODEL == HYDRO )
Src_Init_User_Ptr = NULL; // option: SRC_USER; example: SourceTerms/User_Template/CPU_Src_User_Template.cpp
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s ... done\n", __FUNCTION__ );
} // FUNCTION : Init_TestProb_Template
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_wchar_t_declare_54b.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-54b.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: declare Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_wchar_t_declare_54
{
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
/* bad function declaration */
void badSink_c(wchar_t * data);
void badSink_b(wchar_t * data)
{
badSink_c(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(wchar_t * data);
void goodG2BSink_b(wchar_t * data)
{
goodG2BSink_c(data);
}
#endif /* OMITGOOD */
} /* close namespace */
|
/* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</editor-fold> */
#include <vsg/commands/BindVertexBuffers.h>
#include <vsg/io/Options.h>
#include <vsg/traversals/CompileTraversal.h>
#include <vsg/vk/CommandBuffer.h>
using namespace vsg;
BindVertexBuffers::~BindVertexBuffers()
{
for (auto& vkd : _vulkanData)
{
size_t numBufferEntries = std::min(vkd.buffers.size(), vkd.offsets.size());
for (size_t i = 0; i < numBufferEntries; ++i)
{
if (vkd.buffers[i])
{
vkd.buffers[i]->release(vkd.offsets[i], 0); // TODO
}
}
}
}
void BindVertexBuffers::read(Input& input)
{
Command::read(input);
// clear Vulkan objects
_vulkanData.clear();
// read vertex arrays
_arrays.resize(input.readValue<uint32_t>("NumArrays"));
for (auto& array : _arrays)
{
input.readObject("Array", array);
}
}
void BindVertexBuffers::write(Output& output) const
{
Command::write(output);
output.writeValue<uint32_t>("NumArrays", _arrays.size());
for (auto& array : _arrays)
{
output.writeObject("Array", array.get());
}
}
void BindVertexBuffers::compile(Context& context)
{
// nothing to compile
if (_arrays.empty()) return;
auto& vkd = _vulkanData[context.deviceID];
// already compiled
if (vkd.buffers.size() == _arrays.size()) return;
vkd.buffers.clear();
vkd.vkBuffers.clear();
vkd.offsets.clear();
auto bufferDataList = vsg::createBufferAndTransferData(context, _arrays, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE);
for (auto& bufferData : bufferDataList)
{
vkd.buffers.push_back(bufferData.buffer);
vkd.vkBuffers.push_back(bufferData.buffer->vk(context.deviceID));
vkd.offsets.push_back(bufferData.offset);
}
}
void BindVertexBuffers::record(CommandBuffer& commandBuffer) const
{
auto& vkd = _vulkanData[commandBuffer.deviceID];
vkCmdBindVertexBuffers(commandBuffer, _firstBinding, static_cast<uint32_t>(vkd.vkBuffers.size()), vkd.vkBuffers.data(), vkd.offsets.data());
}
|
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <csim/model.h>
#include <csim/error_codes.h>
#include <csim/executable_functions.h>
#include "version.h"
void usage(int argc, char* argv[])
{
std::cout << "This is CellML-2-BeatBox version: " << versionString() << std::endl;
}
int main(int argc, char* argv[])
{
// check command line arguments
usage(argc, argv);
return 0;
}
|
/**
* @file methods/random_forest/random_forest_main.cpp
* @author Ryan Curtin
*
* A program to build and evaluate random forests.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/core.hpp>
#include <mlpack/core/util/io.hpp>
#ifdef BINDING_NAME
#undef BINDING_NAME
#endif
#define BINDING_NAME random_forest
#include <mlpack/core/util/mlpack_main.hpp>
#include <mlpack/core/math/random.hpp>
#include <mlpack/methods/random_forest/random_forest.hpp>
#include <mlpack/methods/decision_tree/random_dimension_select.hpp>
using namespace mlpack;
using namespace mlpack::math;
using namespace mlpack::tree;
using namespace mlpack::util;
using namespace std;
// Program Name.
BINDING_USER_NAME("Random forests");
// Short description.
BINDING_SHORT_DESC(
"An implementation of the standard random forest algorithm by Leo Breiman "
"for classification. Given labeled data, a random forest can be trained "
"and saved for future use; or, a pre-trained random forest can be used for "
"classification.");
// Long description.
BINDING_LONG_DESC(
"This program is an implementation of the standard random forest "
"classification algorithm by Leo Breiman. A random forest can be "
"trained and saved for later use, or a random forest may be loaded "
"and predictions or class probabilities for points may be generated."
"\n\n"
"The training set and associated labels are specified with the " +
PRINT_PARAM_STRING("training") + " and " + PRINT_PARAM_STRING("labels") +
" parameters, respectively. The labels should be in the range [0, "
"num_classes - 1]. Optionally, if " +
PRINT_PARAM_STRING("labels") + " is not specified, the labels are assumed "
"to be the last dimension of the training dataset."
"\n\n"
"When a model is trained, the " + PRINT_PARAM_STRING("output_model") + " "
"output parameter may be used to save the trained model. A model may be "
"loaded for predictions with the " + PRINT_PARAM_STRING("input_model") +
"parameter. The " + PRINT_PARAM_STRING("input_model") + " parameter may "
"not be specified when the " + PRINT_PARAM_STRING("training") + " parameter"
" is specified. The " + PRINT_PARAM_STRING("minimum_leaf_size") +
" parameter specifies the minimum number of training points that must fall "
"into each leaf for it to be split. The " +
PRINT_PARAM_STRING("num_trees") +
" controls the number of trees in the random forest. The " +
PRINT_PARAM_STRING("minimum_gain_split") + " parameter controls the minimum"
" required gain for a decision tree node to split. Larger values will "
"force higher-confidence splits. The " +
PRINT_PARAM_STRING("maximum_depth") + " parameter specifies "
"the maximum depth of the tree. The " +
PRINT_PARAM_STRING("subspace_dim") + " parameter is used to control the "
"number of random dimensions chosen for an individual node's split. If " +
PRINT_PARAM_STRING("print_training_accuracy") + " is specified, the "
"calculated accuracy on the training set will be printed."
"\n\n"
"Test data may be specified with the " + PRINT_PARAM_STRING("test") + " "
"parameter, and if performance measures are desired for that test set, "
"labels for the test points may be specified with the " +
PRINT_PARAM_STRING("test_labels") + " parameter. Predictions for each "
"test point may be saved via the " + PRINT_PARAM_STRING("predictions") +
"output parameter. Class probabilities for each prediction may be saved "
"with the " + PRINT_PARAM_STRING("probabilities") + " output parameter.");
// Example.
BINDING_EXAMPLE(
"For example, to train a random forest with a minimum leaf size of 20 "
"using 10 trees on the dataset contained in " + PRINT_DATASET("data") +
"with labels " + PRINT_DATASET("labels") + ", saving the output random "
"forest to " + PRINT_MODEL("rf_model") + " and printing the training "
"error, one could call"
"\n\n" +
PRINT_CALL("random_forest", "training", "data", "labels", "labels",
"minimum_leaf_size", 20, "num_trees", 10, "output_model", "rf_model",
"print_training_accuracy", true) +
"\n\n"
"Then, to use that model to classify points in " +
PRINT_DATASET("test_set") + " and print the test error given the labels " +
PRINT_DATASET("test_labels") + " using that model, while saving the "
"predictions for each point to " + PRINT_DATASET("predictions") + ", one "
"could call "
"\n\n" +
PRINT_CALL("random_forest", "input_model", "rf_model", "test", "test_set",
"test_labels", "test_labels", "predictions", "predictions"));
// See also...
BINDING_SEE_ALSO("@decision_tree", "#decision_tree");
BINDING_SEE_ALSO("@hoeffding_tree", "#hoeffding_tree");
BINDING_SEE_ALSO("@softmax_regression", "#softmax_regression");
BINDING_SEE_ALSO("Random forest on Wikipedia",
"https://en.wikipedia.org/wiki/Random_forest");
BINDING_SEE_ALSO("Random forests (pdf)",
"https://link.springer.com/content/pdf/10.1023/A:1010933404324.pdf");
BINDING_SEE_ALSO("mlpack::tree::RandomForest C++ class documentation",
"@doxygen/classmlpack_1_1tree_1_1RandomForest.html");
PARAM_MATRIX_IN("training", "Training dataset.", "t");
PARAM_UROW_IN("labels", "Labels for training dataset.", "l");
PARAM_MATRIX_IN("test", "Test dataset to produce predictions for.", "T");
PARAM_UROW_IN("test_labels", "Test dataset labels, if accuracy calculation is "
"desired.", "L");
PARAM_FLAG("print_training_accuracy", "If set, then the accuracy of the model "
"on the training set will be predicted (verbose must also be specified).",
"a");
PARAM_INT_IN("num_trees", "Number of trees in the random forest.", "N", 10);
PARAM_INT_IN("minimum_leaf_size", "Minimum number of points in each leaf "
"node.", "n", 1);
PARAM_INT_IN("maximum_depth", "Maximum depth of the tree (0 means no limit).",
"D", 0);
PARAM_MATRIX_OUT("probabilities", "Predicted class probabilities for each "
"point in the test set.", "P");
PARAM_UROW_OUT("predictions", "Predicted classes for each point in the test "
"set.", "p");
PARAM_DOUBLE_IN("minimum_gain_split", "Minimum gain needed to make a split "
"when building a tree.", "g", 0);
PARAM_INT_IN("subspace_dim", "Dimensionality of random subspace to use for "
"each split. '0' will autoselect the square root of data dimensionality.",
"d", 0);
PARAM_INT_IN("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_FLAG("warm_start", "If true and passed along with `training` and "
"`input_model` then trains more trees on top of existing model.", "w");
/**
* This is the class that we will serialize. It is a pretty simple wrapper
* around DecisionTree<>. In order to support categoricals, it will need to
* also hold and serialize a DatasetInfo.
*/
class RandomForestModel
{
public:
// The tree itself, left public for direct access by this program.
RandomForest<> rf;
// Create the model.
RandomForestModel() { /* Nothing to do. */ }
// Serialize the model.
template<typename Archive>
void serialize(Archive& ar, const uint32_t /* version */)
{
ar(CEREAL_NVP(rf));
}
};
PARAM_MODEL_IN(RandomForestModel, "input_model", "Pre-trained random forest to "
"use for classification.", "m");
PARAM_MODEL_OUT(RandomForestModel, "output_model", "Model to save trained "
"random forest to.", "M");
void BINDING_FUNCTION(util::Params& params, util::Timers& timers)
{
// Initialize random seed if needed.
if (params.Get<int>("seed") != 0)
RandomSeed((size_t) params.Get<int>("seed"));
else
RandomSeed((size_t) std::time(NULL));
// Check for incompatible input parameters.
if (!params.Has("warm_start"))
{
RequireOnlyOnePassed(params, { "training", "input_model" }, true);
}
else
{
// When warm_start is passed, training and input_model must also be passed.
RequireNoneOrAllPassed(params, {"warm_start", "training", "input_model"},
true);
}
ReportIgnoredParam(params, {{ "training", false }},
"print_training_accuracy");
ReportIgnoredParam(params, {{ "test", false }}, "test_labels");
RequireAtLeastOnePassed(params, { "test", "output_model",
"print_training_accuracy" }, false, "the trained forest model will not "
"be used or saved");
if (params.Has("training"))
{
RequireAtLeastOnePassed(params, { "labels" }, true, "must pass labels when "
"training set given");
}
RequireParamValue<int>(params, "num_trees", [](int x) { return x > 0; }, true,
"number of trees in forest must be positive");
ReportIgnoredParam(params, {{ "test", false }}, "predictions");
ReportIgnoredParam(params, {{ "test", false }}, "probabilities");
RequireParamValue<int>(params, "minimum_leaf_size",
[](int x) { return x > 0; }, true, "minimum leaf size must be greater "
"than 0");
RequireParamValue<int>(params, "maximum_depth", [](int x) { return x >= 0; },
true, "maximum depth must not be negative");
RequireParamValue<int>(params, "subspace_dim", [](int x) { return x >= 0; },
true, "subspace dimensionality must be nonnegative");
RequireParamValue<double>(params, "minimum_gain_split",
[](double x) { return x >= 0.0; }, true,
"minimum gain for splitting must be nonnegative");
ReportIgnoredParam(params, {{ "training", false }}, "num_trees");
ReportIgnoredParam(params, {{ "training", false }}, "minimum_leaf_size");
RandomForestModel* rfModel;
// Input model is loaded when we are either doing warm-started training or
// else we are making predictions only or both.
if (params.Has("input_model"))
rfModel = params.Get<RandomForestModel*>("input_model");
// Handles the case when we are training new forest from scratch.
else
rfModel = new RandomForestModel();
if (params.Has("training"))
{
timers.Start("rf_training");
// Train the model on the given input data.
arma::mat data = std::move(params.Get<arma::mat>("training"));
arma::Row<size_t> labels =
std::move(params.Get<arma::Row<size_t>>("labels"));
// Make sure the subspace dimensionality is valid.
RequireParamValue<int>(params, "subspace_dim",
[data](int x) { return (size_t) x <= data.n_rows; }, true, "subspace "
"dimensionality must not be greater than data dimensionality");
const size_t numTrees = (size_t) params.Get<int>("num_trees");
const size_t minimumLeafSize =
(size_t) params.Get<int>("minimum_leaf_size");
const size_t maxDepth = (size_t) params.Get<int>("maximum_depth");
const double minimumGainSplit = params.Get<double>("minimum_gain_split");
const size_t randomDims = (params.Get<int>("subspace_dim") == 0) ?
(size_t) std::sqrt(data.n_rows) :
(size_t) params.Get<int>("subspace_dim");
MultipleRandomDimensionSelect mrds(randomDims);
Log::Info << "Training random forest with " << numTrees << " trees..."
<< endl;
const size_t numClasses = arma::max(labels) + 1;
// Train the model.
rfModel->rf.Train(data, labels, numClasses, numTrees, minimumLeafSize,
minimumGainSplit, maxDepth, params.Has("warm_start"), mrds);
timers.Stop("rf_training");
// Did we want training accuracy?
if (params.Has("print_training_accuracy"))
{
timers.Start("rf_prediction");
arma::Row<size_t> predictions;
rfModel->rf.Classify(data, predictions);
const size_t correct = arma::accu(predictions == labels);
Log::Info << correct << " of " << labels.n_elem << " correct on training"
<< " set (" << (double(correct) / double(labels.n_elem) * 100) << ")."
<< endl;
timers.Stop("rf_prediction");
}
}
if (params.Has("test"))
{
arma::mat testData = std::move(params.Get<arma::mat>("test"));
timers.Start("rf_prediction");
// Get predictions and probabilities.
arma::Row<size_t> predictions;
arma::mat probabilities;
rfModel->rf.Classify(testData, predictions, probabilities);
// Did we want to calculate test accuracy?
if (params.Has("test_labels"))
{
arma::Row<size_t> testLabels =
std::move(params.Get<arma::Row<size_t>>("test_labels"));
const size_t correct = arma::accu(predictions == testLabels);
Log::Info << correct << " of " << testLabels.n_elem << " correct on test"
<< " set (" << (double(correct) / double(testLabels.n_elem) * 100)
<< ")." << endl;
timers.Stop("rf_prediction");
}
// Save the outputs.
params.Get<arma::mat>("probabilities") = std::move(probabilities);
params.Get<arma::Row<size_t>>("predictions") = std::move(predictions);
}
// Save the output model.
params.Get<RandomForestModel*>("output_model") = rfModel;
}
|
#include"../localedef.h"
namespace fast_io_i18n
{
namespace
{
inline constexpr std::size_t numeric_grouping_storage[]{3};
inline constexpr lc_all lc_all_global{.identification={.title=tsc("Furlan locale for Italy"),.source=tsc("fast_io"),.address=tsc("https://github.com/expnkx/fast_io"),.contact=tsc("Pablo Saratxaga\t\t;\t\tfast_io"),.email=tsc("pablo@mandrakesoft.com;euloanty@live.com"),.tel=tsc(""),.fax=tsc(""),.language=tsc("Friulian"),.territory=tsc("Italy"),.revision=tsc("0.3"),.date=tsc("2004-04-26")},.monetary={.int_curr_symbol=tsc("EUR "),.currency_symbol=tsc("€"),.mon_decimal_point=tsc(","),.mon_thousands_sep=tsc("."),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(""),.negative_sign=tsc("-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(","),.thousands_sep=tsc("."),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc("Dom"),tsc("Lun"),tsc("Mar"),tsc("Mie"),tsc("Joi"),tsc("Vin"),tsc("Sab")},.day={tsc("Domenie"),tsc("Lunis"),tsc("Martars"),tsc("Miercus"),tsc("Joibe"),tsc("Vinars"),tsc("Sabide")},.abmon={tsc("Zen"),tsc("Fev"),tsc("Mar"),tsc("Avr"),tsc("Mai"),tsc("Jug"),tsc("Lui"),tsc("Avo"),tsc("Set"),tsc("Otu"),tsc("Nov"),tsc("Dic")},.mon={tsc("Zenâr"),tsc("Fevrâr"),tsc("Març"),tsc("Avrîl"),tsc("Mai"),tsc("Jugn"),tsc("Lui"),tsc("Avost"),tsc("Setembar"),tsc("Otubar"),tsc("Novembar"),tsc("Dicembar")},.d_t_fmt=tsc("%a %d %b %Y %T"),.d_fmt=tsc("%d. %m. %y"),.t_fmt=tsc("%T"),.t_fmt_ampm=tsc(""),.date_fmt=tsc("%a %d %b %Y %T %Z"),.am_pm={tsc(""),tsc("")},.week={7,19971130,4},.first_weekday=2},.messages={.yesexpr=tsc("^[+1sSjJoOyY]"),.noexpr=tsc("^[-0nN]"),.yesstr=tsc("sì"),.nostr=tsc("no")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc("+%c %a %l"),.int_select=tsc("00"),.int_prefix=tsc("39")},.name={.name_fmt=tsc("%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc("%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc("Italie"),.country_ab2=tsc("IT"),.country_ab3=tsc("ITA"),.country_num=380,.country_car=tsc("I"),.country_isbn=tsc("978-88,979-12"),.lang_name=tsc("furlan"),.lang_term=tsc("fur")},.measurement={.measurement=1}};
inline constexpr wlc_all wlc_all_global{.identification={.title=tsc(L"Furlan locale for Italy"),.source=tsc(L"fast_io"),.address=tsc(L"https://github.com/expnkx/fast_io"),.contact=tsc(L"Pablo Saratxaga\t\t;\t\tfast_io"),.email=tsc(L"pablo@mandrakesoft.com;euloanty@live.com"),.tel=tsc(L""),.fax=tsc(L""),.language=tsc(L"Friulian"),.territory=tsc(L"Italy"),.revision=tsc(L"0.3"),.date=tsc(L"2004-04-26")},.monetary={.int_curr_symbol=tsc(L"EUR "),.currency_symbol=tsc(L"€"),.mon_decimal_point=tsc(L","),.mon_thousands_sep=tsc(L"."),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(L""),.negative_sign=tsc(L"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(L","),.thousands_sep=tsc(L"."),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(L"Dom"),tsc(L"Lun"),tsc(L"Mar"),tsc(L"Mie"),tsc(L"Joi"),tsc(L"Vin"),tsc(L"Sab")},.day={tsc(L"Domenie"),tsc(L"Lunis"),tsc(L"Martars"),tsc(L"Miercus"),tsc(L"Joibe"),tsc(L"Vinars"),tsc(L"Sabide")},.abmon={tsc(L"Zen"),tsc(L"Fev"),tsc(L"Mar"),tsc(L"Avr"),tsc(L"Mai"),tsc(L"Jug"),tsc(L"Lui"),tsc(L"Avo"),tsc(L"Set"),tsc(L"Otu"),tsc(L"Nov"),tsc(L"Dic")},.mon={tsc(L"Zenâr"),tsc(L"Fevrâr"),tsc(L"Març"),tsc(L"Avrîl"),tsc(L"Mai"),tsc(L"Jugn"),tsc(L"Lui"),tsc(L"Avost"),tsc(L"Setembar"),tsc(L"Otubar"),tsc(L"Novembar"),tsc(L"Dicembar")},.d_t_fmt=tsc(L"%a %d %b %Y %T"),.d_fmt=tsc(L"%d. %m. %y"),.t_fmt=tsc(L"%T"),.t_fmt_ampm=tsc(L""),.date_fmt=tsc(L"%a %d %b %Y %T %Z"),.am_pm={tsc(L""),tsc(L"")},.week={7,19971130,4},.first_weekday=2},.messages={.yesexpr=tsc(L"^[+1sSjJoOyY]"),.noexpr=tsc(L"^[-0nN]"),.yesstr=tsc(L"sì"),.nostr=tsc(L"no")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(L"+%c %a %l"),.int_select=tsc(L"00"),.int_prefix=tsc(L"39")},.name={.name_fmt=tsc(L"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(L"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(L"Italie"),.country_ab2=tsc(L"IT"),.country_ab3=tsc(L"ITA"),.country_num=380,.country_car=tsc(L"I"),.country_isbn=tsc(L"978-88,979-12"),.lang_name=tsc(L"furlan"),.lang_term=tsc(L"fur")},.measurement={.measurement=1}};
inline constexpr u8lc_all u8lc_all_global{.identification={.title=tsc(u8"Furlan locale for Italy"),.source=tsc(u8"fast_io"),.address=tsc(u8"https://github.com/expnkx/fast_io"),.contact=tsc(u8"Pablo Saratxaga\t\t;\t\tfast_io"),.email=tsc(u8"pablo@mandrakesoft.com;euloanty@live.com"),.tel=tsc(u8""),.fax=tsc(u8""),.language=tsc(u8"Friulian"),.territory=tsc(u8"Italy"),.revision=tsc(u8"0.3"),.date=tsc(u8"2004-04-26")},.monetary={.int_curr_symbol=tsc(u8"EUR "),.currency_symbol=tsc(u8"€"),.mon_decimal_point=tsc(u8","),.mon_thousands_sep=tsc(u8"."),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(u8""),.negative_sign=tsc(u8"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u8","),.thousands_sep=tsc(u8"."),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(u8"Dom"),tsc(u8"Lun"),tsc(u8"Mar"),tsc(u8"Mie"),tsc(u8"Joi"),tsc(u8"Vin"),tsc(u8"Sab")},.day={tsc(u8"Domenie"),tsc(u8"Lunis"),tsc(u8"Martars"),tsc(u8"Miercus"),tsc(u8"Joibe"),tsc(u8"Vinars"),tsc(u8"Sabide")},.abmon={tsc(u8"Zen"),tsc(u8"Fev"),tsc(u8"Mar"),tsc(u8"Avr"),tsc(u8"Mai"),tsc(u8"Jug"),tsc(u8"Lui"),tsc(u8"Avo"),tsc(u8"Set"),tsc(u8"Otu"),tsc(u8"Nov"),tsc(u8"Dic")},.mon={tsc(u8"Zenâr"),tsc(u8"Fevrâr"),tsc(u8"Març"),tsc(u8"Avrîl"),tsc(u8"Mai"),tsc(u8"Jugn"),tsc(u8"Lui"),tsc(u8"Avost"),tsc(u8"Setembar"),tsc(u8"Otubar"),tsc(u8"Novembar"),tsc(u8"Dicembar")},.d_t_fmt=tsc(u8"%a %d %b %Y %T"),.d_fmt=tsc(u8"%d. %m. %y"),.t_fmt=tsc(u8"%T"),.t_fmt_ampm=tsc(u8""),.date_fmt=tsc(u8"%a %d %b %Y %T %Z"),.am_pm={tsc(u8""),tsc(u8"")},.week={7,19971130,4},.first_weekday=2},.messages={.yesexpr=tsc(u8"^[+1sSjJoOyY]"),.noexpr=tsc(u8"^[-0nN]"),.yesstr=tsc(u8"sì"),.nostr=tsc(u8"no")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u8"+%c %a %l"),.int_select=tsc(u8"00"),.int_prefix=tsc(u8"39")},.name={.name_fmt=tsc(u8"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(u8"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(u8"Italie"),.country_ab2=tsc(u8"IT"),.country_ab3=tsc(u8"ITA"),.country_num=380,.country_car=tsc(u8"I"),.country_isbn=tsc(u8"978-88,979-12"),.lang_name=tsc(u8"furlan"),.lang_term=tsc(u8"fur")},.measurement={.measurement=1}};
inline constexpr u16lc_all u16lc_all_global{.identification={.title=tsc(u"Furlan locale for Italy"),.source=tsc(u"fast_io"),.address=tsc(u"https://github.com/expnkx/fast_io"),.contact=tsc(u"Pablo Saratxaga\t\t;\t\tfast_io"),.email=tsc(u"pablo@mandrakesoft.com;euloanty@live.com"),.tel=tsc(u""),.fax=tsc(u""),.language=tsc(u"Friulian"),.territory=tsc(u"Italy"),.revision=tsc(u"0.3"),.date=tsc(u"2004-04-26")},.monetary={.int_curr_symbol=tsc(u"EUR "),.currency_symbol=tsc(u"€"),.mon_decimal_point=tsc(u","),.mon_thousands_sep=tsc(u"."),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(u""),.negative_sign=tsc(u"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u","),.thousands_sep=tsc(u"."),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(u"Dom"),tsc(u"Lun"),tsc(u"Mar"),tsc(u"Mie"),tsc(u"Joi"),tsc(u"Vin"),tsc(u"Sab")},.day={tsc(u"Domenie"),tsc(u"Lunis"),tsc(u"Martars"),tsc(u"Miercus"),tsc(u"Joibe"),tsc(u"Vinars"),tsc(u"Sabide")},.abmon={tsc(u"Zen"),tsc(u"Fev"),tsc(u"Mar"),tsc(u"Avr"),tsc(u"Mai"),tsc(u"Jug"),tsc(u"Lui"),tsc(u"Avo"),tsc(u"Set"),tsc(u"Otu"),tsc(u"Nov"),tsc(u"Dic")},.mon={tsc(u"Zenâr"),tsc(u"Fevrâr"),tsc(u"Març"),tsc(u"Avrîl"),tsc(u"Mai"),tsc(u"Jugn"),tsc(u"Lui"),tsc(u"Avost"),tsc(u"Setembar"),tsc(u"Otubar"),tsc(u"Novembar"),tsc(u"Dicembar")},.d_t_fmt=tsc(u"%a %d %b %Y %T"),.d_fmt=tsc(u"%d. %m. %y"),.t_fmt=tsc(u"%T"),.t_fmt_ampm=tsc(u""),.date_fmt=tsc(u"%a %d %b %Y %T %Z"),.am_pm={tsc(u""),tsc(u"")},.week={7,19971130,4},.first_weekday=2},.messages={.yesexpr=tsc(u"^[+1sSjJoOyY]"),.noexpr=tsc(u"^[-0nN]"),.yesstr=tsc(u"sì"),.nostr=tsc(u"no")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u"+%c %a %l"),.int_select=tsc(u"00"),.int_prefix=tsc(u"39")},.name={.name_fmt=tsc(u"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(u"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(u"Italie"),.country_ab2=tsc(u"IT"),.country_ab3=tsc(u"ITA"),.country_num=380,.country_car=tsc(u"I"),.country_isbn=tsc(u"978-88,979-12"),.lang_name=tsc(u"furlan"),.lang_term=tsc(u"fur")},.measurement={.measurement=1}};
inline constexpr u32lc_all u32lc_all_global{.identification={.title=tsc(U"Furlan locale for Italy"),.source=tsc(U"fast_io"),.address=tsc(U"https://github.com/expnkx/fast_io"),.contact=tsc(U"Pablo Saratxaga\t\t;\t\tfast_io"),.email=tsc(U"pablo@mandrakesoft.com;euloanty@live.com"),.tel=tsc(U""),.fax=tsc(U""),.language=tsc(U"Friulian"),.territory=tsc(U"Italy"),.revision=tsc(U"0.3"),.date=tsc(U"2004-04-26")},.monetary={.int_curr_symbol=tsc(U"EUR "),.currency_symbol=tsc(U"€"),.mon_decimal_point=tsc(U","),.mon_thousands_sep=tsc(U"."),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(U""),.negative_sign=tsc(U"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(U","),.thousands_sep=tsc(U"."),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(U"Dom"),tsc(U"Lun"),tsc(U"Mar"),tsc(U"Mie"),tsc(U"Joi"),tsc(U"Vin"),tsc(U"Sab")},.day={tsc(U"Domenie"),tsc(U"Lunis"),tsc(U"Martars"),tsc(U"Miercus"),tsc(U"Joibe"),tsc(U"Vinars"),tsc(U"Sabide")},.abmon={tsc(U"Zen"),tsc(U"Fev"),tsc(U"Mar"),tsc(U"Avr"),tsc(U"Mai"),tsc(U"Jug"),tsc(U"Lui"),tsc(U"Avo"),tsc(U"Set"),tsc(U"Otu"),tsc(U"Nov"),tsc(U"Dic")},.mon={tsc(U"Zenâr"),tsc(U"Fevrâr"),tsc(U"Març"),tsc(U"Avrîl"),tsc(U"Mai"),tsc(U"Jugn"),tsc(U"Lui"),tsc(U"Avost"),tsc(U"Setembar"),tsc(U"Otubar"),tsc(U"Novembar"),tsc(U"Dicembar")},.d_t_fmt=tsc(U"%a %d %b %Y %T"),.d_fmt=tsc(U"%d. %m. %y"),.t_fmt=tsc(U"%T"),.t_fmt_ampm=tsc(U""),.date_fmt=tsc(U"%a %d %b %Y %T %Z"),.am_pm={tsc(U""),tsc(U"")},.week={7,19971130,4},.first_weekday=2},.messages={.yesexpr=tsc(U"^[+1sSjJoOyY]"),.noexpr=tsc(U"^[-0nN]"),.yesstr=tsc(U"sì"),.nostr=tsc(U"no")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(U"+%c %a %l"),.int_select=tsc(U"00"),.int_prefix=tsc(U"39")},.name={.name_fmt=tsc(U"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(U"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(U"Italie"),.country_ab2=tsc(U"IT"),.country_ab3=tsc(U"ITA"),.country_num=380,.country_car=tsc(U"I"),.country_isbn=tsc(U"978-88,979-12"),.lang_name=tsc(U"furlan"),.lang_term=tsc(U"fur")},.measurement={.measurement=1}};
}
}
#include"../main.h"
|
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <time.h>
struct Card
{
// a card is defined in the datatype of struct
std::string displayvalue;
std::string actualvalue;
int frequency;
};
class Player {
private:
void replenish (int letterasciiv)
{
// this is the method that changes the card in player hands
// it changes the letter form a-g to position values in vector , then does the swap
this-> discardIndex = abs(97-letterasciiv);
//Its takes the value of the discardlist on which it wants to swap in and stores it in a temp variable
// then takes the card he wants to replace in another variable
// then swap them
Card Toswapcad = discardlist[this->takeFrom];
Card Togocard = this->hand[discardIndex]; // set the card to pick the one user does not want from the card
Player::discardlist[selfIndex] = Togocard;
this->hand[discardIndex] = Toswapcad;
std::cout << std::endl;
std::cout << " "<< "Player " << this->selfIndex << " gave Player 1 " << Togocard.actualvalue << std::endl;
}
protected:
static Card discardlist[5];
// the default is that of the player
int selfIndex = 0; //index within player vector, starting with 0 for the human
int takeFrom = 4; //player supplying new Card
int discardIndex; //position within hand of card being discarded
std::vector<Card> hand;
Card defaultcard = {"z","4"};
//Card discard = hand[discardIndex]; //card being discarded
public:
static void displaycl();
//player() = default;
Player()
{
for(int k = 0;k<7;k++)
{
Card defaultcardx = {"z","4",0};
this->hand.push_back(defaultcardx);
this->showcards();
}
}
Player(std::vector<Card> topickcard,int begin)
{
//constructor take the vector full of randomized cards and have an offset to start from so that it does not take a card
// the same card as the next player , the cards will be randomized then distributed lineraly . For example player one will
// take card from 0-6, player 2 will take from 7 - 13 and so on
for(int k = 0;k<7;k++)
{
this->hand.push_back(topickcard[k+begin]);
//std::cout<< "yeah";
}
}
static void chnagedisplaycard(Card exa,int k)
{
// THIS changes the discard list cards incase the card is being passed around too much , it is also used to
//set default of cards
Player::discardlist[0]=exa;
Player::discardlist[1]=exa;
Player::discardlist[2]=exa;
Player::discardlist[3]=exa;
Player::discardlist[4]=exa;
}
void changecardvalue(Card h,int indexo)
{
// this is a function that is used to debug
this->hand[indexo] = h;
}
bool everythingequal()
{
std::string ku = this->hand[0].displayvalue;
bool result = true;
for(int k = 0;k<7;k++)
{
if(this->hand[k].displayvalue!=ku)
{
result = false;
break;
}
}
return result;
}
void showcards()
{
for(int i = 0;i<7;i++)
{
std::cout << " "<<this->hand[i].actualvalue << " ";
}
std::cout << std::endl;
for(int i = 0;i<7;i++)
{
char a = i+97;
std::cout << " " << a << " " ;
}
std::cout << std::endl;
}
std::vector<Card> getcopyofcurrentcards()
{
return hand;
}
virtual void chooseDiscard(int decimaasciivalue)
{
// this is the method that changes
//void replenish( );
// user can only input from a - g
// this takes the char value from the user
this->replenish(decimaasciivalue);
}
};
class Autoplayer : public Player {
private:
static void processchangeofcard()
{
// THIS is the decision maker that makes the decision of wether to change the call
std::cout << "life" << std::endl;
}
void getthemaximumval()
{
}
public:
// this sets the index for the auto player
// it also sets the take from the auto player
// it sets the take from to previous index precidng it .
// FOR example index 3 to 2
Autoplayer()
{
// The auto player should never ever be called by the default constructor
}
Autoplayer(std::vector<Card> topickcardu,int beginy,int indexi) : Player(topickcardu,beginy)
{
this->selfIndex = indexi;
this->takeFrom = this->selfIndex-1;
//constructor take the vector full of randomized cards and have an offset to start from so that it does not take a card
// the same card as the next player , the cards will be randomized then distributed lineraly . For example player one will
// take card from 0-6, player 2 will take from 7 - 13 and so on
}
int mapc(Card tempc)
{
// this is a function that transform cards to integers so the lowest can be counted by using frquency
// think of it as a number id for the card ;
if(tempc.displayvalue== "S")
{
return 0;
}
else if(tempc.displayvalue=="H")
{
return 1;
}
else if(tempc.displayvalue=="D")
{
return 2;
}
else
{
return 3;
}
}
std::string unpac(int k)
{
// this is a function that integers to cards
// think of it as a number id for the card ;
if(k==0)
{
return "S";
}
else if(k==1)
{
return "H";
}
else if(k==2)
{
return "D";
}
else
{
return "Q";
}
}
std::string getlowest(std::string namec)
{
// this functions does a systematic sort , it gives a group of CARDs or a card That have the lowest frequency
// this function returns vectors with the lowest frequency
//int lowestf = mapc(this->hand[0]);
int sf =0;
int hf = 0;
int df = 0;
int qf = 0;
for(int i = 0;i<7;i++)
{
if(mapc(this->hand[i])==0)
{
sf++;
}
else if(mapc(this->hand[i])==1)
{
hf++;
}
else if(mapc(this->hand[i])==2)
{
df++;
}
else
{
qf++;
}
}
std::vector<int> moblower = {sf,hf,df,qf};
int min = 6;
for(int k = 0;k<4;k++)
{
std::string g = unpac(k);
if((moblower[k] < min) && (moblower[k]!=0) && (g != namec))
{
min = moblower[k];
}
}
std::string result = "S";
if(sf==min)
{
return result;
}
if(hf==min)
{
result = "H";
return result;
}
if(df==min)
{
result = "D";
return result;
}
if(qf==min)
{
result = "Q";
return result;
}
}
int choosefrom(std::string facevofcard)
{
int index = 0;
for(int i = 0;i<7;i++)
{
if(this->hand[i].displayvalue == facevofcard)
{
index = i;
break;
}
}
return index;
}
void chooseDiscard(int k)
{
// this choses the cards that is going to be discarded
// it takes another form of the choosediscard in base class
// it takes the card available for autocard
// The method getlowest uses a simple method to choose the card that is about to be discarded
Card takein = Player::discardlist[this->takeFrom];
std::string getlowestfv = getlowest(takein.displayvalue);
this->discardIndex = choosefrom(getlowestfv);
Card togo = this->hand[discardIndex];
this->hand[this->discardIndex] = takein;
Player::discardlist[selfIndex] = togo;
int next = selfIndex+1;
if(next==5)
{
next =0;
}
std::cout << std::endl;
std::cout << " "<< "Player " << this->selfIndex << " gave Player " << next << " " << togo.actualvalue << std::endl;
//this->showcards();
}
};
// the static discardlist will be initially populated with the non card member
Card idefaultcard = {"z","0",0};
Card specialcard = {"Q","3",0};
Card aspc = {"U","8",0};
Card tte = {"R","2",0};
Card Player::discardlist[5] = {idefaultcard,aspc,tte,idefaultcard,specialcard};
void Player::displaycl()
{
// this is used for debugging to display the card on the discardlist
for(int k = 0;k<5;k++)
{
std::cout << Player::discardlist[k].displayvalue;
}
}
std::vector<Card> generatecards()
{
// this generates random positioned cards
// it uses the struct structure to define cards
// it gives cards from SPADES, HEARTS,D, AND Q . where it generates 13 for each category making ti 52
// each card type(spades , hearts etc having staus to them (king ,queek , jack and numbers) , where numbers are from 1-9 and ace)
std::vector<Card> gencard;
for(int j = 0;j<52;j++)
{
// 0 - 12 is for spade
int k = j/13;
int r = j%13;
std::string facevalue;
std::string statusvalue;
// this set the face value
if(k==0)
{
facevalue = "S";
}
else if(k == 1)
{
facevalue = "H";
}
else if(k == 2)
{
facevalue = "D";
}
else
{
facevalue = "Q";
}
if(r == 0)
{
statusvalue = "A";
}
else if(r>=1 && r<=9)
{
statusvalue = std::to_string(r);
}
else if(r==10)
{
statusvalue = "J";
}
else if(r==11)
{
statusvalue = "Q";
}
else if(r==12)
{
statusvalue = "K";
}
Card temp = {facevalue,facevalue+statusvalue,0};
gencard.push_back(temp);
}
return gencard;
}
void printplayershands(std::vector<Player *> playersx)
{
// This function takes in a a vector of pointers to Player objects so that the value can be printed
//
std::cout << std::endl;
for(int g=0;g<playersx.size();g++)
{
Player temp1 = * playersx[g];
std::vector<Card> tempcards = temp1.getcopyofcurrentcards();
std::cout << g << ": ";
for(int k = 0;k<7;k++)
{
std::cout << tempcards[k].actualvalue << " ";
}
std::cout << std::endl;
std::cout << std::endl;
}
}
int main()
{
// firs step generate cards
srand(time(NULL));
std::vector<Card> dealtcards = generatecards();
std::random_shuffle(dealtcards.begin(),dealtcards.end());
std::cout << dealtcards.size() <<std::endl;
Player user(dealtcards,0);
Autoplayer comp1(dealtcards,7,1);
Autoplayer comp2(dealtcards,14,2);
Autoplayer comp3(dealtcards,21,3);
Autoplayer comp4(dealtcards,28,4);
// this defaultcard available on the list;
int changeindex = 35;
Player::chnagedisplaycard(dealtcards[changeindex],0);
std::vector<Player *> players;
players.push_back(&user);
players.push_back(&comp1);
players.push_back(&comp2);
players.push_back(&comp3);
players.push_back(&comp4);
//user.chooseDiscard(5);
//std::cout << "changed" << std::endl;
//comp3.chooseDiscard();
//comp2.chooseDiscard();
//printplayershands(players);
int winner = 0;
while(true)
{
char userinput;
while(true)
{
std::cout << "your hand : " << std::endl;
std::cout << std::endl;
user.showcards();
std::cin >> userinput;
int decimaasciivalue = int(userinput);
if(!((decimaasciivalue>103) || (decimaasciivalue<97) ))
{
user.chooseDiscard(decimaasciivalue);
break;
}
else if(decimaasciivalue==63)
{
// print the values of the cards
printplayershands(players);
}
else
{
std::cout << "invalid choice" << std::endl;
}
}
comp1.chooseDiscard(1);
comp2.chooseDiscard(2);
comp3.chooseDiscard(3);
comp4.chooseDiscard(4);
if(user.everythingequal())
{
std::cout<<std::endl;
std::cout <<" "<<"Player 0 is winner " << std::endl;
winner++;
}
if(comp1.everythingequal())
{
std::cout<<std::endl;
std::cout <<" "<<"Player 1 is winner " << std::endl;
winner++;
}
if(comp2.everythingequal())
{
std::cout<<std::endl;
std::cout <<" "<<"Player 2 is winner " << std::endl;
winner++;
}
if(comp3.everythingequal())
{
std::cout<<std::endl;
std::cout <<" "<<"Player 3 is winner " << std::endl;
winner++;
}
if(comp4.everythingequal())
{
std::cout<<std::endl;
std::cout <<" "<<"Player 4 is winner " << std::endl;
winner++;
}
if(winner>0)
{
printplayershands(players);
break;
}
}
return 0;
}
|
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program 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.
*
* This program 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "GTWidget.h"
#include "GTMouseDriver.h"
#include <U2Core/AppContext.h>
#include <U2Gui/MainWindow.h>
#include <QtGui/QWidget>
#include <QtGui/QMainWindow>
#include <QtGui/qcombobox.h>
namespace U2 {
#define GT_CLASS_NAME "GTWidget"
#define GT_METHOD_NAME "click"
void GTWidget::click(U2OpStatus &os, QWidget *w, Qt::MouseButton mouseButton, QPoint p) {
GTGlobals::sleep(100);
GT_CHECK(w != NULL, "widget is NULL");
GT_CHECK(w->isEnabled() == true, "widget is not enabled");
if (p.isNull()) {
p = w->rect().center();
}
GTMouseDriver::moveTo(os, w->mapToGlobal(p));
GTMouseDriver::click(os, mouseButton);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "setFocus"
void GTWidget::setFocus(U2OpStatus &os, QWidget *w) {
GT_CHECK(w != NULL, "widget is NULL");
GTWidget::click(os, w);
GTGlobals::sleep(1000);
if(!qobject_cast<QComboBox*>(w)){
GT_CHECK(w->hasFocus(), "Can't set focus on widget");
}
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "findWidget"
QWidget* GTWidget::findWidget(U2OpStatus &os, const QString &widgetName, QWidget *parentWidget, const GTGlobals::FindOptions& options) {
if (parentWidget == NULL) {
parentWidget = AppContext::getMainWindow()->getQMainWindow();
}
QWidget* widget = parentWidget->findChild<QWidget*>(widgetName);
if (options.failIfNull) {
GT_CHECK_RESULT(widget != NULL, "Widget " + widgetName + " not found", NULL);
}
return widget;
}
#undef GT_METHOD_NAME
#undef GT_CLASS_NAME
} //namespace
|
#ifndef BOOST_METAPARSE_V1_ONE_OF_C_HPP
#define BOOST_METAPARSE_V1_ONE_OF_C_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.
// 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)
#include <boost/metaparse/v1/one_of.hpp>
#include <boost/metaparse/v1/lit_c.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/tuple/eat.hpp>
#include <climits>
namespace boost
{
namespace metaparse
{
namespace v1
{
#ifdef BOOST_NO_SCALAR_VALUE
# error BOOST_NO_SCALAR_VALUE already defined
#endif
#define BOOST_NO_SCALAR_VALUE LONG_MAX
template <
BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(
BOOST_METAPARSE_LIMIT_ONE_OF_SIZE,
long C,
BOOST_NO_SCALAR_VALUE
)
>
struct one_of_c;
#ifdef BOOST_METAPARSE_ONE_OF_C_LIT
# error BOOST_METAPARSE_ONE_OF_C_LIT already defined
#endif
#define BOOST_METAPARSE_ONE_OF_C_LIT(z, n, unused) lit_c<BOOST_PP_CAT(C, n)>
#ifdef BOOST_METAPARSE_ONE_OF_C_CASE
# error BOOST_METAPARSE_ONE_OF_C_CASE already defined
#endif
#define BOOST_METAPARSE_ONE_OF_C_CASE(z, n, unused) \
template <BOOST_PP_ENUM_PARAMS(n, long C)> \
struct \
one_of_c< \
BOOST_PP_ENUM_PARAMS(n, C) \
BOOST_PP_COMMA_IF(n) \
BOOST_PP_ENUM( \
BOOST_PP_SUB(BOOST_METAPARSE_LIMIT_ONE_OF_SIZE, n), \
BOOST_NO_SCALAR_VALUE BOOST_PP_TUPLE_EAT(3), \
~ \
) \
> : \
one_of< BOOST_PP_ENUM(n, BOOST_METAPARSE_ONE_OF_C_LIT, ~) > \
{};
BOOST_PP_REPEAT(
BOOST_METAPARSE_LIMIT_ONE_OF_SIZE,
BOOST_METAPARSE_ONE_OF_C_CASE,
~
)
#undef BOOST_METAPARSE_ONE_OF_C_CASE
#undef BOOST_METAPARSE_ONE_OF_C_LIT
#undef BOOST_NO_SCALAR_VALUE
}
}
}
#endif
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "MMFilesLogfileManager.h"
#include "ApplicationFeatures/PageSizeFeature.h"
#include "Basics/Exceptions.h"
#include "Basics/FileUtils.h"
#include "Basics/MutexLocker.h"
#include "Basics/ReadLocker.h"
#include "Basics/StringUtils.h"
#include "Basics/VelocyPackHelper.h"
#include "Basics/WriteLocker.h"
#include "Basics/files.h"
#include "Basics/hashes.h"
#include "Basics/memory-map.h"
#include "Cluster/ServerState.h"
#include "Logger/Logger.h"
#include "MMFiles/MMFilesAllocatorThread.h"
#include "MMFiles/MMFilesCollectorThread.h"
#include "MMFiles/MMFilesRemoverThread.h"
#include "MMFiles/MMFilesSynchronizerThread.h"
#include "MMFiles/MMFilesWalMarker.h"
#include "MMFiles/MMFilesWalRecoverState.h"
#include "MMFiles/MMFilesWalSlots.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/FlushFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/StorageEngine.h"
#include "Transaction/ManagerFeature.h"
#include "StorageEngine/TransactionState.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
// the logfile manager singleton
MMFilesLogfileManager* MMFilesLogfileManager::Instance = nullptr;
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
std::atomic<bool> MMFilesLogfileManager::SafeToUseInstance{ false };
#endif
// whether or not there was a SHUTDOWN file with a last tick at
// server start
int MMFilesLogfileManager::FoundLastTick = -1;
namespace {
// minimum value for --wal.throttle-when-pending
static constexpr uint64_t MinThrottleWhenPending() { return 1024 * 1024; }
// minimum value for --wal.sync-interval
static constexpr uint64_t MinSyncInterval() { return 5; }
// minimum value for --wal.logfile-size
static constexpr uint32_t MinFileSize() {
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
// this allows testing with smaller logfile-sizes
return 1 * 1024 * 1024;
#else
return 8 * 1024 * 1024;
#endif
}
// get the maximum size of a logfile entry
static constexpr uint32_t MaxEntrySize() {
return 2 << 30; // 2 GB
}
// minimum number of slots
static constexpr uint32_t MinSlots() { return 1024 * 8; }
// maximum number of slots
static constexpr uint32_t MaxSlots() { return 1024 * 1024 * 16; }
} // namespace
// create the logfile manager
MMFilesLogfileManager::MMFilesLogfileManager(application_features::ApplicationServer& server)
: ApplicationFeature(server, "MMFilesLogfileManager"),
_allowWrites(false), // start in read-only mode
_recoveryState(RecoveryState::BEFORE),
_recoveryTick(0),
_logfilesLock(),
_logfiles(),
_slots(nullptr),
_synchronizerThread(nullptr),
_allocatorThread(nullptr),
_collectorThread(nullptr),
_removerThread(nullptr),
_lastOpenedId(0),
_lastCollectedId(0),
_lastSealedId(0),
_shutdownFileLock(),
_droppedCollections(),
_droppedDatabases(),
_idLock(),
_writeThrottled(false),
_shutdown(0) {
TRI_ASSERT(!_allowWrites);
setOptional(true);
startsAfter("BasicsPhase");
startsAfter("Database");
startsAfter("EngineSelector");
startsAfter("MMFilesEngine");
startsAfter("SystemDatabase");
onlyEnabledWith("MMFilesEngine");
}
// destroy the logfile manager
MMFilesLogfileManager::~MMFilesLogfileManager() {
for (auto& it : _barriers) {
delete it.second;
}
_barriers.clear();
delete _slots;
for (auto& it : _logfiles) {
if (it.second != nullptr) {
delete it.second;
}
}
Instance = nullptr;
}
void MMFilesLogfileManager::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addSection(Section("wal", "Configure the WAL of the MMFiles engine",
"wal", false, false));
options->addOption("--wal.allow-oversize-entries",
"allow entries that are bigger than '--wal.logfile-size'",
new BooleanParameter(&_allowOversizeEntries),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
options->addOption(
"--wal.use-mlock",
"mlock WAL logfiles in memory (may require elevated privileges or "
"limits)",
new BooleanParameter(&_useMLock),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
options->addOption("--wal.directory", "logfile directory",
new StringParameter(&_directory));
options->addOption(
"--wal.historic-logfiles",
"maximum number of historic logfiles to keep after collection",
new UInt32Parameter(&_historicLogfiles));
options->addOption(
"--wal.ignore-logfile-errors",
"ignore logfile errors. this will read recoverable data from corrupted "
"logfiles but ignore any unrecoverable data",
new BooleanParameter(&_ignoreLogfileErrors));
options->addOption("--wal.ignore-recovery-errors",
"continue recovery even if re-applying operations fails",
new BooleanParameter(&_ignoreRecoveryErrors));
options->addOption("--wal.flush-timeout", "flush timeout (in milliseconds)",
new UInt64Parameter(&_flushTimeout),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
options->addOption("--wal.logfile-size", "size of each logfile (in bytes)",
new UInt32Parameter(&_filesize));
options->addOption("--wal.open-logfiles",
"maximum number of parallel open logfiles",
new UInt32Parameter(&_maxOpenLogfiles));
options->addOption("--wal.reserve-logfiles",
"maximum number of reserve logfiles to maintain",
new UInt32Parameter(&_reserveLogfiles));
options->addOption("--wal.slots", "number of logfile slots to use",
new UInt32Parameter(&_numberOfSlots),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
options->addOption(
"--wal.sync-interval",
"interval for automatic, non-requested disk syncs (in milliseconds)",
new UInt64Parameter(&_syncInterval));
options->addOption(
"--wal.throttle-when-pending",
"throttle writes when at least this many operations are waiting for "
"collection (set to 0 to deactivate write-throttling)",
new UInt64Parameter(&_throttleWhenPending),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
options->addOption(
"--wal.throttle-wait",
"maximum wait time per operation when write-throttled (in milliseconds)",
new UInt64Parameter(&_maxThrottleWait),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
}
void MMFilesLogfileManager::validateOptions(std::shared_ptr<options::ProgramOptions> options) {
if (_filesize < MinFileSize()) {
// minimum filesize per logfile
LOG_TOPIC("6a37e", FATAL, arangodb::Logger::ENGINES)
<< "invalid value for --wal.logfile-size. Please use a value of "
<< "at least " << MinFileSize();
FATAL_ERROR_EXIT();
}
if (_numberOfSlots < MinSlots() || _numberOfSlots > MaxSlots()) {
// invalid number of slots
LOG_TOPIC("973f8", FATAL, arangodb::Logger::ENGINES)
<< "invalid value for --wal.slots. Please use a value between "
<< MinSlots() << " and " << MaxSlots();
FATAL_ERROR_EXIT();
}
if (_throttleWhenPending > 0 && _throttleWhenPending < MinThrottleWhenPending()) {
LOG_TOPIC("1fb3f", FATAL, arangodb::Logger::ENGINES)
<< "invalid value for --wal.throttle-when-pending. Please use a "
<< "value of at least " << MinThrottleWhenPending();
FATAL_ERROR_EXIT();
}
if (_syncInterval < MinSyncInterval()) {
LOG_TOPIC("8811f", FATAL, arangodb::Logger::ENGINES)
<< "invalid value for --wal.sync-interval. Please use a value "
<< "of at least " << MinSyncInterval();
FATAL_ERROR_EXIT();
}
// sync interval is specified in milliseconds by the user, but internally
// we use microseconds
_syncInterval = _syncInterval * 1000;
}
void MMFilesLogfileManager::prepare() {
Instance = this;
FoundLastTick = 0; // initialize the last found tick value to "not found"
auto databasePath =
ApplicationServer::getFeature<DatabasePathFeature>("DatabasePath");
_databasePath = databasePath->directory();
_shutdownFile = shutdownFilename();
bool const shutdownFileExists = basics::FileUtils::exists(_shutdownFile);
if (shutdownFileExists) {
LOG_TOPIC("d50be", TRACE, arangodb::Logger::ENGINES) << "shutdown file found";
int res = readShutdownInfo();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("7c0cf", FATAL, arangodb::Logger::ENGINES)
<< "could not open shutdown file '" << _shutdownFile
<< "': " << TRI_errno_string(res);
FATAL_ERROR_EXIT();
}
} else {
LOG_TOPIC("fd46e", TRACE, arangodb::Logger::ENGINES) << "no shutdown file found";
}
}
void MMFilesLogfileManager::start() {
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
SafeToUseInstance = true;
#endif
// needs server initialized
size_t pageSize = PageSizeFeature::getPageSize();
_filesize = static_cast<uint32_t>(((_filesize + pageSize - 1) / pageSize) * pageSize);
if (_directory.empty()) {
// use global configuration variable
_directory = _databasePath;
// append "/journals"
if (_directory[_directory.size() - 1] != TRI_DIR_SEPARATOR_CHAR) {
// append a trailing slash to directory name
_directory.push_back(TRI_DIR_SEPARATOR_CHAR);
}
_directory.append("journals");
}
if (_directory.empty()) {
LOG_TOPIC("84854", FATAL, arangodb::Logger::ENGINES)
<< "no directory specified for WAL logfiles. Please use the "
<< "'--wal.directory' option";
FATAL_ERROR_EXIT();
}
if (_directory[_directory.size() - 1] != TRI_DIR_SEPARATOR_CHAR) {
// append a trailing slash to directory name
_directory.push_back(TRI_DIR_SEPARATOR_CHAR);
}
// initialize some objects
_slots = new MMFilesWalSlots(this, _numberOfSlots, 0);
_recoverState.reset(new MMFilesWalRecoverState(_ignoreRecoveryErrors, _recoveryTick));
TRI_ASSERT(!_allowWrites);
int res = inventory();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("3eabc", FATAL, arangodb::Logger::ENGINES)
<< "could not create WAL logfile inventory: " << TRI_errno_string(res);
FATAL_ERROR_EXIT();
}
res = inspectLogfiles();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("c3b68", FATAL, arangodb::Logger::ENGINES)
<< "could not inspect WAL logfiles: " << TRI_errno_string(res);
FATAL_ERROR_EXIT();
}
LOG_TOPIC("b7006", TRACE, arangodb::Logger::ENGINES)
<< "WAL logfile manager configuration: historic logfiles: " << _historicLogfiles
<< ", reserve logfiles: " << _reserveLogfiles
<< ", filesize: " << _filesize << ", sync interval: " << _syncInterval;
}
bool MMFilesLogfileManager::open() {
// note all failed transactions that we found plus the list
// of collections and databases that we can ignore
std::unordered_set<TRI_voc_tid_t> failedTransactions;
for (auto const& it : _recoverState->failedTransactions) {
failedTransactions.emplace(it.first);
}
transaction::ManagerFeature::manager()->registerFailedTransactions(failedTransactions);
_droppedDatabases = _recoverState->droppedDatabases;
_droppedCollections = _recoverState->droppedCollections;
{
// set every open logfile to a status of sealed
WRITE_LOCKER(writeLocker, _logfilesLock);
for (auto& it : _logfiles) {
MMFilesWalLogfile* logfile = it.second;
if (logfile == nullptr) {
continue;
}
MMFilesWalLogfile::StatusType status = logfile->status();
if (status == MMFilesWalLogfile::StatusType::OPEN) {
// set all logfiles to sealed status so they can be collected
// we don't care about the previous status here
logfile->forceStatus(MMFilesWalLogfile::StatusType::SEALED);
MUTEX_LOCKER(mutexLocker, _idLock);
if (logfile->id() > _lastSealedId) {
_lastSealedId = logfile->id();
}
}
}
}
// now start allocator and synchronizer
int res = startMMFilesAllocatorThread();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("51461", FATAL, arangodb::Logger::ENGINES)
<< "could not start WAL allocator thread: " << TRI_errno_string(res);
return false;
}
res = startMMFilesSynchronizerThread();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("d5d1f", FATAL, arangodb::Logger::ENGINES)
<< "could not start WAL synchronizer thread: " << TRI_errno_string(res);
return false;
}
// from now on, we allow writes to the logfile
allowWrites(true);
// explicitly abort any open transactions found in the logs
res = _recoverState->abortOpenTransactions();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("1ee72", FATAL, arangodb::Logger::ENGINES)
<< "could not abort open transactions: " << TRI_errno_string(res);
return false;
}
// remove all empty logfiles
_recoverState->removeEmptyLogfiles();
// now fill secondary indexes of all collections used in the recovery
_recoverState->fillIndexes();
// remove usage locks for databases and collections
_recoverState->releaseResources();
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
auto* engine = EngineSelectorFeature::ENGINE;
TRI_ASSERT(engine);
TRI_ASSERT(engine->recoveryTick() == _recoverState->lastTick);
#endif
// not needed anymore
_recoverState.reset();
// write the current state into the shutdown file
writeShutdownInfo(false);
// finished recovery
_recoveryState = RecoveryState::DONE;
res = startMMFilesCollectorThread();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("d856c", FATAL, arangodb::Logger::ENGINES)
<< "could not start WAL collector thread: " << TRI_errno_string(res);
return false;
}
TRI_ASSERT(_collectorThread != nullptr);
res = startMMFilesRemoverThread();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("6d3eb", FATAL, arangodb::Logger::ENGINES)
<< "could not start WAL remover thread: " << TRI_errno_string(res);
return false;
}
// tell the allocator that the recovery is over now
_allocatorThread->recoveryDone();
return true;
}
void MMFilesLogfileManager::beginShutdown() {
if (!isEnabled()) {
return;
}
throttleWhenPending(0); // deactivate write-throttling on shutdown
}
void MMFilesLogfileManager::stop() {
if (!isEnabled()) {
return;
}
// deactivate write-throttling (again) on shutdown in case it was set again
// after beginShutdown
throttleWhenPending(0);
}
void MMFilesLogfileManager::unprepare() {
if (!isEnabled()) {
return;
}
// deactivate write-throttling (again) on shutdown in case it was set again
// after beginShutdown
throttleWhenPending(0);
_shutdown = 1;
LOG_TOPIC("6e9ba", TRACE, arangodb::Logger::ENGINES) << "shutting down WAL";
// set WAL to read-only mode
allowWrites(false);
// notify slots that we're shutting down
_slots->shutdown();
// finalize allocator thread
// this prevents creating new (empty) WAL logfile once we flush
// the current logfile
stopMMFilesAllocatorThread();
if (_allocatorThread != nullptr) {
LOG_TOPIC("17e47", TRACE, arangodb::Logger::ENGINES) << "stopping allocator thread";
while (_allocatorThread->isRunning()) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
delete _allocatorThread;
_allocatorThread = nullptr;
}
// do a final flush at shutdown
if (!isInRecovery()) {
flush(true, true, false);
}
// stop other threads
LOG_TOPIC("84ed0", TRACE, arangodb::Logger::ENGINES)
<< "sending shutdown request to WAL threads";
stopMMFilesRemoverThread();
stopMMFilesCollectorThread();
stopMMFilesSynchronizerThread();
// physically destroy all threads
if (_removerThread != nullptr) {
LOG_TOPIC("89e81", TRACE, arangodb::Logger::ENGINES) << "stopping remover thread";
while (_removerThread->isRunning()) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
delete _removerThread;
_removerThread = nullptr;
}
{
WRITE_LOCKER(locker, _collectorThreadLock);
if (_collectorThread != nullptr) {
LOG_TOPIC("1e470", TRACE, arangodb::Logger::ENGINES)
<< "stopping collector thread";
_collectorThread->forceStop();
while (_collectorThread->isRunning()) {
locker.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
locker.lock();
}
delete _collectorThread;
_collectorThread = nullptr;
}
}
if (_synchronizerThread != nullptr) {
LOG_TOPIC("f4f93", TRACE, arangodb::Logger::ENGINES)
<< "stopping synchronizer thread";
while (_synchronizerThread->isRunning()) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
delete _synchronizerThread;
_synchronizerThread = nullptr;
}
// close all open logfiles
LOG_TOPIC("9b882", TRACE, arangodb::Logger::ENGINES) << "closing logfiles";
closeLogfiles();
TRI_IF_FAILURE("LogfileManagerStop") {
// intentionally kill the server
TRI_SegfaultDebugging("MMFilesLogfileManagerStop");
}
int res = writeShutdownInfo(true);
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC("41e44", ERR, arangodb::Logger::ENGINES)
<< "could not write WAL shutdown info: " << TRI_errno_string(res);
}
}
// registers a transaction
int MMFilesLogfileManager::registerTransaction(TRI_voc_tid_t transactionId,
bool isReadOnlyTransaction) {
auto lastCollectedId = _lastCollectedId.load();
auto lastSealedId = _lastSealedId.load();
TRI_IF_FAILURE("LogfileManagerRegisterTransactionOom") {
// intentionally fail here
return TRI_ERROR_OUT_OF_MEMORY;
}
TRI_ASSERT(lastCollectedId <= lastSealedId);
if (isReadOnlyTransaction) {
// in case this is a read-only transaction, we are sure that the transaction
// can only see committed data (as itself it will not write anything, and
// write transactions run exclusively). we thus can allow the WAL collector
// to already seal and collect logfiles. the only thing that needs to be
// ensured for read-only transactions is that a logfile does not get thrown
// away while the read-only transaction is ongoing
lastSealedId = 0;
}
try {
auto data = std::make_unique<MMFilesTransactionData>(lastCollectedId, lastSealedId);
transaction::ManagerFeature::manager()->registerTransaction(transactionId, std::move(data));
return TRI_ERROR_NO_ERROR;
} catch (...) {
return TRI_ERROR_OUT_OF_MEMORY;
}
}
// return the set of dropped collections
/// this is used during recovery and not used afterwards
std::unordered_set<TRI_voc_cid_t> MMFilesLogfileManager::getDroppedCollections() {
std::unordered_set<TRI_voc_cid_t> droppedCollections;
{
READ_LOCKER(readLocker, _logfilesLock);
droppedCollections = _droppedCollections;
}
return droppedCollections;
}
// return the set of dropped databases
/// this is used during recovery and not used afterwards
std::unordered_set<TRI_voc_tick_t> MMFilesLogfileManager::getDroppedDatabases() {
std::unordered_set<TRI_voc_tick_t> droppedDatabases;
{
READ_LOCKER(readLocker, _logfilesLock);
droppedDatabases = _droppedDatabases;
}
return droppedDatabases;
}
// whether or not it is currently allowed to create an additional
/// logfile
bool MMFilesLogfileManager::logfileCreationAllowed(uint32_t size) {
if (size + MMFilesDatafileHelper::JournalOverhead() > filesize()) {
// oversize entry. this is always allowed because otherwise everything would
// lock
return true;
}
if (_maxOpenLogfiles == 0) {
return true;
}
uint32_t numberOfLogfiles = 0;
// note: this information could also be cached instead of being recalculated
// every time
READ_LOCKER(readLocker, _logfilesLock);
for (auto it = _logfiles.begin(); it != _logfiles.end(); ++it) {
MMFilesWalLogfile* logfile = (*it).second;
TRI_ASSERT(logfile != nullptr);
if (logfile->status() == MMFilesWalLogfile::StatusType::OPEN ||
logfile->status() == MMFilesWalLogfile::StatusType::SEAL_REQUESTED) {
++numberOfLogfiles;
}
}
return (numberOfLogfiles <= _maxOpenLogfiles);
}
// whether or not there are reserve logfiles
bool MMFilesLogfileManager::hasReserveLogfiles() {
uint32_t numberOfLogfiles = 0;
// note: this information could also be cached instead of being recalculated
// every time
READ_LOCKER(readLocker, _logfilesLock);
// reverse-scan the logfiles map
for (auto it = _logfiles.rbegin(); it != _logfiles.rend(); ++it) {
MMFilesWalLogfile* logfile = (*it).second;
TRI_ASSERT(logfile != nullptr);
if (logfile->freeSize() > 0 && !logfile->isSealed()) {
if (++numberOfLogfiles >= reserveLogfiles()) {
return true;
}
}
}
return false;
}
// signal that a sync operation is required
void MMFilesLogfileManager::signalSync(bool waitForSync) {
_synchronizerThread->signalSync(waitForSync);
}
// allocate space in a logfile for later writing
MMFilesWalSlotInfo MMFilesLogfileManager::allocate(uint32_t size) {
TRI_ASSERT(size >= sizeof(MMFilesMarker));
if (!_allowWrites) {
// no writes allowed
return MMFilesWalSlotInfo(TRI_ERROR_ARANGO_READ_ONLY);
}
if (size > MaxEntrySize()) {
// entry is too big
return MMFilesWalSlotInfo(TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE);
}
if (size > _filesize && !_allowOversizeEntries) {
// entry is too big for a logfile
return MMFilesWalSlotInfo(TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE);
}
return _slots->nextUnused(size);
}
// allocate space in a logfile for later writing
MMFilesWalSlotInfo MMFilesLogfileManager::allocate(TRI_voc_tick_t databaseId,
TRI_voc_cid_t collectionId,
uint32_t size) {
TRI_ASSERT(size >= sizeof(MMFilesMarker));
if (!_allowWrites) {
// no writes allowed
return MMFilesWalSlotInfo(TRI_ERROR_ARANGO_READ_ONLY);
}
if (size > MaxEntrySize()) {
// entry is too big
return MMFilesWalSlotInfo(TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE);
}
if (size > _filesize && !_allowOversizeEntries) {
// entry is too big for a logfile
return MMFilesWalSlotInfo(TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE);
}
return _slots->nextUnused(databaseId, collectionId, size);
}
// write data into the logfile, using database id and collection id
// this is a convenience function that combines allocate, memcpy and finalize
MMFilesWalSlotInfoCopy MMFilesLogfileManager::allocateAndWrite(
TRI_voc_tick_t databaseId, TRI_voc_cid_t collectionId, MMFilesWalMarker const* marker,
bool wakeUpSynchronizer, bool waitForSyncRequested, bool waitUntilSyncDone) {
TRI_ASSERT(marker != nullptr);
MMFilesWalSlotInfo slotInfo = allocate(databaseId, collectionId, marker->size());
if (slotInfo.errorCode != TRI_ERROR_NO_ERROR) {
return MMFilesWalSlotInfoCopy(slotInfo.errorCode);
}
return writeSlot(slotInfo, marker, wakeUpSynchronizer, waitForSyncRequested, waitUntilSyncDone);
}
// write data into the logfile
// this is a convenience function that combines allocate, memcpy and finalize
MMFilesWalSlotInfoCopy MMFilesLogfileManager::allocateAndWrite(
MMFilesWalMarker const* marker, bool wakeUpSynchronizer,
bool waitForSyncRequested, bool waitUntilSyncDone) {
TRI_ASSERT(marker != nullptr);
MMFilesWalSlotInfo slotInfo = allocate(marker->size());
if (slotInfo.errorCode != TRI_ERROR_NO_ERROR) {
return MMFilesWalSlotInfoCopy(slotInfo.errorCode);
}
return writeSlot(slotInfo, marker, wakeUpSynchronizer, waitForSyncRequested, waitUntilSyncDone);
}
// write marker into the logfile
// this is a convenience function with less parameters
MMFilesWalSlotInfoCopy MMFilesLogfileManager::allocateAndWrite(MMFilesWalMarker const& marker,
bool waitForSync) {
return allocateAndWrite(&marker, true, waitForSync, waitForSync);
}
// memcpy the data into the WAL region and return the filled slot
// to the WAL logfile manager
MMFilesWalSlotInfoCopy MMFilesLogfileManager::writeSlot(MMFilesWalSlotInfo& slotInfo,
MMFilesWalMarker const* marker,
bool wakeUpSynchronizer,
bool waitForSyncRequested,
bool waitUntilSyncDone) {
TRI_ASSERT(slotInfo.slot != nullptr);
TRI_ASSERT(marker != nullptr);
try {
// write marker data into slot
marker->store(static_cast<char*>(slotInfo.slot->mem()));
slotInfo.slot->finalize(marker);
// we must copy the slotinfo because Slots::returnUsed() will set the
// internals of slotInfo.slot to 0 again
MMFilesWalSlotInfoCopy copy(slotInfo.slot);
int res = _slots->returnUsed(slotInfo, wakeUpSynchronizer,
waitForSyncRequested, waitUntilSyncDone);
if (res == TRI_ERROR_NO_ERROR) {
return copy;
}
return MMFilesWalSlotInfoCopy(res);
} catch (...) {
// if we don't return the slot we'll run into serious problems later
int res = _slots->returnUsed(slotInfo, false, false, false);
if (res != TRI_ERROR_NO_ERROR) {
return MMFilesWalSlotInfoCopy(res);
}
return MMFilesWalSlotInfoCopy(TRI_ERROR_INTERNAL);
}
}
// wait for the collector queue to get cleared for the given collection
int MMFilesLogfileManager::waitForCollectorQueue(TRI_voc_cid_t cid, double timeout) {
double const end = TRI_microtime() + timeout;
while (true) {
READ_LOCKER(locker, _collectorThreadLock);
if (_collectorThread == nullptr) {
break;
}
if (!_collectorThread->hasQueuedOperations(cid)) {
break;
}
// sleep without holding the lock
locker.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
if (TRI_microtime() > end) {
return TRI_ERROR_LOCKED;
}
}
return TRI_ERROR_NO_ERROR;
}
// finalize and seal the currently open logfile
// this is useful to ensure that any open writes up to this point have made
// it into a logfile
int MMFilesLogfileManager::flush(bool waitForSync, bool waitForCollector, bool writeShutdownFile,
double maxWaitTime, bool abortWaitOnShutdown) {
TRI_IF_FAILURE("LogfileManagerFlush") { return TRI_ERROR_NO_ERROR; }
TRI_ASSERT(!isInRecovery());
MMFilesWalLogfile::IdType lastOpenLogfileId;
MMFilesWalLogfile::IdType lastSealedLogfileId;
{
MUTEX_LOCKER(mutexLocker, _idLock);
lastOpenLogfileId = _lastOpenedId;
lastSealedLogfileId = _lastSealedId;
}
if (lastOpenLogfileId == 0) {
return TRI_ERROR_NO_ERROR;
}
LOG_TOPIC("3c773", TRACE, arangodb::Logger::REPLICATION)
<< "about to flush active WAL logfile. currentLogfileId: " << lastOpenLogfileId
<< ", waitForSync: " << waitForSync << ", waitForCollector: " << waitForCollector
<< ", last committed tick: " << _slots->lastCommittedTick();
int res = _slots->flush(waitForSync);
if (res != TRI_ERROR_NO_ERROR && res != TRI_ERROR_ARANGO_DATAFILE_EMPTY) {
LOG_TOPIC("d4cc6", ERR, arangodb::Logger::ENGINES)
<< "unexpected error in WAL flush request: " << TRI_errno_string(res);
return res;
}
if (waitForCollector) {
if (maxWaitTime < 0.0) {
// this means wait forever
maxWaitTime = 0.0;
}
if (_shutdown == 1) {
// limit wait time on shutdown somewhat
maxWaitTime = 120.0;
}
if (res == TRI_ERROR_NO_ERROR) {
// we need to wait for the collector...
LOG_TOPIC("d7042", TRACE, arangodb::Logger::ENGINES)
<< "entering waitForCollector with lastOpenLogfileId " << lastOpenLogfileId;
res = this->waitForCollector(lastOpenLogfileId, maxWaitTime, abortWaitOnShutdown);
if (res == TRI_ERROR_LOCK_TIMEOUT) {
LOG_TOPIC("f6b77", DEBUG, arangodb::Logger::ENGINES)
<< "got lock timeout when waiting for WAL flush. "
"lastOpenLogfileId: "
<< lastOpenLogfileId;
}
LOG_TOPIC("73165", TRACE, Logger::ENGINES)
<< "waitForCollector returned with res = " << res;
} else if (res == TRI_ERROR_ARANGO_DATAFILE_EMPTY) {
// current logfile is empty and cannot be collected
// we need to wait for the collector to collect the previously sealed
// datafile
if (lastSealedLogfileId > 0) {
res = this->waitForCollector(lastSealedLogfileId, maxWaitTime, abortWaitOnShutdown);
if (res == TRI_ERROR_LOCK_TIMEOUT) {
LOG_TOPIC("ca961", DEBUG, arangodb::Logger::ENGINES)
<< "got lock timeout when waiting for WAL flush. "
<< "lastSealedLogfileId: " << lastSealedLogfileId;
}
LOG_TOPIC("f5cce", TRACE, Logger::ENGINES)
<< "waitForCollector returned with res = " << res;
}
}
}
if (writeShutdownFile &&
(res == TRI_ERROR_NO_ERROR || res == TRI_ERROR_ARANGO_DATAFILE_EMPTY)) {
// update the file with the last tick, last sealed etc.
return writeShutdownInfo(false);
}
return res;
}
/// wait until all changes to the current logfile are synced
bool MMFilesLogfileManager::waitForSync(double maxWait) {
TRI_ASSERT(!isInRecovery());
double const end = TRI_microtime() + maxWait;
TRI_voc_tick_t lastAssignedTick = 0;
while (true) {
// fill the state
MMFilesLogfileManagerState state;
_slots->statistics(state.lastAssignedTick, state.lastCommittedTick,
state.lastCommittedDataTick, state.numEvents, state.numEventsSync);
if (lastAssignedTick == 0) {
// get last assigned tick only once
lastAssignedTick = state.lastAssignedTick;
}
// now compare last committed tick with first lastAssigned tick that we got
if (state.lastCommittedTick >= lastAssignedTick) {
// everything was already committed
return true;
}
// not everything was committed yet. wait a bit
std::this_thread::sleep_for(std::chrono::milliseconds(10));
if (TRI_microtime() >= end) {
// time's up!
return false;
}
}
}
// re-inserts a logfile back into the inventory only
void MMFilesLogfileManager::relinkLogfile(MMFilesWalLogfile* logfile) {
MMFilesWalLogfile::IdType const id = logfile->id();
WRITE_LOCKER(writeLocker, _logfilesLock);
_logfiles.emplace(id, logfile);
}
// removes logfiles that are allowed to be removed
bool MMFilesLogfileManager::removeLogfiles() {
int iterations = 0;
bool worked = false;
while (++iterations < 6) {
MMFilesWalLogfile* logfile = getRemovableLogfile();
if (logfile == nullptr) {
break;
}
removeLogfile(logfile);
worked = true;
}
return worked;
}
// sets the status of a logfile to open
void MMFilesLogfileManager::setLogfileOpen(MMFilesWalLogfile* logfile) {
TRI_ASSERT(logfile != nullptr);
WRITE_LOCKER(writeLocker, _logfilesLock);
logfile->setStatus(MMFilesWalLogfile::StatusType::OPEN);
}
// sets the status of a logfile to seal-requested
void MMFilesLogfileManager::setLogfileSealRequested(MMFilesWalLogfile* logfile) {
TRI_ASSERT(logfile != nullptr);
{
WRITE_LOCKER(writeLocker, _logfilesLock);
logfile->setStatus(MMFilesWalLogfile::StatusType::SEAL_REQUESTED);
}
signalSync(true);
}
// sets the status of a logfile to sealed
void MMFilesLogfileManager::setLogfileSealed(MMFilesWalLogfile* logfile) {
TRI_ASSERT(logfile != nullptr);
setLogfileSealed(logfile->id());
}
// sets the status of a logfile to sealed
void MMFilesLogfileManager::setLogfileSealed(MMFilesWalLogfile::IdType id) {
{
WRITE_LOCKER(writeLocker, _logfilesLock);
auto it = _logfiles.find(id);
if (it == _logfiles.end()) {
return;
}
(*it).second->setStatus(MMFilesWalLogfile::StatusType::SEALED);
}
{
MUTEX_LOCKER(mutexLocker, _idLock);
_lastSealedId = id;
}
}
// return the status of a logfile
MMFilesWalLogfile::StatusType MMFilesLogfileManager::getLogfileStatus(MMFilesWalLogfile::IdType id) {
READ_LOCKER(readLocker, _logfilesLock);
auto it = _logfiles.find(id);
if (it == _logfiles.end()) {
return MMFilesWalLogfile::StatusType::UNKNOWN;
}
return (*it).second->status();
}
// return the file descriptor of a logfile
int MMFilesLogfileManager::getLogfileDescriptor(MMFilesWalLogfile::IdType id) {
READ_LOCKER(readLocker, _logfilesLock);
auto it = _logfiles.find(id);
if (it == _logfiles.end()) {
// error
LOG_TOPIC("78579", ERR, arangodb::Logger::ENGINES) << "could not find logfile " << id;
return -1;
}
MMFilesWalLogfile* logfile = (*it).second;
TRI_ASSERT(logfile != nullptr);
return logfile->fd();
}
// get the current open region of a logfile
/// this uses the slots lock
void MMFilesLogfileManager::getActiveLogfileRegion(MMFilesWalLogfile* logfile,
char const*& begin, char const*& end) {
_slots->getActiveLogfileRegion(logfile, begin, end);
}
// garbage collect expired logfile barriers
void MMFilesLogfileManager::collectLogfileBarriers() {
auto now = TRI_microtime();
WRITE_LOCKER(barrierLock, _barriersLock);
for (auto it = _barriers.begin(); it != _barriers.end(); /* no hoisting */) {
auto logfileBarrier = (*it).second;
if (logfileBarrier->expires <= now) {
LOG_TOPIC("93059", TRACE, Logger::REPLICATION)
<< "garbage-collecting expired WAL logfile barrier " << logfileBarrier->id;
it = _barriers.erase(it);
delete logfileBarrier;
} else {
++it;
}
}
}
// drop barriers for a specific database
void MMFilesLogfileManager::dropLogfileBarriers(TRI_voc_tick_t databaseId) {
WRITE_LOCKER(barrierLock, _barriersLock);
for (auto it = _barriers.begin(); it != _barriers.end(); /* no hoisting */) {
auto logfileBarrier = (*it).second;
if (logfileBarrier->databaseId == databaseId) {
it = _barriers.erase(it);
delete logfileBarrier;
} else {
++it;
}
}
}
// returns a list of all logfile barrier ids
std::vector<TRI_voc_tick_t> MMFilesLogfileManager::getLogfileBarriers() {
std::vector<TRI_voc_tick_t> result;
{
READ_LOCKER(barrierLock, _barriersLock);
result.reserve(_barriers.size());
for (auto& it : _barriers) {
result.emplace_back(it.second->id);
}
}
return result;
}
// remove a specific logfile barrier
bool MMFilesLogfileManager::removeLogfileBarrier(TRI_voc_tick_t id) {
LogfileBarrier* logfileBarrier = nullptr;
{
WRITE_LOCKER(barrierLock, _barriersLock);
auto it = _barriers.find(id);
if (it == _barriers.end()) {
return false;
}
logfileBarrier = (*it).second;
_barriers.erase(it);
}
TRI_ASSERT(logfileBarrier != nullptr);
LOG_TOPIC("9ef77", DEBUG, Logger::REPLICATION)
<< "removing WAL logfile barrier " << logfileBarrier->id;
delete logfileBarrier;
return true;
}
// adds a barrier that prevents removal of logfiles
TRI_voc_tick_t MMFilesLogfileManager::addLogfileBarrier(TRI_voc_tick_t databaseId,
TRI_voc_tick_t minTick, double ttl) {
TRI_voc_tick_t id = TRI_NewTickServer();
double expires = TRI_microtime() + ttl;
auto logfileBarrier = std::make_unique<LogfileBarrier>(id, databaseId, expires, minTick);
LOG_TOPIC("4d442", DEBUG, Logger::REPLICATION)
<< "adding WAL logfile barrier " << logfileBarrier->id << ", minTick: " << minTick;
{
WRITE_LOCKER(barrierLock, _barriersLock);
_barriers.emplace(id, logfileBarrier.get());
}
logfileBarrier.release();
return id;
}
// extend the lifetime of a logfile barrier
bool MMFilesLogfileManager::extendLogfileBarrier(TRI_voc_tick_t id, double ttl,
TRI_voc_tick_t tick) {
WRITE_LOCKER(barrierLock, _barriersLock);
auto it = _barriers.find(id);
if (it == _barriers.end()) {
return false;
}
auto logfileBarrier = (*it).second;
logfileBarrier->expires = TRI_microtime() + ttl;
if (tick > 0 && tick > logfileBarrier->minTick) {
// patch tick
logfileBarrier->minTick = tick;
LOG_TOPIC("f24c0", TRACE, Logger::REPLICATION)
<< "extending WAL logfile barrier " << logfileBarrier->id
<< ", minTick: " << logfileBarrier->minTick;
}
return true;
}
// get minimum tick value from all logfile barriers
TRI_voc_tick_t MMFilesLogfileManager::getMinBarrierTick() {
TRI_voc_tick_t value = 0;
READ_LOCKER(barrierLock, _barriersLock);
for (auto const& it : _barriers) {
auto logfileBarrier = it.second;
LOG_TOPIC("353f3", TRACE, Logger::REPLICATION)
<< "server has WAL logfile barrier " << logfileBarrier->id
<< ", minTick: " << logfileBarrier->minTick;
if (value == 0) {
value = logfileBarrier->minTick;
} else {
value = (std::min)(value, logfileBarrier->minTick);
}
}
LOG_TOPIC("b11d2", TRACE, Logger::REPLICATION)
<< "min barrier tick is " << value << ", barriers: " << _barriers.size();
return value;
}
// get logfiles for a tick range
std::vector<MMFilesWalLogfile*> MMFilesLogfileManager::getLogfilesForTickRange(
TRI_voc_tick_t minTick, TRI_voc_tick_t maxTick, bool& minTickIncluded) {
std::vector<MMFilesWalLogfile*> temp;
std::vector<MMFilesWalLogfile*> matching;
minTickIncluded = false;
// we need a two step logfile qualification procedure
// this is to avoid holding the lock on _logfilesLock and then acquiring the
// mutex on the _slots. If we hold both locks, we might deadlock with other
// threads
{
READ_LOCKER(readLocker, _logfilesLock);
temp.reserve(_logfiles.size());
matching.reserve(_logfiles.size());
for (auto it = _logfiles.begin(); it != _logfiles.end(); ++it) {
MMFilesWalLogfile* logfile = (*it).second;
if (logfile == nullptr || logfile->status() == MMFilesWalLogfile::StatusType::EMPTY) {
continue;
}
// found a datafile
temp.emplace_back(logfile);
// mark it as being used so it isn't deleted
logfile->use();
}
}
// now go on without the lock
for (auto it = temp.begin(); it != temp.end(); ++it) {
MMFilesWalLogfile* logfile = (*it);
TRI_voc_tick_t logMin;
TRI_voc_tick_t logMax;
_slots->getActiveTickRange(logfile, logMin, logMax);
if (logMin <= minTick && logMin > 0) {
minTickIncluded = true;
}
if (minTick > logMax || maxTick < logMin) {
// datafile is older than requested range
// or: datafile is newer than requested range
// release the logfile, so it can be deleted
logfile->release();
continue;
}
// finally copy all qualifying logfiles into the result
matching.push_back(logfile);
}
// all qualifying locks are marked as used now
return matching;
}
// return logfiles for a tick range
void MMFilesLogfileManager::returnLogfiles(std::vector<MMFilesWalLogfile*> const& logfiles) {
for (auto& logfile : logfiles) {
logfile->release();
}
}
// get a logfile by id
MMFilesWalLogfile* MMFilesLogfileManager::getLogfile(MMFilesWalLogfile::IdType id) {
READ_LOCKER(readLocker, _logfilesLock);
auto it = _logfiles.find(id);
if (it != _logfiles.end()) {
return (*it).second;
}
return nullptr;
}
// get a logfile and its status by id
MMFilesWalLogfile* MMFilesLogfileManager::getLogfile(MMFilesWalLogfile::IdType id,
MMFilesWalLogfile::StatusType& status) {
READ_LOCKER(readLocker, _logfilesLock);
auto it = _logfiles.find(id);
if (it != _logfiles.end()) {
status = (*it).second->status();
return (*it).second;
}
status = MMFilesWalLogfile::StatusType::UNKNOWN;
return nullptr;
}
// get a logfile for writing. this may return nullptr
int MMFilesLogfileManager::getWriteableLogfile(uint32_t size,
MMFilesWalLogfile::StatusType& status,
MMFilesWalLogfile*& result) {
// always initialize the result
result = nullptr;
TRI_IF_FAILURE("LogfileManagerGetWriteableLogfile") {
// intentionally don't return a logfile
return TRI_ERROR_DEBUG;
}
size_t iterations = 0;
double const end = TRI_microtime() + (_flushTimeout / 1000.0);
while (true) {
{
WRITE_LOCKER(writeLocker, _logfilesLock);
auto it = _logfiles.begin();
while (it != _logfiles.end()) {
MMFilesWalLogfile* logfile = (*it).second;
TRI_ASSERT(logfile != nullptr);
if (logfile->isWriteable(size)) {
// found a logfile, update the status variable and return the logfile
{
// LOG_TOPIC("2f389", TRACE, arangodb::Logger::ENGINES) << "setting
// lastOpenedId " << logfile->id();
MUTEX_LOCKER(mutexLocker, _idLock);
_lastOpenedId = logfile->id();
}
result = logfile;
status = logfile->status();
return TRI_ERROR_NO_ERROR;
}
if (logfile->status() == MMFilesWalLogfile::StatusType::EMPTY &&
!logfile->isWriteable(size)) {
// we found an empty logfile, but the entry won't fit
// delete the logfile from the sequence of logfiles
_logfiles.erase(it++);
// and physically remove the file
// note: this will also delete the logfile object!
removeLogfile(logfile);
} else {
++it;
}
}
}
// signal & sleep outside the lock
if (++iterations % 10 == 1) {
_allocatorThread->signal(size);
}
int res = _allocatorThread->waitForResult(15000);
if (res != TRI_ERROR_LOCK_TIMEOUT && res != TRI_ERROR_NO_ERROR) {
TRI_ASSERT(result == nullptr);
// some error occurred
return res;
}
if (TRI_microtime() > end) {
// timeout
break;
}
}
TRI_ASSERT(result == nullptr);
LOG_TOPIC("2dacb", ERR, arangodb::Logger::ENGINES)
<< "unable to acquire writeable WAL logfile after " << _flushTimeout << " ms";
return TRI_ERROR_LOCK_TIMEOUT;
}
// get a logfile to collect. this may return nullptr
MMFilesWalLogfile* MMFilesLogfileManager::getCollectableLogfile() {
// iterate over all active readers and find their minimum used logfile id
MMFilesWalLogfile::IdType minId = UINT64_MAX;
LOG_TOPIC("f2032", DEBUG, Logger::ENGINES) << "getCollectableLogfile: called";
auto cb = [&minId](TRI_voc_tid_t, TransactionData const* data) {
MMFilesWalLogfile::IdType lastWrittenId =
static_cast<MMFilesTransactionData const*>(data)->lastSealedId;
if (lastWrittenId < minId && lastWrittenId != 0) {
minId = lastWrittenId;
}
};
// iterate over all active transactions and find their minimum used logfile id
transaction::ManagerFeature::manager()->iterateActiveTransactions(cb);
{
READ_LOCKER(readLocker, _logfilesLock);
StorageEngine* engine = EngineSelectorFeature::ENGINE;
TRI_voc_tick_t released = engine->releasedTick();
for (auto& it : _logfiles) {
auto logfile = it.second;
if (logfile == nullptr) {
continue;
}
if (logfile->id() <= minId && logfile->canBeCollected(released)) {
LOG_TOPIC("19526", DEBUG, Logger::ENGINES)
<< "getCollectableLogfile: found logfile id: " << logfile->id();
return logfile;
}
if (logfile->id() > minId) {
LOG_TOPIC("c2cb6", DEBUG, Logger::ENGINES)
<< "getCollectableLogfile: abort early1 " << logfile->id()
<< " minId: " << minId;
break;
}
if (!logfile->hasBeenReleased(released)) {
// abort early
LOG_TOPIC("92c06", DEBUG, Logger::ENGINES)
<< "getCollectableLogfile: abort early2 released: " << released;
break;
}
}
}
LOG_TOPIC("dbee0", DEBUG, Logger::ENGINES) << "getCollectableLogfile: "
<< "found no logfile to collect, minId: " << minId;
return nullptr;
}
// get a logfile to remove. this may return nullptr
/// if it returns a logfile, the logfile is removed from the list of available
/// logfiles
MMFilesWalLogfile* MMFilesLogfileManager::getRemovableLogfile() {
TRI_ASSERT(!isInRecovery());
// take all barriers into account
MMFilesWalLogfile::IdType const minBarrierTick = getMinBarrierTick();
MMFilesWalLogfile::IdType minId = UINT64_MAX;
// iterate over all active transactions and find their minimum used logfile id
auto cb = [&minId](TRI_voc_tid_t, TransactionData const* data) {
MMFilesWalLogfile::IdType lastCollectedId =
static_cast<MMFilesTransactionData const*>(data)->lastCollectedId;
if (lastCollectedId < minId && lastCollectedId != 0) {
minId = lastCollectedId;
}
};
transaction::ManagerFeature::manager()->iterateActiveTransactions(cb);
{
uint32_t numberOfLogfiles = 0;
uint32_t const minHistoricLogfiles = historicLogfiles();
MMFilesWalLogfile* first = nullptr;
WRITE_LOCKER(writeLocker, _logfilesLock);
for (auto& it : _logfiles) {
MMFilesWalLogfile* logfile = it.second;
// find the first logfile that can be safely removed
if (logfile == nullptr) {
continue;
}
if (logfile->id() <= minId && logfile->canBeRemoved() &&
(minBarrierTick == 0 || (logfile->df()->_tickMin < minBarrierTick &&
logfile->df()->_tickMax < minBarrierTick))) {
// only check those logfiles that are outside the ranges specified by
// barriers
if (first == nullptr) {
// note the oldest of the logfiles (_logfiles is a map, thus sorted)
first = logfile;
}
if (++numberOfLogfiles > minHistoricLogfiles) {
TRI_ASSERT(first != nullptr);
_logfiles.erase(first->id());
TRI_ASSERT(_logfiles.find(first->id()) == _logfiles.end());
return first;
}
}
}
}
return nullptr;
}
// increase the number of collect operations for a logfile
void MMFilesLogfileManager::increaseCollectQueueSize(MMFilesWalLogfile* logfile) {
logfile->increaseCollectQueueSize();
}
// decrease the number of collect operations for a logfile
void MMFilesLogfileManager::decreaseCollectQueueSize(MMFilesWalLogfile* logfile) {
logfile->decreaseCollectQueueSize();
}
// mark a file as being requested for collection
void MMFilesLogfileManager::setCollectionRequested(MMFilesWalLogfile* logfile) {
TRI_ASSERT(logfile != nullptr);
{
WRITE_LOCKER(writeLocker, _logfilesLock);
if (logfile->status() == MMFilesWalLogfile::StatusType::COLLECTION_REQUESTED) {
// the collector already asked for this file, but couldn't process it
// due to some exception
return;
}
logfile->setStatus(MMFilesWalLogfile::StatusType::COLLECTION_REQUESTED);
}
if (!isInRecovery()) {
// to start collection
READ_LOCKER(locker, _collectorThreadLock);
if (_collectorThread != nullptr) {
_collectorThread->signal();
}
}
}
// mark a file as being done with collection
void MMFilesLogfileManager::setCollectionDone(MMFilesWalLogfile* logfile) {
TRI_IF_FAILURE("setCollectionDone") { return; }
TRI_ASSERT(logfile != nullptr);
MMFilesWalLogfile::IdType id = logfile->id();
// LOG_TOPIC("b5d01", ERR, arangodb::Logger::ENGINES) << "setCollectionDone setting
// lastCollectedId to " << id
{
WRITE_LOCKER(writeLocker, _logfilesLock);
logfile->setStatus(MMFilesWalLogfile::StatusType::COLLECTED);
if (_useMLock) {
logfile->unlockFromMemory();
}
}
{
MUTEX_LOCKER(mutexLocker, _idLock);
_lastCollectedId = id;
}
if (!isInRecovery()) {
// to start removal of unneeded datafiles
{
READ_LOCKER(locker, _collectorThreadLock);
if (_collectorThread != nullptr) {
_collectorThread->signal();
}
}
writeShutdownInfo(false);
}
}
// force the status of a specific logfile
void MMFilesLogfileManager::forceStatus(MMFilesWalLogfile* logfile,
MMFilesWalLogfile::StatusType status) {
TRI_ASSERT(logfile != nullptr);
{
WRITE_LOCKER(writeLocker, _logfilesLock);
logfile->forceStatus(status);
}
}
// return the current state
MMFilesLogfileManagerState MMFilesLogfileManager::state() {
MMFilesLogfileManagerState state;
// now fill the state
while (true) {
_slots->statistics(state.lastAssignedTick, state.lastCommittedTick,
state.lastCommittedDataTick, state.numEvents, state.numEventsSync);
// check if lastCommittedTick is still 0. this will be the case directly
// after server start. in this case, we need to wait for the server to write
// and sync at least one WAL entry so the tick increases beyond 0
if (state.lastCommittedTick != 0) {
break;
}
// don't hang forever on shutdown
if (application_features::ApplicationServer::isStopping()) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
TRI_ASSERT(arangodb::ServerState::instance()->isCoordinator() ||
state.lastCommittedTick > 0);
state.timeString = utilities::timeString();
return state;
}
// return the current available logfile ranges
MMFilesLogfileManager::LogfileRanges MMFilesLogfileManager::ranges() {
LogfileRanges result;
READ_LOCKER(readLocker, _logfilesLock);
for (auto const& it : _logfiles) {
MMFilesWalLogfile* logfile = it.second;
if (logfile == nullptr) {
continue;
}
auto df = logfile->df();
if (df->_tickMin == 0 && df->_tickMax == 0) {
continue;
}
result.emplace_back(LogfileRange(it.first, logfile->filename(),
logfile->statusText(), df->_tickMin, df->_tickMax));
}
return result;
}
// get information about running transactions
std::tuple<size_t, MMFilesWalLogfile::IdType, MMFilesWalLogfile::IdType> MMFilesLogfileManager::runningTransactions() {
size_t count = 0;
MMFilesWalLogfile::IdType lastCollectedId = UINT64_MAX;
MMFilesWalLogfile::IdType lastSealedId = UINT64_MAX;
auto cb = [&count, &lastCollectedId,
&lastSealedId](TRI_voc_tid_t, TransactionData const* data) {
++count;
MMFilesWalLogfile::IdType value =
static_cast<MMFilesTransactionData const*>(data)->lastCollectedId;
if (value < lastCollectedId && value != 0) {
lastCollectedId = value;
}
value = static_cast<MMFilesTransactionData const*>(data)->lastSealedId;
if (value < lastSealedId && value != 0) {
lastSealedId = value;
}
};
// iterate over all active transactions
transaction::ManagerFeature::manager()->iterateActiveTransactions(cb);
return std::tuple<size_t, MMFilesWalLogfile::IdType, MMFilesWalLogfile::IdType>(
count, lastCollectedId, lastSealedId);
}
// remove a logfile in the file system
void MMFilesLogfileManager::removeLogfile(MMFilesWalLogfile* logfile) {
// old filename
MMFilesWalLogfile::IdType const id = logfile->id();
std::string const filename = logfileName(id);
LOG_TOPIC("fadc2", TRACE, arangodb::Logger::ENGINES) << "removing logfile '" << filename << "'";
// now close the logfile
delete logfile;
int res = TRI_ERROR_NO_ERROR;
// now physically remove the file
if (!basics::FileUtils::remove(filename, &res)) {
LOG_TOPIC("be385", ERR, arangodb::Logger::ENGINES) << "unable to remove logfile '" << filename
<< "': " << TRI_errno_string(res);
}
}
void MMFilesLogfileManager::waitForCollectorOnShutdown() {
READ_LOCKER(locker, _collectorThreadLock);
if (_collectorThread == nullptr) {
return;
}
if (!_collectorThread->hasQueuedOperations()) {
return;
}
_collectorThread->clearQueuedOperations();
}
// execute a callback during a phase in which the collector has nothing
// queued. This is used in the DatabaseManagerThread when dropping
// a database to avoid existence of ditches of type DOCUMENT.
bool MMFilesLogfileManager::executeWhileNothingQueued(std::function<void()> const& cb) {
READ_LOCKER(locker, _collectorThreadLock);
if (_collectorThread != nullptr) {
return _collectorThread->executeWhileNothingQueued(cb);
}
locker.unlock();
cb();
return true;
}
// wait until a specific logfile has been collected
int MMFilesLogfileManager::waitForCollector(MMFilesWalLogfile::IdType logfileId,
double maxWaitTime, bool abortWaitOnShutdown) {
if (maxWaitTime <= 0.0) {
maxWaitTime = 24.0 * 3600.0; // wait "forever"
}
LOG_TOPIC("0e003", TRACE, arangodb::Logger::ENGINES)
<< "waiting for collector thread to collect logfile " << logfileId;
// wait for the collector thread to finish the collection
double const end = TRI_microtime() + maxWaitTime;
while (true) {
if (_lastCollectedId.load() >= logfileId) {
return TRI_ERROR_NO_ERROR;
}
if (application_features::ApplicationServer::isStopping()) {
return TRI_ERROR_SHUTTING_DOWN;
}
READ_LOCKER(locker, _collectorThreadLock);
if (_collectorThread == nullptr) {
return TRI_ERROR_NO_ERROR;
}
int res = _collectorThread->waitForResult(50 * 1000);
locker.unlock();
LOG_TOPIC("2c5fe", DEBUG, arangodb::Logger::ENGINES)
<< "still waiting for collector. logfileId: " << logfileId
<< " lastCollected: " << _lastCollectedId.load() << ", result: " << res;
if (res != TRI_ERROR_LOCK_TIMEOUT && res != TRI_ERROR_NO_ERROR) {
// some error occurred
return res;
}
double const now = TRI_microtime();
if (now > end || !FlushFeature::isRunning()) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
// try again
}
LOG_TOPIC("6c07d", DEBUG, arangodb::Logger::ENGINES)
<< "going into lock timeout. having waited for logfile: " << logfileId
<< ", maxWaitTime: " << maxWaitTime;
logStatus();
if (application_features::ApplicationServer::isStopping()) {
return TRI_ERROR_SHUTTING_DOWN;
}
// waited for too long
return TRI_ERROR_LOCK_TIMEOUT;
}
void MMFilesLogfileManager::logStatus() {
LOG_TOPIC("a9666", DEBUG, arangodb::Logger::ENGINES)
<< "logfile manager status report: lastCollectedId: " << _lastCollectedId.load()
<< ", lastSealedId: " << _lastSealedId.load();
READ_LOCKER(locker, _logfilesLock);
for (auto logfile : _logfiles) {
LOG_TOPIC("b1d96", DEBUG, arangodb::Logger::ENGINES)
<< "- logfile " << logfile.second->id() << ", filename '"
<< logfile.second->filename() << "', status " << logfile.second->statusText();
}
}
// run the recovery procedure
// this is called after the logfiles have been scanned completely and
// recovery state has been build. additionally, all databases have been
// opened already so we can use collections
int MMFilesLogfileManager::runRecovery() {
TRI_ASSERT(!_allowWrites);
_recoveryState = RecoveryState::IN_PROGRESS;
if (!_recoverState->mustRecover()) {
// nothing to do
_recoveryTick = _recoverState->lastTick;
return TRI_ERROR_NO_ERROR;
}
if (_ignoreRecoveryErrors) {
LOG_TOPIC("0599d", INFO, arangodb::Logger::ENGINES)
<< "running WAL recovery (" << _recoverState->logfilesToProcess.size()
<< " logfiles), ignoring recovery errors";
} else {
LOG_TOPIC("b9b8e", INFO, arangodb::Logger::ENGINES)
<< "running WAL recovery (" << _recoverState->logfilesToProcess.size()
<< " logfiles)";
}
// now iterate over all logfiles that we found during recovery
// we can afford to iterate the files without _logfilesLock
// this is because all other threads competing for the lock are
// not active yet
{
int res = _recoverState->replayLogfiles();
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
}
if (_recoverState->errorCount == 0) {
LOG_TOPIC("87be8", INFO, arangodb::Logger::ENGINES)
<< "WAL recovery finished successfully";
} else {
LOG_TOPIC("a1de0", WARN, arangodb::Logger::ENGINES)
<< "WAL recovery finished, some errors ignored due to settings";
}
return TRI_ERROR_NO_ERROR;
}
// closes all logfiles
void MMFilesLogfileManager::closeLogfiles() {
WRITE_LOCKER(writeLocker, _logfilesLock);
for (auto& it : _logfiles) {
MMFilesWalLogfile* logfile = it.second;
if (logfile != nullptr) {
delete logfile;
}
}
_logfiles.clear();
}
// reads the shutdown information
int MMFilesLogfileManager::readShutdownInfo() {
TRI_ASSERT(!_shutdownFile.empty());
VPackBuilder builder;
try {
builder = arangodb::basics::VelocyPackHelper::velocyPackFromFile(_shutdownFile);
} catch (...) {
return TRI_ERROR_INTERNAL;
}
VPackSlice slice = builder.slice();
if (!slice.isObject()) {
return TRI_ERROR_INTERNAL;
}
uint64_t lastTick =
arangodb::basics::VelocyPackHelper::stringUInt64(slice.get("tick"));
TRI_UpdateTickServer(static_cast<TRI_voc_tick_t>(lastTick));
if (lastTick > 0) {
FoundLastTick = 1;
}
// read last assigned revision id to seed HLC value
uint64_t hlc =
arangodb::basics::VelocyPackHelper::stringUInt64(slice.get("hlc"));
TRI_HybridLogicalClock(static_cast<TRI_voc_tick_t>(hlc));
// read id of last collected logfile (maybe 0)
uint64_t lastCollectedId = arangodb::basics::VelocyPackHelper::stringUInt64(
slice.get("lastCollected"));
// read if of last sealed logfile (maybe 0)
uint64_t lastSealedId =
arangodb::basics::VelocyPackHelper::stringUInt64(slice.get("lastSealed"));
if (lastSealedId < lastCollectedId) {
// should not happen normally
lastSealedId = lastCollectedId;
}
// read last tick released to persistent external storage (maybe 0)
uint64_t released = arangodb::basics::VelocyPackHelper::stringUInt64(
slice.get("releasedTick"));
StorageEngine* engine = EngineSelectorFeature::ENGINE;
engine->releaseTick(released);
std::string const shutdownTime =
arangodb::basics::VelocyPackHelper::getStringValue(slice, "shutdownTime",
"");
if (shutdownTime.empty()) {
LOG_TOPIC("ee82e", TRACE, arangodb::Logger::ENGINES)
<< "no previous shutdown time found";
} else {
LOG_TOPIC("2f036", TRACE, arangodb::Logger::ENGINES)
<< "previous shutdown was at '" << shutdownTime << "'";
}
{
MUTEX_LOCKER(mutexLocker, _idLock);
_lastCollectedId = static_cast<MMFilesWalLogfile::IdType>(lastCollectedId);
_lastSealedId = static_cast<MMFilesWalLogfile::IdType>(lastSealedId);
LOG_TOPIC("38f13", TRACE, arangodb::Logger::ENGINES)
<< "initial values for WAL logfile manager: tick: " << lastTick
<< ", hlc: " << hlc << ", lastCollected: " << _lastCollectedId.load()
<< ", lastSealed: " << _lastSealedId.load();
}
return TRI_ERROR_NO_ERROR;
}
// writes the shutdown information
/// this function is called at shutdown and at every logfile flush request
int MMFilesLogfileManager::writeShutdownInfo(bool writeShutdownTime) {
TRI_IF_FAILURE("LogfileManagerWriteShutdown") { return TRI_ERROR_DEBUG; }
TRI_ASSERT(!_shutdownFile.empty());
try {
VPackBuilder builder;
builder.openObject();
// create local copies of the instance variables while holding the read lock
MMFilesWalLogfile::IdType lastCollectedId;
MMFilesWalLogfile::IdType lastSealedId;
{
MUTEX_LOCKER(mutexLocker, _idLock);
lastCollectedId = _lastCollectedId;
lastSealedId = _lastSealedId;
}
StorageEngine* engine = EngineSelectorFeature::ENGINE;
TRI_voc_tick_t released = engine->releasedTick();
builder.add("tick", VPackValue(basics::StringUtils::itoa(TRI_CurrentTickServer())));
builder.add("hlc", VPackValue(basics::StringUtils::itoa(TRI_HybridLogicalClock())));
builder.add("lastCollected", VPackValue(basics::StringUtils::itoa(lastCollectedId)));
builder.add("lastSealed", VPackValue(basics::StringUtils::itoa(lastSealedId)));
builder.add("releasedTick", VPackValue(basics::StringUtils::itoa(released)));
if (writeShutdownTime) {
std::string const t(utilities::timeString());
builder.add("shutdownTime", VPackValue(t));
}
builder.close();
bool ok;
{
// grab a lock so no two threads can write the shutdown info at the same
// time
MUTEX_LOCKER(mutexLocker, _shutdownFileLock);
ok = arangodb::basics::VelocyPackHelper::velocyPackToFile(_shutdownFile,
builder.slice(), true);
}
if (!ok) {
LOG_TOPIC("2eb4f", ERR, arangodb::Logger::ENGINES)
<< "unable to write WAL state file '" << _shutdownFile << "'";
return TRI_ERROR_CANNOT_WRITE_FILE;
}
} catch (...) {
LOG_TOPIC("09842", ERR, arangodb::Logger::ENGINES)
<< "unable to write WAL state file '" << _shutdownFile << "'";
return TRI_ERROR_OUT_OF_MEMORY;
}
return TRI_ERROR_NO_ERROR;
}
// start the synchronizer thread
int MMFilesLogfileManager::startMMFilesSynchronizerThread() {
_synchronizerThread = new MMFilesSynchronizerThread(this, _syncInterval);
if (!_synchronizerThread->start()) {
delete _synchronizerThread;
return TRI_ERROR_INTERNAL;
}
return TRI_ERROR_NO_ERROR;
}
// stop the synchronizer thread
void MMFilesLogfileManager::stopMMFilesSynchronizerThread() {
if (_synchronizerThread != nullptr) {
LOG_TOPIC("5dd5e", TRACE, arangodb::Logger::ENGINES)
<< "stopping WAL synchronizer thread";
_synchronizerThread->beginShutdown();
}
}
// start the allocator thread
int MMFilesLogfileManager::startMMFilesAllocatorThread() {
_allocatorThread = new MMFilesAllocatorThread(this);
if (!_allocatorThread->start()) {
delete _allocatorThread;
return TRI_ERROR_INTERNAL;
}
return TRI_ERROR_NO_ERROR;
}
// stop the allocator thread
void MMFilesLogfileManager::stopMMFilesAllocatorThread() {
if (_allocatorThread != nullptr) {
LOG_TOPIC("d47e8", TRACE, arangodb::Logger::ENGINES)
<< "stopping WAL allocator thread";
_allocatorThread->beginShutdown();
}
}
// start the collector thread
int MMFilesLogfileManager::startMMFilesCollectorThread() {
WRITE_LOCKER(locker, _collectorThreadLock);
_collectorThread = new MMFilesCollectorThread(this);
if (!_collectorThread->start()) {
delete _collectorThread;
return TRI_ERROR_INTERNAL;
}
return TRI_ERROR_NO_ERROR;
}
// stop the collector thread
void MMFilesLogfileManager::stopMMFilesCollectorThread() {
if (_collectorThread == nullptr) {
return;
}
LOG_TOPIC("14310", TRACE, arangodb::Logger::ENGINES)
<< "stopping WAL collector thread";
// wait for at most 5 seconds for the collector
// to catch up
double const end = TRI_microtime() + 5.0;
while (TRI_microtime() < end) {
bool canAbort = true;
{
READ_LOCKER(readLocker, _logfilesLock);
for (auto& it : _logfiles) {
MMFilesWalLogfile* logfile = it.second;
if (logfile == nullptr) {
continue;
}
MMFilesWalLogfile::StatusType status = logfile->status();
if (status == MMFilesWalLogfile::StatusType::SEAL_REQUESTED) {
canAbort = false;
break;
}
}
}
if (canAbort) {
MUTEX_LOCKER(mutexLocker, _idLock);
if (_lastSealedId == _lastCollectedId) {
break;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
_collectorThread->beginShutdown();
}
// start the remover thread
int MMFilesLogfileManager::startMMFilesRemoverThread() {
_removerThread = new MMFilesRemoverThread(this);
if (!_removerThread->start()) {
delete _removerThread;
return TRI_ERROR_INTERNAL;
}
return TRI_ERROR_NO_ERROR;
}
// stop the remover thread
void MMFilesLogfileManager::stopMMFilesRemoverThread() {
if (_removerThread != nullptr) {
LOG_TOPIC("51d42", TRACE, arangodb::Logger::ENGINES)
<< "stopping WAL remover thread";
_removerThread->beginShutdown();
}
}
// check which logfiles are present in the log directory
int MMFilesLogfileManager::inventory() {
int res = ensureDirectory();
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
LOG_TOPIC("ed035", TRACE, arangodb::Logger::ENGINES)
<< "scanning WAL directory: '" << _directory << "'";
std::vector<std::string> files = basics::FileUtils::listFiles(_directory);
for (auto it = files.begin(); it != files.end(); ++it) {
std::string const file = (*it);
if (StringUtils::isPrefix(file, "logfile-") &&
StringUtils::isSuffix(file, ".db")) {
MMFilesWalLogfile::IdType const id =
basics::StringUtils::uint64(file.substr(8, file.size() - 8 - 3));
if (id == 0) {
LOG_TOPIC("dc4f6", WARN, arangodb::Logger::ENGINES)
<< "encountered invalid id for logfile '" << file << "'. ids must be > 0";
} else {
// update global tick
TRI_UpdateTickServer(static_cast<TRI_voc_tick_t>(id));
WRITE_LOCKER(writeLocker, _logfilesLock);
_logfiles.emplace(id, nullptr);
}
}
}
return TRI_ERROR_NO_ERROR;
}
// inspect the logfiles in the log directory
int MMFilesLogfileManager::inspectLogfiles() {
LOG_TOPIC("972e5", TRACE, arangodb::Logger::ENGINES) << "inspecting WAL logfiles";
WRITE_LOCKER(writeLocker, _logfilesLock);
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
// print an inventory
for (auto it = _logfiles.begin(); it != _logfiles.end(); ++it) {
MMFilesWalLogfile* logfile = (*it).second;
if (logfile != nullptr) {
LOG_TOPIC("ca138", DEBUG, arangodb::Logger::ENGINES)
<< "logfile " << logfile->id() << ", filename '"
<< logfile->filename() << "', status " << logfile->statusText();
}
}
#endif
for (auto it = _logfiles.begin(); it != _logfiles.end(); /* no hoisting */) {
MMFilesWalLogfile::IdType const id = (*it).first;
std::string const filename = logfileName(id);
TRI_ASSERT((*it).second == nullptr);
int res = MMFilesDatafile::judge(filename);
if (res == TRI_ERROR_ARANGO_DATAFILE_EMPTY) {
_recoverState->emptyLogfiles.push_back(filename);
_logfiles.erase(it++);
continue;
}
bool const wasCollected = (id <= _lastCollectedId);
std::unique_ptr<MMFilesWalLogfile> logfile(
MMFilesWalLogfile::openExisting(filename, id, wasCollected, _ignoreLogfileErrors));
if (logfile == nullptr) {
// an error happened when opening a logfile
if (!_ignoreLogfileErrors) {
// we don't ignore errors, so we abort here
int res = TRI_errno();
if (res == TRI_ERROR_NO_ERROR) {
// must have an error!
res = TRI_ERROR_ARANGO_DATAFILE_UNREADABLE;
}
return res;
}
_logfiles.erase(it++);
continue;
}
if (logfile->status() == MMFilesWalLogfile::StatusType::OPEN ||
logfile->status() == MMFilesWalLogfile::StatusType::SEALED) {
_recoverState->logfilesToProcess.push_back(logfile.get());
}
LOG_TOPIC("f4891", TRACE, arangodb::Logger::ENGINES)
<< "inspecting logfile " << logfile->id() << " ("
<< logfile->statusText() << ")";
MMFilesDatafile* df = logfile->df();
df->sequentialAccess();
// update the tick statistics
if (!TRI_IterateDatafile(df, &MMFilesWalRecoverState::InitialScanMarker,
static_cast<void*>(_recoverState.get()))) {
std::string const logfileName = logfile->filename();
LOG_TOPIC("c04b1", WARN, arangodb::Logger::ENGINES)
<< "WAL inspection failed when scanning logfile '" << logfileName << "'";
return TRI_ERROR_ARANGO_RECOVERY;
}
LOG_TOPIC("b7073", TRACE, arangodb::Logger::ENGINES)
<< "inspected logfile " << logfile->id() << " (" << logfile->statusText()
<< "), tickMin: " << df->_tickMin << ", tickMax: " << df->_tickMax;
if (logfile->status() == MMFilesWalLogfile::StatusType::SEALED) {
// If it is sealed, switch to random access:
df->randomAccess();
}
{
MUTEX_LOCKER(mutexLocker, _idLock);
if (logfile->status() == MMFilesWalLogfile::StatusType::SEALED && id > _lastSealedId) {
_lastSealedId = id;
}
if ((logfile->status() == MMFilesWalLogfile::StatusType::SEALED ||
logfile->status() == MMFilesWalLogfile::StatusType::OPEN) &&
id > _lastOpenedId) {
_lastOpenedId = id;
}
}
(*it).second = logfile.release();
++it;
}
// update the tick with the max tick we found in the WAL
TRI_UpdateTickServer(_recoverState->lastTick);
// return the lock here to ensure proper locking order
writeLocker.unlock();
TRI_ASSERT(_slots != nullptr);
// set the last ticks we found in existing logfile data
_slots->setLastTick(_recoverState->lastTick);
// use maximum revision value found from WAL to adjust HLC value
// should it be lower
LOG_TOPIC("21a90", TRACE, arangodb::Logger::ENGINES)
<< "setting max HLC value to " << _recoverState->maxRevisionId;
TRI_HybridLogicalClock(_recoverState->maxRevisionId);
// track maximum local document id as well
LocalDocumentId::track(_recoverState->maxLocalDocumentId);
return TRI_ERROR_NO_ERROR;
}
// allocates a new reserve logfile
int MMFilesLogfileManager::createReserveLogfile(uint32_t size) {
MMFilesWalLogfile::IdType const id = nextId();
std::string const filename = logfileName(id);
LOG_TOPIC("c9f68", TRACE, arangodb::Logger::ENGINES)
<< "creating empty logfile '" << filename << "' with size " << size;
uint32_t realsize;
if (size > 0 && size > filesize()) {
// create a logfile with the requested size
realsize = size + MMFilesDatafileHelper::JournalOverhead();
} else {
// create a logfile with default size
realsize = filesize();
}
std::unique_ptr<MMFilesWalLogfile> logfile(
MMFilesWalLogfile::createNew(filename, id, realsize));
if (logfile == nullptr) {
int res = TRI_errno();
LOG_TOPIC("e3868", ERR, arangodb::Logger::ENGINES)
<< "unable to create logfile: " << TRI_errno_string(res);
return res;
}
if (_useMLock) {
logfile->lockInMemory();
}
{
WRITE_LOCKER(writeLocker, _logfilesLock);
_logfiles.emplace(id, logfile.get());
}
logfile.release();
return TRI_ERROR_NO_ERROR;
}
// get an id for the next logfile
MMFilesWalLogfile::IdType MMFilesLogfileManager::nextId() {
return static_cast<MMFilesWalLogfile::IdType>(TRI_NewTickServer());
}
// ensure the wal logfiles directory is actually there
int MMFilesLogfileManager::ensureDirectory() {
// strip directory separator from path
// this is required for Windows
std::string directory(_directory);
TRI_ASSERT(!directory.empty());
if (directory[directory.size() - 1] == TRI_DIR_SEPARATOR_CHAR) {
directory = directory.substr(0, directory.size() - 1);
}
if (!basics::FileUtils::isDirectory(directory)) {
LOG_TOPIC("ba9db", INFO, arangodb::Logger::ENGINES)
<< "WAL directory '" << directory << "' does not exist. creating it...";
int res;
if (!basics::FileUtils::createDirectory(directory, &res)) {
LOG_TOPIC("3cf62", ERR, arangodb::Logger::ENGINES)
<< "could not create WAL directory: '" << directory
<< "': " << TRI_last_error();
return TRI_ERROR_SYS_ERROR;
}
}
if (!basics::FileUtils::isDirectory(directory)) {
LOG_TOPIC("4c35d", ERR, arangodb::Logger::ENGINES)
<< "WAL directory '" << directory << "' does not exist";
return TRI_ERROR_FILE_NOT_FOUND;
}
return TRI_ERROR_NO_ERROR;
}
// return the absolute name of the shutdown file
std::string MMFilesLogfileManager::shutdownFilename() const {
return _databasePath + TRI_DIR_SEPARATOR_STR + "SHUTDOWN";
}
// return an absolute filename for a logfile id
std::string MMFilesLogfileManager::logfileName(MMFilesWalLogfile::IdType id) const {
return _directory + std::string("logfile-") + basics::StringUtils::itoa(id) +
std::string(".db");
}
|
// Copyright 2014 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 "extensions/browser/api/networking_private/networking_private_delegate_factory.h"
#include "build/build_config.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/extensions_browser_client.h"
#if defined(OS_CHROMEOS)
#include "extensions/browser/api/networking_private/networking_private_chromeos.h"
#elif defined(OS_LINUX)
#include "extensions/browser/api/networking_private/networking_private_linux.h"
#elif defined(OS_WIN) || defined(OS_MACOSX)
#include "components/wifi/wifi_service.h"
#include "extensions/browser/api/networking_private/networking_private_service_client.h"
#endif
namespace extensions {
using content::BrowserContext;
NetworkingPrivateDelegateFactory::VerifyDelegateFactory::
VerifyDelegateFactory() {
}
NetworkingPrivateDelegateFactory::VerifyDelegateFactory::
~VerifyDelegateFactory() {
}
NetworkingPrivateDelegateFactory::UIDelegateFactory::UIDelegateFactory() {}
NetworkingPrivateDelegateFactory::UIDelegateFactory::~UIDelegateFactory() {}
// static
NetworkingPrivateDelegate*
NetworkingPrivateDelegateFactory::GetForBrowserContext(
BrowserContext* browser_context) {
return static_cast<NetworkingPrivateDelegate*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
NetworkingPrivateDelegateFactory*
NetworkingPrivateDelegateFactory::GetInstance() {
return base::Singleton<NetworkingPrivateDelegateFactory>::get();
}
NetworkingPrivateDelegateFactory::NetworkingPrivateDelegateFactory()
: BrowserContextKeyedServiceFactory(
"NetworkingPrivateDelegate",
BrowserContextDependencyManager::GetInstance()) {
}
NetworkingPrivateDelegateFactory::~NetworkingPrivateDelegateFactory() {
}
void NetworkingPrivateDelegateFactory::SetVerifyDelegateFactory(
std::unique_ptr<VerifyDelegateFactory> factory) {
verify_factory_ = std::move(factory);
}
void NetworkingPrivateDelegateFactory::SetUIDelegateFactory(
std::unique_ptr<UIDelegateFactory> factory) {
ui_factory_ = std::move(factory);
}
KeyedService* NetworkingPrivateDelegateFactory::BuildServiceInstanceFor(
BrowserContext* browser_context) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::unique_ptr<NetworkingPrivateDelegate::VerifyDelegate> verify_delegate;
if (verify_factory_)
verify_delegate = verify_factory_->CreateDelegate();
NetworkingPrivateDelegate* delegate;
#if defined(OS_CHROMEOS)
delegate = new NetworkingPrivateChromeOS(browser_context,
std::move(verify_delegate));
#elif defined(OS_LINUX)
delegate = new NetworkingPrivateLinux(std::move(verify_delegate));
#elif defined(OS_WIN) || defined(OS_MACOSX)
std::unique_ptr<wifi::WiFiService> wifi_service(wifi::WiFiService::Create());
delegate = new NetworkingPrivateServiceClient(std::move(wifi_service),
std::move(verify_delegate));
#else
NOTREACHED();
delegate = nullptr;
#endif
if (ui_factory_)
delegate->set_ui_delegate(ui_factory_->CreateDelegate());
return delegate;
}
BrowserContext* NetworkingPrivateDelegateFactory::GetBrowserContextToUse(
BrowserContext* context) const {
return ExtensionsBrowserClient::Get()->GetOriginalContext(context);
}
bool NetworkingPrivateDelegateFactory::ServiceIsCreatedWithBrowserContext()
const {
return false;
}
bool NetworkingPrivateDelegateFactory::ServiceIsNULLWhileTesting() const {
return false;
}
} // namespace extensions
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=4 sw=4 et tw=99:
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Assembler-x64.h"
#include "gc/Marking.h"
#include "jsscriptinlines.h"
using namespace js;
using namespace js::ion;
void
Assembler::writeRelocation(JmpSrc src, Relocation::Kind reloc)
{
if (!jumpRelocations_.length()) {
// The jump relocation table starts with a fixed-width integer pointing
// to the start of the extended jump table. But, we don't know the
// actual extended jump table offset yet, so write a 0 which we'll
// patch later.
jumpRelocations_.writeFixedUint32(0);
}
if (reloc == Relocation::IONCODE) {
jumpRelocations_.writeUnsigned(src.offset());
jumpRelocations_.writeUnsigned(jumps_.length());
}
}
void
Assembler::addPendingJump(JmpSrc src, void *target, Relocation::Kind reloc)
{
JS_ASSERT(target);
// Emit reloc before modifying the jump table, since it computes a 0-based
// index. This jump is not patchable at runtime.
if (reloc == Relocation::IONCODE)
writeRelocation(src, reloc);
enoughMemory_ &= jumps_.append(RelativePatch(src.offset(), target, reloc));
}
size_t
Assembler::addPatchableJump(JmpSrc src, Relocation::Kind reloc)
{
// This jump is patchable at runtime so we always need to make sure the
// jump table is emitted.
writeRelocation(src, reloc);
size_t index = jumps_.length();
enoughMemory_ &= jumps_.append(RelativePatch(src.offset(), NULL, reloc));
return index;
}
/* static */
uint8 *
Assembler::PatchableJumpAddress(IonCode *code, size_t index)
{
// The assembler stashed the offset into the code of the fragments used
// for far jumps at the start of the relocation table.
uint32 jumpOffset = * (uint32 *) code->jumpRelocTable();
jumpOffset += index * SizeOfJumpTableEntry;
JS_ASSERT(jumpOffset + SizeOfExtendedJump <= code->instructionsSize());
return code->raw() + jumpOffset;
}
/* static */
void
Assembler::PatchJumpEntry(uint8 *entry, uint8 *target)
{
uint8 **index = (uint8 **) (entry + SizeOfExtendedJump - sizeof(void*));
*index = target;
}
void
Assembler::flush()
{
if (!jumps_.length() || oom())
return;
// Emit the jump table.
masm.align(16);
extendedJumpTable_ = masm.size();
// Now that we know the offset to the jump table, squirrel it into the
// jump relocation buffer if any IonCode references exist and must be
// tracked for GC.
JS_ASSERT_IF(jumpRelocations_.length(), jumpRelocations_.length() >= sizeof(uint32));
if (jumpRelocations_.length())
*(uint32 *)jumpRelocations_.buffer() = extendedJumpTable_;
// Zero the extended jumps table.
for (size_t i = 0; i < jumps_.length(); i++) {
#ifdef DEBUG
size_t oldSize = masm.size();
#endif
masm.jmp_rip(0);
masm.immediate64(0);
masm.align(SizeOfJumpTableEntry);
JS_ASSERT(masm.size() - oldSize == SizeOfJumpTableEntry);
}
}
void
Assembler::executableCopy(uint8 *buffer)
{
AssemblerX86Shared::executableCopy(buffer);
for (size_t i = 0; i < jumps_.length(); i++) {
RelativePatch &rp = jumps_[i];
uint8 *src = buffer + rp.offset;
if (!rp.target) {
// The patch target is NULL for jumps that have been linked to a
// label within the same code block, but may be repatched later to
// jump to a different code block.
continue;
}
if (JSC::X86Assembler::canRelinkJump(src, rp.target)) {
JSC::X86Assembler::setRel32(src, rp.target);
} else {
// An extended jump table must exist, and its offset must be in
// range.
JS_ASSERT(extendedJumpTable_);
JS_ASSERT((extendedJumpTable_ + i * SizeOfJumpTableEntry) <= size() - SizeOfJumpTableEntry);
// Patch the jump to go to the extended jump entry.
uint8 *entry = buffer + extendedJumpTable_ + i * SizeOfJumpTableEntry;
JSC::X86Assembler::setRel32(src, entry);
// Now patch the pointer, note that we need to align it to
// *after* the extended jump, i.e. after the 64-bit immedate.
JSC::X86Assembler::repatchPointer(entry + SizeOfExtendedJump, rp.target);
}
}
}
class RelocationIterator
{
CompactBufferReader reader_;
uint32 tableStart_;
uint32 offset_;
uint32 extOffset_;
public:
RelocationIterator(CompactBufferReader &reader)
: reader_(reader)
{
tableStart_ = reader_.readFixedUint32();
}
bool read() {
if (!reader_.more())
return false;
offset_ = reader_.readUnsigned();
extOffset_ = reader_.readUnsigned();
return true;
}
uint32 offset() const {
return offset_;
}
uint32 extendedOffset() const {
return extOffset_;
}
};
IonCode *
Assembler::CodeFromJump(IonCode *code, uint8 *jump)
{
uint8 *target = (uint8 *)JSC::X86Assembler::getRel32Target(jump);
if (target >= code->raw() && target < code->raw() + code->instructionsSize()) {
// This jump is within the code buffer, so it has been redirected to
// the extended jump table.
JS_ASSERT(target + SizeOfJumpTableEntry <= code->raw() + code->instructionsSize());
target = (uint8 *)JSC::X86Assembler::getPointer(target + SizeOfExtendedJump);
}
return IonCode::FromExecutable(target);
}
void
Assembler::TraceJumpRelocations(JSTracer *trc, IonCode *code, CompactBufferReader &reader)
{
RelocationIterator iter(reader);
while (iter.read()) {
IonCode *child = CodeFromJump(code, code->raw() + iter.offset());
MarkIonCodeUnbarriered(trc, &child, "rel32");
JS_ASSERT(child == CodeFromJump(code, code->raw() + iter.offset()));
}
}
|
/**
*/
#ifndef __codex_slist_h__
#define __codex_slist_h__
namespace codex {
/**
*/
template < class T >
class slist{
public:
///
slist( void );
///
~slist( void );
///
template < class U >
void swap( slist<U>& rhs );
///
void add_tail( T* node );
///
T* head( void );
///
T* remove_head( void );
private:
T* _head;
T* _tail;
};
template < class T >
slist< T >::slist( void )
: _head( nullptr ) , _tail( nullptr )
{
}
template < class T >
slist< T >::~slist( void )
{
}
template < class T >
template < class U >
void slist< T >::swap( slist<U>& rhs ) {
std::swap( _head , rhs._head );
std::swap( _tail , rhs._tail );
}
template < class T >
void slist< T >::add_tail( T* node ) {
if ( _head == nullptr ){
_head = _tail = node;
} else {
_tail->next( node );
_tail = node;
}
node->next( nullptr );
}
template < class T >
T* slist< T >::head( void ) {
return _head;
}
template < class T >
T* slist< T >::remove_head( void ) {
T* head = _head;
if ( _head == _tail ) {
_head = _tail = nullptr;
} else {
_head = static_cast<T*>(_head->next());
}
return head;
}
}
#endif
|
#include "CLI11.hpp"
#include "dataset_loader.hpp"
#include "dsp.hpp"
// This software is composed of 3 parts
// The first part is the data loader which loads all the dataset into a one
// giant std vector.
// Second part is the EMD computation part which contains the C
// code that is used to compute the IMF
// The third part statistical part which contains the computation
// of the mean, std dev, skewness, etc...
// Finally the fourth part, saving all of these extracted features to a
// file locally.
int main(int argc, char** argv)
{
CLI::App app{"This software contains the necessary implementation to convert the raw MCSA dataset"
" into a usable statistical feature dataset using the CEEMDAN methods.\n"
"This software can convert the entire dataset published by the Automatica platform, or"
" only a specific raw dataset that is obtained from the motor directly.\n"
"This software can be considered as a DSP block that extract features from the raw motors signals.\n"};
std::string path;
app.add_option("-p", path, "Enter the full path to the entire dataset. Usually this folder contains a set of classes folders.");
CLI11_PARSE(app, argc, argv);
std::vector<arma::mat> dataset;
arma::mat features_matrix;
if (!path.empty())
{
DataLoader data(path);
data.load_all_datasets(dataset, 0);
}
create_feature_matrix(dataset, features_matrix);
//Verify that the matrix is good.
features_matrix = features_matrix.t();
features_matrix.save("extracted_features.csv", arma::csv_ascii);
}
// Write the code of inference,
// Divide the code into a set of classes
// Add more docs related to each function
|
/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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.
**/
#include <gtest/gtest.h>
#include <ros/ros.h>
#include <ubiquity_motor/motor_message.h>
#include <ubiquity_motor/motor_serial.h>
#include <string>
#if defined(__linux__)
#include <pty.h>
#else
#include <util.h>
#endif
class MotorSerialTests : public ::testing::Test {
protected:
virtual void SetUp() {
if (openpty(&master_fd, &slave_fd, name, NULL, NULL) == -1) {
perror("openpty");
exit(127);
}
ASSERT_TRUE(master_fd > 0);
ASSERT_TRUE(slave_fd > 0);
ASSERT_TRUE(std::string(name).length() > 0);
ros::Time::init();
motors = new MotorSerial(std::string(name), 9600);
}
virtual void TearDown() { delete motors; }
MotorSerial *motors;
int master_fd;
int slave_fd;
char name[100];
};
TEST(MotorSerialNoFixtureTests, badPortnameException) {
ASSERT_THROW(MotorSerial motors(std::string("foo"), 9600),
serial::IOException);
}
TEST_F(MotorSerialTests, serialClosedOnInterupt) {
ASSERT_EQ(true, motors->motors.isOpen());
motors->serial_thread.interrupt();
sleep(1);
ASSERT_EQ(false, motors->motors.isOpen());
}
TEST_F(MotorSerialTests, goodReadWorks) {
uint8_t test[] = {0x7E, 0x3B, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x90};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 8));
while (!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors->receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, misalignedOneGoodReadWorks) {
uint8_t test[] = {0x00, 0x7E, 0x3B, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x90};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 9));
while (!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors->receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, misalignedManyGoodReadWorks) {
uint8_t test[] = {0x01, 0x2C, 0x0E, 0x7E, 0x3B, 0x07,
0x00, 0x00, 0x01, 0x2C, 0x90};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 11));
while (!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors->receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, errorReadWorks) {
uint8_t test[] = {0x7E, 0x3D, 0x07, 0x00, 0x00, 0x00, 0x00, 0xBB};
// uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
ASSERT_NE(-1, write(master_fd, test, 8));
while (!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors->receiveCommand();
ASSERT_EQ(MotorMessage::TYPE_ERROR, mm.getType());
}
TEST_F(MotorSerialTests, badReadFails) {
uint8_t test[] = {0xdd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
ASSERT_NE(-1, write(master_fd, test, 9));
ros::Rate loop(100);
int times = 0;
while (!motors->commandAvailable()) {
loop.sleep();
times++;
if (times >= 20) {
break;
}
}
if (times >= 20) {
SUCCEED();
} else {
FAIL();
}
}
TEST_F(MotorSerialTests, misalignedOneBadReadFails) {
uint8_t test[] = {0x00, 0x7d, 0x3B, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x90};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 9));
ros::Rate loop(100);
int times = 0;
while (!motors->commandAvailable()) {
loop.sleep();
times++;
if (times >= 20) {
break;
}
}
if (times >= 20) {
SUCCEED();
} else {
FAIL();
}
}
TEST_F(MotorSerialTests, incompleteReadFails) {
uint8_t test[] = {0x7E, 0x3B, 0x00};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 3));
ros::Rate loop(100);
int times = 0;
while (!motors->commandAvailable()) {
loop.sleep();
times++;
if (times >= 20) {
break;
}
}
if (times >= 20) {
SUCCEED();
} else {
FAIL();
}
}
TEST_F(MotorSerialTests, incompleteMisalignedReadFails) {
uint8_t test[] = {0x0f, 0x7E, 0x3B, 0x00};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 4));
ros::Rate loop(100);
int times = 0;
while (!motors->commandAvailable()) {
loop.sleep();
times++;
if (times >= 20) {
break;
}
}
if (times >= 20) {
SUCCEED();
} else {
FAIL();
}
}
TEST_F(MotorSerialTests, badProtocolReadFails) {
uint8_t test[] = {0x7E, 0xFB, 0x07, 0x00, 0x00, 0x00, 0x00, 0xFB};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 8));
ros::Rate loop(100);
int times = 0;
while (!motors->commandAvailable()) {
loop.sleep();
times++;
if (times >= 20) {
break;
}
}
if (times >= 20) {
SUCCEED();
} else {
FAIL();
}
}
TEST_F(MotorSerialTests, badTypeReadFails) {
uint8_t test[] = {0x7E, 0x2E, 0x07, 0x00, 0x00, 0x00, 0x00, 0xCA};
// char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
ASSERT_NE(-1, write(master_fd, test, 8));
ros::Rate loop(100);
int times = 0;
while (!motors->commandAvailable()) {
loop.sleep();
times++;
if (times >= 20) {
break;
}
}
if (times >= 20) {
SUCCEED();
} else {
FAIL();
}
}
TEST_F(MotorSerialTests, writeOutputs) {
MotorMessage version;
version.setRegister(MotorMessage::REG_FIRMWARE_VERSION);
version.setType(MotorMessage::TYPE_READ);
version.setData(0);
motors->transmitCommand(version);
int count = 0;
while (count < 8) {
ASSERT_NE(-1, ioctl(master_fd, TIOCINQ, &count));
}
EXPECT_EQ(8, count);
RawMotorMessage input;
EXPECT_EQ(input.size(), read(master_fd, input.c_array(), input.size()));
ASSERT_EQ(input, version.serialize());
}
TEST_F(MotorSerialTests, writeMultipleOutputs) {
std::vector<MotorMessage> commands;
MotorMessage left_odom;
left_odom.setRegister(MotorMessage::REG_LEFT_ODOM);
left_odom.setType(MotorMessage::TYPE_READ);
left_odom.setData(0);
commands.push_back(left_odom);
MotorMessage right_odom;
right_odom.setRegister(MotorMessage::REG_RIGHT_ODOM);
right_odom.setType(MotorMessage::TYPE_READ);
right_odom.setData(0);
commands.push_back(right_odom);
MotorMessage left_vel;
left_vel.setRegister(MotorMessage::REG_LEFT_SPEED_MEASURED);
left_vel.setType(MotorMessage::TYPE_READ);
left_vel.setData(0);
commands.push_back(left_vel);
MotorMessage right_vel;
right_vel.setRegister(MotorMessage::REG_RIGHT_SPEED_MEASURED);
right_vel.setType(MotorMessage::TYPE_READ);
right_vel.setData(0);
commands.push_back(right_vel);
motors->transmitCommands(commands);
fd_set fds;
FD_ZERO(&fds);
FD_SET(master_fd, &fds);
struct timeval timeout = { 10, 0 }; /* 10 seconds */
uint8_t arr[32];
int count = 0;
while (count < 31) {
// Wait for data
int ret = select(master_fd+1, &fds, NULL, NULL, &timeout);
EXPECT_EQ(1, ret);
// Get number of bytes availible
int avail = 0;
ASSERT_NE(-1, ioctl(master_fd, TIOCINQ, &avail));
// Read bytes into the buffer
EXPECT_EQ(avail, read(master_fd, arr+count, avail));
count += avail;
}
ASSERT_EQ(32, count);
std::vector<uint8_t> input(arr, arr + sizeof(arr) / sizeof(uint8_t));
std::vector<uint8_t> expected(0);
for (std::vector<MotorMessage>::iterator i = commands.begin();
i != commands.end(); ++i) {
RawMotorMessage serialized = i->serialize();
expected.insert(expected.end(), serialized.begin(), serialized.end());
}
ASSERT_EQ(expected, input);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
// IFT3100H21_ShaderClassic/main.cpp
// Démonstration de 5 modèles d'illumination classiques implémentés avec des shaders :
// - couleur de remplissage uniforme sur toute la surface,
// - modèle d'illumination de Lambert,
// - modèle d'illumination de Gouraud,
// - modèle d'illumination de Phong et
// - modèle d'illumination de Blinn-Phong.
// Le facteur de brillance spéculaire est animé par oscillation.
// La position de la source de lumière est interactive.
#include "ofMain.h"
#include "application.h"
int main()
{
ofGLWindowSettings windowSettings;
windowSettings.setSize(1024, 512);
windowSettings.setGLVersion(3, 3);
ofCreateWindow(windowSettings);
ofRunApp(new Application());
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <PhysX_precompiled.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzFramework/Viewport/ViewportColors.h>
#include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h>
#include <PhysXCharacters/API/CharacterController.h>
#include <PhysXCharacters/Components/EditorCharacterControllerComponent.h>
#include <PhysXCharacters/Components/CharacterControllerComponent.h>
#include <LmbrCentral/Geometry/GeometrySystemComponentBus.h>
#include <System/PhysXSystem.h>
namespace PhysX
{
// this epsilon is deliberately chosen to be somewhat larger than AZ::Constants::FloatEpsilon so that it does not vanish
// when compared to the typical height of a character
static const float HeightEpsilon = 1e-5f;
void EditorCharacterControllerProxyShapeConfig::Reflect(AZ::ReflectContext* context)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<EditorCharacterControllerProxyShapeConfig>()
->Version(1)
->Field("ShapeType", &EditorCharacterControllerProxyShapeConfig::m_shapeType)
->Field("Box", &EditorCharacterControllerProxyShapeConfig::m_box)
->Field("Capsule", &EditorCharacterControllerProxyShapeConfig::m_capsule)
;
if (auto editContext = serializeContext->GetEditContext())
{
editContext->Class<EditorCharacterControllerProxyShapeConfig>(
"EditorCharacterControllerProxyShapeConfig", "PhysX character controller shape")
->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorCharacterControllerProxyShapeConfig::m_shapeType, "Shape",
"The shape associated with the character controller")
->EnumAttribute(Physics::ShapeType::Capsule, "Capsule")
->EnumAttribute(Physics::ShapeType::Box, "Box")
->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree)
->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerProxyShapeConfig::m_box, "Box",
"Configuration of box shape")
->Attribute(AZ::Edit::Attributes::Visibility, &EditorCharacterControllerProxyShapeConfig::IsBoxConfig)
->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerProxyShapeConfig::m_capsule, "Capsule",
"Configuration of capsule shape")
->Attribute(AZ::Edit::Attributes::Visibility, &EditorCharacterControllerProxyShapeConfig::IsCapsuleConfig)
;
}
}
}
bool EditorCharacterControllerProxyShapeConfig::IsBoxConfig() const
{
return m_shapeType == Physics::ShapeType::Box;
}
bool EditorCharacterControllerProxyShapeConfig::IsCapsuleConfig() const
{
return m_shapeType == Physics::ShapeType::Capsule;
}
const Physics::ShapeConfiguration& EditorCharacterControllerProxyShapeConfig::GetCurrent() const
{
switch (m_shapeType)
{
case Physics::ShapeType::Box:
return m_box;
case Physics::ShapeType::Capsule:
return m_capsule;
default:
AZ_Warning("EditorCharacterControllerProxyShapeConfig", false, "Unsupported shape type.");
return m_capsule;
}
}
void EditorCharacterControllerComponent::Reflect(AZ::ReflectContext* context)
{
EditorCharacterControllerProxyShapeConfig::Reflect(context);
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<EditorCharacterControllerComponent, EditorComponentBase>()
->Version(1)
->Field("Configuration", &EditorCharacterControllerComponent::m_configuration)
->Field("ShapeConfig", &EditorCharacterControllerComponent::m_proxyShapeConfiguration)
;
if (auto editContext = serializeContext->GetEditContext())
{
editContext->Class<EditorCharacterControllerComponent>(
"PhysX Character Controller", "PhysX Character Controller")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "PhysX")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PhysXCharacter.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/PhysXCharacter.svg")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerComponent::m_configuration,
"Configuration", "Configuration for the character controller")
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorCharacterControllerComponent::OnControllerConfigChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &EditorCharacterControllerComponent::m_proxyShapeConfiguration,
"Shape Configuration", "The configuration for the shape associated with the character controller")
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorCharacterControllerComponent::OnShapeConfigChanged)
;
}
}
}
EditorCharacterControllerComponent::EditorCharacterControllerComponent()
: m_physXConfigChangedHandler(
[]([[maybe_unused]]const AzPhysics::SystemConfiguration* config)
{
AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh,
AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues);
})
{
}
void EditorCharacterControllerComponent::Activate()
{
AzToolsFramework::Components::EditorComponentBase::Activate();
AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId());
AzToolsFramework::EntitySelectionEvents::Bus::Handler::BusConnect(GetEntityId());
}
void EditorCharacterControllerComponent::Deactivate()
{
AzToolsFramework::EntitySelectionEvents::Bus::Handler::BusDisconnect();
AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect();
AzToolsFramework::Components::EditorComponentBase::Deactivate();
}
// AzToolsFramework::EntitySelectionEvents
void EditorCharacterControllerComponent::OnSelected()
{
if (auto* physXSystem = GetPhysXSystem())
{
if (!m_physXConfigChangedHandler.IsConnected())
{
physXSystem->RegisterSystemConfigurationChangedEvent(m_physXConfigChangedHandler);
}
}
}
void EditorCharacterControllerComponent::OnDeselected()
{
m_physXConfigChangedHandler.Disconnect();
}
// AzFramework::EntityDebugDisplayEventBus
void EditorCharacterControllerComponent::DisplayEntityViewport(
[[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay)
{
if (IsSelected())
{
const AZ::Vector3 upDirectionNormalized = m_configuration.m_upDirection.IsZero()
? AZ::Vector3::CreateAxisZ()
: m_configuration.m_upDirection.GetNormalized();
// PhysX uses the x-axis as the height direction of the controller, and so takes the shortest arc from the
// x-axis to the up direction. To obtain the same orientation in the LY co-ordinate system (which uses z
// as the height direction), we need to combine a rotation from the x-axis to the up direction with a
// rotation from the z-axis to the x-axis.
const AZ::Quaternion upDirectionQuat = AZ::Quaternion::CreateShortestArc(AZ::Vector3::CreateAxisX(),
upDirectionNormalized) * AZ::Quaternion::CreateRotationY(AZ::Constants::HalfPi);
if (m_proxyShapeConfiguration.IsCapsuleConfig())
{
const auto& capsuleConfig = static_cast<const Physics::CapsuleShapeConfiguration&>(m_proxyShapeConfiguration.GetCurrent());
const float heightOffset = 0.5f * capsuleConfig.m_height + m_configuration.m_contactOffset;
const AZ::Transform controllerTransform = AZ::Transform::CreateFromQuaternionAndTranslation(
upDirectionQuat, GetWorldTM().GetTranslation() + heightOffset * upDirectionNormalized);
debugDisplay.PushMatrix(controllerTransform);
// draw the actual shape
LmbrCentral::CapsuleGeometrySystemRequestBus::Broadcast(
&LmbrCentral::CapsuleGeometrySystemRequestBus::Events::GenerateCapsuleMesh,
m_configuration.m_scaleCoefficient * capsuleConfig.m_radius,
m_configuration.m_scaleCoefficient * capsuleConfig.m_height,
16, 8,
m_vertexBuffer,
m_indexBuffer,
m_lineBuffer
);
debugDisplay.SetLineWidth(2.0f);
debugDisplay.DrawTrianglesIndexed(m_vertexBuffer, m_indexBuffer, AzFramework::ViewportColors::SelectedColor);
debugDisplay.DrawLines(m_lineBuffer, AzFramework::ViewportColors::WireColor);
// draw the shape inflated by the contact offset
LmbrCentral::CapsuleGeometrySystemRequestBus::Broadcast(
&LmbrCentral::CapsuleGeometrySystemRequestBus::Events::GenerateCapsuleMesh,
m_configuration.m_scaleCoefficient * capsuleConfig.m_radius + m_configuration.m_contactOffset,
m_configuration.m_scaleCoefficient * capsuleConfig.m_height + 2.0f * m_configuration.m_contactOffset,
16, 8,
m_vertexBuffer,
m_indexBuffer,
m_lineBuffer
);
debugDisplay.DrawLines(m_lineBuffer, AzFramework::ViewportColors::WireColor);
debugDisplay.PopMatrix();
}
if (m_proxyShapeConfiguration.IsBoxConfig())
{
const auto& boxConfig = static_cast<const Physics::BoxShapeConfiguration&>(m_proxyShapeConfiguration.GetCurrent());
const float heightOffset = 0.5f * boxConfig.m_dimensions.GetZ() + m_configuration.m_contactOffset;
const AZ::Transform controllerTransform = AZ::Transform::CreateFromQuaternionAndTranslation(
upDirectionQuat, GetWorldTM().GetTranslation() + heightOffset * upDirectionNormalized);
const AZ::Vector3 boxHalfExtentsScaled = 0.5f * m_configuration.m_scaleCoefficient * boxConfig.m_dimensions;
const AZ::Vector3 boxHalfExtentsScaledWithContactOffset = boxHalfExtentsScaled +
m_configuration.m_contactOffset * AZ::Vector3::CreateOne();
debugDisplay.PushMatrix(controllerTransform);
// draw the actual shape
debugDisplay.SetLineWidth(2.0f);
debugDisplay.SetColor(AzFramework::ViewportColors::SelectedColor);
debugDisplay.DrawSolidBox(-boxHalfExtentsScaled, boxHalfExtentsScaled);
debugDisplay.SetColor(AzFramework::ViewportColors::WireColor);
debugDisplay.DrawWireBox(-boxHalfExtentsScaled, boxHalfExtentsScaled);
// draw the shape inflated by the contact offset
debugDisplay.DrawWireBox(-boxHalfExtentsScaledWithContactOffset, boxHalfExtentsScaledWithContactOffset);
debugDisplay.PopMatrix();
}
}
}
// EditorComponentBase
void EditorCharacterControllerComponent::BuildGameEntity(AZ::Entity* gameEntity)
{
switch (m_proxyShapeConfiguration.m_shapeType)
{
case Physics::ShapeType::Box:
gameEntity->CreateComponent<CharacterControllerComponent>(
AZStd::make_unique<CharacterControllerConfiguration>(m_configuration),
AZStd::make_unique<Physics::BoxShapeConfiguration>(m_proxyShapeConfiguration.m_box));
break;
case Physics::ShapeType::Capsule:
gameEntity->CreateComponent<CharacterControllerComponent>(
AZStd::make_unique<CharacterControllerConfiguration>(m_configuration),
AZStd::make_unique<Physics::CapsuleShapeConfiguration>(m_proxyShapeConfiguration.m_capsule));
break;
}
}
// editor change notifications
AZ::u32 EditorCharacterControllerComponent::OnControllerConfigChanged()
{
if (m_proxyShapeConfiguration.IsCapsuleConfig())
{
float capsuleHeight = m_proxyShapeConfiguration.m_capsule.m_height;
m_configuration.m_stepHeight = AZ::GetClamp(m_configuration.m_stepHeight, 0.0f, capsuleHeight - HeightEpsilon);
}
else if (m_proxyShapeConfiguration.IsBoxConfig())
{
float boxHeight = m_proxyShapeConfiguration.m_box.m_dimensions.GetZ();
m_configuration.m_stepHeight = AZ::GetClamp(m_configuration.m_stepHeight, 0.0f, boxHeight - HeightEpsilon);
}
return AZ::Edit::PropertyRefreshLevels::ValuesOnly;
}
AZ::u32 EditorCharacterControllerComponent::OnShapeConfigChanged()
{
float minHeight = m_configuration.m_stepHeight + HeightEpsilon;
if (m_proxyShapeConfiguration.IsCapsuleConfig())
{
m_proxyShapeConfiguration.m_capsule.m_height = AZ::GetMax(m_proxyShapeConfiguration.m_capsule.m_height, minHeight);
}
else if (m_proxyShapeConfiguration.IsBoxConfig())
{
float height = m_proxyShapeConfiguration.m_box.m_dimensions.GetZ();
m_proxyShapeConfiguration.m_box.m_dimensions.SetZ(AZ::GetMax(height, minHeight));
}
return AZ::Edit::PropertyRefreshLevels::ValuesOnly;
}
} // namespace PhysX
|
// Copyright 2019 The Fuchsia 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 "src/ui/a11y/lib/view/view_manager.h"
#include <fuchsia/accessibility/cpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fdio/fd.h>
#include <lib/gtest/test_loop_fixture.h>
#include <lib/sys/cpp/testing/component_context_provider.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/vfs/cpp/pseudo_dir.h>
#include <lib/zx/event.h>
#include <map>
#include <vector>
#include <gtest/gtest.h>
#include "src/ui/a11y/bin/a11y_manager/tests/util/util.h"
#include "src/ui/a11y/lib/annotation/tests/mocks/mock_annotation_view.h"
#include "src/ui/a11y/lib/semantics/tests/mocks/mock_semantic_listener.h"
#include "src/ui/a11y/lib/semantics/tests/mocks/mock_semantic_provider.h"
#include "src/ui/a11y/lib/semantics/tests/mocks/mock_semantic_tree_service_factory.h"
#include "src/ui/a11y/lib/semantics/tests/mocks/mock_semantics_event_manager.h"
#include "src/ui/a11y/lib/util/util.h"
#include "src/ui/a11y/lib/view/tests/mocks/mock_view_semantics.h"
namespace accessibility_test {
namespace {
using fuchsia::accessibility::semantics::Attributes;
using fuchsia::accessibility::semantics::Node;
using fuchsia::accessibility::semantics::NodePtr;
using fuchsia::accessibility::semantics::Role;
using fuchsia::accessibility::semantics::SemanticsManager;
class ViewManagerTest : public gtest::TestLoopFixture {
public:
ViewManagerTest() = default;
void SetUp() override {
gtest::TestLoopFixture::SetUp();
tree_service_factory_ = std::make_unique<MockSemanticTreeServiceFactory>();
tree_service_factory_ptr_ = tree_service_factory_.get();
auto view_semantics_factory = std::make_unique<MockViewSemanticsFactory>();
view_semantics_factory_ = view_semantics_factory.get();
auto annotation_view_factory = std::make_unique<MockAnnotationViewFactory>();
annotation_view_factory_ = annotation_view_factory.get();
view_manager_ = std::make_unique<a11y::ViewManager>(
std::move(tree_service_factory_), std::move(view_semantics_factory),
std::move(annotation_view_factory), std::make_unique<MockSemanticsEventManager>(),
context_provider_.context(), debug_dir());
view_manager_->SetAnnotationsEnabled(true);
semantic_provider_ =
std::make_unique<MockSemanticProvider>(view_manager_.get(), view_manager_.get());
RunLoopUntilIdle();
}
vfs::PseudoDir* debug_dir() { return context_provider_.context()->outgoing()->debug_dir(); }
void AddNodeToTree(uint32_t node_id, std::string label,
std::vector<uint32_t> child_ids = std::vector<uint32_t>()) {
std::vector<a11y::SemanticTree::TreeUpdate> node_updates;
auto node = CreateTestNode(node_id, label, child_ids);
node_updates.emplace_back(std::move(node));
ApplyNodeUpdates(std::move(node_updates));
}
void ApplyNodeUpdates(std::vector<a11y::SemanticTree::TreeUpdate> node_updates) {
auto mock_view_semantics = view_semantics_factory_->GetViewSemantics();
ASSERT_TRUE(mock_view_semantics);
auto tree_ptr = mock_view_semantics->GetTree();
ASSERT_TRUE(tree_ptr);
ASSERT_TRUE(tree_ptr->Update(std::move(node_updates)));
RunLoopUntilIdle();
}
sys::testing::ComponentContextProvider context_provider_;
std::unique_ptr<MockSemanticTreeServiceFactory> tree_service_factory_;
std::unique_ptr<a11y::ViewManager> view_manager_;
std::unique_ptr<MockSemanticProvider> semantic_provider_;
MockSemanticTreeServiceFactory* tree_service_factory_ptr_;
MockViewSemanticsFactory* view_semantics_factory_;
MockAnnotationViewFactory* annotation_view_factory_;
};
TEST_F(ViewManagerTest, ProviderGetsNotifiedOfSemanticsEnabled) {
// Enable Semantics Manager.
view_manager_->SetSemanticsEnabled(true);
// Upon initialization, MockSemanticProvider calls RegisterViewForSemantics().
// Ensure that it called the factory to instantiate a new service.
EXPECT_TRUE(tree_service_factory_ptr_->service());
RunLoopUntilIdle();
EXPECT_TRUE(semantic_provider_->GetSemanticsEnabled());
// Disable Semantics Manager.
view_manager_->SetSemanticsEnabled(false);
RunLoopUntilIdle();
// Semantics Listener should get notified about Semantics manager disable.
EXPECT_FALSE(semantic_provider_->GetSemanticsEnabled());
}
TEST_F(ViewManagerTest, ClosesChannel) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
EXPECT_TRUE(view_manager_->ViewHasSemantics(semantic_provider_->koid()));
// Forces the client to disconnect.
semantic_provider_->SendEventPairSignal();
RunLoopUntilIdle();
EXPECT_FALSE(view_manager_->ViewHasSemantics(semantic_provider_->koid()));
}
// Tests that log file is removed when semantic tree service entry is removed from semantics
// manager.
TEST_F(ViewManagerTest, LogFileRemoved) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
std::string debug_file = std::to_string(semantic_provider_->koid());
{
vfs::internal::Node* node;
EXPECT_EQ(ZX_OK, debug_dir()->Lookup(debug_file, &node));
}
// Forces the client to disconnect.
semantic_provider_->SendEventPairSignal();
RunLoopUntilIdle();
// Check Log File is removed.
{
vfs::internal::Node* node;
EXPECT_EQ(ZX_ERR_NOT_FOUND, debug_dir()->Lookup(debug_file, &node));
}
}
TEST_F(ViewManagerTest, SemanticsSourceViewHasSemantics) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
a11y::SemanticsSource* semantics_source = view_manager_.get();
EXPECT_TRUE(semantics_source->ViewHasSemantics(a11y::GetKoid(semantic_provider_->view_ref())));
// Forces the client to disconnect.
semantic_provider_->SendEventPairSignal();
RunLoopUntilIdle();
EXPECT_FALSE(semantics_source->ViewHasSemantics(a11y::GetKoid(semantic_provider_->view_ref())));
}
TEST_F(ViewManagerTest, SemanticsSourceViewRefClone) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
a11y::SemanticsSource* semantics_source = view_manager_.get();
auto view_ref_or_null =
semantics_source->ViewRefClone(a11y::GetKoid(semantic_provider_->view_ref()));
EXPECT_EQ(a11y::GetKoid(semantic_provider_->view_ref()), a11y::GetKoid(*view_ref_or_null));
// Forces the client to disconnect.
semantic_provider_->SendEventPairSignal();
RunLoopUntilIdle();
// The view is not providing semantics anymore, so there is no return value.
EXPECT_FALSE(semantics_source->ViewRefClone(a11y::GetKoid(semantic_provider_->view_ref())));
}
TEST_F(ViewManagerTest, SemanticsSourceGetSemanticNode) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
AddNodeToTree(0u, "test_label");
const auto node = view_manager_->GetSemanticNode(semantic_provider_->koid(), 0u);
EXPECT_TRUE(node);
EXPECT_TRUE(node->has_attributes());
EXPECT_TRUE(node->attributes().has_label());
EXPECT_EQ(node->attributes().label(), "test_label");
}
TEST_F(ViewManagerTest, SemanticsSourceGetParentNode) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
std::vector<a11y::SemanticTree::TreeUpdate> node_updates;
node_updates.emplace_back(CreateTestNode(0u, "test_label_0", {1u, 2u, 3u}));
node_updates.emplace_back(CreateTestNode(1u, "test_label_1"));
node_updates.emplace_back(CreateTestNode(2u, "test_label_2"));
node_updates.emplace_back(CreateTestNode(3u, "test_label_3"));
ApplyNodeUpdates(std::move(node_updates));
const auto root_node = view_manager_->GetParentNode(semantic_provider_->koid(), 2u);
const auto null_node = view_manager_->GetParentNode(semantic_provider_->koid(), 0u);
EXPECT_TRUE(root_node);
EXPECT_EQ(root_node->node_id(), 0u);
EXPECT_FALSE(null_node);
}
TEST_F(ViewManagerTest, SemanticsSourceGetNeighboringNodes) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
auto mock_tree = tree_service_factory_ptr_->semantic_tree();
ASSERT_TRUE(mock_tree);
auto next_node = CreateTestNode(3u, "test_label_3");
mock_tree->SetNextNode(&next_node);
auto previous_node = CreateTestNode(1u, "test_label_1");
mock_tree->SetPreviousNode(&previous_node);
const auto returned_next_node = view_manager_->GetNextNode(
semantic_provider_->koid(), 2u,
[](const fuchsia::accessibility::semantics::Node* node) { return true; });
const auto returned_previous_node = view_manager_->GetPreviousNode(
semantic_provider_->koid(), 2u,
[](const fuchsia::accessibility::semantics::Node* node) { return true; });
EXPECT_TRUE(returned_next_node);
EXPECT_EQ(returned_next_node->node_id(), 3u);
EXPECT_TRUE(returned_previous_node);
EXPECT_EQ(returned_previous_node->node_id(), 1u);
}
TEST_F(ViewManagerTest, SemanticsSourceHitTest) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
AddNodeToTree(0u, "test_label");
semantic_provider_->SetHitTestResult(0u);
view_manager_->ExecuteHitTesting(semantic_provider_->koid(), fuchsia::math::PointF(),
[](fuchsia::accessibility::semantics::Hit hit) {
EXPECT_TRUE(hit.has_node_id());
EXPECT_EQ(hit.node_id(), 0u);
});
RunLoopUntilIdle();
}
TEST_F(ViewManagerTest, SemanticsSourcePerformAction) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
AddNodeToTree(0u, "test_label");
view_manager_->PerformAccessibilityAction(semantic_provider_->koid(), 0u,
fuchsia::accessibility::semantics::Action::DEFAULT,
[](bool result) { EXPECT_TRUE(result); });
RunLoopUntilIdle();
EXPECT_EQ(semantic_provider_->GetRequestedAction(),
fuchsia::accessibility::semantics::Action::DEFAULT);
EXPECT_EQ(semantic_provider_->GetRequestedActionNodeId(), 0u);
}
TEST_F(ViewManagerTest, SemanticsSourcePerformActionFailsBecausePointsToWrongTree) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
AddNodeToTree(0u, "test_label");
bool callback_ran = false;
view_manager_->PerformAccessibilityAction(
semantic_provider_->koid() +
1 /*to simulate a koid that does not match the one we are expeting*/,
0u, fuchsia::accessibility::semantics::Action::DEFAULT, [&callback_ran](bool result) {
callback_ran = true;
EXPECT_FALSE(result);
});
RunLoopUntilIdle();
EXPECT_TRUE(callback_ran);
}
TEST_F(ViewManagerTest, FocusHighlightManagerDrawAndClearHighlights) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
std::vector<a11y::SemanticTree::TreeUpdate> node_updates;
node_updates.emplace_back(CreateTestNode(0u, "test_label_0", {1u}));
auto node_with_bounding_box = CreateTestNode(1u, "test_label_1");
fuchsia::ui::gfx::BoundingBox bounding_box = {.min = {.x = 0, .y = 0, .z = 0},
.max = {.x = 1.0, .y = 2.0, .z = 3.0}};
node_with_bounding_box.set_location(bounding_box);
node_updates.emplace_back(std::move(node_with_bounding_box));
ApplyNodeUpdates(std::move(node_updates));
a11y::FocusHighlightManager::SemanticNodeIdentifier newly_highlighted_node;
newly_highlighted_node.koid = semantic_provider_->koid();
newly_highlighted_node.node_id = 1u;
view_manager_->UpdateHighlight(newly_highlighted_node);
auto highlighted_view = annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
ASSERT_TRUE(highlighted_view);
auto highlight = highlighted_view->GetCurrentFocusHighlight();
EXPECT_TRUE(highlight.has_value());
EXPECT_EQ(highlight->max.x, 1.0);
EXPECT_EQ(highlight->max.y, 2.0);
EXPECT_EQ(highlight->max.z, 3.0);
view_manager_->ClearFocusHighlights();
auto maybe_highlighted_view =
annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
ASSERT_TRUE(maybe_highlighted_view);
auto maybe_highlight = maybe_highlighted_view->GetCurrentFocusHighlight();
EXPECT_FALSE(maybe_highlight.has_value());
}
TEST_F(ViewManagerTest, FocusHighlightManagerDrawAndClearMagnificationHighlight) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
// Create test nodes.
std::vector<a11y::SemanticTree::TreeUpdate> node_updates;
{
fuchsia::ui::gfx::BoundingBox bounding_box = {.min = {.x = 0.0f, .y = 0.0f, .z = 1.0f},
.max = {.x = 1024.0f, .y = 600.0f, .z = 1.0f}};
auto node = CreateTestNode(0u, "test_label_0", {});
node.set_transform({10, 0, 0, 0, 0, 10, 0, 0, 0, 0, 10, 0, 50, 60, 70, 1});
node.set_location(std::move(bounding_box));
node_updates.emplace_back(std::move(node));
}
ApplyNodeUpdates(std::move(node_updates));
// Highlight magnification viewport.
view_manager_->HighlightMagnificationViewport(semantic_provider_->koid(), 2.0f, -.2f, .4f);
auto highlighted_view = annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
const auto& highlight_bounding_box = highlighted_view->GetCurrentMagnificationHighlight();
EXPECT_TRUE(highlight_bounding_box.has_value());
EXPECT_EQ(highlight_bounding_box->min.x, 358.4f);
EXPECT_EQ(highlight_bounding_box->min.y, 180.0f);
EXPECT_EQ(highlight_bounding_box->max.x, 870.4f);
EXPECT_EQ(highlight_bounding_box->max.y, 480.0f);
const auto& highlight_translation =
highlighted_view->GetMagnificationHighlightTranslationVector();
EXPECT_TRUE(highlight_translation.has_value());
EXPECT_EQ((*highlight_translation)[0], 50.0f);
EXPECT_EQ((*highlight_translation)[1], 60.0f);
EXPECT_EQ((*highlight_translation)[2], 70.0f);
const auto& highlight_scale = highlighted_view->GetMagnificationHighlightScaleVector();
EXPECT_TRUE(highlight_scale.has_value());
EXPECT_EQ((*highlight_scale)[0], 10.0f);
EXPECT_EQ((*highlight_scale)[1], 10.0f);
view_manager_->ClearMagnificationHighlights();
RunLoopUntilIdle();
auto maybe_highlighted_view =
annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
ASSERT_TRUE(maybe_highlighted_view);
auto maybe_highlight = maybe_highlighted_view->GetCurrentMagnificationHighlight();
EXPECT_FALSE(maybe_highlight.has_value());
}
TEST_F(ViewManagerTest, FocusHighlightManagerDisableAnnotations) {
view_manager_->SetSemanticsEnabled(true);
RunLoopUntilIdle();
std::vector<a11y::SemanticTree::TreeUpdate> node_updates;
node_updates.emplace_back(CreateTestNode(0u, "test_label_0", {1u}));
auto node_with_bounding_box = CreateTestNode(1u, "test_label_1");
fuchsia::ui::gfx::BoundingBox bounding_box = {.min = {.x = 0, .y = 0, .z = 0},
.max = {.x = 1.0, .y = 2.0, .z = 3.0}};
node_with_bounding_box.set_location(bounding_box);
node_updates.emplace_back(std::move(node_with_bounding_box));
ApplyNodeUpdates(std::move(node_updates));
a11y::FocusHighlightManager::SemanticNodeIdentifier newly_highlighted_node;
newly_highlighted_node.koid = semantic_provider_->koid();
newly_highlighted_node.node_id = 1u;
view_manager_->UpdateHighlight(newly_highlighted_node);
RunLoopUntilIdle();
// Highlight magnification viewport.
view_manager_->HighlightMagnificationViewport(semantic_provider_->koid(), 2.0f, -.2f, .4f);
RunLoopUntilIdle();
auto highlighted_view = annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
ASSERT_TRUE(highlighted_view);
auto highlight = highlighted_view->GetCurrentFocusHighlight();
EXPECT_TRUE(highlight.has_value());
EXPECT_EQ(highlight->max.x, 1.0);
EXPECT_EQ(highlight->max.y, 2.0);
EXPECT_EQ(highlight->max.z, 3.0);
// Disable annotations.
view_manager_->SetAnnotationsEnabled(false);
// Verify that focus highlights were cleared.
auto maybe_highlighted_view =
annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
ASSERT_TRUE(maybe_highlighted_view);
auto maybe_highlight = maybe_highlighted_view->GetCurrentFocusHighlight();
EXPECT_FALSE(maybe_highlight.has_value());
// Verify that magnification highlights were cleared.
maybe_highlighted_view = annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
ASSERT_TRUE(maybe_highlighted_view);
maybe_highlight = maybe_highlighted_view->GetCurrentMagnificationHighlight();
EXPECT_FALSE(maybe_highlight.has_value());
}
TEST_F(ViewManagerTest, FocusHighlightManagerDrawHighlightWithAnnotationsDisabled) {
view_manager_->SetAnnotationsEnabled(false);
std::vector<a11y::SemanticTree::TreeUpdate> node_updates;
node_updates.emplace_back(CreateTestNode(0u, "test_label_0", {1u}));
auto node_with_bounding_box = CreateTestNode(1u, "test_label_1");
fuchsia::ui::gfx::BoundingBox bounding_box = {.min = {.x = 0, .y = 0, .z = 0},
.max = {.x = 1.0, .y = 2.0, .z = 3.0}};
node_with_bounding_box.set_location(bounding_box);
node_updates.emplace_back(std::move(node_with_bounding_box));
ApplyNodeUpdates(std::move(node_updates));
a11y::FocusHighlightManager::SemanticNodeIdentifier newly_highlighted_node;
newly_highlighted_node.koid = semantic_provider_->koid();
newly_highlighted_node.node_id = 1u;
view_manager_->UpdateHighlight(newly_highlighted_node);
auto maybe_highlighted_view =
annotation_view_factory_->GetAnnotationView(semantic_provider_->koid());
ASSERT_TRUE(maybe_highlighted_view);
auto maybe_highlight = maybe_highlighted_view->GetCurrentFocusHighlight();
EXPECT_FALSE(maybe_highlight.has_value());
}
TEST_F(ViewManagerTest, VirtualkeyboardListenerUpdates) {
EXPECT_TRUE(semantic_provider_->IsVirtualkeyboardListenerConnected());
EXPECT_FALSE(view_manager_->ViewHasVisibleVirtualkeyboard(semantic_provider_->koid()));
semantic_provider_->UpdateVirtualkeyboardVisibility(true);
RunLoopUntilIdle();
EXPECT_TRUE(view_manager_->ViewHasVisibleVirtualkeyboard(semantic_provider_->koid()));
auto invalid_koid = semantic_provider_->koid() + 1;
EXPECT_FALSE(view_manager_->ViewHasVisibleVirtualkeyboard(invalid_koid));
// Connects a second semantic provider which tries to add a new virtual keyboard listener. This
// one should fail, as only one registered is supported.
auto semantic_provider_2 =
std::make_unique<MockSemanticProvider>(view_manager_.get(), view_manager_.get());
RunLoopUntilIdle();
EXPECT_FALSE(semantic_provider_2->IsVirtualkeyboardListenerConnected());
semantic_provider_->UpdateVirtualkeyboardVisibility(false);
RunLoopUntilIdle();
EXPECT_FALSE(view_manager_->ViewHasVisibleVirtualkeyboard(semantic_provider_->koid()));
}
} // namespace
} // namespace accessibility_test
|
// Copyright 2006-2008 the V8 project authors. 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 <ctype.h>
#include <stdlib.h>
#include "v8.h"
#include "platform.h"
#include "smart-pointers.h"
#include "string-stream.h"
namespace v8 {
namespace internal {
// Define all of our flags.
#define FLAG_MODE_DEFINE
#include "flag-definitions.h"
// Define all of our flags default values.
#define FLAG_MODE_DEFINE_DEFAULTS
#include "flag-definitions.h"
namespace {
// This structure represents a single entry in the flag system, with a pointer
// to the actual flag, default value, comment, etc. This is designed to be POD
// initialized as to avoid requiring static constructors.
struct Flag {
enum FlagType { TYPE_BOOL, TYPE_INT, TYPE_FLOAT, TYPE_STRING, TYPE_ARGS };
FlagType type_; // What type of flag, bool, int, or string.
const char* name_; // Name of the flag, ex "my_flag".
void* valptr_; // Pointer to the global flag variable.
const void* defptr_; // Pointer to the default value.
const char* cmt_; // A comment about the flags purpose.
bool owns_ptr_; // Does the flag own its string value?
FlagType type() const { return type_; }
const char* name() const { return name_; }
const char* comment() const { return cmt_; }
bool* bool_variable() const {
ASSERT(type_ == TYPE_BOOL);
return reinterpret_cast<bool*>(valptr_);
}
int* int_variable() const {
ASSERT(type_ == TYPE_INT);
return reinterpret_cast<int*>(valptr_);
}
double* float_variable() const {
ASSERT(type_ == TYPE_FLOAT);
return reinterpret_cast<double*>(valptr_);
}
const char* string_value() const {
ASSERT(type_ == TYPE_STRING);
return *reinterpret_cast<const char**>(valptr_);
}
void set_string_value(const char* value, bool owns_ptr) {
ASSERT(type_ == TYPE_STRING);
const char** ptr = reinterpret_cast<const char**>(valptr_);
if (owns_ptr_ && *ptr != NULL) DeleteArray(*ptr);
*ptr = value;
owns_ptr_ = owns_ptr;
}
JSArguments* args_variable() const {
ASSERT(type_ == TYPE_ARGS);
return reinterpret_cast<JSArguments*>(valptr_);
}
bool bool_default() const {
ASSERT(type_ == TYPE_BOOL);
return *reinterpret_cast<const bool*>(defptr_);
}
int int_default() const {
ASSERT(type_ == TYPE_INT);
return *reinterpret_cast<const int*>(defptr_);
}
double float_default() const {
ASSERT(type_ == TYPE_FLOAT);
return *reinterpret_cast<const double*>(defptr_);
}
const char* string_default() const {
ASSERT(type_ == TYPE_STRING);
return *reinterpret_cast<const char* const *>(defptr_);
}
JSArguments args_default() const {
ASSERT(type_ == TYPE_ARGS);
return *reinterpret_cast<const JSArguments*>(defptr_);
}
// Compare this flag's current value against the default.
bool IsDefault() const {
switch (type_) {
case TYPE_BOOL:
return *bool_variable() == bool_default();
case TYPE_INT:
return *int_variable() == int_default();
case TYPE_FLOAT:
return *float_variable() == float_default();
case TYPE_STRING: {
const char* str1 = string_value();
const char* str2 = string_default();
if (str2 == NULL) return str1 == NULL;
if (str1 == NULL) return str2 == NULL;
return strcmp(str1, str2) == 0;
}
case TYPE_ARGS:
return args_variable()->argc() == 0;
}
UNREACHABLE();
return true;
}
// Set a flag back to it's default value.
void Reset() {
switch (type_) {
case TYPE_BOOL:
*bool_variable() = bool_default();
break;
case TYPE_INT:
*int_variable() = int_default();
break;
case TYPE_FLOAT:
*float_variable() = float_default();
break;
case TYPE_STRING:
set_string_value(string_default(), false);
break;
case TYPE_ARGS:
*args_variable() = args_default();
break;
}
}
};
Flag flags[] = {
#define FLAG_MODE_META
#include "flag-definitions.h"
};
const size_t num_flags = sizeof(flags) / sizeof(*flags);
} // namespace
static const char* Type2String(Flag::FlagType type) {
switch (type) {
case Flag::TYPE_BOOL: return "bool";
case Flag::TYPE_INT: return "int";
case Flag::TYPE_FLOAT: return "float";
case Flag::TYPE_STRING: return "string";
case Flag::TYPE_ARGS: return "arguments";
}
UNREACHABLE();
return NULL;
}
static SmartArrayPointer<const char> ToString(Flag* flag) {
HeapStringAllocator string_allocator;
StringStream buffer(&string_allocator);
switch (flag->type()) {
case Flag::TYPE_BOOL:
buffer.Add("%s", (*flag->bool_variable() ? "true" : "false"));
break;
case Flag::TYPE_INT:
buffer.Add("%d", *flag->int_variable());
break;
case Flag::TYPE_FLOAT:
buffer.Add("%f", FmtElm(*flag->float_variable()));
break;
case Flag::TYPE_STRING: {
const char* str = flag->string_value();
buffer.Add("%s", str ? str : "NULL");
break;
}
case Flag::TYPE_ARGS: {
JSArguments args = *flag->args_variable();
if (args.argc() > 0) {
buffer.Add("%s", args[0]);
for (int i = 1; i < args.argc(); i++) {
buffer.Add(" %s", args[i]);
}
}
break;
}
}
return buffer.ToCString();
}
// static
List<const char*>* FlagList::argv() {
List<const char*>* args = new List<const char*>(8);
Flag* args_flag = NULL;
for (size_t i = 0; i < num_flags; ++i) {
Flag* f = &flags[i];
if (!f->IsDefault()) {
if (f->type() == Flag::TYPE_ARGS) {
ASSERT(args_flag == NULL);
args_flag = f; // Must be last in arguments.
continue;
}
HeapStringAllocator string_allocator;
StringStream buffer(&string_allocator);
if (f->type() != Flag::TYPE_BOOL || *(f->bool_variable())) {
buffer.Add("--%s", f->name());
} else {
buffer.Add("--no%s", f->name());
}
args->Add(buffer.ToCString().Detach());
if (f->type() != Flag::TYPE_BOOL) {
args->Add(ToString(f).Detach());
}
}
}
if (args_flag != NULL) {
HeapStringAllocator string_allocator;
StringStream buffer(&string_allocator);
buffer.Add("--%s", args_flag->name());
args->Add(buffer.ToCString().Detach());
JSArguments jsargs = *args_flag->args_variable();
for (int j = 0; j < jsargs.argc(); j++) {
args->Add(StrDup(jsargs[j]));
}
}
return args;
}
// Helper function to parse flags: Takes an argument arg and splits it into
// a flag name and flag value (or NULL if they are missing). is_bool is set
// if the arg started with "-no" or "--no". The buffer may be used to NUL-
// terminate the name, it must be large enough to hold any possible name.
static void SplitArgument(const char* arg,
char* buffer,
int buffer_size,
const char** name,
const char** value,
bool* is_bool) {
*name = NULL;
*value = NULL;
*is_bool = false;
if (arg != NULL && *arg == '-') {
// find the begin of the flag name
arg++; // remove 1st '-'
if (*arg == '-') {
arg++; // remove 2nd '-'
if (arg[0] == '\0') {
const char* kJSArgumentsFlagName = "js_arguments";
*name = kJSArgumentsFlagName;
return;
}
}
if (arg[0] == 'n' && arg[1] == 'o') {
arg += 2; // remove "no"
*is_bool = true;
}
*name = arg;
// find the end of the flag name
while (*arg != '\0' && *arg != '=')
arg++;
// get the value if any
if (*arg == '=') {
// make a copy so we can NUL-terminate flag name
size_t n = arg - *name;
CHECK(n < static_cast<size_t>(buffer_size)); // buffer is too small
memcpy(buffer, *name, n);
buffer[n] = '\0';
*name = buffer;
// get the value
*value = arg + 1;
}
}
}
inline char NormalizeChar(char ch) {
return ch == '_' ? '-' : ch;
}
static bool EqualNames(const char* a, const char* b) {
for (int i = 0; NormalizeChar(a[i]) == NormalizeChar(b[i]); i++) {
if (a[i] == '\0') {
return true;
}
}
return false;
}
static Flag* FindFlag(const char* name) {
for (size_t i = 0; i < num_flags; ++i) {
if (EqualNames(name, flags[i].name()))
return &flags[i];
}
return NULL;
}
// static
int FlagList::SetFlagsFromCommandLine(int* argc,
char** argv,
bool remove_flags) {
int return_code = 0;
// parse arguments
for (int i = 1; i < *argc;) {
int j = i; // j > 0
const char* arg = argv[i++];
// split arg into flag components
char buffer[1*KB];
const char* name;
const char* value;
bool is_bool;
SplitArgument(arg, buffer, sizeof buffer, &name, &value, &is_bool);
if (name != NULL) {
// lookup the flag
Flag* flag = FindFlag(name);
if (flag == NULL) {
if (remove_flags) {
// We don't recognize this flag but since we're removing
// the flags we recognize we assume that the remaining flags
// will be processed somewhere else so this flag might make
// sense there.
continue;
} else {
fprintf(stderr, "Error: unrecognized flag %s\n"
"Try --help for options\n", arg);
return_code = j;
break;
}
}
// if we still need a flag value, use the next argument if available
if (flag->type() != Flag::TYPE_BOOL &&
flag->type() != Flag::TYPE_ARGS &&
value == NULL) {
if (i < *argc) {
value = argv[i++];
} else {
fprintf(stderr, "Error: missing value for flag %s of type %s\n"
"Try --help for options\n",
arg, Type2String(flag->type()));
return_code = j;
break;
}
}
// set the flag
char* endp = const_cast<char*>(""); // *endp is only read
switch (flag->type()) {
case Flag::TYPE_BOOL:
*flag->bool_variable() = !is_bool;
break;
case Flag::TYPE_INT:
*flag->int_variable() = strtol(value, &endp, 10); // NOLINT
break;
case Flag::TYPE_FLOAT:
*flag->float_variable() = strtod(value, &endp);
break;
case Flag::TYPE_STRING:
flag->set_string_value(value ? StrDup(value) : NULL, true);
break;
case Flag::TYPE_ARGS: {
int start_pos = (value == NULL) ? i : i - 1;
int js_argc = *argc - start_pos;
const char** js_argv = NewArray<const char*>(js_argc);
if (value != NULL) {
js_argv[0] = StrDup(value);
}
for (int k = i; k < *argc; k++) {
js_argv[k - start_pos] = StrDup(argv[k]);
}
*flag->args_variable() = JSArguments::Create(js_argc, js_argv);
i = *argc; // Consume all arguments
break;
}
}
// handle errors
if ((flag->type() == Flag::TYPE_BOOL && value != NULL) ||
(flag->type() != Flag::TYPE_BOOL && is_bool) ||
*endp != '\0') {
fprintf(stderr, "Error: illegal value for flag %s of type %s\n"
"Try --help for options\n",
arg, Type2String(flag->type()));
return_code = j;
break;
}
// remove the flag & value from the command
if (remove_flags) {
while (j < i) {
argv[j++] = NULL;
}
}
}
}
// shrink the argument list
if (remove_flags) {
int j = 1;
for (int i = 1; i < *argc; i++) {
if (argv[i] != NULL)
argv[j++] = argv[i];
}
*argc = j;
}
if (FLAG_help) {
PrintHelp();
exit(0);
}
// parsed all flags successfully
return return_code;
}
static char* SkipWhiteSpace(char* p) {
while (*p != '\0' && isspace(*p) != 0) p++;
return p;
}
static char* SkipBlackSpace(char* p) {
while (*p != '\0' && isspace(*p) == 0) p++;
return p;
}
// static
int FlagList::SetFlagsFromString(const char* str, int len) {
// make a 0-terminated copy of str
ScopedVector<char> copy0(len + 1);
memcpy(copy0.start(), str, len);
copy0[len] = '\0';
// strip leading white space
char* copy = SkipWhiteSpace(copy0.start());
// count the number of 'arguments'
int argc = 1; // be compatible with SetFlagsFromCommandLine()
for (char* p = copy; *p != '\0'; argc++) {
p = SkipBlackSpace(p);
p = SkipWhiteSpace(p);
}
// allocate argument array
ScopedVector<char*> argv(argc);
// split the flags string into arguments
argc = 1; // be compatible with SetFlagsFromCommandLine()
for (char* p = copy; *p != '\0'; argc++) {
argv[argc] = p;
p = SkipBlackSpace(p);
if (*p != '\0') *p++ = '\0'; // 0-terminate argument
p = SkipWhiteSpace(p);
}
// set the flags
int result = SetFlagsFromCommandLine(&argc, argv.start(), false);
return result;
}
// static
void FlagList::ResetAllFlags() {
for (size_t i = 0; i < num_flags; ++i) {
flags[i].Reset();
}
}
// static
void FlagList::PrintHelp() {
printf("Usage:\n");
printf(" shell [options] -e string\n");
printf(" execute string in V8\n");
printf(" shell [options] file1 file2 ... filek\n");
printf(" run JavaScript scripts in file1, file2, ..., filek\n");
printf(" shell [options]\n");
printf(" shell [options] --shell [file1 file2 ... filek]\n");
printf(" run an interactive JavaScript shell\n");
printf(" d8 [options] file1 file2 ... filek\n");
printf(" d8 [options]\n");
printf(" d8 [options] --shell [file1 file2 ... filek]\n");
printf(" run the new debugging shell\n\n");
printf("Options:\n");
for (size_t i = 0; i < num_flags; ++i) {
Flag* f = &flags[i];
SmartArrayPointer<const char> value = ToString(f);
printf(" --%s (%s)\n type: %s default: %s\n",
f->name(), f->comment(), Type2String(f->type()), *value);
}
}
void FlagList::EnforceFlagImplications() {
#define FLAG_MODE_DEFINE_IMPLICATIONS
#include "flag-definitions.h"
#undef FLAG_MODE_DEFINE_IMPLICATIONS
}
} } // namespace v8::internal
|
// Created on: 2000-08-17
// Created by: Andrey BETENEV
// Copyright (c) 2000-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESCAFControl_Writer_HeaderFile
#define _IGESCAFControl_Writer_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <IGESControl_Writer.hxx>
#include <Standard_CString.hxx>
#include <TDF_LabelSequence.hxx>
#include <XCAFPrs_DataMapOfShapeStyle.hxx>
#include <XCAFPrs_DataMapOfStyleTransient.hxx>
#include <TopTools_MapOfShape.hxx>
class XSControl_WorkSession;
class TDocStd_Document;
class TCollection_AsciiString;
class TopoDS_Shape;
class XCAFPrs_Style;
//! Provides a tool to write DECAF document to the
//! IGES file. Besides transfer of shapes (including
//! assemblies) provided by IGESControl, supports also
//! colors and part names
//! IGESCAFControl_Writer writer();
//! Methods for writing IGES file:
//! writer.Transfer (Document);
//! writer.Write("filename") or writer.Write(OStream) or
//! writer.Perform(Document,"filename");
//! Methods for managing the writing of attributes.
//! Colors
//! writer.SetColorMode(colormode);
//! Standard_Boolean colormode = writer.GetColorMode();
//! Layers
//! writer.SetLayerMode(layermode);
//! Standard_Boolean layermode = writer.GetLayerMode();
//! Names
//! writer.SetNameMode(namemode);
//! Standard_Boolean namemode = writer.GetNameMode();
class IGESCAFControl_Writer : public IGESControl_Writer
{
public:
DEFINE_STANDARD_ALLOC
//! Creates a writer with an empty
//! IGES model and sets ColorMode, LayerMode and NameMode to Standard_True.
Standard_EXPORT IGESCAFControl_Writer();
//! Creates a reader tool and attaches it to an already existing Session
//! Clears the session if it was not yet set for IGES
Standard_EXPORT IGESCAFControl_Writer(const Handle(XSControl_WorkSession)& WS, const Standard_Boolean scratch = Standard_True);
//! Transfers a document to a IGES model
//! Returns True if translation is OK
Standard_EXPORT Standard_Boolean Transfer (const Handle(TDocStd_Document)& doc);
//! Transfers labels to a IGES model
//! Returns True if translation is OK
Standard_EXPORT Standard_Boolean Transfer (const TDF_LabelSequence& labels);
//! Transfers label to a IGES model
//! Returns True if translation is OK
Standard_EXPORT Standard_Boolean Transfer (const TDF_Label& label);
Standard_EXPORT Standard_Boolean Perform (const Handle(TDocStd_Document)& doc, const TCollection_AsciiString& filename);
//! Transfers a document and writes it to a IGES file
//! Returns True if translation is OK
Standard_EXPORT Standard_Boolean Perform (const Handle(TDocStd_Document)& doc, const Standard_CString filename);
//! Set ColorMode for indicate write Colors or not.
Standard_EXPORT void SetColorMode (const Standard_Boolean colormode);
Standard_EXPORT Standard_Boolean GetColorMode() const;
//! Set NameMode for indicate write Name or not.
Standard_EXPORT void SetNameMode (const Standard_Boolean namemode);
Standard_EXPORT Standard_Boolean GetNameMode() const;
//! Set LayerMode for indicate write Layers or not.
Standard_EXPORT void SetLayerMode (const Standard_Boolean layermode);
Standard_EXPORT Standard_Boolean GetLayerMode() const;
protected:
//! Reads colors from DECAF document and assigns them
//! to corresponding IGES entities
Standard_EXPORT Standard_Boolean WriteAttributes (const TDF_LabelSequence& labels);
//! Reads layers from DECAF document and assigns them
//! to corresponding IGES entities
Standard_EXPORT Standard_Boolean WriteLayers (const TDF_LabelSequence& labels);
//! Recursivile iterates on subshapes and assign names
//! to IGES entity
Standard_EXPORT Standard_Boolean WriteNames (const TDF_LabelSequence& labels);
private:
//! Recursively iterates on subshapes and assigns colors
//! to faces and edges (if set)
Standard_EXPORT void MakeColors (const TopoDS_Shape& S, const XCAFPrs_DataMapOfShapeStyle& settings, XCAFPrs_DataMapOfStyleTransient& colors, TopTools_MapOfShape& Map, const XCAFPrs_Style& inherit);
Standard_Boolean myColorMode;
Standard_Boolean myNameMode;
Standard_Boolean myLayerMode;
};
#endif // _IGESCAFControl_Writer_HeaderFile
|
#include "Core.h"
namespace Upp {
#ifdef _DEBUG
void String0::Dsyn()
{
String *d_str = static_cast<String *>(this);
d_str->s = Begin();
d_str->len = GetCount();
}
#endif
String0::Rc String0::voidptr[2];
void String0::LSet(const String0& s)
{
w[2] = s.w[2];
w[3] = s.w[3];
if(s.IsRef()) {
ptr = s.ptr;
if(ptr != (char *)(voidptr + 1))
AtomicInc(s.Ref()->refcount);
}
else {
ptr = (char *)MemoryAlloc32();
// qword *d = qptr;
// const qword *q = s.qptr;
// d[0] = q[0]; d[1] = q[1]; d[2] = q[2]; d[3] = q[3];
fast_copy128(ptr, s.ptr);
fast_copy128(ptr + 16, s.ptr + 16);
}
}
void String0::LFree()
{
if(IsRef()) {
if(ptr != (char *)(voidptr + 1)) {
Rc *rc = Ref();
ASSERT(rc->refcount > 0);
if(AtomicDec(rc->refcount) == 0) MemoryFree(rc);
}
}
else
MemoryFree32(ptr);
}
dword String0::LEqual(const String0& s) const
{
int l = GetCount();
if(s.GetCount() != l) return 1;
#ifdef CPU_64
const qword *qa = (const qword *)Begin();
const qword *qb = (const qword *)s.Begin();
while(l >= 8) {
if(*qa++ != *qb++) return 1;
l -= 8;
}
const dword *da = (const dword *)qa;
const dword *db = (const dword *)qb;
if((l & 4) && *da++ != *db++) return 1;
#else
const dword *da = (const dword *)Begin();
const dword *db = (const dword *)s.Begin();
while(l >= 4) {
if(*da++ != *db++) return 1;
l -= 4;
}
#endif
const word *wa = (const word *)da;
const word *wb = (const word *)db;
if((l & 2) && *wa++ != *wb++) return 1;
return (l & 1) ? *(const char *)wa != *(const char *)wb : 0;
}
unsigned String0::LHashValue() const
{
int l = LLen();
if(l < 15) {
dword w[4];
w[0] = w[1] = w[2] = w[3] = 0;
SVO_MEMCPY((char *)w, ptr, l);
((byte *)w)[SLEN] = l;
return CombineHash(w[0], w[1], w[2], w[3]);
}
return memhash(ptr, l);
}
int String0::LCompare(const String0& s) const
{
const char *a = Begin();
int la = GetLength();
const char *b = s.Begin();
int lb = s.GetLength();
int q = fast_memcmp(a, b, min(la, lb));
return q ? q : SgnCompare(la, lb);
}
char *String0::Alloc(int count, char& kind)
{
if(count < 32) {
kind = MEDIUM;
return (char *)MemoryAlloc32();
}
size_t sz = sizeof(Rc) + count + 1;
Rc *rc = (Rc *)MemoryAllocSz(sz);
if(count == INT_MAX)
rc->alloc = INT_MAX;
else
rc->alloc = (int)sz - sizeof(Rc) - 1;
rc->refcount = 1;
kind = min(rc->alloc, 255);
return (char *)(rc + 1);
}
char *String0::Insert(int pos, int count, const char *s)
{
ASSERT(pos >= 0 && count >= 0 && pos <= GetCount());
int len = GetCount();
int newlen = len + count;
if(newlen < len) // overflow, string >2GB
Panic("String is too big!");
char *str = (char *)Begin();
if(newlen < GetAlloc() && !IsSharedRef() && (!s || s < str || s > str + len)) {
if(pos < len)
memmove(str + pos + count, str + pos, len - pos);
if(IsSmall())
SLen() = newlen;
else
LLen() = newlen;
str[newlen] = 0;
if(s)
SVO_MEMCPY(str + pos, s, count);
Dsyn();
return str + pos;
}
char kind;
char *p = Alloc(max(len >= int((int64)2 * INT_MAX / 3) ? INT_MAX : len + (len >> 1), newlen),
kind);
if(pos > 0)
SVO_MEMCPY(p, str, pos);
if(pos < len)
SVO_MEMCPY(p + pos + count, str + pos, len - pos);
if(s)
SVO_MEMCPY(p + pos, s, count);
p[newlen] = 0;
Free();
ptr = p;
LLen() = newlen;
SLen() = 15;
chr[KIND] = kind;
Dsyn();
return ptr + pos;
}
void String0::UnShare()
{
if(IsSharedRef()) {
int len = LLen();
char kind;
char *p = Alloc(len, kind);
SVO_MEMCPY(p, ptr, len + 1);
Free();
chr[KIND] = kind;
ptr = p;
}
}
void String0::SetSLen(int l)
{
SLen() = l;
memset(chr + l, 0, 15 - l);
}
void String0::Remove(int pos, int count)
{
ASSERT(pos >= 0 && count >= 0 && pos + count <= GetCount());
UnShare();
char *s = (char *)Begin();
memmove(s + pos, s + pos + count, GetCount() - pos - count + 1);
if(IsSmall())
SetSLen(SLen() - count);
else
LLen() -= count;
Dsyn();
}
void String0::Set(int pos, int chr)
{
ASSERT(pos >= 0 && pos < GetCount());
UnShare();
Ptr()[pos] = chr;
}
void String0::Trim(int pos)
{
ASSERT(pos >= 0 && pos <= GetCount());
if(IsSmall()) {
chr[pos] = 0;
SetSLen(pos);
}
else {
UnShare();
ptr[pos] = 0;
LLen() = pos;
}
Dsyn();
}
void String0::LCat(int c)
{
if(IsSmall()) {
qword *x = (qword *)MemoryAlloc32();
x[0] = q[0];
x[1] = q[1];
LLen() = SLen();
SLen() = 15;
chr[KIND] = MEDIUM;
qptr = x;
}
int l = LLen();
if(IsRef() ? !IsShared() && l < (int)Ref()->alloc : l < 31) {
ptr[l] = c;
ptr[LLen() = l + 1] = 0;
}
else {
char *s = Insert(l, 1, NULL);
s[0] = c;
s[1] = 0;
}
}
void String0::Cat(const char *s, int len)
{
if(IsSmall()) {
if(SLen() + len < 14) {
SVO_MEMCPY(chr + SLen(), s, len);
SLen() += len;
chr[(int)SLen()] = 0;
Dsyn();
return;
}
}
else
if((int)LLen() + len < LAlloc() && !IsSharedRef()) {
SVO_MEMCPY(ptr + LLen(), s, len);
LLen() += len;
ptr[LLen()] = 0;
Dsyn();
return;
}
Insert(GetCount(), len, s);
}
void String0::Reserve(int r)
{
int l = GetCount();
Insert(GetCount(), r, NULL);
Trim(l);
}
void String0::SetL(const char *s, int len)
{
char *p = Alloc(len, chr[KIND]);
memcpy(p, s, len);
p[len] = 0;
ptr = p;
LLen() = len;
SLen() = 15;
}
void String0::Set0(const char *s, int len)
{
Zero();
switch(len) {
#define MOV(x) case x: chr[x - 1] = s[x - 1];
MOV(14) MOV(13) MOV(12) MOV(11) MOV(10) MOV(9) MOV(8)
MOV(7) MOV(6) MOV(5) MOV(4) MOV(3) MOV(2) MOV(1)
case 0:
SLen() = len;
break;
default:
SetL(s, len);
};
Dsyn();
}
void String::AssignLen(const char *s, int slen)
{
int len = GetCount();
char *str = (char *)Begin();
if(s >= str && s <= str + len)
*this = String(s, slen);
else {
String0::Free();
String0::Set0(s, slen);
}
}
String String::GetVoid()
{
String s;
s.ptr = (char *)(voidptr + 1);
s.LLen() = 0;
s.SLen() = 15;
s.chr[KIND] = 50;
return s;
}
bool String::IsVoid() const
{
return IsRef() && ptr == (char *)(voidptr + 1);
}
WString String::ToWString() const
{
return WString(Begin(), GetCount());
}
int String::GetCharCount() const
{
return GetDefaultCharset() == CHARSET_UTF8 ? utf8len(Begin(), GetCount()) : GetCount();
}
String::String(StringBuffer& b)
{
if(b.pbegin == b.buffer) {
String0::Set0(b.pbegin, (int)(uintptr_t)(b.pend - b.pbegin));
return;
}
int l = b.GetLength();
if(l <= 14) {
Zero();
memcpy(chr, b.pbegin, l);
SLen() = l;
b.Free();
}
else {
ptr = b.pbegin;
ptr[l] = 0;
SLen() = 15;
LLen() = l;
chr[KIND] = min(b.GetAlloc(), 255);
if(GetAlloc() > 4 * GetLength() / 3)
Shrink();
}
b.Zero();
// char h[100];
// DLOG(sprintf(h, "String(StringBuffer) end %p (%p)", ptr, this));
Dsyn();
// DLOG(sprintf(h, "String(StringBuffer) end2 %p (%p)", ptr, this));
}
char *StringBuffer::Alloc(int count, int& alloc)
{
if(count <= 31) {
char *s = (char *)MemoryAlloc32();
alloc = 31;
return s;
}
else {
size_t sz = sizeof(Rc) + count + 1;
Rc *rc = (Rc *)MemoryAlloc(sz);
alloc = rc->alloc = (int)min((size_t)INT_MAX, sz - sizeof(Rc) - 1);
rc->refcount = 1;
return (char *)(rc + 1);
}
}
void StringBuffer::Free()
{
if(pbegin == buffer)
return;
int all = (int)(limit - pbegin);
if(all == 31)
MemoryFree32(pbegin);
if(all > 31)
MemoryFree((Rc *)pbegin - 1);
}
void StringBuffer::Realloc(dword n, const char *cat, int l)
{
int al;
size_t ep = pend - pbegin;
if(n > INT_MAX)
n = INT_MAX;
char *p = Alloc(n, al);
memcpy(p, pbegin, min((dword)GetLength(), n));
if(cat) {
if(ep + l > INT_MAX)
Panic("StringBuffer is too big!");
memcpy(p + ep, cat, l);
ep += l;
}
Free();
pbegin = p;
pend = pbegin + ep;
limit = pbegin + al;
}
void StringBuffer::Expand()
{
Realloc(GetLength() * 2);
if(pend == limit)
Panic("StringBuffer is too big!");
}
void StringBuffer::SetLength(int l)
{
if(l > GetAlloc())
Realloc(l);
pend = pbegin + l;
}
void StringBuffer::Shrink()
{
int l = GetLength();
if(l < GetAlloc() && l > 14)
Realloc(l);
pend = pbegin + l;
}
void StringBuffer::Cat(const char *s, int l)
{
if(pend + l > limit)
Realloc(max(GetLength(), l) + GetLength(), s, l);
else {
SVO_MEMCPY(pend, s, l);
pend += l;
}
}
void StringBuffer::Cat(int c, int l)
{
if(pend + l > limit)
Realloc(max(GetLength(), l) + GetLength(), NULL, l);
memset(pend, c, l);
pend += l;
}
void StringBuffer::Set(String& s)
{
s.UnShare();
int l = s.GetLength();
if(s.GetAlloc() == 14) {
pbegin = (char *)MemoryAlloc32();
limit = pbegin + 31;
memcpy(pbegin, s.Begin(), l);
pend = pbegin + l;
}
else {
pbegin = s.ptr;
pend = pbegin + l;
limit = pbegin + s.GetAlloc();
}
s.Zero();
}
String TrimLeft(const String& str)
{
const char *s = str;
if(!IsSpace(*s))
return str;
while(IsSpace((byte)*s)) s++;
return String(s, str.End());
}
String TrimRight(const String& str)
{
if(str.IsEmpty())
return str;
const char *s = str.Last();
if(!IsSpace(*s))
return str;
while(s >= ~str && IsSpace((byte)*s)) s--;
return String(~str, s + 1);
}
String TrimBoth(const String& str)
{
return TrimLeft(TrimRight(str));
}
String TrimLeft(const char *sw, int len, const String& s)
{
return s.StartsWith(sw, len) ? s.Mid(len) : s;
}
String TrimRight(const char *sw, int len, const String& s)
{
return s.EndsWith(sw, len) ? s.Mid(0, s.GetCount() - len) : s;
}
struct StringICompare__
{
int encoding;
int operator()(char a, char b) const { return ToUpper(a, encoding) - ToUpper(b, encoding); }
StringICompare__(int e) : encoding(e) {}
};
int CompareNoCase(const String& a, const String& b, byte encoding)
{
if(encoding == CHARSET_DEFAULT) encoding = GetDefaultCharset();
if(encoding == CHARSET_UTF8) return CompareNoCase(FromUtf8(a), FromUtf8(b));
return IterCompare(a.Begin(), a.End(), b.Begin(), b.End(), StringICompare__(encoding));
}
int CompareNoCase(const String& a, const char *b, byte encoding)
{
if(encoding == CHARSET_DEFAULT) encoding = GetDefaultCharset();
if(encoding == CHARSET_UTF8) return CompareNoCase(FromUtf8(a), FromUtf8(b, (int)strlen(b)));
return IterCompare(a.Begin(), a.End(), b, b + strlen(b), StringICompare__(encoding));
}
}
|
#include "reduced_particle.h"
#include "Pythia8/Pythia.h"
namespace analysis {
ReducedParticle::ReducedParticle(const Pythia8::Particle& part,
const Pythia8::Event& event) {
pt_ = part.pT();
pz_ = part.pz();
phi_ = part.phi();
eta_ = part.eta();
index_ = part.index();
pdg_ = part.id();
origin_ = CheckOrigin(event, part.index());
}
std::vector<int> FindMothers(const Pythia8::Event& event,
const std::vector<int>& places) {
std::vector<int> list_mothers;
list_mothers.reserve(event.size());
for (auto no : places) {
auto mothers_current_particle = event[no].motherList();
list_mothers.insert(list_mothers.end(), mothers_current_particle.begin(),
mothers_current_particle.end());
auto mother_of_mothers = FindMothers(event, mothers_current_particle);
list_mothers.insert(list_mothers.end(), mother_of_mothers.begin(),
mother_of_mothers.end());
}
list_mothers.shrink_to_fit();
return list_mothers;
}
int CheckOrigin(const Pythia8::Event& event, int position) {
auto mother_list = FindMothers(event, {position});
for (auto mother_no : mother_list) {
int id = event[mother_no].idAbs();
if (id == 5) return 5;
}
for (auto mother_no : mother_list) {
int id = event[mother_no].idAbs();
if (id == 4) return 4;
}
return -1;
}
} // namespace analysis
|
#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
typedef long long ll;
typedef pair<int, int> pi;
const int MOD = 1000000007;
const ll INF = 1000000000000000000LL;
const int MAX_K = 11;
const int MAX_M = 50005;
int K, M;
string strings[MAX_K];
vector<int> pre; //prefix sums
int L[MAX_K][2 * MAX_M];
map<vector<int>, pi> mp;
int main() {
freopen("cbs.in", "r", stdin);
freopen("cbs.out", "w", stdout);
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> K >> M;
for (int i = 0; i < K; ++i) cin >> strings[i];
int ans = 0;
pre = vector<int>(K, M);
for (int i = 0; i < K; ++i) fill(L[i], L[i] + 2 * MAX_M, M);
for (int i = 0; i < K; ++i) L[i][M] = 0;
mp[pre] = {0, 1};
for (int i = 0; i < M; ++i) {
int left = 0;
for (int j = 0; j < K; ++j) {
if (strings[j][i] == '(') {
L[j][++pre[j]] = i + 1;
}
else {
--pre[j];
L[j][pre[j]] = min(L[j][pre[j]], i + 1);
}
left = max(left, L[j][pre[j]]);
}
if (left == M) continue;
pi &val = mp[pre];
if (val.ff == left) ans += val.ss++;
else val = {left, 1};
}
cout << ans << '\n';
return 0;
}
|
#include <gtest/gtest.h>
#include "trick/tc.h"
#include "trick/attributes.h"
#include "trick/tc_proto.h"
#include "trick/trick_byteswap.h"
#include "trick/trick_error_hndlr.h"
class TCBlockioTest : public testing::Test {
protected:
TCBlockioTest(){}
~TCBlockioTest(){}
TCDevice* device;
void SetUp(){
device = (TCDevice *) malloc(sizeof(TCDevice));
memset( (void *)device,'\0',sizeof(TCDevice) );
}
void TearDown(){
free(device);
}
};
#if 0
TEST_F( TCBlockioTest, testNullDevice ) {
int blockio_status = tc_blockio( NULL, TC_COMM_ALL_OR_NOTHING );
EXPECT_EQ( TC_EWOULDBLOCK, blockio_status );
}
TEST_F( TCBlockioTest, testTC_COMM_BLOCKIO ) {
(void) tc_blockio( device, TC_COMM_BLOCKIO );
EXPECT_EQ( TC_COMM_BLOCKIO, device->blockio_type);
}
TEST_F( TCBlockioTest, testTC_COMM_NOBLOCKIO ) {
(void) tc_blockio( device, TC_COMM_NOBLOCKIO );
EXPECT_EQ( TC_COMM_NOBLOCKIO, device->blockio_type);
}
TEST_F( TCBlockioTest, testTC_COMM_TIMED_BLOCKIO ) {
(void) tc_blockio( device, TC_COMM_TIMED_BLOCKIO );
EXPECT_EQ( TC_COMM_TIMED_BLOCKIO, device->blockio_type );
}
TEST_F( TCBlockioTest, testTC_COMM_ALL_OR_NOTHING ) {
(void) tc_blockio( device, TC_COMM_ALL_OR_NOTHING );
EXPECT_EQ( TC_COMM_ALL_OR_NOTHING, device->blockio_type );
}
#endif
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script/script.h"
#include "scriptnum10.h"
#include "test/test_luk.h"
#include <boost/test/unit_test.hpp>
#include <limits.h>
#include <stdint.h>
BOOST_FIXTURE_TEST_SUITE(scriptnum_tests, BasicTestingSetup)
/** A selection of numbers that do not trigger int64_t overflow
* when added/subtracted. */
static const int64_t values[] = {0, 1, -2, 127, 128, -255, 256, (1LL << 15) - 1, -(1LL << 16), (1LL << 24) - 1, (1LL << 31), 1 - (1LL << 32), 1LL << 40};
static const int64_t offsets[] = {1, 0x79, 0x80, 0x81, 0xFF, 0x7FFF, 0x8000, 0xFFFF, 0x10000};
static bool verify(const CScriptNum10& bignum, const CScriptNum& scriptnum)
{
return bignum.getvch() == scriptnum.getvch() && bignum.getint() == scriptnum.getint();
}
static void CheckCreateVch(const int64_t& num)
{
CScriptNum10 bignum(num);
CScriptNum scriptnum(num);
BOOST_CHECK(verify(bignum, scriptnum));
std::vector<unsigned char> vch = bignum.getvch();
CScriptNum10 bignum2(bignum.getvch(), false);
vch = scriptnum.getvch();
CScriptNum scriptnum2(scriptnum.getvch(), false);
BOOST_CHECK(verify(bignum2, scriptnum2));
CScriptNum10 bignum3(scriptnum2.getvch(), false);
CScriptNum scriptnum3(bignum2.getvch(), false);
BOOST_CHECK(verify(bignum3, scriptnum3));
}
static void CheckCreateInt(const int64_t& num)
{
CScriptNum10 bignum(num);
CScriptNum scriptnum(num);
BOOST_CHECK(verify(bignum, scriptnum));
BOOST_CHECK(verify(CScriptNum10(bignum.getint()), CScriptNum(scriptnum.getint())));
BOOST_CHECK(verify(CScriptNum10(scriptnum.getint()), CScriptNum(bignum.getint())));
BOOST_CHECK(verify(CScriptNum10(CScriptNum10(scriptnum.getint()).getint()), CScriptNum(CScriptNum(bignum.getint()).getint())));
}
static void CheckAdd(const int64_t& num1, const int64_t& num2)
{
const CScriptNum10 bignum1(num1);
const CScriptNum10 bignum2(num2);
const CScriptNum scriptnum1(num1);
const CScriptNum scriptnum2(num2);
CScriptNum10 bignum3(num1);
CScriptNum10 bignum4(num1);
CScriptNum scriptnum3(num1);
CScriptNum scriptnum4(num1);
// int64_t overflow is undefined.
bool invalid = (((num2 > 0) && (num1 > (std::numeric_limits<int64_t>::max() - num2))) ||
((num2 < 0) && (num1 < (std::numeric_limits<int64_t>::min() - num2))));
if (!invalid) {
BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + scriptnum2));
BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + num2));
BOOST_CHECK(verify(bignum1 + bignum2, scriptnum2 + num1));
}
}
static void CheckNegate(const int64_t& num)
{
const CScriptNum10 bignum(num);
const CScriptNum scriptnum(num);
// -INT64_MIN is undefined
if (num != std::numeric_limits<int64_t>::min())
BOOST_CHECK(verify(-bignum, -scriptnum));
}
static void CheckSubtract(const int64_t& num1, const int64_t& num2)
{
const CScriptNum10 bignum1(num1);
const CScriptNum10 bignum2(num2);
const CScriptNum scriptnum1(num1);
const CScriptNum scriptnum2(num2);
bool invalid = false;
// int64_t overflow is undefined.
invalid = ((num2 > 0 && num1 < std::numeric_limits<int64_t>::min() + num2) ||
(num2 < 0 && num1 > std::numeric_limits<int64_t>::max() + num2));
if (!invalid) {
BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - scriptnum2));
BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - num2));
}
invalid = ((num1 > 0 && num2 < std::numeric_limits<int64_t>::min() + num1) ||
(num1 < 0 && num2 > std::numeric_limits<int64_t>::max() + num1));
if (!invalid) {
BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - scriptnum1));
BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - num1));
}
}
static void CheckCompare(const int64_t& num1, const int64_t& num2)
{
const CScriptNum10 bignum1(num1);
const CScriptNum10 bignum2(num2);
const CScriptNum scriptnum1(num1);
const CScriptNum scriptnum2(num2);
BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == scriptnum1));
BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != scriptnum1));
BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < scriptnum1));
BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > scriptnum1));
BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= scriptnum1));
BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= scriptnum1));
BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == num1));
BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != num1));
BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < num1));
BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > num1));
BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= num1));
BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= num1));
BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == scriptnum2));
BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != scriptnum2));
BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < scriptnum2));
BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > scriptnum2));
BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= scriptnum2));
BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= scriptnum2));
BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == num2));
BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != num2));
BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < num2));
BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > num2));
BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= num2));
BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= num2));
}
static void RunCreate(const int64_t& num)
{
CheckCreateInt(num);
CScriptNum scriptnum(num);
if (scriptnum.getvch().size() <= CScriptNum::nDefaultMaxNumSize)
CheckCreateVch(num);
else {
BOOST_CHECK_THROW(CheckCreateVch(num), scriptnum10_error);
}
}
static void RunOperators(const int64_t& num1, const int64_t& num2)
{
CheckAdd(num1, num2);
CheckSubtract(num1, num2);
CheckNegate(num1);
CheckCompare(num1, num2);
}
BOOST_AUTO_TEST_CASE(creation)
{
for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) {
for (size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j) {
RunCreate(values[i]);
RunCreate(values[i] + offsets[j]);
RunCreate(values[i] - offsets[j]);
}
}
}
BOOST_AUTO_TEST_CASE(operators)
{
for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) {
for (size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j) {
RunOperators(values[i], values[i]);
RunOperators(values[i], -values[i]);
RunOperators(values[i], values[j]);
RunOperators(values[i], -values[j]);
RunOperators(values[i] + values[j], values[j]);
RunOperators(values[i] + values[j], -values[j]);
RunOperators(values[i] - values[j], values[j]);
RunOperators(values[i] - values[j], -values[j]);
RunOperators(values[i] + values[j], values[i] + values[j]);
RunOperators(values[i] + values[j], values[i] - values[j]);
RunOperators(values[i] - values[j], values[i] + values[j]);
RunOperators(values[i] - values[j], values[i] - values[j]);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
|
//
// Synchronized publisher in C++
//
// Olivier Chamoux <olivier.chamoux@fr.thalesgroup.com>
#include "zhelpers.hpp"
// We wait for 10 subscribers
#define SUBSCRIBERS_EXPECTED 10
int main () {
zmq::context_t context(1);
// Socket to talk to clients
zmq::socket_t publisher (context, ZMQ_PUB);
publisher.bind("tcp://*:5561");
// Socket to receive signals
zmq::socket_t syncservice (context, ZMQ_REP);
syncservice.bind("tcp://*:5562");
// Get synchronization from subscribers
int subscribers = 0;
while (subscribers < SUBSCRIBERS_EXPECTED) {
// - wait for synchronization request
s_recv (syncservice);
// - send synchronization reply
s_send (syncservice, "");
subscribers++;
}
// Now broadcast exactly 1M updates followed by END
int update_nbr;
for (update_nbr = 0; update_nbr < 1000000; update_nbr++) {
s_send (publisher, "Rhubarb");
}
s_send (publisher, "END");
sleep (1); // Give 0MQ time to flush output
return 0;
}
|
#include "sound.hpp"
CSound::CSound(void)
{
}
CSound::~CSound(void)
{
}
/* Load sounds and save the handle in a array*/
void CSound::InitSound()
{
snd_stream_init(NULL);
#ifdef _TETRIS_DEBUG_
sndfxid[0]=snd_sfx_load("/cd/master/sounds/block_down.wav");
sndfxid[1]=snd_sfx_load("/cd/master/sounds/menu_change.wav");
sndfxid[2]=snd_sfx_load("/cd/master/sounds/line_delete.wav");
#elif _TETRIS_RELEASE_
sndfxid[0]=snd_sfx_load("/cd/sounds/block_down.wav");
sndfxid[1]=snd_sfx_load("/cd/sounds/menu_change.wav");
sndfxid[2]=snd_sfx_load("/cd/sounds/line_delete.wav");
#endif
}
/* Play a given sound at a given volume and pan (128=Center, 0=Left, 255=Right) */
void CSound::Play(int id, int vol, int pan)
{
snd_sfx_play(sndfxid[id],vol,pan);
}
|
/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
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.
indent = tab
tab-size = 4
*/
#include <fstream>
#include <ranges>
#include <cmath>
#include <unistd.h>
#include <numeric>
#include <regex>
#include <sys/statvfs.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <net/if.h>
#ifndef STATIC_BUILD
#include <pwd.h>
#endif
#include <btop_shared.hpp>
#include <btop_config.hpp>
#include <btop_tools.hpp>
using std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min;
using std::clamp, std::string_literals::operator""s, std::cmp_equal, std::cmp_less, std::cmp_greater;
namespace fs = std::filesystem;
namespace rng = std::ranges;
using namespace Tools;
//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------
namespace Cpu {
vector<long long> core_old_totals;
vector<long long> core_old_idles;
vector<string> available_fields;
vector<string> available_sensors = {"Auto"};
cpu_info current_cpu;
fs::path freq_path = "/sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq";
bool got_sensors = false, cpu_temp_only = false;
//* Populate found_sensors map
bool get_sensors();
//* Get current cpu clock speed
string get_cpuHz();
//* Search /proc/cpuinfo for a cpu name
string get_cpuName();
struct Sensor {
fs::path path;
string label;
int64_t temp = 0;
int64_t high = 0;
int64_t crit = 0;
};
unordered_flat_map<string, Sensor> found_sensors;
string cpu_sensor;
vector<string> core_sensors;
unordered_flat_map<int, int> core_mapping;
}
namespace Mem {
double old_uptime;
}
namespace Shared {
fs::path procPath, passwd_path;
long pageSize, clkTck, coreCount;
void init() {
//? Shared global variables init
procPath = (fs::is_directory(fs::path("/proc")) and access("/proc", R_OK) != -1) ? "/proc" : "";
if (procPath.empty())
throw std::runtime_error("Proc filesystem not found or no permission to read from it!");
passwd_path = (fs::is_regular_file(fs::path("/etc/passwd")) and access("/etc/passwd", R_OK) != -1) ? "/etc/passwd" : "";
if (passwd_path.empty())
Logger::warning("Could not read /etc/passwd, will show UID instead of username.");
coreCount = sysconf(_SC_NPROCESSORS_ONLN);
if (coreCount < 1) {
coreCount = 1;
Logger::warning("Could not determine number of cores, defaulting to 1.");
}
pageSize = sysconf(_SC_PAGE_SIZE);
if (pageSize <= 0) {
pageSize = 4096;
Logger::warning("Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.");
}
clkTck = sysconf(_SC_CLK_TCK);
if (clkTck <= 0) {
clkTck = 100;
Logger::warning("Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.");
}
//? Init for namespace Cpu
if (not fs::exists(Cpu::freq_path) or access(Cpu::freq_path.c_str(), R_OK) == -1) Cpu::freq_path.clear();
Cpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});
Cpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});
Cpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);
Cpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);
Cpu::collect();
for (auto& [field, vec] : Cpu::current_cpu.cpu_percent) {
if (not vec.empty()) Cpu::available_fields.push_back(field);
}
Cpu::cpuName = Cpu::get_cpuName();
Cpu::got_sensors = Cpu::get_sensors();
for (const auto& [sensor, ignored] : Cpu::found_sensors) {
Cpu::available_sensors.push_back(sensor);
}
Cpu::core_mapping = Cpu::get_core_mapping();
//? Init for namespace Mem
Mem::old_uptime = system_uptime();
Mem::collect();
}
}
namespace Cpu {
string cpuName;
string cpuHz;
bool has_battery = true;
tuple<int, long, string> current_bat;
const array<string, 10> time_names = {"user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal", "guest", "guest_nice"};
unordered_flat_map<string, long long> cpu_old = {
{"totals", 0},
{"idles", 0},
{"user", 0},
{"nice", 0},
{"system", 0},
{"idle", 0},
{"iowait", 0},
{"irq", 0},
{"softirq", 0},
{"steal", 0},
{"guest", 0},
{"guest_nice", 0}
};
string get_cpuName() {
string name;
ifstream cpuinfo(Shared::procPath / "cpuinfo");
if (cpuinfo.good()) {
for (string instr; getline(cpuinfo, instr, ':') and not instr.starts_with("model name");)
cpuinfo.ignore(SSmax, '\n');
if (cpuinfo.bad()) return name;
else if (not cpuinfo.eof()) {
cpuinfo.ignore(1);
getline(cpuinfo, name);
}
else if (fs::exists("/sys/devices")) {
for (const auto& d : fs::directory_iterator("/sys/devices")) {
if (string(d.path().filename()).starts_with("arm")) {
name = d.path().filename();
break;
}
}
if (not name.empty()) {
auto name_vec = ssplit(name, '_');
if (name_vec.size() < 2) return capitalize(name);
else return capitalize(name_vec.at(1)) + (name_vec.size() > 2 ? ' ' + capitalize(name_vec.at(2)) : "");
}
}
auto name_vec = ssplit(name);
if ((s_contains(name, "Xeon"s) or v_contains(name_vec, "Duo"s)) and v_contains(name_vec, "CPU"s)) {
auto cpu_pos = v_index(name_vec, "CPU"s);
if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')'))
name = name_vec.at(cpu_pos + 1);
else
name.clear();
}
else if (v_contains(name_vec, "Ryzen"s)) {
auto ryz_pos = v_index(name_vec, "Ryzen"s);
name = "Ryzen" + (ryz_pos < name_vec.size() - 1 ? ' ' + name_vec.at(ryz_pos + 1) : "")
+ (ryz_pos < name_vec.size() - 2 ? ' ' + name_vec.at(ryz_pos + 2) : "");
}
else if (s_contains(name, "Intel"s) and v_contains(name_vec, "CPU"s)) {
auto cpu_pos = v_index(name_vec, "CPU"s);
if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')') and name_vec.at(cpu_pos + 1) != "@")
name = name_vec.at(cpu_pos + 1);
else
name.clear();
}
else
name.clear();
if (name.empty() and not name_vec.empty()) {
for (const auto& n : name_vec) {
if (n == "@") break;
name += n + ' ';
}
name.pop_back();
for (const auto& reg : {regex("Processor"), regex("CPU"), regex("\\(R\\)"), regex("\\(TM\\)"), regex("Intel"),
regex("AMD"), regex("Core"), regex("\\d?\\.?\\d+[mMgG][hH][zZ]")}) {
name = std::regex_replace(name, reg, "");
}
name = trim(name);
}
}
return name;
}
bool get_sensors() {
bool got_cpu = false, got_coretemp = false;
vector<fs::path> search_paths;
try {
//? Setup up paths to search for sensors
if (fs::exists(fs::path("/sys/class/hwmon")) and access("/sys/class/hwmon", R_OK) != -1) {
for (const auto& dir : fs::directory_iterator(fs::path("/sys/class/hwmon"))) {
fs::path add_path = fs::canonical(dir.path());
if (v_contains(search_paths, add_path) or v_contains(search_paths, add_path / "device")) continue;
if (s_contains(add_path, "coretemp"))
got_coretemp = true;
if (fs::exists(add_path / "temp1_input")) {
search_paths.push_back(add_path);
}
else if (fs::exists(add_path / "device/temp1_input"))
search_paths.push_back(add_path / "device");
}
}
if (not got_coretemp and fs::exists(fs::path("/sys/devices/platform/coretemp.0/hwmon"))) {
for (auto& d : fs::directory_iterator(fs::path("/sys/devices/platform/coretemp.0/hwmon"))) {
fs::path add_path = fs::canonical(d.path());
if (fs::exists(d.path() / "temp1_input") and not v_contains(search_paths, add_path)) {
search_paths.push_back(add_path);
got_coretemp = true;
}
}
}
//? Scan any found directories for temperature sensors
if (not search_paths.empty()) {
for (const auto& path : search_paths) {
const string pname = readfile(path / "name", path.filename());
for (int i = 1; fs::exists(path / string("temp" + to_string(i) + "_input")); i++) {
const string basepath = path / string("temp" + to_string(i) + "_");
const string label = readfile(fs::path(basepath + "label"), "temp" + to_string(i));
const string sensor_name = pname + "/" + label;
const int64_t temp = stol(readfile(fs::path(basepath + "input"), "0")) / 1000;
const int64_t high = stol(readfile(fs::path(basepath + "max"), "80000")) / 1000;
const int64_t crit = stol(readfile(fs::path(basepath + "crit"), "95000")) / 1000;
found_sensors[sensor_name] = {fs::path(basepath + "input"), label, temp, high, crit};
if (not got_cpu and (label.starts_with("Package id") or label.starts_with("Tdie"))) {
got_cpu = true;
cpu_sensor = sensor_name;
}
else if (label.starts_with("Core") or label.starts_with("Tccd")) {
got_coretemp = true;
if (not v_contains(core_sensors, sensor_name)) core_sensors.push_back(sensor_name);
}
}
}
}
//? If no good candidate for cpu temp has been found scan /sys/class/thermal
if (not got_cpu and fs::exists(fs::path("/sys/class/thermal"))) {
const string rootpath = fs::path("/sys/class/thermal/thermal_zone");
for (int i = 0; fs::exists(fs::path(rootpath + to_string(i))); i++) {
const fs::path basepath = rootpath + to_string(i);
if (not fs::exists(basepath / "temp")) continue;
const string label = readfile(basepath / "type", "temp" + to_string(i));
const string sensor_name = "thermal" + to_string(i) + "/" + label;
const int64_t temp = stol(readfile(basepath / "temp", "0")) / 1000;
int64_t high, crit;
for (int ii = 0; fs::exists(basepath / string("trip_point_" + to_string(ii) + "_temp")); ii++) {
const string trip_type = readfile(basepath / string("trip_point_" + to_string(ii) + "_type"));
if (not is_in(trip_type, "high", "critical")) continue;
auto& val = (trip_type == "high" ? high : crit);
val = stol(readfile(basepath / string("trip_point_" + to_string(ii) + "_temp"), "0")) / 1000;
}
if (high < 1) high = 80;
if (crit < 1) crit = 95;
found_sensors[sensor_name] = {basepath / "temp", label, temp, high, crit};
}
}
}
catch (...) {}
if (not got_coretemp or core_sensors.empty()) cpu_temp_only = true;
if (cpu_sensor.empty() and not found_sensors.empty()) {
for (const auto& [name, sensor] : found_sensors) {
if (s_contains(str_to_lower(name), "cpu")) {
cpu_sensor = name;
break;
}
}
if (cpu_sensor.empty()) {
cpu_sensor = found_sensors.begin()->first;
Logger::warning("No good candidate for cpu sensor found, using random from all found sensors.");
}
}
return not found_sensors.empty();
}
void update_sensors() {
if (cpu_sensor.empty()) return;
const auto& cpu_sensor = (not Config::getS("cpu_sensor").empty() and found_sensors.contains(Config::getS("cpu_sensor")) ? Config::getS("cpu_sensor") : Cpu::cpu_sensor);
found_sensors.at(cpu_sensor).temp = stol(readfile(found_sensors.at(cpu_sensor).path, "0")) / 1000;
current_cpu.temp.at(0).push_back(found_sensors.at(cpu_sensor).temp);
current_cpu.temp_max = found_sensors.at(cpu_sensor).crit;
if (current_cpu.temp.at(0).size() > 20) current_cpu.temp.at(0).pop_front();
if (Config::getB("show_coretemp") and not cpu_temp_only) {
vector<string> done;
for (const auto& sensor : core_sensors) {
if (v_contains(done, sensor)) continue;
found_sensors.at(sensor).temp = stol(readfile(found_sensors.at(sensor).path, "0")) / 1000;
done.push_back(sensor);
}
for (const auto& [core, temp] : core_mapping) {
if (cmp_less(core + 1, current_cpu.temp.size()) and cmp_less(temp, core_sensors.size())) {
current_cpu.temp.at(core + 1).push_back(found_sensors.at(core_sensors.at(temp)).temp);
if (current_cpu.temp.at(core + 1).size() > 20) current_cpu.temp.at(core + 1).pop_front();
}
}
}
}
string get_cpuHz() {
static int failed = 0;
if (failed > 4) return ""s;
string cpuhz;
try {
double hz = 0.0;
//? Try to get freq from /sys/devices/system/cpu/cpufreq/policy first (faster)
if (not freq_path.empty()) {
hz = stod(readfile(freq_path, "0.0")) / 1000;
if (hz <= 0.0 and ++failed >= 2)
freq_path.clear();
}
//? If freq from /sys failed or is missing try to use /proc/cpuinfo
if (hz <= 0.0) {
ifstream cpufreq(Shared::procPath / "cpuinfo");
if (cpufreq.good()) {
while (cpufreq.ignore(SSmax, '\n')) {
if (cpufreq.peek() == 'c') {
cpufreq.ignore(SSmax, ' ');
if (cpufreq.peek() == 'M') {
cpufreq.ignore(SSmax, ':');
cpufreq.ignore(1);
cpufreq >> hz;
break;
}
}
}
}
}
if (hz <= 1 or hz >= 1000000) throw std::runtime_error("Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo.");
if (hz >= 1000) {
if (hz >= 10000) cpuhz = to_string((int)round(hz / 1000)); // Future proof until we reach THz speeds :)
else cpuhz = to_string(round(hz / 100) / 10.0).substr(0, 3);
cpuhz += " GHz";
}
else if (hz > 0)
cpuhz = to_string((int)round(hz)) + " MHz";
}
catch (const std::exception& e) {
if (++failed < 5) return ""s;
else {
Logger::warning("get_cpuHZ() : " + (string)e.what());
return ""s;
}
}
return cpuhz;
}
auto get_core_mapping() -> unordered_flat_map<int, int> {
unordered_flat_map<int, int> core_map;
if (cpu_temp_only) return core_map;
//? Try to get core mapping from /proc/cpuinfo
ifstream cpuinfo(Shared::procPath / "cpuinfo");
if (cpuinfo.good()) {
int cpu, core, n = 0;
for (string instr; cpuinfo >> instr;) {
if (instr == "processor") {
cpuinfo.ignore(SSmax, ':');
cpuinfo >> cpu;
}
else if (instr.starts_with("core")) {
cpuinfo.ignore(SSmax, ':');
cpuinfo >> core;
if (std::cmp_greater_equal(core, core_sensors.size())) {
if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
core_map[cpu] = n++;
}
else
core_map[cpu] = core;
}
cpuinfo.ignore(SSmax, '\n');
}
}
//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.
if (cmp_less(core_map.size(), Shared::coreCount)) {
if (Shared::coreCount % 2 == 0 and (long)core_map.size() == Shared::coreCount / 2) {
for (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {
if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
core_map[Shared::coreCount / 2 + i] = n++;
}
}
else {
core_map.clear();
for (int i = 0, n = 0; i < Shared::coreCount; i++) {
if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
core_map[i] = n++;
}
}
}
//? Apply user set custom mapping if any
const auto& custom_map = Config::getS("cpu_core_map");
if (not custom_map.empty()) {
try {
for (const auto& split : ssplit(custom_map)) {
const auto vals = ssplit(split, ':');
if (vals.size() != 2) continue;
int change_id = std::stoi(vals.at(0));
int new_id = std::stoi(vals.at(1));
if (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;
core_map.at(change_id) = new_id;
}
}
catch (...) {}
}
return core_map;
}
auto get_battery() -> tuple<int, long, string> {
if (not has_battery) return {0, 0, ""};
static fs::path bat_dir, energy_now_path, energy_full_path, power_now_path, status_path, online_path;
static bool use_energy = true;
//? Get paths to needed files and check for valid values on first run
if (bat_dir.empty() and has_battery) {
if (fs::exists("/sys/class/power_supply")) {
for (const auto& d : fs::directory_iterator("/sys/class/power_supply")) {
if (const string dir_name = d.path().filename(); d.is_directory() and (dir_name.starts_with("BAT") or s_contains(str_to_lower(dir_name), "battery"))) {
bat_dir = d.path();
break;
}
}
}
if (bat_dir.empty()) {
has_battery = false;
return {0, 0, ""};
}
else {
if (fs::exists(bat_dir / "energy_now")) energy_now_path = bat_dir / "energy_now";
else if (fs::exists(bat_dir / "charge_now")) energy_now_path = bat_dir / "charge_now";
else use_energy = false;
if (fs::exists(bat_dir / "energy_full")) energy_full_path = bat_dir / "energy_full";
else if (fs::exists(bat_dir / "charge_full")) energy_full_path = bat_dir / "charge_full";
else use_energy = false;
if (not use_energy and not fs::exists(bat_dir / "capacity")) {
has_battery = false;
return {0, 0, ""};
}
if (fs::exists(bat_dir / "power_now")) power_now_path = bat_dir / "power_now";
else if (fs::exists(bat_dir / "current_now")) power_now_path = bat_dir / "current_now";
if (fs::exists(bat_dir / "AC0/online")) online_path = bat_dir / "AC0/online";
else if (fs::exists(bat_dir / "AC/online")) online_path = bat_dir / "AC/online";
}
}
int percent = -1;
long seconds = -1;
//? Try to get battery percentage
if (use_energy) {
try {
percent = round(100.0 * stoll(readfile(energy_now_path, "-1")) / stoll(readfile(energy_full_path, "1")));
}
catch (const std::invalid_argument&) { }
catch (const std::out_of_range&) { }
}
if (percent < 0) {
try {
percent = stoll(readfile(bat_dir / "capacity", "-1"));
}
catch (const std::invalid_argument&) { }
catch (const std::out_of_range&) { }
}
if (percent < 0) {
has_battery = false;
return {0, 0, ""};
}
//? Get charging/discharging status
string status = str_to_lower(readfile(bat_dir / "status", "unknown"));
if (status == "unknown" and not online_path.empty()) {
const auto online = readfile(online_path, "0");
if (online == "1" and percent < 100) status = "charging";
else if (online == "1") status = "full";
else status = "discharging";
}
//? Get seconds to empty
if (not is_in(status, "charging", "full")) {
if (use_energy and not power_now_path.empty()) {
try {
seconds = round((double)stoll(readfile(energy_now_path, "0")) / stoll(readfile(power_now_path, "1")) * 3600);
}
catch (const std::invalid_argument&) { }
catch (const std::out_of_range&) { }
}
if (seconds < 0 and fs::exists(bat_dir / "time_to_empty")) {
try {
seconds = stoll(readfile(bat_dir / "time_to_empty", "0")) * 60;
}
catch (const std::invalid_argument&) { }
catch (const std::out_of_range&) { }
}
}
return {percent, seconds, status};
}
auto collect(const bool no_update) -> cpu_info& {
if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) return current_cpu;
auto& cpu = current_cpu;
ifstream cread;
try {
//? Get cpu load averages from /proc/loadavg
cread.open(Shared::procPath / "loadavg");
if (cread.good()) {
cread >> cpu.load_avg[0] >> cpu.load_avg[1] >> cpu.load_avg[2];
}
cread.close();
//? Get cpu total times for all cores from /proc/stat
cread.open(Shared::procPath / "stat");
for (int i = 0; cread.good() and cread.peek() == 'c'; i++) {
cread.ignore(SSmax, ' ');
//? Expected on kernel 2.6.3> : 0=user, 1=nice, 2=system, 3=idle, 4=iowait, 5=irq, 6=softirq, 7=steal, 8=guest, 9=guest_nice
vector<long long> times;
long long total_sum = 0;
for (uint64_t val; cread >> val; total_sum += val) {
times.push_back(val);
}
cread.clear();
if (times.size() < 4) throw std::runtime_error("Malformatted /proc/stat");
//? Subtract fields 8-9 and any future unknown fields
const long long totals = max(0ll, total_sum - (times.size() > 8 ? std::accumulate(times.begin() + 8, times.end(), 0) : 0));
//? Add iowait field if present
const long long idles = max(0ll, times.at(3) + (times.size() > 4 ? times.at(4) : 0));
//? Calculate values for totals from first line of stat
if (i == 0) {
const long long calc_totals = max(1ll, totals - cpu_old.at("totals"));
const long long calc_idles = max(1ll, idles - cpu_old.at("idles"));
cpu_old.at("totals") = totals;
cpu_old.at("idles") = idles;
//? Total usage of cpu
cpu.cpu_percent.at("total").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));
//? Reduce size if there are more values than needed for graph
while (cmp_greater(cpu.cpu_percent.at("total").size(), width * 2)) cpu.cpu_percent.at("total").pop_front();
//? Populate cpu.cpu_percent with all fields from stat
for (int ii = 0; const auto& val : times) {
cpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll));
cpu_old.at(time_names.at(ii)) = val;
//? Reduce size if there are more values than needed for graph
while (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();
if (++ii == 10) break;
}
}
//? Calculate cpu total for each core
else {
if (i > Shared::coreCount) break;
const long long calc_totals = max(0ll, totals - core_old_totals.at(i-1));
const long long calc_idles = max(0ll, idles - core_old_idles.at(i-1));
core_old_totals.at(i-1) = totals;
core_old_idles.at(i-1) = idles;
cpu.core_percent.at(i-1).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));
//? Reduce size if there are more values than needed for graph
if (cpu.core_percent.at(i-1).size() > 40) cpu.core_percent.at(i-1).pop_front();
}
}
}
catch (const std::exception& e) {
Logger::debug("get_cpuHz() : " + (string)e.what());
if (cread.bad()) throw std::runtime_error("Failed to read /proc/stat");
else throw std::runtime_error("collect() : " + (string)e.what());
}
if (Config::getB("show_cpu_freq"))
cpuHz = get_cpuHz();
if (Config::getB("check_temp") and got_sensors)
update_sensors();
if (Config::getB("show_battery") and has_battery)
current_bat = get_battery();
return cpu;
}
}
namespace Mem {
bool has_swap = false;
vector<string> fstab;
fs::file_time_type fstab_time;
int disk_ios = 0;
vector<string> last_found;
mem_info current_mem {};
uint64_t get_totalMem() {
ifstream meminfo(Shared::procPath / "meminfo");
int64_t totalMem;
if (meminfo.good()) {
meminfo.ignore(SSmax, ':');
meminfo >> totalMem;
totalMem <<= 10;
}
if (not meminfo.good() or totalMem == 0)
throw std::runtime_error("Could not get total memory size from /proc/meminfo");
return totalMem;
}
auto collect(const bool no_update) -> mem_info& {
if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) return current_mem;
auto& show_swap = Config::getB("show_swap");
auto& swap_disk = Config::getB("swap_disk");
auto& show_disks = Config::getB("show_disks");
auto totalMem = get_totalMem();
auto& mem = current_mem;
mem.stats.at("swap_total") = 0;
//? Read memory info from /proc/meminfo
ifstream meminfo(Shared::procPath / "meminfo");
if (meminfo.good()) {
bool got_avail = false;
for (string label; meminfo >> label;) {
if (label == "MemFree:") {
meminfo >> mem.stats.at("free");
mem.stats.at("free") <<= 10;
}
else if (label == "MemAvailable:") {
meminfo >> mem.stats.at("available");
mem.stats.at("available") <<= 10;
got_avail = true;
}
else if (label == "Cached:") {
meminfo >> mem.stats.at("cached");
mem.stats.at("cached") <<= 10;
if (not show_swap and not swap_disk) break;
}
else if (label == "SwapTotal:") {
meminfo >> mem.stats.at("swap_total");
mem.stats.at("swap_total") <<= 10;
}
else if (label == "SwapFree:") {
meminfo >> mem.stats.at("swap_free");
mem.stats.at("swap_free") <<= 10;
break;
}
meminfo.ignore(SSmax, '\n');
}
if (not got_avail) mem.stats.at("available") = mem.stats.at("free") + mem.stats.at("cached");
mem.stats.at("used") = totalMem - mem.stats.at("available");
if (mem.stats.at("swap_total") > 0) mem.stats.at("swap_used") = mem.stats.at("swap_total") - mem.stats.at("swap_free");
}
else
throw std::runtime_error("Failed to read /proc/meminfo");
meminfo.close();
//? Calculate percentages
for (const auto& name : mem_names) {
mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / totalMem));
while (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front();
}
if (show_swap and mem.stats.at("swap_total") > 0) {
for (const auto& name : swap_names) {
mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at("swap_total")));
while (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front();
}
has_swap = true;
}
else
has_swap = false;
//? Get disks stats
if (show_disks) {
double uptime = system_uptime();
try {
auto& disks_filter = Config::getS("disks_filter");
bool filter_exclude = false;
auto& use_fstab = Config::getB("use_fstab");
auto& only_physical = Config::getB("only_physical");
auto& disks = mem.disks;
ifstream diskread;
vector<string> filter;
if (not disks_filter.empty()) {
filter = ssplit(disks_filter);
if (filter.at(0).starts_with("exclude=")) {
filter_exclude = true;
filter.at(0) = filter.at(0).substr(8);
}
}
//? Get list of "real" filesystems from /proc/filesystems
vector<string> fstypes;
if (only_physical and not use_fstab) {
fstypes = {"zfs", "wslfs", "drvfs"};
diskread.open(Shared::procPath / "filesystems");
if (diskread.good()) {
for (string fstype; diskread >> fstype;) {
if (not is_in(fstype, "nodev", "squashfs", "nullfs"))
fstypes.push_back(fstype);
diskread.ignore(SSmax, '\n');
}
}
else
throw std::runtime_error("Failed to read /proc/filesystems");
diskread.close();
}
//? Get disk list to use from fstab if enabled
if (use_fstab and fs::last_write_time("/etc/fstab") != fstab_time) {
fstab.clear();
fstab_time = fs::last_write_time("/etc/fstab");
diskread.open("/etc/fstab");
if (diskread.good()) {
for (string instr; diskread >> instr;) {
if (not instr.starts_with('#')) {
diskread >> instr;
#ifdef SNAPPED
if (instr == "/") fstab.push_back("/mnt");
else if (not is_in(instr, "none", "swap")) fstab.push_back(instr);
#else
if (not is_in(instr, "none", "swap")) fstab.push_back(instr);
#endif
}
diskread.ignore(SSmax, '\n');
}
}
else
throw std::runtime_error("Failed to read /etc/fstab");
diskread.close();
}
//? Get mounts from /etc/mtab or /proc/self/mounts
diskread.open((fs::exists("/etc/mtab") ? fs::path("/etc/mtab") : Shared::procPath / "self/mounts"));
if (diskread.good()) {
vector<string> found;
found.reserve(last_found.size());
string dev, mountpoint, fstype;
while (not diskread.eof()) {
std::error_code ec;
diskread >> dev >> mountpoint >> fstype;
//? Match filter if not empty
if (not filter.empty()) {
bool match = v_contains(filter, mountpoint);
if ((filter_exclude and match) or (not filter_exclude and not match))
continue;
}
if ((not use_fstab and not only_physical)
or (use_fstab and v_contains(fstab, mountpoint))
or (not use_fstab and only_physical and v_contains(fstypes, fstype))) {
found.push_back(mountpoint);
if (not v_contains(last_found, mountpoint)) redraw = true;
//? Save mountpoint, name, dev path and path to /sys/block stat file
if (not disks.contains(mountpoint)) {
disks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename()};
if (disks.at(mountpoint).dev.empty()) disks.at(mountpoint).dev = dev;
#ifdef SNAPPED
if (mountpoint == "/mnt") disks.at(mountpoint).name = "root";
#endif
if (disks.at(mountpoint).name.empty()) disks.at(mountpoint).name = (mountpoint == "/" ? "root" : mountpoint);
string devname = disks.at(mountpoint).dev.filename();
while (devname.size() >= 2) {
if (fs::exists("/sys/block/" + devname + "/stat", ec) and access(string("/sys/block/" + devname + "/stat").c_str(), R_OK) == 0) {
disks.at(mountpoint).stat = "/sys/block/" + devname + "/stat";
break;
}
devname.resize(devname.size() - 1);
}
}
}
diskread.ignore(SSmax, '\n');
}
//? Remove disks no longer mounted or filtered out
if (swap_disk and has_swap) found.push_back("swap");
for (auto it = disks.begin(); it != disks.end();) {
if (not v_contains(found, it->first))
it = disks.erase(it);
else
it++;
}
if (found.size() != last_found.size()) redraw = true;
last_found = std::move(found);
}
else
throw std::runtime_error("Failed to get mounts from /etc/mtab and /proc/self/mounts");
diskread.close();
//? Get disk/partition stats
for (auto& [mountpoint, disk] : disks) {
if (std::error_code ec; not fs::exists(mountpoint, ec)) continue;
struct statvfs vfs;
if (statvfs(mountpoint.c_str(), &vfs) < 0) {
Logger::warning("Failed to get disk/partition stats with statvfs() for: " + mountpoint);
continue;
}
disk.total = vfs.f_blocks * vfs.f_frsize;
disk.free = vfs.f_bfree * vfs.f_frsize;
disk.used = disk.total - disk.free;
disk.used_percent = round((double)disk.used * 100 / disk.total);
disk.free_percent = 100 - disk.used_percent;
}
//? Setup disks order in UI and add swap if enabled
mem.disks_order.clear();
#ifdef SNAPPED
if (disks.contains("/mnt")) mem.disks_order.push_back("/mnt");
#else
if (disks.contains("/")) mem.disks_order.push_back("/");
#endif
if (swap_disk and has_swap) {
mem.disks_order.push_back("swap");
if (not disks.contains("swap")) disks["swap"] = {"", "swap"};
disks.at("swap").total = mem.stats.at("swap_total");
disks.at("swap").used = mem.stats.at("swap_used");
disks.at("swap").free = mem.stats.at("swap_free");
disks.at("swap").used_percent = mem.percent.at("swap_used").back();
disks.at("swap").free_percent = mem.percent.at("swap_free").back();
}
for (const auto& name : last_found)
if (not is_in(name, "/", "swap")) mem.disks_order.push_back(name);
//? Get disks IO
int64_t sectors_read, sectors_write, io_ticks;
disk_ios = 0;
for (auto& [ignored, disk] : disks) {
if (disk.stat.empty() or access(disk.stat.c_str(), R_OK) != 0) continue;
diskread.open(disk.stat);
if (diskread.good()) {
disk_ios++;
for (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }
diskread >> sectors_read;
if (disk.io_read.empty())
disk.io_read.push_back(0);
else
disk.io_read.push_back(max((int64_t)0, (sectors_read - disk.old_io.at(0)) * 512));
disk.old_io.at(0) = sectors_read;
while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();
for (int i = 0; i < 3; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }
diskread >> sectors_write;
if (disk.io_write.empty())
disk.io_write.push_back(0);
else
disk.io_write.push_back(max((int64_t)0, (sectors_write - disk.old_io.at(1)) * 512));
disk.old_io.at(1) = sectors_write;
while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();
for (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }
diskread >> io_ticks;
if (disk.io_activity.empty())
disk.io_activity.push_back(0);
else
disk.io_activity.push_back(clamp((long)round((double)(io_ticks - disk.old_io.at(2)) / (uptime - old_uptime) / 10), 0l, 100l));
disk.old_io.at(2) = io_ticks;
while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();
}
diskread.close();
}
old_uptime = uptime;
}
catch (const std::exception& e) {
Logger::warning("Error in Mem::collect() : " + (string)e.what());
}
}
return mem;
}
}
namespace Net {
unordered_flat_map<string, net_info> current_net;
net_info empty_net = {};
vector<string> interfaces;
string selected_iface;
int errors = 0;
unordered_flat_map<string, uint64_t> graph_max = { {"download", {}}, {"upload", {}} };
unordered_flat_map<string, array<int, 2>> max_count = { {"download", {}}, {"upload", {}} };
bool rescale = true;
uint64_t timestamp = 0;
//* RAII wrapper for getifaddrs
class getifaddr_wrapper {
struct ifaddrs* ifaddr;
public:
int status;
getifaddr_wrapper() { status = getifaddrs(&ifaddr); }
~getifaddr_wrapper() { freeifaddrs(ifaddr); }
auto operator()() -> struct ifaddrs* { return ifaddr; }
};
auto collect(const bool no_update) -> net_info& {
auto& net = current_net;
auto& config_iface = Config::getS("net_iface");
auto& net_sync = Config::getB("net_sync");
auto& net_auto = Config::getB("net_auto");
auto new_timestamp = time_ms();
if (not no_update and errors < 3) {
//? Get interface list using getifaddrs() wrapper
getifaddr_wrapper if_wrap {};
if (if_wrap.status != 0) {
errors++;
Logger::error("Net::collect() -> getifaddrs() failed with id " + to_string(if_wrap.status));
redraw = true;
return empty_net;
}
int family = 0;
char ip[NI_MAXHOST];
interfaces.clear();
string ipv4, ipv6;
//? Iteration over all items in getifaddrs() list
for (auto* ifa = if_wrap(); ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) continue;
family = ifa->ifa_addr->sa_family;
const auto& iface = ifa->ifa_name;
//? Get IPv4 address
if (family == AF_INET) {
if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
net[iface].ipv4 = ip;
}
//? Get IPv6 address
else if (family == AF_INET6) {
if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
net[iface].ipv6 = ip;
}
//? Update available interfaces vector and get status of interface
if (not v_contains(interfaces, iface)) {
interfaces.push_back(iface);
net[iface].connected = (ifa->ifa_flags & IFF_RUNNING);
}
}
//? Get total recieved and transmitted bytes + device address if no ip was found
for (const auto& iface : interfaces) {
if (net.at(iface).ipv4.empty() and net.at(iface).ipv6.empty())
net.at(iface).ipv4 = readfile("/sys/class/net/" + iface + "/address");
for (const string dir : {"download", "upload"}) {
const fs::path sys_file = "/sys/class/net/" + iface + "/statistics/" + (dir == "download" ? "rx_bytes" : "tx_bytes");
auto& saved_stat = net.at(iface).stat.at(dir);
auto& bandwidth = net.at(iface).bandwidth.at(dir);
uint64_t val = saved_stat.last;
try { val = max((uint64_t)stoul(readfile(sys_file, "0")), val); }
catch (const std::invalid_argument&) {}
catch (const std::out_of_range&) {}
//? Update speed, total and top values
saved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));
if (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;
if (saved_stat.offset > val) saved_stat.offset = 0;
saved_stat.total = val - saved_stat.offset;
saved_stat.last = val;
//? Add values to graph
bandwidth.push_back(saved_stat.speed);
while (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();
//? Set counters for auto scaling
if (net_auto and selected_iface == iface) {
if (saved_stat.speed > graph_max[dir]) {
++max_count[dir][0];
if (max_count[dir][1] > 0) --max_count[dir][1];
}
else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {
++max_count[dir][1];
if (max_count[dir][0] > 0) --max_count[dir][0];
}
}
}
}
//? Clean up net map if needed
if (net.size() > interfaces.size()) {
for (auto it = net.begin(); it != net.end();) {
if (not v_contains(interfaces, it->first))
it = net.erase(it);
else
it++;
}
net.compact();
}
timestamp = new_timestamp;
}
//? Return empty net_info struct if no interfaces was found
if (net.empty())
return empty_net;
//? Find an interface to display if selected isn't set or valid
if (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {
max_count["download"][0] = max_count["download"][1] = max_count["upload"][0] = max_count["upload"][1] = 0;
redraw = true;
if (net_auto) rescale = true;
if (not config_iface.empty() and v_contains(interfaces, config_iface)) selected_iface = config_iface;
else {
//? Sort interfaces by total upload + download bytes
auto sorted_interfaces = interfaces;
rng::sort(sorted_interfaces, [&](const auto& a, const auto& b){
return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total,
net.at(b).stat["download"].total + net.at(b).stat["upload"].total);
});
selected_iface.clear();
//? Try to set to a connected interface
for (const auto& iface : sorted_interfaces) {
if (net.at(iface).connected) selected_iface = iface;
break;
}
//? If no interface is connected set to first available
if (selected_iface.empty() and not sorted_interfaces.empty()) selected_iface = sorted_interfaces.at(0);
else if (sorted_interfaces.empty()) return empty_net;
}
}
//? Calculate max scale for graphs if needed
if (net_auto) {
bool sync = false;
for (const auto& dir: {"download", "upload"}) {
for (const auto& sel : {0, 1}) {
if (rescale or max_count[dir][sel] >= 5) {
const uint64_t avg_speed = (net[selected_iface].bandwidth[dir].size() > 5
? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0) / 5
: net[selected_iface].stat[dir].speed);
graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);
max_count[dir][0] = max_count[dir][1] = 0;
redraw = true;
if (net_sync) sync = true;
break;
}
}
//? Sync download/upload graphs if enabled
if (sync) {
const auto other = (string(dir) == "upload" ? "download" : "upload");
graph_max[other] = graph_max[dir];
max_count[other][0] = max_count[other][1] = 0;
break;
}
}
}
rescale = false;
return net.at(selected_iface);
}
}
namespace Proc {
vector<proc_info> current_procs;
unordered_flat_map<string, string> uid_user;
string current_sort;
string current_filter;
bool current_rev = false;
fs::file_time_type passwd_time;
uint64_t cputimes;
int collapse = -1, expand = -1;
uint64_t old_cputimes = 0;
atomic<int> numpids = 0;
int filter_found = 0;
detail_container detailed;
//* Generate process tree list
void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<std::reference_wrapper<proc_info>>& out_procs, int cur_depth, const bool collapsed, const string& filter, bool found=false, const bool no_update=false, const bool should_filter=false) {
auto cur_pos = out_procs.size();
bool filtering = false;
//? If filtering, include children of matching processes
if (not found and (should_filter or not filter.empty())) {
if (not s_contains(std::to_string(cur_proc.pid), filter)
and not s_contains(cur_proc.name, filter)
and not s_contains(cur_proc.cmd, filter)
and not s_contains(cur_proc.user, filter)) {
filtering = true;
cur_proc.filtered = true;
filter_found++;
}
else {
found = true;
cur_depth = 0;
}
}
else if (cur_proc.filtered) cur_proc.filtered = false;
//? Set tree index position for process if not filtered out or currently in a collapsed sub-tree
if (not collapsed and not filtering) {
out_procs.push_back(std::ref(cur_proc));
cur_proc.tree_index = out_procs.size() - 1;
//? Try to find name of the binary file and append to program name if not the same
if (cur_proc.short_cmd.empty() and not cur_proc.cmd.empty()) {
std::string_view cmd_view = cur_proc.cmd;
cmd_view = cmd_view.substr((size_t)0, min(cmd_view.find(' '), cmd_view.size()));
cmd_view = cmd_view.substr(min(cmd_view.find_last_of('/') + 1, cmd_view.size()));
cur_proc.short_cmd = (string)cmd_view;
}
}
else {
cur_proc.tree_index = in_procs.size();
}
//? Recursive iteration over all children
int children = 0;
for (auto& p : rng::equal_range(in_procs, cur_proc.pid, rng::less{}, &proc_info::ppid)) {
if (not no_update and not filtering and (collapsed or cur_proc.collapsed)) {
out_procs.back().get().cpu_p += p.cpu_p;
out_procs.back().get().mem += p.mem;
out_procs.back().get().threads += p.threads;
filter_found++;
}
if (collapsed and not filtering) {
cur_proc.filtered = true;
}
else children++;
_tree_gen(p, in_procs, out_procs, cur_depth + 1, (collapsed ? true : cur_proc.collapsed), filter, found, no_update, should_filter);
}
if (collapsed or filtering) return;
//? Add tree terminator symbol if it's the last child in a sub-tree
if (out_procs.size() > cur_pos + 1 and not out_procs.back().get().prefix.ends_with("]─"))
out_procs.back().get().prefix.replace(out_procs.back().get().prefix.size() - 8, 8, " └─ ");
//? Add collapse/expand symbols if process have any children
out_procs.at(cur_pos).get().prefix = " │ "s * cur_depth + (children > 0 ? (cur_proc.collapsed ? "[+]─" : "[-]─") : " ├─ ");
}
//* Get detailed info for selected process
void _collect_details(const size_t pid, const uint64_t uptime, vector<proc_info>& procs) {
fs::path pid_path = Shared::procPath / std::to_string(pid);
if (pid != detailed.last_pid) {
detailed = {};
detailed.last_pid = pid;
detailed.skip_smaps = not Config::getB("proc_info_smaps");
}
//? Copy proc_info for process from proc vector
auto p_info = rng::find(procs, pid, &proc_info::pid);
detailed.entry = *p_info;
//? Update cpu percent deque for process cpu graph
if (not Config::getB("proc_per_core")) detailed.entry.cpu_p *= Shared::coreCount;
detailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));
while (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();
//? Process runtime
detailed.elapsed = sec_to_dhms(uptime - (detailed.entry.cpu_s / Shared::clkTck));
if (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);
//? Get parent process name
if (detailed.parent.empty()) {
auto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);
if (p_entry != procs.end()) detailed.parent = p_entry->name;
}
//? Expand process status from single char to explanative string
detailed.status = (proc_states.contains(detailed.entry.state)) ? proc_states.at(detailed.entry.state) : "Unknown";
ifstream d_read;
string short_str;
//? Try to get RSS mem from proc/[pid]/smaps
detailed.memory.clear();
if (not detailed.skip_smaps and fs::exists(pid_path / "smaps")) {
d_read.open(pid_path / "smaps");
uint64_t rss = 0;
try {
while (d_read.good()) {
d_read.ignore(SSmax, 'R');
if (d_read.peek() == 's') {
d_read.ignore(SSmax, ':');
getline(d_read, short_str, 'k');
rss += stoull(short_str);
}
}
if (rss == detailed.entry.mem >> 10)
detailed.skip_smaps = true;
else {
detailed.mem_bytes.push_back(rss << 10);
detailed.memory = floating_humanizer(rss, false, 1);
}
}
catch (const std::invalid_argument&) {}
catch (const std::out_of_range&) {}
d_read.close();
}
if (detailed.memory.empty()) {
detailed.mem_bytes.push_back(detailed.entry.mem);
detailed.memory = floating_humanizer(detailed.entry.mem);
}
if (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {
detailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());
redraw = true;
}
while (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();
//? Get bytes read and written from proc/[pid]/io
if (fs::exists(pid_path / "io")) {
d_read.open(pid_path / "io");
try {
string name;
while (d_read.good()) {
getline(d_read, name, ':');
if (name.ends_with("read_bytes")) {
getline(d_read, short_str);
detailed.io_read = floating_humanizer(stoull(short_str));
}
else if (name.ends_with("write_bytes")) {
getline(d_read, short_str);
detailed.io_write = floating_humanizer(stoull(short_str));
break;
}
else
d_read.ignore(SSmax, '\n');
}
}
catch (const std::invalid_argument&) {}
catch (const std::out_of_range&) {}
d_read.close();
}
}
//* Collects and sorts process information from /proc
auto collect(const bool no_update) -> vector<proc_info>& {
const auto& sorting = Config::getS("proc_sorting");
const auto& reverse = Config::getB("proc_reversed");
const auto& filter = Config::getS("proc_filter");
const auto& per_core = Config::getB("proc_per_core");
const auto& tree = Config::getB("proc_tree");
const auto& show_detailed = Config::getB("show_detailed");
const size_t detailed_pid = Config::getI("detailed_pid");
bool should_filter = current_filter != filter;
if (should_filter) current_filter = filter;
const bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);
if (sorted_change) {
current_sort = sorting;
current_rev = reverse;
}
ifstream pread;
string long_string;
string short_str;
const double uptime = system_uptime();
const int cmult = (per_core) ? Shared::coreCount : 1;
bool got_detailed = false;
//* Use pids from last update if only changing filter, sorting or tree options
if (no_update and not current_procs.empty()) {
if (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, round(uptime), current_procs);
}
//* ---------------------------------------------Collection start----------------------------------------------
else {
should_filter = true;
auto totalMem = Mem::get_totalMem();
int totalMem_len = to_string(totalMem >> 10).size();
//? Update uid_user map if /etc/passwd changed since last run
if (not Shared::passwd_path.empty() and fs::last_write_time(Shared::passwd_path) != passwd_time) {
string r_uid, r_user;
passwd_time = fs::last_write_time(Shared::passwd_path);
uid_user.clear();
pread.open(Shared::passwd_path);
if (pread.good()) {
while (not pread.eof()) {
getline(pread, r_user, ':');
pread.ignore(SSmax, ':');
getline(pread, r_uid, ':');
uid_user[r_uid] = r_user;
pread.ignore(SSmax, '\n');
}
}
else {
Shared::passwd_path.clear();
}
pread.close();
}
//? Get cpu total times from /proc/stat
cputimes = 0;
pread.open(Shared::procPath / "stat");
if (pread.good()) {
pread.ignore(SSmax, ' ');
for (uint64_t times; pread >> times; cputimes += times);
}
else throw std::runtime_error("Failure to read /proc/stat");
pread.close();
//? Iterate over all pids in /proc
vector<size_t> found;
for (const auto& d: fs::directory_iterator(Shared::procPath)) {
if (Runner::stopping)
return current_procs;
if (pread.is_open()) pread.close();
const string pid_str = d.path().filename();
if (not isdigit(pid_str[0])) continue;
const size_t pid = stoul(pid_str);
found.push_back(pid);
//? Check if pid already exists in current_procs
auto find_old = rng::find(current_procs, pid, &proc_info::pid);
bool no_cache = false;
if (find_old == current_procs.end()) {
current_procs.push_back({pid});
find_old = current_procs.end() - 1;
no_cache = true;
}
auto& new_proc = *find_old;
//? Get program name, command and username
if (no_cache) {
pread.open(d.path() / "comm");
if (not pread.good()) continue;
getline(pread, new_proc.name);
pread.close();
//? Check for whitespace characters in name and set offset to get correct fields from stat file
new_proc.name_offset = rng::count(new_proc.name, ' ');
pread.open(d.path() / "cmdline");
if (not pread.good()) continue;
long_string.clear();
while(getline(pread, long_string, '\0')) new_proc.cmd += long_string + ' ';
pread.close();
if (not new_proc.cmd.empty()) new_proc.cmd.pop_back();
pread.open(d.path() / "status");
if (not pread.good()) continue;
string uid;
string line;
while (not pread.eof()) {
getline(pread, line, ':');
if (line == "Uid") {
pread.ignore();
getline(pread, uid, '\t');
break;
} else {
pread.ignore(SSmax, '\n');
}
}
pread.close();
if (uid_user.contains(uid)) {
new_proc.user = uid_user.at(uid);
}
else {
#ifndef STATIC_BUILD
try {
struct passwd* udet;
udet = getpwuid(stoi(uid));
if (udet != NULL and udet->pw_name != NULL) {
new_proc.user = string(udet->pw_name);
}
else {
new_proc.user = uid;
}
}
catch (...) { new_proc.user = uid; }
#else
new_proc.user = uid;
#endif
}
}
//? Parse /proc/[pid]/stat
pread.open(d.path() / "stat");
if (not pread.good()) continue;
const auto& offset = new_proc.name_offset;
short_str.clear();
int x = 0, next_x = 3;
uint64_t cpu_t = 0;
try {
for (;;) {
while (++x < next_x + offset) pread.ignore(SSmax, ' ');
getline(pread, short_str, ' ');
if (not pread.good()) break;
switch (x-offset) {
case 3: //? Process state
new_proc.state = short_str.at(0);
if (new_proc.ppid != 0) next_x = 14;
continue;
case 4: //? Parent pid
new_proc.ppid = stoull(short_str);
next_x = 14;
continue;
case 14: //? Process utime
cpu_t = stoull(short_str);
continue;
case 15: //? Process stime
cpu_t += stoull(short_str);
next_x = 19;
continue;
case 19: //? Nice value
new_proc.p_nice = stoull(short_str);
continue;
case 20: //? Number of threads
new_proc.threads = stoull(short_str);
if (new_proc.cpu_s == 0) {
next_x = 22;
new_proc.cpu_t = cpu_t;
}
else
next_x = 24;
continue;
case 22: //? Get cpu seconds if missing
new_proc.cpu_s = stoull(short_str);
next_x = 24;
continue;
case 24: //? RSS memory (can be inaccurate, but parsing smaps increases total cpu usage by ~20x)
if (cmp_greater(short_str.size(), totalMem_len))
new_proc.mem = totalMem;
else
new_proc.mem = stoull(short_str) * Shared::pageSize;
}
break;
}
}
catch (const std::invalid_argument&) { continue; }
catch (const std::out_of_range&) { continue; }
pread.close();
if (x-offset < 24) continue;
//? Get RSS memory from /proc/[pid]/statm if value from /proc/[pid]/stat looks wrong
if (new_proc.mem >= totalMem) {
pread.open(d.path() / "statm");
if (not pread.good()) continue;
pread.ignore(SSmax, ' ');
pread >> new_proc.mem;
new_proc.mem *= Shared::pageSize;
pread.close();
}
//? Process cpu usage since last update
new_proc.cpu_p = clamp(round(cmult * 1000 * (cpu_t - new_proc.cpu_t) / max((uint64_t)1, cputimes - old_cputimes)) / 10.0, 0.0, 100.0 * Shared::coreCount);
//? Process cumulative cpu usage since process start
new_proc.cpu_c = (double)cpu_t / max(1.0, (uptime * Shared::clkTck) - new_proc.cpu_s);
//? Update cached value with latest cpu times
new_proc.cpu_t = cpu_t;
if (show_detailed and not got_detailed and new_proc.pid == detailed_pid) {
got_detailed = true;
}
}
//? Clear dead processes from current_procs
auto eraser = rng::remove_if(current_procs, [&](const auto& element){ return not v_contains(found, element.pid); });
current_procs.erase(eraser.begin(), eraser.end());
//? Update the details info box for process if active
if (show_detailed and got_detailed) {
_collect_details(detailed_pid, round(uptime), current_procs);
}
else if (show_detailed and not got_detailed and detailed.status != "Dead") {
detailed.status = "Dead";
redraw = true;
}
old_cputimes = cputimes;
}
//* ---------------------------------------------Collection done-----------------------------------------------
//* Sort processes
if (sorted_change or not no_update) {
switch (v_index(sort_vector, sorting)) {
case 0: rng::sort(current_procs, rng::greater{}, &proc_info::pid); break;
case 1: rng::sort(current_procs, rng::greater{}, &proc_info::name); break;
case 2: rng::sort(current_procs, rng::greater{}, &proc_info::cmd); break;
case 3: rng::sort(current_procs, rng::greater{}, &proc_info::threads); break;
case 4: rng::sort(current_procs, rng::greater{}, &proc_info::user); break;
case 5: rng::sort(current_procs, rng::greater{}, &proc_info::mem); break;
case 6: rng::sort(current_procs, rng::greater{}, &proc_info::cpu_p); break;
case 7: rng::sort(current_procs, rng::greater{}, &proc_info::cpu_c); break;
}
if (reverse) rng::reverse(current_procs);
//* When sorting with "cpu lazy" push processes over threshold cpu usage to the front regardless of cumulative usage
if (not tree and not reverse and sorting == "cpu lazy") {
double max = 10.0, target = 30.0;
for (size_t i = 0, x = 0, offset = 0; i < current_procs.size(); i++) {
if (i <= 5 and current_procs.at(i).cpu_p > max)
max = current_procs.at(i).cpu_p;
else if (i == 6)
target = (max > 30.0) ? max : 10.0;
if (i == offset and current_procs.at(i).cpu_p > 30.0)
offset++;
else if (current_procs.at(i).cpu_p > target) {
rotate(current_procs.begin() + offset, current_procs.begin() + i, current_procs.begin() + i + 1);
if (++x > 10) break;
}
}
}
}
//* Match filter if defined
if (should_filter) {
filter_found = 0;
for (auto& p : current_procs) {
if (not tree and not filter.empty()) {
if (not s_contains(to_string(p.pid), filter)
and not s_contains(p.name, filter)
and not s_contains(p.cmd, filter)
and not s_contains(p.user, filter)) {
p.filtered = true;
filter_found++;
}
else {
p.filtered = false;
}
}
else {
p.filtered = false;
}
}
}
//* Generate tree view if enabled
if (tree and (not no_update or should_filter or sorted_change)) {
if (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) {
auto collapser = rng::find(current_procs, find_pid, &proc_info::pid);
if (collapser != current_procs.end()) {
if (collapse == expand) {
collapser->collapsed = not collapser->collapsed;
}
else if (collapse > -1) {
collapser->collapsed = true;
}
else if (expand > -1) {
collapser->collapsed = false;
}
}
collapse = expand = -1;
}
if (should_filter or not filter.empty()) filter_found = 0;
vector<std::reference_wrapper<proc_info>> tree_procs;
tree_procs.reserve(current_procs.size());
//? Stable sort to retain selected sorting among processes with the same parent
rng::stable_sort(current_procs, rng::less{}, &proc_info::ppid);
//? Start recursive iteration over processes with the lowest shared parent pids
for (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) {
_tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter);
}
//? Final sort based on tree index
rng::sort(current_procs, rng::less{}, &proc_info::tree_index);
if (reverse) rng::reverse(current_procs);
}
numpids = (int)current_procs.size() - filter_found;
return current_procs;
}
}
namespace Tools {
double system_uptime() {
string upstr;
ifstream pread(Shared::procPath / "uptime");
if (pread.good()) {
try {
getline(pread, upstr, ' ');
pread.close();
return stod(upstr);
}
catch (const std::invalid_argument&) {}
catch (const std::out_of_range&) {}
}
throw std::runtime_error("Failed get uptime from from " + (string)Shared::procPath + "/uptime");
}
}
|
// 2019 Spring CS380 Homework 4
// You have to implement
// 1. Normal mapping
// NormalMaterial.cpp, NormalMaterial.hpp
// Vertex has new attribute vec4 tangent (see ModelLoader.cpp or Geometry.cpp)
// 2. Shadow Mapping
// ShadowMap.hpp, ShadowMaterial.cpp, ShadowMaterial.hpp
//
// You can create/modify any functions or files in APP
// Use the OpenGL documentation
// You could use glm::ortho(), glm::lookAt() for shadow mapping
// STL
#include <iostream>
// include opengl extension and application library
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
// include Engine
#include <Camera.hpp>
#include <Mesh.hpp>
#include <Material.hpp>
#include <Texture.hpp>
#include <RenderObject.hpp>
#include <Geometry.hpp>
#include <DiffuseMaterial.hpp>
#include <NormalMaterial.hpp>
#include <CubeMaterial.hpp>
#include <ShadowMap.hpp>
#include <ShadowMaterial.hpp>
#include <ShadowCastingObject.hpp>
GLFWwindow* g_window;
float g_window_width = 1440.f;
float g_window_height = 1080.f;
int g_framebuffer_width = 1440;
int g_framebuffer_height = 1080;
constexpr float PI = 3.14159265f;
constexpr float CAMERA_ROTATE_SPEED = 1.2f;
static float camera_direction = 0;
static Engine::Camera *camera;
static std::vector<Light> lights;
static bool mode_cam_left = false;
static bool mode_cam_right = false;
static bool mode_cam_forward = false;
static bool mode_cam_back = false;
static void KeyboardCallback(GLFWwindow* a_window, int a_key, int a_scancode, int a_action, int a_mods)
{
if (a_action == GLFW_PRESS)
{
switch (a_key)
{
case GLFW_KEY_LEFT:
mode_cam_left = true;
break;
case GLFW_KEY_RIGHT:
mode_cam_right = true;
break;
case GLFW_KEY_UP:
mode_cam_forward = true;
break;
case GLFW_KEY_DOWN:
mode_cam_back = true;
break;
case GLFW_KEY_P:
lights[1].enabled = !lights[1].enabled;
break;
}
}
else if (a_action == GLFW_RELEASE)
{
switch (a_key)
{
case GLFW_KEY_LEFT:
mode_cam_left = false;
break;
case GLFW_KEY_RIGHT:
mode_cam_right = false;
break;
case GLFW_KEY_UP:
mode_cam_forward = false;
break;
case GLFW_KEY_DOWN:
mode_cam_back = false;
break;
}
}
}
int main(int argc, char** argv)
{
// Initialize GLFW library
if (!glfwInit())
{
return -1;
}
// Create window and OpenGL context
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
/* Create a windowed mode window and its OpenGL context */
g_window = glfwCreateWindow(g_window_width, g_window_height, "HW4 - 20170737", NULL, NULL);
if (!g_window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(g_window);
// Initialize GLEW library
GLenum glew_error = glewInit();
if (glew_error != GLEW_OK)
{
std::cout << "GLEW Error: " << glewGetErrorString(glew_error) << std::endl;
exit(1);
}
// Initialization
// Screw OOP and just write everything here
camera = new Engine::Camera(
glm::vec3(0),
glm::mat4(1)
);
camera->SetProjection(g_window_width / g_window_height, 70.0, 0.1, 1200);
lights.push_back({
LightType::DirectionalLight,
1,
new Engine::Transform(),
glm::vec3(0, 0, 0),
glm::vec3(2, 2, 2)
});
lights.push_back({
LightType::PointLight,
false,
new Engine::Transform(),
glm::vec3(1, 1, 1),
glm::vec3(10, 10, 10)
});
lights[1].transform->SetPosition(glm::vec3(0, 2, 0));
Engine::Mesh *roomMesh = new Engine::Mesh();
roomMesh->AddAttribute(4);
roomMesh->AddAttribute(4);
roomMesh->AddAttribute(2);
roomMesh->AddAttribute(4);
for (int x = -10; x < 10; x++)
{
for (int y = -5; y < 5; y++)
{
int block_type = 0x06;
int block_x = block_type & 0xF;
int block_y = block_type >> 4;
float offset = 0.025f / 16.0f;
float atlas_size = 1.0f / 16.0f;
roomMesh->AddVertexData(glm::vec4(x, y, -1, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x+1, y, -1, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x+1, y+1, -1, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, y, -1, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x+1, y+1, -1, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, y+1, -1, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
block_type = (x == -10 || x == 9) || (y == -5 || y == 4) ? 0x15 : 0x10;
if ((x == -1 || x == 0) && (y == -1 || y == 0))
block_type = 0xD3;
block_x = block_type & 0xF;
block_y = block_type >> 4;
roomMesh->AddVertexData(glm::vec4(x, y, 3, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, -1, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, y + 1, 3, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, -1, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, y, 3, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, -1, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, y, 3, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, -1, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, y + 1, 3, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, -1, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, y + 1, 3, 1));
roomMesh->AddVertexData(glm::vec4(0, 0, -1, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
}
}
for (int x = -10; x < 10; x++)
{
for (int z = -1; z < 3; z++)
{
int block_type = x == -10 || x == 9 ? 0x14 : (x > -8 && x < 7 && (z == 0 || z == 1)) ? 0x31 : 0x04;
int block_x = block_type & 0xF;
int block_y = block_type >> 4;
float offset = 0.025f / 16.0f;
float atlas_size = 1.0f / 16.0f;
roomMesh->AddVertexData(glm::vec4(x, -5, z, 1));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size) - offset);
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, -5, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, -5, z, 1));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, -5, z, 1));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, -5, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, -5, z+1, 1));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
block_type = x == -10 || x == 9 ? 0x14 : (x > -7 && x < 5 && z == 1) ? 0x54 : 0x04;
block_x = block_type & 0xF;
block_y = block_type >> 4;
roomMesh->AddVertexData(glm::vec4(x, 5, z, 1));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, 5, z, 1));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, 5, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, 5, z, 1));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x + 1, 5, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec4(x, 5, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
}
}
for (int y = -5; y < 5; y++)
{
for (int z = -1; z < 3; z++)
{
int block_type = y == -5 || y == 4 ? 0x14 : (y > -4 && y < 3 && (z == 0 || z == 1)) ? 0x31 : 0x04;
int block_x = block_type & 0xF;
int block_y = block_type >> 4;
float offset = 0.025f / 16.0f;
float atlas_size = 1.0f / 16.0f;
roomMesh->AddVertexData(glm::vec4(-10, y, z, 1));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec4(-10, y + 1, z, 1));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec4(-10, y+1, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec4(-10, y, z, 1));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec4(-10, y + 1, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec4(-10, y, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(0, 1, 0, 0));
roomMesh->AddVertexData(glm::vec4(10, y, z, 1));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec4(10, y + 1, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec4(10, y + 1, z, 1));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec4(10, y, z, 1));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, (block_y + 1) * atlas_size - offset));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec4(10, y, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2(block_x * atlas_size + offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
roomMesh->AddVertexData(glm::vec4(10, y + 1, z + 1, 1));
roomMesh->AddVertexData(glm::vec4(-1, 0, 0, 0));
roomMesh->AddVertexData(glm::vec2((block_x + 1) * atlas_size - offset, block_y * atlas_size + offset));
roomMesh->AddVertexData(glm::vec4(0, -1, 0, 0));
}
}
roomMesh->SetNumElements(3840);
roomMesh->CreateMesh();
Engine::TextureLoader *roomTextureLoader = new Engine::TextureLoader(0, "Resources\\Textures\\BlockTexture.png");
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
Engine::TextureLoader *blockNormalTexture = new Engine::TextureLoader(1, "Resources\\Textures\\NormalMap.png");
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
NormalMaterial *normalMaterial = new NormalMaterial();
normalMaterial->CreateMaterial(roomTextureLoader->GetUnit(), blockNormalTexture->GetUnit(), 3);
ShadowCastingObject *roomObject = new ShadowCastingObject(roomMesh, normalMaterial);
roomObject->GetTransform()->SetOrientation(
glm::rotate(
glm::mat4(1),
-0.5f * PI,
glm::vec3(1, 0, 0)
)
);
Engine::Mesh *cube_mesh = new Engine::Mesh();
Geometry geometry = Geometry();
geometry.GenerateCube(cube_mesh);
std::string path_prefix = "Resources\\Textures\\skybox\\criminal-element_";
Engine::TextureLoader* skyboxTextureLoader = new Engine::TextureLoader(2, path_prefix + "bk.tga", path_prefix + "ft.tga",
path_prefix + "up.tga", path_prefix + "dn.tga", path_prefix + "lf.tga", path_prefix + "rt.tga");
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
CubeMaterial *cubemap_material = new CubeMaterial();
cubemap_material->CreateMaterial(skyboxTextureLoader->GetUnit());
Engine::RenderObject *cubemap_object = new Engine::RenderObject(cube_mesh, cubemap_material);
ShadowMaterial *shadowMaterial = new ShadowMaterial();
shadowMaterial->CreateMaterial();
roomObject->SetShadowMat(shadowMaterial);
shadowInitialize(1024, 1024, 3);
/*
Engine::Mesh *quadMesh = new Engine::Mesh();
quadMesh->AddAttribute(4);
quadMesh->AddAttribute(4);
quadMesh->AddAttribute(2);
quadMesh->AddAttribute(4);
quadMesh->AddVertexData(glm::vec4(-1, -1, -1, 1));
quadMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
quadMesh->AddVertexData(glm::vec2(1, 0));
quadMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
quadMesh->AddVertexData(glm::vec4(1, -1, -1, 1));
quadMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
quadMesh->AddVertexData(glm::vec2(0, 0));
quadMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
quadMesh->AddVertexData(glm::vec4(1, 1, -1, 1));
quadMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
quadMesh->AddVertexData(glm::vec2(0, 1));
quadMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
quadMesh->AddVertexData(glm::vec4(-1, -1, -1, 1));
quadMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
quadMesh->AddVertexData(glm::vec2(1, 0));
quadMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
quadMesh->AddVertexData(glm::vec4(1, 1, -1, 1));
quadMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
quadMesh->AddVertexData(glm::vec2(0, 1));
quadMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
quadMesh->AddVertexData(glm::vec4(-1, 1, -1, 1));
quadMesh->AddVertexData(glm::vec4(0, 0, 1, 0));
quadMesh->AddVertexData(glm::vec2(1, 1));
quadMesh->AddVertexData(glm::vec4(1, 0, 0, 0));
quadMesh->SetNumElements(6);
quadMesh->CreateMesh();
DiffuseMaterial *diffuseMaterial = new DiffuseMaterial();
diffuseMaterial->CreateMaterial(3);
Engine::RenderObject *quadObject = new Engine::RenderObject(quadMesh, diffuseMaterial);
*/
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles
glEnable(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_CUBE_MAP);
glfwSetInputMode(g_window, GLFW_STICKY_KEYS, GL_TRUE);
glfwSetKeyCallback(g_window, KeyboardCallback);
float prev_time = (float)glfwGetTime();
glClearColor(1, 0, 0, 1);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(g_window) && glfwGetKey(g_window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
{
float total_time = (float)glfwGetTime();
float elapsed_time = total_time - prev_time;
prev_time = total_time;
lights[0].light_direction = glm::vec3(5 * cos(0.01 * total_time), 1, 5 * sin(0.01 * total_time));
camera_direction += mode_cam_left ? elapsed_time * CAMERA_ROTATE_SPEED : 0;
camera_direction += mode_cam_right ? -elapsed_time * CAMERA_ROTATE_SPEED : 0;
camera->GetTransform()->SetPosition(glm::vec3(
camera->GetTransform()->GetPosition()
+ (mode_cam_forward ? 2 * elapsed_time * glm::vec3(cos(camera_direction + 0.5 * PI), 0.0f, -sin(camera_direction + 0.5 * PI)) : glm::vec3(0.0f))
+ (mode_cam_back ? -2 * elapsed_time * glm::vec3(cos(camera_direction + 0.5 * PI), 0.0f, -sin(camera_direction + 0.5 * PI)) : glm::vec3(0.0f))
));
glm::vec3 pos = camera->GetTransform()->GetPosition();
if (pos.x > 9)
camera->GetTransform()->SetPosition(glm::vec3(9, pos.y, pos.z));
else if (pos.x < -9)
camera->GetTransform()->SetPosition(glm::vec3(-9, pos.y, pos.z));
pos = camera->GetTransform()->GetPosition();
if (pos.z > 4)
camera->GetTransform()->SetPosition(glm::vec3(pos.x, pos.y, 4));
else if (pos.z < -4)
camera->GetTransform()->SetPosition(glm::vec3(pos.x, pos.y, -4));
camera->GetTransform()->SetOrientation(
glm::rotate(
glm::mat4(1),
camera_direction,
glm::vec3(0, 1, 0)
)
);
glViewport(0, 0, 1024, 1024);
glBindFramebuffer(GL_FRAMEBUFFER, shadow_fbo);
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_CULL_FACE);
roomObject->RenderShadow(lights[0]);
glEnable(GL_CULL_FACE);
glViewport(0, 0, g_framebuffer_width, g_framebuffer_height);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_CULL_FACE);
glDepthMask(GL_FALSE);
cubemap_material->IsSkybox(1);
cubemap_object->Render(camera);
glEnable(GL_CULL_FACE);
glDepthMask(GL_TRUE);
normalMaterial->UpdateDiffuseReflectance(glm::vec3(1, 1, 1));
normalMaterial->UpdateLight(lights);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
roomObject->Render(camera);
glDisable(GL_BLEND);
// quadObject->Render(camera);
/* Swap front and back buffers */
glfwSwapBuffers(g_window);
/* Poll for and process events */
glfwPollEvents();
}
// Delete resources
glfwTerminate();
return 0;
}
|
//
// type.cpp
// dgmpp
//
// Created by Artem Shimanski on 14.12.2017.
//
#include "type.h"
#include "internal.h"
DGMPP_TYPE dgmpp_get_type (dgmpp_type type) {
auto base = get<Type>(type).get();
if (dynamic_cast<Gang*>(base))
return DGMPP_TYPE_GANG;
else if (dynamic_cast<Character*>(base))
return DGMPP_TYPE_CHARACTER;
else if (dynamic_cast<Skill*>(base))
return DGMPP_TYPE_SKILL;
else if (dynamic_cast<Implant*>(base))
return DGMPP_TYPE_IMPLANT;
else if (dynamic_cast<Booster*>(base))
return DGMPP_TYPE_BOOSTER;
else if (dynamic_cast<Structure*>(base))
return DGMPP_TYPE_STRUCTURE;
else if (dynamic_cast<Ship*>(base))
return DGMPP_TYPE_SHIP;
else if (dynamic_cast<Module*>(base))
return DGMPP_TYPE_MODULE;
else if (dynamic_cast<Drone*>(base))
return DGMPP_TYPE_DRONE;
else if (dynamic_cast<Charge*>(base))
return DGMPP_TYPE_CHARGE;
else if (dynamic_cast<Area*>(base))
return DGMPP_TYPE_AREA;
else if (dynamic_cast<Cargo*>(base))
return DGMPP_TYPE_CARGO;
else
return DGMPP_TYPE_NONE;
}
dgmpp_type_id dgmpp_type_get_type_id (dgmpp_type type) {
return static_cast<dgmpp_type_id>(get<Type>(type)->metaInfo().typeID);
}
dgmpp_group_id dgmpp_type_get_group_id (dgmpp_type type) {
return static_cast<dgmpp_group_id>(get<Type>(type)->metaInfo().groupID);
}
dgmpp_category_id dgmpp_type_get_category_id (dgmpp_type type) {
return static_cast<dgmpp_category_id>(get<Type>(type)->metaInfo().categoryID);
}
dgmpp_type dgmpp_type_copy_parent (dgmpp_type type) {
if (auto parent = get<Type>(type)->parent()) {
return new_handle(parent->shared_from_this());
}
else {
return nullptr;
}
}
dgmpp_attribute dgmpp_type_get_attribute (dgmpp_type type, dgmpp_attribute_id attribute_id) {
auto attribute = (*get<Type>(type))[static_cast<AttributeID>(attribute_id)];
return attribute;
}
dgmpp_array dgmpp_type_copy_affectors (dgmpp_type type) {
auto affectors = get<Type>(type)->affectors();
std::vector<dgmpp_handle> result;
result.reserve(affectors.size());
std::transform(affectors.begin(), affectors.end(), std::back_inserter(result), [](const auto& i) {
return new_handle(i->shared_from_this());
//return dgmpp_handle_store_impl<std::shared_ptr<Type>>(i->shared_from_this());
});
return dgmpp_make_array< dgmpp_handle>(std::move(result));
}
dgmpp_array dgmpp_type_copy_attributes (dgmpp_type type) {
auto attributes = get<Type>(type)->attributes();
std::vector<Attribute*> result(attributes.begin(), attributes.end());
return dgmpp_make_array<Attribute*>(std::move(result));
}
size_t dgmpp_type_get_identifier (dgmpp_type type) {
return get<Type>(type)->identifier();
}
void dgmpp_type_set_identifier (dgmpp_type type, size_t identifier) {
get<Type>(type)->identifier(identifier);
}
DGMPP_META_GROUP dgmpp_type_get_meta_group (dgmpp_type type) {
return static_cast<DGMPP_META_GROUP>(get<Type>(type)->metaInfo().metaGroup);
}
size_t dgmpp_type_get_meta_level (dgmpp_type type) {
return get<Type>(type)->metaInfo().metaLevel;
}
|
/**
* Copyright (C) 2016 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage
#include "mongo/platform/basic.h"
#include "mongo/db/dbmain.h"
#include <boost/filesystem/operations.hpp>
#include <boost/optional.hpp>
#include <fstream>
#include <iostream>
#include <limits>
#include <signal.h>
#include <string>
#include "mongo/base/init.h"
#include "mongo/base/initializer.h"
#include "mongo/base/status.h"
#include "mongo/client/global_conn_pool.h"
#include "mongo/client/replica_set_monitor.h"
#include "mongo/config.h"
#include "mongo/db/audit.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_manager_global.h"
#include "mongo/db/auth/sasl_options.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/create_collection.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/database_catalog_entry.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/health_log.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/catalog/index_key_validate.h"
#include "mongo/db/catalog/uuid_catalog.h"
#include "mongo/db/client.h"
#include "mongo/db/clientcursor.h"
#include "mongo/db/commands/feature_compatibility_version.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/lock_state.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/dbmessage.h"
#include "mongo/db/exec/working_set_common.h"
#include "mongo/db/free_mon/free_mon_mongod.h"
#include "mongo/db/ftdc/ftdc_mongod.h"
#include "mongo/db/global_settings.h"
#include "mongo/db/index_names.h"
#include "mongo/db/index_rebuilder.h"
#include "mongo/db/initialize_server_global_state.h"
#include "mongo/db/initialize_snmp.h"
#include "mongo/db/introspect.h"
#include "mongo/db/json.h"
#include "mongo/db/keys_collection_client_direct.h"
#include "mongo/db/keys_collection_client_sharded.h"
#include "mongo/db/keys_collection_manager.h"
#include "mongo/db/kill_sessions.h"
#include "mongo/db/kill_sessions_local.h"
#include "mongo/db/log_process_details.h"
#include "mongo/db/logical_clock.h"
#include "mongo/db/logical_session_cache.h"
#include "mongo/db/logical_session_cache_factory_mongod.h"
#include "mongo/db/logical_time_metadata_hook.h"
#include "mongo/db/logical_time_validator.h"
#include "mongo/db/mongod_options.h"
#include "mongo/db/op_observer_registry.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/periodic_runner_job_abort_expired_transactions.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/repair_database_and_check_version.h"
#include "mongo/db/repl/drop_pending_collection_reaper.h"
#include "mongo/db/repl/oplog.h"
#include "mongo/db/repl/repl_settings.h"
#include "mongo/db/repl/replication_consistency_markers_impl.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/replication_coordinator_external_state_impl.h"
#include "mongo/db/repl/replication_coordinator_impl.h"
#include "mongo/db/repl/replication_process.h"
#include "mongo/db/repl/replication_recovery.h"
#include "mongo/db/repl/storage_interface_impl.h"
#include "mongo/db/repl/topology_coordinator.h"
#include "mongo/db/s/balancer/balancer.h"
#include "mongo/db/s/config/sharding_catalog_manager.h"
#include "mongo/db/s/config_server_op_observer.h"
#include "mongo/db/s/op_observer_sharding_impl.h"
#include "mongo/db/s/shard_server_op_observer.h"
#include "mongo/db/s/sharding_initialization_mongod.h"
#include "mongo/db/s/sharding_state_recovery.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_parameters.h"
#include "mongo/db/service_context.h"
#include "mongo/db/service_entry_point_mongod.h"
#include "mongo/db/session_catalog.h"
#include "mongo/db/session_killer.h"
#include "mongo/db/startup_warnings_mongod.h"
#include "mongo/db/stats/counters.h"
#include "mongo/db/storage/encryption_hooks.h"
#include "mongo/db/storage/mmap_v1/mmap_v1_options.h"
#include "mongo/db/storage/storage_engine.h"
#include "mongo/db/storage/storage_engine_init.h"
#include "mongo/db/storage/storage_options.h"
#include "mongo/db/system_index.h"
#include "mongo/db/ttl.h"
#include "mongo/db/wire_version.h"
#include "mongo/executor/network_connection_hook.h"
#include "mongo/executor/network_interface_factory.h"
#include "mongo/executor/network_interface_thread_pool.h"
#include "mongo/executor/thread_pool_task_executor.h"
#include "mongo/platform/process_id.h"
#include "mongo/rpc/metadata/egress_metadata_hook_list.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/grid.h"
#include "mongo/s/sharding_initialization.h"
#include "mongo/scripting/dbdirectclient_factory.h"
#include "mongo/scripting/engine.h"
#include "mongo/stdx/future.h"
#include "mongo/stdx/memory.h"
#include "mongo/stdx/thread.h"
#include "mongo/transport/transport_layer_manager.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/background.h"
#include "mongo/util/cmdline_utils/censor_cmdline.h"
#include "mongo/util/concurrency/idle_thread_block.h"
#include "mongo/util/concurrency/thread_name.h"
#include "mongo/util/exception_filter_win32.h"
#include "mongo/util/exit.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/fast_clock_source_factory.h"
#include "mongo/util/log.h"
#include "mongo/util/net/socket_utils.h"
#include "mongo/util/net/ssl_manager.h"
#include "mongo/util/ntservice.h"
#include "mongo/util/options_parser/startup_options.h"
#include "mongo/util/periodic_runner.h"
#include "mongo/util/periodic_runner_factory.h"
#include "mongo/util/quick_exit.h"
#include "mongo/util/ramlog.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/sequence_util.h"
#include "mongo/util/signal_handlers.h"
#include "mongo/util/stacktrace.h"
#include "mongo/util/startup_test.h"
#include "mongo/util/text.h"
#include "mongo/util/time_support.h"
#include "mongo/util/version.h"
#ifdef MONGO_CONFIG_SSL
#include "mongo/util/net/ssl_options.h"
#endif
#if !defined(_WIN32)
#include <sys/file.h>
#endif
namespace mongo {
using logger::LogComponent;
using std::endl;
namespace {
const NamespaceString startupLogCollectionName("local.startup_log");
const NamespaceString kSystemReplSetCollection("local.system.replset");
#ifdef _WIN32
const ntservice::NtServiceDefaultStrings defaultServiceStrings = {
L"MongoDB", L"MongoDB", L"MongoDB Server"};
#endif
void logStartup(OperationContext* opCtx) {
BSONObjBuilder toLog;
std::stringstream id;
id << getHostNameCached() << "-" << jsTime().asInt64();
toLog.append("_id", id.str());
toLog.append("hostname", getHostNameCached());
toLog.appendTimeT("startTime", time(0));
toLog.append("startTimeLocal", dateToCtimeString(Date_t::now()));
toLog.append("cmdLine", serverGlobalParams.parsedOpts);
toLog.append("pid", ProcessId::getCurrent().asLongLong());
BSONObjBuilder buildinfo(toLog.subobjStart("buildinfo"));
VersionInfoInterface::instance().appendBuildInfo(&buildinfo);
appendStorageEngineList(opCtx->getServiceContext(), &buildinfo);
buildinfo.doneFast();
BSONObj o = toLog.obj();
Lock::GlobalWrite lk(opCtx);
AutoGetOrCreateDb autoDb(opCtx, startupLogCollectionName.db(), mongo::MODE_X);
Database* db = autoDb.getDb();
Collection* collection = db->getCollection(opCtx, startupLogCollectionName);
WriteUnitOfWork wunit(opCtx);
if (!collection) {
BSONObj options = BSON("capped" << true << "size" << 10 * 1024 * 1024);
repl::UnreplicatedWritesBlock uwb(opCtx);
CollectionOptions collectionOptions;
uassertStatusOK(
collectionOptions.parse(options, CollectionOptions::ParseKind::parseForCommand));
uassertStatusOK(
Database::userCreateNS(opCtx, db, startupLogCollectionName.ns(), collectionOptions));
collection = db->getCollection(opCtx, startupLogCollectionName);
}
invariant(collection);
OpDebug* const nullOpDebug = nullptr;
uassertStatusOK(collection->insertDocument(opCtx, InsertStatement(o), nullOpDebug, false));
wunit.commit();
}
/**
* Checks if this server was started without --replset but has a config in local.system.replset
* (meaning that this is probably a replica set member started in stand-alone mode).
*
* @returns the number of documents in local.system.replset or 0 if this was started with
* --replset.
*/
unsigned long long checkIfReplMissingFromCommandLine(OperationContext* opCtx) {
// This is helpful for the query below to work as you can't open files when readlocked
Lock::GlobalWrite lk(opCtx);
if (!repl::ReplicationCoordinator::get(opCtx)->getSettings().usingReplSets()) {
DBDirectClient c(opCtx);
return c.count(kSystemReplSetCollection.ns());
}
return 0;
}
void initWireSpec() {
WireSpec& spec = WireSpec::instance();
// The featureCompatibilityVersion behavior defaults to the downgrade behavior while the
// in-memory version is unset.
spec.incomingInternalClient.minWireVersion = RELEASE_2_4_AND_BEFORE;
spec.incomingInternalClient.maxWireVersion = LATEST_WIRE_VERSION;
spec.outgoing.minWireVersion = RELEASE_2_4_AND_BEFORE;
spec.outgoing.maxWireVersion = LATEST_WIRE_VERSION;
spec.isInternalClient = true;
}
MONGO_FAIL_POINT_DEFINE(shutdownAtStartup);
ExitCode _initAndListen(int listenPort) {
Client::initThread("initandlisten");
initWireSpec();
auto serviceContext = getGlobalServiceContext();
serviceContext->setFastClockSource(FastClockSourceFactory::create(Milliseconds(10)));
auto opObserverRegistry = stdx::make_unique<OpObserverRegistry>();
opObserverRegistry->addObserver(stdx::make_unique<OpObserverShardingImpl>());
opObserverRegistry->addObserver(stdx::make_unique<UUIDCatalogObserver>());
if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
opObserverRegistry->addObserver(stdx::make_unique<ShardServerOpObserver>());
} else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
opObserverRegistry->addObserver(stdx::make_unique<ConfigServerOpObserver>());
}
setupFreeMonitoringOpObserver(opObserverRegistry.get());
serviceContext->setOpObserver(std::move(opObserverRegistry));
DBDirectClientFactory::get(serviceContext).registerImplementation([](OperationContext* opCtx) {
return std::unique_ptr<DBClientBase>(new DBDirectClient(opCtx));
});
const repl::ReplSettings& replSettings =
repl::ReplicationCoordinator::get(serviceContext)->getSettings();
{
ProcessId pid = ProcessId::getCurrent();
LogstreamBuilder l = log(LogComponent::kControl);
l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port
<< " dbpath=" << storageGlobalParams.dbpath;
const bool is32bit = sizeof(int*) == 4;
l << (is32bit ? " 32" : " 64") << "-bit host=" << getHostNameCached() << endl;
}
DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl;
#if defined(_WIN32)
VersionInfoInterface::instance().logTargetMinOS();
#endif
logProcessDetails();
serviceContext->setServiceEntryPoint(
stdx::make_unique<ServiceEntryPointMongod>(serviceContext));
if (!storageGlobalParams.repair) {
auto tl =
transport::TransportLayerManager::createWithConfig(&serverGlobalParams, serviceContext);
auto res = tl->setup();
if (!res.isOK()) {
error() << "Failed to set up listener: " << res;
return EXIT_NET_ERROR;
}
serviceContext->setTransportLayer(std::move(tl));
}
initializeStorageEngine(serviceContext, StorageEngineInitFlags::kNone);
#ifdef MONGO_CONFIG_WIREDTIGER_ENABLED
if (EncryptionHooks::get(serviceContext)->restartRequired()) {
exitCleanly(EXIT_CLEAN);
}
#endif
// Warn if we detect configurations for multiple registered storage engines in the same
// configuration file/environment.
if (serverGlobalParams.parsedOpts.hasField("storage")) {
BSONElement storageElement = serverGlobalParams.parsedOpts.getField("storage");
invariant(storageElement.isABSONObj());
for (auto&& e : storageElement.Obj()) {
// Ignore if field name under "storage" matches current storage engine.
if (storageGlobalParams.engine == e.fieldName()) {
continue;
}
// Warn if field name matches non-active registered storage engine.
if (isRegisteredStorageEngine(serviceContext, e.fieldName())) {
warning() << "Detected configuration for non-active storage engine "
<< e.fieldName() << " when current storage engine is "
<< storageGlobalParams.engine;
}
}
}
// Disallow running a storage engine that doesn't support capped collections with --profile
if (!serviceContext->getStorageEngine()->supportsCappedCollections() &&
serverGlobalParams.defaultProfile != 0) {
log() << "Running " << storageGlobalParams.engine << " with profiling is not supported. "
<< "Make sure you are not using --profile.";
exitCleanly(EXIT_BADOPTIONS);
}
// Disallow running WiredTiger with --nojournal in a replica set
if (storageGlobalParams.engine == "wiredTiger" && !storageGlobalParams.dur &&
replSettings.usingReplSets()) {
log() << "Running wiredTiger without journaling in a replica set is not "
<< "supported. Make sure you are not using --nojournal and that "
<< "storage.journal.enabled is not set to 'false'.";
exitCleanly(EXIT_BADOPTIONS);
}
logMongodStartupWarnings(storageGlobalParams, serverGlobalParams, serviceContext);
#ifdef MONGO_CONFIG_SSL
if (sslGlobalParams.sslAllowInvalidCertificates &&
((serverGlobalParams.clusterAuthMode.load() == ServerGlobalParams::ClusterAuthMode_x509) ||
sequenceContains(saslGlobalParams.authenticationMechanisms, "MONGODB-X509"))) {
log() << "** WARNING: While invalid X509 certificates may be used to" << startupWarningsLog;
log() << "** connect to this server, they will not be considered"
<< startupWarningsLog;
log() << "** permissible for authentication." << startupWarningsLog;
log() << startupWarningsLog;
}
#endif
{
std::stringstream ss;
ss << endl;
ss << "*********************************************************************" << endl;
ss << " ERROR: dbpath (" << storageGlobalParams.dbpath << ") does not exist." << endl;
ss << " Create this directory or give existing directory in --dbpath." << endl;
ss << " See http://dochub.mongodb.org/core/startingandstoppingmongo" << endl;
ss << "*********************************************************************" << endl;
uassert(10296, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.dbpath));
}
{
std::stringstream ss;
ss << "repairpath (" << storageGlobalParams.repairpath << ") does not exist";
uassert(12590, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.repairpath));
}
initializeSNMP();
if (!storageGlobalParams.readOnly) {
boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/");
}
if (mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalRecoverOnly)
return EXIT_NET_ERROR;
if (mongodGlobalParams.scriptingEnabled) {
ScriptEngine::setup();
}
auto startupOpCtx = serviceContext->makeOperationContext(&cc());
bool canCallFCVSetIfCleanStartup =
!storageGlobalParams.readOnly && (storageGlobalParams.engine != "devnull");
if (canCallFCVSetIfCleanStartup && !replSettings.usingReplSets()) {
Lock::GlobalWrite lk(startupOpCtx.get());
FeatureCompatibilityVersion::setIfCleanStartup(startupOpCtx.get(),
repl::StorageInterface::get(serviceContext));
}
auto swNonLocalDatabases = repairDatabasesAndCheckVersion(startupOpCtx.get());
if (!swNonLocalDatabases.isOK()) {
// SERVER-31611 introduced a return value to `repairDatabasesAndCheckVersion`. Previously,
// a failing condition would fassert. SERVER-31611 covers a case where the binary (3.6) is
// refusing to start up because it refuses acknowledgement of FCV 3.2 and requires the
// user to start up with an older binary. Thus shutting down the server must leave the
// datafiles in a state that the older binary can start up. This requires going through a
// clean shutdown.
//
// The invariant is *not* a statement that `repairDatabasesAndCheckVersion` must return
// `MustDowngrade`. Instead, it is meant as a guardrail to protect future developers from
// accidentally buying into this behavior. New errors that are returned from the method
// may or may not want to go through a clean shutdown, and they likely won't want the
// program to return an exit code of `EXIT_NEED_DOWNGRADE`.
severe(LogComponent::kControl) << "** IMPORTANT: "
<< swNonLocalDatabases.getStatus().reason();
invariant(swNonLocalDatabases == ErrorCodes::MustDowngrade);
exitCleanly(EXIT_NEED_DOWNGRADE);
}
// Assert that the in-memory featureCompatibilityVersion parameter has been explicitly set. If
// we are part of a replica set and are started up with no data files, we do not set the
// featureCompatibilityVersion until a primary is chosen. For this case, we expect the in-memory
// featureCompatibilityVersion parameter to still be uninitialized until after startup.
if (canCallFCVSetIfCleanStartup &&
(!replSettings.usingReplSets() || swNonLocalDatabases.getValue())) {
invariant(serverGlobalParams.featureCompatibility.isVersionInitialized());
}
if (storageGlobalParams.upgrade) {
log() << "finished checking dbs";
exitCleanly(EXIT_CLEAN);
}
// Start up health log writer thread.
HealthLog::get(startupOpCtx.get()).startup();
auto const globalAuthzManager = AuthorizationManager::get(serviceContext);
uassertStatusOK(globalAuthzManager->initialize(startupOpCtx.get()));
// This is for security on certain platforms (nonce generation)
srand((unsigned)(curTimeMicros64()) ^ (unsigned(uintptr_t(&startupOpCtx))));
if (globalAuthzManager->shouldValidateAuthSchemaOnStartup()) {
Status status = verifySystemIndexes(startupOpCtx.get());
if (!status.isOK()) {
log() << redact(status);
if (status == ErrorCodes::AuthSchemaIncompatible) {
exitCleanly(EXIT_NEED_UPGRADE);
} else if (status == ErrorCodes::NotMaster) {
// Try creating the indexes if we become master. If we do not become master,
// the master will create the indexes and we will replicate them.
} else {
quickExit(EXIT_FAILURE);
}
}
// SERVER-14090: Verify that auth schema version is schemaVersion26Final.
int foundSchemaVersion;
status =
globalAuthzManager->getAuthorizationVersion(startupOpCtx.get(), &foundSchemaVersion);
if (!status.isOK()) {
log() << "Auth schema version is incompatible: "
<< "User and role management commands require auth data to have "
<< "at least schema version " << AuthorizationManager::schemaVersion26Final
<< " but startup could not verify schema version: " << status;
exitCleanly(EXIT_NEED_UPGRADE);
}
if (foundSchemaVersion <= AuthorizationManager::schemaVersion26Final) {
log() << "This server is using MONGODB-CR, an authentication mechanism which "
<< "has been removed from MongoDB 4.0. In order to upgrade the auth schema, "
<< "first downgrade MongoDB binaries to version 3.6 and then run the "
<< "authSchemaUpgrade command. "
<< "See http://dochub.mongodb.org/core/3.0-upgrade-to-scram-sha-1";
exitCleanly(EXIT_NEED_UPGRADE);
}
} else if (globalAuthzManager->isAuthEnabled()) {
error() << "Auth must be disabled when starting without auth schema validation";
exitCleanly(EXIT_BADOPTIONS);
} else {
// If authSchemaValidation is disabled and server is running without auth,
// warn the user and continue startup without authSchema metadata checks.
log() << startupWarningsLog;
log() << "** WARNING: Startup auth schema validation checks are disabled for the "
"database."
<< startupWarningsLog;
log() << "** This mode should only be used to manually repair corrupted auth "
"data."
<< startupWarningsLog;
}
// This function may take the global lock.
auto shardingInitialized = ShardingInitializationMongoD::get(startupOpCtx.get())
->initializeShardingAwarenessIfNeeded(startupOpCtx.get());
if (shardingInitialized) {
waitForShardRegistryReload(startupOpCtx.get()).transitional_ignore();
}
auto storageEngine = serviceContext->getStorageEngine();
invariant(storageEngine);
if (!storageGlobalParams.readOnly) {
if (storageEngine->supportsCappedCollections()) {
logStartup(startupOpCtx.get());
}
startMongoDFTDC();
startFreeMonitoring(serviceContext);
restartInProgressIndexesFromLastShutdown(startupOpCtx.get());
if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
// Note: For replica sets, ShardingStateRecovery happens on transition to primary.
if (!repl::ReplicationCoordinator::get(startupOpCtx.get())->isReplEnabled()) {
uassertStatusOK(ShardingStateRecovery::recover(startupOpCtx.get()));
}
} else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
initializeGlobalShardingStateForMongoD(startupOpCtx.get(),
ConnectionString::forLocal(),
kDistLockProcessIdForConfigServer);
Balancer::create(startupOpCtx->getServiceContext());
ShardingCatalogManager::create(
startupOpCtx->getServiceContext(),
makeShardingTaskExecutor(executor::makeNetworkInterface("AddShard-TaskExecutor")));
} else if (replSettings.usingReplSets()) { // standalone replica set
auto keysCollectionClient = stdx::make_unique<KeysCollectionClientDirect>();
auto keyManager = std::make_shared<KeysCollectionManager>(
KeysCollectionManager::kKeyManagerPurposeString,
std::move(keysCollectionClient),
Seconds(KeysRotationIntervalSec));
keyManager->startMonitoring(startupOpCtx->getServiceContext());
LogicalTimeValidator::set(startupOpCtx->getServiceContext(),
stdx::make_unique<LogicalTimeValidator>(keyManager));
}
repl::ReplicationCoordinator::get(startupOpCtx.get())->startup(startupOpCtx.get());
const unsigned long long missingRepl =
checkIfReplMissingFromCommandLine(startupOpCtx.get());
if (missingRepl) {
log() << startupWarningsLog;
log() << "** WARNING: mongod started without --replSet yet " << missingRepl
<< " documents are present in local.system.replset." << startupWarningsLog;
log() << "** Database contents may appear inconsistent with the oplog and may "
"appear to not contain"
<< startupWarningsLog;
log() << "** writes that were visible when this node was running as part of a "
"replica set."
<< startupWarningsLog;
log() << "** Restart with --replSet unless you are doing maintenance and no "
"other clients are connected."
<< startupWarningsLog;
log() << "** The TTL collection monitor will not start because of this."
<< startupWarningsLog;
log() << "** ";
log() << " For more info see http://dochub.mongodb.org/core/ttlcollections";
log() << startupWarningsLog;
} else {
startTTLBackgroundJob();
}
if (replSettings.usingReplSets() || !internalValidateFeaturesAsMaster) {
serverGlobalParams.validateFeaturesAsMaster.store(false);
}
}
startClientCursorMonitor();
startAuditLogFlusher();
PeriodicTask::startRunningPeriodicTasks();
// Set up the periodic runner for background job execution
auto runner = makePeriodicRunner(serviceContext);
runner->startup();
serviceContext->setPeriodicRunner(std::move(runner));
SessionKiller::set(serviceContext,
std::make_shared<SessionKiller>(serviceContext, killSessionsLocal));
// Start up a background task to periodically check for and kill expired transactions.
// Only do this on storage engines supporting snapshot reads, which hold resources we wish to
// release periodically in order to avoid storage cache pressure build up.
if (storageEngine->supportsReadConcernSnapshot()) {
startPeriodicThreadToAbortExpiredTransactions(serviceContext);
}
// Set up the logical session cache
LogicalSessionCacheServer kind = LogicalSessionCacheServer::kStandalone;
if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
kind = LogicalSessionCacheServer::kSharded;
} else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
kind = LogicalSessionCacheServer::kConfigServer;
} else if (replSettings.usingReplSets()) {
kind = LogicalSessionCacheServer::kReplicaSet;
}
auto sessionCache = makeLogicalSessionCacheD(kind);
LogicalSessionCache::set(serviceContext, std::move(sessionCache));
// MessageServer::run will return when exit code closes its socket and we don't need the
// operation context anymore
startupOpCtx.reset();
auto start = serviceContext->getServiceExecutor()->start();
if (!start.isOK()) {
error() << "Failed to start the service executor: " << start;
return EXIT_NET_ERROR;
}
if (!storageGlobalParams.repair) {
start = serviceContext->getTransportLayer()->start();
if (!start.isOK()) {
error() << "Failed to start the listener: " << start.toString();
return EXIT_NET_ERROR;
}
}
serviceContext->notifyStartupComplete();
#ifndef _WIN32
mongo::signalForkSuccess();
#else
if (ntservice::shouldStartService()) {
ntservice::reportStatus(SERVICE_RUNNING);
log() << "Service running";
}
#endif
if (MONGO_FAIL_POINT(shutdownAtStartup)) {
log() << "starting clean exit via failpoint";
exitCleanly(EXIT_CLEAN);
}
MONGO_IDLE_THREAD_BLOCK;
return waitForShutdown();
}
ExitCode initAndListen(int listenPort) {
try {
return _initAndListen(listenPort);
} catch (DBException& e) {
log() << "exception in initAndListen: " << e.toString() << ", terminating";
return EXIT_UNCAUGHT;
} catch (std::exception& e) {
log() << "exception in initAndListen std::exception: " << e.what() << ", terminating";
return EXIT_UNCAUGHT;
} catch (int& n) {
log() << "exception in initAndListen int: " << n << ", terminating";
return EXIT_UNCAUGHT;
} catch (...) {
log() << "exception in initAndListen, terminating";
return EXIT_UNCAUGHT;
}
}
#if defined(_WIN32)
ExitCode initService() {
return initAndListen(serverGlobalParams.port);
}
#endif
MONGO_INITIALIZER_GENERAL(ForkServer, ("EndStartupOptionHandling"), ("default"))
(InitializerContext* context) {
mongo::forkServerOrDie();
return Status::OK();
}
/*
* This function should contain the startup "actions" that we take based on the startup config.
* It is intended to separate the actions from "storage" and "validation" of our startup
* configuration.
*/
void startupConfigActions(const std::vector<std::string>& args) {
// The "command" option is deprecated. For backward compatibility, still support the "run"
// and "dbppath" command. The "run" command is the same as just running mongod, so just
// falls through.
if (moe::startupOptionsParsed.count("command")) {
const auto command = moe::startupOptionsParsed["command"].as<std::vector<std::string>>();
if (command[0].compare("dbpath") == 0) {
std::cout << storageGlobalParams.dbpath << endl;
quickExit(EXIT_SUCCESS);
}
if (command[0].compare("run") != 0) {
std::cout << "Invalid command: " << command[0] << endl;
printMongodHelp(moe::startupOptions);
quickExit(EXIT_FAILURE);
}
if (command.size() > 1) {
std::cout << "Too many parameters to 'run' command" << endl;
printMongodHelp(moe::startupOptions);
quickExit(EXIT_FAILURE);
}
}
#ifdef _WIN32
ntservice::configureService(initService,
moe::startupOptionsParsed,
defaultServiceStrings,
std::vector<std::string>(),
args);
#endif // _WIN32
#ifdef __linux__
if (moe::startupOptionsParsed.count("shutdown") &&
moe::startupOptionsParsed["shutdown"].as<bool>() == true) {
bool failed = false;
std::string name =
(boost::filesystem::path(storageGlobalParams.dbpath) / "mongod.lock").string();
if (!boost::filesystem::exists(name) || boost::filesystem::file_size(name) == 0)
failed = true;
pid_t pid;
std::string procPath;
if (!failed) {
try {
std::ifstream f(name.c_str());
f >> pid;
procPath = (str::stream() << "/proc/" << pid);
if (!boost::filesystem::exists(procPath))
failed = true;
} catch (const std::exception& e) {
std::cerr << "Error reading pid from lock file [" << name << "]: " << e.what()
<< endl;
failed = true;
}
}
if (failed) {
std::cerr << "There doesn't seem to be a server running with dbpath: "
<< storageGlobalParams.dbpath << std::endl;
quickExit(EXIT_FAILURE);
}
std::cout << "killing process with pid: " << pid << endl;
int ret = kill(pid, SIGTERM);
if (ret) {
int e = errno;
std::cerr << "failed to kill process: " << errnoWithDescription(e) << endl;
quickExit(EXIT_FAILURE);
}
while (boost::filesystem::exists(procPath)) {
sleepsecs(1);
}
quickExit(EXIT_SUCCESS);
}
#endif
}
auto makeReplicationExecutor(ServiceContext* serviceContext) {
ThreadPool::Options tpOptions;
tpOptions.poolName = "replexec";
tpOptions.maxThreads = 50;
tpOptions.onCreateThread = [](const std::string& threadName) {
Client::initThread(threadName.c_str());
};
auto hookList = stdx::make_unique<rpc::EgressMetadataHookList>();
hookList->addHook(stdx::make_unique<rpc::LogicalTimeMetadataHook>(serviceContext));
return stdx::make_unique<executor::ThreadPoolTaskExecutor>(
stdx::make_unique<ThreadPool>(tpOptions),
executor::makeNetworkInterface("Replication", nullptr, std::move(hookList)));
}
void setUpReplication(ServiceContext* serviceContext) {
repl::StorageInterface::set(serviceContext, stdx::make_unique<repl::StorageInterfaceImpl>());
auto storageInterface = repl::StorageInterface::get(serviceContext);
auto consistencyMarkers =
stdx::make_unique<repl::ReplicationConsistencyMarkersImpl>(storageInterface);
auto recovery = stdx::make_unique<repl::ReplicationRecoveryImpl>(storageInterface,
consistencyMarkers.get());
repl::ReplicationProcess::set(
serviceContext,
stdx::make_unique<repl::ReplicationProcess>(
storageInterface, std::move(consistencyMarkers), std::move(recovery)));
auto replicationProcess = repl::ReplicationProcess::get(serviceContext);
repl::DropPendingCollectionReaper::set(
serviceContext, stdx::make_unique<repl::DropPendingCollectionReaper>(storageInterface));
auto dropPendingCollectionReaper = repl::DropPendingCollectionReaper::get(serviceContext);
repl::TopologyCoordinator::Options topoCoordOptions;
topoCoordOptions.maxSyncSourceLagSecs = Seconds(repl::maxSyncSourceLagSecs);
topoCoordOptions.clusterRole = serverGlobalParams.clusterRole;
auto logicalClock = stdx::make_unique<LogicalClock>(serviceContext);
LogicalClock::set(serviceContext, std::move(logicalClock));
auto replCoord = stdx::make_unique<repl::ReplicationCoordinatorImpl>(
serviceContext,
getGlobalReplSettings(),
stdx::make_unique<repl::ReplicationCoordinatorExternalStateImpl>(
serviceContext, dropPendingCollectionReaper, storageInterface, replicationProcess),
makeReplicationExecutor(serviceContext),
stdx::make_unique<repl::TopologyCoordinator>(topoCoordOptions),
replicationProcess,
storageInterface,
static_cast<int64_t>(curTimeMillis64()));
repl::ReplicationCoordinator::set(serviceContext, std::move(replCoord));
repl::setOplogCollectionName(serviceContext);
}
#ifdef MONGO_CONFIG_SSL
MONGO_INITIALIZER_GENERAL(setSSLManagerType, MONGO_NO_PREREQUISITES, ("SSLManager"))
(InitializerContext* context) {
isSSLServer = true;
return Status::OK();
}
#endif
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
// NOTE: This function may be called at any time after registerShutdownTask is called below. It
// must not depend on the prior execution of mongo initializers or the existence of threads.
void shutdownTask() {
Client::initThreadIfNotAlready();
auto const client = Client::getCurrent();
auto const serviceContext = client->getServiceContext();
// Shutdown the TransportLayer so that new connections aren't accepted
if (auto tl = serviceContext->getTransportLayer()) {
log(LogComponent::kNetwork) << "shutdown: going to close listening sockets...";
tl->shutdown();
}
// Shut down the global dbclient pool so callers stop waiting for connections.
globalConnPool.shutdown();
if (serviceContext->getStorageEngine()) {
ServiceContext::UniqueOperationContext uniqueOpCtx;
OperationContext* opCtx = client->getOperationContext();
if (!opCtx) {
uniqueOpCtx = client->makeOperationContext();
opCtx = uniqueOpCtx.get();
}
// This can wait a long time while we drain the secondary's apply queue, especially if it
// is building an index.
repl::ReplicationCoordinator::get(serviceContext)->shutdown(opCtx);
ShardingInitializationMongoD::get(serviceContext)->shutDown(opCtx);
// Destroy all stashed transaction resources, in order to release locks.
SessionKiller::Matcher matcherAllSessions(
KillAllSessionsByPatternSet{makeKillAllSessionsByPattern(opCtx)});
killSessionsLocalKillTransactions(opCtx, matcherAllSessions);
}
serviceContext->setKillAllOperations();
// Shut down the background periodic task runner
if (auto runner = serviceContext->getPeriodicRunner()) {
runner->shutdown();
}
ReplicaSetMonitor::shutdown();
if (auto sr = Grid::get(serviceContext)->shardRegistry()) {
sr->shutdown();
}
// Validator shutdown must be called after setKillAllOperations is called. Otherwise, this can
// deadlock.
if (auto validator = LogicalTimeValidator::get(serviceContext)) {
validator->shutDown();
}
#if __has_feature(address_sanitizer)
// When running under address sanitizer, we get false positive leaks due to disorder around
// the lifecycle of a connection and request. When we are running under ASAN, we try a lot
// harder to dry up the server from active connections before going on to really shut down.
// Shutdown the Service Entry Point and its sessions and give it a grace period to complete.
if (auto sep = serviceContext->getServiceEntryPoint()) {
if (!sep->shutdown(Seconds(10))) {
log(LogComponent::kNetwork)
<< "Service entry point failed to shutdown within timelimit.";
}
}
// Shutdown and wait for the service executor to exit
if (auto svcExec = serviceContext->getServiceExecutor()) {
Status status = svcExec->shutdown(Seconds(5));
if (!status.isOK()) {
log(LogComponent::kNetwork) << "Service executor failed to shutdown within timelimit: "
<< status.reason();
}
}
#endif
stopFreeMonitoring();
// Shutdown Full-Time Data Capture
stopMongoDFTDC();
HealthLog::get(serviceContext).shutdown();
// We should always be able to acquire the global lock at shutdown.
//
// TODO: This call chain uses the locker directly, because we do not want to start an
// operation context, which also instantiates a recovery unit. Also, using the
// lockGlobalBegin/lockGlobalComplete sequence, we avoid taking the flush lock.
//
// For a Windows service, dbexit does not call exit(), so we must leak the lock outside
// of this function to prevent any operations from running that need a lock.
//
DefaultLockerImpl* globalLocker = new DefaultLockerImpl();
LockResult result = globalLocker->lockGlobalBegin(MODE_X, Date_t::max());
if (result == LOCK_WAITING) {
result = globalLocker->lockGlobalComplete(Date_t::max());
}
invariant(LOCK_OK == result);
// Global storage engine may not be started in all cases before we exit
if (serviceContext->getStorageEngine()) {
shutdownGlobalStorageEngineCleanly(serviceContext);
}
// We drop the scope cache because leak sanitizer can't see across the
// thread we use for proxying MozJS requests. Dropping the cache cleans up
// the memory and makes leak sanitizer happy.
ScriptEngine::dropScopeCache();
log(LogComponent::kControl) << "now exiting";
audit::logShutdown(client);
}
} // namespace
int mongoDbMain(int argc, char* argv[], char** envp) {
registerShutdownTask(shutdownTask);
setupSignalHandlers();
srand(static_cast<unsigned>(curTimeMicros64()));
Status status = mongo::runGlobalInitializers(argc, argv, envp);
if (!status.isOK()) {
severe(LogComponent::kControl) << "Failed global initialization: " << status;
quickExit(EXIT_FAILURE);
}
try {
setGlobalServiceContext(ServiceContext::make());
} catch (...) {
auto cause = exceptionToStatus();
severe(LogComponent::kControl) << "Failed to create service context: " << redact(cause);
quickExit(EXIT_FAILURE);
}
auto service = getGlobalServiceContext();
setUpReplication(service);
service->setServiceEntryPoint(std::make_unique<ServiceEntryPointMongod>(service));
ErrorExtraInfo::invariantHaveAllParsers();
startupConfigActions(std::vector<std::string>(argv, argv + argc));
cmdline_utils::censorArgvArray(argc, argv);
if (!initializeServerGlobalState())
quickExit(EXIT_FAILURE);
// Per SERVER-7434, startSignalProcessingThread() must run after any forks
// (initializeServerGlobalState()) and before creation of any other threads.
startSignalProcessingThread();
#if defined(_WIN32)
if (ntservice::shouldStartService()) {
ntservice::startService();
// exits directly and so never reaches here either.
}
#endif
StartupTest::runTests();
ExitCode exitCode = initAndListen(serverGlobalParams.port);
exitCleanly(exitCode);
return 0;
}
} // namespace mongo
|
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#define WATCHERS 4
SYNCHRONIZATION_BARRIER g_stBarrier = {};
HANDLE g_hMovieFinished = nullptr;
// Watchers gonna watch.
DWORD CALLBACK MovieWatcherThread(void* p)
{
int id = PtrToInt(p);
// Build a string that we use to prefix our messages.
char tag[WATCHERS + 1];
for (int i = 0; i < WATCHERS; i++)
{
tag[i] = (i == id) ? (char)('1' + i) : ' ';
}
tag[WATCHERS] = 0;
printf("%s Sitting down\n", tag);
if (EnterSynchronizationBarrier(&g_stBarrier, 0))
{
// We are the one who should start the movie.
printf("%s Starting the movie\n", tag);
// For demonstration purposes, the movie is only one second long.
LARGE_INTEGER dueTime;
dueTime.QuadPart = -1000000LL;
SetWaitableTimer(g_hMovieFinished, &dueTime, 0,
nullptr, nullptr, FALSE);
}
// Watch the movie until it ends.
printf("%s Enjoying the movie\n", tag);
WaitForSingleObject(g_hMovieFinished, INFINITE);
// Now leave the room.
printf("%s Leaving the room\n", tag);
if (EnterSynchronizationBarrier(&g_stBarrier, 0))
{
// We are the one who should lock the door.
printf("%s Locking the door\n", tag);
}
printf("%s Saying good-bye and going home\n", tag);
return 0;
}
int __cdecl main(int, char**)
{
g_hMovieFinished = CreateWaitableTimer(nullptr, TRUE, nullptr);
InitializeSynchronizationBarrier(&g_stBarrier, WATCHERS, -1);
HANDLE threads[WATCHERS] = {};
for (int i = 0; i < WATCHERS; i++)
{
DWORD threadId;
threads[i] = CreateThread(nullptr, 0, MovieWatcherThread,
IntToPtr(i), 0, &threadId);
}
// Wait for the demonstration to complete.
WaitForMultipleObjects(WATCHERS, threads, TRUE, INFINITE);
CloseHandle(g_hMovieFinished);
DeleteSynchronizationBarrier(&g_stBarrier);
return 0;
}
|
#include "sai_vs.h"
service_method_table_t g_services;
bool g_api_initialized = false;
std::recursive_mutex g_recursive_mutex;
sai_status_t sai_api_initialize(
_In_ uint64_t flags,
_In_ const service_method_table_t* services)
{
std::lock_guard<std::recursive_mutex> lock(g_recursive_mutex);
SWSS_LOG_ENTER();
if ((NULL == services) || (NULL == services->profile_get_next_value) || (NULL == services->profile_get_value))
{
SWSS_LOG_ERROR("Invalid services handle passed to SAI API initialize");
return SAI_STATUS_INVALID_PARAMETER;
}
memcpy(&g_services, services, sizeof(g_services));
if (0 != flags)
{
SWSS_LOG_ERROR("Invalid flags passed to SAI API initialize");
return SAI_STATUS_INVALID_PARAMETER;
}
g_api_initialized = true;
return SAI_STATUS_SUCCESS;
}
sai_status_t sai_log_set(
_In_ sai_api_t sai_api_id,
_In_ sai_log_level_t log_level)
{
std::lock_guard<std::recursive_mutex> lock(g_recursive_mutex);
SWSS_LOG_ENTER();
return SAI_STATUS_SUCCESS;
}
sai_status_t sai_api_query(
_In_ sai_api_t sai_api_id,
_Out_ void** api_method_table)
{
std::lock_guard<std::recursive_mutex> lock(g_recursive_mutex);
SWSS_LOG_ENTER();
if (NULL == api_method_table)
{
SWSS_LOG_ERROR("NULL method table passed to SAI API initialize");
return SAI_STATUS_INVALID_PARAMETER;
}
if (!g_api_initialized)
{
SWSS_LOG_ERROR("SAI API not initialized before calling API query");
return SAI_STATUS_UNINITIALIZED;
}
switch (sai_api_id) {
case SAI_API_BUFFERS:
*(const sai_buffer_api_t**)api_method_table = &vs_buffer_api;
return SAI_STATUS_SUCCESS;
case SAI_API_HASH:
*(const sai_hash_api_t**)api_method_table = &vs_hash_api;
return SAI_STATUS_SUCCESS;
case SAI_API_SWITCH:
*(const sai_switch_api_t**)api_method_table = &vs_switch_api;
return SAI_STATUS_SUCCESS;
case SAI_API_PORT:
*(const sai_port_api_t**)api_method_table = &vs_port_api;
return SAI_STATUS_SUCCESS;
case SAI_API_FDB:
*(const sai_fdb_api_t**)api_method_table = &vs_fdb_api;
return SAI_STATUS_SUCCESS;
case SAI_API_VLAN:
*(const sai_vlan_api_t**)api_method_table = &vs_vlan_api;
return SAI_STATUS_SUCCESS;
case SAI_API_WRED:
*(const sai_wred_api_t**)api_method_table = &vs_wred_api;
return SAI_STATUS_SUCCESS;
case SAI_API_VIRTUAL_ROUTER:
*(const sai_virtual_router_api_t**)api_method_table = &vs_router_api;
return SAI_STATUS_SUCCESS;
case SAI_API_ROUTE:
*(const sai_route_api_t**)api_method_table = &vs_route_api;
return SAI_STATUS_SUCCESS;
case SAI_API_NEXT_HOP:
*(const sai_next_hop_api_t**)api_method_table = &vs_next_hop_api;
return SAI_STATUS_SUCCESS;
case SAI_API_NEXT_HOP_GROUP:
*(const sai_next_hop_group_api_t**)api_method_table = &vs_next_hop_group_api;
return SAI_STATUS_SUCCESS;
case SAI_API_ROUTER_INTERFACE:
*(const sai_router_interface_api_t**)api_method_table = &vs_router_interface_api;
return SAI_STATUS_SUCCESS;
case SAI_API_NEIGHBOR:
*(const sai_neighbor_api_t**)api_method_table = &vs_neighbor_api;
return SAI_STATUS_SUCCESS;
case SAI_API_ACL:
*(const sai_acl_api_t**)api_method_table = &vs_acl_api;
return SAI_STATUS_SUCCESS;
case SAI_API_HOST_INTERFACE:
*(const sai_hostif_api_t**)api_method_table = &vs_host_interface_api;
return SAI_STATUS_SUCCESS;
case SAI_API_POLICER:
*(const sai_policer_api_t**)api_method_table = &vs_policer_api;
return SAI_STATUS_SUCCESS;
case SAI_API_QOS_MAPS:
*(const sai_qos_map_api_t**)api_method_table = &vs_qos_map_api;
return SAI_STATUS_SUCCESS;
case SAI_API_QUEUE:
*(const sai_queue_api_t**)api_method_table = &vs_queue_api;
return SAI_STATUS_SUCCESS;
case SAI_API_SCHEDULER:
*(const sai_scheduler_api_t**)api_method_table = &vs_scheduler_api;
return SAI_STATUS_SUCCESS;
case SAI_API_SCHEDULER_GROUP:
*(const sai_scheduler_group_api_t**)api_method_table = &vs_scheduler_group_api;
return SAI_STATUS_SUCCESS;
case SAI_API_MIRROR:
*(const sai_mirror_api_t**)api_method_table = &vs_mirror_api;
return SAI_STATUS_SUCCESS;
case SAI_API_UDF:
*(const sai_udf_api_t**)api_method_table = &vs_udf_api;
return SAI_STATUS_SUCCESS;
case SAI_API_SAMPLEPACKET:
*(const sai_samplepacket_api_t**)api_method_table = &vs_samplepacket_api;
return SAI_STATUS_SUCCESS;
case SAI_API_STP:
*(const sai_stp_api_t**)api_method_table = &vs_stp_api;
return SAI_STATUS_NOT_IMPLEMENTED;
case SAI_API_LAG:
*(const sai_lag_api_t**)api_method_table = &vs_lag_api;
return SAI_STATUS_SUCCESS;
case SAI_API_TUNNEL:
*(const sai_tunnel_api_t**)api_method_table = &vs_tunnel_api;
return SAI_STATUS_SUCCESS;
default:
SWSS_LOG_ERROR("Invalid API type %d", sai_api_id);
return SAI_STATUS_INVALID_PARAMETER;
}
}
sai_status_t sai_api_uninitialize(
void)
{
std::lock_guard<std::recursive_mutex> lock(g_recursive_mutex);
SWSS_LOG_ENTER();
g_api_initialized = false;
return SAI_STATUS_SUCCESS;
}
|
/*
* simplify_expr.cpp --- AST expression simplifications.
*
* (c) Seq project. All rights reserved.
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
*/
#include <deque>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
#include "parser/ast.h"
#include "parser/cache.h"
#include "parser/common.h"
#include "parser/peg/peg.h"
#include "parser/visitors/simplify/simplify.h"
using fmt::format;
namespace seq {
namespace ast {
ExprPtr SimplifyVisitor::transform(const ExprPtr &expr) {
return transform(expr, false, true);
}
ExprPtr SimplifyVisitor::transform(const ExprPtr &expr, bool allowTypes,
bool allowAssign) {
if (!expr)
return nullptr;
SimplifyVisitor v(ctx, preamble);
v.setSrcInfo(expr->getSrcInfo());
auto oldAssign = ctx->canAssign;
ctx->canAssign = allowAssign;
const_cast<Expr *>(expr.get())->accept(v);
ctx->canAssign = oldAssign;
if (!allowTypes && v.resultExpr && v.resultExpr->isType())
error("unexpected type expression");
return v.resultExpr;
}
ExprPtr SimplifyVisitor::transformType(const ExprPtr &expr, bool allowTypeOf) {
auto oldTypeOf = ctx->allowTypeOf;
ctx->allowTypeOf = allowTypeOf;
auto e = transform(expr, true);
ctx->allowTypeOf = oldTypeOf;
if (e && !e->isType())
error("expected type expression");
return e;
}
void SimplifyVisitor::defaultVisit(Expr *e) { resultExpr = e->clone(); }
/**************************************************************************************/
void SimplifyVisitor::visit(NoneExpr *expr) {
resultExpr = transform(N<CallExpr>(N<IdExpr>(TYPE_OPTIONAL)));
}
void SimplifyVisitor::visit(IntExpr *expr) {
resultExpr = transformInt(expr->value, expr->suffix);
}
void SimplifyVisitor::visit(FloatExpr *expr) {
resultExpr = transformFloat(expr->value, expr->suffix);
}
void SimplifyVisitor::visit(StringExpr *expr) {
vector<ExprPtr> exprs;
string concat;
int realStrings = 0;
for (auto &p : expr->strings) {
if (p.second == "f" || p.second == "F") {
/// F-strings
exprs.push_back(transformFString(p.first));
} else if (!p.second.empty()) {
/// Custom-prefix strings
exprs.push_back(
transform(N<CallExpr>(N<DotExpr>("str", format("__prefix_{}__", p.second)),
N<StringExpr>(p.first), N<IntExpr>(p.first.size()))));
} else {
exprs.push_back(N<StringExpr>(p.first));
concat += p.first;
realStrings++;
}
}
if (realStrings == expr->strings.size())
resultExpr = N<StringExpr>(concat);
else if (exprs.size() == 1)
resultExpr = exprs[0];
else
resultExpr = transform(N<CallExpr>(N<DotExpr>("str", "cat"), exprs));
}
void SimplifyVisitor::visit(IdExpr *expr) {
if (ctx->substitutions) {
auto it = ctx->substitutions->find(expr->value);
if (it != ctx->substitutions->end()) {
resultExpr = transform(it->second, true);
return;
}
}
if (in(set<string>{"type", "TypeVar", "Callable"}, expr->value)) {
resultExpr = N<IdExpr>(expr->value == "TypeVar" ? "type" : expr->value);
resultExpr->markType();
return;
}
auto val = ctx->find(expr->value);
if (!val)
error("identifier '{}' not found", expr->value);
auto canonicalName = val->canonicalName;
// If we are accessing an outer non-global variable, raise an error unless
// we are capturing variables (in that case capture it).
bool captured = false;
auto newName = canonicalName;
if (val->isVar()) {
if (ctx->getBase() != val->getBase() && !val->isGlobal()) {
if (!ctx->captures.empty()) {
captured = true;
if (!in(ctx->captures.back(), canonicalName)) {
ctx->captures.back()[canonicalName] = newName =
ctx->generateCanonicalName(canonicalName);
ctx->cache->reverseIdentifierLookup[newName] = newName;
}
newName = ctx->captures.back()[canonicalName];
} else {
error("cannot access non-global variable '{}'",
ctx->cache->reverseIdentifierLookup[expr->value]);
}
}
}
// Replace the variable with its canonical name. Do not canonize captured
// variables (they will be later passed as argument names).
resultExpr = N<IdExpr>(newName);
// Flag the expression as a type expression if it points to a class name or a generic.
if (val->isType())
resultExpr->markType();
// The only variables coming from the enclosing base must be class generics.
seqassert(!val->isFunc() || val->getBase().empty(), "{} has invalid base ({})",
expr->value, val->getBase());
if (!val->getBase().empty() && ctx->getBase() != val->getBase()) {
// Assumption: only 2 bases are available (class -> function)
if (ctx->bases.size() == 2 && ctx->bases[0].isType() &&
ctx->bases[0].name == val->getBase()) {
ctx->bases.back().attributes |= FLAG_METHOD;
return;
}
}
// If that is not the case, we are probably having a class accessing its enclosing
// function variable (generic or other identifier). We do not like that!
if (!captured && ctx->getBase() != val->getBase() && !val->getBase().empty())
error("identifier '{}' not found (cannot access outer function identifiers)",
expr->value);
}
void SimplifyVisitor::visit(StarExpr *expr) {
error("cannot use star-expression here");
}
void SimplifyVisitor::visit(TupleExpr *expr) {
vector<ExprPtr> items;
for (auto &i : expr->items) {
if (auto es = i->getStar())
items.emplace_back(N<StarExpr>(transform(es->what)));
else
items.emplace_back(transform(i));
}
resultExpr = N<TupleExpr>(items);
}
void SimplifyVisitor::visit(ListExpr *expr) {
vector<StmtPtr> stmts;
ExprPtr var = N<IdExpr>(ctx->cache->getTemporaryVar("list"));
stmts.push_back(transform(N<AssignStmt>(
clone(var),
N<CallExpr>(N<IdExpr>("List"),
!expr->items.empty() ? N<IntExpr>(expr->items.size()) : nullptr),
nullptr, true)));
for (const auto &it : expr->items) {
if (auto star = it->getStar()) {
ExprPtr forVar = N<IdExpr>(ctx->cache->getTemporaryVar("it"));
stmts.push_back(transform(N<ForStmt>(
clone(forVar), star->what->clone(),
N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "append"), clone(forVar))))));
} else {
stmts.push_back(transform(
N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "append"), clone(it)))));
}
}
resultExpr = N<StmtExpr>(stmts, transform(var));
}
void SimplifyVisitor::visit(SetExpr *expr) {
vector<StmtPtr> stmts;
ExprPtr var = N<IdExpr>(ctx->cache->getTemporaryVar("set"));
stmts.push_back(transform(
N<AssignStmt>(clone(var), N<CallExpr>(N<IdExpr>("Set")), nullptr, true)));
for (auto &it : expr->items)
if (auto star = it->getStar()) {
ExprPtr forVar = N<IdExpr>(ctx->cache->getTemporaryVar("it"));
stmts.push_back(transform(N<ForStmt>(
clone(forVar), star->what->clone(),
N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "add"), clone(forVar))))));
} else {
stmts.push_back(transform(
N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "add"), clone(it)))));
}
resultExpr = N<StmtExpr>(stmts, transform(var));
}
void SimplifyVisitor::visit(DictExpr *expr) {
vector<StmtPtr> stmts;
ExprPtr var = N<IdExpr>(ctx->cache->getTemporaryVar("dict"));
stmts.push_back(transform(
N<AssignStmt>(clone(var), N<CallExpr>(N<IdExpr>("Dict")), nullptr, true)));
for (auto &it : expr->items)
if (auto star = CAST(it.value, KeywordStarExpr)) {
ExprPtr forVar = N<IdExpr>(ctx->cache->getTemporaryVar("it"));
stmts.push_back(transform(N<ForStmt>(
clone(forVar), N<CallExpr>(N<DotExpr>(star->what->clone(), "items")),
N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "__setitem__"),
N<IndexExpr>(clone(forVar), N<IntExpr>(0)),
N<IndexExpr>(clone(forVar), N<IntExpr>(1)))))));
} else {
stmts.push_back(transform(N<ExprStmt>(N<CallExpr>(
N<DotExpr>(clone(var), "__setitem__"), clone(it.key), clone(it.value)))));
}
resultExpr = N<StmtExpr>(stmts, transform(var));
}
void SimplifyVisitor::visit(GeneratorExpr *expr) {
SuiteStmt *prev;
vector<StmtPtr> stmts;
auto loops = clone_nop(expr->loops);
// List comprehension optimization: pass iter.__len__() if we only have a single for
// loop without any conditions.
string optimizeVar;
if (expr->kind == GeneratorExpr::ListGenerator && loops.size() == 1 &&
loops[0].conds.empty()) {
optimizeVar = ctx->cache->getTemporaryVar("iter");
stmts.push_back(
transform(N<AssignStmt>(N<IdExpr>(optimizeVar), loops[0].gen, nullptr, true)));
loops[0].gen = N<IdExpr>(optimizeVar);
}
auto suite = transformGeneratorBody(loops, prev);
ExprPtr var = N<IdExpr>(ctx->cache->getTemporaryVar("gen"));
if (expr->kind == GeneratorExpr::ListGenerator) {
vector<ExprPtr> args;
// Use special List.__init__(bool, T) constructor.
if (!optimizeVar.empty())
args = {N<BoolExpr>(true), N<IdExpr>(optimizeVar)};
stmts.push_back(transform(N<AssignStmt>(
clone(var), N<CallExpr>(N<IdExpr>("List"), args), nullptr, true)));
prev->stmts.push_back(
N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "append"), clone(expr->expr))));
stmts.push_back(transform(suite));
resultExpr = N<StmtExpr>(stmts, transform(var));
} else if (expr->kind == GeneratorExpr::SetGenerator) {
stmts.push_back(transform(
N<AssignStmt>(clone(var), N<CallExpr>(N<IdExpr>("Set")), nullptr, true)));
prev->stmts.push_back(
N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "add"), clone(expr->expr))));
stmts.push_back(transform(suite));
resultExpr = N<StmtExpr>(stmts, transform(var));
} else {
prev->stmts.push_back(N<YieldStmt>(clone(expr->expr)));
stmts.push_back(suite);
resultExpr = N<CallExpr>(N<DotExpr>(N<CallExpr>(makeAnonFn(stmts)), "__iter__"));
}
}
void SimplifyVisitor::visit(DictGeneratorExpr *expr) {
SuiteStmt *prev;
auto suite = transformGeneratorBody(expr->loops, prev);
vector<StmtPtr> stmts;
ExprPtr var = N<IdExpr>(ctx->cache->getTemporaryVar("gen"));
stmts.push_back(transform(
N<AssignStmt>(clone(var), N<CallExpr>(N<IdExpr>("Dict")), nullptr, true)));
prev->stmts.push_back(N<ExprStmt>(N<CallExpr>(N<DotExpr>(clone(var), "__setitem__"),
clone(expr->key), clone(expr->expr))));
stmts.push_back(transform(suite));
resultExpr = N<StmtExpr>(stmts, transform(var));
}
void SimplifyVisitor::visit(IfExpr *expr) {
auto cond = transform(expr->cond);
auto newExpr = N<IfExpr>(cond, transform(expr->ifexpr, false, /*allowAssign*/ false),
transform(expr->elsexpr, false, /*allowAssign*/ false));
resultExpr = newExpr;
}
void SimplifyVisitor::visit(UnaryExpr *expr) {
resultExpr = N<UnaryExpr>(expr->op, transform(expr->expr));
}
void SimplifyVisitor::visit(BinaryExpr *expr) {
auto lhs = (startswith(expr->op, "is") && expr->lexpr->getNone())
? clone(expr->lexpr)
: transform(expr->lexpr);
auto rhs = (startswith(expr->op, "is") && expr->rexpr->getNone())
? clone(expr->rexpr)
: transform(expr->rexpr, false,
/*allowAssign*/ expr->op != "&&" && expr->op != "||");
resultExpr = N<BinaryExpr>(lhs, expr->op, rhs, expr->inPlace);
}
void SimplifyVisitor::visit(ChainBinaryExpr *expr) {
seqassert(expr->exprs.size() >= 2, "not enough expressions in ChainBinaryExpr");
vector<ExprPtr> e;
string prev;
for (int i = 1; i < expr->exprs.size(); i++) {
auto l = prev.empty() ? clone(expr->exprs[i - 1].second) : N<IdExpr>(prev);
prev = ctx->generateCanonicalName("chain");
auto r =
(i + 1 == expr->exprs.size())
? clone(expr->exprs[i].second)
: N<StmtExpr>(N<AssignStmt>(N<IdExpr>(prev), clone(expr->exprs[i].second)),
N<IdExpr>(prev));
e.emplace_back(N<BinaryExpr>(l, expr->exprs[i].first, r));
}
int i = int(e.size()) - 1;
ExprPtr b = e[i];
for (i -= 1; i >= 0; i--)
b = N<BinaryExpr>(e[i], "&&", b);
resultExpr = transform(b);
}
void SimplifyVisitor::visit(PipeExpr *expr) {
vector<PipeExpr::Pipe> p;
for (auto &i : expr->items) {
auto e = clone(i.expr);
if (auto ec = const_cast<CallExpr *>(e->getCall())) {
for (auto &a : ec->args)
if (auto ee = const_cast<EllipsisExpr *>(a.value->getEllipsis()))
ee->isPipeArg = true;
}
p.push_back({i.op, transform(e)});
}
resultExpr = N<PipeExpr>(p);
}
void SimplifyVisitor::visit(IndexExpr *expr) {
ExprPtr e = nullptr;
auto index = expr->index->clone();
// First handle the tuple[] and function[] cases.
if (expr->expr->isId("tuple") || expr->expr->isId("Tuple")) {
auto t = index->getTuple();
e = N<IdExpr>(format(TYPE_TUPLE "{}", t ? t->items.size() : 1));
e->markType();
} else if (expr->expr->isId("function") || expr->expr->isId("Function") ||
expr->expr->isId("Callable")) {
auto t = const_cast<TupleExpr *>(index->getTuple());
if (!t || t->items.size() != 2 || !t->items[0]->getList())
error("invalid {} type declaration", expr->expr->getId()->value);
for (auto &i : const_cast<ListExpr *>(t->items[0]->getList())->items)
t->items.emplace_back(i);
t->items.erase(t->items.begin());
e = N<IdExpr>(
format(expr->expr->isId("Callable") ? TYPE_CALLABLE "{}" : TYPE_FUNCTION "{}",
t ? int(t->items.size()) - 1 : 0));
e->markType();
} else if (expr->expr->isId("Static")) {
if (!expr->index->isId("int") && !expr->index->isId("str"))
error("only static integers and strings are supported");
resultExpr = expr->clone();
resultExpr->markType();
return;
} else {
e = transform(expr->expr, true);
}
// IndexExpr[i1, ..., iN] is internally stored as IndexExpr[TupleExpr[i1, ..., iN]]
// for N > 1, so make sure to check that case.
vector<ExprPtr> it;
if (auto t = index->getTuple())
for (auto &i : t->items)
it.push_back(transform(i, true));
else
it.push_back(transform(index, true));
if (e->isType()) {
resultExpr = N<InstantiateExpr>(e, it);
resultExpr->markType();
} else {
resultExpr = N<IndexExpr>(e, it.size() == 1 ? it[0] : N<TupleExpr>(it));
}
}
void SimplifyVisitor::visit(CallExpr *expr) {
// Special calls
// 1. __ptr__(v)
if (expr->expr->isId("__ptr__")) {
if (expr->args.size() == 1 && expr->args[0].value->getId()) {
auto v = ctx->find(expr->args[0].value->getId()->value);
if (v && v->isVar()) {
resultExpr = N<PtrExpr>(transform(expr->args[0].value));
return;
}
}
error("__ptr__ only accepts a single argument (variable identifier)");
}
// 2. __array__[T](n)
if (expr->expr->getIndex() && expr->expr->getIndex()->expr->isId("__array__")) {
if (expr->args.size() != 1)
error("__array__ only accepts a single argument (size)");
resultExpr = N<StackAllocExpr>(transformType(expr->expr->getIndex()->index),
transform(expr->args[0].value));
return;
}
// 3. isinstance(v, T)
if (expr->expr->isId("isinstance")) {
if (expr->args.size() != 2 || !expr->args[0].name.empty() ||
!expr->args[1].name.empty())
error("isinstance only accepts two arguments");
auto lhs = transform(expr->args[0].value, true);
ExprPtr type;
if (expr->args[1].value->isId("Tuple") || expr->args[1].value->isId("tuple") ||
(lhs->isType() && expr->args[1].value->getNone()) ||
expr->args[1].value->isId("ByVal") || expr->args[1].value->isId("ByRef"))
type = expr->args[1].value->clone();
else
type = transformType(expr->args[1].value);
resultExpr = N<CallExpr>(clone(expr->expr), lhs, type);
return;
}
// 4. staticlen(v)
if (expr->expr->isId("staticlen")) {
if (expr->args.size() != 1)
error("staticlen only accepts a single arguments");
resultExpr = N<CallExpr>(clone(expr->expr), transform(expr->args[0].value));
return;
}
// 5. hasattr(v, "id")
if (expr->expr->isId("hasattr")) {
if (expr->args.size() < 2 || !expr->args[0].name.empty() ||
!expr->args[1].name.empty())
error("hasattr accepts at least two arguments");
auto s = transform(expr->args[1].value);
auto arg = N<CallExpr>(N<IdExpr>("type"), expr->args[0].value);
vector<ExprPtr> args{transformType(arg), transform(s)};
for (int i = 2; i < expr->args.size(); i++)
args.push_back(transformType(expr->args[i].value));
resultExpr = N<CallExpr>(clone(expr->expr), args);
return;
}
// 6. compile_error("msg")
if (expr->expr->isId("compile_error")) {
if (expr->args.size() != 1)
error("compile_error accepts a single argument");
auto s = transform(expr->args[0].value);
resultExpr = N<CallExpr>(clone(expr->expr), transform(s));
return;
}
// 7. tuple(i for i in j)
if (expr->expr->isId("tuple")) {
GeneratorExpr *g = nullptr;
if (expr->args.size() != 1 || !(g = CAST(expr->args[0].value, GeneratorExpr)) ||
g->kind != GeneratorExpr::Generator || g->loops.size() != 1 ||
!g->loops[0].conds.empty())
error("tuple only accepts a simple comprehension over a tuple");
ctx->addBlock();
auto var = clone(g->loops[0].vars);
auto ex = clone(g->expr);
if (auto i = var->getId()) {
ctx->add(SimplifyItem::Var, i->value, ctx->generateCanonicalName(i->value));
var = transform(var);
ex = transform(ex);
} else {
string varName = ctx->cache->getTemporaryVar("for");
ctx->add(SimplifyItem::Var, varName, varName);
var = N<IdExpr>(varName);
ex = N<StmtExpr>(
transform(N<AssignStmt>(clone(g->loops[0].vars), clone(var), nullptr, true)),
transform(ex));
}
vector<GeneratorBody> body;
body.push_back({var, transform(g->loops[0].gen), {}});
resultExpr = N<GeneratorExpr>(GeneratorExpr::Generator, ex, body);
ctx->popBlock();
return;
}
// 8. type(i)
if (expr->expr->isId("type")) {
if (expr->args.size() != 1 || !expr->args[0].name.empty())
error("type only accepts two arguments");
if (!ctx->allowTypeOf)
error("type() not allowed in definitions");
resultExpr = N<CallExpr>(clone(expr->expr), transform(expr->args[0].value, true));
resultExpr->markType();
return;
}
// 9. getattr(v, "id")
if (expr->expr->isId("getattr")) {
if (expr->args.size() != 2 || !expr->args[0].name.empty() ||
!expr->args[1].name.empty())
error("getattr accepts at least two arguments");
auto s = transform(expr->args[1].value);
vector<ExprPtr> args{transform(expr->args[0].value), transform(s)};
resultExpr = N<CallExpr>(clone(expr->expr), args);
return;
}
auto e = transform(expr->expr, true);
// 8. namedtuple
if (e->isId("std.collections.namedtuple")) {
if (expr->args.size() != 2 || !expr->args[0].value->getString() ||
!expr->args[1].value->getList())
error("invalid namedtuple arguments");
vector<Param> generics, args;
int ti = 1;
for (auto &i : expr->args[1].value->getList()->items)
if (auto s = i->getString()) {
generics.emplace_back(
Param{format("T{}", ti), N<IdExpr>("type"), nullptr, true});
args.emplace_back(
Param{s->getValue(), N<IdExpr>(format("T{}", ti++)), nullptr});
} else if (i->getTuple() && i->getTuple()->items.size() == 2 &&
i->getTuple()->items[0]->getString()) {
args.emplace_back(Param{i->getTuple()->items[0]->getString()->getValue(),
transformType(i->getTuple()->items[1]), nullptr});
} else {
error("invalid namedtuple arguments");
}
for (auto &g : generics)
args.push_back(g);
auto name = expr->args[0].value->getString()->getValue();
transform(N<ClassStmt>(name, args, nullptr, Attr({Attr::Tuple})));
auto i = N<IdExpr>(name);
resultExpr = transformType(i);
return;
}
// 9. partial
if (e->isId("std.functools.partial")) {
if (expr->args.size() < 1)
error("invalid namedtuple arguments");
vector<CallExpr::Arg> args = clone_nop(expr->args);
args.erase(args.begin());
args.push_back({"", N<EllipsisExpr>()});
resultExpr = transform(N<CallExpr>(clone(expr->args[0].value), args));
return;
}
vector<CallExpr::Arg> args;
bool namesStarted = false;
bool foundEllispis = false;
for (auto &i : expr->args) {
if (i.name.empty() && namesStarted &&
!(CAST(i.value, KeywordStarExpr) || i.value->getEllipsis()))
error("unnamed argument after a named argument");
if (!i.name.empty() && (i.value->getStar() || CAST(i.value, KeywordStarExpr)))
error("named star-expressions not allowed");
namesStarted |= !i.name.empty();
if (auto ee = i.value->getEllipsis()) {
if (foundEllispis ||
(!ee->isPipeArg && i.value.get() != expr->args.back().value.get()))
error("unexpected ellipsis expression");
foundEllispis = true;
args.push_back({i.name, clone(i.value)});
} else if (auto es = i.value->getStar())
args.push_back({i.name, N<StarExpr>(transform(es->what))});
else if (auto ek = CAST(i.value, KeywordStarExpr))
args.push_back({i.name, N<KeywordStarExpr>(transform(ek->what))});
else
args.push_back({i.name, transform(i.value, true)});
}
resultExpr = N<CallExpr>(e, args);
}
void SimplifyVisitor::visit(DotExpr *expr) {
/// First flatten the imports.
const Expr *e = expr;
std::deque<string> chain;
while (auto d = e->getDot()) {
chain.push_front(d->member);
e = d->expr.get();
}
if (auto d = e->getId()) {
chain.push_front(d->value);
/// Check if this is a import or a class access:
/// (import1.import2...).(class1.class2...)?.method?
int importEnd = 0, itemEnd = 0;
string importName, itemName;
shared_ptr<SimplifyItem> val = nullptr;
for (int i = int(chain.size()) - 1; i >= 0; i--) {
auto s = join(chain, "/", 0, i + 1);
val = ctx->find(s);
if (val && val->isImport()) {
importName = val->importPath;
importEnd = i + 1;
break;
}
}
// a.b.c is completely import name
if (importEnd == chain.size()) {
resultExpr = transform(N<IdExpr>(val->canonicalName));
return;
}
auto fctx = importName.empty() ? ctx : ctx->cache->imports[importName].ctx;
for (int i = int(chain.size()) - 1; i >= importEnd; i--) {
auto s = join(chain, ".", importEnd, i + 1);
val = fctx->find(s);
// Make sure that we access only global imported variables.
if (val && (importName.empty() || val->isGlobal())) {
itemName = val->canonicalName;
itemEnd = i + 1;
if (!importName.empty())
ctx->add(val->canonicalName, val);
break;
}
}
if (itemName.empty() && importName.empty())
error("identifier '{}' not found", chain[importEnd]);
if (itemName.empty())
error("identifier '{}' not found in {}", chain[importEnd], importName);
resultExpr = N<IdExpr>(itemName);
if (importName.empty())
resultExpr = transform(resultExpr, true);
if (val->isType() && itemEnd == chain.size())
resultExpr->markType();
for (int i = itemEnd; i < chain.size(); i++)
resultExpr = N<DotExpr>(resultExpr, chain[i]);
} else {
resultExpr = N<DotExpr>(transform(expr->expr, true), expr->member);
}
}
void SimplifyVisitor::visit(SliceExpr *expr) {
resultExpr = N<SliceExpr>(transform(expr->start), transform(expr->stop),
transform(expr->step));
}
void SimplifyVisitor::visit(EllipsisExpr *expr) {
error("unexpected ellipsis expression");
}
void SimplifyVisitor::visit(YieldExpr *expr) {
if (!ctx->inFunction())
error("expected function body");
defaultVisit(expr);
}
void SimplifyVisitor::visit(LambdaExpr *expr) {
resultExpr =
makeAnonFn(vector<StmtPtr>{N<ReturnStmt>(clone(expr->expr))}, expr->vars);
}
void SimplifyVisitor::visit(AssignExpr *expr) {
seqassert(expr->var->getId(), "only simple assignment expression are supported");
if (!ctx->canAssign)
error("assignment expression in a short-circuiting subexpression");
resultExpr = transform(
N<StmtExpr>(vector<StmtPtr>{N<AssignStmt>(clone(expr->var), clone(expr->expr))},
clone(expr->var)));
}
void SimplifyVisitor::visit(RangeExpr *expr) {
error("unexpected pattern range expression");
}
void SimplifyVisitor::visit(StmtExpr *expr) {
vector<StmtPtr> stmts;
for (auto &s : expr->stmts)
stmts.emplace_back(transform(s));
resultExpr = N<StmtExpr>(stmts, transform(expr->expr));
}
/**************************************************************************************/
ExprPtr SimplifyVisitor::transformInt(const string &value, const string &suffix) {
auto to_int = [](const string &s) {
if (startswith(s, "0b") || startswith(s, "0B"))
return std::stoull(s.substr(2), nullptr, 2);
return std::stoull(s, nullptr, 0);
};
try {
if (suffix.empty()) {
auto expr = N<IntExpr>(to_int(value));
return expr;
}
/// Unsigned numbers: use UInt[64] for that
if (suffix == "u")
return transform(N<CallExpr>(N<IndexExpr>(N<IdExpr>("UInt"), N<IntExpr>(64)),
N<IntExpr>(to_int(value))));
/// Fixed-precision numbers (uXXX and iXXX)
/// NOTE: you cannot use binary (0bXXX) format with those numbers.
/// TODO: implement non-string constructor for these cases.
if (suffix[0] == 'u' && isdigit(suffix.substr(1)))
return transform(N<CallExpr>(
N<IndexExpr>(N<IdExpr>("UInt"), N<IntExpr>(std::stoi(suffix.substr(1)))),
N<StringExpr>(value)));
if (suffix[0] == 'i' && isdigit(suffix.substr(1)))
return transform(N<CallExpr>(
N<IndexExpr>(N<IdExpr>("Int"), N<IntExpr>(std::stoi(suffix.substr(1)))),
N<StringExpr>(value)));
} catch (std::out_of_range &) {
error("integer {} out of range", value);
}
/// Custom suffix sfx: use int.__suffix_sfx__(str) call.
/// NOTE: you cannot neither use binary (0bXXX) format here.
return transform(N<CallExpr>(N<DotExpr>("int", format("__suffix_{}__", suffix)),
N<StringExpr>(value)));
}
ExprPtr SimplifyVisitor::transformFloat(const string &value, const string &suffix) {
try {
if (suffix.empty()) {
auto expr = N<FloatExpr>(std::stod(value));
return expr;
}
} catch (std::out_of_range &) {
error("float {} out of range", value);
}
/// Custom suffix sfx: use float.__suffix_sfx__(str) call.
return transform(N<CallExpr>(N<DotExpr>("float", format("__suffix_{}__", suffix)),
N<StringExpr>(value)));
}
ExprPtr SimplifyVisitor::transformFString(string value) {
vector<ExprPtr> items;
int braceCount = 0, braceStart = 0;
for (int i = 0; i < value.size(); i++) {
if (value[i] == '{') {
if (braceStart < i)
items.push_back(N<StringExpr>(value.substr(braceStart, i - braceStart)));
if (!braceCount)
braceStart = i + 1;
braceCount++;
} else if (value[i] == '}') {
braceCount--;
if (!braceCount) {
string code = value.substr(braceStart, i - braceStart);
auto offset = getSrcInfo();
offset.col += i;
if (!code.empty() && code.back() == '=') {
code = code.substr(0, code.size() - 1);
items.push_back(N<StringExpr>(format("{}=", code)));
}
items.push_back(
N<CallExpr>(N<IdExpr>("str"), parseExpr(ctx->cache, code, offset)));
}
braceStart = i + 1;
}
}
if (braceCount)
error("f-string braces are not balanced");
if (braceStart != value.size())
items.push_back(N<StringExpr>(value.substr(braceStart, value.size() - braceStart)));
return transform(N<CallExpr>(N<DotExpr>("str", "cat"), items));
}
StmtPtr SimplifyVisitor::transformGeneratorBody(const vector<GeneratorBody> &loops,
SuiteStmt *&prev) {
StmtPtr suite = N<SuiteStmt>(), newSuite = nullptr;
prev = (SuiteStmt *)suite.get();
for (auto &l : loops) {
newSuite = N<SuiteStmt>();
auto nextPrev = (SuiteStmt *)newSuite.get();
prev->stmts.push_back(N<ForStmt>(l.vars->clone(), l.gen->clone(), newSuite));
prev = nextPrev;
for (auto &cond : l.conds) {
newSuite = N<SuiteStmt>();
nextPrev = (SuiteStmt *)newSuite.get();
prev->stmts.push_back(N<IfStmt>(cond->clone(), newSuite));
prev = nextPrev;
}
}
return suite;
}
ExprPtr SimplifyVisitor::makeAnonFn(vector<StmtPtr> stmts,
const vector<string> &argNames) {
vector<Param> params;
string name = ctx->cache->getTemporaryVar("lambda");
for (auto &s : argNames)
params.emplace_back(Param{s, nullptr, nullptr});
auto s = transform(N<FunctionStmt>(name, nullptr, params, N<SuiteStmt>(move(stmts)),
Attr({Attr::Capture})));
if (s)
return N<StmtExpr>(s, transform(N<IdExpr>(name)));
return transform(N<IdExpr>(name));
}
} // namespace ast
} // namespace seq
|
/*-----------------------------------------------------------------------
Matt Marchant 2021
http://trederia.blogspot.com
crogine application - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#pragma once
#include "CircularBuffer.hpp"
#include <crogine/core/Clock.hpp>
#include <crogine/ecs/System.hpp>
#include <crogine/detail/glm/vec3.hpp>
#include <crogine/detail/glm/gtc/quaternion.hpp>
/*!
\brief Contains information required for a inperpolation to occur
*/
struct InterpolationPoint final
{
InterpolationPoint(glm::vec3 pos = glm::vec3(0.f), glm::quat rot = glm::quat(1.f,0.f,0.f,0.f), std::int32_t ts = 0)
: position(pos), rotation(rot), timestamp(ts){}
glm::vec3 position = glm::vec3(0.f);
glm::quat rotation = glm::quat(1.f, 0.f, 0.f, 0.f);
std::int32_t timestamp = 0;
};
/*!
\brief Interpolates position and rotation received from a server.
When receiving infrequent (say 100ms or so) position updates from
a remote server entities can have their position interpolated via
this component. The component, when coupled with an InterpolationSystem
will travel towards the given target position using the given timestamp
to linearly interpolate movement. This component is not limited to
networked entities, and can be used anywhere linear interpolation of
movement is desired, for example path finding.
Requires:
CircularBuffer.hpp
InterpolationSystem.hpp
InterpolationSystem.cpp
InterpolationComponent.cpp
*/
class InterpolationComponent final
{
public:
/*!
\brief Constructor
Interpolation components should be passed an interpolation
point containing the initial transform and server time of the
actor to prevent large lags between the default timestamp (0)
and the first server update
*/
explicit InterpolationComponent(InterpolationPoint = {});
/*!
\brief Sets the target position and timestamp.
The timestamp is used in conjunction with the previous timestamp
to decide how quickly motion should be integrated between positions.
The timestamp would usually be in server time, and arrive in the packet
data with the destination postion, in milliseconds.
\param pos Target destination
\param timestamp Time at which this position should be reached, relative
to the previous position.
*/
void setTarget(const InterpolationPoint&);
/*!
\brief Sets whether or not this component is enabled
*/
void setEnabled(bool);
/*!
\brief Returns whether or not this component is enabled
*/
bool getEnabled() const;
/*!
\brief Overrides the current position with the given position
*/
void resetPosition(glm::vec3);
/*!
\brief Overrides the rotation with the given rotation
*/
void resetRotation(glm::quat);
/*!
\brief Sets the timestamp at which this entity should be destroyed
*/
void setRemoved(std::int32_t timestamp) { m_removalTimestamp = timestamp; }
private:
bool m_enabled;
InterpolationPoint m_targetPoint;
InterpolationPoint m_previousPoint;
cro::Clock m_elapsedTimer;
std::int32_t m_timeDifference;
std::int32_t m_removalTimestamp;
CircularBuffer<InterpolationPoint, 16u> m_buffer;
bool m_started;
friend class InterpolationSystem;
void applyNextTarget();
};
/*!
\brief Uses the InterpolationComponent to linearly
interpolate a transform component between two points.
\see InterpolationComponent
*/
class InterpolationSystem : public cro::System
{
public:
explicit InterpolationSystem(cro::MessageBus&);
void process(float) override;
private:
};
|
#include <unordered_set>
#include <unordered_map>
#include "L1Trigger/L1THGCal/interface/be_algorithms/HGCalClusteringImpl.h"
#include "DataFormats/Common/interface/PtrVector.h"
#include "DataFormats/Common/interface/OrphanHandle.h"
//class constructor
HGCalClusteringImpl::HGCalClusteringImpl(const edm::ParameterSet & conf):
siliconSeedThreshold_(conf.getParameter<double>("seeding_threshold_silicon")),
siliconTriggerCellThreshold_(conf.getParameter<double>("clustering_threshold_silicon")),
scintillatorSeedThreshold_(conf.getParameter<double>("seeding_threshold_scintillator")),
scintillatorTriggerCellThreshold_(conf.getParameter<double>("clustering_threshold_scintillator")),
dr_(conf.getParameter<double>("dR_cluster")),
clusteringAlgorithmType_(conf.getParameter<string>("clusterType")),
calibSF_(conf.getParameter<double>("calibSF_cluster")),
layerWeights_(conf.getParameter< std::vector<double> >("layerWeights")),
applyLayerWeights_(conf.getParameter< bool >("applyLayerCalibration"))
{
edm::LogInfo("HGCalClusterParameters") << "C2d Clustering Algorithm selected : " << clusteringAlgorithmType_ ;
edm::LogInfo("HGCalClusterParameters") << "C2d silicon seeding Thr: " << siliconSeedThreshold_ ;
edm::LogInfo("HGCalClusterParameters") << "C2d silicon clustering Thr: " << siliconTriggerCellThreshold_ ;
edm::LogInfo("HGCalClusterParameters") << "C2d scintillator seeding Thr: " << scintillatorSeedThreshold_ ;
edm::LogInfo("HGCalClusterParameters") << "C2d scintillator clustering Thr: " << scintillatorTriggerCellThreshold_ ;
edm::LogInfo("HGCalClusterParameters") << "C2d global calibration factor: " << calibSF_;
}
/* dR-algorithms */
bool HGCalClusteringImpl::isPertinent( const l1t::HGCalTriggerCell & tc,
const l1t::HGCalCluster & clu,
double distXY ) const
{
HGCalDetId tcDetId( tc.detId() );
HGCalDetId cluDetId( clu.detId() );
if( (tcDetId.layer() != cluDetId.layer()) ||
(tcDetId.subdetId() != cluDetId.subdetId()) ||
(tcDetId.zside() != cluDetId.zside()) ){
return false;
}
if ( clu.distance((tc)) < distXY ){
return true;
}
return false;
}
void HGCalClusteringImpl::clusterizeDR( const std::vector<edm::Ptr<l1t::HGCalTriggerCell>> & triggerCellsPtrs,
l1t::HGCalClusterBxCollection & clusters
){
bool isSeed[triggerCellsPtrs.size()];
/* search for cluster seeds */
int itc(0);
for( std::vector<edm::Ptr<l1t::HGCalTriggerCell>>::const_iterator tc = triggerCellsPtrs.begin(); tc != triggerCellsPtrs.end(); ++tc,++itc ){
double seedThreshold = ((*tc)->subdetId()==HGCHEB ? scintillatorSeedThreshold_ : siliconSeedThreshold_);
isSeed[itc] = ( (*tc)->mipPt() > seedThreshold) ? true : false;
}
/* clustering the TCs */
std::vector<l1t::HGCalCluster> clustersTmp;
itc=0;
for( std::vector<edm::Ptr<l1t::HGCalTriggerCell>>::const_iterator tc = triggerCellsPtrs.begin(); tc != triggerCellsPtrs.end(); ++tc,++itc ){
double threshold = ((*tc)->subdetId()==HGCHEB ? scintillatorTriggerCellThreshold_ : siliconTriggerCellThreshold_);
if( (*tc)->mipPt() < threshold ){
continue;
}
/*
searching for TC near the center of the cluster
ToBeFixed: if a tc is not a seed, but could be potencially be part of a cluster generated by a late seed,
the tc will not be clusterized
*/
int iclu=0;
vector<int> tcPertinentClusters;
for( const auto& clu : clustersTmp){
if( this->isPertinent(**tc, clu, dr_) ){
tcPertinentClusters.push_back(iclu);
}
++iclu;
}
if( tcPertinentClusters.empty() && isSeed[itc] ){
clustersTmp.emplace_back( *tc );
}
else if ( !tcPertinentClusters.empty() ){
unsigned minDist(300);
unsigned targetClu(0);
for( int iclu : tcPertinentClusters){
double d = clustersTmp.at(iclu).distance(**tc);
if( d < minDist ){
minDist = d;
targetClu = iclu;
}
}
clustersTmp.at(targetClu).addConstituent( *tc );
}
}
/* store clusters in the persistent collection */
clusters.resize(0, clustersTmp.size());
for( unsigned i(0); i<clustersTmp.size(); ++i ){
calibratePt(clustersTmp.at(i));
clusters.set( 0, i, clustersTmp.at(i) );
}
}
/* NN-algorithms */
/* storing trigger cells into vector per layer and per endcap */
void HGCalClusteringImpl::triggerCellReshuffling( const std::vector<edm::Ptr<l1t::HGCalTriggerCell>> & triggerCellsPtrs,
std::array< std::vector<std::vector<edm::Ptr<l1t::HGCalTriggerCell>>>,kNSides_> & reshuffledTriggerCells
){
for( const auto& tc : triggerCellsPtrs ){
int endcap = tc->zside() == -1 ? 0 : 1 ;
HGCalDetId tcDetId( tc->detId() );
unsigned layer = triggerTools_.layerWithOffset(tc->detId());
reshuffledTriggerCells[endcap][layer-1].emplace_back(tc);
}
}
/* merge clusters that have common neighbors */
void HGCalClusteringImpl::mergeClusters( l1t::HGCalCluster & main_cluster,
const l1t::HGCalCluster & secondary_cluster ) const
{
const std::unordered_map<uint32_t, edm::Ptr<l1t::HGCalTriggerCell>>& pertinentTC = secondary_cluster.constituents();
for(const auto& id_tc : pertinentTC){
main_cluster.addConstituent(id_tc.second);
}
}
void HGCalClusteringImpl::NNKernel( const std::vector<edm::Ptr<l1t::HGCalTriggerCell>> & reshuffledTriggerCells,
l1t::HGCalClusterBxCollection & clusters,
const HGCalTriggerGeometryBase & triggerGeometry
){
/* declaring the clusters vector */
std::vector<l1t::HGCalCluster> clustersTmp;
// map TC id -> cluster index in clustersTmp
std::unordered_map<uint32_t, unsigned> cluNNmap;
/* loop over the trigger-cells */
for( const auto& tc_ptr : reshuffledTriggerCells ){
double threshold = (tc_ptr->subdetId()==HGCHEB ? scintillatorTriggerCellThreshold_ : siliconTriggerCellThreshold_);
if( tc_ptr->mipPt() < threshold ){
continue;
}
// Check if the neighbors of that TC are already included in a cluster
// If this is the case, add the TC to the first (arbitrary) neighbor cluster
// Otherwise create a new cluster
bool createNewC2d(true);
const auto neighbors = triggerGeometry.getNeighborsFromTriggerCell(tc_ptr->detId());
for( const auto neighbor : neighbors ){
auto tc_cluster_itr = cluNNmap.find(neighbor);
if(tc_cluster_itr!=cluNNmap.end()){
createNewC2d = false;
if( tc_cluster_itr->second < clustersTmp.size()){
clustersTmp.at(tc_cluster_itr->second).addConstituent(tc_ptr);
// map TC id to the existing cluster
cluNNmap.emplace(tc_ptr->detId(), tc_cluster_itr->second);
}
else{
throw cms::Exception("HGCTriggerUnexpected")
<< "Trying to access a non-existing cluster. But it should exist...\n";
}
break;
}
}
if(createNewC2d){
clustersTmp.emplace_back(tc_ptr);
clustersTmp.back().setValid(true);
// map TC id to the cluster index (size - 1)
cluNNmap.emplace(tc_ptr->detId(), clustersTmp.size()-1);
}
}
/* declaring the vector with possible clusters merged */
// Merge neighbor clusters together
for( auto& cluster1 : clustersTmp){
// If the cluster has been merged into another one, skip it
if( !cluster1.valid() ) continue;
// Fill a set containing all TC included in the clusters
// as well as all neighbor TC
std::unordered_set<uint32_t> cluTcSet;
for(const auto& tc_clu1 : cluster1.constituents()){
cluTcSet.insert( tc_clu1.second->detId() );
const auto neighbors = triggerGeometry.getNeighborsFromTriggerCell( tc_clu1.second->detId() );
for(const auto neighbor : neighbors){
cluTcSet.insert( neighbor );
}
}
for( auto& cluster2 : clustersTmp ){
// If the cluster has been merged into another one, skip it
if( cluster1.detId()==cluster2.detId() ) continue;
if( !cluster2.valid() ) continue;
// Check if the TC in clu2 are in clu1 or its neighbors
// If yes, merge the second cluster into the first one
for(const auto& tc_clu2 : cluster2.constituents()){
if( cluTcSet.find(tc_clu2.second->detId())!=cluTcSet.end() ){
mergeClusters( cluster1, cluster2 );
cluTcSet.insert( tc_clu2.second->detId() );
const auto neighbors = triggerGeometry.getNeighborsFromTriggerCell( tc_clu2.second->detId() );
for(const auto neighbor : neighbors){
cluTcSet.insert( neighbor );
}
cluster2.setValid(false);
break;
}
}
}
}
/* store clusters in the persistent collection */
// only if the cluster contain a TC above the seed threshold
for( auto& cluster : clustersTmp ){
if( !cluster.valid() ) continue;
bool saveInCollection(false);
for( const auto& id_tc : cluster.constituents() ){
/* threshold in transverse-mip */
double seedThreshold = (id_tc.second->subdetId()==HGCHEB ? scintillatorSeedThreshold_ : siliconSeedThreshold_);
if( id_tc.second->mipPt() > seedThreshold ){
saveInCollection = true;
break;
}
}
if(saveInCollection){
calibratePt(cluster);
clusters.push_back( 0, cluster );
}
}
}
void HGCalClusteringImpl::clusterizeNN( const std::vector<edm::Ptr<l1t::HGCalTriggerCell>> & triggerCellsPtrs,
l1t::HGCalClusterBxCollection & clusters,
const HGCalTriggerGeometryBase & triggerGeometry
){
std::array< std::vector< std::vector<edm::Ptr<l1t::HGCalTriggerCell>>>,kNSides_> reshuffledTriggerCells;
unsigned layers = triggerTools_.layers(ForwardSubdetector::ForwardEmpty);
for(unsigned side=0; side<kNSides_; side++)
{
reshuffledTriggerCells[side].resize(layers);
}
triggerCellReshuffling( triggerCellsPtrs, reshuffledTriggerCells );
for(unsigned iec=0; iec<kNSides_; ++iec){
for(unsigned il=0; il<layers; ++il){
NNKernel( reshuffledTriggerCells[iec][il], clusters, triggerGeometry );
}
}
}
/*** FW-algorithms ***/
void HGCalClusteringImpl::clusterizeDRNN( const std::vector<edm::Ptr<l1t::HGCalTriggerCell>> & triggerCellsPtrs,
l1t::HGCalClusterBxCollection & clusters,
const HGCalTriggerGeometryBase & triggerGeometry
){
bool isSeed[triggerCellsPtrs.size()];
std::vector<unsigned> seedPositions;
seedPositions.reserve( triggerCellsPtrs.size() );
/* search for cluster seeds */
int itc(0);
for( std::vector<edm::Ptr<l1t::HGCalTriggerCell>>::const_iterator tc = triggerCellsPtrs.begin(); tc != triggerCellsPtrs.end(); ++tc,++itc ){
double seedThreshold = ((*tc)->subdetId()==HGCHEB ? scintillatorSeedThreshold_ : siliconSeedThreshold_);
/* decide if is a seed, if yes store the position into of triggerCellsPtrs */
isSeed[itc] = ( (*tc)->mipPt() > seedThreshold) ? true : false;
if( isSeed[itc] ) {
seedPositions.push_back( itc );
/* remove tc from the seed vector if is a NN of an other seed*/
for( auto pos : seedPositions ){
if( ( (*tc)->position() - triggerCellsPtrs[pos]->position() ).mag() < dr_ ){
if( this->areTCneighbour( (*tc)->detId(), triggerCellsPtrs[pos]->detId(), triggerGeometry ) )
{
isSeed[itc] = false;
seedPositions.pop_back();
}
}
}
}
}
/* clustering the TCs */
std::vector<l1t::HGCalCluster> clustersTmp;
// every seed generates a cluster
for( auto pos : seedPositions ) {
clustersTmp.emplace_back( triggerCellsPtrs[pos] );
}
/* add the tc to the clusters */
itc=0;
for( std::vector<edm::Ptr<l1t::HGCalTriggerCell>>::const_iterator tc = triggerCellsPtrs.begin(); tc != triggerCellsPtrs.end(); ++tc,++itc ){
/* get the correct threshold for the different part of the detector */
double threshold = ((*tc)->subdetId()==HGCHEB ? scintillatorTriggerCellThreshold_ : siliconTriggerCellThreshold_);
/* continue if not passing the threshold */
if( (*tc)->mipPt() < threshold ) continue;
if( isSeed[itc] ) continue; //No sharing of seeds between clusters (TBC)
/* searching for TC near the centre of the cluster */
std::vector<unsigned> tcPertinentClusters;
unsigned iclu(0);
for ( const auto& clu : clustersTmp ) {
if( this->isPertinent(**tc, clu, dr_) ){
tcPertinentClusters.push_back( iclu );
}
++iclu;
}
if ( tcPertinentClusters.empty() ) {
continue;
}
else if( tcPertinentClusters.size() == 1 ) {
clustersTmp.at( tcPertinentClusters.at(0) ).addConstituent( *tc );
}
else {
/* calculate the fractions */
double totMipt = 0;
for( auto clu : tcPertinentClusters ){
totMipt += clustersTmp.at( clu ).seedMipPt();
}
for( auto clu : tcPertinentClusters ){
double seedMipt = clustersTmp.at( clu ).seedMipPt();
clustersTmp.at( clu ).addConstituent( *tc, true, seedMipt/totMipt );
}
}
}
/* store clusters in the persistent collection */
clusters.resize(0, clustersTmp.size());
for( unsigned i(0); i<clustersTmp.size(); ++i ){
this->removeUnconnectedTCinCluster( clustersTmp.at(i), triggerGeometry );
calibratePt( clustersTmp.at(i) );
clusters.set( 0, i, clustersTmp.at(i) );
}
}
bool HGCalClusteringImpl::areTCneighbour(uint32_t detIDa, uint32_t detIDb, const HGCalTriggerGeometryBase & triggerGeometry
){
const auto neighbors = triggerGeometry.getNeighborsFromTriggerCell( detIDa );
if( neighbors.find( detIDb ) != neighbors.end() ) return true;
return false;
}
void HGCalClusteringImpl::removeUnconnectedTCinCluster( l1t::HGCalCluster & cluster, const HGCalTriggerGeometryBase & triggerGeometry ) {
/* get the constituents and the centre of the seed tc (considered as the first of the constituents) */
const std::unordered_map<uint32_t, edm::Ptr<l1t::HGCalTriggerCell>>& constituents = cluster.constituents();
Basic3DVector<float> seedCentre( constituents.at(cluster.detId())->position() );
/* distances from the seed */
vector<pair<edm::Ptr<l1t::HGCalTriggerCell>,float>> distances;
for( const auto & id_tc : constituents )
{
Basic3DVector<float> tcCentre( id_tc.second->position() );
float distance = ( seedCentre - tcCentre ).mag();
distances.push_back( pair<edm::Ptr<l1t::HGCalTriggerCell>,float>( id_tc.second, distance ) );
}
/* sorting (needed in order to be sure that we are skipping any tc) */
/* FIXME: better sorting needed!!! */
std::sort( distances.begin(), distances.end(), distanceSorter );
/* checking if the tc is connected to the seed */
bool toRemove[constituents.size()];
toRemove[0] = false; // this is the seed
for( unsigned itc=1; itc<distances.size(); itc++ ){
/* get the tc under study */
toRemove[itc] = true;
const edm::Ptr<l1t::HGCalTriggerCell>& tcToStudy = distances[itc].first;
/* compare with the tc in the cluster */
for( unsigned itc_ref=0; itc_ref<itc; itc_ref++ ){
if( !toRemove[itc_ref] ) {
if( areTCneighbour( tcToStudy->detId(), distances.at( itc_ref ).first->detId(), triggerGeometry ) ) {
toRemove[itc] = false;
break;
}
}
}
}
/* remove the unconnected TCs */
for( unsigned i=0; i<distances.size(); i++){
if( toRemove[i] ) cluster.removeConstituent( distances.at( i ).first );
}
}
void HGCalClusteringImpl::calibratePt( l1t::HGCalCluster & cluster ){
double calibPt=0.;
if(applyLayerWeights_){
unsigned layerN = triggerTools_.layerWithOffset(cluster.detId());
if(layerWeights_.at(layerN)==0.){
throw cms::Exception("BadConfiguration")
<<"2D cluster energy forced to 0 by calibration coefficients.\n"
<<"The configuration should be changed. "
<<"Discarded layers should be defined in hgcalTriggerGeometryESProducer.TriggerGeometry.DisconnectedLayers and not with calibration coefficients = 0\n";
}
calibPt = layerWeights_.at(layerN) * cluster.mipPt();
}
else{
calibPt = cluster.pt() * calibSF_;
}
math::PtEtaPhiMLorentzVector calibP4( calibPt,
cluster.eta(),
cluster.phi(),
0. );
cluster.setP4( calibP4 );
}
|
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "storage/ob_block_sample_iterator.h"
namespace oceanbase {
using namespace common;
namespace storage {
ObBlockSampleIterator::ObBlockSampleIterator(const SampleInfo& sample_info)
: ObISampleIterator(sample_info),
scan_merge_(nullptr),
block_num_(0),
row_cnt_from_cur_block_(0),
has_open_block_(false),
table_handle_(),
access_ctx_(nullptr)
{}
ObBlockSampleIterator::~ObBlockSampleIterator()
{}
int ObBlockSampleIterator::open(ObMultipleScanMerge& scan_merge, ObTableAccessContext& access_ctx,
const ObExtStoreRange& range, const ObGetTableParam& get_table_param, const bool is_reverse_scan)
{
int ret = OB_SUCCESS;
ObTableHandle table_handle;
ObSSTable* sstable = NULL;
if (OB_UNLIKELY(NULL == get_table_param.partition_store_)) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "invalid arguments", K(ret), K(get_table_param));
} else if (OB_FAIL(get_table_param.partition_store_->get_last_major_sstable(
get_table_param.sample_info_.table_id_, table_handle))) {
STORAGE_LOG(WARN, "fail to get last major sstable", K(ret));
} else if (OB_FAIL(table_handle.get_sstable(sstable))) {
STORAGE_LOG(WARN, "fail to get last major sstable", K(ret));
} else if (OB_FAIL(table_handle_.set_table(sstable))) {
STORAGE_LOG(WARN, "fail to set sstable", K(ret));
} else if (OB_FAIL(micro_block_iterator_.init(sample_info_->table_id_, table_handle_, range, is_reverse_scan))) {
STORAGE_LOG(WARN, "failed to init micro_block_iterator_", K(ret));
} else {
range_ = range;
scan_merge_ = &scan_merge;
has_open_block_ = false;
block_num_ = 0;
row_cnt_from_cur_block_ = 0;
access_ctx_ = &access_ctx;
}
return ret;
}
void ObBlockSampleIterator::reuse()
{
micro_block_iterator_.reset();
range_.reset();
block_num_ = 0;
row_cnt_from_cur_block_ = 0;
has_open_block_ = false;
table_handle_.reset();
}
void ObBlockSampleIterator::reset()
{
micro_block_iterator_.reset();
range_.reset();
scan_merge_ = nullptr;
block_num_ = 0;
row_cnt_from_cur_block_ = 0;
has_open_block_ = false;
table_handle_.reset();
}
int ObBlockSampleIterator::get_next_row(ObStoreRow*& row)
{
int ret = OB_SUCCESS;
const ObStoreRange* range = nullptr;
row = nullptr;
if (OB_ISNULL(scan_merge_)) {
ret = OB_NOT_INIT;
STORAGE_LOG(WARN, "block sample iterator is not opened", K(ret));
} else {
while (OB_SUCC(ret) && (!has_open_block_ || ++row_cnt_from_cur_block_ > ROW_CNT_LIMIT_PER_BLOCK ||
OB_FAIL(scan_merge_->get_next_row(row)))) {
if (OB_ITER_END == ret || OB_SUCCESS == ret) {
ret = OB_SUCCESS;
has_open_block_ = false;
}
if (OB_SUCC(ret)) {
if (OB_FAIL(micro_block_iterator_.get_next_range(range))) {
if (OB_ITER_END != ret) {
STORAGE_LOG(WARN, "failed to get next range", K(ret));
}
} else if (OB_ISNULL(range)) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "range is null", K(ret), K_(block_num));
} else if (return_this_sample(block_num_++)) {
STORAGE_LOG(DEBUG, "open a range", K(*range), K_(block_num));
micro_range_.reset();
micro_range_.get_range() = *range;
if (OB_FAIL(open_range(micro_range_))) {
STORAGE_LOG(WARN, "failed to open range", K(ret), K_(micro_range));
}
}
}
}
if (OB_FAIL(ret) && OB_ITER_END != ret) {
STORAGE_LOG(WARN, "failed to get next row from ObBlockSampleIterator", K(ret));
}
}
return ret;
}
int ObBlockSampleIterator::open_range(ObExtStoreRange& range)
{
int ret = OB_SUCCESS;
scan_merge_->reuse();
allocator_.reuse();
access_ctx_->allocator_->reuse();
if (OB_FAIL(range.to_collation_free_range_on_demand_and_cutoff_range(allocator_))) {
STORAGE_LOG(WARN, "failed to covert to collation free range", K(range), K(ret));
} else if (OB_FAIL(scan_merge_->open(range))) {
STORAGE_LOG(WARN, "failed to open ObMultipleScanMerge", K(ret), K(range));
} else {
has_open_block_ = true;
row_cnt_from_cur_block_ = 0;
}
return ret;
}
} // namespace storage
} // namespace oceanbase
|
/**
/**
* @file
* @copyright defined in bos/LICENSE.txt
*/
#include <eosio/chain/types.hpp>
#include <eosio/ibc_plugin/ibc_plugin.hpp>
#include <eosio/ibc_plugin/protocol.hpp>
#include <eosio/chain/controller.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/block.hpp>
#include <eosio/chain/plugin_interface.hpp>
#include <eosio/chain/thread_utils.hpp>
#include <eosio/producer_plugin/producer_plugin.hpp>
#include <eosio/chain/contract_types.hpp>
#include <fc/network/message_buffer.hpp>
#include <fc/network/ip.hpp>
#include <fc/io/json.hpp>
#include <fc/io/raw.hpp>
#include <fc/log/appender.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/crypto/rand.hpp>
#include <fc/exception/exception.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/steady_timer.hpp>
using namespace eosio::chain::plugin_interface::compat;
namespace eosio { namespace ibc {
static appbase::abstract_plugin& _ibc_plugin = app().register_plugin<ibc_plugin>();
using std::vector;
using boost::asio::ip::tcp;
using boost::asio::ip::address_v4;
using boost::asio::ip::host_name;
using boost::multi_index_container;
using fc::time_point;
using fc::time_point_sec;
using eosio::chain::transaction_id_type;
using eosio::chain::name;
using namespace eosio::chain::plugin_interface;
using mvo = fc::mutable_variant_object;
namespace bip = boost::interprocess;
// consts
const static uint32_t MaxSendSectionLength = 30;
const static uint32_t AfterLib = 10;
const static uint32_t BPScheduleReplaceMinLength = 330; // important para, 330 > 325, safer
const static uint32_t BlocksPerSecond = 2;
const static uint32_t MaxLocalOrigtrxsCache = 10000;
const static uint32_t MaxLocalCashtrxsCache = 10000;
const static uint32_t MaxLocalOldSectionsCache = 5;
class connection;
class ibc_chain_contract;
class ibc_token_contract;
using connection_ptr = std::shared_ptr<connection>;
using connection_wptr = std::weak_ptr<connection>;
using socket_ptr = std::shared_ptr<tcp::socket>;
using io_work_t = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>;
using ibc_message_ptr = shared_ptr<ibc_message>;
struct by_block_num;
struct by_trx_id;
typedef multi_index_container<
ibc_trx_rich_info,
indexed_by<
ordered_unique<
tag< by_id >,
member < ibc_trx_rich_info,
uint64_t,
&ibc_trx_rich_info::table_id > >,
ordered_non_unique<
tag< by_block_num >,
member< ibc_trx_rich_info,
uint32_t,
&ibc_trx_rich_info::block_num > >,
ordered_non_unique<
tag< by_trx_id >,
member< ibc_trx_rich_info,
transaction_id_type,
&ibc_trx_rich_info::trx_id > >
>
>
ibc_transaction_index;
struct trx_rich_info_update {
std::vector<digest_type> block_id_merkle_path;
uint32_t anchor_block_num;
trx_rich_info_update ( std::vector<digest_type> merkle_path, uint32_t block_num ) : block_id_merkle_path(merkle_path),anchor_block_num(block_num) {}
void operator () ( ibc_trx_rich_info& info ) {
info.block_id_merkle_path = block_id_merkle_path;
info.anchor_block_num = anchor_block_num;
}
};
class ibc_plugin_impl {
public:
unique_ptr<tcp::acceptor> acceptor;
tcp::endpoint listen_endpoint;
string p2p_address;
string p2p_server_address;
uint32_t max_client_count = 0;
uint32_t max_nodes_per_host = 1;
uint32_t num_clients = 0;
vector<string> supplied_peers;
vector<chain::public_key_type> allowed_peers; ///< peer keys allowed to connect
std::map<chain::public_key_type,
chain::private_key_type> private_keys;
enum possible_connections : char {
None = 0,
Specified = 1 << 0,
Any = 1 << 1
};
possible_connections allowed_connections{None};
connection_ptr find_connection( string host )const;
std::set< connection_ptr > connections;
bool done = false;
std::vector<blockroot_merkle_type> blockroot_merkle_cache;
name relay;
chain::private_key_type relay_private_key;
unique_ptr< ibc_chain_contract > chain_contract;
unique_ptr< ibc_token_contract > token_contract;
unique_ptr<boost::asio::steady_timer> connector_check;
boost::asio::steady_timer::duration connector_period;
int max_cleanup_time_ms = 0;
unique_ptr<boost::asio::steady_timer> keepalive_timer;
boost::asio::steady_timer::duration keepalive_interval{std::chrono::seconds{5}};
unique_ptr<boost::asio::steady_timer> ibc_heartbeat_timer;
boost::asio::steady_timer::duration ibc_heartbeat_interval{std::chrono::seconds{3}};
unique_ptr<boost::asio::steady_timer> ibc_core_timer;
boost::asio::steady_timer::duration ibc_core_interval{std::chrono::seconds{2}};
const std::chrono::system_clock::duration peer_authentication_interval{std::chrono::seconds{1}}; ///< Peer clock may be no more than 1 second skewed from our clock, including network latency.
bool network_version_match = false;
fc::sha256 chain_id;
fc::sha256 peerchain_id;
fc::sha256 node_id;
ibc_transaction_index local_origtrxs;
ibc_transaction_index local_cashtrxs;
uint32_t new_prod_blk_num = 0;
string user_agent_name;
chain_plugin* chain_plug = nullptr;
int started_sessions = 0;
shared_ptr<tcp::resolver> resolver;
bool use_socket_read_watermark = false;
uint16_t thread_pool_size = 1;
optional<eosio::chain::named_thread_pool> thread_pool;
void connect( const connection_ptr& c );
void connect( const connection_ptr& c, const std::shared_ptr<tcp::resolver>& resolver, tcp::resolver::results_type endpoints );
bool start_session(const connection_ptr& c);
void start_listen_loop();
void start_read_message(const connection_ptr& c);
/** \brief Process the next message from the pending message buffer
*
* Process the next message from the pending_message_buffer.
* message_length is the already determined length of the data
* part of the message that will handle the message.
* Returns true is successful. Returns false if an error was
* encountered unpacking or processing the message.
*/
bool process_next_message(const connection_ptr& conn, uint32_t message_length);
void close(const connection_ptr& c );
size_t count_open_sockets() const;
void irreversible_block(const block_state_ptr&);
bool is_valid( const handshake_message &msg);
void handle_message(const connection_ptr& c, const handshake_message &msg);
void handle_message(const connection_ptr& c, const go_away_message &msg );
/** Process time_message
* Calculate offset, delay and dispersion. Note carefully the
* implied processing. The first-order difference is done
* directly in 64-bit arithmetic, then the result is converted
* to floating double. All further processing is in
* floating-double arithmetic with rounding done by the hardware.
* This is necessary in order to avoid overflow and preserve precision.
*/
void handle_message(const connection_ptr& c, const time_message& msg);
void handle_message(const connection_ptr& c, const ibc_heartbeat_message &msg);
void handle_message(const connection_ptr& c, const lwc_init_message &msg);
void handle_message(const connection_ptr& c, const lwc_section_request_message &msg);
void handle_message(const connection_ptr& c, const lwc_section_data_message &msg);
void handle_message(const connection_ptr& c, const lwc_block_commits_request_message &msg);
void handle_message(const connection_ptr& c, const lwc_block_commits_data_message &msg);
void handle_message(const connection_ptr& c, const ibc_trxs_request_message &msg);
void handle_message(const connection_ptr& c, const ibc_trxs_data_message &msg);
void handle_message(const connection_ptr& c, const ibc_block_merkle_path_request_message &msg);
void handle_message(const connection_ptr& c, const ibc_block_merkle_path_data_message &msg);
bool head_catched_up = false;
lwc_section_type sum_received_lwcls_info( );
bool is_head_catchup( );
bool should_send_ibc_heartbeat( );
void chain_checker( ibc_heartbeat_message& msg );
void ibc_chain_contract_checker( ibc_heartbeat_message& msg );
void ibc_token_contract_checker( ibc_heartbeat_message& msg );
void start_ibc_heartbeat_timer( );
incremental_merkle get_brtm_from_cache( uint32_t block_num );
uint32_t get_head_tslot( );
uint32_t get_lib_tslot( );
uint32_t get_block_num_by_time_slot( uint32_t block_time_slot );
optional<ibc_trx_rich_info> get_ibc_trx_rich_info( uint32_t block_time_slot, transaction_id_type trx_id, uint64_t table_id );
void check_if_remove_old_data_in_ibc_contracts();
void ibc_core_checker( );
void start_ibc_core_timer( );
void connection_monitor(std::weak_ptr<connection> from_connection);
void start_conn_timer( boost::asio::steady_timer::duration du, std::weak_ptr<connection> from_connection );
void start_monitors( );
/** Peer heartbeat ticker.
*/
void ticker();
bool authenticate_peer(const handshake_message& msg) const;
/** Retrieve public key used to authenticate with peers.
*
* Finds a key to use for authentication. If this node is a producer, use
* the front of the producer key map. If the node is not a producer but has
* a configured private key, use it. If the node is neither a producer nor has
* a private key, returns an empty key.
*
* note: On a node with multiple private keys configured, the key with the first
* numerically smaller byte will always be used.
*/
chain::public_key_type get_authentication_key() const;
/** Returns a signature of the digest using the corresponding private key of the signer.
* If there are no configured private keys, returns an empty signature.
*/
chain::signature_type sign_compact(const chain::public_key_type& signer, const fc::sha256& digest) const;
};
const fc::string logger_name("ibc_plugin_impl");
fc::logger logger;
std::string peer_log_format;
#define peer_dlog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( logger.is_enabled( fc::log_level::debug ) ) \
logger.log( FC_LOG_MESSAGE( debug, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant()) ) ); \
FC_MULTILINE_MACRO_END
#define peer_ilog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( logger.is_enabled( fc::log_level::info ) ) \
logger.log( FC_LOG_MESSAGE( info, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant()) ) ); \
FC_MULTILINE_MACRO_END
#define peer_wlog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( logger.is_enabled( fc::log_level::warn ) ) \
logger.log( FC_LOG_MESSAGE( warn, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant()) ) ); \
FC_MULTILINE_MACRO_END
#define peer_elog( PEER, FORMAT, ... ) \
FC_MULTILINE_MACRO_BEGIN \
if( logger.is_enabled( fc::log_level::error ) ) \
logger.log( FC_LOG_MESSAGE( error, peer_log_format + FORMAT, __VA_ARGS__ (PEER->get_logger_variant())) ); \
FC_MULTILINE_MACRO_END
template<class enum_type, class=typename std::enable_if<std::is_enum<enum_type>::value>::type>
inline enum_type& operator|=(enum_type& lhs, const enum_type& rhs)
{
using T = std::underlying_type_t <enum_type>;
return lhs = static_cast<enum_type>(static_cast<T>(lhs) | static_cast<T>(rhs));
}
static ibc_plugin_impl *my_impl;
/**
* default value initializers
*/
constexpr auto def_send_buffer_size_mb = 4;
constexpr auto def_send_buffer_size = 1024*1024*def_send_buffer_size_mb;
constexpr auto def_max_write_queue_size = def_send_buffer_size*10;
constexpr boost::asio::chrono::milliseconds def_read_delay_for_full_write_queue{100};
constexpr auto def_max_clients = 10; // 0 for unlimited clients
constexpr auto def_max_nodes_per_host = 1;
constexpr auto def_conn_retry_wait = 3;
constexpr auto message_header_size = 4;
constexpr uint16_t net_version = 1;
struct handshake_initializer {
static void populate(handshake_message &hello);
};
class queued_buffer : boost::noncopyable {
public:
void clear_write_queue() {
_write_queue.clear();
_sync_write_queue.clear();
_write_queue_size = 0;
}
void clear_out_queue() {
while ( _out_queue.size() > 0 ) {
_out_queue.pop_front();
}
}
uint32_t write_queue_size() const { return _write_queue_size; }
bool is_out_queue_empty() const { return _out_queue.empty(); }
bool ready_to_send() const {
// if out_queue is not empty then async_write is in progress
return ((!_sync_write_queue.empty() || !_write_queue.empty()) && _out_queue.empty());
}
bool add_write_queue( const std::shared_ptr<vector<char>>& buff,
std::function<void( boost::system::error_code, std::size_t )> callback,
bool to_sync_queue ) {
if( to_sync_queue ) {
_sync_write_queue.push_back( {buff, callback} );
} else {
_write_queue.push_back( {buff, callback} );
}
_write_queue_size += buff->size();
if( _write_queue_size > 2 * def_max_write_queue_size ) {
return false;
}
return true;
}
void fill_out_buffer( std::vector<boost::asio::const_buffer>& bufs ) {
if( _sync_write_queue.size() > 0 ) { // always send msgs from sync_write_queue first
fill_out_buffer( bufs, _sync_write_queue );
} else { // postpone real_time write_queue if sync queue is not empty
fill_out_buffer( bufs, _write_queue );
EOS_ASSERT( _write_queue_size == 0, plugin_exception, "write queue size expected to be zero" );
}
}
void out_callback( boost::system::error_code ec, std::size_t w ) {
for( auto& m : _out_queue ) {
m.callback( ec, w );
}
}
private:
struct queued_write;
void fill_out_buffer( std::vector<boost::asio::const_buffer>& bufs,
deque<queued_write>& w_queue ) {
while ( w_queue.size() > 0 ) {
auto& m = w_queue.front();
bufs.push_back( boost::asio::buffer( *m.buff ));
_write_queue_size -= m.buff->size();
_out_queue.emplace_back( m );
w_queue.pop_front();
}
}
private:
struct queued_write {
std::shared_ptr<vector<char>> buff;
std::function<void( boost::system::error_code, std::size_t )> callback;
};
uint32_t _write_queue_size = 0;
deque<queued_write> _write_queue;
deque<queued_write> _sync_write_queue; // sync_write_queue will be sent first
deque<queued_write> _out_queue;
}; // queued_buffer
class connection : public std::enable_shared_from_this<connection> {
public:
explicit connection( string endpoint );
explicit connection( socket_ptr s );
~connection();
void initialize();
boost::asio::io_context& server_ioc;
boost::asio::io_context::strand strand;
socket_ptr socket;
fc::message_buffer<1024*1024> pending_message_buffer;
fc::optional<std::size_t> outstanding_read_bytes;
queued_buffer buffer_queue;
fc::sha256 node_id;
handshake_message last_handshake_recv;
handshake_message last_handshake_sent;
int16_t sent_handshake_count = 0;
bool connecting = false;
uint16_t protocol_version = 0;
string peer_addr;
unique_ptr<boost::asio::steady_timer> response_expected;
unique_ptr<boost::asio::steady_timer> read_delay_timer;
go_away_reason no_retry = no_reason;
connection_status get_status()const {
connection_status stat;
stat.peer = peer_addr;
stat.connecting = connecting;
stat.last_handshake = last_handshake_recv;
return stat;
}
tstamp org{0}; //!< originate timestamp
tstamp rec{0}; //!< receive timestamp
tstamp dst{0}; //!< destination timestamp
tstamp xmt{0}; //!< transmit timestamp
double offset{0}; //!< peer offset
static const size_t ts_buffer_size{32};
char ts[ts_buffer_size]; //!< working buffer for making human readable timestamps
/** @} */
lwc_section_type lwcls_info;
time_point lwcls_info_update_time;
bool connected();
bool current();
void reset();
void close();
void send_handshake();
/** \name Peer Timestamps
* Time message handling
*/
/** \brief Populate and queue time_message
*/
void send_time();
/** \brief Populate and queue time_message immediately using incoming time_message
*/
void send_time(const time_message& msg);
/** \brief Read system time and convert to a 64 bit integer.
*
* There are only two calls on this routine in the program. One
* when a packet arrives from the network and the other when a
* packet is placed on the send queue. Calls the kernel time of
* day routine and converts to a (at least) 64 bit integer.
*/
tstamp get_time()
{
return std::chrono::system_clock::now().time_since_epoch().count();
}
/** @} */
const string peer_name();
void enqueue( const ibc_message &msg, bool trigger_send = true );
void enqueue_buffer( const std::shared_ptr<std::vector<char>>& send_buffer,
bool trigger_send, int priority, go_away_reason close_after_send,
bool to_sync_queue = false);
void cancel_sync(go_away_reason);
void flush_queues();
void cancel_wait();
void queue_write(const std::shared_ptr<vector<char>>& buff,
bool trigger_send,
int priority,
std::function<void(boost::system::error_code, std::size_t)> callback,
bool to_sync_queue = false);
void do_queue_write(int priority);
fc::optional<fc::variant_object> _logger_variant;
const fc::variant_object& get_logger_variant() {
if (!_logger_variant) {
boost::system::error_code ec;
auto rep = socket->remote_endpoint(ec);
string ip = ec ? "<unknown>" : rep.address().to_string();
string port = ec ? "<unknown>" : std::to_string(rep.port());
auto lep = socket->local_endpoint(ec);
string lip = ec ? "<unknown>" : lep.address().to_string();
string lport = ec ? "<unknown>" : std::to_string(lep.port());
_logger_variant.emplace(fc::mutable_variant_object()
("_name", peer_name())
("_id", node_id)
("_sid", ((string)node_id).substr(0, 7))
("_ip", ip)
("_port", port)
("_lip", lip)
("_lport", lport)
);
}
return *_logger_variant;
}
};
struct msg_handler : public fc::visitor<void> {
ibc_plugin_impl &impl;
connection_ptr c;
msg_handler( ibc_plugin_impl &imp, connection_ptr conn) : impl(imp), c(conn) {}
template <typename T>
void operator()( T&& msg ) const
{
impl.handle_message( c, std::forward<T>(msg) );
}
};
// ---- contract related consts ----
static const uint32_t default_expiration_delta = 120; ///< 120 seconds
static const fc::microseconds abi_serializer_max_time{500 * 1000}; ///< 500ms
static const uint32_t min_lwc_lib_depth = 50;
static const uint32_t max_lwc_lib_depth = 400;
// ---- low layer function to read contract table and singleton ----
optional<key_value_object> get_table_nth_row_kvo_by_primary_key( const name& code, const name& scope, const name& table, const uint64_t nth = 0, bool reverse = false ) {
const auto& d = app().get_plugin<chain_plugin>().chain().db();
const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(code, scope, table));
if (t_id != nullptr) {
const auto &idx = d.get_index<chain::key_value_index, chain::by_scope_primary>();
decltype(t_id->id) next_tid(t_id->id._id + 1);
auto lower = idx.lower_bound(boost::make_tuple(t_id->id));
auto upper = idx.lower_bound(boost::make_tuple(next_tid));
if ( lower == upper ){
return optional<key_value_object>();
}
if ( reverse ){
int i = nth;
auto itr = --upper;
for (; itr != lower && i >= 0; --itr ){
if (i == 0) {
const key_value_object &obj = *itr;
return obj;
}
--i;
}
if ( i == 0 && itr == lower ){
return *lower;
}
} else {
int i = nth;
auto itr = lower;
for (; itr != upper && i >= 0; ++itr ){
if (i == 0) {
const key_value_object &obj = *itr;
return obj;
}
--i;
}
}
}
return optional<key_value_object>();
}
range_type get_table_primary_key_range( const name& code, const name& scope, const name& table ) {
const auto& d = app().get_plugin<chain_plugin>().chain().db();
const auto* t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(boost::make_tuple(code, scope, table));
if (t_id != nullptr) {
const auto &idx = d.get_index<chain::key_value_index, chain::by_scope_primary>();
decltype(t_id->id) next_tid(t_id->id._id + 1);
auto lower = idx.lower_bound(boost::make_tuple(t_id->id));
auto upper = idx.lower_bound(boost::make_tuple(next_tid));
if ( lower != upper ){
const key_value_object& first = *lower;
const key_value_object& last = *(--upper);
return std::make_pair( first.primary_key, last.primary_key );
}
}
return range_type();
}
optional<key_value_object> get_singleton_kvo( const name& code, const name& scope, const name& table ) {
const auto &d = app().get_plugin<chain_plugin>().chain().db();
const auto *t_id = d.find<chain::table_id_object, chain::by_code_scope_table>(
boost::make_tuple(code, scope, table));
if (t_id != nullptr) {
const auto &idx = d.get_index<chain::key_value_index, chain::by_scope_primary>();
decltype(t_id->id) next_tid(t_id->id._id + 1);
auto lower = idx.lower_bound(boost::make_tuple(t_id->id));
auto upper = idx.lower_bound(boost::make_tuple(next_tid));
if (lower == upper) {
return optional<key_value_object>();
}
return *lower;
}
return optional<key_value_object>();
}
// ---- contract exist check ----
bool account_has_contract( name account ){
auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api();
chain_apis::read_only::get_code_hash_params params{account};
try {
auto result = ro_api.get_code_hash( params );
if ( result.code_hash != fc::sha256() ){
return true;
}
} catch (...){}
return false;
}
// ---- transaction constructor and push function ----
void set_transaction_headers( transaction& trx, uint32_t expiration = default_expiration_delta, uint32_t delay_sec = 0 ) {
trx.expiration = my_impl->chain_plug->chain().head_block_time() + fc::seconds(expiration);
trx.set_reference_block( my_impl->chain_plug->chain().last_irreversible_block_id() );
trx.max_net_usage_words = 0; // No limit
trx.max_cpu_usage_ms = 0; // No limit
trx.delay_sec = delay_sec;
}
optional<action> get_action( account_name code, action_name acttype, vector<permission_level> auths, const fc::variant& data ) {
try {
const auto& acnt = my_impl->chain_plug->chain().get_account(code);
auto abi = acnt.get_abi();
chain::abi_serializer abis(abi, abi_serializer_max_time);
string action_type_name = abis.get_action_type(acttype);
FC_ASSERT( action_type_name != string(), "unknown action type ${a}", ("a",acttype) );
action act;
act.account = code;
act.name = acttype;
act.authorization = auths;
act.data = abis.variant_to_binary(action_type_name, data, abi_serializer_max_time);
return act;
} FC_LOG_AND_DROP()
return optional<action>();
}
void push_transaction_base( signed_transaction& trx ) {
auto next = [=](const fc::static_variant<fc::exception_ptr, chain_apis::read_write::push_transaction_results>& result){
if (result.contains<fc::exception_ptr>()) {
try {
result.get<fc::exception_ptr>()->dynamic_rethrow_exception();
} FC_LOG_AND_DROP()
} else {
// auto trx_id = result.get<chain_apis::read_write::push_transaction_results>().transaction_id;
// fc_dlog(logger,"pushed transaction: ${id}", ( "id", trx_id ));
}
};
my_impl->chain_plug->get_read_write_api().push_transaction_v2( fc::variant_object( mvo(packed_transaction(trx)) ), next );
}
void push_recurse(int index, const std::shared_ptr<std::vector<signed_transaction>>& params, bool allow_failure ) {
auto next = [=](const fc::static_variant<fc::exception_ptr, chain_apis::read_write::push_transaction_results>& result) {
if (result.contains<fc::exception_ptr>()) {
try {
result.get<fc::exception_ptr>()->dynamic_rethrow_exception();
} FC_LOG_AND_DROP()
if ( !allow_failure ){ return; }
} else {
// auto trx_id = result.get<chain_apis::read_write::push_transaction_results>().transaction_id;
// fc_dlog(logger,"pushed transaction: ${id}", ( "id", trx_id ));
}
int next_index = index + 1;
if (next_index < params->size()) {
push_recurse( next_index, params, allow_failure );
}
};
my_impl->chain_plug->get_read_write_api().push_transaction_v2( fc::variant_object(mvo(packed_transaction( params->at(index) ))), next );
}
void push_transactions( const std::vector<signed_transaction>& params, bool allow_failure ){
try {
EOS_ASSERT( params.size() <= 1000, too_many_tx_at_once, "Attempt to push too many transactions at once" );
auto params_copy = std::make_shared<std::vector<signed_transaction>>(params.begin(), params.end());
push_recurse( 0, params_copy, allow_failure );
} FC_LOG_AND_DROP()
}
optional<signed_transaction> generate_signed_transaction_from_action( action actn ){
if ( my_impl->relay_private_key == chain::private_key_type() ){
fc_elog(logger,"ibc relay private key not found, can not execute action");
return optional<signed_transaction>();
}
signed_transaction trx;
trx.actions.emplace_back( actn );
set_transaction_headers( trx );
trx.sign( my_impl->relay_private_key, my_impl->chain_plug->chain().get_chain_id() );
return trx;
}
void push_action( action actn ) {
auto trx_opt = generate_signed_transaction_from_action( actn );
if ( trx_opt.valid() ){
push_transaction_base( *trx_opt );
} else {
fc_elog(logger,"push_action failed, for generate_signed_transaction_from_action failed");
}
}
// --------------- ibc_chain_contract ---------------
class ibc_chain_contract {
public:
ibc_chain_contract( name contract ):account(contract){}
contract_state state = none;
name chain_name;
fc::sha256 chain_id;
name consensus_algo;
uint32_t lwc_lib_depth = 0;
// actions
void chain_init( const lwc_init_message& msg );
void pushsection( const lwc_section_data_message& msg );
void pushblkcmits( const lwc_block_commits_data_message& msg );
void rmfirstsctn();
// tables
optional<section_type> get_sections_tb_reverse_nth_section( uint64_t nth = 0 ) const;
uint32_t get_sections_tb_size() const;
range_type get_chaindb_tb_id_range() const;
optional<block_header_state_type> get_chaindb_tb_bhs_by_block_num( uint64_t num ) const;
block_id_type get_chaindb_tb_block_id_by_block_num( uint64_t num ) const;
optional<global_state_ibc_chain> get_ibc_chain_global_state_singleton() const;
optional<global_mutable_ibc_chain> get_ibc_chain_global_mutable_singleton() const;
name get_consensus_algo();
uint32_t get_last_anchor_block_num();
// other
bool has_contract() const;
bool lwc_config_valid() const;
bool lwc_chain_initialized() const;
void get_contract_state();
name get_account(){ return account; }
private:
name account;
};
bool ibc_chain_contract::has_contract() const {
return account_has_contract( account );
}
bool ibc_chain_contract::lwc_config_valid() const {
if ( chain_name != name() && chain_id != fc::sha256() ){
if ( consensus_algo == N(pipeline) ){
if ( min_lwc_lib_depth <= lwc_lib_depth && lwc_lib_depth <= max_lwc_lib_depth ){
return true;
}
return false;
} else if ( consensus_algo == N(batch) ){
return true;
}
}
return false;
}
bool ibc_chain_contract::lwc_chain_initialized() const {
const auto& ret = get_chaindb_tb_id_range();
if ( ret != range_type() ){
return true;
}
return false;
}
void ibc_chain_contract::get_contract_state(){
contract_state c_state = none;
if ( has_contract() ) {
c_state = deployed;
auto sp = get_ibc_chain_global_state_singleton();
if ( sp.valid() ) {
global_state_ibc_chain gstate = *sp;
chain_name = gstate.chain_name;
chain_id = gstate.chain_id;
consensus_algo = gstate.consensus_algo;
lwc_lib_depth = 325;
/*lwc_lib_depth = 50; // used for test env */
}
if ( lwc_chain_initialized() && lwc_config_valid() ){
c_state = working;
}
}
state = c_state;
}
optional<section_type> ibc_chain_contract::get_sections_tb_reverse_nth_section( uint64_t nth ) const {
auto p = get_table_nth_row_kvo_by_primary_key( account, account, N(sections), nth, true );
if ( p.valid() ){
auto obj = *p;
fc::datastream<const char *> ds(obj.value.data(), obj.value.size());
section_type result;
fc::raw::unpack( ds, result );
return result;
}
return optional<section_type>();
}
uint32_t ibc_chain_contract::get_sections_tb_size() const {
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = account.to_string();
par.table = N(sections);
par.table_key = "primary_key";
par.lower_bound = to_string(0);
par.upper_bound = "";
par.limit = 10;
par.key_type = "i64";
par.index_position = "1";
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
return result.rows.size();
} FC_LOG_AND_DROP()
return 0;
}
range_type ibc_chain_contract::get_chaindb_tb_id_range() const {
return get_table_primary_key_range( account, account, N(chaindb) );
}
optional<block_header_state_type> ibc_chain_contract::get_chaindb_tb_bhs_by_block_num( uint64_t num ) const {
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = account.to_string();
par.table = N(chaindb);
par.table_key = "block_num";
par.lower_bound = to_string(num);
par.upper_bound = to_string(num + 1);
par.limit = 1;
par.key_type = "i64";
par.index_position = "1";
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
if ( result.rows.size() != 0 ){
auto ret = result.rows[0];
block_header_state_type bhs;
bhs.block_num = ret["block_num"].as<uint64_t>();
bhs.block_id = ret["block_id"].as<block_id_type>();
bhs.header.timestamp = ret["header"]["timestamp"].as<block_timestamp_type>();
bhs.header.producer = ret["header"]["producer"].as<account_name>();
bhs.header.confirmed = ret["header"]["confirmed"].as<uint16_t>();
bhs.header.previous = ret["header"]["previous"].as<block_id_type>();
bhs.header.transaction_mroot = ret["header"]["transaction_mroot"].as<checksum256_type>();
bhs.header.action_mroot = ret["header"]["action_mroot"].as<checksum256_type>();
bhs.header.schedule_version = ret["header"]["schedule_version"].as<uint32_t>();
bhs.header.new_producers = ret["header"]["new_producers"].as<optional<producer_schedule_type>>();
/*bhs.header.header_extensions = ret["header"]["header_extensions"].as<extensions_type>();*/ // a bug here
bhs.header.producer_signature = ret["header"]["producer_signature"].as<signature_type>();
bhs.active_schedule_id = ret["active_schedule_id"].as<uint32_t>();
bhs.pending_schedule_id = ret["pending_schedule_id"].as<uint32_t>();
bhs.blockroot_merkle = ret["blockroot_merkle"].as<incremental_merkle>();
bhs.block_signing_key = ret["block_signing_key"].as<public_key_type>();
bhs.is_anchor_block = ret["is_anchor_block"].as<bool>();
return bhs;
}
} FC_LOG_AND_DROP()
return optional<block_header_state_type>();
}
block_id_type ibc_chain_contract::get_chaindb_tb_block_id_by_block_num( uint64_t num ) const {
auto p = get_chaindb_tb_bhs_by_block_num( num );
if ( p.valid() ){
return p->block_id;
}
return block_id_type();
}
optional<global_state_ibc_chain> ibc_chain_contract::get_ibc_chain_global_state_singleton() const {
auto p = get_singleton_kvo( account, account, N(global) );
if ( p.valid() ){
auto obj = *p;
fc::datastream<const char *> ds(obj.value.data(), obj.value.size());
global_state_ibc_chain result;
fc::raw::unpack( ds, result );
return result;
}
return optional<global_state_ibc_chain>();
}
optional<global_mutable_ibc_chain> ibc_chain_contract::get_ibc_chain_global_mutable_singleton() const {
auto p = get_singleton_kvo( account, account, N(globalm) );
if ( p.valid() ){
auto obj = *p;
fc::datastream<const char *> ds(obj.value.data(), obj.value.size());
global_mutable_ibc_chain result;
fc::raw::unpack( ds, result );
return result;
} else {
fc_elog(logger,"get_ibc_chain_global_mutable_singleton failed");
}
return optional<global_mutable_ibc_chain>();
}
name ibc_chain_contract::get_consensus_algo(){
auto gsp = get_ibc_chain_global_state_singleton();
if ( gsp.valid() ) {
return gsp->consensus_algo;
}
return name();
}
uint32_t ibc_chain_contract::get_last_anchor_block_num(){
auto gmp = get_ibc_chain_global_mutable_singleton();
if ( gmp.valid() ) {
return gmp->last_anchor_block_num;
} else {
fc_elog(logger,"get_last_anchor_block_num failed");
}
return 0;
}
void ibc_chain_contract::chain_init( const lwc_init_message &msg ){
auto actn = get_action( account, N(chaininit), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("header", fc::raw::pack(msg.header))
("active_schedule", msg.active_schedule)
("blockroot_merkle", msg.blockroot_merkle)
("relay", my_impl->relay));
if ( ! actn.valid() ){
fc_elog(logger,"chain_init: get action failed");
return;
}
push_action( *actn );
}
void ibc_chain_contract::pushsection( const lwc_section_data_message& msg ){
auto actn = get_action( account, N(pushsection), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("headers", fc::raw::pack(msg.headers))
("blockroot_merkle", msg.blockroot_merkle)
("relay", my_impl->relay));
if ( ! actn.valid() ){
fc_elog(logger,"newsection: get action failed");
return;
}
push_action( *actn );
}
void ibc_chain_contract::pushblkcmits( const lwc_block_commits_data_message& msg ){
auto actn = get_action( account, N(pushblkcmits), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("headers", fc::raw::pack(msg.headers))
("blockroot_merkle", msg.blockroot_merkle)
("proof_data", msg.proof_data)
("proof_type", msg.proof_type)
("relay", my_impl->relay));
if ( ! actn.valid() ){
fc_elog(logger,"newsection: get action failed");
return;
}
push_action( *actn );
}
void ibc_chain_contract::rmfirstsctn(){
auto actn = get_action( account, N(rmfirstsctn), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("relay", my_impl->relay));
if ( ! actn.valid() ){
fc_elog(logger,"newsection: get action failed");
return;
}
push_action( *actn );
}
name peer_chain_name(){
return my_impl->chain_contract->chain_name;
}
// --------------- ibc_token_contract ---------------
class ibc_token_contract {
public:
ibc_token_contract( name contract ):account(contract){}
contract_state state = none;
// actions
void cash( const cash_action_params& p );
void cashconfirm( const cashconfirm_action_params& p );
// tables
range_type get_table_origtrxs_id_range( bool raw = false );
optional<original_trx_info> get_table_origtrxs_trx_info_by_id( uint64_t id );
range_type get_table_cashtrxs_seq_num_range( bool raw = false );
optional<cash_trx_info> get_table_cashtrxs_trx_info_by_seq_num( uint64_t seq_num );
optional<global_state_ibc_token> get_global_state_singleton();
optional<peer_chain_state_ibc_token> get_peer_chain_state();
optional<peer_chain_mutable_ibc_token> get_peer_chain_mutable();
// other
optional<transaction> get_transaction( std::vector<char> packed_trx_receipt );
optional<transfer_action_type> get_original_action_params( std::vector<char> packed_trx_receipt, transaction_id_type* trx_id_ptr = nullptr );
optional<cash_action_params> get_cash_action_params( std::vector<char> packed_trx_receipt );
transaction_id_type last_origtrx_pushed; // note: update this even push failed
// recurse actions
void push_cash_recurse( int index, const std::shared_ptr<std::vector<cash_action_params>>& params, uint32_t start_seq_num );
void push_cash_trxs( const std::vector<ibc_trx_rich_info>& params, uint32_t start_seq_num );
void push_cashconfirm_recurse( int index, const std::shared_ptr<std::vector<cashconfirm_action_params>>& params );
void push_cashconfirm_trxs( const std::vector<ibc_trx_rich_info>& params, uint64_t start_seq_num );
void push_rborrm_recurse( int index, const std::shared_ptr<std::vector<transaction_id_type>>& params, name action_name);
void rollback( const std::vector<transaction_id_type> trxs );
void rmunablerb( const std::vector<transaction_id_type> trxs );
optional<memo_info_type> get_memo_info( const string& memo );
bool has_contract();
void get_contract_state();
private:
name account;
};
optional<memo_info_type> ibc_token_contract::get_memo_info( const string& memo_str ){
memo_info_type info;
string memo = trim( memo_str );
// --- get receiver ---
auto pos = memo.find("@");
if ( pos == std::string::npos ){
fc_elog(logger,"memo format error, didn't find charactor \'@\' in memo");
return optional<memo_info_type>();
}
string receiver_str = memo.substr( 0, pos );
receiver_str = trim( receiver_str );
info.receiver = name( receiver_str );
// --- trim ---
memo = memo.substr( pos + 1 );
memo = trim( memo );
// --- get chain name and notes ---
pos = memo.find_first_not_of("abcdefghijklmnopqrstuvwxyz012345");
if ( pos == std::string::npos ){
info.chain = name( memo );
info.notes = "";
} else {
info.chain = name( memo.substr(0,pos) );
info.notes = memo.substr( pos );
info.notes = trim( info.notes );
}
if ( info.receiver == name() ){
fc_elog(logger,"memo format error, receiver not provided in memo");
return optional<memo_info_type>();
}
if ( info.chain == name() ){
fc_elog(logger,"memo format error, chain not provided in memo");
return optional<memo_info_type>();
}
return info;
}
bool ibc_token_contract::has_contract(){
return account_has_contract( account );
}
void ibc_token_contract::get_contract_state(){
contract_state c_state = none;
if ( has_contract() ) {
c_state = deployed;
auto gs = get_global_state_singleton();
bool bool_gs = false;
if ( gs.valid() ){
const auto& obj = *gs;
if ( obj.this_chain != name() && obj.active ){
bool_gs = true;
}
} else {
fc_dlog(logger,"get ibc.token contract's global_state_singleton failed, is it initialized?");
}
auto pchs = get_peer_chain_state();
bool bool_pchs = false;
if ( pchs.valid() ){
const auto& obj = *pchs;
if ( obj.thischain_ibc_chain_contract == my_impl->chain_contract->get_account() ){
if ( obj.active ){
bool_pchs = true;
}
} else {
fc_elog(logger,"'thischain_ibc_chain_contract' configed in table 'peerchains' of ibc.token not consist with 'chain_name' configed in singleton 'global' of ibc.chain");
}
} else {
fc_dlog(logger,"get ibc.token contract's peer_chain_state failed, is it initialized?");
}
if( bool_pchs && bool_gs ){
c_state = working;
}
}
state = c_state;
}
range_type ibc_token_contract::get_table_origtrxs_id_range( bool raw ) {
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ){
return range_type();
}
auto range = get_table_primary_key_range( account, peerchain_name, N(origtrxs) );
if ( raw ){
return range;
}
uint64_t lib_tslot = my_impl->get_lib_tslot() - AfterLib;
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = peerchain_name.to_string();
par.table = N(origtrxs);
par.table_key = "tslot";
par.lower_bound = to_string(lib_tslot);
par.upper_bound = ""; // to last
par.limit = 1;
par.key_type = "i64";
par.index_position = "2"; // by_slot
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
if ( result.rows.size() != 0 ){
auto info = result.rows.front().as<original_trx_info>();
range.second = info.id - 1;
if ( range.second < range.first ){
return range_type();
}
}
} FC_LOG_AND_DROP()
return range;
}
optional<original_trx_info> ibc_token_contract::get_table_origtrxs_trx_info_by_id( uint64_t id ) {
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ){
return optional<original_trx_info>();
}
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = peerchain_name.to_string();
par.table = N(origtrxs);
par.table_key = "id";
par.lower_bound = to_string(id);
par.upper_bound = to_string(id + 1);
par.limit = 1;
par.key_type = "i64";
par.index_position = "1";
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
if ( result.rows.size() != 0 ){
return result.rows.front().as<original_trx_info>();
}
} FC_LOG_AND_DROP()
return optional<original_trx_info>();
}
range_type ibc_token_contract::get_table_cashtrxs_seq_num_range( bool raw ) {
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ){
return range_type();
}
auto range = get_table_primary_key_range( account, peerchain_name, N(cashtrxs) );
if ( raw ){
return range;
}
uint64_t lib_tslot = my_impl->get_lib_tslot() - AfterLib;
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = peerchain_name.to_string();
par.table = N(cashtrxs);
par.table_key = "tslot";
par.lower_bound = to_string(lib_tslot);
par.upper_bound = ""; // to last
par.limit = 1;
par.key_type = "i64";
par.index_position = "2"; // by_slot
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
if ( result.rows.size() != 0 ){
auto info = result.rows.front().as<cash_trx_info>();
range.second = info.seq_num - 1;
if ( range.second < range.first ){
return range_type();
}
}
} FC_LOG_AND_DROP()
return range;
}
optional<cash_trx_info> ibc_token_contract::get_table_cashtrxs_trx_info_by_seq_num( uint64_t seq_num ) {
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ){
return optional<cash_trx_info>();
}
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = peerchain_name.to_string();
par.table = N(cashtrxs);
par.table_key = "seq_num";
par.lower_bound = to_string(seq_num);
par.upper_bound = to_string(seq_num + 1);
par.limit = 1;
par.key_type = "i64";
par.index_position = "1";
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
if ( result.rows.size() != 0 ){
return result.rows.front().as<cash_trx_info>();
}
} FC_LOG_AND_DROP()
return optional<cash_trx_info>();
}
// singletons
optional<global_state_ibc_token> ibc_token_contract::get_global_state_singleton() {
auto p = get_singleton_kvo( account, account, N(globals) );
if ( p.valid() ){
auto obj = *p;
fc::datastream<const char *> ds(obj.value.data(), obj.value.size());
global_state_ibc_token result;
try {
fc::raw::unpack( ds, result );
return result;
} FC_LOG_AND_DROP()
}
return optional<global_state_ibc_token>();
}
optional<peer_chain_state_ibc_token> ibc_token_contract::get_peer_chain_state() {
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ){
return optional<peer_chain_state_ibc_token>();
}
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = account.to_string();
par.table = N(peerchains);
par.table_key = "peerchain_name";
par.lower_bound = to_string(peerchain_name.value);
par.upper_bound = to_string(peerchain_name.value + 1);
par.limit = 1;
par.key_type = "i64";
par.index_position = "1";
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
if ( result.rows.size() != 0 ){
return result.rows.front().as<peer_chain_state_ibc_token>();
}
} FC_LOG_AND_DROP()
return optional<peer_chain_state_ibc_token>();
}
optional<peer_chain_mutable_ibc_token> ibc_token_contract::get_peer_chain_mutable() {
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ){
return optional<peer_chain_mutable_ibc_token>();
}
chain_apis::read_only::get_table_rows_params par;
par.json = true; // must be true
par.code = account;
par.scope = account.to_string();
par.table = N(peerchainm);
par.table_key = "peerchain_name";
par.lower_bound = to_string(peerchain_name.value);
par.upper_bound = to_string(peerchain_name.value + 1);
par.limit = 1;
par.key_type = "i64";
par.index_position = "1";
try {
auto result = my_impl->chain_plug->get_read_only_api().get_table_rows( par );
if ( result.rows.size() != 0 ){
return result.rows.front().as<peer_chain_mutable_ibc_token>();
}
} FC_LOG_AND_DROP()
return optional<peer_chain_mutable_ibc_token>();
}
optional<transaction> ibc_token_contract::get_transaction( std::vector<char> packed_trx_receipt ){
try {
transaction_receipt trx_rcpt = fc::raw::unpack<transaction_receipt>( packed_trx_receipt );
const auto& pkd_trx = trx_rcpt.trx.get<packed_transaction>();
return fc::raw::unpack<transaction>( pkd_trx.get_packed_transaction() );
} FC_LOG_AND_DROP()
return optional<transaction>();
}
optional<transfer_action_type> ibc_token_contract::get_original_action_params( std::vector<char> packed_trx_receipt, transaction_id_type* trx_id_ptr ){
try {
auto trx_opt = get_transaction( packed_trx_receipt );
if ( trx_opt.valid() ){
if ( trx_id_ptr != nullptr ){
*trx_id_ptr = trx_opt->id();
}
return fc::raw::unpack<transfer_action_type>( trx_opt->actions.front().data );
}
} FC_LOG_AND_DROP()
return optional<transfer_action_type>();
}
optional<cash_action_params> ibc_token_contract::get_cash_action_params( std::vector<char> packed_trx_receipt ){
try {
auto trx_opt = get_transaction( packed_trx_receipt );
if ( trx_opt.valid() ){
return fc::raw::unpack<cash_action_params>( trx_opt->actions.front().data );
}
} FC_LOG_AND_DROP()
return optional<cash_action_params>();
}
void ibc_token_contract::push_cash_recurse( int index, const std::shared_ptr<std::vector<cash_action_params>>& params, uint32_t start_seq_num ){
auto next = [=](const fc::static_variant<fc::exception_ptr, chain_apis::read_write::push_transaction_results>& result) {
uint32_t next_seq_num = start_seq_num;
if (result.contains<fc::exception_ptr>()) {
try {
result.get<fc::exception_ptr>()->dynamic_rethrow_exception();
} FC_LOG_AND_DROP()
fc_elog(logger,"push cash transaction failed, orig_trx_id ${id}, index ${i}",("id", params->at(index).orig_trx_id)("i",index));
} else {
auto trx_id = result.get<chain_apis::read_write::push_transaction_results>().transaction_id;
fc_dlog(logger,"pushed cash transaction: ${id}, index ${idx}", ( "id", trx_id )("idx", index));
next_seq_num += 1;
}
last_origtrx_pushed = params->at(index).orig_trx_id; // used to push failed cash transactions a certain number of times
int next_index = index + 1;
if (next_index < params->size()) {
push_cash_recurse( next_index, params, next_seq_num );
} else {
fc_dlog(logger,"all ${sum} cash transactions have tried to push, which belongs to blocks [${f},${t}]",
("sum",params->size())("f",params->front().orig_trx_block_num)("t",params->back().orig_trx_block_num));
}
};
auto par = params->at(index);
auto actn = get_action( account, N(cash), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("seq_num", start_seq_num)
("from_chain", par.from_chain)
("orig_trx_id", par.orig_trx_id)
("orig_trx_packed_trx_receipt", par.orig_trx_packed_trx_receipt)
("orig_trx_merkle_path", par.orig_trx_merkle_path)
("orig_trx_block_num", par.orig_trx_block_num)
("orig_trx_block_header", par.orig_trx_block_header)
("orig_trx_block_id_merkle_path",par.orig_trx_block_id_merkle_path)
("anchor_block_num", par.anchor_block_num)
("to", par.to)
("quantity", par.quantity)
("memo", par.memo)
("relay", my_impl->relay));
if ( ! actn.valid() ){
fc_elog(logger,"get cash action failed");
return;
}
auto trx_opt = generate_signed_transaction_from_action( *actn );
if ( ! trx_opt.valid() ){
fc_elog(logger,"generate_signed_transaction_from_action failed");
return;
}
my_impl->chain_plug->get_read_write_api().push_transaction_v2( fc::variant_object(mvo(packed_transaction(*trx_opt))), next );
}
void ibc_token_contract::push_cash_trxs( const std::vector<ibc_trx_rich_info>& params, uint32_t start_seq_num ){
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ) {
fc_elog(logger,"internal error! peerchain_name is empty");
return;
}
std::vector<cash_action_params> actions;
for ( const auto& trx : params ){
cash_action_params par;
par.seq_num = 0;
par.from_chain = peerchain_name;
par.orig_trx_id = trx.trx_id;
par.orig_trx_packed_trx_receipt = trx.packed_trx_receipt;
par.orig_trx_merkle_path = trx.trx_merkle_path;
par.orig_trx_block_num = trx.block_num;
par.orig_trx_block_header = trx.block_header;
par.orig_trx_block_id_merkle_path = trx.block_id_merkle_path;
par.anchor_block_num = trx.anchor_block_num;
auto opt = get_original_action_params( trx.packed_trx_receipt );
if ( opt.valid() ){
transfer_action_type actn = *opt;
auto info = get_memo_info( actn.memo );
if ( ! info.valid() ){
fc_elog(logger,"internal error! memo string invalid");
break;
}
par.to = info->receiver;
par.quantity = actn.quantity;
par.memo = "memo";
actions.push_back(par);
} else {
continue;
fc_elog(logger,"internal error, failed to get transfer action infomation from packed_trx_receipt");
break;
}
}
if ( actions.empty() ){
return;
}
try {
EOS_ASSERT( actions.size() <= 1000, too_many_tx_at_once, "Attempt to push too many transactions at once" );
auto params_copy = std::make_shared<std::vector<cash_action_params>>(actions.begin(), actions.end());
push_cash_recurse( 0, params_copy, start_seq_num );
} FC_LOG_AND_DROP()
}
void ibc_token_contract::push_cashconfirm_recurse( int index, const std::shared_ptr<std::vector<cashconfirm_action_params>>& params ){
auto next = [=](const fc::static_variant<fc::exception_ptr, chain_apis::read_write::push_transaction_results>& result) {
if (result.contains<fc::exception_ptr>()) {
try {
result.get<fc::exception_ptr>()->dynamic_rethrow_exception();
} FC_LOG_AND_DROP()
fc_elog(logger,"push cashconfirm transaction failed, cash_trx_id: ${id}, ${s} succeed, ${l} left",("id",params->at(index).cash_trx_id)("s",index)("l",params->size() - index));
return;
} else {
auto trx_id = result.get<chain_apis::read_write::push_transaction_results>().transaction_id;
fc_dlog(logger,"pushed cashconfirm transaction: ${id}, index ${idx}", ( "id", trx_id )("idx", index));
}
int next_index = index + 1;
if (next_index < params->size()) {
push_cashconfirm_recurse( next_index, params );
} else {
fc_dlog(logger,"successfully pushed all ${sum} cashconfirm transactions, which belongs to blocks [${f},${t}]",
("sum",params->size())("f",params->front().cash_trx_block_num)("t",params->back().cash_trx_block_num));
}
};
auto par = params->at(index);
auto actn = get_action( account, N(cashconfirm), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("from_chain", par.from_chain)
("cash_trx_id", par.cash_trx_id)
("cash_trx_packed_trx_receipt", par.cash_trx_packed_trx_receipt)
("cash_trx_merkle_path", par.cash_trx_merkle_path)
("cash_trx_block_num", par.cash_trx_block_num)
("cash_trx_block_header", par.cash_trx_block_header)
("cash_trx_block_id_merkle_path",par.cash_trx_block_id_merkle_path)
("anchor_block_num", par.anchor_block_num)
("orig_trx_id", par.orig_trx_id));
if ( ! actn.valid() ){
fc_elog(logger,"get cashconfirm action failed");
return;
}
auto trx_opt = generate_signed_transaction_from_action( *actn );
if ( ! trx_opt.valid() ){
fc_elog(logger,"generate_signed_transaction_from_action failed");
return;
}
my_impl->chain_plug->get_read_write_api().push_transaction_v2( fc::variant_object(mvo(packed_transaction(*trx_opt))), next );
}
void ibc_token_contract::push_cashconfirm_trxs( const std::vector<ibc_trx_rich_info>& params, uint64_t start_seq_num ) {
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ) {
fc_elog(logger,"internal error! peerchain_name is empty");
return;
}
std::vector<cashconfirm_action_params> actions;
uint64_t next_seq_num = start_seq_num;
for ( const auto& trx : params ){
auto opt_cash = get_cash_action_params( trx.packed_trx_receipt );
if ( ! opt_cash.valid() ){
fc_elog(logger,"failed to get cash action parameters from packed_trx_receipt");
return;
}
cash_action_params cash_params = *opt_cash;
transaction_id_type orig_trx_id;
auto opt_orig = get_original_action_params( cash_params.orig_trx_packed_trx_receipt, &orig_trx_id );
if ( ! opt_orig.valid() ){
fc_elog(logger,"failed to get original action parameters from orig_trx_packed_trx_receipt");
return;
}
transfer_action_type orig_params = *opt_orig;
if ( cash_params.seq_num != next_seq_num ){
fc_elog(logger,"cash_params.seq_num ${n1} != next_seq_num ${n2}", ("n1",cash_params.seq_num)("n2",next_seq_num));
return;
}
cashconfirm_action_params par;
par.from_chain = peerchain_name;
par.cash_trx_id = trx.trx_id;
par.cash_trx_packed_trx_receipt = trx.packed_trx_receipt;
par.cash_trx_merkle_path = trx.trx_merkle_path;
par.cash_trx_block_num = trx.block_num;
par.cash_trx_block_header = trx.block_header;
par.cash_trx_block_id_merkle_path = trx.block_id_merkle_path;
par.anchor_block_num = trx.anchor_block_num;
par.orig_trx_id = orig_trx_id;
actions.push_back( par );
next_seq_num += 1;
}
if ( actions.empty() ){
return;
}
try {
EOS_ASSERT( actions.size() <= 1000, too_many_tx_at_once, "Attempt to push too many transactions at once" );
auto params_copy = std::make_shared<std::vector<cashconfirm_action_params>>(actions.begin(), actions.end());
push_cashconfirm_recurse( 0, params_copy );
} FC_LOG_AND_DROP()
}
void ibc_token_contract::cash( const cash_action_params& par ){
auto actn = get_action( account, N(cash), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("seq_num", par.seq_num)
("from_chain", par.from_chain)
("orig_trx_id", par.orig_trx_id)
("orig_trx_packed_trx_receipt", par.orig_trx_packed_trx_receipt)
("orig_trx_merkle_path", par.orig_trx_merkle_path)
("orig_trx_block_num", par.orig_trx_block_num)
("orig_trx_block_header", par.orig_trx_block_header)
("orig_trx_block_id_merkle_path",par.orig_trx_block_id_merkle_path)
("anchor_block_num", par.anchor_block_num)
("to", par.to)
("quantity", par.quantity)
("memo", par.memo)
("relay", my_impl->relay));
if ( ! actn.valid() ){
fc_elog(logger,"cash: get action failed");
return;
}
push_action( *actn );
}
void ibc_token_contract::cashconfirm( const cashconfirm_action_params& par ){
auto actn = get_action( account, N(cashconfirm), vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("from_chain", par.from_chain)
("cash_trx_id", par.cash_trx_id)
("cash_trx_packed_trx_receipt", par.cash_trx_packed_trx_receipt)
("cash_trx_merkle_path", par.cash_trx_merkle_path)
("cash_trx_block_num", par.cash_trx_block_num)
("cash_trx_block_header", par.cash_trx_block_header)
("cash_trx_block_id_merkle_path",par.cash_trx_block_id_merkle_path)
("anchor_block_num", par.anchor_block_num)
("orig_trx_id", par.orig_trx_id));
if ( ! actn.valid() ){
fc_elog(logger,"cash: get action failed");
return;
}
push_action( *actn );
}
void ibc_token_contract::push_rborrm_recurse( int index, const std::shared_ptr<std::vector<transaction_id_type>>& params, name action_name){
auto peerchain_name = peer_chain_name();
if ( peerchain_name == name() ) {
fc_elog(logger,"internal error! peerchain_name is empty");
return;
}
auto next = [=](const fc::static_variant<fc::exception_ptr, chain_apis::read_write::push_transaction_results>& result) {
if (result.contains<fc::exception_ptr>()) {
try {
result.get<fc::exception_ptr>()->dynamic_rethrow_exception();
} FC_LOG_AND_DROP()
fc_elog(logger,"push rollback transaction failed, index ${idx}", ("idx", index));
} else {
auto trx_id = result.get<chain_apis::read_write::push_transaction_results>().transaction_id;
fc_dlog(logger,"pushed rollback transaction: ${id}, index ${idx}", ( "id", trx_id )("idx", index));
}
int next_index = index + 1;
if (next_index < params->size()) {
push_rborrm_recurse( next_index, params, action_name );
}
};
auto trx_id = params->at(index);
auto actn = get_action( account, action_name, vector<permission_level>{{ my_impl->relay, config::active_name}}, mvo()
("peerchain_name", peerchain_name)
("trx_id", trx_id)
("relay", my_impl->relay));
if ( ! actn.valid() ){
fc_elog(logger,"newsection: get action failed");
return;
}
auto trx_opt = generate_signed_transaction_from_action( *actn );
if ( ! trx_opt.valid() ){
fc_elog(logger,"generate_signed_transaction_from_action failed");
return;
}
my_impl->chain_plug->get_read_write_api().push_transaction_v2( fc::variant_object(mvo(packed_transaction(*trx_opt))), next );
}
void ibc_token_contract::rollback( const std::vector<transaction_id_type> trxs ){
if ( trxs.empty() ){
return;
}
try {
EOS_ASSERT( trxs.size() <= 1000, too_many_tx_at_once, "Attempt to push too many transactions at once" );
auto params_copy = std::make_shared<std::vector<transaction_id_type>>(trxs.begin(), trxs.end());
push_rborrm_recurse( 0, params_copy, N(rollback) );
} FC_LOG_AND_DROP()
}
void ibc_token_contract::rmunablerb( const std::vector<transaction_id_type> trxs ){
if ( trxs.empty() ){
return;
}
try {
EOS_ASSERT( trxs.size() <= 1000, too_many_tx_at_once, "Attempt to push too many transactions at once" );
auto params_copy = std::make_shared<std::vector<transaction_id_type>>(trxs.begin(), trxs.end());
push_rborrm_recurse( 0, params_copy, N(rmunablerb) );
} FC_LOG_AND_DROP()
}
// --------------- connection ---------------
connection::connection(string endpoint)
: server_ioc( app().get_io_service() ),
strand( app().get_io_service() ),
socket( std::make_shared<tcp::socket>( app().get_io_service() ) ),
node_id(),
last_handshake_recv(),
last_handshake_sent(),
sent_handshake_count(0),
connecting(false),
protocol_version(0),
peer_addr(endpoint),
response_expected(),
read_delay_timer(),
no_retry(no_reason)
{
fc_ilog( logger, "created connection to ${n}", ("n", endpoint) );
initialize();
}
connection::connection( socket_ptr s )
: server_ioc( app().get_io_service() ),
strand( app().get_io_service() ),
socket( s ),
node_id(),
last_handshake_recv(),
last_handshake_sent(),
sent_handshake_count(0),
connecting(true),
protocol_version(0),
peer_addr(),
response_expected(),
read_delay_timer(),
no_retry(no_reason)
{
fc_ilog( logger, "accepted network connection" );
initialize();
}
connection::~connection() {}
void connection::initialize() {
auto *rnd = node_id.data();
rnd[0] = 0;
response_expected.reset(new boost::asio::steady_timer( app().get_io_service() ));
read_delay_timer.reset(new boost::asio::steady_timer( app().get_io_service() ));
}
bool connection::connected() {
return (socket && socket->is_open() && !connecting);
}
bool connection::current() {
return connected();
}
void connection::reset() {}
void connection::flush_queues() {
buffer_queue.clear_write_queue();
}
void connection::close() {
if(socket) {
socket->close();
socket.reset( new tcp::socket( app().get_io_service() ) );
}
else {
fc_wlog( logger, "no socket to close!" );
}
flush_queues();
connecting = false;
reset();
sent_handshake_count = 0;
node_id = fc::sha256();
last_handshake_recv = handshake_message();
last_handshake_sent = handshake_message();
fc_dlog(logger, "canceling wait on ${p}", ("p",peer_name()));
cancel_wait();
if( read_delay_timer ) read_delay_timer->cancel();
}
void connection::send_handshake() {
handshake_initializer::populate(last_handshake_sent);
last_handshake_sent.generation = ++sent_handshake_count;
fc_dlog(logger, "Sending handshake generation ${g} to ${ep}",
("g",last_handshake_sent.generation)("ep", peer_name()));
enqueue(last_handshake_sent);
}
void connection::send_time() {
time_message xpkt;
xpkt.org = rec;
xpkt.rec = dst;
xpkt.xmt = get_time();
org = xpkt.xmt;
enqueue(xpkt);
}
void connection::send_time(const time_message& msg) {
time_message xpkt;
xpkt.org = msg.xmt;
xpkt.rec = msg.dst;
xpkt.xmt = get_time();
enqueue(xpkt);
}
void connection::queue_write(const std::shared_ptr<vector<char>>& buff,
bool trigger_send,
int priority,
std::function<void(boost::system::error_code, std::size_t)> callback,
bool to_sync_queue) {
if( !buffer_queue.add_write_queue( buff, callback, to_sync_queue )) {
fc_wlog( logger, "write_queue full ${s} bytes, giving up on connection ${p}",
("s", buffer_queue.write_queue_size())("p", peer_name()) );
my_impl->close( shared_from_this() );
return;
}
if( buffer_queue.is_out_queue_empty() && trigger_send) {
do_queue_write( priority );
}
}
void connection::do_queue_write(int priority) {
if( !buffer_queue.ready_to_send() )
return;
connection_wptr c(shared_from_this());
if(!socket->is_open()) {
fc_elog(logger,"socket not open to ${p}",("p",peer_name()));
my_impl->close(c.lock());
return;
}
std::vector<boost::asio::const_buffer> bufs;
buffer_queue.fill_out_buffer( bufs );
boost::asio::async_write(*socket, bufs,
boost::asio::bind_executor(strand, [c, socket=socket, priority]( boost::system::error_code ec, std::size_t w ) {
app().post(priority, [c, priority, ec, w]() {
try {
auto conn = c.lock();
if(!conn)
return;
conn->buffer_queue.out_callback( ec, w );
if(ec) {
string pname = conn ? conn->peer_name() : "no connection name";
if( ec.value() != boost::asio::error::eof) {
fc_elog( logger, "Error sending to peer ${p}: ${i}", ("p",pname)("i", ec.message()) );
}
else {
fc_wlog( logger, "connection closure detected on write to ${p}",("p",pname) );
}
my_impl->close(conn);
return;
}
conn->buffer_queue.clear_out_queue();
conn->do_queue_write( priority );
}
catch(const std::exception &ex) {
auto conn = c.lock();
string pname = conn ? conn->peer_name() : "no connection name";
fc_elog( logger,"Exception in do_queue_write to ${p} ${s}", ("p",pname)("s",ex.what()) );
}
catch(const fc::exception &ex) {
auto conn = c.lock();
string pname = conn ? conn->peer_name() : "no connection name";
fc_elog( logger,"Exception in do_queue_write to ${p} ${s}", ("p",pname)("s",ex.to_string()) );
}
catch(...) {
auto conn = c.lock();
string pname = conn ? conn->peer_name() : "no connection name";
fc_elog( logger,"Exception in do_queue_write to ${p}", ("p",pname) );
}
});
}));
}
void connection::cancel_sync(go_away_reason reason) {
fc_dlog(logger,"cancel sync reason = ${m}, write queue size ${o} bytes peer ${p}",
("m",reason_str(reason)) ("o", buffer_queue.write_queue_size())("p", peer_name()));
cancel_wait();
flush_queues();
switch (reason) {
case validation :
case fatal_other : {
no_retry = reason;
enqueue( go_away_message( reason ));
break;
}
default:
fc_dlog(logger, "sending empty request but not calling sync wait on ${p}", ("p",peer_name()));
}
}
void connection::enqueue( const ibc_message& m, bool trigger_send ) {
go_away_reason close_after_send = no_reason;
if (m.contains<go_away_message>()) {
close_after_send = m.get<go_away_message>().reason;
}
const uint32_t payload_size = fc::raw::pack_size( m );
const char* const header = reinterpret_cast<const char* const>(&payload_size); // avoid variable size encoding of uint32_t
constexpr size_t header_size = sizeof(payload_size);
static_assert( header_size == message_header_size, "invalid message_header_size" );
const size_t buffer_size = header_size + payload_size;
auto send_buffer = std::make_shared<vector<char>>(buffer_size);
fc::datastream<char*> ds( send_buffer->data(), buffer_size);
ds.write( header, header_size );
fc::raw::pack( ds, m );
enqueue_buffer( send_buffer, trigger_send, priority::low, close_after_send );
}
void connection::enqueue_buffer( const std::shared_ptr<std::vector<char>>& send_buffer,
bool trigger_send, int priority, go_away_reason close_after_send,
bool to_sync_queue)
{
connection_wptr weak_this = shared_from_this();
queue_write(send_buffer,trigger_send, priority,
[weak_this, close_after_send](boost::system::error_code ec, std::size_t ) {
connection_ptr conn = weak_this.lock();
if (conn) {
if (close_after_send != no_reason) {
fc_elog( logger, "sent a go away message: ${r}, closing connection to ${p}",
("r", reason_str(close_after_send))("p", conn->peer_name()) );
my_impl->close(conn);
return;
}
} else {
fc_wlog(logger, "connection expired before enqueued ibc_message called callback!");
}
},
to_sync_queue);
}
void connection::cancel_wait() {
if (response_expected)
response_expected->cancel();
}
const string connection::peer_name() {
if( !last_handshake_recv.p2p_address.empty() ) {
return last_handshake_recv.p2p_address;
}
if( !peer_addr.empty() ) {
return peer_addr;
}
if( socket != nullptr ) {
boost::system::error_code ec;
auto rep = socket->remote_endpoint(ec);
if( !ec ) {
return rep.address().to_string() + ':' + std::to_string( rep.port() );
}
}
return "connecting client";
}
// --------------- ibc_plugin_impl ---------------
void ibc_plugin_impl::connect(const connection_ptr& c ) {
if( c->no_retry != go_away_reason::no_reason) {
fc_dlog( logger, "Skipping connect due to go_away reason ${r}",("r", reason_str( c->no_retry )));
return;
}
auto colon = c->peer_addr.find(':');
if (colon == std::string::npos || colon == 0) {
fc_elog( logger, "Invalid peer address. must be \"host:port\": ${p}", ("p",c->peer_addr) );
for ( auto itr : connections ) {
if((*itr).peer_addr == c->peer_addr) {
(*itr).reset();
close(itr);
connections.erase(itr);
break;
}
}
return;
}
shared_ptr<tcp::resolver> resolver = std::make_shared<tcp::resolver>( app().get_io_service() );
c->strand.post( [this, c, resolver{std::move(resolver)}](){
auto colon = c->peer_addr.find(':');
auto host = c->peer_addr.substr( 0, colon );
auto port = c->peer_addr.substr( colon + 1);
idump((host)(port));
// Note: need to add support for IPv6 too
tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str() );
connection_wptr weak_conn = c;
resolver->async_resolve( query, boost::asio::bind_executor( c->strand,
[weak_conn, resolver, this]( const boost::system::error_code& err, tcp::resolver::results_type endpoints ) {
app().post( priority::low, [err, resolver, endpoints, weak_conn, this]() {
auto c = weak_conn.lock();
if( !c ) return;
if( !err ) {
connect( c, resolver, endpoints );
} else {
fc_elog( logger, "Unable to resolve ${peer_addr}: ${error}",
("peer_addr", c->peer_name())( "error", err.message()) );
}
} );
} ) );
} );
}
void ibc_plugin_impl::connect( const connection_ptr& c, const std::shared_ptr<tcp::resolver>& resolver, tcp::resolver::results_type endpoints ) {
if( c->no_retry != go_away_reason::no_reason) {
string rsn = reason_str(c->no_retry);
return;
}
c->connecting = true;
c->pending_message_buffer.reset();
c->buffer_queue.clear_out_queue();
connection_wptr weak_conn = c;
boost::asio::async_connect( *c->socket, endpoints,
boost::asio::bind_executor( c->strand,
[weak_conn, resolver, socket=c->socket, this]( const boost::system::error_code& err, const tcp::endpoint& endpoint ) {
app().post( priority::low, [weak_conn, this, err]() {
auto c = weak_conn.lock();
if( !c ) return;
if( !err && c->socket->is_open()) {
if( start_session( c )) {
c->send_handshake();
}
} else {
elog( "connection failed to ${peer}: ${error}", ("peer", c->peer_name())( "error", err.message()) );
c->connecting = false;
my_impl->close( c );
}
} );
} ) );
}
bool ibc_plugin_impl::start_session(const connection_ptr& con ) {
boost::asio::ip::tcp::no_delay nodelay( true );
boost::system::error_code ec;
con->socket->set_option( nodelay, ec );
if (ec) {
fc_elog( logger, "connection failed to ${peer}: ${error}", ( "peer", con->peer_name())("error",ec.message()) );
con->connecting = false;
close(con);
return false;
}
else {
start_read_message( con );
++started_sessions;
return true;
}
}
void ibc_plugin_impl::start_listen_loop() {
auto socket = std::make_shared<tcp::socket>( app().get_io_service() );
acceptor->async_accept( *socket, [socket, this]( boost::system::error_code ec ) {
app().post( priority::low, [socket, this, ec]() {
if( !ec ) {
uint32_t visitors = 0;
uint32_t from_addr = 0;
boost::system::error_code rec;
auto paddr = socket->remote_endpoint(rec).address();
if (rec) {
fc_elog(logger,"Error getting remote endpoint: ${m}",("m", rec.message()));
}
else {
for (auto &conn : connections) {
if(conn->socket->is_open()) {
if (conn->peer_addr.empty()) {
visitors++;
boost::system::error_code ec;
if (paddr == conn->socket->remote_endpoint(ec).address()) {
from_addr++;
}
}
}
}
if (num_clients != visitors) {
fc_ilog( logger,"checking max client, visitors = ${v} num clients ${n}",("v",visitors)("n",num_clients) );
num_clients = visitors;
}
if( from_addr < max_nodes_per_host && (max_client_count == 0 || num_clients < max_client_count )) {
++num_clients;
connection_ptr c = std::make_shared<connection>( socket );
connections.insert( c );
start_session( c );
}
else {
if (from_addr >= max_nodes_per_host) {
fc_elog(logger, "Number of connections (${n}) from ${ra} exceeds limit",
("n", from_addr+1)("ra",paddr.to_string()));
}
else {
fc_elog(logger, "Error max_client_count ${m} exceeded",
( "m", max_client_count) );
}
socket->close();
}
}
} else {
fc_elog( logger, "Error accepting connection: ${m}",( "m", ec.message() ) );
// For the listed error codes below, recall start_listen_loop()
switch (ec.value()) {
case ECONNABORTED:
case EMFILE:
case ENFILE:
case ENOBUFS:
case ENOMEM:
case EPROTO:
break;
default:
return;
}
}
start_listen_loop();
});
});
}
void ibc_plugin_impl::start_read_message(const connection_ptr& conn) {
try {
if(!conn->socket) {
return;
}
connection_wptr weak_conn = conn;
std::size_t minimum_read = conn->outstanding_read_bytes ? *conn->outstanding_read_bytes : message_header_size;
if (use_socket_read_watermark) {
const size_t max_socket_read_watermark = 4096;
std::size_t socket_read_watermark = std::min<std::size_t>(minimum_read, max_socket_read_watermark);
boost::asio::socket_base::receive_low_watermark read_watermark_opt(socket_read_watermark);
conn->socket->set_option(read_watermark_opt);
}
auto completion_handler = [minimum_read](boost::system::error_code ec, std::size_t bytes_transferred) -> std::size_t {
if (ec || bytes_transferred >= minimum_read ) {
return 0;
} else {
return minimum_read - bytes_transferred;
}
};
if( conn->buffer_queue.write_queue_size() > def_max_write_queue_size )
{
// too much queued up, reschedule
if( conn->buffer_queue.write_queue_size() > def_max_write_queue_size ) {
peer_wlog( conn, "write_queue full ${s} bytes", ("s", conn->buffer_queue.write_queue_size()) );
}
if( conn->buffer_queue.write_queue_size() > 2*def_max_write_queue_size )
{
fc_elog( logger, "queues over full, giving up on connection ${p}", ("p", conn->peer_name()) );
fc_elog( logger, " write_queue ${s} bytes", ("s", conn->buffer_queue.write_queue_size()) );
my_impl->close( conn );
return;
}
if( !conn->read_delay_timer ) return;
conn->read_delay_timer->expires_from_now( def_read_delay_for_full_write_queue );
conn->read_delay_timer->async_wait( [this, weak_conn]( boost::system::error_code ec ) {
app().post( priority::low, [this, weak_conn, ec]() {
auto conn = weak_conn.lock();
if( !conn ) return;
if( !ec ) {
start_read_message( conn );
} else {
fc_elog( logger, "Read delay timer error: ${e}, closing connection: ${p}",
("e", ec.message())("p",conn->peer_name()) );
close( conn );
}
} );
} );
return;
}
boost::asio::async_read(*conn->socket,
conn->pending_message_buffer.get_buffer_sequence_for_boost_async_read(), completion_handler,
boost::asio::bind_executor( conn->strand,
[this,weak_conn,socket=conn->socket]( boost::system::error_code ec, std::size_t bytes_transferred ) {
app().post( priority::medium, [this,weak_conn, socket, ec, bytes_transferred]() {
auto conn = weak_conn.lock();
if (!conn || !conn->socket || !conn->socket->is_open() || !socket->is_open()) {
return;
}
conn->outstanding_read_bytes.reset();
try {
if( !ec ) {
if (bytes_transferred > conn->pending_message_buffer.bytes_to_write()) {
fc_elog( logger,"async_read_some callback: bytes_transfered = ${bt}, buffer.bytes_to_write = ${btw}",
("bt",bytes_transferred)("btw",conn->pending_message_buffer.bytes_to_write()) );
}
EOS_ASSERT(bytes_transferred <= conn->pending_message_buffer.bytes_to_write(), plugin_exception, "");
conn->pending_message_buffer.advance_write_ptr(bytes_transferred);
while (conn->pending_message_buffer.bytes_to_read() > 0) {
uint32_t bytes_in_buffer = conn->pending_message_buffer.bytes_to_read();
if (bytes_in_buffer < message_header_size) {
conn->outstanding_read_bytes.emplace(message_header_size - bytes_in_buffer);
break;
} else {
uint32_t message_length;
auto index = conn->pending_message_buffer.read_index();
conn->pending_message_buffer.peek(&message_length, sizeof(message_length), index);
if(message_length > def_send_buffer_size*2 || message_length == 0) {
boost::system::error_code ec;
fc_elog( logger,"incoming message length unexpected (${i}), from ${p}",
("i", message_length)("p",boost::lexical_cast<std::string>(conn->socket->remote_endpoint(ec))) );
close(conn);
return;
}
auto total_message_bytes = message_length + message_header_size;
if (bytes_in_buffer >= total_message_bytes) {
conn->pending_message_buffer.advance_read_ptr(message_header_size);
if (!process_next_message(conn, message_length)) {
return;
}
} else {
auto outstanding_message_bytes = total_message_bytes - bytes_in_buffer;
auto available_buffer_bytes = conn->pending_message_buffer.bytes_to_write();
if (outstanding_message_bytes > available_buffer_bytes) {
conn->pending_message_buffer.add_space( outstanding_message_bytes - available_buffer_bytes );
}
conn->outstanding_read_bytes.emplace(outstanding_message_bytes);
break;
}
}
}
start_read_message(conn);
} else {
auto pname = conn->peer_name();
if (ec.value() != boost::asio::error::eof) {
fc_elog( logger, "Error reading message from ${p}: ${m}",("p",pname)( "m", ec.message() ) );
} else {
fc_ilog( logger, "Peer ${p} closed connection",("p",pname) );
}
close( conn );
}
}
catch(const std::exception &ex) {
fc_elog( logger, "Exception in handling read data from ${p}: ${s}",
("p",conn->peer_name())("s",ex.what()) );
close( conn );
}
catch(const fc::exception &ex) {
fc_elog( logger, "Exception in handling read data from ${p}: ${s}",
("p",conn->peer_name())("s",ex.to_string()) );
close( conn );
}
catch (...) {
fc_elog( logger, "Undefined exception handling the read data from ${p}",( "p",conn->peer_name()) );
close( conn );
}
});
}));
} catch (...) {
string pname = conn ? conn->peer_name() : "no connection name";
fc_elog( logger, "Undefined exception handling reading ${p}",("p",pname) );
close( conn );
}
}
bool ibc_plugin_impl::process_next_message(const connection_ptr& conn, uint32_t message_length) {
try {
auto ds = conn->pending_message_buffer.create_datastream();
ibc_message msg;
fc::raw::unpack( ds, msg );
msg_handler m( *this, conn );
msg.visit( m );
} catch( const fc::exception& e ) {
fc_elog( logger, "Exception in handling message from ${p}: ${s}",
("p", conn->peer_name())("s", e.to_detail_string()) );
close( conn );
return false;
}
return true;
}
size_t ibc_plugin_impl::count_open_sockets() const {
size_t count = 0;
for( auto &c : connections) {
if(c->socket->is_open())
++count;
}
return count;
}
void ibc_plugin_impl::irreversible_block(const block_state_ptr& block) {
/* fc_dlog(logger,"signaled, block: ${n}, id: ${id}",("n", block->block_num)("id", block->id)); */
blockroot_merkle_type brtm;
brtm.block_num = block->block_num;
brtm.merkle = block->blockroot_merkle;
blockroot_merkle_cache.push_back( brtm );
if ( blockroot_merkle_cache.size() > 3600*BlocksPerSecond * 2 ){ // two hour
blockroot_merkle_cache.erase( blockroot_merkle_cache.begin() );
}
}
bool ibc_plugin_impl::is_valid( const handshake_message &msg) {
// Do some basic validation of an incoming handshake_message, so things
// that really aren't handshake messages can be quickly discarded without
// affecting state.
bool valid = true;
if (msg.last_irreversible_block_num > msg.head_num) {
fc_wlog( logger, "Handshake message validation: last irreversible block (${i}) is greater than head block (${h})",
("i", msg.last_irreversible_block_num)("h", msg.head_num) );
valid = false;
}
if (msg.p2p_address.empty()) {
fc_wlog( logger, "Handshake message validation: p2p_address is null string" );
valid = false;
}
if (msg.os.empty()) {
fc_wlog( logger, "Handshake message validation: os field is null string" );
valid = false;
}
if ((msg.sig != chain::signature_type() || msg.token != sha256()) && (msg.token != fc::sha256::hash(msg.time))) {
fc_wlog( logger, "Handshake message validation: token field invalid" );
valid = false;
}
return valid;
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const handshake_message& msg) {
peer_ilog(c, "received handshake_message");
if (!is_valid(msg)) {
peer_elog( c, "bad handshake message");
c->enqueue( go_away_message( fatal_other ));
return;
}
if( c->connecting ) {
c->connecting = false;
}
if (msg.generation == 1) {
if( msg.node_id == node_id) {
fc_elog( logger, "Self connection detected. Closing connection" );
c->enqueue( go_away_message( self ) );
return;
}
if( c->peer_addr.empty() || c->last_handshake_recv.node_id == fc::sha256()) {
fc_dlog(logger, "checking for duplicate" );
for(const auto &check : connections) {
if(check == c)
continue;
if(check->connected() && check->peer_name() == msg.p2p_address) {
// It's possible that both peers could arrive here at relatively the same time, so
// we need to avoid the case where they would both tell a different connection to go away.
// Using the sum of the initial handshake times of the two connections, we will
// arbitrarily (but consistently between the two peers) keep one of them.
if (msg.time + c->last_handshake_sent.time <= check->last_handshake_sent.time + check->last_handshake_recv.time)
continue;
fc_dlog( logger, "sending go_away duplicate to ${ep}", ("ep",msg.p2p_address) );
go_away_message gam(duplicate);
gam.node_id = node_id;
c->enqueue(gam);
c->no_retry = duplicate;
return;
}
}
}
else {
fc_dlog(logger, "skipping duplicate check, addr == ${pa}, id = ${ni}",("pa",c->peer_addr)("ni",c->last_handshake_recv.node_id));
}
//if( msg.chain_id != peerchain_id) {
// fc_elog(logger,"Peer chain id not correct. Closing connection");
// c->enqueue( go_away_message(go_away_reason::wrong_chain) );
// return;
//}
c->protocol_version = msg.network_version;
if(c->protocol_version != net_version) {
if (network_version_match) {
fc_elog( logger, "Peer network version does not match expected ${nv} but got ${mnv}",
("nv", net_version)("mnv", c->protocol_version) );
c->enqueue(go_away_message(wrong_version));
return;
} else {
fc_ilog( logger, "Local network version: ${nv} Remote version: ${mnv}",
("nv", net_version)("mnv", c->protocol_version));
}
}
if( c->node_id != msg.node_id) {
c->node_id = msg.node_id;
}
if(!authenticate_peer(msg)) {
fc_elog( logger, "Peer not authenticated. Closing connection." );
c->enqueue(go_away_message(authentication));
return;
}
if (c->sent_handshake_count == 0) {
c->send_handshake();
}
}
c->last_handshake_recv = msg;
c->_logger_variant.reset();
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const go_away_message& msg) {
peer_wlog(c, "received go_away_message, reason = ${r}", ("r",reason_str( msg.reason )) );
c->no_retry = msg.reason;
if(msg.reason == duplicate ) {
c->node_id = msg.node_id;
}
c->flush_queues();
close(c);
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const time_message& msg) {
peer_ilog(c, "received time_message");
/* We've already lost however many microseconds it took to dispatch
* the message, but it can't be helped.
*/
msg.dst = c->get_time();
// If the transmit timestamp is zero, the peer is horribly broken.
if(msg.xmt == 0)
return; /* invalid timestamp */
if(msg.xmt == c->xmt)
return; /* duplicate packet */
c->xmt = msg.xmt;
c->rec = msg.rec;
c->dst = msg.dst;
if(msg.org == 0)
{
c->send_time(msg);
return; // We don't have enough data to perform the calculation yet.
}
c->offset = (double(c->rec - c->org) + double(msg.xmt - c->dst)) / 2;
double NsecPerUsec{1000};
if(logger.is_enabled(fc::log_level::all))
logger.log(FC_LOG_MESSAGE(all, "Clock offset is ${o}ns (${us}us)", ("o", c->offset)("us", c->offset/NsecPerUsec)));
c->org = 0;
c->rec = 0;
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const ibc_heartbeat_message &msg ) {
peer_dlog(c, "received ibc_heartbeat_message");
fc_ilog(logger,"received msg: origtrxs_table_id_range [${of},${ot}] cashtrxs_table_seq_num_range [${cf},${ct}] new_producers_block_num ${n}, lwcls_range [${lsf},${lst}]",
("of",msg.origtrxs_table_id_range.first)("ot",msg.origtrxs_table_id_range.second)
("cf",msg.cashtrxs_table_seq_num_range.first)("ct",msg.cashtrxs_table_seq_num_range.second)
("n",msg.new_producers_block_num)("lsf",msg.lwcls.first_num)("lst",msg.lwcls.last_num));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
// step one: check ibc_chain_state and lwcls
if ( msg.ibc_chain_state == deployed ) { // send lwc_init_message
controller &cc = chain_plug->chain();
uint32_t head_num = cc.fork_db_head_block_num();
int depth = 64;
block_state_ptr p;
while ( p == block_state_ptr() && depth >= 0 ){
uint32_t check_num = head_num - depth;
p = cc.fetch_block_state_by_number( check_num );
if ( p == block_state_ptr() ){
fc_ilog(logger,"didn't get block_state_ptr of block num: ${n}", ("n", check_num ));
}else{
break;
}
if ( depth > 8 ){
depth /= 2;
} else {
--depth;
}
}
if ( p == block_state_ptr() ){
fc_ilog(logger,"didn't get any block state finally, wait");
return;
}
if ( p->pending_schedule.schedule.version != p->active_schedule.version ){
fc_ilog(logger,"pending_schedule version not equal to active_schedule version, wait until equal");
return;
}
lwc_init_message msg;
msg.header = p->header;
msg.active_schedule = p->active_schedule;
msg.blockroot_merkle = p->blockroot_merkle;
peer_ilog(c,"send lwc_init_message");
c->enqueue( msg, true);
} else if ( msg.ibc_chain_state == working ){ // validate and update local lwcls_info
auto check_id = [=](uint32_t block_num, block_id_type id) -> bool {
if ( block_num == 0 || block_num > chain_plug->chain().head_block_num() ){
return false;
}
try {
auto ret_id = my_impl->chain_plug->chain().get_block_id_for_num(block_num);
return ret_id == id;
} FC_LOG_AND_DROP()
return false;
};
bool valid = false;
if (check_id(msg.lwcls.first_num, msg.lwcls.first_id)) {
if (msg.lwcls.valid && msg.lwcls.lib_num != 0 ) {
if (check_id(msg.lwcls.lib_num, msg.lwcls.lib_id)) {
valid = true;
} else {
valid = false;
}
}
valid = true;
}
if ( valid ) {
c->lwcls_info = msg.lwcls;
c->lwcls_info_update_time = fc::time_point::now();
} else {
c->lwcls_info = lwc_section_type();
c->lwcls_info_update_time = fc::time_point();
peer_elog(c,"received invalid ibc_heartbeat_message::lwcls");
idump((msg.lwcls));
}
}
// step two: check origtrxs_table_id_range
if ( msg.origtrxs_table_id_range != range_type() ){
ibc_trxs_request_message request;
request.table = N(origtrxs);
if ( local_origtrxs.size() == 0 ){
request.range = msg.origtrxs_table_id_range;
} else if ( local_origtrxs.rbegin()->table_id < msg.origtrxs_table_id_range.second ) {
request.range.first = local_origtrxs.rbegin()->table_id + 1;
request.range.second = msg.origtrxs_table_id_range.second;
}
if ( request.range != range_type() ){
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c,"send ibc_trxs_request_message, origtrxs id range:[${f},${t}]", ("f",request.range.first)("t",request.range.second));
c->enqueue( request );
}
}
}
}
// step three: check cashtrxs_table_id_range
if ( msg.cashtrxs_table_seq_num_range != range_type() ) {
ibc_trxs_request_message request;
request.table = N(cashtrxs);
if (local_cashtrxs.size() == 0) {
auto gm_opt = token_contract->get_peer_chain_mutable();
if ( !gm_opt.valid() ){
fc_elog(logger,"internal error, failed to get global_mutable_singleton");
return;
}
if( msg.cashtrxs_table_seq_num_range.second >= gm_opt->cash_seq_num + 1 ){
request.range.first = gm_opt->cash_seq_num + 1;
request.range.second = msg.cashtrxs_table_seq_num_range.second;
}
} else if (local_cashtrxs.rbegin()->table_id < msg.cashtrxs_table_seq_num_range.second) {
request.range.first = local_cashtrxs.rbegin()->table_id + 1;
request.range.second = msg.cashtrxs_table_seq_num_range.second;
}
if ( request.range != range_type() ) {
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c,"send ibc_trxs_request_message, cashtrxs id range:[${f},${t}]", ("f", request.range.first)("t", request.range.second));
c->enqueue( request );
}
}
}
}
// step four: check new_producers_block_num
if ( msg.new_producers_block_num ){
new_prod_blk_num = msg.new_producers_block_num;
}
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const lwc_init_message &msg) {
peer_dlog(c, "received lwc_init_message");
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
chain_contract->get_contract_state();
if ( chain_contract->state == deployed && chain_contract->lwc_config_valid() ){
chain_contract->chain_init( msg );
}
}
incremental_merkle get_blockroot_merkle_by_num( uint32_t check_num ){
incremental_merkle empty;
// search from forkdb
auto bsp = my_impl->chain_plug->chain().fetch_block_state_by_number( check_num );
if ( bsp != block_state_ptr() ){
return bsp->blockroot_merkle;
}
// search form cache
incremental_merkle mkl = my_impl->get_brtm_from_cache( check_num );
if ( mkl._node_count != 0 && mkl._active_nodes.size() > 0 ){
return mkl;
}
// calculate from known block, ( may happen when node restarted )
fc_ilog(logger,"didn't find blockroot_merkle of block ${n} in cache, calculate it by known blockroot_merkles",("n",check_num));
blockroot_merkle_type walk_point;
walk_point.block_num = check_num - ( check_num % 64 );
auto sbp = my_impl->chain_plug->chain().fetch_block_by_number( walk_point.block_num );
if ( sbp == signed_block_ptr() ){
fc_elog(logger,"walk_point block ${n} not exist", ("n", check_num));
return empty;
}
bool has_merkle_extension = false;
for( auto& ext : sbp->block_extensions ){
if ( ext.first == 0xF && ext.second.size() > 0 ){
has_merkle_extension = true;
walk_point.merkle = fc::raw::unpack<incremental_merkle>( ext.second );
break;
}
}
if ( ! has_merkle_extension ){
fc_elog(logger,"didn't find blockroot_merkle of block ${n} in block_log.dat, can't calculate block ${m}'s blockroot_merkle",("n",walk_point.block_num )("m",check_num));
return empty;
} else {
fc_dlog(logger,"calculate block ${n}'s blockroot_merkle from block ${m}",("n",check_num)("m",walk_point.block_num ));
}
uint32_t count = check_num - walk_point.block_num;
for( uint32_t i = 0; i < count; ++i ){
walk_point.merkle.append( my_impl->chain_plug->chain().get_block_id_for_num( walk_point.block_num ) );
walk_point.block_num++;
}
if (walk_point.block_num == check_num ){
return walk_point.merkle;
}
fc_elog(logger,"internal error, calculate blockroot_merkle of block ${n} failed", ("n",check_num));
return empty;
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const lwc_section_request_message &msg) {
peer_dlog(c, "received lwc_section_request_message [${from},${to}]",("from",msg.start_block_num)("to",msg.end_block_num));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
uint32_t rq_length = msg.end_block_num - msg.start_block_num + 1;
uint32_t lib_block_num = chain_plug->chain().last_irreversible_block_num();
if ( msg.start_block_num >= lib_block_num || rq_length == 0 ){
return;
}
if ( rq_length >= MaxSendSectionLength && lib_block_num - msg.start_block_num < MaxSendSectionLength ){
// fc_ilog(logger,"have not enough data");
return;
}
if ( rq_length < MaxSendSectionLength && msg.end_block_num > lib_block_num ) {
// fc_ilog(logger,"have not enough data");
return;
}
uint32_t end_num = std::min( lib_block_num, msg.end_block_num );
if ( msg.end_block_num > lib_block_num ){
end_num = msg.start_block_num + ((end_num - msg.start_block_num ) / MaxSendSectionLength) * MaxSendSectionLength;
}
for ( uint32_t start_num = msg.start_block_num; start_num < end_num; start_num += MaxSendSectionLength ){
lwc_section_data_message ret_msg;
uint32_t check_num = start_num;
auto sbp = chain_plug->chain().fetch_block_by_number(start_num);
if ( sbp == signed_block_ptr() ){
fc_elog(logger,"block ${n} not exist", ("n", start_num));
return;
}
auto inc_merkle = get_blockroot_merkle_by_num( start_num );
if ( inc_merkle._node_count == 0 ){
fc_elog(logger,"get blockroot_merkle of block ${n} failed", ("n", start_num));
return;
}
ret_msg.headers.push_back( *sbp );
ret_msg.blockroot_merkle = inc_merkle;
++check_num;
uint32_t tmp_end_num = std::min( start_num + MaxSendSectionLength - 1, end_num );
while ( check_num <= tmp_end_num ){
auto shr_ptr = chain_plug->chain().fetch_block_by_number( check_num );
if ( ! shr_ptr ){ fc_elog(logger,"fatal internal error, block ${n} not exist", ("n", check_num)); }
ret_msg.headers.push_back( * shr_ptr );
check_num += 1;
}
peer_ilog(c,"sending lwc_section_data_message, range [${from},${to}], merkle nodes ${nodes}", ("from",start_num)("to",tmp_end_num)("nodes",ret_msg.blockroot_merkle._active_nodes.size()));
c->enqueue( ret_msg );
return; // send only once
}
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const lwc_section_data_message &msg) {
peer_dlog(c, "received lwc_section_data_message [${from},${to}]",("from",msg.headers.front().block_num())("to",msg.headers.back().block_num()));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
auto p = chain_contract->get_sections_tb_reverse_nth_section();
if ( !p.valid() ){
fc_elog(logger,"can not get section info from ibc.chain contract");
return;
}
section_type ls = *p;
uint32_t msg_first_num = msg.headers.begin()->block_num();
uint32_t msg_last_num = msg.headers.rbegin()->block_num();
if( msg_last_num <= ls.last && msg.headers.rbegin()->id() == chain_contract->get_chaindb_tb_block_id_by_block_num(msg_last_num) ){
fc_ilog(logger,"lwc_section_data_message has no new data");
return;
}
if ( ls.valid && msg_last_num <= std::max(ls.first, ls.last - chain_contract->lwc_lib_depth) ){
fc_ilog(logger,"nothing to do");
return;
}
if ( msg_first_num == ls.last + 1 ){ // append directly
chain_contract->pushsection( msg );
return;
}
if( msg_first_num <= ls.last ) { // find fit number then append directly // todo review
// find the first block number, which id is same in msg and lwcls.
uint32_t check_num_first = std::min( uint32_t(ls.last), msg.headers.rbegin()->block_num() );
uint32_t check_num_last = std::max( uint32_t(ls.valid ? ls.last - chain_contract->lwc_lib_depth : ls.first), msg.headers.front().block_num() );
uint32_t identical_num = 0;
uint32_t check_num = check_num_first;
while ( check_num >= check_num_last ){
auto id_from_msg = msg.headers[ check_num - msg.headers.front().block_num()].id();
auto id_from_lwc = chain_contract->get_chaindb_tb_block_id_by_block_num( check_num );
if ( id_from_lwc != block_id_type() && id_from_msg == id_from_lwc ){
identical_num = check_num;
break;
}
--check_num;
}
idump((identical_num));
if ( identical_num == 0 ){
if ( check_num == ls.first ){
// delete lwcls ?
chain_contract->pushsection( msg );
}
fc_elog(logger,"*****??");
return;
}
// construct and push section data
incremental_merkle merkle = msg.blockroot_merkle;
for ( int i = 0; i < identical_num - msg.headers.front().block_num() + 1; ++i ){
merkle.append( msg.headers[i].id() );
}
lwc_section_data_message par;
par.blockroot_merkle = merkle;
auto first_itr = msg.headers.begin() + ( identical_num - msg.headers.front().block_num() + 1 );
for ( auto it = first_itr; it != msg.headers.end(); ++it ){
par.headers.push_back( *it );
}
chain_contract->pushsection( par );
return;
}
if ( msg_first_num > ls.last && ls.valid ){
chain_contract->pushsection( msg );
}
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const lwc_block_commits_request_message &msg){
peer_dlog(c, "received lwc_block_commits_request_message [${num}]",("num",msg.block_num));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
#ifdef BOSCORE
uint32_t lib_block_num = chain_plug->chain().last_irreversible_block_num();
if ( msg.block_num > lib_block_num ){ return; }
const auto& block_id = chain_plug->chain().get_block_id_for_num( msg.block_num );
const auto bps_ptr = chain_plug->pbft_ctrl().pbft_db.get_pbft_state_by_id( block_id );
lwc_block_commits_data_message ret_msg;
if ( bps_ptr ){
// ret_msg.headers
uint32_t end_block_num = msg.block_num ;
for( auto& commit : bps_ptr->commits ){
idump((commit));
end_block_num = std::max( end_block_num, commit.block_num );
}
for( uint32_t num = msg.block_num; num <= end_block_num; ++num ){
auto sbp = chain_plug->chain().fetch_block_by_number( num );
if ( sbp == signed_block_ptr() ){ fc_elog(logger,"block ${n} not exist", ("n", num)); return; }
ret_msg.headers.push_back( *sbp );
}
// ret_msg.blockroot_merkle
ret_msg.blockroot_merkle = get_blockroot_merkle_by_num( msg.block_num );
if ( ret_msg.blockroot_merkle._node_count == 0 ){
fc_elog(logger,"get blockroot_merkle of block ${n} failed", ("n", msg.block_num));
return;
}
ret_msg.proof_data = fc::raw::pack( bps_ptr->commits );
ret_msg.proof_type = N(commit);
c->enqueue( ret_msg );
return;
}
/* bps_ptr == nullptr */
vector<char> content;
uint32_t check_num;
for( int i = 0; i < 101; ++i ){
check_num = msg.block_num + i;
if ( check_num > lib_block_num ){ break;}
fc_ilog(logger,"check_num = ${n}", ("n",check_num));
signed_block_ptr sbp = chain_plug->chain().fetch_block_by_number( check_num );
if ( sbp == signed_block_ptr() ){ fc_elog(logger,"block ${n} not exist", ("n", check_num)); return; }
for ( auto& ext : sbp->block_extensions ){
if ( ext.first == 0x1 && ext.second.size()>0 ){
content = ext.second;
break;
}
}
if ( !content.empty() ){
break;
}
}
if( content.empty() ){
fc_elog(logger,"didn't get pbft_state of block ${n}", ("n",msg.block_num));
return;
}
auto scp = fc::raw::unpack<pbft_stable_checkpoint>( content );
// ret_msg.headers
uint32_t end_block_num = check_num ;
for( auto& checkpoint : scp.checkpoints ){
idump((checkpoint));
end_block_num = std::max( end_block_num, checkpoint.block_num );
}
for( uint32_t num = check_num; num <= end_block_num; ++num ){
auto sbp = chain_plug->chain().fetch_block_by_number( num );
if ( sbp == signed_block_ptr() ){ fc_elog(logger,"block ${n} not exist", ("n", num)); return; }
ret_msg.headers.push_back( *sbp );
}
// ret_msg.blockroot_merkle
ret_msg.blockroot_merkle = get_blockroot_merkle_by_num( check_num );
if ( ret_msg.blockroot_merkle._node_count == 0 ){
fc_elog(logger,"get blockroot_merkle of block ${n} failed", ("n", check_num));
return;
}
ret_msg.proof_data = fc::raw::pack( scp.checkpoints );
ret_msg.proof_type = N(checkpoint);
c->enqueue( ret_msg );
#endif
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const lwc_block_commits_data_message &msg){
peer_dlog(c, "received lwc_block_commits_data_message [${from},${to}]",("from",msg.headers.front().block_num())("to",msg.headers.back().block_num()));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
auto p = chain_contract->get_sections_tb_reverse_nth_section();
if ( !p.valid() ){
fc_elog(logger,"can not get section info from ibc.chain contract");
return;
}
section_type ls = *p;
if ( msg.headers.front().block_num() > ls.last ){
chain_contract->pushblkcmits( msg );
}
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const ibc_trxs_request_message &msg ) {
peer_dlog(c, "received ibc_trxs_request_message, table ${tb}, id range [${f},${t}]",("tb",msg.table)("f",msg.range.first)("t",msg.range.second));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
uint32_t safe_tslot = my_impl->get_lib_tslot();
ibc_trxs_data_message ret_msg;
ret_msg.table = msg.table;
static const uint32_t max_responses_per_time = 50;
if ( msg.table == N(origtrxs) ){
for( auto id = msg.range.first; id <= msg.range.second && id <= msg.range.first + max_responses_per_time; ++id ){
auto p = token_contract->get_table_origtrxs_trx_info_by_id( id );
if ( p.valid() ){
original_trx_info trx_info = *p;
if ( trx_info.block_time_slot >= safe_tslot ){ break; }
auto info_opt = get_ibc_trx_rich_info( trx_info.block_time_slot, trx_info.trx_id, trx_info.id );
if ( info_opt.valid() ){
ret_msg.trxs_rich_info.push_back( *info_opt );
} else {
fc_elog(logger,"internal error, failed to get rich info of transaction: ${trx}, block time slot: ${tsl}",("trx",trx_info.trx_id)("tsl",trx_info.block_time_slot));
}
}
}
} else if ( msg.table == N(cashtrxs) ){
for( auto id = msg.range.first; id <= msg.range.second && id <= msg.range.first + max_responses_per_time; ++id ){
auto p = token_contract->get_table_cashtrxs_trx_info_by_seq_num( id );
if ( p.valid() ){
cash_trx_info trx_info = *p;
if ( trx_info.block_time_slot >= safe_tslot ){ break; }
auto info_opt = get_ibc_trx_rich_info( trx_info.block_time_slot, trx_info.trx_id, trx_info.seq_num );
if ( info_opt.valid() ){
ret_msg.trxs_rich_info.push_back( *info_opt );
} else {
fc_elog(logger,"internal error, failed to get rich info of transaction: ${trx}, block time slot: ${tsl}",("trx",trx_info.trx_id)("tsl",trx_info.block_time_slot));
}
}
}
}
if ( ret_msg.trxs_rich_info.empty() ){
return;
}
peer_ilog(c,"send ibc_trxs_data_message, table ${b}, size:${s}, id range:[${f},${t}]",("b",msg.table)("s",ret_msg.trxs_rich_info.size())("f",ret_msg.trxs_rich_info.begin()->table_id)("t",ret_msg.trxs_rich_info.rbegin()->table_id));
c->enqueue( ret_msg );
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const ibc_trxs_data_message &msg ) {
peer_dlog(c, "received ibc_trxs_data_message, table ${tb}, id range [${f},${t}]", ("tb",msg.table)("f",msg.trxs_rich_info.front().table_id)("t",msg.trxs_rich_info.back().table_id));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
if ( msg.table == N(origtrxs) ) {
for( const auto& trx_info : msg.trxs_rich_info ){
if ( local_origtrxs.size() == 0 ){
local_origtrxs.insert(trx_info);
break;
}
auto it = local_origtrxs.find( trx_info.table_id );
if ( it == local_origtrxs.end() ) { // link
if ( trx_info.table_id == local_origtrxs.rbegin()->table_id + 1 ){
local_origtrxs.insert(trx_info);
} else {
peer_elog(c,"received unlinkable trxs_rich_info table: origtrxs, table_id: ${tb_id}, trx_id: ${trx_id}",("tb_id",trx_info.table_id)("trx_id",trx_info.trx_id));
local_origtrxs.insert(trx_info); // add it still
}
} else {
if ( it->trx_id == trx_info.trx_id ){ // duplicate
break;
} else { // replace
local_origtrxs.erase( it );
local_origtrxs.insert(trx_info);
peer_elog(c,"received conflict trxs_rich_info table: origtrxs, table_id: ${tb_id}",("tb_id",trx_info.table_id));
}
}
}
while ( local_origtrxs.size() != 0 &&
local_origtrxs.rbegin()->table_id - local_origtrxs.begin()->table_id > MaxLocalOrigtrxsCache ){
local_origtrxs.erase( local_origtrxs.begin() );
}
return;
}
if ( msg.table == N(cashtrxs) ){
for( const auto& trx_info : msg.trxs_rich_info ){
if ( local_cashtrxs.size() == 0 ){
local_cashtrxs.insert(trx_info);
break;
}
auto it = local_cashtrxs.find( trx_info.table_id );
if ( it == local_cashtrxs.end() ) { // link
if ( trx_info.table_id == local_cashtrxs.rbegin()->table_id + 1 ){
local_cashtrxs.insert(trx_info);
} else {
peer_elog(c,"received unlinkable trxs_rich_info table: cashtrxs, table_id: ${tb_id}, trx_id: ${trx_id}",("tb_id",trx_info.table_id)("trx_id",trx_info.trx_id));
local_cashtrxs.insert(trx_info); // add it still
}
} else {
if ( it->trx_id == trx_info.trx_id ){
break;
} else { // replace
local_cashtrxs.erase( it );
local_cashtrxs.insert(trx_info);
peer_elog(c,"received conflict trxs_rich_info table: cashtrxs, table_id: ${tb_id}",("tb_id",trx_info.table_id));
}
}
}
while ( local_cashtrxs.size() != 0 &&
local_cashtrxs.rbegin()->table_id - local_cashtrxs.begin()->table_id > MaxLocalCashtrxsCache ){
local_cashtrxs.erase( local_cashtrxs.begin() );
}
return;
}
}
std::vector<digest_type> get_block_id_merkle_path_to_anchor_block( uint32_t from_block_num, uint32_t anchor_block_num );
void ibc_plugin_impl::handle_message(const connection_ptr& c, const ibc_block_merkle_path_request_message &msg){
peer_dlog(c, "received ibc_block_merkle_path_request_message, anchor_block_num [${num}]",("num",msg.anchor_block_num));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
ibc_block_merkle_path_data_message ret_msg;
ret_msg.table = msg.table;
ret_msg.anchor_block_num = msg.anchor_block_num;
for( auto block_num : msg.block_nums ){
if ( block_num < msg.anchor_block_num ){
auto merkle_path = get_block_id_merkle_path_to_anchor_block( block_num, msg.anchor_block_num );
if ( merkle_path.size() == 0 ){
fc_elog(logger,"get_block_id_merkle_path_to_anchor_block from ${f} to ${t} failed", ("f",block_num)("t",msg.anchor_block_num));
return;
}
ret_msg.block_merkle_paths.emplace_back( block_num, merkle_path );
} else { // block_num == msg.anchor_block_num
ret_msg.block_merkle_paths.emplace_back( block_num, std::vector<digest_type>() );
}
}
peer_ilog(c,"send ibc_block_merkle_path_data_message, anchor_block_num [${num}]",("num",ret_msg.anchor_block_num));
c->enqueue( ret_msg );
}
void ibc_plugin_impl::handle_message(const connection_ptr& c, const ibc_block_merkle_path_data_message &msg){
peer_dlog(c, "received ibc_block_merkle_path_data_message, anchor_block_num [${num}]",("num",msg.anchor_block_num));
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
uint32_t first_block_num = msg.block_merkle_paths.front().first;
if ( msg.table == N(origtrxs) ) {
auto it_blk_num = local_origtrxs.get<by_block_num>().lower_bound( first_block_num );
auto it = local_origtrxs.project<0>(it_blk_num);
if ( it == local_origtrxs.end() || it->block_num != first_block_num ){
fc_elog(logger,"internal error, it->block_num != first_block_num");
return;
}
auto path_itr = msg.block_merkle_paths.begin();
while ( it != local_origtrxs.end() && path_itr != msg.block_merkle_paths.end() ) {
if ( it->block_num == path_itr->first ){
local_origtrxs.modify( it, trx_rich_info_update(path_itr->second, msg.anchor_block_num) );
it++;
} else {
path_itr++;
}
}
return;
}
if ( msg.table == N(cashtrxs) ) {
auto it_blk_num = local_cashtrxs.get<by_block_num>().lower_bound( first_block_num );
auto it = local_cashtrxs.project<0>(it_blk_num);
if ( it == local_cashtrxs.end() || it->block_num != first_block_num ){
fc_elog(logger,"internal error, it->block_num != first_block_num");
return;
}
auto path_itr = msg.block_merkle_paths.begin();
while ( it != local_cashtrxs.end() && path_itr != msg.block_merkle_paths.end() ) {
if ( it->block_num == path_itr->first ){
local_cashtrxs.modify( it, trx_rich_info_update(path_itr->second, msg.anchor_block_num) );
it++;
} else {
path_itr++;
}
}
return;
}
fc_elog(logger,"internal error!");
}
incremental_merkle ibc_plugin_impl::get_brtm_from_cache( uint32_t block_num ){
if ( blockroot_merkle_cache.begin() != blockroot_merkle_cache.end() &&
blockroot_merkle_cache.begin()->block_num <= block_num && block_num <= blockroot_merkle_cache.rbegin()->block_num ){
return blockroot_merkle_cache[ block_num - blockroot_merkle_cache.begin()->block_num ].merkle;
}
incremental_merkle mkl;
mkl._node_count = 0;
return mkl;
}
uint32_t ibc_plugin_impl::get_lib_tslot(){
auto block_num = chain_plug->chain().last_irreversible_block_num();
auto shr_ptr = chain_plug->chain().fetch_block_by_number( block_num );
if ( ! shr_ptr ){ fc_elog(logger,"fatal error, block ${n} not exist", ("n", block_num)); return 0; }
return shr_ptr->timestamp.slot;
}
uint32_t ibc_plugin_impl::get_head_tslot(){
auto block_num = chain_plug->chain().fork_db_head_block_num();
auto shr_ptr = chain_plug->chain().fetch_block_by_number( block_num );
if ( ! shr_ptr ){ fc_elog(logger,"fatal error, block ${n} not exist", ("n", block_num)); return 0; }
return shr_ptr->timestamp.slot;
}
lwc_section_type ibc_plugin_impl::sum_received_lwcls_info() {
std::vector<lwc_section_type> sv;
for (auto &c : connections ) {
if ( c->lwcls_info_update_time != fc::time_point() &&
c->lwcls_info != lwc_section_type() &&
( fc::time_point::now() - c->lwcls_info_update_time < fc::seconds(30)) ){
sv.push_back( c->lwcls_info );
}
}
if( sv.empty() ){
return lwc_section_type();
}
std::sort( sv.begin(), sv.end(), []( lwc_section_type s1, lwc_section_type s2 ){
return s1.first_num < s2.first_num ;
} );
return sv[ sv.size() / 2 ];
}
bool ibc_plugin_impl::is_head_catchup() {
auto head_block_time_point = fc::time_point( chain_plug->chain().fork_db_head_block_time() );
return head_block_time_point < fc::time_point::now() + fc::seconds(3) &&
head_block_time_point > fc::time_point::now() - fc::seconds(3);
}
bool ibc_plugin_impl::should_send_ibc_heartbeat(){
// if ( chain_plug->chain().fork_db_head_block_num() < 400 ){
// fc_dlog(logger,"waiting chain's head block number greater than 400");
// return false;
// }
// check if local head catch up
head_catched_up = is_head_catchup();
if ( ! head_catched_up ){
fc_ilog(logger,"local chain head doesn't catch up current chain head, waiting...");
return false;
}
// check ibc.chain contract
if ( chain_contract->state != working ){
chain_contract->get_contract_state();
}
if ( chain_contract->state == none ){
fc_ilog(logger,"ibc.chain contract not deployed");
return false;
}
if (!chain_contract->lwc_config_valid() ){
fc_ilog(logger,"ibc.chain contract global_state validate failed");
return false;
}
// check ibc.token contract
if ( token_contract->state != working ){
token_contract->get_contract_state();
fc_ilog(logger,"ibc.token contract not in working state, current state: ${s}", ("s", contract_state_str( token_contract->state )));
return false;
}
return true;
}
// get new producer schedule info for ibc_heartbeat_message to send, check if has new producer schedule since lwcls's last block
void ibc_plugin_impl::chain_checker( ibc_heartbeat_message& msg ) {
msg.new_producers_block_num = 0;
auto lwcls = sum_received_lwcls_info();
if ( lwcls == lwc_section_type() ){
fc_ilog(logger,"doesn't receive any lwcls infomation from connected peer chain relay nodes");
return;
}
uint32_t lib_block_num = chain_plug->chain().last_irreversible_block_num();
if ( lwcls.last_num >= lib_block_num ){
return;
}
static uint32_t check_block_num = 0;
if ( lwcls.last_num >= check_block_num ){
check_block_num = lwcls.last_num + 1;
}
auto get_block_ptr = [=]( uint32_t num ) -> signed_block_ptr {
return chain_plug->chain().fetch_block_by_number(num);
};
while ( check_block_num < lib_block_num ){
auto sh_ptr = get_block_ptr(check_block_num);
if ( ! sh_ptr ){
fc_dlog(logger,"there is no block ${n} data",("n",check_block_num));
++check_block_num;
continue;
}
auto np_opt = sh_ptr->new_producers;
if ( np_opt.valid() && np_opt->producers.size() > 0 ){
msg.new_producers_block_num = check_block_num - 1;
fc_ilog(logger,"find new_producers_block_num ${n} < ---- new producers ---- >",("n",msg.new_producers_block_num));
return;
}
++check_block_num;
}
}
// get lwcls info for ibc_heartbeat_message to send
void ibc_plugin_impl::ibc_chain_contract_checker( ibc_heartbeat_message& msg ) {
auto p = my_impl->chain_contract->get_sections_tb_reverse_nth_section();
if ( p.valid() ){
auto obj = *p;
lwc_section_type ls;
ls.first_num = obj.first;
ls.first_id = chain_contract->get_chaindb_tb_block_id_by_block_num( ls.first_num );
ls.last_num = obj.last;
ls.last_id = chain_contract->get_chaindb_tb_block_id_by_block_num( ls.last_num );
if ( obj.last - chain_contract->lwc_lib_depth >= obj.first ){
ls.lib_num = obj.last - chain_contract->lwc_lib_depth;
ls.lib_id = chain_contract->get_chaindb_tb_block_id_by_block_num( ls.lib_num );
} else {
ls.lib_num = 0;
ls.lib_id = block_id_type();
}
ls.valid = obj.valid;
msg.lwcls = ls;
}
msg.ibc_chain_state = chain_contract->state;
}
// get origtrxs and cashtrxs tables info for ibc_heartbeat_message to send
void ibc_plugin_impl::ibc_token_contract_checker( ibc_heartbeat_message& msg ){
msg.ibc_token_state = token_contract->state;
msg.origtrxs_table_id_range = token_contract->get_table_origtrxs_id_range();
msg.cashtrxs_table_seq_num_range = token_contract->get_table_cashtrxs_seq_num_range();
}
void ibc_plugin_impl::start_ibc_heartbeat_timer() {
if ( count_open_sockets() != 0 ){
try{
if ( should_send_ibc_heartbeat() ){
ibc_heartbeat_message msg;
chain_checker(msg);
ibc_chain_contract_checker(msg);
ibc_token_contract_checker(msg);
if ( connections.size() == 0 ){
fc_elog(logger,"connections.size() == 0");
}
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c,"sending ibc_heartbeat_message");
fc_dlog(logger,"origtrxs_table_id_range [${of},${ot}] cashtrxs_table_seq_num_range [${cf},${ct}] new_producers_block_num ${n}, lwcls_range [${lsf},${lst},${v}]",
("of",msg.origtrxs_table_id_range.first)("ot",msg.origtrxs_table_id_range.second)
("cf",msg.cashtrxs_table_seq_num_range.first)("ct",msg.cashtrxs_table_seq_num_range.second)
("n",msg.new_producers_block_num)("lsf",msg.lwcls.first_num)("lst",msg.lwcls.last_num)("v",msg.lwcls.valid));
c->enqueue( msg );
} else {
fc_elog(logger,"c->current() is faulse" );
fc_ilog(logger,"close connection" );
close(c);
}
}
}
} FC_LOG_AND_DROP()
} else {
fc_elog(logger,"count_open_sockets() == 0");
}
ibc_heartbeat_timer->expires_from_now (ibc_heartbeat_interval);
ibc_heartbeat_timer->async_wait ([this](boost::system::error_code ec) {
start_ibc_heartbeat_timer();
if (ec) {
fc_wlog(logger,"start_ibc_heartbeat_timer error: ${m}", ("m", ec.message()));
}
});
}
vector<digest_type> get_merkle_path( vector<digest_type> ids, uint32_t num ) {
if( 0 == ids.size() || num > ids.size() - 1 ) { return vector<digest_type>(); }
vector<digest_type> result;
if( ids.size() == 1 ){
result.push_back( ids.front() );
return result;
}
// add the first two elements to merkle path
if ( num % 2 == 0 ){ // left side
result.push_back(ids[num]);
if ( num == ids.size() - 1 ){
result.push_back(ids[num]);
} else {
result.push_back(ids[num+1]);
}
} else { // right side
result.push_back(ids[num-1]);
result.push_back(ids[num]);
}
// append middle path
uint32_t idx_in_layer = num;
while( ids.size() > 1 ) {
if( ids.size() % 2 )
ids.push_back(ids.back());
for (int i = 0; i < ids.size() / 2; i++) {
ids[i] = digest_type::hash(make_canonical_pair(ids[2 * i], ids[(2 * i) + 1]));
}
ids.resize(ids.size() / 2);
if ( ids.size() > 1 ){ // not reach root yet
idx_in_layer /= 2;
if ( idx_in_layer % 2 == 0 ){ // left side
if ( idx_in_layer == ids.size() - 1 ){
result.push_back( make_canonical_right(ids[idx_in_layer]) );
} else {
result.push_back( make_canonical_right(ids[idx_in_layer+1]) );
}
} else { // right side
result.push_back( make_canonical_left(ids[idx_in_layer-1]) );
}
}
}
// append merkle root
result.push_back( ids.front() );
return result;
}
//--------------- incremental_merkle related functions , start ---------------
/** merkle tree
* layer, Increase upward from leaf node layer, starting from 1
* layer index, Increase from left to right in every layer, starting from 1
*
* * root layer 5 depth 1
* * * layer 4 depth 2
* * * * * layer 3 depth 3
* * * * * * * * * layer 2 depth 4
* * * * * * * * * * * * * * * * * layer 1 depth 5 leafs
*
*/
bool inc_merkle_verify( const incremental_merkle& inc_mkl ){
auto max_depth = eosio::chain::detail::calcluate_max_depth( inc_mkl._node_count );
auto current_depth = max_depth;
auto index = inc_mkl._node_count;
auto active_iter = inc_mkl._active_nodes.begin();
digest_type top;
if ( inc_mkl._active_nodes.size() == 1 ){
return true;
}
while (current_depth > 1) {
if ((index & 0x1)) { // left
if ( top == digest_type() ){
const auto& left_value = *active_iter;
++active_iter;
top = digest_type::hash(make_canonical_pair(left_value, left_value));
} else {
top = digest_type::hash(make_canonical_pair(top, top));
}
} else { // right
if ( top != digest_type()){
const auto& left_value = *active_iter;
++active_iter;
top = digest_type::hash(make_canonical_pair(left_value, top));
}
}
// move up a level in the tree
current_depth--;
index = (index + 1) >> 1;
}
return top == inc_mkl.get_root();
}
digest_type get_block_id_by_num( uint32_t block_num ){
return my_impl->chain_plug->chain().get_block_id_for_num(block_num);
}
digest_type get_inc_merkle_layer_left_node( const incremental_merkle& inc_mkl, const uint32_t& layer ){
auto max_layers = eosio::chain::detail::calcluate_max_depth( inc_mkl._node_count );
if ( inc_mkl._node_count == 0 ){ fc_elog(logger,"inc_mkl._node_count == 0"); return digest_type(); }
if ( layer >= max_layers ){ fc_elog(logger,"layer >= max_layers"); return digest_type(); }
auto current_layer = 1;
auto index = inc_mkl._node_count;
auto active_iter = inc_mkl._active_nodes.begin();
if ( layer == 1 ){
return inc_mkl._active_nodes.back();
}
digest_type current_layer_node;
while ( current_layer < max_layers ) {
if ((index & 0x1)) { // left
current_layer_node = *active_iter;
++active_iter;
} else {
current_layer_node = digest_type();
}
if ( current_layer == layer ){
return current_layer_node;
}
// move up a level in the tree
current_layer++;
index = index >> 1;
}
return digest_type();
}
std::tuple<uint32_t,uint32_t,digest_type> get_inc_merkle_full_branch_root_cover_from( const uint32_t& from_block_num, const incremental_merkle& inc_mkl ) {
if ( from_block_num > inc_mkl._node_count ){
fc_elog(logger,"from_block_num > inc_mkl._node_count");
return std::tuple<uint32_t,uint32_t,digest_type>();
}
auto max_layers = eosio::chain::detail::calcluate_max_depth( inc_mkl._node_count );
auto current_layer = 1;
auto index = inc_mkl._node_count;
auto active_iter = inc_mkl._active_nodes.begin();
digest_type current_layer_node = digest_type();
while (current_layer <= max_layers ) {
// std::cout << "current_layer: " << current_layer << std::endl;
if (index & 0x1) { // left
current_layer_node = *active_iter;
++active_iter;
uint32_t first, last;
uint32_t diff = current_layer - 1;
last = index << diff;
first = last - (1 << diff) + 1;
// std::cout << "first: " << first << " last: " << last << std::endl;
if ( first <= from_block_num && from_block_num <= last ){
return { current_layer, index, current_layer_node };
}
}
// move up a level in the tree
current_layer++;
index = index >> 1;
}
fc_elog(logger,"can not get_inc_merkle_full_branch_root_cover_from");
return std::tuple<uint32_t,uint32_t,digest_type>();
}
// nodes in layer range [ 2, max_layers ]
std::vector<std::pair<uint32_t,uint32_t>> get_merkle_path_positions_to_layer_in_full_branch( uint32_t from_block_num, uint32_t to_layer ){
std::vector<std::pair<uint32_t,uint32_t>> path;
if ( to_layer < 2 ){ fc_elog(logger,"to_layer < 2"); return path; }
auto index = from_block_num;
auto current_layer = 2;
while ( current_layer < to_layer ){
index = ( index + 1 ) >> 1;
if ( index & 0x1 ){
path.emplace_back( current_layer, index + 1 );
} else{
path.emplace_back( current_layer, index - 1 );
}
current_layer++;
}
index = ( index + 1 ) >> 1;
path.emplace_back( to_layer, index );
return path;
}
digest_type get_merkle_node_value_in_full_sub_branch( const incremental_merkle& reference_inc_merkle, uint32_t layer, uint32_t index ){
if ( layer < 2 ){ fc_elog(logger,"to_layer < 2"); return digest_type(); }
if ( index & 0x1 ){
auto max_layers = eosio::chain::detail::calcluate_max_depth( reference_inc_merkle._node_count );
if ( layer < max_layers ){ // search in reference_inc_merkle first
auto ret = get_inc_merkle_layer_left_node( reference_inc_merkle, layer );
if ( ret != digest_type() ){
// fc_ilog(logger,"access self inc_merkle ok");
return ret;
}
}
// fc_ilog(logger,"access self inc_merkle failed --");
auto inc_merkle = get_blockroot_merkle_by_num( (index << (layer - 1)) + 1 );
return inc_merkle._active_nodes.front();
} else {
auto block_num = index << ( layer - 1 );
// fc_ilog(logger,"access blockroot_merkle of block ${n}", ("n",block_num));
auto inc_merkle = get_blockroot_merkle_by_num( block_num );
auto active_iter = inc_merkle._active_nodes.begin();
auto block_id = get_block_id_by_num( block_num );
uint32_t current_layer = 1;
digest_type top = block_id;
while ( current_layer < layer ){
const auto& left_value = *active_iter;
++active_iter;
top = digest_type::hash(make_canonical_pair(left_value, top));
current_layer++;
}
return top;
}
}
std::vector<digest_type> get_block_id_merkle_path_to_anchor_block( uint32_t from_block_num, uint32_t anchor_block_num ){
// idump((from_block_num)(anchor_block_num));
std::vector<digest_type> result;
if ( from_block_num >= anchor_block_num ){ fc_elog(logger,"from_block_num must be less then anchor_block_num"); return result; } //important
auto anchor_block_inc_merkle = get_blockroot_merkle_by_num( anchor_block_num );
uint32_t full_root_layer;
uint32_t full_root_index;
digest_type full_root_value;
std::tie( full_root_layer, full_root_index, full_root_value ) = get_inc_merkle_full_branch_root_cover_from( from_block_num, anchor_block_inc_merkle );
//idump((full_root_layer)(full_root_index)(string(full_root_value)));
if( full_root_layer == 1 ){
result.push_back( full_root_value );
return result;
}
auto position_path = get_merkle_path_positions_to_layer_in_full_branch( from_block_num, full_root_layer );
if ( position_path.back().first != full_root_layer || position_path.back().second != full_root_index ){
fc_elog(logger,"internal error! position_path.back() calculate failed");
return result;
}
// add the first two elements to merkle path
if ( from_block_num % 2 == 1 ){ // left side
result.push_back( get_block_id_by_num( from_block_num ) );
result.push_back( get_block_id_by_num( from_block_num + 1 ) );
} else { // right side
result.push_back( get_block_id_by_num( from_block_num - 1) );
result.push_back( get_block_id_by_num( from_block_num ) );
}
auto from_block_inc_merkle = get_blockroot_merkle_by_num( from_block_num );
position_path.erase( --position_path.end() );
for( auto p : position_path ){
auto value = get_merkle_node_value_in_full_sub_branch( from_block_inc_merkle, p.first, p.second );
if ( p.second & 0x1 ){
result.push_back( make_canonical_left(value) );
} else {
result.push_back( make_canonical_right(value) );
}
}
result.push_back( full_root_value );
return result;
}
bool verify_merkle_path( const std::vector<digest_type>& merkle_path ) {
if ( merkle_path.size() == 0 ){ fc_elog(logger,"merkle_path is empty"); return false; }
if ( merkle_path.size() == 1 ){ return true; }
digest_type result = digest_type::hash( make_canonical_pair(merkle_path[0], merkle_path[1]) );
for( auto i = 0; i < merkle_path.size() - 3; ++i ){
digest_type left;
digest_type right;
if ( is_canonical_left(merkle_path[i+2]) ){
left = merkle_path[i+2];
right = make_canonical_right( result );
} else {
left = make_canonical_left( result );
right = merkle_path[i+2];
}
result = digest_type::hash( std::make_pair(left,right) );
}
return result == merkle_path.back();
}
//--------------- incremental_merkle related functions , end ---------------
uint32_t ibc_plugin_impl::get_block_num_by_time_slot( uint32_t block_time_slot ){
auto head_num = chain_plug->chain().fork_db_head_block_num();
auto shr_ptr = chain_plug->chain().fetch_block_by_number( head_num );
if ( ! shr_ptr ){ fc_elog(logger,"fatal error, block ${n} not exist", ("n", head_num)); return 0; }
auto head_slot = shr_ptr->timestamp.slot;
if ( head_slot < block_time_slot ){
fc_elog(logger,"unknown block_time_slot" );
return 0;
}
// get block number from block_time_slot
uint32_t diff = head_slot - block_time_slot;
uint32_t check_num = head_num > diff ? head_num - diff : 1;
auto shr_ptr2 = chain_plug->chain().fetch_block_by_number(check_num);
if ( ! shr_ptr2 ){ fc_elog(logger,"block ${n} not exist", ("n", check_num)); return 0; }
uint32_t check_slot = shr_ptr2->timestamp.slot;
while ( check_slot < block_time_slot ){
check_num += 1;
auto shr_ptr3 = chain_plug->chain().fetch_block_by_number(check_num);
if ( ! shr_ptr3 ){ fc_elog(logger,"block ${n} not exist", ("n", check_num)); return 0; }
check_slot = shr_ptr3->timestamp.slot;
}
if ( check_slot != block_time_slot ){
fc_elog(logger,"block of block_time_slot not found" );
return 0;
}
return check_num;
}
optional<ibc_trx_rich_info> ibc_plugin_impl::get_ibc_trx_rich_info( uint32_t block_time_slot, transaction_id_type trx_id, uint64_t table_id ){
uint32_t trx_block_num = get_block_num_by_time_slot( block_time_slot );
if ( trx_block_num == 0 ){
fc_elog(logger,"block of time slot: ${n} not exist", ("n", block_time_slot));
return optional<ibc_trx_rich_info>();
}
ibc_trx_rich_info trx_info;
trx_info.table_id = table_id;
trx_info.trx_id = trx_id;
trx_info.block_num = trx_block_num;
// get trx merkle path
auto blk_ptr = chain_plug->chain().fetch_block_by_number( trx_info.block_num );
if ( ! blk_ptr ){
fc_elog(logger,"block ${n} not exist", ("n", trx_info.block_num));
return optional<ibc_trx_rich_info>();
}
std::vector<digest_type> trx_digests;
std::vector<transaction_id_type> trx_ids;
std::vector<char> packed_trx_receipt;
bool found = false;
uint32_t found_num = 0;
for ( auto const& trx : blk_ptr->transactions ){
trx_digests.push_back( trx.digest() );
transaction_id_type check_trx_id = transaction_id_type();
try {
check_trx_id = trx.trx.get<packed_transaction>().id();
} catch (...) {}
if ( check_trx_id == trx_id ){
found = true;
packed_trx_receipt = fc::raw::pack(trx);
}
if (!found){
found_num += 1;
}
}
if ( merkle(trx_digests) != blk_ptr->transaction_mroot ){
fc_elog(logger,"internal error");
return optional<ibc_trx_rich_info>();
}
if ( !found ){
fc_elog(logger,"trx not found");
return optional<ibc_trx_rich_info>();
}
auto mp = get_merkle_path( trx_digests, found_num );
if ( mp.empty() ){
fc_elog(logger,"internal error");
return optional<ibc_trx_rich_info>();
}
trx_info.trx_merkle_path = mp;
trx_info.packed_trx_receipt = packed_trx_receipt;
trx_info.block_header = fc::raw::pack(block_header(*blk_ptr));
trx_info.block_id_merkle_path = std::vector<digest_type>(); // init
trx_info.anchor_block_num = 0; //init
return trx_info;
}
void ibc_plugin_impl::check_if_remove_old_data_in_ibc_contracts(){
// ---- ibc.chain ----
uint32_t size = chain_contract->get_sections_tb_size();
if ( size >=3 ){
chain_contract->rmfirstsctn();
}
// ---- ibc.token ----
uint32_t last_confirmed_orig_trx_block_time_slot = 0;
auto pchm_opt = token_contract->get_peer_chain_mutable();
if ( pchm_opt.valid() ){
last_confirmed_orig_trx_block_time_slot = pchm_opt->last_confirmed_orig_trx_block_time_slot;
} else {
fc_elog(logger,"get_peer_chain_mutable failed");
return;
}
if ( last_confirmed_orig_trx_block_time_slot == 0 ){
return;
}
uint32_t count = 0;
range_type range = token_contract->get_table_origtrxs_id_range();
if ( range == range_type() ){
return;
}
std::vector<transaction_id_type> to_rmunablerb;
std::vector<transaction_id_type> to_rollback;
for ( uint64_t i = range.first; i <= range.second ; ++i ){
auto trx_opt = token_contract->get_table_origtrxs_trx_info_by_id( i );
if ( trx_opt.valid() ){
if ( trx_opt->block_time_slot + 3600 * 24 * 2 < last_confirmed_orig_trx_block_time_slot ){
to_rmunablerb.push_back( trx_opt->trx_id );
continue;
}
if ( trx_opt->block_time_slot + 25 < last_confirmed_orig_trx_block_time_slot ){
to_rollback.push_back( trx_opt->trx_id );
} else {
break;
}
}
}
static const uint32_t max_push_trxs_per_time = 30;
if ( ! to_rollback.empty() ){
token_contract->rollback( to_rollback );
}
if ( ! to_rmunablerb.empty() ){
std::vector<transaction_id_type> to_push;
if ( to_rmunablerb.size() > max_push_trxs_per_time ){
to_push = std::vector<transaction_id_type>( to_rmunablerb.begin(), to_rmunablerb.begin() + max_push_trxs_per_time );
} else {
to_push = to_rmunablerb;
}
token_contract->rmunablerb( to_push );
}
}
/**
* This function implements the core ibc logic of the plugin
*/
void ibc_plugin_impl::ibc_core_checker( ){
if ( ! head_catched_up ) { fc_ilog(logger,"head not catch up"); return; }
if ( chain_contract->state != working || token_contract->state != working ){
chain_contract->get_contract_state();
token_contract->get_contract_state();
return;
}
// dump debug info
uint32_t orig_begin = 0, orig_end = 0, cash_begin = 0, cash_end = 0;
if( local_origtrxs.begin() != local_origtrxs.end() ){
orig_begin = local_origtrxs.begin()->table_id;
orig_end = local_origtrxs.rbegin()->table_id;
}
if( local_cashtrxs.begin() != local_cashtrxs.end() ){
cash_begin = local_cashtrxs.begin()->table_id;
cash_end = local_cashtrxs.rbegin()->table_id;
}
fc_ilog(logger,"local_origtrxs id range [${of},${ot}], local_cashtrxs id range [${cf},${ct}]",("of",orig_begin)("ot",orig_end)("cf",cash_begin)("ct",cash_end));
///< ---- step 0: remove side effect of unapplied trxs ---- >///
chain_plug->chain().abort_block();
chain_plug->chain().drop_all_unapplied_transactions();
check_if_remove_old_data_in_ibc_contracts();
///< ---- step 1: let lwcls in ibc.chain reach its minimum length ---- >///
fc_ilog(logger,"step 1");
auto opt_sctn = chain_contract->get_sections_tb_reverse_nth_section();
if ( !opt_sctn.valid() ){
fc_elog(logger,"internal error, can not get lwcls");
return;
}
section_type lwcls = *opt_sctn;
bool reached_min_length = true;
name consensus = chain_contract->get_consensus_algo();
if( consensus == name() || ( consensus != N(pipeline) && consensus != N(batch)) ){
fc_elog(logger,"ibc.chain consensus config error");
return;
}
if ( consensus == N(pipeline) ) {
// calculation the minimun range of lwcls should reach through information of local_origtrxs, local_cashtrxs and new_prod_blk_num
uint32_t min_last_num = lwcls.first + chain_contract->lwc_lib_depth ;
min_last_num = std::max( min_last_num, uint32_t(lwcls.last) ); // important logic
if ( lwcls.np_num != 0 ){
min_last_num = std::max( min_last_num, uint32_t( lwcls.np_num + BPScheduleReplaceMinLength + chain_contract->lwc_lib_depth) );
}
///< --- local_origtrxs --- >///
auto _it_orig = local_origtrxs.get<by_block_num>().lower_bound( lwcls.first );
auto it_orig = local_origtrxs.project<0>(_it_orig);
while ( it_orig != local_origtrxs.end() && it_orig->block_num < min_last_num ){
min_last_num = std::max( min_last_num, it_orig->block_num + chain_contract->lwc_lib_depth );
++it_orig;
}
///< --- local_cashtrxs --- >///
auto _it_cash = local_cashtrxs.get<by_block_num>().lower_bound( lwcls.first ); // the case with last_complete_origtrxs_rich_info_id == 0
auto it_cash = local_cashtrxs.project<0>(_it_cash);
while ( it_cash != local_cashtrxs.end() && it_cash->block_num < min_last_num ){
min_last_num = std::max( min_last_num, it_cash->block_num + chain_contract->lwc_lib_depth );
++it_cash;
}
if ( lwcls.first <= new_prod_blk_num && new_prod_blk_num <= min_last_num ){
min_last_num = std::max( min_last_num, new_prod_blk_num + BPScheduleReplaceMinLength + chain_contract->lwc_lib_depth );
}
// check if lwcls reached the minimum range, if not, send lwc_section_request_message
if ( lwcls.last < min_last_num ){
reached_min_length = false;
lwc_section_request_message msg;
msg.start_block_num = lwcls.last + 1;
msg.end_block_num = min_last_num + 1;
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c, "send lwc_section_request_message [${from},${to}]",("from",msg.start_block_num)("to",msg.end_block_num));
c->enqueue( msg );
}
}
}
}
///< ---- step two: fill related trx rich info according anchor block number ---- >///
fc_ilog(logger,"step 2");
uint32_t last_anchor_block_num = chain_contract->get_last_anchor_block_num();
bool origtrxs_complete = false;
bool cashtrxs_complete = false;
// handle local_origtrxs
{
static uint64_t last_complete_origtrxs_rich_info_id = 0;
if ( last_complete_origtrxs_rich_info_id == 0 ){
auto itr = local_origtrxs.rbegin();
while ( itr != local_origtrxs.rend() ){
if( itr->anchor_block_num != 0 ){
last_complete_origtrxs_rich_info_id = itr->table_id;
break;
}
itr++;
}
} else {
auto itr = local_origtrxs.find( last_complete_origtrxs_rich_info_id );
if ( itr == local_origtrxs.end() ){
fc_elog(logger,"internal error!");
return;
}
while ( itr != local_origtrxs.end() && itr->anchor_block_num != 0 ){
last_complete_origtrxs_rich_info_id = itr->table_id;
itr++;
}
}
auto itr = local_origtrxs.lower_bound( last_complete_origtrxs_rich_info_id + 1 ); // the case with last_complete_origtrxs_rich_info_id == 0
if ( itr == local_origtrxs.end() || itr->block_num > last_anchor_block_num ){
origtrxs_complete = true;
fc_ilog(logger,"origtrxs_complete = true;");
} else {
ibc_block_merkle_path_request_message bmp_req_msg;
bmp_req_msg.table = N(origtrxs);
bmp_req_msg.anchor_block_num = last_anchor_block_num;
while ( itr != local_origtrxs.end() && itr->block_num <= last_anchor_block_num ){
if( bmp_req_msg.block_nums.size() > 0 && itr->block_num == bmp_req_msg.block_nums.back() ){
itr++;
continue;
}
bmp_req_msg.block_nums.push_back( itr->block_num );
itr++;
}
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c, "send ibc_block_merkle_path_request_message");
c->enqueue( bmp_req_msg );
}
}
}
}
// handle local_cashtrxs
{
static uint64_t last_complete_cashtrxs_rich_info_id = 0;
if ( last_complete_cashtrxs_rich_info_id == 0 ){
auto itr = local_cashtrxs.rbegin();
while ( itr != local_cashtrxs.rend() ){
if( itr->anchor_block_num != 0 ){
last_complete_cashtrxs_rich_info_id = itr->table_id;
break;
}
itr++;
}
} else {
auto itr = local_cashtrxs.find( last_complete_cashtrxs_rich_info_id );
if ( itr == local_cashtrxs.end() ){
fc_elog(logger,"internal error!");
return;
}
while ( itr != local_cashtrxs.end() && itr->anchor_block_num != 0 ){
last_complete_cashtrxs_rich_info_id = itr->table_id;
itr++;
}
}
auto itr = local_cashtrxs.lower_bound( last_complete_cashtrxs_rich_info_id + 1 );
if ( itr == local_cashtrxs.end() || itr->block_num > last_anchor_block_num ){
cashtrxs_complete = true;
fc_ilog(logger,"cashtrxs_complete = true;");
} else {
ibc_block_merkle_path_request_message bmp_req_msg;
bmp_req_msg.table = N(cashtrxs);
bmp_req_msg.anchor_block_num = last_anchor_block_num;
while ( itr != local_cashtrxs.end() && itr->block_num <= last_anchor_block_num ){
if( bmp_req_msg.block_nums.size() > 0 && itr->block_num == bmp_req_msg.block_nums.back() ){
itr++;
continue;
}
bmp_req_msg.block_nums.push_back( itr->block_num );
itr++;
}
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c, "send ibc_block_merkle_path_request_message");
c->enqueue( bmp_req_msg );
}
}
}
}
if ( ! (origtrxs_complete && cashtrxs_complete ) ){
return;
}
///< ---- step 3: push all transactions which should validate within this lwcls ---- >///
fc_ilog(logger,"step 3");
if ( consensus == N(pipeline) && lwcls.valid == false ){
return;
}
static const uint32_t max_push_orig_trxs_per_time = 30;
static const uint32_t max_push_cash_trxs_per_time = 30;
std::vector<ibc_trx_rich_info> orig_trxs_to_push;
std::vector<ibc_trx_rich_info> cash_trxs_to_push;
///< --- local_origtrxs --- >///
auto range = token_contract->get_table_cashtrxs_seq_num_range(true);
if ( range.first == 0 ){ // range.first == 0 means cashtrxs is empty, range.second shoule also be 0
for( const auto& t : local_origtrxs.get<by_id>( ) ) {
if ( t.block_num <= last_anchor_block_num && t.anchor_block_num != 0 ){
if ( t.trx_id == token_contract->last_origtrx_pushed ){ orig_trxs_to_push.clear(); }
orig_trxs_to_push.push_back( t );
} else { break; }
}
} else {
auto cash_opt = token_contract->get_table_cashtrxs_trx_info_by_seq_num( range.second );
if ( cash_opt.valid() ){
auto orig_trx_id = cash_opt->orig_trx_id;
auto it_trx_id = local_origtrxs.get<by_trx_id>().find( orig_trx_id );
auto it = local_origtrxs.project<0>(it_trx_id);
if ( it != local_origtrxs.end() ){
++it;
while ( it != local_origtrxs.end() ){
if ( it->block_num <= last_anchor_block_num && it->anchor_block_num != 0 ){
if ( it->trx_id == token_contract->last_origtrx_pushed ){ orig_trxs_to_push.clear(); }
orig_trxs_to_push.push_back( *it );
} else { break; }
++it;
}
} else { // maybe happen when restart ibc_plugin node
// fc_ilog(logger,"can not find original transacton infomation form local_origtrxs");
auto it_blk_num = local_origtrxs.get<by_block_num>().lower_bound( cash_opt->orig_trx_block_num + 1 );
it = local_origtrxs.project<0>(it_blk_num);
while ( it != local_origtrxs.end() ){
if ( it->block_num <= last_anchor_block_num && it->anchor_block_num != 0 ){
if ( it->trx_id == token_contract->last_origtrx_pushed ){ orig_trxs_to_push.clear(); }
orig_trxs_to_push.push_back( *it );
} else { break; }
++it;
}
}
} else { fc_ilog(logger,"internal error, failed to get cash transaction information of seq_num ${n}",("n",range.second)); }
}
bool force_forward = false;
if ( ! orig_trxs_to_push.empty() ){
std::vector<ibc_trx_rich_info> to_push;
if ( orig_trxs_to_push.size() > max_push_orig_trxs_per_time ){
to_push = std::vector<ibc_trx_rich_info>( orig_trxs_to_push.begin(), orig_trxs_to_push.begin() + max_push_orig_trxs_per_time );
} else {
to_push = orig_trxs_to_push;
}
static uint64_t highest_idx = 0;
static uint32_t times = 0;
if ( to_push.back().table_id != highest_idx ){
highest_idx = to_push.back().table_id;
times = 1;
} else {
times += 1;
}
if ( times <= 3 ){
fc_ilog(logger,"---------orig_trxs_to_push to push size ${n}, retry times ${try}",("n",to_push.size())("try",times));
try {
token_contract->push_cash_trxs( to_push, range.second + 1 );
} FC_LOG_AND_DROP()
} else {
force_forward = true;
token_contract->last_origtrx_pushed = to_push.back().trx_id;
}
}
///< --- local_cashtrxs --- >///
auto gm_opt = token_contract->get_peer_chain_mutable();
if ( !gm_opt.valid() ){
fc_elog(logger,"internal error, failed to get global_mutable_singleton");
return;
}
uint32_t last_cash_seq_num = gm_opt->cash_seq_num;
uint32_t next_cash_seq_num = last_cash_seq_num + 1;
auto it = local_cashtrxs.get<by_id>().find( next_cash_seq_num );
if ( it == local_cashtrxs.end() ){
auto it_up = local_cashtrxs.get<by_id>().upper_bound( next_cash_seq_num );
if ( it_up != local_cashtrxs.end() ){
// cashconfirm action can't jump, must push according to the serial number
// so, return directly here
// this may be caused by start a new relay-relay channel when other relay-relay channel is working
fc_wlog(logger,"============= cashconfirm action can't jump, return directly =============");
return; // important!
}
}
while ( it != local_cashtrxs.end() && it->block_num <= last_anchor_block_num && it->anchor_block_num != 0 ){
cash_trxs_to_push.push_back( *it );
++it;
}
if ( !cash_trxs_to_push.empty() ){
std::vector<ibc_trx_rich_info> to_push;
if ( cash_trxs_to_push.size() > max_push_cash_trxs_per_time ){
to_push = std::vector<ibc_trx_rich_info>( cash_trxs_to_push.begin(), cash_trxs_to_push.begin() + max_push_cash_trxs_per_time );
} else {
to_push = cash_trxs_to_push;
}
fc_ilog(logger,"---------cash_trxs_to_push to push size ${n}",("n",to_push.size()));
try {
token_contract->push_cashconfirm_trxs( to_push, last_cash_seq_num + 1 );
} FC_LOG_AND_DROP()
return;
}
///< ---- step 4: check if all related trxs about lwcls in local_origtrxs and local_cashtrxs have handled ---- >///
fc_ilog(logger,"step 4");
bool orig_b = false, cash_b = false;
// --- check local_origtrxs ---
if ( orig_trxs_to_push.empty() || orig_trxs_to_push.back().trx_id == token_contract->last_origtrx_pushed || force_forward ){
orig_b = true;
}
// --- check local_cashtrxs ---
if ( cash_trxs_to_push.empty() ){
cash_b = true;
} else {
auto actn_params_opt = token_contract->get_cash_action_params( cash_trxs_to_push.back().packed_trx_receipt );
if ( ! actn_params_opt.valid() ){
fc_elog(logger,"internal error, failed to get_cash_action_params");
return;
}
if ( gm_opt->cash_seq_num == actn_params_opt->seq_num ){
cash_b = true;
}
}
// --- summary ---
if ( ! (reached_min_length && orig_b && cash_b ) ){
idump((reached_min_length)(orig_b)(cash_b)(force_forward));
return;
}
///< ---- step 5: if has new local_origtrxs, local_cashtrxs or new_prod_blk_num, request the next section ---- >///
fc_ilog(logger,"step 5");
{
uint32_t start_blk_num = 0;
// --- check new_prod_blk_num ---
if ( new_prod_blk_num >= lwcls.last ){
start_blk_num = new_prod_blk_num;
if ( consensus == N(batch) ){
start_blk_num++;
}
} else {
// --- check local_origtrxs ---
auto __it_orig = local_origtrxs.get<by_block_num>().lower_bound( lwcls.last + 1 );
auto it_orig = local_origtrxs.project<0>(__it_orig);
if ( it_orig != local_origtrxs.end() ){
if ( consensus == N(pipeline) ){
start_blk_num = it_orig->block_num;
} else {
start_blk_num = (--local_origtrxs.end())->block_num;
}
fc_ilog(logger,"origtrxs has new trxs, start block ${n}",("n",start_blk_num));
}
// --- check local_cashtrxs ---
auto __it_cash = local_cashtrxs.get<by_block_num>().lower_bound( lwcls.last + 1 );
auto it_cash = local_cashtrxs.project<0>(__it_cash);
if ( it_cash != local_cashtrxs.end() ){
if ( consensus == N(pipeline) ){
start_blk_num = std::max( start_blk_num, it_cash->block_num );
} else {
start_blk_num = std::max( start_blk_num, (--local_cashtrxs.end())->block_num );
}
fc_ilog(logger,"cashtrxs has new trxs, start block ${n}",("n",start_blk_num));
}
}
// --- summary ----
if ( start_blk_num != 0 ){
if ( consensus == N(pipeline) ){
lwc_section_request_message msg;
msg.start_block_num = start_blk_num;
msg.end_block_num = start_blk_num + chain_contract->lwc_lib_depth + 1;
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c, "send lwc_section_request_message [${from},${to}]",("from",msg.start_block_num)("to",msg.end_block_num));
c->enqueue( msg );
}
}
} else { // consensus == N(batch)
lwc_block_commits_request_message msg;
msg.block_num = start_blk_num;
for( auto &c : connections) {
if( c->current() ) {
peer_ilog(c, "send lwc_block_commits_request_message [${from}]",("from",msg.block_num));
c->enqueue( msg );
}
}
}
}
}
}
void ibc_plugin_impl::start_ibc_core_timer( ){
static int i = 0;
if ( count_open_sockets() != 0 ){
try {
// this is used for let ibc_heartbeat_timer work and exchange basic infomation first.
if ( i < 5 ){
++i;
} else {
ibc_core_checker();
}
} FC_LOG_AND_DROP()
} else {
// when reconnect with peer plugin node
i = 0;
fc_elog(logger,"count_open_sockets() == 0");
}
ibc_core_timer->expires_from_now( ibc_core_interval );
ibc_core_timer->async_wait( [this](boost::system::error_code ec) {
start_ibc_core_timer();
if( ec) {
fc_wlog(logger,"start_ibc_core_timer error: ${m}", ("m", ec.message()));
}
});
}
void ibc_plugin_impl::connection_monitor(std::weak_ptr<connection> from_connection) {
auto max_time = fc::time_point::now();
max_time += fc::milliseconds(max_cleanup_time_ms);
auto from = from_connection.lock();
auto it = (from ? connections.find(from) : connections.begin());
if (it == connections.end()) it = connections.begin();
while (it != connections.end()) {
if (fc::time_point::now() >= max_time) {
start_conn_timer(std::chrono::milliseconds(1), *it); // avoid exhausting
return;
}
if( !(*it)->socket->is_open() && !(*it)->connecting) {
if( (*it)->peer_addr.length() > 0) {
connect(*it);
}
else {
it = connections.erase(it);
continue;
}
}
++it;
}
start_conn_timer(connector_period, std::weak_ptr<connection>());
}
void ibc_plugin_impl::close(const connection_ptr& c) {
if( c->peer_addr.empty() && c->socket->is_open() ) {
if (num_clients == 0) {
fc_wlog( logger, "num_clients already at 0");
}
else {
--num_clients;
}
}
c->close();
}
void ibc_plugin_impl::start_conn_timer(boost::asio::steady_timer::duration du, std::weak_ptr<connection> from_connection) {
connector_check->expires_from_now( du);
connector_check->async_wait( [this, from_connection](boost::system::error_code ec) {
if( !ec) {
connection_monitor(from_connection);
}
else {
fc_elog(logger,"Error from connection check monitor: ${m}",( "m", ec.message()));
start_conn_timer( connector_period, std::weak_ptr<connection>());
}
});
}
void ibc_plugin_impl::start_monitors() {
connector_check.reset(new boost::asio::steady_timer( app().get_io_service() ));
start_conn_timer(connector_period, std::weak_ptr<connection>());
ibc_heartbeat_timer.reset(new boost::asio::steady_timer( app().get_io_service() ));
start_ibc_heartbeat_timer();
ibc_core_timer.reset(new boost::asio::steady_timer( app().get_io_service() ));
start_ibc_core_timer();
}
void ibc_plugin_impl::ticker() {
keepalive_timer->expires_from_now (keepalive_interval);
keepalive_timer->async_wait ([this](boost::system::error_code ec) {
ticker ();
if (ec) {
fc_wlog(logger,"Peer keepalive ticked sooner than expected: ${m}", ("m", ec.message()));
}
for (auto &c : connections ) {
if (c->socket->is_open()) {
c->send_time();
}
}
});
}
bool ibc_plugin_impl::authenticate_peer(const handshake_message& msg) const {
if(allowed_connections == None)
return false;
if(allowed_connections == Any)
return true;
if(allowed_connections == Specified) {
auto allowed_it = std::find(allowed_peers.begin(), allowed_peers.end(), msg.key);
auto private_it = private_keys.find(msg.key);
if( allowed_it == allowed_peers.end() && private_it == private_keys.end() ) {
fc_elog(logger,"Peer ${peer} sent a handshake with an unauthorized key: ${key}.",
("peer", msg.p2p_address)("key", msg.key));
return false;
}
}
namespace sc = std::chrono;
sc::system_clock::duration msg_time(msg.time);
auto time = sc::system_clock::now().time_since_epoch();
if(time - msg_time > peer_authentication_interval) {
fc_elog(logger,"Peer ${peer} sent a handshake with a timestamp skewed by more than ${time}.",
("peer", msg.p2p_address)("time", "1 second")); // TODO Add to_variant for std::chrono::system_clock::duration
return false;
}
if(msg.sig != chain::signature_type() && msg.token != sha256()) {
sha256 hash = fc::sha256::hash(msg.time);
if(hash != msg.token) {
fc_elog(logger,"Peer ${peer} sent a handshake with an invalid token.",
("peer", msg.p2p_address));
return false;
}
chain::public_key_type peer_key;
try {
peer_key = crypto::public_key(msg.sig, msg.token, true);
}
catch (fc::exception& /*e*/) {
fc_elog(logger,"Peer ${peer} sent a handshake with an unrecoverable key.",
("peer", msg.p2p_address));
return false;
}
if((allowed_connections & Specified) && peer_key != msg.key) {
fc_elog(logger,"Peer ${peer} sent a handshake with an unauthenticated key.",
("peer", msg.p2p_address));
return false;
}
}
else if(allowed_connections & Specified) {
fc_dlog(logger,"Peer sent a handshake with blank signature and token, but this node accepts only authenticated connections.");
return false;
}
return true;
}
chain::public_key_type ibc_plugin_impl::get_authentication_key() const {
if(!private_keys.empty())
return private_keys.begin()->first;
return chain::public_key_type();
}
chain::signature_type ibc_plugin_impl::sign_compact(const chain::public_key_type& signer, const fc::sha256& digest) const {
auto private_key_itr = private_keys.find(signer);
if(private_key_itr != private_keys.end())
return private_key_itr->second.sign(digest);
return chain::signature_type();
}
connection_ptr ibc_plugin_impl::find_connection( string host )const {
for( const auto& c : connections )
if( c->peer_addr == host ) return c;
return connection_ptr();
}
//--------------- handshake_initializer ---------------
void handshake_initializer::populate( handshake_message &hello) {
namespace sc = std::chrono;
hello.network_version = net_version;
hello.chain_id = my_impl->chain_id;
hello.node_id = my_impl->node_id;
hello.key = my_impl->get_authentication_key();
hello.time = sc::duration_cast<sc::nanoseconds>(sc::system_clock::now().time_since_epoch()).count();
hello.token = fc::sha256::hash(hello.time);
hello.sig = my_impl->sign_compact(hello.key, hello.token);
// If we couldn't sign, don't send a token.
if(hello.sig == chain::signature_type())
hello.token = sha256();
hello.p2p_address = my_impl->p2p_address + " - " + hello.node_id.str().substr(0,7);
#if defined( __APPLE__ )
hello.os = "osx";
#elif defined( __linux__ )
hello.os = "linux";
#elif defined( _MSC_VER )
hello.os = "win32";
#else
hello.os = "other";
#endif
hello.agent = my_impl->user_agent_name;
controller& cc = my_impl->chain_plug->chain();
hello.head_id = fc::sha256();
hello.last_irreversible_block_id = fc::sha256();
hello.head_num = cc.fork_db_pending_head_block_num();
hello.last_irreversible_block_num = cc.last_irreversible_block_num();
if( hello.last_irreversible_block_num ) {
try {
hello.last_irreversible_block_id = cc.get_block_id_for_num(hello.last_irreversible_block_num);
}
catch( const unknown_block_exception &ex) {
fc_wlog( logger, "caught unkown_block" );
hello.last_irreversible_block_num = 0;
}
}
if( hello.head_num ) {
try {
hello.head_id = cc.get_block_id_for_num( hello.head_num );
}
catch( const unknown_block_exception &ex) {
hello.head_num = 0;
}
}
}
//--------------- ibc_plugin ---------------
ibc_plugin::ibc_plugin()
:my( new ibc_plugin_impl ) {
my_impl = my.get();
}
ibc_plugin::~ibc_plugin() {
}
void ibc_plugin::set_program_options( options_description& /*cli*/, options_description& cfg )
{
cfg.add_options()
( "ibc-chain-contract", bpo::value<string>(), "Name of this chain's ibc chain contract")
( "ibc-token-contract", bpo::value<string>(), "Name of this chain's ibc token contract")
( "ibc-relay-name", bpo::value<string>(), "ID of relay controlled by this node (e.g. relayone)")
( "ibc-relay-private-key", bpo::value<string>(), "Key=Value pairs in the form <public-key>=KEY:<private-key>\n"
" <public-key> \tis a string form of a vaild EOSIO public key\n\n"
" <private-key> \tis a string form of a valid EOSIO private key which maps to the provided public key\n\n")
( "ibc-listen-endpoint", bpo::value<string>()->default_value( "0.0.0.0:5678" ), "The actual host:port used to listen for incoming ibc connections.")
( "ibc-server-address", bpo::value<string>(), "An externally accessible host:port for identifying this node. Defaults to ibc-listen-endpoint.")
( "ibc-agent-name", bpo::value<string>()->default_value("\"EOSIO IBC Agent\""), "The name supplied to identify this node amongst the peers.")
( "ibc-peer-chain-id", bpo::value<string>()->default_value(""), "The peer chain's chain id")
( "ibc-peer-address", bpo::value<vector<string>>()->composing(), "The public endpoint of a peer node to connect to. Use multiple ibc-peer-address options as needed to compose a network.")
( "ibc-allowed-connection", bpo::value<string>()->default_value( "any" ), "Can be 'any' or 'specified'. If 'specified', 'ibc-peer-key' must be specified at least once.")
( "ibc-peer-key", bpo::value<vector<string>>()->composing()->multitoken(), "Optional public key of peer allowed to connect. May be used multiple times.")
( "ibc-peer-private-key", bpo::value<vector<string>>()->composing()->multitoken(), "Key=Value pairs in the form <public-key>=KEY:<private-key>\n"
" <public-key> \tis a string form of a vaild EOSIO public key\n\n"
" <private-key> \tis a string form of a valid EOSIO private key which maps to the provided public key\n\n")
( "ibc-max-clients", bpo::value<int>()->default_value(def_max_clients), "Maximum number of clients from which connections are accepted, use 0 for no limit")
( "ibc-max-nodes-per-host", bpo::value<int>()->default_value(def_max_nodes_per_host), "Maximum number of client nodes from any single IP address")
( "ibc-connection-cleanup-period", bpo::value<int>()->default_value(def_conn_retry_wait), "Number of seconds to wait before cleaning up dead connections")
( "ibc-max-cleanup-time-msec", bpo::value<int>()->default_value(10), "Maximum connection cleanup time per cleanup call in millisec")
( "ibc-version-match", bpo::value<bool>()->default_value(false), "True to require exact match of ibc plugin version.")
( "ibc-log-format", bpo::value<string>()->default_value( "[\"${_name}\" ${_ip}:${_port}]" ),
"The string used to format peers when logging messages about them. Variables are escaped with ${<variable name>}.\n"
"Available Variables:\n"
" _name \tself-reported name\n\n"
" _id \tself-reported ID (64 hex characters)\n\n"
" _sid \tfirst 8 characters of _peer.id\n\n"
" _ip \tremote IP address of peer\n\n"
" _port \tremote port number of peer\n\n"
" _lip \tlocal IP address connected to peer\n\n"
" _lport \tlocal port number connected to peer\n\n")
;
}
template<typename T>
T dejsonify(const string& s) {
return fc::json::from_string(s).as<T>();
}
#define OPTION_ASSERT( option ) EOS_ASSERT( options.count( option ) && options.at( option ).as<string>() != string(), chain::plugin_config_exception, option " not specified" );
void ibc_plugin::plugin_initialize( const variables_map& options ) {
fc_ilog(logger,"Initialize ibc plugin");
try {
OPTION_ASSERT( "ibc-chain-contract" )
my->chain_contract.reset( new ibc_chain_contract( eosio::chain::name{ options.at("ibc-chain-contract").as<string>()}));
fc_ilog(logger,"ibc chain contract account is ${name}", ("name", options.at("ibc-chain-contract").as<string>()));
OPTION_ASSERT( "ibc-token-contract" )
my->token_contract.reset( new ibc_token_contract( eosio::chain::name{ options.at("ibc-token-contract").as<string>()}));
fc_ilog(logger,"ibc token contract account is ${name}", ("name", options.at("ibc-token-contract").as<string>()));
OPTION_ASSERT( "ibc-relay-name" )
my->relay = eosio::chain::name{ options.at("ibc-relay-name").as<string>() };
fc_ilog(logger,"ibc relay account is ${name}", ("name", options.at("ibc-relay-name").as<string>()));
auto get_key = [=]( string key_spec_pair ) -> std::pair<public_key_type,private_key_type> {
auto delim = key_spec_pair.find("=");
EOS_ASSERT(delim != std::string::npos, plugin_config_exception, "Missing \"=\" in the key spec pair");
auto pub_key_str = key_spec_pair.substr(0, delim);
auto spec_str = key_spec_pair.substr(delim + 1);
auto spec_delim = spec_str.find(":");
EOS_ASSERT(spec_delim != std::string::npos, plugin_config_exception, "Missing \":\" in the key spec pair");
auto spec_type_str = spec_str.substr(0, spec_delim);
auto spec_data = spec_str.substr(spec_delim + 1);
return std::make_pair( public_key_type(pub_key_str), private_key_type(spec_data) );
};
OPTION_ASSERT( "ibc-relay-private-key" )
const auto& key_spec_pair = options.at("ibc-relay-private-key").as<string>();
try {
auto key = get_key( key_spec_pair );
my->relay_private_key = key.second;
fc_ilog(logger,"ibc relay public key is ${key}", ("key", key.first));
} catch (...) {
EOS_ASSERT( false, chain::plugin_config_exception, "Malformed ibc-relay-private-key: \"${val}\"", ("val", key_spec_pair));
}
if( options.count( "ibc-listen-endpoint" ) && options.at( "ibc-listen-endpoint" ).as<string>().length()) {
my->p2p_address = options.at( "ibc-listen-endpoint" ).as<string>();
}
if( options.count( "ibc-server-address" )) {
my->p2p_server_address = options.at( "ibc-server-address" ).as<string>();
}
if( options.count( "ibc-agent-name" )) {
my->user_agent_name = options.at( "ibc-agent-name" ).as<string>();
}
my->peerchain_id = fc::sha256( options.at( "ibc-peer-chain-id" ).as<string>() );
fc_ilog(logger,"ibc peer chain id is ${id}", ("id", my->peerchain_id.str()));
if( options.count( "ibc-peer-address" )) {
my->supplied_peers = options.at( "ibc-peer-address" ).as<vector<string> >();
}
if( options.count( "ibc-allowed-connection" )) {
const std::string allowed_remote = options["ibc-allowed-connection"].as<std::string>();
EOS_ASSERT( allowed_remote == "any" || allowed_remote == "specified" , plugin_config_exception,
"'ibc-allowed-connection' must be 'any' or 'specified'" );
if( allowed_remote == "specified" )
my->allowed_connections = ibc_plugin_impl::Specified;
else
my->allowed_connections = ibc_plugin_impl::Any;
}
if( my->allowed_connections & ibc_plugin_impl::Specified )
EOS_ASSERT( options.count( "ibc-peer-key" ), plugin_config_exception,
"At least one ibc-peer-key must accompany 'ibc-allowed-connection = specified'" );
if( options.count( "ibc-peer-key" )) {
const std::vector<std::string> key_strings = options["ibc-peer-key"].as<std::vector<std::string>>();
for( const std::string& key_string : key_strings ) {
my->allowed_peers.push_back( chain::public_key_type( key_string ));
}
}
if( options.count("ibc-peer-private-key") ) {
const std::vector<std::string> key_spec_pairs = options["ibc-peer-private-key"].as<std::vector<std::string>>();
for (const auto& key_spec_pair : key_spec_pairs) {
try {
auto key = get_key( key_spec_pair );
my->private_keys[key.first] = key.second;
} catch (...) {
fc_elog(logger,"Malformed ibc-peer-private-key: \"${val}\", ignoring!", ("val", key_spec_pair));
}
}
}
my->max_client_count = options.at( "ibc-max-clients" ).as<int>();
my->max_nodes_per_host = options.at( "ibc-max-nodes-per-host" ).as<int>();
my->connector_period = std::chrono::seconds( options.at( "ibc-connection-cleanup-period" ).as<int>());
my->max_cleanup_time_ms = options.at("ibc-max-cleanup-time-msec").as<int>();
my->num_clients = 0;
my->started_sessions = 0;
my->network_version_match = options.at( "ibc-version-match" ).as<bool>();
peer_log_format = options.at( "ibc-log-format" ).as<string>();
my->chain_plug = app().find_plugin<chain_plugin>();
EOS_ASSERT( my->chain_plug, chain::missing_chain_plugin_exception, "missing chain plugin");
my->chain_id = app().get_plugin<chain_plugin>().get_chain_id();
fc::rand_pseudo_bytes( my->node_id.data(), my->node_id.data_size());
} FC_LOG_AND_RETHROW()
}
void ibc_plugin::plugin_startup() {
// currently thread_pool only used for server_ioc
my->thread_pool.emplace( "ibc", my->thread_pool_size );
shared_ptr<tcp::resolver> resolver = std::make_shared<tcp::resolver>( app().get_io_service() );
if( my->p2p_address.size() > 0 ) {
auto host = my->p2p_address.substr( 0, my->p2p_address.find( ':' ));
auto port = my->p2p_address.substr( host.size() + 1, my->p2p_address.size());
tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str());
// Note: need to add support for IPv6 too?
my->listen_endpoint = *resolver->resolve( query );
my->acceptor.reset( new tcp::acceptor( app().get_io_service() ) );
if( !my->p2p_server_address.empty() ) {
my->p2p_address = my->p2p_server_address;
} else {
if( my->listen_endpoint.address().to_v4() == address_v4::any()) {
boost::system::error_code ec;
auto host = host_name( ec );
if( ec.value() != boost::system::errc::success ) {
FC_THROW_EXCEPTION( fc::invalid_arg_exception,
"Unable to retrieve host_name. ${msg}", ("msg", ec.message()));
}
auto port = my->p2p_address.substr( my->p2p_address.find( ':' ), my->p2p_address.size());
my->p2p_address = host + port;
}
}
}
my->keepalive_timer.reset( new boost::asio::steady_timer( app().get_io_service() ) );
my->ticker();
if( my->acceptor ) {
my->acceptor->open(my->listen_endpoint.protocol());
my->acceptor->set_option(tcp::acceptor::reuse_address(true));
try {
my->acceptor->bind(my->listen_endpoint);
} catch (const std::exception& e) {
fc_elog( logger, "ibc_plugin::plugin_startup failed to bind to port ${port}",
("port", my->listen_endpoint.port()));
throw e;
}
my->acceptor->listen();
fc_ilog( logger, "starting listener, max clients is ${mc}",("mc",my->max_client_count) );
my->start_listen_loop();
}
chain::controller&cc = my->chain_plug->chain();
{
cc.irreversible_block.connect( boost::bind(&ibc_plugin_impl::irreversible_block, my.get(), _1));
}
my->start_monitors();
for( auto seed_node : my->supplied_peers ) {
connect( seed_node );
}
handle_sighup();
}
void ibc_plugin::handle_sighup() {
fc::logger::update( logger_name, logger );
}
void ibc_plugin::plugin_shutdown() {
try {
fc_ilog( logger, "shutdown.." );
if( my->connector_check )
my->connector_check->cancel();
if( my->keepalive_timer )
my->keepalive_timer->cancel();
my->done = true;
if( my->acceptor ) {
fc_ilog( logger, "close acceptor" );
my->acceptor->cancel();
my->acceptor->close();
fc_ilog( logger, "close ${s} connections",( "s",my->connections.size()) );
for( auto& con : my->connections ) {
fc_dlog( logger, "close: ${p}", ("p",con->peer_name()) );
my->close( con );
}
my->connections.clear();
}
if( my->thread_pool ) {
my->thread_pool->stop();
}
app().post( 0, [me = my](){} ); // keep my pointer alive until queue is drained
fc_ilog( logger, "exit shutdown" );
}
FC_CAPTURE_AND_RETHROW()
}
size_t ibc_plugin::num_peers() const {
return my->count_open_sockets();
}
/**
* Used to trigger a new connection from RPC API
*/
string ibc_plugin::connect( const string& host ) {
if( my->find_connection( host ) )
return "already connected";
connection_ptr c = std::make_shared<connection>(host);
fc_dlog(logger,"adding new connection to the list");
my->connections.insert( c );
fc_dlog(logger,"calling active connector");
my->connect( c );
return "added connection";
}
string ibc_plugin::disconnect( const string& host ) {
for( auto itr = my->connections.begin(); itr != my->connections.end(); ++itr ) {
if( (*itr)->peer_addr == host ) {
(*itr)->reset();
fc_ilog( logger, "disconnecting: ${p}", ("p", (*itr)->peer_name()) );
my->close(*itr);
my->connections.erase(itr);
return "connection removed";
}
}
return "no known connection for host";
}
optional<connection_status> ibc_plugin::status( const string& host )const {
auto con = my->find_connection( host );
if( con )
return con->get_status();
return optional<connection_status>();
}
vector<connection_status> ibc_plugin::connections()const {
vector<connection_status> result;
result.reserve( my->connections.size() );
for( const auto& c : my->connections ) {
result.push_back( c->get_status() );
}
return result;
}
}}
|
/*
*************************************************************************
ArmageTron -- Just another Tron Lightcycle Game in 3D.
Copyright (C) 2000 Manuel Moos (manuel@moosnet.de)
**************************************************************************
This program 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.
This program 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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
***************************************************************************
*/
#define NO_MALLOC_REPLACEMENT
#include "tMemManager.h"
#include <iostream>
#include <stdlib.h>
#include <string>
#include "tArray.h"
#include <string.h>
void GrowingArrayBase::Swap( GrowingArrayBase & other )
{
::Swap( len, other.len );
::Swap( size, other.size );
::Swap( base, other.base );
}
void GrowingArrayBase::ComplainIfFull(){
if (Len()>0)
tERR_ERROR("Array should be empty.");
}
GrowingArrayBase::GrowingArrayBase(int firstsize,int size_of_T, bool useMalloc)
{
// dump(low,dump,"con:size " << firstsize << ",element size " << size_of_T);
len=firstsize;
if (firstsize) size=firstsize;
else size=1;
if ( useMalloc )
base=malloc(size * size_of_T);
else
base=tNEW( char[size * size_of_T] );
if(NULL==base) {
tERR_ERROR("Error Allocating " << size_of_T*(size) << " bytes." );
}
for(int i=size*size_of_T-1;i>=0;i--)
(reinterpret_cast<char *>(base))[i]=0;
}
GrowingArrayBase::~GrowingArrayBase(){
tASSERT( base == NULL );
// dump(very_low,flow,"des");
}
void GrowingArrayBase::Delete( bool useMalloc ){
// dump(very_low,flow,"des");
if ( useMalloc )
{
free(base);
}
else
{
delete[] (char*)base;
}
base = NULL;
size = len = 0;
}
void GrowingArrayBase::ResizeBase(int i,int size_of_T, bool useMalloc){
i++;
// dump(very_low,flow,"Array-base resize");
unsigned int oldsize=size;
int size_a=i+(1<<12);
int size_b=i+(i>>2);
int new_size;
if (size_a<size_b)
new_size=size_a;
else
new_size=size_b;
// void *newbase=NULL;//realloc(base,size_of_T*(size));
// void *newbase=realloc(base,size_of_T*(size));
// if(NULL==newbase){
void *newbase;
if ( useMalloc )
newbase = malloc(new_size * size_of_T);
else
newbase=tNEW( char[new_size * size_of_T] );
if(NULL==newbase){
tERR_ERROR("Error reallocating " << size_of_T*(new_size) << " bytes.");
}
else{
memcpy(newbase,base,size_of_T*(oldsize));
if ( useMalloc )
{
free(base);
}
else
{
delete[] (char*)base;
}
}
//
size = new_size;
// clear the newly allocated memory
char *start=(reinterpret_cast<char *>(newbase)) + oldsize*size_of_T;
for(int j=(size-oldsize)*size_of_T-1;j>=0;j--)
start[j]=0;
base=newbase;
}
|
/*
Project: SSBRenderer
File: path.cpp
Copyright (c) 2015, Christoph "Youka" Spanknebel
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../gutils.hpp"
#include <stdexcept>
#include <iostream>
using namespace GUtils;
using PType = PathSegment::Type;
static void print_path(const std::vector<GUtils::PathSegment>& path){
for(auto& segment : path)
switch(segment.type){
case PType::MOVE: std::cout << "M " << segment.x << '|' << segment.y << std::endl; break;
case PType::LINE: std::cout << "L " << segment.x << '|' << segment.y << std::endl; break;
case PType::CURVE: std::cout << "B " << segment.x << '|' << segment.y << std::endl; break;
case PType::CLOSE: std::cout << 'C' << std::endl; break;
}
}
int main(){
std::vector<PathSegment> path{
{PType::MOVE, 10, 20.5},
{PType::LINE, 19, 11},
{PType::CURVE, 14, 3},
{PType::CURVE, 11, 13},
{PType::CURVE, 9, 10},
};
double x0, y0, x1, y1;
if(!path_extents(path, &x0, &y0, &x1, &y1) || x0 != 9 || y0 != 3 || x1 != 19 || y1 != 20.5)
throw std::logic_error("Path extents aren't right");
path_close(path);
if(path.back().type != PType::CLOSE)
throw std::logic_error("Path closing didn't happen");
Matrix4x4d mat;
print_path(path_transform(path, mat.translate(5, 7.2, -3))),
print_path(path_flatten(path, 0.035)),
print_path(path_by_arc(0, 30, 30, 30, 3.2));
return 0;
}
|
// Copyright 2021 The Fuchsia 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 <lib/elfldltl/memory.h>
#include <lib/stdcompat/span.h>
#include <string_view>
#include <zxtest/zxtest.h>
namespace {
using namespace std::literals;
constexpr uintptr_t kBaseAddress = 0x12340;
constexpr std::string_view kHeaderBytes = "HeaderOf16Bytes\0"sv;
struct Header {
char bytes_[16];
};
TEST(ElfldltlDirectMemoryTests, FileApi) {
char file_image[] = "HeaderOf16Bytes\0Dataaabb";
auto image_bytes = cpp20::as_writable_bytes(cpp20::span(file_image));
elfldltl::DirectMemory file(image_bytes, kBaseAddress);
auto header = file.ReadFromFile<Header>(0);
ASSERT_TRUE(header.has_value());
std::string_view header_bytes(header->get().bytes_, 16);
EXPECT_EQ(header_bytes, kHeaderBytes);
auto bad_offset = file.ReadFromFile<uint32_t>(30);
EXPECT_FALSE(bad_offset.has_value());
auto array = file.ReadArrayFromFile<char, 32>(16, 4);
ASSERT_TRUE(array.has_value());
EXPECT_EQ(4, array->size());
EXPECT_STREQ(std::string_view(array->data(), array->size()), "Data");
auto array2 = file.ReadArrayFromFile<uint16_t, 32>(20, 2);
ASSERT_TRUE(array2.has_value());
ASSERT_EQ(2, array2->size());
EXPECT_EQ(uint16_t{('a' << 8) | 'a'}, (*array2)[0]);
EXPECT_EQ(uint16_t{('b' << 8) | 'b'}, (*array2)[1]);
auto bad_array = file.ReadArrayFromFile<uint32_t, 36>(24, 36);
EXPECT_FALSE(bad_array.has_value());
}
TEST(ElfldltlDirectMemoryTests, MemoryApi) {
char file_image[] = "HeaderOf16Bytes\0Dataaabb";
auto image_bytes = cpp20::as_writable_bytes(cpp20::span(file_image));
elfldltl::DirectMemory file(image_bytes, kBaseAddress);
auto array = file.ReadArray<char>(kBaseAddress + 16, 4);
ASSERT_TRUE(array.has_value());
EXPECT_EQ(4, array->size());
EXPECT_STREQ(std::string_view(array->data(), array->size()), "Data");
auto bad_address_low = file.ReadArray<uint64_t>(kBaseAddress - 4, 16);
EXPECT_FALSE(bad_address_low.has_value());
auto bad_address_high = file.ReadArray<uint64_t>(kBaseAddress + 40, 16);
EXPECT_FALSE(bad_address_high.has_value());
auto unbounded = file.ReadArray<char>(kBaseAddress + 16);
ASSERT_TRUE(unbounded.has_value());
EXPECT_EQ(9, unbounded->size());
EXPECT_EQ(array->data(), unbounded->data());
EXPECT_TRUE(file.Store<uint32_t>(kBaseAddress + 16, 0xaabbccdd));
EXPECT_EQ(0xaabbccdd, *reinterpret_cast<uint32_t*>(file_image + 16));
EXPECT_TRUE(file.StoreAdd<uint32_t>(kBaseAddress + 16, 0x11111111));
EXPECT_EQ(0xbbccddee, *reinterpret_cast<uint32_t*>(file_image + 16));
EXPECT_FALSE(file.Store<uint32_t>(kBaseAddress - 4, 0x12345678));
EXPECT_FALSE(file.Store<uint32_t>(kBaseAddress + 40, 0x12345678));
EXPECT_FALSE(file.StoreAdd<uint32_t>(kBaseAddress - 4, 0x12345678));
EXPECT_FALSE(file.StoreAdd<uint32_t>(kBaseAddress + 40, 0x12345678));
}
} // namespace
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: OVR.OpenVR.EVRNotificationType
// [TokenAttribute] Offset: FFFFFFFF
struct EVRNotificationType/*, public System::Enum*/ {
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: EVRNotificationType
constexpr EVRNotificationType(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public OVR.OpenVR.EVRNotificationType Transient
static constexpr const int Transient = 0;
// Get static field: static public OVR.OpenVR.EVRNotificationType Transient
static OVR::OpenVR::EVRNotificationType _get_Transient();
// Set static field: static public OVR.OpenVR.EVRNotificationType Transient
static void _set_Transient(OVR::OpenVR::EVRNotificationType value);
// static field const value: static public OVR.OpenVR.EVRNotificationType Persistent
static constexpr const int Persistent = 1;
// Get static field: static public OVR.OpenVR.EVRNotificationType Persistent
static OVR::OpenVR::EVRNotificationType _get_Persistent();
// Set static field: static public OVR.OpenVR.EVRNotificationType Persistent
static void _set_Persistent(OVR::OpenVR::EVRNotificationType value);
// static field const value: static public OVR.OpenVR.EVRNotificationType Transient_SystemWithUserValue
static constexpr const int Transient_SystemWithUserValue = 2;
// Get static field: static public OVR.OpenVR.EVRNotificationType Transient_SystemWithUserValue
static OVR::OpenVR::EVRNotificationType _get_Transient_SystemWithUserValue();
// Set static field: static public OVR.OpenVR.EVRNotificationType Transient_SystemWithUserValue
static void _set_Transient_SystemWithUserValue(OVR::OpenVR::EVRNotificationType value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // OVR.OpenVR.EVRNotificationType
#pragma pack(pop)
static check_size<sizeof(EVRNotificationType), 0 + sizeof(int)> __OVR_OpenVR_EVRNotificationTypeSizeCheck;
static_assert(sizeof(EVRNotificationType) == 0x4);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::EVRNotificationType, "OVR.OpenVR", "EVRNotificationType");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
|
//
// Connector.cpp
//
// $Id: //poco/Main/Data/ODBC/src/Connector.cpp#2 $
//
// Library: Data/ODBC
// Package: ODBC
// Module: Connector
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Data/ODBC/Connector.h"
#include "Poco/Data/ODBC/SessionImpl.h"
#include "Poco/Data/SessionFactory.h"
namespace Poco {
namespace Data {
namespace ODBC {
const std::string Connector::KEY("ODBC");
Connector::Connector()
{
}
Connector::~Connector()
{
}
Poco::AutoPtr<Poco::Data::SessionImpl> Connector::createSession(const std::string& connectionString,
std::size_t timeout)
{
return Poco::AutoPtr<Poco::Data::SessionImpl>(new SessionImpl(connectionString, timeout));
}
void Connector::registerConnector()
{
Poco::Data::SessionFactory::instance().add(new Connector());
}
void Connector::unregisterConnector()
{
Poco::Data::SessionFactory::instance().remove(KEY);
}
} } } // namespace Poco::Data::ODBC
|
/************************************************************
*
* CmdAcceptInvoices.hpp
*
*/
/************************************************************
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
*
* EMAIL:
* FellowTraveler@rayservers.net
*
* BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
*
* KEY FINGERPRINT (PGP Key in license file):
* 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
*
* OFFICIAL PROJECT WIKI(s):
* https://github.com/FellowTraveler/Moneychanger
* https://github.com/FellowTraveler/Open-Transactions/wiki
*
* WEBSITE:
* http://www.OpenTransactions.org/
*
* Components and licensing:
* -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
* -- otlib.........A class library.......LICENSE:...LAGPLv3
* -- otapi.........A client API..........LICENSE:...LAGPLv3
* -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
* -- otserver......Server Application....LICENSE:....AGPLv3
* Github.com/FellowTraveler/Open-Transactions/wiki/Components
*
* All of the above OT components were designed and written by
* Fellow Traveler, with the exception of Moneychanger, which
* was contracted out to Vicky C (bitcointrader4@gmail.com).
* The open-source community has since actively contributed.
*
* -----------------------------------------------------
*
* LICENSE:
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* ADDITIONAL PERMISSION under the GNU Affero GPL version 3
* section 7: (This paragraph applies only to the LAGPLv3
* components listed above.) If you modify this Program, or
* any covered work, by linking or combining it with other
* code, such other code is not for that reason alone subject
* to any of the requirements of the GNU Affero GPL version 3.
* (==> This means if you are only using the OT API, then you
* don't have to open-source your code--only your changes to
* Open-Transactions itself must be open source. Similar to
* LGPLv3, except it applies to software-as-a-service, not
* just to distributing binaries.)
*
* Extra WAIVER for OpenSSL, Lucre, and all other libraries
* used by Open Transactions: This program is released under
* the AGPL with the additional exemption that compiling,
* linking, and/or using OpenSSL is allowed. The same is true
* for any other open source libraries included in this
* project: complete waiver from the AGPL is hereby granted to
* compile, link, and/or use them with Open-Transactions,
* according to their own terms, as long as the rest of the
* Open-Transactions terms remain respected, with regard to
* the Open-Transactions code itself.
*
* Lucre License:
* This code is also "dual-license", meaning that Ben Lau-
* rie's license must also be included and respected, since
* the code for Lucre is also included with Open Transactions.
* See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
* The Laurie requirements are light, but if there is any
* problem with his license, simply remove the Lucre code.
* Although there are no other blind token algorithms in Open
* Transactions (yet. credlib is coming), the other functions
* will continue to operate.
* See Lucre on Github: https://github.com/benlaurie/lucre
* -----------------------------------------------------
* You should have received a copy of the GNU Affero General
* Public License along with this program. If not, see:
* http://www.gnu.org/licenses/
*
* If you would like to use this software outside of the free
* software license, please contact FellowTraveler.
* (Unfortunately many will run anonymously and untraceably,
* so who could really stop them?)
*
* DISCLAIMER:
* This program 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 Affero General Public License for
* more details.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Darwin)
iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
kamH0Y/n11lCvo1oQxM+
=uSzz
-----END PGP SIGNATURE-----
**************************************************************/
#ifndef OPENTXS_CLIENT_CMDACCEPTINVOICES_HPP
#define OPENTXS_CLIENT_CMDACCEPTINVOICES_HPP
#include "CmdBaseAccept.hpp"
namespace opentxs
{
class CmdAcceptInvoices : public CmdBaseAccept
{
public:
EXPORT CmdAcceptInvoices();
virtual ~CmdAcceptInvoices();
EXPORT int32_t run(std::string myacct, std::string indices);
protected:
virtual int32_t runWithOptions();
};
} // namespace opentxs
#endif // OPENTXS_CLIENT_CMDACCEPTINVOICES_HPP
|
#include "noosascript.h"
#include "game.h"
#include "../pd/quad.h"
#include "../engine/util.h"
const char* VERT_SHADER = R"(
uniform mat4 uCamera;
uniform mat4 uModel;
attribute vec4 aXYZW;
attribute vec2 aUV;
varying vec2 vUV;
void main() {
gl_Position = uCamera * uModel * aXYZW;
vUV = aUV;
}
)";
const char* FRAG_SHADER = R"(
precision mediump float;
varying vec2 vUV;
uniform sampler2D uTex;
uniform vec4 uColorM;
uniform vec4 uColorA;
void main() {
gl_FragColor = texture2D( uTex, vUV ) * uColorM + uColorA;
}
)";
const char* VERT_SHADER_TEST = R"(
uniform mat4 uCamera;
uniform mat4 uModel;
attribute vec2 aPos;
attribute vec2 aUV;
varying vec2 vUV;
void main() {
gl_Position.xy = (uCamera * uModel * vec4(aPos, 0, 1)).xy;
//gl_Position.xy = aXYZW;
gl_Position.z = 0.0;
gl_Position.w = 1.0;
vUV = aUV;
}
)";
const char* FRAG_SHADER_TEST = R"(
precision mediump float;
varying vec2 vUV;
uniform sampler2D uTex;
uniform vec4 uColorM;
uniform vec4 uColorA;
void main() {
gl_FragColor = texture2D( uTex, vUV )* uColorM + uColorA;
//gl_FragColor = vec4(1,0,0,1);
//gl_FragColor = texture2D( uTex, vUV );
}
)";
NoosaScript::NoosaScript()
{
compile(VERT_SHADER_TEST, FRAG_SHADER_TEST);
uCamera = uniform("uCamera");
uModel = uniform("uModel");
uTex = uniform("uTex");
uColorM = uniform("uColorM");
uColorA = uniform("uColorA");
aXY = attribute("aPos");
aUV = attribute("aUV");
}
void NoosaScript::use()
{
Script::use();
aXY.enable();
aUV.enable();
}
void NoosaScript::lighting(float rm, float gm, float bm, float am, float ra, float ga, float ba, float aa)
{
uColorM.value4f(rm, gm, bm, am);
uColorA.value4f(ra, ga, ba, aa);
}
NoosaScript* NoosaScript::get()
{
Script* sc = Script::get<NoosaScript>();
//if (sc == NULL)
//{
// Script::_all.insert(std::make_pair("NoosaScript", new NoosaScript()));
// return dynamic_cast<NoosaScript*>(Script::get("NoosaScript"));
//}
return dynamic_cast<NoosaScript*>(sc);
}
void NoosaScript::camera(Camera* camera)
{
if (camera == NULL)
{
camera = Camera::mainCamera;
}
if (camera != _lastCamera)
{
_lastCamera = camera;
//uCamera.valueM4(camera->mat);
glScissor(
camera->x,
Game::height - camera->screenHeightf - camera->y,
camera->screenWidthf,
camera->screenHeightf);
}
}
void NoosaScript::drawQuad(float* buffer)
{
uCamera.valueM4(_lastCamera->mat);
aXY.vertexPointer(2, 4 * sizeof(float), buffer);
aUV.vertexPointer(2, 4 * sizeof(float), buffer + 2);
//std::vector<short>* indices = Quad::getIndices(1);
//glDrawElements(GL_TRIANGLES, Quad::SIZE, GL_UNSIGNED_SHORT, (void*)(&((*indices)[0])));
short indices[] = { 0, 1, 2, 0, 2, 3 };
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)indices);
}
void NoosaScript::drawQuadSet(float* buffer, int size)
{
uCamera.valueM4(_lastCamera->mat);
aXY.vertexPointer(2, 4 * sizeof(float), buffer);
aUV.vertexPointer(2, 4 * sizeof(float), buffer + 2);
static std::vector<short> indices;
if (size*6 > indices.size())
{
indices.resize(size * 6);
int pos = 0;
int limit = size * 4;
for (int ofs = 0; ofs < limit; ofs += 4)
{
indices[pos++] = (short)(ofs + 0);
indices[pos++] = (short)(ofs + 1);
indices[pos++] = (short)(ofs + 2);
indices[pos++] = (short)(ofs + 0);
indices[pos++] = (short)(ofs + 2);
indices[pos++] = (short)(ofs + 3);
}
}
glDrawElements(GL_TRIANGLES, 6*size, GL_UNSIGNED_SHORT, (void*)&indices[0]);
}
void NoosaScript::drawElements(FloatBuffer* vertices, ShortBuffer* indices, int size)
{
vertices->position(0);
aXY.vertexPointer(2, 4, vertices->buffer());
vertices->position(2);
aUV.vertexPointer(2, 4, vertices->buffer());
glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_SHORT, indices->buffer());
}
|
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>
#include <limits.h>
#include <stack>
#include <queue>
#include <iomanip>
#include <list>
#include <set>
#include <deque>
#include <bitset>
#include <map>
#include <assert.h>
#include <utility>
#include <string.h>
#include <cstring>
#include <cstdlib>
#define FOR(A, B, C) for(int A = B; A < C; A++)
#define EFOR(A, B, C) for(int A = B; A <= C; A++)
#define RFOR(A, B, C) for(int A = B; A >= C; A--)
#define SC(A) scanf("%d", &A)
#define PF(A) printf("%d", A)
using namespace std;
typedef long long int lint;
typedef vector<bool> VB;
typedef pair<int,int> PI;
typedef vector<int> VI;
typedef vector<lint> VLI;
typedef vector<PI> VPI;
typedef vector<VI> VVI;
typedef map<int,int> MP;
int inline scan() {
int N = 0;
char C;
C=getchar_unlocked();
while (C < '0' || C>'9') C=getchar_unlocked();
while (C >= '0' && C <= '9')
{
N = (N<<3) + (N<<1) + C - '0';
C=getchar_unlocked();
}
return N;
}
int main() {
int T;
T = scan();
while(T--) {
int c = 1;
int N, A;
N = scan();
A = scan();
FOR(i, 1, N) {
int B;
B = scan();
if(B <= A) {
A = B;
c++;
}
}
printf("%d\n", c);
}
return 0;
}
|
/**
* Copyright 2021 Scott Brauer
*
* Licensed under the Apache License, Version 2.0 (the );
* 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 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 AppManagerApp.cpp
* @author Scott Brauer
* @date 11-29-2021
*/
#include <iostream>
#include <regex>
#include "easylogging++.h"
#include "offcenter/common/InterruptHandler.hpp"
#include "offcenter/common/app_manager/AppManagerApp.hpp"
#include "offcenter/common/Processes.hpp"
#include "offcenter/common/threading/RunningThread.hpp"
namespace offcenter {
namespace common {
namespace appmanager {
/*
* A thread safe print method
*
* value - The string to print
*/
void printString(const std::string& value) {
static std::mutex printMutex;
std::lock_guard<std::mutex> lock {printMutex};
std::cout << "Monitor: " << value << std::endl;
}
/*
*
*/
class MonitorStdOut:
public offcenter::common::threading::RunningThread
{
public:
MonitorStdOut(boost::iostreams::stream<boost::iostreams::file_descriptor_source>& stdOutStream, int millisecondsSleep = 100):
RunningThread(),
m_stdOutStream(stdOutStream),
m_millisecondsSleep(millisecondsSleep)
{}
virtual ~MonitorStdOut() = default;
protected:
void task() override {
std::string message;
std::getline(m_stdOutStream, message);
if (!message.empty()) {
offcenter::common::appmanager::printString(message);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(m_millisecondsSleep));
}
//char gfg[50] = {};
//m_stdOutSourceInStream.readsome(gfg, 3);
//std::cout << gfg;
// char
// std::cout << message;
}
void stopped() override {
// ::printString("ExampleThread1: Stopped");
}
private:
//offcenter::common::ProcessPipeReadWrite& m_stdOutSourceInStream;
boost::iostreams::stream<boost::iostreams::file_descriptor_source>& m_stdOutStream;
int m_millisecondsSleep;
};
AppManagerApp::AppManagerApp():
IApp()
{
}
AppManagerApp::~AppManagerApp() {
// TODO Auto-generated destructor stub
}
void AppManagerApp::onInitProgramOptions(
program_options::ProgramOptionsManager &optionsManager)
{
m_appManagerOptions = optionsManager.add<offcenter::common::appmanager::AppManagerProgramOptions>();
}
void AppManagerApp::onSetUp()
{
}
void AppManagerApp::onExecute()
{
std::vector<std::string> arguments;
offcenter::common::Process::Ptr process = offcenter::common::Process::factory();
MonitorStdOut monitorStdOut(process->stdOutStream());
process->init("${HOME}/dev/github/offcenter_trading_system/build/Debug/bin/waitfor_sigint", arguments);
process->run();
monitorStdOut.run();
std::cout << "AppManagerApp: Waiting for Ctrl-C" << std::endl;
offcenter::common::interrupthandler::waitForUserInterrupt();
std::cout << "AppManagerApp: Ctrl-C pressed" << std::endl;
process->waitSigint();
monitorStdOut.stop();
monitorStdOut.join();
}
void AppManagerApp::onTearDown()
{
}
/**
* Called when help should be displayed.
*
* @param help A string that contains the help
*/
void AppManagerApp::onHelp(const std::string &help)
{
std::cout << help << std::endl;
}
void AppManagerApp::onVersion()
{
}
} /* namespace appmanager */
} /* namespace common */
} /* namespace offcenter */
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2004 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program 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 license for more details.
*/
#include <ql/time/calendars/austria.hpp>
#include <ql/errors.hpp>
namespace QuantLib {
Austria::Austria(Austria::Market market) {
// all calendar instances on the same market share the same
// implementation instance
static ext::shared_ptr<Calendar::Impl> settlementImpl(
new Austria::SettlementImpl);
static ext::shared_ptr<Calendar::Impl> exchangeImpl(
new Austria::ExchangeImpl);
switch (market) {
case Settlement:
impl_ = settlementImpl;
break;
case Exchange:
impl_ = exchangeImpl;
break;
default:
QL_FAIL("unknown market");
}
}
bool Austria::SettlementImpl::isBusinessDay(const Date& date) const {
Weekday w = date.weekday();
Day d = date.dayOfMonth(), dd = date.dayOfYear();
Month m = date.month();
Year y = date.year();
Day em = easterMonday(y);
if (isWeekend(w)
// New Year's Day
|| (d == 1 && m == January)
// Epiphany
|| (d == 6 && m == January)
// Easter Monday
|| (dd == em)
// Ascension Thurday
|| (dd == em+38)
// Whit Monday
|| (dd == em+49)
// Corpus Christi
|| (dd == em+59)
// Labour Day
|| (d == 1 && m == May)
// Assumption
|| (d == 15 && m == August)
// National Holiday since 1967
|| (d == 26 && m == October && y >= 1967)
// National Holiday 1919-1934
|| (d == 12 && m == November && y >= 1919 && y <= 1934)
// All Saints' Day
|| (d == 1 && m == November)
// Immaculate Conception
|| (d == 8 && m == December)
// Christmas
|| (d == 25 && m == December)
// St. Stephen
|| (d == 26 && m == December))
return false;
return true;
}
bool Austria::ExchangeImpl::isBusinessDay(const Date& date) const {
Weekday w = date.weekday();
Day d = date.dayOfMonth(), dd = date.dayOfYear();
Month m = date.month();
Year y = date.year();
Day em = easterMonday(y);
if (isWeekend(w)
// New Year's Day
|| (d == 1 && m == January)
// Good Friday
|| (dd == em-3)
// Easter Monday
|| (dd == em)
// Whit Monay
|| (dd == em+49)
// Labour Day
|| (d == 1 && m == May)
// National Holiday since 1967
|| (d == 26 && m == October && y >= 1967)
// National Holiday 1919-1934
|| (d == 12 && m == November && y >= 1919 && y <= 1934)
// Christmas' Eve
|| (d == 24 && m == December)
// Christmas
|| (d == 25 && m == December)
// St. Stephen
|| (d == 26 && m == December)
// Exchange Holiday
|| (d == 31 && m == December))
return false;
return true;
}
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "EditorDefs.h"
#include "StringDlg.h"
// Qt
#include <QDialogButtonBox>
#include <QLabel>
#include <QVBoxLayout>
/////////////////////////////////////////////////////////////////////////////
// StringDlg dialog
StringDlg::StringDlg(const QString &title, QWidget* pParent, bool bFileNameLimitation)
: QInputDialog(pParent)
, m_bFileNameLimitation(bFileNameLimitation)
{
setWindowTitle(title);
setLabelText("");
}
void StringDlg::accept()
{
if (m_bFileNameLimitation)
{
const QString text = textValue();
const QString reservedCharacters("<>:\"/\\|?*}");
foreach(auto reserv, reservedCharacters)
{
if (text.contains(reserv))
{
QMessageBox::warning(this, tr("Warning"), tr(" This string can't contain the following characters: %1").arg(reserv), QMessageBox::Ok);
return;
}
}
}
if (m_Check && !m_Check(textValue()))
return;
QInputDialog::accept();
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// CMultiLineStringDlg dialog
StringGroupDlg::StringGroupDlg(const QString &title, QWidget *parent)
: QDialog(parent)
{
if (!title.isEmpty())
setWindowTitle(title);
m_group = new QLineEdit(this);
m_string = new QLineEdit(this);
QFrame *horLine = new QFrame(this);
horLine->setFrameStyle(QFrame::HLine | QFrame::Plain);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(new QLabel(tr("Group"), this));
layout->addWidget(m_group);
layout->addWidget(new QLabel(tr("Name"), this));
layout->addWidget(m_string);
layout->addWidget(horLine);
layout->addWidget(buttonBox);
}
void StringGroupDlg::SetString(const QString &str)
{
m_string->setText(str);
}
QString StringGroupDlg::GetString() const
{
return m_string->text();
}
void StringGroupDlg::SetGroup(const QString &str)
{
m_group->setText(str);
}
QString StringGroupDlg::GetGroup() const
{
return m_group->text();
}
|
#include <steem/chain/util/reward.hpp>
#include <steem/chain/util/uint256.hpp>
namespace steem { namespace chain { namespace util {
uint8_t find_msb( const uint128_t& u )
{
uint64_t x;
uint8_t places;
x = (u.lo ? u.lo : 1);
places = (u.hi ? 64 : 0);
x = (u.hi ? u.hi : x);
return uint8_t( boost::multiprecision::detail::find_msb(x) + places );
}
uint64_t approx_sqrt( const uint128_t& x )
{
if( (x.lo == 0) && (x.hi == 0) )
return 0;
uint8_t msb_x = find_msb(x);
uint8_t msb_z = msb_x >> 1;
uint128_t msb_x_bit = uint128_t(1) << msb_x;
uint64_t msb_z_bit = uint64_t (1) << msb_z;
uint128_t mantissa_mask = msb_x_bit - 1;
uint128_t mantissa_x = x & mantissa_mask;
uint64_t mantissa_z_hi = (msb_x & 1) ? msb_z_bit : 0;
uint64_t mantissa_z_lo = (mantissa_x >> (msb_x - msb_z)).lo;
uint64_t mantissa_z = (mantissa_z_hi | mantissa_z_lo) >> 1;
uint64_t result = msb_z_bit | mantissa_z;
return result;
}
uint64_t get_rshare_reward( const comment_reward_context& ctx )
{
try
{
FC_ASSERT( ctx.rshares > 0 );
FC_ASSERT( ctx.total_reward_shares2 > 0 );
u256 rf(ctx.total_reward_fund_steem.amount.value);
u256 total_claims = to256( ctx.total_reward_shares2 );
//idump( (ctx) );
u256 claim = to256( evaluate_reward_curve( ctx.rshares.value, ctx.reward_curve, ctx.content_constant ) );
claim = ( claim * ctx.reward_weight ) / STEEM_100_PERCENT;
u256 payout_u256 = ( rf * claim ) / total_claims;
FC_ASSERT( payout_u256 <= u256( uint64_t( std::numeric_limits<int64_t>::max() ) ) );
uint64_t payout = static_cast< uint64_t >( payout_u256 );
if( is_comment_payout_dust( ctx.current_steem_price, payout ) )
payout = 0;
asset max_steem = to_steem( ctx.current_steem_price, ctx.max_sbd );
payout = std::min( payout, uint64_t( max_steem.amount.value ) );
return payout;
} FC_CAPTURE_AND_RETHROW( (ctx) )
}
uint128_t evaluate_reward_curve( const uint128_t& rshares, const protocol::curve_id& curve, const uint128_t& var1 )
{
uint128_t result = 0;
switch( curve )
{
case protocol::quadratic:
{
const uint128_t& content_constant = var1;
uint128_t rshares_plus_s = rshares + content_constant;
result = rshares_plus_s * rshares_plus_s - content_constant * content_constant;
}
break;
case protocol::bounded_curation:
{
const uint128_t& content_constant = var1;
uint128_t two_alpha = content_constant * 2;
result = uint128_t( rshares.lo, 0 ) / ( two_alpha + rshares );
}
break;
case protocol::linear:
result = rshares;
break;
case protocol::square_root:
result = approx_sqrt( rshares );
break;
case protocol::convergent_linear:
{
const uint128_t& s = var1;
result = ( ( rshares + s ) * ( rshares + s ) - s * s ) / ( rshares + 4 * s );
}
break;
case protocol::convergent_square_root:
{
const uint128_t& s = var1;
result = rshares / approx_sqrt( rshares + 2 * s );
}
break;
}
return result;
}
} } } // steem::chain::util
|
#include "utility.h"
void draw_tracked_faces(
const cv::Mat& image,
const SeetaTrackingFaceInfoArray& tracked_faces)
{
for (int i = 0; i < tracked_faces.size; ++i) {
const SeetaTrackingFaceInfo& track_face_info = tracked_faces.data[i];
cv::Rect rect = {
track_face_info.pos.x,
track_face_info.pos.y,
track_face_info.pos.width,
track_face_info.pos.height
};
cv::rectangle(image, rect, cv::Scalar(0, 0, 255), 2);
std::string info = \
std::string("id: ") + std::to_string(track_face_info.PID) + " " + \
std::string("s: ") + std::to_string(int(track_face_info.score * 100));
cv::putText(
image, info, cv::Point(rect.x, rect.y - 10),
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255)
);
}
}
void draw_detected_faces(
const cv::Mat& image,
const SeetaFaceInfoArray& detected_faces)
{
for (int i = 0; i < detected_faces.size; ++i) {
const SeetaFaceInfo& detected_face_info = detected_faces.data[i];
cv::Rect rect = {
detected_face_info.pos.x,
detected_face_info.pos.y,
detected_face_info.pos.width,
detected_face_info.pos.height
};
cv::rectangle(image, rect, cv::Scalar(0, 0, 255), 2);
std::string info =
std::string("s: ") + std::to_string(int(detected_face_info.score * 100));
cv::putText(
image, info, cv::Point(rect.x, rect.y - 10),
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255)
);
}
}
void draw_face_landmarkers(
const cv::Mat& image,
const std::vector<SeetaPointF>& landmarkers)
{
for (const SeetaPointF& marker : landmarkers) {
cv::Point p(int(marker.x), int(marker.y));
cv::circle(image, p, 3, cv::Scalar(0, 0, 255), -1);
}
}
void draw_face_quality(
const cv::Mat& image,
const SeetaRect& face_rect,
float quality)
{
cv::putText(image,
std::string("q: ") + std::to_string(int(quality * 100)),
cv::Point(face_rect.x, face_rect.y + face_rect.height + 20),
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255));
}
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <graphene/chain/database.hpp>
#include <graphene/chain/db_with.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/global_property_object.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/market_object.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <graphene/chain/transaction_object.hpp>
#include <graphene/chain/withdraw_permission_object.hpp>
#include <graphene/chain/witness_object.hpp>
#include <graphene/chain/protocol/fee_schedule.hpp>
#include <fc/uint128.hpp>
namespace graphene { namespace chain {
void database::update_global_dynamic_data( const signed_block& b )
{
const dynamic_global_property_object& _dgp = dynamic_global_property_id_type(0)(*this);
const global_property_object& gpo = get_global_properties();
uint32_t missed_blocks = get_slot_at_time( b.timestamp );
//#define DIRTY_TRICK // problem with missed_blocks can occur when "maintenance_interval" set to few minutes
#ifdef DIRTY_TRICK
if (missed_blocks != 0) {
#else
assert( missed_blocks != 0 );
#endif
// bad if-condition, this code needs to execute for both shuffled and rng algorithms
// if (gpo.parameters.witness_schedule_algorithm == GRAPHENE_WITNESS_SHUFFLED_ALGORITHM)
// {
missed_blocks--;
for( uint32_t i = 0; i < missed_blocks; ++i ) {
const auto& witness_missed = get_scheduled_witness( i+1 )(*this);
if( witness_missed.id != b.witness ) {
/*
const auto& witness_account = witness_missed.witness_account(*this);
if( (fc::time_point::now() - b.timestamp) < fc::seconds(30) )
wlog( "Witness ${name} missed block ${n} around ${t}", ("name",witness_account.name)("n",b.block_num())("t",b.timestamp) );
*/
modify( witness_missed, [&]( witness_object& w ) {
w.total_missed++;
});
}
}
// }
#ifdef DIRTY_TRICK
}
#endif
// dynamic global properties updating
modify( _dgp, [&]( dynamic_global_property_object& dgp ){
secret_hash_type::encoder enc;
fc::raw::pack( enc, dgp.random );
fc::raw::pack( enc, b.previous_secret );
dgp.random = enc.result();
_random_number_generator = fc::hash_ctr_rng<secret_hash_type, 20>(dgp.random.data());
if( BOOST_UNLIKELY( b.block_num() == 1 ) )
dgp.recently_missed_count = 0;
else if( _checkpoints.size() && _checkpoints.rbegin()->first >= b.block_num() )
dgp.recently_missed_count = 0;
else if( missed_blocks )
dgp.recently_missed_count += GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT*missed_blocks;
else if( dgp.recently_missed_count > GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT )
dgp.recently_missed_count -= GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT;
else if( dgp.recently_missed_count > 0 )
dgp.recently_missed_count--;
dgp.head_block_number = b.block_num();
dgp.head_block_id = b.id();
dgp.time = b.timestamp;
dgp.current_witness = b.witness;
dgp.recent_slots_filled = (
(dgp.recent_slots_filled << 1)
+ 1) << missed_blocks;
dgp.current_aslot += missed_blocks+1;
});
if( !(get_node_properties().skip_flags & skip_undo_history_check) )
{
GRAPHENE_ASSERT( _dgp.head_block_number - _dgp.last_irreversible_block_num < GRAPHENE_MAX_UNDO_HISTORY, undo_database_exception,
"The database does not have enough undo history to support a blockchain with so many missed blocks. "
"Please add a checkpoint if you would like to continue applying blocks beyond this point.",
("last_irreversible_block_num",_dgp.last_irreversible_block_num)("head", _dgp.head_block_number)
("recently_missed",_dgp.recently_missed_count)("max_undo",GRAPHENE_MAX_UNDO_HISTORY) );
}
_undo_db.set_max_size( _dgp.head_block_number - _dgp.last_irreversible_block_num + 1 );
_fork_db.set_max_size( _dgp.head_block_number - _dgp.last_irreversible_block_num + 1 );
}
void database::update_signing_witness(const witness_object& signing_witness, const signed_block& new_block)
{
const global_property_object& gpo = get_global_properties();
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
uint64_t new_block_aslot = dpo.current_aslot + get_slot_at_time( new_block.timestamp );
share_type witness_pay = std::min( gpo.parameters.witness_pay_per_block, dpo.witness_budget );
modify( dpo, [&]( dynamic_global_property_object& _dpo )
{
_dpo.witness_budget -= witness_pay;
} );
deposit_witness_pay( signing_witness, witness_pay );
modify( signing_witness, [&]( witness_object& _wit )
{
_wit.last_aslot = new_block_aslot;
_wit.last_confirmed_block_num = new_block.block_num();
_wit.previous_secret = new_block.previous_secret;
_wit.next_secret_hash = new_block.next_secret_hash;
} );
}
void database::update_last_irreversible_block()
{
const global_property_object& gpo = get_global_properties();
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
vector< const witness_object* > wit_objs;
wit_objs.reserve( gpo.active_witnesses.size() );
for( const witness_id_type& wid : gpo.active_witnesses )
wit_objs.push_back( &(wid(*this)) );
static_assert( GRAPHENE_IRREVERSIBLE_THRESHOLD > 0, "irreversible threshold must be nonzero" );
// 1 1 1 2 2 2 2 2 2 2 -> 2 .7*10 = 7
// 1 1 1 1 1 1 1 2 2 2 -> 1
// 3 3 3 3 3 3 3 3 3 3 -> 3
size_t offset = ((GRAPHENE_100_PERCENT - GRAPHENE_IRREVERSIBLE_THRESHOLD) * wit_objs.size() / GRAPHENE_100_PERCENT);
std::nth_element( wit_objs.begin(), wit_objs.begin() + offset, wit_objs.end(),
[]( const witness_object* a, const witness_object* b )
{
return a->last_confirmed_block_num < b->last_confirmed_block_num;
} );
uint32_t new_last_irreversible_block_num = wit_objs[offset]->last_confirmed_block_num;
if( new_last_irreversible_block_num > dpo.last_irreversible_block_num )
{
modify( dpo, [&]( dynamic_global_property_object& _dpo )
{
_dpo.last_irreversible_block_num = new_last_irreversible_block_num;
} );
}
}
void database::clear_expired_transactions()
{ try {
//Look for expired transactions in the deduplication list, and remove them.
//Transactions must have expired by at least two forking windows in order to be removed.
auto& transaction_idx = static_cast<transaction_index&>(get_mutable_index(implementation_ids, impl_transaction_object_type));
const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();
while( (!dedupe_index.empty()) && (head_block_time() > dedupe_index.begin()->trx.expiration) )
transaction_idx.remove(*dedupe_index.begin());
} FC_CAPTURE_AND_RETHROW() }
void database::clear_expired_proposals()
{
const auto& proposal_expiration_index = get_index_type<proposal_index>().indices().get<by_expiration>();
while( !proposal_expiration_index.empty() && proposal_expiration_index.begin()->expiration_time <= head_block_time() )
{
const proposal_object& proposal = *proposal_expiration_index.begin();
processed_transaction result;
try {
if( proposal.is_authorized_to_execute(*this) )
{
result = push_proposal(proposal);
//TODO: Do something with result so plugins can process it.
continue;
}
} catch( const fc::exception& e ) {
elog("Failed to apply proposed transaction on its expiration. Deleting it.\n${proposal}\n${error}",
("proposal", proposal)("error", e.to_detail_string()));
}
remove(proposal);
}
}
/**
* let HB = the highest bid for the collateral (aka who will pay the most DEBT for the least collateral)
* let SP = current median feed's Settlement Price
* let LC = the least collateralized call order's swan price (debt/collateral)
*
* If there is no valid price feed or no bids then there is no black swan.
*
* A black swan occurs if MAX(HB,SP) <= LC
*/
bool database::check_for_blackswan( const asset_object& mia, bool enable_black_swan )
{
if( !mia.is_market_issued() ) return false;
const asset_bitasset_data_object& bitasset = mia.bitasset_data(*this);
if( bitasset.has_settlement() ) return true; // already force settled
auto settle_price = bitasset.current_feed.settlement_price;
if( settle_price.is_null() ) return false; // no feed
const call_order_index& call_index = get_index_type<call_order_index>();
const auto& call_price_index = call_index.indices().get<by_price>();
const limit_order_index& limit_index = get_index_type<limit_order_index>();
const auto& limit_price_index = limit_index.indices().get<by_price>();
// looking for limit orders selling the most USD for the least CORE
auto highest_possible_bid = price::max( mia.id, bitasset.options.short_backing_asset );
// stop when limit orders are selling too little USD for too much CORE
auto lowest_possible_bid = price::min( mia.id, bitasset.options.short_backing_asset );
assert( highest_possible_bid.base.asset_id == lowest_possible_bid.base.asset_id );
// NOTE limit_price_index is sorted from greatest to least
auto limit_itr = limit_price_index.lower_bound( highest_possible_bid );
auto limit_end = limit_price_index.upper_bound( lowest_possible_bid );
auto call_min = price::min( bitasset.options.short_backing_asset, mia.id );
auto call_max = price::max( bitasset.options.short_backing_asset, mia.id );
auto call_itr = call_price_index.lower_bound( call_min );
auto call_end = call_price_index.upper_bound( call_max );
if( call_itr == call_end ) return false; // no call orders
price highest = settle_price;
if( limit_itr != limit_end ) {
assert( settle_price.base.asset_id == limit_itr->sell_price.base.asset_id );
highest = std::max( limit_itr->sell_price, settle_price );
}
auto least_collateral = call_itr->collateralization();
if( ~least_collateral >= highest )
{
elog( "Black Swan detected: \n"
" Least collateralized call: ${lc} ${~lc}\n"
// " Highest Bid: ${hb} ${~hb}\n"
" Settle Price: ${sp} ${~sp}\n"
" Max: ${h} ${~h}\n",
("lc",least_collateral.to_real())("~lc",(~least_collateral).to_real())
// ("hb",limit_itr->sell_price.to_real())("~hb",(~limit_itr->sell_price).to_real())
("sp",settle_price.to_real())("~sp",(~settle_price).to_real())
("h",highest.to_real())("~h",(~highest).to_real()) );
FC_ASSERT( enable_black_swan, "Black swan was detected during a margin update which is not allowed to trigger a blackswan" );
globally_settle_asset(mia, ~least_collateral );
return true;
}
return false;
}
void database::clear_expired_orders()
{ try {
detail::with_skip_flags( *this,
get_node_properties().skip_flags | skip_authority_check, [&](){
transaction_evaluation_state cancel_context(this);
//Cancel expired limit orders
auto& limit_index = get_index_type<limit_order_index>().indices().get<by_expiration>();
while( !limit_index.empty() && limit_index.begin()->expiration <= head_block_time() )
{
limit_order_cancel_operation canceler;
const limit_order_object& order = *limit_index.begin();
canceler.fee_paying_account = order.seller;
canceler.order = order.id;
canceler.fee = current_fee_schedule().calculate_fee( canceler );
if( canceler.fee.amount > order.deferred_fee )
{
// Cap auto-cancel fees at deferred_fee; see #549
wlog( "At block ${b}, fee for clearing expired order ${oid} was capped at deferred_fee ${fee}", ("b", head_block_num())("oid", order.id)("fee", order.deferred_fee) );
canceler.fee = asset( order.deferred_fee, asset_id_type() );
}
// we know the fee for this op is set correctly since it is set by the chain.
// this allows us to avoid a hung chain:
// - if #549 case above triggers
// - if the fee is incorrect, which may happen due to #435 (although since cancel is a fixed-fee op, it shouldn't)
cancel_context.skip_fee_schedule_check = true;
apply_operation(cancel_context, canceler);
}
});
//Process expired force settlement orders
auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();
if( !settlement_index.empty() )
{
asset_id_type current_asset = settlement_index.begin()->settlement_asset_id();
asset max_settlement_volume;
bool extra_dump = false;
auto next_asset = [¤t_asset, &settlement_index, &extra_dump] {
auto bound = settlement_index.upper_bound(current_asset);
if( bound == settlement_index.end() )
{
if( extra_dump )
{
ilog( "next_asset() returning false" );
}
return false;
}
if( extra_dump )
{
ilog( "next_asset returning true, bound is ${b}", ("b", *bound) );
}
current_asset = bound->settlement_asset_id();
return true;
};
uint32_t count = 0;
// At each iteration, we either consume the current order and remove it, or we move to the next asset
for( auto itr = settlement_index.lower_bound(current_asset);
itr != settlement_index.end();
itr = settlement_index.lower_bound(current_asset) )
{
++count;
const force_settlement_object& order = *itr;
auto order_id = order.id;
current_asset = order.settlement_asset_id();
const asset_object& mia_object = get(current_asset);
const asset_bitasset_data_object& mia = mia_object.bitasset_data(*this);
extra_dump = ((count >= 1000) && (count <= 1020));
if( extra_dump )
{
wlog( "clear_expired_orders() dumping extra data for iteration ${c}", ("c", count) );
ilog( "head_block_num is ${hb} current_asset is ${a}", ("hb", head_block_num())("a", current_asset) );
}
if( mia.has_settlement() )
{
ilog( "Canceling a force settlement because of black swan" );
cancel_order( order );
continue;
}
// Has this order not reached its settlement date?
if( order.settlement_date > head_block_time() )
{
if( next_asset() )
{
if( extra_dump )
{
ilog( "next_asset() returned true when order.settlement_date > head_block_time()" );
}
continue;
}
break;
}
// Can we still settle in this asset?
if( mia.current_feed.settlement_price.is_null() )
{
ilog("Canceling a force settlement in ${asset} because settlement price is null",
("asset", mia_object.symbol));
cancel_order(order);
continue;
}
if( max_settlement_volume.asset_id != current_asset )
max_settlement_volume = mia_object.amount(mia.max_force_settlement_volume(mia_object.dynamic_data(*this).current_supply));
if( mia.force_settled_volume >= max_settlement_volume.amount )
{
/*
ilog("Skipping force settlement in ${asset}; settled ${settled_volume} / ${max_volume}",
("asset", mia_object.symbol)("settlement_price_null",mia.current_feed.settlement_price.is_null())
("settled_volume", mia.force_settled_volume)("max_volume", max_settlement_volume));
*/
if( next_asset() )
{
if( extra_dump )
{
ilog( "next_asset() returned true when mia.force_settled_volume >= max_settlement_volume.amount" );
}
continue;
}
break;
}
auto& pays = order.balance;
auto receives = (order.balance * mia.current_feed.settlement_price);
receives.amount = (fc::uint128_t(receives.amount.value) *
(GRAPHENE_100_PERCENT - mia.options.force_settlement_offset_percent) / GRAPHENE_100_PERCENT).to_uint64();
assert(receives <= order.balance * mia.current_feed.settlement_price);
price settlement_price = pays / receives;
auto& call_index = get_index_type<call_order_index>().indices().get<by_collateral>();
asset settled = mia_object.amount(mia.force_settled_volume);
// Match against the least collateralized short until the settlement is finished or we reach max settlements
while( settled < max_settlement_volume && find_object(order_id) )
{
auto itr = call_index.lower_bound(boost::make_tuple(price::min(mia_object.bitasset_data(*this).options.short_backing_asset,
mia_object.get_id())));
// There should always be a call order, since asset exists!
assert(itr != call_index.end() && itr->debt_type() == mia_object.get_id());
asset max_settlement = max_settlement_volume - settled;
if( order.balance.amount == 0 )
{
wlog( "0 settlement detected" );
cancel_order( order );
break;
}
try {
settled += match(*itr, order, settlement_price, max_settlement);
}
catch ( const black_swan_exception& e ) {
wlog( "black swan detected: ${e}", ("e", e.to_detail_string() ) );
cancel_order( order );
break;
}
}
if( mia.force_settled_volume != settled.amount )
{
modify(mia, [settled](asset_bitasset_data_object& b) {
b.force_settled_volume = settled.amount;
});
}
}
}
} FC_CAPTURE_AND_RETHROW() }
void database::update_expired_feeds()
{
auto& asset_idx = get_index_type<asset_index>().indices().get<by_type>();
auto itr = asset_idx.lower_bound( true /** market issued */ );
while( itr != asset_idx.end() )
{
const asset_object& a = *itr;
++itr;
assert( a.is_market_issued() );
const asset_bitasset_data_object& b = a.bitasset_data(*this);
bool feed_is_expired;
if( head_block_time() < HARDFORK_615_TIME )
feed_is_expired = b.feed_is_expired_before_hardfork_615( head_block_time() );
else
feed_is_expired = b.feed_is_expired( head_block_time() );
if( feed_is_expired )
{
modify(b, [this](asset_bitasset_data_object& a) {
a.update_median_feeds(head_block_time());
});
check_call_orders(b.current_feed.settlement_price.base.asset_id(*this));
}
if( !b.current_feed.core_exchange_rate.is_null() &&
a.options.core_exchange_rate != b.current_feed.core_exchange_rate )
modify(a, [&b](asset_object& a) {
a.options.core_exchange_rate = b.current_feed.core_exchange_rate;
});
}
}
void database::update_maintenance_flag( bool new_maintenance_flag )
{
modify( get_dynamic_global_properties(), [&]( dynamic_global_property_object& dpo )
{
auto maintenance_flag = dynamic_global_property_object::maintenance_flag;
dpo.dynamic_flags =
(dpo.dynamic_flags & ~maintenance_flag)
| (new_maintenance_flag ? maintenance_flag : 0);
} );
return;
}
void database::update_withdraw_permissions()
{
auto& permit_index = get_index_type<withdraw_permission_index>().indices().get<by_expiration>();
while( !permit_index.empty() && permit_index.begin()->expiration <= head_block_time() )
remove(*permit_index.begin());
}
uint64_t database::get_random_bits( uint64_t bound )
{
return _random_number_generator(bound);
}
} }
|
/*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
/*
* signal infowindow buttons //Ves
*/
#include "signal_info.h"
#include "simwin.h"
#include "signal_connector_gui.h"
#include "../obj/signal.h" // The rest of the dialog
#include "../obj/gebaeude.h"
#include "../simmenu.h"
#include "../simworld.h"
#include "../display/viewport.h"
#include "../simsignalbox.h"
#include "../utils/simstring.h"
signal_info_t::signal_info_t(signal_t* const s) :
obj_infowin_t(s),
sig(s)
{
new_component<gui_label_t>("Controlled from");
add_table(3,3);
{
bt_goto_signalbox.init(button_t::posbutton, NULL);
bt_goto_signalbox.set_visible(false);
bt_goto_signalbox.set_tooltip(translator::translate("goto_signalbox"));
bt_goto_signalbox.set_rigid(true);
add_component(&bt_goto_signalbox);
bt_goto_signalbox.add_listener(this);
add_component(&lb_sb_name);
bt_info_signalbox.init(button_t::roundbox, "Details");
if (skinverwaltung_t::open_window) {
bt_info_signalbox.set_image(skinverwaltung_t::open_window->get_image_id(0));
bt_info_signalbox.set_image_position_right(true);
}
bt_info_signalbox.set_size(scr_size(D_BUTTON_WIDTH*2/3, D_BUTTON_HEIGHT));
bt_info_signalbox.set_visible(false);
bt_info_signalbox.set_tooltip(translator::translate("open_signalbox_info"));
bt_info_signalbox.add_listener(this);
bt_info_signalbox.set_rigid(true);
add_component(&bt_info_signalbox);
new_component<gui_empty_t>();
add_component(&lb_sb_distance);
bt_switch_signalbox.init(button_t::roundbox, "switch_sb");
bt_switch_signalbox.set_size(scr_size(proportional_string_width(translator::translate("switch_sb"))+D_BUTTON_PADDINGS_X, D_BUTTON_HEIGHT));
bt_switch_signalbox.set_visible(false);
bt_switch_signalbox.set_tooltip(translator::translate("open_signal_connector_gui"));
bt_switch_signalbox.add_listener(this);
bt_switch_signalbox.set_rigid(true);
add_component(&bt_switch_signalbox);
new_component<gui_margin_t>(D_H_SPACE,D_V_SPACE);
}
end_table();
// show author below the settings
if (char const* const maker = sig->get_desc()->get_copyright()) {
gui_label_buf_t* lb = new_component<gui_label_buf_t>();
lb->buf().printf(translator::translate("Constructed by %s"), maker);
lb->update();
}
update_data();
}
void signal_info_t::update_data()
{
sig = static_cast<const signal_t *>(view.get_obj());
koord3d sb = sig->get_signalbox();
if (sb == koord3d::invalid) {
lb_sb_name.buf().append(translator::translate("keine"));
}
else {
const grund_t* gr = welt->lookup(sb);
if (gr) {
const gebaeude_t* gb = gr->get_building();
if (gb) {
char sb_name[1024] = { '\0' };
int max_width = 250;
int max_lines = 5; // Set a limit
sprintf(sb_name, "%s", translator::translate(gb->get_name()));
//sprintf(sb_name,"This is a very very long signal box name which is so long that no one remembers what it was actually called before the super long name of the signalbox got changed to its current slightly longer name which is still too long to display in only one line therefore splitting this very long signalbox name into several lines although maximum five lines which should suffice more than enough to guard against silly long signal box names");
int next_char_index = 0;
for (int l = 0; l < max_lines; l++) {
char temp_name[1024] = { '\0' };
next_char_index = display_fit_proportional(sb_name, max_width, 0);
if (sb_name[next_char_index] == '\0') {
lb_sb_name.buf().append(sb_name);
break;
}
else {
for (int i = 0; i < next_char_index; i++) {
temp_name[i] = sb_name[i];
}
lb_sb_name.buf().append(temp_name);
if (l + 1 == max_lines) {
lb_sb_name.buf().append("...");
}
for (int i = 0; sb_name[i] != '\0'; i++) {
sb_name[i] = sb_name[i + next_char_index];
}
}
}
const grund_t *ground = welt->lookup_kartenboden(sb.x, sb.y);
bool sb_underground = ground->get_hoehe() > sb.z;
char sb_coordinates[20];
sprintf(sb_coordinates, "<%i,%i>", sb.x, sb.y);
lb_sb_name.buf().printf(" %s", sb_coordinates);
if (sb_underground) {
lb_sb_name.buf().printf(" (%s)", translator::translate("underground"));
}
// Show the distance between the signal and its signalbox, along with the signals maximum range
const uint32 tiles_to_signalbox = shortest_distance(sig->get_pos().get_2d(), sb.get_2d());
const double km_per_tile = welt->get_settings().get_meters_per_tile() / 1000.0;
const double km_to_signalbox = (double)tiles_to_signalbox * km_per_tile;
if (km_to_signalbox < 1)
{
float m_to_signalbox = km_to_signalbox * 1000;
lb_sb_distance.buf().append(m_to_signalbox);
lb_sb_distance.buf().append("m");
}
else {
uint n_actual;
if (km_to_signalbox < 20) {
n_actual = 1;
}
else {
n_actual = 0;
}
char number_actual[10];
number_to_string(number_actual, km_to_signalbox, n_actual);
lb_sb_distance.buf().append(number_actual);
lb_sb_distance.buf().append("km");
}
if (sig->get_desc()->get_working_method() != moving_block)
{
lb_sb_distance.buf().append(" (");
uint32 mdt_sb = sig->get_desc()->get_max_distance_to_signalbox();
if (mdt_sb == 0) {
lb_sb_distance.buf().append(translator::translate("infinite_range"));
}
else {
if (mdt_sb < 1000) {
lb_sb_distance.buf().printf("%s: ", translator::translate("max"));
lb_sb_distance.buf().append(mdt_sb);
lb_sb_distance.buf().append("m");
}
else {
uint n_max;
const double max_dist = (double)mdt_sb / 1000;
if (max_dist < 20) {
n_max = 1;
}
else {
n_max = 0;
}
char number_max[10];
number_to_string(number_max, max_dist, n_max);
lb_sb_distance.buf().printf("%s: ", translator::translate("max"));
lb_sb_distance.buf().append(number_max);
lb_sb_distance.buf().append("km");
}
}
lb_sb_distance.buf().append(")");
}
}
else {
lb_sb_name.buf().append(translator::translate("keine"));
dbg->warning("signal_t::info()", "Signalbox could not be found from a signal on valid ground");
}
}
else {
lb_sb_name.buf().append(translator::translate("keine"));
dbg->warning("signal_t::info()", "Signalbox could not be found from a signal on valid ground");
}
}
lb_sb_name.update();
lb_sb_distance.update();
if (sb == koord3d::invalid) {
// No signalbox
}
else
{
const grund_t* gr = welt->lookup(sb);
if (gr)
{
const gebaeude_t* gb = gr->get_building();
if (gb) {
bt_goto_signalbox.set_visible(true);
bt_info_signalbox.set_visible(true);
bt_switch_signalbox.set_visible(sig->get_owner_nr() == welt->get_active_player()->get_player_nr());
}
}
}
recalc_size();
}
/**
* This method is called if an action is triggered
*
* Returns true, if action is done and no more
* components should be triggered.
*/
bool signal_info_t::action_triggered(gui_action_creator_t *comp, value_t)
{
if (comp == &bt_goto_signalbox)
{
koord3d sb = sig->get_signalbox();
welt->get_viewport()->change_world_position(koord3d(sb));
}
if (comp == &bt_info_signalbox)
{
koord3d sb = sig->get_signalbox();
if (sb == koord3d::invalid)
{
// No signalbox
}
else
{
const grund_t* gr = welt->lookup(sb);
if (gr)
{
gebaeude_t* gb = gr->get_building();
if (gb)
{
gr->get_building()->show_info();
if (sig->get_owner_nr() == welt->get_active_player()->get_player_nr())
{
welt->get_active_player()->set_selected_signalbox(static_cast<signalbox_t *>(gb));
}
}
}
return true;
}
}
if( comp==&bt_switch_signalbox && sig->get_owner_nr()==welt->get_active_player()->get_player_nr() ) {
destroy_win( magic_signal_connector_gui_t );
create_win( new signal_connector_gui_t(sig), w_info, magic_signal_connector_gui_t );
return true;
}
return false;
}
|
// Copyright 2019 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/memory/ptr_util.h"
#include "chrome/browser/chromeos/arc/session/arc_session_manager.h"
#include "chrome/browser/chromeos/policy/configuration_policy_handler_chromeos.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "components/arc/arc_prefs.h"
#include "components/arc/arc_util.h"
#include "components/arc/session/arc_session_runner.h"
#include "components/arc/test/fake_arc_session.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
namespace policy {
class ArcPolicyTest : public PolicyTest {
public:
ArcPolicyTest() {}
~ArcPolicyTest() override {}
protected:
void SetUpOnMainThread() override {
PolicyTest::SetUpOnMainThread();
arc::ArcSessionManager::SetUiEnabledForTesting(false);
arc::ArcSessionManager::Get()->SetArcSessionRunnerForTesting(
std::make_unique<arc::ArcSessionRunner>(
base::BindRepeating(arc::FakeArcSession::Create)));
browser()->profile()->GetPrefs()->SetBoolean(arc::prefs::kArcSignedIn,
true);
browser()->profile()->GetPrefs()->SetBoolean(arc::prefs::kArcTermsAccepted,
true);
}
void TearDownOnMainThread() override {
arc::ArcSessionManager::Get()->Shutdown();
PolicyTest::TearDownOnMainThread();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
PolicyTest::SetUpCommandLine(command_line);
arc::SetArcAvailableCommandLineForTesting(command_line);
}
void SetArcEnabledByPolicy(bool enabled) {
PolicyMap policies;
policies.Set(key::kArcEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
POLICY_SOURCE_CLOUD,
base::WrapUnique(new base::Value(enabled)), nullptr);
UpdateProviderPolicy(policies);
if (browser()) {
const PrefService* const prefs = browser()->profile()->GetPrefs();
EXPECT_EQ(prefs->GetBoolean(arc::prefs::kArcEnabled), enabled);
}
}
private:
DISALLOW_COPY_AND_ASSIGN(ArcPolicyTest);
};
// Test ArcEnabled policy.
IN_PROC_BROWSER_TEST_F(ArcPolicyTest, ArcEnabled) {
const PrefService* const pref = browser()->profile()->GetPrefs();
const auto* const arc_session_manager = arc::ArcSessionManager::Get();
// ARC is switched off by default.
EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcEnabled));
EXPECT_FALSE(arc_session_manager->enable_requested());
// Enable ARC.
SetArcEnabledByPolicy(true);
EXPECT_TRUE(arc_session_manager->enable_requested());
// Disable ARC.
SetArcEnabledByPolicy(false);
EXPECT_FALSE(arc_session_manager->enable_requested());
}
// Test ArcBackupRestoreServiceEnabled policy.
IN_PROC_BROWSER_TEST_F(ArcPolicyTest, ArcBackupRestoreServiceEnabled) {
PrefService* const pref = browser()->profile()->GetPrefs();
// Enable ARC backup and restore in user prefs.
pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, true);
// ARC backup and restore is disabled by policy by default.
UpdateProviderPolicy(PolicyMap());
EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
EXPECT_TRUE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
// Set ARC backup and restore to user control via policy.
PolicyMap policies;
policies.Set(key::kArcBackupRestoreServiceEnabled, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(
static_cast<int>(ArcServicePolicyValue::kUnderUserControl)),
nullptr);
UpdateProviderPolicy(policies);
// User choice should be honored now.
EXPECT_TRUE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
EXPECT_FALSE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, false);
EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, true);
EXPECT_TRUE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
// Set ARC backup and restore to disabled via policy.
policies.Set(key::kArcBackupRestoreServiceEnabled, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(
static_cast<int>(ArcServicePolicyValue::kDisabled)),
nullptr);
UpdateProviderPolicy(policies);
EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
EXPECT_TRUE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
// Disable ARC backup and restore in user prefs.
pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, true);
// Set ARC backup and restore to enabled via policy.
policies.Set(key::kArcBackupRestoreServiceEnabled, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(
static_cast<int>(ArcServicePolicyValue::kEnabled)),
nullptr);
UpdateProviderPolicy(policies);
EXPECT_TRUE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
EXPECT_TRUE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
}
// Test ArcGoogleLocationServicesEnabled policy and its interplay with the
// DefaultGeolocationSetting policy.
IN_PROC_BROWSER_TEST_F(ArcPolicyTest, ArcGoogleLocationServicesEnabled) {
PrefService* const pref = browser()->profile()->GetPrefs();
// Values of the ArcGoogleLocationServicesEnabled policy to be tested.
std::vector<base::Value> test_policy_values;
test_policy_values.emplace_back(); // unset
test_policy_values.emplace_back(
static_cast<int>(ArcServicePolicyValue::kDisabled));
test_policy_values.emplace_back(
static_cast<int>(ArcServicePolicyValue::kUnderUserControl));
test_policy_values.emplace_back(
static_cast<int>(ArcServicePolicyValue::kEnabled));
// Values of the DefaultGeolocationSetting policy to be tested.
std::vector<base::Value> test_default_geo_policy_values;
test_default_geo_policy_values.emplace_back(); // unset
test_default_geo_policy_values.emplace_back(1); // 'AllowGeolocation'
test_default_geo_policy_values.emplace_back(2); // 'BlockGeolocation'
test_default_geo_policy_values.emplace_back(3); // 'AskGeolocation'
// Switch on the pref in user prefs.
pref->SetBoolean(arc::prefs::kArcLocationServiceEnabled, true);
// The pref is overridden to disabled by policy by default.
UpdateProviderPolicy(PolicyMap());
EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcLocationServiceEnabled));
EXPECT_TRUE(
pref->IsManagedPreference(arc::prefs::kArcLocationServiceEnabled));
for (const auto& test_policy_value : test_policy_values) {
for (const auto& test_default_geo_policy_value :
test_default_geo_policy_values) {
PolicyMap policies;
if (test_policy_value.is_int()) {
policies.Set(key::kArcGoogleLocationServicesEnabled,
POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
POLICY_SOURCE_CLOUD, test_policy_value.CreateDeepCopy(),
nullptr);
}
if (test_default_geo_policy_value.is_int()) {
policies.Set(key::kDefaultGeolocationSetting, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
test_default_geo_policy_value.CreateDeepCopy(), nullptr);
}
UpdateProviderPolicy(policies);
const bool should_be_disabled_by_policy =
test_policy_value.is_none() ||
(test_policy_value.GetInt() ==
static_cast<int>(ArcServicePolicyValue::kDisabled));
const bool should_be_enabled_by_policy =
test_policy_value.is_int() &&
test_policy_value.GetInt() ==
static_cast<int>(ArcServicePolicyValue::kEnabled);
const bool should_be_disabled_by_default_geo_policy =
test_default_geo_policy_value.is_int() &&
test_default_geo_policy_value.GetInt() == 2;
const bool expected_pref_value =
!(should_be_disabled_by_policy ||
should_be_disabled_by_default_geo_policy);
EXPECT_EQ(expected_pref_value,
pref->GetBoolean(arc::prefs::kArcLocationServiceEnabled))
<< "ArcGoogleLocationServicesEnabled policy is set to "
<< test_policy_value << "DefaultGeolocationSetting policy is set to "
<< test_default_geo_policy_value;
const bool expected_pref_managed =
should_be_disabled_by_policy || should_be_enabled_by_policy ||
should_be_disabled_by_default_geo_policy;
EXPECT_EQ(
expected_pref_managed,
pref->IsManagedPreference(arc::prefs::kArcLocationServiceEnabled))
<< "ArcGoogleLocationServicesEnabled policy is set to "
<< test_policy_value << "DefaultGeolocationSetting policy is set to "
<< test_default_geo_policy_value;
}
}
}
} // namespace policy
|
/*
* ----------------- BEGIN LICENSE BLOCK ---------------------------------
*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
* ----------------- END LICENSE BLOCK -----------------------------------
*/
/**
* Generated file
* @file
*
* Generator Version : 11.0.0-1997
*/
#pragma once
#include <cmath>
#include <limits>
#include "ad/map/restriction/RoadUserTypeValidInputRange.hpp"
#include "ad/map/restriction/VehicleDescriptor.hpp"
#include "ad/physics/DistanceValidInputRange.hpp"
#include "ad/physics/WeightValidInputRange.hpp"
#include "spdlog/fmt/ostr.h"
#include "spdlog/spdlog.h"
/*!
* \brief check if the given VehicleDescriptor is within valid input range
*
* \param[in] input the VehicleDescriptor as an input value
* \param[in] logErrors enables error logging
*
* \returns \c true if VehicleDescriptor is considered to be within the specified input range
*
* \note the specified input range is defined by the ranges of all members
*/
inline bool withinValidInputRange(::ad::map::restriction::VehicleDescriptor const &input, bool const logErrors = true)
{
// check for generic member input ranges
bool inValidInputRange = true;
inValidInputRange = withinValidInputRange(input.type, logErrors) && withinValidInputRange(input.width, logErrors)
&& withinValidInputRange(input.height, logErrors) && withinValidInputRange(input.length, logErrors)
&& withinValidInputRange(input.weight, logErrors);
if (!inValidInputRange && logErrors)
{
spdlog::error("withinValidInputRange(::ad::map::restriction::VehicleDescriptor)>> {} has invalid member",
input); // LCOV_EXCL_BR_LINE
}
return inValidInputRange;
}
|
//$Id$
//------------------------------------------------------------------------------
// UserDefinedFunction
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2018 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG04CC06P.
//
// Author: Linda Jun
// Created: 2016.10.20
//
/**
* Implements UserDefinedFunction class. All user defined function classes
* such as GmatFunction are derived from this class.
*/
//------------------------------------------------------------------------------
#include "UserDefinedFunction.hpp"
#include "FunctionException.hpp" // for exception
#include "StringUtil.hpp" // for GmatStringUtil::
#include "Parameter.hpp" // for GetOwner()
#include "MessageInterface.hpp"
//#define DEBUG_FUNCTION_SET
//#define DEBUG_FUNCTION_FINALIZE
//#ifndef DEBUG_MEMORY
//#define DEBUG_MEMORY
//#endif
#ifdef DEBUG_MEMORY
#include "MemoryTracker.hpp"
#endif
//---------------------------------
// static data
//---------------------------------
//------------------------------------------------------------------------------
// UserDefinedFunction(std::string typeStr, std::string name)
//------------------------------------------------------------------------------
/**
* Constructs the UserDefinedFunction object (default constructor).
*
* @param <typeStr> String text identifying the object type
* @param <name> Name for the object
*/
//------------------------------------------------------------------------------
UserDefinedFunction::UserDefinedFunction(const std::string &typeStr, const std::string &name) :
ObjectManagedFunction(typeStr, name),
fcs (NULL),
fcsInitialized (false),
fcsFinalized (false),
validator (NULL),
objectsInitialized (false)
{
if (typeStr != "")
objectTypeNames.push_back(typeStr);
objectTypeNames.push_back("UserDefinedFunction");
}
//------------------------------------------------------------------------------
// ~UserDefinedFunction(void)
//------------------------------------------------------------------------------
/**
* Destroys the UserDefinedFunction object (destructor).
*/
//------------------------------------------------------------------------------
UserDefinedFunction::~UserDefinedFunction()
{
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
("UserDefinedFunction::~UserDefinedFunction() <%p>[%s]'%s' entered\n", this, GetTypeName().c_str(),
GetName().c_str());
#endif
// Clear original objects
ClearAutomaticObjects();
ClearFunctionObjects();
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
("UserDefinedFunction::~UserDefinedFunction() <%p>[%s]'%s' leaving\n", this, GetTypeName().c_str(),
GetName().c_str());
#endif
}
//------------------------------------------------------------------------------
// UserDefinedFunction(const UserDefinedFunction &f)
//------------------------------------------------------------------------------
/**
* Constructs the UserDefinedFunction object (copy constructor).
*
* @param <f> Object that is copied
*/
//------------------------------------------------------------------------------
UserDefinedFunction::UserDefinedFunction(const UserDefinedFunction &f) :
ObjectManagedFunction (f),
fcs (NULL),
fcsInitialized (f.fcsInitialized),
fcsFinalized (f.fcsFinalized),
functionObjectMap (f.functionObjectMap), // Do I want to do this?
validator (f.validator),
objectsInitialized (false)
{
//parameterCount = UserDefinedFunctionParamCount;
}
//------------------------------------------------------------------------------
// UserDefinedFunction& operator=(const UserDefinedFunction &f)
//------------------------------------------------------------------------------
/**
* Sets one UserDefinedFunction object to match another (assignment operator).
*
* @param <f> The object that is copied.
*
* @return this object, with the parameters set as needed.
*/
//------------------------------------------------------------------------------
UserDefinedFunction& UserDefinedFunction::operator=(const UserDefinedFunction &f)
{
if (this == &f)
return *this;
ObjectManagedFunction::operator=(f);
fcs = NULL;
fcsInitialized = f.fcsInitialized;
fcsFinalized = f.fcsFinalized;
validator = f.validator;
objectsInitialized = f.objectsInitialized;
return *this;
}
//------------------------------------------------------------------------------
// bool Initialize(ObjectInitializer *objInit, bool reinitialize = false)
//------------------------------------------------------------------------------
bool UserDefinedFunction::Initialize(ObjectInitializer *objInit, bool reinitialize)
{
validator = Validator::Instance();
ObjectManagedFunction::Initialize(objInit, reinitialize);
return true;
}
//------------------------------------------------------------------------------
// bool UserDefinedFunction::Execute(ObjectInitializer *objInit) [default implementation]
//------------------------------------------------------------------------------
bool UserDefinedFunction::Execute(ObjectInitializer *objInit, bool reinitialize)
{
return true;
}
//------------------------------------------------------------------------------
// bool UserDefinedFunction::Finalize(bool cleanUp = false) [default implementation]
//------------------------------------------------------------------------------
void UserDefinedFunction::Finalize(bool cleanUp)
{
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
("\nUserDefinedFunction::Finalize() entered, fcsFinalized=%d\n", fcsFinalized);
#endif
if (sandboxObjects.size() == 0)
{
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
("UserDefinedFunction::Finalize() leaving, there is nothing to do since snadboxObjects are empty\n\n");
#endif
return;
}
if (globalObjectStore == NULL)
{
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
("UserDefinedFunction::Finalize() leaving, there is nothing to do since globalObjectStore is NULL\n\n");
#endif
return;
}
#ifdef DEBUG_FUNCTION_FINALIZE
ShowObjects("In UserDefinedFunction::Finalize()");
#endif
// Set ref Parameter back to original ref Parameter for global ReportFile and XyPlot
// since these subscribers uses Parameters for reporting and plotting
GmatBase *sandboxObj = NULL;
GmatBase *globalObj = NULL;
GmatBase *autoObj = NULL;
std::string sandboxObjName;
std::string globalObjName;
std::string autoObjName;
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
("Going through sandboxObjects to see if global Parameters in global "
"Subscribers need to point back to sandbox pointer\n");
#endif
// Go through already managed sandbox objects
for (UnsignedInt i = 0; i < sandboxObjects.size(); i++)
{
sandboxObj = sandboxObjects[i];
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
(" sandboxObj=<%p>[%s]'%s'\n", sandboxObj,
sandboxObj ? sandboxObj->GetTypeName().c_str() : "NULL",
sandboxObj ? sandboxObj->GetName().c_str() : "NULL");
#endif
if (sandboxObj == NULL)
continue;
sandboxObjName = sandboxObj->GetName();
if (sandboxObj->IsOfType(Gmat::PARAMETER))
{
GmatBase *paramOwner = ((Parameter*)sandboxObj)->GetOwner();
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
(" sandboxObj is Parameter, paramOwner = <%p>[%s]'%s'\n", paramOwner,
paramOwner ? paramOwner->GetTypeName().c_str() : "NULL",
paramOwner ? paramOwner->GetName().c_str() : "NULL");
#endif
// Go through global ReportFile or XYPlot and reset ref Parameter
for (ObjectMap::iterator i = globalObjectStore->begin(); i != globalObjectStore->end(); ++i)
{
try
{
globalObj = i->second;
globalObjName = i->first;
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage(GmatBase::WriteObjectInfo(" ", globalObj));
MessageInterface::ShowMessage("Checking if it is ReportFile or XYPlot\n");
#endif
if (globalObj &&
(globalObj->IsOfType("ReportFile") || globalObj->IsOfType("XYPlot")))
{
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
(" Found global <%p>[%s]'%s', so calling globalObj->SetRefObject(%s)\n",
globalObj, globalObj->GetTypeName().c_str(), globalObjName.c_str(),
sandboxObjName.c_str());
#endif
// We can use globalObj->GetRefObjectNameArray() and go through this list
// or ignore exception. Ignoring exception for now.
try
{
globalObj->SetRefObject(sandboxObj, Gmat::PARAMETER, sandboxObjName);
}
catch (BaseException &be)
{
// Ignore exception
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage(" Ignoring exception: %s\n", be.GetFullMessage().c_str());
#endif
}
}
}
catch (BaseException &be)
{
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage
("Caught exception: %s\n", be.GetFullMessage().c_str());
#endif
// If cleanup mode, ignore exception
if (!cleanUp)
throw;
}
}
}
}
ObjectManagedFunction::Finalize();
#ifdef DEBUG_FUNCTION_FINALIZE
MessageInterface::ShowMessage("UserDefinedFunction::Finalize() leaving\n\n");
#endif
}
//------------------------------------------------------------------------------
// bool IsFcsFinalized()
//------------------------------------------------------------------------------
bool UserDefinedFunction::IsFcsFinalized()
{
return fcsFinalized;
}
//------------------------------------------------------------------------------
// bool IsFunctionControlSequenceSet()
//------------------------------------------------------------------------------
bool UserDefinedFunction::IsFunctionControlSequenceSet()
{
if (fcs != NULL) return true;
return false;
}
//------------------------------------------------------------------------------
// bool SetFunctionControlSequence(GmatCommand *cmd)
//------------------------------------------------------------------------------
bool UserDefinedFunction::SetFunctionControlSequence(GmatCommand *cmd)
{
#ifdef DEBUG_FUNCTION_SET
if (!cmd) MessageInterface::ShowMessage("Trying to set FCS on %s, but it is NULL!!!\n",
functionName.c_str());
else
{
MessageInterface::ShowMessage("Setting FCS for function %s with FCS pointer = %p\n",
functionName.c_str(), cmd);
MessageInterface::ShowMessage("First command is a %s\n", (cmd->GetTypeName()).c_str());
}
#endif
fcs = cmd;
return true;
}
//------------------------------------------------------------------------------
// GmatBase* GetFunctionControlSequence()
//------------------------------------------------------------------------------
GmatCommand* UserDefinedFunction::GetFunctionControlSequence()
{
return fcs;
}
//------------------------------------------------------------------------------
// void ClearFunctionObjects()
//------------------------------------------------------------------------------
void UserDefinedFunction::ClearFunctionObjects()
{
#ifdef DEBUG_FUNCTION_OBJ
MessageInterface::ShowMessage
("UserDefinedFunction::ClearFunctionObjects() this=<%p> '%s' entered\n "
"functionObjectMap.size()=%d, sandboxObjects.size()=%d, "
"objectsToDelete.size()=%d\n", this, GetName().c_str(),
functionObjectMap.size(), sandboxObjects.size(), objectsToDelete.size());
ShowObjectMap(&functionObjectMap, "In ClearFunctionObjects()", "functionObjectMap");
#endif
StringArray toDelete;
ObjectMap::iterator omi = functionObjectMap.begin();
while (omi != functionObjectMap.end())
{
GmatBase *obj = omi->second;
#ifdef DEBUG_FUNCTION_OBJ
MessageInterface::ShowMessage
(" ==> Checking if <%p>[%s]'%s' can be deleted\n", obj,
obj ? obj->GetTypeName().c_str() : "NULL", (omi->first).c_str());
#endif
// If object is not NULL and not this function, delete
if (obj != NULL && (!obj->IsOfType("GmatFunction")))
{
#ifdef DEBUG_FUNCTION_OBJ
MessageInterface::ShowMessage
(" isLocal = %d, isGlobal = %d, isAutomaticGlobal = %d, \n",
obj->IsLocal(), obj->IsGlobal(), obj->IsAutomaticGlobal());
#endif
// @note CelestialBody is added to SolarSystem and it will be deleted when
// when SolarSystem in use is deleted (LOJ: 2014.12.23)
if (obj->IsLocal() && !(obj->IsOfType(Gmat::CELESTIAL_BODY)))
{
#ifdef DEBUG_MEMORY
GmatBase *obj = omi->second;
MemoryTracker::Instance()->Remove
(obj, obj->GetName(), "Function::ClearFunctionObjects()",
"deleting functionObj");
#endif
#ifdef DEBUG_FUNCTION_OBJ
MessageInterface::ShowMessage(" Deleting since it is a local object\n");
#endif
delete omi->second;
omi->second = NULL;
//functionObjectMap.erase(omi);
//++omi;
}
}
++omi;
}
#ifdef DEBUG_FUNCTION_OBJ
MessageInterface::ShowMessage
("UserDefinedFunction::ClearFunctionObjects() this=<%p> '%s' leaving\n",
this, GetName().c_str());
#endif
}
//------------------------------------------------------------------------------
// void AddFunctionObject(GmatBase *obj)
//------------------------------------------------------------------------------
void UserDefinedFunction::AddFunctionObject(GmatBase *obj)
{
#ifdef DEBUG_FUNCTION_OBJ
MessageInterface::ShowMessage
("UserDefinedFunction::AddFunctionObject() entered, obj=<%p>[%s]'%s'\n", obj,
obj ? obj->GetTypeName().c_str() : "NULL",
obj ? obj->GetName().c_str() : "NULL");
//ShowObjects("Entered UserDefinedFunction::AddFunctionObject()");
#endif
if (obj && obj->GetName() != "")
{
std::string objName = obj->GetName();
if (functionObjectMap.find(objName) == functionObjectMap.end())
functionObjectMap.insert(std::make_pair(objName, obj));
}
#ifdef DEBUG_FUNCTION_OBJ
MessageInterface::ShowMessage("UserDefinedFunction::AddFunctionObject() leaving\n");
ShowObjectMap(&functionObjectMap, "Leaving AddFunctionObject()", "functionObjectMap");
#endif
}
//------------------------------------------------------------------------------
// GmatBase* FindFunctionObject(const std::string &name)
//------------------------------------------------------------------------------
GmatBase* UserDefinedFunction::FindFunctionObject(const std::string &name)
{
#ifdef DEBUG_FIND_OBJECT
MessageInterface::ShowMessage
("UserDefinedFunction::FindFunctionObject() entered, name='%s'\n", name.c_str());
//ShowObjects("In Function::FindFunctionObject()");
#endif
// Ignore array index
std::string newName = name;
std::string::size_type index = name.find_first_of("([");
if (index != name.npos)
newName = name.substr(0, index);
#ifdef DEBUG_FIND_OBJECT
MessageInterface::ShowMessage(" newName='%s'\n", newName.c_str());
#endif
GmatBase *obj = NULL;
if (functionObjectMap.find(newName) != functionObjectMap.end())
obj = functionObjectMap[newName];
// try SolarSystem if obj is still NULL
if (obj == NULL && solarSys != NULL)
obj = (GmatBase*)(solarSys->GetBody(newName));
#ifdef DEBUG_FIND_OBJECT
MessageInterface::ShowMessage
("UserDefinedFunction::FindFunctionObject() returning <%p>\n", obj);
#endif
return obj;
}
//------------------------------------------------------------------------------
// ObjectMap* GetFunctionObjectMap()
//------------------------------------------------------------------------------
ObjectMap* UserDefinedFunction::GetFunctionObjectMap()
{
return &functionObjectMap;
}
//------------------------------------------------------------------------------
// void ClearAutomaticObjects()
//------------------------------------------------------------------------------
void UserDefinedFunction::ClearAutomaticObjects()
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
("UserDefinedFunction::ClearAutomaticObjects() this=<%p> '%s' entered\n "
"automaticObjectMap.size()=%d, sandboxObjects.size()=%d, "
"objectsToDelete.size()=%d\n", this, GetName().c_str(),
automaticObjectMap.size(), sandboxObjects.size(), objectsToDelete.size());
#endif
StringArray toDelete;
ObjectMap::iterator omi;
for (omi = automaticObjectMap.begin(); omi != automaticObjectMap.end(); ++omi)
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
("Checking if <%p> '%s' can be deleted\n", omi->second,
(omi->first).c_str());
#endif
if (omi->second != NULL)
{
std::string objName = (omi->second)->GetName();
// If same object found in sandboxObjects then skip
if (!sandboxObjects.empty() &&
find(sandboxObjects.begin(), sandboxObjects.end(), omi->second) !=
sandboxObjects.end())
continue;
// If same object found in functionObjectMap then skip
if (functionObjectMap.find(objName) != functionObjectMap.end())
{
ObjectMap::iterator iobjfound = functionObjectMap.find(objName);
if (omi->second == iobjfound->second)
continue;
}
//------------------------------------------------------
#ifdef __COLLECT_AUTO_OBJECTS__
//------------------------------------------------------
// if object is not in objectsToDelete then add
if (find(objectsToDelete.begin(), objectsToDelete.end(), omi->second) ==
objectsToDelete.end())
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage(" Added to objectsToDelete\n");
#endif
objectsToDelete.push_back(omi->second);
}
else
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage(" Already in the objectsToDelete\n");
#endif
}
//------------------------------------------------------
#else
//------------------------------------------------------
// if object not found in sandboxObjects then delete
if (find(sandboxObjects.begin(), sandboxObjects.end(), omi->second) ==
sandboxObjects.end())
{
#ifdef DEBUG_MEMORY
GmatBase *obj = omi->second;
MemoryTracker::Instance()->Remove
(obj, obj->GetName(), "UserDefinedFunction::ClearAutomaticObjects()",
"deleting autoObj");
#endif
delete omi->second;
omi->second = NULL;
}
//------------------------------------------------------
#endif //__COLLECT_AUTO_OBJECTS__
//------------------------------------------------------
}
else
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage(" Skipped since sandbox object\n");
#endif
}
toDelete.push_back(omi->first);
}
for (unsigned int kk = 0; kk < toDelete.size(); kk++)
automaticObjectMap.erase(toDelete.at(kk));
#ifdef __COLLECT_AUTO_OBJECTS__
// delete old automatic objects collected if not already deleted
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
(" There are %d automatic objects to delete\n", objectsToDelete.size());
#endif
ObjectArray::iterator oai;
for (oai = objectsToDelete.begin(); oai != objectsToDelete.end(); ++oai)
{
#ifdef DEBUG_MEMORY
MemoryTracker::Instance()->Remove
((*oai), (*oai)->GetName(), "UserDefinedFunction::ClearAutomaticObjects()", "deleting old object");
#endif
delete (*oai);
(*oai) = NULL;
}
objectsToDelete.clear();
#endif //__COLLECT_AUTO_OBJECTS__
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
("UserDefinedFunction::ClearAutomaticObjects() this=<%p> '%s' leaving\n",
this, GetName().c_str());
#endif
}
//------------------------------------------------------------------------------
// void AddAutomaticObject(const std::string &withName, GmatBase *obj,
// bool alreadyManaged)
//------------------------------------------------------------------------------
/*
* Adds automatic objects such as Parameter, e.g. sat.X, to automatic object map.
* The GmatFunction::Initialize() calls Validator to validate and to create
* ElementWrappers for commands in the FCS. The Validator creates automatic
* Parameters if necessary and calls this method for adding. Since function can be
* initialized more than one time multiple automatic Parameters can be created
* which is the case for nested and recursive call.
*
* @param withName Automatic object name
* @param obj Automatic object pointer
* @param alreadyManaged true if object is Sandbox object
*
* @note Make sure that old automatic objects are deleted properly
*/
//------------------------------------------------------------------------------
void UserDefinedFunction::AddAutomaticObject(const std::string &withName, GmatBase *obj,
bool alreadyManaged)
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
("\nUserDefinedFunction::AddAutomaticObject() <%p>'%s' entered\n name='%s', obj=<%p>[%s]'%s', "
"alreadyManaged=%d, objectStore=<%p>\n", this, GetName().c_str(),
withName.c_str(), obj, obj->GetTypeName().c_str(), obj->GetName().c_str(),
alreadyManaged, objectStore);
#endif
// Make sure that the owner of automatic Parameter exist in the objectStore
// (LOJ: 2009.03.25)
if (objectStore != NULL)
{
std::string type, ownerName, dep;
GmatStringUtil::ParseParameter(withName, type, ownerName, dep);
GmatBase *owner = FindObject(ownerName);
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
(" ownerName='%s', owner=<%p>[%s]'%s'\n", ownerName.c_str(), owner,
owner ? owner->GetTypeName().c_str() : "NULL",
owner ? owner->GetName().c_str() : "NULL");
#ifdef DEBUG_OBJECT_MAP
ShowObjectMap(objectStore, "In UserDefinedFunction::AddAutomaticObject", "objectStore");
#endif
#endif
}
// If same name exist in the sandbox, add it to sandboxObjects so that
// it can be handled appropriately during finalization
if (alreadyManaged)
{
if (find(sandboxObjects.begin(), sandboxObjects.end(), obj) ==
sandboxObjects.end() &&
automaticObjectMap.find(withName) == automaticObjectMap.end())
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
(" ==> Adding <%p>'%s' to sandboxObjects\n", obj, obj->GetName().c_str());
#endif
sandboxObjects.push_back(obj);
}
}
#ifdef __COLLECT_AUTO_OBJECTS__
if (automaticObjectMap.find(withName) != automaticObjectMap.end())
{
GmatBase *oldObj = automaticObjectMap[withName];
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
(" Found oldObj=<%p>[%s] '%s'\n", oldObj, oldObj ?
oldObj->GetTypeName().c_str() : "NULL",
oldObj ? oldObj->GetName().c_str() : "NULL");
#endif
// if old object is not in the sandboxObjects add it to delete list,
// since objects in the Sandbox objectMap will be deleted from the Sandbox first.
// (LOJ: 2009.03.16)
if (oldObj != NULL &&
(find(sandboxObjects.begin(), sandboxObjects.end(), oldObj) ==
sandboxObjects.end()))
{
if (find(objectsToDelete.begin(), objectsToDelete.end(), oldObj) ==
objectsToDelete.end())
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage(" Adding to objectsToDelete\n");
#endif
objectsToDelete.push_back(oldObj);
}
}
}
#endif
// Insert object to automaticObjectMap if not already inserted
if (automaticObjectMap.find(withName) != automaticObjectMap.end())
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
(" The object <%p>'%s' is already in automaticObjectMap\n", obj, withName.c_str());
#endif
}
else
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
(" ==> Inserting <%p>'%s' to automaticObjectMap\n", obj, withName.c_str());
#endif
// Objects in automaticObjectMap are cloned and add to function objectStore
// in GmatFunction::Initialize()
automaticObjectMap.insert(std::make_pair(withName,obj));
}
#ifdef DEBUG_AUTO_OBJ
ShowObjectMap(&automaticObjectMap, "In UserDefinedFunction::AddAutomaticObject()", "automaticObjectMap");
MessageInterface::ShowMessage
("UserDefinedFunction::AddAutomaticObject() <%p>'%s' leaving\n\n", this, GetName().c_str());
#endif
}
//------------------------------------------------------------------------------
// GmatBase* FindAutomaticObject(const std::string &name)
//------------------------------------------------------------------------------
GmatBase* UserDefinedFunction::FindAutomaticObject(const std::string &name)
{
if (automaticObjectMap.find(name) != automaticObjectMap.end())
return automaticObjectMap[name];
else
return NULL;
}
//------------------------------------------------------------------------------
// ObjectMap* GetAutomaticObjectMap()
//------------------------------------------------------------------------------
ObjectMap* UserDefinedFunction::GetAutomaticObjectMap()
{
return &automaticObjectMap;
}
//---------------------------------
// protected
//---------------------------------
//------------------------------------------------------------------------------
// GmatBase* FindObject(const std::string &name)
//------------------------------------------------------------------------------
GmatBase* UserDefinedFunction::FindObject(const std::string &name)
{
#ifdef DEBUG_FIND_OBJECT
MessageInterface::ShowMessage
("UserDefinedFunction::FindObject() <%p>'%s' entered, name = '%s'\n", this,
functionName.c_str(), name.c_str());
ShowObjectMap(objectStore, "In FindObject()", "objectStore");
ShowObjectMap(globalObjectStore, "In FindObject()", "globalObjectStore");
ShowObjectMap(&functionObjectMap, "In FindObject()", "functionObjectMap");
#endif
std::string newName = name;
GmatBase *obj = NULL;
// Ignore array indexing of Array
std::string::size_type index = name.find('(');
if (index != name.npos)
newName = name.substr(0, index);
// Check for the object in the Local Object Store (LOS) first
if (objectStore && objectStore->find(newName) != objectStore->end())
obj = (*objectStore)[newName];
// If not found in the LOS, check the Global Object Store (GOS)
else if (globalObjectStore && globalObjectStore->find(newName) != globalObjectStore->end())
obj = (*globalObjectStore)[newName];
// Let's try SolarSystem (loj: 2008.06.12)
else if (solarSys && solarSys->GetBody(newName))
obj = (GmatBase*)(solarSys->GetBody(newName));
// If still not found, try functionObjectMap
// Should this moved to top?
else if (functionObjectMap.find(newName) != functionObjectMap.end())
obj = functionObjectMap[newName];
#ifdef DEBUG_FIND_OBJECT
MessageInterface::ShowMessage
("UserDefinedFunction::FindObject() <%p>'%s' returning <%p> for '%s'\n", this,
functionName.c_str(), obj, name.c_str());
#endif
return obj;
}
//------------------------------------------------------------------------------
//bool IsAutomaticObjectGlobal(const std::string &autoObjName, GmatBase *owner)
//------------------------------------------------------------------------------
/**
* Checks if the owner of automatic object such as Parameter is global object.
*
* @param autoObjName Input object name
* @param *owner Owner of the automatic object if owner is found
*/
//------------------------------------------------------------------------------
bool UserDefinedFunction::IsAutomaticObjectGlobal(const std::string &autoObjName,
GmatBase **owner)
{
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
("UserDefinedFunction::IsAutomaticObjectGlobal() entered, autoObjName='%s'\n",
autoObjName.c_str());
#endif
*owner = NULL;
std::string type, ownerName, dep;
GmatStringUtil::ParseParameter(autoObjName, type, ownerName, dep);
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage(" ownerName='%s'\n", ownerName.c_str());
#endif
bool isParamOwnerGlobal = false;
if (globalObjectStore->find(ownerName) != globalObjectStore->end())
{
*owner = (globalObjectStore->find(ownerName))->second;
isParamOwnerGlobal = true;
}
#ifdef DEBUG_AUTO_OBJ
MessageInterface::ShowMessage
("UserDefinedFunction::IsAutomaticObjectGlobal() leaving, autoObjName='%s' is %s, ",
autoObjName.c_str(), isParamOwnerGlobal ? "global" : "not global");
MessageInterface::ShowMessage(GmatBase::WriteObjectInfo("owner=", (*owner)));
#endif
return isParamOwnerGlobal;
}
//------------------------------------------------------------------------------
// void ShowObjects(const std::string &title)
//------------------------------------------------------------------------------
void UserDefinedFunction::ShowObjects(const std::string &title)
{
MessageInterface::ShowMessage("%s\n", title.c_str());
MessageInterface::ShowMessage("this=<%p>, functionName='%s'\n", this, functionName.c_str());
MessageInterface::ShowMessage("========================================\n");
MessageInterface::ShowMessage("solarSys = <%p>\n", solarSys);
MessageInterface::ShowMessage("internalCoordSys = <%p>\n", internalCoordSys);
MessageInterface::ShowMessage("forces = <%p>\n", forces);
MessageInterface::ShowMessage("sandboxObjects.size() = %d\n", sandboxObjects.size());
for (UnsignedInt i = 0; i < sandboxObjects.size(); i++)
{
GmatBase *obj = sandboxObjects[i];
MessageInterface::ShowMessage
(" <%p>[%s]'%s'", obj, obj ? obj->GetTypeName().c_str() : "NULL",
obj ? obj->GetName().c_str() : "NULL");
if (obj->IsOfType(Gmat::PARAMETER))
{
GmatBase *paramOwner = ((Parameter*)obj)->GetOwner();
MessageInterface::ShowMessage
(" paramOwner = <%p>[%s]'%s'\n", paramOwner,
paramOwner ? paramOwner->GetTypeName().c_str() : "NULL",
paramOwner ? paramOwner->GetName().c_str() : "NULL");
}
else
{
MessageInterface::ShowMessage("\n");
}
}
ShowObjectMap(&functionObjectMap, "ShowObjects()", "functionObjectMap");
ShowObjectMap(&automaticObjectMap, "ShowObjects()", "automaticObjectMap");
ShowObjectMap(objectStore, "ShowObjects()", "objectStore");
ShowObjectMap(globalObjectStore, "ShowObjects()", "globalObjectStore");
MessageInterface::ShowMessage("========================================\n");
}
|
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2014 Live Networks, Inc. All rights reserved.
// File Sinks
// C++ header
#ifndef _FILE_SINK_HH
#define _FILE_SINK_HH
#ifndef _MEDIA_SINK_HH
#include "MediaSink.hh"
#endif
class FileSink: public MediaSink {
public:
static FileSink* createNew(UsageEnvironment& env, char const* fileName,
unsigned bufferSize = 20000,
Boolean oneFilePerFrame = False);
// "bufferSize" should be at least as large as the largest expected
// input frame.
// "oneFilePerFrame" - if True - specifies that each input frame will
// be written to a separate file (using the presentation time as a
// file name suffix). The default behavior ("oneFilePerFrame" == False)
// is to output all incoming data into a single file.
virtual void addData(unsigned char const* data, unsigned dataSize,
struct timeval presentationTime);
// (Available in case a client wants to add extra data to the output file)
protected:
FileSink(UsageEnvironment& env, FILE* fid, unsigned bufferSize,
char const* perFrameFileNamePrefix);
// called only by createNew()
virtual ~FileSink();
protected: // redefined virtual functions:
virtual Boolean continuePlaying();
protected:
static void afterGettingFrame(void* clientData, unsigned frameSize,
unsigned numTruncatedBytes,
struct timeval presentationTime,
unsigned durationInMicroseconds);
virtual void afterGettingFrame(unsigned frameSize,
unsigned numTruncatedBytes,
struct timeval presentationTime);
FILE* fOutFid;
unsigned char* fBuffer;
unsigned fBufferSize;
char* fPerFrameFileNamePrefix; // used if "oneFilePerFrame" is True
char* fPerFrameFileNameBuffer; // used if "oneFilePerFrame" is True
struct timeval fPrevPresentationTime;
unsigned fSamePresentationTimeCounter;
};
#endif
|
//
// Copyright 2016 gRPC authors.
//
// 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.
//
// This is similar to the sockaddr resolver, except that it supports a
// bunch of query args that are useful for dependency injection in tests.
#include <grpc/support/port_platform.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
namespace grpc_core {
// This cannot be in an anonymous namespace, because it is a friend of
// FakeResolverResponseGenerator.
class FakeResolver : public Resolver {
public:
explicit FakeResolver(ResolverArgs args);
void StartLocked() override;
void RequestReresolutionLocked() override;
private:
friend class FakeResolverResponseGenerator;
virtual ~FakeResolver();
void ShutdownLocked() override { active_ = false; }
void MaybeSendResultLocked();
static void ReturnReresolutionResult(void* arg, grpc_error* error);
// passed-in parameters
grpc_channel_args* channel_args_ = nullptr;
// If has_next_result_ is true, next_result_ is the next resolution result
// to be returned.
bool has_next_result_ = false;
Result next_result_;
// Result to use for the pretended re-resolution in
// RequestReresolutionLocked().
bool has_reresolution_result_ = false;
Result reresolution_result_;
// True between the calls to StartLocked() ShutdownLocked().
bool active_ = false;
// if true, return failure
bool return_failure_ = false;
// pending re-resolution
grpc_closure reresolution_closure_;
bool reresolution_closure_pending_ = false;
};
FakeResolver::FakeResolver(ResolverArgs args)
: Resolver(args.combiner, std::move(args.result_handler)) {
GRPC_CLOSURE_INIT(&reresolution_closure_, ReturnReresolutionResult, this,
grpc_combiner_scheduler(combiner()));
channel_args_ = grpc_channel_args_copy(args.args);
FakeResolverResponseGenerator* response_generator =
FakeResolverResponseGenerator::GetFromArgs(args.args);
if (response_generator != nullptr) {
response_generator->resolver_ = this;
if (response_generator->has_result_) {
response_generator->SetResponse(std::move(response_generator->result_));
response_generator->has_result_ = false;
}
}
}
FakeResolver::~FakeResolver() { grpc_channel_args_destroy(channel_args_); }
void FakeResolver::StartLocked() {
active_ = true;
MaybeSendResultLocked();
}
void FakeResolver::RequestReresolutionLocked() {
if (has_reresolution_result_ || return_failure_) {
next_result_ = reresolution_result_;
has_next_result_ = true;
// Return the result in a different closure, so that we don't call
// back into the LB policy while it's still processing the previous
// update.
if (!reresolution_closure_pending_) {
reresolution_closure_pending_ = true;
Ref().release(); // ref held by closure
GRPC_CLOSURE_SCHED(&reresolution_closure_, GRPC_ERROR_NONE);
}
}
}
void FakeResolver::MaybeSendResultLocked() {
if (!active_) return;
if (return_failure_) {
// TODO(roth): Change resolver result generator to be able to inject
// the error to be returned.
result_handler()->ReturnError(grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver transient failure"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
return_failure_ = false;
} else if (has_next_result_) {
Result result;
result.addresses = std::move(next_result_.addresses);
result.service_config = std::move(next_result_.service_config);
// TODO(roth): Use std::move() once grpc_error is converted to C++.
result.service_config_error = next_result_.service_config_error;
next_result_.service_config_error = GRPC_ERROR_NONE;
// When both next_results_ and channel_args_ contain an arg with the same
// name, only the one in next_results_ will be kept since next_results_ is
// before channel_args_.
result.args = grpc_channel_args_union(next_result_.args, channel_args_);
result_handler()->ReturnResult(std::move(result));
has_next_result_ = false;
}
}
void FakeResolver::ReturnReresolutionResult(void* arg, grpc_error* error) {
FakeResolver* self = static_cast<FakeResolver*>(arg);
self->reresolution_closure_pending_ = false;
self->MaybeSendResultLocked();
self->Unref();
}
//
// FakeResolverResponseGenerator
//
struct SetResponseClosureArg {
grpc_closure set_response_closure;
FakeResolverResponseGenerator* generator;
Resolver::Result result;
bool has_result = false;
bool immediate = true;
};
void FakeResolverResponseGenerator::SetResponseLocked(void* arg,
grpc_error* error) {
SetResponseClosureArg* closure_arg = static_cast<SetResponseClosureArg*>(arg);
FakeResolver* resolver = closure_arg->generator->resolver_;
resolver->next_result_ = std::move(closure_arg->result);
resolver->has_next_result_ = true;
resolver->MaybeSendResultLocked();
closure_arg->generator->Unref();
Delete(closure_arg);
}
void FakeResolverResponseGenerator::SetResponse(Resolver::Result result) {
if (resolver_ != nullptr) {
Ref().release(); // ref to be held by closure
SetResponseClosureArg* closure_arg = New<SetResponseClosureArg>();
closure_arg->generator = this;
closure_arg->result = std::move(result);
GRPC_CLOSURE_SCHED(
GRPC_CLOSURE_INIT(&closure_arg->set_response_closure, SetResponseLocked,
closure_arg,
grpc_combiner_scheduler(resolver_->combiner())),
GRPC_ERROR_NONE);
} else {
GPR_ASSERT(!has_result_);
has_result_ = true;
result_ = std::move(result);
}
}
void FakeResolverResponseGenerator::SetReresolutionResponseLocked(
void* arg, grpc_error* error) {
SetResponseClosureArg* closure_arg = static_cast<SetResponseClosureArg*>(arg);
FakeResolver* resolver = closure_arg->generator->resolver_;
resolver->reresolution_result_ = std::move(closure_arg->result);
resolver->has_reresolution_result_ = closure_arg->has_result;
Delete(closure_arg);
}
void FakeResolverResponseGenerator::SetReresolutionResponse(
Resolver::Result result) {
GPR_ASSERT(resolver_ != nullptr);
SetResponseClosureArg* closure_arg = New<SetResponseClosureArg>();
closure_arg->generator = this;
closure_arg->result = std::move(result);
closure_arg->has_result = true;
GRPC_CLOSURE_SCHED(
GRPC_CLOSURE_INIT(&closure_arg->set_response_closure,
SetReresolutionResponseLocked, closure_arg,
grpc_combiner_scheduler(resolver_->combiner())),
GRPC_ERROR_NONE);
}
void FakeResolverResponseGenerator::UnsetReresolutionResponse() {
GPR_ASSERT(resolver_ != nullptr);
SetResponseClosureArg* closure_arg = New<SetResponseClosureArg>();
closure_arg->generator = this;
GRPC_CLOSURE_SCHED(
GRPC_CLOSURE_INIT(&closure_arg->set_response_closure,
SetReresolutionResponseLocked, closure_arg,
grpc_combiner_scheduler(resolver_->combiner())),
GRPC_ERROR_NONE);
}
void FakeResolverResponseGenerator::SetFailureLocked(void* arg,
grpc_error* error) {
SetResponseClosureArg* closure_arg = static_cast<SetResponseClosureArg*>(arg);
FakeResolver* resolver = closure_arg->generator->resolver_;
resolver->return_failure_ = true;
if (closure_arg->immediate) resolver->MaybeSendResultLocked();
Delete(closure_arg);
}
void FakeResolverResponseGenerator::SetFailure() {
GPR_ASSERT(resolver_ != nullptr);
SetResponseClosureArg* closure_arg = New<SetResponseClosureArg>();
closure_arg->generator = this;
GRPC_CLOSURE_SCHED(
GRPC_CLOSURE_INIT(&closure_arg->set_response_closure, SetFailureLocked,
closure_arg,
grpc_combiner_scheduler(resolver_->combiner())),
GRPC_ERROR_NONE);
}
void FakeResolverResponseGenerator::SetFailureOnReresolution() {
GPR_ASSERT(resolver_ != nullptr);
SetResponseClosureArg* closure_arg = New<SetResponseClosureArg>();
closure_arg->generator = this;
closure_arg->immediate = false;
GRPC_CLOSURE_SCHED(
GRPC_CLOSURE_INIT(&closure_arg->set_response_closure, SetFailureLocked,
closure_arg,
grpc_combiner_scheduler(resolver_->combiner())),
GRPC_ERROR_NONE);
}
namespace {
static void* response_generator_arg_copy(void* p) {
FakeResolverResponseGenerator* generator =
static_cast<FakeResolverResponseGenerator*>(p);
// TODO(roth): We currently deal with this ref manually. Once the
// new channel args code is converted to C++, find a way to track this ref
// in a cleaner way.
RefCountedPtr<FakeResolverResponseGenerator> copy = generator->Ref();
copy.release();
return p;
}
static void response_generator_arg_destroy(void* p) {
FakeResolverResponseGenerator* generator =
static_cast<FakeResolverResponseGenerator*>(p);
generator->Unref();
}
static int response_generator_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
static const grpc_arg_pointer_vtable response_generator_arg_vtable = {
response_generator_arg_copy, response_generator_arg_destroy,
response_generator_cmp};
} // namespace
grpc_arg FakeResolverResponseGenerator::MakeChannelArg(
FakeResolverResponseGenerator* generator) {
grpc_arg arg;
arg.type = GRPC_ARG_POINTER;
arg.key = (char*)GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR;
arg.value.pointer.p = generator;
arg.value.pointer.vtable = &response_generator_arg_vtable;
return arg;
}
FakeResolverResponseGenerator* FakeResolverResponseGenerator::GetFromArgs(
const grpc_channel_args* args) {
const grpc_arg* arg =
grpc_channel_args_find(args, GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR);
if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr;
return static_cast<FakeResolverResponseGenerator*>(arg->value.pointer.p);
}
//
// Factory
//
namespace {
class FakeResolverFactory : public ResolverFactory {
public:
OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
return OrphanablePtr<Resolver>(New<FakeResolver>(std::move(args)));
}
const char* scheme() const override { return "fake"; }
};
} // namespace
} // namespace grpc_core
void grpc_resolver_fake_init() {
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::FakeResolverFactory>()));
}
void grpc_resolver_fake_shutdown() {}
|
///*
// * Copyright (c) 2009-2011, NVIDIA Corporation
// * 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 NVIDIA Corporation 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 <COPYRIGHT HOLDER> 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 "Thread.hpp"
//
//using namespace FW;
//
////------------------------------------------------------------------------
//
//Spinlock Thread::s_lock;
//Hash<U32, Thread*> Thread::s_threads;
//Thread* Thread::s_mainThread = NULL;
//
////------------------------------------------------------------------------
//
//Spinlock::Spinlock(void)
//{
// InitializeCriticalSection(&m_critSect);
//}
//
////------------------------------------------------------------------------
//
//Spinlock::~Spinlock(void)
//{
// DeleteCriticalSection(&m_critSect);
//}
//
////------------------------------------------------------------------------
//
//void Spinlock::enter(void)
//{
// EnterCriticalSection(&m_critSect);
//}
//
////------------------------------------------------------------------------
//
//void Spinlock::leave(void)
//{
// LeaveCriticalSection(&m_critSect);
//}
//
////------------------------------------------------------------------------
//
//Semaphore::Semaphore(int initCount, int maxCount)
//{
// m_handle = CreateSemaphore(NULL, initCount, maxCount, NULL);
// if (!m_handle)
// failWin32Error("CreateSemaphore");
//}
//
////------------------------------------------------------------------------
//
//Semaphore::~Semaphore(void)
//{
// CloseHandle(m_handle);
//}
//
////------------------------------------------------------------------------
//
//bool Semaphore::acquire(int millis)
//{
// DWORD res = WaitForSingleObject(m_handle, (millis >= 0) ? millis : INFINITE);
// if (res == WAIT_FAILED)
// failWin32Error("WaitForSingleObject");
// return (res == WAIT_OBJECT_0);
//}
//
////------------------------------------------------------------------------
//
//void Semaphore::release(void)
//{
// if (!ReleaseSemaphore(m_handle, 1, NULL))
// failWin32Error("ReleaseSemaphore");
//}
//
////------------------------------------------------------------------------
//
//Monitor::Monitor(void)
//: m_ownerSem (1, 1),
// m_waitSem (0, 1),
// m_notifySem (0, 1),
// m_ownerThread (0),
// m_enterCount (0),
// m_waitCount (0)
//{
// InitializeCriticalSection(&m_mutex);
// if (isAvailable_InitializeConditionVariable())
// InitializeConditionVariable(&m_condition);
//}
//
////------------------------------------------------------------------------
//
//Monitor::~Monitor(void)
//{
// DeleteCriticalSection(&m_mutex);
//}
//
////------------------------------------------------------------------------
//
//void Monitor::enter(void)
//{
// if (isAvailable_InitializeConditionVariable())
// {
// EnterCriticalSection(&m_mutex);
// }
// else
// {
// U32 currThread = Thread::getID();
//
// m_lock.enter();
// if (m_ownerThread != currThread || !m_enterCount)
// {
// m_lock.leave();
// m_ownerSem.acquire();
// m_lock.enter();
// }
//
// m_ownerThread = currThread;
// m_enterCount++;
// m_lock.leave();
//}
//}
//
////------------------------------------------------------------------------
//
//void Monitor::leave(void)
//{
// if (isAvailable_InitializeConditionVariable())
// {
// LeaveCriticalSection(&m_mutex);
// }
// else
// {
// FW_ASSERT(m_ownerThread == Thread::getID() && m_enterCount);
// m_enterCount--;
// if (!m_enterCount)
// m_ownerSem.release();
//}
//}
//
////------------------------------------------------------------------------
//
//void Monitor::wait(void)
//{
// if (isAvailable_InitializeConditionVariable())
// {
// SleepConditionVariableCS(&m_condition, &m_mutex, INFINITE);
// }
// else
// {
// FW_ASSERT(m_ownerThread == Thread::getID() && m_enterCount);
// U32 currThread = m_ownerThread;
// int enterCount = m_enterCount;
//
// m_waitCount++;
// m_enterCount = 0;
// m_ownerSem.release();
//
// m_waitSem.acquire();
// m_waitCount--;
// m_notifySem.release();
//
// m_ownerSem.acquire();
// m_lock.enter();
// m_ownerThread = currThread;
// m_enterCount = enterCount;
// m_lock.leave();
//}
//}
//
////------------------------------------------------------------------------
//
//void Monitor::notify(void)
//{
// if (isAvailable_InitializeConditionVariable())
// {
// WakeConditionVariable(&m_condition);
// }
// else
// {
// FW_ASSERT(m_ownerThread == Thread::getID() && m_enterCount);
// if (m_waitCount)
// {
// m_waitSem.release();
// m_notifySem.acquire();
// }
//}
//}
//
////------------------------------------------------------------------------
//
//void Monitor::notifyAll(void)
//{
// if (isAvailable_InitializeConditionVariable())
// {
// WakeAllConditionVariable(&m_condition);
// }
// else
// {
// FW_ASSERT(m_ownerThread == Thread::getID() && m_enterCount);
// while (m_waitCount)
// {
// m_waitSem.release();
// m_notifySem.acquire();
// }
//}
//}
//
////------------------------------------------------------------------------
//
//Thread::Thread(void)
//: m_refCount (0),
// m_id (0),
// m_handle (NULL),
// m_priority (Priority_Normal)
//{
//}
//
////------------------------------------------------------------------------
//
//Thread::~Thread(void)
//{
// // Wait and exit.
//
// if (this != getCurrent())
// join();
// else
// {
// failIfError();
// refer();
// m_exited = true;
// unrefer();
// }
//
// // Deinit user data.
//
// for (int i = m_userData.firstSlot(); i != -1; i = m_userData.nextSlot(i))
// {
// const UserData& data = m_userData.getSlot(i).value;
// if (data.deinitFunc)
// data.deinitFunc(data.data);
// }
//}
//
////------------------------------------------------------------------------
//
//void Thread::start(ThreadFunc func, void* param)
//{
// m_startLock.enter();
// join();
//
// StartParams params;
// params.thread = this;
// params.userFunc = func;
// params.userParam = param;
// params.ready.acquire();
//
// if (!CreateThread(NULL, 0, threadProc, ¶ms, 0, NULL))
// failWin32Error("CreateThread");
//
// params.ready.acquire();
// m_startLock.leave();
//}
//
////------------------------------------------------------------------------
//
//Thread* Thread::getCurrent(void)
//{
// s_lock.enter();
// Thread** found = s_threads.search(getID());
// Thread* thread = (found) ? *found : NULL;
// s_lock.leave();
//
// if (!thread)
// {
// thread = new Thread;
// thread->started();
// }
// return thread;
//}
//
////------------------------------------------------------------------------
//
//Thread* Thread::getMain(void)
//{
// getCurrent();
// return s_mainThread;
//}
//
////------------------------------------------------------------------------
//
//bool Thread::isMain(void)
//{
// Thread* curr = getCurrent();
// return (curr == s_mainThread);
//}
//
////------------------------------------------------------------------------
//
//U32 Thread::getID(void)
//{
// return GetCurrentThreadId();
//}
//
////------------------------------------------------------------------------
//
//void Thread::sleep(int millis)
//{
// Sleep(millis);
//}
//
////------------------------------------------------------------------------
//
//void Thread::yield(void)
//{
// SwitchToThread();
//}
//
////------------------------------------------------------------------------
//
//int Thread::getPriority(void)
//{
// refer();
// if (m_handle)
// m_priority = GetThreadPriority(m_handle);
// unrefer();
//
// if (m_priority == THREAD_PRIORITY_ERROR_RETURN)
// failWin32Error("GetThreadPriority");
// return m_priority;
//}
//
////------------------------------------------------------------------------
//
//void Thread::setPriority(int priority)
//{
// refer();
// m_priority = priority;
// if (m_handle && !SetThreadPriority(m_handle, priority))
// failWin32Error("SetThreadPriority");
// unrefer();
//}
//
////------------------------------------------------------------------------
//
//bool Thread::isAlive(void)
//{
// bool alive = false;
// refer();
//
// if (m_handle)
// {
// DWORD exitCode;
// if (!GetExitCodeThread(m_handle, &exitCode))
// failWin32Error("GetExitCodeThread");
//
// if (exitCode == STILL_ACTIVE)
// alive = true;
// else
// m_exited = true;
// }
//
// unrefer();
// return alive;
//}
//
////------------------------------------------------------------------------
//
//void Thread::join(void)
//{
// FW_ASSERT(this != getMain());
// FW_ASSERT(this != getCurrent());
//
// refer();
// if (m_handle && WaitForSingleObject(m_handle, INFINITE) == WAIT_FAILED)
// failWin32Error("WaitForSingleObject");
// m_exited = true;
// unrefer();
//}
//
////------------------------------------------------------------------------
//
//void* Thread::getUserData(const String& id)
//{
// m_lock.enter();
// UserData* found = m_userData.search(id);
// void* data = (found) ? found->data : NULL;
// m_lock.leave();
// return data;
//}
//
////------------------------------------------------------------------------
//
//void Thread::setUserData(const String& id, void* data, DeinitFunc deinitFunc)
//{
// UserData oldData;
// oldData.data = NULL;
// oldData.deinitFunc = NULL;
//
// UserData newData;
// newData.data = data;
// newData.deinitFunc = deinitFunc;
//
// // Replace data.
//
// m_lock.enter();
//
// UserData* found = m_userData.search(id);
// if (found)
// {
// oldData = *found;
// *found = newData;
// }
//
// if ((found != NULL) != (data != NULL || deinitFunc != NULL))
// {
// if (found)
// m_userData.remove(id);
// else
// m_userData.add(id, newData);
// }
//
// m_lock.leave();
//
// // Deinit old data.
//
// if (oldData.deinitFunc)
// oldData.deinitFunc(oldData.data);
//}
//
////------------------------------------------------------------------------
//
//void Thread::suspendAll(void)
//{
// s_lock.enter();
// for (int i = s_threads.firstSlot(); i != -1; i = s_threads.nextSlot(i))
// {
// Thread* thread = s_threads.getSlot(i).value;
// thread->refer();
// if (thread->m_handle && thread->m_id != getID())
// SuspendThread(thread->m_handle);
// thread->unrefer();
// }
// s_lock.leave();
//}
//
////------------------------------------------------------------------------
//
//void Thread::refer(void)
//{
// m_lock.enter();
// m_refCount++;
// m_lock.leave();
//}
//
////------------------------------------------------------------------------
//
//void Thread::unrefer(void)
//{
// m_lock.enter();
// if (--m_refCount == 0 && m_exited)
// {
// m_exited = false;
// exited();
// }
// m_lock.leave();
//}
//
////------------------------------------------------------------------------
//
//void Thread::started(void)
//{
// m_id = getID();
// HANDLE process = GetCurrentProcess();
// if (!DuplicateHandle(process, GetCurrentThread(), process, &m_handle, THREAD_ALL_ACCESS, FALSE, 0))
// failWin32Error("DuplicateHandle");
//
// s_lock.enter();
//
// if (!s_mainThread)
// s_mainThread = this;
//
// if (!s_threads.contains(m_id))
// s_threads.add(m_id, this);
//
// s_lock.leave();
//}
//
////------------------------------------------------------------------------
//
//void Thread::exited(void)
//{
// if (!m_handle)
// return;
//
// s_lock.enter();
//
// if (this == s_mainThread)
// s_mainThread = NULL;
//
// if (s_threads.contains(m_id))
// s_threads.remove(m_id);
//
// if (!s_threads.getSize())
// s_threads.reset();
//
// s_lock.leave();
//
// if (m_handle)
// CloseHandle(m_handle);
// m_id = 0;
// m_handle = NULL;
//}
//
////------------------------------------------------------------------------
//
//DWORD WINAPI Thread::threadProc(LPVOID lpParameter)
//{
// StartParams* params = (StartParams*)lpParameter;
// Thread* thread = params->thread;
// ThreadFunc userFunc = params->userFunc;
// void* userParam = params->userParam;
//
// // Initialize.
//
// thread->started();
// thread->setPriority(thread->m_priority);
// params->ready.release();
//
// // Execute.
//
// userFunc(userParam);
//
// // Check whether the thread object still exists,
// // as userFunc() may have deleted it.
//
// s_lock.enter();
// bool exists = s_threads.contains(getID());
// s_lock.leave();
//
// // Still exists => deinit.
//
// if (exists)
// {
// failIfError();
// thread->getPriority();
//
// thread->refer();
// thread->m_exited = true;
// thread->unrefer();
// }
// return 0;
//}
//
////------------------------------------------------------------------------
|
//=================================================================================================
// Copyright 2014-2015 Dirk Lemstra <https://graphicsmagick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// 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.
//=================================================================================================
#include "Stdafx.h"
#include "MagickFormatInfo.h"
#include "Exceptions\Base\MagickException.h"
#include "Helpers\EnumHelper.h"
using namespace System::Globalization;
namespace GraphicsMagick
{
//==============================================================================================
void MagickFormatInfo::AddStealthCoder(std::list<Magick::CoderInfo>* coderList, std::string name)
{
try
{
Magick::CoderInfo coderInfo(name);
coderList->push_back(coderInfo);
}
catch(Magick::ErrorModule)
{
}
catch(Magick::Exception& exception)
{
MagickException::Throw(exception);
}
}
//==============================================================================================
Collection<MagickFormatInfo^>^ MagickFormatInfo::LoadFormats()
{
Collection<MagickFormatInfo^>^ result = gcnew Collection<MagickFormatInfo^>();
std::list<Magick::CoderInfo> coderList;
try
{
coderInfoList(&coderList);
}
catch(Magick::Exception& exception)
{
MagickException::Throw(exception);
}
AddStealthCoder(&coderList, "DIB");
AddStealthCoder(&coderList, "TIF");
std::list<Magick::CoderInfo>::const_iterator coder = coderList.begin();
while(coder != coderList.end())
{
MagickFormatInfo^ formatInfo = gcnew MagickFormatInfo();
String^ name = Marshaller::Marshal(coder->name());
name = name->Replace("-", "");
if (name == "3FR")
name = "ThreeFr";
if (!_CustomStealthFormats->Contains(name))
{
formatInfo->_Format = EnumHelper::Parse<MagickFormat>(name, MagickFormat::Unknown);
formatInfo->_Description = Marshaller::Marshal(coder->description());
formatInfo->_CoderInfo = new Magick::CoderInfo(*coder);
result->Add(formatInfo);
}
coder++;
}
return result;
}
//==============================================================================================
String^ MagickFormatInfo::Description::get()
{
return _Description;
}
//==============================================================================================
MagickFormat MagickFormatInfo::Format::get()
{
return _Format;
}
//==============================================================================================
bool MagickFormatInfo::IsMultiFrame::get()
{
return _CoderInfo->isMultiFrame();
}
//==============================================================================================
bool MagickFormatInfo::IsReadable::get()
{
return _CoderInfo->isReadable();
}
//==============================================================================================
bool MagickFormatInfo::IsWritable::get()
{
return _CoderInfo->isWritable();
}
//==============================================================================================
String^ MagickFormatInfo::ToString()
{
return String::Format(CultureInfo::InvariantCulture, "{0}: {1} ({2}R{3}W{4}M)", Format, Description,
IsReadable ? "+" : "-", IsWritable ? "+" : "-", IsMultiFrame ? "+" : "-");
}
//==============================================================================================
}
|
//
// stream_descriptor.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef BOOST_ASIO_POSIX_STREAM_DESCRIPTOR_HPP
#define BOOST_ASIO_POSIX_STREAM_DESCRIPTOR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/push_options.hpp>
#include <boost/asio/posix/basic_stream_descriptor.hpp>
#if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \
|| defined(GENERATING_DOCUMENTATION)
namespace boost {
namespace asio {
namespace posix {
/// Typedef for the typical usage of a stream-oriented descriptor.
typedef basic_stream_descriptor<> stream_descriptor;
} // namespace posix
} // namespace asio
} // namespace boost
#endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
// || defined(GENERATING_DOCUMENTATION)
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_POSIX_STREAM_DESCRIPTOR_HPP
|
/*
引用元:https://atcoder.jp/contests/abc042/tasks/arc058_a
C - Iroha's ObsessionEditorial
// ソースコードの引用元 :
https://atcoder.jp/contests/abc042/submissions/11403600
// 提出ID : 11403600
// 問題ID : arc058_a
// コンテストID : abc042
// ユーザID : xryuseix
// コード長 : 2673
// 実行時間 : 2
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_set>
#include <vector>
#pragma GCC optimize("Ofast")
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int, int>> vpii;
typedef vector<vector<int>> vvi;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
typedef vector<vector<ll>> vvll;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
#define fin(ans) cout << (ans) << '\n'
#define STLL(s) strtoll(s.c_str(), NULL, 10)
#define mp(p, q) make_pair(p, q)
#define pb(n) push_back(n)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define Sort(a) sort(a.begin(), a.end())
#define Rort(a) sort(a.rbegin(), a.rend())
#define MATHPI acos(-1)
#define itn int;
#define endl '\n';
const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
template <class T>
inline bool chmax(T &a, T b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T>
inline bool chmin(T &a, T b) {
if (a > b) {
a = b;
return 1;
}
return 0;
}
inline string getline() {
string s;
getline(cin, s);
return s;
}
inline void yn(const bool b) { b ? fin("yes") : fin("no"); }
inline void Yn(const bool b) { b ? fin("Yes") : fin("No"); }
inline void YN(const bool b) { b ? fin("YES") : fin("NO"); }
struct io {
io() {
ios::sync_with_stdio(false);
cin.tie(0);
}
};
const int INF = INT_MAX;
const ll LLINF = 1LL << 60;
const ll MOD = 1000000007;
const double EPS = 1e-9;
vi dp(222222, false);
int n, k;
set<int> v;
vi use;
int t;
int main() {
cin >> n >> k;
rep(i, k) {
cin >> t;
v.insert(t);
}
rep(i, 1e1) {
if (!v.count(i)) use.pb(i);
}
rep(i, use.size()) dp[use[i]] = 1;
for (int i = 0; i <= 1e4; i++) {
if (dp[i]) {
rep(j, use.size()) { dp[i * 10 + use[j]] = 1; }
}
}
for (int i = n; i < 1e5; i++) {
if (!dp[i]) continue;
fin(i);
return 0;
}
}
|
//=================================================================================================
/*!
// \file src/mathtest/dvecdvecdiv/V6bV6b.cpp
// \brief Source file for the V6bV6b dense vector/dense vector division math test
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecdvecdiv/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V6bV6b'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
using V6b = blaze::StaticVector<TypeB,6UL>;
// Creator type definitions
using CV6b = blazetest::Creator<V6b>;
// Running the tests
RUN_DVECDVECDIV_OPERATION_TEST( CV6b(), CV6b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector division:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// author - sonaspy@outlook.com
// coding - utf_8
#include <iostream>
#include<string>
#include<algorithm>
#define test() freopen("in", "r", stdin)
using namespace std;
int main(int argc, char const *argv[])
{
/* code */
//test();
int a, b, c, d, sh, r;
cin >> a >> b >> d;
c = a + b;
string s;
sh = c / d;
r = c % d;
while (sh || r)
{
s.push_back(r+'0');
r = sh % d;
sh /= d;
}
reverse(s.begin(),s.end());
if (!c)
cout << 0;
else
cout << s;
return 0;
}
|
/**
* This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
*
* Copyright 2019 Huawei Technologies Co., Ltd
*
* 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.
*/
#include "optimizer/cse.h"
#include <vector>
#include <set>
#include <unordered_map>
#include "./common.h"
namespace mindspore {
/* namespace to support opt */
namespace opt {
using mindspore::abstract::AbstractBase;
using mindspore::abstract::AbstractFunction;
using mindspore::abstract::AbstractFunctionPtr;
BasePtr AbsOf(const AnfNodePtr &node) {
MS_EXCEPTION_IF_NULL(node);
auto node_abs = node->abstract();
// in testcase: TestOptOpt.CSE, node->abstract() is null;
if (node_abs == nullptr) {
return kAnyValue;
}
return node_abs;
}
bool CSE::BuildOrderGroupAndDoReplace(const FuncGraphManagerPtr manager) const {
bool changed = false;
for (FuncGraphPtr fg : manager->func_graphs()) {
MS_EXCEPTION_IF_NULL(fg);
std::vector<std::size_t> order_group;
std::unordered_map<std::size_t, std::vector<AnfNodePtr>> groups;
std::unordered_map<AnfNodePtr, std::size_t> hashes;
std::vector<AnfNodePtr> toposet = TopoSort(fg->get_return());
for (auto node : toposet) {
MS_EXCEPTION_IF_NULL(node);
if (hashes.find(node) != hashes.end()) {
continue;
}
std::size_t h = 0;
if (node->isa<ValueNode>()) {
ValueNodePtr value_node = node->cast<ValueNodePtr>();
auto value = value_node->value();
MS_EXCEPTION_IF_NULL(value);
h = hash_combine(value->hash(), (AbsOf(value_node)->hash()));
} else if (node->isa<CNode>()) {
auto cnode = node->cast<CNodePtr>();
auto &inputs = cnode->inputs();
size_t init = 0;
h = std::accumulate(inputs.begin(), inputs.end(), init, [&hashes](std::size_t hash, const AnfNodePtr &node_in) {
return hash_combine(hash, hashes[node_in]);
});
} else if (node->isa<Parameter>()) {
h = node->hash();
} else {
MS_LOG(ERROR) << "Unknow node type";
}
hashes[node] = h;
if (groups.find(h) == groups.end()) {
std::vector<AnfNodePtr> innervec({node});
groups[h] = innervec;
order_group.emplace_back(h);
} else {
groups[h].push_back(node);
}
}
changed = DoReplace(manager, order_group, &groups) || changed;
}
return changed;
}
bool CSE::CheckReplace(const AnfNodePtr &main, const AnfNodePtr &node) const {
MS_EXCEPTION_IF_NULL(main);
MS_EXCEPTION_IF_NULL(node);
bool replace = false;
if (main->isa<ValueNode>() && node->isa<ValueNode>()) {
auto main_value = GetValueNode(main);
auto node_value = GetValueNode(node);
replace = (AbsOf(main) == AbsOf(node)) && (*main_value == *node_value);
} else if (main->isa<CNode>() && node->isa<CNode>()) {
auto c_main = main->cast<CNodePtr>();
auto c_node = node->cast<CNodePtr>();
const auto &inp1 = c_main->inputs();
const auto &inp2 = c_node->inputs();
if (inp1.size() == inp2.size()) {
bool appsame = true;
for (size_t j = 0; j < inp1.size(); j++) {
MS_EXCEPTION_IF_NULL(inp1[j]);
MS_EXCEPTION_IF_NULL(inp2[j]);
if (!(*inp1[j] == *inp2[j])) {
// Handle the case of two different Tensor, but with the same value
if (IsValueNode<tensor::Tensor>(inp1[j]) && IsValueNode<tensor::Tensor>(inp2[j])) {
auto tensor1 = GetValueNode<tensor::TensorPtr>(inp1[j]);
auto tensor2 = GetValueNode<tensor::TensorPtr>(inp2[j]);
if (tensor1->ValueEqual(*tensor2)) {
continue;
}
}
appsame = false;
break;
}
}
if (IsPrimitiveCNode(c_main, prim::kPrimDropoutGenMask)) {
appsame = false;
}
replace = appsame;
}
}
return replace;
}
bool CSE::DoReplace(const FuncGraphManagerPtr manager, const std::vector<std::size_t> &order_group,
std::unordered_map<std::size_t, std::vector<AnfNodePtr>> *groups) const {
bool changes = false;
std::set<size_t> clear_set;
for (auto &h : order_group) {
std::vector<AnfNodePtr> &group = (*groups)[h];
// If there are more than 2 node in that group, they may be same common expression can be eliminated.
if (group.size() > 1) {
for (size_t k = 0; k < group.size() - 1; k++) {
AnfNodePtr main = group[k];
MS_EXCEPTION_IF_NULL(main);
// When all node in group has been replaced
// or a valuenode node, skip compare in group
if ((k + 1 + clear_set.size() == group.size()) || (k > 0 && main->isa<ValueNode>())) {
break;
}
// skip node has been replaced
if (clear_set.find(k) != clear_set.end()) {
continue;
}
// Compare with rest elements in this group.
for (size_t i = k + 1; i < group.size(); i++) {
auto node = group[i];
MS_EXCEPTION_IF_NULL(node);
if (clear_set.find(i) != clear_set.end()) {
continue;
}
if (main->func_graph() != node->func_graph()) {
continue;
}
if (CheckReplace(node, main)) {
changes = true;
(void)manager->Replace(node, main);
(void)clear_set.insert(i);
}
}
}
clear_set.clear();
}
}
return changes;
}
bool CSE::Cse(const FuncGraphPtr root, const FuncGraphManagerPtr manager) const {
MS_EXCEPTION_IF_NULL(manager);
manager->AddFuncGraph(root);
return BuildOrderGroupAndDoReplace(manager);
}
} // namespace opt
} // namespace mindspore
|
// Copyright (c) 2014-2017 The paymeal Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "checkpoints.h"
#include "governance.h"
#include "validation.h"
#include "masternode.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "netfulfilledman.h"
#include "netmessagemaker.h"
#include "spork.h"
#include "ui_interface.h"
#include "util.h"
class CMasternodeSync;
CMasternodeSync masternodeSync;
void CMasternodeSync::Fail()
{
nTimeLastFailure = GetTime();
nRequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;
}
void CMasternodeSync::Reset()
{
nRequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;
nRequestedMasternodeAttempt = 0;
nTimeAssetSyncStarted = GetTime();
nTimeLastBumped = GetTime();
nTimeLastFailure = 0;
}
void CMasternodeSync::BumpAssetLastTime(const std::string& strFuncName)
{
if(IsSynced() || IsFailed()) return;
nTimeLastBumped = GetTime();
LogPrint("mnsync", "CMasternodeSync::BumpAssetLastTime -- %s\n", strFuncName);
}
std::string CMasternodeSync::GetAssetName()
{
switch(nRequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_INITIAL): return "MASTERNODE_SYNC_INITIAL";
case(MASTERNODE_SYNC_WAITING): return "MASTERNODE_SYNC_WAITING";
case(MASTERNODE_SYNC_LIST): return "MASTERNODE_SYNC_LIST";
case(MASTERNODE_SYNC_MNW): return "MASTERNODE_SYNC_MNW";
case(MASTERNODE_SYNC_GOVERNANCE): return "MASTERNODE_SYNC_GOVERNANCE";
case(MASTERNODE_SYNC_FAILED): return "MASTERNODE_SYNC_FAILED";
case MASTERNODE_SYNC_FINISHED: return "MASTERNODE_SYNC_FINISHED";
default: return "UNKNOWN";
}
}
void CMasternodeSync::SwitchToNextAsset(CConnman& connman)
{
switch(nRequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_FAILED):
throw std::runtime_error("Can't switch to next asset from failed, should use Reset() first!");
break;
case(MASTERNODE_SYNC_INITIAL):
ClearFulfilledRequests(connman);
nRequestedMasternodeAssets = MASTERNODE_SYNC_WAITING;
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName());
break;
case(MASTERNODE_SYNC_WAITING):
ClearFulfilledRequests(connman);
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted);
nRequestedMasternodeAssets = MASTERNODE_SYNC_LIST;
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName());
break;
case(MASTERNODE_SYNC_LIST):
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted);
nRequestedMasternodeAssets = MASTERNODE_SYNC_MNW;
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName());
break;
case(MASTERNODE_SYNC_MNW):
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted);
nRequestedMasternodeAssets = MASTERNODE_SYNC_GOVERNANCE;
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName());
break;
case(MASTERNODE_SYNC_GOVERNANCE):
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted);
nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
uiInterface.NotifyAdditionalDataSyncProgressChanged(1);
//try to activate our masternode if possible
activeMasternode.ManageState(connman);
connman.ForEachNode(CConnman::AllNodes, [](CNode* pnode) {
netfulfilledman.AddFulfilledRequest(pnode->addr, "full-sync");
});
LogPrintf("CMasternodeSync::SwitchToNextAsset -- Sync has finished\n");
break;
}
nRequestedMasternodeAttempt = 0;
nTimeAssetSyncStarted = GetTime();
BumpAssetLastTime("CMasternodeSync::SwitchToNextAsset");
}
std::string CMasternodeSync::GetSyncStatus()
{
switch (masternodeSync.nRequestedMasternodeAssets) {
case MASTERNODE_SYNC_INITIAL: return _("Synchroning blockchain...");
case MASTERNODE_SYNC_WAITING: return _("Synchronization pending...");
case MASTERNODE_SYNC_LIST: return _("Synchronizing masternodes...");
case MASTERNODE_SYNC_MNW: return _("Synchronizing masternode payments...");
case MASTERNODE_SYNC_GOVERNANCE: return _("Synchronizing governance objects...");
case MASTERNODE_SYNC_FAILED: return _("Synchronization failed");
case MASTERNODE_SYNC_FINISHED: return _("Synchronization finished");
default: return "";
}
}
void CMasternodeSync::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv)
{
if (strCommand == NetMsgType::SYNCSTATUSCOUNT) { //Sync status count
//do not care about stats if sync process finished or failed
if(IsSynced() || IsFailed()) return;
int nItemID;
int nCount;
vRecv >> nItemID >> nCount;
LogPrintf("SYNCSTATUSCOUNT -- got inventory count: nItemID=%d nCount=%d peer=%d\n", nItemID, nCount, pfrom->id);
}
}
void CMasternodeSync::ClearFulfilledRequests(CConnman& connman)
{
connman.ForEachNode(CConnman::AllNodes, [](CNode* pnode) {
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "spork-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "masternode-list-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "masternode-payment-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "governance-sync");
netfulfilledman.RemoveFulfilledRequest(pnode->addr, "full-sync");
});
}
void CMasternodeSync::ProcessTick(CConnman& connman)
{
static int nTick = 0;
if(nTick++ % MASTERNODE_SYNC_TICK_SECONDS != 0) return;
// reset the sync process if the last call to this function was more than 60 minutes ago (client was in sleep mode)
static int64_t nTimeLastProcess = GetTime();
if(GetTime() - nTimeLastProcess > 60*60) {
LogPrintf("CMasternodeSync::ProcessTick -- WARNING: no actions for too long, restarting sync...\n");
Reset();
SwitchToNextAsset(connman);
nTimeLastProcess = GetTime();
return;
}
nTimeLastProcess = GetTime();
// reset sync status in case of any other sync failure
if(IsFailed()) {
if(nTimeLastFailure + (1*60) < GetTime()) { // 1 minute cooldown after failed sync
LogPrintf("CMasternodeSync::ProcessTick -- WARNING: failed to sync, trying again...\n");
Reset();
SwitchToNextAsset(connman);
}
return;
}
// gradually request the rest of the votes after sync finished
if(IsSynced()) {
std::vector<CNode*> vNodesCopy = connman.CopyNodeVector(CConnman::FullyConnectedOnly);
governance.RequestGovernanceObjectVotes(vNodesCopy, connman);
connman.ReleaseNodeVector(vNodesCopy);
return;
}
// Calculate "progress" for LOG reporting / GUI notification
double nSyncProgress = double(nRequestedMasternodeAttempt + (nRequestedMasternodeAssets - 1) * 8) / (8*4);
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d nRequestedMasternodeAttempt %d nSyncProgress %f\n", nTick, nRequestedMasternodeAssets, nRequestedMasternodeAttempt, nSyncProgress);
uiInterface.NotifyAdditionalDataSyncProgressChanged(nSyncProgress);
std::vector<CNode*> vNodesCopy = connman.CopyNodeVector(CConnman::FullyConnectedOnly);
for (auto& pnode : vNodesCopy)
{
CNetMsgMaker msgMaker(pnode->GetSendVersion());
// Don't try to sync any data from outbound "masternode" connections -
// they are temporary and should be considered unreliable for a sync process.
// Inbound connection this early is most likely a "masternode" connection
// initiated from another node, so skip it too.
if(pnode->fMasternode || (fMasternodeMode && pnode->fInbound)) continue;
// QUICK MODE (REGTEST ONLY!)
if(Params().NetworkIDString() == CBaseChainParams::REGTEST)
{
if(nRequestedMasternodeAttempt <= 2) {
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETSPORKS)); //get current network sporks
} else if(nRequestedMasternodeAttempt < 4) {
mnodeman.DsegUpdate(pnode, connman);
} else if(nRequestedMasternodeAttempt < 6) {
//sync payment votes
if(pnode->nVersion == 70208) {
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MASTERNODEPAYMENTSYNC, mnpayments.GetStorageLimit())); //sync payment votes
} else {
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MASTERNODEPAYMENTSYNC)); //sync payment votes
}
SendGovernanceSyncRequest(pnode, connman);
} else {
nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
}
nRequestedMasternodeAttempt++;
connman.ReleaseNodeVector(vNodesCopy);
return;
}
// NORMAL NETWORK MODE - TESTNET/MAINNET
{
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "full-sync")) {
// We already fully synced from this node recently,
// disconnect to free this connection slot for another peer.
pnode->fDisconnect = true;
LogPrintf("CMasternodeSync::ProcessTick -- disconnecting from recently synced peer=%d\n", pnode->id);
continue;
}
// SPORK : ALWAYS ASK FOR SPORKS AS WE SYNC
if(!netfulfilledman.HasFulfilledRequest(pnode->addr, "spork-sync")) {
// always get sporks first, only request once from each peer
netfulfilledman.AddFulfilledRequest(pnode->addr, "spork-sync");
// get current network sporks
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETSPORKS));
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- requesting sporks from peer=%d\n", nTick, nRequestedMasternodeAssets, pnode->id);
}
// INITIAL TIMEOUT
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_WAITING) {
if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) {
// At this point we know that:
// a) there are peers (because we are looping on at least one of them);
// b) we waited for at least MASTERNODE_SYNC_TIMEOUT_SECONDS since we reached
// the headers tip the last time (i.e. since we switched from
// MASTERNODE_SYNC_INITIAL to MASTERNODE_SYNC_WAITING and bumped time);
// c) there were no blocks (UpdatedBlockTip, NotifyHeaderTip) or headers (AcceptedBlockHeader)
// for at least MASTERNODE_SYNC_TIMEOUT_SECONDS.
// We must be at the tip already, let's move to the next asset.
SwitchToNextAsset(connman);
}
}
// MNLIST : SYNC MASTERNODE LIST FROM OTHER CONNECTED CLIENTS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {
LogPrint("masternode", "CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d nTimeLastBumped %lld GetTime() %lld diff %lld\n", nTick, nRequestedMasternodeAssets, nTimeLastBumped, GetTime(), GetTime() - nTimeLastBumped);
// check for timeout first
if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) {
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if (nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::ProcessTick -- ERROR: failed to sync %s\n", GetAssetName());
// there is no way we can continue without masternode list, fail here and try later
Fail();
connman.ReleaseNodeVector(vNodesCopy);
return;
}
SwitchToNextAsset(connman);
connman.ReleaseNodeVector(vNodesCopy);
return;
}
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-list-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-list-sync");
if (pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue;
nRequestedMasternodeAttempt++;
mnodeman.DsegUpdate(pnode, connman);
connman.ReleaseNodeVector(vNodesCopy);
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
// MNW : SYNC MASTERNODE PAYMENT VOTES FROM OTHER CONNECTED CLIENTS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {
LogPrint("mnpayments", "CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d nTimeLastBumped %lld GetTime() %lld diff %lld\n", nTick, nRequestedMasternodeAssets, nTimeLastBumped, GetTime(), GetTime() - nTimeLastBumped);
// check for timeout first
// This might take a lot longer than MASTERNODE_SYNC_TIMEOUT_SECONDS due to new blocks,
// but that should be OK and it should timeout eventually.
if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) {
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if (nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::ProcessTick -- ERROR: failed to sync %s\n", GetAssetName());
// probably not a good idea to proceed without winner list
Fail();
connman.ReleaseNodeVector(vNodesCopy);
return;
}
SwitchToNextAsset(connman);
connman.ReleaseNodeVector(vNodesCopy);
return;
}
// check for data
// if mnpayments already has enough blocks and votes, switch to the next asset
// try to fetch data from at least two peers though
if(nRequestedMasternodeAttempt > 1 && mnpayments.IsEnoughData()) {
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- found enough data\n", nTick, nRequestedMasternodeAssets);
SwitchToNextAsset(connman);
connman.ReleaseNodeVector(vNodesCopy);
return;
}
// only request once from each peer
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-payment-sync")) continue;
netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-payment-sync");
if(pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue;
nRequestedMasternodeAttempt++;
// ask node for all payment votes it has (new nodes will only return votes for future payments)
//sync payment votes
if(pnode->nVersion == 70208) {
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MASTERNODEPAYMENTSYNC, mnpayments.GetStorageLimit()));
} else {
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MASTERNODEPAYMENTSYNC));
}
// ask node for missing pieces only (old nodes will not be asked)
mnpayments.RequestLowDataPaymentBlocks(pnode, connman);
connman.ReleaseNodeVector(vNodesCopy);
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
// GOVOBJ : SYNC GOVERNANCE ITEMS FROM OUR PEERS
if(nRequestedMasternodeAssets == MASTERNODE_SYNC_GOVERNANCE) {
LogPrint("gobject", "CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d nTimeLastBumped %lld GetTime() %lld diff %lld\n", nTick, nRequestedMasternodeAssets, nTimeLastBumped, GetTime(), GetTime() - nTimeLastBumped);
// check for timeout first
if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) {
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- timeout\n", nTick, nRequestedMasternodeAssets);
if(nRequestedMasternodeAttempt == 0) {
LogPrintf("CMasternodeSync::ProcessTick -- WARNING: failed to sync %s\n", GetAssetName());
// it's kind of ok to skip this for now, hopefully we'll catch up later?
}
SwitchToNextAsset(connman);
connman.ReleaseNodeVector(vNodesCopy);
return;
}
// only request obj sync once from each peer, then request votes on per-obj basis
if(netfulfilledman.HasFulfilledRequest(pnode->addr, "governance-sync")) {
int nObjsLeftToAsk = governance.RequestGovernanceObjectVotes(pnode, connman);
static int64_t nTimeNoObjectsLeft = 0;
// check for data
if(nObjsLeftToAsk == 0) {
static int nLastTick = 0;
static int nLastVotes = 0;
if(nTimeNoObjectsLeft == 0) {
// asked all objects for votes for the first time
nTimeNoObjectsLeft = GetTime();
}
// make sure the condition below is checked only once per tick
if(nLastTick == nTick) continue;
if(GetTime() - nTimeNoObjectsLeft > MASTERNODE_SYNC_TIMEOUT_SECONDS &&
governance.GetVoteCount() - nLastVotes < std::max(int(0.0001 * nLastVotes), MASTERNODE_SYNC_TICK_SECONDS)
) {
// We already asked for all objects, waited for MASTERNODE_SYNC_TIMEOUT_SECONDS
// after that and less then 0.01% or MASTERNODE_SYNC_TICK_SECONDS
// (i.e. 1 per second) votes were recieved during the last tick.
// We can be pretty sure that we are done syncing.
LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nRequestedMasternodeAssets %d -- asked for all objects, nothing to do\n", nTick, nRequestedMasternodeAssets);
// reset nTimeNoObjectsLeft to be able to use the same condition on resync
nTimeNoObjectsLeft = 0;
SwitchToNextAsset(connman);
connman.ReleaseNodeVector(vNodesCopy);
return;
}
nLastTick = nTick;
nLastVotes = governance.GetVoteCount();
}
continue;
}
netfulfilledman.AddFulfilledRequest(pnode->addr, "governance-sync");
if (pnode->nVersion < MIN_GOVERNANCE_PEER_PROTO_VERSION) continue;
nRequestedMasternodeAttempt++;
SendGovernanceSyncRequest(pnode, connman);
connman.ReleaseNodeVector(vNodesCopy);
return; //this will cause each peer to get one request each six seconds for the various assets we need
}
}
}
// looped through all nodes, release them
connman.ReleaseNodeVector(vNodesCopy);
}
void CMasternodeSync::SendGovernanceSyncRequest(CNode* pnode, CConnman& connman)
{
CNetMsgMaker msgMaker(pnode->GetSendVersion());
if(pnode->nVersion >= GOVERNANCE_FILTER_PROTO_VERSION) {
CBloomFilter filter;
filter.clear();
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MNGOVERNANCESYNC, uint256(), filter));
}
else {
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MNGOVERNANCESYNC, uint256()));
}
}
void CMasternodeSync::AcceptedBlockHeader(const CBlockIndex *pindexNew)
{
LogPrint("mnsync", "CMasternodeSync::AcceptedBlockHeader -- pindexNew->nHeight: %d\n", pindexNew->nHeight);
if (!IsBlockchainSynced()) {
// Postpone timeout each time new block header arrives while we are still syncing blockchain
BumpAssetLastTime("CMasternodeSync::AcceptedBlockHeader");
}
}
void CMasternodeSync::NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman)
{
LogPrint("mnsync", "CMasternodeSync::NotifyHeaderTip -- pindexNew->nHeight: %d fInitialDownload=%d\n", pindexNew->nHeight, fInitialDownload);
if (IsFailed() || IsSynced() || !pindexBestHeader)
return;
if (!IsBlockchainSynced()) {
// Postpone timeout each time new block arrives while we are still syncing blockchain
BumpAssetLastTime("CMasternodeSync::NotifyHeaderTip");
}
}
void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman)
{
LogPrint("mnsync", "CMasternodeSync::UpdatedBlockTip -- pindexNew->nHeight: %d fInitialDownload=%d\n", pindexNew->nHeight, fInitialDownload);
if (IsFailed() || IsSynced() || !pindexBestHeader)
return;
if (!IsBlockchainSynced()) {
// Postpone timeout each time new block arrives while we are still syncing blockchain
BumpAssetLastTime("CMasternodeSync::UpdatedBlockTip");
}
if (fInitialDownload) {
// switched too early
if (IsBlockchainSynced()) {
Reset();
}
// no need to check any further while still in IBD mode
return;
}
// Note: since we sync headers first, it should be ok to use this
static bool fReachedBestHeader = false;
bool fReachedBestHeaderNew = pindexNew->GetBlockHash() == pindexBestHeader->GetBlockHash();
if (fReachedBestHeader && !fReachedBestHeaderNew) {
// Switching from true to false means that we previousely stuck syncing headers for some reason,
// probably initial timeout was not enough,
// because there is no way we can update tip not having best header
Reset();
fReachedBestHeader = false;
return;
}
fReachedBestHeader = fReachedBestHeaderNew;
LogPrint("mnsync", "CMasternodeSync::UpdatedBlockTip -- pindexNew->nHeight: %d pindexBestHeader->nHeight: %d fInitialDownload=%d fReachedBestHeader=%d\n",
pindexNew->nHeight, pindexBestHeader->nHeight, fInitialDownload, fReachedBestHeader);
if (!IsBlockchainSynced() && fReachedBestHeader) {
if (fLiteMode) {
// nothing to do in lite mode, just finish the process immediately
nRequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
return;
}
// Reached best header while being in initial mode.
// We must be at the tip already, let's move to the next asset.
SwitchToNextAsset(connman);
}
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <set>
// class set
// template <class InputIterator>
// void insert(InputIterator first, InputIterator last);
#include <set>
#include <cassert>
#include "test_iterators.h"
#include "min_allocator.h"
int main()
{
{
typedef std::set<int> M;
typedef int V;
V ar[] =
{
1,
1,
1,
2,
2,
2,
3,
3,
3
};
M m;
m.insert(input_iterator<const V*>(ar),
input_iterator<const V*>(ar + sizeof(ar)/sizeof(ar[0])));
assert(m.size() == 3);
assert(*m.begin() == 1);
assert(*next(m.begin()) == 2);
assert(*next(m.begin(), 2) == 3);
}
#if __cplusplus >= 201103L
{
typedef std::set<int, std::less<int>, min_allocator<int>> M;
typedef int V;
V ar[] =
{
1,
1,
1,
2,
2,
2,
3,
3,
3
};
M m;
m.insert(input_iterator<const V*>(ar),
input_iterator<const V*>(ar + sizeof(ar)/sizeof(ar[0])));
assert(m.size() == 3);
assert(*m.begin() == 1);
assert(*next(m.begin()) == 2);
assert(*next(m.begin(), 2) == 3);
}
#endif
}
|
#include <string>
#include "envoy/stats/refcount_ptr.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Stats {
class RefcountedString : public std::string, public RefcountHelper {
public:
explicit RefcountedString(const std::string& s) : std::string(s) {}
};
using SharedString = RefcountPtr<RefcountedString>;
class DerivedRefcountedString : public RefcountedString {};
using DerivedSharedString = RefcountPtr<RefcountedString>;
TEST(RefcountPtr, Constructors) {
SharedString rp1; // Default constructor.
EXPECT_FALSE(rp1);
rp1 = new RefcountedString("Hello"); // Assign from pointer.
EXPECT_EQ(1, rp1.use_count());
SharedString rp2(rp1); // Copy-constructor.
EXPECT_EQ(2, rp1.use_count());
EXPECT_EQ(2, rp2.use_count());
EXPECT_EQ(rp1, rp2);
EXPECT_EQ(*rp1, *rp2);
*rp1 += ", World!"; // Object is shared, so mutations are shared.
EXPECT_EQ(rp1, rp2);
EXPECT_EQ(*rp1, *rp2);
EXPECT_EQ("Hello, World!", *rp2);
SharedString rp3(std::move(rp2)); // Move-constructor.
EXPECT_EQ(2, rp3.use_count());
EXPECT_EQ("Hello, World!", *rp3);
EXPECT_NE(rp2, rp3); // NOLINT -- intentionally testing what happens to a variable post-move.
EXPECT_EQ(nullptr, rp2); // NOLINT -- ditto
EXPECT_NE(rp1, rp2); // NOLINT -- ditto
EXPECT_EQ(rp1, rp3);
EXPECT_FALSE(rp2); // NOLINT -- ditto
EXPECT_TRUE(rp3);
EXPECT_TRUE(rp1);
SharedString rp4(new RefcountedString("Hello, World!")); // Construct from pointer.
EXPECT_EQ(*rp4, *rp3);
EXPECT_NE(rp4, rp3);
DerivedSharedString rp5(rp4); // Construct across hierarchies.
EXPECT_EQ(rp5, rp4);
EXPECT_EQ(*rp5, *rp4);
SharedString rp6;
rp6 = std::move(rp4); // move-assign.
EXPECT_EQ(nullptr, rp4); // NOLINT -- intentionally testing what happens to a variable post-move.
EXPECT_EQ(rp5, rp6);
}
TEST(RefcountPtr, Operators) {
RefcountedString* ptr = new RefcountedString("Hello, World!");
SharedString shared(ptr);
EXPECT_TRUE(shared);
EXPECT_EQ(13, shared->size());
RefcountedString& ref = *shared;
EXPECT_EQ(&ref, ptr);
SharedString shared2(new RefcountedString("Hello, World!"));
EXPECT_NE(&ref, shared2.get());
SharedString shared3(shared2.get());
EXPECT_EQ(shared2, shared3);
EXPECT_EQ(2, shared2.use_count());
shared2.reset();
EXPECT_EQ(nullptr, shared2);
EXPECT_EQ(1, shared3.use_count());
}
} // namespace Stats
} // namespace Envoy
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef itkSpatialObjectToImageFilter_hxx
#define itkSpatialObjectToImageFilter_hxx
#include "itkSpatialObjectToImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkProgressReporter.h"
#include "itkMath.h"
namespace itk
{
/** Constructor */
template <typename TInputSpatialObject, typename TOutputImage>
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SpatialObjectToImageFilter()
{
this->SetNumberOfRequiredInputs(1);
m_ChildrenDepth = TInputSpatialObject::MaximumDepth;
m_Size.Fill(0);
m_Direction.SetIdentity();
for (unsigned int i = 0; i < OutputImageDimension; ++i)
{
m_Spacing[i] = 1.0;
m_Origin[i] = 0.;
}
m_InsideValue = 0;
m_OutsideValue = 0;
m_UseObjectValue = false;
}
/** Set the Input SpatialObject */
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetInput(const InputSpatialObjectType * input)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(0, const_cast<InputSpatialObjectType *>(input));
}
/** Connect one of the operands */
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetInput(unsigned int index,
const TInputSpatialObject * object)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(index, const_cast<TInputSpatialObject *>(object));
}
/** Get the input Spatial Object */
template <typename TInputSpatialObject, typename TOutputImage>
auto
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::GetInput() -> const InputSpatialObjectType *
{
return static_cast<const TInputSpatialObject *>(this->GetPrimaryInput());
}
/** Get the input Spatial Object */
template <typename TInputSpatialObject, typename TOutputImage>
auto
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::GetInput(unsigned int idx)
-> const InputSpatialObjectType *
{
return static_cast<const TInputSpatialObject *>(this->ProcessObject::GetInput(idx));
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetSpacing(const SpacingType & spacing)
{
unsigned int i;
for (i = 0; i < TOutputImage::ImageDimension; ++i)
{
if (Math::NotExactlyEquals((double)spacing[i], m_Spacing[i]))
{
break;
}
}
if (i < TOutputImage::ImageDimension)
{
for (i = 0; i < TOutputImage::ImageDimension; ++i)
{
if (spacing[i] != 0)
{
m_Spacing[i] = spacing[i];
}
}
this->Modified();
}
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetSpacing(const double * spacing)
{
unsigned int i;
for (i = 0; i < OutputImageDimension; ++i)
{
if (Math::NotExactlyEquals(spacing[i], m_Spacing[i]))
{
break;
}
}
if (i < OutputImageDimension)
{
for (i = 0; i < OutputImageDimension; ++i)
{
if (spacing[i] != 0)
{
m_Spacing[i] = spacing[i];
}
}
this->Modified();
}
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetSpacing(const float * spacing)
{
unsigned int i;
for (i = 0; i < OutputImageDimension; ++i)
{
if (Math::NotExactlyEquals((double)spacing[i], m_Spacing[i]))
{
break;
}
}
if (i < OutputImageDimension)
{
for (i = 0; i < OutputImageDimension; ++i)
{
if (spacing[i] != 0)
{
m_Spacing[i] = spacing[i];
}
}
this->Modified();
}
}
template <typename TInputSpatialObject, typename TOutputImage>
const double *
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::GetSpacing() const
{
return m_Spacing;
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetOrigin(const PointType & origin)
{
unsigned int i;
for (i = 0; i < OutputImageDimension; ++i)
{
if (Math::NotExactlyEquals((double)origin[i], m_Origin[i]))
{
break;
}
}
if (i < OutputImageDimension)
{
for (i = 0; i < OutputImageDimension; ++i)
{
m_Origin[i] = origin[i];
}
this->Modified();
}
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetOrigin(const double * origin)
{
unsigned int i;
for (i = 0; i < OutputImageDimension; ++i)
{
if (Math::NotExactlyEquals(origin[i], m_Origin[i]))
{
break;
}
}
if (i < OutputImageDimension)
{
for (i = 0; i < OutputImageDimension; ++i)
{
m_Origin[i] = origin[i];
}
this->Modified();
}
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetOrigin(const float * origin)
{
unsigned int i;
for (i = 0; i < OutputImageDimension; ++i)
{
if (Math::NotExactlyEquals((double)origin[i], m_Origin[i]))
{
break;
}
}
if (i < OutputImageDimension)
{
for (i = 0; i < OutputImageDimension; ++i)
{
m_Origin[i] = origin[i];
}
this->Modified();
}
}
template <typename TInputSpatialObject, typename TOutputImage>
const double *
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::GetOrigin() const
{
return m_Origin;
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::SetDirection(const DirectionType & dir)
{
m_Direction = dir;
this->Modified();
}
template <typename TInputSpatialObject, typename TOutputImage>
auto
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::GetDirection() const -> const DirectionType &
{
return m_Direction;
}
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::GenerateData()
{
unsigned int i;
itkDebugMacro(<< "SpatialObjectToImageFilter::Update() called");
// Get the input and output pointers
const InputSpatialObjectType * InputObject = this->GetInput();
OutputImagePointer OutputImage = this->GetOutput();
// Generate the image
SizeType size;
InputObject->ComputeFamilyBoundingBox(m_ChildrenDepth);
for (i = 0; i < ObjectDimension; ++i)
{
size[i] = static_cast<SizeValueType>(InputObject->GetFamilyBoundingBoxInWorldSpace()->GetMaximum()[i] -
InputObject->GetFamilyBoundingBoxInWorldSpace()->GetMinimum()[i]);
}
typename OutputImageType::IndexType index;
index.Fill(0);
typename OutputImageType::RegionType region;
// If the size of the output has been explicitly specified, the filter
// will set the output size to the explicit size, otherwise the size from the
// spatial
// object's bounding box will be used as default.
bool specified = false;
for (i = 0; i < OutputImageDimension; ++i)
{
if (m_Size[i] != 0)
{
specified = true;
break;
}
}
if (specified)
{
region.SetSize(m_Size);
}
else
{
region.SetSize(size);
}
region.SetIndex(index);
OutputImage->SetLargestPossibleRegion(region); //
OutputImage->SetBufferedRegion(region); // set the region
OutputImage->SetRequestedRegion(region); //
OutputImage->SetSpacing(m_Spacing); // set spacing
OutputImage->SetOrigin(m_Origin); // and origin
OutputImage->SetDirection(m_Direction);
OutputImage->Allocate(); // allocate the image
using myIteratorType = itk::ImageRegionIteratorWithIndex<OutputImageType>;
myIteratorType it(OutputImage, region);
itk::Point<double, ObjectDimension> objectPoint;
itk::Point<double, OutputImageDimension> imagePoint;
ProgressReporter progress(this, 0, OutputImage->GetRequestedRegion().GetNumberOfPixels());
while (!it.IsAtEnd())
{
// ValueAtInWorldSpace requires the point to be in physical coordinate i.e
OutputImage->TransformIndexToPhysicalPoint(it.GetIndex(), imagePoint);
for (i = 0; i < ObjectDimension; ++i)
{
objectPoint[i] = imagePoint[i];
}
double val = 0;
bool evaluable = InputObject->ValueAtInWorldSpace(objectPoint, val, m_ChildrenDepth);
if (Math::NotExactlyEquals(m_InsideValue, NumericTraits<ValueType>::ZeroValue()) ||
Math::NotExactlyEquals(m_OutsideValue, NumericTraits<ValueType>::ZeroValue()))
{
if (evaluable)
{
if (m_UseObjectValue)
{
it.Set(static_cast<ValueType>(val));
}
else
{
it.Set(m_InsideValue);
}
}
else
{
it.Set(m_OutsideValue);
}
}
else
{
it.Set(static_cast<ValueType>(val));
}
++it;
progress.CompletedPixel();
}
itkDebugMacro(<< "SpatialObjectToImageFilter::Update() finished");
} // end update function
template <typename TInputSpatialObject, typename TOutputImage>
void
SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Size : " << m_Size << std::endl;
os << indent << "Children depth : " << m_ChildrenDepth << std::endl;
os << indent << "Inside Value : " << m_InsideValue << std::endl;
os << indent << "Outside Value : " << m_OutsideValue << std::endl;
if (m_UseObjectValue)
{
os << indent << "Using Object Value : ON" << std::endl;
}
else
{
os << indent << "Using Object Value : OFF" << std::endl;
}
}
} // end namespace itk
#endif
|
// Copyright 1994, 1996, 2005, 2008 by Jon Dart
#include "bitboard.h"
static int done_init = 0;
const CACHE_ALIGN uint64 Bitboard::mask[64] =
{
1,
((uint64)1) << 1,
((uint64)1) << 2,
((uint64)1) << 3,
((uint64)1) << 4,
((uint64)1) << 5,
((uint64)1) << 6,
((uint64)1) << 7,
((uint64)1) << 8,
((uint64)1) << 9,
((uint64)1) << 10,
((uint64)1) << 11,
((uint64)1) << 12,
((uint64)1) << 13,
((uint64)1) << 14,
((uint64)1) << 15,
((uint64)1) << 16,
((uint64)1) << 17,
((uint64)1) << 18,
((uint64)1) << 19,
((uint64)1) << 20,
((uint64)1) << 21,
((uint64)1) << 22,
((uint64)1) << 23,
((uint64)1) << 24,
((uint64)1) << 25,
((uint64)1) << 26,
((uint64)1) << 27,
((uint64)1) << 28,
((uint64)1) << 29,
((uint64)1) << 30,
((uint64)1) << 31,
((uint64)1) << 32,
((uint64)1) << 33,
((uint64)1) << 34,
((uint64)1) << 35,
((uint64)1) << 36,
((uint64)1) << 37,
((uint64)1) << 38,
((uint64)1) << 39,
((uint64)1) << 40,
((uint64)1) << 41,
((uint64)1) << 42,
((uint64)1) << 43,
((uint64)1) << 44,
((uint64)1) << 45,
((uint64)1) << 46,
((uint64)1) << 47,
((uint64)1) << 48,
((uint64)1) << 49,
((uint64)1) << 50,
((uint64)1) << 51,
((uint64)1) << 52,
((uint64)1) << 53,
((uint64)1) << 54,
((uint64)1) << 55,
((uint64)1) << 56,
((uint64)1) << 57,
((uint64)1) << 58,
((uint64)1) << 59,
((uint64)1) << 60,
((uint64)1) << 61,
((uint64)1) << 62,
((uint64)1) << 63
};
int Bitboard::MagicTable32[32];
#if defined(_64BIT)
int Bitboard::MagicTable64[64];
#endif
int Bitboard::msbTable[256];
void Bitboard::init()
{
int i;
#if defined(_64BIT)
for (i=0;i<64;i++) {
int64 bits = (int64)(((uint64)1)<<i);
int index = (int)((GETBIT64(bits)*MAGIC64)>>58);
MagicTable64[index] = i;
}
#else
for (i=0;i<32;i++) {
unsigned bits = (((unsigned)1)<<i);
int index = (int)((GETBIT32(bits)*MAGIC32)>>27);
MagicTable32[index] = i;
}
#endif
for (int i = 0; i < 256; i++) {
int mask = 128;
int msb = 7;
msbTable[i] = 0;
while (mask > 0) {
if (i & mask) {
msbTable[i] = msb;
break;
}
mask >>=1; msb--;
}
}
done_init++;
}
void Bitboard::cleanup()
{
}
ostream & operator << (ostream &o, const Bitboard &b)
{
o << (hex) << b.data << (dec);
return o;
}
|
//
// AKPWMOscillatorDSP.hpp
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
#pragma once
#import <AVFoundation/AVFoundation.h>
typedef NS_ENUM(AUParameterAddress, AKPWMOscillatorParameter) {
AKPWMOscillatorParameterFrequency,
AKPWMOscillatorParameterAmplitude,
AKPWMOscillatorParameterPulseWidth,
AKPWMOscillatorParameterDetuningOffset,
AKPWMOscillatorParameterDetuningMultiplier,
AKPWMOscillatorParameterRampDuration
};
#import "AKLinearParameterRamp.hpp" // have to put this here to get it included in umbrella header
#ifndef __cplusplus
void *createPWMOscillatorDSP(int nChannels, double sampleRate);
#else
#import "AKSoundpipeDSPBase.hpp"
class AKPWMOscillatorDSP : public AKSoundpipeDSPBase {
sp_blsquare *_blsquare;
private:
AKLinearParameterRamp frequencyRamp;
AKLinearParameterRamp amplitudeRamp;
AKLinearParameterRamp pulseWidthRamp;
AKLinearParameterRamp detuningOffsetRamp;
AKLinearParameterRamp detuningMultiplierRamp;
public:
AKPWMOscillatorDSP() {
frequencyRamp.setTarget(440, true);
frequencyRamp.setDurationInSamples(10000);
amplitudeRamp.setTarget(1, true);
amplitudeRamp.setDurationInSamples(10000);
pulseWidthRamp.setTarget(0, true);
pulseWidthRamp.setDurationInSamples(10000);
detuningOffsetRamp.setTarget(0, true);
detuningOffsetRamp.setDurationInSamples(10000);
detuningMultiplierRamp.setTarget(1, true);
detuningMultiplierRamp.setDurationInSamples(10000);
}
/** Uses the ParameterAddress as a key */
void setParameter(AUParameterAddress address, float value, bool immediate) override {
switch (address) {
case AKPWMOscillatorParameterFrequency:
frequencyRamp.setTarget(value, immediate);
break;
case AKPWMOscillatorParameterAmplitude:
amplitudeRamp.setTarget(value, immediate);
break;
case AKPWMOscillatorParameterPulseWidth:
pulseWidthRamp.setTarget(value, immediate);
break;
case AKPWMOscillatorParameterDetuningOffset:
detuningOffsetRamp.setTarget(value, immediate);
break;
case AKPWMOscillatorParameterDetuningMultiplier:
detuningMultiplierRamp.setTarget(value, immediate);
break;
case AKPWMOscillatorParameterRampDuration:
frequencyRamp.setRampDuration(value, _sampleRate);
amplitudeRamp.setRampDuration(value, _sampleRate);
pulseWidthRamp.setRampDuration(value, _sampleRate);
detuningOffsetRamp.setRampDuration(value, _sampleRate);
detuningMultiplierRamp.setRampDuration(value, _sampleRate);
break;
}
}
/** Uses the ParameterAddress as a key */
float getParameter(AUParameterAddress address) override {
switch (address) {
case AKPWMOscillatorParameterFrequency:
return frequencyRamp.getTarget();
case AKPWMOscillatorParameterAmplitude:
return amplitudeRamp.getTarget();
case AKPWMOscillatorParameterPulseWidth:
return pulseWidthRamp.getTarget();
case AKPWMOscillatorParameterDetuningOffset:
return detuningOffsetRamp.getTarget();
case AKPWMOscillatorParameterDetuningMultiplier:
return detuningMultiplierRamp.getTarget();
case AKPWMOscillatorParameterRampDuration:
return frequencyRamp.getRampDuration(_sampleRate);
}
return 0;
}
void init(int _channels, double _sampleRate) override {
AKSoundpipeDSPBase::init(_channels, _sampleRate);
_playing = false;
sp_blsquare_create(&_blsquare);
sp_blsquare_init(_sp, _blsquare);
*_blsquare->freq = 440;
*_blsquare->amp = 1.0;
*_blsquare->width = 0.5;
}
void deinit() override {
sp_blsquare_destroy(&_blsquare);
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int frameOffset = int(frameIndex + bufferOffset);
// do ramping every 8 samples
if ((frameOffset & 0x7) == 0) {
frequencyRamp.advanceTo(_now + frameOffset);
amplitudeRamp.advanceTo(_now + frameOffset);
pulseWidthRamp.advanceTo(_now + frameOffset);
detuningOffsetRamp.advanceTo(_now + frameOffset);
detuningMultiplierRamp.advanceTo(_now + frameOffset);
}
float frequency = frequencyRamp.getValue();
float amplitude = amplitudeRamp.getValue();
float pulseWidth = pulseWidthRamp.getValue();
float detuningOffset = detuningOffsetRamp.getValue();
float detuningMultiplier = detuningMultiplierRamp.getValue();
*_blsquare->freq = frequency * detuningMultiplier + detuningOffset;
*_blsquare->amp = amplitude;
*_blsquare->width = pulseWidth;
float temp = 0;
for (int channel = 0; channel < _nChannels; ++channel) {
float *out = (float *)_outBufferListPtr->mBuffers[channel].mData + frameOffset;
if (_playing) {
if (channel == 0) {
sp_blsquare_compute(_sp, _blsquare, nil, &temp);
}
*out = temp;
} else {
*out = 0.0;
}
}
}
}
};
#endif
|
/****************************************************************************
*
* Copyright (c) 2013-2014 PX4 Development Team. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file Takeoff.cpp
*
* Helper class to Takeoff
*
* @author Lorenz Meier <lorenz@px4.io
*/
#include "takeoff.h"
#include "navigator.h"
Takeoff::Takeoff(Navigator *navigator) :
MissionBlock(navigator)
{
}
void
Takeoff::on_activation()
{
set_takeoff_position();
}
void
Takeoff::on_active()
{
struct position_setpoint_triplet_s *rep = _navigator->get_takeoff_triplet();
if (rep->current.valid) {
// reset the position
set_takeoff_position();
} else if (is_mission_item_reached() && !_navigator->get_mission_result()->finished) {
_navigator->get_mission_result()->finished = true;
_navigator->set_mission_result_updated();
// set loiter item so position controllers stop doing takeoff logic
set_loiter_item(&_mission_item);
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
mission_apply_limitation(_mission_item);
mission_item_to_position_setpoint(_mission_item, &pos_sp_triplet->current);
_navigator->set_position_setpoint_triplet_updated();
}
}
void
Takeoff::set_takeoff_position()
{
struct position_setpoint_triplet_s *rep = _navigator->get_takeoff_triplet();
float abs_altitude = 0.0f;
float min_abs_altitude;
if (_navigator->home_position_valid()) { //only use home position if it is valid
min_abs_altitude = _navigator->get_global_position()->alt + _navigator->get_takeoff_min_alt();
} else { //e.g. flow
min_abs_altitude = _navigator->get_takeoff_min_alt();
}
// Use altitude if it has been set. If home position is invalid use min_abs_altitude
if (rep->current.valid && PX4_ISFINITE(rep->current.alt) && _navigator->home_position_valid()) {
abs_altitude = rep->current.alt;
// If the altitude suggestion is lower than home + minimum clearance, raise it and complain.
if (abs_altitude < min_abs_altitude) {
if (abs_altitude < min_abs_altitude - 0.1f) { // don't complain if difference is smaller than 10cm
mavlink_log_critical(_navigator->get_mavlink_log_pub(),
"Using minimum takeoff altitude: %.2f m", (double)_navigator->get_takeoff_min_alt());
}
abs_altitude = min_abs_altitude;
}
} else {
// Use home + minimum clearance but only notify.
abs_altitude = min_abs_altitude;
mavlink_log_info(_navigator->get_mavlink_log_pub(),
"Using minimum takeoff altitude: %.2f m", (double)_navigator->get_takeoff_min_alt());
}
if (abs_altitude < _navigator->get_global_position()->alt) {
// If the suggestion is lower than our current alt, let's not go down.
abs_altitude = _navigator->get_global_position()->alt;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "Already higher than takeoff altitude");
}
// set current mission item to takeoff
set_takeoff_item(&_mission_item, abs_altitude);
_navigator->get_mission_result()->finished = false;
_navigator->set_mission_result_updated();
reset_mission_item_reached();
// convert mission item to current setpoint
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
mission_apply_limitation(_mission_item);
mission_item_to_position_setpoint(_mission_item, &pos_sp_triplet->current);
pos_sp_triplet->previous.valid = false;
pos_sp_triplet->current.yaw_valid = true;
pos_sp_triplet->next.valid = false;
if (rep->current.valid) {
// Go on and check which changes had been requested
if (PX4_ISFINITE(rep->current.yaw)) {
pos_sp_triplet->current.yaw = rep->current.yaw;
}
if (PX4_ISFINITE(rep->current.lat) && PX4_ISFINITE(rep->current.lon)) {
pos_sp_triplet->current.lat = rep->current.lat;
pos_sp_triplet->current.lon = rep->current.lon;
}
// mark this as done
memset(rep, 0, sizeof(*rep));
}
_navigator->set_can_loiter_at_sp(true);
_navigator->set_position_setpoint_triplet_updated();
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:0e21e9d7740f5f6cc50f76e2811a719679a628a783b4a129454e6c2d9021331a
size 6628
|
#pragma once
#include "lue/framework/partitioned_array.hpp"
namespace lue {
/*!
@brief Fill a partitioned array in-place with @a fill_value
@tparam Element Type of elements in the arrays
@tparam rank Rank of the input arrays
@tparam Array Class template of the type of the arrays
@param array Partitioned array
@param fill_value Value to assign to each cell in @a array
@return Future that becomes ready once the algorithm has finished
The existing @a array passed in is updated. Use the returned future if
you need to know when the filling is done.
*/
template<
typename Element,
Rank rank>
[[nodiscard]] hpx::future<void> fill(
PartitionedArray<Element, rank>& array,
hpx::shared_future<Element> const& fill_value)
{
std::vector<hpx::future<void>> fill_partitions(nr_partitions(array));
typename server::ArrayPartition<Element, rank>::FillAction action;
for(Index p = 0; p < nr_partitions(array); ++p)
{
fill_partitions[p] = hpx::dataflow(
hpx::launch::async,
hpx::unwrapping(action),
array.partitions()[p],
fill_value);
}
return hpx::when_all(std::move(fill_partitions));
}
template<
typename Element,
Rank rank>
[[nodiscard]] hpx::future<void> fill(
PartitionedArray<Element, rank>& array,
Element const& fill_value)
{
return fill(array, hpx::make_ready_future<Element>(fill_value).share());
}
} // namespace lue
|
/*
* Copyright © 2017 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#include "hb.hh"
#ifndef HB_NO_VAR
#include "hb-ot-var.h"
#include "hb-ot-var-avar-table.hh"
#include "hb-ot-var-fvar-table.hh"
#include "hb-ot-var-mvar-table.hh"
/**
* SECTION:hb-ot-var
* @title: hb-ot-var
* @short_description: OpenType Font Variations
* @include: hb-ot.h
*
* Functions for fetching information about OpenType Variable Fonts.
**/
/*
* fvar/avar
*/
/**
* hb_ot_var_has_data:
* @face: The #hb_face_t to work on
*
* Tests whether a face includes any OpenType variation data in the `fvar` table.
*
* Return value: %true if data found, %false otherwise
*
* Since: 1.4.2
**/
hb_bool_t
hb_ot_var_has_data (hb_face_t* face) {
return face->table.fvar->has_data ();
}
/**
* hb_ot_var_get_axis_count:
* @face: The #hb_face_t to work on
*
* Fetches the number of OpenType variation axes included in the face.
*
* Return value: the number of variation axes defined
*
* Since: 1.4.2
**/
unsigned int
hb_ot_var_get_axis_count (hb_face_t* face) {
return face->table.fvar->get_axis_count ();
}
#ifndef HB_DISABLE_DEPRECATED
/**
* hb_ot_var_get_axes:
* @face: #hb_face_t to work upon
* @start_offset: offset of the first lookup to retrieve
* @axes_count: (inout) (optional): Input = the maximum number of variation axes to return;
* Output = the actual number of variation axes returned (may be zero)
* @axes_array: (out caller-allocates) (array length=axes_count): The array of variation axes found
*
* Fetches a list of all variation axes in the specified face. The list returned will begin
* at the offset provided.
*
* Since: 1.4.2
* Deprecated: 2.2.0: use hb_ot_var_get_axis_infos() instead
**/
unsigned int
hb_ot_var_get_axes (hb_face_t* face,
unsigned int start_offset,
unsigned int* axes_count /* IN/OUT */,
hb_ot_var_axis_t* axes_array /* OUT */) {
return face->table.fvar->get_axes_deprecated (start_offset, axes_count, axes_array);
}
/**
* hb_ot_var_find_axis:
* @face: #hb_face_t to work upon
* @axis_tag: The #hb_tag_t of the variation axis to query
* @axis_index: The index of the variation axis
* @axis_info: (out): The #hb_ot_var_axis_info_t of the axis tag queried
*
* Fetches the variation-axis information corresponding to the specified axis tag
* in the specified face.
*
* Since: 1.4.2
* Deprecated: 2.2.0 - use hb_ot_var_find_axis_info() instead
**/
hb_bool_t
hb_ot_var_find_axis (hb_face_t* face,
hb_tag_t axis_tag,
unsigned int* axis_index,
hb_ot_var_axis_t* axis_info) {
return face->table.fvar->find_axis_deprecated (axis_tag, axis_index, axis_info);
}
#endif
/**
* hb_ot_var_get_axis_infos:
* @face: #hb_face_t to work upon
* @start_offset: offset of the first lookup to retrieve
* @axes_count: (inout) (optional): Input = the maximum number of variation axes to return;
* Output = the actual number of variation axes returned (may be zero)
* @axes_array: (out caller-allocates) (array length=axes_count): The array of variation axes found
*
* Fetches a list of all variation axes in the specified face. The list returned will begin
* at the offset provided.
*
* Return value: the number of variation axes in the face
*
* Since: 2.2.0
**/
HB_EXTERN unsigned int
hb_ot_var_get_axis_infos (hb_face_t* face,
unsigned int start_offset,
unsigned int* axes_count /* IN/OUT */,
hb_ot_var_axis_info_t* axes_array /* OUT */) {
return face->table.fvar->get_axis_infos (start_offset, axes_count, axes_array);
}
/**
* hb_ot_var_find_axis_info:
* @face: #hb_face_t to work upon
* @axis_tag: The #hb_tag_t of the variation axis to query
* @axis_info: (out): The #hb_ot_var_axis_info_t of the axis tag queried
*
* Fetches the variation-axis information corresponding to the specified axis tag
* in the specified face.
*
* Return value: %true if data found, %false otherwise
*
* Since: 2.2.0
**/
HB_EXTERN hb_bool_t
hb_ot_var_find_axis_info (hb_face_t* face,
hb_tag_t axis_tag,
hb_ot_var_axis_info_t* axis_info) {
return face->table.fvar->find_axis_info (axis_tag, axis_info);
}
/*
* Named instances.
*/
/**
* hb_ot_var_get_named_instance_count:
* @face: The #hb_face_t to work on
*
* Fetches the number of named instances included in the face.
*
* Return value: the number of named instances defined
*
* Since: 2.2.0
**/
unsigned int
hb_ot_var_get_named_instance_count (hb_face_t* face) {
return face->table.fvar->get_instance_count ();
}
/**
* hb_ot_var_named_instance_get_subfamily_name_id:
* @face: The #hb_face_t to work on
* @instance_index: The index of the named instance to query
*
* Fetches the `name` table Name ID that provides display names for
* the "Subfamily name" defined for the given named instance in the face.
*
* Return value: the Name ID found for the Subfamily name
*
* Since: 2.2.0
**/
hb_ot_name_id_t
hb_ot_var_named_instance_get_subfamily_name_id (hb_face_t* face,
unsigned int instance_index) {
return face->table.fvar->get_instance_subfamily_name_id (instance_index);
}
/**
* hb_ot_var_named_instance_get_postscript_name_id:
* @face: The #hb_face_t to work on
* @instance_index: The index of the named instance to query
*
* Fetches the `name` table Name ID that provides display names for
* the "PostScript name" defined for the given named instance in the face.
*
* Return value: the Name ID found for the PostScript name
*
* Since: 2.2.0
**/
hb_ot_name_id_t
hb_ot_var_named_instance_get_postscript_name_id (hb_face_t* face,
unsigned int instance_index) {
return face->table.fvar->get_instance_postscript_name_id (instance_index);
}
/**
* hb_ot_var_named_instance_get_design_coords:
* @face: The #hb_face_t to work on
* @instance_index: The index of the named instance to query
* @coords_length: (inout) (optional): Input = the maximum number of coordinates to return;
* Output = the actual number of coordinates returned (may be zero)
* @coords: (out) (array length=coords_length): The array of coordinates found for the query
*
* Fetches the design-space coordinates corresponding to the given
* named instance in the face.
*
* Return value: the number of variation axes in the face
*
* Since: 2.2.0
**/
unsigned int
hb_ot_var_named_instance_get_design_coords (hb_face_t* face,
unsigned int instance_index,
unsigned int* coords_length, /* IN/OUT */
float* coords /* OUT */) {
return face->table.fvar->get_instance_coords (instance_index, coords_length, coords);
}
/**
* hb_ot_var_normalize_variations:
* @face: The #hb_face_t to work on
* @variations: The array of variations to normalize
* @variations_length: The number of variations to normalize
* @coords: (out) (array length=coords_length): The array of normalized coordinates
* @coords_length: The length of the coordinate array
*
* Normalizes all of the coordinates in the given list of variation axes.
*
* Since: 1.4.2
**/
void
hb_ot_var_normalize_variations (hb_face_t* face,
const hb_variation_t* variations, /* IN */
unsigned int variations_length,
int* coords, /* OUT */
unsigned int coords_length) {
for (unsigned int i = 0; i < coords_length; i++)
coords[i] = 0;
const OT::fvar& fvar = *face->table.fvar;
for (unsigned int i = 0; i < variations_length; i++) {
hb_ot_var_axis_info_t info;
if (hb_ot_var_find_axis_info (face, variations[i].tag, &info) &&
info.axis_index < coords_length)
coords[info.axis_index] = fvar.normalize_axis_value (info.axis_index, variations[i].value);
}
face->table.avar->map_coords (coords, coords_length);
}
/**
* hb_ot_var_normalize_coords:
* @face: The #hb_face_t to work on
* @coords_length: The length of the coordinate array
* @design_coords: The design-space coordinates to normalize
* @normalized_coords: (out): The normalized coordinates
*
* Normalizes the given design-space coordinates. The minimum and maximum
* values for the axis are mapped to the interval [-1,1], with the default
* axis value mapped to 0.
*
* Any additional scaling defined in the face's `avar` table is also
* applied, as described at https://docs.microsoft.com/en-us/typography/opentype/spec/avar
*
* Since: 1.4.2
**/
void
hb_ot_var_normalize_coords (hb_face_t* face,
unsigned int coords_length,
const float* design_coords, /* IN */
int* normalized_coords /* OUT */) {
const OT::fvar& fvar = *face->table.fvar;
for (unsigned int i = 0; i < coords_length; i++)
normalized_coords[i] = fvar.normalize_axis_value (i, design_coords[i]);
face->table.avar->map_coords (normalized_coords, coords_length);
}
#endif
|
#include <nan.h>
using namespace v8;
NAN_METHOD(Print) {
}
void Init(Handle<Object> exports) {
exports->Set(NanNew("print"), NanNew<FunctionTemplate>(Print)->GetFunction());
}
|
#pragma once
#include <basiclib/types.h>
namespace basic {
/**
* Converts a base32 symbol into its binary representation, used by string_to_name()
*
* @ingroup types
*/
static constexpr char char_to_symbol( char c ) {
if( c >= 'a' && c <= 'z' )
return (c - 'a') + 1;
if( c >= '1' && c <= '5' )
return (c - '1') + 27;
return 0;
}
/**
* Converts a base32 string to a uint64_t. This is a constexpr so that
* this method can be used in template arguments as well.
*
* @ingroup types
*/
static constexpr uint64_t string_to_name( const char* str ) {
uint32_t len = 0;
while( str[len] ) ++len;
uint64_t value = 0;
for( uint32_t i = 0; i <= 12; ++i ) {
uint64_t c = 0;
if( i < len && i <= 12 ) c = char_to_symbol( str[i] );
if( i < 12 ) {
c &= 0x1f;
c <<= 64-5*(i+1);
}
else {
c &= 0x0f;
}
value |= c;
}
return value;
}
/**
* @brief used to generate a compile time uint64_t from the base32 encoded string interpretation of X
* @ingroup types
*/
#define N(X) ::basic::string_to_name(#X)
/**
* @class Name
* @brief wraps a uint64_t to ensure it is only passed to methods that expect a Name
* @details wraps a uint64_t to ensure it is only passed to methods that expect a Name and
* that no mathematical operations occur. It also enables specialization of print
* so that it is printed as a base32 string.
*
* @ingroup types
* @{
*/
struct Name {
Name( uint64_t v = 0 ): value(v) {}
operator uint64_t()const { return value; }
friend bool operator==( const Name& a, const Name& b ) { return a.value == b.value; }
AccountName value = 0;
};
/// @}
/**
* @ingroup types
*
* @{
*/
template<typename T> struct remove_reference { typedef T type; };
template<typename T> struct remove_reference<T&> { typedef T type; };
template<typename T> struct remove_reference<const T&> { typedef T type; };
///@}
} // namespace basic
|
//
// Copyright 2018 Google LLC
//
// 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.
//
#include "zetasql/base/mathlimits.h"
#include <stdio.h>
#include "gtest/gtest.h"
#include <cstdint>
#include "zetasql/base/logging.h"
#include "zetasql/base/mathutil.h"
namespace zetasql_base {
template<typename Type>
static void TestMathLimits() {
const Type kOne = 1;
const Type kMin = MathLimits<Type>::kMin;
const Type kMax = MathLimits<Type>::kMax;
const Type kPosMin = MathLimits<Type>::kPosMin;
const Type kMax10Exp = MathLimits<Type>::kMax10Exp;
const Type kMin10Exp = MathLimits<Type>::kMin10Exp;
const Type kEpsilon = MathLimits<Type>::kEpsilon;
ZETASQL_LOG(INFO) << "Size = " << sizeof(Type);
ZETASQL_LOG(INFO) << "kMin = " << kMin;
ZETASQL_LOG(INFO) << "kMax = " << kMax;
ZETASQL_LOG(INFO) << "kPosMin = " << kPosMin;
ZETASQL_LOG(INFO) << "kMax10Exp = " << kMax10Exp;
ZETASQL_LOG(INFO) << "kMin10Exp = " << kMin10Exp;
ZETASQL_LOG(INFO) << "kEpsilon = " << kEpsilon;
ZETASQL_LOG(INFO) << "kStdError = " << MathLimits<Type>::kStdError;
// Some basic checks:
ZETASQL_CHECK_EQ(sizeof(typename MathLimits<Type>::UnsignedType), sizeof(Type));
ZETASQL_CHECK_EQ(kMax, MathLimits<Type>::kPosMax);
ZETASQL_CHECK_GT(Type(1 + kEpsilon), Type(1));
if (MathLimits<Type>::kIsSigned) {
ZETASQL_CHECK_LT(kMin, 0);
ZETASQL_CHECK_LE(-(kMin + kMax), kEpsilon);
} else {
ZETASQL_CHECK_EQ(kMin, 0);
}
// Check kMax10Exp's claim:
Type pow = kOne;
for (int i = 0; i < kMax10Exp; ++i) {
pow *= 10;
}
ZETASQL_LOG(INFO) << "1 * 10^kMaxExp = " << pow;
ZETASQL_LOG(INFO) << "kMax - 1 * 10^kMaxExp = " << kMax - pow;
ZETASQL_CHECK_GT(pow, kOne);
ZETASQL_CHECK_LE(pow, kMax);
ZETASQL_CHECK_GE(pow, kPosMin);
for (int i = 0; i < kMax10Exp; ++i) {
pow /= 10;
}
ZETASQL_LOG(INFO) << "1 * 10^kMaxExp / 10^kMaxExp - 1 = " << pow - kOne;
ZETASQL_CHECK(MathUtil::WithinMargin(pow, kOne, MathLimits<Type>::kStdError));
// Check kMin10Exp's claim:
pow = kOne;
for (int i = 0; i < -kMin10Exp; ++i) {
pow /= 10;
}
ZETASQL_LOG(INFO) << "1 * 10^kMinExp = " << pow;
ZETASQL_LOG(INFO) << "1 * 10^kMaxExp - kPosMin = " << pow - kPosMin;
if (MathLimits<Type>::kIsInteger) {
ZETASQL_CHECK_EQ(pow, kOne);
} else {
ZETASQL_CHECK_LT(pow, kOne);
}
ZETASQL_CHECK_LE(pow, kMax);
ZETASQL_CHECK_GE(pow, kPosMin);
for (int i = 0; i < -kMin10Exp; ++i) {
pow *= 10;
}
ZETASQL_LOG(INFO) << "1 * 10^kMinExp / 10^kMinExp - 1 = " << pow - kOne;
ZETASQL_CHECK(MathUtil::WithinMargin(pow, kOne, MathLimits<Type>::kStdError));
}
TEST(MathLimits, IntMathLimits) {
// The standard part:
TestMathLimits<uint8_t>();
TestMathLimits<uint16_t>();
TestMathLimits<uint32_t>();
TestMathLimits<uint64_t>();
TestMathLimits<int8_t>();
TestMathLimits<int16_t>();
TestMathLimits<int32_t>();
TestMathLimits<int64_t>();
// Guaranteed size relations:
ZETASQL_CHECK_LE(MathLimits<uint8_t>::kMax, MathLimits<uint16_t>::kMax);
ZETASQL_CHECK_LE(MathLimits<uint16_t>::kMax, MathLimits<uint32_t>::kMax);
ZETASQL_CHECK_LE(MathLimits<uint32_t>::kMax, MathLimits<uint64_t>::kMax);
ZETASQL_CHECK_LE(MathLimits<int8_t>::kMax, MathLimits<int16_t>::kMax);
ZETASQL_CHECK_LE(MathLimits<int16_t>::kMax, MathLimits<int32_t>::kMax);
ZETASQL_CHECK_LE(MathLimits<int32_t>::kMax, MathLimits<int64_t>::kMax);
}
template<typename Type, typename TypeTwo, typename TypeThree>
static void TestFPMathLimits() {
// The standard part:
TestMathLimits<Type>();
const Type kNaN = MathLimits<Type>::kNaN;
const Type kPosInf = MathLimits<Type>::kPosInf;
const Type kNegInf = MathLimits<Type>::kNegInf;
ZETASQL_LOG(INFO) << "Size = " << sizeof(Type);
ZETASQL_LOG(INFO) << "kNaN = " << kNaN;
ZETASQL_LOG(INFO) << "kPosInf = " << kPosInf;
ZETASQL_LOG(INFO) << "kNegInf = " << kNegInf;
// Special value compatibility:
ZETASQL_CHECK(MathLimits<TypeTwo>::IsNaN(kNaN));
ZETASQL_CHECK(MathLimits<TypeTwo>::IsPosInf(kPosInf));
ZETASQL_CHECK(MathLimits<TypeTwo>::IsNegInf(kNegInf));
ZETASQL_CHECK(MathLimits<TypeThree>::IsNaN(kNaN));
ZETASQL_CHECK(MathLimits<TypeThree>::IsPosInf(kPosInf));
ZETASQL_CHECK(MathLimits<TypeThree>::IsNegInf(kNegInf));
// Special values and operations over them:
ZETASQL_CHECK(MathLimits<Type>::IsFinite(0));
ZETASQL_CHECK(MathLimits<Type>::IsFinite(1.1));
ZETASQL_CHECK(MathLimits<Type>::IsFinite(-1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsFinite(kNaN));
ZETASQL_CHECK(!MathLimits<Type>::IsFinite(kPosInf));
ZETASQL_CHECK(!MathLimits<Type>::IsFinite(kNegInf));
ZETASQL_CHECK(!MathLimits<Type>::IsNaN(0));
ZETASQL_CHECK(!MathLimits<Type>::IsNaN(1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsNaN(-1.1));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN));
ZETASQL_CHECK(!MathLimits<Type>::IsNaN(kPosInf));
ZETASQL_CHECK(!MathLimits<Type>::IsNaN(kNegInf));
ZETASQL_CHECK(!MathLimits<Type>::IsInf(0));
ZETASQL_CHECK(!MathLimits<Type>::IsInf(1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsInf(-1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsInf(kNaN));
ZETASQL_CHECK(MathLimits<Type>::IsInf(kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsInf(kNegInf));
ZETASQL_CHECK(!MathLimits<Type>::IsPosInf(0));
ZETASQL_CHECK(!MathLimits<Type>::IsPosInf(1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsPosInf(-1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsPosInf(kNaN));
ZETASQL_CHECK(MathLimits<Type>::IsPosInf(kPosInf));
ZETASQL_CHECK(!MathLimits<Type>::IsPosInf(kNegInf));
ZETASQL_CHECK(!MathLimits<Type>::IsNegInf(0));
ZETASQL_CHECK(!MathLimits<Type>::IsNegInf(1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsNegInf(-1.1));
ZETASQL_CHECK(!MathLimits<Type>::IsNegInf(kNaN));
ZETASQL_CHECK(!MathLimits<Type>::IsNegInf(kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsNegInf(kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN + 1));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN + 1e30));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN + kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN + kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN * 1));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN * 1e30));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN * kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN * kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN / 1));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN / 1e30));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN / kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNaN / kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kPosInf + kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kPosInf - kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNegInf - kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kPosInf / kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kPosInf / kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNaN(kNegInf / kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsPosInf(kPosInf + 1));
ZETASQL_CHECK(MathLimits<Type>::IsPosInf(kPosInf - 1e30));
ZETASQL_CHECK(MathLimits<Type>::IsPosInf(kPosInf + kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsPosInf(kPosInf * kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsPosInf(kPosInf - kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsPosInf(kNegInf * kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNegInf(kNegInf - 1));
ZETASQL_CHECK(MathLimits<Type>::IsNegInf(kNegInf + 1e30));
ZETASQL_CHECK(MathLimits<Type>::IsNegInf(kNegInf + kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNegInf(kNegInf - kPosInf));
ZETASQL_CHECK(MathLimits<Type>::IsNegInf(kPosInf * kNegInf));
ZETASQL_CHECK(MathLimits<Type>::IsNegInf(kNegInf * kPosInf));
ZETASQL_CHECK_NE(kNaN, 0);
ZETASQL_CHECK_NE(kNaN, 1);
ZETASQL_CHECK_NE(kNaN, kNegInf);
ZETASQL_CHECK_NE(kNaN, kPosInf);
ZETASQL_CHECK_NE(kNaN, kNaN);
ZETASQL_CHECK(!(kNaN < 0));
ZETASQL_CHECK(!(kNaN > 0));
ZETASQL_CHECK_NE(kPosInf, 0);
ZETASQL_CHECK_NE(kPosInf, 1);
ZETASQL_CHECK_NE(kPosInf, kNegInf);
ZETASQL_CHECK(!(kPosInf < 0));
ZETASQL_CHECK_GT(kPosInf, 0);
ZETASQL_CHECK_NE(kNegInf, 0);
ZETASQL_CHECK_NE(kNegInf, 1);
ZETASQL_CHECK_LT(kNegInf, 0);
ZETASQL_CHECK(!(kNegInf > 0));
}
TEST(MathLimits, FPMathLimits) {
TestFPMathLimits<float, double, long double>();
TestFPMathLimits<double, float, long double>();
TestFPMathLimits<long double, float, double>();
}
} // namespace zetasql_base
|
// boost cast.hpp header file
//
// (C) Copyright Antony Polukhin 2014.
//
// 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/conversion for Documentation.
// This is a DEPRECATED header file!
// Use <boost/polymorphic_cast.hpp> or <boost/numeric/conversion/cast.hpp> instead
#ifndef BOOST_CAST_HPP
#define BOOST_CAST_HPP
# include <boost/polymorphic_cast.hpp>
# include <boost/numeric/conversion/cast.hpp>
#endif // BOOST_CAST_HPP
|
#include "PyScaffolder.hpp"
#include "OptimalSlice.hpp"
#include "MeshOperation.h"
#include "implicit_function.h"
#include "QuadricSimplification.h"
#include "dualmc/dualmc.h"
#define LOG std::cout
#define IS_INSTANCE_ARRAYLIST(x) (py::isinstance<py::list>(x) || py::isinstance<py::tuple>(x) || py::isinstance<py::array>(x))
using namespace PyScaffolder;
using namespace optimal_slice;
namespace py = pybind11;
// format Eigen object to readable text
Eigen::IOFormat CleanFmt(4, Eigen::DontAlignCols, ", ", "\n", "[", "]");
Eigen::IOFormat CSVFmt(-1, Eigen::DontAlignCols, ", ", ", ");
void clean_mesh(TMesh &mesh) {
// It's a good practice to clean STL mesh firstly (VCGLib)
mesh.face.EnableFFAdjacency();
vcg::tri::Clean<TMesh>::RemoveDuplicateFace(mesh);
vcg::tri::Clean<TMesh>::RemoveDuplicateVertex(mesh);
vcg::tri::Clean<TMesh>::RemoveUnreferencedVertex(mesh);
vcg::tri::UpdateTopology<TMesh>::FaceFace(mesh);
vcg::tri::Clean<TMesh>::RemoveZeroAreaFace(mesh);
vcg::tri::Clean<TMesh>::RemoveNonManifoldFace(mesh);
vcg::tri::Clean<TMesh>::RemoveUnreferencedVertex(mesh);
vcg::tri::UpdateTopology<TMesh>::FaceFace(mesh);
mesh.face.DisableFFAdjacency();
}
MeshInfo PyScaffolder::generate_scaffold(
Eigen::MatrixXd V1,
Eigen::MatrixXi F1,
Parameter params,
const std::function<void(int)>& callback
) {
MeshInfo mesh_info;
TMesh mesh;
double volume1 = EPSIL, volume2 = EPSIL;
double area1 = EPSIL, area2 = EPSIL;
{
Eigen::MatrixXd V, Fxyz, IFxyz;
Eigen::MatrixXi F;
Eigen::RowVector3d V1min1;
Eigen::RowVector3i grid_size;
Eigen::RowVector3d V1min, V1max, L, delta;
double grid_delta;
{
TMesh stl;
eigen_vector_to_mesh(V1, F1, stl);
// It's a good practice to clean STL mesh firstly (VCGLib)
stl.face.EnableFFAdjacency();
vcg::tri::Clean<TMesh>::RemoveDuplicateFace(stl);
vcg::tri::Clean<TMesh>::RemoveDuplicateVertex(stl);
vcg::tri::Clean<TMesh>::RemoveUnreferencedVertex(stl);
vcg::tri::UpdateTopology<TMesh>::FaceFace(stl);
vcg::tri::Clean<TMesh>::RemoveZeroAreaFace(stl);
vcg::tri::Clean<TMesh>::RemoveNonManifoldFace(stl);
vcg::tri::Clean<TMesh>::RemoveUnreferencedVertex(stl);
vcg::tri::UpdateTopology<TMesh>::FaceFace(stl);
stl.face.DisableFFAdjacency();
// Check that the mesh is neither point cloud (has only vertices) nor non-watertight (has some self-intersacting faces).
int edgeNum = 0, edgeBorderNum = 0, edgeNonManifNum = 0;
vcg::tri::Clean<TMesh>::CountEdgeNum(stl, edgeNum, edgeBorderNum, edgeNonManifNum);
bool watertight = (edgeBorderNum == 0) && (edgeNonManifNum == 0);
bool pointcloud = (stl.fn == 0 && stl.vn != 0);
if (!pointcloud && watertight) {
// Collect the volume and surface area of original mesh
area1 = vcg::tri::Stat<TMesh>::ComputeMeshArea(stl);
volume1 = vcg::tri::Stat<TMesh>::ComputeMeshVolume(stl);
}
else {
std::stringstream error_message;
error_message << "Error: Input file is not valid" << std::endl
<< "-- Watertight: " << watertight << (watertight ? "[Valid]" : "[Invalid]") << std::endl
<< "-- Point cloud: " << pointcloud << (!pointcloud ? "[Valid]" : "[Invalid]") << std::endl;
throw std::runtime_error(error_message.str());
}
// Calculate the grid size parameters
V1min = V1.colwise().minCoeff();
V1max = V1.colwise().maxCoeff();
L = V1max - V1min;
delta = L / params.grid_size;
grid_delta = delta.minCoeff();
// Create border offset from the original box
V1min1 = V1min - params.grid_offset * grid_delta * Eigen::RowVector3d::Ones();
grid_size = (L / grid_delta).cast<int>() + 2 * params.grid_offset * Eigen::RowVector3i::Ones();
if (params.verbose)
LOG << "-- Bounding Box: "
<< V1min.format(CleanFmt) << ' ' << V1max.format(CleanFmt) << std::endl
<< "-- Length: " << L.format(CleanFmt) << std::endl
<< "-- Grid delta: " << grid_delta << std::endl;
// Convert input STL from VCG::TMesh to Eigen matrixXd V1
mesh_to_eigen_vector(stl, V1, F1);
}
// Generate Grid index (x,y,z)
if (params.verbose) LOG << "[Generating grid] ";
Eigen::MatrixXd GV(grid_size.prod(), 3);
for (size_t k = 0; k < grid_size(2); k++) {
const double z = V1min1(2) + k * grid_delta;
for (size_t j = 0; j < grid_size(1); j++) {
const double y = V1min1(1) + j * grid_delta;
for (size_t i = 0; i < grid_size(0); i++) {
const double x = V1min1(0) + i * grid_delta;
const size_t index = i + grid_size(0) * (j + grid_size(1) * k);
GV.row(index) = Eigen::RowVector3d(x, y, z);
}
}
}
if (params.verbose)
LOG << "OK" << std::endl
<< "-- Grid size: " << grid_size.prod() << " " << grid_size.format(CleanFmt) << std::endl;
if (callback != NULL) callback(1);
Eigen::VectorXd W, D, Signed_Distance;
{
igl::FastWindingNumberBVH bvh;
igl::AABB<Eigen::MatrixXd, 3> tree;
tree.init(V1, F1);
igl::fast_winding_number(V1, F1, 2, bvh);
igl::fast_winding_number(bvh, 2, GV, W);
igl::signed_distance_fast_winding_number(GV, V1, F1, tree, bvh, Signed_Distance);
Signed_Distance *= -1;
}
if (params.verbose)
LOG << "-- Sign Distance: [ " << Signed_Distance.minCoeff() << ", " << Signed_Distance.maxCoeff() << "] "
<< "Wind: [ " << W.minCoeff() << ", " << W.maxCoeff() << "]" << std::endl;
if (callback != NULL) callback(10);
sol::state lua;
Function* surface;
sol::function f;
// Initialize surface
bool isLuaFunction = false;
if (util::PathGetExtension(params.surface_name) == ".lua") {
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string);
set_shorten_function(lua);
sol::load_result lua_file = lua.load_file(params.surface_name);
if (!lua_file.valid()) {
sol::error err = lua_file;
std::cerr << "[Lua Error] " << err.what() << std::endl;
exit(-1);
}
else {
lua["params"] = lua.create_table_with(
"coff", params.coff,
"isolevel", params.isolevel,
"k_slice", params.k_slice,
"k_polygon", params.k_polygon
);
lua["bbox"] = lua.create_table_with(
"length", sol::as_table(std::vector<double>{L(0), L(1), L(2)}),
"min", sol::as_table(std::vector<double>{V1min(0), V1min(1), V1min(2)}),
"max", sol::as_table(std::vector<double>{V1max(0), V1max(1), V1max(2)}),
"grid_density", sol::as_table(std::vector<int>{grid_size(0), grid_size(1), grid_size(2)})
);
lua.set_function("winding", [W, V1min1, grid_delta, grid_size](double x, double y, double z) -> double
{
auto i = floor((x - V1min1(0)) / grid_delta);
auto j = floor((y - V1min1(1)) / grid_delta);
auto k = floor((z - V1min1(2)) / grid_delta);
const size_t index = i + grid_size(0) * (j + grid_size(1) * k);
if (index < 0 || index >= (size_t)grid_size(0) * grid_size(1) * grid_size(2))
return (double)-1;
return W(index);
});
lua.set_function("signed_distance", [Signed_Distance, V1min1, grid_delta, grid_size](double x, double y, double z) -> double
{
auto i = floor((x - V1min1(0)) / grid_delta);
auto j = floor((y - V1min1(1)) / grid_delta);
auto k = floor((z - V1min1(2)) / grid_delta);
const size_t index = i + grid_size(0) * (j + grid_size(1) * k);
if (index < 0 || index >= (size_t)grid_size(0) * grid_size(1) * grid_size(2))
return (double)-1;
return Signed_Distance(index);
});
lua_file();
f = lua["surface"];
surface = new LuaFunction(f);
isLuaFunction = true;
}
}
else {
surface = isosurface(params.surface_name, params.isolevel);
}
Implicit_function fn(surface, params.coff);
// test for fn function, in case of lua function
// if it's invalid, the exception will occur
fn(0.1, 0.23, 0.45);
Fxyz.resize(grid_size.prod(), 1);
IFxyz.resize(grid_size.prod(), 1);
// voxelize the surface
for (size_t k = 0; k < grid_size(2); k++) {
const double z = V1min1(2) + k * grid_delta;
for (size_t j = 0; j < grid_size(1); j++) {
const double y = V1min1(1) + j * grid_delta;
for (size_t i = 0; i < grid_size(0); i++) {
const double x = V1min1(0) + i * grid_delta;
const size_t index = i + grid_size(0) * (j + grid_size(1) * k);
const double s = Signed_Distance(index);
const double w = W(index);
const double fv = fn(x, y, z);
if (params.is_intersect && w < 0.8) {
Fxyz(index) = -1.0;
IFxyz(index) = -1.0;
}
else if (params.is_intersect && params.shell > 0 && s <= params.shell) {
Fxyz(index) = s;
IFxyz(index) = s;
}
else if (
!params.is_intersect &&
(
i < params.grid_offset ||
i >= grid_size(0) - params.grid_offset ||
j < params.grid_offset ||
j >= grid_size(1) - params.grid_offset ||
k < params.grid_offset ||
k >= grid_size(2) - params.grid_offset
)
) {
Fxyz(index) = -1.0;
IFxyz(index) = -1.0;
}
else {
Fxyz(index) = fv;
IFxyz(index) = -fv;
}
}
}
}
if (callback != NULL) callback(20);
// Create scaffolder and inverse mesh by dual marching cube
if (params.is_build_inverse) {
marching_cube(mesh, IFxyz, grid_size, V1min1, grid_delta, false, false);
}
else {
marching_cube(mesh, Fxyz, grid_size, V1min1, grid_delta, false, false);
}
if (callback != NULL) callback(50);
clean_mesh(mesh, params.minimum_diameter, params.smooth_step);
if (params.fix_self_intersect > 0) fix_self_intersect_mesh(mesh, params.minimum_diameter, params.fix_self_intersect);
if (callback != NULL) callback(60);
if (params.qsim_percent > 0) {
vcg::tri::mesh_quad_simplification(mesh, params.qsim_percent, null_callback);
}
if (callback != NULL) callback(90);
bool is_manifold = is_mesh_manifold(mesh);
if (!is_manifold) {
is_manifold = fix_non_manifold_vertices(mesh, params.minimum_diameter, 5);
is_manifold = is_manifold && fix_non_manifold_edges(mesh, params.minimum_diameter, 5);
}
if (!is_manifold) {
if (params.verbose)
LOG << "[Warning] Mesh is not two manifold" << std::endl;
}
else {
area2 = vcg::tri::Stat<TMesh>::ComputeMeshArea(mesh);
volume2 = vcg::tri::Stat<TMesh>::ComputeMeshVolume(mesh);
mesh_info.porosity = 1 - abs(volume2 / volume1);
mesh_info.surface_area = area2;
mesh_info.surface_area_ratio = abs(area2 / area1);
}
}
clean_mesh(mesh);
mesh_to_eigen_vector(mesh, mesh_info.v, mesh_info.f);
if (callback != NULL) callback(100);
return mesh_info;
}
std::tuple<Eigen::MatrixXd, Eigen::MatrixXi> PyScaffolder::marching_cubes(
Eigen::VectorXd& Fxyz,
py::object& grid_size,
py::object& _delta,
const std::vector<double>& Vmin,
bool clean,
const std::function<void(int)>& callback
) {
try {
dualmc::DualMC<double> builder;
std::vector<dualmc::Vertex> mc_vertices;
std::vector<dualmc::Quad> mc_quads;
if (callback != NULL) builder.callback = callback;
// Type conversion
std::array<int32_t, 3> g;
if (IS_INSTANCE_ARRAYLIST(grid_size)) {
g = py::cast< std::array<int32_t, 3> >(grid_size);
}
else {
int32_t gs = py::cast<int32_t>(grid_size);
g[0] = gs;
g[1] = gs;
g[2] = gs;
}
std::array<double, 3> delta;
if (IS_INSTANCE_ARRAYLIST(_delta)) {
delta = py::cast< std::array<double, 3> >(_delta);
}
else {
double d = py::cast<double>(_delta);
delta[0] = d;
delta[1] = d;
delta[2] = d;
}
// Dual-Marching cubes
builder.build((double const*)Fxyz.data(), g[0], g[1], g[2], 0, true, true, mc_vertices, mc_quads);
Eigen::MatrixXd v;
Eigen::MatrixXi f;
if (clean) {
TMesh mesh;
TMesh::VertexIterator vi = vcg::tri::Allocator<TMesh>::AddVertices(mesh, mc_vertices.size());
TMesh::FaceIterator fi = vcg::tri::Allocator<TMesh>::AddFaces(mesh, mc_quads.size() * 2);
std::vector<TMesh::VertexPointer> vp(mc_vertices.size());
for (size_t i = 0, len = mc_vertices.size(); i < len; i++, ++vi) {
vp[i] = &(*vi);
vi->P() = TMesh::CoordType(
Vmin[0] + mc_vertices[i].x * delta[0],
Vmin[1] + mc_vertices[i].y * delta[1],
Vmin[2] + mc_vertices[i].z * delta[2]
);
}
for (size_t i = 0, len = mc_quads.size(); i < len; i++, ++fi) {
fi->V(0) = vp[mc_quads[i].i0];
fi->V(1) = vp[mc_quads[i].i1];
fi->V(2) = vp[mc_quads[i].i2];
++fi;
fi->V(0) = vp[mc_quads[i].i2];
fi->V(1) = vp[mc_quads[i].i3];
fi->V(2) = vp[mc_quads[i].i0];
}
clean_mesh(mesh);
mesh_to_eigen_vector(mesh, v, f);
}
else {
v.resize(mc_vertices.size(), 3);
for (size_t i = 0, len = mc_vertices.size(); i < len; i++) {
v.row(i) << Vmin[0] + mc_vertices[i].x * delta[0], Vmin[1] + mc_vertices[i].y * delta[1], Vmin[2] + mc_vertices[i].z * delta[2];
}
f.resize(mc_quads.size() * 2, 3);
for (size_t i = 0, j = 0, len = mc_quads.size(); i < len; i++) {
f.row(j) << mc_quads[i].i0, mc_quads[i].i1, mc_quads[i].i2;
j++;
f.row(j) << mc_quads[i].i2, mc_quads[i].i3, mc_quads[i].i0;
j++;
}
}
return make_tuple(v, f);
}
catch (std::exception& e) {
if (callback != NULL) callback(100);
throw std::runtime_error(e.what());
}
}
PoreSize PyScaffolder::slice_test(Eigen::MatrixXd v, Eigen::MatrixXi f, size_t k_slice, size_t k_polygon, int direction, const std::function<void(int)>& callback) {
PoreSize pore_size;
TMesh mesh;
eigen_vector_to_mesh(v, f, mesh);
vcg::tri::UpdateBounding<TMesh>::Box(mesh);
vcg::tri::Clean<TMesh>::RemoveDuplicateVertex(mesh);
vcg::tri::Allocator<TMesh>::CompactEveryVector(mesh);
vcg::tri::UpdateTopology<TMesh>::FaceFace(mesh);
vcg::tri::Clean<TMesh>::RemoveDuplicateFace(mesh);
vcg::tri::UpdateTopology<TMesh>::FaceFace(mesh);
vcg::tri::Clean<TMesh>::RemoveZeroAreaFace(mesh);
vcg::tri::UpdateTopology<TMesh>::FaceFace(mesh);
vcg::tri::Clean<TMesh>::MergeCloseVertex(mesh, SLICE_PRECISION * 10);
vcg::tri::UpdateTopology<TMesh>::FaceFace(mesh);
if (callback != NULL) callback(20);
std::vector<double> minFeret, maxFeret, shape[5];
if (direction > 2) {
for (int i = 0; i < 2; i++) {
Slice s = incremental_slicing(mesh, k_slice, i);
ContourSlice C = contour_construct(s, i);
measure_feret_and_shape(C, 4, minFeret, maxFeret, shape);
if (callback != NULL) callback(20 + 30 * (i + 1));
}
}
else {
Slice s = incremental_slicing(mesh, k_slice, direction);
ContourSlice C = contour_construct(s, direction);
measure_feret_and_shape(C, k_polygon, minFeret, maxFeret, shape);
}
if (minFeret.size() > 0) {
std::sort(minFeret.begin(), minFeret.end());
pore_size.minFeret = Eigen::VectorXd::Map(&minFeret[0], minFeret.size());
}
if (maxFeret.size() > 0) {
std::sort(maxFeret.begin(), maxFeret.end());
pore_size.maxFeret = Eigen::VectorXd::Map(&maxFeret[0], maxFeret.size());
}
if (callback != NULL) callback(100);
return pore_size;
}
|
#pragma once
#include "../common.hpp"
namespace Mirb
{
class Input
{
private:
const char_t *input;
public:
enum Characters
{
Null = 0,
CarrigeReturn = 0x13,
NewLine = 0x10
};
Input& operator=(const Input& other)
{
input = other.input;
return *this;
}
void set(const char_t *input)
{
this->input = input;
}
bool in(char_t start, char_t stop)
{
return char_in(*input, start, stop);
}
static bool char_in(char_t c, char_t start, char_t stop)
{
return c >= start && c <= stop;
}
const char_t *operator &()
{
return input;
}
operator char_t()
{
return *input;
}
char_t operator++()
{
return *(++input);
}
char_t operator++(int)
{
return *(input++);
}
char_t operator--()
{
return *(--input);
}
char_t operator--(int)
{
return *(input--);
}
};
};
|
#define BOOST_TEST_MODULE Zoocoin Test Suite
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"
#include "util.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
boost::filesystem::path pathTemp;
boost::thread_group threadGroup;
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
noui_connect();
bitdb.MakeMock();
pathTemp = GetTempPath() / strprintf("test_zoocoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
InitBlockIndex();
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
~TestingSetup()
{
threadGroup.interrupt_all();
threadGroup.join_all();
delete pwalletMain;
pwalletMain = NULL;
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
bitdb.Flush(true);
boost::filesystem::remove_all(pathTemp);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
|
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "Cosmology.h"
#include "PowerSpectrum.h"
#include "Quadrature.h"
#include "BSPT.h"
#include "BSPTN.h"
#include "SPT.h"
#include "Spline.h"
#include "SpecialFunctions.h"
#include "LinearPS.h"
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <math.h> /* pow */
#include <gsl/gsl_math.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <gsl/gsl_deriv.h>
#include <random>
#include <functional>
using std::cref;
using std::bind;
BSPT::BSPT(const Cosmology& C_, const PowerSpectrum& P_L_, real epsrel_)
: C(C_), P_L(P_L_)
{
epsrel = epsrel_;
}
static double neff_integrand(const PowerSpectrum& P_L, double lambda, double k, double q){
return P_L(q)/neffehu(q)*exp(-pow2(log(k/q)/lambda)/2.)/q;
}
static double myfunc(double k,void * params){
(void)(params);
return log(neffnw(k));
}
static double myneff(double k){
gsl_function F;
double result, abserr;
F.function = &myfunc;
F.params = 0;
abserr = 1e-5;
gsl_deriv_central(&F, k, 1e-5, &result, &abserr);
return k*result;
}
// Calculate sigma_8 at some redshift
static double sigma8int2(const PowerSpectrum& P_L, double k){
return pow2(3.*((sin(k*8.) - k*8.*cos(k*8.))/pow2(k*8.))/k/8.) * pow2(k) * pow2(D_spt/dnorm_spt) * P_L(k)/2./M_PI/M_PI;
}
static double mysigma82(const PowerSpectrum& P_L){
return sqrt(Integrate(bind(sigma8int2,cref(P_L),std::placeholders::_1),0.0001,30.,1e-4));
}
// Find K_nl
double myknls2(const PowerSpectrum& P_L)
{
std::mt19937 gen(2);
const double lower_bound = 1e-4;
const double upper_bound = 1000.;
std::uniform_real_distribution<> dis(lower_bound, upper_bound);
double pos_pt = dis(gen);
double neg_pt = dis(gen);
while ( (pow2(D_spt/dnorm_spt)*P_L(pos_pt)*pow3(pos_pt)/2./M_PI/M_PI - 1.) < 0.){
pos_pt = dis(gen);}
while ( (pow2(D_spt/dnorm_spt)*P_L(neg_pt)*pow3(neg_pt)/2./M_PI/M_PI- 1.) > 0.){
neg_pt = dis(gen);}
const double about_zero_mag = 1e-5;
for (;;)
{
double mid_pt = (pos_pt + neg_pt)/2.0;
double f_mid_pt = pow2(D_spt/dnorm_spt)*P_L(mid_pt)*pow3(mid_pt)/2./M_PI/M_PI -1.;
if (fabs(f_mid_pt) < about_zero_mag){
return mid_pt;
}
if (f_mid_pt >= 0.){
pos_pt = mid_pt;}
else{
neg_pt = mid_pt;}
}
}
// No wiggle spectrum for neff used in Vlah et al
Spline neffnw;
Spline neffehu;
Spline mylinearps;
double mys8,myknl;
// Initialize the NW power spectrum, A^{nw,0l}, sigma8 and knl
// j initialises k_nl and sigma8 at the redshift set by inite (defined in GR)
void BSPT::mypspline(double scalef, double omega0, int j) const{
SPT spt(C, P_L, 1e-2);
NoWigglePS now(C, 0. , EisensteinHu);
vector<double> kval_table, now_table, ehu_table, linps_table;
double k, nowps, lambda, ehups, linps;
const double kmin = 1e-4;
const double kmax = 80.;
const int n1 = 2000;
// initialise halofit functions
spt.phinit(scalef, omega0);
for(int i = 0; i<n1; i++ ){
k = kmin*exp(i*log(kmax/kmin)/(n1-1.));
kval_table.push_back(k);
ehups = now.Evaluate(k);
linps = P_L(k);
ehu_table.push_back(ehups);
linps_table.push_back(linps);
}
neffehu = CubicSpline(kval_table,ehu_table);
mylinearps = CubicSpline(kval_table,linps_table);
for(int i = 0; i<n1; i++ ){
k = kmin*exp(i*log(kmax/kmin)/(n1-1.));
lambda = 0.25*pow(k/0.05,0.04);
nowps = now.Evaluate(k)/sqrt(2.*M_PI*pow2(lambda))*Integrate<ExpSub>(bind(neff_integrand,cref(P_L),lambda, k,std::placeholders::_1),kmin,kmax,1e-5);
now_table.push_back(nowps);
}
neffnw = CubicSpline(kval_table,now_table);
if(j==1){
mys8 = mysigma82(cref(P_L));
myknl = myknls2(cref(P_L));
}
}
// Fitting formula prescription of 1805.10567
real BSPT::Bfit(double k1, double k2, double x) const {
double k3 = sqrt(pow2(k1) + pow2(k2) + 2.*k2*k1*x);
double F2A,F2B,F2C, vars[6];
vars[0] = mys8;
vars[1] = myknl;
vars[2] = 1.;
vars[3] = (1.- F_spt * 7./2./pow2(D_spt));
vars[4] = myneff(k1);
vars[5] = myneff(k2);
F2A = F2fit(vars,k1,k2,x);
vars[4] = myneff(k1);
vars[5] = myneff(k3);
F2B = F2fit(vars,k1,k3,-(k2*x+k1)/k3);
vars[4] = myneff(k2);
vars[5] = myneff(k3);
F2C = F2fit(vars,k2,k3,-(k1*x+k2)/k3);
SPT spt(C, P_L, 1e-3);
double p1,p2,p3;
p1 = spt.PHALO(k1);
p2 = spt.PHALO(k2);
p3 = spt.PHALO(k3);
return 2.*(p1*p2*F2A + p3*p1*F2B + p2*p3*F2C);
}
// GR/nDGP Tree level Bispectrum (Real space)
// a==1 (GR analytic depending if you run inite )
// a=2 (DGP analytic)
real BSPT::Btree(int a, double k1, double k2, double x) const {
double k3 = sqrt(pow2(k1) + pow2(k2) + 2.*k2*k1*x);
double F2A,F2B,F2C,growth;
switch (a) {
case 1:
growth = pow2(Dl_spt/dnorm_spt);
F2A = growth*F2eds(k1, k2, x);
F2B = growth*F2eds(k1,k3,-(k2*x+k1)/k3);
F2C = growth*F2eds(k2,k3,-(k1*x+k2)/k3);
break;
case 2:
growth = pow2(D_spt/dnorm_spt);
F2A = F2ndgp(k1,k2,x);
F2B = F2ndgp(k1,k3,-(k2*x+k1)/k3);
F2C = F2ndgp(k2,k3,-(k1*x+k2)/k3);
break;
default:
warning("BSPT: invalid indices, a = %d\n", a);
return 0;
}
//Tree
return 2.*growth*(P_L(k1)*P_L(k2)*F2A + P_L(k3)*P_L(k1)*F2B + P_L(k2)*P_L(k3)*F2C);
}
// GR/DGP 1-loop Bispectrum (Real space)
// a=1 (GR analytic)
// a=2 (DGP analytic)
real BSPT::Bloop(int a, double k1, double k2, double x) const {
SPT spt(C, P_L, 1e-2);
double k3 = sqrt(pow2(k1) + pow2(k2) + 2.*k2*k1*x);
double F2A,F2B,F2C,P131,P132,P133,growth;
switch (a) {
case 1:
growth = pow2(Dl_spt/dnorm_spt);
F2A = growth*F2eds(k1, k2, x);
F2B = growth*F2eds(k1,k3,-(k2*x+k1)/k3);
F2C = growth*F2eds(k2,k3,-(k1*x+k2)/k3);
P131 = spt.P13_dd(k1);
P132 = spt.P13_dd(k2);
P133 = spt.P13_dd(k3);
break;
case 2:
growth = pow2(D_spt/dnorm_spt);
F2A = F2ndgp(k1, k2, x);
F2B = F2ndgp(k1,k3,-(k2*x+k1)/k3);
F2C = F2ndgp(k2,k3,-(k1*x+k2)/k3);
P131 = spt.P13D_dd(k1);
P132 = spt.P13D_dd(k2);
P133 = spt.P13D_dd(k3);
break;
default:
warning("BSPT: invalid indices, a = %d\n", a);
return 0;
}
//Tree
return 2.*growth*(P_L(k1)*P_L(k2)*F2A + P_L(k3)*P_L(k1)*F2B + P_L(k2)*P_L(k3)*F2C)
// B222, B321-I and B411
+ Bloopterms(a,k1,k2,k3,x)
// B123-II
+ F2A*(P_L(k1)*P132 + P_L(k2)*P131) + F2B*(P_L(k3)*P131 + P_L(k1)*P133) + F2C*(P_L(k3)*P132 + P_L(k2)*P133);
}
static real B_222(const PowerSpectrum& P_L, real k1, real k2, real x, real k3, real r, real u, real o) {
double k1s = pow2(k1);
double k2s = pow2(k2);
double p = k1*r;
double ps = pow2(p);
double d = sqrt(1. + r*r - 2.*r*u);
real k1mp = k1*d;
real k2p = u*x - sqrt((1.-pow2(u))*(1.-pow2(x)))*cos(o);
real k2pp = sqrt(k2s + ps + 2*k2*p*k2p);
if(d < 1e-5 )
return 0;
else{
return 8.*pow2(r)*P_L(p)*(F2eds(r*k1,k1mp,(u-r)/d)*F2eds(p,k2pp,-(k2*k2p+p)/k2pp)*F2eds(k1mp,k2pp,(k2*x+p*u-k2*r*k2p-p*r)/d/k2pp)*P_L(k1mp)*P_L(k2pp));
}
}
static real B_222D(const PowerSpectrum& P_L, real k1, real k2, real x, real k3, real r, real u, real o) {
double k1s = pow2(k1);
double k2s = pow2(k2);
double p = k1*r;
double ps = pow2(p);
double d = sqrt(1. + r*r - 2.*r*u);
real k1mp = k1*d;
real k2p = u*x - sqrt((1.-pow2(u))*(1.-pow2(x)))*cos(o);
real k2pp = sqrt(k2s + ps + 2*k2*p*k2p);
if(d < 1e-5 )
return 0;
else{
return 8.*pow2(r)*P_L(p)*(F2ndgp(r*k1,k1mp,(u-r)/d)*F2ndgp(p,k2pp,-(k2*k2p+p)/k2pp)*F2ndgp(k1mp,k2pp,(k2*x+p*u-k2*r*k2p-p*r)/d/k2pp)*P_L(k1mp)*P_L(k2pp));
}
}
static real B_321I(const PowerSpectrum& P_L, real k1, real k2, real x, real k3, real r, real u, real o) {
double k1s = pow2(k1);
double k2s = pow2(k2);
double k3s = pow2(k3);
double p = k1*r;
double ps = pow2(p);
double d = sqrt(1. + r*r - 2.*r*u);
double d1 = sqrt(1. + r*r + 2.*r*u);
real k1mp = k1*d;
real k1pp = k1*d1;
real k2p = u*x - sqrt((1.-pow2(u))*(1.-pow2(x)))*cos(o);
real k2mp = sqrt(k2s + ps - 2.*k2*p*k2p);
real k2pp = sqrt(k2s + ps + 2.*k2*p*k2p);
real k3pp = sqrt(k2s + k1s + ps + 2.*k1*k2*x - 2.*k1s*r*u - 2.*k2*p*k2p);
real k3mp = sqrt(k2s + k1s + ps + 2.*k1*k2*x + 2.*k1s*r*u + 2.*k2*p*k2p);
double kernel1= F2eds(r*k1,k1mp,(u-r)/d);
double kernel2= F2eds(r*k1,k2mp,(k2*k2p-p)/k2mp);
double kernel3 = F2eds(r*k1,k3mp,-(k1*u+k2*k2p+p)/k3mp);
if(d < 1e-5 || d1<1e-5)
return 0;
else{
return 6.*pow2(r)*P_L(p)*(
kernel2*F3eds(k1,p,k2mp,(k2*k2p-p)/k2mp,u,(k2*x-p*u)/k2mp)*P_L(k2mp)*P_L(k1)
+ kernel3*F3eds(k1,p,k3mp,-(k1*u+k2*k2p+p)/k3mp,u,-(k1+k2*x+p*u)/k3mp)*P_L(k3mp)*P_L(k1)
+ kernel1*F3eds(k2,p,k1mp,(u-r)/d,k2p,(x-r*k2p)/d)*P_L(k1mp)*P_L(k2)
+ kernel3*F3eds(k2,p,k3mp,-(k1*u+k2*k2p+p)/k3mp,k2p,-(k2+k1*x+p*k2p)/k3mp)*P_L(k3mp)*P_L(k2)
+ kernel1*F3eds(k3,p,k1mp,(u-r)/d,-(k1*u+k2*k2p)/k3, (-k1+p*u-k2*x+k2*r*k2p)/d/k3)*P_L(k1mp)*P_L(k3)
+ kernel2*F3eds(k3,p,k2mp,(k2*k2p-p)/k2mp,-(k1*u+k2*k2p)/k3,-(k1*k2*x-k1*p*u+k2s- k2*p*k2p)/k3/k2mp)*P_L(k2mp)*P_L(k3));
}}
static real B_321ID(const PowerSpectrum& P_L, real k1, real k2, real x, real k3, real r, real u, real o) {
double k1s = pow2(k1);
double k2s = pow2(k2);
double k3s = pow2(k3);
double p = k1*r;
double ps = pow2(p);
double d = sqrt(1. + r*r - 2.*r*u);
double d1 = sqrt(1. + r*r + 2.*r*u);
real k1mp = k1*d;
real k1pp = k1*d1;
real k2p = u*x - sqrt((1.-pow2(u))*(1.-pow2(x)))*cos(o);
real k2mp = sqrt(k2s + ps - 2.*k2*p*k2p);
real k2pp = sqrt(k2s + ps + 2.*k2*p*k2p);
real k3pp = sqrt(k2s + k1s + ps + 2.*k1*k2*x - 2.*k1s*r*u - 2.*k2*p*k2p);
real k3mp = sqrt(k2s + k1s + ps + 2.*k1*k2*x + 2.*k1s*r*u + 2.*k2*p*k2p);
double kernel1= F2ndgp(p,k1mp,(u-r)/d);
double kernel2= F2ndgp(p,k2mp,(k2*k2p-p)/k2mp);
double kernel3 = F2ndgp(p,k3mp,-(k1*u+k2*k2p+p)/k3mp);
if(d < 1e-5 || d1<1e-5)
return 0;
else{
return D_spt/dnorm_spt*6.*pow2(r)*P_L(p)*(
kernel2*F3ndgp(k1,p,k2mp,(k2*k2p-p)/k2mp,u,(k2*x-p*u)/k2mp)*P_L(k2mp)*P_L(k1)
+ kernel3*F3ndgp(k1,p,k3mp,-(k1*u+k2*k2p+p)/k3mp,u,-(k1+k2*x+p*u)/k3mp)*P_L(k3mp)*P_L(k1)
+ kernel1*F3ndgp(k2,p,k1mp,(u-r)/d,k2p,(x-r*k2p)/d)*P_L(k1mp)*P_L(k2)
+ kernel3*F3ndgp(k2,p,k3mp,-(k1*u+k2*k2p+p)/k3mp,k2p,-(k2+k1*x+p*k2p)/k3mp)*P_L(k3mp)*P_L(k2)
+ kernel1*F3ndgp(k3,p,k1mp,(u-r)/d,-(k1*u+k2*k2p)/k3, (-k1+p*u-k2*x+k2*r*k2p)/d/k3)*P_L(k1mp)*P_L(k3)
+ kernel2*F3ndgp(k3,p,k2mp,(k2*k2p-p)/k2mp,-(k1*u+k2*k2p)/k3,-(k1*k2*x-k1*p*u+k2s- k2*p*k2p)/k3/k2mp)*P_L(k2mp)*P_L(k3));
}}
static real B_411(const PowerSpectrum& P_L, real k1, real k2, real x, real k3, real r, real u, real o) {
double p = k1*r;
double k2p = u*x - sqrt((1.-pow2(u))*(1.-pow2(x)))*cos(o);
double k3p = (-k1*u-k2*k2p)/k3;
double k1mp = sqrt(pow2(k1)+pow2(p)-2.*k1*p*u);
return 12.*pow2(r)*P_L(p)*(F4edsb(k1,k2,p,p,-k2p,k2p,x,-u,u)*P_L(k1)*P_L(k2)
+ F4edsb(k2,k3,p,p,(k1*u+k2*k2p)/k3,-(k1*u+k2*k2p)/k3,-(k1*x+k2)/k3,-k2p,k2p)*P_L(k2)*P_L(k3)
+ F4edsb(k3,k1,p,p,-u,u,-(k1+k2*x)/k3,(k1*u+k2*k2p)/k3,-(k1*u+k2*k2p)/k3)*P_L(k3)*P_L(k1));
}
static real B_411D(const PowerSpectrum& P_L, real k1, real k2, real x, real k3, real r, real u, real o) {
double p = k1*r;
double k2p = u*x - sqrt((1.-pow2(u))*(1.-pow2(x)))*cos(o);
double k3p = (-k1*u-k2*k2p)/k3;
double k1mp = sqrt(pow2(k1)+pow2(p)-2.*k1*p*u);
double karg1[4],karg2[4],karg3[4];
double xarg1[6],xarg2[6],xarg3[6];
karg1[0]=k1;
karg1[1]=k2;
karg1[2]=p;
karg1[3]=p;
karg2[0]=k2;
karg2[1]=k3;
karg2[2]=p;
karg2[3]=p;
karg3[0]=k1;
karg3[1]=k3;
karg3[2]=p;
karg3[3]=p;
xarg1[0]=k2p;
xarg1[1]=x;
xarg1[2]=-u;
xarg1[3]=-k2p;
xarg1[4]= XMIN;
xarg1[5]=u;
xarg2[0]=-(k1*u+k2*k2p)/k3;
xarg2[1]=-(k1*x+k2)/k3;
xarg2[2]=-k2p;
xarg2[3]=(k1*u+k2*k2p)/k3;
xarg2[4]= XMIN;
xarg2[5]=k2p;
xarg3[0]=u;
xarg3[1]=-(k1+k2*x)/k3;
xarg3[2]=(k1*u+k2*k2p)/k3;
xarg3[3]=-u;
xarg3[4]= XMIN;
xarg3[5]=-(k1*u+k2*k2p)/k3;
return pow2(D_spt/dnorm_spt)*12.*pow2(r)*P_L(p)*(F4dgp(karg1,xarg1)*P_L(k1)*P_L(k2)
+F4dgp(karg2,xarg2)*P_L(k2)*P_L(k3)
+F4dgp(karg3,xarg3)*P_L(k1)*P_L(k3));
}
double BSPT::Bloopterms(int a, real k1, real k2, real k3, real x) const{
real KMAX = QMAXp/k1;
real KMIN = QMINp/k1;
real tp = 2.*M_PI;
real c[3] = {KMIN,-1.,0.};
real d[3] = {KMAX,0.99999999,tp};
switch (a) {
case 1:
return pow6(Dl_spt/dnorm_spt)*pow3(k1/tp)*(Integrate<3>(bind(B_222, cref(P_L), k1, k2, x, k3, std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d,epsrel)
+ Integrate<3>(bind(B_321I, cref(P_L), k1, k2, x, k3, std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d,epsrel)
+ Integrate<3>(bind(B_411, cref(P_L), k1, k2, x, k3, std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d,epsrel));
break;
case 2:
return pow3(k1/tp)*(Integrate<3>(bind(B_222D, cref(P_L), k1, k2, x, k3, std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d,epsrel)
+ Integrate<3>(bind(B_321ID, cref(P_L), k1, k2, x, k3, std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d,epsrel)
+ Integrate<3>(bind(B_411D, cref(P_L), k1, k2, x, k3, std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d,epsrel));
break;
default:
warning("BSPT: invalid indices, a = %d \n", a);
return 0;
}
}
///////////////////// NUMERICAL TREE LEVEL SPECTRUM ////////////////////////
// 0 = omega0, 1 = mg1, 2=mg2, 3=mg3, 4=a, 5=mg o
// vars[5] = 1 (DGP or GR)
// vars[5] = 2 (f(R) Hu-Sawicki)
real BSPT::Btreen(double vars[], double k1, double k2, double x) const {
BSPTN bsptn;
IOW iow;
double ka[3],xa[3],kargs[3];
double k1s,k2s,k3;
k1s = pow2(k1);
k2s = pow2(k2);
ka[0]=k1;
ka[1]=k2;
ka[2]=sqrt(k1s+k2s+2.*x*k1*k2);
k3 = ka[2];
kargs[0] = k3;
kargs[1] = k2;
kargs[2] = k1;
xa[0] = -(k1*x+k2)/k3; // k2.k3
xa[1] = x; //k1.k2
xa[2] = -(k2*x+k1)/k3;// k1.k3
switch( (int)vars[5] ) {
case 1:
bsptn.initnb0_dgp(vars[4], ka, xa, kargs, vars[0], vars[1], vars[2],vars[3]);
return 2./pow4(dnorm_spt)*(P_L(k1)*P_L(k2)*F1b_k1*F1b_k2*F2b_k12 + P_L(k3)*P_L(k1)*F1b_k1*F1b_k3*F2b_k13 + P_L(k2)*P_L(k3)*F1b_k2*F1b_k3*F2b_k23);
case 2:
bsptn.initnb0_fofr(vars[4], ka, xa, kargs, vars[0], vars[1], vars[2],vars[3]);
return 2./pow4(dnorm_spt)*(P_L(k1)*P_L(k2)*F1b_k1*F1b_k2*F2b_k12 + P_L(k3)*P_L(k1)*F1b_k1*F1b_k3*F2b_k13 + P_L(k2)*P_L(k3)*F1b_k2*F1b_k3*F2b_k23);
default:
warning("BSPT: invalid indices, vars[5] = %e\n", vars[5]);
return 0.;
}
}
///////////////////// NUMERICAL 1-LOOP SPECTRUM ///////////////////////////
// MG INITIALISATION
static real bloopdgp(const PowerSpectrum& P_L, double vars[], double k1, double k2, double x, double k3, double p, double mu, double phi){
BSPTN bsptn;
double B411,B222,B321a,B321b,pkp,pk1,pk2,pk3,pka1,pka4,pka3;
double scalef = vars[4];
double omega0= vars[0];
double mg1= vars[1];
double mg2= vars[2];
double mg3= vars[3];
double epars[3];
epars[0]= vars[7];
epars[1]= vars[8];
epars[2]= 1.; //vars[9];
double k2p,k2pp,k3p,ps,ka[8],xa[8],kargs[25];
double sx = (1.-pow2(x));
double k1s = pow2(k1);
double k2s = pow2(k2);
double k3s = pow2(k3);
kargs[5] = x;
ka[5] = k1;
ka[6] = k2;
ka[7] = k3;
kargs[9] = -(k1 + k2*x)/k3; // k1.k3
kargs[13] = -(k2 + k1*x)/k3; // k2.k3
ka[0] = p;
ps = pow2(p);
k2pp = sqrt(sx*(1.-pow2(mu)));
ka[1] = sqrt(k1s+ps-2.*p*k1*mu); // k1-p
xa[1] = (k1*mu-p)/ka[1]; // p. k1-p
xa[5] = mu;
kargs[1] = sqrt(k1s + ps + 2.*p*k1*mu); // p + k1
kargs[14] = -(k1*mu + p)/kargs[1]; // - p . k1+p
k2p = mu*x - k2pp*cos(phi*M_PI+M_PI); // k2.p
k3p = (-k1*mu-k2*k2p)/k3; // k3.p
ka[2] = sqrt(k2s+ps+2.*p*k2*k2p); // k2+p
ka[3] = sqrt(k2s + ps - 2.*k2*p*k2p); // k2 - p
ka[4] = sqrt(k3s + ps - 2.*k3*p*k3p); // k3-p
xa[0] = (k1*k2*x + k1*p*mu - p*k2*k2p - ps)/ka[1]/ka[2]; //k1-p . k2+p
xa[2] = -(k2*k2p+p)/ka[2]; //k2+p . -p
xa[3] = (k2*k2p - p)/ka[3]; // k2-p . p
xa[4] = (k3*k3p - p)/ka[4]; // k3-p.p
xa[6] = k2p;
xa[7] = k3p;
kargs[0] = sqrt(k2s + 4.*ps + 4.*k2*p*k2p); // k2 + 2p
kargs[2] = sqrt(k3s + ps + 2.*k3*p*k3p); // k3+p
kargs[3] = (k2*x - p*mu)/ka[3]; // k2-p . k1 = k2x - pu /k2mp
kargs[4] = (k2*p*k2p + k1*k2*x - ps -p*k1*mu)/kargs[1]/ka[3]; // k2-p . p+k1
kargs[6] = (k1*mu + k2*k2p - p)/kargs[2]; // p. -k3-p
kargs[7] = -(k1+k2*x+p*mu)/ka[4]; // k3-p. k1
kargs[8] = (k3*k1* kargs[9] + k3p*k3*p-p*k1*mu-ps)/ka[4]/kargs[1]; //k3-p.k1+p
kargs[10] = (k1*x+p*k2p)/kargs[1]; // k2.k1+p
kargs[11] = -(k2+k1*x+p*k2p)/ka[4]; // k3-p.k2
kargs[12] = (kargs[13]*k2*k3 -k2p*k2*p+ k3p*k3*p - ps)/ka[4]/ka[2]; // k2+p.k3-p
kargs[15] = (k1*x - p*k2p)/ka[1]; // k1-p.k2
kargs[16] = (k1*x + k2 - p*k2p)/kargs[2]; // k2. -k3-p
kargs[17] = (kargs[13]*k2*k3 - p*k3*k3p)/k3/ka[3]; // k2-p.k3
kargs[18] = (k2p*k2*p + kargs[13]*k3*k2 - ps -k3*p*k3p)/ka[3]/kargs[2]; // k2-p.p+k3
kargs[19] = -(k1*k2*x + k1s - k2*p*k2p - k1*p*mu)/ka[1]/k3; // k1-p . k3
kargs[20] = (k1*p*mu + k3*k1*kargs[9] - ps - p*k3*k3p)/kargs[2]/ka[1];// k1-p.p+k3
kargs[21] = (k2*x + p*mu)/ka[2]; // k1.k2+p
kargs[22] = (-k1s-k1*p*mu-k1*k2*x-k2*k2p*p)/kargs[1]/k3; // k1+p.k3
kargs[23] = (-k1*k2*x - k2s + k3p*p*k3)/k3/ka[2]; // k2+p.k3
kargs[24] = (-k1-k2*x+p*mu)/kargs[2];//k1.k3+p
pkp = P_L(p);
pk1 = P_L(k1);
pk2= P_L(k2);
pk3 = P_L(k3);
pka1 = P_L(ka[1]);
pka3 = P_L(ka[3]);
pka4 = P_L(ka[4]);
bsptn.initnb1_dgp(scalef, ka, xa, kargs, omega0, mg1, mg2, mg3,epars);
B222 = 8.*ps*pkp* F2b_k13 * F2b_k12 * F2b_k23 * P_L(ka[2])* pka1;
B321a = 6.*ps*pkp*( F2b_12a * (pk1 * pk2 * F3b_2pp * F1b_1 + pk2 * pk1 * F3b_1pp * F1b_2)
+F2b_13a * (pk3 * pk1 * F3b_1pp * F1b_3 + pk1 * pk3 * F3b_3pp * F1b_1)
+F2b_23a * (pk3 * pk2 * F3b_2pp * F1b_3 + pk2 * pk3 * F3b_3pp * F1b_2));
B321b = 6.*ps*pkp*(pk1 * F1b_1 *(F2b_p2mp * F3b_12mp * pka3 + F2b_p3mp * F3b_13mp * pka4)
+ pk2 * F1b_2 *(F2b_k12 * F3b_21mp * pka1 + F2b_p3mp * F3b_23mp * pka4)
+ pk3 * F1b_3 *(F2b_k12 * F3b_31mp * pka1 + F2b_p2mp * F3b_32mp * pka3));
B411 = 12.*ps*pkp*(F4b_12pp * F1b_1 * F1b_2 * pk1 * pk2
+ F4b_13pp * F1b_1 * F1b_3 * pk1 * pk3
+ F4b_23pp * F1b_2 * F1b_3 * pk2 * pk3);
return B222+B321a+B321b+B411;
}
static real bloopfr(const PowerSpectrum& P_L, double vars[], double k1, double k2, double x, double k3, double p, double mu, double phi){
BSPTN bsptn;
double B411,B222,B321a,B321b,pkp,pk1,pk2,pk3,pka1,pka4,pka3;
double scalef = vars[4];
double omega0= vars[0];
double mg1= vars[1];
double mg2= vars[2];
double mg3= vars[3];
double epars[3];
epars[0]=vars[7];
epars[1]=vars[8];
epars[2]=1.; //vars[9];
double k2p,k2pp,k3p,ps,ka[8],xa[8],kargs[36];
double sx = (1.-pow2(x));
double k1s = pow2(k1);
double k2s = pow2(k2);
double k3s = pow2(k3);
kargs[5] = x;
ka[5] = k1;
ka[6] = k2;
ka[7] = k3;
kargs[9] = -(k1 + k2*x)/k3; // k1.k3
kargs[13] = -(k2 + k1*x)/k3; // k2.k3
ka[0] = p;
ps = pow2(p);
k2pp = sqrt(sx*(1.-pow2(mu)));
ka[1] = sqrt(k1s+ps-2.*p*k1*mu); // k1-p
xa[1] = (k1*mu-p)/ka[1]; // p. k1-p
xa[5] = mu;
kargs[1] = sqrt(k1s + ps + 2.*p*k1*mu); // p + k1
kargs[14] = -(k1*mu + p)/kargs[1]; // - p . k1+p
k2p = mu*x - k2pp*cos(phi*M_PI+M_PI); // k2.p
k3p = (-k1*mu-k2*k2p)/k3; // k3.p
ka[2] = sqrt(k2s+ps+2.*p*k2*k2p); // k2+p
ka[3] = sqrt(k2s + ps - 2.*k2*p*k2p); // k2 - p
ka[4] = sqrt(k3s + ps - 2.*k3*p*k3p); // k3-p
xa[0] = (k1*k2*x + k1*p*mu - p*k2*k2p - ps)/ka[1]/ka[2]; //k1-p . k2+p
xa[2] = -(k2*k2p+p)/ka[2]; //k2+p . -p
xa[3] = (k2*k2p - p)/ka[3]; // k2-p . p
xa[4] = (k3*k3p - p)/ka[4]; // k3-p.p
xa[6] = k2p;
xa[7] = k3p;
kargs[0] = sqrt(k2s + 4.*ps + 4.*k2*p*k2p); // k2 + 2p
kargs[2] = sqrt(k3s + ps + 2.*k3*p*k3p); // k3+p
kargs[3] = (k2*x - p*mu)/ka[3]; // k2-p . k1 = k2x - pu /k2mp
kargs[4] = (k2*p*k2p + k1*k2*x - ps -p*k1*mu)/kargs[1]/ka[3]; // k2-p . p+k1
kargs[6] = (k1*mu + k2*k2p - p)/kargs[2]; // p. -k3-p
kargs[7] = -(k1+k2*x+p*mu)/ka[4]; // k3-p. k1
kargs[8] = (k3*k1* kargs[9] + k3p*k3*p-p*k1*mu-ps)/ka[4]/kargs[1]; //k3-p.k1+p
kargs[10] = (k1*x+p*k2p)/kargs[1]; // k2.k1+p
kargs[11] = -(k2+k1*x+p*k2p)/ka[4]; // k3-p.k2
kargs[12] = (kargs[13]*k2*k3 -k2p*k2*p+ k3p*k3*p - ps)/ka[4]/ka[2]; // k2+p.k3-p
kargs[15] = (k1*x - p*k2p)/ka[1]; // k1-p.k2
kargs[16] = (k1*x + k2 - p*k2p)/kargs[2]; // k2. -k3-p
kargs[17] = (kargs[13]*k2*k3 - p*k3*k3p)/k3/ka[3]; // k2-p.k3
kargs[18] = (k2p*k2*p + kargs[13]*k3*k2 - ps -k3*p*k3p)/ka[3]/kargs[2]; // k2-p.p+k3
kargs[19] = -(k1*k2*x + k1s - k2*p*k2p - k1*p*mu)/ka[1]/k3; // k1-p . k3
kargs[20] = (k1*p*mu + k3*k1*kargs[9] - ps - p*k3*k3p)/kargs[2]/ka[1];// k1-p.p+k3
kargs[21] = (k2*x + p*mu)/ka[2]; // k1.k2+p
kargs[22] = (-k1s-k1*p*mu-k1*k2*x-k2*k2p*p)/kargs[1]/k3; // k1+p.k3
kargs[23] = (-k1*k2*x - k2s + k3p*p*k3)/k3/ka[2]; // k2+p.k3
kargs[24] = (-k1-k2*x+p*mu)/kargs[2];//k1.k3+p
kargs[25] = ps;
kargs[26] = pow2(ka[1]);
kargs[27] = pow2(ka[2]);
kargs[28] = pow2(ka[3]);
kargs[29] = pow2(ka[4]);
kargs[30] = k1s;
kargs[31] = k2s;
kargs[32] = k3s;
kargs[33] = pow2(kargs[0]);
kargs[34] = pow2(kargs[1]);
kargs[35] = pow2(kargs[2]);
pkp = P_L(p);
pk1 = P_L(k1);
pk2= P_L(k2);
pk3 = P_L(k3);
pka1 = P_L(ka[1]);
pka3 = P_L(ka[3]);
pka4 = P_L(ka[4]);
bsptn.initnb1_fr(scalef, ka, xa, kargs, omega0, mg1, mg2, mg3,epars);
B222 = 8.*ps*pkp*F2b_k13 * F2b_k12 * F2b_k23 * P_L(ka[2])* pka1;
B321a = 6.*ps*pkp*( F2b_12a * (pk1 * pk2 * F3b_2pp * F1b_1 + pk2 * pk1 * F3b_1pp * F1b_2)
+F2b_13a * (pk3 * pk1 * F3b_1pp * F1b_3 + pk1 * pk3 * F3b_3pp * F1b_1)
+F2b_23a * (pk3 * pk2 * F3b_2pp * F1b_3 + pk2 * pk3 * F3b_3pp * F1b_2));
B321b = 6.*ps*pkp*(pk1 * F1b_1 *(F2b_p2mp * F3b_12mp * pka3 + F2b_p3mp * F3b_13mp * pka4)
+ pk2 * F1b_2 *(F2b_k12 * F3b_21mp * pka1 + F2b_p3mp * F3b_23mp * pka4)
+ pk3 * F1b_3 *(F2b_k12 * F3b_31mp * pka1 + F2b_p2mp * F3b_32mp * pka3));
B411 = 12.*ps*pkp*(F4b_12pp * F1b_1 * F1b_2 * pk1 * pk2
+ F4b_13pp * F1b_1 * F1b_3 * pk1 * pk3
+ F4b_23pp * F1b_2 * F1b_3 * pk2 * pk3);
return B321a + B321b + B222 + B411 ;
}
// vars :
// 0 = omega0, 1 = mg1, 2=mg2, 3=mg3, 4=a, 5=which model , 6 = integration accuracy
double BSPT::Bloopn(double vars[], double k1, double k2, double x)const{
BSPTN bsptn;
IOW iow;
int check = vars[5];
double loop,tree,prefac;
double c[3] = {QMINp,-0.99999999,-1.};
double d[3] = {QMAXp,0.9999999,1.};
double k3 = sqrt(pow2(k1)+pow2(k2)+2.*k1*k2*x);
double ka[3],kargs[3],xa[3];
ka[0]=k1;
ka[1]=k2;
ka[2]=k3;
k3 = ka[2];
kargs[0] = k3;
kargs[1] = k2;
kargs[2] = k1;
xa[0] = -(k1*x+k2)/k3; // k2.k3
xa[1] = x; //k1.k2
xa[2] = -(k2*x+k1)/k3;// k1.k3
switch (check) {
case 1:
prefac = M_PI/pow3(pow2(dnorm_spt)*2.*M_PI);
if (k1<0.005 && k2 <0.005 && k3<0.005) {
bsptn.initnb0_dgp(vars[4], ka, xa, kargs, vars[0], vars[1], vars[2],vars[3]);
tree = 2./pow4(dnorm_spt)*(P_L(k1)*P_L(k2)*F1b_k1*F1b_k2*F2b_k12 + P_L(k3)*P_L(k1)*F1b_k1*F1b_k3*F2b_k13 + P_L(k2)*P_L(k3)*F1b_k2*F1b_k3*F2b_k23);
loop = 0.;
}
else{
loop = prefac*Integrate<3>(bind(bloopdgp,cref(P_L),vars,k1,k2,x,k3,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d, vars[6]);
tree = 2./pow4(dnorm_spt)*(P_L(k1)*P_L(k2)*F1b_1*F1b_2*F2b_12a + P_L(k3)*P_L(k1)*F1b_1*F1b_3*F2b_13a + P_L(k2)*P_L(k3)*F1b_2*F1b_3*F2b_23a);
}
return tree+loop;
case 2:
prefac = M_PI/pow3(pow2(dnorm_spt)*2.*M_PI);
if (k1<0.005 && k2 <0.005 && k3<0.005) {
bsptn.initnb0_fofr(vars[4], ka, xa, kargs, vars[0], vars[1], vars[2],vars[3]);
loop = 0.;
tree = 2./pow4(dnorm_spt)*(P_L(k1)*P_L(k2)*F1b_k1*F1b_k2*F2b_k12 + P_L(k3)*P_L(k1)*F1b_k1*F1b_k3*F2b_k13 + P_L(k2)*P_L(k3)*F1b_k2*F1b_k3*F2b_k23);
}
else{
loop = prefac*Integrate<3>(bind(bloopfr,cref(P_L),vars,k1,k2,x,k3,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3), c, d, vars[6]);
tree = 2./pow4(dnorm_spt)*(P_L(k1)*P_L(k2)*F1b_1*F1b_2*F2b_12a + P_L(k3)*P_L(k1)*F1b_1*F1b_3*F2b_13a + P_L(k2)*P_L(k3)*F1b_2*F1b_3*F2b_23a);
}
return tree+loop;
default:
warning("BSPT: invalid indices, a = %d \n", check);
return 0;
}
}
|
// Note: This test requires the SysV AMD64 ABI to be in use, and requires
// compiler support for DWARF entry values.
// Inhibit dead-arg-elim by using 'x'.
template<typename T> __attribute__((noinline)) void use(T x) {
asm volatile (""
/* Outputs */ :
/* Inputs */ : "g"(x)
/* Clobbers */ :
);
}
// Destroy %rsi in the current frame.
#define DESTROY_RSI \
asm volatile ("xorq %%rsi, %%rsi" \
/* Outputs */ : \
/* Inputs */ : \
/* Clobbers */ : "rsi" \
);
struct S1 {
int field1 = 123;
int *field2 = &field1;
};
__attribute__((noinline))
void func1(int &sink, int x) {
use(x);
// Destroy 'x' in the current frame.
DESTROY_RSI;
//% self.filecheck("image lookup -va $pc", "main.cpp", "-check-prefix=FUNC1-DESC")
// FUNC1-DESC: name = "x", type = "int", location = DW_OP_entry_value(DW_OP_reg4 RSI)
++sink;
}
__attribute__((noinline))
void func2(int &sink, int x) {
use(x);
// Destroy 'x' in the current frame.
DESTROY_RSI;
//% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC2-EXPR")
// FUNC2-EXPR: (int) ${{.*}} = 123
++sink;
}
__attribute__((noinline))
void func3(int &sink, int *p) {
use(p);
// Destroy 'p' in the current frame.
DESTROY_RSI;
//% self.filecheck("expr *p", "main.cpp", "-check-prefix=FUNC3-EXPR")
// FUNC3-EXPR: (int) ${{.*}} = 123
++sink;
}
__attribute__((noinline))
void func4_amb(int &sink, int x) {
use(x);
// Destroy 'x' in the current frame.
DESTROY_RSI;
//% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC4-EXPR", expect_cmd_failure=True)
// FUNC4-EXPR: couldn't get the value of variable x: Could not evaluate DW_OP_entry_value.
++sink;
}
__attribute__((noinline))
void func5_amb() {}
__attribute__((noinline))
void func6(int &sink, int x) {
if (sink > 0)
func4_amb(sink, x); /* tail (taken) */
else
func5_amb(); /* tail */
}
__attribute__((noinline))
void func7(int &sink, int x) {
//% self.filecheck("bt", "main.cpp", "-check-prefix=FUNC7-BT")
// FUNC7-BT: func7
// FUNC7-BT-NEXT: [inlined] func8_inlined
// FUNC7-BT-NEXT: [inlined] func9_inlined
// FUNC7-BT-NEXT: func10
use(x);
// Destroy 'x' in the current frame.
DESTROY_RSI;
//% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC7-EXPR")
// FUNC7-EXPR: (int) ${{.*}} = 123
++sink;
}
__attribute__((always_inline))
void func8_inlined(int &sink, int x) {
func7(sink, x);
}
__attribute__((always_inline))
void func9_inlined(int &sink, int x) {
func8_inlined(sink, x);
}
__attribute__((noinline, disable_tail_calls))
void func10(int &sink, int x) {
func9_inlined(sink, x);
}
__attribute__((noinline))
void func11_tailcalled(int &sink, int x) {
//% self.filecheck("bt", "main.cpp", "-check-prefix=FUNC11-BT")
// FUNC11-BT: func11_tailcalled{{.*}}
// FUNC11-BT-NEXT: func12{{.*}} [artificial]
use(x);
// Destroy 'x' in the current frame.
DESTROY_RSI;
//% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC11-EXPR")
// FUNC11-EXPR: (int) ${{.*}} = 123
++sink;
}
__attribute__((noinline))
void func12(int &sink, int x) {
func11_tailcalled(sink, x);
}
__attribute__((noinline))
void func13(int &sink, int x) {
//% self.filecheck("bt", "main.cpp", "-check-prefix=FUNC13-BT")
// FUNC13-BT: func13{{.*}}
// FUNC13-BT-NEXT: func14{{.*}}
use(x);
// Destroy 'x' in the current frame.
DESTROY_RSI;
//% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC13-EXPR")
// FUNC13-EXPR: (int) ${{.*}} = 123
++sink;
}
__attribute__((noinline, disable_tail_calls))
void func14(int &sink, void (*target_no_tailcall)(int &, int)) {
// Move the call target into a register that won't get clobbered. Do this
// by calling the same indirect target twice, and hoping that regalloc is
// 'smart' enough to stash the call target in a non-clobbered register.
//
// llvm.org/PR43926 tracks work in the compiler to emit call targets which
// describe non-clobbered values.
target_no_tailcall(sink, 123);
target_no_tailcall(sink, 123);
}
__attribute__((disable_tail_calls))
int main() {
int sink = 0;
S1 s1;
// Test location dumping for DW_OP_entry_value.
func1(sink, 123);
// Test evaluation of "DW_OP_constu" in the parent frame.
func2(sink, 123);
// Test evaluation of "DW_OP_fbreg -24, DW_OP_deref" in the parent frame.
// Disabled for now, see: llvm.org/PR43343
#if 0
func3(sink, s1.field2);
#endif
// The sequences `main -> func4 -> func{5,6}_amb -> sink` are both plausible.
// Test that lldb doesn't attempt to guess which one occurred: entry value
// evaluation should fail.
func6(sink, 123);
// Test that evaluation can "see through" inlining.
func10(sink, 123);
// Test that evaluation can "see through" tail calls.
func12(sink, 123);
// Test that evaluation can "see through" an indirect tail call.
func14(sink, func13);
return 0;
}
|
// Copyright 2014 the V8 project 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 "src/heap/gc-tracer.h"
#include <cstdarg>
#include "include/v8-metrics.h"
#include "src/base/atomic-utils.h"
#include "src/base/strings.h"
#include "src/common/globals.h"
#include "src/execution/isolate.h"
#include "src/execution/thread-id.h"
#include "src/heap/cppgc-js/cpp-heap.h"
#include "src/heap/cppgc/metric-recorder.h"
#include "src/heap/heap-inl.h"
#include "src/heap/incremental-marking.h"
#include "src/heap/spaces.h"
#include "src/logging/counters.h"
#include "src/logging/metrics.h"
#include "src/logging/tracing-flags.h"
#include "src/tracing/tracing-category-observer.h"
namespace v8 {
namespace internal {
static size_t CountTotalHolesSize(Heap* heap) {
size_t holes_size = 0;
PagedSpaceIterator spaces(heap);
for (PagedSpace* space = spaces.Next(); space != nullptr;
space = spaces.Next()) {
DCHECK_GE(holes_size + space->Waste() + space->Available(), holes_size);
holes_size += space->Waste() + space->Available();
}
return holes_size;
}
#ifdef V8_RUNTIME_CALL_STATS
WorkerThreadRuntimeCallStats* GCTracer::worker_thread_runtime_call_stats() {
return heap_->isolate()->counters()->worker_thread_runtime_call_stats();
}
RuntimeCallCounterId GCTracer::RCSCounterFromScope(Scope::ScopeId id) {
STATIC_ASSERT(Scope::FIRST_SCOPE == Scope::MC_INCREMENTAL);
return static_cast<RuntimeCallCounterId>(
static_cast<int>(RuntimeCallCounterId::kGC_MC_INCREMENTAL) +
static_cast<int>(id));
}
#endif // defined(V8_RUNTIME_CALL_STATS)
double GCTracer::MonotonicallyIncreasingTimeInMs() {
if (V8_UNLIKELY(FLAG_predictable)) {
return heap_->MonotonicallyIncreasingTimeInMs();
} else {
return base::TimeTicks::Now().ToInternalValue() /
static_cast<double>(base::Time::kMicrosecondsPerMillisecond);
}
}
CollectionEpoch GCTracer::CurrentEpoch(Scope::ScopeId scope_id) {
if (Scope::NeedsYoungEpoch(scope_id)) {
return heap_->epoch_young();
} else {
return heap_->epoch_full();
}
}
GCTracer::Scope::Scope(GCTracer* tracer, ScopeId scope, ThreadKind thread_kind)
: tracer_(tracer), scope_(scope), thread_kind_(thread_kind) {
start_time_ = tracer_->MonotonicallyIncreasingTimeInMs();
#ifdef V8_RUNTIME_CALL_STATS
if (V8_LIKELY(!TracingFlags::is_runtime_stats_enabled())) return;
if (thread_kind_ == ThreadKind::kMain) {
#if DEBUG
AssertMainThread();
#endif // DEBUG
runtime_stats_ =
tracer_->heap_->isolate()->counters()->runtime_call_stats();
runtime_stats_->Enter(&timer_, GCTracer::RCSCounterFromScope(scope));
} else {
runtime_call_stats_scope_.emplace(
tracer->worker_thread_runtime_call_stats());
runtime_stats_ = runtime_call_stats_scope_->Get();
runtime_stats_->Enter(&timer_, GCTracer::RCSCounterFromScope(scope));
}
#endif // defined(V8_RUNTIME_CALL_STATS)
}
GCTracer::Scope::~Scope() {
double duration_ms = tracer_->MonotonicallyIncreasingTimeInMs() - start_time_;
if (thread_kind_ == ThreadKind::kMain) {
#if DEBUG
AssertMainThread();
#endif // DEBUG
tracer_->AddScopeSample(scope_, duration_ms);
if (scope_ == ScopeId::MC_INCREMENTAL ||
scope_ == ScopeId::MC_INCREMENTAL_START ||
scope_ == ScopeId::MC_INCREMENTAL_FINALIZE) {
auto* long_task_stats =
tracer_->heap_->isolate()->GetCurrentLongTaskStats();
long_task_stats->gc_full_incremental_wall_clock_duration_us +=
static_cast<int64_t>(duration_ms *
base::Time::kMicrosecondsPerMillisecond);
}
} else {
tracer_->AddScopeSampleBackground(scope_, duration_ms);
}
#ifdef V8_RUNTIME_CALL_STATS
if (V8_LIKELY(runtime_stats_ == nullptr)) return;
runtime_stats_->Leave(&timer_);
#endif // defined(V8_RUNTIME_CALL_STATS)
}
#if DEBUG
void GCTracer::Scope::AssertMainThread() {
Isolate* isolate = tracer_->heap_->isolate();
Isolate* shared_isolate = isolate->shared_isolate();
ThreadId thread_id = ThreadId::Current();
// Either run on isolate's main thread or on the current main thread of the
// shared isolate during shared GCs.
DCHECK(isolate->thread_id() == thread_id ||
(shared_isolate && shared_isolate->thread_id() == thread_id));
}
#endif // DEBUG
const char* GCTracer::Scope::Name(ScopeId id) {
#define CASE(scope) \
case Scope::scope: \
return "V8.GC_" #scope;
switch (id) {
TRACER_SCOPES(CASE)
TRACER_BACKGROUND_SCOPES(CASE)
case Scope::NUMBER_OF_SCOPES:
break;
}
#undef CASE
UNREACHABLE();
}
bool GCTracer::Scope::NeedsYoungEpoch(ScopeId id) {
#define CASE(scope) \
case Scope::scope: \
return true;
switch (id) {
TRACER_YOUNG_EPOCH_SCOPES(CASE)
default:
return false;
}
#undef CASE
UNREACHABLE();
}
GCTracer::Event::Event(Type type, GarbageCollectionReason gc_reason,
const char* collector_reason)
: type(type),
gc_reason(gc_reason),
collector_reason(collector_reason),
start_time(0.0),
end_time(0.0),
reduce_memory(false),
start_object_size(0),
end_object_size(0),
start_memory_size(0),
end_memory_size(0),
start_holes_size(0),
end_holes_size(0),
young_object_size(0),
survived_young_object_size(0),
incremental_marking_bytes(0),
incremental_marking_duration(0.0) {
for (int i = 0; i < Scope::NUMBER_OF_SCOPES; i++) {
scopes[i] = 0;
}
}
const char* GCTracer::Event::TypeName(bool short_name) const {
switch (type) {
case SCAVENGER:
return (short_name) ? "s" : "Scavenge";
case MARK_COMPACTOR:
case INCREMENTAL_MARK_COMPACTOR:
return (short_name) ? "ms" : "Mark-sweep";
case MINOR_MARK_COMPACTOR:
return (short_name) ? "mmc" : "Minor Mark-Compact";
case START:
return (short_name) ? "st" : "Start";
}
return "Unknown Event Type";
}
GCTracer::GCTracer(Heap* heap)
: heap_(heap),
current_(Event::START, GarbageCollectionReason::kUnknown, nullptr),
previous_(current_),
incremental_marking_bytes_(0),
incremental_marking_duration_(0.0),
incremental_marking_start_time_(0.0),
recorded_incremental_marking_speed_(0.0),
allocation_time_ms_(0.0),
new_space_allocation_counter_bytes_(0),
old_generation_allocation_counter_bytes_(0),
embedder_allocation_counter_bytes_(0),
allocation_duration_since_gc_(0.0),
new_space_allocation_in_bytes_since_gc_(0),
old_generation_allocation_in_bytes_since_gc_(0),
embedder_allocation_in_bytes_since_gc_(0),
combined_mark_compact_speed_cache_(0.0),
start_counter_(0),
average_mutator_duration_(0),
average_mark_compact_duration_(0),
current_mark_compact_mutator_utilization_(1.0),
previous_mark_compact_end_time_(0) {
// All accesses to incremental_marking_scope assume that incremental marking
// scopes come first.
STATIC_ASSERT(0 == Scope::FIRST_INCREMENTAL_SCOPE);
// We assume that MC_INCREMENTAL is the first scope so that we can properly
// map it to RuntimeCallStats.
STATIC_ASSERT(0 == Scope::MC_INCREMENTAL);
current_.end_time = MonotonicallyIncreasingTimeInMs();
for (int i = 0; i < Scope::NUMBER_OF_SCOPES; i++) {
background_counter_[i].total_duration_ms = 0;
}
}
void GCTracer::ResetForTesting() {
current_ = Event(Event::START, GarbageCollectionReason::kTesting, nullptr);
current_.end_time = MonotonicallyIncreasingTimeInMs();
previous_ = current_;
ResetIncrementalMarkingCounters();
allocation_time_ms_ = 0.0;
new_space_allocation_counter_bytes_ = 0.0;
old_generation_allocation_counter_bytes_ = 0.0;
allocation_duration_since_gc_ = 0.0;
new_space_allocation_in_bytes_since_gc_ = 0.0;
old_generation_allocation_in_bytes_since_gc_ = 0.0;
combined_mark_compact_speed_cache_ = 0.0;
recorded_minor_gcs_total_.Reset();
recorded_minor_gcs_survived_.Reset();
recorded_compactions_.Reset();
recorded_mark_compacts_.Reset();
recorded_incremental_mark_compacts_.Reset();
recorded_new_generation_allocations_.Reset();
recorded_old_generation_allocations_.Reset();
recorded_embedder_generation_allocations_.Reset();
recorded_survival_ratios_.Reset();
start_counter_ = 0;
average_mutator_duration_ = 0;
average_mark_compact_duration_ = 0;
current_mark_compact_mutator_utilization_ = 1.0;
previous_mark_compact_end_time_ = 0;
base::MutexGuard guard(&background_counter_mutex_);
for (int i = 0; i < Scope::NUMBER_OF_SCOPES; i++) {
background_counter_[i].total_duration_ms = 0;
}
}
void GCTracer::NotifyYoungGenerationHandling(
YoungGenerationHandling young_generation_handling) {
DCHECK(current_.type == Event::SCAVENGER || start_counter_ > 1);
heap_->isolate()->counters()->young_generation_handling()->AddSample(
static_cast<int>(young_generation_handling));
}
void GCTracer::Start(GarbageCollector collector,
GarbageCollectionReason gc_reason,
const char* collector_reason) {
start_counter_++;
if (start_counter_ != 1) return;
previous_ = current_;
switch (collector) {
case GarbageCollector::SCAVENGER:
current_ = Event(Event::SCAVENGER, gc_reason, collector_reason);
break;
case GarbageCollector::MINOR_MARK_COMPACTOR:
current_ =
Event(Event::MINOR_MARK_COMPACTOR, gc_reason, collector_reason);
break;
case GarbageCollector::MARK_COMPACTOR:
if (heap_->incremental_marking()->WasActivated()) {
current_ = Event(Event::INCREMENTAL_MARK_COMPACTOR, gc_reason,
collector_reason);
} else {
current_ = Event(Event::MARK_COMPACTOR, gc_reason, collector_reason);
}
break;
}
current_.reduce_memory = heap_->ShouldReduceMemory();
current_.start_time = MonotonicallyIncreasingTimeInMs();
current_.start_object_size = 0;
current_.start_memory_size = 0;
current_.start_holes_size = 0;
current_.young_object_size = 0;
current_.incremental_marking_bytes = 0;
current_.incremental_marking_duration = 0;
for (int i = 0; i < Scope::NUMBER_OF_SCOPES; i++) {
current_.scopes[i] = 0;
}
Counters* counters = heap_->isolate()->counters();
if (Heap::IsYoungGenerationCollector(collector)) {
counters->scavenge_reason()->AddSample(static_cast<int>(gc_reason));
} else {
counters->mark_compact_reason()->AddSample(static_cast<int>(gc_reason));
if (FLAG_trace_gc_freelists) {
PrintIsolate(heap_->isolate(),
"FreeLists statistics before collection:\n");
heap_->PrintFreeListsStats();
}
}
}
void GCTracer::StartInSafepoint() {
SampleAllocation(current_.start_time, heap_->NewSpaceAllocationCounter(),
heap_->OldGenerationAllocationCounter(),
heap_->EmbedderAllocationCounter());
current_.start_object_size = heap_->SizeOfObjects();
current_.start_memory_size = heap_->memory_allocator()->Size();
current_.start_holes_size = CountTotalHolesSize(heap_);
size_t new_space_size = (heap_->new_space() ? heap_->new_space()->Size() : 0);
size_t new_lo_space_size =
(heap_->new_lo_space() ? heap_->new_lo_space()->SizeOfObjects() : 0);
current_.young_object_size = new_space_size + new_lo_space_size;
}
void GCTracer::ResetIncrementalMarkingCounters() {
incremental_marking_bytes_ = 0;
incremental_marking_duration_ = 0;
for (int i = 0; i < Scope::NUMBER_OF_INCREMENTAL_SCOPES; i++) {
incremental_marking_scopes_[i].ResetCurrentCycle();
}
}
void GCTracer::StopInSafepoint() {
current_.end_object_size = heap_->SizeOfObjects();
current_.end_memory_size = heap_->memory_allocator()->Size();
current_.end_holes_size = CountTotalHolesSize(heap_);
current_.survived_young_object_size = heap_->SurvivedYoungObjectSize();
}
void GCTracer::Stop(GarbageCollector collector) {
start_counter_--;
if (start_counter_ != 0) {
if (FLAG_trace_gc_verbose) {
heap_->isolate()->PrintWithTimestamp(
"[Finished reentrant %s during %s.]\n",
Heap::CollectorName(collector), current_.TypeName(false));
}
return;
}
DCHECK_LE(0, start_counter_);
DCHECK((collector == GarbageCollector::SCAVENGER &&
current_.type == Event::SCAVENGER) ||
(collector == GarbageCollector::MINOR_MARK_COMPACTOR &&
current_.type == Event::MINOR_MARK_COMPACTOR) ||
(collector == GarbageCollector::MARK_COMPACTOR &&
(current_.type == Event::MARK_COMPACTOR ||
current_.type == Event::INCREMENTAL_MARK_COMPACTOR)));
current_.end_time = MonotonicallyIncreasingTimeInMs();
AddAllocation(current_.end_time);
double duration = current_.end_time - current_.start_time;
int64_t duration_us =
static_cast<int64_t>(duration * base::Time::kMicrosecondsPerMillisecond);
auto* long_task_stats = heap_->isolate()->GetCurrentLongTaskStats();
switch (current_.type) {
case Event::SCAVENGER:
case Event::MINOR_MARK_COMPACTOR:
recorded_minor_gcs_total_.Push(
MakeBytesAndDuration(current_.young_object_size, duration));
recorded_minor_gcs_survived_.Push(
MakeBytesAndDuration(current_.survived_young_object_size, duration));
FetchBackgroundMinorGCCounters();
long_task_stats->gc_young_wall_clock_duration_us += duration_us;
break;
case Event::INCREMENTAL_MARK_COMPACTOR:
current_.incremental_marking_bytes = incremental_marking_bytes_;
current_.incremental_marking_duration = incremental_marking_duration_;
for (int i = 0; i < Scope::NUMBER_OF_INCREMENTAL_SCOPES; i++) {
current_.incremental_marking_scopes[i] = incremental_marking_scopes_[i];
current_.scopes[i] = incremental_marking_scopes_[i].duration;
}
RecordMutatorUtilization(
current_.end_time, duration + current_.incremental_marking_duration);
RecordIncrementalMarkingSpeed(current_.incremental_marking_bytes,
current_.incremental_marking_duration);
recorded_incremental_mark_compacts_.Push(
MakeBytesAndDuration(current_.end_object_size, duration));
RecordGCSumCounters(duration);
ResetIncrementalMarkingCounters();
combined_mark_compact_speed_cache_ = 0.0;
FetchBackgroundMarkCompactCounters();
long_task_stats->gc_full_atomic_wall_clock_duration_us += duration_us;
break;
case Event::MARK_COMPACTOR:
DCHECK_EQ(0u, current_.incremental_marking_bytes);
DCHECK_EQ(0, current_.incremental_marking_duration);
RecordMutatorUtilization(
current_.end_time, duration + current_.incremental_marking_duration);
recorded_mark_compacts_.Push(
MakeBytesAndDuration(current_.end_object_size, duration));
RecordGCSumCounters(duration);
ResetIncrementalMarkingCounters();
combined_mark_compact_speed_cache_ = 0.0;
FetchBackgroundMarkCompactCounters();
long_task_stats->gc_full_atomic_wall_clock_duration_us += duration_us;
break;
case Event::START:
UNREACHABLE();
}
FetchBackgroundGeneralCounters();
heap_->UpdateTotalGCTime(duration);
if (current_.type == Event::SCAVENGER ||
current_.type == Event::MINOR_MARK_COMPACTOR) {
ReportYoungCycleToRecorder();
if (FLAG_trace_gc_ignore_scavenger) return;
}
if (FLAG_trace_gc_nvp) {
PrintNVP();
} else {
Print();
}
if (FLAG_trace_gc) {
heap_->PrintShortHeapStatistics();
}
if (V8_UNLIKELY(TracingFlags::gc.load(std::memory_order_relaxed) &
v8::tracing::TracingCategoryObserver::ENABLED_BY_TRACING)) {
std::stringstream heap_stats;
heap_->DumpJSONHeapStatistics(heap_stats);
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "V8.GC_Heap_Stats",
TRACE_EVENT_SCOPE_THREAD, "stats",
TRACE_STR_COPY(heap_stats.str().c_str()));
}
}
void GCTracer::NotifySweepingCompleted() {
if (FLAG_trace_gc_freelists) {
PrintIsolate(heap_->isolate(),
"FreeLists statistics after sweeping completed:\n");
heap_->PrintFreeListsStats();
}
if (FLAG_trace_allocations_origins) {
heap_->new_space()->PrintAllocationsOrigins();
heap_->old_space()->PrintAllocationsOrigins();
heap_->code_space()->PrintAllocationsOrigins();
heap_->map_space()->PrintAllocationsOrigins();
}
metrics_report_pending_ = true;
NotifyGCCompleted();
}
void GCTracer::SampleAllocation(double current_ms,
size_t new_space_counter_bytes,
size_t old_generation_counter_bytes,
size_t embedder_counter_bytes) {
if (allocation_time_ms_ == 0) {
// It is the first sample.
allocation_time_ms_ = current_ms;
new_space_allocation_counter_bytes_ = new_space_counter_bytes;
old_generation_allocation_counter_bytes_ = old_generation_counter_bytes;
embedder_allocation_counter_bytes_ = embedder_counter_bytes;
return;
}
// This assumes that counters are unsigned integers so that the subtraction
// below works even if the new counter is less than the old counter.
size_t new_space_allocated_bytes =
new_space_counter_bytes - new_space_allocation_counter_bytes_;
size_t old_generation_allocated_bytes =
old_generation_counter_bytes - old_generation_allocation_counter_bytes_;
size_t embedder_allocated_bytes =
embedder_counter_bytes - embedder_allocation_counter_bytes_;
double duration = current_ms - allocation_time_ms_;
allocation_time_ms_ = current_ms;
new_space_allocation_counter_bytes_ = new_space_counter_bytes;
old_generation_allocation_counter_bytes_ = old_generation_counter_bytes;
embedder_allocation_counter_bytes_ = embedder_counter_bytes;
allocation_duration_since_gc_ += duration;
new_space_allocation_in_bytes_since_gc_ += new_space_allocated_bytes;
old_generation_allocation_in_bytes_since_gc_ +=
old_generation_allocated_bytes;
embedder_allocation_in_bytes_since_gc_ += embedder_allocated_bytes;
}
void GCTracer::AddAllocation(double current_ms) {
allocation_time_ms_ = current_ms;
if (allocation_duration_since_gc_ > 0) {
recorded_new_generation_allocations_.Push(
MakeBytesAndDuration(new_space_allocation_in_bytes_since_gc_,
allocation_duration_since_gc_));
recorded_old_generation_allocations_.Push(
MakeBytesAndDuration(old_generation_allocation_in_bytes_since_gc_,
allocation_duration_since_gc_));
recorded_embedder_generation_allocations_.Push(MakeBytesAndDuration(
embedder_allocation_in_bytes_since_gc_, allocation_duration_since_gc_));
}
allocation_duration_since_gc_ = 0;
new_space_allocation_in_bytes_since_gc_ = 0;
old_generation_allocation_in_bytes_since_gc_ = 0;
embedder_allocation_in_bytes_since_gc_ = 0;
}
void GCTracer::AddCompactionEvent(double duration,
size_t live_bytes_compacted) {
recorded_compactions_.Push(
MakeBytesAndDuration(live_bytes_compacted, duration));
}
void GCTracer::AddSurvivalRatio(double promotion_ratio) {
recorded_survival_ratios_.Push(promotion_ratio);
}
void GCTracer::AddIncrementalMarkingStep(double duration, size_t bytes) {
if (bytes > 0) {
incremental_marking_bytes_ += bytes;
incremental_marking_duration_ += duration;
}
ReportIncrementalMarkingStepToRecorder();
}
void GCTracer::Output(const char* format, ...) const {
if (FLAG_trace_gc) {
va_list arguments;
va_start(arguments, format);
base::OS::VPrint(format, arguments);
va_end(arguments);
}
const int kBufferSize = 256;
char raw_buffer[kBufferSize];
base::Vector<char> buffer(raw_buffer, kBufferSize);
va_list arguments2;
va_start(arguments2, format);
base::VSNPrintF(buffer, format, arguments2);
va_end(arguments2);
heap_->AddToRingBuffer(buffer.begin());
}
void GCTracer::Print() const {
double duration = current_.end_time - current_.start_time;
const size_t kIncrementalStatsSize = 128;
char incremental_buffer[kIncrementalStatsSize] = {0};
if (current_.type == Event::INCREMENTAL_MARK_COMPACTOR) {
base::OS::SNPrintF(
incremental_buffer, kIncrementalStatsSize,
" (+ %.1f ms in %d steps since start of marking, "
"biggest step %.1f ms, walltime since start of marking %.f ms)",
current_.scopes[Scope::MC_INCREMENTAL],
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL].steps,
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL].longest_step,
current_.end_time - incremental_marking_start_time_);
}
// Avoid PrintF as Output also appends the string to the tracing ring buffer
// that gets printed on OOM failures.
Output(
"[%d:%p] "
"%8.0f ms: "
"%s%s%s %.1f (%.1f) -> %.1f (%.1f) MB, "
"%.1f / %.1f ms %s (average mu = %.3f, current mu = %.3f) %s; %s\n",
base::OS::GetCurrentProcessId(),
reinterpret_cast<void*>(heap_->isolate()),
heap_->isolate()->time_millis_since_init(),
heap_->IsShared() ? "Shared " : "", current_.TypeName(false),
current_.reduce_memory ? " (reduce)" : "",
static_cast<double>(current_.start_object_size) / MB,
static_cast<double>(current_.start_memory_size) / MB,
static_cast<double>(current_.end_object_size) / MB,
static_cast<double>(current_.end_memory_size) / MB, duration,
TotalExternalTime(), incremental_buffer,
AverageMarkCompactMutatorUtilization(),
CurrentMarkCompactMutatorUtilization(),
Heap::GarbageCollectionReasonToString(current_.gc_reason),
current_.collector_reason != nullptr ? current_.collector_reason : "");
}
void GCTracer::PrintNVP() const {
double duration = current_.end_time - current_.start_time;
double spent_in_mutator = current_.start_time - previous_.end_time;
size_t allocated_since_last_gc =
current_.start_object_size - previous_.end_object_size;
double incremental_walltime_duration = 0;
if (current_.type == Event::INCREMENTAL_MARK_COMPACTOR) {
incremental_walltime_duration =
current_.end_time - incremental_marking_start_time_;
}
switch (current_.type) {
case Event::SCAVENGER:
heap_->isolate()->PrintWithTimestamp(
"pause=%.1f "
"mutator=%.1f "
"gc=%s "
"reduce_memory=%d "
"time_to_safepoint=%.2f "
"heap.prologue=%.2f "
"heap.epilogue=%.2f "
"heap.epilogue.reduce_new_space=%.2f "
"heap.external.prologue=%.2f "
"heap.external.epilogue=%.2f "
"heap.external_weak_global_handles=%.2f "
"fast_promote=%.2f "
"complete.sweep_array_buffers=%.2f "
"scavenge=%.2f "
"scavenge.free_remembered_set=%.2f "
"scavenge.roots=%.2f "
"scavenge.weak=%.2f "
"scavenge.weak_global_handles.identify=%.2f "
"scavenge.weak_global_handles.process=%.2f "
"scavenge.parallel=%.2f "
"scavenge.update_refs=%.2f "
"scavenge.sweep_array_buffers=%.2f "
"background.scavenge.parallel=%.2f "
"background.unmapper=%.2f "
"unmapper=%.2f "
"incremental.steps_count=%d "
"incremental.steps_took=%.1f "
"scavenge_throughput=%.f "
"total_size_before=%zu "
"total_size_after=%zu "
"holes_size_before=%zu "
"holes_size_after=%zu "
"allocated=%zu "
"promoted=%zu "
"semi_space_copied=%zu "
"nodes_died_in_new=%d "
"nodes_copied_in_new=%d "
"nodes_promoted=%d "
"promotion_ratio=%.1f%% "
"average_survival_ratio=%.1f%% "
"promotion_rate=%.1f%% "
"semi_space_copy_rate=%.1f%% "
"new_space_allocation_throughput=%.1f "
"unmapper_chunks=%d\n",
duration, spent_in_mutator, current_.TypeName(true),
current_.reduce_memory, current_.scopes[Scope::TIME_TO_SAFEPOINT],
current_.scopes[Scope::HEAP_PROLOGUE],
current_.scopes[Scope::HEAP_EPILOGUE],
current_.scopes[Scope::HEAP_EPILOGUE_REDUCE_NEW_SPACE],
current_.scopes[Scope::HEAP_EXTERNAL_PROLOGUE],
current_.scopes[Scope::HEAP_EXTERNAL_EPILOGUE],
current_.scopes[Scope::HEAP_EXTERNAL_WEAK_GLOBAL_HANDLES],
current_.scopes[Scope::SCAVENGER_FAST_PROMOTE],
current_.scopes[Scope::SCAVENGER_COMPLETE_SWEEP_ARRAY_BUFFERS],
current_.scopes[Scope::SCAVENGER_SCAVENGE],
current_.scopes[Scope::SCAVENGER_FREE_REMEMBERED_SET],
current_.scopes[Scope::SCAVENGER_SCAVENGE_ROOTS],
current_.scopes[Scope::SCAVENGER_SCAVENGE_WEAK],
current_
.scopes[Scope::SCAVENGER_SCAVENGE_WEAK_GLOBAL_HANDLES_IDENTIFY],
current_
.scopes[Scope::SCAVENGER_SCAVENGE_WEAK_GLOBAL_HANDLES_PROCESS],
current_.scopes[Scope::SCAVENGER_SCAVENGE_PARALLEL],
current_.scopes[Scope::SCAVENGER_SCAVENGE_UPDATE_REFS],
current_.scopes[Scope::SCAVENGER_SWEEP_ARRAY_BUFFERS],
current_.scopes[Scope::SCAVENGER_BACKGROUND_SCAVENGE_PARALLEL],
current_.scopes[Scope::BACKGROUND_UNMAPPER],
current_.scopes[Scope::UNMAPPER],
current_.incremental_marking_scopes[GCTracer::Scope::MC_INCREMENTAL]
.steps,
current_.scopes[Scope::MC_INCREMENTAL],
ScavengeSpeedInBytesPerMillisecond(), current_.start_object_size,
current_.end_object_size, current_.start_holes_size,
current_.end_holes_size, allocated_since_last_gc,
heap_->promoted_objects_size(),
heap_->semi_space_copied_object_size(),
heap_->nodes_died_in_new_space_, heap_->nodes_copied_in_new_space_,
heap_->nodes_promoted_, heap_->promotion_ratio_,
AverageSurvivalRatio(), heap_->promotion_rate_,
heap_->semi_space_copied_rate_,
NewSpaceAllocationThroughputInBytesPerMillisecond(),
heap_->memory_allocator()->unmapper()->NumberOfChunks());
break;
case Event::MINOR_MARK_COMPACTOR:
heap_->isolate()->PrintWithTimestamp(
"pause=%.1f "
"mutator=%.1f "
"gc=%s "
"reduce_memory=%d "
"minor_mc=%.2f "
"finish_sweeping=%.2f "
"time_to_safepoint=%.2f "
"mark=%.2f "
"mark.seed=%.2f "
"mark.roots=%.2f "
"mark.weak=%.2f "
"mark.global_handles=%.2f "
"clear=%.2f "
"clear.string_table=%.2f "
"clear.weak_lists=%.2f "
"evacuate=%.2f "
"evacuate.copy=%.2f "
"evacuate.update_pointers=%.2f "
"evacuate.update_pointers.to_new_roots=%.2f "
"evacuate.update_pointers.slots=%.2f "
"background.mark=%.2f "
"background.evacuate.copy=%.2f "
"background.evacuate.update_pointers=%.2f "
"background.unmapper=%.2f "
"unmapper=%.2f "
"update_marking_deque=%.2f "
"reset_liveness=%.2f\n",
duration, spent_in_mutator, "mmc", current_.reduce_memory,
current_.scopes[Scope::MINOR_MC],
current_.scopes[Scope::MINOR_MC_SWEEPING],
current_.scopes[Scope::TIME_TO_SAFEPOINT],
current_.scopes[Scope::MINOR_MC_MARK],
current_.scopes[Scope::MINOR_MC_MARK_SEED],
current_.scopes[Scope::MINOR_MC_MARK_ROOTS],
current_.scopes[Scope::MINOR_MC_MARK_WEAK],
current_.scopes[Scope::MINOR_MC_MARK_GLOBAL_HANDLES],
current_.scopes[Scope::MINOR_MC_CLEAR],
current_.scopes[Scope::MINOR_MC_CLEAR_STRING_TABLE],
current_.scopes[Scope::MINOR_MC_CLEAR_WEAK_LISTS],
current_.scopes[Scope::MINOR_MC_EVACUATE],
current_.scopes[Scope::MINOR_MC_EVACUATE_COPY],
current_.scopes[Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS],
current_
.scopes[Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS_TO_NEW_ROOTS],
current_.scopes[Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS_SLOTS],
current_.scopes[Scope::MINOR_MC_BACKGROUND_MARKING],
current_.scopes[Scope::MINOR_MC_BACKGROUND_EVACUATE_COPY],
current_.scopes[Scope::MINOR_MC_BACKGROUND_EVACUATE_UPDATE_POINTERS],
current_.scopes[Scope::BACKGROUND_UNMAPPER],
current_.scopes[Scope::UNMAPPER],
current_.scopes[Scope::MINOR_MC_MARKING_DEQUE],
current_.scopes[Scope::MINOR_MC_RESET_LIVENESS]);
break;
case Event::MARK_COMPACTOR:
case Event::INCREMENTAL_MARK_COMPACTOR:
heap_->isolate()->PrintWithTimestamp(
"pause=%.1f "
"mutator=%.1f "
"gc=%s "
"reduce_memory=%d "
"time_to_safepoint=%.2f "
"heap.prologue=%.2f "
"heap.embedder_tracing_epilogue=%.2f "
"heap.epilogue=%.2f "
"heap.epilogue.reduce_new_space=%.2f "
"heap.external.prologue=%.1f "
"heap.external.epilogue=%.1f "
"heap.external.weak_global_handles=%.1f "
"clear=%1.f "
"clear.dependent_code=%.1f "
"clear.maps=%.1f "
"clear.slots_buffer=%.1f "
"clear.string_table=%.1f "
"clear.weak_collections=%.1f "
"clear.weak_lists=%.1f "
"clear.weak_references=%.1f "
"complete.sweep_array_buffers=%.1f "
"epilogue=%.1f "
"evacuate=%.1f "
"evacuate.candidates=%.1f "
"evacuate.clean_up=%.1f "
"evacuate.copy=%.1f "
"evacuate.prologue=%.1f "
"evacuate.epilogue=%.1f "
"evacuate.rebalance=%.1f "
"evacuate.update_pointers=%.1f "
"evacuate.update_pointers.to_new_roots=%.1f "
"evacuate.update_pointers.slots.main=%.1f "
"evacuate.update_pointers.weak=%.1f "
"finish=%.1f "
"finish.sweep_array_buffers=%.1f "
"mark=%.1f "
"mark.finish_incremental=%.1f "
"mark.roots=%.1f "
"mark.main=%.1f "
"mark.weak_closure=%.1f "
"mark.weak_closure.ephemeron=%.1f "
"mark.weak_closure.ephemeron.marking=%.1f "
"mark.weak_closure.ephemeron.linear=%.1f "
"mark.weak_closure.weak_handles=%.1f "
"mark.weak_closure.weak_roots=%.1f "
"mark.weak_closure.harmony=%.1f "
"mark.embedder_prologue=%.1f "
"mark.embedder_tracing=%.1f "
"prologue=%.1f "
"sweep=%.1f "
"sweep.code=%.1f "
"sweep.map=%.1f "
"sweep.old=%.1f "
"incremental=%.1f "
"incremental.finalize=%.1f "
"incremental.finalize.body=%.1f "
"incremental.finalize.external.prologue=%.1f "
"incremental.finalize.external.epilogue=%.1f "
"incremental.layout_change=%.1f "
"incremental.sweep_array_buffers=%.1f "
"incremental.sweeping=%.1f "
"incremental.embedder_prologue=%.1f "
"incremental.embedder_tracing=%.1f "
"incremental_wrapper_tracing_longest_step=%.1f "
"incremental_finalize_longest_step=%.1f "
"incremental_finalize_steps_count=%d "
"incremental_longest_step=%.1f "
"incremental_steps_count=%d "
"incremental_marking_throughput=%.f "
"incremental_walltime_duration=%.f "
"background.mark=%.1f "
"background.sweep=%.1f "
"background.evacuate.copy=%.1f "
"background.evacuate.update_pointers=%.1f "
"background.unmapper=%.1f "
"unmapper=%.1f "
"total_size_before=%zu "
"total_size_after=%zu "
"holes_size_before=%zu "
"holes_size_after=%zu "
"allocated=%zu "
"promoted=%zu "
"semi_space_copied=%zu "
"nodes_died_in_new=%d "
"nodes_copied_in_new=%d "
"nodes_promoted=%d "
"promotion_ratio=%.1f%% "
"average_survival_ratio=%.1f%% "
"promotion_rate=%.1f%% "
"semi_space_copy_rate=%.1f%% "
"new_space_allocation_throughput=%.1f "
"unmapper_chunks=%d "
"compaction_speed=%.f\n",
duration, spent_in_mutator, current_.TypeName(true),
current_.reduce_memory, current_.scopes[Scope::TIME_TO_SAFEPOINT],
current_.scopes[Scope::HEAP_PROLOGUE],
current_.scopes[Scope::HEAP_EMBEDDER_TRACING_EPILOGUE],
current_.scopes[Scope::HEAP_EPILOGUE],
current_.scopes[Scope::HEAP_EPILOGUE_REDUCE_NEW_SPACE],
current_.scopes[Scope::HEAP_EXTERNAL_PROLOGUE],
current_.scopes[Scope::HEAP_EXTERNAL_EPILOGUE],
current_.scopes[Scope::HEAP_EXTERNAL_WEAK_GLOBAL_HANDLES],
current_.scopes[Scope::MC_CLEAR],
current_.scopes[Scope::MC_CLEAR_DEPENDENT_CODE],
current_.scopes[Scope::MC_CLEAR_MAPS],
current_.scopes[Scope::MC_CLEAR_SLOTS_BUFFER],
current_.scopes[Scope::MC_CLEAR_STRING_TABLE],
current_.scopes[Scope::MC_CLEAR_WEAK_COLLECTIONS],
current_.scopes[Scope::MC_CLEAR_WEAK_LISTS],
current_.scopes[Scope::MC_CLEAR_WEAK_REFERENCES],
current_.scopes[Scope::MC_COMPLETE_SWEEP_ARRAY_BUFFERS],
current_.scopes[Scope::MC_EPILOGUE],
current_.scopes[Scope::MC_EVACUATE],
current_.scopes[Scope::MC_EVACUATE_CANDIDATES],
current_.scopes[Scope::MC_EVACUATE_CLEAN_UP],
current_.scopes[Scope::MC_EVACUATE_COPY],
current_.scopes[Scope::MC_EVACUATE_PROLOGUE],
current_.scopes[Scope::MC_EVACUATE_EPILOGUE],
current_.scopes[Scope::MC_EVACUATE_REBALANCE],
current_.scopes[Scope::MC_EVACUATE_UPDATE_POINTERS],
current_.scopes[Scope::MC_EVACUATE_UPDATE_POINTERS_TO_NEW_ROOTS],
current_.scopes[Scope::MC_EVACUATE_UPDATE_POINTERS_SLOTS_MAIN],
current_.scopes[Scope::MC_EVACUATE_UPDATE_POINTERS_WEAK],
current_.scopes[Scope::MC_FINISH],
current_.scopes[Scope::MC_FINISH_SWEEP_ARRAY_BUFFERS],
current_.scopes[Scope::MC_MARK],
current_.scopes[Scope::MC_MARK_FINISH_INCREMENTAL],
current_.scopes[Scope::MC_MARK_ROOTS],
current_.scopes[Scope::MC_MARK_MAIN],
current_.scopes[Scope::MC_MARK_WEAK_CLOSURE],
current_.scopes[Scope::MC_MARK_WEAK_CLOSURE_EPHEMERON],
current_.scopes[Scope::MC_MARK_WEAK_CLOSURE_EPHEMERON_MARKING],
current_.scopes[Scope::MC_MARK_WEAK_CLOSURE_EPHEMERON_LINEAR],
current_.scopes[Scope::MC_MARK_WEAK_CLOSURE_WEAK_HANDLES],
current_.scopes[Scope::MC_MARK_WEAK_CLOSURE_WEAK_ROOTS],
current_.scopes[Scope::MC_MARK_WEAK_CLOSURE_HARMONY],
current_.scopes[Scope::MC_MARK_EMBEDDER_PROLOGUE],
current_.scopes[Scope::MC_MARK_EMBEDDER_TRACING],
current_.scopes[Scope::MC_PROLOGUE], current_.scopes[Scope::MC_SWEEP],
current_.scopes[Scope::MC_SWEEP_CODE],
current_.scopes[Scope::MC_SWEEP_MAP],
current_.scopes[Scope::MC_SWEEP_OLD],
current_.scopes[Scope::MC_INCREMENTAL],
current_.scopes[Scope::MC_INCREMENTAL_FINALIZE],
current_.scopes[Scope::MC_INCREMENTAL_FINALIZE_BODY],
current_.scopes[Scope::MC_INCREMENTAL_EXTERNAL_PROLOGUE],
current_.scopes[Scope::MC_INCREMENTAL_EXTERNAL_EPILOGUE],
current_.scopes[Scope::MC_INCREMENTAL_LAYOUT_CHANGE],
current_.scopes[Scope::MC_INCREMENTAL_START],
current_.scopes[Scope::MC_INCREMENTAL_SWEEPING],
current_.scopes[Scope::MC_INCREMENTAL_EMBEDDER_PROLOGUE],
current_.scopes[Scope::MC_INCREMENTAL_EMBEDDER_TRACING],
current_
.incremental_marking_scopes
[Scope::MC_INCREMENTAL_EMBEDDER_TRACING]
.longest_step,
current_
.incremental_marking_scopes[Scope::MC_INCREMENTAL_FINALIZE_BODY]
.longest_step,
current_
.incremental_marking_scopes[Scope::MC_INCREMENTAL_FINALIZE_BODY]
.steps,
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL]
.longest_step,
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL].steps,
IncrementalMarkingSpeedInBytesPerMillisecond(),
incremental_walltime_duration,
current_.scopes[Scope::MC_BACKGROUND_MARKING],
current_.scopes[Scope::MC_BACKGROUND_SWEEPING],
current_.scopes[Scope::MC_BACKGROUND_EVACUATE_COPY],
current_.scopes[Scope::MC_BACKGROUND_EVACUATE_UPDATE_POINTERS],
current_.scopes[Scope::BACKGROUND_UNMAPPER],
current_.scopes[Scope::UNMAPPER], current_.start_object_size,
current_.end_object_size, current_.start_holes_size,
current_.end_holes_size, allocated_since_last_gc,
heap_->promoted_objects_size(),
heap_->semi_space_copied_object_size(),
heap_->nodes_died_in_new_space_, heap_->nodes_copied_in_new_space_,
heap_->nodes_promoted_, heap_->promotion_ratio_,
AverageSurvivalRatio(), heap_->promotion_rate_,
heap_->semi_space_copied_rate_,
NewSpaceAllocationThroughputInBytesPerMillisecond(),
heap_->memory_allocator()->unmapper()->NumberOfChunks(),
CompactionSpeedInBytesPerMillisecond());
break;
case Event::START:
break;
default:
UNREACHABLE();
}
}
double GCTracer::AverageSpeed(const base::RingBuffer<BytesAndDuration>& buffer,
const BytesAndDuration& initial, double time_ms) {
BytesAndDuration sum = buffer.Sum(
[time_ms](BytesAndDuration a, BytesAndDuration b) {
if (time_ms != 0 && a.second >= time_ms) return a;
return std::make_pair(a.first + b.first, a.second + b.second);
},
initial);
uint64_t bytes = sum.first;
double durations = sum.second;
if (durations == 0.0) return 0;
double speed = bytes / durations;
const int max_speed = 1024 * MB;
const int min_speed = 1;
if (speed >= max_speed) return max_speed;
if (speed <= min_speed) return min_speed;
return speed;
}
double GCTracer::AverageSpeed(
const base::RingBuffer<BytesAndDuration>& buffer) {
return AverageSpeed(buffer, MakeBytesAndDuration(0, 0), 0);
}
void GCTracer::RecordIncrementalMarkingSpeed(size_t bytes, double duration) {
if (duration == 0 || bytes == 0) return;
double current_speed = bytes / duration;
if (recorded_incremental_marking_speed_ == 0) {
recorded_incremental_marking_speed_ = current_speed;
} else {
recorded_incremental_marking_speed_ =
(recorded_incremental_marking_speed_ + current_speed) / 2;
}
}
void GCTracer::RecordTimeToIncrementalMarkingTask(double time_to_task) {
if (average_time_to_incremental_marking_task_ == 0.0) {
average_time_to_incremental_marking_task_ = time_to_task;
} else {
average_time_to_incremental_marking_task_ =
(average_time_to_incremental_marking_task_ + time_to_task) / 2;
}
}
double GCTracer::AverageTimeToIncrementalMarkingTask() const {
return average_time_to_incremental_marking_task_;
}
void GCTracer::RecordEmbedderSpeed(size_t bytes, double duration) {
if (duration == 0 || bytes == 0) return;
double current_speed = bytes / duration;
if (recorded_embedder_speed_ == 0.0) {
recorded_embedder_speed_ = current_speed;
} else {
recorded_embedder_speed_ = (recorded_embedder_speed_ + current_speed) / 2;
}
}
void GCTracer::RecordMutatorUtilization(double mark_compact_end_time,
double mark_compact_duration) {
if (previous_mark_compact_end_time_ == 0) {
// The first event only contributes to previous_mark_compact_end_time_,
// because we cannot compute the mutator duration.
previous_mark_compact_end_time_ = mark_compact_end_time;
} else {
double total_duration =
mark_compact_end_time - previous_mark_compact_end_time_;
double mutator_duration = total_duration - mark_compact_duration;
if (average_mark_compact_duration_ == 0 && average_mutator_duration_ == 0) {
// This is the first event with mutator and mark-compact durations.
average_mark_compact_duration_ = mark_compact_duration;
average_mutator_duration_ = mutator_duration;
} else {
average_mark_compact_duration_ =
(average_mark_compact_duration_ + mark_compact_duration) / 2;
average_mutator_duration_ =
(average_mutator_duration_ + mutator_duration) / 2;
}
current_mark_compact_mutator_utilization_ =
total_duration ? mutator_duration / total_duration : 0;
previous_mark_compact_end_time_ = mark_compact_end_time;
}
}
double GCTracer::AverageMarkCompactMutatorUtilization() const {
double average_total_duration =
average_mark_compact_duration_ + average_mutator_duration_;
if (average_total_duration == 0) return 1.0;
return average_mutator_duration_ / average_total_duration;
}
double GCTracer::CurrentMarkCompactMutatorUtilization() const {
return current_mark_compact_mutator_utilization_;
}
double GCTracer::IncrementalMarkingSpeedInBytesPerMillisecond() const {
if (recorded_incremental_marking_speed_ != 0) {
return recorded_incremental_marking_speed_;
}
if (incremental_marking_duration_ != 0.0) {
return incremental_marking_bytes_ / incremental_marking_duration_;
}
return kConservativeSpeedInBytesPerMillisecond;
}
double GCTracer::EmbedderSpeedInBytesPerMillisecond() const {
// Note: Returning 0 is ok here as callers check for whether embedder speeds
// have been recorded at all.
return recorded_embedder_speed_;
}
double GCTracer::ScavengeSpeedInBytesPerMillisecond(
ScavengeSpeedMode mode) const {
if (mode == kForAllObjects) {
return AverageSpeed(recorded_minor_gcs_total_);
} else {
return AverageSpeed(recorded_minor_gcs_survived_);
}
}
double GCTracer::CompactionSpeedInBytesPerMillisecond() const {
return AverageSpeed(recorded_compactions_);
}
double GCTracer::MarkCompactSpeedInBytesPerMillisecond() const {
return AverageSpeed(recorded_mark_compacts_);
}
double GCTracer::FinalIncrementalMarkCompactSpeedInBytesPerMillisecond() const {
return AverageSpeed(recorded_incremental_mark_compacts_);
}
double GCTracer::CombinedMarkCompactSpeedInBytesPerMillisecond() {
const double kMinimumMarkingSpeed = 0.5;
if (combined_mark_compact_speed_cache_ > 0)
return combined_mark_compact_speed_cache_;
// MarkCompact speed is more stable than incremental marking speed, because
// there might not be many incremental marking steps because of concurrent
// marking.
combined_mark_compact_speed_cache_ = MarkCompactSpeedInBytesPerMillisecond();
if (combined_mark_compact_speed_cache_ > 0)
return combined_mark_compact_speed_cache_;
double speed1 = IncrementalMarkingSpeedInBytesPerMillisecond();
double speed2 = FinalIncrementalMarkCompactSpeedInBytesPerMillisecond();
if (speed1 < kMinimumMarkingSpeed || speed2 < kMinimumMarkingSpeed) {
// No data for the incremental marking speed.
// Return the non-incremental mark-compact speed.
combined_mark_compact_speed_cache_ =
MarkCompactSpeedInBytesPerMillisecond();
} else {
// Combine the speed of incremental step and the speed of the final step.
// 1 / (1 / speed1 + 1 / speed2) = speed1 * speed2 / (speed1 + speed2).
combined_mark_compact_speed_cache_ = speed1 * speed2 / (speed1 + speed2);
}
return combined_mark_compact_speed_cache_;
}
double GCTracer::CombineSpeedsInBytesPerMillisecond(double default_speed,
double optional_speed) {
constexpr double kMinimumSpeed = 0.5;
if (optional_speed < kMinimumSpeed) {
return default_speed;
}
return default_speed * optional_speed / (default_speed + optional_speed);
}
double GCTracer::NewSpaceAllocationThroughputInBytesPerMillisecond(
double time_ms) const {
size_t bytes = new_space_allocation_in_bytes_since_gc_;
double durations = allocation_duration_since_gc_;
return AverageSpeed(recorded_new_generation_allocations_,
MakeBytesAndDuration(bytes, durations), time_ms);
}
double GCTracer::OldGenerationAllocationThroughputInBytesPerMillisecond(
double time_ms) const {
size_t bytes = old_generation_allocation_in_bytes_since_gc_;
double durations = allocation_duration_since_gc_;
return AverageSpeed(recorded_old_generation_allocations_,
MakeBytesAndDuration(bytes, durations), time_ms);
}
double GCTracer::EmbedderAllocationThroughputInBytesPerMillisecond(
double time_ms) const {
size_t bytes = embedder_allocation_in_bytes_since_gc_;
double durations = allocation_duration_since_gc_;
return AverageSpeed(recorded_embedder_generation_allocations_,
MakeBytesAndDuration(bytes, durations), time_ms);
}
double GCTracer::AllocationThroughputInBytesPerMillisecond(
double time_ms) const {
return NewSpaceAllocationThroughputInBytesPerMillisecond(time_ms) +
OldGenerationAllocationThroughputInBytesPerMillisecond(time_ms);
}
double GCTracer::CurrentAllocationThroughputInBytesPerMillisecond() const {
return AllocationThroughputInBytesPerMillisecond(kThroughputTimeFrameMs);
}
double GCTracer::CurrentOldGenerationAllocationThroughputInBytesPerMillisecond()
const {
return OldGenerationAllocationThroughputInBytesPerMillisecond(
kThroughputTimeFrameMs);
}
double GCTracer::CurrentEmbedderAllocationThroughputInBytesPerMillisecond()
const {
return EmbedderAllocationThroughputInBytesPerMillisecond(
kThroughputTimeFrameMs);
}
double GCTracer::AverageSurvivalRatio() const {
if (recorded_survival_ratios_.Count() == 0) return 0.0;
double sum = recorded_survival_ratios_.Sum(
[](double a, double b) { return a + b; }, 0.0);
return sum / recorded_survival_ratios_.Count();
}
bool GCTracer::SurvivalEventsRecorded() const {
return recorded_survival_ratios_.Count() > 0;
}
void GCTracer::ResetSurvivalEvents() { recorded_survival_ratios_.Reset(); }
void GCTracer::NotifyIncrementalMarkingStart() {
incremental_marking_start_time_ = MonotonicallyIncreasingTimeInMs();
}
void GCTracer::FetchBackgroundMarkCompactCounters() {
FetchBackgroundCounters(Scope::FIRST_MC_BACKGROUND_SCOPE,
Scope::LAST_MC_BACKGROUND_SCOPE);
heap_->isolate()->counters()->background_marking()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_BACKGROUND_MARKING]));
heap_->isolate()->counters()->background_sweeping()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_BACKGROUND_SWEEPING]));
}
void GCTracer::FetchBackgroundMinorGCCounters() {
FetchBackgroundCounters(Scope::FIRST_MINOR_GC_BACKGROUND_SCOPE,
Scope::LAST_MINOR_GC_BACKGROUND_SCOPE);
heap_->isolate()->counters()->background_scavenger()->AddSample(
static_cast<int>(
current_.scopes[Scope::SCAVENGER_BACKGROUND_SCAVENGE_PARALLEL]));
}
void GCTracer::FetchBackgroundGeneralCounters() {
FetchBackgroundCounters(Scope::FIRST_GENERAL_BACKGROUND_SCOPE,
Scope::LAST_GENERAL_BACKGROUND_SCOPE);
}
void GCTracer::FetchBackgroundCounters(int first_scope, int last_scope) {
base::MutexGuard guard(&background_counter_mutex_);
for (int i = first_scope; i <= last_scope; i++) {
current_.scopes[i] += background_counter_[i].total_duration_ms;
background_counter_[i].total_duration_ms = 0;
}
}
void GCTracer::AddScopeSampleBackground(Scope::ScopeId scope, double duration) {
base::MutexGuard guard(&background_counter_mutex_);
BackgroundCounter& counter = background_counter_[scope];
counter.total_duration_ms += duration;
}
void GCTracer::RecordGCPhasesHistograms(TimedHistogram* gc_timer) {
Counters* counters = heap_->isolate()->counters();
if (gc_timer == counters->gc_finalize()) {
DCHECK_EQ(Scope::FIRST_TOP_MC_SCOPE, Scope::MC_CLEAR);
counters->gc_finalize_clear()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_CLEAR]));
counters->gc_finalize_epilogue()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_EPILOGUE]));
counters->gc_finalize_evacuate()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_EVACUATE]));
counters->gc_finalize_finish()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_FINISH]));
counters->gc_finalize_mark()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_MARK]));
counters->gc_finalize_prologue()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_PROLOGUE]));
counters->gc_finalize_sweep()->AddSample(
static_cast<int>(current_.scopes[Scope::MC_SWEEP]));
if (incremental_marking_duration_ > 0) {
heap_->isolate()->counters()->incremental_marking_sum()->AddSample(
static_cast<int>(incremental_marking_duration_));
}
const double overall_marking_time =
incremental_marking_duration_ + current_.scopes[Scope::MC_MARK];
heap_->isolate()->counters()->gc_marking_sum()->AddSample(
static_cast<int>(overall_marking_time));
// Filter out samples where
// - we don't have high-resolution timers;
// - size of marked objects is very small;
// - marking time is rounded to 0;
constexpr size_t kMinObjectSizeForReportingThroughput = 1024 * 1024;
if (base::TimeTicks::IsHighResolution() &&
heap_->SizeOfObjects() > kMinObjectSizeForReportingThroughput &&
overall_marking_time > 0) {
const double overall_v8_marking_time =
overall_marking_time -
current_.scopes[Scope::MC_MARK_EMBEDDER_TRACING];
if (overall_v8_marking_time > 0) {
const int main_thread_marking_throughput_mb_per_s =
static_cast<int>(static_cast<double>(heap_->SizeOfObjects()) /
overall_v8_marking_time * 1000 / 1024 / 1024);
heap_->isolate()
->counters()
->gc_main_thread_marking_throughput()
->AddSample(
static_cast<int>(main_thread_marking_throughput_mb_per_s));
}
}
DCHECK_EQ(Scope::LAST_TOP_MC_SCOPE, Scope::MC_SWEEP);
} else if (gc_timer == counters->gc_scavenger()) {
counters->gc_scavenger_scavenge_main()->AddSample(
static_cast<int>(current_.scopes[Scope::SCAVENGER_SCAVENGE_PARALLEL]));
counters->gc_scavenger_scavenge_roots()->AddSample(
static_cast<int>(current_.scopes[Scope::SCAVENGER_SCAVENGE_ROOTS]));
}
}
void GCTracer::RecordGCSumCounters(double atomic_pause_duration) {
base::MutexGuard guard(&background_counter_mutex_);
const double overall_duration =
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL_LAYOUT_CHANGE]
.duration +
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL_START]
.duration +
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL_SWEEPING]
.duration +
incremental_marking_duration_ +
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL_FINALIZE]
.duration +
atomic_pause_duration;
const double background_duration =
background_counter_[Scope::MC_BACKGROUND_EVACUATE_COPY]
.total_duration_ms +
background_counter_[Scope::MC_BACKGROUND_EVACUATE_UPDATE_POINTERS]
.total_duration_ms +
background_counter_[Scope::MC_BACKGROUND_MARKING].total_duration_ms +
background_counter_[Scope::MC_BACKGROUND_SWEEPING].total_duration_ms;
const double marking_duration =
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL_LAYOUT_CHANGE]
.duration +
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL_START]
.duration +
incremental_marking_duration_ +
current_.incremental_marking_scopes[Scope::MC_INCREMENTAL_FINALIZE]
.duration +
current_.scopes[Scope::MC_MARK];
const double marking_background_duration =
background_counter_[Scope::MC_BACKGROUND_MARKING].total_duration_ms;
// UMA.
heap_->isolate()->counters()->gc_mark_compactor()->AddSample(
static_cast<int>(overall_duration));
// Emit trace event counters.
TRACE_EVENT_INSTANT2(TRACE_DISABLED_BY_DEFAULT("v8.gc"),
"V8.GCMarkCompactorSummary", TRACE_EVENT_SCOPE_THREAD,
"duration", overall_duration, "background_duration",
background_duration);
TRACE_EVENT_INSTANT2(TRACE_DISABLED_BY_DEFAULT("v8.gc"),
"V8.GCMarkCompactorMarkingSummary",
TRACE_EVENT_SCOPE_THREAD, "duration", marking_duration,
"background_duration", marking_background_duration);
}
void GCTracer::NotifyGCCompleted() {
// Report full GC cycle metric to recorder only when both v8 and cppgc (if
// available) GCs have finished. This method is invoked by both v8 and cppgc.
if (!metrics_report_pending_) {
// V8 sweeping is not done yet.
return;
}
const auto* cpp_heap = heap_->cpp_heap();
if (cpp_heap &&
!CppHeap::From(cpp_heap)->GetMetricRecorder()->MetricsReportPending()) {
// Cppgc sweeping is not done yet.
return;
}
ReportFullCycleToRecorder();
}
namespace {
void CopyTimeMetrics(
::v8::metrics::GarbageCollectionPhases& metrics,
const cppgc::internal::MetricRecorder::FullCycle::IncrementalPhases&
cppgc_metrics) {
DCHECK_NE(-1, cppgc_metrics.mark_duration_us);
metrics.mark_wall_clock_duration_in_us = cppgc_metrics.mark_duration_us;
DCHECK_NE(-1, cppgc_metrics.sweep_duration_us);
metrics.sweep_wall_clock_duration_in_us = cppgc_metrics.sweep_duration_us;
}
void CopyTimeMetrics(
::v8::metrics::GarbageCollectionPhases& metrics,
const cppgc::internal::MetricRecorder::FullCycle::Phases& cppgc_metrics) {
DCHECK_NE(-1, cppgc_metrics.compact_duration_us);
metrics.compact_wall_clock_duration_in_us = cppgc_metrics.compact_duration_us;
DCHECK_NE(-1, cppgc_metrics.mark_duration_us);
metrics.mark_wall_clock_duration_in_us = cppgc_metrics.mark_duration_us;
DCHECK_NE(-1, cppgc_metrics.sweep_duration_us);
metrics.sweep_wall_clock_duration_in_us = cppgc_metrics.sweep_duration_us;
DCHECK_NE(-1, cppgc_metrics.weak_duration_us);
metrics.weak_wall_clock_duration_in_us = cppgc_metrics.weak_duration_us;
}
void CopySizeMetrics(
::v8::metrics::GarbageCollectionSizes& metrics,
const cppgc::internal::MetricRecorder::FullCycle::Sizes& cppgc_metrics) {
DCHECK_NE(-1, cppgc_metrics.after_bytes);
metrics.bytes_after = cppgc_metrics.after_bytes;
DCHECK_NE(-1, cppgc_metrics.before_bytes);
metrics.bytes_before = cppgc_metrics.before_bytes;
DCHECK_NE(-1, cppgc_metrics.freed_bytes);
metrics.bytes_freed = cppgc_metrics.freed_bytes;
}
::v8::metrics::Recorder::ContextId GetContextId(
v8::internal::Isolate* isolate) {
DCHECK_NOT_NULL(isolate);
if (isolate->context().is_null())
return v8::metrics::Recorder::ContextId::Empty();
HandleScope scope(isolate);
return isolate->GetOrRegisterRecorderContextId(isolate->native_context());
}
void FlushBatchedIncrementalEvents(
v8::metrics::GarbageCollectionFullMainThreadBatchedIncrementalMark&
batched_events,
Isolate* isolate) {
DCHECK_NOT_NULL(isolate->metrics_recorder());
DCHECK(!batched_events.events.empty());
isolate->metrics_recorder()->AddMainThreadEvent(std::move(batched_events),
GetContextId(isolate));
}
} // namespace
void GCTracer::ReportFullCycleToRecorder() {
const std::shared_ptr<metrics::Recorder>& recorder =
heap_->isolate()->metrics_recorder();
DCHECK_NOT_NULL(recorder);
metrics_report_pending_ = false;
if (!recorder->HasEmbedderRecorder()) {
incremental_mark_batched_events_.events.clear();
if (heap_->cpp_heap()) {
v8::internal::CppHeap::From(heap_->cpp_heap())
->GetMetricRecorder()
->ClearCachedEvents();
}
return;
}
if (!incremental_mark_batched_events_.events.empty()) {
FlushBatchedIncrementalEvents(incremental_mark_batched_events_,
heap_->isolate());
}
v8::metrics::GarbageCollectionFullCycle event;
if (heap_->cpp_heap()) {
auto* cpp_heap = v8::internal::CppHeap::From(heap_->cpp_heap());
cpp_heap->GetMetricRecorder()->FlushBatchedIncrementalEvents();
const base::Optional<cppgc::internal::MetricRecorder::FullCycle>
optional_cppgc_event =
cpp_heap->GetMetricRecorder()->ExtractLastFullGcEvent();
DCHECK(optional_cppgc_event.has_value());
DCHECK(!cpp_heap->GetMetricRecorder()->MetricsReportPending());
const cppgc::internal::MetricRecorder::FullCycle& cppgc_event =
optional_cppgc_event.value();
CopyTimeMetrics(event.total_cpp, cppgc_event.total);
CopyTimeMetrics(event.main_thread_cpp, cppgc_event.main_thread);
CopyTimeMetrics(event.main_thread_atomic_cpp,
cppgc_event.main_thread_atomic);
CopyTimeMetrics(event.main_thread_incremental_cpp,
cppgc_event.main_thread_incremental);
CopySizeMetrics(event.objects_cpp, cppgc_event.objects);
CopySizeMetrics(event.memory_cpp, cppgc_event.memory);
DCHECK_NE(-1, cppgc_event.collection_rate_in_percent);
event.collection_rate_cpp_in_percent =
cppgc_event.collection_rate_in_percent;
DCHECK_NE(-1, cppgc_event.efficiency_in_bytes_per_us);
event.efficiency_cpp_in_bytes_per_us =
cppgc_event.efficiency_in_bytes_per_us;
DCHECK_NE(-1, cppgc_event.main_thread_efficiency_in_bytes_per_us);
event.main_thread_efficiency_cpp_in_bytes_per_us =
cppgc_event.main_thread_efficiency_in_bytes_per_us;
}
// TODO(chromium:1154636): Populate v8 metrics.
recorder->AddMainThreadEvent(event, GetContextId(heap_->isolate()));
}
void GCTracer::ReportIncrementalMarkingStepToRecorder() {
static constexpr int kMaxBatchedEvents =
CppHeap::MetricRecorderAdapter::kMaxBatchedEvents;
const std::shared_ptr<metrics::Recorder>& recorder =
heap_->isolate()->metrics_recorder();
DCHECK_NOT_NULL(recorder);
if (!recorder->HasEmbedderRecorder()) return;
incremental_mark_batched_events_.events.emplace_back();
if (heap_->cpp_heap()) {
const base::Optional<
cppgc::internal::MetricRecorder::MainThreadIncrementalMark>
cppgc_event = v8::internal::CppHeap::From(heap_->cpp_heap())
->GetMetricRecorder()
->ExtractLastIncrementalMarkEvent();
if (cppgc_event.has_value()) {
DCHECK_NE(-1, cppgc_event.value().duration_us);
incremental_mark_batched_events_.events.back()
.cpp_wall_clock_duration_in_us = cppgc_event.value().duration_us;
}
}
// TODO(chromium:1154636): Populate event.wall_clock_duration_in_us.
if (incremental_mark_batched_events_.events.size() == kMaxBatchedEvents) {
FlushBatchedIncrementalEvents(incremental_mark_batched_events_,
heap_->isolate());
}
}
void GCTracer::ReportYoungCycleToRecorder() {
const std::shared_ptr<metrics::Recorder>& recorder =
heap_->isolate()->metrics_recorder();
DCHECK_NOT_NULL(recorder);
if (!recorder->HasEmbedderRecorder()) return;
v8::metrics::GarbageCollectionYoungCycle event;
// Reason:
event.reason = static_cast<int>(current_.gc_reason);
// Total:
const double total_wall_clock_duration_in_us =
(current_.scopes[Scope::SCAVENGER] +
current_.scopes[Scope::MINOR_MARK_COMPACTOR] +
current_.scopes[Scope::SCAVENGER_BACKGROUND_SCAVENGE_PARALLEL] +
current_.scopes[Scope::MINOR_MC_BACKGROUND_EVACUATE_COPY] +
current_.scopes[Scope::MINOR_MC_BACKGROUND_MARKING] +
current_.scopes[Scope::MINOR_MC_BACKGROUND_EVACUATE_UPDATE_POINTERS]) *
base::Time::kMicrosecondsPerMillisecond;
// TODO(chromium:1154636): Consider adding BACKGROUND_YOUNG_ARRAY_BUFFER_SWEEP
// (both for the case of the scavenger and the minor mark-compactor), and
// BACKGROUND_UNMAPPER (for the case of the minor mark-compactor).
event.total_wall_clock_duration_in_us =
static_cast<int64_t>(total_wall_clock_duration_in_us);
// MainThread:
const double main_thread_wall_clock_duration_in_us =
(current_.scopes[Scope::SCAVENGER] +
current_.scopes[Scope::MINOR_MARK_COMPACTOR]) *
base::Time::kMicrosecondsPerMillisecond;
event.main_thread_wall_clock_duration_in_us =
static_cast<int64_t>(main_thread_wall_clock_duration_in_us);
// Collection Rate:
event.collection_rate_in_percent =
static_cast<double>(current_.survived_young_object_size) /
current_.young_object_size;
// Efficiency:
auto freed_bytes =
current_.young_object_size - current_.survived_young_object_size;
event.efficiency_in_bytes_per_us =
freed_bytes / total_wall_clock_duration_in_us;
event.main_thread_efficiency_in_bytes_per_us =
freed_bytes / main_thread_wall_clock_duration_in_us;
recorder->AddMainThreadEvent(event, GetContextId(heap_->isolate()));
}
} // namespace internal
} // namespace v8
|
/*==================================================================
Program: Visualization Toolkit
Module: TestHyperTreeGridTernaryHyperbola.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
===================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware 2012
// This test was revised by Philippe Pebay, 2016
// This work was supported by Commissariat a l'Energie Atomique (CEA/DIF)
#include "vtkHyperTreeGridGeometry.h"
#include "vtkHyperTreeGridSource.h"
#include "vtkCamera.h"
#include "vtkCellData.h"
#include "vtkColorTransferFunction.h"
#include "vtkContourFilter.h"
#include "vtkMath.h"
#include "vtkNew.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkProperty2D.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkScalarBarActor.h"
#include "vtkTextProperty.h"
#include "vtkQuadric.h"
int TestHyperTreeGridTernaryHyperbola( int argc, char* argv[] )
{
// Hyper tree grid
vtkNew<vtkHyperTreeGridSource> htGrid;
htGrid->SetMaximumLevel( 6 );
htGrid->SetGridSize( 8, 12, 1 );
htGrid->SetGridScale( 1.5, 1., .7 );
htGrid->SetDimension( 2 );
htGrid->SetOrientation( 2 ); // in xy plane
htGrid->SetBranchFactor( 3 );
htGrid->UseDescriptorOff();
htGrid->UseMaterialMaskOff();
vtkNew<vtkQuadric> quadric;
quadric->SetCoefficients( 1., -1., 0.,
0., 0., 0.,
-12., 12., 0.,
1. );
htGrid->SetQuadric( quadric );
// Geometry
vtkNew<vtkHyperTreeGridGeometry> geometry;
geometry->SetInputConnection( htGrid->GetOutputPort() );
geometry->Update();
vtkPolyData* pd = geometry->GetPolyDataOutput();
pd->GetCellData()->SetActiveScalars( "Quadric" );
// Contour
vtkNew<vtkContourFilter> contour;
contour->SetInputConnection( htGrid->GetOutputPort() );
contour->SetNumberOfContours( 0 );
contour->SetValue( 0, 0 );
contour->SetInputArrayToProcess( 0, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_POINTS,
"Quadric" );
// Color transfer function
vtkNew<vtkColorTransferFunction> colorFunction;
colorFunction->AddRGBSegment( -30., 0., 0., 1.,
0., 0., 1., 1.);
colorFunction->AddRGBSegment( VTK_DBL_MIN, 1., 1., 0.,
30., 1., 0., 0.);
// Mappers
vtkMapper::SetResolveCoincidentTopologyToPolygonOffset();
vtkNew<vtkPolyDataMapper> mapper1;
mapper1->SetInputConnection( geometry->GetOutputPort() );
mapper1->UseLookupTableScalarRangeOn();
mapper1->SetLookupTable( colorFunction );
vtkNew<vtkPolyDataMapper> mapper2;
mapper2->SetInputConnection( geometry->GetOutputPort() );
mapper2->ScalarVisibilityOff();
vtkNew<vtkPolyDataMapper> mapper3;
mapper3->SetInputConnection( contour->GetOutputPort() );
mapper3->ScalarVisibilityOff();
// Actors
vtkNew<vtkActor> actor1;
actor1->SetMapper( mapper1 );
vtkNew<vtkActor> actor2;
actor2->SetMapper( mapper2 );
actor2->GetProperty()->SetRepresentationToWireframe();
actor2->GetProperty()->SetColor( .7, .7, .7 );
vtkNew<vtkActor> actor3;
actor3->SetMapper( mapper3 );
actor3->GetProperty()->SetColor( 0., 0., 0. );
actor3->GetProperty()->SetLineWidth( 2 );
// Camera
double bd[6];
pd->GetBounds( bd );
vtkNew<vtkCamera> camera;
camera->SetClippingRange( 1., 100. );
camera->SetFocalPoint( pd->GetCenter() );
camera->SetPosition( .5 * bd[1], .5 * bd[3], 24. );
// Scalar bar
vtkNew<vtkScalarBarActor> scalarBar;
scalarBar->SetLookupTable( colorFunction );
scalarBar->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport();
scalarBar->GetPositionCoordinate()->SetValue( .65, .05 );
scalarBar->SetTitle( "Quadric" );
scalarBar->SetWidth( 0.15 );
scalarBar->SetHeight( 0.4 );
scalarBar->SetTextPad( 4 );
scalarBar->SetMaximumWidthInPixels( 60 );
scalarBar->SetMaximumHeightInPixels( 200 );
scalarBar->SetTextPositionToPrecedeScalarBar();
scalarBar->GetTitleTextProperty()->SetColor( .4, .4, .4 );
scalarBar->GetLabelTextProperty()->SetColor( .4, .4, .4 );
scalarBar->SetDrawFrame( 1 );
scalarBar->GetFrameProperty()->SetColor( .4, .4, .4 );
scalarBar->SetDrawBackground( 1 );
scalarBar->GetBackgroundProperty()->SetColor( 1., 1., 1. );
// Renderer
vtkNew<vtkRenderer> renderer;
renderer->SetActiveCamera( camera );
renderer->SetBackground( 1., 1., 1. );
renderer->AddActor( actor1 );
renderer->AddActor( actor2 );
renderer->AddActor( actor3 );
renderer->AddActor( scalarBar );
// Render window
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer( renderer );
renWin->SetSize( 400, 400 );
renWin->SetMultiSamples( 0 );
// Interactor
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow( renWin );
// Render and test
renWin->Render();
int retVal = vtkRegressionTestImageThreshold( renWin, 70 );
if ( retVal == vtkRegressionTester::DO_INTERACTOR )
{
iren->Start();
}
return !retVal;
}
|
/*
* BSD LICENSE
* Copyright (c) 2021 Samsung Electronics Corporation
* 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 Samsung Electronics Corporation 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 "nvram_meta_volume.h"
#include "metafs_log.h"
namespace pos
{
NvRamMetaVolume::NvRamMetaVolume(const int arrayId, const MetaLpnType maxVolumePageNum,
InodeManager* inodeMgr, CatalogManager* catalogMgr)
: MetaVolume(arrayId, MetaVolumeType::NvRamVolume, maxVolumePageNum, inodeMgr, catalogMgr)
{
}
NvRamMetaVolume::~NvRamMetaVolume(void)
{
MFS_TRACE_DEBUG((int)POS_EVENT_ID::MFS_DEBUG_MESSAGE,
"NvRAM Meta Vol. destructed...");
}
bool
NvRamMetaVolume::IsFreeSpaceEnough(FileSizeType fileByteSize)
{
MFS_TRACE_DEBUG((int)POS_EVENT_ID::MFS_DEBUG_MESSAGE,
"NVRAM Space. free space={}, request={}", fileByteSize, GetAvailableSpace());
if (fileByteSize == 0) // MetaFsFileControlType::GetFreeFileRegionSize
{
return true;
}
if (GetAvailableSpace() >= fileByteSize)
{
return true;
}
return false;
}
void
NvRamMetaVolume::InitVolumeBaseLpn(void)
{
volumeBaseLpn_ = NVRAM_VOLUME_BASE_LPN;
}
bool
NvRamMetaVolume::IsOkayToStore(FileSizeType fileByteSize, MetaFilePropertySet& prop)
{
if (GetUtilizationInPercent() >= META_VOL_CAPACITY_FULL_LIMIT_IN_PERCENT)
{
POS_TRACE_DEBUG((int)POS_EVENT_ID::MFS_META_VOLUME_ALMOST_FULL,
"NVRAM Volume is almost full");
return false;
}
if (true == IsFreeSpaceEnough(fileByteSize))
{
if (_IsNVRAMStoreStronglyPreferred(prop))
{
return true;
}
else
{
return false;
}
}
return false;
}
bool
NvRamMetaVolume::_IsNVRAMStoreStronglyPreferred(MetaFilePropertySet& prop)
{
if (prop.ioAccPattern == MetaFileAccessPattern::ByteIntensive ||
prop.ioAccPattern == MetaFileAccessPattern::SmallSizeBlockIO)
{
return true;
}
if (prop.ioOpType == MetaFileDominant::WriteDominant)
{
return true;
}
return false;
}
} // namespace pos
|
#include "AI013x0x1xDecoder.h"
#include <zxing/common/StringUtils.h>
namespace zxing {
namespace oned {
namespace rss {
AI013x0x1xDecoder::AI013x0x1xDecoder(QSharedPointer<BitArray> information, String firstAIdigits, String dateCode)
: AI01weightDecoder(information), m_dateCode(dateCode), m_firstAIdigits(firstAIdigits)
{
}
String AI013x0x1xDecoder::parseInformation()
{
if (getInformation()->getSize() != HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE + DATE_SIZE) {
throw NotFoundException();
}
String buf("");
encodeCompressedGtin(buf, HEADER_SIZE);
encodeCompressedWeight(buf, HEADER_SIZE + GTIN_SIZE, WEIGHT_SIZE);
encodeCompressedDate(buf, HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE);
return buf;
}
void AI013x0x1xDecoder::encodeCompressedDate(String &buf, int currentPos)
{
int numericDate = getGeneralDecoder().extractNumericValueFromBitArray(currentPos, DATE_SIZE);
if (numericDate == 38400) {
return;
}
buf.append('(');
buf.append(m_dateCode.getText());
buf.append(')');
int day = numericDate % 32;
numericDate /= 32;
int month = numericDate % 12 + 1;
numericDate /= 12;
int year = numericDate;
if (year / 10 == 0) {
buf.append('0');
}
buf.append(common::StringUtils::intToStr(year));
if (month / 10 == 0) {
buf.append('0');
}
buf.append(common::StringUtils::intToStr(month));
if (day / 10 == 0) {
buf.append('0');
}
buf.append(common::StringUtils::intToStr(day));
}
void AI013x0x1xDecoder::addWeightCode(String &buf, int weight)
{
buf.append('(');
buf.append(m_firstAIdigits.getText());
buf.append(common::StringUtils::intToStr(weight / 100000));
buf.append(')');
}
int AI013x0x1xDecoder::checkWeight(int weight)
{
return weight % 100000;
}
}
}
}
|
// Copyright 2017 the V8 project 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 "src/builtins/accessors.h"
#include "src/codegen/compilation-cache.h"
#include "src/execution/isolate.h"
#include "src/execution/protectors.h"
#include "src/heap/factory.h"
#include "src/heap/heap-inl.h"
#include "src/ic/handler-configuration.h"
#include "src/init/heap-symbols.h"
#include "src/init/setup-isolate.h"
#include "src/interpreter/interpreter.h"
#include "src/objects/arguments.h"
#include "src/objects/cell-inl.h"
#include "src/objects/contexts.h"
#include "src/objects/data-handler.h"
#include "src/objects/debug-objects.h"
#include "src/objects/descriptor-array.h"
#include "src/objects/dictionary.h"
#include "src/objects/foreign.h"
#include "src/objects/heap-number.h"
#include "src/objects/instance-type-inl.h"
#include "src/objects/js-generator.h"
#include "src/objects/js-weak-refs.h"
#include "src/objects/layout-descriptor.h"
#include "src/objects/literal-objects-inl.h"
#include "src/objects/lookup-cache.h"
#include "src/objects/map.h"
#include "src/objects/microtask.h"
#include "src/objects/objects-inl.h"
#include "src/objects/oddball-inl.h"
#include "src/objects/ordered-hash-table.h"
#include "src/objects/promise.h"
#include "src/objects/property-descriptor-object.h"
#include "src/objects/script.h"
#include "src/objects/shared-function-info.h"
#include "src/objects/smi.h"
#include "src/objects/source-text-module.h"
#include "src/objects/stack-frame-info.h"
#include "src/objects/string.h"
#include "src/objects/synthetic-module.h"
#include "src/objects/template-objects-inl.h"
#include "src/regexp/regexp.h"
#include "src/wasm/wasm-objects.h"
#include "torque-generated/class-definitions.h"
#include "torque-generated/exported-class-definitions-inl.h"
#include "torque-generated/internal-class-definitions-inl.h"
namespace v8 {
namespace internal {
namespace {
Handle<SharedFunctionInfo> CreateSharedFunctionInfo(
Isolate* isolate, Builtins::Name builtin_id, int len,
FunctionKind kind = FunctionKind::kNormalFunction) {
Handle<SharedFunctionInfo> shared =
isolate->factory()->NewSharedFunctionInfoForBuiltin(
isolate->factory()->empty_string(), builtin_id, kind);
shared->set_internal_formal_parameter_count(len);
shared->set_length(len);
return shared;
}
} // namespace
bool SetupIsolateDelegate::SetupHeapInternal(Heap* heap) {
return heap->CreateHeapObjects();
}
bool Heap::CreateHeapObjects() {
// Create initial maps.
if (!CreateInitialMaps()) return false;
CreateApiObjects();
// Create initial objects
CreateInitialObjects();
CreateInternalAccessorInfoObjects();
CHECK_EQ(0u, gc_count_);
set_native_contexts_list(ReadOnlyRoots(this).undefined_value());
set_allocation_sites_list(ReadOnlyRoots(this).undefined_value());
set_dirty_js_finalization_registries_list(
ReadOnlyRoots(this).undefined_value());
set_dirty_js_finalization_registries_list_tail(
ReadOnlyRoots(this).undefined_value());
return true;
}
const Heap::StringTypeTable Heap::string_type_table[] = {
#define STRING_TYPE_ELEMENT(type, size, name, CamelName) \
{type, size, RootIndex::k##CamelName##Map},
STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
#undef STRING_TYPE_ELEMENT
};
const Heap::ConstantStringTable Heap::constant_string_table[] = {
{"", RootIndex::kempty_string},
#define CONSTANT_STRING_ELEMENT(_, name, contents) \
{contents, RootIndex::k##name},
INTERNALIZED_STRING_LIST_GENERATOR(CONSTANT_STRING_ELEMENT, /* not used */)
#undef CONSTANT_STRING_ELEMENT
};
const Heap::StructTable Heap::struct_table[] = {
#define STRUCT_TABLE_ELEMENT(TYPE, Name, name) \
{TYPE, Name::kSize, RootIndex::k##Name##Map},
STRUCT_LIST(STRUCT_TABLE_ELEMENT)
#undef STRUCT_TABLE_ELEMENT
#define ALLOCATION_SITE_ELEMENT(_, TYPE, Name, Size, name) \
{TYPE, Name::kSize##Size, RootIndex::k##Name##Size##Map},
ALLOCATION_SITE_LIST(ALLOCATION_SITE_ELEMENT, /* not used */)
#undef ALLOCATION_SITE_ELEMENT
#define DATA_HANDLER_ELEMENT(_, TYPE, Name, Size, name) \
{TYPE, Name::kSizeWithData##Size, RootIndex::k##Name##Size##Map},
DATA_HANDLER_LIST(DATA_HANDLER_ELEMENT, /* not used */)
#undef DATA_HANDLER_ELEMENT
};
AllocationResult Heap::AllocateMap(InstanceType instance_type,
int instance_size,
ElementsKind elements_kind,
int inobject_properties) {
STATIC_ASSERT(LAST_JS_OBJECT_TYPE == LAST_TYPE);
bool is_js_object = InstanceTypeChecker::IsJSObject(instance_type);
bool is_wasm_object =
(instance_type == WASM_STRUCT_TYPE || instance_type == WASM_ARRAY_TYPE);
DCHECK_IMPLIES(is_js_object &&
!Map::CanHaveFastTransitionableElementsKind(instance_type),
IsDictionaryElementsKind(elements_kind) ||
IsTerminalElementsKind(elements_kind));
HeapObject result;
// JSObjects have maps with a mutable prototype_validity_cell, so they cannot
// go in RO_SPACE. Maps for managed Wasm objects have mutable subtype lists.
bool is_mutable = is_js_object || is_wasm_object;
AllocationResult allocation =
AllocateRaw(Map::kSize, is_mutable ? AllocationType::kMap
: AllocationType::kReadOnly);
if (!allocation.To(&result)) return allocation;
result.set_map_after_allocation(ReadOnlyRoots(this).meta_map(),
SKIP_WRITE_BARRIER);
Map map = isolate()->factory()->InitializeMap(
Map::cast(result), instance_type, instance_size, elements_kind,
inobject_properties);
return map;
}
AllocationResult Heap::AllocatePartialMap(InstanceType instance_type,
int instance_size) {
Object result;
AllocationResult allocation =
AllocateRaw(Map::kSize, AllocationType::kReadOnly);
if (!allocation.To(&result)) return allocation;
// Map::cast cannot be used due to uninitialized map field.
Map map = Map::unchecked_cast(result);
map.set_map_after_allocation(
Map::unchecked_cast(isolate()->root(RootIndex::kMetaMap)),
SKIP_WRITE_BARRIER);
map.set_instance_type(instance_type);
map.set_instance_size(instance_size);
// Initialize to only containing tagged fields.
if (FLAG_unbox_double_fields) {
map.set_layout_descriptor(LayoutDescriptor::FastPointerLayout(),
kReleaseStore);
}
// GetVisitorId requires a properly initialized LayoutDescriptor.
map.set_visitor_id(Map::GetVisitorId(map));
map.set_inobject_properties_start_or_constructor_function_index(0);
DCHECK(!map.IsJSObjectMap());
map.set_prototype_validity_cell(Smi::FromInt(Map::kPrototypeChainValid));
map.SetInObjectUnusedPropertyFields(0);
map.set_bit_field(0);
map.set_bit_field2(0);
int bit_field3 =
Map::Bits3::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
Map::Bits3::OwnsDescriptorsBit::encode(true) |
Map::Bits3::ConstructionCounterBits::encode(Map::kNoSlackTracking);
map.set_bit_field3(bit_field3);
DCHECK(!map.is_in_retained_map_list());
map.clear_padding();
map.set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
return map;
}
void Heap::FinalizePartialMap(Map map) {
ReadOnlyRoots roots(this);
map.set_dependent_code(DependentCode::cast(roots.empty_weak_fixed_array()));
map.set_raw_transitions(MaybeObject::FromSmi(Smi::zero()));
map.SetInstanceDescriptors(isolate(), roots.empty_descriptor_array(), 0);
if (FLAG_unbox_double_fields) {
map.set_layout_descriptor(LayoutDescriptor::FastPointerLayout(),
kReleaseStore);
}
map.set_prototype(roots.null_value());
map.set_constructor_or_backpointer(roots.null_value());
}
AllocationResult Heap::Allocate(Map map, AllocationType allocation_type) {
DCHECK(map.instance_type() != MAP_TYPE);
int size = map.instance_size();
HeapObject result;
AllocationResult allocation = AllocateRaw(size, allocation_type);
if (!allocation.To(&result)) return allocation;
// New space objects are allocated white.
WriteBarrierMode write_barrier_mode =
allocation_type == AllocationType::kYoung ? SKIP_WRITE_BARRIER
: UPDATE_WRITE_BARRIER;
result.set_map_after_allocation(map, write_barrier_mode);
return result;
}
bool Heap::CreateInitialMaps() {
HeapObject obj;
{
AllocationResult allocation = AllocatePartialMap(MAP_TYPE, Map::kSize);
if (!allocation.To(&obj)) return false;
}
// Map::cast cannot be used due to uninitialized map field.
Map new_meta_map = Map::unchecked_cast(obj);
set_meta_map(new_meta_map);
new_meta_map.set_map_after_allocation(new_meta_map);
ReadOnlyRoots roots(this);
{ // Partial map allocation
#define ALLOCATE_PARTIAL_MAP(instance_type, size, field_name) \
{ \
Map map; \
if (!AllocatePartialMap((instance_type), (size)).To(&map)) return false; \
set_##field_name##_map(map); \
}
ALLOCATE_PARTIAL_MAP(FIXED_ARRAY_TYPE, kVariableSizeSentinel, fixed_array);
ALLOCATE_PARTIAL_MAP(WEAK_FIXED_ARRAY_TYPE, kVariableSizeSentinel,
weak_fixed_array);
ALLOCATE_PARTIAL_MAP(WEAK_ARRAY_LIST_TYPE, kVariableSizeSentinel,
weak_array_list);
ALLOCATE_PARTIAL_MAP(FIXED_ARRAY_TYPE, kVariableSizeSentinel,
fixed_cow_array)
DCHECK_NE(roots.fixed_array_map(), roots.fixed_cow_array_map());
ALLOCATE_PARTIAL_MAP(DESCRIPTOR_ARRAY_TYPE, kVariableSizeSentinel,
descriptor_array)
ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, undefined);
ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, null);
ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, the_hole);
#undef ALLOCATE_PARTIAL_MAP
}
// Allocate the empty array.
{
AllocationResult alloc =
AllocateRaw(FixedArray::SizeFor(0), AllocationType::kReadOnly);
if (!alloc.To(&obj)) return false;
obj.set_map_after_allocation(roots.fixed_array_map(), SKIP_WRITE_BARRIER);
FixedArray::cast(obj).set_length(0);
}
set_empty_fixed_array(FixedArray::cast(obj));
{
AllocationResult alloc =
AllocateRaw(WeakFixedArray::SizeFor(0), AllocationType::kReadOnly);
if (!alloc.To(&obj)) return false;
obj.set_map_after_allocation(roots.weak_fixed_array_map(),
SKIP_WRITE_BARRIER);
WeakFixedArray::cast(obj).set_length(0);
}
set_empty_weak_fixed_array(WeakFixedArray::cast(obj));
{
AllocationResult allocation = AllocateRaw(WeakArrayList::SizeForCapacity(0),
AllocationType::kReadOnly);
if (!allocation.To(&obj)) return false;
obj.set_map_after_allocation(roots.weak_array_list_map(),
SKIP_WRITE_BARRIER);
WeakArrayList::cast(obj).set_capacity(0);
WeakArrayList::cast(obj).set_length(0);
}
set_empty_weak_array_list(WeakArrayList::cast(obj));
{
AllocationResult allocation =
Allocate(roots.null_map(), AllocationType::kReadOnly);
if (!allocation.To(&obj)) return false;
}
set_null_value(Oddball::cast(obj));
Oddball::cast(obj).set_kind(Oddball::kNull);
{
AllocationResult allocation =
Allocate(roots.undefined_map(), AllocationType::kReadOnly);
if (!allocation.To(&obj)) return false;
}
set_undefined_value(Oddball::cast(obj));
Oddball::cast(obj).set_kind(Oddball::kUndefined);
DCHECK(!InYoungGeneration(roots.undefined_value()));
{
AllocationResult allocation =
Allocate(roots.the_hole_map(), AllocationType::kReadOnly);
if (!allocation.To(&obj)) return false;
}
set_the_hole_value(Oddball::cast(obj));
Oddball::cast(obj).set_kind(Oddball::kTheHole);
// Set preliminary exception sentinel value before actually initializing it.
set_exception(roots.null_value());
// Setup the struct maps first (needed for the EnumCache).
for (unsigned i = 0; i < arraysize(struct_table); i++) {
const StructTable& entry = struct_table[i];
Map map;
if (!AllocatePartialMap(entry.type, entry.size).To(&map)) return false;
roots_table()[entry.index] = map.ptr();
}
// Allocate the empty enum cache.
{
AllocationResult allocation =
Allocate(roots.enum_cache_map(), AllocationType::kReadOnly);
if (!allocation.To(&obj)) return false;
}
set_empty_enum_cache(EnumCache::cast(obj));
EnumCache::cast(obj).set_keys(roots.empty_fixed_array());
EnumCache::cast(obj).set_indices(roots.empty_fixed_array());
// Allocate the empty descriptor array.
{
int size = DescriptorArray::SizeFor(0);
if (!AllocateRaw(size, AllocationType::kReadOnly).To(&obj)) return false;
obj.set_map_after_allocation(roots.descriptor_array_map(),
SKIP_WRITE_BARRIER);
DescriptorArray array = DescriptorArray::cast(obj);
array.Initialize(roots.empty_enum_cache(), roots.undefined_value(), 0, 0);
}
set_empty_descriptor_array(DescriptorArray::cast(obj));
// Fix the instance_descriptors for the existing maps.
FinalizePartialMap(roots.meta_map());
FinalizePartialMap(roots.fixed_array_map());
FinalizePartialMap(roots.weak_fixed_array_map());
FinalizePartialMap(roots.weak_array_list_map());
FinalizePartialMap(roots.fixed_cow_array_map());
FinalizePartialMap(roots.descriptor_array_map());
FinalizePartialMap(roots.undefined_map());
roots.undefined_map().set_is_undetectable(true);
FinalizePartialMap(roots.null_map());
roots.null_map().set_is_undetectable(true);
FinalizePartialMap(roots.the_hole_map());
for (unsigned i = 0; i < arraysize(struct_table); ++i) {
const StructTable& entry = struct_table[i];
FinalizePartialMap(Map::cast(Object(roots_table()[entry.index])));
}
{ // Map allocation
#define ALLOCATE_MAP(instance_type, size, field_name) \
{ \
Map map; \
if (!AllocateMap((instance_type), size).To(&map)) return false; \
set_##field_name##_map(map); \
}
#define ALLOCATE_VARSIZE_MAP(instance_type, field_name) \
ALLOCATE_MAP(instance_type, kVariableSizeSentinel, field_name)
#define ALLOCATE_PRIMITIVE_MAP(instance_type, size, field_name, \
constructor_function_index) \
{ \
ALLOCATE_MAP((instance_type), (size), field_name); \
roots.field_name##_map().SetConstructorFunctionIndex( \
(constructor_function_index)); \
}
ALLOCATE_VARSIZE_MAP(SCOPE_INFO_TYPE, scope_info)
ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, module_info)
ALLOCATE_VARSIZE_MAP(CLOSURE_FEEDBACK_CELL_ARRAY_TYPE,
closure_feedback_cell_array)
ALLOCATE_VARSIZE_MAP(FEEDBACK_VECTOR_TYPE, feedback_vector)
ALLOCATE_PRIMITIVE_MAP(HEAP_NUMBER_TYPE, HeapNumber::kSize, heap_number,
Context::NUMBER_FUNCTION_INDEX)
ALLOCATE_PRIMITIVE_MAP(SYMBOL_TYPE, Symbol::kSize, symbol,
Context::SYMBOL_FUNCTION_INDEX)
ALLOCATE_MAP(FOREIGN_TYPE, Foreign::kSize, foreign)
ALLOCATE_VARSIZE_MAP(STRONG_DESCRIPTOR_ARRAY_TYPE, strong_descriptor_array)
ALLOCATE_PRIMITIVE_MAP(ODDBALL_TYPE, Oddball::kSize, boolean,
Context::BOOLEAN_FUNCTION_INDEX);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, uninitialized);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, arguments_marker);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, exception);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, termination_exception);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, optimized_out);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, stale_register);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, self_reference_marker);
ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, basic_block_counters_marker);
ALLOCATE_VARSIZE_MAP(BIGINT_TYPE, bigint);
for (unsigned i = 0; i < arraysize(string_type_table); i++) {
const StringTypeTable& entry = string_type_table[i];
Map map;
if (!AllocateMap(entry.type, entry.size).To(&map)) return false;
map.SetConstructorFunctionIndex(Context::STRING_FUNCTION_INDEX);
// Mark cons string maps as unstable, because their objects can change
// maps during GC.
if (StringShape(entry.type).IsCons()) map.mark_unstable();
roots_table()[entry.index] = map.ptr();
}
ALLOCATE_VARSIZE_MAP(FIXED_DOUBLE_ARRAY_TYPE, fixed_double_array)
roots.fixed_double_array_map().set_elements_kind(HOLEY_DOUBLE_ELEMENTS);
ALLOCATE_VARSIZE_MAP(FEEDBACK_METADATA_TYPE, feedback_metadata)
ALLOCATE_VARSIZE_MAP(BYTE_ARRAY_TYPE, byte_array)
ALLOCATE_VARSIZE_MAP(BYTECODE_ARRAY_TYPE, bytecode_array)
ALLOCATE_VARSIZE_MAP(FREE_SPACE_TYPE, free_space)
ALLOCATE_VARSIZE_MAP(PROPERTY_ARRAY_TYPE, property_array)
ALLOCATE_VARSIZE_MAP(SMALL_ORDERED_HASH_MAP_TYPE, small_ordered_hash_map)
ALLOCATE_VARSIZE_MAP(SMALL_ORDERED_HASH_SET_TYPE, small_ordered_hash_set)
ALLOCATE_VARSIZE_MAP(SMALL_ORDERED_NAME_DICTIONARY_TYPE,
small_ordered_name_dictionary)
#define TORQUE_ALLOCATE_MAP(NAME, Name, name) \
ALLOCATE_MAP(NAME, Name::kSize, name)
TORQUE_DEFINED_FIXED_INSTANCE_TYPE_LIST(TORQUE_ALLOCATE_MAP);
#undef TORQUE_ALLOCATE_MAP
#define TORQUE_ALLOCATE_VARSIZE_MAP(NAME, Name, name) \
ALLOCATE_VARSIZE_MAP(NAME, name)
TORQUE_DEFINED_VARSIZE_INSTANCE_TYPE_LIST(TORQUE_ALLOCATE_VARSIZE_MAP);
#undef TORQUE_ALLOCATE_VARSIZE_MAP
ALLOCATE_VARSIZE_MAP(CODE_TYPE, code)
ALLOCATE_MAP(CELL_TYPE, Cell::kSize, cell);
{
// The invalid_prototype_validity_cell is needed for JSObject maps.
Smi value = Smi::FromInt(Map::kPrototypeChainInvalid);
AllocationResult alloc = AllocateRaw(Cell::kSize, AllocationType::kOld);
if (!alloc.To(&obj)) return false;
obj.set_map_after_allocation(roots.cell_map(), SKIP_WRITE_BARRIER);
Cell::cast(obj).set_value(value);
set_invalid_prototype_validity_cell(Cell::cast(obj));
}
ALLOCATE_MAP(PROPERTY_CELL_TYPE, PropertyCell::kSize, global_property_cell)
ALLOCATE_MAP(FILLER_TYPE, kTaggedSize, one_pointer_filler)
ALLOCATE_MAP(FILLER_TYPE, 2 * kTaggedSize, two_pointer_filler)
// The "no closures" and "one closure" FeedbackCell maps need
// to be marked unstable because their objects can change maps.
ALLOCATE_MAP(FEEDBACK_CELL_TYPE, FeedbackCell::kAlignedSize,
no_closures_cell)
roots.no_closures_cell_map().mark_unstable();
ALLOCATE_MAP(FEEDBACK_CELL_TYPE, FeedbackCell::kAlignedSize,
one_closure_cell)
roots.one_closure_cell_map().mark_unstable();
ALLOCATE_MAP(FEEDBACK_CELL_TYPE, FeedbackCell::kAlignedSize,
many_closures_cell)
ALLOCATE_VARSIZE_MAP(TRANSITION_ARRAY_TYPE, transition_array)
ALLOCATE_VARSIZE_MAP(HASH_TABLE_TYPE, hash_table)
ALLOCATE_VARSIZE_MAP(ORDERED_HASH_MAP_TYPE, ordered_hash_map)
ALLOCATE_VARSIZE_MAP(ORDERED_HASH_SET_TYPE, ordered_hash_set)
ALLOCATE_VARSIZE_MAP(ORDERED_NAME_DICTIONARY_TYPE, ordered_name_dictionary)
ALLOCATE_VARSIZE_MAP(NAME_DICTIONARY_TYPE, name_dictionary)
ALLOCATE_VARSIZE_MAP(GLOBAL_DICTIONARY_TYPE, global_dictionary)
ALLOCATE_VARSIZE_MAP(NUMBER_DICTIONARY_TYPE, number_dictionary)
ALLOCATE_VARSIZE_MAP(SIMPLE_NUMBER_DICTIONARY_TYPE,
simple_number_dictionary)
ALLOCATE_VARSIZE_MAP(EMBEDDER_DATA_ARRAY_TYPE, embedder_data_array)
ALLOCATE_VARSIZE_MAP(EPHEMERON_HASH_TABLE_TYPE, ephemeron_hash_table)
ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, array_list)
ALLOCATE_VARSIZE_MAP(SCRIPT_CONTEXT_TABLE_TYPE, script_context_table)
ALLOCATE_VARSIZE_MAP(OBJECT_BOILERPLATE_DESCRIPTION_TYPE,
object_boilerplate_description)
ALLOCATE_VARSIZE_MAP(COVERAGE_INFO_TYPE, coverage_info);
ALLOCATE_MAP(CALL_HANDLER_INFO_TYPE, CallHandlerInfo::kSize,
side_effect_call_handler_info)
ALLOCATE_MAP(CALL_HANDLER_INFO_TYPE, CallHandlerInfo::kSize,
side_effect_free_call_handler_info)
ALLOCATE_MAP(CALL_HANDLER_INFO_TYPE, CallHandlerInfo::kSize,
next_call_side_effect_free_call_handler_info)
ALLOCATE_VARSIZE_MAP(PREPARSE_DATA_TYPE, preparse_data)
ALLOCATE_MAP(UNCOMPILED_DATA_WITHOUT_PREPARSE_DATA_TYPE,
UncompiledDataWithoutPreparseData::kSize,
uncompiled_data_without_preparse_data)
ALLOCATE_MAP(UNCOMPILED_DATA_WITH_PREPARSE_DATA_TYPE,
UncompiledDataWithPreparseData::kSize,
uncompiled_data_with_preparse_data)
ALLOCATE_MAP(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kAlignedSize,
shared_function_info)
ALLOCATE_MAP(SOURCE_TEXT_MODULE_TYPE, SourceTextModule::kSize,
source_text_module)
ALLOCATE_MAP(SYNTHETIC_MODULE_TYPE, SyntheticModule::kSize,
synthetic_module)
ALLOCATE_MAP(CODE_DATA_CONTAINER_TYPE, CodeDataContainer::kSize,
code_data_container)
// The wasm_rttcanon_* maps are never used for real objects, only as
// sentinels. They are maps so that they fit in with their subtype maps
// (which are real maps).
ALLOCATE_MAP(WASM_STRUCT_TYPE, 0, wasm_rttcanon_eqref)
ALLOCATE_MAP(WASM_STRUCT_TYPE, 0, wasm_rttcanon_externref)
ALLOCATE_MAP(WASM_STRUCT_TYPE, 0, wasm_rttcanon_funcref)
ALLOCATE_MAP(WASM_STRUCT_TYPE, 0, wasm_rttcanon_i31ref)
ALLOCATE_MAP(WASM_TYPE_INFO_TYPE, WasmTypeInfo::kSize, wasm_type_info)
ALLOCATE_MAP(WEAK_CELL_TYPE, WeakCell::kSize, weak_cell)
ALLOCATE_MAP(JS_MESSAGE_OBJECT_TYPE, JSMessageObject::kHeaderSize,
message_object)
ALLOCATE_MAP(JS_OBJECT_TYPE, JSObject::kHeaderSize + kEmbedderDataSlotSize,
external)
external_map().set_is_extensible(false);
#undef ALLOCATE_PRIMITIVE_MAP
#undef ALLOCATE_VARSIZE_MAP
#undef ALLOCATE_MAP
}
{
AllocationResult alloc =
AllocateRaw(FixedArray::SizeFor(0), AllocationType::kReadOnly);
if (!alloc.To(&obj)) return false;
obj.set_map_after_allocation(roots.scope_info_map(), SKIP_WRITE_BARRIER);
FixedArray::cast(obj).set_length(0);
}
set_empty_scope_info(ScopeInfo::cast(obj));
{
// Empty boilerplate needs a field for literal_flags
AllocationResult alloc =
AllocateRaw(FixedArray::SizeFor(1), AllocationType::kReadOnly);
if (!alloc.To(&obj)) return false;
obj.set_map_after_allocation(roots.object_boilerplate_description_map(),
SKIP_WRITE_BARRIER);
FixedArray::cast(obj).set_length(1);
FixedArray::cast(obj).set(ObjectBoilerplateDescription::kLiteralTypeOffset,
Smi::zero());
}
set_empty_object_boilerplate_description(
ObjectBoilerplateDescription::cast(obj));
{
// Empty array boilerplate description
AllocationResult alloc = Allocate(roots.array_boilerplate_description_map(),
AllocationType::kReadOnly);
if (!alloc.To(&obj)) return false;
ArrayBoilerplateDescription::cast(obj).set_constant_elements(
roots.empty_fixed_array());
ArrayBoilerplateDescription::cast(obj).set_elements_kind(
ElementsKind::PACKED_SMI_ELEMENTS);
}
set_empty_array_boilerplate_description(
ArrayBoilerplateDescription::cast(obj));
{
AllocationResult allocation =
Allocate(roots.boolean_map(), AllocationType::kReadOnly);
if (!allocation.To(&obj)) return false;
}
set_true_value(Oddball::cast(obj));
Oddball::cast(obj).set_kind(Oddball::kTrue);
{
AllocationResult allocation =
Allocate(roots.boolean_map(), AllocationType::kReadOnly);
if (!allocation.To(&obj)) return false;
}
set_false_value(Oddball::cast(obj));
Oddball::cast(obj).set_kind(Oddball::kFalse);
// Empty arrays.
{
if (!AllocateRaw(ByteArray::SizeFor(0), AllocationType::kReadOnly).To(&obj))
return false;
obj.set_map_after_allocation(roots.byte_array_map(), SKIP_WRITE_BARRIER);
ByteArray::cast(obj).set_length(0);
set_empty_byte_array(ByteArray::cast(obj));
}
{
if (!AllocateRaw(FixedArray::SizeFor(0), AllocationType::kReadOnly)
.To(&obj)) {
return false;
}
obj.set_map_after_allocation(roots.property_array_map(),
SKIP_WRITE_BARRIER);
PropertyArray::cast(obj).initialize_length(0);
set_empty_property_array(PropertyArray::cast(obj));
}
{
if (!AllocateRaw(FixedArray::SizeFor(0), AllocationType::kReadOnly)
.To(&obj)) {
return false;
}
obj.set_map_after_allocation(roots.closure_feedback_cell_array_map(),
SKIP_WRITE_BARRIER);
FixedArray::cast(obj).set_length(0);
set_empty_closure_feedback_cell_array(ClosureFeedbackCellArray::cast(obj));
}
// Set up the WasmTypeInfo objects for built-in generic Wasm RTTs.
#define ALLOCATE_TYPE_INFO(which) \
{ \
int slot_count = ArrayList::kHeaderFields; \
if (!AllocateRaw(ArrayList::SizeFor(slot_count), AllocationType::kOld) \
.To(&obj)) { \
return false; \
} \
obj.set_map_after_allocation(roots.array_list_map()); \
ArrayList subtypes = ArrayList::cast(obj); \
subtypes.set_length(slot_count); \
subtypes.SetLength(0); \
if (!AllocateRaw(WasmTypeInfo::kSize, AllocationType::kOld).To(&obj)) { \
return false; \
} \
obj.set_map_after_allocation(roots.wasm_type_info_map(), \
SKIP_WRITE_BARRIER); \
WasmTypeInfo type_info = WasmTypeInfo::cast(obj); \
type_info.set_subtypes(subtypes); \
type_info.set_parent(roots.null_map()); \
type_info.clear_foreign_address(isolate()); \
wasm_rttcanon_##which##_map().set_wasm_type_info(type_info); \
}
ALLOCATE_TYPE_INFO(eqref)
ALLOCATE_TYPE_INFO(externref)
ALLOCATE_TYPE_INFO(funcref)
ALLOCATE_TYPE_INFO(i31ref)
#undef ALLOCATE_TYPE_INFO
DCHECK(!InYoungGeneration(roots.empty_fixed_array()));
roots.bigint_map().SetConstructorFunctionIndex(
Context::BIGINT_FUNCTION_INDEX);
return true;
}
void Heap::CreateApiObjects() {
Isolate* isolate = this->isolate();
HandleScope scope(isolate);
set_message_listeners(*TemplateList::New(isolate, 2));
Handle<InterceptorInfo> info =
Handle<InterceptorInfo>::cast(isolate->factory()->NewStruct(
INTERCEPTOR_INFO_TYPE, AllocationType::kReadOnly));
info->set_flags(0);
set_noop_interceptor_info(*info);
}
void Heap::CreateInitialObjects() {
HandleScope scope(isolate());
Factory* factory = isolate()->factory();
ReadOnlyRoots roots(this);
// The -0 value must be set before NewNumber works.
set_minus_zero_value(
*factory->NewHeapNumber<AllocationType::kReadOnly>(-0.0));
DCHECK(std::signbit(roots.minus_zero_value().Number()));
set_nan_value(*factory->NewHeapNumber<AllocationType::kReadOnly>(
std::numeric_limits<double>::quiet_NaN()));
set_hole_nan_value(*factory->NewHeapNumberFromBits<AllocationType::kReadOnly>(
kHoleNanInt64));
set_infinity_value(
*factory->NewHeapNumber<AllocationType::kReadOnly>(V8_INFINITY));
set_minus_infinity_value(
*factory->NewHeapNumber<AllocationType::kReadOnly>(-V8_INFINITY));
set_hash_seed(*factory->NewByteArray(kInt64Size, AllocationType::kReadOnly));
InitializeHashSeed();
// There's no "current microtask" in the beginning.
set_current_microtask(roots.undefined_value());
set_weak_refs_keep_during_job(roots.undefined_value());
// Allocate cache for single character one byte strings.
set_single_character_string_cache(*factory->NewFixedArray(
String::kMaxOneByteCharCode + 1, AllocationType::kOld));
for (unsigned i = 0; i < arraysize(constant_string_table); i++) {
Handle<String> str =
factory->InternalizeUtf8String(constant_string_table[i].contents);
roots_table()[constant_string_table[i].index] = str->ptr();
}
// Allocate
// Finish initializing oddballs after creating the string table.
Oddball::Initialize(isolate(), factory->undefined_value(), "undefined",
factory->nan_value(), "undefined", Oddball::kUndefined);
// Initialize the null_value.
Oddball::Initialize(isolate(), factory->null_value(), "null",
handle(Smi::zero(), isolate()), "object", Oddball::kNull);
// Initialize the_hole_value.
Oddball::Initialize(isolate(), factory->the_hole_value(), "hole",
factory->hole_nan_value(), "undefined",
Oddball::kTheHole);
// Initialize the true_value.
Oddball::Initialize(isolate(), factory->true_value(), "true",
handle(Smi::FromInt(1), isolate()), "boolean",
Oddball::kTrue);
// Initialize the false_value.
Oddball::Initialize(isolate(), factory->false_value(), "false",
handle(Smi::zero(), isolate()), "boolean",
Oddball::kFalse);
set_uninitialized_value(
*factory->NewOddball(factory->uninitialized_map(), "uninitialized",
handle(Smi::FromInt(-1), isolate()), "undefined",
Oddball::kUninitialized));
set_arguments_marker(
*factory->NewOddball(factory->arguments_marker_map(), "arguments_marker",
handle(Smi::FromInt(-4), isolate()), "undefined",
Oddball::kArgumentsMarker));
set_termination_exception(*factory->NewOddball(
factory->termination_exception_map(), "termination_exception",
handle(Smi::FromInt(-3), isolate()), "undefined", Oddball::kOther));
set_exception(*factory->NewOddball(factory->exception_map(), "exception",
handle(Smi::FromInt(-5), isolate()),
"undefined", Oddball::kException));
set_optimized_out(*factory->NewOddball(factory->optimized_out_map(),
"optimized_out",
handle(Smi::FromInt(-6), isolate()),
"undefined", Oddball::kOptimizedOut));
set_stale_register(
*factory->NewOddball(factory->stale_register_map(), "stale_register",
handle(Smi::FromInt(-7), isolate()), "undefined",
Oddball::kStaleRegister));
// Initialize marker objects used during compilation.
set_self_reference_marker(*factory->NewSelfReferenceMarker());
set_basic_block_counters_marker(*factory->NewBasicBlockCountersMarker());
set_interpreter_entry_trampoline_for_profiling(roots.undefined_value());
{
HandleScope scope(isolate());
#define SYMBOL_INIT(_, name) \
{ \
Handle<Symbol> symbol( \
isolate()->factory()->NewPrivateSymbol(AllocationType::kReadOnly)); \
roots_table()[RootIndex::k##name] = symbol->ptr(); \
}
PRIVATE_SYMBOL_LIST_GENERATOR(SYMBOL_INIT, /* not used */)
#undef SYMBOL_INIT
}
{
HandleScope scope(isolate());
#define SYMBOL_INIT(_, name, description) \
Handle<Symbol> name = factory->NewSymbol(AllocationType::kReadOnly); \
Handle<String> name##d = factory->InternalizeUtf8String(#description); \
name->set_description(*name##d); \
roots_table()[RootIndex::k##name] = name->ptr();
PUBLIC_SYMBOL_LIST_GENERATOR(SYMBOL_INIT, /* not used */)
#undef SYMBOL_INIT
#define SYMBOL_INIT(_, name, description) \
Handle<Symbol> name = factory->NewSymbol(AllocationType::kReadOnly); \
Handle<String> name##d = factory->InternalizeUtf8String(#description); \
name->set_is_well_known_symbol(true); \
name->set_description(*name##d); \
roots_table()[RootIndex::k##name] = name->ptr();
WELL_KNOWN_SYMBOL_LIST_GENERATOR(SYMBOL_INIT, /* not used */)
#undef SYMBOL_INIT
// Mark "Interesting Symbols" appropriately.
to_string_tag_symbol->set_is_interesting_symbol(true);
}
Handle<NameDictionary> empty_property_dictionary = NameDictionary::New(
isolate(), 1, AllocationType::kReadOnly, USE_CUSTOM_MINIMUM_CAPACITY);
DCHECK(!empty_property_dictionary->HasSufficientCapacityToAdd(1));
set_empty_property_dictionary(*empty_property_dictionary);
set_public_symbol_table(*empty_property_dictionary);
set_api_symbol_table(*empty_property_dictionary);
set_api_private_symbol_table(*empty_property_dictionary);
set_number_string_cache(*factory->NewFixedArray(
kInitialNumberStringCacheSize * 2, AllocationType::kOld));
set_basic_block_profiling_data(ArrayList::cast(roots.empty_fixed_array()));
// Allocate cache for string split and regexp-multiple.
set_string_split_cache(*factory->NewFixedArray(
RegExpResultsCache::kRegExpResultsCacheSize, AllocationType::kOld));
set_regexp_multiple_cache(*factory->NewFixedArray(
RegExpResultsCache::kRegExpResultsCacheSize, AllocationType::kOld));
// Allocate FeedbackCell for builtins.
Handle<FeedbackCell> many_closures_cell =
factory->NewManyClosuresCell(factory->undefined_value());
set_many_closures_cell(*many_closures_cell);
set_detached_contexts(roots.empty_weak_array_list());
set_retaining_path_targets(roots.empty_weak_array_list());
set_feedback_vectors_for_profiling_tools(roots.undefined_value());
set_pending_optimize_for_test_bytecode(roots.undefined_value());
set_shared_wasm_memories(roots.empty_weak_array_list());
set_script_list(roots.empty_weak_array_list());
Handle<NumberDictionary> slow_element_dictionary = NumberDictionary::New(
isolate(), 1, AllocationType::kReadOnly, USE_CUSTOM_MINIMUM_CAPACITY);
DCHECK(!slow_element_dictionary->HasSufficientCapacityToAdd(1));
set_empty_slow_element_dictionary(*slow_element_dictionary);
set_materialized_objects(*factory->NewFixedArray(0, AllocationType::kOld));
// Handling of script id generation is in Heap::NextScriptId().
set_last_script_id(Smi::FromInt(v8::UnboundScript::kNoScriptId));
set_last_debugging_id(Smi::FromInt(DebugInfo::kNoDebuggingId));
set_next_template_serial_number(Smi::zero());
// Allocate the empty OrderedHashMap.
Handle<OrderedHashMap> empty_ordered_hash_map =
OrderedHashMap::AllocateEmpty(isolate(), AllocationType::kReadOnly)
.ToHandleChecked();
set_empty_ordered_hash_map(*empty_ordered_hash_map);
// Allocate the empty OrderedHashSet.
Handle<OrderedHashSet> empty_ordered_hash_set =
OrderedHashSet::AllocateEmpty(isolate(), AllocationType::kReadOnly)
.ToHandleChecked();
set_empty_ordered_hash_set(*empty_ordered_hash_set);
// Allocate the empty OrderedNameDictionary
Handle<OrderedNameDictionary> empty_ordered_property_dictionary =
OrderedNameDictionary::AllocateEmpty(isolate(), AllocationType::kReadOnly)
.ToHandleChecked();
set_empty_ordered_property_dictionary(*empty_ordered_property_dictionary);
// Allocate the empty FeedbackMetadata.
Handle<FeedbackMetadata> empty_feedback_metadata =
factory->NewFeedbackMetadata(0, 0, AllocationType::kReadOnly);
set_empty_feedback_metadata(*empty_feedback_metadata);
// Canonical scope arrays.
Handle<ScopeInfo> global_this_binding =
ScopeInfo::CreateGlobalThisBinding(isolate());
set_global_this_binding_scope_info(*global_this_binding);
Handle<ScopeInfo> empty_function =
ScopeInfo::CreateForEmptyFunction(isolate());
set_empty_function_scope_info(*empty_function);
Handle<ScopeInfo> native_scope_info =
ScopeInfo::CreateForNativeContext(isolate());
set_native_scope_info(*native_scope_info);
// Allocate the empty script.
Handle<Script> script = factory->NewScript(factory->empty_string());
script->set_type(Script::TYPE_NATIVE);
// This is used for exceptions thrown with no stack frames. Such exceptions
// can be shared everywhere.
script->set_origin_options(ScriptOriginOptions(true, false));
set_empty_script(*script);
{
Handle<PropertyCell> cell = factory->NewPropertyCell(
factory->empty_string(), AllocationType::kReadOnly);
cell->set_value(roots.the_hole_value());
set_empty_property_cell(*cell);
}
// Protectors
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_array_constructor_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_no_elements_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_array_iterator_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_map_iterator_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_set_iterator_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_is_concat_spreadable_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_array_species_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_typed_array_species_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_promise_species_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_regexp_species_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_string_iterator_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_string_length_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_array_buffer_detaching_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_promise_hook_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_promise_resolve_protector(*cell);
}
{
Handle<PropertyCell> cell =
factory->NewPropertyCell(factory->empty_string());
cell->set_value(Smi::FromInt(Protectors::kProtectorValid));
set_promise_then_protector(*cell);
}
set_serialized_objects(roots.empty_fixed_array());
set_serialized_global_proxy_sizes(roots.empty_fixed_array());
/* Canonical off-heap trampoline data */
set_off_heap_trampoline_relocation_info(
*Builtins::GenerateOffHeapTrampolineRelocInfo(isolate_));
set_trampoline_trivial_code_data_container(
*isolate()->factory()->NewCodeDataContainer(0,
AllocationType::kReadOnly));
set_trampoline_promise_rejection_code_data_container(
*isolate()->factory()->NewCodeDataContainer(
Code::IsPromiseRejectionField::encode(true),
AllocationType::kReadOnly));
// Evaluate the hash values which will then be cached in the strings.
isolate()->factory()->zero_string()->Hash();
isolate()->factory()->one_string()->Hash();
// Initialize builtins constants table.
set_builtins_constants_table(roots.empty_fixed_array());
// Initialize descriptor cache.
isolate_->descriptor_lookup_cache()->Clear();
// Initialize compilation cache.
isolate_->compilation_cache()->Clear();
// Create internal SharedFunctionInfos.
// Async functions:
{
Handle<SharedFunctionInfo> info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncFunctionAwaitRejectClosure, 1);
set_async_function_await_reject_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncFunctionAwaitResolveClosure, 1);
set_async_function_await_resolve_shared_fun(*info);
}
// Async generators:
{
Handle<SharedFunctionInfo> info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncGeneratorAwaitResolveClosure, 1);
set_async_generator_await_resolve_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncGeneratorAwaitRejectClosure, 1);
set_async_generator_await_reject_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncGeneratorYieldResolveClosure, 1);
set_async_generator_yield_resolve_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncGeneratorReturnResolveClosure, 1);
set_async_generator_return_resolve_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncGeneratorReturnClosedResolveClosure, 1);
set_async_generator_return_closed_resolve_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate(), Builtins::kAsyncGeneratorReturnClosedRejectClosure, 1);
set_async_generator_return_closed_reject_shared_fun(*info);
}
// AsyncIterator:
{
Handle<SharedFunctionInfo> info = CreateSharedFunctionInfo(
isolate_, Builtins::kAsyncIteratorValueUnwrap, 1);
set_async_iterator_value_unwrap_shared_fun(*info);
}
// Promises:
{
Handle<SharedFunctionInfo> info = CreateSharedFunctionInfo(
isolate_, Builtins::kPromiseCapabilityDefaultResolve, 1,
FunctionKind::kConciseMethod);
info->set_native(true);
info->set_function_map_index(
Context::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX);
set_promise_capability_default_resolve_shared_fun(*info);
info = CreateSharedFunctionInfo(isolate_,
Builtins::kPromiseCapabilityDefaultReject,
1, FunctionKind::kConciseMethod);
info->set_native(true);
info->set_function_map_index(
Context::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX);
set_promise_capability_default_reject_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate_, Builtins::kPromiseGetCapabilitiesExecutor, 2);
set_promise_get_capabilities_executor_shared_fun(*info);
}
// Promises / finally:
{
Handle<SharedFunctionInfo> info =
CreateSharedFunctionInfo(isolate(), Builtins::kPromiseThenFinally, 1);
info->set_native(true);
set_promise_then_finally_shared_fun(*info);
info =
CreateSharedFunctionInfo(isolate(), Builtins::kPromiseCatchFinally, 1);
info->set_native(true);
set_promise_catch_finally_shared_fun(*info);
info = CreateSharedFunctionInfo(isolate(),
Builtins::kPromiseValueThunkFinally, 0);
set_promise_value_thunk_finally_shared_fun(*info);
info = CreateSharedFunctionInfo(isolate(), Builtins::kPromiseThrowerFinally,
0);
set_promise_thrower_finally_shared_fun(*info);
}
// Promise combinators:
{
Handle<SharedFunctionInfo> info = CreateSharedFunctionInfo(
isolate_, Builtins::kPromiseAllResolveElementClosure, 1);
set_promise_all_resolve_element_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate_, Builtins::kPromiseAllSettledResolveElementClosure, 1);
set_promise_all_settled_resolve_element_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate_, Builtins::kPromiseAllSettledRejectElementClosure, 1);
set_promise_all_settled_reject_element_shared_fun(*info);
info = CreateSharedFunctionInfo(
isolate_, Builtins::kPromiseAnyRejectElementClosure, 1);
set_promise_any_reject_element_shared_fun(*info);
}
// ProxyRevoke:
{
Handle<SharedFunctionInfo> info =
CreateSharedFunctionInfo(isolate_, Builtins::kProxyRevoke, 0);
set_proxy_revoke_shared_fun(*info);
}
}
void Heap::CreateInternalAccessorInfoObjects() {
Isolate* isolate = this->isolate();
HandleScope scope(isolate);
Handle<AccessorInfo> accessor_info;
#define INIT_ACCESSOR_INFO(_, accessor_name, AccessorName, ...) \
accessor_info = Accessors::Make##AccessorName##Info(isolate); \
roots_table()[RootIndex::k##AccessorName##Accessor] = accessor_info->ptr();
ACCESSOR_INFO_LIST_GENERATOR(INIT_ACCESSOR_INFO, /* not used */)
#undef INIT_ACCESSOR_INFO
#define INIT_SIDE_EFFECT_FLAG(_, accessor_name, AccessorName, GetterType, \
SetterType) \
AccessorInfo::cast( \
Object(roots_table()[RootIndex::k##AccessorName##Accessor])) \
.set_getter_side_effect_type(SideEffectType::GetterType); \
AccessorInfo::cast( \
Object(roots_table()[RootIndex::k##AccessorName##Accessor])) \
.set_setter_side_effect_type(SideEffectType::SetterType);
ACCESSOR_INFO_LIST_GENERATOR(INIT_SIDE_EFFECT_FLAG, /* not used */)
#undef INIT_SIDE_EFFECT_FLAG
}
} // namespace internal
} // namespace v8
|
/* Mednafen - Multi-system Emulator
*
* This program 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.
*
* This program 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Support functions for the emulated system code-side of the debugger. */
#include "mednafen.h"
#ifdef WANT_DEBUGGER
static std::vector<AddressSpaceType> AddressSpaces;
static std::vector<const RegGroupType*> RegGroups;
// Currently only called on emulator startup, not game load...
void MDFNDBG_Init(void)
{
AddressSpaces.clear();
RegGroups.clear();
}
void MDFNDBG_PostGameLoad(void)
{
if(MDFNGameInfo->Debugger)
{
MDFNGameInfo->Debugger->AddressSpaces = &AddressSpaces;
MDFNGameInfo->Debugger->RegGroups = &RegGroups;
}
}
// Called on game close.
void MDFNDBG_Kill(void)
{
AddressSpaces.clear();
RegGroups.clear();
}
AddressSpaceType::AddressSpaceType() : TotalBits(0), NP2Size(0), IsWave(false), WaveFormat(ASPACE_WFMT_UNSIGNED), WaveBits(0),
GetAddressSpaceBytes(NULL), PutAddressSpaceBytes(NULL), private_data(NULL), EnableUsageMap(NULL),
UsageMapRead(NULL), UsageMapWrite(NULL), UsageReadMemUsed(0), UsageWriteMemUsed(0)
{
}
AddressSpaceType::~AddressSpaceType()
{
}
int ASpace_Add(void (*gasb)(const char *name, uint32 Address, uint32 Length, uint8 *Buffer),
void (*pasb)(const char *name, uint32 Address, uint32 Length, uint32 Granularity, bool hl, const uint8 *Buffer), const char *name, const char *long_name,
uint32 TotalBits, uint32 NP2Size)
{
AddressSpaceType newt;
newt.GetAddressSpaceBytes = gasb;
newt.PutAddressSpaceBytes = pasb;
newt.name = std::string(name);
newt.long_name = std::string(long_name);
newt.TotalBits = TotalBits;
newt.NP2Size = NP2Size;
AddressSpaces.push_back(newt);
return(AddressSpaces.size() - 1);
}
int ASpace_Add(const AddressSpaceType &newt)
{
AddressSpaces.push_back(newt);
return(AddressSpaces.size() - 1);
}
#if 0
// Returns number of new bytes allocated.
static INLINE uint64 IncUsageMap(uint64 *****UsageMap, const uint32 address)
{
uint64 ret = 0;
if(!(*UsageMap))
{
(*UsageMap) = (uint64 ****)MDFN_calloc(sizeof(uint64 ***), 256, "Usage map");
ret += sizeof(uint64 ***) * 256;
}
if(!(*UsageMap)[address >> 24])
{
(*UsageMap)[address >> 24] = (uint64 ***)MDFN_calloc(sizeof(uint64 **), 256, "Usage map");
ret += sizeof(uint64 **) * 256;
}
if(!(*UsageMap)[address >> 24][(address >> 16) & 0xFF])
{
(*UsageMap)[address >> 24][(address >> 16) & 0xFF] = (uint64 **)MDFN_calloc(sizeof(uint64 *), 256, "Usage map");
ret += sizeof(uint64 *) * 256;
}
if(!(*UsageMap)[address >> 24][(address >> 16) & 0xFF][(address >> 8) & 0xFF])
{
(*UsageMap)[address >> 24][(address >> 16) & 0xFF][(address >> 8) & 0xFF] = (uint64 *)MDFN_calloc(sizeof(uint64), 256, "Usage map");
ret += sizeof(uint64) * 256;
}
(*UsageMap)[address >> 24][(address >> 16) & 0xFF][(address >> 8) & 0xFF][address & 0xFF]++;
return(ret);
}
bool ASpace_Read(const int id, const uint32 address, const unsigned int size, const bool pre_bpoint)
{
AddressSpaceType *as;
assert(id > 0 && (const unsigned int)id < AddressSpaces.size());
as = &AddressSpaces[id];
if(pre_bpoint)
return(false);
else
{
as->UsageReadMemUsed += IncUsageMap(&as->UsageMapRead, address);
}
return(false);
}
bool ASpace_Write(const int id, const uint32 address, const uint32 value, const unsigned int size, const bool pre_bpoint)
{
AddressSpaceType *as;
assert(id > 0 && (const unsigned int)id < AddressSpaces.size());
as = &AddressSpaces[id];
if(pre_bpoint)
return(false);
else
{
as->UsageWriteMemUsed += IncUsageMap(&as->UsageMapWrite, address);
return(false);
}
}
static INLINE void ClearUsageMap(uint64 *****UsageMap)
{
// Maybe we should use an alloced memory vector to speed this up...
if((*UsageMap))
{
for(int a = 0; a < 256; a++)
{
if((*UsageMap)[a])
{
for(int b = 0; b < 256; b++)
{
if((*UsageMap)[a][b])
{
for(int c = 0; c < 256; c++)
{
if((*UsageMap)[a][b][c])
{
MDFN_free((*UsageMap)[a][b][c]);
(*UsageMap)[a][b][c] = NULL;
}
}
MDFN_free((*UsageMap)[a][b]);
(*UsageMap)[a][b] = NULL;
}
}
MDFN_free((*UsageMap)[a]);
(*UsageMap)[a] = NULL;
}
}
MDFN_free((*UsageMap));
(*UsageMap) = NULL;
}
}
void ASpace_ClearReadMap(const int id)
{
AddressSpaceType *as;
assert(id > 0 && (const unsigned int)id < AddressSpaces.size());
as = &AddressSpaces[id];
ClearUsageMap(&as->UsageMapRead);
as->UsageReadMemUsed = 0;
}
void ASpace_ClearWriteMap(const int id)
{
AddressSpaceType *as;
assert(id > 0 && (const unsigned int)id < AddressSpaces.size());
as = &AddressSpaces[id];
ClearUsageMap(&as->UsageMapWrite);
as->UsageWriteMemUsed = 0;
}
#endif
void MDFNDBG_ResetRegGroupsInfo(void)
{
RegGroups.clear();
}
void MDFNDBG_AddRegGroup(const RegGroupType* groupie)
{
RegGroups.push_back(groupie);
}
void ASpace_Reset(void)
{
AddressSpaces.clear();
}
#endif
|
// Arquivo cmd_update_caddie_item.hpp
// Criado em 14/05/2018 as 00:01 por Acrisio
// Defini��o da classe CmdUpdateCaddieItem
#pragma once
#ifndef _STDA_CMD_UPDATE_CADDIE_ITEM_HPP
#define _STDA_CMD_UPDATE_CADDIE_ITEM_HPP
#include "../../Projeto IOCP/PANGYA_DB/pangya_db.h"
#include "../TYPE/pangya_game_st.h"
namespace stdA {
class CmdUpdateCaddieItem : public pangya_db {
public:
explicit CmdUpdateCaddieItem(bool _waiter = false);
CmdUpdateCaddieItem(uint32_t _uid, std::string& _time, CaddieInfoEx& _ci, bool _waiter = false);
virtual ~CmdUpdateCaddieItem();
uint32_t getUID();
void setUID(uint32_t _uid);
std::string& getTime();
void setTime(std::string& _time);
CaddieInfoEx& getInfo();
void setInfo(CaddieInfoEx& _ci);
protected:
void lineResult(result_set::ctx_res* _result, uint32_t _index_result) override;
response* prepareConsulta(database& _db) override;
// get Class name
virtual std::string _getName() override { return "CmdUpdateCaddieItem"; };
virtual std::wstring _wgetName() override { return L"CmdUpdateCaddieItem"; };
private:
uint32_t m_uid;
std::string m_time;
CaddieInfoEx m_ci;
const char* m_szConsulta = "pangya.ProcUpdateCaddieItem";
};
}
#endif // !_STDA_CMD_UPDATE_CADDIE_ITEM_HPP
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.