text
stringlengths 5
1.04M
|
|---|
/* file: neural_networks_training_result_fpt.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* 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 "neural_networks_training_result.h"
using namespace daal::data_management;
using namespace daal::services;
namespace daal
{
namespace algorithms
{
namespace neural_networks
{
namespace training
{
template<typename algorithmFPType>
DAAL_EXPORT Status Result::allocate(const daal::algorithms::Input *input, const daal::algorithms::Parameter *parameter, const int method)
{
return Status();
}
template DAAL_EXPORT Status Result::allocate<DAAL_FPTYPE>(const daal::algorithms::Input *input, const daal::algorithms::Parameter *parameter, const int method);
}
}
}
}
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/signin/identity_manager_factory.h"
#include <memory>
#include <utility>
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/image_fetcher/image_decoder_impl.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/account_consistency_mode_manager.h"
#include "chrome/browser/signin/chrome_signin_client_factory.h"
#include "chrome/browser/signin/identity_manager_provider.h"
#include "chrome/browser/signin/signin_features.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_manager_builder.h"
#include "components/signin/public/webdata/token_web_data.h"
#include "content/public/browser/network_service_instance.h"
#if !defined(OS_ANDROID)
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/web_data_service_factory.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/keyed_service/core/service_access_type.h"
#include "components/signin/core/browser/cookie_settings_util.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/components/account_manager/account_manager_factory.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "components/account_manager_core/chromeos/account_manager_facade_factory.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#include "chrome/browser/lacros/account_manager/profile_account_manager.h"
#include "chrome/browser/lacros/account_manager/profile_account_manager_factory.h"
#include "components/account_manager_core/chromeos/account_manager_facade_factory.h"
#endif
#if defined(OS_WIN)
#include "base/bind.h"
#include "chrome/browser/signin/signin_util_win.h"
#endif
void IdentityManagerFactory::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
signin::IdentityManager::RegisterProfilePrefs(registry);
}
IdentityManagerFactory::IdentityManagerFactory()
: BrowserContextKeyedServiceFactory(
"IdentityManager",
BrowserContextDependencyManager::GetInstance()) {
#if !defined(OS_ANDROID)
DependsOn(WebDataServiceFactory::GetInstance());
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
if (base::FeatureList::IsEnabled(kMultiProfileAccountConsistency))
DependsOn(ProfileAccountManagerFactory::GetInstance());
#endif
DependsOn(ChromeSigninClientFactory::GetInstance());
signin::SetIdentityManagerProvider(
base::BindRepeating([](content::BrowserContext* context) {
return GetForProfile(Profile::FromBrowserContext(context));
}));
}
IdentityManagerFactory::~IdentityManagerFactory() {
signin::SetIdentityManagerProvider({});
}
// static
signin::IdentityManager* IdentityManagerFactory::GetForProfile(
Profile* profile) {
return static_cast<signin::IdentityManager*>(
GetInstance()->GetServiceForBrowserContext(profile, true));
}
// static
signin::IdentityManager* IdentityManagerFactory::GetForProfileIfExists(
const Profile* profile) {
return static_cast<signin::IdentityManager*>(
GetInstance()->GetServiceForBrowserContext(const_cast<Profile*>(profile),
false));
}
// static
IdentityManagerFactory* IdentityManagerFactory::GetInstance() {
return base::Singleton<IdentityManagerFactory>::get();
}
// static
void IdentityManagerFactory::EnsureFactoryAndDependeeFactoriesBuilt() {
IdentityManagerFactory::GetInstance();
ChromeSigninClientFactory::GetInstance();
}
void IdentityManagerFactory::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void IdentityManagerFactory::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
KeyedService* IdentityManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = Profile::FromBrowserContext(context);
signin::IdentityManagerBuildParams params;
params.account_consistency =
AccountConsistencyModeManager::GetMethodForProfile(profile),
params.image_decoder = std::make_unique<ImageDecoderImpl>();
params.local_state = g_browser_process->local_state();
params.network_connection_tracker = content::GetNetworkConnectionTracker();
params.pref_service = profile->GetPrefs();
params.profile_path = profile->GetPath();
params.signin_client = ChromeSigninClientFactory::GetForProfile(profile);
#if !defined(OS_ANDROID)
params.delete_signin_cookies_on_exit =
signin::SettingsDeleteSigninCookiesOnExit(
CookieSettingsFactory::GetForProfile(profile).get());
params.token_web_data = WebDataServiceFactory::GetTokenWebDataForProfile(
profile, ServiceAccessType::EXPLICIT_ACCESS);
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
auto* factory =
g_browser_process->platform_part()->GetAccountManagerFactory();
DCHECK(factory);
params.account_manager =
factory->GetAccountManager(profile->GetPath().value());
params.account_manager_facade =
GetAccountManagerFacade(profile->GetPath().value());
params.is_regular_profile =
chromeos::ProfileHelper::IsRegularProfile(profile);
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
params.account_manager_facade =
base::FeatureList::IsEnabled(kMultiProfileAccountConsistency)
? ProfileAccountManagerFactory::GetForProfile(profile)
: GetAccountManagerFacade(profile->GetPath().value());
// Lacros runs inside a user session and is not used to render Chrome OS's
// Login Screen, or its Lock Screen. Hence, all Profiles in Lacros are regular
// Profiles.
params.is_regular_profile = true;
#endif
#if defined(OS_WIN)
params.reauth_callback =
base::BindRepeating(&signin_util::ReauthWithCredentialProviderIfPossible,
base::Unretained(profile));
#endif
std::unique_ptr<signin::IdentityManager> identity_manager =
signin::BuildIdentityManager(¶ms);
for (Observer& observer : observer_list_)
observer.IdentityManagerCreated(identity_manager.get());
return identity_manager.release();
}
|
//
// Copyright (C) 2013 Jack.
//
// Author: jack
// Email: jack.wgm@gmail.com
//
#ifndef AVHTTP_LOGGING_HPP
#define AVHTTP_LOGGING_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#ifdef WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif // !WIN32_LEAN_AND_MEAN
# include <Windows.h> // for win32 Console api.
#endif // WIN32
#define LOGGER_THREAD_SAFE
#include <iostream>
#include <string>
#include <fstream>
#include <boost/thread/mutex.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/noncopyable.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "detail/utf8.hpp"
namespace avhttp {
///内部使用的简易日志类.
// 使用说明:
// 在程序入口(如:main)函数调用 INIT_LOGGER 宏, 它有两个参数, 第一个参数指定了日志文件保存
// 的路径, 第二个参数指定了日志文件保存的文件名, 详细见INIT_LOGGER.
// 然后就可以使用LOG_DBG/LOG_INFO/LOG_WARN/LOG_ERR这几个宏来输出日志信息.
// @begin example
// #include "logging.hpp"
// int main()
// {
// AVHTTP_AUTO_LOGGER("."); // 在当前目录创建以日期命名的日志文件.
// // 也可 AVHTTP_INIT_LOGGER("example.log"); // 指定日志文件名.
// AVHTTP_LOG_DBG << "Initialized.";
// std::string result = do_something();
// AVHTTP_LOG_DBG << "do_something return : " << result; // 输出do_something返回结果到日志.
// ...
// }
// @end example
//
// 一些可选参数:
// AVHTTP_LOG_FILE_NUM, 定义 AVHTTP_LOG_FILE_NUM 可指定最大连续运行日志文件个数, 超出将删除旧日志文件.
// 默认是每天生成按日期的日志文件, 所以, AVHTTP_LOG_FILE_NUM参数也相当是指定保留日志的天数.
//
// AVHTTP_LOG_FILE_BUFFER, 定义写入日志文件的写入缓冲大小, 默认为系统指定大小.
// 该参数实际上指定的是 std::ofstream 的写入缓冲大小.
#ifndef AVHTTP_LOG_FILE_NUM
# define AVHTTP_LOG_FILE_NUM 3
#endif
#ifndef AVHTTP_LOG_FILE_BUFFER
# define AVHTTP_LOG_FILE_BUFFER -1
#endif
class auto_logger_file
{
public:
auto_logger_file()
: m_auto_mode(false)
{}
~auto_logger_file()
{}
typedef boost::shared_ptr<std::ofstream> ofstream_ptr;
typedef std::map<std::string, ofstream_ptr> loglist;
void open(const char * filename, std::ios_base::openmode flag)
{
m_auto_mode = false;
const char* pos = std::strstr(filename, "*");
if (pos)
{
m_auto_mode = true;
char save_path[65536] = { 0 };
std::ptrdiff_t len = pos - filename;
if (len < 0 || len > 65536)
return;
strncpy(save_path, filename, pos - filename);
m_log_path = save_path;
}
else
{
m_file.open(filename, flag);
}
std::string start_string = "\n\n\n*** starting log ***\n\n\n";
write(start_string.c_str(), start_string.size());
}
bool is_open() const
{
if (m_auto_mode) return true;
return m_file.is_open();
}
void write(const char* str, std::streamsize size)
{
if (!m_auto_mode)
{
if (m_file.is_open())
m_file.write(str, size);
return;
}
ofstream_ptr of;
std::string fn = make_filename(m_log_path.string());
loglist::iterator iter = m_log_list.find(fn);
if (iter == m_log_list.end())
{
of.reset(new std::ofstream);
of->open(fn.c_str(), std::ios_base::out | std::ios_base::app);
if (AVHTTP_LOG_FILE_BUFFER != -1)
of->rdbuf()->pubsetbuf(NULL, AVHTTP_LOG_FILE_BUFFER);
m_log_list.insert(std::make_pair(fn, of));
if (m_log_list.size() > AVHTTP_LOG_FILE_NUM)
{
iter = m_log_list.begin();
fn = iter->first;
ofstream_ptr f = iter->second;
m_log_list.erase(iter);
f->close();
f.reset();
boost::system::error_code ignore_ec;
boost::filesystem::remove(fn, ignore_ec);
if (ignore_ec)
std::cout << "delete log failed: " << fn <<
", error code: " << ignore_ec.message() << std::endl;
}
}
else
{
of = iter->second;
}
if (of->is_open())
{
(*of).write(str, size);
(*of).flush();
}
}
void flush()
{
m_file.flush();
}
std::string make_filename(const std::string &p = "") const
{
boost::posix_time::ptime time = boost::posix_time::second_clock::local_time();
if (m_last_day != boost::posix_time::not_a_date_time && m_last_day.date().day() == time.date().day())
return m_last_filename;
m_last_day = time;
std::ostringstream oss;
boost::posix_time::time_facet* _facet = new boost::posix_time::time_facet("%Y%m%d");
oss.imbue(std::locale(std::locale::classic(), _facet));
oss << boost::posix_time::second_clock::local_time();
if (!boost::filesystem::exists(p)) {
boost::system::error_code ignore_ec;
boost::filesystem::create_directories(p, ignore_ec);
}
m_last_filename = (boost::filesystem::path(p) / (oss.str() + ".log")).string();
return m_last_filename;
}
private:
std::fstream m_file;
bool m_auto_mode;
boost::filesystem::path m_log_path;
loglist m_log_list;
mutable boost::posix_time::ptime m_last_day;
mutable std::string m_last_filename;
};
namespace aux {
template<class Lock>
Lock& lock_single()
{
static Lock lock_instance;
return lock_instance;
}
template<class Writer>
Writer& writer_single()
{
static Writer writer_instance;
return writer_instance;
}
inline char const* time_now_string()
{
static std::ostringstream oss;
if (oss.str().empty())
{
boost::posix_time::time_facet* _facet = new boost::posix_time::time_facet("%Y-%m-%d %H:%M:%S.%f");
oss.imbue(std::locale(std::locale::classic(), _facet));
}
oss.str("");
oss << boost::posix_time::microsec_clock::local_time();
std::string s = oss.str();
if (s.size() > 3)
s = std::string(s.substr(0, s.size() - 3));
static char str[200];
std::sprintf(str, "%s ", s.c_str());
return str;
}
}
#ifndef DISABLE_LOGGER_THREAD_SAFE
# define LOGGER_LOCKS_() boost::mutex::scoped_lock lock(aux::lock_single<boost::mutex>())
#else
# define LOGGER_LOCKS_() ((void)0)
#endif // DISABLE_LOGGER_THREAD_SAFE
#if defined(WIN32) && defined(LOGGER_DBG_VIEW)
# define LOGGER_DBG_VIEW_(x) do { ::OutputDebugStringA(x.c_str()); } while (0)
#else
# define LOGGER_DBG_VIEW_(x) ((void)0)
#endif // WIN32 && LOGGER_DBG_VIEW
static std::string LOGGER_DEBUG_STR = "DEBUG";
static std::string LOGGER_INFO_STR = "INFO";
static std::string LOGGER_WARN_STR = "WARNING";
static std::string LOGGER_ERR_STR = "ERROR";
static std::string LOGGER_FILE_STR = "FILE";
inline void output_console(std::string& level, const std::string& prefix, const std::string& message)
{
#ifdef WIN32
HANDLE handle_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(handle_stdout, &csbi);
if (level == LOGGER_INFO_STR)
SetConsoleTextAttribute(handle_stdout, FOREGROUND_GREEN);
else if (level == LOGGER_DEBUG_STR)
SetConsoleTextAttribute(handle_stdout, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
else if (level == LOGGER_WARN_STR)
SetConsoleTextAttribute(handle_stdout, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
else if (level == LOGGER_ERR_STR)
SetConsoleTextAttribute(handle_stdout, FOREGROUND_RED | FOREGROUND_INTENSITY);
std::wstring l = avhttp::detail::utf8_wide(prefix);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), l.data(), (DWORD)l.length(), nullptr, nullptr);
SetConsoleTextAttribute(handle_stdout, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE);
l = avhttp::detail::utf8_wide(message);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), l.data(), (DWORD)l.length(), nullptr, nullptr);
SetConsoleTextAttribute(handle_stdout, csbi.wAttributes);
#else
if (level == LOGGER_INFO_STR)
std::cout << "\033[32m" << prefix << "\033[0m" << message;
else if (level == LOGGER_DEBUG_STR)
std::cout << "\033[1;32m" << prefix << "\033[0m" << message;
else if (level == LOGGER_WARN_STR)
std::cout << "\033[1;33m" << prefix << "\033[0m" << message;
else if (level == LOGGER_ERR_STR)
std::cout << "\033[1;31m" << prefix << "\033[0m" << message;
#endif
std::cout.flush();
}
inline void logger_writer(std::string& level, std::string& message, bool disable_cout = false)
{
LOGGER_LOCKS_();
std::string prefix = aux::time_now_string() + std::string("[") + level + std::string("]: ");
std::string tmp = message + "\n";
std::string whole = prefix + tmp;
if (aux::writer_single<auto_logger_file>().is_open())
{
aux::writer_single<auto_logger_file>().write(whole.c_str(), whole.size());
aux::writer_single<auto_logger_file>().flush();
}
LOGGER_DBG_VIEW_(whole);
#ifndef AVHTTP_DISABLE_LOGGER_TO_CONSOLE
if (!disable_cout)
output_console(level, prefix, tmp);
#endif
}
class logger : boost::noncopyable
{
public:
logger(std::string& level)
: level_(level)
, m_disable_cout(false)
{}
logger(std::string& level, bool disable_cout)
: level_(level)
, m_disable_cout(disable_cout)
{}
~logger()
{
std::string message = oss_.str();
logger_writer(level_, message, m_disable_cout);
}
template <class T>
logger& operator << (T const& v)
{
oss_ << v;
return *this;
}
std::ostringstream oss_;
std::string& level_;
bool m_disable_cout;
};
class empty_logger : boost::noncopyable
{
public:
template <class T>
empty_logger& operator << (T const& v)
{
return *this;
}
};
} // namespace avhttp
#define AVHTTP_INIT_LOGGER(logfile) do \
{ \
avhttp::auto_logger_file& file = avhttp::aux::writer_single<avhttp::auto_logger_file>(); \
std::string filename = logfile; \
if (!filename.empty()) \
file.open(filename.c_str(), std::ios::in | std::ios::out | std::ios::app); \
} while (0)
#define AVHTTP_AUTO_LOGGER(path) do \
{ \
avhttp::auto_logger_file& file = avhttp::aux::writer_single<avhttp::auto_logger_file>(); \
std::string filename = "*"; \
filename = std::string(path) + filename; \
if (!filename.empty()) \
file.open(filename.c_str(), std::ios::in | std::ios::out | std::ios::app); \
} while (0)
#if (defined(DEBUG) || defined(_DEBUG) || defined(ENABLE_LOGGER)) && !defined(DISABLE_LOGGER)
#define AVHTTP_LOG_DBG avhttp::logger(avhttp::LOGGER_DEBUG_STR)
#define AVHTTP_LOG_INFO avhttp::logger(avhttp::LOGGER_INFO_STR)
#define AVHTTP_LOG_WARN avhttp::logger(avhttp::LOGGER_WARN_STR)
#define AVHTTP_LOG_ERR avhttp::logger(avhttp::LOGGER_ERR_STR)
#define AVHTTP_LOG_FILE avhttp::logger(avhttp::LOGGER_FILE_STR, true)
#else
#define AVHTTP_LOG_DBG avhttp::empty_logger()
#define AVHTTP_LOG_INFO avhttp::empty_logger()
#define AVHTTP_LOG_WARN avhttp::empty_logger()
#define AVHTTP_LOG_ERR avhttp::empty_logger()
#define AVHTTP_LOG_OUT avhttp::empty_logger()
#define AVHTTP_LOG_FILE avhttp::empty_logger()
#endif
#endif // AVHTTP_LOGGING_HPP
|
/*
* Copyright 2016-2018 Alex Beregszaszi et al.
*
* 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 <vector>
#include <pass.h>
#include <wasm.h>
#include <wasm-binary.h>
#include <wasm-builder.h>
#include <wasm-interpreter.h>
#include <wasm-printing.h>
#include <wasm-validator.h>
#include "binaryen.h"
#include "debugging.h"
#include "eei.h"
#include "exceptions.h"
#include "shell-interface.h"
using namespace std;
namespace hera {
class BinaryenEthereumInterface : public wasm::ShellExternalInterface, EthereumInterface {
public:
explicit BinaryenEthereumInterface(
evmc::HostContext& _context,
bytes_view _code,
evmc_message const& _msg,
ExecutionResult & _result,
bool _meterGas
):
ShellExternalInterface(),
EthereumInterface(_context, _code, _msg, _result, _meterGas)
{ }
protected:
wasm::Literal callImport(wasm::Import *import, wasm::LiteralList& arguments) override;
#if HERA_DEBUGGING
wasm::Literal callDebugImport(wasm::Import *import, wasm::LiteralList& arguments);
#endif
void importGlobals(map<wasm::Name, wasm::Literal>& globals, wasm::Module& wasm) override;
void trap(const char* why) override {
ensureCondition(false, VMTrap, why);
}
private:
size_t memorySize() const override { return memory.size(); }
void memorySet(size_t offset, uint8_t value) override { memory.set<uint8_t>(offset, value); }
uint8_t memoryGet(size_t offset) override { return memory.get<uint8_t>(offset); }
uint8_t* memoryPointer(size_t offset, size_t length) override {
ensureCondition(memorySize() >= (offset + length), InvalidMemoryAccess, "Memory is shorter than requested segment");
return reinterpret_cast<uint8_t*>(memory.rawpointer(offset));
}
};
void BinaryenEthereumInterface::importGlobals(map<wasm::Name, wasm::Literal>& globals, wasm::Module& wasm) {
(void)globals;
(void)wasm;
HERA_DEBUG << "importGlobals\n";
}
#if HERA_DEBUGGING
wasm::Literal BinaryenEthereumInterface::callDebugImport(wasm::Import *import, wasm::LiteralList& arguments) {
heraAssert(import->module == wasm::Name("debug"), "Import namespace error.");
if (import->base == wasm::Name("print32")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t value = static_cast<uint32_t>(arguments[0].geti32());
debugPrint32(value);
return wasm::Literal();
}
if (import->base == wasm::Name("print64")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint64_t value = static_cast<uint64_t>(arguments[0].geti64());
debugPrint64(value);
return wasm::Literal();
}
if (import->base == wasm::Name("printMem") || import->base == wasm::Name("printMemHex")) {
heraAssert(arguments.size() == 2, string("Argument count mismatch in: ") + import->base.str);
uint32_t offset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t length = static_cast<uint32_t>(arguments[1].geti32());
debugPrintMem(import->base == wasm::Name("printMemHex"), offset, length);
return wasm::Literal();
}
if (import->base == wasm::Name("printStorage") || import->base == wasm::Name("printStorageHex")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t pathOffset = static_cast<uint32_t>(arguments[0].geti32());
debugPrintStorage(import->base == wasm::Name("printStorageHex"), pathOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("evmTrace")) {
heraAssert(arguments.size() == 4, string("Argument count mismatch in: ") + import->base.str);
uint32_t pc = static_cast<uint32_t>(arguments[0].geti32());
int32_t opcode = arguments[1].geti32();
uint32_t cost = static_cast<uint32_t>(arguments[2].geti32());
int32_t sp = arguments[3].geti32();
debugEvmTrace(pc, opcode, cost, sp);
return wasm::Literal();
}
heraAssert(false, string("Unsupported import called: ") + import->module.str + "::" + import->base.str + " (" + to_string(arguments.size()) + " arguments)");
}
#endif
wasm::Literal BinaryenEthereumInterface::callImport(wasm::Import *import, wasm::LiteralList& arguments) {
#if HERA_DEBUGGING
if (import->module == wasm::Name("debug"))
// Reroute to debug namespace
return callDebugImport(import, arguments);
#endif
heraAssert(import->module == wasm::Name("ethereum"), "Only imports from the 'ethereum' namespace are allowed.");
if (import->base == wasm::Name("useGas")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
int64_t gas = arguments[0].geti64();
eeiUseGas(gas);
return wasm::Literal();
}
if (import->base == wasm::Name("getGasLeft")) {
heraAssert(arguments.size() == 0, string("Argument count mismatch in: ") + import->base.str);
return wasm::Literal(eeiGetGasLeft());
}
if (import->base == wasm::Name("getAddress")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t resultOffset = static_cast<uint32_t>(arguments[0].geti32());
eeiGetAddress(resultOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("getExternalBalance")) {
heraAssert(arguments.size() == 2, string("Argument count mismatch in: ") + import->base.str);
uint32_t addressOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t resultOffset = static_cast<uint32_t>(arguments[1].geti32());
eeiGetExternalBalance(addressOffset, resultOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("getBlockHash")) {
heraAssert(arguments.size() == 2, string("Argument count mismatch in: ") + import->base.str);
uint64_t number = static_cast<uint64_t>(arguments[0].geti64());
uint32_t resultOffset = static_cast<uint32_t>(arguments[1].geti32());
return wasm::Literal(eeiGetBlockHash(number, resultOffset));
}
if (import->base == wasm::Name("getCallDataSize")) {
heraAssert(arguments.size() == 0, string("Argument count mismatch in: ") + import->base.str);
return wasm::Literal(eeiGetCallDataSize());
}
if (import->base == wasm::Name("callDataCopy")) {
heraAssert(arguments.size() == 3, string("Argument count mismatch in: ") + import->base.str);
uint32_t resultOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t dataOffset = static_cast<uint32_t>(arguments[1].geti32());
uint32_t length = static_cast<uint32_t>(arguments[2].geti32());
eeiCallDataCopy(resultOffset, dataOffset, length);
return wasm::Literal();
}
if (import->base == wasm::Name("getCaller")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t resultOffset = static_cast<uint32_t>(arguments[0].geti32());
eeiGetCaller(resultOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("getCallValue")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t resultOffset = static_cast<uint32_t>(arguments[0].geti32());
eeiGetCallValue(resultOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("codeCopy")) {
heraAssert(arguments.size() == 3, string("Argument count mismatch in: ") + import->base.str);
uint32_t resultOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t codeOffset = static_cast<uint32_t>(arguments[1].geti32());
uint32_t length = static_cast<uint32_t>(arguments[2].geti32());
eeiCodeCopy(resultOffset, codeOffset, length);
return wasm::Literal();
}
if (import->base == wasm::Name("getCodeSize")) {
heraAssert(arguments.size() == 0, string("Argument count mismatch in: ") + import->base.str);
return wasm::Literal(eeiGetCodeSize());
}
if (import->base == wasm::Name("externalCodeCopy")) {
heraAssert(arguments.size() == 4, string("Argument count mismatch in: ") + import->base.str);
uint32_t addressOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t resultOffset = static_cast<uint32_t>(arguments[1].geti32());
uint32_t codeOffset = static_cast<uint32_t>(arguments[2].geti32());
uint32_t length = static_cast<uint32_t>(arguments[3].geti32());
eeiExternalCodeCopy(addressOffset, resultOffset, codeOffset, length);
return wasm::Literal();
}
if (import->base == wasm::Name("getExternalCodeSize")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t addressOffset = static_cast<uint32_t>(arguments[0].geti32());
return wasm::Literal(eeiGetExternalCodeSize(addressOffset));
}
if (import->base == wasm::Name("getBlockCoinbase")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t resultOffset = static_cast<uint32_t>(arguments[0].geti32());
eeiGetBlockCoinbase(resultOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("getBlockDifficulty")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t offset = static_cast<uint32_t>(arguments[0].geti32());
eeiGetBlockDifficulty(offset);
return wasm::Literal();
}
if (import->base == wasm::Name("getBlockGasLimit")) {
heraAssert(arguments.size() == 0, string("Argument count mismatch in: ") + import->base.str);
return wasm::Literal(eeiGetBlockGasLimit());
}
if (import->base == wasm::Name("getTxGasPrice")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t valueOffset = static_cast<uint32_t>(arguments[0].geti32());
eeiGetTxGasPrice(valueOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("log")) {
heraAssert(arguments.size() == 7, string("Argument count mismatch in: ") + import->base.str);
uint32_t dataOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t length = static_cast<uint32_t>(arguments[1].geti32());
uint32_t numberOfTopics = static_cast<uint32_t>(arguments[2].geti32());
uint32_t topic1 = static_cast<uint32_t>(arguments[3].geti32());
uint32_t topic2 = static_cast<uint32_t>(arguments[4].geti32());
uint32_t topic3 = static_cast<uint32_t>(arguments[5].geti32());
uint32_t topic4 = static_cast<uint32_t>(arguments[6].geti32());
eeiLog(dataOffset, length, numberOfTopics, topic1, topic2, topic3, topic4);
return wasm::Literal();
}
if (import->base == wasm::Name("getBlockNumber")) {
heraAssert(arguments.size() == 0, string("Argument count mismatch in: ") + import->base.str);
return wasm::Literal(eeiGetBlockNumber());
}
if (import->base == wasm::Name("getBlockTimestamp")) {
heraAssert(arguments.size() == 0, string("Argument count mismatch in: ") + import->base.str);
return wasm::Literal(eeiGetBlockTimestamp());
}
if (import->base == wasm::Name("getTxOrigin")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t resultOffset = static_cast<uint32_t>(arguments[0].geti32());
eeiGetTxOrigin(resultOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("storageStore")) {
heraAssert(arguments.size() == 2, string("Argument count mismatch in: ") + import->base.str);
uint32_t pathOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t valueOffset = static_cast<uint32_t>(arguments[1].geti32());
eeiStorageStore(pathOffset, valueOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("storageLoad")) {
heraAssert(arguments.size() == 2, string("Argument count mismatch in: ") + import->base.str);
uint32_t pathOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t resultOffset = static_cast<uint32_t>(arguments[1].geti32());
eeiStorageLoad(pathOffset, resultOffset);
return wasm::Literal();
}
if (import->base == wasm::Name("finish")) {
heraAssert(arguments.size() == 2, string("Argument count mismatch in: ") + import->base.str);
uint32_t offset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t size = static_cast<uint32_t>(arguments[1].geti32());
// This traps.
eeiFinish(offset, size);
}
if (import->base == wasm::Name("revert")) {
heraAssert(arguments.size() == 2, string("Argument count mismatch in: ") + import->base.str);
uint32_t offset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t size = static_cast<uint32_t>(arguments[1].geti32());
// This traps.
eeiRevert(offset, size);
}
if (import->base == wasm::Name("getReturnDataSize")) {
heraAssert(arguments.size() == 0, string("Argument count mismatch in: ") + import->base.str);
return wasm::Literal(eeiGetReturnDataSize());
}
if (import->base == wasm::Name("returnDataCopy")) {
heraAssert(arguments.size() == 3, string("Argument count mismatch in: ") + import->base.str);
uint32_t dataOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t offset = static_cast<uint32_t>(arguments[1].geti32());
uint32_t size = static_cast<uint32_t>(arguments[2].geti32());
eeiReturnDataCopy(dataOffset, offset, size);
return wasm::Literal();
}
if (
import->base == wasm::Name("call") ||
import->base == wasm::Name("callCode") ||
import->base == wasm::Name("callDelegate") ||
import->base == wasm::Name("callStatic")
) {
EEICallKind kind;
if (import->base == wasm::Name("call"))
kind = EEICallKind::Call;
else if (import->base == wasm::Name("callCode"))
kind = EEICallKind::CallCode;
else if (import->base == wasm::Name("callDelegate"))
kind = EEICallKind::CallDelegate;
else if (import->base == wasm::Name("callStatic"))
kind = EEICallKind::CallStatic;
else
heraAssert(false, "");
if ((kind == EEICallKind::Call) || (kind == EEICallKind::CallCode)) {
heraAssert(arguments.size() == 5, string("Argument count mismatch in: ") + import->base.str);
} else {
heraAssert(arguments.size() == 4, string("Argument count mismatch in: ") + import->base.str);
}
int64_t gas = arguments[0].geti64();
uint32_t addressOffset = static_cast<uint32_t>(arguments[1].geti32());
uint32_t valueOffset;
uint32_t dataOffset;
uint32_t dataLength;
if (kind == EEICallKind::Call || kind == EEICallKind::CallCode) {
valueOffset = static_cast<uint32_t>(arguments[2].geti32());
dataOffset = static_cast<uint32_t>(arguments[3].geti32());
dataLength = static_cast<uint32_t>(arguments[4].geti32());
} else {
valueOffset = 0;
dataOffset = static_cast<uint32_t>(arguments[2].geti32());
dataLength = static_cast<uint32_t>(arguments[3].geti32());
}
return wasm::Literal(eeiCall(kind, gas, addressOffset, valueOffset, dataOffset, dataLength));
}
if (import->base == wasm::Name("create")) {
heraAssert(arguments.size() == 4, string("Argument count mismatch in: ") + import->base.str);
uint32_t valueOffset = static_cast<uint32_t>(arguments[0].geti32());
uint32_t dataOffset = static_cast<uint32_t>(arguments[1].geti32());
uint32_t length = static_cast<uint32_t>(arguments[2].geti32());
uint32_t resultOffset = static_cast<uint32_t>(arguments[3].geti32());
return wasm::Literal(eeiCreate(valueOffset, dataOffset, length, resultOffset));
}
if (import->base == wasm::Name("selfDestruct")) {
heraAssert(arguments.size() == 1, string("Argument count mismatch in: ") + import->base.str);
uint32_t addressOffset = static_cast<uint32_t>(arguments[0].geti32());
// This traps.
eeiSelfDestruct(addressOffset);
}
heraAssert(false, string("Unsupported import called: ") + import->module.str + "::" + import->base.str + " (" + to_string(arguments.size()) + "arguments)");
}
unique_ptr<WasmEngine> BinaryenEngine::create()
{
return unique_ptr<WasmEngine>{new BinaryenEngine};
}
// Execute the contract through Binaryen.
ExecutionResult BinaryenEngine::execute(
evmc::HostContext& context,
bytes_view code,
bytes_view state_code,
evmc_message const& msg,
bool meterInterfaceGas
) {
instantiationStarted();
wasm::Module module;
// Load module
loadModule(code, module);
// Print
// WasmPrinter::printModule(module);
// Validate
verifyContract(module);
// NOTE: DO NOT use the optimiser here, it will conflict with metering
// Interpret
ExecutionResult result;
BinaryenEthereumInterface interface(context, state_code, msg, result, meterInterfaceGas);
wasm::ModuleInstance instance(module, &interface);
executionStarted();
try {
wasm::Name main = wasm::Name("main");
wasm::LiteralList args;
instance.callExport(main, args);
} catch (EndExecution const&) {
// This exception is ignored here because we consider it to be a success.
// It is only a clutch for POSIX style exit()
}
executionFinished();
return result;
}
void BinaryenEngine::loadModule(bytes_view code, wasm::Module& module)
{
try {
auto const b = reinterpret_cast<char const*>(code.begin());
auto const e = reinterpret_cast<char const*>(code.end());
std::vector<char> codeCopy{b, e};
wasm::WasmBinaryBuilder parser(module, codeCopy, false);
parser.read();
} catch (wasm::ParseException const& e) {
string msg = "Error in parsing WASM binary: '" + e.text + "'";
if (e.line != size_t(-1))
msg += " (at " + to_string(e.line) + ":" + to_string(e.col) + ")";
ensureCondition(false, ContractValidationFailure, msg);
}
}
void BinaryenEngine::verifyContract(bytes_view code)
{
wasm::Module module;
loadModule(code, module);
verifyContract(module);
}
namespace {
wasm::FunctionType createFunctionType(vector<wasm::Type> params, wasm::Type result) {
wasm::FunctionType ret;
ret.params = move(params);
ret.result = move(result);
return ret;
}
}
void BinaryenEngine::verifyContract(wasm::Module & module)
{
ensureCondition(
wasm::WasmValidator().validate(module),
ContractValidationFailure,
"Module is not valid."
);
// NOTE: Most of this should be caught during deployment time by the Sentinel.
ensureCondition(
module.start.isNull(),
ContractValidationFailure,
"Contract contains start function."
);
ensureCondition(
module.getExportOrNull(wasm::Name("main")) != nullptr,
ContractValidationFailure,
"Contract entry point (\"main\") missing."
);
ensureCondition(
module.getExportOrNull(wasm::Name("memory")) != nullptr,
ContractValidationFailure,
"Contract export (\"memory\") missing."
);
ensureCondition(
module.exports.size() == 2,
ContractValidationFailure,
"Contract exports more than (\"main\") and (\"memory\")."
);
// The existence of this is ensured above.
wasm::Export* main_export = module.getExport(wasm::Name("main"));
wasm::Function* main_function = module.getFunctionOrNull(main_export->value);
ensureCondition(
main_function,
ContractValidationFailure,
"Contract is invalid. \"main\" is not a function."
);
ensureCondition(
(main_function->getNumParams() == 0) &&
(main_function->result == wasm::Type::none),
ContractValidationFailure,
"Contract is invalid. \"main\" has an invalid signature."
);
static const map<wasm::Name const, wasm::FunctionType const> eei_signatures{
{ wasm::Name("useGas"), createFunctionType({ wasm::Type::i64 }, wasm::Type::none) },
{ wasm::Name("getGasLeft"), createFunctionType({}, wasm::Type::i64) },
{ wasm::Name("getAddress"), createFunctionType({ wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getExternalBalance"), createFunctionType({ wasm::Type::i32,wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getBlockHash"), createFunctionType({ wasm::Type::i64, wasm::Type::i32 }, wasm::Type::i32) },
{ wasm::Name("getCallDataSize"), createFunctionType({}, wasm::Type::i32) },
{ wasm::Name("callDataCopy"), createFunctionType({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getCaller"), createFunctionType({ wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getCallValue"), createFunctionType({ wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("codeCopy"), createFunctionType({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32}, wasm::Type::none) },
{ wasm::Name("getCodeSize"), createFunctionType({}, wasm::Type::i32) },
{ wasm::Name("externalCodeCopy"), createFunctionType({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getExternalCodeSize"), createFunctionType({ wasm::Type::i32 }, wasm::Type::i32) },
{ wasm::Name("getBlockCoinbase"), createFunctionType({ wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getBlockDifficulty"), createFunctionType({ wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getBlockGasLimit"), createFunctionType({}, wasm::Type::i64) },
{ wasm::Name("getTxGasPrice"), createFunctionType({ wasm::Type::i32}, wasm::Type::none) },
{ wasm::Name("log"), createFunctionType({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getBlockNumber"), createFunctionType({}, wasm::Type::i64) },
{ wasm::Name("getBlockTimestamp"), createFunctionType({}, wasm::Type::i64) },
{ wasm::Name("getTxOrigin"), createFunctionType({ wasm::Type::i32}, wasm::Type::none) },
{ wasm::Name("storageStore"), createFunctionType({ wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("storageLoad"), createFunctionType({ wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("finish"), createFunctionType({ wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("revert"), createFunctionType({ wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("getReturnDataSize"), createFunctionType({ }, wasm::Type::i32) },
{ wasm::Name("returnDataCopy"), createFunctionType({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::none) },
{ wasm::Name("call"), createFunctionType({ wasm::Type::i64, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::i32) },
{ wasm::Name("callCode"), createFunctionType({ wasm::Type::i64, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::i32) },
{ wasm::Name("callDelegate"), createFunctionType({ wasm::Type::i64, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::i32) },
{ wasm::Name("callStatic"), createFunctionType({ wasm::Type::i64, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::i32) },
{ wasm::Name("create"), createFunctionType({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }, wasm::Type::i32) },
{ wasm::Name("selfDestruct"), createFunctionType({ wasm::Type::i32 }, wasm::Type::none) }
};
for (auto const& import: module.imports) {
#if HERA_DEBUGGING
if (import->module == wasm::Name("debug"))
continue;
#endif
ensureCondition(
import->module == wasm::Name("ethereum"),
ContractValidationFailure,
"Import from invalid namespace."
);
ensureCondition(
eei_signatures.count(import->base),
ContractValidationFailure,
"Importing invalid EEI method."
);
// NOTE: needs to be a copy by value due to `structuralComparison` requiring a non-const input
wasm::FunctionType eei_function_type = eei_signatures.at(import->base);
wasm::FunctionType* function_type = module.getFunctionTypeOrNull(import->functionType);
ensureCondition(
function_type,
ContractValidationFailure,
"Imported function type is missing."
);
ensureCondition(
function_type->structuralComparison(eei_function_type),
ContractValidationFailure,
"Imported function type mismatch."
);
}
}
}
|
/**
* @file main.cpp
*
*/
/* Copyright (C) 2019-2021 by Arjan van Vught mailto:info@orangepi-dmx.nl
*
* 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 <cstdint>
#include "hardware.h"
#include "network.h"
#include "networkconst.h"
#include "ledblink.h"
#include "displayudf.h"
#include "displayudfparams.h"
#include "storedisplayudf.h"
#include "e131bridge.h"
#include "e131params.h"
#include "e131reboot.h"
#include "storee131.h"
#include "e131msgconst.h"
// DMX Output
#include "dmxparams.h"
#include "dmxsend.h"
#include "storedmxsend.h"
#include "dmxconfigudp.h"
// DMX Input
#include "dmxinput.h"
#include "spiflashinstall.h"
#include "spiflashstore.h"
#include "remoteconfig.h"
#include "remoteconfigparams.h"
#include "storeremoteconfig.h"
#include "firmwareversion.h"
#include "software_version.h"
#include "displayhandler.h"
extern "C" {
void notmain(void) {
Hardware hw;
Network nw;
LedBlink lb;
DisplayUdf display;
FirmwareVersion fw(SOFTWARE_VERSION, __DATE__, __TIME__);
SpiFlashInstall spiFlashInstall;
SpiFlashStore spiFlashStore;
fw.Print();
console_puts("Ethernet sACN E1.31 ");
console_set_fg_color(CONSOLE_GREEN);
console_puts("DMX ");
console_set_fg_color(CONSOLE_WHITE);
#if defined(ORANGE_PI)
console_puts("{2 Universes}\n");
#else
console_puts("{4 Universes}\n");
#endif
hw.SetLed(hardware::LedStatus::ON);
hw.SetRebootHandler(new E131Reboot);
lb.SetLedBlinkDisplay(new DisplayHandler);
display.TextStatus(NetworkConst::MSG_NETWORK_INIT, Display7SegmentMessage::INFO_NETWORK_INIT, CONSOLE_YELLOW);
nw.SetNetworkStore(StoreNetwork::Get());
nw.Init(StoreNetwork::Get());
nw.Print();
display.TextStatus(E131MsgConst::PARAMS, Display7SegmentMessage::INFO_BRIDGE_PARMAMS, CONSOLE_YELLOW);
StoreE131 storeE131;
E131Params e131params(&storeE131);
E131Bridge bridge;
if (e131params.Load()) {
e131params.Set(&bridge);
e131params.Dump();
}
uint16_t nUniverse;
bool bIsSet;
nUniverse = e131params.GetUniverse(0, bIsSet);
if (bIsSet) {
bridge.SetUniverse(0, e131params.GetDirection(0), nUniverse);
}
nUniverse = e131params.GetUniverse(1, bIsSet);
if (bIsSet) {
bridge.SetUniverse(1, e131params.GetDirection(1), nUniverse);
}
#if defined (ORANGE_PI_ONE)
nUniverse = e131params.GetUniverse(2, bIsSet);
if (bIsSet) {
bridge.SetUniverse(2, e131params.GetDirection(2), nUniverse);
}
#ifndef DO_NOT_USE_UART0
nUniverse = e131params.GetUniverse(3, bIsSet);
if (bIsSet) {
bridge.SetUniverse(3, e131params.GetDirection(3), nUniverse);
}
#endif
#endif
StoreDmxSend storeDmxSend;
DmxParams dmxparams(&storeDmxSend);
Dmx dmx;
if (dmxparams.Load()) {
dmxparams.Dump();
dmxparams.Set(&dmx);
}
DmxSend dmxSend;
dmxSend.Print();
DmxConfigUdp *pDmxConfigUdp = nullptr;
if (bridge.GetActiveOutputPorts() != 0) {
bridge.SetOutput(&dmxSend);
pDmxConfigUdp = new DmxConfigUdp;
assert(pDmxConfigUdp != nullptr);
}
DmxInput dmxInput;
if (bridge.GetActiveInputPorts() != 0) {
bridge.SetE131Dmx(&dmxInput);
}
bridge.Print();
const auto nActivePorts = static_cast<uint32_t>(bridge.GetActiveInputPorts() + bridge.GetActiveOutputPorts());
display.SetTitle("sACN E1.31 DMX %u", nActivePorts);
display.Set(2, displayudf::Labels::IP);
display.Set(3, displayudf::Labels::NETMASK);
display.Set(4, displayudf::Labels::UNIVERSE_PORT_A);
display.Set(5, displayudf::Labels::UNIVERSE_PORT_B);
display.Set(6, displayudf::Labels::BOARDNAME);
StoreDisplayUdf storeDisplayUdf;
DisplayUdfParams displayUdfParams(&storeDisplayUdf);
if(displayUdfParams.Load()) {
displayUdfParams.Set(&display);
displayUdfParams.Dump();
}
display.Show(&bridge);
RemoteConfig remoteConfig(remoteconfig::Node::E131, remoteconfig::Output::DMX, nActivePorts);
StoreRemoteConfig storeRemoteConfig;
RemoteConfigParams remoteConfigParams(&storeRemoteConfig);
if (remoteConfigParams.Load()) {
remoteConfigParams.Set(&remoteConfig);
remoteConfigParams.Dump();
}
while (spiFlashStore.Flash())
;
display.TextStatus(E131MsgConst::START, Display7SegmentMessage::INFO_BRIDGE_START, CONSOLE_YELLOW);
bridge.Start();
display.TextStatus(E131MsgConst::STARTED, Display7SegmentMessage::INFO_BRIDGE_STARTED, CONSOLE_GREEN);
hw.WatchdogInit();
for (;;) {
hw.WatchdogFeed();
nw.Run();
bridge.Run();
remoteConfig.Run();
spiFlashStore.Flash();
lb.Run();
display.Run();
if (pDmxConfigUdp != nullptr) {
pDmxConfigUdp->Run();
}
}
}
}
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer.h"
#include "build/build_config.h"
#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_intersection_observer_init.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_document_element.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_delegate.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/core/testing/intersection_observer_test_helper.h"
#include "third_party/blink/renderer/core/testing/sim/sim_compositor.h"
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
namespace blink {
class IntersectionObserverTest : public SimTest {};
class IntersectionObserverV2Test : public IntersectionObserverTest {
public:
IntersectionObserverV2Test() {
IntersectionObserver::SetThrottleDelayEnabledForTesting(false);
}
~IntersectionObserverV2Test() override {
IntersectionObserver::SetThrottleDelayEnabledForTesting(true);
}
};
TEST_F(IntersectionObserverTest, ObserveSchedulesFrame) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete("<div id='target'></div>");
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Compositor().BeginFrame();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_TRUE(observer->takeRecords(exception_state).IsEmpty());
EXPECT_EQ(observer_delegate->CallCount(), 0);
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
observer->observe(target, exception_state);
EXPECT_TRUE(Compositor().NeedsBeginFrame());
}
TEST_F(IntersectionObserverTest, NotificationSentWhenRootRemoved) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
#target {
width: 100px;
height: 100px;
}
</style>
<div id='root'>
<div id='target'></div>
</div>
)HTML");
Compositor().BeginFrame();
Element* root = GetDocument().getElementById("root");
ASSERT_TRUE(root);
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
observer_init->setRoot(MakeGarbageCollected<V8UnionDocumentOrElement>(root));
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
observer->observe(target, exception_state);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 1);
EXPECT_EQ(observer_delegate->EntryCount(), 1);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
root->remove();
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 2);
EXPECT_EQ(observer_delegate->EntryCount(), 2);
EXPECT_FALSE(observer_delegate->LastEntry()->isIntersecting());
}
TEST_F(IntersectionObserverTest, DocumentRootClips) {
ScopedIntersectionObserverDocumentScrollingElementRootForTest scope(true);
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
SimRequest iframe_resource("https://example.com/iframe.html", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<iframe src="iframe.html" style="width:200px; height:100px"></iframe>
)HTML");
iframe_resource.Complete(R"HTML(
<div id='target'>Hello, world!</div>
<div id='spacer' style='height:2000px'></div>
)HTML");
Compositor().BeginFrame();
Document* iframe_document = To<WebLocalFrameImpl>(MainFrame().FirstChild())
->GetFrame()
->GetDocument();
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
observer_init->setRoot(
MakeGarbageCollected<V8UnionDocumentOrElement>(iframe_document));
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = iframe_document->getElementById("target");
ASSERT_TRUE(target);
observer->observe(target, exception_state);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 1);
EXPECT_EQ(observer_delegate->EntryCount(), 1);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
iframe_document->View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 1000), mojom::blink::ScrollType::kProgrammatic);
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 2);
EXPECT_EQ(observer_delegate->EntryCount(), 2);
EXPECT_FALSE(observer_delegate->LastEntry()->isIntersecting());
}
TEST_F(IntersectionObserverTest, ReportsFractionOfTargetOrRoot) {
// Place a 100x100 target element in the middle of a 200x200 main frame.
WebView().MainFrameViewWidget()->Resize(gfx::Size(200, 200));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
#target {
position: absolute;
top: 50px; left: 50px; width: 100px; height: 100px;
}
</style>
<div id='target'></div>
)HTML");
Compositor().BeginFrame();
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
// 100% of the target element's area intersects with the frame.
constexpr float kExpectedFractionOfTarget = 1.0f;
// 25% of the frame's area is covered by the target element.
constexpr float kExpectedFractionOfRoot = 0.25f;
TestIntersectionObserverDelegate* target_observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* target_observer =
MakeGarbageCollected<IntersectionObserver>(
*target_observer_delegate, nullptr, Vector<Length>(),
Vector<float>{kExpectedFractionOfTarget / 2},
IntersectionObserver::kFractionOfTarget, 0, false, false,
IntersectionObserver::kApplyMarginToRoot,
/* use_overflow_clip_edge */ false);
DummyExceptionStateForTesting exception_state;
target_observer->observe(target, exception_state);
ASSERT_FALSE(exception_state.HadException());
TestIntersectionObserverDelegate* root_observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* root_observer =
MakeGarbageCollected<IntersectionObserver>(
*root_observer_delegate, nullptr, Vector<Length>(),
Vector<float>{kExpectedFractionOfRoot / 2},
IntersectionObserver::kFractionOfRoot, 0, false, false,
IntersectionObserver::kApplyMarginToRoot,
/* use_overflow_clip_edge */ false);
root_observer->observe(target, exception_state);
ASSERT_FALSE(exception_state.HadException());
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(target_observer_delegate->CallCount(), 1);
EXPECT_EQ(target_observer_delegate->EntryCount(), 1);
EXPECT_TRUE(target_observer_delegate->LastEntry()->isIntersecting());
EXPECT_NEAR(kExpectedFractionOfTarget,
target_observer_delegate->LastEntry()->intersectionRatio(), 1e-6);
EXPECT_EQ(root_observer_delegate->CallCount(), 1);
EXPECT_EQ(root_observer_delegate->EntryCount(), 1);
EXPECT_TRUE(root_observer_delegate->LastEntry()->isIntersecting());
EXPECT_NEAR(kExpectedFractionOfRoot,
root_observer_delegate->LastEntry()->intersectionRatio(), 1e-6);
}
TEST_F(IntersectionObserverTest, TargetRectIsEmptyAfterMapping) {
// Place a 100x100 target element in the middle of a 200x200 main frame.
WebView().MainFrameViewWidget()->Resize(gfx::Size(200, 200));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
.clipper {
transform: rotatey(90deg);
}
.container {
overflow: hidden;
}
#target {
width: 10px;
height: 10px;
}
</style>
<div class=clipper>
<div class=container>
<div id=target></div>
</div>
</div>
)HTML");
Compositor().BeginFrame();
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
TestIntersectionObserverDelegate* target_observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* target_observer =
MakeGarbageCollected<IntersectionObserver>(
*target_observer_delegate, nullptr, Vector<Length>(),
Vector<float>{std::numeric_limits<float>::min()},
IntersectionObserver::kFractionOfTarget, 0, false, false,
IntersectionObserver::kApplyMarginToRoot,
/* use_overflow_clip_edge */ false);
DummyExceptionStateForTesting exception_state;
target_observer->observe(target, exception_state);
ASSERT_FALSE(exception_state.HadException());
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(target_observer_delegate->CallCount(), 1);
EXPECT_EQ(target_observer_delegate->EntryCount(), 1);
EXPECT_TRUE(target_observer_delegate->LastEntry()->isIntersecting());
}
TEST_F(IntersectionObserverTest, ResumePostsTask) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<div id='leading-space' style='height: 700px;'></div>
<div id='target'></div>
<div id='trailing-space' style='height: 700px;'></div>
)HTML");
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
observer->observe(target, exception_state);
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 1);
// When document is not suspended, beginFrame() will generate notifications
// and post a task to deliver them.
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 300), mojom::blink::ScrollType::kProgrammatic);
Compositor().BeginFrame();
EXPECT_EQ(observer_delegate->CallCount(), 1);
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 2);
// When a document is suspended, beginFrame() will generate a notification,
// but it will not be delivered. The notification will, however, be
// available via takeRecords();
WebView().GetPage()->SetPaused(true);
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 0), mojom::blink::ScrollType::kProgrammatic);
Compositor().BeginFrame();
EXPECT_EQ(observer_delegate->CallCount(), 2);
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 2);
EXPECT_FALSE(observer->takeRecords(exception_state).IsEmpty());
// Generate a notification while document is suspended; then resume document.
// Notification should happen in a post task.
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 300), mojom::blink::ScrollType::kProgrammatic);
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 2);
WebView().GetPage()->SetPaused(false);
EXPECT_EQ(observer_delegate->CallCount(), 2);
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 3);
}
TEST_F(IntersectionObserverTest, HitTestAfterMutation) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<div id='leading-space' style='height: 700px;'></div>
<div id='target'></div>
<div id='trailing-space' style='height: 700px;'></div>
)HTML");
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
observer->observe(target, exception_state);
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 1);
GetDocument().View()->ScheduleAnimation();
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 1);
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 300), mojom::blink::ScrollType::kProgrammatic);
HitTestLocation location{PhysicalOffset()};
HitTestResult result(
HitTestRequest(HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kAllowChildFrameContent),
location);
GetDocument().View()->GetLayoutView()->HitTest(location, result);
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 2);
}
TEST_F(IntersectionObserverTest, DisconnectClearsNotifications) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<div id='leading-space' style='height: 700px;'></div>
<div id='target'></div>
<div id='trailing-space' style='height: 700px;'></div>
)HTML");
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
IntersectionObserverController& controller =
GetDocument().EnsureIntersectionObserverController();
observer->observe(target, exception_state);
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 1u);
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 1);
// If disconnect() is called while an observer has unsent notifications,
// those notifications should be discarded.
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 300), mojom::blink::ScrollType::kProgrammatic);
Compositor().BeginFrame();
observer->disconnect();
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 1);
}
TEST_F(IntersectionObserverTest, RootIntersectionWithForceZeroLayoutHeight) {
WebView().GetSettings()->SetForceZeroLayoutHeight(true);
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<!DOCTYPE html>
<style>
body {
margin: 0;
height: 2000px;
}
#target {
width: 100px;
height: 100px;
position: absolute;
top: 1000px;
left: 200px;
}
</style>
<div id='target'></div>
)HTML");
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
observer->observe(target, exception_state);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_EQ(observer_delegate->CallCount(), 1);
EXPECT_TRUE(observer_delegate->LastIntersectionRect().IsEmpty());
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 600), mojom::blink::ScrollType::kProgrammatic);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_EQ(observer_delegate->CallCount(), 2);
EXPECT_FALSE(observer_delegate->LastIntersectionRect().IsEmpty());
EXPECT_EQ(PhysicalRect(200, 400, 100, 100),
observer_delegate->LastIntersectionRect());
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 1200), mojom::blink::ScrollType::kProgrammatic);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_EQ(observer_delegate->CallCount(), 3);
EXPECT_TRUE(observer_delegate->LastIntersectionRect().IsEmpty());
}
TEST_F(IntersectionObserverTest, TrackedTargetBookkeeping) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
</style>
<div id='target'></div>
)HTML");
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer1 =
IntersectionObserver::Create(observer_init, *observer_delegate);
observer1->observe(target);
IntersectionObserver* observer2 =
IntersectionObserver::Create(observer_init, *observer_delegate);
observer2->observe(target);
ElementIntersectionObserverData* target_data =
target->IntersectionObserverData();
ASSERT_TRUE(target_data);
IntersectionObserverController& controller =
GetDocument().EnsureIntersectionObserverController();
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 2u);
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
target->remove();
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
GetDocument().body()->AppendChild(target);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 2u);
observer1->unobserve(target);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 1u);
observer2->unobserve(target);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
}
TEST_F(IntersectionObserverTest, TrackedRootBookkeeping) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<div id='root'>
<div id='target1'></div>
<div id='target2'></div>
</div>
)HTML");
IntersectionObserverController& controller =
GetDocument().EnsureIntersectionObserverController();
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
Persistent<Element> root = GetDocument().getElementById("root");
Persistent<Element> target = GetDocument().getElementById("target1");
Persistent<IntersectionObserverInit> observer_init =
IntersectionObserverInit::Create();
observer_init->setRoot(MakeGarbageCollected<V8UnionDocumentOrElement>(root));
Persistent<TestIntersectionObserverDelegate> observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
Persistent<IntersectionObserver> observer =
IntersectionObserver::Create(observer_init, *observer_delegate);
// For an explicit-root observer, the root element is tracked only when it
// has observations and is connected. Target elements are not tracked.
ElementIntersectionObserverData* root_data = root->IntersectionObserverData();
ASSERT_TRUE(root_data);
EXPECT_FALSE(root_data->IsEmpty());
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
observer->observe(target);
ElementIntersectionObserverData* target_data =
target->IntersectionObserverData();
ASSERT_TRUE(target_data);
EXPECT_FALSE(target_data->IsEmpty());
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 1u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
// Root should not be tracked if it's not connected.
root->remove();
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
GetDocument().body()->AppendChild(root);
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 1u);
// Root should not be tracked if it has no observations.
observer->disconnect();
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
observer->observe(target);
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 1u);
observer->unobserve(target);
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
observer->observe(target);
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 1u);
// The existing observation should keep the observer alive and active.
// Flush any pending notifications, which hold a hard reference to the
// observer and can prevent it from being gc'ed. The observation will be the
// only thing keeping the observer alive.
test::RunPendingTasks();
observer_delegate->Clear();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_FALSE(root_data->IsEmpty());
EXPECT_FALSE(target_data->IsEmpty());
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 1u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
// When the last observation is disconnected, as a result of the target being
// gc'ed, the root element should no longer be tracked after the next
// lifecycle update.
target->remove();
target = nullptr;
target_data = nullptr;
// Removing the target from the DOM tree forces a notification to be
// queued, so flush it out.
test::RunPendingTasks();
observer_delegate->Clear();
ThreadState::Current()->CollectAllGarbageForTesting();
Compositor().BeginFrame();
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
// Removing the last reference to the observer should allow it to be dropeed
// from the root's ElementIntersectionObserverData.
observer = nullptr;
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_TRUE(root_data->IsEmpty());
target = GetDocument().getElementById("target2");
observer = IntersectionObserver::Create(observer_init, *observer_delegate);
observer->observe(target);
target_data = target->IntersectionObserverData();
ASSERT_TRUE(target_data);
// If the explicit root of an observer goes away, any existing observations
// should be disconnected.
target->remove();
root->remove();
root = nullptr;
test::RunPendingTasks();
observer_delegate->Clear();
observer_delegate = nullptr;
observer_init = nullptr;
// Removing the target from the tree is not enough to disconnect the
// observation.
EXPECT_FALSE(target_data->IsEmpty());
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_TRUE(target_data->IsEmpty());
EXPECT_EQ(controller.GetTrackedObserverCountForTesting(), 0u);
EXPECT_EQ(controller.GetTrackedObservationCountForTesting(), 0u);
}
TEST_F(IntersectionObserverTest, InaccessibleTarget) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<div id=target></div>
)HTML");
Persistent<TestIntersectionObserverDelegate> observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
Persistent<IntersectionObserver> observer = IntersectionObserver::Create(
IntersectionObserverInit::Create(), *observer_delegate);
Persistent<Element> target = GetDocument().getElementById("target");
ASSERT_EQ(observer_delegate->CallCount(), 0);
ASSERT_FALSE(observer->HasPendingActivity());
// When we start observing a target, we should queue up a task to deliver the
// observation. The observer should have pending activity.
observer->observe(target);
Compositor().BeginFrame();
ASSERT_EQ(observer_delegate->CallCount(), 0);
EXPECT_TRUE(observer->HasPendingActivity());
// After the observation is delivered, the observer no longer has activity
// pending.
test::RunPendingTasks();
ASSERT_EQ(observer_delegate->CallCount(), 1);
EXPECT_FALSE(observer->HasPendingActivity());
WeakPersistent<TestIntersectionObserverDelegate> observer_delegate_weak =
observer_delegate.Get();
WeakPersistent<IntersectionObserver> observer_weak = observer.Get();
WeakPersistent<Element> target_weak = target.Get();
ASSERT_TRUE(target_weak);
ASSERT_TRUE(observer_weak);
ASSERT_TRUE(observer_delegate_weak);
// When |target| is no longer live, and |observer| has no more pending tasks,
// both should be garbage-collected.
target->remove();
target = nullptr;
observer = nullptr;
observer_delegate = nullptr;
test::RunPendingTasks();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_FALSE(target_weak);
EXPECT_FALSE(observer_weak);
EXPECT_FALSE(observer_delegate_weak);
}
TEST_F(IntersectionObserverTest, InaccessibleTargetBeforeDelivery) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<div id=target></div>
)HTML");
Persistent<TestIntersectionObserverDelegate> observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
Persistent<IntersectionObserver> observer = IntersectionObserver::Create(
IntersectionObserverInit::Create(), *observer_delegate);
Persistent<Element> target = GetDocument().getElementById("target");
ASSERT_EQ(observer_delegate->CallCount(), 0);
ASSERT_FALSE(observer->HasPendingActivity());
WeakPersistent<TestIntersectionObserverDelegate> observer_delegate_weak =
observer_delegate.Get();
WeakPersistent<IntersectionObserver> observer_weak = observer.Get();
WeakPersistent<Element> target_weak = target.Get();
ASSERT_TRUE(target_weak);
ASSERT_TRUE(observer_weak);
ASSERT_TRUE(observer_delegate_weak);
// When we start observing |target|, a task should be queued to call the
// callback with |target| and other information. So even if we remove
// |target| in the same tick, |observer| would be kept alive.
observer->observe(target);
target->remove();
target = nullptr;
observer = nullptr;
observer_delegate = nullptr;
Compositor().BeginFrame();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_TRUE(target_weak);
EXPECT_TRUE(observer_weak);
EXPECT_TRUE(observer_delegate_weak);
// Once we run the callback, the observer has no more pending tasks, and so
// it should be garbage-collected along with the target.
test::RunPendingTasks();
ThreadState::Current()->CollectAllGarbageForTesting();
EXPECT_FALSE(target_weak);
EXPECT_FALSE(observer_weak);
EXPECT_FALSE(observer_delegate_weak);
}
TEST_F(IntersectionObserverTest, RootMarginDevicePixelRatio) {
WebView().SetZoomFactorForDeviceScaleFactor(3.5f);
WebView().MainFrameViewWidget()->Resize(gfx::Size(2800, 2100));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
body {
margin: 0;
}
#target {
height: 30px;
}
</style>
<div id='target'>Hello, world!</div>
)HTML");
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
observer_init->setRootMargin("-31px 0px 0px 0px");
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
observer->observe(target, exception_state);
ASSERT_FALSE(exception_state.HadException());
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_EQ(observer_delegate->CallCount(), 1);
EXPECT_EQ(observer_delegate->EntryCount(), 1);
EXPECT_FALSE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_EQ(ToPixelSnappedRect(
observer_delegate->LastEntry()->GetGeometry().RootRect()),
gfx::Rect(0, 31, 800, 600 - 31));
}
TEST_F(IntersectionObserverTest, CachedRectsTest) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
body { margin: 0; }
.spacer { height: 1000px; }
.scroller { overflow-y: scroll; height: 100px; }
</style>
<div id='root' class='scroller'>
<div id='target1-container'>
<div id='target1'>Hello, world!</div>
</div>
<div class='scroller'>
<div id='target2'>Hello, world!</div>
<div class='spacer'></div>
</div>
<div class='spacer'></div>
</div>
)HTML");
Element* root = GetDocument().getElementById("root");
Element* target1 = GetDocument().getElementById("target1");
Element* target2 = GetDocument().getElementById("target2");
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
observer_init->setRoot(MakeGarbageCollected<V8UnionDocumentOrElement>(root));
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
observer->observe(target1, exception_state);
ASSERT_FALSE(exception_state.HadException());
observer->observe(target2, exception_state);
ASSERT_FALSE(exception_state.HadException());
IntersectionObservation* observation1 =
target1->IntersectionObserverData()->GetObservationFor(*observer);
EXPECT_FALSE(observation1->CanUseCachedRectsForTesting());
IntersectionObservation* observation2 =
target2->IntersectionObserverData()->GetObservationFor(*observer);
EXPECT_FALSE(observation2->CanUseCachedRectsForTesting());
// Generate initial notifications and populate cache
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_TRUE(observation1->CanUseCachedRectsForTesting());
// observation2 can't use cached rects because the observer's root is not the
// target's enclosing scroller.
EXPECT_FALSE(observation2->CanUseCachedRectsForTesting());
// Scrolling the root should not invalidate.
PaintLayerScrollableArea* root_scroller =
root->GetLayoutBoxForScrolling()->GetScrollableArea();
root_scroller->SetScrollOffset(ScrollOffset(0, 100),
mojom::blink::ScrollType::kProgrammatic);
EXPECT_TRUE(observation1->CanUseCachedRectsForTesting());
// Changing layout between root and target should invalidate.
target1->parentElement()->SetInlineStyleProperty(CSSPropertyID::kMarginLeft,
"10px");
// Invalidation happens during style recalc, so force it here.
GetDocument().EnsurePaintLocationDataValidForNode(
target1, DocumentUpdateReason::kTest);
EXPECT_FALSE(observation1->CanUseCachedRectsForTesting());
// Moving target2 out from the subscroller should allow it to cache rects.
target2->remove();
root->appendChild(target2);
Compositor().BeginFrame();
test::RunPendingTasks();
EXPECT_TRUE(observation1->CanUseCachedRectsForTesting());
EXPECT_TRUE(observation2->CanUseCachedRectsForTesting());
}
TEST_F(IntersectionObserverV2Test, TrackVisibilityInit) {
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
EXPECT_FALSE(observer->trackVisibility());
// This should fail because no delay is set.
observer_init->setTrackVisibility(true);
observer = IntersectionObserver::Create(observer_init, *observer_delegate,
exception_state);
EXPECT_TRUE(exception_state.HadException());
// This should fail because the delay is < 100.
exception_state.ClearException();
observer_init->setDelay(99.9);
observer = IntersectionObserver::Create(observer_init, *observer_delegate,
exception_state);
EXPECT_TRUE(exception_state.HadException());
exception_state.ClearException();
observer_init->setDelay(101.);
observer = IntersectionObserver::Create(observer_init, *observer_delegate,
exception_state);
ASSERT_FALSE(exception_state.HadException());
EXPECT_TRUE(observer->trackVisibility());
EXPECT_EQ(observer->delay(), 101.);
}
TEST_F(IntersectionObserverV2Test, BasicOcclusion) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
div {
width: 100px;
height: 100px;
}
</style>
<div id='target'>
<div id='child'></div>
</div>
<div id='occluder'></div>
)HTML");
Compositor().BeginFrame();
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
observer_init->setTrackVisibility(true);
observer_init->setDelay(100);
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
Element* occluder = GetDocument().getElementById("occluder");
ASSERT_TRUE(target);
observer->observe(target);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 1);
EXPECT_EQ(observer_delegate->EntryCount(), 1);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_TRUE(observer_delegate->LastEntry()->isVisible());
occluder->SetInlineStyleProperty(CSSPropertyID::kMarginTop, "-10px");
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 2);
EXPECT_EQ(observer_delegate->EntryCount(), 2);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_FALSE(observer_delegate->LastEntry()->isVisible());
// Zero-opacity objects should not count as occluding.
occluder->SetInlineStyleProperty(CSSPropertyID::kOpacity, "0");
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 3);
EXPECT_EQ(observer_delegate->EntryCount(), 3);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_TRUE(observer_delegate->LastEntry()->isVisible());
}
TEST_F(IntersectionObserverV2Test, BasicOpacity) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
div {
width: 100px;
height: 100px;
}
</style>
<div id='transparent'>
<div id='target'></div>
</div>
)HTML");
Compositor().BeginFrame();
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
observer_init->setTrackVisibility(true);
observer_init->setDelay(100);
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
Element* transparent = GetDocument().getElementById("transparent");
ASSERT_TRUE(target);
ASSERT_TRUE(transparent);
observer->observe(target);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 1);
EXPECT_EQ(observer_delegate->EntryCount(), 1);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_TRUE(observer_delegate->LastEntry()->isVisible());
transparent->SetInlineStyleProperty(CSSPropertyID::kOpacity, "0.99");
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 2);
EXPECT_EQ(observer_delegate->EntryCount(), 2);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_FALSE(observer_delegate->LastEntry()->isVisible());
}
TEST_F(IntersectionObserverV2Test, BasicTransform) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
div {
width: 100px;
height: 100px;
}
</style>
<div id='transformed'>
<div id='target'></div>
</div>
)HTML");
Compositor().BeginFrame();
IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
observer_init->setTrackVisibility(true);
observer_init->setDelay(100);
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* observer = IntersectionObserver::Create(
observer_init, *observer_delegate, exception_state);
ASSERT_FALSE(exception_state.HadException());
Element* target = GetDocument().getElementById("target");
Element* transformed = GetDocument().getElementById("transformed");
ASSERT_TRUE(target);
ASSERT_TRUE(transformed);
observer->observe(target);
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 1);
EXPECT_EQ(observer_delegate->EntryCount(), 1);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_TRUE(observer_delegate->LastEntry()->isVisible());
// 2D translations and proportional upscaling is permitted.
transformed->SetInlineStyleProperty(
CSSPropertyID::kTransform, "translateX(10px) translateY(20px) scale(2)");
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 1);
EXPECT_EQ(observer_delegate->EntryCount(), 1);
// Any other transform is not permitted.
transformed->SetInlineStyleProperty(CSSPropertyID::kTransform,
"skewX(10deg)");
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(observer_delegate->CallCount(), 2);
EXPECT_EQ(observer_delegate->EntryCount(), 2);
EXPECT_TRUE(observer_delegate->LastEntry()->isIntersecting());
EXPECT_FALSE(observer_delegate->LastEntry()->isVisible());
}
TEST_F(IntersectionObserverTest, ApplyMarginToTarget) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(200, 200));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
#scroller { height: 100px; overflow: scroll; }
#target { width: 50px; height: 50px; }
.spacer { height: 105px; }
</style>
<div id=scroller>
<div class=spacer></div>
<div id=target></div>
</div>
)HTML");
Compositor().BeginFrame();
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
TestIntersectionObserverDelegate* root_margin_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
IntersectionObserver* root_margin_observer =
MakeGarbageCollected<IntersectionObserver>(
*root_margin_delegate, nullptr, Vector<Length>{Length::Fixed(10)},
Vector<float>{std::numeric_limits<float>::min()},
IntersectionObserver::kFractionOfTarget, 0, false, false,
IntersectionObserver::kApplyMarginToRoot,
/* use_overflow_clip_edge */ false);
DummyExceptionStateForTesting exception_state;
root_margin_observer->observe(target, exception_state);
ASSERT_FALSE(exception_state.HadException());
TestIntersectionObserverDelegate* target_margin_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
// Same parameters as above except that margin is applied to target.
IntersectionObserver* target_margin_observer =
MakeGarbageCollected<IntersectionObserver>(
*target_margin_delegate, nullptr, Vector<Length>{Length::Fixed(10)},
Vector<float>{std::numeric_limits<float>::min()},
IntersectionObserver::kFractionOfTarget, 0, false, false,
IntersectionObserver::kApplyMarginToTarget,
/* use_overflow_clip_edge */ false);
target_margin_observer->observe(target, exception_state);
ASSERT_FALSE(exception_state.HadException());
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(root_margin_delegate->CallCount(), 1);
EXPECT_EQ(root_margin_delegate->EntryCount(), 1);
// Since the inner scroller clips content, the root margin has no effect and
// target is not intersecting.
EXPECT_FALSE(root_margin_delegate->LastEntry()->isIntersecting());
EXPECT_EQ(target_margin_delegate->CallCount(), 1);
EXPECT_EQ(target_margin_delegate->EntryCount(), 1);
// Since the margin is applied to the target, the inner scroller clips an
// expanded rect, which ends up being visible in the root. Hence, it is
// intersecting.
EXPECT_TRUE(target_margin_delegate->LastEntry()->isIntersecting());
}
TEST_F(IntersectionObserverTest, TargetMarginPercentResolvesAgainstRoot) {
WebView().MainFrameViewWidget()->Resize(gfx::Size(200, 500));
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
<style>
#scroller { height: 100px; overflow: scroll; }
#target { width: 50px; height: 50px; }
.spacer { height: 145px; }
</style>
<div id=scroller>
<div class=spacer></div>
<div id=target></div>
</div>
)HTML");
Compositor().BeginFrame();
Element* target = GetDocument().getElementById("target");
ASSERT_TRUE(target);
TestIntersectionObserverDelegate* target_margin_delegate =
MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
// 10% margin on a target would be 5px if it resolved against target, which is
// not enough to intersect. It would be 10px if it resolved against the
// scroller, which is also not enough. However, it would be 50px if it
// resolved against root, which would make it intersecting.
IntersectionObserver* target_margin_observer =
MakeGarbageCollected<IntersectionObserver>(
*target_margin_delegate, nullptr, Vector<Length>{Length::Percent(10)},
Vector<float>{std::numeric_limits<float>::min()},
IntersectionObserver::kFractionOfTarget, 0, false, false,
IntersectionObserver::kApplyMarginToTarget,
/* use_overflow_clip_edge */ false);
DummyExceptionStateForTesting exception_state;
target_margin_observer->observe(target, exception_state);
ASSERT_FALSE(exception_state.HadException());
Compositor().BeginFrame();
test::RunPendingTasks();
ASSERT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_EQ(target_margin_delegate->CallCount(), 1);
EXPECT_EQ(target_margin_delegate->EntryCount(), 1);
EXPECT_TRUE(target_margin_delegate->LastEntry()->isIntersecting());
}
} // namespace blink
|
// Copyright (c) 2012 House of Life Property Ltd. All rights reserved.
// Copyright (c) 2012 Crystalnix <vgachkaylo@crystalnix.com>
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/facebook_chat/facebook_chat_manager_service_factory.h"
#include "chrome/browser/facebook_chat/facebook_chat_manager.h"
#include "chrome/browser/profiles/profile_dependency_manager.h"
// static
FacebookChatManager* FacebookChatManagerServiceFactory::GetForProfile(Profile* profile) {
return static_cast<FacebookChatManager*>(
GetInstance()->GetServiceForProfile(profile, true));
}
// static
FacebookChatManagerServiceFactory* FacebookChatManagerServiceFactory::GetInstance() {
return Singleton<FacebookChatManagerServiceFactory>::get();
}
FacebookChatManagerServiceFactory::FacebookChatManagerServiceFactory()
: ProfileKeyedServiceFactory("facebook_chat_manager", ProfileDependencyManager::GetInstance()) {
}
FacebookChatManagerServiceFactory::~FacebookChatManagerServiceFactory() {
}
ProfileKeyedService* FacebookChatManagerServiceFactory::BuildServiceInstanceFor(
Profile* profile) const {
return new FacebookChatManager();
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QMessageBox>
#include<QFile>
#include<QFileDialog>
#include<QDir>
#include<QTextStream>
#include<QFontDialog>
#include<QFont>
#include<QColor>
#include<QColorDialog>
#include<QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowIcon(QIcon(":/image/myicon"));
this->setWindowTitle("Untitled.txt----------PN结记事本");
QObject::connect(ui->newFile,SIGNAL(triggered()),this,SLOT(newFileSlot()));
QObject::connect(ui->openFile,SIGNAL(triggered()),this,SLOT(openFileSlot()));
QObject::connect(ui->saveFile,SIGNAL(triggered()),this,SLOT(saveFileSlot()));
QObject::connect(ui->saveAsFile,SIGNAL(triggered()),this,SLOT(saveAsFileSlot()));
QObject::connect(ui->quit,SIGNAL(triggered()),this,SLOT(close()));
QObject::connect(ui->undoAction,SIGNAL(triggered()),ui->textEdit,SLOT(undo()));
QObject::connect(ui->redoAction,SIGNAL(triggered()),ui->textEdit,SLOT(redo()));
QObject::connect(ui->copyAction,SIGNAL(triggered()),ui->textEdit,SLOT(copy()));
QObject::connect(ui->pastAction,SIGNAL(triggered()),ui->textEdit,SLOT(paste()));
QObject::connect(ui->cutAction,SIGNAL(triggered()),ui->textEdit,SLOT(cut()));
QObject::connect(ui->deleteAction,SIGNAL(triggered()),ui->textEdit,SLOT(clear()));
QObject::connect(ui->allAction,SIGNAL(triggered()),ui->textEdit,SLOT(selectAll()));
QObject::connect(ui->fontAction,SIGNAL(triggered()),this,SLOT(setFontSlot()));
QObject::connect(ui->colorAction,SIGNAL(triggered()),this,SLOT(setColorSlot()));
QObject::connect(ui->aboutAction,SIGNAL(triggered()),this,SLOT(aboutSlot()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::newFileSlot()
{
if(ui->textEdit->document()->isModified())
{
// qDebug()<<"内容已经改变";
QString FileName=QFileDialog::getSaveFileName(this,tr("Save File"),"Untitled.txt",tr("Text(*.txt);;C++ (*.cpp)"));
if(FileName.isEmpty())
{
QMessageBox::information(this,"Error Message","请选择一个文件");
return;
}
else
{
QFile *file=new QFile;
file->setFileName(FileName);
bool ok=file->open(QIODevice::WriteOnly);
if(ok)
{
QTextStream out(file);
out<<ui->textEdit->toPlainText();
file->close();
delete file;
}
else
{
QMessageBox::warning(this,"Error","保存不成功");
}
}
}
else
{
ui->textEdit->clear();
this->setWindowTitle("Untitled.txt----------PN结记事本");
}
}
void MainWindow::openFileSlot()
{
QString FileName=QFileDialog::getOpenFileName(this,"Open File",QDir::currentPath());
// qDebug()<<FileName;
if(FileName.isEmpty())
{
QMessageBox::information(this,"Error Message","请选择有效路径");
return;
}
else
{
QFile *file=new QFile;
file->setFileName(FileName);
bool ok=file->open(QIODevice::ReadOnly);
if(ok)
{
QTextStream in(file);
ui->textEdit->setText(in.readAll());
file->close();
delete file;
}
else
{
QMessageBox::warning(this,"Error","文件打开不成功!"+file->error());
}
}
}
void MainWindow::saveFileSlot()
{
if(saveFileName==NULL)
{
saveFileName=QFileDialog::getSaveFileName(this,tr("Save File"),"Untitled.txt",tr("Text(*.txt);;C++ (*.cpp)"));
if(saveFileName.isEmpty())
{
QMessageBox::information(this,"Error Message","请选择一个文件");
}
}
this->setWindowTitle(saveFileName+".txt----------PN结记事本");
QString FileName=saveFileName;
QFile *file=new QFile;
file->setFileName(FileName);
bool ok=file->open(QIODevice::WriteOnly);
if(ok)
{
QTextStream out(file);
out<<ui->textEdit->toPlainText();
file->close();
}
else
{
QMessageBox::warning(this,"Error","保存不成功");
}
delete file;
}
void MainWindow::saveAsFileSlot()
{
QString FileName=QFileDialog::getSaveFileName(this,tr("Save File"),"Untitled.txt",tr("Text(*.txt);;C++ (*.cpp)"));
this->saveFileName=FileName;
if(FileName.isEmpty())
{
QMessageBox::information(this,"Error Message","未能保存,请选择一个文件");
return;
}
else
{
this->setWindowTitle(saveFileName+".txt----------PN结记事本");
QFile *file=new QFile;
file->setFileName(FileName);
bool ok=file->open(QIODevice::WriteOnly);
if(ok)
{
QTextStream out(file);
out<<ui->textEdit->toPlainText();
file->close();
}
else
{
QMessageBox::warning(this,"Error","保存不成功");
}
delete file;
}
}
void MainWindow::setFontSlot()
{
bool ok;
QFont font = QFontDialog::getFont(&ok, QFont("Times", 12), this);
if (ok) {
// font is set to the font the user selected
ui->textEdit->setFont(font);
} else {
QMessageBox::information(this,"Error","获取字体失败!");
// the user canceled the dialog; font is set to the initial
// value, in this case Times, 12.
}
}
void MainWindow::setColorSlot()
{
const QColor color = QColorDialog::getColor(Qt::green, this, "Select Color");
if (color.isValid())
{
ui->textEdit->setTextColor(color);
}
else
{
QMessageBox::information(this,"Error","颜色设置失败!");
}
}
void MainWindow::aboutSlot()
{
}
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdio.h>
#include <stdlib.h>
#include <kcpolydb.h>
#include "util/histogram.h"
#include "util/random.h"
#include "util/testutil.h"
// Comma-separated list of operations to run in the specified order
// Actual benchmarks:
//
// fillseq -- write N values in sequential key order in async mode
// fillrandom -- write N values in random key order in async mode
// overwrite -- overwrite N values in random key order in async mode
// fillseqsync -- write N/100 values in sequential key order in sync mode
// fillrandsync -- write N/100 values in random key order in sync mode
// fillrand100K -- write N/1000 100K values in random order in async mode
// fillseq100K -- write N/1000 100K values in seq order in async mode
// readseq -- read N times sequentially
// readseq100K -- read N/1000 100K values in sequential order in async mode
// readrand100K -- read N/1000 100K values in sequential order in async mode
// readrandom -- read N times in random order
static const char* FLAGS_benchmarks =
"fillseq,"
"fillseqsync,"
"fillrandsync,"
"fillrandom,"
"overwrite,"
"readrandom,"
"readseq,"
"fillrand100K,"
"fillseq100K,"
"readseq100K,"
"readrand100K,"
;
// Number of key/values to place in database
static int FLAGS_num = 1000000;
// Number of read operations to do. If negative, do FLAGS_num reads.
static int FLAGS_reads = -1;
// Size of each value
static int FLAGS_value_size = 100;
// Arrange to generate values that shrink to this fraction of
// their original size after compression
static double FLAGS_compression_ratio = 0.5;
// Print histogram of operation timings
static bool FLAGS_histogram = false;
// Cache size. Default 4 MB
static int FLAGS_cache_size = 4194304;
// Page size. Default 1 KB
static int FLAGS_page_size = 1024;
// If true, do not destroy the existing database. If you set this
// flag and also specify a benchmark that wants a fresh database, that
// benchmark will fail.
static bool FLAGS_use_existing_db = false;
// Compression flag. If true, compression is on. If false, compression
// is off.
static bool FLAGS_compression = true;
// Use the db with the following name.
static const char* FLAGS_db = NULL;
inline
static void DBSynchronize(kyotocabinet::TreeDB* db_)
{
// Synchronize will flush writes to disk
if (!db_->synchronize()) {
fprintf(stderr, "synchronize error: %s\n", db_->error().name());
}
}
namespace leveldb {
// Helper for quickly generating random data.
namespace {
class RandomGenerator {
private:
std::string data_;
int pos_;
public:
RandomGenerator() {
// We use a limited amount of data over and over again and ensure
// that it is larger than the compression window (32KB), and also
// large enough to serve all typical value sizes we want to write.
Random rnd(301);
std::string piece;
while (data_.size() < 1048576) {
// Add a short fragment that is as compressible as specified
// by FLAGS_compression_ratio.
test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
data_.append(piece);
}
pos_ = 0;
}
Slice Generate(int len) {
if (pos_ + len > data_.size()) {
pos_ = 0;
assert(len < data_.size());
}
pos_ += len;
return Slice(data_.data() + pos_ - len, len);
}
};
static Slice TrimSpace(Slice s) {
int start = 0;
while (start < s.size() && isspace(s[start])) {
start++;
}
int limit = s.size();
while (limit > start && isspace(s[limit-1])) {
limit--;
}
return Slice(s.data() + start, limit - start);
}
} // namespace
class Benchmark {
private:
kyotocabinet::TreeDB* db_;
int db_num_;
int num_;
int reads_;
double start_;
double last_op_finish_;
int64_t bytes_;
std::string message_;
Histogram hist_;
RandomGenerator gen_;
Random rand_;
kyotocabinet::LZOCompressor<kyotocabinet::LZO::RAW> comp_;
// State kept for progress messages
int done_;
int next_report_; // When to report next
void PrintHeader() {
const int kKeySize = 16;
PrintEnvironment();
fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
fprintf(stdout, "Values: %d bytes each (%d bytes after compression)\n",
FLAGS_value_size,
static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
fprintf(stdout, "Entries: %d\n", num_);
fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_)
/ 1048576.0));
fprintf(stdout, "FileSize: %.1f MB (estimated)\n",
(((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_)
/ 1048576.0));
PrintWarnings();
fprintf(stdout, "------------------------------------------------\n");
}
void PrintWarnings() {
#if defined(__GNUC__) && !defined(__OPTIMIZE__)
fprintf(stdout,
"WARNING: Optimization is disabled: benchmarks unnecessarily slow\n"
);
#endif
#ifndef NDEBUG
fprintf(stdout,
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
#endif
}
void PrintEnvironment() {
fprintf(stderr, "Kyoto Cabinet: version %s, lib ver %d, lib rev %d\n",
kyotocabinet::VERSION, kyotocabinet::LIBVER, kyotocabinet::LIBNFTY);
#if defined(__linux)
time_t now = time(NULL);
fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline
FILE* cpuinfo = fopen("/proc/cpuinfo", "r");
if (cpuinfo != NULL) {
char line[1000];
int num_cpus = 0;
std::string cpu_type;
std::string cache_size;
while (fgets(line, sizeof(line), cpuinfo) != NULL) {
const char* sep = strchr(line, ':');
if (sep == NULL) {
continue;
}
Slice key = TrimSpace(Slice(line, sep - 1 - line));
Slice val = TrimSpace(Slice(sep + 1));
if (key == "model name") {
++num_cpus;
cpu_type = val.ToString();
} else if (key == "cache size") {
cache_size = val.ToString();
}
}
fclose(cpuinfo);
fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
}
#endif
}
void Start() {
start_ = Env::Default()->NowMicros() * 1e-6;
bytes_ = 0;
message_.clear();
last_op_finish_ = start_;
hist_.Clear();
done_ = 0;
next_report_ = 100;
}
void FinishedSingleOp() {
if (FLAGS_histogram) {
double now = Env::Default()->NowMicros() * 1e-6;
double micros = (now - last_op_finish_) * 1e6;
hist_.Add(micros);
if (micros > 20000) {
fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
fflush(stderr);
}
last_op_finish_ = now;
}
done_++;
if (done_ >= next_report_) {
if (next_report_ < 1000) next_report_ += 100;
else if (next_report_ < 5000) next_report_ += 500;
else if (next_report_ < 10000) next_report_ += 1000;
else if (next_report_ < 50000) next_report_ += 5000;
else if (next_report_ < 100000) next_report_ += 10000;
else if (next_report_ < 500000) next_report_ += 50000;
else next_report_ += 100000;
fprintf(stderr, "... finished %d ops%30s\r", done_, "");
fflush(stderr);
}
}
void Stop(const Slice& name) {
double finish = Env::Default()->NowMicros() * 1e-6;
// Pretend at least one op was done in case we are running a benchmark
// that does not call FinishedSingleOp().
if (done_ < 1) done_ = 1;
if (bytes_ > 0) {
char rate[100];
snprintf(rate, sizeof(rate), "%6.1f MB/s",
(bytes_ / 1048576.0) / (finish - start_));
if (!message_.empty()) {
message_ = std::string(rate) + " " + message_;
} else {
message_ = rate;
}
}
fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
name.ToString().c_str(),
(finish - start_) * 1e6 / done_,
(message_.empty() ? "" : " "),
message_.c_str());
if (FLAGS_histogram) {
fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str());
}
fflush(stdout);
}
public:
enum Order {
SEQUENTIAL,
RANDOM
};
enum DBState {
FRESH,
EXISTING
};
Benchmark()
: db_(NULL),
num_(FLAGS_num),
reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
bytes_(0),
rand_(301) {
std::vector<std::string> files;
std::string test_dir;
Env::Default()->GetTestDirectory(&test_dir);
Env::Default()->GetChildren(test_dir.c_str(), &files);
if (!FLAGS_use_existing_db) {
for (int i = 0; i < files.size(); i++) {
if (Slice(files[i]).starts_with("dbbench_polyDB")) {
std::string file_name(test_dir);
file_name += "/";
file_name += files[i];
Env::Default()->DeleteFile(file_name.c_str());
}
}
}
}
~Benchmark() {
if (!db_->close()) {
fprintf(stderr, "close error: %s\n", db_->error().name());
}
}
void Run() {
PrintHeader();
Open(false);
const char* benchmarks = FLAGS_benchmarks;
while (benchmarks != NULL) {
const char* sep = strchr(benchmarks, ',');
Slice name;
if (sep == NULL) {
name = benchmarks;
benchmarks = NULL;
} else {
name = Slice(benchmarks, sep - benchmarks);
benchmarks = sep + 1;
}
Start();
bool known = true;
bool write_sync = false;
if (name == Slice("fillseq")) {
Write(write_sync, SEQUENTIAL, FRESH, num_, FLAGS_value_size, 1);
DBSynchronize(db_);
} else if (name == Slice("fillrandom")) {
Write(write_sync, RANDOM, FRESH, num_, FLAGS_value_size, 1);
DBSynchronize(db_);
} else if (name == Slice("overwrite")) {
Write(write_sync, RANDOM, EXISTING, num_, FLAGS_value_size, 1);
DBSynchronize(db_);
} else if (name == Slice("fillrandsync")) {
write_sync = true;
Write(write_sync, RANDOM, FRESH, num_ / 100, FLAGS_value_size, 1);
DBSynchronize(db_);
} else if (name == Slice("fillseqsync")) {
write_sync = true;
Write(write_sync, SEQUENTIAL, FRESH, num_ / 100, FLAGS_value_size, 1);
DBSynchronize(db_);
} else if (name == Slice("fillrand100K")) {
Write(write_sync, RANDOM, FRESH, num_ / 1000, 100 * 1000, 1);
DBSynchronize(db_);
} else if (name == Slice("fillseq100K")) {
Write(write_sync, SEQUENTIAL, FRESH, num_ / 1000, 100 * 1000, 1);
DBSynchronize(db_);
} else if (name == Slice("readseq")) {
ReadSequential();
} else if (name == Slice("readrandom")) {
ReadRandom();
} else if (name == Slice("readrand100K")) {
int n = reads_;
reads_ /= 1000;
ReadRandom();
reads_ = n;
} else if (name == Slice("readseq100K")) {
int n = reads_;
reads_ /= 1000;
ReadSequential();
reads_ = n;
} else {
known = false;
if (name != Slice()) { // No error message for empty name
fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
}
}
if (known) {
Stop(name);
}
}
}
private:
void Open(bool sync) {
assert(db_ == NULL);
// Initialize db_
db_ = new kyotocabinet::TreeDB();
char file_name[100];
db_num_++;
std::string test_dir;
Env::Default()->GetTestDirectory(&test_dir);
snprintf(file_name, sizeof(file_name),
"%s/dbbench_polyDB-%d.kct",
test_dir.c_str(),
db_num_);
// Create tuning options and open the database
int open_options = kyotocabinet::PolyDB::OWRITER |
kyotocabinet::PolyDB::OCREATE;
int tune_options = kyotocabinet::TreeDB::TSMALL |
kyotocabinet::TreeDB::TLINEAR;
if (FLAGS_compression) {
tune_options |= kyotocabinet::TreeDB::TCOMPRESS;
db_->tune_compressor(&comp_);
}
db_->tune_options(tune_options);
db_->tune_page_cache(FLAGS_cache_size);
db_->tune_page(FLAGS_page_size);
db_->tune_map(256LL<<20);
if (sync) {
open_options |= kyotocabinet::PolyDB::OAUTOSYNC;
}
if (!db_->open(file_name, open_options)) {
fprintf(stderr, "open error: %s\n", db_->error().name());
}
}
void Write(bool sync, Order order, DBState state,
int num_entries, int value_size, int entries_per_batch) {
// Create new database if state == FRESH
if (state == FRESH) {
if (FLAGS_use_existing_db) {
message_ = "skipping (--use_existing_db is true)";
return;
}
delete db_;
db_ = NULL;
Open(sync);
Start(); // Do not count time taken to destroy/open
}
if (num_entries != num_) {
char msg[100];
snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
message_ = msg;
}
// Write to database
for (int i = 0; i < num_entries; i++)
{
const int k = (order == SEQUENTIAL) ? i : (rand_.Next() % num_entries);
char key[100];
snprintf(key, sizeof(key), "%016d", k);
bytes_ += value_size + strlen(key);
std::string cpp_key = key;
if (!db_->set(cpp_key, gen_.Generate(value_size).ToString())) {
fprintf(stderr, "set error: %s\n", db_->error().name());
}
FinishedSingleOp();
}
}
void ReadSequential() {
kyotocabinet::DB::Cursor* cur = db_->cursor();
cur->jump();
std::string ckey, cvalue;
while (cur->get(&ckey, &cvalue, true)) {
bytes_ += ckey.size() + cvalue.size();
FinishedSingleOp();
}
delete cur;
}
void ReadRandom() {
std::string value;
for (int i = 0; i < reads_; i++) {
char key[100];
const int k = rand_.Next() % reads_;
snprintf(key, sizeof(key), "%016d", k);
db_->get(key, &value);
FinishedSingleOp();
}
}
};
} // namespace leveldb
int main(int argc, char** argv) {
std::string default_db_path;
for (int i = 1; i < argc; i++) {
double d;
int n;
char junk;
if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
} else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
FLAGS_compression_ratio = d;
} else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 &&
(n == 0 || n == 1)) {
FLAGS_histogram = n;
} else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
FLAGS_num = n;
} else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
FLAGS_reads = n;
} else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
FLAGS_value_size = n;
} else if (sscanf(argv[i], "--cache_size=%d%c", &n, &junk) == 1) {
FLAGS_cache_size = n;
} else if (sscanf(argv[i], "--page_size=%d%c", &n, &junk) == 1) {
FLAGS_page_size = n;
} else if (sscanf(argv[i], "--compression=%d%c", &n, &junk) == 1 &&
(n == 0 || n == 1)) {
FLAGS_compression = (n == 1) ? true : false;
} else if (strncmp(argv[i], "--db=", 5) == 0) {
FLAGS_db = argv[i] + 5;
} else {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
exit(1);
}
}
// Choose a location for the test database if none given with --db=<path>
if (FLAGS_db == NULL) {
leveldb::Env::Default()->GetTestDirectory(&default_db_path);
default_db_path += "/dbbench";
FLAGS_db = default_db_path.c_str();
}
leveldb::Benchmark benchmark;
benchmark.Run();
return 0;
}
|
// License: BSD 3 Clause
// Copyright (C) 2012, Google Inc. All rights reserved.
// Copyright (C) 2015+, The LabSound Authors. All rights reserved.
#include "LabSound/core/OscillatorNode.h"
#include "LabSound/core/WaveTable.h"
#include "LabSound/core/AudioArray.h"
#include "internal/Assertions.h"
#include "internal/FFTFrame.h"
#include "internal/VectorMath.h"
#include <algorithm>
#include <iostream>
#include <exception>
// The number of bands per octave. Each octave will have this many entries in the wave tables.
const unsigned kNumberOfOctaveBands = 3;
// The max length of a periodic wave. This must be a power of two greater than or equal to 2048 and
// must be supported by the FFT routines.
const unsigned kMaxPeriodicWaveSize = 16384;
const float CentsPerRange = 1200 / kNumberOfOctaveBands;
namespace lab
{
using namespace VectorMath;
WaveTable::WaveTable(float sampleRate, OscillatorType basicWaveform) :
m_sampleRate(sampleRate),
m_centsPerRange(CentsPerRange)
{
float nyquist = 0.5 * m_sampleRate;
m_lowestFundamentalFrequency = nyquist / maxNumberOfPartials();
m_rateScale = periodicWaveSize() / m_sampleRate;
// Compute the number of ranges needed to cover the entire frequency range, assuming
// kNumberOfOctaveBands per octave.
m_numberOfRanges = 0.5 + kNumberOfOctaveBands * log2f(periodicWaveSize());
generateBasicWaveform(basicWaveform);
}
WaveTable::WaveTable(float sampleRate, OscillatorType basicWaveform, std::vector<float> & real, std::vector<float> & imag)
: m_sampleRate(sampleRate),
m_centsPerRange(CentsPerRange)
{
float nyquist = 0.5 * m_sampleRate;
m_lowestFundamentalFrequency = nyquist / maxNumberOfPartials();
m_rateScale = periodicWaveSize() / m_sampleRate;
// Compute the number of ranges needed to cover the entire frequency range, assuming
// kNumberOfOctaveBands per octave.
m_numberOfRanges = 0.5 + kNumberOfOctaveBands * log2f(periodicWaveSize());
bool isGood = real.size() == imag.size() && real.size() > 0;
if (isGood)
{
createBandLimitedTables(&real[0], &imag[0], real.size());
}
else
{
throw std::runtime_error("Bad FFT data");
}
}
WaveTable::~WaveTable()
{
}
unsigned WaveTable::periodicWaveSize() const
{
// Choose an appropriate wave size for the given sample rate. This allows us to use shorter
// FFTs when possible to limit the complexity. The breakpoints here are somewhat arbitrary, but
// we want sample rates around 44.1 kHz or so to have a size of 4096 to preserve backward
// compatibility.
if (m_sampleRate <= 24000) {
return 2048;
}
if (m_sampleRate <= 88200) {
return 4096;
}
return kMaxPeriodicWaveSize;
}
void WaveTable::waveDataForFundamentalFrequency(float fundamentalFrequency, float* &lowerWaveData, float* &higherWaveData, float& tableInterpolationFactor)
{
// Negative frequencies are allowed, in which case we alias to the positive frequency.
fundamentalFrequency = std::abs(fundamentalFrequency);
// Calculate the pitch range.
float ratio = fundamentalFrequency > 0 ? fundamentalFrequency / m_lowestFundamentalFrequency : 0.5;
float centsAboveLowestFrequency = log2f(ratio) * 1200;
// Add one to round-up to the next range just in time to truncate partials before aliasing occurs.
float pitchRange = 1 + centsAboveLowestFrequency / m_centsPerRange;
pitchRange = std::max(pitchRange, 0.0f);
pitchRange = std::min(pitchRange, static_cast<float>(numberOfRanges() - 1));
// The words "lower" and "higher" refer to the table data having the lower and higher numbers of partials.
// It's a little confusing since the range index gets larger the more partials we cull out.
// So the lower table data will have a larger range index.
unsigned rangeIndex1 = static_cast<unsigned>(pitchRange);
unsigned rangeIndex2 = rangeIndex1 < numberOfRanges() - 1 ? rangeIndex1 + 1 : rangeIndex1;
lowerWaveData = m_bandLimitedTables[rangeIndex2]->data();
higherWaveData = m_bandLimitedTables[rangeIndex1]->data();
// Ranges from 0 -> 1 to interpolate between lower -> higher.
tableInterpolationFactor = pitchRange - rangeIndex1;
}
unsigned WaveTable::maxNumberOfPartials() const
{
return periodicWaveSize() / 2;
}
unsigned WaveTable::numberOfPartialsForRange(unsigned rangeIndex) const
{
// Number of cents below nyquist where we cull partials.
float centsToCull = rangeIndex * m_centsPerRange;
// A value from 0 -> 1 representing what fraction of the partials to keep.
float cullingScale = pow(2, -centsToCull / 1200);
// The very top range will have all the partials culled.
unsigned numberOfPartials = cullingScale * maxNumberOfPartials();
return numberOfPartials;
}
// Convert into time-domain wave tables.
// One table is created for each range for non-aliasing playback at different playback rates.
// Thus, higher ranges have more high-frequency partials culled out.
void WaveTable::createBandLimitedTables(const float* realData, const float* imagData, unsigned numberOfComponents)
{
float normalizationScale = 1.f;
unsigned fftSize = periodicWaveSize();
unsigned halfSize = fftSize / 2 + 1;
unsigned i;
numberOfComponents = std::min(numberOfComponents, halfSize);
m_bandLimitedTables.reserve(numberOfRanges());
for (unsigned rangeIndex = 0; rangeIndex < numberOfRanges(); ++rangeIndex) {
// This FFTFrame is used to cull partials (represented by frequency bins).
FFTFrame frame(fftSize);
float* realP = frame.realData();
float* imagP = frame.imagData();
// Copy from loaded frequency data and generate the complex conjugate because of the way the
// inverse FFT is defined versus the values in the arrays. Note also that although the IFFT
// does a scaling by 1/N, we take care of this when the normalization scaling is done.
float minusOne = -1;
memcpy(realP, realData, numberOfComponents * sizeof(*realP));
vsmul(imagData, 1, &minusOne, imagP, 1, numberOfComponents);
// Find the starting bin where we should start culling. We need to clear out the highest
// frequencies to band-limit the waveform.
unsigned numberOfPartials = numberOfPartialsForRange(rangeIndex);
// If fewer components were provided than 1/2 FFT size, then clear the remaining bins.
// We also need to cull the aliasing partials for this pitch range.
for (i = std::min(numberOfComponents, numberOfPartials + 1); i < halfSize; ++i) {
realP[i] = 0;
imagP[i] = 0;
}
// Clear packed-nyquist and any DC-offset.
realP[0] = 0;
imagP[0] = 0;
// Create the band-limited table.
m_bandLimitedTables.push_back(std::unique_ptr<lab::AudioFloatArray>(new lab::AudioFloatArray(periodicWaveSize())));
// Apply an inverse FFT to generate the time-domain table data.
float* data = m_bandLimitedTables[rangeIndex]->data();
frame.doInverseFFT(data);
// For the first range (which has the highest power), calculate its peak value then compute normalization scale.
if (!rangeIndex) {
float maxValue;
vmaxmgv(data, 1, &maxValue, fftSize);
if (maxValue)
normalizationScale = 1.0f / maxValue;
}
// Apply normalization scale.
vsmul(data, 1, &normalizationScale, data, 1, fftSize);
}
}
void WaveTable::generateBasicWaveform(OscillatorType shape)
{
unsigned fftSize = periodicWaveSize();
unsigned halfSize = fftSize / 2;
lab::AudioFloatArray real(halfSize);
lab::AudioFloatArray imag(halfSize);
float* realP = real.data();
float* imagP = imag.data();
// Clear DC and Nyquist.
realP[0] = 0;
imagP[0] = 0;
const float piFloat = float(3.14159265358979323846);
for (unsigned n = 1; n < halfSize; ++n)
{
float piFactor = 2 / (n * piFloat);
// All waveforms are odd functions with a positive slope at time 0. Hence the coefficients
// for cos() are always 0.
// Fourier coefficients according to standard definition:
// b = 1/pi*integrate(f(x)*sin(n*x), x, -pi, pi)
// = 2/pi*integrate(f(x)*sin(n*x), x, 0, pi)
// since f(x) is an odd function.
float b; // Coefficient for sin().
// Calculate Fourier coefficients depending on the shape. Note that the overall scaling
// (magnitude) of the waveforms is normalized in createBandLimitedTables().
switch (shape) {
case OscillatorType::SINE:
// Standard sine wave function.
b = (n == 1) ? 1 : 0;
break;
case OscillatorType::SQUARE:
// Square-shaped waveform with the first half its maximum value and the second half its
// minimum value.
//
// See http://mathworld.wolfram.com/FourierSeriesSquareWave.html
//
// b[n] = 2/n/pi*(1-(-1)^n)
// = 4/n/pi for n odd and 0 otherwise.
// = 2*(2/(n*pi)) for n odd
b = (n & 1) ? 2 * piFactor : 0;
break;
case OscillatorType::SAWTOOTH:
// Sawtooth-shaped waveform with the first half ramping from zero to maximum and the
// second half from minimum to zero.
//
// b[n] = -2*(-1)^n/pi/n
// = (2/(n*pi))*(-1)^(n+1)
b = piFactor * ((n & 1) ? 1 : -1);
break;
case OscillatorType::TRIANGLE:
// Triangle-shaped waveform going from 0 at time 0 to 1 at time pi/2 and back to 0 at
// time pi.
//
// See http://mathworld.wolfram.com/FourierSeriesTriangleWave.html
//
// b[n] = 8*sin(pi*k/2)/(pi*k)^2
// = 8/pi^2/n^2*(-1)^((n-1)/2) for n odd and 0 otherwise
// = 2*(2/(n*pi))^2 * (-1)^((n-1)/2)
if (n & 1) {
b = 2 * (piFactor * piFactor) * ((((n - 1) >> 1) & 1) ? -1 : 1);
} else {
b = 0;
}
break;
default:
ASSERT_NOT_REACHED();
b = 0;
break;
}
realP[n] = 0;
imagP[n] = b;
}
createBandLimitedTables(realP, imagP, halfSize);
}
} // namespace lab
|
#include "LineEdit3D.h"
LineEdit3D::LineEdit3D(void)
{
only2D = false;
}
LineEdit3D::~LineEdit3D(void)
{
}
void LineEdit3D::set_points( std::vector<cml::vector3d> &points_ )
{
points = points_;
}
void LineEdit3D::set_cons_pos( int i, cml::vector3d &position )
{
cons_pos[i] = position;
}
double LineEdit3D::edit_xz()
{
double error;
LineEdit2D le2d;
std::vector<cml::vector2d> points_2d;
for (int i = 0; i < points.size(); ++i)
{
points_2d.push_back(cml::vector2d(points[i][2], points[i][0]));
}
le2d.set_points(points_2d);
for ( std::map<int, cml::vector3d>::iterator it=cons_pos.begin() ; it != cons_pos.end(); it++ )
{
int i = (*it).first;
cml::vector3d &p = (*it).second;
cml::vector2d p2d(p[2], p[0]);
le2d.set_cons_pos(i, p2d);
}
for ( std::map<int, cml::vector3d>::iterator it=cons_ori.begin() ; it != cons_ori.end(); it++ )
{
int i = (*it).first;
cml::vector3d &ori = (*it).second;
cml::vector2d p2d(ori[2], ori[0]);
le2d.set_cons_ori(i, p2d);
}
le2d.set_cons_stationary(cons_stationary);
error = le2d.edit();
points_2d = le2d.get_points();
for (int i = 0; i < points.size(); ++i)
{
points[i][0] = points_2d[i][1];
points[i][2] = points_2d[i][0];
}
return error;
}
#include <cassert>
int get_k(std::vector<double> &ls, double deformed_l)
{
for (int a = 0; a < ls.size() - 1; ++a)
{
if (ls[a] <= deformed_l && deformed_l < ls[a+1])
return a;
}
if (deformed_l < ls[0])
return 0;
if (ls[ls.size()-1] <= deformed_l)
return ls.size()-2;
assert(false);
}
double LineEdit3D::edit_ly()
{
double error;
std::vector<cml::vector3d> points_bar = points;
LineEdit2D le2d;
std::vector<double> ls;
ls.push_back(0.0);
for (int i = 1; i < points.size(); ++i)
{
double l_part = sqrt(pow(points[i][0] - points[i-1][0], 2) + pow(points[i][2] - points[i-1][2], 2));
ls.push_back(ls[i-1] + l_part);
}
std::vector<cml::vector2d> points_2d;
for (int i = 0; i < points.size(); ++i)
{
points_2d.push_back(cml::vector2d(ls[i], points[i][1]));
}
le2d.set_points(points_2d);
for ( std::map<int, cml::vector3d>::iterator it=cons_pos.begin() ; it != cons_pos.end(); it++ )
{
int i = (*it).first;
cml::vector3d &p = (*it).second;
cml::vector2d p2d(ls[i], p[1]);
le2d.set_cons_pos(i, p2d);
}
le2d.set_cons_stationary(cons_stationary);
error = le2d.edit();
points_2d = le2d.get_points();
for (int i = 0; i < points.size(); ++i)
{
double l = points_2d[i][0];
int k = get_k(ls, l);
double a = l - ls[k];
double b = ls[k+1] - l;
points[i][0] = (a * points_bar[k+1][0] + b * points_bar[k][0]) / (a + b);
points[i][2] = (a * points_bar[k+1][2] + b * points_bar[k][2]) / (a + b);
points[i][1] = points_2d[i][1];
}
return error;
}
double LineEdit3D::edit()
{
double error = 0.0;
error += edit_xz();
if (only2D == false)
error += edit_ly();
return error;
}
void LineEdit3D::cons_rigid( double cons_rigid_value )
{
throw std::exception("The method or operation is not implemented.");
}
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include <armnn/Exceptions.hpp>
#include <memory>
namespace armnn
{
namespace profiling
{
class Packet
{
public:
Packet()
: m_Header(0)
, m_Length(0)
, m_Data(nullptr)
{}
Packet(uint32_t header)
: m_Header(header)
, m_Length(0)
, m_Data(nullptr)
{
m_PacketId = ((header >> 16) & 1023);
m_PacketFamily = (header >> 26);
}
Packet(uint32_t header, uint32_t length, std::unique_ptr<unsigned char[]>& data)
: m_Header(header)
, m_Length(length)
, m_Data(std::move(data))
{
m_PacketId = ((header >> 16) & 1023);
m_PacketFamily = (header >> 26);
if (length == 0 && m_Data != nullptr)
{
throw armnn::InvalidArgumentException("Data should be null when length is zero");
}
}
Packet(Packet&& other)
: m_Header(other.m_Header)
, m_PacketFamily(other.m_PacketFamily)
, m_PacketId(other.m_PacketId)
, m_Length(other.m_Length)
, m_Data(std::move(other.m_Data))
{
other.m_Header = 0;
other.m_PacketFamily = 0;
other.m_PacketId = 0;
other.m_Length = 0;
}
~Packet() = default;
Packet(const Packet& other) = delete;
Packet& operator=(const Packet&) = delete;
Packet& operator=(Packet&&) = default;
uint32_t GetHeader() const { return m_Header; }
uint32_t GetPacketFamily() const { return m_PacketFamily; }
uint32_t GetPacketId() const { return m_PacketId; }
uint32_t GetPacketClass() const { return m_PacketId >> 3; }
uint32_t GetPacketType() const { return m_PacketId & 7; }
uint32_t GetLength() const { return m_Length; }
const unsigned char* const GetData() const { return m_Data.get(); }
bool IsEmpty() { return m_Header == 0 && m_Length == 0; }
private:
uint32_t m_Header;
uint32_t m_PacketFamily;
uint32_t m_PacketId;
uint32_t m_Length;
std::unique_ptr<unsigned char[]> m_Data;
};
} // namespace profiling
} // namespace armnn
|
#include <algorithm>
using namespace std;
/**
Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
*/
// NOTE(Wuxiang): The Difficulty is how to distinguish 4 cases in switch.
class Solution
{
public:
int minDepth(TreeNode *root)
{
if (root == nullptr)
{
return 0;
}
if (root->left != nullptr && root->right != nullptr)
{
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
else if (root->left == nullptr && root->right == nullptr)
{
return 1;
}
else if (root->left != nullptr)
{
return minDepth(root->left) + 1;
}
else
{
return minDepth(root->right) + 1;
}
}
};
|
#include "rtp/SRPacketHandler.h"
#include "./WebRtcConnection.h"
#include "lib/ClockUtils.h"
namespace erizo {
DEFINE_LOGGER(SRPacketHandler, "rtp.SRPacketHandler");
SRPacketHandler::SRPacketHandler() :
enabled_{true}, initialized_{false}, connection_(nullptr) {}
void SRPacketHandler::enable() {
enabled_ = true;
}
void SRPacketHandler::disable() {
enabled_ = false;
}
void SRPacketHandler::handleRtpPacket(std::shared_ptr<dataPacket> packet) {
RtpHeader *head = reinterpret_cast<RtpHeader*>(packet->data);
uint32_t ssrc = head->getSSRC();
auto sr_selected_info_iter = sr_info_map_.find(ssrc);
std::shared_ptr<SRInfo> selected_info;
if (sr_selected_info_iter == sr_info_map_.end()) {
ELOG_DEBUG("message: Inserting new SSRC in sr_info_map, ssrc: %u", ssrc);
sr_info_map_[ssrc] = std::make_shared<SRInfo>();
}
selected_info = sr_info_map_[ssrc];
selected_info->sent_packets++;
selected_info->sent_octets += (packet->length - head->getHeaderLength());
}
void SRPacketHandler::handleSR(std::shared_ptr<dataPacket> packet) {
RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data);
uint32_t ssrc = chead->getSSRC();
auto sr_selected_info_iter = sr_info_map_.find(ssrc);
if (sr_selected_info_iter == sr_info_map_.end()) {
ELOG_DEBUG("message: handleSR no info for this SSRC, ssrc: %u", ssrc);
return;
}
std::shared_ptr<SRInfo> selected_info = sr_selected_info_iter->second;
ELOG_DEBUG("message: Rewriting SR, ssrc: %u, octets_sent_before: %u, packets_sent_before: %u"
" octets_sent_after %u packets_sent_after: %u", ssrc, chead->getOctetsSent(), chead->getPacketsSent(),
selected_info->sent_octets, selected_info->sent_packets);
chead->setOctetsSent(selected_info->sent_octets);
chead->setPacketsSent(selected_info->sent_packets);
}
void SRPacketHandler::write(Context *ctx, std::shared_ptr<dataPacket> packet) {
if (initialized_ && enabled_) {
RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data);
if (!chead->isRtcp() && enabled_) {
handleRtpPacket(packet);
} else if (chead->packettype == RTCP_Sender_PT && enabled_) {
handleSR(packet);
}
}
ctx->fireWrite(std::move(packet));
}
void SRPacketHandler::read(Context *ctx, std::shared_ptr<dataPacket> packet) {
ctx->fireRead(std::move(packet));
}
void SRPacketHandler::notifyUpdate() {
if (initialized_) {
return;
}
auto pipeline = getContext()->getPipelineShared();
if (pipeline && !connection_) {
connection_ = pipeline->getService<WebRtcConnection>().get();
}
if (!connection_) {
return;
}
initialized_ = true;
}
} // namespace erizo
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2011-2015 Akira Takahashi
// Copyright (c) 2011-2015 Barend Gehrels, Amsterdam, the Netherlands.
// This file was modified by Oracle on 2015.
// Modifications copyright (c) 2015, Oracle and/or its affiliates.
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
// Use, modification and distribution is subject to 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_GEOMETRY_GEOMETRIES_ADAPTED_FUSION_HPP
#define BOOST_GEOMETRY_GEOMETRIES_ADAPTED_FUSION_HPP
#include <cstddef>
#include <boost/core/enable_if.hpp>
#include <boost/fusion/include/is_sequence.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/fusion/include/tag_of.hpp>
#include <boost/fusion/include/front.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/mpl.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/count_if.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/size.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/coordinate_system.hpp>
#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tags.hpp>
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry
{
namespace fusion_adapt_detail
{
template <class Sequence>
struct all_same :
geofeatures_boost::mpl::bool_<
geofeatures_boost::mpl::count_if<
Sequence,
geofeatures_boost::is_same<
typename geofeatures_boost::mpl::front<Sequence>::type,
geofeatures_boost::mpl::_
>
>::value == geofeatures_boost::mpl::size<Sequence>::value
>
{};
template <class Sequence>
struct is_coordinate_size : geofeatures_boost::mpl::bool_<
geofeatures_boost::fusion::result_of::size<Sequence>::value == 2 ||
geofeatures_boost::fusion::result_of::size<Sequence>::value == 3> {};
template<typename Sequence>
struct is_fusion_sequence
: geofeatures_boost::mpl::and_<geofeatures_boost::fusion::traits::is_sequence<Sequence>,
fusion_adapt_detail::is_coordinate_size<Sequence>,
fusion_adapt_detail::all_same<Sequence> >
{};
} // namespace fusion_adapt_detail
#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
namespace traits
{
// Boost Fusion Sequence, 2D or 3D
template <typename Sequence>
struct coordinate_type
<
Sequence,
typename geofeatures_boost::enable_if
<
fusion_adapt_detail::is_fusion_sequence<Sequence>
>::type
>
{
typedef typename geofeatures_boost::mpl::front<Sequence>::type type;
};
template <typename Sequence>
struct dimension
<
Sequence,
typename geofeatures_boost::enable_if
<
fusion_adapt_detail::is_fusion_sequence<Sequence>
>::type
> : geofeatures_boost::mpl::size<Sequence>
{};
template <typename Sequence, std::size_t Dimension>
struct access
<
Sequence,
Dimension,
typename geofeatures_boost::enable_if
<
fusion_adapt_detail::is_fusion_sequence<Sequence>
>::type
>
{
typedef typename coordinate_type<Sequence>::type ctype;
static inline ctype get(Sequence const& point)
{
return geofeatures_boost::fusion::at_c<Dimension>(point);
}
template <class CoordinateType>
static inline void set(Sequence& point, CoordinateType const& value)
{
geofeatures_boost::fusion::at_c<Dimension>(point) = value;
}
};
template <typename Sequence>
struct tag
<
Sequence,
typename geofeatures_boost::enable_if
<
fusion_adapt_detail::is_fusion_sequence<Sequence>
>::type
>
{
typedef point_tag type;
};
} // namespace traits
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS
}} // namespace geofeatures_boost::geometry
// Convenience registration macro to bind a Fusion sequence to a CS
#define BOOST_GEOMETRY_REGISTER_BOOST_FUSION_CS(CoordinateSystem) \
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace traits { \
template <typename Sequence> \
struct coordinate_system \
< \
Sequence, \
typename geofeatures_boost::enable_if \
< \
fusion_adapt_detail::is_fusion_sequence<Sequence> \
>::type \
> \
{ typedef CoordinateSystem type; }; \
}}}
#endif // BOOST_GEOMETRY_GEOMETRIES_ADAPTED_FUSION_HPP
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All 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.
*/
#include <tencentcloud/dayu/v20180709/model/CreateCCFrequencyRulesResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Dayu::V20180709::Model;
using namespace std;
CreateCCFrequencyRulesResponse::CreateCCFrequencyRulesResponse() :
m_cCFrequencyRuleIdHasBeenSet(false)
{
}
CoreInternalOutcome CreateCCFrequencyRulesResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("CCFrequencyRuleId") && !rsp["CCFrequencyRuleId"].IsNull())
{
if (!rsp["CCFrequencyRuleId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CCFrequencyRuleId` IsString=false incorrectly").SetRequestId(requestId));
}
m_cCFrequencyRuleId = string(rsp["CCFrequencyRuleId"].GetString());
m_cCFrequencyRuleIdHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string CreateCCFrequencyRulesResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_cCFrequencyRuleIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CCFrequencyRuleId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_cCFrequencyRuleId.c_str(), allocator).Move(), allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
string CreateCCFrequencyRulesResponse::GetCCFrequencyRuleId() const
{
return m_cCFrequencyRuleId;
}
bool CreateCCFrequencyRulesResponse::CCFrequencyRuleIdHasBeenSet() const
{
return m_cCFrequencyRuleIdHasBeenSet;
}
|
/********** tell emacs we use -*- c++ -*- style comments *******************
$Revision: 1.15 $ $Author: trey $ $Date: 2006/10/30 20:00:15 $
@file RTDP.cc
@brief Implementation of Barto, Bradke, and Singh's RTDP algorithm.
Copyright (c) 2006, Trey Smith. All 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.
***************************************************************************/
/**********************************************************************
This is my implementation of the RTDP algorithm, based on the paper
"Learning to Act Using Real-Time Dynamic Programming."
A. Barto, S. Bradke, and S. Singh.
Artificial Intelligence 72(1-2): 81-138. 1995.
Inevitably they could not include all the details of the algorithm in
their paper, so it is possible that my implementation differs from
theirs in important ways. They have not signed off on this
implementation: use at your own risk. (And please inform me if you
find any errors!)
-Trey Smith, Feb. 2006
**********************************************************************/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <queue>
#include "zmdpCommonDefs.h"
#include "zmdpCommonTime.h"
#include "MatrixUtils.h"
#include "Pomdp.h"
#include "RTDP.h"
using namespace std;
using namespace sla;
using namespace MatrixUtils;
namespace zmdp {
RTDP::RTDP(void)
{}
void RTDP::trialRecurse(MDPNode& cn, int depth)
{
// check for termination
if (cn.isTerminal) {
if (zmdpDebugLevelG >= 1) {
printf("trialRecurse: depth=%d ubVal=%g terminal node (terminating)\n",
depth, cn.ubVal);
}
return;
}
// cached Q values must be up to date for subsequent calls
int maxUBAction;
bounds->update(cn, &maxUBAction);
trackBackup(cn);
int simulatedOutcome = bounds->getSimulatedOutcome(cn, maxUBAction);
if (zmdpDebugLevelG >= 1) {
printf(" trialRecurse: depth=%d a=%d o=%d ubVal=%g\n",
depth, maxUBAction, simulatedOutcome, cn.ubVal);
printf(" trialRecurse: s=%s\n", sparseRep(cn.s).c_str());
}
// recurse to successor
trialRecurse(cn.getNextState(maxUBAction, simulatedOutcome), depth+1);
bounds->update(cn, NULL);
trackBackup(cn);
}
bool RTDP::doTrial(MDPNode& cn)
{
if (zmdpDebugLevelG >= 1) {
printf("-*- doTrial: trial %d\n", (numTrials+1));
}
trialRecurse(cn, 0);
numTrials++;
return false;
}
}; // namespace zmdp
/***************************************************************************
* REVISION HISTORY:
* $Log: RTDP.cc,v $
* Revision 1.15 2006/10/30 20:00:15 trey
* USE_DEBUG_PRINT replaced with a run-time config parameter "debugLevel"
*
* Revision 1.14 2006/10/19 19:31:26 trey
* added support for backup logging
*
* Revision 1.13 2006/04/28 17:57:41 trey
* changed to use apache license
*
* Revision 1.12 2006/04/07 19:42:42 trey
* removed initUpperBound argument to constructor
*
* Revision 1.11 2006/04/06 04:14:11 trey
* changed how bounds are initialized
*
* Revision 1.10 2006/04/03 21:39:24 trey
* updated to use IncrementalBounds
*
* Revision 1.9 2006/02/27 20:12:37 trey
* cleaned up meta-information in header
*
* Revision 1.8 2006/02/19 18:33:47 trey
* targetPrecision now stared as a field rather than passed around recursively
*
* Revision 1.7 2006/02/14 19:34:43 trey
* now use targetPrecision properly
*
* Revision 1.6 2006/02/13 20:20:33 trey
* refactored some common code from RTDP and LRTDP
*
* Revision 1.5 2006/02/13 19:08:49 trey
* moved numBackups tracking code for better flexibility
*
* Revision 1.4 2006/02/11 22:38:10 trey
* moved much of the RTDP implementation into RTDPCore, where it can be shared by many RTDP variants
*
* Revision 1.3 2006/02/10 20:14:33 trey
* standardized fields in bounds.plot
*
* Revision 1.2 2006/02/10 19:33:32 trey
* chooseAction() now relies on upper bound as it should (since the lower bound is not even calculated in vanilla RTDP!
*
* Revision 1.1 2006/02/09 21:59:04 trey
* initial check-in
*
*
***************************************************************************/
|
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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 "platform/testing/URLTestHelpers.h"
#include "platform/testing/UnitTestHelpers.h"
#include "public/platform/Platform.h"
#include "public/platform/WebString.h"
#include "public/platform/WebThread.h"
#include "public/platform/WebURL.h"
#include "public/platform/WebURLLoader.h"
#include "public/platform/WebURLLoaderClient.h"
#include "public/platform/WebURLLoaderMockFactory.h"
#include "public/platform/WebURLRequest.h"
#include "public/platform/WebURLResponse.h"
#include "public/web/WebCache.h"
#include "public/web/WebFrame.h"
#include "public/web/WebURLLoaderOptions.h"
#include "public/web/WebView.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "web/tests/FrameTestHelpers.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
using blink::URLTestHelpers::toKURL;
using blink::testing::runPendingTasks;
namespace blink {
class AssociatedURLLoaderTest : public ::testing::Test,
public WebURLLoaderClient {
public:
AssociatedURLLoaderTest()
: m_willFollowRedirect(false)
, m_didSendData(false)
, m_didReceiveResponse(false)
, m_didReceiveData(false)
, m_didReceiveCachedMetadata(false)
, m_didFinishLoading(false)
, m_didFail(false)
{
// Reuse one of the test files from WebFrameTest.
m_baseFilePath = testing::blinkRootDir();
m_baseFilePath.append("/Source/web/tests/data/");
m_frameFilePath = m_baseFilePath;
m_frameFilePath.append("iframes_test.html");
}
KURL RegisterMockedUrl(const std::string& urlRoot, const WTF::String& filename)
{
WebURLResponse response;
response.initialize();
response.setMIMEType("text/html");
WTF::String localPath = m_baseFilePath;
localPath.append(filename);
KURL url = toKURL(urlRoot + filename.utf8().data());
Platform::current()->getURLLoaderMockFactory()->registerURL(url, response, localPath);
return url;
}
void SetUp() override
{
m_helper.initialize();
std::string urlRoot = "http://www.test.com/";
KURL url = RegisterMockedUrl(urlRoot, "iframes_test.html");
const char* iframeSupportFiles[] = {
"invisible_iframe.html",
"visible_iframe.html",
"zero_sized_iframe.html",
};
for (size_t i = 0; i < WTF_ARRAY_LENGTH(iframeSupportFiles); ++i) {
RegisterMockedUrl(urlRoot, iframeSupportFiles[i]);
}
FrameTestHelpers::loadFrame(mainFrame(), url.getString().utf8().data());
Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
}
void TearDown() override
{
Platform::current()->getURLLoaderMockFactory()->unregisterAllURLs();
WebCache::clear();
}
void serveRequests()
{
Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
}
PassOwnPtr<WebURLLoader> createAssociatedURLLoader(const WebURLLoaderOptions options = WebURLLoaderOptions())
{
return adoptPtr(mainFrame()->createAssociatedURLLoader(options));
}
// WebURLLoaderClient implementation.
void willFollowRedirect(WebURLLoader* loader, WebURLRequest& newRequest, const WebURLResponse& redirectResponse) override
{
m_willFollowRedirect = true;
EXPECT_EQ(m_expectedLoader, loader);
EXPECT_EQ(m_expectedNewRequest.url(), newRequest.url());
// Check that CORS simple headers are transferred to the new request.
EXPECT_EQ(m_expectedNewRequest.httpHeaderField("accept"), newRequest.httpHeaderField("accept"));
EXPECT_EQ(m_expectedRedirectResponse.url(), redirectResponse.url());
EXPECT_EQ(m_expectedRedirectResponse.httpStatusCode(), redirectResponse.httpStatusCode());
EXPECT_EQ(m_expectedRedirectResponse.mimeType(), redirectResponse.mimeType());
}
void didSendData(WebURLLoader* loader, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) override
{
m_didSendData = true;
EXPECT_EQ(m_expectedLoader, loader);
}
void didReceiveResponse(WebURLLoader* loader, const WebURLResponse& response) override
{
m_didReceiveResponse = true;
m_actualResponse = WebURLResponse(response);
EXPECT_EQ(m_expectedLoader, loader);
EXPECT_EQ(m_expectedResponse.url(), response.url());
EXPECT_EQ(m_expectedResponse.httpStatusCode(), response.httpStatusCode());
}
void didDownloadData(WebURLLoader* loader, int dataLength, int encodedDataLength) override
{
m_didDownloadData = true;
EXPECT_EQ(m_expectedLoader, loader);
}
void didReceiveData(WebURLLoader* loader, const char* data, int dataLength, int encodedDataLength) override
{
m_didReceiveData = true;
EXPECT_EQ(m_expectedLoader, loader);
EXPECT_TRUE(data);
EXPECT_GT(dataLength, 0);
}
void didReceiveCachedMetadata(WebURLLoader* loader, const char* data, int dataLength) override
{
m_didReceiveCachedMetadata = true;
EXPECT_EQ(m_expectedLoader, loader);
}
void didFinishLoading(WebURLLoader* loader, double finishTime, int64_t encodedDataLength) override
{
m_didFinishLoading = true;
EXPECT_EQ(m_expectedLoader, loader);
}
void didFail(WebURLLoader* loader, const WebURLError& error) override
{
m_didFail = true;
EXPECT_EQ(m_expectedLoader, loader);
}
void CheckMethodFails(const char* unsafeMethod)
{
WebURLRequest request;
request.initialize();
request.setURL(toKURL("http://www.test.com/success.html"));
request.setHTTPMethod(WebString::fromUTF8(unsafeMethod));
WebURLLoaderOptions options;
options.untrustedHTTP = true;
CheckFails(request, options);
}
void CheckHeaderFails(const char* headerField)
{
CheckHeaderFails(headerField, "foo");
}
void CheckHeaderFails(const char* headerField, const char* headerValue)
{
WebURLRequest request;
request.initialize();
request.setURL(toKURL("http://www.test.com/success.html"));
if (equalIgnoringCase(WebString::fromUTF8(headerField), "referer"))
request.setHTTPReferrer(WebString::fromUTF8(headerValue), WebReferrerPolicyDefault);
else
request.setHTTPHeaderField(WebString::fromUTF8(headerField), WebString::fromUTF8(headerValue));
WebURLLoaderOptions options;
options.untrustedHTTP = true;
CheckFails(request, options);
}
void CheckFails(const WebURLRequest& request, WebURLLoaderOptions options = WebURLLoaderOptions())
{
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_didFail = false;
m_expectedLoader->loadAsynchronously(request, this);
// Failure should not be reported synchronously.
EXPECT_FALSE(m_didFail);
// Allow the loader to return the error.
runPendingTasks();
EXPECT_TRUE(m_didFail);
EXPECT_FALSE(m_didReceiveResponse);
}
bool CheckAccessControlHeaders(const char* headerName, bool exposed)
{
std::string id("http://www.other.com/CheckAccessControlExposeHeaders_");
id.append(headerName);
if (exposed)
id.append("-Exposed");
id.append(".html");
KURL url = toKURL(id);
WebURLRequest request;
request.initialize();
request.setURL(url);
WebString headerNameString(WebString::fromUTF8(headerName));
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
m_expectedResponse.addHTTPHeaderField("Access-Control-Allow-Origin", "*");
if (exposed)
m_expectedResponse.addHTTPHeaderField("access-control-expose-headers", headerNameString);
m_expectedResponse.addHTTPHeaderField(headerNameString, "foo");
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
EXPECT_TRUE(m_didReceiveResponse);
EXPECT_TRUE(m_didReceiveData);
EXPECT_TRUE(m_didFinishLoading);
return !m_actualResponse.httpHeaderField(headerNameString).isEmpty();
}
WebFrame* mainFrame() const { return m_helper.webView()->mainFrame(); }
protected:
String m_baseFilePath;
String m_frameFilePath;
FrameTestHelpers::WebViewHelper m_helper;
OwnPtr<WebURLLoader> m_expectedLoader;
WebURLResponse m_actualResponse;
WebURLResponse m_expectedResponse;
WebURLRequest m_expectedNewRequest;
WebURLResponse m_expectedRedirectResponse;
bool m_willFollowRedirect;
bool m_didSendData;
bool m_didReceiveResponse;
bool m_didDownloadData;
bool m_didReceiveData;
bool m_didReceiveCachedMetadata;
bool m_didFinishLoading;
bool m_didFail;
};
// Test a successful same-origin URL load.
TEST_F(AssociatedURLLoaderTest, SameOriginSuccess)
{
KURL url = toKURL("http://www.test.com/SameOriginSuccess.html");
WebURLRequest request;
request.initialize();
request.setURL(url);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedResponse, m_frameFilePath);
m_expectedLoader = createAssociatedURLLoader();
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
EXPECT_TRUE(m_didReceiveResponse);
EXPECT_TRUE(m_didReceiveData);
EXPECT_TRUE(m_didFinishLoading);
}
// Test that the same-origin restriction is the default.
TEST_F(AssociatedURLLoaderTest, SameOriginRestriction)
{
// This is cross-origin since the frame was loaded from www.test.com.
KURL url = toKURL("http://www.other.com/SameOriginRestriction.html");
WebURLRequest request;
request.initialize();
request.setURL(url);
CheckFails(request);
}
// Test a successful cross-origin load.
TEST_F(AssociatedURLLoaderTest, CrossOriginSuccess)
{
// This is cross-origin since the frame was loaded from www.test.com.
KURL url = toKURL("http://www.other.com/CrossOriginSuccess");
WebURLRequest request;
request.initialize();
request.setURL(url);
// No-CORS requests (CrossOriginRequestPolicyAllow) aren't allowed for the
// default context. So we set the context as Script here.
request.setRequestContext(WebURLRequest::RequestContextScript);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
EXPECT_TRUE(m_didReceiveResponse);
EXPECT_TRUE(m_didReceiveData);
EXPECT_TRUE(m_didFinishLoading);
}
// Test a successful cross-origin load using CORS.
TEST_F(AssociatedURLLoaderTest, CrossOriginWithAccessControlSuccess)
{
// This is cross-origin since the frame was loaded from www.test.com.
KURL url = toKURL("http://www.other.com/CrossOriginWithAccessControlSuccess.html");
WebURLRequest request;
request.initialize();
request.setURL(url);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
m_expectedResponse.addHTTPHeaderField("access-control-allow-origin", "*");
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
EXPECT_TRUE(m_didReceiveResponse);
EXPECT_TRUE(m_didReceiveData);
EXPECT_TRUE(m_didFinishLoading);
}
// Test an unsuccessful cross-origin load using CORS.
TEST_F(AssociatedURLLoaderTest, CrossOriginWithAccessControlFailure)
{
// This is cross-origin since the frame was loaded from www.test.com.
KURL url = toKURL("http://www.other.com/CrossOriginWithAccessControlFailure.html");
WebURLRequest request;
request.initialize();
request.setURL(url);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
m_expectedResponse.addHTTPHeaderField("access-control-allow-origin", "*");
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
// Send credentials. This will cause the CORS checks to fail, because credentials can't be
// sent to a server which returns the header "access-control-allow-origin" with "*" as its value.
options.allowCredentials = true;
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
// Failure should not be reported synchronously.
EXPECT_FALSE(m_didFail);
// The loader needs to receive the response, before doing the CORS check.
serveRequests();
EXPECT_TRUE(m_didFail);
EXPECT_FALSE(m_didReceiveResponse);
}
// Test an unsuccessful cross-origin load using CORS.
TEST_F(AssociatedURLLoaderTest, CrossOriginWithAccessControlFailureBadStatusCode)
{
// This is cross-origin since the frame was loaded from www.test.com.
KURL url = toKURL("http://www.other.com/CrossOriginWithAccessControlFailure.html");
WebURLRequest request;
request.initialize();
request.setURL(url);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(0);
m_expectedResponse.addHTTPHeaderField("access-control-allow-origin", "*");
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
// Failure should not be reported synchronously.
EXPECT_FALSE(m_didFail);
// The loader needs to receive the response, before doing the CORS check.
serveRequests();
EXPECT_TRUE(m_didFail);
EXPECT_FALSE(m_didReceiveResponse);
}
// Test a same-origin URL redirect and load.
TEST_F(AssociatedURLLoaderTest, RedirectSuccess)
{
KURL url = toKURL("http://www.test.com/RedirectSuccess.html");
char redirect[] = "http://www.test.com/RedirectSuccess2.html"; // Same-origin
KURL redirectURL = toKURL(redirect);
WebURLRequest request;
request.initialize();
request.setURL(url);
m_expectedRedirectResponse = WebURLResponse();
m_expectedRedirectResponse.initialize();
m_expectedRedirectResponse.setMIMEType("text/html");
m_expectedRedirectResponse.setHTTPStatusCode(301);
m_expectedRedirectResponse.setHTTPHeaderField("Location", redirect);
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedRedirectResponse, m_frameFilePath);
m_expectedNewRequest = WebURLRequest();
m_expectedNewRequest.initialize();
m_expectedNewRequest.setURL(redirectURL);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
Platform::current()->getURLLoaderMockFactory()->registerURL(redirectURL, m_expectedResponse, m_frameFilePath);
m_expectedLoader = createAssociatedURLLoader();
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
EXPECT_TRUE(m_willFollowRedirect);
EXPECT_TRUE(m_didReceiveResponse);
EXPECT_TRUE(m_didReceiveData);
EXPECT_TRUE(m_didFinishLoading);
}
// Test a cross-origin URL redirect without Access Control set.
TEST_F(AssociatedURLLoaderTest, RedirectCrossOriginFailure)
{
KURL url = toKURL("http://www.test.com/RedirectCrossOriginFailure.html");
char redirect[] = "http://www.other.com/RedirectCrossOriginFailure.html"; // Cross-origin
KURL redirectURL = toKURL(redirect);
WebURLRequest request;
request.initialize();
request.setURL(url);
m_expectedRedirectResponse = WebURLResponse();
m_expectedRedirectResponse.initialize();
m_expectedRedirectResponse.setMIMEType("text/html");
m_expectedRedirectResponse.setHTTPStatusCode(301);
m_expectedRedirectResponse.setHTTPHeaderField("Location", redirect);
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedRedirectResponse, m_frameFilePath);
m_expectedNewRequest = WebURLRequest();
m_expectedNewRequest.initialize();
m_expectedNewRequest.setURL(redirectURL);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
Platform::current()->getURLLoaderMockFactory()->registerURL(redirectURL, m_expectedResponse, m_frameFilePath);
m_expectedLoader = createAssociatedURLLoader();
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
EXPECT_FALSE(m_willFollowRedirect);
EXPECT_FALSE(m_didReceiveResponse);
EXPECT_FALSE(m_didReceiveData);
EXPECT_FALSE(m_didFinishLoading);
}
// Test that a cross origin redirect response without CORS headers fails.
TEST_F(AssociatedURLLoaderTest, RedirectCrossOriginWithAccessControlFailure)
{
KURL url = toKURL("http://www.test.com/RedirectCrossOriginWithAccessControlFailure.html");
char redirect[] = "http://www.other.com/RedirectCrossOriginWithAccessControlFailure.html"; // Cross-origin
KURL redirectURL = toKURL(redirect);
WebURLRequest request;
request.initialize();
request.setURL(url);
m_expectedRedirectResponse = WebURLResponse();
m_expectedRedirectResponse.initialize();
m_expectedRedirectResponse.setMIMEType("text/html");
m_expectedRedirectResponse.setHTTPStatusCode(301);
m_expectedRedirectResponse.setHTTPHeaderField("Location", redirect);
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedRedirectResponse, m_frameFilePath);
m_expectedNewRequest = WebURLRequest();
m_expectedNewRequest.initialize();
m_expectedNewRequest.setURL(redirectURL);
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
Platform::current()->getURLLoaderMockFactory()->registerURL(redirectURL, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
// We should get a notification about access control check failure.
EXPECT_FALSE(m_willFollowRedirect);
EXPECT_FALSE(m_didReceiveResponse);
EXPECT_FALSE(m_didReceiveData);
EXPECT_TRUE(m_didFail);
}
// Test that a cross origin redirect response with CORS headers that allow the requesting origin succeeds.
TEST_F(AssociatedURLLoaderTest, RedirectCrossOriginWithAccessControlSuccess)
{
KURL url = toKURL("http://www.test.com/RedirectCrossOriginWithAccessControlSuccess.html");
char redirect[] = "http://www.other.com/RedirectCrossOriginWithAccessControlSuccess.html"; // Cross-origin
KURL redirectURL = toKURL(redirect);
WebURLRequest request;
request.initialize();
request.setURL(url);
// Add a CORS simple header.
request.setHTTPHeaderField("accept", "application/json");
// Create a redirect response that allows the redirect to pass the access control checks.
m_expectedRedirectResponse = WebURLResponse();
m_expectedRedirectResponse.initialize();
m_expectedRedirectResponse.setMIMEType("text/html");
m_expectedRedirectResponse.setHTTPStatusCode(301);
m_expectedRedirectResponse.setHTTPHeaderField("Location", redirect);
m_expectedRedirectResponse.addHTTPHeaderField("access-control-allow-origin", "*");
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedRedirectResponse, m_frameFilePath);
m_expectedNewRequest = WebURLRequest();
m_expectedNewRequest.initialize();
m_expectedNewRequest.setURL(redirectURL);
m_expectedNewRequest.setHTTPHeaderField("accept", "application/json");
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
m_expectedResponse.addHTTPHeaderField("access-control-allow-origin", "*");
Platform::current()->getURLLoaderMockFactory()->registerURL(redirectURL, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
// We should not receive a notification for the redirect.
EXPECT_FALSE(m_willFollowRedirect);
EXPECT_TRUE(m_didReceiveResponse);
EXPECT_TRUE(m_didReceiveData);
EXPECT_TRUE(m_didFinishLoading);
}
// Test that untrusted loads can't use a forbidden method.
TEST_F(AssociatedURLLoaderTest, UntrustedCheckMethods)
{
// Check non-token method fails.
CheckMethodFails("GET()");
CheckMethodFails("POST\x0d\x0ax-csrf-token:\x20test1234");
// Forbidden methods should fail regardless of casing.
CheckMethodFails("CoNneCt");
CheckMethodFails("TrAcK");
CheckMethodFails("TrAcE");
}
// This test is flaky on Windows and Android. See <http://crbug.com/471645>.
#if OS(WIN) || OS(ANDROID)
#define MAYBE_UntrustedCheckHeaders DISABLED_UntrustedCheckHeaders
#else
#define MAYBE_UntrustedCheckHeaders UntrustedCheckHeaders
#endif
// Test that untrusted loads can't use a forbidden header field.
TEST_F(AssociatedURLLoaderTest, MAYBE_UntrustedCheckHeaders)
{
// Check non-token header fails.
CheckHeaderFails("foo()");
// Check forbidden headers fail.
CheckHeaderFails("accept-charset");
CheckHeaderFails("accept-encoding");
CheckHeaderFails("connection");
CheckHeaderFails("content-length");
CheckHeaderFails("cookie");
CheckHeaderFails("cookie2");
CheckHeaderFails("date");
CheckHeaderFails("dnt");
CheckHeaderFails("expect");
CheckHeaderFails("host");
CheckHeaderFails("keep-alive");
CheckHeaderFails("origin");
CheckHeaderFails("referer", "http://example.com/");
CheckHeaderFails("te");
CheckHeaderFails("trailer");
CheckHeaderFails("transfer-encoding");
CheckHeaderFails("upgrade");
CheckHeaderFails("user-agent");
CheckHeaderFails("via");
CheckHeaderFails("proxy-");
CheckHeaderFails("proxy-foo");
CheckHeaderFails("sec-");
CheckHeaderFails("sec-foo");
// Check that validation is case-insensitive.
CheckHeaderFails("AcCePt-ChArSeT");
CheckHeaderFails("ProXy-FoO");
// Check invalid header values.
CheckHeaderFails("foo", "bar\x0d\x0ax-csrf-token:\x20test1234");
}
// Test that the loader filters response headers according to the CORS standard.
TEST_F(AssociatedURLLoaderTest, CrossOriginHeaderWhitelisting)
{
// Test that whitelisted headers are returned without exposing them.
EXPECT_TRUE(CheckAccessControlHeaders("cache-control", false));
EXPECT_TRUE(CheckAccessControlHeaders("content-language", false));
EXPECT_TRUE(CheckAccessControlHeaders("content-type", false));
EXPECT_TRUE(CheckAccessControlHeaders("expires", false));
EXPECT_TRUE(CheckAccessControlHeaders("last-modified", false));
EXPECT_TRUE(CheckAccessControlHeaders("pragma", false));
// Test that non-whitelisted headers aren't returned.
EXPECT_FALSE(CheckAccessControlHeaders("non-whitelisted", false));
// Test that Set-Cookie headers aren't returned.
EXPECT_FALSE(CheckAccessControlHeaders("Set-Cookie", false));
EXPECT_FALSE(CheckAccessControlHeaders("Set-Cookie2", false));
// Test that exposed headers that aren't whitelisted are returned.
EXPECT_TRUE(CheckAccessControlHeaders("non-whitelisted", true));
// Test that Set-Cookie headers aren't returned, even if exposed.
EXPECT_FALSE(CheckAccessControlHeaders("Set-Cookie", true));
}
// Test that the loader can allow non-whitelisted response headers for trusted CORS loads.
TEST_F(AssociatedURLLoaderTest, CrossOriginHeaderAllowResponseHeaders)
{
WebURLRequest request;
request.initialize();
KURL url = toKURL("http://www.other.com/CrossOriginHeaderAllowResponseHeaders.html");
request.setURL(url);
WebString headerNameString(WebString::fromUTF8("non-whitelisted"));
m_expectedResponse = WebURLResponse();
m_expectedResponse.initialize();
m_expectedResponse.setMIMEType("text/html");
m_expectedResponse.setHTTPStatusCode(200);
m_expectedResponse.addHTTPHeaderField("Access-Control-Allow-Origin", "*");
m_expectedResponse.addHTTPHeaderField(headerNameString, "foo");
Platform::current()->getURLLoaderMockFactory()->registerURL(url, m_expectedResponse, m_frameFilePath);
WebURLLoaderOptions options;
options.exposeAllResponseHeaders = true; // This turns off response whitelisting.
options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
m_expectedLoader = createAssociatedURLLoader(options);
EXPECT_TRUE(m_expectedLoader);
m_expectedLoader->loadAsynchronously(request, this);
serveRequests();
EXPECT_TRUE(m_didReceiveResponse);
EXPECT_TRUE(m_didReceiveData);
EXPECT_TRUE(m_didFinishLoading);
EXPECT_FALSE(m_actualResponse.httpHeaderField(headerNameString).isEmpty());
}
} // namespace blink
|
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdio.h>
#include <algorithm>
#include <string>
#include "db/db_test_util.h"
#include "port/stack_trace.h"
#include "rocksdb/listener.h"
#include "rocksdb/options.h"
#include "rocksdb/perf_context.h"
#include "rocksdb/perf_level.h"
#include "rocksdb/table.h"
#include "util/random.h"
#include "util/string_util.h"
namespace ROCKSDB_NAMESPACE {
class DBPropertiesTest : public DBTestBase {
public:
DBPropertiesTest()
: DBTestBase("/db_properties_test", /*env_do_fsync=*/false) {}
};
#ifndef ROCKSDB_LITE
TEST_F(DBPropertiesTest, Empty) {
do {
Options options;
options.env = env_;
options.write_buffer_size = 100000; // Small write buffer
options.allow_concurrent_memtable_write = false;
options = CurrentOptions(options);
CreateAndReopenWithCF({"pikachu"}, options);
std::string num;
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &num));
ASSERT_EQ("0", num);
ASSERT_OK(Put(1, "foo", "v1"));
ASSERT_EQ("v1", Get(1, "foo"));
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &num));
ASSERT_EQ("1", num);
// Block sync calls
env_->delay_sstable_sync_.store(true, std::memory_order_release);
ASSERT_OK(Put(1, "k1", std::string(100000, 'x'))); // Fill memtable
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &num));
ASSERT_EQ("2", num);
ASSERT_OK(Put(1, "k2", std::string(100000, 'y'))); // Trigger compaction
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &num));
ASSERT_EQ("1", num);
ASSERT_EQ("v1", Get(1, "foo"));
// Release sync calls
env_->delay_sstable_sync_.store(false, std::memory_order_release);
ASSERT_OK(db_->DisableFileDeletions());
ASSERT_TRUE(
dbfull()->GetProperty("rocksdb.is-file-deletions-enabled", &num));
ASSERT_EQ("0", num);
ASSERT_OK(db_->DisableFileDeletions());
ASSERT_TRUE(
dbfull()->GetProperty("rocksdb.is-file-deletions-enabled", &num));
ASSERT_EQ("0", num);
ASSERT_OK(db_->DisableFileDeletions());
ASSERT_TRUE(
dbfull()->GetProperty("rocksdb.is-file-deletions-enabled", &num));
ASSERT_EQ("0", num);
ASSERT_OK(db_->EnableFileDeletions(false));
ASSERT_TRUE(
dbfull()->GetProperty("rocksdb.is-file-deletions-enabled", &num));
ASSERT_EQ("0", num);
ASSERT_OK(db_->EnableFileDeletions());
ASSERT_TRUE(
dbfull()->GetProperty("rocksdb.is-file-deletions-enabled", &num));
ASSERT_EQ("1", num);
} while (ChangeOptions());
}
TEST_F(DBPropertiesTest, CurrentVersionNumber) {
uint64_t v1, v2, v3;
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.current-super-version-number", &v1));
ASSERT_OK(Put("12345678", ""));
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.current-super-version-number", &v2));
ASSERT_OK(Flush());
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.current-super-version-number", &v3));
ASSERT_EQ(v1, v2);
ASSERT_GT(v3, v2);
}
TEST_F(DBPropertiesTest, GetAggregatedIntPropertyTest) {
const int kKeySize = 100;
const int kValueSize = 500;
const int kKeyNum = 100;
Options options;
options.env = env_;
options.create_if_missing = true;
options.write_buffer_size = (kKeySize + kValueSize) * kKeyNum / 10;
// Make them never flush
options.min_write_buffer_number_to_merge = 1000;
options.max_write_buffer_number = 1000;
options = CurrentOptions(options);
CreateAndReopenWithCF({"one", "two", "three", "four"}, options);
Random rnd(301);
for (auto* handle : handles_) {
for (int i = 0; i < kKeyNum; ++i) {
ASSERT_OK(db_->Put(WriteOptions(), handle, rnd.RandomString(kKeySize),
rnd.RandomString(kValueSize)));
}
}
uint64_t manual_sum = 0;
uint64_t api_sum = 0;
uint64_t value = 0;
for (auto* handle : handles_) {
ASSERT_TRUE(
db_->GetIntProperty(handle, DB::Properties::kSizeAllMemTables, &value));
manual_sum += value;
}
ASSERT_TRUE(db_->GetAggregatedIntProperty(DB::Properties::kSizeAllMemTables,
&api_sum));
ASSERT_GT(manual_sum, 0);
ASSERT_EQ(manual_sum, api_sum);
ASSERT_FALSE(db_->GetAggregatedIntProperty(DB::Properties::kDBStats, &value));
uint64_t before_flush_trm;
uint64_t after_flush_trm;
for (auto* handle : handles_) {
ASSERT_TRUE(db_->GetAggregatedIntProperty(
DB::Properties::kEstimateTableReadersMem, &before_flush_trm));
// Issue flush and expect larger memory usage of table readers.
ASSERT_OK(db_->Flush(FlushOptions(), handle));
ASSERT_TRUE(db_->GetAggregatedIntProperty(
DB::Properties::kEstimateTableReadersMem, &after_flush_trm));
ASSERT_GT(after_flush_trm, before_flush_trm);
}
}
namespace {
void ResetTableProperties(TableProperties* tp) {
tp->data_size = 0;
tp->index_size = 0;
tp->filter_size = 0;
tp->raw_key_size = 0;
tp->raw_value_size = 0;
tp->num_data_blocks = 0;
tp->num_entries = 0;
tp->num_deletions = 0;
tp->num_merge_operands = 0;
tp->num_range_deletions = 0;
}
void ParseTablePropertiesString(std::string tp_string, TableProperties* tp) {
double dummy_double;
std::replace(tp_string.begin(), tp_string.end(), ';', ' ');
std::replace(tp_string.begin(), tp_string.end(), '=', ' ');
ResetTableProperties(tp);
sscanf(tp_string.c_str(),
"# data blocks %" SCNu64 " # entries %" SCNu64 " # deletions %" SCNu64
" # merge operands %" SCNu64 " # range deletions %" SCNu64
" raw key size %" SCNu64
" raw average key size %lf "
" raw value size %" SCNu64
" raw average value size %lf "
" data block size %" SCNu64 " index block size (user-key? %" SCNu64
", delta-value? %" SCNu64 ") %" SCNu64 " filter block size %" SCNu64,
&tp->num_data_blocks, &tp->num_entries, &tp->num_deletions,
&tp->num_merge_operands, &tp->num_range_deletions, &tp->raw_key_size,
&dummy_double, &tp->raw_value_size, &dummy_double, &tp->data_size,
&tp->index_key_is_user_key, &tp->index_value_is_delta_encoded,
&tp->index_size, &tp->filter_size);
}
void VerifySimilar(uint64_t a, uint64_t b, double bias) {
ASSERT_EQ(a == 0U, b == 0U);
if (a == 0) {
return;
}
double dbl_a = static_cast<double>(a);
double dbl_b = static_cast<double>(b);
if (dbl_a > dbl_b) {
ASSERT_LT(static_cast<double>(dbl_a - dbl_b) / (dbl_a + dbl_b), bias);
} else {
ASSERT_LT(static_cast<double>(dbl_b - dbl_a) / (dbl_a + dbl_b), bias);
}
}
void VerifyTableProperties(
const TableProperties& base_tp, const TableProperties& new_tp,
double filter_size_bias = CACHE_LINE_SIZE >= 256 ? 0.15 : 0.1,
double index_size_bias = 0.1, double data_size_bias = 0.1,
double num_data_blocks_bias = 0.05) {
VerifySimilar(base_tp.data_size, new_tp.data_size, data_size_bias);
VerifySimilar(base_tp.index_size, new_tp.index_size, index_size_bias);
VerifySimilar(base_tp.filter_size, new_tp.filter_size, filter_size_bias);
VerifySimilar(base_tp.num_data_blocks, new_tp.num_data_blocks,
num_data_blocks_bias);
ASSERT_EQ(base_tp.raw_key_size, new_tp.raw_key_size);
ASSERT_EQ(base_tp.raw_value_size, new_tp.raw_value_size);
ASSERT_EQ(base_tp.num_entries, new_tp.num_entries);
ASSERT_EQ(base_tp.num_deletions, new_tp.num_deletions);
ASSERT_EQ(base_tp.num_range_deletions, new_tp.num_range_deletions);
// Merge operands may become Puts, so we only have an upper bound the exact
// number of merge operands.
ASSERT_GE(base_tp.num_merge_operands, new_tp.num_merge_operands);
}
void GetExpectedTableProperties(
TableProperties* expected_tp, const int kKeySize, const int kValueSize,
const int kPutsPerTable, const int kDeletionsPerTable,
const int kMergeOperandsPerTable, const int kRangeDeletionsPerTable,
const int kTableCount, const int kBloomBitsPerKey, const size_t kBlockSize,
const bool index_key_is_user_key, const bool value_delta_encoding) {
const int kKeysPerTable =
kPutsPerTable + kDeletionsPerTable + kMergeOperandsPerTable;
const int kPutCount = kTableCount * kPutsPerTable;
const int kDeletionCount = kTableCount * kDeletionsPerTable;
const int kMergeCount = kTableCount * kMergeOperandsPerTable;
const int kRangeDeletionCount = kTableCount * kRangeDeletionsPerTable;
const int kKeyCount = kPutCount + kDeletionCount + kMergeCount + kRangeDeletionCount;
const int kAvgSuccessorSize = kKeySize / 5;
const int kEncodingSavePerKey = kKeySize / 4;
expected_tp->raw_key_size = kKeyCount * (kKeySize + 8);
expected_tp->raw_value_size =
(kPutCount + kMergeCount + kRangeDeletionCount) * kValueSize;
expected_tp->num_entries = kKeyCount;
expected_tp->num_deletions = kDeletionCount + kRangeDeletionCount;
expected_tp->num_merge_operands = kMergeCount;
expected_tp->num_range_deletions = kRangeDeletionCount;
expected_tp->num_data_blocks =
kTableCount * (kKeysPerTable * (kKeySize - kEncodingSavePerKey + kValueSize)) /
kBlockSize;
expected_tp->data_size =
kTableCount * (kKeysPerTable * (kKeySize + 8 + kValueSize));
expected_tp->index_size =
expected_tp->num_data_blocks *
(kAvgSuccessorSize + (index_key_is_user_key ? 0 : 8) -
// discount 1 byte as value size is not encoded in value delta encoding
(value_delta_encoding ? 1 : 0));
expected_tp->filter_size =
kTableCount * ((kKeysPerTable * kBloomBitsPerKey + 7) / 8 +
/*average-ish overhead*/ CACHE_LINE_SIZE / 2);
}
} // anonymous namespace
TEST_F(DBPropertiesTest, ValidatePropertyInfo) {
for (const auto& ppt_name_and_info : InternalStats::ppt_name_to_info) {
// If C++ gets a std::string_literal, this would be better to check at
// compile-time using static_assert.
ASSERT_TRUE(ppt_name_and_info.first.empty() ||
!isdigit(ppt_name_and_info.first.back()));
int count = 0;
count += (ppt_name_and_info.second.handle_string == nullptr) ? 0 : 1;
count += (ppt_name_and_info.second.handle_int == nullptr) ? 0 : 1;
count += (ppt_name_and_info.second.handle_string_dbimpl == nullptr) ? 0 : 1;
ASSERT_TRUE(count == 1);
}
}
TEST_F(DBPropertiesTest, ValidateSampleNumber) {
// When "max_open_files" is -1, we read all the files for
// "rocksdb.estimate-num-keys" computation, which is the ground truth.
// Otherwise, we sample 20 newest files to make an estimation.
// Formula: lastest_20_files_active_key_ratio * total_files
Options options = CurrentOptions();
options.disable_auto_compactions = true;
options.level0_stop_writes_trigger = 1000;
DestroyAndReopen(options);
int key = 0;
for (int files = 20; files >= 10; files -= 10) {
for (int i = 0; i < files; i++) {
int rows = files / 10;
for (int j = 0; j < rows; j++) {
ASSERT_OK(db_->Put(WriteOptions(), std::to_string(++key), "foo"));
}
ASSERT_OK(db_->Flush(FlushOptions()));
}
}
std::string num;
Reopen(options);
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.estimate-num-keys", &num));
ASSERT_EQ("45", num);
options.max_open_files = -1;
Reopen(options);
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.estimate-num-keys", &num));
ASSERT_EQ("50", num);
}
TEST_F(DBPropertiesTest, AggregatedTableProperties) {
for (int kTableCount = 40; kTableCount <= 100; kTableCount += 30) {
const int kDeletionsPerTable = 5;
const int kMergeOperandsPerTable = 15;
const int kRangeDeletionsPerTable = 5;
const int kPutsPerTable = 100;
const int kKeySize = 80;
const int kValueSize = 200;
const int kBloomBitsPerKey = 20;
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 8;
options.compression = kNoCompression;
options.create_if_missing = true;
options.preserve_deletes = true;
options.merge_operator.reset(new TestPutOperator());
BlockBasedTableOptions table_options;
table_options.filter_policy.reset(
NewBloomFilterPolicy(kBloomBitsPerKey, false));
table_options.block_size = 1024;
options.table_factory.reset(new BlockBasedTableFactory(table_options));
DestroyAndReopen(options);
// Hold open a snapshot to prevent range tombstones from being compacted
// away.
ManagedSnapshot snapshot(db_);
Random rnd(5632);
for (int table = 1; table <= kTableCount; ++table) {
for (int i = 0; i < kPutsPerTable; ++i) {
ASSERT_OK(db_->Put(WriteOptions(), rnd.RandomString(kKeySize),
rnd.RandomString(kValueSize)));
}
for (int i = 0; i < kDeletionsPerTable; i++) {
ASSERT_OK(db_->Delete(WriteOptions(), rnd.RandomString(kKeySize)));
}
for (int i = 0; i < kMergeOperandsPerTable; i++) {
ASSERT_OK(db_->Merge(WriteOptions(), rnd.RandomString(kKeySize),
rnd.RandomString(kValueSize)));
}
for (int i = 0; i < kRangeDeletionsPerTable; i++) {
std::string start = rnd.RandomString(kKeySize);
std::string end = start;
end.resize(kValueSize);
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(),
start, end));
}
ASSERT_OK(db_->Flush(FlushOptions()));
}
std::string property;
db_->GetProperty(DB::Properties::kAggregatedTableProperties, &property);
TableProperties output_tp;
ParseTablePropertiesString(property, &output_tp);
bool index_key_is_user_key = output_tp.index_key_is_user_key > 0;
bool value_is_delta_encoded = output_tp.index_value_is_delta_encoded > 0;
TableProperties expected_tp;
GetExpectedTableProperties(
&expected_tp, kKeySize, kValueSize, kPutsPerTable, kDeletionsPerTable,
kMergeOperandsPerTable, kRangeDeletionsPerTable, kTableCount,
kBloomBitsPerKey, table_options.block_size, index_key_is_user_key,
value_is_delta_encoded);
VerifyTableProperties(expected_tp, output_tp);
}
}
TEST_F(DBPropertiesTest, ReadLatencyHistogramByLevel) {
Options options = CurrentOptions();
options.write_buffer_size = 110 << 10;
options.level0_file_num_compaction_trigger = 6;
options.num_levels = 4;
options.compression = kNoCompression;
options.max_bytes_for_level_base = 4500 << 10;
options.target_file_size_base = 98 << 10;
options.max_write_buffer_number = 2;
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
options.max_open_files = 11; // Make sure no proloading of table readers
// RocksDB sanitize max open files to at least 20. Modify it back.
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
int* max_open_files = static_cast<int*>(arg);
*max_open_files = 11;
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
BlockBasedTableOptions table_options;
table_options.no_block_cache = true;
CreateAndReopenWithCF({"pikachu"}, options);
int key_index = 0;
Random rnd(301);
for (int num = 0; num < 8; num++) {
ASSERT_OK(Put("foo", "bar"));
GenerateNewFile(&rnd, &key_index);
ASSERT_OK(dbfull()->TEST_WaitForCompact());
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
std::string prop;
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.dbstats", &prop));
// Get() after flushes, See latency histogram tracked.
for (int key = 0; key < key_index; key++) {
Get(Key(key));
}
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.cfstats", &prop));
ASSERT_NE(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_NE(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
// Reopen and issue Get(). See thee latency tracked
ReopenWithColumnFamilies({"default", "pikachu"}, options);
ASSERT_OK(dbfull()->TEST_WaitForCompact());
for (int key = 0; key < key_index; key++) {
Get(Key(key));
}
// Test for getting immutable_db_options_.statistics
ASSERT_TRUE(dbfull()->GetProperty(dbfull()->DefaultColumnFamily(),
"rocksdb.options-statistics", &prop));
ASSERT_NE(std::string::npos, prop.find("rocksdb.block.cache.miss"));
ASSERT_EQ(std::string::npos, prop.find("rocksdb.db.f.micros"));
ASSERT_TRUE(dbfull()->GetProperty(dbfull()->DefaultColumnFamily(),
"rocksdb.cf-file-histogram", &prop));
ASSERT_NE(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_NE(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
// Reopen and issue iterating. See thee latency tracked
ReopenWithColumnFamilies({"default", "pikachu"}, options);
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.cf-file-histogram", &prop));
ASSERT_EQ(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
{
std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
for (iter->Seek(Key(0)); iter->Valid(); iter->Next()) {
}
ASSERT_OK(iter->status());
}
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.cf-file-histogram", &prop));
ASSERT_NE(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_NE(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
// CF 1 should show no histogram.
ASSERT_TRUE(
dbfull()->GetProperty(handles_[1], "rocksdb.cf-file-histogram", &prop));
ASSERT_EQ(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
// put something and read it back , CF 1 should show histogram.
ASSERT_OK(Put(1, "foo", "bar"));
ASSERT_OK(Flush(1));
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_EQ("bar", Get(1, "foo"));
ASSERT_TRUE(
dbfull()->GetProperty(handles_[1], "rocksdb.cf-file-histogram", &prop));
ASSERT_NE(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
// options.max_open_files preloads table readers.
options.max_open_files = -1;
ReopenWithColumnFamilies({"default", "pikachu"}, options);
ASSERT_TRUE(dbfull()->GetProperty(dbfull()->DefaultColumnFamily(),
"rocksdb.cf-file-histogram", &prop));
ASSERT_NE(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_NE(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
for (int key = 0; key < key_index; key++) {
Get(Key(key));
}
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.cfstats", &prop));
ASSERT_NE(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_NE(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
// Clear internal stats
ASSERT_OK(dbfull()->ResetStats());
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.cfstats", &prop));
ASSERT_EQ(std::string::npos, prop.find("** Level 0 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 1 read latency histogram"));
ASSERT_EQ(std::string::npos, prop.find("** Level 2 read latency histogram"));
}
TEST_F(DBPropertiesTest, AggregatedTablePropertiesAtLevel) {
const int kTableCount = 100;
const int kDeletionsPerTable = 2;
const int kMergeOperandsPerTable = 2;
const int kRangeDeletionsPerTable = 2;
const int kPutsPerTable = 10;
const int kKeySize = 50;
const int kValueSize = 400;
const int kMaxLevel = 7;
const int kBloomBitsPerKey = 20;
Random rnd(301);
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 8;
options.compression = kNoCompression;
options.create_if_missing = true;
options.level0_file_num_compaction_trigger = 2;
options.target_file_size_base = 8192;
options.max_bytes_for_level_base = 10000;
options.max_bytes_for_level_multiplier = 2;
// This ensures there no compaction happening when we call GetProperty().
options.disable_auto_compactions = true;
options.preserve_deletes = true;
options.merge_operator.reset(new TestPutOperator());
BlockBasedTableOptions table_options;
table_options.filter_policy.reset(
NewBloomFilterPolicy(kBloomBitsPerKey, false));
table_options.block_size = 1024;
options.table_factory.reset(new BlockBasedTableFactory(table_options));
DestroyAndReopen(options);
// Hold open a snapshot to prevent range tombstones from being compacted away.
ManagedSnapshot snapshot(db_);
std::string level_tp_strings[kMaxLevel];
std::string tp_string;
TableProperties level_tps[kMaxLevel];
TableProperties tp, sum_tp, expected_tp;
for (int table = 1; table <= kTableCount; ++table) {
for (int i = 0; i < kPutsPerTable; ++i) {
ASSERT_OK(db_->Put(WriteOptions(), rnd.RandomString(kKeySize),
rnd.RandomString(kValueSize)));
}
for (int i = 0; i < kDeletionsPerTable; i++) {
ASSERT_OK(db_->Delete(WriteOptions(), rnd.RandomString(kKeySize)));
}
for (int i = 0; i < kMergeOperandsPerTable; i++) {
ASSERT_OK(db_->Merge(WriteOptions(), rnd.RandomString(kKeySize),
rnd.RandomString(kValueSize)));
}
for (int i = 0; i < kRangeDeletionsPerTable; i++) {
std::string start = rnd.RandomString(kKeySize);
std::string end = start;
end.resize(kValueSize);
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(),
start, end));
}
ASSERT_OK(db_->Flush(FlushOptions()));
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ResetTableProperties(&sum_tp);
for (int level = 0; level < kMaxLevel; ++level) {
db_->GetProperty(
DB::Properties::kAggregatedTablePropertiesAtLevel + ToString(level),
&level_tp_strings[level]);
ParseTablePropertiesString(level_tp_strings[level], &level_tps[level]);
sum_tp.data_size += level_tps[level].data_size;
sum_tp.index_size += level_tps[level].index_size;
sum_tp.filter_size += level_tps[level].filter_size;
sum_tp.raw_key_size += level_tps[level].raw_key_size;
sum_tp.raw_value_size += level_tps[level].raw_value_size;
sum_tp.num_data_blocks += level_tps[level].num_data_blocks;
sum_tp.num_entries += level_tps[level].num_entries;
sum_tp.num_deletions += level_tps[level].num_deletions;
sum_tp.num_merge_operands += level_tps[level].num_merge_operands;
sum_tp.num_range_deletions += level_tps[level].num_range_deletions;
}
db_->GetProperty(DB::Properties::kAggregatedTableProperties, &tp_string);
ParseTablePropertiesString(tp_string, &tp);
bool index_key_is_user_key = tp.index_key_is_user_key > 0;
bool value_is_delta_encoded = tp.index_value_is_delta_encoded > 0;
ASSERT_EQ(sum_tp.data_size, tp.data_size);
ASSERT_EQ(sum_tp.index_size, tp.index_size);
ASSERT_EQ(sum_tp.filter_size, tp.filter_size);
ASSERT_EQ(sum_tp.raw_key_size, tp.raw_key_size);
ASSERT_EQ(sum_tp.raw_value_size, tp.raw_value_size);
ASSERT_EQ(sum_tp.num_data_blocks, tp.num_data_blocks);
ASSERT_EQ(sum_tp.num_entries, tp.num_entries);
ASSERT_EQ(sum_tp.num_deletions, tp.num_deletions);
ASSERT_EQ(sum_tp.num_merge_operands, tp.num_merge_operands);
ASSERT_EQ(sum_tp.num_range_deletions, tp.num_range_deletions);
if (table > 3) {
GetExpectedTableProperties(
&expected_tp, kKeySize, kValueSize, kPutsPerTable, kDeletionsPerTable,
kMergeOperandsPerTable, kRangeDeletionsPerTable, table,
kBloomBitsPerKey, table_options.block_size, index_key_is_user_key,
value_is_delta_encoded);
// Gives larger bias here as index block size, filter block size,
// and data block size become much harder to estimate in this test.
VerifyTableProperties(expected_tp, tp, 0.5, 0.4, 0.4, 0.25);
}
}
}
TEST_F(DBPropertiesTest, NumImmutableMemTable) {
do {
Options options = CurrentOptions();
WriteOptions writeOpt = WriteOptions();
writeOpt.disableWAL = true;
options.max_write_buffer_number = 4;
options.min_write_buffer_number_to_merge = 3;
options.write_buffer_size = 1000000;
options.max_write_buffer_size_to_maintain =
5 * static_cast<int64_t>(options.write_buffer_size);
CreateAndReopenWithCF({"pikachu"}, options);
std::string big_value(1000000 * 2, 'x');
std::string num;
uint64_t value;
SetPerfLevel(kEnableTime);
ASSERT_TRUE(GetPerfLevel() == kEnableTime);
ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "k1", big_value));
ASSERT_TRUE(dbfull()->GetProperty(handles_[1],
"rocksdb.num-immutable-mem-table", &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], DB::Properties::kNumImmutableMemTableFlushed, &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &num));
ASSERT_EQ(num, "1");
get_perf_context()->Reset();
Get(1, "k1");
ASSERT_EQ(1, static_cast<int>(get_perf_context()->get_from_memtable_count));
ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "k2", big_value));
ASSERT_TRUE(dbfull()->GetProperty(handles_[1],
"rocksdb.num-immutable-mem-table", &num));
ASSERT_EQ(num, "1");
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &num));
ASSERT_EQ(num, "1");
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-imm-mem-tables", &num));
ASSERT_EQ(num, "1");
get_perf_context()->Reset();
Get(1, "k1");
ASSERT_EQ(2, static_cast<int>(get_perf_context()->get_from_memtable_count));
get_perf_context()->Reset();
Get(1, "k2");
ASSERT_EQ(1, static_cast<int>(get_perf_context()->get_from_memtable_count));
ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "k3", big_value));
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.cur-size-active-mem-table", &num));
ASSERT_TRUE(dbfull()->GetProperty(handles_[1],
"rocksdb.num-immutable-mem-table", &num));
ASSERT_EQ(num, "2");
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &num));
ASSERT_EQ(num, "1");
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], "rocksdb.num-entries-imm-mem-tables", &num));
ASSERT_EQ(num, "2");
get_perf_context()->Reset();
Get(1, "k2");
ASSERT_EQ(2, static_cast<int>(get_perf_context()->get_from_memtable_count));
get_perf_context()->Reset();
Get(1, "k3");
ASSERT_EQ(1, static_cast<int>(get_perf_context()->get_from_memtable_count));
get_perf_context()->Reset();
Get(1, "k1");
ASSERT_EQ(3, static_cast<int>(get_perf_context()->get_from_memtable_count));
ASSERT_OK(Flush(1));
ASSERT_TRUE(dbfull()->GetProperty(handles_[1],
"rocksdb.num-immutable-mem-table", &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty(
handles_[1], DB::Properties::kNumImmutableMemTableFlushed, &num));
ASSERT_EQ(num, "3");
ASSERT_TRUE(dbfull()->GetIntProperty(
handles_[1], "rocksdb.cur-size-active-mem-table", &value));
// "192" is the size of the metadata of two empty skiplists, this would
// break if we change the default skiplist implementation
ASSERT_GE(value, 192);
uint64_t int_num;
uint64_t base_total_size;
ASSERT_TRUE(dbfull()->GetIntProperty(
handles_[1], "rocksdb.estimate-num-keys", &base_total_size));
ASSERT_OK(dbfull()->Delete(writeOpt, handles_[1], "k2"));
ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "k3", ""));
ASSERT_OK(dbfull()->Delete(writeOpt, handles_[1], "k3"));
ASSERT_TRUE(dbfull()->GetIntProperty(
handles_[1], "rocksdb.num-deletes-active-mem-table", &int_num));
ASSERT_EQ(int_num, 2U);
ASSERT_TRUE(dbfull()->GetIntProperty(
handles_[1], "rocksdb.num-entries-active-mem-table", &int_num));
ASSERT_EQ(int_num, 3U);
ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "k2", big_value));
ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "k2", big_value));
ASSERT_TRUE(dbfull()->GetIntProperty(
handles_[1], "rocksdb.num-entries-imm-mem-tables", &int_num));
ASSERT_EQ(int_num, 4U);
ASSERT_TRUE(dbfull()->GetIntProperty(
handles_[1], "rocksdb.num-deletes-imm-mem-tables", &int_num));
ASSERT_EQ(int_num, 2U);
ASSERT_TRUE(dbfull()->GetIntProperty(
handles_[1], "rocksdb.estimate-num-keys", &int_num));
ASSERT_EQ(int_num, base_total_size + 1);
SetPerfLevel(kDisable);
ASSERT_TRUE(GetPerfLevel() == kDisable);
} while (ChangeCompactOptions());
}
// TODO(techdept) : Disabled flaky test #12863555
TEST_F(DBPropertiesTest, DISABLED_GetProperty) {
// Set sizes to both background thread pool to be 1 and block them.
env_->SetBackgroundThreads(1, Env::HIGH);
env_->SetBackgroundThreads(1, Env::LOW);
test::SleepingBackgroundTask sleeping_task_low;
env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
Env::Priority::LOW);
test::SleepingBackgroundTask sleeping_task_high;
env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
&sleeping_task_high, Env::Priority::HIGH);
Options options = CurrentOptions();
WriteOptions writeOpt = WriteOptions();
writeOpt.disableWAL = true;
options.compaction_style = kCompactionStyleUniversal;
options.level0_file_num_compaction_trigger = 1;
options.compaction_options_universal.size_ratio = 50;
options.max_background_compactions = 1;
options.max_background_flushes = 1;
options.max_write_buffer_number = 10;
options.min_write_buffer_number_to_merge = 1;
options.max_write_buffer_size_to_maintain = 0;
options.write_buffer_size = 1000000;
Reopen(options);
std::string big_value(1000000 * 2, 'x');
std::string num;
uint64_t int_num;
SetPerfLevel(kEnableTime);
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.estimate-table-readers-mem", &int_num));
ASSERT_EQ(int_num, 0U);
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.estimate-live-data-size", &int_num));
ASSERT_EQ(int_num, 0U);
ASSERT_OK(dbfull()->Put(writeOpt, "k1", big_value));
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.num-immutable-mem-table", &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.mem-table-flush-pending", &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.compaction-pending", &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.estimate-num-keys", &num));
ASSERT_EQ(num, "1");
get_perf_context()->Reset();
ASSERT_OK(dbfull()->Put(writeOpt, "k2", big_value));
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.num-immutable-mem-table", &num));
ASSERT_EQ(num, "1");
ASSERT_OK(dbfull()->Delete(writeOpt, "k-non-existing"));
ASSERT_OK(dbfull()->Put(writeOpt, "k3", big_value));
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.num-immutable-mem-table", &num));
ASSERT_EQ(num, "2");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.mem-table-flush-pending", &num));
ASSERT_EQ(num, "1");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.compaction-pending", &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.estimate-num-keys", &num));
ASSERT_EQ(num, "2");
// Verify the same set of properties through GetIntProperty
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.num-immutable-mem-table", &int_num));
ASSERT_EQ(int_num, 2U);
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.mem-table-flush-pending", &int_num));
ASSERT_EQ(int_num, 1U);
ASSERT_TRUE(dbfull()->GetIntProperty("rocksdb.compaction-pending", &int_num));
ASSERT_EQ(int_num, 0U);
ASSERT_TRUE(dbfull()->GetIntProperty("rocksdb.estimate-num-keys", &int_num));
ASSERT_EQ(int_num, 2U);
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.estimate-table-readers-mem", &int_num));
ASSERT_EQ(int_num, 0U);
sleeping_task_high.WakeUp();
sleeping_task_high.WaitUntilDone();
dbfull()->TEST_WaitForFlushMemTable();
ASSERT_OK(dbfull()->Put(writeOpt, "k4", big_value));
ASSERT_OK(dbfull()->Put(writeOpt, "k5", big_value));
dbfull()->TEST_WaitForFlushMemTable();
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.mem-table-flush-pending", &num));
ASSERT_EQ(num, "0");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.compaction-pending", &num));
ASSERT_EQ(num, "1");
ASSERT_TRUE(dbfull()->GetProperty("rocksdb.estimate-num-keys", &num));
ASSERT_EQ(num, "4");
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.estimate-table-readers-mem", &int_num));
ASSERT_GT(int_num, 0U);
sleeping_task_low.WakeUp();
sleeping_task_low.WaitUntilDone();
// Wait for compaction to be done. This is important because otherwise RocksDB
// might schedule a compaction when reopening the database, failing assertion
// (A) as a result.
ASSERT_OK(dbfull()->TEST_WaitForCompact());
options.max_open_files = 10;
Reopen(options);
// After reopening, no table reader is loaded, so no memory for table readers
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.estimate-table-readers-mem", &int_num));
ASSERT_EQ(int_num, 0U); // (A)
ASSERT_TRUE(dbfull()->GetIntProperty("rocksdb.estimate-num-keys", &int_num));
ASSERT_GT(int_num, 0U);
// After reading a key, at least one table reader is loaded.
Get("k5");
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.estimate-table-readers-mem", &int_num));
ASSERT_GT(int_num, 0U);
// Test rocksdb.num-live-versions
{
options.level0_file_num_compaction_trigger = 20;
Reopen(options);
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.num-live-versions", &int_num));
ASSERT_EQ(int_num, 1U);
// Use an iterator to hold current version
std::unique_ptr<Iterator> iter1(dbfull()->NewIterator(ReadOptions()));
ASSERT_OK(dbfull()->Put(writeOpt, "k6", big_value));
ASSERT_OK(Flush());
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.num-live-versions", &int_num));
ASSERT_EQ(int_num, 2U);
// Use an iterator to hold current version
std::unique_ptr<Iterator> iter2(dbfull()->NewIterator(ReadOptions()));
ASSERT_OK(dbfull()->Put(writeOpt, "k7", big_value));
ASSERT_OK(Flush());
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.num-live-versions", &int_num));
ASSERT_EQ(int_num, 3U);
iter2.reset();
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.num-live-versions", &int_num));
ASSERT_EQ(int_num, 2U);
iter1.reset();
ASSERT_TRUE(
dbfull()->GetIntProperty("rocksdb.num-live-versions", &int_num));
ASSERT_EQ(int_num, 1U);
}
}
TEST_F(DBPropertiesTest, ApproximateMemoryUsage) {
const int kNumRounds = 10;
// TODO(noetzli) kFlushesPerRound does not really correlate with how many
// flushes happen.
const int kFlushesPerRound = 10;
const int kWritesPerFlush = 10;
const int kKeySize = 100;
const int kValueSize = 1000;
Options options;
options.write_buffer_size = 1000; // small write buffer
options.min_write_buffer_number_to_merge = 4;
options.compression = kNoCompression;
options.create_if_missing = true;
options = CurrentOptions(options);
DestroyAndReopen(options);
Random rnd(301);
std::vector<Iterator*> iters;
uint64_t active_mem;
uint64_t unflushed_mem;
uint64_t all_mem;
uint64_t prev_all_mem;
// Phase 0. The verify the initial value of all these properties are the same
// as we have no mem-tables.
dbfull()->GetIntProperty("rocksdb.cur-size-active-mem-table", &active_mem);
dbfull()->GetIntProperty("rocksdb.cur-size-all-mem-tables", &unflushed_mem);
dbfull()->GetIntProperty("rocksdb.size-all-mem-tables", &all_mem);
ASSERT_EQ(all_mem, active_mem);
ASSERT_EQ(all_mem, unflushed_mem);
// Phase 1. Simply issue Put() and expect "cur-size-all-mem-tables" equals to
// "size-all-mem-tables"
for (int r = 0; r < kNumRounds; ++r) {
for (int f = 0; f < kFlushesPerRound; ++f) {
for (int w = 0; w < kWritesPerFlush; ++w) {
ASSERT_OK(
Put(rnd.RandomString(kKeySize), rnd.RandomString(kValueSize)));
}
}
// Make sure that there is no flush between getting the two properties.
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
dbfull()->GetIntProperty("rocksdb.cur-size-all-mem-tables", &unflushed_mem);
dbfull()->GetIntProperty("rocksdb.size-all-mem-tables", &all_mem);
// in no iterator case, these two number should be the same.
ASSERT_EQ(unflushed_mem, all_mem);
}
prev_all_mem = all_mem;
// Phase 2. Keep issuing Put() but also create new iterators. This time we
// expect "size-all-mem-tables" > "cur-size-all-mem-tables".
for (int r = 0; r < kNumRounds; ++r) {
iters.push_back(db_->NewIterator(ReadOptions()));
for (int f = 0; f < kFlushesPerRound; ++f) {
for (int w = 0; w < kWritesPerFlush; ++w) {
ASSERT_OK(
Put(rnd.RandomString(kKeySize), rnd.RandomString(kValueSize)));
}
}
// Force flush to prevent flush from happening between getting the
// properties or after getting the properties and before the new round.
ASSERT_OK(Flush());
// In the second round, add iterators.
dbfull()->GetIntProperty("rocksdb.cur-size-active-mem-table", &active_mem);
dbfull()->GetIntProperty("rocksdb.cur-size-all-mem-tables", &unflushed_mem);
dbfull()->GetIntProperty("rocksdb.size-all-mem-tables", &all_mem);
ASSERT_GT(all_mem, active_mem);
ASSERT_GT(all_mem, unflushed_mem);
ASSERT_GT(all_mem, prev_all_mem);
prev_all_mem = all_mem;
}
// Phase 3. Delete iterators and expect "size-all-mem-tables" shrinks
// whenever we release an iterator.
for (auto* iter : iters) {
ASSERT_OK(iter->status());
delete iter;
dbfull()->GetIntProperty("rocksdb.size-all-mem-tables", &all_mem);
// Expect the size shrinking
ASSERT_LT(all_mem, prev_all_mem);
prev_all_mem = all_mem;
}
// Expect all these three counters to be the same.
dbfull()->GetIntProperty("rocksdb.cur-size-active-mem-table", &active_mem);
dbfull()->GetIntProperty("rocksdb.cur-size-all-mem-tables", &unflushed_mem);
dbfull()->GetIntProperty("rocksdb.size-all-mem-tables", &all_mem);
ASSERT_EQ(active_mem, unflushed_mem);
ASSERT_EQ(unflushed_mem, all_mem);
// Phase 5. Reopen, and expect all these three counters to be the same again.
Reopen(options);
dbfull()->GetIntProperty("rocksdb.cur-size-active-mem-table", &active_mem);
dbfull()->GetIntProperty("rocksdb.cur-size-all-mem-tables", &unflushed_mem);
dbfull()->GetIntProperty("rocksdb.size-all-mem-tables", &all_mem);
ASSERT_EQ(active_mem, unflushed_mem);
ASSERT_EQ(unflushed_mem, all_mem);
}
TEST_F(DBPropertiesTest, EstimatePendingCompBytes) {
// Set sizes to both background thread pool to be 1 and block them.
env_->SetBackgroundThreads(1, Env::HIGH);
env_->SetBackgroundThreads(1, Env::LOW);
test::SleepingBackgroundTask sleeping_task_low;
env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
Env::Priority::LOW);
Options options = CurrentOptions();
WriteOptions writeOpt = WriteOptions();
writeOpt.disableWAL = true;
options.compaction_style = kCompactionStyleLevel;
options.level0_file_num_compaction_trigger = 2;
options.max_background_compactions = 1;
options.max_background_flushes = 1;
options.max_write_buffer_number = 10;
options.min_write_buffer_number_to_merge = 1;
options.max_write_buffer_size_to_maintain = 0;
options.write_buffer_size = 1000000;
Reopen(options);
std::string big_value(1000000 * 2, 'x');
std::string num;
uint64_t int_num;
ASSERT_OK(dbfull()->Put(writeOpt, "k1", big_value));
ASSERT_OK(Flush());
ASSERT_TRUE(dbfull()->GetIntProperty(
"rocksdb.estimate-pending-compaction-bytes", &int_num));
ASSERT_EQ(int_num, 0U);
ASSERT_OK(dbfull()->Put(writeOpt, "k2", big_value));
ASSERT_OK(Flush());
ASSERT_TRUE(dbfull()->GetIntProperty(
"rocksdb.estimate-pending-compaction-bytes", &int_num));
ASSERT_GT(int_num, 0U);
ASSERT_OK(dbfull()->Put(writeOpt, "k3", big_value));
ASSERT_OK(Flush());
ASSERT_TRUE(dbfull()->GetIntProperty(
"rocksdb.estimate-pending-compaction-bytes", &int_num));
ASSERT_GT(int_num, 0U);
sleeping_task_low.WakeUp();
sleeping_task_low.WaitUntilDone();
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_TRUE(dbfull()->GetIntProperty(
"rocksdb.estimate-pending-compaction-bytes", &int_num));
ASSERT_EQ(int_num, 0U);
}
TEST_F(DBPropertiesTest, EstimateCompressionRatio) {
if (!Snappy_Supported()) {
return;
}
const int kNumL0Files = 3;
const int kNumEntriesPerFile = 1000;
Options options = CurrentOptions();
options.compression_per_level = {kNoCompression, kSnappyCompression};
options.disable_auto_compactions = true;
options.num_levels = 2;
Reopen(options);
// compression ratio is -1.0 when no open files at level
ASSERT_EQ(CompressionRatioAtLevel(0), -1.0);
const std::string kVal(100, 'a');
for (int i = 0; i < kNumL0Files; ++i) {
for (int j = 0; j < kNumEntriesPerFile; ++j) {
// Put common data ("key") at end to prevent delta encoding from
// compressing the key effectively
std::string key = ToString(i) + ToString(j) + "key";
ASSERT_OK(dbfull()->Put(WriteOptions(), key, kVal));
}
ASSERT_OK(Flush());
}
// no compression at L0, so ratio is less than one
ASSERT_LT(CompressionRatioAtLevel(0), 1.0);
ASSERT_GT(CompressionRatioAtLevel(0), 0.0);
ASSERT_EQ(CompressionRatioAtLevel(1), -1.0);
ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, nullptr));
ASSERT_EQ(CompressionRatioAtLevel(0), -1.0);
// Data at L1 should be highly compressed thanks to Snappy and redundant data
// in values (ratio is 12.846 as of 4/19/2016).
ASSERT_GT(CompressionRatioAtLevel(1), 10.0);
}
#endif // ROCKSDB_LITE
class CountingUserTblPropCollector : public TablePropertiesCollector {
public:
const char* Name() const override { return "CountingUserTblPropCollector"; }
Status Finish(UserCollectedProperties* properties) override {
std::string encoded;
PutVarint32(&encoded, count_);
*properties = UserCollectedProperties{
{"CountingUserTblPropCollector", message_}, {"Count", encoded},
};
return Status::OK();
}
Status AddUserKey(const Slice& /*user_key*/, const Slice& /*value*/,
EntryType /*type*/, SequenceNumber /*seq*/,
uint64_t /*file_size*/) override {
++count_;
return Status::OK();
}
UserCollectedProperties GetReadableProperties() const override {
return UserCollectedProperties{};
}
private:
std::string message_ = "Rocksdb";
uint32_t count_ = 0;
};
class CountingUserTblPropCollectorFactory
: public TablePropertiesCollectorFactory {
public:
explicit CountingUserTblPropCollectorFactory(
uint32_t expected_column_family_id)
: expected_column_family_id_(expected_column_family_id),
num_created_(0) {}
TablePropertiesCollector* CreateTablePropertiesCollector(
TablePropertiesCollectorFactory::Context context) override {
EXPECT_EQ(expected_column_family_id_, context.column_family_id);
num_created_++;
return new CountingUserTblPropCollector();
}
const char* Name() const override {
return "CountingUserTblPropCollectorFactory";
}
void set_expected_column_family_id(uint32_t v) {
expected_column_family_id_ = v;
}
uint32_t expected_column_family_id_;
uint32_t num_created_;
};
class CountingDeleteTabPropCollector : public TablePropertiesCollector {
public:
const char* Name() const override { return "CountingDeleteTabPropCollector"; }
Status AddUserKey(const Slice& /*user_key*/, const Slice& /*value*/,
EntryType type, SequenceNumber /*seq*/,
uint64_t /*file_size*/) override {
if (type == kEntryDelete) {
num_deletes_++;
}
return Status::OK();
}
bool NeedCompact() const override { return num_deletes_ > 10; }
UserCollectedProperties GetReadableProperties() const override {
return UserCollectedProperties{};
}
Status Finish(UserCollectedProperties* properties) override {
*properties =
UserCollectedProperties{{"num_delete", ToString(num_deletes_)}};
return Status::OK();
}
private:
uint32_t num_deletes_ = 0;
};
class CountingDeleteTabPropCollectorFactory
: public TablePropertiesCollectorFactory {
public:
TablePropertiesCollector* CreateTablePropertiesCollector(
TablePropertiesCollectorFactory::Context /*context*/) override {
return new CountingDeleteTabPropCollector();
}
const char* Name() const override {
return "CountingDeleteTabPropCollectorFactory";
}
};
#ifndef ROCKSDB_LITE
TEST_F(DBPropertiesTest, GetUserDefinedTableProperties) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = (1 << 30);
options.table_properties_collector_factories.resize(1);
std::shared_ptr<CountingUserTblPropCollectorFactory> collector_factory =
std::make_shared<CountingUserTblPropCollectorFactory>(0);
options.table_properties_collector_factories[0] = collector_factory;
Reopen(options);
// Create 4 tables
for (int table = 0; table < 4; ++table) {
for (int i = 0; i < 10 + table; ++i) {
ASSERT_OK(db_->Put(WriteOptions(), ToString(table * 100 + i), "val"));
}
ASSERT_OK(db_->Flush(FlushOptions()));
}
TablePropertiesCollection props;
ASSERT_OK(db_->GetPropertiesOfAllTables(&props));
ASSERT_EQ(4U, props.size());
uint32_t sum = 0;
for (const auto& item : props) {
auto& user_collected = item.second->user_collected_properties;
ASSERT_TRUE(user_collected.find("CountingUserTblPropCollector") !=
user_collected.end());
ASSERT_EQ(user_collected.at("CountingUserTblPropCollector"), "Rocksdb");
ASSERT_TRUE(user_collected.find("Count") != user_collected.end());
Slice key(user_collected.at("Count"));
uint32_t count;
ASSERT_TRUE(GetVarint32(&key, &count));
sum += count;
}
ASSERT_EQ(10u + 11u + 12u + 13u, sum);
ASSERT_GT(collector_factory->num_created_, 0U);
collector_factory->num_created_ = 0;
ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, nullptr));
ASSERT_GT(collector_factory->num_created_, 0U);
}
#endif // ROCKSDB_LITE
TEST_F(DBPropertiesTest, UserDefinedTablePropertiesContext) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 3;
options.table_properties_collector_factories.resize(1);
std::shared_ptr<CountingUserTblPropCollectorFactory> collector_factory =
std::make_shared<CountingUserTblPropCollectorFactory>(1);
options.table_properties_collector_factories[0] = collector_factory,
CreateAndReopenWithCF({"pikachu"}, options);
// Create 2 files
for (int table = 0; table < 2; ++table) {
for (int i = 0; i < 10 + table; ++i) {
ASSERT_OK(Put(1, ToString(table * 100 + i), "val"));
}
ASSERT_OK(Flush(1));
}
ASSERT_GT(collector_factory->num_created_, 0U);
collector_factory->num_created_ = 0;
// Trigger automatic compactions.
for (int table = 0; table < 3; ++table) {
for (int i = 0; i < 10 + table; ++i) {
ASSERT_OK(Put(1, ToString(table * 100 + i), "val"));
}
ASSERT_OK(Flush(1));
ASSERT_OK(dbfull()->TEST_WaitForCompact());
}
ASSERT_GT(collector_factory->num_created_, 0U);
collector_factory->num_created_ = 0;
ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]));
ASSERT_GT(collector_factory->num_created_, 0U);
// Come back to write to default column family
collector_factory->num_created_ = 0;
collector_factory->set_expected_column_family_id(0); // default CF
// Create 4 tables in default column family
for (int table = 0; table < 2; ++table) {
for (int i = 0; i < 10 + table; ++i) {
ASSERT_OK(Put(ToString(table * 100 + i), "val"));
}
ASSERT_OK(Flush());
}
ASSERT_GT(collector_factory->num_created_, 0U);
collector_factory->num_created_ = 0;
// Trigger automatic compactions.
for (int table = 0; table < 3; ++table) {
for (int i = 0; i < 10 + table; ++i) {
ASSERT_OK(Put(ToString(table * 100 + i), "val"));
}
ASSERT_OK(Flush());
ASSERT_OK(dbfull()->TEST_WaitForCompact());
}
ASSERT_GT(collector_factory->num_created_, 0U);
collector_factory->num_created_ = 0;
ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, nullptr));
ASSERT_GT(collector_factory->num_created_, 0U);
}
#ifndef ROCKSDB_LITE
TEST_F(DBPropertiesTest, TablePropertiesNeedCompactTest) {
Random rnd(301);
Options options;
options.create_if_missing = true;
options.write_buffer_size = 4096;
options.max_write_buffer_number = 8;
options.level0_file_num_compaction_trigger = 2;
options.level0_slowdown_writes_trigger = 2;
options.level0_stop_writes_trigger = 4;
options.target_file_size_base = 2048;
options.max_bytes_for_level_base = 10240;
options.max_bytes_for_level_multiplier = 4;
options.soft_pending_compaction_bytes_limit = 1024 * 1024;
options.num_levels = 8;
options.env = env_;
std::shared_ptr<TablePropertiesCollectorFactory> collector_factory =
std::make_shared<CountingDeleteTabPropCollectorFactory>();
options.table_properties_collector_factories.resize(1);
options.table_properties_collector_factories[0] = collector_factory;
DestroyAndReopen(options);
const int kMaxKey = 1000;
for (int i = 0; i < kMaxKey; i++) {
ASSERT_OK(Put(Key(i), rnd.RandomString(102)));
ASSERT_OK(Put(Key(kMaxKey + i), rnd.RandomString(102)));
}
ASSERT_OK(Flush());
ASSERT_OK(dbfull()->TEST_WaitForCompact());
if (NumTableFilesAtLevel(0) == 1) {
// Clear Level 0 so that when later flush a file with deletions,
// we don't trigger an organic compaction.
ASSERT_OK(Put(Key(0), ""));
ASSERT_OK(Put(Key(kMaxKey * 2), ""));
ASSERT_OK(Flush());
ASSERT_OK(dbfull()->TEST_WaitForCompact());
}
ASSERT_EQ(NumTableFilesAtLevel(0), 0);
{
int c = 0;
std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
iter->Seek(Key(kMaxKey - 100));
while (iter->Valid() && iter->key().compare(Key(kMaxKey + 100)) < 0) {
iter->Next();
++c;
}
ASSERT_OK(iter->status());
ASSERT_EQ(c, 200);
}
ASSERT_OK(Delete(Key(0)));
for (int i = kMaxKey - 100; i < kMaxKey + 100; i++) {
ASSERT_OK(Delete(Key(i)));
}
ASSERT_OK(Delete(Key(kMaxKey * 2)));
ASSERT_OK(Flush());
ASSERT_OK(dbfull()->TEST_WaitForCompact());
{
SetPerfLevel(kEnableCount);
get_perf_context()->Reset();
int c = 0;
std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
iter->Seek(Key(kMaxKey - 100));
while (iter->Valid() && iter->key().compare(Key(kMaxKey + 100)) < 0) {
iter->Next();
}
ASSERT_OK(iter->status());
ASSERT_EQ(c, 0);
ASSERT_LT(get_perf_context()->internal_delete_skipped_count, 30u);
ASSERT_LT(get_perf_context()->internal_key_skipped_count, 30u);
SetPerfLevel(kDisable);
}
}
TEST_F(DBPropertiesTest, NeedCompactHintPersistentTest) {
Random rnd(301);
Options options;
options.create_if_missing = true;
options.max_write_buffer_number = 8;
options.level0_file_num_compaction_trigger = 10;
options.level0_slowdown_writes_trigger = 10;
options.level0_stop_writes_trigger = 10;
options.disable_auto_compactions = true;
options.env = env_;
std::shared_ptr<TablePropertiesCollectorFactory> collector_factory =
std::make_shared<CountingDeleteTabPropCollectorFactory>();
options.table_properties_collector_factories.resize(1);
options.table_properties_collector_factories[0] = collector_factory;
DestroyAndReopen(options);
const int kMaxKey = 100;
for (int i = 0; i < kMaxKey; i++) {
ASSERT_OK(Put(Key(i), ""));
}
ASSERT_OK(Flush());
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
for (int i = 1; i < kMaxKey - 1; i++) {
ASSERT_OK(Delete(Key(i)));
}
ASSERT_OK(Flush());
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
ASSERT_EQ(NumTableFilesAtLevel(0), 2);
// Restart the DB. Although number of files didn't reach
// options.level0_file_num_compaction_trigger, compaction should
// still be triggered because of the need-compaction hint.
options.disable_auto_compactions = false;
Reopen(options);
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_EQ(NumTableFilesAtLevel(0), 0);
{
SetPerfLevel(kEnableCount);
get_perf_context()->Reset();
int c = 0;
std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
for (iter->Seek(Key(0)); iter->Valid(); iter->Next()) {
c++;
}
ASSERT_OK(iter->status());
ASSERT_EQ(c, 2);
ASSERT_EQ(get_perf_context()->internal_delete_skipped_count, 0);
// We iterate every key twice. Is it a bug?
ASSERT_LE(get_perf_context()->internal_key_skipped_count, 2);
SetPerfLevel(kDisable);
}
}
TEST_F(DBPropertiesTest, EstimateNumKeysUnderflow) {
Options options;
Reopen(options);
ASSERT_OK(Put("foo", "bar"));
ASSERT_OK(Delete("foo"));
ASSERT_OK(Delete("foo"));
uint64_t num_keys = 0;
ASSERT_TRUE(dbfull()->GetIntProperty("rocksdb.estimate-num-keys", &num_keys));
ASSERT_EQ(0, num_keys);
}
TEST_F(DBPropertiesTest, EstimateOldestKeyTime) {
uint64_t oldest_key_time = 0;
Options options = CurrentOptions();
SetTimeElapseOnlySleepOnReopen(&options);
// "rocksdb.estimate-oldest-key-time" only available to fifo compaction.
for (auto compaction : {kCompactionStyleLevel, kCompactionStyleUniversal,
kCompactionStyleNone}) {
options.compaction_style = compaction;
options.create_if_missing = true;
DestroyAndReopen(options);
ASSERT_OK(Put("foo", "bar"));
ASSERT_FALSE(dbfull()->GetIntProperty(
DB::Properties::kEstimateOldestKeyTime, &oldest_key_time));
}
int64_t mock_start_time;
ASSERT_OK(env_->GetCurrentTime(&mock_start_time));
options.compaction_style = kCompactionStyleFIFO;
options.ttl = 300;
options.compaction_options_fifo.allow_compaction = false;
DestroyAndReopen(options);
env_->MockSleepForSeconds(100);
ASSERT_OK(Put("k1", "v1"));
ASSERT_TRUE(dbfull()->GetIntProperty(DB::Properties::kEstimateOldestKeyTime,
&oldest_key_time));
ASSERT_EQ(100, oldest_key_time - mock_start_time);
ASSERT_OK(Flush());
ASSERT_EQ("1", FilesPerLevel());
ASSERT_TRUE(dbfull()->GetIntProperty(DB::Properties::kEstimateOldestKeyTime,
&oldest_key_time));
ASSERT_EQ(100, oldest_key_time - mock_start_time);
env_->MockSleepForSeconds(100); // -> 200
ASSERT_OK(Put("k2", "v2"));
ASSERT_OK(Flush());
ASSERT_EQ("2", FilesPerLevel());
ASSERT_TRUE(dbfull()->GetIntProperty(DB::Properties::kEstimateOldestKeyTime,
&oldest_key_time));
ASSERT_EQ(100, oldest_key_time - mock_start_time);
env_->MockSleepForSeconds(100); // -> 300
ASSERT_OK(Put("k3", "v3"));
ASSERT_OK(Flush());
ASSERT_EQ("3", FilesPerLevel());
ASSERT_TRUE(dbfull()->GetIntProperty(DB::Properties::kEstimateOldestKeyTime,
&oldest_key_time));
ASSERT_EQ(100, oldest_key_time - mock_start_time);
env_->MockSleepForSeconds(150); // -> 450
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_EQ("2", FilesPerLevel());
ASSERT_TRUE(dbfull()->GetIntProperty(DB::Properties::kEstimateOldestKeyTime,
&oldest_key_time));
ASSERT_EQ(200, oldest_key_time - mock_start_time);
env_->MockSleepForSeconds(100); // -> 550
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_EQ("1", FilesPerLevel());
ASSERT_TRUE(dbfull()->GetIntProperty(DB::Properties::kEstimateOldestKeyTime,
&oldest_key_time));
ASSERT_EQ(300, oldest_key_time - mock_start_time);
env_->MockSleepForSeconds(100); // -> 650
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_EQ("", FilesPerLevel());
ASSERT_FALSE(dbfull()->GetIntProperty(DB::Properties::kEstimateOldestKeyTime,
&oldest_key_time));
}
TEST_F(DBPropertiesTest, SstFilesSize) {
struct TestListener : public EventListener {
void OnCompactionCompleted(DB* db,
const CompactionJobInfo& /*info*/) override {
assert(callback_triggered == false);
assert(size_before_compaction > 0);
callback_triggered = true;
uint64_t total_sst_size = 0;
uint64_t live_sst_size = 0;
bool ok = db->GetIntProperty(DB::Properties::kTotalSstFilesSize,
&total_sst_size);
ASSERT_TRUE(ok);
// total_sst_size include files before and after compaction.
ASSERT_GT(total_sst_size, size_before_compaction);
ok =
db->GetIntProperty(DB::Properties::kLiveSstFilesSize, &live_sst_size);
ASSERT_TRUE(ok);
// live_sst_size only include files after compaction.
ASSERT_GT(live_sst_size, 0);
ASSERT_LT(live_sst_size, size_before_compaction);
}
uint64_t size_before_compaction = 0;
bool callback_triggered = false;
};
std::shared_ptr<TestListener> listener = std::make_shared<TestListener>();
Options options;
options.disable_auto_compactions = true;
options.listeners.push_back(listener);
Reopen(options);
for (int i = 0; i < 10; i++) {
ASSERT_OK(Put("key" + ToString(i), std::string(1000, 'v')));
}
ASSERT_OK(Flush());
for (int i = 0; i < 5; i++) {
ASSERT_OK(Delete("key" + ToString(i)));
}
ASSERT_OK(Flush());
uint64_t sst_size;
bool ok = db_->GetIntProperty(DB::Properties::kTotalSstFilesSize, &sst_size);
ASSERT_TRUE(ok);
ASSERT_GT(sst_size, 0);
listener->size_before_compaction = sst_size;
// Compact to clean all keys and trigger listener.
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_TRUE(listener->callback_triggered);
}
TEST_F(DBPropertiesTest, MinObsoleteSstNumberToKeep) {
class TestListener : public EventListener {
public:
void OnTableFileCreated(const TableFileCreationInfo& info) override {
if (info.reason == TableFileCreationReason::kCompaction) {
// Verify the property indicates that SSTs created by a running
// compaction cannot be deleted.
uint64_t created_file_num;
FileType created_file_type;
std::string filename =
info.file_path.substr(info.file_path.rfind('/') + 1);
ASSERT_TRUE(
ParseFileName(filename, &created_file_num, &created_file_type));
ASSERT_EQ(kTableFile, created_file_type);
uint64_t keep_sst_lower_bound;
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kMinObsoleteSstNumberToKeep,
&keep_sst_lower_bound));
ASSERT_LE(keep_sst_lower_bound, created_file_num);
validated_ = true;
}
}
void SetDB(DB* db) { db_ = db; }
int GetNumCompactions() { return num_compactions_; }
// True if we've verified the property for at least one output file
bool Validated() { return validated_; }
private:
int num_compactions_ = 0;
bool validated_ = false;
DB* db_ = nullptr;
};
const int kNumL0Files = 4;
std::shared_ptr<TestListener> listener = std::make_shared<TestListener>();
Options options = CurrentOptions();
options.listeners.push_back(listener);
options.level0_file_num_compaction_trigger = kNumL0Files;
DestroyAndReopen(options);
listener->SetDB(db_);
for (int i = 0; i < kNumL0Files; ++i) {
// Make sure they overlap in keyspace to prevent trivial move
ASSERT_OK(Put("key1", "val"));
ASSERT_OK(Put("key2", "val"));
ASSERT_OK(Flush());
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_TRUE(listener->Validated());
}
TEST_F(DBPropertiesTest, BlockCacheProperties) {
Options options;
uint64_t value;
// Block cache properties are not available for tables other than
// block-based table.
options.table_factory.reset(NewPlainTableFactory());
Reopen(options);
ASSERT_FALSE(
db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_FALSE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
ASSERT_FALSE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
options.table_factory.reset(NewCuckooTableFactory());
Reopen(options);
ASSERT_FALSE(
db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_FALSE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
ASSERT_FALSE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
// Block cache properties are not available if block cache is not used.
BlockBasedTableOptions table_options;
table_options.no_block_cache = true;
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
Reopen(options);
ASSERT_FALSE(
db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_FALSE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
ASSERT_FALSE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
// Test with empty block cache.
constexpr size_t kCapacity = 100;
LRUCacheOptions co;
co.capacity = kCapacity;
co.num_shard_bits = 0;
co.metadata_charge_policy = kDontChargeCacheMetadata;
auto block_cache = NewLRUCache(co);
table_options.block_cache = block_cache;
table_options.no_block_cache = false;
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
Reopen(options);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_EQ(kCapacity, value);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
ASSERT_EQ(0, value);
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
ASSERT_EQ(0, value);
// Insert unpinned item to the cache and check size.
constexpr size_t kSize1 = 50;
ASSERT_OK(block_cache->Insert("item1", nullptr /*value*/, kSize1,
nullptr /*deleter*/));
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_EQ(kCapacity, value);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
ASSERT_EQ(kSize1, value);
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
ASSERT_EQ(0, value);
// Insert pinned item to the cache and check size.
constexpr size_t kSize2 = 30;
Cache::Handle* item2 = nullptr;
ASSERT_OK(block_cache->Insert("item2", nullptr /*value*/, kSize2,
nullptr /*deleter*/, &item2));
ASSERT_NE(nullptr, item2);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_EQ(kCapacity, value);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
ASSERT_EQ(kSize1 + kSize2, value);
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
ASSERT_EQ(kSize2, value);
// Insert another pinned item to make the cache over-sized.
constexpr size_t kSize3 = 80;
Cache::Handle* item3 = nullptr;
ASSERT_OK(block_cache->Insert("item3", nullptr /*value*/, kSize3,
nullptr /*deleter*/, &item3));
ASSERT_NE(nullptr, item2);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_EQ(kCapacity, value);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
// Item 1 is evicted.
ASSERT_EQ(kSize2 + kSize3, value);
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
ASSERT_EQ(kSize2 + kSize3, value);
// Check size after release.
block_cache->Release(item2);
block_cache->Release(item3);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheCapacity, &value));
ASSERT_EQ(kCapacity, value);
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kBlockCacheUsage, &value));
// item2 will be evicted, while item3 remain in cache after release.
ASSERT_EQ(kSize3, value);
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kBlockCachePinnedUsage, &value));
ASSERT_EQ(0, value);
}
#endif // ROCKSDB_LITE
} // namespace ROCKSDB_NAMESPACE
int main(int argc, char** argv) {
ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
// Copyright 1996-2021 Cyberbotics 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.
#ifndef COMMUNICATION_HPP
#define COMMUNICATION_HPP
#include <webots/types.h>
#include <string>
class EPuckCommandPacket;
class EPuckInputPacket;
class Communication {
public:
Communication();
virtual ~Communication();
bool initialize(const std::string &ip);
void cleanup();
bool isInitialized() const { return mFd > 0; }
bool send(const char *, int size);
int receive(char *, int size, bool block);
private:
int mFd;
};
#endif
|
// Copyright (c) 2020 Graphcore Ltd.
// 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.
// This file has been modified by Graphcore Ltd.
// It has been modified to run the application on IPU hardware.
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "coord.h"
#include "position.h"
using minigo::BoardVisitor;
using minigo::Color;
using minigo::Coord;
using minigo::GroupVisitor;
using minigo::kDefaultKomi;
using minigo::Position;
namespace {
void BM_PlayGame(benchmark::State& state) { // NOLINT(runtime/references)
std::vector<std::string> str_moves = {
"pd", "dd", "qp", "dp", "fq", "hq", "oq", "cn", "qj", "nc", "pf", "pb",
"cf", "fc", "qc", "ld", "bd", "ch", "cc", "ce", "be", "df", "dg", "cg",
"bf", "ef", "jq", "eq", "dm", "fp", "jc", "kc", "eg", "fg", "di", "dj",
"ei", "ci", "ej", "ek", "dk", "cj", "fk", "el", "dl", "fl", "gj", "bl",
"gl", "fm", "fo", "gp", "gm", "fn", "go", "gn", "hn", "eo", "ho", "en",
"im", "pk", "pj", "ok", "oj", "nk", "qk", "pm", "ql", "oo", "nm", "mn",
"mm", "lm", "ll", "nq", "nr", "pq", "pp", "op", "or", "ln", "mk", "mq",
"mr", "lq", "jd", "gf", "kf", "om", "nn", "no", "nj", "qb", "dc", "hc",
"qn", "lr", "iq", "ko", "hp", "gr", "hr", "gq", "jo", "lp", "he", "ge",
"hd", "gd", "hb", "hf", "gb", "gi", "hi", "fi", "fj", "hh", "ii", "fb",
"ih", "ca", "ba", "ea", "db", "da", "bb", "je", "ke", "id", "kb", "kd",
"ic", "ie", "lb", "md", "mb", "nb", "ga", "rb", "rc", "mf", "lg", "mg",
"mh", "og", "pg", "sc", "oc", "of", "od", "ne", "sb", "sa", "sd", "sb",
"rd", "nh", "lh", "ph", "qh", "kl", "jl", "lk", "ml", "km", "kk", "po",
"qo", "pr", "qr", "ms", "qq", "bg", "ag", "ah", "af", "bk", "ob", "oa",
"jf", "pe", "oe", "qg", "qf", "qi", "rg", "pi", "ri", "ni", "hg", "ib",
"jb", "mi", "li", "gc", "fh", "gg", "gh", "jm", "jk", "mj", "lj", "jn",
"ma", "na", "cd", "de", "oi", "oh", "is", "ig", "jg", "dh", "eh", "if",
"kr", "qm", "rm", "ks", "js", "ls", "ec", "ed", "le", "me", "kq", "io",
"ip", "jp", "gs", "fs", "hs", "ia", "ja", "ns", "ps", "kp", "in", "pc",
"pl", "ol", "ha", "nd", "qe", "on", "lf", "fa", "lk", "cb", "nl", "pn",
"os", "eb", "mc", "lc", "hh", "jo",
};
std::vector<Coord> moves;
for (const auto& str_move : str_moves) {
moves.push_back(Coord::FromSgf(str_move));
}
BoardVisitor bv;
GroupVisitor gv;
std::vector<Position> boards;
boards.reserve(str_moves.size());
for (auto _ : state) {
for (int i = 0; i < 1000; ++i) {
// For a fair comparison with the Python performance, create a new board
// for each move.
boards.clear();
boards.emplace_back(&bv, &gv, Color::kBlack);
for (const auto& move : moves) {
boards.push_back(boards.back());
boards.back().PlayMove(move);
}
}
}
}
BENCHMARK(BM_PlayGame);
} // namespace
BENCHMARK_MAIN();
|
#ifndef CPPDATASTRUCTURES_NUMBERFORMATTER_H
#define CPPDATASTRUCTURES_NUMBERFORMATTER_H
#include <cassert>
#include "BitConverter.h"
#include "String.h"
class NumberFormatter final
{
private:
static constexpr int32_t INT32_PRECISION = 10;
static constexpr int32_t UINT32_PRECISION = INT32_PRECISION;
static constexpr int32_t INT64_PRECISION = 19;
static constexpr int32_t UINT64_PRECISION = 20;
static constexpr int32_t FLOAT_PRECISION = 7;
static constexpr int32_t DOUBLE_PRECISION = 15;
static constexpr int32_t LARGE_BUFFER_SIZE = 600;
static constexpr int32_t MIN_BUFFER_SIZE = 105;
static constexpr int32_t SCALE_NAN = 0x80000000;
static constexpr int32_t SCALE_INF = 0x7FFFFFFF;
struct FPSINGLE
{
#if BitConverter::IsLittleEndian() == 0
uint32_t sign : 1;
uint32_t exp : 8;
uint32_t mant : 23;
#else
uint32_t mant : 23;
uint32_t exp : 8;
uint32_t sign : 1;
#endif
};
struct FPDOUBLE
{
#if BitConverter::IsLittleEndian() == 0
unsigned int sign : 1;
unsigned int exp : 11;
unsigned int mantHi : 20;
unsigned int mantLo;
#else
unsigned int mantLo;
unsigned int mantHi : 20;
unsigned int exp : 11;
unsigned int sign : 1;
#endif
};
static constexpr const char* const posCurrencyFormats[] = {
"$#", "#$", "$ #", "# $" };
static constexpr const char* const negCurrencyFormats[] = {
"($#)", "-$#", "$-#", "$#-",
"(#$)", "-#$", "#-$", "#$-",
"-# $", "-$ #", "# $-", "$ #-",
"$ -#", "#- $", "($ #)", "(# $)" };
static constexpr const char* const posPercentFormats[] = {
"# %", "#%", "%#", "% #"
};
static constexpr const char* const negPercentFormats[] = {
"-# %", "-#%", "-%#",
"%-#", "%#-",
"#-%", "#%-",
"-% #", "# %-", "% #-",
"% -#", "#- %"
};
static constexpr const char* const negNumberFormats[] = {
"(#)", "-#", "- #", "#-", "# -",
};
static constexpr const char posNumberFormat[] = "#";
static char ParseFormatSpecifier(String& value, int* digits) noexcept
{
assert(digits != nullptr);
if(value.IsEmpty())
{
*digits = -1;
return 'G';
}
const char* p = reinterpret_cast<const char*>(value.GetPointer());
char ch = *p;
if(ch != 0)
{
if(ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
++p;
int n = -1;
if(*p >= '0' && *p <= '9')
{
n = *p++ - '0';
while(*p >= '0' && *p <= '9')
{
n = n * 10 + *p++ - '0';
if(n > 10) break;
}
}
if(*p == 0)
{
*digits = n;
return ch;
}
}
return 0;
}
}
public:
static constexpr String FormatDouble(double& value, String& format)
{
// We are purposely using stack for this
uint8_t numberBufferByte[Number::NumberBuffer::NumberBufferBytes];
Number::NumberBuffer number(numberBufferByte);
int32_t digits;
double test;
char fmt = ParseFormatSpecifier(format, &digits);
char val = (fmt & 0xFFDF);
int precision = DOUBLE_PRECISION;
switch(val)
{
case 'R':
/* In order to give numbers that are both friendly to display and round-trippable,
* we parse the number using 15 digits and then determine if it round trips to the same
* value. If it does, we convert that NUMBER to a string, otherwise we reparse using 17 digits
* and display that.
*/
DoubleToNumber(value, DOUBLE_PRECISION, &number);
if(number.Scale == SCALE_NAN) goto lExit;
if(number.Scale == SCALE_INF) goto lExit;
Number::NumberBufferToDouble(number, &test);
if(test == value)
{
return NumberToString(&number, 'G', DOUBLE_PRECISION);
goto lExit;
}
DoubleToNumber(value, 17, &number);
return NumberToString(&number, 'G', 17);
}
}
};
#endif //CPPDATASTRUCTURES_NUMBERFORMATTER_H
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// clang-format off
#include "pch.h"
#include "webrtc.RtpReceiver.h"
#include "webrtc.RtpReceiver.g.cpp"
// clang-format on
#include "webrtc.MediaStreamTrack.h"
namespace winrt::Microsoft::WinRTC::WebRtcWrapper::webrtc::implementation
{
RtpReceiver::RtpReceiver(::rtc::scoped_refptr<::webrtc::RtpReceiverInterface> webrtc_rtp_receiver)
: webrtc_rtp_receiver_(webrtc_rtp_receiver)
{
}
Microsoft::WinRTC::WebRtcWrapper::webrtc::MediaStreamTrack
RtpReceiver::Track()
{
return make<Microsoft::WinRTC::WebRtcWrapper::webrtc::implementation::MediaStreamTrack>(
webrtc_rtp_receiver_->track());
}
} // namespace winrt::Microsoft::WinRTC::WebRtcWrapper::webrtc::implementation
|
#include "vectors.h"
#include<vector>
/*
Write a value return function get_max_from_vector with a const reference
vector of intsparameter that returns the max value in a vector
@param numbers is a const reference to a vector of integers
@return the max value in the vector
*/
int get_max_from_vector(const vector<int>& numbers)
{
int max_num = numbers[0];
for (auto& num : numbers)
{
if (num > max_num)
{
max_num = num;
}
}
return max_num;
}
/*
Write a function named is_prime with an integer parameter that
given a number returns true if prime or false if not prime
@param number: Any whole number
@return: bool if prime False if not
*/
bool is_prime(int number)
{
for (int i=2; i<number; ++i)
{
if (number%i == 0)
{
return false;
}
}
return true;
}
/*
Write a a function named vector_of_primes with an integer parameter
that given a number returns all the prime numbers up to the number
Example given number 10 returns a vector with elements 2,3,5,7,
@param int integer value
@return vector of ints containing prime values up to a value
Make sure to use the is_prime function to determine if current
number is prime.
*/
vector<int> vector_of_primes(int integer)
{
vector<int> vec_primes;
for (int i = 2; i <= integer; ++i)
{
if (is_prime(i))
{
vec_primes.push_back(i);
}
}
return vec_primes;
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/api/file_browser_handlers/file_browser_handler.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_constants.h"
#include "content/public/common/url_constants.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/url_pattern.h"
namespace keys = extensions::manifest_keys;
namespace errors = extensions::manifest_errors;
namespace {
const char kReadAccessString[] = "read";
const char kReadWriteAccessString[] = "read-write";
const char kCreateAccessString[] = "create";
unsigned int kPermissionsNotDefined = 0;
unsigned int kReadPermission = 1;
unsigned int kWritePermission = 1 << 1;
unsigned int kCreatePermission = 1 << 2;
unsigned int kInvalidPermission = 1 << 3;
unsigned int GetAccessPermissionFlagFromString(const std::string& access_str) {
if (access_str == kReadAccessString)
return kReadPermission;
if (access_str == kReadWriteAccessString)
return kReadPermission | kWritePermission;
if (access_str == kCreateAccessString)
return kCreatePermission;
return kInvalidPermission;
}
// Stored on the Extension.
struct FileBrowserHandlerInfo : public extensions::Extension::ManifestData {
FileBrowserHandler::List file_browser_handlers;
FileBrowserHandlerInfo();
virtual ~FileBrowserHandlerInfo();
};
FileBrowserHandlerInfo::FileBrowserHandlerInfo() {
}
FileBrowserHandlerInfo::~FileBrowserHandlerInfo() {
}
} // namespace
FileBrowserHandler::FileBrowserHandler()
: file_access_permission_flags_(kPermissionsNotDefined) {
}
FileBrowserHandler::~FileBrowserHandler() {
}
void FileBrowserHandler::AddPattern(const URLPattern& pattern) {
url_set_.AddPattern(pattern);
}
void FileBrowserHandler::ClearPatterns() {
url_set_.ClearPatterns();
}
bool FileBrowserHandler::MatchesURL(const GURL& url) const {
return url_set_.MatchesURL(url);
}
bool FileBrowserHandler::AddFileAccessPermission(
const std::string& access) {
file_access_permission_flags_ |= GetAccessPermissionFlagFromString(access);
return (file_access_permission_flags_ & kInvalidPermission) != 0U;
}
bool FileBrowserHandler::ValidateFileAccessPermissions() {
bool is_invalid = (file_access_permission_flags_ & kInvalidPermission) != 0U;
bool can_create = (file_access_permission_flags_ & kCreatePermission) != 0U;
bool can_read_or_write = (file_access_permission_flags_ &
(kReadPermission | kWritePermission)) != 0U;
if (is_invalid || (can_create && can_read_or_write)) {
file_access_permission_flags_ = kInvalidPermission;
return false;
}
if (file_access_permission_flags_ == kPermissionsNotDefined)
file_access_permission_flags_ = kReadPermission | kWritePermission;
return true;
}
bool FileBrowserHandler::CanRead() const {
DCHECK(!(file_access_permission_flags_ & kInvalidPermission));
return (file_access_permission_flags_ & kReadPermission) != 0;
}
bool FileBrowserHandler::CanWrite() const {
DCHECK(!(file_access_permission_flags_ & kInvalidPermission));
return (file_access_permission_flags_ & kWritePermission) != 0;
}
bool FileBrowserHandler::HasCreateAccessPermission() const {
DCHECK(!(file_access_permission_flags_ & kInvalidPermission));
return (file_access_permission_flags_ & kCreatePermission) != 0;
}
// static
FileBrowserHandler::List*
FileBrowserHandler::GetHandlers(const extensions::Extension* extension) {
FileBrowserHandlerInfo* info = static_cast<FileBrowserHandlerInfo*>(
extension->GetManifestData(keys::kFileBrowserHandlers));
if (info)
return &info->file_browser_handlers;
return NULL;
}
FileBrowserHandlerParser::FileBrowserHandlerParser() {
}
FileBrowserHandlerParser::~FileBrowserHandlerParser() {
}
namespace {
FileBrowserHandler* LoadFileBrowserHandler(
const std::string& extension_id,
const DictionaryValue* file_browser_handler,
string16* error) {
scoped_ptr<FileBrowserHandler> result(new FileBrowserHandler());
result->set_extension_id(extension_id);
std::string handler_id;
// Read the file action |id| (mandatory).
if (!file_browser_handler->HasKey(keys::kPageActionId) ||
!file_browser_handler->GetString(keys::kPageActionId, &handler_id)) {
*error = ASCIIToUTF16(errors::kInvalidPageActionId);
return NULL;
}
result->set_id(handler_id);
// Read the page action title from |default_title| (mandatory).
std::string title;
if (!file_browser_handler->HasKey(keys::kPageActionDefaultTitle) ||
!file_browser_handler->GetString(keys::kPageActionDefaultTitle, &title)) {
*error = ASCIIToUTF16(errors::kInvalidPageActionDefaultTitle);
return NULL;
}
result->set_title(title);
// Initialize access permissions (optional).
const ListValue* access_list_value = NULL;
if (file_browser_handler->HasKey(keys::kFileAccessList)) {
if (!file_browser_handler->GetList(keys::kFileAccessList,
&access_list_value) ||
access_list_value->empty()) {
*error = ASCIIToUTF16(errors::kInvalidFileAccessList);
return NULL;
}
for (size_t i = 0; i < access_list_value->GetSize(); ++i) {
std::string access;
if (!access_list_value->GetString(i, &access) ||
result->AddFileAccessPermission(access)) {
*error = extensions::ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidFileAccessValue, base::IntToString(i));
return NULL;
}
}
}
if (!result->ValidateFileAccessPermissions()) {
*error = ASCIIToUTF16(errors::kInvalidFileAccessList);
return NULL;
}
// Initialize file filters (mandatory, unless "create" access is specified,
// in which case is ignored). The list can be empty.
if (!result->HasCreateAccessPermission()) {
const ListValue* file_filters = NULL;
if (!file_browser_handler->HasKey(keys::kFileFilters) ||
!file_browser_handler->GetList(keys::kFileFilters, &file_filters)) {
*error = ASCIIToUTF16(errors::kInvalidFileFiltersList);
return NULL;
}
for (size_t i = 0; i < file_filters->GetSize(); ++i) {
std::string filter;
if (!file_filters->GetString(i, &filter)) {
*error = extensions::ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidFileFilterValue, base::IntToString(i));
return NULL;
}
StringToLowerASCII(&filter);
if (!StartsWithASCII(filter,
std::string(chrome::kFileSystemScheme) + ':',
true)) {
*error = extensions::ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidURLPatternError, filter);
return NULL;
}
// The user inputs filesystem:*; we don't actually implement scheme
// wildcards in URLPattern, so transform to what will match correctly.
filter.replace(0, 11, "chrome-extension://*/");
URLPattern pattern(URLPattern::SCHEME_EXTENSION);
if (pattern.Parse(filter) != URLPattern::PARSE_SUCCESS) {
*error = extensions::ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidURLPatternError, filter);
return NULL;
}
std::string path = pattern.path();
bool allowed = path == "/*" || path == "/*.*" ||
(path.compare(0, 3, "/*.") == 0 &&
path.find_first_of('*', 3) == std::string::npos);
if (!allowed) {
*error = extensions::ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidURLPatternError, filter);
return NULL;
}
result->AddPattern(pattern);
}
}
std::string default_icon;
// Read the file browser action |default_icon| (optional).
if (file_browser_handler->HasKey(keys::kPageActionDefaultIcon)) {
if (!file_browser_handler->GetString(
keys::kPageActionDefaultIcon, &default_icon) ||
default_icon.empty()) {
*error = ASCIIToUTF16(errors::kInvalidPageActionIconPath);
return NULL;
}
result->set_icon_path(default_icon);
}
return result.release();
}
// Loads FileBrowserHandlers from |extension_actions| into a list in |result|.
bool LoadFileBrowserHandlers(
const std::string& extension_id,
const ListValue* extension_actions,
FileBrowserHandler::List* result,
string16* error) {
for (ListValue::const_iterator iter = extension_actions->begin();
iter != extension_actions->end();
++iter) {
if (!(*iter)->IsType(Value::TYPE_DICTIONARY)) {
*error = ASCIIToUTF16(errors::kInvalidFileBrowserHandler);
return false;
}
scoped_ptr<FileBrowserHandler> action(
LoadFileBrowserHandler(
extension_id, reinterpret_cast<DictionaryValue*>(*iter), error));
if (!action.get())
return false; // Failed to parse file browser action definition.
result->push_back(linked_ptr<FileBrowserHandler>(action.release()));
}
return true;
}
} // namespace
bool FileBrowserHandlerParser::Parse(extensions::Extension* extension,
string16* error) {
const ListValue* file_browser_handlers_value = NULL;
if (!extension->manifest()->GetList(keys::kFileBrowserHandlers,
&file_browser_handlers_value)) {
*error = ASCIIToUTF16(errors::kInvalidFileBrowserHandler);
return false;
}
scoped_ptr<FileBrowserHandlerInfo> info(new FileBrowserHandlerInfo);
if (!LoadFileBrowserHandlers(extension->id(),
file_browser_handlers_value,
&info->file_browser_handlers,
error)) {
return false; // Failed to parse file browser actions definition.
}
extension->SetManifestData(keys::kFileBrowserHandlers, info.release());
return true;
}
const std::vector<std::string> FileBrowserHandlerParser::Keys() const {
return SingleKey(keys::kFileBrowserHandlers);
}
|
#include "benchmark_runner.hpp"
#include <chrono>
#include <fstream>
#include <random>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptors.hpp>
#include "cxxopts.hpp"
#include "benchmark_config.hpp"
#include "constant_mappings.hpp"
#include "hyrise.hpp"
#include "scheduler/job_task.hpp"
#include "sql/sql_pipeline_builder.hpp"
#include "storage/chunk.hpp"
#include "tpch/tpch_table_generator.hpp"
#include "utils/format_duration.hpp"
#include "utils/sqlite_wrapper.hpp"
#include "utils/timer.hpp"
#include "version.hpp"
namespace opossum {
BenchmarkRunner::BenchmarkRunner(const BenchmarkConfig& config,
std::unique_ptr<AbstractBenchmarkItemRunner> benchmark_item_runner,
std::unique_ptr<AbstractTableGenerator> table_generator, const nlohmann::json& context)
: _config(config),
_benchmark_item_runner(std::move(benchmark_item_runner)),
_table_generator(std::move(table_generator)),
_context(context) {
Hyrise::get().default_pqp_cache = std::make_shared<SQLPhysicalPlanCache>();
Hyrise::get().default_lqp_cache = std::make_shared<SQLLogicalPlanCache>();
// Initialise the scheduler if the benchmark was requested to run multi-threaded
if (config.enable_scheduler) {
Hyrise::get().topology.use_default_topology(config.cores);
std::cout << "- Multi-threaded Topology:" << std::endl;
std::cout << Hyrise::get().topology;
// Add NUMA topology information to the context, for processing in the benchmark_multithreaded.py script
auto numa_cores_per_node = std::vector<size_t>();
for (const auto& node : Hyrise::get().topology.nodes()) {
numa_cores_per_node.push_back(node.cpus.size());
}
_context.push_back({"utilized_cores_per_numa_node", numa_cores_per_node});
const auto scheduler = std::make_shared<NodeQueueScheduler>();
Hyrise::get().set_scheduler(scheduler);
}
_table_generator->generate_and_store();
_benchmark_item_runner->on_tables_loaded();
// SQLite data is only loaded if the dedicated result set is not complete, i.e,
// items exist for which no dedicated result could be loaded.
if (_config.verify && _benchmark_item_runner->has_item_without_dedicated_result()) {
std::cout << "- Loading tables into SQLite for verification." << std::endl;
Timer timer;
// Load the data into SQLite
sqlite_wrapper = std::make_shared<SQLiteWrapper>();
for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) {
std::cout << "- Loading '" << table_name << "' into SQLite " << std::flush;
Timer per_table_timer;
sqlite_wrapper->create_sqlite_table(*table, table_name);
std::cout << "(" << per_table_timer.lap_formatted() << ")" << std::endl;
}
std::cout << "- All tables loaded into SQLite (" << timer.lap_formatted() << ")" << std::endl;
_benchmark_item_runner->set_sqlite_wrapper(sqlite_wrapper);
}
}
void BenchmarkRunner::run() {
std::cout << "- Starting Benchmark..." << std::endl;
_benchmark_start = std::chrono::system_clock::now();
auto track_system_utilization = std::atomic_bool{_config.metrics};
auto system_utilization_tracker = std::thread{[&] {
if (!track_system_utilization) return;
// Start tracking the system utilization. Use a hack to make the timestamp column a long column, as CAST is not yet
// supported.
SQLPipelineBuilder{
"CREATE TABLE benchmark_system_utilization_log AS SELECT 999999999999 - 999999999999 AS \"timestamp\", * FROM "
"meta_system_utilization"}
.create_pipeline()
.get_result_table();
while (track_system_utilization) {
const auto timestamp =
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - _benchmark_start)
.count();
auto sql_builder = std::stringstream{};
sql_builder << "INSERT INTO benchmark_system_utilization_log SELECT 999999999999 - 999999999999 + " << timestamp
<< ", * FROM meta_system_utilization";
SQLPipelineBuilder{sql_builder.str()}.create_pipeline().get_result_table();
std::this_thread::sleep_for(SYSTEM_UTILIZATION_TRACKING_INTERVAL);
}
}};
if (_config.metrics) {
// Create a table for the segment access counter log
SQLPipelineBuilder{
"CREATE TABLE benchmark_segments_log AS SELECT 0 AS snapshot_id, 'init' AS moment, * FROM meta_segments"}
.create_pipeline()
.get_result_table();
}
// Retrieve the items to be executed and prepare the result vector
const auto& items = _benchmark_item_runner->items();
if (!items.empty()) {
_results = std::vector<BenchmarkItemResult>{*std::max_element(items.begin(), items.end()) + 1u};
}
switch (_config.benchmark_mode) {
case BenchmarkMode::Ordered: {
_benchmark_ordered();
break;
}
case BenchmarkMode::Shuffled: {
_benchmark_shuffled();
break;
}
}
// Create report
if (_config.output_file_path) {
if (!_config.verify && !_config.enable_visualization) {
write_report_to_file();
} else {
std::cout << "- Not writing JSON result as either verification or visualization are activated." << std::endl;
std::cout << " These options make the results meaningless." << std::endl;
}
}
// For the Ordered mode, results have already been printed to the console
if (_config.benchmark_mode == BenchmarkMode::Shuffled && !_config.verify && !_config.enable_visualization) {
for (const auto& item_id : items) {
std::cout << "- Results for " << _benchmark_item_runner->item_name(item_id) << std::endl;
std::cout << " -> Executed " << _results[item_id].successful_runs.size() << " times" << std::endl;
if (!_results[item_id].unsuccessful_runs.empty()) {
std::cout << " -> " << _results[item_id].unsuccessful_runs.size() << " additional runs failed" << std::endl;
}
}
}
// Fail if verification against SQLite was requested and failed
if (_config.verify) {
auto any_verification_failed = false;
for (const auto& item_id : items) {
const auto& result = _results[item_id];
if (result.successful_runs.empty()) continue;
Assert(result.verification_passed.load(), "Verification result should have been set");
any_verification_failed |= !(*result.verification_passed.load());
}
Assert(!any_verification_failed, "Verification failed");
}
if (Hyrise::get().scheduler()) {
Hyrise::get().scheduler()->finish();
Hyrise::get().set_scheduler(std::make_shared<ImmediateExecutionScheduler>());
}
// Stop the thread that tracks the system utilization
track_system_utilization = false;
system_utilization_tracker.join();
}
void BenchmarkRunner::_benchmark_shuffled() {
auto item_ids = _benchmark_item_runner->items();
if (const auto& weights = _benchmark_item_runner->weights(); !weights.empty()) {
auto item_ids_weighted = std::vector<BenchmarkItemID>{};
for (const auto& selected_item_id : item_ids) {
const auto item_weight = weights.at(selected_item_id);
item_ids_weighted.resize(item_ids_weighted.size() + item_weight, selected_item_id);
}
item_ids = item_ids_weighted;
}
auto item_ids_shuffled = std::vector<BenchmarkItemID>{};
for (const auto& item_id : item_ids) {
_warmup(item_id);
}
// For shuffling the item order
std::random_device random_device;
std::mt19937 random_generator(random_device());
Assert(_currently_running_clients == 0, "Did not expect any clients to run at this time");
_state = BenchmarkState{_config.max_duration};
while (_state.keep_running() && (_config.max_runs < 0 || _total_finished_runs.load(std::memory_order_relaxed) <
static_cast<size_t>(_config.max_runs))) {
// We want to only schedule as many items simultaneously as we have simulated clients
if (_currently_running_clients.load(std::memory_order_relaxed) < _config.clients) {
if (item_ids_shuffled.empty()) {
item_ids_shuffled = item_ids;
std::shuffle(item_ids_shuffled.begin(), item_ids_shuffled.end(), random_generator);
}
const auto item_id = item_ids_shuffled.back();
item_ids_shuffled.pop_back();
_schedule_item_run(item_id);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
_state.set_done();
for (auto& result : _results) {
// As the execution of benchmark items is intermingled, we use the total duration for all items
result.duration = _state.benchmark_duration;
}
// Wait for the rest of the tasks that didn't make it in time - they will not count towards the results
Hyrise::get().scheduler()->wait_for_all_tasks();
Assert(_currently_running_clients == 0, "All runs must be finished at this point");
_snapshot_segment_access_counters("End of Benchmark");
}
void BenchmarkRunner::_benchmark_ordered() {
for (const auto& item_id : _benchmark_item_runner->items()) {
_warmup(item_id);
const auto& name = _benchmark_item_runner->item_name(item_id);
std::cout << "- Benchmarking " << name << std::endl;
auto& result = _results[item_id];
Assert(_currently_running_clients == 0, "Did not expect any clients to run at this time");
_state = BenchmarkState{_config.max_duration};
while (_state.keep_running() &&
(_config.max_runs < 0 || (result.successful_runs.size() + result.unsuccessful_runs.size()) <
static_cast<size_t>(_config.max_runs))) {
// We want to only schedule as many items simultaneously as we have simulated clients
if (_currently_running_clients.load(std::memory_order_relaxed) < _config.clients) {
_schedule_item_run(item_id);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
_state.set_done();
// Wait for the rest of the tasks that didn't make it in time - they will not count toward the results
if (_currently_running_clients > 0) std::cout << " -> Waiting for clients that are still running" << std::endl;
Hyrise::get().scheduler()->wait_for_all_tasks();
Assert(_currently_running_clients == 0, "All runs must be finished at this point");
result.duration = _state.benchmark_duration;
const auto duration_of_all_runs_ns =
static_cast<float>(std::chrono::duration_cast<std::chrono::nanoseconds>(_state.benchmark_duration).count());
const auto duration_seconds = duration_of_all_runs_ns / 1'000'000'000.f;
const auto items_per_second = static_cast<float>(result.successful_runs.size()) / duration_seconds;
// Compute mean by using accumulators
boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::mean>>
accumulator;
for (const auto& entry : result.successful_runs) {
const auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(entry.duration);
accumulator(static_cast<double>(duration.count()));
}
const auto mean_in_nanoseconds = boost::accumulators::mean(accumulator);
// For readability and to be consistent with compare_benchmarks.py SQL queries should be in milliseconds
const auto mean_in_milliseconds = mean_in_nanoseconds / 1'000'000;
if (!_config.verify && !_config.enable_visualization) {
std::cout << " -> Executed " << result.successful_runs.size() << " times in " << duration_seconds
<< " seconds (Latency: " << mean_in_milliseconds << " ms/iter, Throughput: " << items_per_second
<< " iter/s)" << std::endl;
if (!result.unsuccessful_runs.empty()) {
std::cout << " -> " << result.unsuccessful_runs.size() << " additional runs failed" << std::endl;
}
}
// Taking the snapshot at this point means that both warmup runs and runs that finish after the deadline are taken
// into account, too. In light of the significant amount of data added by the snapshots to the JSON file and the
// unclear advantage of excluding those runs, we only take one snapshot here.
_snapshot_segment_access_counters(name);
}
}
void BenchmarkRunner::_schedule_item_run(const BenchmarkItemID item_id) {
_currently_running_clients++;
BenchmarkItemResult& result = _results[item_id];
auto task = std::make_shared<JobTask>(
[&, item_id]() {
const auto run_start = std::chrono::system_clock::now();
auto [success, metrics, any_run_verification_failed] = _benchmark_item_runner->execute_item(item_id);
const auto run_end = std::chrono::system_clock::now();
--_currently_running_clients;
++_total_finished_runs;
// If result.verification_passed was previously unset, set it; otherwise only invalidate it if the run failed.
result.verification_passed = result.verification_passed.load().value_or(true) && !any_run_verification_failed;
if (!_state.is_done()) { // To prevent items from adding their result after the time is up
if (!_config.metrics) metrics.clear();
const auto item_result =
BenchmarkItemRunResult{run_start - _benchmark_start, run_end - run_start, std::move(metrics)};
if (success) {
result.successful_runs.push_back(item_result);
} else {
result.unsuccessful_runs.push_back(item_result);
}
}
},
SchedulePriority::High);
task->schedule();
}
void BenchmarkRunner::_warmup(const BenchmarkItemID item_id) {
if (_config.warmup_duration == Duration{0}) return;
const auto& name = _benchmark_item_runner->item_name(item_id);
std::cout << "- Warming up for " << name << std::endl;
Assert(_currently_running_clients == 0, "Did not expect any clients to run at this time");
_state = BenchmarkState{_config.warmup_duration};
while (_state.keep_running()) {
// We want to only schedule as many items simultaneously as we have simulated clients
if (_currently_running_clients.load(std::memory_order_relaxed) < _config.clients) {
_schedule_item_run(item_id);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
// Clear the results
_results[item_id].successful_runs = {};
_results[item_id].unsuccessful_runs = {};
_results[item_id].duration = {};
_state.set_done();
// Wait for the rest of the tasks that didn't make it in time
Hyrise::get().scheduler()->wait_for_all_tasks();
Assert(_currently_running_clients == 0, "All runs must be finished at this point");
}
void BenchmarkRunner::write_report_to_file() const {
const auto total_duration = std::chrono::system_clock::now() - _benchmark_start;
nlohmann::json benchmarks;
for (const auto& item_id : _benchmark_item_runner->items()) {
const auto& name = _benchmark_item_runner->item_name(item_id);
const auto& result = _results.at(item_id);
const auto runs_to_json = [](auto runs) {
auto runs_json = nlohmann::json::array();
for (const auto& run_result : runs) {
// Convert the SQLPipelineMetrics for each run of the BenchmarkItem into JSON
auto all_pipeline_metrics_json = nlohmann::json::array();
// metrics can be empty if _config.metrics is false
for (const auto& pipeline_metrics : run_result.metrics) {
auto pipeline_metrics_json = nlohmann::json{{"parse_duration", pipeline_metrics.parse_time_nanos.count()},
{"statements", nlohmann::json::array()}};
for (const auto& sql_statement_metrics : pipeline_metrics.statement_metrics) {
nlohmann::json rule_metrics_json;
for (const auto& rule_duration : sql_statement_metrics->optimizer_rule_durations) {
rule_metrics_json[rule_duration.rule_name] += rule_duration.duration.count();
}
auto sql_statement_metrics_json =
nlohmann::json{{"sql_translation_duration", sql_statement_metrics->sql_translation_duration.count()},
{"optimization_duration", sql_statement_metrics->optimization_duration.count()},
{"optimizer_rule_durations", rule_metrics_json},
{"lqp_translation_duration", sql_statement_metrics->lqp_translation_duration.count()},
{"plan_execution_duration", sql_statement_metrics->plan_execution_duration.count()},
{"query_plan_cache_hit", sql_statement_metrics->query_plan_cache_hit}};
pipeline_metrics_json["statements"].push_back(sql_statement_metrics_json);
}
all_pipeline_metrics_json.push_back(pipeline_metrics_json);
}
runs_json.push_back(nlohmann::json{{"begin", run_result.begin.count()},
{"duration", run_result.duration.count()},
{"metrics", all_pipeline_metrics_json}});
}
return runs_json;
};
nlohmann::json benchmark{
{"name", name},
{"duration", std::chrono::duration_cast<std::chrono::nanoseconds>(result.duration).count()},
{"successful_runs", runs_to_json(result.successful_runs)},
{"unsuccessful_runs", runs_to_json(result.unsuccessful_runs)}};
// For ordered benchmarks, report the time that this individual item ran. For shuffled benchmarks, return the
// duration of the entire benchmark. This means that items_per_second of ordered and shuffled runs are not
// comparable.
const auto reported_item_duration =
_config.benchmark_mode == BenchmarkMode::Shuffled ? total_duration : result.duration;
const auto reported_item_duration_ns =
static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(reported_item_duration).count());
const auto duration_seconds = reported_item_duration_ns / 1'000'000'000.0;
const auto items_per_second =
duration_seconds > 0 ? (static_cast<double>(result.successful_runs.size()) / duration_seconds) : 0;
// The field items_per_second is relied upon by a number of visualization scripts. Carefully consider if you really
// want to touch this and potentially break the comparability across commits. Note that items_per_second only
// includes successful iterations.
benchmark["items_per_second"] = items_per_second;
benchmarks.push_back(benchmark);
}
// Gather information on the table size
auto table_size = size_t{0};
for (const auto& table_pair : Hyrise::get().storage_manager.tables()) {
table_size += table_pair.second->memory_usage(MemoryUsageCalculationMode::Full);
}
nlohmann::json summary{
{"table_size_in_bytes", table_size},
{"total_duration", std::chrono::duration_cast<std::chrono::nanoseconds>(total_duration).count()}};
const auto benchmark_start_ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(_benchmark_start.time_since_epoch()).count();
auto log_json = _sql_to_json(std::string{"SELECT \"timestamp\" - "} + std::to_string(benchmark_start_ns) +
" AS \"timestamp\", log_level, reporter, message FROM meta_log");
nlohmann::json report{{"context", _context},
{"benchmarks", std::move(benchmarks)},
{"log", std::move(log_json)},
{"summary", std::move(summary)},
{"table_generation", _table_generator->metrics}};
// Add information that was temporarily stored in the `benchmark_...` tables during the benchmark execution
if (Hyrise::get().storage_manager.has_table("benchmark_system_utilization_log")) {
report["system_utilization"] = _sql_to_json("SELECT * FROM benchmark_system_utilization_log");
}
if (Hyrise::get().storage_manager.has_table("benchmark_segments_log")) {
report["segments"] = _sql_to_json("SELECT * FROM benchmark_segments_log");
}
// Write the output file
std::ofstream{_config.output_file_path.value()} << std::setw(2) << report << std::endl;
}
cxxopts::Options BenchmarkRunner::get_basic_cli_options(const std::string& benchmark_name) {
cxxopts::Options cli_options{benchmark_name};
// Create a comma separated strings with the encoding and compression options
const auto get_first = boost::adaptors::transformed([](auto it) { return it.first; });
const auto encoding_strings_option = boost::algorithm::join(encoding_type_to_string.right | get_first, ", ");
const auto compression_strings_option =
boost::algorithm::join(vector_compression_type_to_string.right | get_first, ", ");
// Make TPC-C run in shuffled mode. While it can also run in ordered mode, it would run out of orders to fulfill at
// some point. The way this is solved here is not really nice, but as the TPC-C benchmark binary has just a main
// method and not a class, retrieving this default value properly would require some major refactoring of how
// benchmarks interact with the BenchmarkRunner. At this moment, that does not seem to be worth the effort.
const auto* const default_mode = (benchmark_name == "TPC-C Benchmark" ? "Shuffled" : "Ordered");
// clang-format off
cli_options.add_options()
("help", "print a summary of CLI options")
("full_help", "print more detailed information about configuration options")
("r,runs", "Maximum number of runs per item, negative values mean infinity", cxxopts::value<int64_t>()->default_value("-1")) // NOLINT
("c,chunk_size", "Chunk size", cxxopts::value<ChunkOffset>()->default_value(std::to_string(Chunk::DEFAULT_SIZE))) // NOLINT
("t,time", "Runtime - per item for Ordered, total for Shuffled", cxxopts::value<uint64_t>()->default_value("60")) // NOLINT
("w,warmup", "Number of seconds that each item is run for warm up", cxxopts::value<uint64_t>()->default_value("0")) // NOLINT
("o,output", "JSON file to output results to, don't specify for stdout", cxxopts::value<std::string>()->default_value("")) // NOLINT
("m,mode", "Ordered or Shuffled", cxxopts::value<std::string>()->default_value(default_mode)) // NOLINT
("e,encoding", "Specify Chunk encoding as a string or as a JSON config file (for more detailed configuration, see --full_help). String options: " + encoding_strings_option, cxxopts::value<std::string>()->default_value("Dictionary")) // NOLINT
("compression", "Specify vector compression as a string. Options: " + compression_strings_option, cxxopts::value<std::string>()->default_value("")) // NOLINT
("chunk_indexes", "Create chunk indexes (where defined by benchmark)", cxxopts::value<bool>()->default_value("false")) // NOLINT
("table_indexes", "Create table indexes (where defined by benchmark)", cxxopts::value<bool>()->default_value("false")) // NOLINT
("scheduler", "Enable or disable the scheduler", cxxopts::value<bool>()->default_value("false")) // NOLINT
("cores", "Specify the number of cores used by the scheduler (if active). 0 means all available cores", cxxopts::value<uint32_t>()->default_value("0")) // NOLINT
("clients", "Specify how many items should run in parallel if the scheduler is active", cxxopts::value<uint32_t>()->default_value("1")) // NOLINT
("visualize", "Create a visualization image of one LQP and PQP for each query, do not properly run the benchmark", cxxopts::value<bool>()->default_value("false")) // NOLINT
("verify", "Verify each query by comparing it with the SQLite result", cxxopts::value<bool>()->default_value("false")) // NOLINT
("dont_cache_binary_tables", "Do not cache tables as binary files for faster loading on subsequent runs", cxxopts::value<bool>()->default_value("false")) // NOLINT
("metrics", "Track more metrics (steps in SQL pipeline, system utilization, etc.) and add them to the output JSON (see -o)", cxxopts::value<bool>()->default_value("false")); // NOLINT
// clang-format on
return cli_options;
}
nlohmann::json BenchmarkRunner::create_context(const BenchmarkConfig& config) {
// Generate YY-MM-DD hh:mm::ss
auto current_time = std::time(nullptr);
auto local_time = *std::localtime(¤t_time);
std::stringstream timestamp_stream;
timestamp_stream << std::put_time(&local_time, "%Y-%m-%d %H:%M:%S");
// clang-format off
std::stringstream compiler;
#if defined(__clang__)
compiler << "clang " << __clang_major__ << "." << __clang_minor__ << "." << __clang_patchlevel__;
#elif defined(__GNUC__)
compiler << "gcc " << __GNUC__ << "." << __GNUC_MINOR__;
#else
compiler << "unknown";
#endif
// clang-format on
return nlohmann::json{
{"date", timestamp_stream.str()},
{"chunk_size", config.chunk_size},
{"compiler", compiler.str()},
{"build_type", HYRISE_DEBUG ? "debug" : "release"},
{"encoding", config.encoding_config.to_json()},
{"chunk_indexes", config.chunk_indexes},
{"table_indexes", config.table_indexes},
{"benchmark_mode", magic_enum::enum_name(config.benchmark_mode)},
{"max_runs", config.max_runs},
{"max_duration", std::chrono::duration_cast<std::chrono::nanoseconds>(config.max_duration).count()},
{"warmup_duration", std::chrono::duration_cast<std::chrono::nanoseconds>(config.warmup_duration).count()},
{"using_scheduler", config.enable_scheduler},
{"cores", config.cores},
{"clients", config.clients},
{"verify", config.verify},
{"time_unit", "ns"},
{"GIT-HASH", GIT_HEAD_SHA1 + std::string(GIT_IS_DIRTY ? "-dirty" : "")}};
}
nlohmann::json BenchmarkRunner::_sql_to_json(const std::string& sql) {
auto pipeline = SQLPipelineBuilder{sql}.create_pipeline();
const auto& [pipeline_status, table] = pipeline.get_result_table();
Assert(pipeline_status == SQLPipelineStatus::Success, "_sql_to_json failed");
auto output = nlohmann::json::array();
for (auto row_nr = uint64_t{0}; row_nr < table->row_count(); ++row_nr) {
auto row = table->get_row(row_nr);
auto entry = nlohmann::json{};
for (auto column_id = ColumnID{0}; column_id < table->column_count(); ++column_id) {
boost::apply_visitor(
// table=table needed because of https://stackoverflow.com/questions/46114214/
[&, table = table](const auto value) {
if constexpr (!std::is_same_v<std::decay_t<decltype(value)>, NullValue>) {
entry[table->column_name(column_id)] = value;
} else {
entry[table->column_name(column_id)] = nullptr;
}
},
row[column_id]);
}
output.emplace_back(std::move(entry));
}
return output;
}
void BenchmarkRunner::_snapshot_segment_access_counters(const std::string& moment) {
if (!_config.metrics) return;
auto moment_or_timestamp = moment;
if (moment_or_timestamp.empty()) {
const auto timestamp =
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - _benchmark_start)
.count();
moment_or_timestamp = std::to_string(timestamp);
}
++_snapshot_id;
auto sql_builder = std::stringstream{};
sql_builder << "INSERT INTO benchmark_segments_log SELECT " << _snapshot_id << ", '" << moment_or_timestamp + "'"
<< ", * FROM meta_segments WHERE table_name NOT LIKE 'benchmark%'";
SQLPipelineBuilder{sql_builder.str()}.create_pipeline().get_result_table();
}
} // namespace opossum
|
/* @flow */
// Copyright (c) 2012-2013 The PPCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include <boost/lexical_cast.hpp>
#include "db.h"
#include "kernel.h"
#include "script/interpreter.h"
#include "timedata.h"
#include "util.h"
using namespace std;
bool fTestNet = false; //Params().NetworkID() == CBaseChainParams::TESTNET;
// Modifier interval: time to elapse before new modifier is computed
// Set to 3-hour for production network and 20-minute for test network
unsigned int nModifierInterval;
int nStakeTargetSpacing = 300;
unsigned int getIntervalVersion(bool fTestNet)
{
if (fTestNet)
return MODIFIER_INTERVAL_TESTNET;
else
return MODIFIER_INTERVAL;
}
// Hard checkpoints of stake modifiers to ensure they are deterministic
static std::map<int, unsigned int> mapStakeModifierCheckpoints =
boost::assign::map_list_of(0, 0xfd11f4e7u);
// Get time weight
int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd)
{
return nIntervalEnd - nIntervalBeginning - nStakeMinAge;
}
// Get the last stake modifier and its generation time from a given block
static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime)
{
if (!pindex)
return error("GetLastStakeModifier: null pindex");
while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
pindex = pindex->pprev;
if (!pindex->GeneratedStakeModifier())
return error("GetLastStakeModifier: no generation at genesis block");
nStakeModifier = pindex->nStakeModifier;
nModifierTime = pindex->GetBlockTime();
return true;
}
// Get selection interval section (in seconds)
static int64_t GetStakeModifierSelectionIntervalSection(int nSection)
{
assert(nSection >= 0 && nSection < 64);
int64_t a = getIntervalVersion(fTestNet) * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)));
return a;
}
// Get stake modifier selection interval (in seconds)
static int64_t GetStakeModifierSelectionInterval()
{
int64_t nSelectionInterval = 0;
for (int nSection = 0; nSection < 64; nSection++) {
nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
}
return nSelectionInterval;
}
// select a block from the candidate blocks in vSortedByTimestamp, excluding
// already selected blocks in vSelectedBlocks, and with timestamp up to
// nSelectionIntervalStop.
static bool SelectBlockFromCandidates(
vector<pair<int64_t, uint256> >& vSortedByTimestamp,
map<uint256, const CBlockIndex*>& mapSelectedBlocks,
int64_t nSelectionIntervalStop,
uint64_t nStakeModifierPrev,
const CBlockIndex** pindexSelected)
{
bool fModifierV2 = false;
bool fFirstRun = true;
bool fSelected = false;
uint256 hashBest = 0;
*pindexSelected = (const CBlockIndex*)0;
BOOST_FOREACH (const PAIRTYPE(int64_t, uint256) & item, vSortedByTimestamp) {
if (!mapBlockIndex.count(item.second))
return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
const CBlockIndex* pindex = mapBlockIndex[item.second];
if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
break;
//if the lowest block height (vSortedByTimestamp[0]) is >= switch height, use new modifier calc
if (fFirstRun){
fModifierV2 = pindex->nHeight >= Params().ModifierUpgradeBlock();
fFirstRun = false;
}
if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
continue;
// compute the selection hash by hashing an input that is unique to that block
uint256 hashProof;
if(fModifierV2)
hashProof = pindex->GetBlockHash();
else
hashProof = pindex->IsProofOfStake() ? 0 : pindex->GetBlockHash();
CDataStream ss(SER_GETHASH, 0);
ss << hashProof << nStakeModifierPrev;
uint256 hashSelection = Hash(ss.begin(), ss.end());
// the selection hash is divided by 2**32 so that proof-of-stake block
// is always favored over proof-of-work block. this is to preserve
// the energy efficiency property
if (pindex->IsProofOfStake())
hashSelection >>= 32;
if (fSelected && hashSelection < hashBest) {
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
} else if (!fSelected) {
fSelected = true;
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
}
}
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
return fSelected;
}
// Stake Modifier (hash modifier of proof-of-stake):
// The purpose of stake modifier is to prevent a txout (coin) owner from
// computing future proof-of-stake generated by this txout at the time
// of transaction confirmation. To meet kernel protocol, the txout
// must hash with a future stake modifier to generate the proof.
// Stake modifier consists of bits each of which is contributed from a
// selected block of a given block group in the past.
// The selection of a block is based on a hash of the block's proof-hash and
// the previous stake modifier.
// Stake modifier is recomputed at a fixed time interval instead of every
// block. This is to make it difficult for an attacker to gain control of
// additional bits in the stake modifier, even after generating a chain of
// blocks.
bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier)
{
nStakeModifier = 0;
fGeneratedStakeModifier = false;
if (!pindexPrev) {
fGeneratedStakeModifier = true;
return true; // genesis block's modifier is 0
}
if (pindexPrev->nHeight == 0) {
//Give a stake modifier to the first block
fGeneratedStakeModifier = true;
nStakeModifier = uint64_t("stakemodifier");
return true;
}
// First find current stake modifier and its generation block time
// if it's not old enough, return the same stake modifier
int64_t nModifierTime = 0;
if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
return error("ComputeNextStakeModifier: unable to get last modifier");
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: prev modifier= %s time=%s\n", boost::lexical_cast<std::string>(nStakeModifier).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nModifierTime).c_str());
if (nModifierTime / getIntervalVersion(fTestNet) >= pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet))
return true;
// Sort candidate blocks by timestamp
vector<pair<int64_t, uint256> > vSortedByTimestamp;
vSortedByTimestamp.reserve(64 * getIntervalVersion(fTestNet) / nStakeTargetSpacing);
int64_t nSelectionInterval = GetStakeModifierSelectionInterval();
int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet)) * getIntervalVersion(fTestNet) - nSelectionInterval;
const CBlockIndex* pindex = pindexPrev;
while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) {
vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
pindex = pindex->pprev;
}
int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
// Select 64 blocks from candidate blocks to generate stake modifier
uint64_t nStakeModifierNew = 0;
int64_t nSelectionIntervalStop = nSelectionIntervalStart;
map<uint256, const CBlockIndex*> mapSelectedBlocks;
for (int nRound = 0; nRound < min(64, (int)vSortedByTimestamp.size()); nRound++) {
// add an interval section to the current selection round
nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
// select a block from the candidates of current round
if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
// write the entropy bit of the selected block
nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
// add the selected block from candidates to selected list
mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
if (fDebug || GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
nRound, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
}
// Print selection map for visualization of the selected blocks
if (fDebug || GetBoolArg("-printstakemodifier", false)) {
string strSelectionMap = "";
// '-' indicates proof-of-work blocks not selected
strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
pindex = pindexPrev;
while (pindex && pindex->nHeight >= nHeightFirstCandidate) {
// '=' indicates proof-of-stake blocks not selected
if (pindex->IsProofOfStake())
strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
pindex = pindex->pprev;
}
BOOST_FOREACH (const PAIRTYPE(uint256, const CBlockIndex*) & item, mapSelectedBlocks) {
// 'S' indicates selected proof-of-stake blocks
// 'W' indicates selected proof-of-work blocks
strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake() ? "S" : "W");
}
LogPrintf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
}
if (fDebug || GetBoolArg("-printstakemodifier", false)) {
LogPrintf("ComputeNextStakeModifier: new modifier=%s time=%s\n", boost::lexical_cast<std::string>(nStakeModifierNew).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexPrev->GetBlockTime()).c_str());
}
nStakeModifier = nStakeModifierNew;
fGeneratedStakeModifier = true;
return true;
}
// The stake modifier used to hash for a stake kernel is chosen as the stake
// modifier about a selection interval later than the coin generating the kernel
bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
{
nStakeModifier = 0;
if (!mapBlockIndex.count(hashBlockFrom))
return error("GetKernelStakeModifier() : block not indexed");
const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
nStakeModifierHeight = pindexFrom->nHeight;
nStakeModifierTime = pindexFrom->GetBlockTime();
int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
const CBlockIndex* pindex = pindexFrom;
CBlockIndex* pindexNext = chainActive[pindexFrom->nHeight + 1];
// loop to find the stake modifier later by a selection interval
while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) {
if (!pindexNext) {
// Should never happen
return error("Null pindexNext\n");
}
pindex = pindexNext;
pindexNext = chainActive[pindexNext->nHeight + 1];
if (pindex->GeneratedStakeModifier()) {
nStakeModifierHeight = pindex->nHeight;
nStakeModifierTime = pindex->GetBlockTime();
}
}
nStakeModifier = pindex->nStakeModifier;
return true;
}
uint256 stakeHash(unsigned int nTimeTx, CDataStream ss, unsigned int prevoutIndex, uint256 prevoutHash, unsigned int nTimeBlockFrom)
{
//Bitcloud will hash in the transaction hash and the index number in order to make sure each hash is unique
ss << nTimeBlockFrom << prevoutIndex << prevoutHash << nTimeTx;
return Hash(ss.begin(), ss.end());
}
//test hash vs target
bool stakeTargetHit(uint256 hashProofOfStake, int64_t nValueIn, uint256 bnTargetPerCoinDay)
{
//get the stake weight - weight is equal to coin amount
uint256 bnCoinDayWeight = uint256(nValueIn) / 100;
// Now check if proof-of-stake hash meets target protocol
return (uint256(hashProofOfStake) < bnCoinDayWeight * bnTargetPerCoinDay);
}
//instead of looping outside and reinitializing variables many times, we will give a nTimeTx and also search interval so that we can do all the hashing here
bool CheckStakeKernelHash(unsigned int nBits, const CBlock blockFrom, const CTransaction txPrev, const COutPoint prevout, unsigned int& nTimeTx, unsigned int nHashDrift, bool fCheck, uint256& hashProofOfStake, bool fPrintProofOfStake)
{
//assign new variables to make it easier to read
int64_t nValueIn = txPrev.vout[prevout.n].nValue;
unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
if (nTimeTx < nTimeBlockFrom) // Transaction timestamp violation
return error("CheckStakeKernelHash() : nTime violation");
if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
return error("CheckStakeKernelHash() : min age violation - nTimeBlockFrom=%d nStakeMinAge=%d nTimeTx=%d", nTimeBlockFrom, nStakeMinAge, nTimeTx);
//grab difficulty
uint256 bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
//grab stake modifier
uint64_t nStakeModifier = 0;
int nStakeModifierHeight = 0;
int64_t nStakeModifierTime = 0;
if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) {
LogPrintf("CheckStakeKernelHash(): failed to get kernel stake modifier \n");
return false;
}
//create data stream once instead of repeating it in the loop
CDataStream ss(SER_GETHASH, 0);
ss << nStakeModifier;
//if wallet is simply checking to make sure a hash is valid
if (fCheck) {
hashProofOfStake = stakeHash(nTimeTx, ss, prevout.n, prevout.hash, nTimeBlockFrom);
return stakeTargetHit(hashProofOfStake, nValueIn, bnTargetPerCoinDay);
}
bool fSuccess = false;
unsigned int nTryTime = 0;
unsigned int i;
for (i = 0; i < (nHashDrift); i++) //iterate the hashing
{
//hash this iteration
nTryTime = nTimeTx + nHashDrift - i;
hashProofOfStake = stakeHash(nTryTime, ss, prevout.n, prevout.hash, nTimeBlockFrom);
// if stake hash does not meet the target then continue to next iteration
if (!stakeTargetHit(hashProofOfStake, nValueIn, bnTargetPerCoinDay))
continue;
fSuccess = true; // if we make it this far then we have successfully created a stake hash
nTimeTx = nTryTime;
if (fDebug || fPrintProofOfStake) {
LogPrintf("CheckStakeKernelHash() : using modifier %s at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
boost::lexical_cast<std::string>(nStakeModifier).c_str(), nStakeModifierHeight,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nStakeModifierTime).c_str(),
mapBlockIndex[blockFrom.GetHash()]->nHeight,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", blockFrom.GetBlockTime()).c_str());
LogPrintf("CheckStakeKernelHash() : pass protocol=%s modifier=%s nTimeBlockFrom=%u prevoutHash=%s nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
"0.3",
boost::lexical_cast<std::string>(nStakeModifier).c_str(),
nTimeBlockFrom, prevout.hash.ToString().c_str(), nTimeBlockFrom, prevout.n, nTryTime,
hashProofOfStake.ToString().c_str());
}
break;
}
mapHashedBlocks.clear();
mapHashedBlocks[chainActive.Tip()->nHeight] = GetTime(); //store a time stamp of when we last hashed on this block
return fSuccess;
}
// Check kernel hash target and coinstake signature
bool CheckProofOfStake(const CBlock block, uint256& hashProofOfStake)
{
const CTransaction tx = block.vtx[1];
if (!tx.IsCoinStake())
return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
// Kernel (input 0) must match the stake hash target per coin age (nBits)
const CTxIn& txin = tx.vin[0];
// First try finding the previous transaction in database
uint256 hashBlock;
CTransaction txPrev;
if (!GetTransaction(txin.prevout.hash, txPrev, hashBlock, true))
return error("CheckProofOfStake() : INFO: read txPrev failed");
//verify signature and script
if (!VerifyScript(txin.scriptSig, txPrev.vout[txin.prevout.n].scriptPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&tx, 0)))
return error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str());
CBlockIndex* pindex = NULL;
BlockMap::iterator it = mapBlockIndex.find(hashBlock);
if (it != mapBlockIndex.end())
pindex = it->second;
else
return error("CheckProofOfStake() : read block failed");
// Read block header
CBlock blockprev;
if (!ReadBlockFromDisk(blockprev, pindex->GetBlockPos()))
return error("CheckProofOfStake(): INFO: failed to find block");
unsigned int nInterval = 0;
unsigned int nTime = block.nTime;
if (!CheckStakeKernelHash(block.nBits, blockprev, txPrev, txin.prevout, nTime, nInterval, true, hashProofOfStake, fDebug))
return error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s \n", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str()); // may occur during initial download or if behind on block chain sync
return true;
}
// Check whether the coinstake timestamp meets protocol
bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx)
{
// v0.3 protocol
return (nTimeBlock == nTimeTx);
}
// Get stake modifier checksum
unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
{
assert(pindex->pprev || pindex->GetBlockHash() == Params().HashGenesisBlock());
// Hash previous checksum with flags, hashProofOfStake and nStakeModifier
CDataStream ss(SER_GETHASH, 0);
if (pindex->pprev)
ss << pindex->pprev->nStakeModifierChecksum;
ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
uint256 hashChecksum = Hash(ss.begin(), ss.end());
hashChecksum >>= (256 - 32);
return hashChecksum.Get64();
}
// Check stake modifier hard checkpoints
bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (mapStakeModifierCheckpoints.count(nHeight)) {
return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];
}
return true;
}
|
#pragma once
#include <string>
struct Subject
{
using string = std::string;
string name;
size_t skill;
};
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#define ll long long
using namespace std;
int main() {
int n;
cin >> n;
std::vector<ll> v(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
}
sort(v.begin(), v.end());
std::vector<pair<ll, ll> > vpii;
ll minDiff = -1;
for (int i = 1; i < n; ++i) {
int diff = v[i] - v[i - 1];
pair<ll, ll> p = make_pair(v[i - 1], v[i]);
if (vpii.empty()) {
minDiff = diff;
vpii.push_back(p);
continue;
}
if (diff == minDiff) {
vpii.push_back(p);
} else if (diff < minDiff) {
minDiff = diff;
vpii.clear();
vpii.push_back(p);
}
}
for (pair<ll, ll> p : vpii) {
cout << p.first << " " << p.second << " ";
}
printf("\n");
return 0;
}
|
// Copyright Carl Philipp Reh 2009 - 2018.
// 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 FCPPT_ASSERT_BASIC_UNCONDITIONAL_MESSAGE_HPP_INCLUDED
#define FCPPT_ASSERT_BASIC_UNCONDITIONAL_MESSAGE_HPP_INCLUDED
#include <fcppt/assert/basic/message_and_action.hpp>
#include <fcppt/assert/basic/unconditional.hpp>
/**
\brief Takes an unconditional action, also printing a message
\ingroup fcpptassert
Takes the unconditional action \a action, also printing a message with \a
reason and \a message.
\param reason The reason for the assertion to fail
\param message The message to print
\param action The action to take
*/
#define FCPPT_ASSERT_BASIC_UNCONDITIONAL_MESSAGE(\
reason,\
message,\
action\
) \
FCPPT_ASSERT_BASIC_MESSAGE_AND_ACTION(\
FCPPT_ASSERT_BASIC_UNCONDITIONAL,\
message,\
reason,\
action \
)
#endif
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "ignite/impl/binary/binary_type_updater_impl.h"
#include "ignite/impl/interop/interop_output_stream.h"
#include "ignite/impl/binary/binary_writer_impl.h"
#include "ignite/binary/binary_raw_writer.h"
using namespace ignite::common::concurrent;
using namespace ignite::jni::java;
using namespace ignite::java;
using namespace ignite::impl;
using namespace ignite::impl::interop;
using namespace ignite::binary;
namespace ignite
{
namespace impl
{
namespace binary
{
/** Operation: metadata update. */
const int32_t OP_PUT_META = 3;
BinaryTypeUpdaterImpl::BinaryTypeUpdaterImpl(IgniteEnvironment& env, jobject javaRef) :
env(env),
javaRef(javaRef)
{
// No-op.
}
BinaryTypeUpdaterImpl::~BinaryTypeUpdaterImpl()
{
JniContext::Release(javaRef);
}
bool BinaryTypeUpdaterImpl::Update(Snap* snap, IgniteError* err)
{
JniErrorInfo jniErr;
SharedPointer<InteropMemory> mem = env.AllocateMemory();
InteropOutputStream out(mem.Get());
BinaryWriterImpl writer(&out, NULL);
BinaryRawWriter rawWriter(&writer);
// We always pass only one meta at a time in current implementation for simplicity.
rawWriter.WriteInt32(1);
rawWriter.WriteInt32(snap->GetTypeId());
rawWriter.WriteString(snap->GetTypeName());
rawWriter.WriteString(NULL); // Affinity key is not supported for now.
if (snap->HasFields())
{
std::map<std::string, int32_t>* fields = snap->GetFields();
rawWriter.WriteInt32(static_cast<int32_t>(fields->size()));
for (std::map<std::string, int32_t>::iterator it = fields->begin(); it != fields->end(); ++it)
{
rawWriter.WriteString(it->first);
rawWriter.WriteInt32(it->second);
}
}
else
rawWriter.WriteInt32(0);
rawWriter.WriteBool(false); // Enums are not supported for now.
rawWriter.WriteInt32(0); // Schema size. Compact schema footer is not yet supported.
out.Synchronize();
long long res = env.Context()->TargetInStreamOutLong(javaRef, OP_PUT_META, mem.Get()->PointerLong(), &jniErr);
IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
if (jniErr.code == IGNITE_JNI_ERR_SUCCESS)
return res == 1;
else
return false;
}
}
}
}
|
/* 用时12分 */
//思路就是找最小的时间点tmin和最大的时间点tmax,找交集
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 2005;
const int MAXT = 1000005;
int tmap[MAXT]; //记录所有时刻
int n;
int main()
{
int ans = 0;
cin >> n;
for (int i = 1; i <= n; i++)
{
int a, b;
cin >> a >> b;
for (int j = a; j < b; j++)
{
tmap[j]++;
}
}
for (int i = 1; i <= n; i++)
{
int c, d;
cin >> c >> d;
for (int j = c; j < d; j++)
{
if (tmap[j] == 1)
{
ans++;
}
}
}
cout << ans << endl;
return 0;
}
/*
4
1 3
5 6
9 13
14 15
2 4
5 7
10 11
13 14
*/
|
#include <star-tape/tape_file_proxy.hpp>
#include <star-tape/tape_operation.hpp>
namespace StarTape
{
//#####################################################################################################################
//#####################################################################################################################
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/medialive/model/Offering.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace MediaLive
{
namespace Model
{
Offering::Offering() :
m_arnHasBeenSet(false),
m_currencyCodeHasBeenSet(false),
m_duration(0),
m_durationHasBeenSet(false),
m_durationUnits(OfferingDurationUnits::NOT_SET),
m_durationUnitsHasBeenSet(false),
m_fixedPrice(0.0),
m_fixedPriceHasBeenSet(false),
m_offeringDescriptionHasBeenSet(false),
m_offeringIdHasBeenSet(false),
m_offeringType(OfferingType::NOT_SET),
m_offeringTypeHasBeenSet(false),
m_regionHasBeenSet(false),
m_resourceSpecificationHasBeenSet(false),
m_usagePrice(0.0),
m_usagePriceHasBeenSet(false)
{
}
Offering::Offering(JsonView jsonValue) :
m_arnHasBeenSet(false),
m_currencyCodeHasBeenSet(false),
m_duration(0),
m_durationHasBeenSet(false),
m_durationUnits(OfferingDurationUnits::NOT_SET),
m_durationUnitsHasBeenSet(false),
m_fixedPrice(0.0),
m_fixedPriceHasBeenSet(false),
m_offeringDescriptionHasBeenSet(false),
m_offeringIdHasBeenSet(false),
m_offeringType(OfferingType::NOT_SET),
m_offeringTypeHasBeenSet(false),
m_regionHasBeenSet(false),
m_resourceSpecificationHasBeenSet(false),
m_usagePrice(0.0),
m_usagePriceHasBeenSet(false)
{
*this = jsonValue;
}
Offering& Offering::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("arn"))
{
m_arn = jsonValue.GetString("arn");
m_arnHasBeenSet = true;
}
if(jsonValue.ValueExists("currencyCode"))
{
m_currencyCode = jsonValue.GetString("currencyCode");
m_currencyCodeHasBeenSet = true;
}
if(jsonValue.ValueExists("duration"))
{
m_duration = jsonValue.GetInteger("duration");
m_durationHasBeenSet = true;
}
if(jsonValue.ValueExists("durationUnits"))
{
m_durationUnits = OfferingDurationUnitsMapper::GetOfferingDurationUnitsForName(jsonValue.GetString("durationUnits"));
m_durationUnitsHasBeenSet = true;
}
if(jsonValue.ValueExists("fixedPrice"))
{
m_fixedPrice = jsonValue.GetDouble("fixedPrice");
m_fixedPriceHasBeenSet = true;
}
if(jsonValue.ValueExists("offeringDescription"))
{
m_offeringDescription = jsonValue.GetString("offeringDescription");
m_offeringDescriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("offeringId"))
{
m_offeringId = jsonValue.GetString("offeringId");
m_offeringIdHasBeenSet = true;
}
if(jsonValue.ValueExists("offeringType"))
{
m_offeringType = OfferingTypeMapper::GetOfferingTypeForName(jsonValue.GetString("offeringType"));
m_offeringTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("region"))
{
m_region = jsonValue.GetString("region");
m_regionHasBeenSet = true;
}
if(jsonValue.ValueExists("resourceSpecification"))
{
m_resourceSpecification = jsonValue.GetObject("resourceSpecification");
m_resourceSpecificationHasBeenSet = true;
}
if(jsonValue.ValueExists("usagePrice"))
{
m_usagePrice = jsonValue.GetDouble("usagePrice");
m_usagePriceHasBeenSet = true;
}
return *this;
}
JsonValue Offering::Jsonize() const
{
JsonValue payload;
if(m_arnHasBeenSet)
{
payload.WithString("arn", m_arn);
}
if(m_currencyCodeHasBeenSet)
{
payload.WithString("currencyCode", m_currencyCode);
}
if(m_durationHasBeenSet)
{
payload.WithInteger("duration", m_duration);
}
if(m_durationUnitsHasBeenSet)
{
payload.WithString("durationUnits", OfferingDurationUnitsMapper::GetNameForOfferingDurationUnits(m_durationUnits));
}
if(m_fixedPriceHasBeenSet)
{
payload.WithDouble("fixedPrice", m_fixedPrice);
}
if(m_offeringDescriptionHasBeenSet)
{
payload.WithString("offeringDescription", m_offeringDescription);
}
if(m_offeringIdHasBeenSet)
{
payload.WithString("offeringId", m_offeringId);
}
if(m_offeringTypeHasBeenSet)
{
payload.WithString("offeringType", OfferingTypeMapper::GetNameForOfferingType(m_offeringType));
}
if(m_regionHasBeenSet)
{
payload.WithString("region", m_region);
}
if(m_resourceSpecificationHasBeenSet)
{
payload.WithObject("resourceSpecification", m_resourceSpecification.Jsonize());
}
if(m_usagePriceHasBeenSet)
{
payload.WithDouble("usagePrice", m_usagePrice);
}
return payload;
}
} // namespace Model
} // namespace MediaLive
} // namespace Aws
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "../shared/shared.h"
DECLARATIVE_EXAMPLE_MAIN(draganddrop/draganddrop)
|
#include "test/test_bitcoin.h"
#include "script/interpreter.h"
#include "script/standard.h"
#include "script/sign.h"
#include "validation.h"
#include "zerocoin.h"
#include "netbase.h"
#include "keystore.h"
#include "base58.h"
#include "evo/specialtx.h"
#include <boost/test/unit_test.hpp>
typedef std::map<COutPoint, std::pair<int, CAmount>> SimpleUTXOMap;
static SimpleUTXOMap BuildSimpleUtxoMap(const std::vector<CTransaction>& txs)
{
SimpleUTXOMap utxos;
CAmount balance = 0;
for (size_t i = 0; i < txs.size(); i++) {
auto& tx = txs[i];
size_t const indexnode_output = tx.vout.size() > 6 ? FindZnodeOutput(tx) : 0;
for (size_t j = 0; j < tx.vout.size(); j++) {
if(j == 0 || j == indexnode_output) {
balance += tx.vout[j].nValue;
utxos.emplace(COutPoint(tx.GetHash(), j), std::make_pair((int)i + 1, tx.vout[j].nValue));
}
}
}
return utxos;
}
static std::vector<COutPoint> SelectUTXOs(SimpleUTXOMap& utoxs, CAmount amount, CAmount& changeRet)
{
changeRet = 0;
std::vector<COutPoint> selectedUtxos;
CAmount selectedAmount = 0;
while (!utoxs.empty()) {
bool found = false;
for (auto it = utoxs.begin(); it != utoxs.end(); ++it) {
if (chainActive.Height() - it->second.first < 101) {
continue;
}
found = true;
selectedAmount += it->second.second;
selectedUtxos.emplace_back(it->first);
utoxs.erase(it);
break;
}
BOOST_ASSERT(found);
if (selectedAmount >= amount) {
changeRet = selectedAmount - amount;
break;
}
}
return selectedUtxos;
}
static void FundTransaction(CMutableTransaction& tx, SimpleUTXOMap& utoxs, const CScript& scriptPayout, CAmount amount, const CKey& coinbaseKey)
{
CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
CAmount change;
auto inputs = SelectUTXOs(utoxs, amount, change);
for (size_t i = 0; i < inputs.size(); i++) {
tx.vin.emplace_back(CTxIn(inputs[i]));
}
tx.vout.emplace_back(CTxOut(amount, scriptPayout));
if (change != 0) {
tx.vout.emplace_back(CTxOut(change, scriptPayout));
}
}
static void SignTransaction(CMutableTransaction& tx, const CKey& coinbaseKey)
{
CBasicKeyStore tempKeystore;
tempKeystore.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
for (size_t i = 0; i < tx.vin.size(); i++) {
CTransactionRef txFrom;
uint256 hashBlock;
BOOST_ASSERT(GetTransaction(tx.vin[i].prevout.hash, txFrom, Params().GetConsensus(), hashBlock));
bool result = SignSignature(tempKeystore, *txFrom, tx, i, SIGHASH_ALL);
if(!result)
std::cerr << i << std::endl;
}
}
static CMutableTransaction CreateProRegTx(SimpleUTXOMap& utxos, int port, const CScript& scriptPayout, const CKey& coinbaseKey, CKey& ownerKeyRet, CBLSSecretKey& operatorKeyRet)
{
ownerKeyRet.MakeNewKey(true);
operatorKeyRet.MakeNewKey();
CAmount change;
auto inputs = SelectUTXOs(utxos, 5000 * COIN, change);
CProRegTx proTx;
proTx.collateralOutpoint.n = 0;
proTx.addr = LookupNumeric("1.1.1.1", port);
proTx.keyIDOwner = ownerKeyRet.GetPubKey().GetID();
proTx.pubKeyOperator = operatorKeyRet.GetPublicKey();
proTx.keyIDVoting = ownerKeyRet.GetPubKey().GetID();
proTx.scriptPayout = scriptPayout;
CMutableTransaction tx;
tx.nVersion = 3;
tx.nType = TRANSACTION_PROVIDER_REGISTER;
FundTransaction(tx, utxos, scriptPayout, 5000 * COIN, coinbaseKey);
proTx.inputsHash = CalcTxInputsHash(tx);
SetTxPayload(tx, proTx);
SignTransaction(tx, coinbaseKey);
return tx;
}
static CScript GenerateRandomAddress()
{
CKey key;
key.MakeNewKey(false);
return GetScriptForDestination(key.GetPubKey().GetID());
}
static CDeterministicMNCPtr FindPayoutDmn(const CBlock& block, CAmount &nValue)
{
auto dmnList = deterministicMNManager->GetListAtChainTip();
for (const auto& txout : block.vtx[0]->vout) {
CDeterministicMNCPtr found;
dmnList.ForEachMN(true, [&](const CDeterministicMNCPtr& dmn) {
if (found == nullptr && txout.scriptPubKey == dmn->pdmnState->scriptPayout) {
found = dmn;
nValue = txout.nValue;
}
});
if (found != nullptr) {
return found;
}
}
return nullptr;
}
BOOST_AUTO_TEST_SUITE(firsthalving)
BOOST_FIXTURE_TEST_CASE(devpayout, TestChainDIP3BeforeActivationSetup)
{
Consensus::Params &consensusParams = const_cast<Consensus::Params &>(Params().GetConsensus());
Consensus::Params consensusParamsBackup = consensusParams;
// Simulate testnet (and its founders' reward)
consensusParams.chainType = Consensus::chainTestnet;
consensusParams.nSubsidyHalvingFirst = 600;
consensusParams.nSubsidyHalvingInterval = 10;
consensusParams.nSubsidyHalvingStopBlock = 1000;
CScript devPayoutScript = GenerateRandomAddress();
CTxDestination devPayoutDest{CScriptID(devPayoutScript)};
consensusParams.stage2DevelopmentFundAddress = CBitcoinAddress(devPayoutDest).ToString();
auto utxos = BuildSimpleUtxoMap(coinbaseTxns);
// we're at block 498, skip to block 499
for (int i=498; i<499; i++)
CreateAndProcessBlock({}, coinbaseKey);
CKey ownerKey;
CBLSSecretKey operatorSecretKey;
CScript indexnodePayoutScript = GenerateRandomAddress();
auto tx = CreateProRegTx(utxos, 4444, indexnodePayoutScript, coinbaseKey, ownerKey, operatorSecretKey);
CreateAndProcessBlock({tx}, coinbaseKey);
deterministicMNManager->UpdatedBlockTip(chainActive.Tip());
// we're at block 500, skip to 549
for (int i=500; i<549; i++) {
CreateAndProcessBlock({}, coinbaseKey);
deterministicMNManager->UpdatedBlockTip(chainActive.Tip());
}
// blocks 550 through 599
for (int i=550; i<600; i++) {
CBlock block = CreateAndProcessBlock({}, coinbaseKey);
deterministicMNManager->UpdatedBlockTip(chainActive.Tip());
CAmount nValue;
auto dmnPayout = FindPayoutDmn(block, nValue);
auto dmnExpectedPayee = deterministicMNManager->GetListAtChainTip().GetMNPayee();
BOOST_ASSERT(dmnPayout != nullptr);
BOOST_CHECK_EQUAL(dmnPayout->proTxHash.ToString(), dmnExpectedPayee->proTxHash.ToString());
CValidationState state;
BOOST_ASSERT(CheckZerocoinFoundersInputs(*block.vtx[0], state, consensusParams, chainActive.Height()));
BOOST_ASSERT(nValue == 15*COIN); // indexnode reward before the first halving
}
// halving occurs at block 600
// devs fund is valid until second block halving at block 610
for (int i=600; i<610; i++) {
CBlock block = CreateAndProcessBlock({}, coinbaseKey);
deterministicMNManager->UpdatedBlockTip(chainActive.Tip());
CAmount nValue;
auto dmnPayout = FindPayoutDmn(block, nValue);
BOOST_ASSERT(dmnPayout != nullptr && nValue == 875*COIN/100); // 8.75 after halving (25*0.35)
bool paymentToDevFound = false;
for (const CTxOut &txout: block.vtx[0]->vout) {
if (txout.scriptPubKey == GetScriptForDestination(CBitcoinAddress(consensusParams.stage2DevelopmentFundAddress).Get())) {
BOOST_ASSERT(txout.nValue == 375*COIN/100); // 25*0.15
paymentToDevFound = true;
}
}
BOOST_ASSERT(paymentToDevFound);
}
CBlock block = CreateAndProcessBlock({}, coinbaseKey);
deterministicMNManager->UpdatedBlockTip(chainActive.Tip());
CAmount nValue;
auto dmnPayout = FindPayoutDmn(block, nValue);
BOOST_ASSERT(dmnPayout != nullptr && nValue == 4375*COIN/1000); // 4.375 (12.5*0.35)
// there should be no more payment to devs fund
for (const CTxOut &txout: block.vtx[0]->vout) {
BOOST_ASSERT(txout.scriptPubKey != GetScriptForDestination(CBitcoinAddress(consensusParams.stage2DevelopmentFundAddress).Get()));
}
// miner's reward should be 12.5-4.375 = 8.125
BOOST_ASSERT(block.vtx[0]->vout[0].nValue == 8125*COIN/1000);
// should be only 2 vouts in coinbase
BOOST_ASSERT(block.vtx[0]->vout.size() == 2);
consensusParams = consensusParamsBackup;
}
/* No Devfee on IDX
BOOST_FIXTURE_TEST_CASE(devpayoutverification, TestChainDIP3BeforeActivationSetup)
{
Consensus::Params &consensusParams = const_cast<Consensus::Params &>(Params().GetConsensus());
Consensus::Params consensusParamsBackup = consensusParams;
consensusParams.nSubsidyHalvingFirst = 600;
consensusParams.nSubsidyHalvingInterval = 10;
consensusParams.nSubsidyHalvingStopBlock = 1000;
// skip to block 600
for (int i=498; i<600; i++)
CreateAndProcessBlock({}, coinbaseKey);
// try to send dev payout to different destination
CKey key;
key.MakeNewKey(false);
consensusParams.stage2DevelopmentFundAddress = CBitcoinAddress(CTxDestination(key.GetPubKey().GetID())).ToString();
{
CBlock block = CreateBlock({}, coinbaseKey);
consensusParams.stage2DevelopmentFundAddress = consensusParamsBackup.stage2DevelopmentFundAddress;
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
BOOST_ASSERT(!ProcessNewBlock(Params(), shared_pblock, true, nullptr));
}
// now try to alter payment value
{
consensusParams.stage2DevelopmentFundShare /= 2;
CBlock block = CreateBlock({}, coinbaseKey);
consensusParams.stage2DevelopmentFundShare = consensusParamsBackup.stage2DevelopmentFundShare;
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
BOOST_ASSERT(!ProcessNewBlock(Params(), shared_pblock, true, nullptr));
}
// now try to alter payment value
{
consensusParams.stage2DevelopmentFundShare *= 2;
CBlock block = CreateBlock({}, coinbaseKey);
consensusParams.stage2DevelopmentFundShare = consensusParamsBackup.stage2DevelopmentFundShare;
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
BOOST_ASSERT(!ProcessNewBlock(Params(), shared_pblock, true, nullptr));
}
consensusParams = consensusParamsBackup;
}
*/
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2018 PaddlePaddle Authors. All 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.
#include <algorithm>
#include <array>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "paddle/fluid/framework/ir/graph_helper.h"
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/ir/graph_traits.h"
#include "paddle/fluid/framework/ir/graph_viz_pass.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/string/pretty_log.h"
#include "paddle/fluid/string/printf.h"
namespace paddle {
namespace framework {
namespace ir {
using string::PrettyLog;
using string::Style;
size_t PDPattern::id_ = 0UL;
PDNode *PDPattern::NewNode(const std::string &name) {
if (!name.empty()) {
PADDLE_ENFORCE_EQ(
node_map_.count(name), 0UL,
platform::errors::PreconditionNotMet(
"PDNode's name should be unique, get duplicate [%s]", name));
}
nodes_.emplace_back(new PDNode(this, name));
auto *cur = nodes_.back().get();
node_map_[name] = cur;
return cur;
}
PDNode *PDPattern::NewNode(PDNode::teller_t &&teller, const std::string &name) {
if (!name.empty()) {
PADDLE_ENFORCE_EQ(
node_map_.count(name), 0UL,
platform::errors::PreconditionNotMet(
"PDNode's name should be unique, get duplicate [%s]", name));
}
nodes_.emplace_back(new PDNode(std::move(teller), this, name));
auto *cur = nodes_.back().get();
node_map_[name] = cur;
return cur;
}
PDNode *PDPattern::RetrieveNode(const std::string &id) const {
auto it = node_map_.find(id);
if (it == node_map_.end()) {
return nullptr;
}
return it->second;
}
void PDPattern::AddEdge(PDNode *a, PDNode *b) {
PADDLE_ENFORCE_NOT_NULL(
a, platform::errors::NotFound("PDNode %s is not found.", a->name()));
PADDLE_ENFORCE_NOT_NULL(
b, platform::errors::NotFound("PDNode %s is not found.", b->name()));
PADDLE_ENFORCE_NE(a, b, platform::errors::PermissionDenied(
"Cannot connect the same node in the graph."));
edges_.emplace_back(a, b);
}
void GraphPatternDetector::operator()(Graph *graph,
GraphPatternDetector::handle_t handler) {
if (!MarkPDNodesInGraph(*graph)) {
return;
}
auto subgraphs = DetectPatterns();
UniquePatterns(&subgraphs);
RemoveOverlappedMatch(&subgraphs);
ValidateByNodeRole(&subgraphs);
if (subgraphs.empty()) return;
LOG(INFO) << "--- detected " << subgraphs.size() << " subgraphs";
int id = 0;
for (auto &g : subgraphs) {
VLOG(3) << "optimizing #" << id++ << " subgraph";
handler(g, graph);
}
}
bool GraphPatternDetector::MarkPDNodesInGraph(const ir::Graph &graph) {
VLOG(3) << "mark pdnodes in graph";
if (graph.Nodes().empty()) return false;
for (auto &node : GraphTraits::DFS(graph)) {
for (const auto &pdnode : pattern_.nodes()) {
if (pdnode->Tell(&node)) {
VLOG(4) << "Node " << node.Name() << " marked as " << pdnode->name();
pdnodes2nodes_[pdnode.get()].insert(&node);
}
}
}
// Check to early stop if some PDNode can't find matched Node.
for (auto &pdnode : pattern_.nodes()) {
if (!pdnodes2nodes_.count(pdnode.get())) {
VLOG(4) << pdnode->name() << " can't find matched Node, early stop";
// return false;
}
}
VLOG(3) << pdnodes2nodes_.size() << " nodes marked";
return !pdnodes2nodes_.empty();
}
// The intermediate Nodes can only link to the nodes inside the pattern, or this
// subgraph will be dropped.
void GraphPatternDetector::ValidateByNodeRole(
std::vector<GraphPatternDetector::subgraph_t> *subgraphs) {
std::vector<GraphPatternDetector::subgraph_t> result;
subgraphs->erase(
std::remove_if(
subgraphs->begin(), subgraphs->end(),
[](const GraphPatternDetector::subgraph_t &subgraph) -> bool {
// Collect the inputs and outputs.
std::set<Node *> ios;
for (auto &item : subgraph) {
if (!item.first->IsIntermediate()) {
ios.insert(item.second);
}
}
for (auto &item : subgraph) {
if (item.first->IsIntermediate()) {
for (auto *x : item.second->inputs) {
if (!ios.count(x)) {
return true;
}
}
for (auto *x : item.second->outputs) {
if (!ios.count(x)) {
return true;
}
}
}
}
return false;
}),
subgraphs->end());
}
struct HitGroup {
std::map<PDNode *, Node *> roles;
bool Match(Node *node, PDNode *pat) {
if (nodes_.count(node)) {
if (roles.count(pat) && roles[pat] == node) return true;
return false;
} else {
if (roles.count(pat) && roles[pat] != node) return false;
return true;
}
}
void Register(Node *node, PDNode *pat) {
roles[pat] = node;
nodes_.insert(node);
}
private:
std::set<Node *> nodes_;
};
// Tell whether Node a links to b.
bool IsNodesLink(Node *a, Node *b) {
for (auto *node : a->outputs) {
if (b == node) {
return true;
}
}
return false;
}
std::vector<GraphPatternDetector::subgraph_t>
GraphPatternDetector::DetectPatterns() {
// Init empty subgraphs.
std::vector<GraphPatternDetector::subgraph_t> result;
std::vector<HitGroup> init_groups;
std::array<std::vector<HitGroup>, 2> bi_records;
auto *first_pnode = pattern_.edges().empty() ? pattern().nodes().front().get()
: pattern_.edges().front().first;
if (!pdnodes2nodes_.count(first_pnode)) return result;
for (auto *node : pdnodes2nodes_[first_pnode]) {
HitGroup group;
group.roles[first_pnode] = node;
init_groups.emplace_back(group);
}
int step = 0;
bi_records[0] = std::move(init_groups);
// Extend a PDNode to subgraphs by deducing the connection relations defined
// in edges of PDNodes.
for (const auto &edge : pattern_.edges()) {
VLOG(4) << "check " << edge.first->name() << " -> " << edge.second->name();
// TODO(Superjomn) Fix bug here, the groups might be duplicate here.
// Each role has two PDNodes, which indicates two roles.
// Detect two Nodes that can match these two roles and they are connected.
auto &pre_groups = bi_records[step % 2];
auto &cur_groups = bi_records[1 - (step++ % 2)];
cur_groups.clear();
if (pre_groups.empty()) break;
// source -> target
for (Node *source : pdnodes2nodes_[edge.first]) {
for (Node *target : pdnodes2nodes_[edge.second]) {
VLOG(8) << "check " << source->id() << " -- " << target->id();
// TODO(Superjomn) add some prune strategies.
for (const auto &group : pre_groups) {
if (IsNodesLink(source, target)) {
HitGroup new_group = group;
bool flag = new_group.Match(source, edge.first) &&
new_group.Match(target, edge.second);
if (flag) {
new_group.Register(source, edge.first);
new_group.Register(target, edge.second);
cur_groups.push_back(new_group);
// TODO(Superjomn) need to unique
}
}
}
}
}
VLOG(3) << "step " << step << " get records: " << cur_groups.size();
for (auto &group : cur_groups) {
for (auto &item : group.roles) {
VLOG(4) << "node " << item.second->id() << " as " << item.first->name();
}
VLOG(4) << "=========================================================";
}
}
for (auto &group : bi_records[step % 2]) {
GraphPatternDetector::subgraph_t subgraph;
for (auto &role : group.roles) {
subgraph.emplace(role.first, role.second);
}
result.emplace_back(subgraph);
}
return result;
}
struct GraphItemLessThan {
bool operator()(const std::pair<PDNode *, Node *> &a,
const std::pair<PDNode *, Node *> &b) {
if (a.first != b.first) {
return a.first < b.first;
} else {
return a.second < b.second;
}
}
};
// TODO(Superjomn) enhance the function as it marks unique unique as duplicates
// see https://github.com/PaddlePaddle/Paddle/issues/13550
void GraphPatternDetector::UniquePatterns(
std::vector<GraphPatternDetector::subgraph_t> *subgraphs) {
if (subgraphs->empty()) return;
std::vector<GraphPatternDetector::subgraph_t> result;
std::set<size_t> set;
std::hash<std::string> hasher;
for (auto &g : *subgraphs) {
// Sort the items in the sub-graph, and transform to a string key.
std::vector<std::pair<PDNode *, Node *>> sorted_keys(g.begin(), g.end());
std::sort(sorted_keys.begin(), sorted_keys.end(), GraphItemLessThan());
std::stringstream ss;
for (auto &item : sorted_keys) {
ss << item.first << ":" << item.second;
}
auto key = hasher(ss.str());
if (!set.count(key)) {
result.emplace_back(g);
set.insert(key);
}
}
*subgraphs = result;
}
void GraphPatternDetector::RemoveOverlappedMatch(
std::vector<subgraph_t> *subgraphs) {
std::vector<subgraph_t> result;
std::set<Node *> node_set;
for (const auto &subgraph : *subgraphs) {
bool valid = true;
for (auto &item : subgraph) {
if (item.first->IsIntermediate() && node_set.count(item.second)) {
valid = false;
break;
}
}
if (valid) {
for (auto &item : subgraph) {
node_set.insert(item.second);
}
result.push_back(subgraph);
}
}
*subgraphs = result;
}
std::string PDPattern::DotString() const {
using inference::analysis::Dot;
Dot dot;
int id = 0;
// Create Nodes
std::unordered_map<PDNode *, std::string> node2dot;
for (const auto &node : nodes()) {
std::string node_id = "Node" + std::to_string(id++);
dot.AddNode(node_id, {}, node->name());
node2dot[node.get()] = node_id;
}
// Create Edges
for (const auto &edge : edges()) {
if (!node2dot.count(edge.first) || !node2dot.count(edge.second)) {
LOG(ERROR) << "no node " << edge.first << " " << edge.second;
continue;
}
auto &src = node2dot.at(edge.first);
auto &trg = node2dot.at(edge.second);
dot.AddEdge(src, trg, {});
}
return dot.Build();
}
PDNode &PDNode::LinksTo(const std::vector<PDNode *> &others) {
// extend outlinks.
for (PDNode *x : others) {
pattern_->AddEdge(this, x);
}
return *this;
}
PDNode &PDNode::LinksFrom(const std::vector<PDNode *> &others) {
// extend outlinks.
for (PDNode *x : others) {
pattern_->AddEdge(x, this);
}
return *this;
}
PDNode *PDNode::assert_is_op() {
asserts_.emplace_back([](Node *x) { return x && x->IsOp(); });
return this;
}
PDNode *PDNode::assert_is_op(const std::string &op_type) {
asserts_.emplace_back([op_type](Node *x) {
return x && x->IsOp() && x->Op()->Type() == op_type;
});
return this;
}
PDNode *PDNode::assert_is_var() {
asserts_.emplace_back([](Node *x) { return x && x->IsVar(); });
return this;
}
PDNode *PDNode::assert_var_dtype(proto::VarType::Type dtype) {
assert_is_var();
asserts_.emplace_back(
[dtype](Node *x) { return x->Var()->GetDataType() == dtype; });
return this;
}
PDNode *PDNode::assert_is_not_ctrl_var() {
asserts_.emplace_back([](Node *x) { return x && !x->IsCtrlVar(); });
return this;
}
PDNode *PDNode::assert_var_not_persistable() {
assert_is_var();
asserts_.emplace_back([](Node *x) { return !x->Var()->Persistable(); });
return this;
}
PDNode *PDNode::assert_is_persistable_var() {
assert_is_var();
asserts_.emplace_back([=](Node *x) { return x->Var()->Persistable(); });
return this;
}
PDNode *PDNode::assert_is_op_nth_input(const std::string &op_type,
const std::string &argument, int nth) {
assert_is_var();
assert_is_op_input(op_type);
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->outputs) {
if (op->IsOp() && op->Op()->Type() == op_type &&
IsNthInput(x, op, argument, nth))
return true;
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_op_nth_output(const std::string &op_type,
const std::string &argument, int nth) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->inputs) {
if (op->IsOp() && op->Op()->Type() == op_type &&
IsNthOutput(x, op, argument, nth))
return true;
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_only_input_of_op(const std::string &op_type) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->outputs) {
if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
op->inputs.size() == 1) {
return true;
}
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_only_output_of_op(const std::string &op_type) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->inputs) {
if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
op->outputs.size() == 1) {
return true;
}
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_op_output(const std::string &op_type) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->inputs) {
if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type) {
return true;
}
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_op_output(const std::string &op_type,
const std::string &argument) {
assert_is_var();
assert_is_op_nth_output(op_type, argument, 0);
return this;
}
PDNode *PDNode::assert_is_op_input(const std::string &op_type) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->outputs) {
if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type) {
return true;
}
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_not_op_input(const std::string &argument) {
assert_is_op();
asserts_.emplace_back([=](Node *x) {
auto &ins = x->Op()->Inputs();
auto iter = ins.find(argument);
return iter == ins.end() || iter->second.empty();
});
return this;
}
PDNode *PDNode::assert_is_op_input(const std::string &op_type,
const std::string &argument) {
assert_is_var();
assert_is_op_nth_input(op_type, argument, 0);
return this;
}
PDNode *PDNode::assert_op_has_n_inputs(const std::string &op_type, size_t n) {
assert_is_op(op_type);
asserts_.emplace_back([=](Node *x) { return x->inputs.size() == n; });
return this;
}
PDNode *PDNode::assert_op_has_n_outputs(const std::string &op_type, size_t n) {
assert_is_op(op_type);
asserts_.emplace_back([=](Node *x) { return x->outputs.size() == n; });
return this;
}
PDNode *PDNode::assert_has_n_inputs(size_t n) {
asserts_.emplace_back([=](Node *x) { return x->inputs.size() == n; });
return this;
}
PDNode *PDNode::assert_has_n_outputs(size_t n) {
asserts_.emplace_back([=](Node *x) { return x->outputs.size() == n; });
return this;
}
PDNode *PDNode::assert_more(PDNode::teller_t &&teller) {
asserts_.emplace_back(std::move(teller));
return this;
}
PDNode *PDNode::assert_is_ops(const std::unordered_set<std::string> &op_types) {
asserts_.emplace_back([op_types](Node *x) {
return x && x->IsOp() && op_types.count(x->Op()->Type());
});
return this;
}
PDNode *PDNode::assert_is_ops_nth_input(
const std::unordered_set<std::string> &op_types,
const std::string &argument, int nth) {
assert_is_var();
assert_is_ops_input(op_types);
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->outputs) {
if (op->IsOp() && op_types.count(op->Op()->Type()) &&
IsNthInput(x, op, argument, nth))
return true;
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_ops_nth_output(
const std::unordered_set<std::string> &op_types,
const std::string &argument, int nth) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->inputs) {
if (op->IsOp() && op_types.count(op->Op()->Type()) &&
IsNthOutput(x, op, argument, nth))
return true;
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_ops_output(
const std::unordered_set<std::string> &op_types) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->inputs) {
if (op && op->IsOp() && op->Op() && op_types.count(op->Op()->Type())) {
return true;
}
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_ops_output(
const std::unordered_set<std::string> &op_types,
const std::string &argument) {
assert_is_var();
assert_is_ops_nth_output(op_types, argument, 0);
return this;
}
PDNode *PDNode::assert_is_ops_input(
const std::unordered_set<std::string> &op_types) {
assert_is_var();
asserts_.emplace_back([=](Node *x) {
for (auto *op : x->outputs) {
if (op && op->IsOp() && op->Op() && op_types.count(op->Op()->Type())) {
return true;
}
}
return false;
});
return this;
}
PDNode *PDNode::assert_is_ops_input(
const std::unordered_set<std::string> &op_types,
const std::string &argument) {
assert_is_var();
assert_is_ops_nth_input(op_types, argument, 0);
return this;
}
bool VarLinksToOp(Node *node, const std::string &op_type) {
for (auto *out : node->outputs) {
if (out->IsOp() && out->Op()->Type() == op_type) {
return true;
}
}
return false;
}
bool IsNthInput(Node *var, Node *op, const std::string &argument, size_t nth) {
PADDLE_ENFORCE_EQ(
var->IsVar(), true,
platform::errors::InvalidArgument(
"First parameter of function IsNthInput must be Node::Var"));
PADDLE_ENFORCE_EQ(
op->IsOp(), true,
platform::errors::InvalidArgument(
"Second parameter of function IsNthInput must be Node::Op"));
if (!HasInput(op, argument) || op->Op()->Input(argument).size() <= nth)
return false;
return var->Name() == op->Op()->Input(argument)[nth];
}
bool HasInput(Node *op, const std::string &argument) {
PADDLE_ENFORCE_EQ(
op->IsOp(), true,
platform::errors::InvalidArgument(
"First parameter of function HasInput must be Node::Op"));
auto const &names = op->Op()->InputNames();
if (std::find(names.begin(), names.end(), argument) == names.end())
return false;
return true;
}
bool HasOutput(Node *op, const std::string &argument) {
PADDLE_ENFORCE_EQ(
op->IsOp(), true,
platform::errors::InvalidArgument(
"First parameter of function HasOuput must be Node::Op"));
auto const &names = op->Op()->OutputNames();
if (std::find(names.begin(), names.end(), argument) == names.end())
return false;
return true;
}
bool IsNthOutput(Node *var, Node *op, const std::string &argument, size_t nth) {
PADDLE_ENFORCE_EQ(
var->IsVar(), true,
platform::errors::InvalidArgument(
"First parameter of function IsNthOutput must be Node::Var"));
PADDLE_ENFORCE_EQ(
op->IsOp(), true,
platform::errors::InvalidArgument(
"Second parameter of function IsNthOutput must be Node::Op"));
if (!HasOutput(op, argument) || op->Op()->Output(argument).size() <= nth)
return false;
return var->Name() == op->Op()->Output(argument)[nth];
}
void GraphSafeRemoveNodes(Graph *graph,
const std::unordered_set<const Node *> &nodes) {
for (auto *node : nodes) {
graph->RemoveNode(const_cast<Node *>(node));
}
for (auto *node : graph->Nodes()) {
for (auto it = node->inputs.begin(); it != node->inputs.end();) {
if (nodes.count(*it)) {
it = const_cast<Node *>(node)->inputs.erase(it);
} else {
it++;
}
}
for (auto it = node->outputs.begin(); it != node->outputs.end();) {
if (nodes.count(*it)) {
it = const_cast<Node *>(node)->outputs.erase(it);
} else {
it++;
}
}
}
}
bool VarLinksFromOp(Node *node, const std::string &op_type) {
for (auto *out : node->inputs) {
if (out->IsOp() && out->Op()->Type() == op_type) {
return true;
}
}
return false;
}
PDNode *patterns::ConvBN::operator()(paddle::framework::ir::PDNode *conv_input,
const std::string &conv_type,
bool with_eltwise_add) {
// Create Operators
conv_input->assert_is_op_input(conv_type, "Input");
auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
PDNode *eltwise_op = nullptr;
if (with_eltwise_add) {
eltwise_op =
pattern->NewNode(eltwise_repr())->assert_is_op("elementwise_add");
}
auto *batch_norm_op =
pattern->NewNode(batch_norm_repr())->assert_is_op("batch_norm");
// Create variables
// Conv Filter
auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input(conv_type, "Filter");
auto *conv_out_var = pattern->NewNode(conv_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op(conv_type);
PDNode *eltwise_y_in_var = nullptr;
PDNode *eltwise_out_var = nullptr;
if (with_eltwise_add) {
// Conv output as Bias input
conv_out_var->assert_is_op_input("elementwise_add", "X");
// Bias
eltwise_y_in_var = pattern->NewNode(eltwise_y_in_repr())
->assert_is_op_input("elementwise_add", "Y")
->AsInput();
eltwise_out_var = pattern->NewNode(eltwise_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op("elementwise_add");
} else {
// Conv output as BN input
conv_out_var->assert_is_op_input("batch_norm", "X");
}
// BN Scale
auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("batch_norm", "Scale");
// BN Bias
auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("batch_norm", "Bias");
// BN Mean
auto *bn_mean_var = pattern->NewNode(bn_mean_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("batch_norm", "Mean");
// BN Variance
auto *bn_variance_var = pattern->NewNode(bn_variance_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("batch_norm", "Variance");
// BN output
auto *bn_out_var = pattern->NewNode(bn_out_repr())
->AsOutput()
->assert_is_op_output("batch_norm");
auto *bn_mean_out_var = pattern->NewNode(bn_mean_out_repr())
->AsOutput()
->assert_is_op_output("batch_norm", "MeanOut");
auto *bn_variance_out_var =
pattern->NewNode(bn_variance_out_repr())
->AsOutput()
->assert_is_op_output("batch_norm", "VarianceOut");
auto *bn_saved_mean_var =
pattern->NewNode(bn_saved_mean_repr())
->AsOutput()
->assert_is_op_output("batch_norm", "SavedMean");
auto *bn_saved_variance_var =
pattern->NewNode(bn_saved_variance_repr())
->AsOutput()
->assert_is_op_output("batch_norm", "SavedVariance");
conv_op->LinksFrom({conv_input, conv_weight_var}).LinksTo({conv_out_var});
if (with_eltwise_add) {
eltwise_op->LinksFrom({conv_out_var, eltwise_y_in_var})
.LinksTo({eltwise_out_var});
batch_norm_op
->LinksFrom({eltwise_out_var, bn_scale_var, bn_bias_var, bn_mean_var,
bn_variance_var})
.LinksTo({bn_out_var, bn_mean_out_var, bn_variance_out_var,
bn_saved_mean_var, bn_saved_variance_var});
} else {
batch_norm_op
->LinksFrom({conv_out_var, bn_scale_var, bn_bias_var, bn_mean_var,
bn_variance_var})
.LinksTo({bn_out_var, bn_mean_out_var, bn_variance_out_var,
bn_saved_mean_var, bn_saved_variance_var});
}
return bn_out_var;
}
PDNode *patterns::ConvActivation::operator()(
paddle::framework::ir::PDNode *conv_input, std::string conv_type,
std::string activation_type) {
// Create Operators
conv_input->assert_is_op_input(conv_type, "Input");
auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
auto *activation_op =
pattern->NewNode(activation_repr())->assert_is_op(activation_type);
// Create variables
// Filter
auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input(conv_type, "Filter");
// intermediate variable, will be removed in the IR after fuse.
auto *conv_out_var = pattern->NewNode(conv_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op(conv_type)
->assert_is_op_input(activation_type);
// output
auto *activation_out_var = pattern->NewNode(activation_out_repr())
->AsOutput()
->assert_is_op_output(activation_type);
conv_op->LinksFrom({conv_input, conv_weight_var}).LinksTo({conv_out_var});
activation_op->LinksFrom({conv_out_var}).LinksTo({activation_out_var});
return activation_out_var;
}
PDNode *patterns::SeqConvEltAddRelu::operator()(
paddle::framework::ir::PDNode *seqconv_input) {
// Create Operators
seqconv_input->assert_is_op_input("sequence_conv", "X");
auto *seqconv_op = pattern->NewNode(seqconv_repr())
->assert_is_op("sequence_conv")
->assert_op_attr<bool>("paddingTrainable", false)
->assert_op_attr<int>("contextStride", 1);
auto *eltadd_op =
pattern->NewNode(eltadd_repr())->assert_is_op("elementwise_add");
auto *relu_op = pattern->NewNode(relu_repr())->assert_is_op("relu");
// Create variables
// Filter
auto *seqconv_weight_var =
pattern->NewNode(seqconv_weight_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("sequence_conv", "Filter");
// Bias
auto *eltadd_bias_var = pattern->NewNode(eltadd_bias_repr())
->AsInput()
->assert_is_op_input("elementwise_add");
// intermediate variable, will be removed in the IR after fuse.
auto *seqconv_out_var = pattern->NewNode(seqconv_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op("sequence_conv")
->assert_is_op_input("elementwise_add");
auto *eltadd_out_var = pattern->NewNode(eltadd_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op("elementwise_add")
->assert_is_only_input_of_op("relu");
// output
auto *relu_out_var = pattern->NewNode(relu_out_repr())
->AsOutput()
->assert_is_op_output("relu");
seqconv_op->LinksFrom({seqconv_input, seqconv_weight_var})
.LinksTo({seqconv_out_var});
eltadd_op->LinksFrom({seqconv_out_var, eltadd_bias_var})
.LinksTo({eltadd_out_var});
relu_op->LinksFrom({eltadd_out_var}).LinksTo({relu_out_var});
return relu_out_var;
}
PDNode *patterns::FC::operator()(paddle::framework::ir::PDNode *x,
bool with_bias, bool with_relu) {
// Create shared nodes.
x->assert_is_op_input("mul", "X");
auto *mul = pattern->NewNode(mul_repr())->assert_is_op("mul");
auto *mul_w_var = pattern->NewNode(w_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("mul", "Y");
auto *mul_out_var =
pattern->NewNode(mul_out_repr())->assert_is_op_output("mul");
// Add links.
mul->LinksFrom({x, mul_w_var}).LinksTo({mul_out_var});
if (!with_bias) { // not with bias
return mul_out_var;
} else { // with bias
mul_out_var->AsIntermediate()->assert_is_op_input("elementwise_add");
// Create operators.
auto *elementwise_add = pattern->NewNode(elementwise_add_repr())
->assert_is_op("elementwise_add");
// Create variables.
auto *bias = pattern->NewNode(bias_repr())
->assert_is_op_input("elementwise_add")
->assert_is_persistable_var()
->AsInput();
auto *elementwise_add_out_var =
pattern->NewNode(elementwise_add_out_repr())
->AsOutput()
->assert_is_op_output("elementwise_add");
elementwise_add->LinksFrom({mul_out_var, bias})
.LinksTo({elementwise_add_out_var});
if (!with_relu) {
return elementwise_add_out_var;
} else {
elementwise_add_out_var->AsIntermediate()->assert_is_op_input("relu");
// Create operators.
auto *relu = pattern->NewNode(relu_repr())->assert_is_op("relu");
auto *relu_out_var = pattern->NewNode(relu_out_repr())
->AsOutput()
->assert_is_op_output("relu");
relu->LinksFrom({elementwise_add_out_var}).LinksTo({relu_out_var});
return relu_out_var;
}
}
}
PDNode *patterns::FCMKLDNN::operator()(paddle::framework::ir::PDNode *x,
bool with_bias) {
// Create shared nodes.
x->assert_is_op_input("fc", "Input");
auto *fc_op = pattern->NewNode(fc_repr())->assert_is_op("fc");
// Create variables
// Input
auto *input_var = pattern->NewNode(input_repr())
->AsInput()
->assert_is_op_input("fc", "Input");
// Filter
auto *fc_weight_var = pattern->NewNode(weights_repr())
->AsInput()
->assert_is_op_input("fc", "W");
// Bias
auto *fc_bias_var = pattern->NewNode(bias_repr())
->AsInput()
->assert_is_op_input("fc", "Bias");
// Output
auto *fc_out_var = pattern->NewNode(output_repr())
->AsOutput()
->assert_is_op_output("fc", "Out")
->assert_is_only_output_of_op("fc");
fc_op->LinksFrom({input_var, fc_weight_var, fc_bias_var})
.LinksTo({fc_out_var});
return fc_out_var;
}
PDNode *patterns::Embedding::operator()(PDNode *x) {
x->assert_is_op_input("lookup_table", "Ids");
auto *lookup_table_op =
pattern->NewNode(lookup_table_repr())->assert_is_op("lookup_table");
#define NEW_NODE(arg__, io__) \
auto *arg__ = pattern->NewNode(arg__##_repr()) \
->assert_is_op_##io__("lookup_table", #arg__);
NEW_NODE(W, input);
NEW_NODE(Out, output);
#undef NEW_NODE
lookup_table_op->LinksFrom({x, W});
lookup_table_op->LinksTo({Out});
return Out;
}
PDNode *patterns::LSTM::operator()(PDNode *x) {
x->assert_is_op_input("lstm", "Input");
auto *lstm_op = pattern->NewNode(lstm_repr())->assert_is_op("lstm");
#define NEW_NODE(arg__, io__) \
auto *arg__ = \
pattern->NewNode(arg__##_repr())->assert_is_op_##io__("lstm", #arg__);
// Currently, the H0 and C0 are optional
// TODO(Superjomn) upgrade the fuse framework to support optional.
// NEW_NODE(H0, input);
// NEW_NODE(C0, input);
NEW_NODE(Weight, input);
NEW_NODE(Bias, input);
NEW_NODE(Hidden, output);
NEW_NODE(Cell, output);
NEW_NODE(BatchGate, output);
NEW_NODE(BatchCellPreAct, output);
#undef NEW_NODE
lstm_op->LinksFrom({x, Weight, Bias});
lstm_op->LinksTo({Hidden, Cell, BatchGate, BatchCellPreAct});
return Hidden;
}
PDNode *patterns::GRU::operator()(PDNode *x) {
x->assert_is_op_input("gru", "Input");
auto *gru_op = pattern->NewNode(gru_repr())->assert_is_op("gru");
#define NEW_NODE(arg__, io__) \
auto *arg__ = \
pattern->NewNode(arg__##_repr())->assert_is_op_##io__("gru", #arg__);
NEW_NODE(Weight, input);
// TODO(Superjomn): upgrade the fuse framework to support optional.
// H0 and bias are optional
NEW_NODE(Bias, input); // also optional
// NEW_NODE(H0, input);
NEW_NODE(Hidden, output);
// below are intermediate
NEW_NODE(BatchGate, output);
NEW_NODE(BatchResetHiddenPrev, output);
NEW_NODE(BatchHidden, output);
#undef NEW_NODE
BatchGate->AsIntermediate();
BatchResetHiddenPrev->AsIntermediate();
BatchHidden->AsIntermediate();
gru_op->LinksFrom({x, Weight, Bias});
gru_op->LinksTo({Hidden, BatchGate, BatchResetHiddenPrev, BatchHidden});
return Hidden;
}
PDNode *patterns::ActElewiseAdd::operator()(
paddle::framework::ir::PDNode *in_var,
std::unordered_set<std::string> act_types) {
in_var->assert_is_ops_input(act_types, "X");
auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);
auto *act_out_var = pattern->NewNode(act_out_repr())
->assert_is_not_ctrl_var()
->assert_is_ops_output(act_types);
act_out_var->AsIntermediate()->assert_is_op_input("elementwise_add");
auto *ele_x_var = pattern->NewNode(ele_x_repr())
->assert_is_not_ctrl_var()
->assert_is_op_input("elementwise_add")
->AsInput();
auto *elementwise_add =
pattern->NewNode(ele_add_repr())->assert_is_op("elementwise_add");
auto *elewise_add_out = pattern->NewNode(elewise_add_out_repr())
->AsOutput()
->assert_is_op_output("elementwise_add", "Out");
act->LinksFrom({in_var}).LinksTo({act_out_var});
elementwise_add->LinksFrom({act_out_var, ele_x_var})
.LinksTo({elewise_add_out});
return elewise_add_out;
}
PDNode *patterns::BatchNormAct::operator()(
paddle::framework::ir::PDNode *bn_x_var,
std::unordered_set<std::string> act_types) {
auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
->assert_is_op_input("batch_norm", "Scale");
auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
->assert_is_op_input("batch_norm", "Bias");
auto *bn_variance_var = pattern->NewNode(bn_variance_repr())
->assert_is_op_input("batch_norm", "Variance");
auto *bn_mean_var = pattern->NewNode(bn_mean_repr())
->assert_is_op_input("batch_norm", "Mean");
auto *bn = pattern->NewNode(batch_norm_repr())
->assert_is_op("batch_norm")
->assert_is_not_op_input("MomentumTensor")
->assert_op_attr<bool>("is_test", false)
->assert_op_attr<bool>("use_global_stats", false)
->assert_op_attr<std::string>("data_layout", "NHWC");
auto *bn_mean_out_var = pattern->NewNode(bn_mean_out_repr())
->assert_is_op_output("batch_norm", "MeanOut");
auto *bn_variance_out_var =
pattern->NewNode(bn_variance_out_repr())
->assert_is_op_output("batch_norm", "VarianceOut");
auto *bn_saved_variance_var =
pattern->NewNode(bn_saved_variance_repr())
->assert_is_op_output("batch_norm", "SavedVariance");
auto *bn_saved_mean_var =
pattern->NewNode(bn_saved_mean_repr())
->assert_is_op_output("batch_norm", "SavedMean");
auto *bn_reserve_space =
pattern->NewNode(bn_reserve_space_repr())
->assert_is_op_output("batch_norm", "ReserveSpace");
auto *bn_out_var = pattern->NewNode(bn_out_repr())
->assert_is_op_output("batch_norm", "Y")
->assert_has_n_outputs(1);
bn_out_var->AsIntermediate()->assert_is_ops_input(act_types);
auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);
auto *act_out_var =
pattern->NewNode(act_out_repr())->assert_is_ops_output(act_types, "Out");
bn->LinksFrom(
{bn_x_var, bn_scale_var, bn_bias_var, bn_variance_var, bn_mean_var})
.LinksTo({bn_mean_out_var, bn_variance_out_var, bn_saved_variance_var,
bn_saved_mean_var, bn_reserve_space, bn_out_var});
act->LinksFrom({bn_out_var}).LinksTo({act_out_var});
return act_out_var;
}
PDNode *patterns::BatchNormActGrad::operator()(
paddle::framework::ir::PDNode *d_act_out_var,
std::unordered_set<std::string> act_grad_types) {
auto *act_grad =
pattern->NewNode(act_grad_repr())->assert_is_ops(act_grad_types);
auto *bn_grad = pattern->NewNode(batch_norm_grad_repr())
->assert_is_op("batch_norm_grad")
->assert_op_attr<bool>("use_global_stats", false)
->assert_op_attr<std::string>("data_layout", "NHWC");
auto *act_out_var = pattern->NewNode(act_out_repr())
->assert_is_ops_input(act_grad_types, "Out");
auto *d_intermediate_var =
pattern->NewNode(d_itermediate_out_repr())
->assert_is_ops_output(act_grad_types, GradVarName("X"))
->assert_has_n_outputs(1);
auto *bn_x_var = pattern->NewNode(bn_x_repr())
->assert_is_op_input("batch_norm_grad", "X")
->assert_var_dtype(proto::VarType::FP16);
auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
->assert_is_op_input("batch_norm_grad", "Scale");
auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
->assert_is_op_input("batch_norm_grad", "Bias");
auto *bn_saved_mean_var =
pattern->NewNode(bn_saved_mean_repr())
->assert_is_op_input("batch_norm_grad", "SavedMean");
auto *bn_saved_variance_var =
pattern->NewNode(bn_saved_variance_repr())
->assert_is_op_input("batch_norm_grad", "SavedVariance");
// ReserveSpace as the output is equal to:
// data_layout == 'NHWC' && FLAGS_cudnn_batchnorm_spatial_persistent == true
auto *bn_reserve_space =
pattern->NewNode(bn_reserve_space_repr())
->assert_is_op_input("batch_norm_grad", "ReserveSpace");
auto *d_bn_x_var =
pattern->NewNode(d_bn_x_repr())
->assert_is_not_ctrl_var()
->assert_is_op_output("batch_norm_grad", GradVarName("X"));
auto *d_bn_scale_var =
pattern->NewNode(d_bn_scale_repr())
->assert_is_not_ctrl_var()
->assert_is_op_output("batch_norm_grad", GradVarName("Scale"));
auto *d_bn_bias_var =
pattern->NewNode(d_bn_bias_repr())
->assert_is_not_ctrl_var()
->assert_is_op_output("batch_norm_grad", GradVarName("Bias"));
act_grad->LinksFrom({d_act_out_var, act_out_var})
.LinksTo({d_intermediate_var});
bn_grad
->LinksFrom({bn_x_var, d_intermediate_var, bn_scale_var, bn_bias_var,
bn_saved_mean_var, bn_saved_variance_var, bn_reserve_space})
.LinksTo({d_bn_x_var, d_bn_scale_var, d_bn_bias_var});
return bn_grad;
}
PDNode *patterns::ElewiseAddAct::operator()(
paddle::framework::ir::PDNode *ele_x_var,
std::unordered_set<std::string> act_types) {
auto *ele_y_var = pattern->NewNode(ele_y_repr())
->assert_is_op_input("elementwise_add", "Y");
auto *ele_add =
pattern->NewNode(ele_add_repr())->assert_is_op("elementwise_add");
auto *ele_out_var = pattern->NewNode(elewise_add_out_repr())
->assert_is_op_output("elementwise_add", "Out");
ele_out_var->AsIntermediate()->assert_is_ops_input(act_types);
auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);
auto *act_out_var =
pattern->NewNode(act_out_repr())->assert_is_ops_output(act_types, "Out");
ele_add->LinksFrom({ele_x_var, ele_y_var}).LinksTo({ele_out_var});
act->LinksFrom({ele_out_var}).LinksTo({act_out_var});
return act_out_var;
}
PDNode *patterns::ElewiseAddActInplaceGrad::operator()(
paddle::framework::ir::PDNode *d_act_out_var,
std::unordered_set<std::string> act_types) {
// act_grad: in["Out", "Out@GRAD"], out["X@GRAD"]
// ele_add_grad: in["Y", "Out@GRAD"], out["X@GRAD", "Y@GRAD"]
auto *act_grad = pattern->NewNode(act_grad_repr())->assert_is_ops(act_types);
auto *act_out_var =
pattern->NewNode(act_out_repr())->assert_is_ops_input(act_types, "Out");
auto *d_intermediate_var =
pattern->NewNode(d_itermediate_out_repr())
->assert_is_ops_output(act_types, GradVarName("X"));
act_grad->LinksFrom({d_act_out_var, act_out_var})
.LinksTo({d_intermediate_var});
auto *ele_y_var = pattern->NewNode(ele_y_repr())
->assert_is_not_ctrl_var()
->assert_is_op_input("elementwise_add_grad", "Y");
auto *ele_add_grad = pattern->NewNode(ele_add_grad_repr())
->assert_is_op("elementwise_add_grad");
auto *d_ele_x_var =
pattern->NewNode(d_ele_x_repr())
->assert_is_not_ctrl_var()
->assert_is_op_output("elementwise_add_grad", GradVarName("X"));
auto *d_ele_y_var =
pattern->NewNode(d_ele_y_repr())
->assert_is_not_ctrl_var()
->assert_is_op_output("elementwise_add_grad", GradVarName("Y"));
ele_add_grad->LinksFrom({d_intermediate_var, ele_y_var})
.LinksTo({d_ele_x_var, d_ele_y_var});
return ele_add_grad;
}
// conv_type: conv2d, conv3d, conv2d_transpose
PDNode *patterns::ConvBias::operator()(
paddle::framework::ir::PDNode *conv_input, std::string conv_type) {
// Create Operators
conv_input->assert_is_op_input(conv_type, "Input");
auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
auto *eltiwse_op =
pattern->NewNode(eltwise_repr())->assert_is_op("elementwise_add");
// Create variables
// Filter
auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input(conv_type, "Filter");
// intermediate variable, will be removed in the IR after fuse.
auto *conv_out_var = pattern->NewNode(conv_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op(conv_type)
->assert_is_op_input("elementwise_add");
// Bias stored in elementwise_add
auto *eltwise_bias_var = pattern->NewNode(eltwise_bias_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("elementwise_add", "Y");
// output
auto *eltwise_out_var = pattern->NewNode(eltwise_out_repr())
->AsOutput()
->assert_is_op_output("elementwise_add");
conv_op->LinksFrom({conv_input, conv_weight_var}).LinksTo({conv_out_var});
eltiwse_op->LinksFrom({conv_out_var, eltwise_bias_var})
.LinksTo({eltwise_out_var});
return eltwise_out_var;
}
PDNode *patterns::Conv::operator()() {
auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
auto input_var = pattern->NewNode(conv_input_repr())
->AsInput()
->assert_is_op_input("conv2d", "Input");
auto filter_var = pattern->NewNode(conv_filter_repr())
->AsInput()
->assert_is_op_input("conv2d", "Filter");
auto output_var = pattern->NewNode(conv_output_repr())
->AsOutput()
->assert_is_op_output("conv2d", "Output");
conv_op->LinksFrom({input_var, filter_var}).LinksTo({output_var});
return output_var;
}
PDNode *patterns::Transpose::operator()() {
auto prev_op = pattern->NewNode(prev_op_repr())->assert_is_op();
auto transpose_op =
pattern->NewNode(transpose_op_repr())->assert_is_op("transpose2");
auto transpose_in = pattern->NewNode(transpose_in_repr())
->AsInput()
->assert_is_op_input("transpose2");
auto transpose_out = pattern->NewNode(transpose_out_repr())
->AsOutput()
->assert_is_op_output("transpose2", "Out");
auto next_op = pattern->NewNode(next_op_repr())->assert_is_op();
prev_op->LinksTo({transpose_in});
transpose_op->LinksFrom({transpose_in}).LinksTo({transpose_out});
next_op->LinksFrom({transpose_out});
return transpose_out;
}
PDNode *patterns::Reshape::operator()() {
auto prev_op = pattern->NewNode(prev_op_repr())->assert_is_op();
auto reshape_op =
pattern->NewNode(reshape_op_repr())->assert_is_op("reshape2");
auto reshape_in = pattern->NewNode(reshape_in_repr())
->AsInput()
->assert_is_op_input("reshape2", "X");
auto reshape_out = pattern->NewNode(reshape_out_repr())
->AsOutput()
->assert_is_op_output("reshape2", "Out");
auto next_op = pattern->NewNode(next_op_repr())->assert_is_op();
prev_op->LinksTo({reshape_in});
reshape_op->LinksFrom({reshape_in}).LinksTo({reshape_out});
next_op->LinksFrom({reshape_out});
return reshape_out;
}
PDNode *patterns::Matmul::operator()() {
auto prev_op_x = pattern->NewNode(prev_op_x_repr())->assert_is_op();
auto prev_op_y = pattern->NewNode(prev_op_y_repr())->assert_is_op();
auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
auto matmul_in_x = pattern->NewNode(matmul_in_x_repr())
->AsInput()
->assert_is_op_input("matmul", "X");
auto matmul_in_y = pattern->NewNode(matmul_in_y_repr())
->AsInput()
->assert_is_op_input("matmul", "Y");
auto matmul_out = pattern->NewNode(matmul_out_repr())
->AsOutput()
->assert_is_op_output("matmul", "Out");
prev_op_x->LinksTo({matmul_in_x});
prev_op_y->LinksTo({matmul_in_y});
matmul_op->LinksFrom({matmul_in_x, matmul_in_y}).LinksTo({matmul_out});
return matmul_out;
}
PDNode *patterns::ConvResidual::operator()(bool with_residual_data) {
auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
if (!with_residual_data) {
conv_op->assert_more([&](Node *x) {
auto node_names = x->Op()->InputNames();
if (!HasInput(x, "ResidualData") ||
x->Op()->Input("ResidualData").size() == 0)
return true;
return false;
});
}
auto input_var = pattern->NewNode(conv_input_repr())
->AsInput()
->assert_is_op_input("conv2d", "Input");
auto filter_var = pattern->NewNode(conv_filter_repr())
->AsInput()
->assert_is_op_input("conv2d", "Filter");
auto output_var = pattern->NewNode(conv_output_repr())
->AsOutput()
->assert_is_op_output("conv2d", "Output");
std::vector<PDNode *> links_from{input_var, filter_var};
if (with_residual_data) {
auto res_conn_var = pattern->NewNode(conv_residual_data_repr())
->AsInput()
->assert_is_op_input("conv2d", "ResidualData");
links_from.push_back(res_conn_var);
}
conv_op->LinksFrom(links_from).LinksTo({output_var});
return output_var;
}
PDNode *patterns::Pool::operator()() {
auto pool_op = pattern->NewNode(pool_op_repr())->assert_is_op("pool2d");
auto input_var = pattern->NewNode(pool_input_repr())
->AsInput()
->assert_is_op_input("pool2d", "X");
auto output_var = pattern->NewNode(pool_output_repr())
->AsOutput()
->assert_is_op_output("pool2d", "Out");
pool_op->LinksFrom({input_var}).LinksTo({output_var});
return output_var;
}
PDNode *patterns::ElementwiseAdd::operator()(PDNode *x_var, PDNode *y_var) {
auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
->assert_is_op("elementwise_add");
x_var->AsInput()->assert_is_op_input("elementwise_add", "X");
y_var->AsInput()->assert_is_op_input("elementwise_add", "Y");
auto out_var = pattern->NewNode(elementwise_add_out_repr())
->AsOutput()
->assert_is_op_output("elementwise_add", "Out");
elementwise_add_op->LinksFrom({x_var, y_var});
elementwise_add_op->LinksTo({out_var});
return out_var;
}
PDNode *patterns::Concat::operator()() {
auto concat_op = pattern->NewNode(concat_op_repr())->assert_is_op("concat");
auto output_var = pattern->NewNode(concat_out_repr())
->AsOutput()
->assert_is_op_output("concat", "Out");
concat_op->LinksTo({output_var});
return output_var;
}
PDNode *patterns::ConcatReLU::operator()() {
auto concat_op = pattern->NewNode(concat_op_repr())->assert_is_op("concat");
auto relu_op = pattern->NewNode(relu_op_repr())->assert_is_op("relu");
auto concat_out =
pattern->NewNode(concat_out_repr())->assert_is_op_output("concat", "Out");
auto relu_out = pattern->NewNode(relu_out_repr())
->AsOutput()
->assert_is_op_output("relu", "Out");
concat_op->LinksTo({concat_out});
relu_op->LinksFrom({concat_out}).LinksTo({relu_out});
return relu_out;
}
PDNode *patterns::ConvConcatReLU::operator()() {
auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
auto concat_op = pattern->NewNode(concat_op_repr())->assert_is_op("concat");
auto relu_op = pattern->NewNode(relu_op_repr())->assert_is_op("relu");
auto conv_out = pattern->NewNode(conv_out_repr())
->assert_is_op_output("conv2d", "Output");
auto concat_out = pattern->NewNode(concat_out_repr())
->assert_is_op_output("concat", "Out")
->assert_is_op_input("relu", "X");
auto relu_out = pattern->NewNode(relu_out_repr())
->AsOutput()
->assert_is_op_output("relu", "Out");
conv_op->LinksTo({conv_out});
concat_op->LinksFrom({conv_out}).LinksTo({concat_out});
relu_op->LinksFrom({concat_out}).LinksTo({relu_out});
return relu_out;
}
PDNode *patterns::OpRequant::operator()() {
auto any_op = pattern->NewNode(any_op_repr())
->assert_is_op()
->assert_more([&](Node *node) {
return node->Op()->HasAttr("Scale_out") ? true : false;
});
auto requant_in = pattern->NewNode(requant_in_repr())
->assert_is_op_input("requantize", "Input");
auto requant_op =
pattern->NewNode(requant_op_repr())->assert_is_op("requantize");
auto requant_out = pattern->NewNode(requant_out_repr())
->AsOutput()
->assert_is_op_output("requantize", "Output");
any_op->LinksTo({requant_in});
requant_op->LinksFrom({requant_in}).LinksTo({requant_out});
return requant_out;
}
PDNode *patterns::RequantOp::operator()() {
auto requant_in = pattern->NewNode(requant_in_repr())
->assert_is_op_input("requantize", "Input");
auto requant_op =
pattern->NewNode(requant_op_repr())->assert_is_op("requantize");
auto requant_out = pattern->NewNode(requant_out_repr())
->AsOutput()
->assert_is_op_output("requantize", "Output");
auto any_op = pattern->NewNode(any_op_repr())
->assert_is_op()
->assert_more([&](Node *node) {
return (node->Op()->HasAttr("Scale_in") ||
node->Op()->HasAttr("Scale_x") ||
node->Op()->HasAttr("Scale_y"));
});
requant_op->LinksFrom({requant_in}).LinksTo({requant_out});
any_op->LinksFrom({requant_out});
return any_op;
}
PDNode *patterns::OpDequant::operator()() {
auto any_op = pattern->NewNode(any_op_repr())
->assert_is_op()
->assert_more([&](Node *node) {
return (node->Op()->Type() == "matmul" ||
node->Op()->Type() == "conv2d" ||
node->Op()->Type() == "fc");
});
auto dequant_in = pattern->NewNode(dequant_in_repr())
->assert_is_op_input("dequantize", "Input");
auto dequant_op =
pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");
auto dequant_out = pattern->NewNode(dequant_out_repr())
->AsOutput()
->assert_is_op_output("dequantize", "Output");
any_op->LinksTo({dequant_in});
dequant_op->LinksFrom({dequant_in}).LinksTo({dequant_out});
return dequant_out;
}
PDNode *patterns::DequantScale::operator()() {
// Create Operators
auto dequant_op =
pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");
auto scale_op = pattern->NewNode(scale_op_repr())->assert_is_op("scale");
auto dequant_out = pattern->NewNode(dequant_out_repr())
->AsOutput()
->assert_is_op_output("dequantize", "Output");
auto scale_out = pattern->NewNode(scale_out_repr())
->AsOutput()
->assert_is_op_output("scale", "Out");
dequant_op->LinksTo({dequant_out});
scale_op->LinksFrom({dequant_out}).LinksTo({scale_out});
return scale_out;
}
PDNode *patterns::ScaleMatmul::operator()() {
auto scale_in = pattern->NewNode(scale_in_repr())
->AsInput()
->assert_is_op_input("scale", "X");
auto scale_op = pattern->NewNode(scale_op_repr())->assert_is_op("scale");
auto scale_out = pattern->NewNode(scale_out_repr())
->AsOutput()
->assert_is_op_output("scale", "Out");
auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
scale_op->LinksFrom({scale_in}).LinksTo({scale_out});
matmul_op->LinksFrom({scale_out});
return matmul_op;
}
PDNode *patterns::PriorBox::operator()() {
auto prior_box_op =
pattern->NewNode(prior_box_op_repr())->assert_is_op("prior_box");
auto input_var = pattern->NewNode(prior_box_input_repr())
->AsInput()
->assert_is_op_input("prior_box", "Input");
auto image_var = pattern->NewNode(prior_box_image_repr())
->AsInput()
->assert_is_op_input("prior_box", "Image");
auto boxes_var = pattern->NewNode(prior_box_boxes_repr())
->AsOutput()
->assert_is_op_output("prior_box", "Boxes");
auto variances_var = pattern->NewNode(prior_box_variances_repr())
->AsOutput()
->assert_is_op_output("prior_box", "Variances");
prior_box_op->LinksFrom({input_var, image_var})
.LinksTo({boxes_var, variances_var});
return boxes_var;
}
std::unordered_set<std::string> conv_act_set({"identity", "relu"});
PDNode *patterns::ConvElementwiseaddAct::operator()(PDNode *conv_in) {
conv_in->AsInput();
auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
auto conv_out = pattern->NewNode(conv_out_repr())
->assert_is_op_output("conv2d")
->assert_is_op_input("elementwise_add", "X")
->AsIntermediate();
auto conv_filter = pattern->NewNode(conv_filter_repr())
->assert_is_op_input("conv2d", "Filter")
->AsInput();
auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
->assert_is_op("elementwise_add");
auto elementwise_add_in_y = pattern->NewNode(elementwise_add_in_y_repr())
->assert_is_persistable_var()
->assert_is_op_input("elementwise_add", "Y")
->AsInput();
auto elementwise_add_out = pattern->NewNode(elementwise_add_out_repr())
->assert_is_op_output("elementwise_add")
->AsIntermediate();
auto act_op = pattern->NewNode(act_op_repr())
->assert_is_op()
->assert_more([&](Node *node) {
auto op_type = node->Name();
return conv_act_set.count(op_type);
});
auto act_out = pattern->NewNode(act_out_repr())
->assert_is_var()
// is activation op's output.
->assert_more([&](Node *node) {
for (auto *in_op : node->inputs) {
if (conv_act_set.count(in_op->Name())) {
return true;
}
}
return false;
})
->AsOutput();
conv_op->LinksFrom({conv_in, conv_filter});
conv_out->LinksFrom({conv_op});
elementwise_add_op->LinksFrom({conv_out, elementwise_add_in_y})
.LinksTo({elementwise_add_out});
act_op->LinksFrom({elementwise_add_out}).LinksTo({act_out});
return act_out;
}
PDNode *patterns::ConvElementwiseadd2Act::operator()(PDNode *conv_in) {
auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
auto conv_filter = pattern->NewNode(conv_filter_repr())
->assert_is_op_input("conv2d", "Filter")
->AsInput();
auto conv_out = pattern->NewNode(conv_out_repr())
->assert_is_op_output("conv2d")
->assert_is_op_input("elementwise_add", "X")
->AsIntermediate();
auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
->assert_is_op("elementwise_add");
auto elementwise_add_in_y = pattern->NewNode(elementwise_add_in_y_repr())
->assert_is_persistable_var()
->assert_is_op_input("elementwise_add", "Y")
->AsInput();
auto elementwise_add_out = pattern->NewNode(elementwise_add_out_repr())
->assert_is_op_output("elementwise_add")
->assert_is_op_input("elementwise_add", "Y")
->AsIntermediate();
auto elementwise_add_op_1 = pattern->NewNode(elementwise_add_op_1_repr())
->assert_is_op("elementwise_add");
auto elementwise_add_in_y_1 = pattern->NewNode(elementwise_add_in_y_1_repr())
->assert_is_op_input("elementwise_add", "X")
->AsInput();
auto elementwise_add_out_1 = pattern->NewNode(elementwise_add_out_1_repr())
->assert_is_op_output("elementwise_add")
->AsIntermediate();
auto act_op = pattern->NewNode(act_op_repr())
->assert_is_op()
->assert_more([&](Node *node) {
auto op_type = node->Name();
return conv_act_set.count(op_type);
});
auto act_out = pattern->NewNode(act_out_repr())
->assert_is_var()
// is activation op's output.
->assert_more([&](Node *node) {
for (auto *in_op : node->inputs) {
if (conv_act_set.count(in_op->Name())) {
return true;
}
}
return false;
})
->AsOutput();
conv_op->LinksFrom({conv_in, conv_filter}).LinksTo({conv_out});
elementwise_add_op->LinksFrom({conv_out, elementwise_add_in_y})
.LinksTo({elementwise_add_out});
elementwise_add_op_1->LinksFrom({elementwise_add_out, elementwise_add_in_y_1})
.LinksTo({elementwise_add_out_1});
act_op->LinksFrom({elementwise_add_out_1}).LinksTo({act_out});
return act_out;
}
PDNode *patterns::ConvElementwiseadd::operator()(PDNode *conv_in) {
conv_in->AsInput();
auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
auto conv_out = pattern->NewNode(conv_out_repr())
->assert_is_op_output("conv2d")
->assert_is_op_input("elementwise_add", "X")
->AsIntermediate();
auto conv_filter = pattern->NewNode(conv_filter_repr())
->assert_is_op_input("conv2d", "Filter")
->AsInput();
auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
->assert_is_op("elementwise_add");
auto elementwise_add_in_y = pattern->NewNode(elementwise_add_in_y_repr())
->assert_is_persistable_var()
->assert_is_op_input("elementwise_add", "Y")
->AsInput();
auto elementwise_add_out = pattern->NewNode(elementwise_add_out_repr())
->assert_is_op_output("elementwise_add")
->AsOutput();
conv_op->LinksFrom({conv_in, conv_filter});
conv_out->LinksFrom({conv_op});
elementwise_add_op->LinksFrom({conv_out, elementwise_add_in_y})
.LinksTo({elementwise_add_out});
return elementwise_add_out;
}
PDNode *patterns::ConvAffineChannel::operator()(
paddle::framework::ir::PDNode *conv_input, bool with_eltwise_add) {
// Create Operators
conv_input->assert_is_op_input("conv2d", "Input");
auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op("conv2d");
PDNode *eltwise_op = nullptr;
if (with_eltwise_add) {
eltwise_op =
pattern->NewNode(eltwise_repr())->assert_is_op("elementwise_add");
}
auto *affine_channel_op =
pattern->NewNode(affine_channel_repr())->assert_is_op("affine_channel");
// Create variables
// Conv Filter
auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
->AsInput()
->assert_is_persistable_var()
->assert_is_op_input("conv2d", "Filter");
auto *conv_out_var = pattern->NewNode(conv_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op("conv2d");
PDNode *eltwise_y_in_var = nullptr;
PDNode *eltwise_out_var = nullptr;
if (with_eltwise_add) {
// Conv output as Bias input
conv_out_var->assert_is_op_input("elementwise_add", "X");
// Bias
eltwise_y_in_var = pattern->NewNode(eltwise_y_in_repr())
->assert_is_op_input("elementwise_add", "Y")
->AsInput();
eltwise_out_var = pattern->NewNode(eltwise_out_repr())
->AsIntermediate()
->assert_is_only_output_of_op("elementwise_add");
} else {
// Conv output as AffineChannel input
conv_out_var->assert_is_op_input("affine_channel", "X");
}
// AC Scale
auto *ac_scale_var = pattern->NewNode(ac_scale_repr())
->AsInput()
->assert_is_persistable_var()
->assert_has_n_outputs(1)
->assert_is_op_input("affine_channel", "Scale");
// AC Bias
auto *ac_bias_var = pattern->NewNode(ac_bias_repr())
->AsInput()
->assert_is_persistable_var()
->assert_has_n_outputs(1)
->assert_is_op_input("affine_channel", "Bias");
// AC output
auto *ac_out_var = pattern->NewNode(ac_out_repr())
->AsOutput()
->assert_is_op_output("affine_channel");
conv_op->LinksFrom({conv_input, conv_weight_var}).LinksTo({conv_out_var});
if (with_eltwise_add) {
eltwise_op->LinksFrom({conv_out_var, eltwise_y_in_var})
.LinksTo({eltwise_out_var});
affine_channel_op->LinksFrom({eltwise_out_var, ac_scale_var, ac_bias_var})
.LinksTo({ac_out_var});
} else {
affine_channel_op->LinksFrom({conv_out_var, ac_scale_var, ac_bias_var})
.LinksTo({ac_out_var});
}
return ac_out_var;
}
PDNode *patterns::DequantQuantAny::operator()() {
auto *dequant_in = pattern->NewNode(dequant_in_repr())
->AsInput()
->assert_is_op_input("dequantize", "Input");
auto *dequant_op =
pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");
auto *dequant_out = pattern->NewNode(dequant_out_repr())
->AsOutput()
->assert_is_op_output("dequantize", "Output");
auto *quant_op = pattern->NewNode(quant_op_repr())
->assert_is_op("quantize")
->AsIntermediate();
auto *quant_out = pattern->NewNode(quant_out_repr())
->AsOutput()
->assert_is_op_output("quantize");
auto *next_op = pattern->NewNode(next_op_repr())->assert_is_op();
dequant_op->LinksFrom({dequant_in}).LinksTo({dequant_out});
quant_op->LinksFrom({dequant_out}).LinksTo({quant_out});
next_op->LinksFrom({quant_out});
return quant_out;
}
PDNode *patterns::DequantAny::operator()() {
auto *dequant_op =
pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");
auto *dequant_out = pattern->NewNode(dequant_out_repr())
->AsOutput()
->assert_is_op_output("dequantize", "Output");
auto *next_op = pattern->NewNode(next_op_repr())->assert_is_op();
dequant_op->LinksTo({dequant_out});
next_op->LinksFrom({dequant_out});
return dequant_out;
}
PDNode *patterns::MultipleQuantize::operator()() {
auto *prev_out = pattern->NewNode(prev_out_repr())->AsOutput();
// find nodes that are inputs to quantize operators
prev_out->assert_more([&](Node *node) {
int counter = std::count_if(
node->outputs.begin(), node->outputs.end(), [&](Node const *iter) {
return iter && iter->IsOp() && iter->Op()->Type() == "quantize";
});
return (counter > 1);
});
return prev_out;
}
PDNode *patterns::MKLDNNInPlace::operator()() {
const std::unordered_set<std::string> &supported_op_types = {
"abs",
"elementwise_mul",
"elementwise_add",
"gelu",
"leaky_relu",
"relu",
"softmax",
"sqrt",
"swish",
"tanh"};
auto possible_inplace_op = pattern->NewNode(inplace_to_be_op_repr())
->assert_is_ops(supported_op_types);
auto input = pattern->NewNode(inplace_to_be_op_in_repr())
->assert_is_ops_input(supported_op_types)
->AsInput();
auto output = pattern->NewNode(inplace_to_be_op_out_repr())
->assert_is_ops_output(supported_op_types)
->AsOutput();
auto next_op = pattern->NewNode(next_op_repr())->assert_is_op();
auto next_output = pattern->NewNode(next_op_out_repr())->AsOutput();
// Check if op is MKL-DNN enabled
possible_inplace_op->assert_op_attr("use_mkldnn", true);
// linked structure
possible_inplace_op->LinksTo({output});
possible_inplace_op->LinksFrom({input});
next_op->LinksFrom({output});
next_op->LinksTo({next_output});
return possible_inplace_op;
}
// a -> transpose_op(1) -> transpose_out_a -> flatten_op(1) -> flatten_out_a
// b -> transpose_op(2) -> transpose_out_b -> flatten_op(2) -> flatten_out_b
// ...
// z -> transpose_op(n) -> transpose_out_z -> flatten_op(n) -> flatten_out_z
// flatten_out_a -> concat_op flatten_out_b -> concat_op ... flatten_out_z ->
// concat_op
PDNode *patterns::TransposeFlattenConcat::operator()(
std::vector<PDNode *> conv_in, int times) {
// The times represents the repeat times of the
// {trans, trans_out, flatten, flatten_out}
const int kNumFields = 4;
const int kTransOutOffset = 1;
const int kFlattenOffset = 2;
const int kFlattenOutOffset = 3;
std::vector<PDNode *> nodes;
for (int i = 0; i < times; i++) {
nodes.push_back(
pattern->NewNode(GetNodeName("transpose" + std::to_string(i)))
->assert_is_op("transpose2"));
nodes.push_back(
pattern->NewNode(GetNodeName("transpose_out" + std::to_string(i)))
->assert_is_op_output("transpose2")
->assert_is_op_input("flatten2", "X")
->AsIntermediate());
nodes.push_back(pattern->NewNode(GetNodeName("flatten" + std::to_string(i)))
->assert_is_op("flatten2"));
nodes.push_back(
pattern->NewNode(GetNodeName("flatten_out" + std::to_string(i)))
->assert_is_op_output("flatten2")
->assert_is_op_nth_input("concat", "X", i)
->AsIntermediate());
}
auto concat_op = pattern->NewNode(GetNodeName("concat"))
->assert_is_op("concat")
->assert_op_has_n_inputs("concat", times);
auto concat_out = pattern->NewNode(GetNodeName("concat_out"))
->assert_is_op_output("concat")
->AsOutput();
std::vector<PDNode *> flatten_outs;
for (int i = 0; i < times; i++) {
conv_in[i]->AsInput();
// trans
nodes[i * kNumFields]->LinksFrom({conv_in[i]});
// trans_out
nodes[i * kNumFields + kTransOutOffset]->LinksFrom({nodes[i * kNumFields]});
// flatten
nodes[i * kNumFields + kFlattenOffset]->LinksFrom(
{nodes[i * kNumFields + kTransOutOffset]});
// flatten_out
nodes[i * kNumFields + kFlattenOutOffset]->LinksFrom(
{nodes[i * kNumFields + kFlattenOffset]});
flatten_outs.push_back(nodes[i * kNumFields + kFlattenOutOffset]);
}
concat_op->LinksFrom(flatten_outs).LinksTo({concat_out});
return concat_out;
}
void patterns::DeleteQuantOpFuse::operator()(PDNode *input_act_node,
const std::string &quant_type) {
auto *input_scale_node = pattern->NewNode(GetNodeName("input_scale_node"))
->assert_is_op_input(quant_type, "InScale")
->AsInput();
auto *quant_node =
pattern->NewNode(GetNodeName("quant_node"))->assert_is_op(quant_type);
auto *output_scale_node = pattern->NewNode(GetNodeName("output_scale_node"))
->assert_is_op_output(quant_type, "OutScale")
->AsOutput();
auto *output_act_node = pattern->NewNode(GetNodeName("output_act_node"))
->assert_is_op_output(quant_type, "Out")
->AsOutput();
quant_node->LinksFrom({input_scale_node, input_act_node});
output_scale_node->LinksFrom({quant_node});
output_act_node->LinksFrom({quant_node});
}
void patterns::DequantOpFuse::operator()(PDNode *quantized_op_input,
const std::string &quantized_op_type,
const std::string &dequant_type,
const std::string &weight_name) {
auto *quantized_op_weight =
pattern->NewNode(GetNodeName("quantized_op_weight"))
->assert_is_op_input(quantized_op_type, weight_name)
->AsInput();
auto *quantized_op = pattern->NewNode(GetNodeName("quantized_op"))
->assert_is_op(quantized_op_type);
auto *quantized_op_out = pattern->NewNode(GetNodeName("quantized_op_out"))
->assert_is_op_output(quantized_op_type)
->assert_is_op_input(dequant_type, "X");
auto *dequant_op =
pattern->NewNode(GetNodeName("dequant_op"))->assert_is_op(dequant_type);
auto *dequant_op_out = pattern->NewNode(GetNodeName("dequant_op_out"))
->assert_is_op_output(dequant_type, "Out")
->AsOutput();
PDNode *dequant_channel_scale = nullptr;
if (dequant_type == "fake_channel_wise_dequantize_max_abs") {
dequant_channel_scale =
pattern->NewNode(GetNodeName("dequant_channel_scale"))
->assert_is_op_nth_input(dequant_type, "Scales", 0)
->AsInput();
}
quantized_op->LinksFrom({quantized_op_input, quantized_op_weight});
quantized_op_out->LinksFrom({quantized_op});
if (dequant_type == "fake_channel_wise_dequantize_max_abs") {
dequant_op->LinksFrom({quantized_op_out, dequant_channel_scale});
} else {
dequant_op->LinksFrom({quantized_op_out});
}
dequant_op_out->LinksFrom({dequant_op});
}
void patterns::ShuffleChannelPattern::operator()(PDNode *reshape1_in) {
auto reshape1_op =
pattern->NewNode(reshape1_op_repr())->assert_is_op("reshape2");
reshape1_op->assert_more([&](Node *x) {
return BOOST_GET_CONST(std::vector<int>, x->Op()->GetAttr("shape"))
.size() == 5;
});
auto reshape1_out = pattern->NewNode(reshape1_out_repr())
->assert_is_op_output("reshape2", "Out")
->assert_is_op_input("transpose2")
->AsIntermediate();
auto transpose_op =
pattern->NewNode(transpose_op_repr())->assert_is_op("transpose2");
auto transpose_out = pattern->NewNode(transpose_out_repr())
->assert_is_op_output("transpose2", "Out")
->assert_is_op_input("reshape2")
->AsIntermediate();
auto reshape2_op =
pattern->NewNode(reshape2_op_repr())->assert_is_op("reshape2");
auto reshape2_out = pattern->NewNode(reshape2_out_repr())
->assert_is_op_output("reshape2", "Out")
->AsOutput();
reshape1_op->LinksFrom({reshape1_in});
reshape1_out->LinksFrom({reshape1_op});
transpose_op->LinksFrom({reshape1_out});
transpose_out->LinksFrom({transpose_op});
reshape2_op->LinksFrom({transpose_out});
reshape2_out->LinksFrom({reshape2_op});
}
void patterns::DeleteQuantDequantOpPattern::operator()() {
auto any_op_out =
pattern->NewNode(any_op_out_repr())
->assert_is_op_input(
"fake_quantize_dequantize_moving_average_abs_max", "X")
->AsInput();
auto quant_dequant_op_inscale =
pattern->NewNode(quant_dequant_op_inscale_repr())
->assert_is_op_input(
"fake_quantize_dequantize_moving_average_abs_max", "InScale")
->AsInput();
auto quant_dequant_op =
pattern->NewNode(quant_dequant_op_repr())
->assert_is_op("fake_quantize_dequantize_moving_average_abs_max");
auto quant_dequant_out =
pattern->NewNode(quant_dequant_op_out_repr())
->assert_is_op_output(
"fake_quantize_dequantize_moving_average_abs_max", "Out")
->AsIntermediate();
auto quant_dequant_op_outscale =
pattern->NewNode(quant_dequant_op_outscale_repr())
->assert_is_op_output(
"fake_quantize_dequantize_moving_average_abs_max", "OutScale")
->AsOutput();
auto any_op2 = pattern->NewNode(any_op2_repr())->assert_is_op()->AsOutput();
quant_dequant_op->LinksFrom({any_op_out, quant_dequant_op_inscale});
quant_dequant_op_outscale->LinksFrom({quant_dequant_op});
quant_dequant_out->LinksFrom({quant_dequant_op});
any_op2->LinksFrom({quant_dequant_out});
}
PDNode *patterns::ReshapeTransposeMatmulPattern::operator()(
bool with_reshape_xshape, bool with_transpose_xshape) {
auto reshape_op =
pattern->NewNode(reshape_op_repr())->assert_is_op("reshape2");
auto transpose_op =
pattern->NewNode(transpose_op_repr())->assert_is_op("transpose2");
auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
auto reshape_in = pattern->NewNode(reshape_in_repr())
->AsInput()
->assert_is_op_input("reshape2", "X");
auto reshape_out = pattern->NewNode(reshape_out_repr())
->AsIntermediate()
->assert_is_op_input("transpose2", "X")
->assert_is_op_output("reshape2", "Out");
if (!with_reshape_xshape)
reshape_out->assert_is_only_output_of_op("reshape2");
auto reshape_xshape = with_reshape_xshape
? pattern->NewNode(reshape_xshape_repr())
->AsIntermediate()
->assert_is_op_output("reshape2", "XShape")
: nullptr;
auto transpose_out = pattern->NewNode(transpose_out_repr())
->AsIntermediate()
->assert_is_op_input("matmul")
->assert_is_op_output("transpose2", "Out");
if (!with_transpose_xshape)
transpose_out->assert_is_only_output_of_op("transpose2");
auto transpose_xshape =
with_transpose_xshape
? pattern->NewNode(transpose_xshape_repr())
->AsIntermediate()
->assert_is_op_output("transpose2", "XShape")
: nullptr;
auto matmul_out = pattern->NewNode(matmul_out_repr())
->AsOutput()
->assert_is_op_output("matmul", "Out");
reshape_op->LinksFrom({reshape_in}).LinksTo({reshape_out});
if (with_reshape_xshape) reshape_op->LinksTo({reshape_xshape});
transpose_op->LinksFrom({reshape_out}).LinksTo({transpose_out});
if (with_transpose_xshape) transpose_op->LinksTo({transpose_xshape});
matmul_op->LinksFrom({transpose_out}).LinksTo({matmul_out});
return matmul_out;
}
PDNode *patterns::MatmulTransposeReshapePattern::operator()() {
auto reshape_op =
pattern->NewNode(reshape_op_repr())->assert_is_op("reshape2");
auto transpose_op =
pattern->NewNode(transpose_op_repr())->assert_is_op("transpose2");
auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
auto matmul_out = pattern->NewNode(matmul_out_repr())
->AsInput()
->assert_is_op_output("matmul", "Out")
->assert_is_op_input("transpose2", "X");
auto transpose_out = pattern->NewNode(transpose_out_repr())
->AsIntermediate()
->assert_is_op_output("transpose2", "Out")
->assert_is_op_input("reshape2", "X");
auto transpose_out_xshape = pattern->NewNode(transpose_out_xshape_repr())
->AsIntermediate()
->assert_is_op_output("transpose2", "XShape");
auto reshape_out = pattern->NewNode(reshape_out_repr())
->AsOutput()
->assert_is_op_output("reshape2");
auto reshape_out_xshape = pattern->NewNode(reshape_out_xshape_repr())
->AsIntermediate()
->assert_is_op_output("reshape2", "XShape");
matmul_op->LinksTo({matmul_out});
transpose_op->LinksTo({transpose_out_xshape});
reshape_op->LinksTo({reshape_out_xshape});
transpose_op->LinksFrom({matmul_out}).LinksTo({transpose_out});
reshape_op->LinksFrom({transpose_out}).LinksTo({reshape_out});
return reshape_out;
}
} // namespace ir
} // namespace framework
} // namespace paddle
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/event-hook.h"
#include "hphp/runtime/base/types.h"
#include "hphp/runtime/vm/func.h"
#include "hphp/runtime/vm/jit/mc-generator.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/ext/ext_function.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/runtime/base/thread-info.h"
#include "hphp/runtime/ext/ext_xenon.h"
namespace HPHP {
static StaticString s_args("args");
static StaticString s_enter("enter");
static StaticString s_exit("exit");
static StaticString s_exception("exception");
static StaticString s_name("name");
static StaticString s_return("return");
// implemented in runtime/ext/ext_hotprofiler.cpp
extern void begin_profiler_frame(Profiler *p, const char *symbol);
extern void end_profiler_frame(Profiler *p, const char *symbol);
void EventHook::Enable() {
ThreadInfo::s_threadInfo->m_reqInjectionData.setEventHookFlag();
}
void EventHook::Disable() {
ThreadInfo::s_threadInfo->m_reqInjectionData.clearEventHookFlag();
}
void EventHook::EnableIntercept() {
ThreadInfo::s_threadInfo->m_reqInjectionData.setInterceptFlag();
}
void EventHook::DisableIntercept() {
ThreadInfo::s_threadInfo->m_reqInjectionData.clearInterceptFlag();
}
ssize_t EventHook::CheckSurprise() {
ThreadInfo* info = ThreadInfo::s_threadInfo.getNoCheck();
return check_request_surprise(info);
}
class ExecutingSetprofileCallbackGuard {
public:
ExecutingSetprofileCallbackGuard() {
g_context->m_executingSetprofileCallback = true;
}
~ExecutingSetprofileCallbackGuard() {
g_context->m_executingSetprofileCallback = false;
}
};
namespace {
bool shouldRunUserProfiler(const Func* func) {
// Don't do anything if we are running the profiling function itself
// or if we haven't set up a profiler.
if (g_context->m_executingSetprofileCallback ||
g_context->m_setprofileCallback.isNull()) {
return false;
}
// Don't profile 86ctor, since its an implementation detail,
// and we dont guarantee to call it
if (func->cls() && func == func->cls()->getCtor() &&
Func::isSpecial(func->name())) {
return false;
}
return true;
}
void runUserProfilerOnFunctionEnter(const ActRec* ar) {
JIT::VMRegAnchor _;
ExecutingSetprofileCallbackGuard guard;
Array params;
params.append(s_enter);
params.append(VarNR(ar->func()->fullName()));
Array frameinfo;
frameinfo.set(s_args, hhvm_get_frame_args(ar, 0));
params.append(frameinfo);
vm_call_user_func(g_context->m_setprofileCallback, params);
}
void runUserProfilerOnFunctionExit(const ActRec* ar, TypedValue* retval) {
JIT::VMRegAnchor _;
ExecutingSetprofileCallbackGuard guard;
Array params;
params.append(s_exit);
params.append(VarNR(ar->func()->fullName()));
Array frameinfo;
if (!g_context->m_faults.empty()) {
Fault fault = g_context->m_faults.back();
if (fault.m_faultType == Fault::Type::UserException) {
frameinfo.set(s_exception, fault.m_userException);
}
} else if (retval) {
frameinfo.set(s_return, tvAsCVarRef(retval));
}
params.append(frameinfo);
vm_call_user_func(g_context->m_setprofileCallback, params);
}
}
static Array get_frame_args_with_ref(const ActRec* ar) {
int numParams = ar->func()->numParams();
int numArgs = ar->numArgs();
PackedArrayInit retArray(numArgs);
auto local = reinterpret_cast<TypedValue*>(
uintptr_t(ar) - sizeof(TypedValue)
);
for (int i = 0; i < numArgs; ++i) {
if (i < numParams) {
// This corresponds to one of the function's formal parameters, so it's
// on the stack.
retArray.appendWithRef(tvAsCVarRef(local));
--local;
} else {
// This is not a formal parameter, so it's in the ExtraArgs.
retArray.appendWithRef(tvAsCVarRef(ar->getExtraArg(i - numParams)));
}
}
return retArray.toArray();
}
bool EventHook::RunInterceptHandler(ActRec* ar) {
const Func* func = ar->func();
if (LIKELY(func->maybeIntercepted() == 0)) return true;
// Intercept only original generator / async function calls, not resumption.
if (ar->resumed()) return true;
Variant* h = get_intercept_handler(func->fullNameStr(),
&func->maybeIntercepted());
if (!h) return true;
/*
* In production mode, only functions that we have assumed can be
* intercepted during static analysis should actually be
* intercepted.
*/
if (RuntimeOption::RepoAuthoritative &&
!RuntimeOption::EvalJitEnableRenameFunction) {
if (!(func->attrs() & AttrInterceptable)) {
raise_error("fb_intercept was used on a non-interceptable function (%s) "
"in RepoAuthoritative mode", func->fullName()->data());
}
}
JIT::VMRegAnchor _;
PC savePc = g_context->m_pc;
Variant doneFlag = true;
Variant called_on;
if (ar->hasThis()) {
called_on = Variant(ar->getThis());
} else if (ar->hasClass()) {
// For static methods, give handler the name of called class
called_on = Variant(const_cast<StringData*>(ar->getClass()->name()));
}
Variant intArgs =
PackedArrayInit(5)
.append(VarNR(ar->func()->fullName()))
.append(called_on)
.append(get_frame_args_with_ref(ar))
.append(h->asCArrRef()[1])
.appendRef(doneFlag)
.toArray();
Variant ret = vm_call_user_func(h->asCArrRef()[0], intArgs);
if (doneFlag.toBoolean()) {
Offset pcOff;
ActRec* outer = g_context->getPrevVMState(ar, &pcOff);
frame_free_locals_inl_no_hook<true>(ar, ar->func()->numLocals());
Stack& stack = g_context->getStack();
stack.top() = (Cell*)(ar + 1);
cellDup(*ret.asCell(), *stack.allocTV());
g_context->m_fp = outer;
g_context->m_pc = outer ? outer->func()->unit()->at(pcOff) : nullptr;
return false;
}
g_context->m_fp = ar;
g_context->m_pc = savePc;
return true;
}
const char* EventHook::GetFunctionNameForProfiler(const Func* func,
int funcType) {
const char* name;
switch (funcType) {
case EventHook::NormalFunc:
name = func->fullName()->data();
if (name[0] == '\0') {
// We're evaling some code for internal purposes, most
// likely getting the default value for a function parameter
name = "{internal}";
}
break;
case EventHook::PseudoMain:
name = makeStaticString(
std::string("run_init::") + func->unit()->filepath()->data())
->data();
break;
case EventHook::Eval:
name = "_";
break;
default:
not_reached();
}
return name;
}
bool EventHook::onFunctionEnter(const ActRec* ar, int funcType) {
ssize_t flags = CheckSurprise();
Xenon::getInstance().log(true);
if (flags & RequestInjectionData::InterceptFlag &&
!RunInterceptHandler(const_cast<ActRec*>(ar))) {
return false;
}
if (flags & RequestInjectionData::EventHookFlag) {
if (shouldRunUserProfiler(ar->func())) {
runUserProfilerOnFunctionEnter(ar);
}
#ifdef HOTPROFILER
Profiler* profiler = ThreadInfo::s_threadInfo->m_profiler;
if (profiler != nullptr) {
begin_profiler_frame(profiler,
GetFunctionNameForProfiler(ar->func(), funcType));
}
#endif
}
return true;
}
void EventHook::onFunctionExit(ActRec* ar, TypedValue* retval) {
// Null out $this for the exiting function, it has been decref'd so it's
// garbage.
//
// NB: This function is also run on async functions that are suspending, so
// we need to check that the function is actually returning.
JIT::VMRegAnchor _;
switch (static_cast<Op>(*g_context->getPC())) {
case OpRetC:
case OpRetV:
ar->setThisOrClassAllowNull(nullptr);
default: break;
}
auto const inlinedRip = JIT::tx->uniqueStubs.retInlHelper;
if ((JIT::TCA)ar->m_savedRip == inlinedRip) {
// Inlined calls normally skip the function enter and exit events. If we
// side exit in an inlined callee, we want to make sure to skip the exit
// event to avoid unbalancing the call stack.
return;
}
Xenon::getInstance().log(false);
#ifdef HOTPROFILER
Profiler* profiler = ThreadInfo::s_threadInfo->m_profiler;
if (profiler != nullptr) {
// NB: we don't have a function type flag to match what we got in
// onFunctionEnter. That's okay, though... we tolerate this in
// TraceProfiler.
end_profiler_frame(profiler,
GetFunctionNameForProfiler(ar->func(), NormalFunc));
}
#endif
// If we have a pending exception, then we're in the process of unwinding
// for that exception. We avoid running more PHP code (the user profiler) and
// also avoid raising more exceptions for surprises (including the pending
// exception).
if (ThreadInfo::s_threadInfo->m_pendingException == nullptr) {
if (shouldRunUserProfiler(ar->func())) {
runUserProfilerOnFunctionExit(ar, retval);
}
// XXX Disabled until t2329497 is fixed:
// CheckSurprise();
}
}
} // namespace HPHP
|
/* Copyright 2018 The TensorFlow Authors. All 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.
==============================================================================*/
#ifdef INTEL_MKL
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/ops/nn_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/kernels/conv_ops_gpu.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
namespace tensorflow {
// Helper class for converting MKL tensors to TF tensors and comparing to
// expected values
static const uint8 dummy_tensor[] = {0, 0, 0, 0, 0, 0, 0, 0};
static const TensorShape dummy_shape({8});
using BiasAddGraphRunner =
std::function<void(const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data, Tensor* out)>;
using FusedGraphRunner =
std::function<void(const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data,
const std::vector<string>& fused_ops, Tensor* out)>;
template <typename T>
class CommonTestUtilities : public OpsTestBase {
public:
void PerformConversion(DataType dtype, const Tensor& tensor,
const Tensor& mkl_meta_tensor, Tensor* output) {
// Create an MKL to TF conversion node and execute it
TF_EXPECT_OK(NodeDefBuilder("mkl_to_tf_op", "_MklToTf")
.Input(FakeInput(dtype)) // Input
.Input(FakeInput(DT_UINT8)) // Mkl second tensor
.Attr("T", dtype)
.Attr("_kernel", "MklLayoutDependentOp")
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
AddInputFromArray<T>(tensor.shape(), tensor.flat<T>());
AddInputFromArray<uint8>(mkl_meta_tensor.shape(),
mkl_meta_tensor.flat<uint8>());
TF_ASSERT_OK(RunOpKernel());
*output = *GetOutput(0);
}
// Runs a Tensorflow graph defined by the root scope, and fetches the result
// of 'fetch' node into the output Tensor.
static void RunAndFetch(const tensorflow::Scope& root, const string& fetch,
Tensor* output) {
tensorflow::GraphDef graph;
TF_ASSERT_OK(root.ToGraphDef(&graph));
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions()));
TF_ASSERT_OK(session->Create(graph));
std::vector<Tensor> unfused_tensors;
TF_ASSERT_OK(session->Run({}, {fetch}, {}, &unfused_tensors));
*output = unfused_tensors[0];
}
void ConvertAndCompare(DataType dtype, const Tensor& tensor,
const Tensor& mkl_meta_tensor,
const Tensor& expected) {
Tensor output;
PerformConversion(dtype, tensor, mkl_meta_tensor, &output);
test::ExpectTensorNear<T>(expected, output, 1e-5);
}
void ConvertAndCompareIntegral(DataType dtype, const Tensor& tensor,
const Tensor& mkl_meta_tensor,
const Tensor& expected) {
Tensor output;
PerformConversion(dtype, tensor, mkl_meta_tensor, &output);
test::ExpectTensorEqual<T>(expected, output);
}
void TestBody() {}
static void VerifyBiasAddTensorsClose(int depth, int image_width,
int image_height, int image_batch_count,
int filter_size, int filter_count,
const BiasAddGraphRunner& run_default,
const BiasAddGraphRunner& run_fused) {
DataType dtype = DataTypeToEnum<T>::v();
Tensor image(dtype, {image_batch_count, image_height, image_width, depth});
image.flat<T>() = image.flat<T>().template setRandom<random_gen_>();
Tensor filter(dtype, {filter_size, filter_size, depth, filter_count});
filter.flat<T>() = filter.flat<T>().template setRandom<random_gen_>();
const int bias_size = filter_count;
Tensor bias(dtype, {bias_size});
bias.flat<T>() = bias.flat<T>().template setRandom<random_gen_>();
Tensor conv_2d;
Tensor fused_conv_2d;
run_default(image, filter, bias, &conv_2d);
run_fused(image, filter, bias, &fused_conv_2d);
ASSERT_EQ(conv_2d.dtype(), fused_conv_2d.dtype());
ASSERT_EQ(conv_2d.shape(), fused_conv_2d.shape());
test::ExpectClose(conv_2d, fused_conv_2d, 1e-5);
}
static void VerifyFusedTensorsClose(int depth, int image_width,
int image_height, int image_batch_count,
int filter_size, int filter_count,
const std::vector<string>& fused_ops,
const FusedGraphRunner& run_default,
const FusedGraphRunner& run_fused) {
DataType dtype = DataTypeToEnum<T>::v();
Tensor image(dtype, {image_batch_count, image_height, image_width, depth});
image.flat<T>() = image.flat<T>().template setRandom<random_gen_>();
Tensor filter(dtype, {filter_size, filter_size, depth, filter_count});
filter.flat<T>() = filter.flat<T>().template setRandom<random_gen_>();
const int bias_size = filter_count;
Tensor bias(dtype, {bias_size});
bias.flat<T>() = bias.flat<T>().template setRandom<random_gen_>();
Tensor conv_2d;
Tensor fused_conv_2d;
run_default(image, filter, bias, fused_ops, &conv_2d);
run_fused(image, filter, bias, fused_ops, &fused_conv_2d);
ASSERT_EQ(conv_2d.dtype(), fused_conv_2d.dtype());
ASSERT_EQ(conv_2d.shape(), fused_conv_2d.shape());
test::ExpectClose(conv_2d, fused_conv_2d, 1e-5);
}
static void VerifyFusedMatrixClose(int depth, int batch, int weight_count,
const std::vector<string>& fused_ops,
const FusedGraphRunner& run_default,
const FusedGraphRunner& run_fused) {
DataType dtype = DataTypeToEnum<T>::v();
Tensor input(dtype, {batch, depth});
input.flat<T>() = input.flat<T>().template setRandom<random_gen_>();
Tensor weight(dtype, {depth, weight_count});
weight.flat<T>() = weight.flat<T>().template setRandom<random_gen_>();
Tensor bias(dtype, {weight_count});
bias.flat<T>() = bias.flat<T>().template setRandom<random_gen_>();
Tensor output;
Tensor fused_output;
run_default(input, weight, bias, fused_ops, &output);
run_fused(input, weight, bias, fused_ops, &fused_output);
ASSERT_EQ(output.dtype(), fused_output.dtype());
ASSERT_EQ(output.shape(), fused_output.shape());
test::ExpectClose(output, fused_output, 1e-5);
}
private:
using random_gen_ = Eigen::internal::NormalRandomGenerator<T>;
};
// Testing MKL's fused convolution ops
template <typename T>
class MklFusedConv2DOpTest : public OpsTestBase {
protected:
static constexpr int kDepth = 3;
static constexpr int kImageWidth = 32;
static constexpr int kImageHeight = 32;
static constexpr int kImageBatchCount = 8;
void RunConv2DUnfused(const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data,
const std::vector<string>& fused_ops, Tensor* output,
int stride = 1) {
auto root = tensorflow::Scope::NewRootScope();
auto input_data_op =
ops::Const(root.WithOpName("input"), Input::Initializer(input_data));
Output next_op = ops::Conv2D(
root.WithOpName("conv"), input_data_op,
ops::Const(root.WithOpName("filter"), Input::Initializer(filter_data)),
{1, stride, stride, 1}, "SAME");
string last_op = "";
if (std::find(fused_ops.begin(), fused_ops.end(), "BiasAdd") !=
fused_ops.end()) {
last_op = "with_bias";
next_op = ops::BiasAdd(
root.WithOpName(last_op), next_op,
ops::Const(root.WithOpName("bias"), Input::Initializer(bias_data)));
}
if (std::find(fused_ops.begin(), fused_ops.end(), "Add") !=
fused_ops.end()) {
last_op = "with_add";
next_op = ops::AddN(root.WithOpName("with_add"),
std::initializer_list<Input>{next_op, input_data_op});
}
if (std::find(fused_ops.begin(), fused_ops.end(), "Relu") !=
fused_ops.end()) {
last_op = "with_relu";
next_op = ops::Relu(root.WithOpName(last_op), next_op);
}
if (std::find(fused_ops.begin(), fused_ops.end(), "Relu6") !=
fused_ops.end()) {
last_op = "with_relu6";
next_op = ops::Relu6(root.WithOpName(last_op), next_op);
}
if (std::find(fused_ops.begin(), fused_ops.end(), "Elu") !=
fused_ops.end()) {
last_op = "with_elu";
next_op = ops::Elu(root.WithOpName(last_op), next_op);
}
CommonTestUtilities<T>::RunAndFetch(root, last_op, output);
}
void RunMklFusedConv2DOp(const Tensor& image, const Tensor& filter,
const std::vector<Tensor>& args,
const std::vector<string>& fused_ops, Tensor* output,
int stride = 1) {
DataType dtype = DataTypeToEnum<T>::v();
int num_args = static_cast<int>(args.size());
TF_EXPECT_OK(NodeDefBuilder("fused_conv_op", "_MklFusedConv2D")
.Input(FakeInput(dtype))
.Input(FakeInput(dtype))
.Input(FakeInput(num_args, dtype))
.Input(FakeInput(DT_UINT8))
.Input(FakeInput(DT_UINT8))
.Input(FakeInput(num_args, DT_UINT8))
.Attr("T", dtype)
.Attr("num_args", num_args)
.Attr("strides", {1, stride, stride, 1})
.Attr("padding", "SAME")
.Attr("fused_ops", fused_ops)
.Attr("_kernel", "MklLayoutDependentOp")
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
AddInputFromArray<T>(image.shape(), image.flat<T>());
AddInputFromArray<T>(filter.shape(), filter.flat<T>());
for (const Tensor& arg : args)
AddInputFromArray<T>(arg.shape(), arg.flat<T>());
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
for (const Tensor& arg : args)
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
TF_ASSERT_OK(RunOpKernel());
// Compare output to expected results
const Tensor& output_tensor = *GetOutput(0);
// Index 2 will need to be changed if the number of outputs produced
// by MklConv2D change.
const Tensor& output_meta_tensor = *GetOutput(2);
CommonTestUtilities<T> test_util;
test_util.PerformConversion(dtype, output_tensor, output_meta_tensor,
output);
}
// Verifies computing unfused ops in a graph is identical to FusedConv2D.
void VerifyFusedConv2D(int filter_size, int filter_count,
const std::vector<string>& fused_ops,
int depth = kDepth, int image_width = kImageWidth,
int image_height = kImageHeight,
int image_batch_count = kImageBatchCount) {
const FusedGraphRunner run_default =
[this](const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data, const std::vector<string>& fused_ops,
Tensor* out) {
RunConv2DUnfused(input_data, filter_data, bias_data, fused_ops, out);
};
const FusedGraphRunner run_fused =
[this](const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data, const std::vector<string>& fused_ops,
Tensor* out) {
std::vector<Tensor> fused_input = {bias_data};
if (std::find(fused_ops.begin(), fused_ops.end(), "Add") !=
fused_ops.end()) {
fused_input.push_back(input_data);
}
RunMklFusedConv2DOp(input_data, filter_data, fused_input, fused_ops,
out);
};
CommonTestUtilities<T>::VerifyFusedTensorsClose(
depth, image_width, image_height, image_batch_count, filter_size,
filter_count, fused_ops, run_default, run_fused);
}
};
template <typename T>
class MklFusedConv2DWithBiasOpTest : public MklFusedConv2DOpTest<T> {};
TYPED_TEST_CASE_P(MklFusedConv2DWithBiasOpTest);
// -------------------------------------------------------------------------- //
// Conv2D + BiasAdd + {Activation} //
// -------------------------------------------------------------------------- //
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolution) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolution) {
const int kFilterSize = 3;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndRelu) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndRelu) {
const int kFilterSize = 3;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndRelu6) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu6"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndRelu6) {
const int kFilterSize = 3;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu6"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndElu) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Elu"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndElu) {
const int kFilterSize = 3;
const int kFilterCount = 12;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Elu"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAdd) {
const int kFilterSize = 1;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAdd) {
const int kFilterSize = 3;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAddRelu) {
const int kFilterSize = 1;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount,
{"BiasAdd", "Add", "Relu"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAddRelu) {
const int kFilterSize = 3;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount,
{"BiasAdd", "Add", "Relu"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAddRelu6) {
const int kFilterSize = 1;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount,
{"BiasAdd", "Add", "Relu6"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAddRelu6) {
const int kFilterSize = 3;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount,
{"BiasAdd", "Add", "Relu6"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAddElu) {
const int kFilterSize = 1;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add", "Elu"});
}
TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAddElu) {
const int kFilterSize = 3;
const int kFilterCount = 3;
this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add", "Elu"});
}
REGISTER_TYPED_TEST_CASE_P(
MklFusedConv2DWithBiasOpTest, OneByOneConvolution, SpatialConvolution,
OneByOneConvolutionAndRelu, SpatialConvolutionAndRelu,
OneByOneConvolutionAndRelu6, SpatialConvolutionAndRelu6,
OneByOneConvolutionAndElu, SpatialConvolutionAndElu,
OneByOneConvolutionAndAdd, SpatialConvolutionAndAdd,
OneByOneConvolutionAndAddRelu, SpatialConvolutionAndAddRelu,
OneByOneConvolutionAndAddRelu6, SpatialConvolutionAndAddRelu6,
OneByOneConvolutionAndAddElu, SpatialConvolutionAndAddElu);
using MklFusedBiasAddDataTypes = ::testing::Types<float>;
INSTANTIATE_TYPED_TEST_CASE_P(Test, MklFusedConv2DWithBiasOpTest,
MklFusedBiasAddDataTypes);
// Testing fusion of pad and convolution
class FusedPadConvOpTest : public OpsTestBase {
public:
template <typename T>
void Run(DataType dtype, Tensor& image, Tensor& filter, Tensor& padding,
Tensor& expected, const string data_format) {
const int stride = 1;
// Create a fused pad+conv2d node
TF_EXPECT_OK(NodeDefBuilder("fused_pad_conv_op", "_MklPadWithConv2D")
.Input(FakeInput(dtype)) // Input
.Input(FakeInput(dtype)) // Filter
.Input(FakeInput(DT_INT32)) // Padding
.Input(FakeInput(DT_UINT8)) // MKl second tensor
.Input(FakeInput(DT_UINT8)) // MKl second tensor
.Input(FakeInput(DT_UINT8)) // MKl second tensor
.Attr("padding", "VALID")
.Attr("data_format", data_format)
.Attr("T", dtype)
.Attr("strides", {1, stride, stride, 1})
.Attr("_kernel", "MklLayoutDependentOp")
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
// Setting up inputs and execute
AddInputFromArray<T>(image.shape(), image.flat<T>());
AddInputFromArray<T>(filter.shape(), filter.flat<T>());
AddInputFromArray<int32>(padding.shape(), padding.flat<int32>());
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
TF_ASSERT_OK(RunOpKernel());
// Compare output to expected results
const Tensor& first = *GetOutput(0);
const Tensor& second = *GetOutput(2);
CommonTestUtilities<T> test_util;
test_util.ConvertAndCompare(dtype, first, second, expected);
}
};
TEST_F(FusedPadConvOpTest, PaddingConvTest) {
const int depth = 1;
const int image_width = 4;
const int image_height = 3;
const int image_batch_count = 1;
Tensor image(DT_FLOAT, {image_batch_count, image_height, image_width, depth});
test::FillValues<float>(&image, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
const int kFilterSize = 3;
const int kFilterCount = 1;
Tensor filter(DT_FLOAT, {kFilterSize, kFilterSize, depth, kFilterCount});
test::FillValues<float>(&filter, {1, 4, 7, 2, 5, 8, 3, 6, 9});
const int padding_height = 4;
const int padding_width = 2;
Tensor padding(DT_INT32, {padding_height, padding_width});
test::FillValues<int32>(&padding, {0, 0, 3, 4, 1, 2, 0, 0});
Tensor expected(DT_FLOAT, TensorShape({1, 8, 5, 1}));
test::FillValues<float>(
&expected,
{0, 0, 0, 0, 0, 24, 42, 60, 33, 12, 105, 150, 183, 95,
32, 235, 312, 357, 178, 56, 187, 234, 261, 121, 32, 106, 126, 138,
59, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
Run<float>(DT_FLOAT, image, filter, padding, expected, "NHWC");
}
TEST_F(FusedPadConvOpTest, PaddingConvTestNchw) {
const int depth = 1;
const int image_width = 4;
const int image_height = 3;
const int image_batch_count = 1;
Tensor image(DT_FLOAT, {image_batch_count, depth, image_height, image_width});
test::FillValues<float>(&image, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
const int kFilterSize = 3;
const int kFilterCount = 1;
Tensor filter(DT_FLOAT, {kFilterSize, kFilterSize, depth, kFilterCount});
test::FillValues<float>(&filter, {1, 4, 7, 2, 5, 8, 3, 6, 9});
const int padding_height = 4;
const int padding_width = 2;
Tensor padding(DT_INT32, {padding_height, padding_width});
test::FillValues<int32>(&padding, {0, 0, 0, 0, 3, 4, 1, 2});
Tensor expected(DT_FLOAT, TensorShape({1, 1, 8, 5}));
test::FillValues<float>(
&expected,
{0, 0, 0, 0, 0, 24, 42, 60, 33, 12, 105, 150, 183, 95,
32, 235, 312, 357, 178, 56, 187, 234, 261, 121, 32, 106, 126, 138,
59, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
Run<float>(DT_FLOAT, image, filter, padding, expected, "NCHW");
}
class FilterCacheTest : public OpsTestBase {
public:
template <typename T>
void Run(DataType dtype, Tensor& image, Tensor& filter, Tensor& expected,
const bool is_filter_const) {
const int stride = 1;
TF_EXPECT_OK(NodeDefBuilder("conv2d_filter_cache", "_MklConv2D")
.Input(FakeInput(dtype)) // Input
.Input(FakeInput(dtype)) // Filter
.Input(FakeInput(DT_UINT8)) // MKl second tensor
.Input(FakeInput(DT_UINT8)) // MKl second tensor
.Attr("padding", "VALID")
.Attr("data_format", "NHWC")
.Attr("is_filter_const", is_filter_const)
.Attr("T", dtype)
.Attr("strides", {1, stride, stride, 1})
.Attr("_kernel", "MklLayoutDependentOp")
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
// Setting up inputs and execute
AddInputFromArray<T>(image.shape(), image.flat<T>());
AddInputFromArray<T>(filter.shape(), filter.flat<T>());
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
TF_ASSERT_OK(RunOpKernel());
// Compare outputs to expected results
const Tensor& output = *GetOutput(0);
const Tensor& output_layout = *GetOutput(2);
CommonTestUtilities<T> conv_comp;
conv_comp.ConvertAndCompare(dtype, output, output_layout, expected);
// TODO(bhavanis): For now, we rely on internal performance tests to
// determine if filter data is being cached and reused.
// However, we still need to add a check here to determine if this is
// still the case by inspecting the contents of the persistent tensor.
TF_ASSERT_OK(RunOpKernel());
// Compare output to expected results
const Tensor& output_new = *GetOutput(0);
const Tensor& output_layout_new = *GetOutput(2);
CommonTestUtilities<T> conv_comp_new;
conv_comp_new.ConvertAndCompare(dtype, output_new, output_layout_new,
expected);
}
};
TEST_F(FilterCacheTest, Conv2DFilterCacheTest) {
const int depth = 1;
const int image_width = 4;
const int image_height = 3;
const int image_batch_count = 1;
Tensor image(DT_FLOAT, {image_batch_count, image_height, image_width, depth});
test::FillValues<float>(&image, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
const int kFilterSize = 3;
const int kFilterCount = 1;
Tensor filter(DT_FLOAT, {kFilterSize, kFilterSize, depth, kFilterCount});
test::FillValues<float>(&filter, {1, 4, 7, 2, 5, 8, 3, 6, 9});
Tensor expected(DT_FLOAT, TensorShape({1, 1, 2, 1}));
test::FillValues<float>(&expected, {312, 357});
Run<float>(DT_FLOAT, image, filter, expected, true);
}
// Testing fusion of MatMul and BiasAdd
template <typename T>
class MklFusedMatMulOpTest : public OpsTestBase {
protected:
void VerifyFusedMatMul(const int kBatch, const int kInputChannel,
const int kOutputChannel) {
const FusedGraphRunner run_default =
[this](const Tensor& input, const Tensor& weight, const Tensor& bias,
const std::vector<string>& fused_ops, Tensor* output) {
auto root = tensorflow::Scope::NewRootScope();
auto input_op =
ops::Const(root.WithOpName("input"), Input::Initializer(input));
Output next_op = ops::MatMul(root.WithOpName("matmul"), input_op,
ops::Const(root.WithOpName("weight"),
Input::Initializer(weight)));
string last_op = "";
if (std::find(fused_ops.begin(), fused_ops.end(), "BiasAdd") !=
fused_ops.end()) {
last_op = "with_bias";
next_op = ops::BiasAdd(
root.WithOpName(last_op), next_op,
ops::Const(root.WithOpName("bias"), Input::Initializer(bias)));
}
CommonTestUtilities<T>::RunAndFetch(root, last_op, output);
};
const FusedGraphRunner run_fused =
[this](const Tensor& input, const Tensor& weight, const Tensor& bias,
const std::vector<string>& fused_ops, Tensor* output) {
DataType dtype = DataTypeToEnum<T>::v();
const int num_args = fused_ops.size();
TF_EXPECT_OK(NodeDefBuilder("MklFusedMatMul", "_MklFusedMatMul")
.Input(FakeInput(dtype))
.Input(FakeInput(dtype))
.Input(FakeInput(num_args, dtype))
.Input(FakeInput(DT_UINT8))
.Input(FakeInput(DT_UINT8))
.Input(FakeInput(num_args, DT_UINT8))
.Attr("T", dtype)
.Attr("transpose_a", false)
.Attr("transpose_b", false)
.Attr("num_args", num_args)
.Attr("fused_ops", fused_ops)
.Attr("epsilon", 0.0001)
.Attr("_kernel", "MklLayoutDependentOp")
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
AddInputFromArray<T>(input.shape(), input.flat<T>());
AddInputFromArray<T>(weight.shape(), weight.flat<T>());
AddInputFromArray<T>(bias.shape(), bias.flat<T>());
// Add MKL meta input for input, filter and bias.
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
TF_ASSERT_OK(RunOpKernel());
const Tensor& output_tensor = *GetOutput(0);
const Tensor& output_meta_tensor = *GetOutput(1);
CommonTestUtilities<T> test_util;
test_util.PerformConversion(dtype, output_tensor, output_meta_tensor,
output);
};
CommonTestUtilities<T>::VerifyFusedMatrixClose(kInputChannel, kBatch,
kOutputChannel, {"BiasAdd"},
run_default, run_fused);
}
};
TYPED_TEST_CASE_P(MklFusedMatMulOpTest);
TYPED_TEST_P(MklFusedMatMulOpTest, BasicTest) {
const int batch = 3;
const int input_channel = 4;
const int output_channel = 5;
this->VerifyFusedMatMul(batch, input_channel, output_channel);
}
REGISTER_TYPED_TEST_CASE_P(MklFusedMatMulOpTest, BasicTest);
using MklFusedMatMulDataTypes = ::testing::Types<float>;
INSTANTIATE_TYPED_TEST_CASE_P(Test, MklFusedMatMulOpTest,
MklFusedMatMulDataTypes);
class BiasCacheTest : public OpsTestBase {
public:
template <typename T>
void Run(DataType dtype, Tensor& image, Tensor& filter, Tensor& bias,
Tensor& min_input, Tensor& max_input, Tensor& min_filter,
Tensor& max_filter, Tensor& min_output, Tensor& max_output,
Tensor& expected, const bool is_filter_const) {
const int stride = 1;
TF_EXPECT_OK(
NodeDefBuilder("quantized_conv2d_bias_cache",
"_MklQuantizedConv2DWithBiasAndReluAndRequantize")
.Input(FakeInput(dtype)) // Input
.Input(FakeInput(DT_QINT8)) // Filter
.Input(FakeInput(DT_FLOAT)) // Bias
.Input(FakeInput(DT_FLOAT)) // Min-input
.Input(FakeInput(DT_FLOAT)) // Max-input
.Input(FakeInput(DT_FLOAT)) // Min-filter
.Input(FakeInput(DT_FLOAT)) // Max-filter
.Input(FakeInput(DT_FLOAT)) // Min-output
.Input(FakeInput(DT_FLOAT)) // Max-output
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Input(FakeInput(DT_UINT8)) // MKL second tensor
.Attr("Tinput", DT_QUINT8)
.Attr("Tfilter", DT_QINT8)
.Attr("Tbias", DT_FLOAT)
.Attr("T", DT_QINT8)
.Attr("out_type", DT_QUINT8)
.Attr("data_format", "NHWC")
.Attr("strides", {1, stride, stride, 1})
.Attr("is_filter_const", is_filter_const)
.Attr("is_bias_const", true)
.Attr("padding", "VALID")
.Attr("_kernel", "QuantizedMklOp")
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
// Setting up inputs and execute
AddInputFromArray<quint8>(image.shape(), image.flat<quint8>());
AddInputFromArray<qint8>(filter.shape(), filter.flat<qint8>());
AddInputFromArray<float>(bias.shape(), bias.flat<float>());
AddInputFromArray<float>(min_input.shape(), min_input.flat<float>());
AddInputFromArray<float>(max_input.shape(), max_input.flat<float>());
AddInputFromArray<float>(min_filter.shape(), min_filter.flat<float>());
AddInputFromArray<float>(max_filter.shape(), max_filter.flat<float>());
AddInputFromArray<float>(min_output.shape(), min_output.flat<float>());
AddInputFromArray<float>(max_output.shape(), max_output.flat<float>());
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
TF_ASSERT_OK(RunOpKernel());
// Compare outputs to expected results
const Tensor& output = *GetOutput(0);
const Tensor& output_layout = *GetOutput(3);
CommonTestUtilities<quint8> conv_comp;
conv_comp.ConvertAndCompareIntegral(dtype, output, output_layout, expected);
// TODO(wenxi): For now, we rely on internal performance tests to
// determine if filter data is being cached and reused.
// However, we still need to add a check here to determine if this is
// still the case by inspecting the contents of the persistent tensor.
TF_ASSERT_OK(RunOpKernel());
// Compare output to expected results
const Tensor& output_new = *GetOutput(0);
const Tensor& output_layout_new = *GetOutput(3);
CommonTestUtilities<quint8> conv_comp_new;
conv_comp_new.ConvertAndCompareIntegral(dtype, output_new,
output_layout_new, expected);
}
};
TEST_F(BiasCacheTest, Conv2DBiasCacheTest) {
const int depth = 1;
const int image_width = 4;
const int image_height = 3;
const int image_batch_count = 1;
Tensor image(DT_QUINT8,
{image_batch_count, image_height, image_width, depth});
test::FillValues<quint8>(&image, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
const int kFilterSize = 3;
const int kFilterCount = 1;
Tensor filter(DT_QINT8, {kFilterSize, kFilterSize, depth, kFilterCount});
test::FillValues<qint8>(&filter, {1, 4, 7, 2, 5, 8, 3, 6, 9});
Tensor bias(DT_FLOAT, {kFilterCount});
test::FillValues<float>(&bias, {1});
Tensor min_input(DT_FLOAT, {1});
test::FillValues<float>(&min_input, {1});
Tensor max_input(DT_FLOAT, {1});
test::FillValues<float>(&max_input, {1});
Tensor min_filter(DT_FLOAT, {1});
test::FillValues<float>(&min_filter, {1});
Tensor max_filter(DT_FLOAT, {1});
test::FillValues<float>(&max_filter, {1});
Tensor min_output(DT_FLOAT, {1});
test::FillValues<float>(&min_output, {1});
Tensor max_output(DT_FLOAT, {1});
test::FillValues<float>(&max_output, {1});
Tensor expected(DT_QUINT8, TensorShape({1, 1, 2, 1}));
test::FillValues<quint8>(&expected, {255, 255});
Run<float>(DT_QUINT8, image, filter, bias, min_input, max_input, min_filter,
max_filter, min_output, max_output, expected, true);
}
// Testing fusion of pad and fusedconv2d
template <typename T>
class MklPadWithFusedConv2DOpTest : public OpsTestBase {
protected:
static constexpr int kDepth = 3;
static constexpr int kImageWidth = 30;
static constexpr int kImageHeight = 28;
static constexpr int kImageBatchCount = 8;
// 0: top pad, 1: bottom pad, 2: left pad, 3: right pad
int padding_list_[4];
// Verifies that computing Pad+Conv2D+BiasAdd in a graph is identical to
// FusedConv2D.
void VerifyPadAndConv2DWithBias(int filter_size, int filter_count,
int depth = kDepth,
int image_width = kImageWidth,
int image_height = kImageHeight,
int image_batch_count = kImageBatchCount) {
const BiasAddGraphRunner run_default = [this](const Tensor& input_data,
const Tensor& filter_data,
const Tensor& bias_data,
Tensor* out) {
RunMklPadWithFusedConv2DAndBias(input_data, filter_data, bias_data, out);
};
const BiasAddGraphRunner run_fused =
[this](const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data, Tensor* out) {
RunMklFusedConv2DWithPadOp(input_data, filter_data, {bias_data},
{"BiasAdd"}, out);
};
CommonTestUtilities<T>::VerifyBiasAddTensorsClose(
depth, image_width, image_height, image_batch_count, filter_size,
filter_count, run_default, run_fused);
}
// Verifies that computing Pad+Conv2D+BiasAdd+Relu in a graph is identical to
// FusedConv2D.
void VerifyPadAndConv2DWithBiasRelu(
int filter_size, int filter_count, int depth = kDepth,
int image_width = kImageWidth, int image_height = kImageHeight,
int image_batch_count = kImageBatchCount) {
const BiasAddGraphRunner run_default =
[this](const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data, Tensor* out) {
RunMklPadWithFusedConv2DAndBiasRelu(input_data, filter_data,
bias_data, out);
};
const BiasAddGraphRunner run_fused =
[this](const Tensor& input_data, const Tensor& filter_data,
const Tensor& bias_data, Tensor* out) {
RunMklFusedConv2DWithPadOp(input_data, filter_data, {bias_data},
{"BiasAdd", "Relu"}, out);
};
CommonTestUtilities<T>::VerifyBiasAddTensorsClose(
depth, image_width, image_height, image_batch_count, filter_size,
filter_count, run_default, run_fused);
}
void RunMklPadWithFusedConv2DAndBias(const Tensor& input_data,
const Tensor& filter_data,
const Tensor& bias_data, Tensor* output,
int stride = 1) {
auto root = tensorflow::Scope::NewRootScope();
// FusedConv2D only supports NHWC format so we use NHWC here.
auto padding = ops::Const(root.WithOpName("padding"),
{0, 0, padding_list_[0], padding_list_[1],
padding_list_[2], padding_list_[3], 0, 0},
{4, 2});
auto pad = ops::Pad(
root.WithOpName("pad"),
ops::Const(root.WithOpName("input"), Input::Initializer(input_data)),
padding);
auto conv = ops::Conv2D(
root.WithOpName("conv"), pad,
ops::Const(root.WithOpName("filter"), Input::Initializer(filter_data)),
{1, stride, stride, 1}, "VALID");
auto with_bias = ops::BiasAdd(
root.WithOpName("with_bias"), conv,
ops::Const(root.WithOpName("bias"), Input::Initializer(bias_data)));
CommonTestUtilities<T>::RunAndFetch(root, "with_bias", output);
}
void RunMklPadWithFusedConv2DAndBiasRelu(const Tensor& input_data,
const Tensor& filter_data,
const Tensor& bias_data,
Tensor* output, int stride = 1) {
auto root = tensorflow::Scope::NewRootScope();
// FusedConv2D only supports NHWC format so we use NHWC here.
auto padding = ops::Const(root.WithOpName("padding"),
{0, 0, padding_list_[0], padding_list_[1],
padding_list_[2], padding_list_[3], 0, 0},
{4, 2});
auto pad = ops::Pad(
root.WithOpName("pad"),
ops::Const(root.WithOpName("input"), Input::Initializer(input_data)),
padding);
auto conv = ops::Conv2D(
root.WithOpName("conv"), pad,
ops::Const(root.WithOpName("filter"), Input::Initializer(filter_data)),
{1, stride, stride, 1}, "VALID");
auto with_bias = ops::BiasAdd(
root.WithOpName("with_bias"), conv,
ops::Const(root.WithOpName("bias"), Input::Initializer(bias_data)));
auto with_relu = ops::Relu(root.WithOpName("with_relu"), with_bias);
CommonTestUtilities<T>::RunAndFetch(root, "with_relu", output);
}
void RunMklFusedConv2DWithPadOp(const Tensor& image, const Tensor& filter,
const std::vector<Tensor>& args,
const std::vector<string>& fused_ops,
Tensor* output, int stride = 1) {
DataType dtype = DataTypeToEnum<T>::v();
const int num_args = static_cast<int>(args.size());
Tensor padding(DT_INT32, {4, 2});
test::FillValues<int32>(
&padding, {0, 0, padding_list_[0], padding_list_[1], padding_list_[2],
padding_list_[3], 0, 0});
TF_EXPECT_OK(NodeDefBuilder("pad_fused_conv_op", "_MklPadWithFusedConv2D")
.Input(FakeInput(dtype))
.Input(FakeInput(dtype))
.Input(FakeInput(num_args, dtype))
.Input(FakeInput(DT_INT32))
.Input(FakeInput(DT_UINT8))
.Input(FakeInput(DT_UINT8))
.Input(FakeInput(num_args, DT_UINT8))
.Input(FakeInput(DT_UINT8))
.Attr("T", dtype)
.Attr("num_args", num_args)
.Attr("strides", {1, stride, stride, 1})
.Attr("padding", "VALID")
.Attr("fused_ops", fused_ops)
.Attr("_kernel", "MklLayoutDependentOp")
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
AddInputFromArray<T>(image.shape(), image.flat<T>());
AddInputFromArray<T>(filter.shape(), filter.flat<T>());
for (const Tensor& arg : args)
AddInputFromArray<T>(arg.shape(), arg.flat<T>());
AddInputFromArray<int32>(padding.shape(), padding.flat<int32>());
// Add MKL meta input for input, filter, pad and agrs.
for (int i = 0; i < args.size() + 3; ++i)
AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
TF_ASSERT_OK(RunOpKernel());
// Compare output to expected results
const Tensor& output_tensor = *GetOutput(0);
// Index 2 will need to be changed if the number of outputs produced
// by MklConv2D change.
const Tensor& output_meta_tensor = *GetOutput(2);
CommonTestUtilities<T> test_util;
test_util.PerformConversion(dtype, output_tensor, output_meta_tensor,
output);
}
public:
void SetPaddingList(int top, int bottom, int left, int right) {
padding_list_[0] = top;
padding_list_[1] = bottom;
padding_list_[2] = left;
padding_list_[3] = right;
}
};
TYPED_TEST_CASE_P(MklPadWithFusedConv2DOpTest);
TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasAndRoundPad) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->SetPaddingList(2, 2, 1, 1);
this->VerifyPadAndConv2DWithBias(kFilterSize, kFilterCount);
}
TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasAndPartialPad) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->SetPaddingList(4, 0, 2, 0);
this->VerifyPadAndConv2DWithBias(kFilterSize, kFilterCount);
}
TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasReluAndRoundPad) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->SetPaddingList(2, 2, 1, 1);
this->VerifyPadAndConv2DWithBiasRelu(kFilterSize, kFilterCount);
}
TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasReluAndPartialPad) {
const int kFilterSize = 1;
const int kFilterCount = 12;
this->SetPaddingList(4, 0, 2, 0);
this->VerifyPadAndConv2DWithBiasRelu(kFilterSize, kFilterCount);
}
REGISTER_TYPED_TEST_CASE_P(MklPadWithFusedConv2DOpTest, //
WithBiasAndRoundPad, //
WithBiasAndPartialPad, //
WithBiasReluAndRoundPad, //
WithBiasReluAndPartialPad);
using MklPadWithFusedConv2DDataTypes = ::testing::Types<float>;
INSTANTIATE_TYPED_TEST_CASE_P(Test, MklPadWithFusedConv2DOpTest,
MklPadWithFusedConv2DDataTypes);
} // namespace tensorflow
#endif // INTEL_MKL
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "crypto/encryptor.h"
#include <CommonCrypto/CommonCryptor.h>
#include "base/logging.h"
#include "base/string_util.h"
#include "crypto/symmetric_key.h"
namespace crypto {
Encryptor::Encryptor()
: key_(NULL),
mode_(CBC) {
}
Encryptor::~Encryptor() {
}
bool Encryptor::Init(SymmetricKey* key, Mode mode, const std::string& iv) {
DCHECK(key);
DCHECK_EQ(CBC, mode) << "Unsupported mode of operation";
CSSM_DATA raw_key = key->cssm_data();
if (raw_key.Length != kCCKeySizeAES128 &&
raw_key.Length != kCCKeySizeAES192 &&
raw_key.Length != kCCKeySizeAES256)
return false;
if (iv.size() != kCCBlockSizeAES128)
return false;
key_ = key;
mode_ = mode;
iv_ = iv;
return true;
}
bool Encryptor::Crypt(int /*CCOperation*/ op,
const std::string& input,
std::string* output) {
DCHECK(key_);
CSSM_DATA raw_key = key_->cssm_data();
// CommonCryptor.h: "A general rule for the size of the output buffer which
// must be provided by the caller is that for block ciphers, the output
// length is never larger than the input length plus the block size."
size_t output_size = input.size() + iv_.size();
CCCryptorStatus err = CCCrypt(op,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
raw_key.Data, raw_key.Length,
iv_.data(),
input.data(), input.size(),
WriteInto(output, output_size+1),
output_size,
&output_size);
if (err) {
output->resize(0);
LOG(ERROR) << "CCCrypt returned " << err;
return false;
}
output->resize(output_size);
return true;
}
bool Encryptor::Encrypt(const std::string& plaintext, std::string* ciphertext) {
return Crypt(kCCEncrypt, plaintext, ciphertext);
}
bool Encryptor::Decrypt(const std::string& ciphertext, std::string* plaintext) {
return Crypt(kCCDecrypt, ciphertext, plaintext);
}
} // namespace crypto
|
//--------------------------------------------------------------------------------------------------
//
// File: m+m/m+mBaseService.cpp
//
// Project: m+m
//
// Contains: The class definition for the minimal functionality required for an m+m service.
//
// Written by: Norman Jaffe
//
// Copyright: (c) 2014 by H Plus Technologies Ltd. and Simon Fraser University.
//
// All rights reserved. Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and / or
// other materials provided with the distribution.
// * Neither the name of the copyright holders 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.
//
// Created: 2014-02-06
//
//--------------------------------------------------------------------------------------------------
#include "m+mBaseService.hpp"
#include "m+mArgumentsRequestHandler.hpp"
#include "m+mChannelsRequestHandler.hpp"
#include "m+mClientsRequestHandler.hpp"
#include "m+mDetachRequestHandler.hpp"
#include "m+mExtraInfoRequestHandler.hpp"
#include "m+mInfoRequestHandler.hpp"
#include "m+mListRequestHandler.hpp"
#include "m+mMetricsRequestHandler.hpp"
#include "m+mMetricsStateRequestHandler.hpp"
#include "m+mNameRequestHandler.hpp"
#include "m+mPingThread.hpp"
#include "m+mSetMetricsStateRequestHandler.hpp"
#include "m+mStopRequestHandler.hpp"
#include <m+m/m+mBaseContext.hpp>
#include <m+m/m+mClientChannel.hpp>
#include <m+m/m+mEndpoint.hpp>
#include <m+m/m+mException.hpp>
#include <m+m/m+mRequests.hpp>
#include <m+m/m+mServiceInputHandler.hpp>
#include <m+m/m+mServiceInputHandlerCreator.hpp>
#include <m+m/m+mServiceRequest.hpp>
#include <m+m/m+mServiceResponse.hpp>
#include <m+m/m+mUtilities.hpp>
#if (! MAC_OR_LINUX_)
# pragma warning(push)
# pragma warning(disable: 4512)
#endif // ! MAC_OR_LINUX_
#include <m+m/optionparser.hpp>
#if (! MAC_OR_LINUX_)
# pragma warning(pop)
#endif // ! MAC_OR_LINUX_
//#include <odlEnable.h>
#include <odlInclude.h>
#if defined(__APPLE__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#endif // defined(__APPLE__)
/*! @file
@brief The class definition for the minimal functionality required for an m+m service. */
#if defined(__APPLE__)
# pragma clang diagnostic pop
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Namespace references
#endif // defined(__APPLE__)
using namespace MplusM;
using namespace MplusM::Common;
using std::cout;
using std::endl;
#if defined(__APPLE__)
# pragma mark Private structures, constants and variables
#endif // defined(__APPLE__)
/*! @brief Whether or not metrics are initially being gathered. */
#if defined(MpM_MetricsInitiallyOn)
static const bool kMeasurementsOn = true;
#else // ! defined(MpM_MetricsInitiallyOn)
static const bool kMeasurementsOn = false;
#endif // ! defined(MpM_MetricsInitiallyOn)
#if defined(__APPLE__)
# pragma mark Global constants and variables
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Local functions
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Class methods
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Constructors and Destructors
#endif // defined(__APPLE__)
BaseService::BaseService(const ServiceKind theKind,
const YarpString & launchPath,
const int argc,
char * * argv,
const YarpString & tag,
const bool useMultipleHandlers,
const YarpString & canonicalName,
const YarpString & description,
const YarpString & requestsDescription,
const YarpString & serviceEndpointName,
const YarpString & servicePortNumber) :
_launchPath(launchPath), _contextsLock(), _requestHandlers(*this), _contexts(),
_description(description), _requestsDescription(requestsDescription), _tag(tag),
_auxCounters(), _argumentsHandler(NULL), _channelsHandler(NULL), _clientsHandler(NULL),
_detachHandler(NULL), _extraInfoHandler(NULL), _infoHandler(NULL), _listHandler(NULL),
_metricsHandler(NULL), _metricsStateHandler(NULL), _nameHandler(NULL),
_setMetricsStateHandler(NULL), _stopHandler(NULL), _endpoint(NULL), _handler(NULL),
_handlerCreator(NULL), _pinger(NULL), _kind(theKind), _metricsEnabled(kMeasurementsOn),
_started(false), _useMultipleHandlers(useMultipleHandlers)
{
ODL_ENTER(); //####
ODL_I2("theKind = ", theKind, "argc = ", argc); //####
ODL_S4s("launchPath = ", launchPath, "canonicalName = ", canonicalName, //####
"description = ", description, "requestsDescription = ", requestsDescription); //####
ODL_S2s("serviceEndpointName = ", serviceEndpointName, "servicePortNumber = ", //####
servicePortNumber); //####
ODL_P1("argv = ", argv); //####
ODL_B1("useMultipleHandlers = ", useMultipleHandlers); //####
if (0 < _tag.length())
{
_serviceName = canonicalName + " " + _tag;
}
else
{
_serviceName = canonicalName;
}
ODL_S1s("_serviceName <- ", _serviceName); //####
_endpoint = new Endpoint(serviceEndpointName, servicePortNumber);
if (_metricsEnabled)
{
_endpoint->enableMetrics();
}
else
{
_endpoint->disableMetrics();
}
for (int ii = 0; argc > ii; ++ii)
{
_originalArguments.push_back(argv[ii]);
}
attachRequestHandlers();
ODL_EXIT_P(this); //####
} // BaseService::BaseService
#if (! MAC_OR_LINUX_)
# pragma warning(push)
# pragma warning(disable: 4100)
#endif // ! MAC_OR_LINUX_
BaseService::BaseService(const ServiceKind theKind,
const YarpString & launchPath,
const int argc,
char * * argv,
const bool useMultipleHandlers,
const YarpString & canonicalName,
const YarpString & description,
const YarpString & requestsDescription) :
_launchPath(launchPath), _contextsLock(), _requestHandlers(*this), _contexts(),
_description(description), _requestsDescription(requestsDescription),
_serviceName(canonicalName), _tag(), _auxCounters(), _argumentsHandler(NULL),
_channelsHandler(NULL), _clientsHandler(NULL), _detachHandler(NULL), _infoHandler(NULL),
_listHandler(NULL), _metricsHandler(NULL), _metricsStateHandler(NULL), _nameHandler(NULL),
_setMetricsStateHandler(NULL), _stopHandler(NULL), _endpoint(NULL), _handler(NULL),
_handlerCreator(NULL), _pinger(NULL), _kind(theKind), _metricsEnabled(kMeasurementsOn),
_started(false), _useMultipleHandlers(useMultipleHandlers)
{
#if (! defined(ODL_ENABLE_LOGGING_))
# if MAC_OR_LINUX_
# pragma unused(requestsDescription)
# endif // MAC_OR_LINUX_
#endif // ! defined(ODL_ENABLE_LOGGING_)
ODL_ENTER(); //####
ODL_I2("theKind = ", theKind, "argc = ", argc); //####
ODL_S4s("launchPath = ", launchPath, "canonicalName = ", canonicalName, //####
"description = ", description, "requestsDescription = ", requestsDescription); //####
ODL_P1("argv = ", argv); //####
ODL_B1("useMultipleHandlers = ", useMultipleHandlers); //####
switch (argc)
{
// Argument order = endpoint name [, port]
case 1 :
_endpoint = new Endpoint(*argv);
break;
case 2 :
_endpoint = new Endpoint(*argv, argv[1]);
break;
default :
ODL_EXIT_THROW_S("Invalid parameters for service endpoint"); //####
throw new Exception("Invalid parameters for service endpoint");
}
if (_metricsEnabled)
{
_endpoint->enableMetrics();
}
else
{
_endpoint->disableMetrics();
}
for (int ii = 0; argc > ii; ++ii)
{
_originalArguments.push_back(argv[ii]);
}
attachRequestHandlers();
ODL_EXIT_P(this); //####
} // BaseService::BaseService
#if (! MAC_OR_LINUX_)
# pragma warning(pop)
#endif // ! MAC_OR_LINUX_
BaseService::~BaseService(void)
{
ODL_OBJENTER(); //####
stopService();
detachRequestHandlers();
delete _endpoint;
delete _handler;
delete _handlerCreator;
clearContexts();
ODL_OBJEXIT(); //####
} // BaseService::~BaseService
#if defined(__APPLE__)
# pragma mark Actions and Accessors
#endif // defined(__APPLE__)
void
BaseService::addContext(const YarpString & key,
BaseContext * context)
{
ODL_OBJENTER(); //####
ODL_S1s("key = ", key); //####
ODL_P1("context = ", context); //####
try
{
if (context)
{
lockContexts();
_contexts.insert(ContextMapValue(key, context));
unlockContexts();
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT(); //####
} // BaseService::addContext
void
BaseService::attachRequestHandlers(void)
{
ODL_OBJENTER(); //####
try
{
_argumentsHandler = new ArgumentsRequestHandler(*this);
_channelsHandler = new ChannelsRequestHandler(*this);
_clientsHandler = new ClientsRequestHandler(*this);
_detachHandler = new DetachRequestHandler(*this);
_extraInfoHandler = new ExtraInfoRequestHandler(*this);
_infoHandler = new InfoRequestHandler(*this);
_listHandler = new ListRequestHandler(*this);
_metricsHandler = new MetricsRequestHandler(*this);
_metricsStateHandler = new MetricsStateRequestHandler(*this);
_nameHandler = new NameRequestHandler(*this);
_setMetricsStateHandler = new SetMetricsStateRequestHandler(*this);
_stopHandler = new StopRequestHandler(*this);
if (_argumentsHandler && _channelsHandler && _clientsHandler && _detachHandler &&
_extraInfoHandler && _infoHandler && _listHandler && _metricsHandler &&
_metricsStateHandler && _nameHandler && _setMetricsStateHandler && _stopHandler)
{
_requestHandlers.registerRequestHandler(_argumentsHandler);
_requestHandlers.registerRequestHandler(_channelsHandler);
_requestHandlers.registerRequestHandler(_clientsHandler);
_requestHandlers.registerRequestHandler(_detachHandler);
_requestHandlers.registerRequestHandler(_extraInfoHandler);
_requestHandlers.registerRequestHandler(_infoHandler);
_requestHandlers.registerRequestHandler(_listHandler);
_requestHandlers.registerRequestHandler(_metricsHandler);
_requestHandlers.registerRequestHandler(_metricsStateHandler);
_requestHandlers.registerRequestHandler(_nameHandler);
_requestHandlers.registerRequestHandler(_setMetricsStateHandler);
_requestHandlers.registerRequestHandler(_stopHandler);
}
else
{
ODL_LOG("! (_argumentsHandler && _channelsHandler && _clientsHandler && " //####
"_detachHandler && _extraInfoHandler && _infoHandler && _listHandler && " //####
"_metricsHandler && _metricsStateHandler && _nameHandler && " //####
"_setMetricsStateHandler && _stopHandler)"); //####
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT(); //####
} // BaseService::attachRequestHandlers
void
BaseService::clearContexts(void)
{
ODL_OBJENTER(); //####
lockContexts();
if (0 < _contexts.size())
{
for (ContextMap::const_iterator walker(_contexts.begin()); _contexts.end() != walker;
++walker)
{
BaseContext * value = walker->second;
if (value)
{
delete value;
}
}
_contexts.clear();
}
unlockContexts();
ODL_OBJEXIT(); //####
} // BaseService::clearContexts
void
BaseService::detachClient(const YarpString & key)
{
ODL_OBJENTER(); //####
ODL_S1s("key = ", key); //####
try
{
removeContext(key);
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT(); //####
} // BaseService::detachClient
void
BaseService::detachRequestHandlers(void)
{
ODL_OBJENTER(); //####
try
{
if (_argumentsHandler)
{
_requestHandlers.unregisterRequestHandler(_argumentsHandler);
delete _argumentsHandler;
_argumentsHandler = NULL;
}
if (_channelsHandler)
{
_requestHandlers.unregisterRequestHandler(_channelsHandler);
delete _channelsHandler;
_channelsHandler = NULL;
}
if (_clientsHandler)
{
_requestHandlers.unregisterRequestHandler(_clientsHandler);
delete _clientsHandler;
_clientsHandler = NULL;
}
if (_detachHandler)
{
_requestHandlers.unregisterRequestHandler(_detachHandler);
delete _detachHandler;
_detachHandler = NULL;
}
if (_extraInfoHandler)
{
_requestHandlers.unregisterRequestHandler(_extraInfoHandler);
delete _extraInfoHandler;
_extraInfoHandler = NULL;
}
if (_infoHandler)
{
_requestHandlers.unregisterRequestHandler(_infoHandler);
delete _infoHandler;
_infoHandler = NULL;
}
if (_listHandler)
{
_requestHandlers.unregisterRequestHandler(_listHandler);
delete _listHandler;
_listHandler = NULL;
}
if (_metricsHandler)
{
_requestHandlers.unregisterRequestHandler(_metricsHandler);
delete _metricsHandler;
_metricsHandler = NULL;
}
if (_metricsStateHandler)
{
_requestHandlers.unregisterRequestHandler(_metricsStateHandler);
delete _metricsStateHandler;
_metricsStateHandler = NULL;
}
if (_nameHandler)
{
_requestHandlers.unregisterRequestHandler(_nameHandler);
delete _nameHandler;
_nameHandler = NULL;
}
if (_setMetricsStateHandler)
{
_requestHandlers.unregisterRequestHandler(_setMetricsStateHandler);
delete _setMetricsStateHandler;
_setMetricsStateHandler = NULL;
}
if (_stopHandler)
{
_requestHandlers.unregisterRequestHandler(_stopHandler);
delete _stopHandler;
_stopHandler = NULL;
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT(); //####
} // BaseService::detachRequestHandlers
void
BaseService::disableMetrics(void)
{
ODL_OBJENTER(); //####
_metricsEnabled = false;
if (_endpoint)
{
_endpoint->disableMetrics();
}
ODL_OBJEXIT(); //####
} // BaseService::disableMetrics
void
BaseService::enableMetrics(void)
{
ODL_OBJENTER(); //####
if (_endpoint)
{
_endpoint->enableMetrics();
}
_metricsEnabled = true;
ODL_OBJEXIT(); //####
} // BaseService::enableMetrics
void
BaseService::fillInClientList(YarpStringVector & clients)
{
ODL_OBJENTER(); //####
ODL_P1("clients = ", &clients); //####
lockContexts();
if (0 < _contexts.size())
{
for (ContextMap::const_iterator walker(_contexts.begin()); _contexts.end() != walker;
++walker)
{
clients.push_back(walker->first.c_str());
}
}
unlockContexts();
ODL_OBJEXIT(); //####
} // BaseService::fillInClientList
void
BaseService::fillInSecondaryClientChannelsList(ChannelVector & channels)
{
ODL_OBJENTER(); //####
ODL_P1("channels = ", &channels); //####
channels.clear();
ODL_OBJEXIT(); //####
} // BaseService::fillInSecondaryClientChannelsList
void
BaseService::fillInSecondaryInputChannelsList(ChannelVector & channels)
{
ODL_OBJENTER(); //####
ODL_P1("channels = ", &channels); //####
channels.clear();
ODL_OBJEXIT(); //####
} // BaseService::fillInSecondaryInputChannelsList
void
BaseService::fillInSecondaryOutputChannelsList(ChannelVector & channels)
{
ODL_OBJENTER(); //####
ODL_P1("channels = ", &channels); //####
channels.clear();
ODL_OBJEXIT(); //####
} // BaseService::fillInSecondaryOutputChannelsList
BaseContext *
BaseService::findContext(const YarpString & key)
{
ODL_OBJENTER(); //####
ODL_S1s("key = ", key); //####
BaseContext * result = NULL;
try
{
lockContexts();
ContextMap::iterator match(_contexts.find(key));
if (_contexts.end() != match)
{
result = match->second;
}
unlockContexts();
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT_P(result); //####
return result;
} // BaseService::findContext
void
BaseService::gatherMetrics(yarp::os::Bottle & metrics)
{
ODL_OBJENTER(); //####
ODL_P1("metrics = ", &metrics); //####
if (_endpoint)
{
SendReceiveCounters counters;
_endpoint->getSendReceiveCounters(counters);
counters.addToList(metrics, _endpoint->getName());
}
_auxCounters.addToList(metrics, "auxiliary");
ODL_OBJEXIT(); //####
} // BaseService::gatherMetrics
void
BaseService::incrementAuxiliaryCounters(const SendReceiveCounters & additionalCounters)
{
ODL_OBJENTER(); //####
ODL_P1("additionalCounters = ", &additionalCounters); //####
_auxCounters += additionalCounters;
ODL_OBJEXIT(); //####
} // BaseService::incrementAuxiliaryCounters
bool
BaseService::processRequest(const YarpString & request,
const yarp::os::Bottle & restOfInput,
const YarpString & senderChannel,
yarp::os::ConnectionWriter * replyMechanism)
{
ODL_OBJENTER(); //####
ODL_S3s("request = ", request, "restOfInput = ", restOfInput.toString(), //####
"senderChannel = ", senderChannel); //####
ODL_P1("replyMechanism = ", replyMechanism); //####
bool result = true;
try
{
BaseRequestHandler * handler = _requestHandlers.lookupRequestHandler(request);
if (handler)
{
ODL_LOG("(handler)"); //####
result = handler->processRequest(request, restOfInput, senderChannel, replyMechanism);
}
else
{
ODL_LOG("! (handler)"); //####
if (replyMechanism)
{
ODL_LOG("(replyMechanism)"); //####
yarp::os::Bottle errorMessage(MpM_UNRECOGNIZED_REQUEST_);
ODL_S1s("errorMessage <- ", errorMessage.toString()); //####
if (! errorMessage.write(*replyMechanism))
{
ODL_LOG("(! errorMessage.write(*replyMechanism))"); //####
#if defined(MpM_StallOnSendProblem)
Stall();
#endif // defined(MpM_StallOnSendProblem)
}
}
result = false;
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT_B(result); //####
return result;
} // BaseService::processRequest
void
BaseService::registerRequestHandler(BaseRequestHandler * handler)
{
ODL_OBJENTER(); //####
ODL_P1("handler = ", handler); //####
_requestHandlers.registerRequestHandler(handler);
ODL_OBJEXIT(); //####
} // BaseService::registerRequestHandler
void
BaseService::removeContext(const YarpString & key)
{
ODL_OBJENTER(); //####
ODL_S1s("key = ", key); //####
try
{
lockContexts();
ContextMap::iterator match(_contexts.find(key));
if (_contexts.end() != match)
{
BaseContext * value = match->second;
if (value)
{
delete value;
}
_contexts.erase(match);
}
unlockContexts();
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT(); //####
} // BaseService::removeContext
bool
BaseService::sendPingForChannel(const YarpString & channelName,
CheckFunction checker,
void * checkStuff)
{
ODL_OBJENTER(); //####
ODL_S1s("channelName = ", channelName); //####
ODL_P1("checkStuff = ", checkStuff); //####
bool result = false;
try
{
YarpString aName(GetRandomChannelName(HIDDEN_CHANNEL_PREFIX_
BUILD_NAME_("ping_",
DEFAULT_CHANNEL_ROOT_)));
ClientChannel * newChannel = new ClientChannel;
#if defined(MpM_ReportOnConnections)
ChannelStatusReporter * reporter = Utilities::GetGlobalStatusReporter();
#endif // defined(MpM_ReportOnConnections)
if (newChannel)
{
if (_metricsEnabled)
{
newChannel->enableMetrics();
}
else
{
newChannel->disableMetrics();
}
#if defined(MpM_ReportOnConnections)
newChannel->setReporter(*reporter);
newChannel->getReport(*reporter);
#endif // defined(MpM_ReportOnConnections)
if (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))
{
if (Utilities::NetworkConnectWithRetries(aName, MpM_REGISTRY_ENDPOINT_NAME_,
STANDARD_WAIT_TIME_, false, checker,
checkStuff))
{
yarp::os::Bottle parameters(channelName);
ServiceRequest request(MpM_PING_REQUEST_, parameters);
ServiceResponse response;
if (request.send(*newChannel, response))
{
// Check that we got a successful ping!
if (MpM_EXPECTED_PING_RESPONSE_SIZE_ == response.count())
{
yarp::os::Value theValue = response.element(0);
if (theValue.isString())
{
result = (theValue.toString() == MpM_OK_RESPONSE_);
}
else
{
ODL_LOG("! (theValue.isString())"); //####
}
}
else
{
ODL_LOG("! (MpM_EXPECTED_PING_RESPONSE_SIZE_ == " //####
"response.count())"); //####
ODL_S1s("response = ", response.asString()); //####
}
}
else
{
ODL_LOG("! (request.send(*newChannel, response))"); //####
}
#if defined(MpM_DoExplicitDisconnect)
if (! Utilities::NetworkDisconnectWithRetries(aName,
MpM_REGISTRY_ENDPOINT_NAME_,
STANDARD_WAIT_TIME_, checker,
checkStuff))
{
ODL_LOG("(! Utilities::NetworkDisconnectWithRetries(aName, " //####
"MpM_REGISTRY_ENDPOINT_NAME_, STANDARD_WAIT_TIME_, checker, " //####
"checkStuff))"); //####
}
#endif // defined(MpM_DoExplicitDisconnect)
}
else
{
ODL_LOG("! (Utilities::NetworkConnectWithRetries(aName, " //####
"MpM_REGISTRY_ENDPOINT_NAME_, STANDARD_WAIT_TIME_, false, " //####
"checker, checkStuff))"); //####
}
#if defined(MpM_DoExplicitClose)
newChannel->close();
#endif // defined(MpM_DoExplicitClose)
}
else
{
ODL_LOG("! (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))"); //####
}
SendReceiveCounters newCounters;
newChannel->getSendReceiveCounters(newCounters);
incrementAuxiliaryCounters(newCounters);
BaseChannel::RelinquishChannel(newChannel);
}
else
{
ODL_LOG("! (newChannel)"); //####
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT_B(result); //####
return result;
} // BaseService::sendPingForChannel
void
BaseService::setDefaultRequestHandler(BaseRequestHandler * handler)
{
ODL_OBJENTER(); //####
ODL_P1("handler = ", handler); //####
_requestHandlers.setDefaultRequestHandler(handler);
ODL_OBJEXIT(); //####
} // BaseService::setDefaultRequestHandler
void
BaseService::setExtraInformation(const YarpString & extraInfo)
{
ODL_OBJENTER(); //####
ODL_S1s("extraInfo = ", extraInfo); //####
_extraInfo = extraInfo;
ODL_OBJEXIT(); //####
} // BaseService::setExtraInformation
bool
BaseService::startService(void)
{
ODL_OBJENTER(); //####
try
{
if (! _started)
{
if (_useMultipleHandlers)
{
_handlerCreator = new ServiceInputHandlerCreator(*this);
if (_handlerCreator)
{
if (_endpoint->setInputHandlerCreator(*_handlerCreator) &&
_endpoint->open(STANDARD_WAIT_TIME_))
{
_started = true;
}
else
{
ODL_LOG("! (_endpoint->setInputHandlerCreator(*_handlerCreator) && " //####
"_endpoint->open(STANDARD_WAIT_TIME_))"); //####
delete _handlerCreator;
_handlerCreator = NULL;
}
}
else
{
ODL_LOG("! (_handlerCreator)"); //####
}
}
else
{
_handler = new ServiceInputHandler(*this);
if (_handler)
{
if (_endpoint->setInputHandler(*_handler) &&
_endpoint->open(STANDARD_WAIT_TIME_))
{
_started = true;
}
else
{
ODL_LOG("! (_endpoint->setInputHandler(*_handler) && " //####
"_endpoint->open(STANDARD_WAIT_TIME_))"); //####
delete _handler;
_handler = NULL;
}
}
else
{
ODL_LOG("! (_handler)"); //####
}
}
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_OBJEXIT_B(_started); //####
return _started;
} // BaseService::startService
void
BaseService::startPinger(void)
{
ODL_OBJENTER(); //####
if ((! _pinger) && _endpoint)
{
_pinger = new PingThread(_endpoint->getName(), *this);
if (! _pinger->start())
{
ODL_LOG("(! _pinger->start())"); //####
delete _pinger;
_pinger = NULL;
}
}
ODL_OBJEXIT(); //####
} // BaseService::startPinger
bool
BaseService::stopService(void)
{
ODL_OBJENTER(); //####
if (_pinger)
{
ODL_LOG("(_pinger)"); //####
_pinger->stop();
delete _pinger;
_pinger = NULL;
}
_started = false;
ODL_OBJEXIT_B(! _started); //####
return (! _started);
} // BaseService::stopService
void
BaseService::unregisterRequestHandler(BaseRequestHandler * handler)
{
ODL_OBJENTER(); //####
ODL_P1("handler = ", handler); //####
_requestHandlers.unregisterRequestHandler(handler);
ODL_OBJEXIT(); //####
} // BaseService::unregisterRequestHandler
void
BaseService::updateResponseCounters(const size_t numBytes)
{
ODL_OBJENTER(); //####
ODL_I1("numBytes = ", numBytes); //####
if (_endpoint && _metricsEnabled)
{
_endpoint->updateSendCounters(numBytes);
}
ODL_OBJEXIT(); //####
} // BaseService::updateResponseCounters
#if defined(__APPLE__)
# pragma mark Global functions
#endif // defined(__APPLE__)
bool
Common::AdjustEndpointName(const YarpString & defaultEndpointNameRoot,
const AddressTagModifier modFlag,
YarpString & tag,
YarpString & serviceEndpointName,
const YarpString & tagModifier)
{
ODL_ENTER(); //####
ODL_S4s("defaultEndpointNameRoot = ", defaultEndpointNameRoot, "tag = ", tag, //####
"serviceEndpointName = ", serviceEndpointName, "tagModifier = ", tagModifier); //####
bool nameWasSet = false;
YarpString trimmedModifier;
if (kModificationNone != modFlag)
{
NetworkAddress ourAddress;
std::stringstream buff;
YarpString addressModifier;
GetOurEffectiveAddress(ourAddress);
switch (modFlag)
{
case kModificationBottomByte :
buff << ourAddress._ipBytes[3];
break;
case kModificationBottomTwoBytes :
buff << ourAddress._ipBytes[2] << "." << ourAddress._ipBytes[3];
break;
case kModificationBottomThreeBytes :
buff << ourAddress._ipBytes[1] << "." << ourAddress._ipBytes[2] << "." <<
ourAddress._ipBytes[3];
break;
case kModificationAllBytes :
buff << ourAddress._ipBytes[0] << "." << ourAddress._ipBytes[1] << "." <<
ourAddress._ipBytes[2] << "." << ourAddress._ipBytes[3];
break;
default :
break;
}
addressModifier = YarpString(buff.str());
if (0 < tag.length())
{
tag += YarpString(".") + addressModifier;
}
else
{
tag = addressModifier;
}
}
if (0 < tagModifier.length())
{
char lastChar = tagModifier[tagModifier.length() - 1];
// Drop a trailing period, if present.
if ('.' == lastChar)
{
trimmedModifier = tagModifier.substr(0, tagModifier.length() - 1);
}
else
{
trimmedModifier = tagModifier;
}
}
if (0 < serviceEndpointName.length())
{
nameWasSet = true;
}
else
{
if (0 < tag.length())
{
serviceEndpointName = defaultEndpointNameRoot + "/" + tag;
}
else
{
serviceEndpointName = defaultEndpointNameRoot;
}
if (0 < trimmedModifier.length())
{
serviceEndpointName += YarpString("/") + trimmedModifier;
}
}
if (0 < tag.length())
{
if (0 < trimmedModifier.length())
{
tag += YarpString(":") + trimmedModifier;
}
}
else
{
tag = trimmedModifier;
}
ODL_EXIT_B(nameWasSet); //####
return nameWasSet;
} // Common::AdjustEndpointName
bool
Common::GetOurEffectiveAddress(NetworkAddress & ourAddress)
{
ODL_ENTER(); //####
ODL_P1("ourAddress = ", &ourAddress); //####
bool okSoFar = false;
try
{
YarpString aName(GetRandomChannelName(HIDDEN_CHANNEL_PREFIX_
BUILD_NAME_("whereAmI_",
DEFAULT_CHANNEL_ROOT_)));
BaseChannel * newChannel = new BaseChannel;
if (newChannel)
{
if (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))
{
yarp::os::Contact aContact(newChannel->where());
YarpString hostName(aContact.getHost());
struct in_addr rawAddress;
if (hostName == SELF_ADDRESS_NAME_)
{
hostName = SELF_ADDRESS_IPADDR_;
}
#if MAC_OR_LINUX_
int res = inet_pton(AF_INET, hostName.c_str(), &rawAddress);
#else // ! MAC_OR_LINUX_
int res = InetPton(AF_INET, hostName.c_str(), &rawAddress);
#endif // ! MAC_OR_LINUX_
if (0 < res)
{
char buffer[INET_ADDRSTRLEN + 5];
#if MAC_OR_LINUX_
const char * converted = inet_ntop(AF_INET, &rawAddress, buffer,
sizeof(buffer));
#else // ! MAC_OR_LINUX_
const char * converted = InetNtop(AF_INET, &rawAddress, buffer,
sizeof(buffer));
#endif // ! MAC_OR_LINUX_
std::stringstream buff(converted);
char sep_0_1;
char sep_1_2;
char sep_2_3;
ourAddress._ipPort = aContact.getPort();
buff >> ourAddress._ipBytes[0] >> sep_0_1 >> ourAddress._ipBytes[1] >>
sep_1_2 >> ourAddress._ipBytes[2] >> sep_2_3 >> ourAddress._ipBytes[3];
okSoFar = (! buff.fail());
}
#if defined(MpM_DoExplicitClose)
newChannel->close();
#endif // defined(MpM_DoExplicitClose)
}
else
{
ODL_LOG("! (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))"); //####
}
BaseChannel::RelinquishChannel(newChannel);
}
else
{
ODL_LOG("! (newChannel)"); //####
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_EXIT_B(okSoFar); //####
return okSoFar;
} // Common::GetOurEffectiveAddress
bool
Common::ProcessStandardServiceOptions(const int argc,
char * * argv,
Utilities::DescriptorVector & argumentDescriptions,
const YarpString & serviceDescription,
const YarpString & matchingCriteria,
const int year,
const char * copyrightHolder,
bool & goWasSet,
bool & reportEndpoint,
bool & reportOnExit,
YarpString & tag,
YarpString & serviceEndpointName,
YarpString & servicePortNumber,
AddressTagModifier & modFlag,
const OptionsMask skipOptions,
YarpStringVector * arguments)
{
ODL_ENTER(); //####
ODL_I2("argc = ", argc, "year = ", year); //####
ODL_P4("argv = ", argv, "argumentDescriptions = ", &argumentDescriptions, //####
"reportEndpoint = ", &reportEndpoint, "reportOnExit = ", &reportOnExit); //####
ODL_P2("modFlag = ", &modFlag, "arguments = ", arguments); //####
ODL_S2s("serviceDescription = ", serviceDescription, "matchingCriteria = ", //####
matchingCriteria); //####
ODL_S1("copyrightHolder = ", copyrightHolder); //####
enum optionIndex
{
kOptionUNKNOWN,
kOptionARGS,
kOptionCHANNEL,
kOptionENDPOINT,
kOptionGO,
kOptionHELP,
kOptionINFO,
kOptionMOD,
kOptionPORT,
kOptionREPORT,
kOptionTAG,
kOptionVERSION
}; // optionIndex
bool isAdapter = (0 < matchingCriteria.length());
bool keepGoing = true;
YarpString serviceKindName(isAdapter ? "adapter" : "service");
YarpString goPartText(" --go, -g Start the ");
YarpString infoPartText(" --info, -i Print executable type, supported ");
YarpString reportPartText(" --report, -r Report the ");
YarpString tagPartText(" --tag, -t Specify the tag to be used as part of the ");
goPartText += serviceKindName + " immediately";
infoPartText += serviceKindName + " options";
if (isAdapter)
{
infoPartText += ", matching criteria";
}
infoPartText += " and description and exit";
reportPartText += serviceKindName + " metrics when the application exits";
tagPartText += serviceKindName + " name";
Option_::Descriptor firstDescriptor(kOptionUNKNOWN, 0, "", "", Option_::Arg::None, NULL);
Option_::Descriptor argsDescriptor(kOptionARGS, 0, ARGS_OPTION_STRING_, "args",
Option_::Arg::None,
T_(" --args, -" ARGS_OPTION_STRING_
" Report the argument formats"));
Option_::Descriptor channelDescriptor(kOptionCHANNEL, 0, CHANNEL_OPTION_STRING_, "channel",
Option_::Arg::None,
T_(" --channel, -" CHANNEL_OPTION_STRING_
" Report the actual endpoint name"));
Option_::Descriptor endpointDescriptor(kOptionENDPOINT, 0, ENDPOINT_OPTION_STRING_,
"endpoint", Option_::Arg::Required,
T_(" --endpoint, -" ENDPOINT_OPTION_STRING_
" Specify an alternative endpoint name to be "
"used"));
Option_::Descriptor goDescriptor(kOptionGO, 0, GO_OPTION_STRING_, "go", Option_::Arg::None,
goPartText.c_str());
Option_::Descriptor helpDescriptor(kOptionHELP, 0, HELP_OPTION_STRING_, "help",
Option_::Arg::None,
T_(" --help, -" HELP_OPTION_STRING_
" Print usage and exit"));
Option_::Descriptor infoDescriptor(kOptionINFO, 0, INFO_OPTION_STRING_, "info",
Option_::Arg::None, infoPartText.c_str());
Option_::Descriptor modDescriptor(kOptionMOD, 0, MOD_OPTION_STRING_, "mod",
Option_::Arg::Required,
T_(" --mod, -" MOD_OPTION_STRING_
" Use the IP address as a modifier for the tag"));
Option_::Descriptor portDescriptor(kOptionPORT, 0, PORT_OPTION_STRING_, "port",
Option_::Arg::Required,
T_(" --port, -" PORT_OPTION_STRING_
" Specify a non-default port to be used"));
Option_::Descriptor reportDescriptor(kOptionREPORT, 0, REPORT_OPTION_STRING_, "report",
Option_::Arg::None, reportPartText.c_str());
Option_::Descriptor tagDescriptor(kOptionTAG, 0, TAG_OPTION_STRING_, "tag",
Option_::Arg::Required, tagPartText.c_str());
Option_::Descriptor versionDescriptor(kOptionVERSION, 0, VERSION_OPTION_STRING_, "vers",
Option_::Arg::None,
T_(" --vers, -" VERSION_OPTION_STRING_
" Print version information and exit"));
Option_::Descriptor lastDescriptor(0, 0, NULL, NULL, NULL, NULL);
int argcWork = argc;
char * * argvWork = argv;
YarpString usageString("USAGE: ");
YarpString argList(ArgumentsToArgString(argumentDescriptions));
reportEndpoint = reportOnExit = goWasSet = false;
tag = serviceEndpointName = serviceEndpointName = "";
modFlag = kModificationNone;
if (arguments)
{
arguments->clear();
}
usageString += *argv;
usageString += " [options]";
if (0 < argList.length())
{
YarpStringVector descriptions;
Utilities::ArgumentsToDescriptionArray(argumentDescriptions, descriptions, 2);
usageString += " ";
usageString += argList + "\n\n";
for (size_t ii = 0, mm = descriptions.size(); mm > ii; ++ii)
{
if (0 < ii)
{
usageString += "\n";
}
usageString += " ";
usageString += descriptions[ii];
}
}
usageString += "\n\nOptions:";
// firstDescriptor, helpDescriptor, versionDescriptor, lastDescriptor
size_t descriptorCount = 4;
if (! (skipOptions & kSkipArgsOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipChannelOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipEndpointOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipGoOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipInfoOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipModOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipPortOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipReportOption))
{
++descriptorCount;
}
if (! (skipOptions & kSkipTagOption))
{
++descriptorCount;
}
Option_::Descriptor * usage = new Option_::Descriptor[descriptorCount];
Option_::Descriptor * usageWalker = usage;
#if MAC_OR_LINUX_
firstDescriptor.help = strdup(usageString.c_str());
#else // ! MAC_OR_LINUX_
firstDescriptor.help = _strdup(usageString.c_str());
#endif // ! MAC_OR_LINUX_
memcpy(usageWalker++, &firstDescriptor, sizeof(firstDescriptor));
if (! (skipOptions & kSkipArgsOption))
{
memcpy(usageWalker++, &argsDescriptor, sizeof(argsDescriptor));
}
if (! (skipOptions & kSkipChannelOption))
{
memcpy(usageWalker++, &channelDescriptor, sizeof(channelDescriptor));
}
if (! (skipOptions & kSkipEndpointOption))
{
memcpy(usageWalker++, &endpointDescriptor, sizeof(endpointDescriptor));
}
if (! (skipOptions & kSkipGoOption))
{
memcpy(usageWalker++, &goDescriptor, sizeof(goDescriptor));
}
memcpy(usageWalker++, &helpDescriptor, sizeof(helpDescriptor));
if (! (skipOptions & kSkipInfoOption))
{
memcpy(usageWalker++, &infoDescriptor, sizeof(infoDescriptor));
}
if (! (skipOptions & kSkipModOption))
{
memcpy(usageWalker++, &modDescriptor, sizeof(modDescriptor));
}
if (! (skipOptions & kSkipPortOption))
{
memcpy(usageWalker++, &portDescriptor, sizeof(portDescriptor));
}
if (! (skipOptions & kSkipReportOption))
{
memcpy(usageWalker++, &reportDescriptor, sizeof(reportDescriptor));
}
if (! (skipOptions & kSkipTagOption))
{
memcpy(usageWalker++, &tagDescriptor, sizeof(tagDescriptor));
}
memcpy(usageWalker++, &versionDescriptor, sizeof(versionDescriptor));
memcpy(usageWalker++, &lastDescriptor, sizeof(lastDescriptor));
argcWork -= (argc > 0);
argvWork += (argc > 0); // skip program name argv[0] if present
Option_::Stats stats(usage, argcWork, argvWork);
Option_::Option * options = new Option_::Option[stats.options_max];
Option_::Option * buffer = new Option_::Option[stats.buffer_max];
Option_::Parser parse(usage, argcWork, argvWork, options, buffer, 1);
YarpString badArgs;
if (parse.error())
{
ODL_LOG("(parse.error())"); //####
keepGoing = false;
}
else if (options[kOptionHELP] || options[kOptionUNKNOWN])
{
ODL_LOG("(options[kOptionHELP] || options[kOptionUNKNOWN])"); //####
Option_::printUsage(cout, usage, HELP_LINE_LENGTH_);
keepGoing = false;
}
else if (options[kOptionVERSION])
{
ODL_LOG("(options[kOptionVERSION])"); //####
YarpString mpmVersionString(SanitizeString(MpM_VERSION_, true));
cout << "Version " << mpmVersionString.c_str() << ": Copyright (c) " << year << " by " <<
copyrightHolder << "." << endl;
keepGoing = false;
}
else if (options[kOptionARGS])
{
ODL_LOG("(options[kOptionARGS])"); //####
for (size_t ii = 0, mm = argumentDescriptions.size(); mm > ii; ++ii)
{
Utilities::BaseArgumentDescriptor * anArg = argumentDescriptions[ii];
if (0 < ii)
{
cout << ARGUMENT_SEPARATOR_;
}
if (anArg)
{
cout << anArg->toString().c_str();
}
}
cout << endl;
keepGoing = false;
}
else if (options[kOptionINFO])
{
ODL_LOG("(options[kOptionINFO])"); //####
bool needTab = true;
// Note that we don't report the 'h' and 'v' options, as they are not involved in
// determining what choices to offer when launching a service.
cout << (isAdapter ? "Adapter" : "Service");
if (! (skipOptions & kSkipArgsOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << ARGS_OPTION_STRING_;
}
if (! (skipOptions & kSkipChannelOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << CHANNEL_OPTION_STRING_;
}
if (! (skipOptions & kSkipEndpointOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << ENDPOINT_OPTION_STRING_;
}
if (! (skipOptions & kSkipGoOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << GO_OPTION_STRING_;
}
if (! (skipOptions & kSkipInfoOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << INFO_OPTION_STRING_;
}
if (! (skipOptions & kSkipModOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << MOD_OPTION_STRING_;
}
if (! (skipOptions & kSkipPortOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << PORT_OPTION_STRING_;
}
if (! (skipOptions & kSkipReportOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << REPORT_OPTION_STRING_;
}
if (! (skipOptions & kSkipTagOption))
{
if (needTab)
{
cout << "\t";
needTab = false;
}
cout << TAG_OPTION_STRING_;
}
if (needTab)
{
cout << "\t";
}
cout << "\t" << matchingCriteria.c_str() << "\t" << serviceDescription.c_str() << endl;
keepGoing = false;
}
else if (ProcessArguments(argumentDescriptions, parse, badArgs))
{
ODL_LOG("(ProcessArguments(argumentDescriptions, parse, badArgs))"); //####
if (options[kOptionGO])
{
goWasSet = true;
}
if (options[kOptionCHANNEL])
{
reportEndpoint = true;
}
if (options[kOptionMOD])
{
YarpString modArg = options[kOptionMOD].arg;
if (0 < modArg.length())
{
const char * startPtr = modArg.c_str();
char * endPtr;
int numBytes = static_cast<int>(strtol(startPtr, &endPtr, 10));
if ((startPtr != endPtr) && (!*endPtr))
{
switch (numBytes)
{
case 0 :
modFlag = kModificationNone;
break;
case 1 :
modFlag = kModificationBottomByte;
break;
case 2 :
modFlag = kModificationBottomTwoBytes;
break;
case 3 :
modFlag = kModificationBottomThreeBytes;
break;
case 4 :
modFlag = kModificationAllBytes;
break;
default :
break;
}
}
}
}
if (options[kOptionREPORT])
{
reportOnExit = true;
}
if (options[kOptionENDPOINT])
{
serviceEndpointName = options[kOptionENDPOINT].arg;
ODL_S1s("serviceEndpointName <- ", serviceEndpointName); //####
}
if (options[kOptionPORT])
{
servicePortNumber = options[kOptionPORT].arg;
ODL_S1s("servicePortNumber <- ", servicePortNumber); //####
if (0 < servicePortNumber.length())
{
const char * startPtr = servicePortNumber.c_str();
char * endPtr;
int aPort = static_cast<int>(strtol(startPtr, &endPtr, 10));
if ((startPtr == endPtr) || *endPtr || (! Utilities::ValidPortNumber(aPort)))
{
cout << "Bad port number." << endl;
keepGoing = false;
}
}
}
if (options[kOptionTAG])
{
tag = options[kOptionTAG].arg;
ODL_S1s("tag <- ", tag); //####
}
if (arguments)
{
for (int ii = 0; ii < parse.nonOptionsCount(); ++ii)
{
arguments->push_back(parse.nonOption(ii));
}
}
}
else
{
ODL_LOG("! (ProcessArguments(argumentDescriptions, parse, badArgs))"); //####
cout << "One or more invalid or missing arguments (" << badArgs.c_str() << ")." << endl;
keepGoing = false;
}
delete[] options;
delete[] buffer;
free(const_cast<char *>(firstDescriptor.help));
delete[] usage;
ODL_EXIT_B(keepGoing); //####
return keepGoing;
} // Common::ProcessStandardServiceOptions
bool
Common::RegisterLocalService(const YarpString & channelName,
BaseService & service,
CheckFunction checker,
void * checkStuff)
{
ODL_ENTER(); //####
ODL_S1s("channelName = ", channelName); //####
ODL_P2("service = ", &service, "checkStuff = ", checkStuff); //####
bool result = false;
try
{
YarpString aName(GetRandomChannelName(HIDDEN_CHANNEL_PREFIX_
BUILD_NAME_("registerlocal_",
DEFAULT_CHANNEL_ROOT_)));
ClientChannel * newChannel = new ClientChannel;
#if defined(MpM_ReportOnConnections)
ChannelStatusReporter * reporter = Utilities::GetGlobalStatusReporter();
#endif // defined(MpM_ReportOnConnections)
if (newChannel)
{
if (service.metricsAreEnabled())
{
newChannel->enableMetrics();
}
else
{
newChannel->disableMetrics();
}
#if defined(MpM_ReportOnConnections)
newChannel->setReporter(*reporter);
newChannel->getReport(*reporter);
#endif // defined(MpM_ReportOnConnections)
if (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))
{
if (Utilities::NetworkConnectWithRetries(aName, MpM_REGISTRY_ENDPOINT_NAME_,
STANDARD_WAIT_TIME_, false, checker,
checkStuff))
{
yarp::os::Bottle parameters(channelName);
ServiceRequest request(MpM_REGISTER_REQUEST_, parameters);
ServiceResponse response;
if (request.send(*newChannel, response))
{
// Check that we got a successful self-registration!
if (MpM_EXPECTED_REGISTER_RESPONSE_SIZE_ == response.count())
{
yarp::os::Value theValue = response.element(0);
if (theValue.isString())
{
result = (theValue.toString() == MpM_OK_RESPONSE_);
}
else
{
ODL_LOG("! (theValue.isString())"); //####
}
}
else
{
ODL_LOG("! (MpM_EXPECTED_REGISTER_RESPONSE_SIZE_ == " //####
"response.count())"); //####
ODL_S1s("response = ", response.asString()); //####
}
}
else
{
ODL_LOG("! (request.send(*newChannel, response))"); //####
}
#if defined(MpM_DoExplicitDisconnect)
if (! Utilities::NetworkDisconnectWithRetries(aName,
MpM_REGISTRY_ENDPOINT_NAME_,
STANDARD_WAIT_TIME_, checker,
checkStuff))
{
ODL_LOG("(! Utilities::NetworkDisconnectWithRetries(aName, " //####
"MpM_REGISTRY_ENDPOINT_NAME_, STANDARD_WAIT_TIME_, checker, " //####
"checkStuff))"); //####
}
#endif // defined(MpM_DoExplicitDisconnect)
}
else
{
ODL_LOG("! (Utilities::NetworkConnectWithRetries(aName, " //####
"MpM_REGISTRY_ENDPOINT_NAME_, STANDARD_WAIT_TIME_, false, " //####
"checker, checkStuff))"); //####
}
#if defined(MpM_DoExplicitClose)
newChannel->close();
#endif // defined(MpM_DoExplicitClose)
}
else
{
ODL_LOG("! (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))"); //####
}
SendReceiveCounters newCounters;
newChannel->getSendReceiveCounters(newCounters);
service.incrementAuxiliaryCounters(newCounters);
BaseChannel::RelinquishChannel(newChannel);
}
else
{
ODL_LOG("! (newChannel)"); //####
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_EXIT_B(result); //####
return result;
} // Common::RegisterLocalService
bool
Common::UnregisterLocalService(const YarpString & channelName,
BaseService & service,
CheckFunction checker,
void * checkStuff)
{
ODL_ENTER(); //####
ODL_S1s("channelName = ", channelName); //####
ODL_P2("service = ", &service, "checkStuff = ", checkStuff); //####
bool result = false;
try
{
YarpString aName(GetRandomChannelName(HIDDEN_CHANNEL_PREFIX_
BUILD_NAME_("unregisterlocal_",
DEFAULT_CHANNEL_ROOT_)));
ClientChannel * newChannel = new ClientChannel;
#if defined(MpM_ReportOnConnections)
ChannelStatusReporter * reporter = Utilities::GetGlobalStatusReporter();
#endif // defined(MpM_ReportOnConnections)
if (newChannel)
{
if (service.metricsAreEnabled())
{
newChannel->enableMetrics();
}
else
{
newChannel->disableMetrics();
}
#if defined(MpM_ReportOnConnections)
newChannel->setReporter(*reporter);
newChannel->getReport(*reporter);
#endif // defined(MpM_ReportOnConnections)
if (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))
{
if (Utilities::NetworkConnectWithRetries(aName, MpM_REGISTRY_ENDPOINT_NAME_,
STANDARD_WAIT_TIME_, false, checker,
checkStuff))
{
yarp::os::Bottle parameters(channelName);
ServiceRequest request(MpM_UNREGISTER_REQUEST_, parameters);
ServiceResponse response;
if (request.send(*newChannel, response))
{
// Check that we got a successful self-deregistration!
if (MpM_EXPECTED_UNREGISTER_RESPONSE_SIZE_ == response.count())
{
yarp::os::Value theValue = response.element(0);
if (theValue.isString())
{
result = (theValue.toString() == MpM_OK_RESPONSE_);
}
else
{
ODL_LOG("! (theValue.isString())"); //####
}
}
else
{
ODL_LOG("! (MpM_EXPECTED_UNREGISTER_RESPONSE_SIZE_ == " //####
"response.count())"); //####
ODL_S1s("response = ", response.asString()); //####
}
}
else
{
ODL_LOG("! (request.send(*newChannel, response))"); //####
}
#if defined(MpM_DoExplicitDisconnect)
if (! Utilities::NetworkDisconnectWithRetries(aName,
MpM_REGISTRY_ENDPOINT_NAME_,
STANDARD_WAIT_TIME_, checker,
checkStuff))
{
ODL_LOG("(! Utilities::NetworkDisconnectWithRetries(aName, " //####
"MpM_REGISTRY_ENDPOINT_NAME_, STANDARD_WAIT_TIME_, checker, " //####
"checkStuff))"); //####
}
#endif // defined(MpM_DoExplicitDisconnect)
}
else
{
ODL_LOG("! (Utilities::NetworkConnectWithRetries(aName, " //####
"MpM_REGISTRY_ENDPOINT_NAME_, STANDARD_WAIT_TIME_, false, " //####
"checker, checkStuff))"); //####
}
#if defined(MpM_DoExplicitClose)
newChannel->close();
#endif // defined(MpM_DoExplicitClose)
}
else
{
ODL_LOG("! (newChannel->openWithRetries(aName, STANDARD_WAIT_TIME_))"); //####
}
SendReceiveCounters newCounters;
newChannel->getSendReceiveCounters(newCounters);
service.incrementAuxiliaryCounters(newCounters);
BaseChannel::RelinquishChannel(newChannel);
}
else
{
ODL_LOG("! (newChannel)"); //####
}
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_EXIT_B(result); //####
return result;
} // Common::UnregisterLocalService
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2015.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Steffen Sass, Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/DATASTRUCTURES/QTCluster.h>
#include <OpenMS/DATASTRUCTURES/GridFeature.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <numeric>
using namespace std;
namespace OpenMS
{
QTCluster::QTCluster()
{
}
QTCluster::QTCluster(GridFeature* center_point, Size num_maps,
double max_distance, bool use_IDs) :
center_point_(center_point), neighbors_(), max_distance_(max_distance),
num_maps_(num_maps), quality_(0.0), changed_(false), use_IDs_(use_IDs),
annotations_(),
valid_(true)
{
if (use_IDs)
annotations_ = center_point->getAnnotations();
}
QTCluster::~QTCluster()
{
}
double QTCluster::getCenterRT() const
{
return center_point_->getRT();
}
double QTCluster::getCenterMZ() const
{
return center_point_->getMZ();
}
Size QTCluster::size() const
{
return neighbors_.size() + 1; // + 1 for the center
}
bool QTCluster::operator<(QTCluster& cluster)
{
return this->getQuality() < cluster.getQuality();
}
void QTCluster::add(GridFeature* element, double distance)
{
// maybe TODO: check here if distance is smaller than max. distance?
// maybe TODO: check here if peptide annotations are compatible?
// (currently, both is done in QTClusterFinder)
Size map_index = element->getMapIndex();
if (map_index != center_point_->getMapIndex())
{
neighbors_[map_index].insert(make_pair(distance, element));
changed_ = true;
}
}
void QTCluster::getElements(OpenMSBoost::unordered_map<Size, GridFeature*>& elements)
{
elements.clear();
elements[center_point_->getMapIndex()] = center_point_;
if (neighbors_.empty())
{
return;
}
// if necessary, compute the optimal annotation for the cluster first:
if (changed_ && use_IDs_ && center_point_->getAnnotations().empty())
{
optimizeAnnotations_();
}
if (annotations_.empty() || !center_point_->getAnnotations().empty())
{
// no need to take annotations into account:
for (NeighborMap::const_iterator it = neighbors_.begin();
it != neighbors_.end(); ++it)
{
elements[it->first] = it->second.begin()->second;
}
}
else // find elements that are compatible with the optimal annotation:
{
for (NeighborMap::const_iterator n_it = neighbors_.begin();
n_it != neighbors_.end(); ++n_it)
{
for (std::multimap<double, GridFeature*>::const_iterator df_it =
n_it->second.begin(); df_it != n_it->second.end(); ++df_it)
{
const set<AASequence>& current = df_it->second->getAnnotations();
if (current.empty() || (current == annotations_))
{
elements[n_it->first] = df_it->second;
break; // found the best element for this input map
}
}
}
}
}
bool QTCluster::update(const OpenMSBoost::unordered_map<Size, GridFeature*>& removed)
{
// check if the cluster center was removed:
for (OpenMSBoost::unordered_map<Size, GridFeature*>::const_iterator rm_it = removed.begin();
rm_it != removed.end(); ++rm_it)
{
if (rm_it->second == center_point_)
return false;
}
// update the cluster contents:
for (OpenMSBoost::unordered_map<Size, GridFeature*>::const_iterator rm_it = removed.begin();
rm_it != removed.end(); ++rm_it)
{
NeighborMap::iterator pos = neighbors_.find(rm_it->first);
if (pos == neighbors_.end())
continue; // no points from this map
for (std::multimap<double, GridFeature*>::iterator feat_it =
pos->second.begin(); feat_it != pos->second.end(); ++feat_it)
{
if (feat_it->second == rm_it->second) // remove this neighbor
{
if (!use_IDs_ || (annotations_ == rm_it->second->getAnnotations()))
{
changed_ = true;
}
// else: removed neighbor doesn't have optimal annotation, so it can't
// be a "true" cluster element => no need to recompute the quality
pos->second.erase(feat_it);
break;
}
}
if (pos->second.empty()) // only neighbor from this map was just removed
{
neighbors_.erase(pos);
}
}
return true;
}
double QTCluster::getQuality()
{
if (changed_)
{
computeQuality_();
changed_ = false;
}
return quality_;
}
void QTCluster::computeQuality_()
{
Size num_other = num_maps_ - 1;
double internal_distance = 0.0;
if (!use_IDs_ || !center_point_->getAnnotations().empty() ||
neighbors_.empty())
{
// if the cluster center is annotated with peptide IDs, the neighbors can
// consist only of features with compatible IDs, so we don't need to check
// again here
Size counter = 0;
for (NeighborMap::iterator it = neighbors_.begin();
it != neighbors_.end(); ++it)
{
internal_distance += it->second.begin()->first;
counter++;
}
// add max. distance for missing cluster elements:
internal_distance += (num_other - counter) * max_distance_;
}
else // find the annotation that gives the best quality
{
internal_distance = optimizeAnnotations_();
}
// normalize:
internal_distance /= num_other;
quality_ = (max_distance_ - internal_distance) / max_distance_;
}
const set<AASequence>& QTCluster::getAnnotations()
{
if (changed_ && use_IDs_ && center_point_->getAnnotations().empty() &&
!neighbors_.empty())
optimizeAnnotations_();
return annotations_;
}
double QTCluster::optimizeAnnotations_()
{
// mapping: peptides -> best distance per input map
map<set<AASequence>, vector<double> > seq_table;
for (NeighborMap::iterator n_it = neighbors_.begin();
n_it != neighbors_.end(); ++n_it)
{
Size map_index = n_it->first;
for (std::multimap<double, GridFeature*>::iterator df_it =
n_it->second.begin(); df_it != n_it->second.end(); ++df_it)
{
double dist = df_it->first;
const set<AASequence>& current = df_it->second->getAnnotations();
map<set<AASequence>, vector<double> >::iterator pos =
seq_table.find(current);
if (pos == seq_table.end()) // new set of annotations
{
seq_table[current].resize(num_maps_, max_distance_);
seq_table[current][map_index] = dist;
}
else // new dist. value for this input map
{
pos->second[map_index] = min(dist, pos->second[map_index]);
}
if (current.empty()) // unannotated feature
{
// no need to check further (annotation-specific distances are worse
// than this unspecific one):
break;
}
}
}
// combine annotation-specific and unspecific distances:
map<set<AASequence>, vector<double> >::iterator unspecific =
seq_table.find(set<AASequence>());
if (unspecific != seq_table.end())
{
for (map<set<AASequence>, vector<double> >::iterator it =
seq_table.begin(); it != seq_table.end(); ++it)
{
if (it == unspecific)
continue;
for (Size i = 0; i < num_maps_; ++i)
{
it->second[i] = min(it->second[i], unspecific->second[i]);
}
}
}
// compute distance totals -> best annotation set has smallest value:
map<set<AASequence>, vector<double> >::iterator best_pos =
seq_table.begin();
double best_total = num_maps_ * max_distance_;
for (map<set<AASequence>, vector<double> >::iterator it =
seq_table.begin(); it != seq_table.end(); ++it)
{
double total = accumulate(it->second.begin(), it->second.end(), 0.0);
if (total < best_total)
{
best_pos = it;
best_total = total;
}
}
if (best_pos != seq_table.end())
annotations_ = best_pos->first;
// one "max_dist." too many (from the input map of the cluster center):
return best_total - max_distance_;
}
}
|
// Copyright 2018 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 "ash/detachable_base/detachable_base_handler.h"
#include "ash/detachable_base/detachable_base_observer.h"
#include "ash/public/cpp/ash_pref_names.h"
#include "ash/public/cpp/session/user_info.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
namespace ash {
namespace {
// Keys in local state used to persist detachable base pairing state.
// Example detachable base pref value:
// {
// ash.detachable_base.devices: {
// user_key_1: {
// last_used: hex encoded base device ID
// },
// user_key_2: {
// // no detachable_base device info, e.g. the user has not ever used it
// }
// }
// }
constexpr char kLastUsedByUserPrefKey[] = "last_used";
std::string GetKeyForPrefs(const AccountId& account_id) {
if (account_id.HasAccountIdKey())
return account_id.GetAccountIdKey();
return account_id.GetUserEmail();
}
} // namespace
// static
void DetachableBaseHandler::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(prefs::kDetachableBaseDevices);
}
DetachableBaseHandler::DetachableBaseHandler(PrefService* local_state)
: local_state_(local_state),
hammerd_observation_(this),
power_manager_observation_(this) {
if (chromeos::HammerdClient::Get()) // May be null in tests
hammerd_observation_.Observe(chromeos::HammerdClient::Get());
chromeos::PowerManagerClient* power_manager_client =
chromeos::PowerManagerClient::Get();
power_manager_observation_.Observe(power_manager_client);
power_manager_client->GetSwitchStates(
base::BindOnce(&DetachableBaseHandler::OnGotPowerManagerSwitchStates,
weak_ptr_factory_.GetWeakPtr()));
if (GetPairingStatus() != DetachableBasePairingStatus::kNone)
NotifyPairingStatusChanged();
}
DetachableBaseHandler::~DetachableBaseHandler() = default;
void DetachableBaseHandler::AddObserver(DetachableBaseObserver* observer) {
observers_.AddObserver(observer);
}
void DetachableBaseHandler::RemoveObserver(DetachableBaseObserver* observer) {
observers_.RemoveObserver(observer);
}
void DetachableBaseHandler::RemoveUserData(const UserInfo& user) {
last_used_devices_.erase(user.account_id);
if (local_state_) {
DictionaryPrefUpdate update(local_state_, prefs::kDetachableBaseDevices);
update->RemoveKey(GetKeyForPrefs(user.account_id));
}
}
DetachableBasePairingStatus DetachableBaseHandler::GetPairingStatus() const {
if (!tablet_mode_.has_value() ||
*tablet_mode_ == chromeos::PowerManagerClient::TabletMode::ON) {
return DetachableBasePairingStatus::kNone;
}
return pairing_status_;
}
bool DetachableBaseHandler::PairedBaseMatchesLastUsedByUser(
const UserInfo& user) const {
if (GetPairingStatus() != DetachableBasePairingStatus::kAuthenticated)
return false;
DCHECK(!authenticated_base_id_.empty());
// If local state is not set for non-ephemeral users, the last used detachable
// base cannot be determined at this point.
// Assume no device has previously been used - the state will be evaluated
// again when the local state prefs get initialzized.
if (!local_state_ && !user.is_ephemeral)
return true;
DetachableBaseId last_used_base = GetLastUsedDeviceForUser(user);
return last_used_base.empty() || authenticated_base_id_ == last_used_base;
}
bool DetachableBaseHandler::SetPairedBaseAsLastUsedByUser(
const UserInfo& user) {
if (GetPairingStatus() != DetachableBasePairingStatus::kAuthenticated)
return false;
// Do not update the last paired device for non-ephemeral users if local state
// is not set, as the value would not be correctly preserved. Note that the
// observers will be notified about the pairing status change when the local
// state gets initialized - they should attempt to set this value at that
// point.
if (!local_state_ && !user.is_ephemeral)
return false;
last_used_devices_[user.account_id] = authenticated_base_id_;
if (!user.is_ephemeral) {
DictionaryPrefUpdate update(local_state_, prefs::kDetachableBaseDevices);
update->SetPath({GetKeyForPrefs(user.account_id), kLastUsedByUserPrefKey},
base::Value(authenticated_base_id_));
}
return true;
}
void DetachableBaseHandler::BaseFirmwareUpdateNeeded() {
NotifyBaseRequiresFirmwareUpdate(true /*requires_update*/);
}
void DetachableBaseHandler::BaseFirmwareUpdateStarted() {}
void DetachableBaseHandler::BaseFirmwareUpdateSucceeded() {
NotifyBaseRequiresFirmwareUpdate(false /*requires_update*/);
}
void DetachableBaseHandler::BaseFirmwareUpdateFailed() {}
void DetachableBaseHandler::PairChallengeSucceeded(
const std::vector<uint8_t>& base_id) {
authenticated_base_id_ = base::HexEncode(base_id.data(), base_id.size());
pairing_status_ = DetachableBasePairingStatus::kAuthenticated;
if (GetPairingStatus() != DetachableBasePairingStatus::kNone)
NotifyPairingStatusChanged();
}
void DetachableBaseHandler::PairChallengeFailed() {
authenticated_base_id_.clear();
pairing_status_ = DetachableBasePairingStatus::kNotAuthenticated;
if (GetPairingStatus() != DetachableBasePairingStatus::kNone)
NotifyPairingStatusChanged();
}
void DetachableBaseHandler::InvalidBaseConnected() {
authenticated_base_id_.clear();
pairing_status_ = DetachableBasePairingStatus::kInvalidDevice;
if (GetPairingStatus() != DetachableBasePairingStatus::kNone)
NotifyPairingStatusChanged();
}
void DetachableBaseHandler::TabletModeEventReceived(
chromeos::PowerManagerClient::TabletMode mode,
base::TimeTicks timestamp) {
UpdateTabletMode(mode);
}
void DetachableBaseHandler::OnGotPowerManagerSwitchStates(
absl::optional<chromeos::PowerManagerClient::SwitchStates> switch_states) {
if (!switch_states.has_value() || tablet_mode_.has_value())
return;
UpdateTabletMode(switch_states->tablet_mode);
}
void DetachableBaseHandler::UpdateTabletMode(
chromeos::PowerManagerClient::TabletMode mode) {
DetachableBasePairingStatus old_pairing_status = GetPairingStatus();
tablet_mode_ = mode;
if (*tablet_mode_ == chromeos::PowerManagerClient::TabletMode::ON) {
authenticated_base_id_.clear();
pairing_status_ = DetachableBasePairingStatus::kNone;
NotifyBaseRequiresFirmwareUpdate(false /*requires_update*/);
}
if (GetPairingStatus() != old_pairing_status)
NotifyPairingStatusChanged();
}
DetachableBaseHandler::DetachableBaseId
DetachableBaseHandler::GetLastUsedDeviceForUser(const UserInfo& user) const {
const auto it = last_used_devices_.find(user.account_id);
// If the last used device was set within this session, bypass local state.
if (it != last_used_devices_.end())
return it->second;
// For ephemeral lookup do not attempt getting the value from local state;
// return empty string instead.
if (user.is_ephemeral)
return "";
const base::DictionaryValue* detachable_base_info =
local_state_->GetDictionary(prefs::kDetachableBaseDevices);
const base::Value* last_used = detachable_base_info->FindPathOfType(
{GetKeyForPrefs(user.account_id), kLastUsedByUserPrefKey},
base::Value::Type::STRING);
if (!last_used)
return "";
return last_used->GetString();
}
void DetachableBaseHandler::NotifyPairingStatusChanged() {
for (auto& observer : observers_)
observer.OnDetachableBasePairingStatusChanged(GetPairingStatus());
}
void DetachableBaseHandler::NotifyBaseRequiresFirmwareUpdate(
bool requires_update) {
for (auto& observer : observers_)
observer.OnDetachableBaseRequiresUpdateChanged(requires_update);
}
} // namespace ash
|
// Copyright (C) 2016 Google Inc.
//
// 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 "deepmind/level_generation/text_level/char_grid.h"
#include <algorithm>
#include <functional>
#include "deepmind/support/logging.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
namespace deepmind {
namespace lab {
CharGrid::CharGrid(std::string text)
: raw_data_(std::move(text)),
rows_(absl::StrSplit(raw_data_, '\n', absl::SkipEmpty())) {
auto it = std::max_element(rows_.begin(), rows_.end(),
[](absl::string_view lhs, absl::string_view rhs) {
return lhs.size() < rhs.size();
});
CHECK(it != rows_.end());
width_ = it->size();
}
} // namespace lab
} // namespace deepmind
|
// socketft.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#if !defined(NO_OS_DEPENDENCE) && defined(SOCKETS_AVAILABLE)
// TODO: http://github.com/weidai11/cryptopp/issues/19
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include "socketft.h"
#include "wait.h"
// Windows 8, Windows Server 2012, and Windows Phone 8.1 need <synchapi.h> and <ioapiset.h>
#if defined(CRYPTOPP_WIN32_AVAILABLE)
# if ((WINVER >= 0x0602 /*_WIN32_WINNT_WIN8*/) || (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/))
# include <synchapi.h>
# include <ioapiset.h>
# define USE_WINDOWS8_API
# endif
#endif
#ifdef USE_BERKELEY_STYLE_SOCKETS
#include <errno.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#endif
#if defined(CRYPTOPP_MSAN)
# include <sanitizer/msan_interface.h>
#endif
#ifdef PREFER_WINDOWS_STYLE_SOCKETS
# pragma comment(lib, "ws2_32.lib")
#endif
NAMESPACE_BEGIN(CryptoPP)
#ifdef USE_WINDOWS_STYLE_SOCKETS
const int SOCKET_EINVAL = WSAEINVAL;
const int SOCKET_EWOULDBLOCK = WSAEWOULDBLOCK;
typedef int socklen_t;
#else
const int SOCKET_EINVAL = EINVAL;
const int SOCKET_EWOULDBLOCK = EWOULDBLOCK;
#endif
// Solaris doesn't have INADDR_NONE
#ifndef INADDR_NONE
# define INADDR_NONE 0xffffffff
#endif /* INADDR_NONE */
Socket::Err::Err(socket_t s, const std::string& operation, int error)
: OS_Error(IO_ERROR, "Socket: " + operation + " operation failed with error " + IntToString(error), operation, error)
, m_s(s)
{
}
Socket::~Socket()
{
if (m_own)
{
try
{
CloseSocket();
}
catch (const Exception&)
{
assert(0);
}
}
}
void Socket::AttachSocket(socket_t s, bool own)
{
if (m_own)
CloseSocket();
m_s = s;
m_own = own;
SocketChanged();
}
socket_t Socket::DetachSocket()
{
socket_t s = m_s;
m_s = INVALID_SOCKET;
SocketChanged();
return s;
}
void Socket::Create(int nType)
{
assert(m_s == INVALID_SOCKET);
m_s = socket(AF_INET, nType, 0);
CheckAndHandleError("socket", m_s);
m_own = true;
SocketChanged();
}
void Socket::CloseSocket()
{
if (m_s != INVALID_SOCKET)
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
# if defined(USE_WINDOWS8_API)
BOOL result = CancelIoEx((HANDLE) m_s, NULL);
assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
CheckAndHandleError_int("closesocket", closesocket(m_s));
CRYPTOPP_UNUSED(result); // Used by assert in debug builds
# else
BOOL result = CancelIo((HANDLE) m_s);
assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
CheckAndHandleError_int("closesocket", closesocket(m_s));
CRYPTOPP_UNUSED(result);
# endif
#else
CheckAndHandleError_int("close", close(m_s));
#endif
m_s = INVALID_SOCKET;
SocketChanged();
}
}
void Socket::Bind(unsigned int port, const char *addr)
{
sockaddr_in sa;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
if (addr == NULL)
sa.sin_addr.s_addr = htonl(INADDR_ANY);
else
{
unsigned long result = inet_addr(addr);
if (result == INADDR_NONE)
{
SetLastError(SOCKET_EINVAL);
CheckAndHandleError_int("inet_addr", SOCKET_ERROR);
}
sa.sin_addr.s_addr = result;
}
sa.sin_port = htons((unsigned short)port);
Bind((sockaddr *)&sa, sizeof(sa));
}
void Socket::Bind(const sockaddr *psa, socklen_t saLen)
{
assert(m_s != INVALID_SOCKET);
// cygwin workaround: needs const_cast
CheckAndHandleError_int("bind", bind(m_s, const_cast<sockaddr *>(psa), saLen));
}
void Socket::Listen(int backlog)
{
assert(m_s != INVALID_SOCKET);
CheckAndHandleError_int("listen", listen(m_s, backlog));
}
bool Socket::Connect(const char *addr, unsigned int port)
{
assert(addr != NULL);
sockaddr_in sa;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr(addr);
if (sa.sin_addr.s_addr == INADDR_NONE)
{
hostent *lphost = gethostbyname(addr);
if (lphost == NULL)
{
SetLastError(SOCKET_EINVAL);
CheckAndHandleError_int("gethostbyname", SOCKET_ERROR);
}
else
{
assert(IsAlignedOn(lphost->h_addr,GetAlignmentOf<in_addr>()));
sa.sin_addr.s_addr = ((in_addr *)(void *)lphost->h_addr)->s_addr;
}
}
sa.sin_port = htons((unsigned short)port);
return Connect((const sockaddr *)&sa, sizeof(sa));
}
bool Socket::Connect(const sockaddr* psa, socklen_t saLen)
{
assert(m_s != INVALID_SOCKET);
int result = connect(m_s, const_cast<sockaddr*>(psa), saLen);
if (result == SOCKET_ERROR && GetLastError() == SOCKET_EWOULDBLOCK)
return false;
CheckAndHandleError_int("connect", result);
return true;
}
bool Socket::Accept(Socket& target, sockaddr *psa, socklen_t *psaLen)
{
assert(m_s != INVALID_SOCKET);
socket_t s = accept(m_s, psa, psaLen);
if (s == INVALID_SOCKET && GetLastError() == SOCKET_EWOULDBLOCK)
return false;
CheckAndHandleError("accept", s);
target.AttachSocket(s, true);
return true;
}
void Socket::GetSockName(sockaddr *psa, socklen_t *psaLen)
{
assert(m_s != INVALID_SOCKET);
CheckAndHandleError_int("getsockname", getsockname(m_s, psa, psaLen));
}
void Socket::GetPeerName(sockaddr *psa, socklen_t *psaLen)
{
assert(m_s != INVALID_SOCKET);
CheckAndHandleError_int("getpeername", getpeername(m_s, psa, psaLen));
}
unsigned int Socket::Send(const byte* buf, size_t bufLen, int flags)
{
assert(m_s != INVALID_SOCKET);
int result = send(m_s, (const char *)buf, UnsignedMin(INT_MAX, bufLen), flags);
CheckAndHandleError_int("send", result);
return result;
}
unsigned int Socket::Receive(byte* buf, size_t bufLen, int flags)
{
assert(m_s != INVALID_SOCKET);
int result = recv(m_s, (char *)buf, UnsignedMin(INT_MAX, bufLen), flags);
CheckAndHandleError_int("recv", result);
return result;
}
void Socket::ShutDown(int how)
{
assert(m_s != INVALID_SOCKET);
int result = shutdown(m_s, how);
CheckAndHandleError_int("shutdown", result);
}
void Socket::IOCtl(long cmd, unsigned long *argp)
{
assert(m_s != INVALID_SOCKET);
#ifdef USE_WINDOWS_STYLE_SOCKETS
CheckAndHandleError_int("ioctlsocket", ioctlsocket(m_s, cmd, argp));
#else
CheckAndHandleError_int("ioctl", ioctl(m_s, cmd, argp));
#endif
}
bool Socket::SendReady(const timeval *timeout)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(m_s, &fds);
#ifdef CRYPTOPP_MSAN
__msan_unpoison(&fds, sizeof(fds));
#endif
int ready;
if (timeout == NULL)
ready = select((int)m_s+1, NULL, &fds, NULL, NULL);
else
{
timeval timeoutCopy = *timeout; // select() modified timeout on Linux
ready = select((int)m_s+1, NULL, &fds, NULL, &timeoutCopy);
}
CheckAndHandleError_int("select", ready);
return ready > 0;
}
bool Socket::ReceiveReady(const timeval *timeout)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(m_s, &fds);
#ifdef CRYPTOPP_MSAN
__msan_unpoison(&fds, sizeof(fds));
#endif
int ready;
if (timeout == NULL)
ready = select((int)m_s+1, &fds, NULL, NULL, NULL);
else
{
timeval timeoutCopy = *timeout; // select() modified timeout on Linux
ready = select((int)m_s+1, &fds, NULL, NULL, &timeoutCopy);
}
CheckAndHandleError_int("select", ready);
return ready > 0;
}
unsigned int Socket::PortNameToNumber(const char *name, const char *protocol)
{
int port = atoi(name);
if (IntToString(port) == name)
return port;
servent *se = getservbyname(name, protocol);
if (!se)
throw Err(INVALID_SOCKET, "getservbyname", SOCKET_EINVAL);
return ntohs(se->s_port);
}
void Socket::StartSockets()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
WSADATA wsd;
int result = WSAStartup(0x0202, &wsd);
if (result != 0)
throw Err(INVALID_SOCKET, "WSAStartup", result);
#endif
}
void Socket::ShutdownSockets()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
int result = WSACleanup();
if (result != 0)
throw Err(INVALID_SOCKET, "WSACleanup", result);
#endif
}
int Socket::GetLastError()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
return WSAGetLastError();
#else
return errno;
#endif
}
void Socket::SetLastError(int errorCode)
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
WSASetLastError(errorCode);
#else
errno = errorCode;
#endif
}
void Socket::HandleError(const char *operation) const
{
int err = GetLastError();
throw Err(m_s, operation, err);
}
#ifdef USE_WINDOWS_STYLE_SOCKETS
SocketReceiver::SocketReceiver(Socket &s)
: m_s(s), m_eofReceived(false), m_resultPending(false)
{
m_event.AttachHandle(CreateEvent(NULL, true, false, NULL), true);
m_s.CheckAndHandleError("CreateEvent", m_event.HandleValid());
memset(&m_overlapped, 0, sizeof(m_overlapped));
m_overlapped.hEvent = m_event;
}
SocketReceiver::~SocketReceiver()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
# if defined(USE_WINDOWS8_API)
BOOL result = CancelIoEx((HANDLE) m_s.GetSocket(), NULL);
assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
CRYPTOPP_UNUSED(result); // Used by assert in debug builds
# else
BOOL result = CancelIo((HANDLE) m_s.GetSocket());
assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
CRYPTOPP_UNUSED(result);
# endif
#endif
}
bool SocketReceiver::Receive(byte* buf, size_t bufLen)
{
assert(!m_resultPending && !m_eofReceived);
DWORD flags = 0;
// don't queue too much at once, or we might use up non-paged memory
WSABUF wsabuf = {UnsignedMin((u_long)128*1024, bufLen), (char *)buf};
if (WSARecv(m_s, &wsabuf, 1, &m_lastResult, &flags, &m_overlapped, NULL) == 0)
{
if (m_lastResult == 0)
m_eofReceived = true;
}
else
{
switch (WSAGetLastError())
{
default:
m_s.CheckAndHandleError_int("WSARecv", SOCKET_ERROR);
case WSAEDISCON:
m_lastResult = 0;
m_eofReceived = true;
break;
case WSA_IO_PENDING:
m_resultPending = true;
}
}
return !m_resultPending;
}
void SocketReceiver::GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack)
{
if (m_resultPending)
container.AddHandle(m_event, CallStack("SocketReceiver::GetWaitObjects() - result pending", &callStack));
else if (!m_eofReceived)
container.SetNoWait(CallStack("SocketReceiver::GetWaitObjects() - result ready", &callStack));
}
unsigned int SocketReceiver::GetReceiveResult()
{
if (m_resultPending)
{
DWORD flags = 0;
if (WSAGetOverlappedResult(m_s, &m_overlapped, &m_lastResult, false, &flags))
{
if (m_lastResult == 0)
m_eofReceived = true;
}
else
{
switch (WSAGetLastError())
{
default:
m_s.CheckAndHandleError("WSAGetOverlappedResult", FALSE);
case WSAEDISCON:
m_lastResult = 0;
m_eofReceived = true;
}
}
m_resultPending = false;
}
return m_lastResult;
}
// *************************************************************
SocketSender::SocketSender(Socket &s)
: m_s(s), m_resultPending(false), m_lastResult(0)
{
m_event.AttachHandle(CreateEvent(NULL, true, false, NULL), true);
m_s.CheckAndHandleError("CreateEvent", m_event.HandleValid());
memset(&m_overlapped, 0, sizeof(m_overlapped));
m_overlapped.hEvent = m_event;
}
SocketSender::~SocketSender()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
# if defined(USE_WINDOWS8_API)
BOOL result = CancelIoEx((HANDLE) m_s.GetSocket(), NULL);
assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
CRYPTOPP_UNUSED(result); // Used by assert in debug builds
# else
BOOL result = CancelIo((HANDLE) m_s.GetSocket());
assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
CRYPTOPP_UNUSED(result);
# endif
#endif
}
void SocketSender::Send(const byte* buf, size_t bufLen)
{
assert(!m_resultPending);
DWORD written = 0;
// don't queue too much at once, or we might use up non-paged memory
WSABUF wsabuf = {UnsignedMin((u_long)128*1024, bufLen), (char *)buf};
if (WSASend(m_s, &wsabuf, 1, &written, 0, &m_overlapped, NULL) == 0)
{
m_resultPending = false;
m_lastResult = written;
}
else
{
if (WSAGetLastError() != WSA_IO_PENDING)
m_s.CheckAndHandleError_int("WSASend", SOCKET_ERROR);
m_resultPending = true;
}
}
void SocketSender::SendEof()
{
assert(!m_resultPending);
m_s.ShutDown(SD_SEND);
m_s.CheckAndHandleError("ResetEvent", ResetEvent(m_event));
m_s.CheckAndHandleError_int("WSAEventSelect", WSAEventSelect(m_s, m_event, FD_CLOSE));
m_resultPending = true;
}
bool SocketSender::EofSent()
{
if (m_resultPending)
{
WSANETWORKEVENTS events;
m_s.CheckAndHandleError_int("WSAEnumNetworkEvents", WSAEnumNetworkEvents(m_s, m_event, &events));
if ((events.lNetworkEvents & FD_CLOSE) != FD_CLOSE)
throw Socket::Err(m_s, "WSAEnumNetworkEvents (FD_CLOSE not present)", E_FAIL);
if (events.iErrorCode[FD_CLOSE_BIT] != 0)
throw Socket::Err(m_s, "FD_CLOSE (via WSAEnumNetworkEvents)", events.iErrorCode[FD_CLOSE_BIT]);
m_resultPending = false;
}
return m_lastResult != 0;
}
void SocketSender::GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack)
{
if (m_resultPending)
container.AddHandle(m_event, CallStack("SocketSender::GetWaitObjects() - result pending", &callStack));
else
container.SetNoWait(CallStack("SocketSender::GetWaitObjects() - result ready", &callStack));
}
unsigned int SocketSender::GetSendResult()
{
if (m_resultPending)
{
DWORD flags = 0;
BOOL result = WSAGetOverlappedResult(m_s, &m_overlapped, &m_lastResult, false, &flags);
m_s.CheckAndHandleError("WSAGetOverlappedResult", result);
m_resultPending = false;
}
return m_lastResult;
}
#endif
#ifdef USE_BERKELEY_STYLE_SOCKETS
SocketReceiver::SocketReceiver(Socket &s)
: m_s(s), m_eofReceived(false), m_lastResult(0)
{
}
void SocketReceiver::GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack)
{
if (!m_eofReceived)
container.AddReadFd(m_s, CallStack("SocketReceiver::GetWaitObjects()", &callStack));
}
bool SocketReceiver::Receive(byte* buf, size_t bufLen)
{
m_lastResult = m_s.Receive(buf, bufLen);
if (bufLen > 0 && m_lastResult == 0)
m_eofReceived = true;
return true;
}
unsigned int SocketReceiver::GetReceiveResult()
{
return m_lastResult;
}
SocketSender::SocketSender(Socket &s)
: m_s(s), m_lastResult(0)
{
}
void SocketSender::Send(const byte* buf, size_t bufLen)
{
m_lastResult = m_s.Send(buf, bufLen);
}
void SocketSender::SendEof()
{
m_s.ShutDown(SD_SEND);
}
unsigned int SocketSender::GetSendResult()
{
return m_lastResult;
}
void SocketSender::GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack)
{
container.AddWriteFd(m_s, CallStack("SocketSender::GetWaitObjects()", &callStack));
}
#endif // USE_BERKELEY_STYLE_SOCKETS
NAMESPACE_END
#endif // SOCKETS_AVAILABLE
|
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
*/
/**
* planner.cpp
*
* Buffer movement commands and manage the acceleration profile plan
*
* Derived from Grbl
* Copyright (c) 2009-2011 Simen Svale Skogsrud
*
* The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
*
*
* Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
*
* s == speed, a == acceleration, t == time, d == distance
*
* Basic definitions:
* Speed[s_, a_, t_] := s + (a*t)
* Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
*
* Distance to reach a specific speed with a constant acceleration:
* Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
* d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
*
* Speed after a given distance of travel with constant acceleration:
* Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
* m -> Sqrt[2 a d + s^2]
*
* DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
*
* When to start braking (di) to reach a specified destination speed (s2) after accelerating
* from initial speed s1 without ever stopping at a plateau:
* Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
* di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
*
* IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
*
* --
*
* The fast inverse function needed for Bézier interpolation for AVR
* was designed, written and tested by Eduardo José Tagle on April/2018
*/
#include "planner.h"
#include "stepper.h"
#include "motion.h"
#include "temperature.h"
#include "../lcd/ultralcd.h"
#include "../core/language.h"
#include "../gcode/parser.h"
#include "../Marlin.h"
#if HAS_LEVELING
#include "../feature/bedlevel/bedlevel.h"
#endif
#if ENABLED(FILAMENT_WIDTH_SENSOR)
#include "../feature/filwidth.h"
#endif
#if ENABLED(BARICUDA)
#include "../feature/baricuda.h"
#endif
#if ENABLED(MIXING_EXTRUDER)
#include "../feature/mixing.h"
#endif
#if ENABLED(AUTO_POWER_CONTROL)
#include "../feature/power.h"
#endif
#if ENABLED(BACKLASH_COMPENSATION)
#include "../feature/backlash.h"
#endif
// Delay for delivery of first block to the stepper ISR, if the queue contains 2 or
// fewer movements. The delay is measured in milliseconds, and must be less than 250ms
#define BLOCK_DELAY_FOR_1ST_MOVE 100
Planner planner;
// public:
/**
* A ring buffer of moves described in steps
*/
block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
Planner::block_buffer_nonbusy, // Index of the first non-busy block
Planner::block_buffer_planned, // Index of the optimally planned block
Planner::block_buffer_tail; // Index of the busy block, if any
uint16_t Planner::cleaning_buffer_counter; // A counter to disable queuing of blocks
uint8_t Planner::delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
planner_settings_t Planner::settings; // Initialized by settings.load()
uint32_t Planner::max_acceleration_steps_per_s2[XYZE_N]; // (steps/s^2) Derived from mm_per_s2
float Planner::steps_to_mm[XYZE_N]; // (mm) Millimeters per step
#if ENABLED(JUNCTION_DEVIATION)
float Planner::junction_deviation_mm; // (mm) M205 J
#if ENABLED(LIN_ADVANCE)
#if ENABLED(DISTINCT_E_FACTORS)
float Planner::max_e_jerk[EXTRUDERS]; // Calculated from junction_deviation_mm
#else
float Planner::max_e_jerk;
#endif
#endif
#endif
#if HAS_CLASSIC_JERK
#if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
float Planner::max_jerk[XYZ]; // (mm/s^2) M205 XYZ - The largest speed change requiring no acceleration.
#else
float Planner::max_jerk[XYZE]; // (mm/s^2) M205 XYZE - The largest speed change requiring no acceleration.
#endif
#endif
#if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
bool Planner::abort_on_endstop_hit = false;
#endif
#if ENABLED(DISTINCT_E_FACTORS)
uint8_t Planner::last_extruder = 0; // Respond to extruder change
#endif
int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement
#if DISABLED(NO_VOLUMETRICS)
float Planner::filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area
Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
#endif
#if HAS_LEVELING
bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
#if ABL_PLANAR
matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
#endif
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
float Planner::z_fade_height, // Initialized by settings.load()
Planner::inverse_z_fade_height,
Planner::last_fade_z;
#endif
#else
constexpr bool Planner::leveling_active;
#endif
skew_factor_t Planner::skew_factor; // Initialized by settings.load()
#if ENABLED(AUTOTEMP)
float Planner::autotemp_max = 250,
Planner::autotemp_min = 210,
Planner::autotemp_factor = 0.1f;
bool Planner::autotemp_enabled = false;
#endif
// private:
int32_t Planner::position[NUM_AXIS] = { 0 };
uint32_t Planner::cutoff_long;
float Planner::previous_speed[NUM_AXIS],
Planner::previous_nominal_speed_sqr;
#if ENABLED(DISABLE_INACTIVE_EXTRUDER)
uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
#endif
#ifdef XY_FREQUENCY_LIMIT
// Old direction bits. Used for speed calculations
unsigned char Planner::old_direction_bits = 0;
// Segment times (in µs). Used for speed calculations
uint32_t Planner::axis_segment_time_us[2][3] = { { MAX_FREQ_TIME_US + 1, 0, 0 }, { MAX_FREQ_TIME_US + 1, 0, 0 } };
#endif
#if ENABLED(LIN_ADVANCE)
float Planner::extruder_advance_K[EXTRUDERS]; // Initialized by settings.load()
#endif
#if HAS_POSITION_FLOAT
float Planner::position_float[XYZE]; // Needed for accurate maths. Steps cannot be used!
#endif
#if IS_KINEMATIC
float Planner::position_cart[XYZE];
#endif
#if ENABLED(ULTRA_LCD)
volatile uint32_t Planner::block_buffer_runtime_us = 0;
#endif
/**
* Class and Instance Methods
*/
Planner::Planner() { init(); }
void Planner::init() {
ZERO(position);
#if HAS_POSITION_FLOAT
ZERO(position_float);
#endif
#if IS_KINEMATIC
ZERO(position_cart);
#endif
ZERO(previous_speed);
previous_nominal_speed_sqr = 0;
#if ABL_PLANAR
bed_level_matrix.set_to_identity();
#endif
clear_block_buffer();
delay_before_delivering = 0;
}
#if ENABLED(S_CURVE_ACCELERATION)
#ifdef __AVR__
/**
* This routine returns 0x1000000 / d, getting the inverse as fast as possible.
* A fast-converging iterative Newton-Raphson method can reach full precision in
* just 1 iteration, and takes 211 cycles (worst case; the mean case is less, up
* to 30 cycles for small divisors), instead of the 500 cycles a normal division
* would take.
*
* Inspired by the following page:
* https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
*
* Suppose we want to calculate floor(2 ^ k / B) where B is a positive integer
* Then, B must be <= 2^k, otherwise, the quotient is 0.
*
* The Newton - Raphson iteration for x = B / 2 ^ k yields:
* q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
*
* This can be rearranged to:
* q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
*
* Each iteration requires only integer multiplications and bit shifts.
* It doesn't necessarily converge to floor(2 ^ k / B) but in the worst case
* it eventually alternates between floor(2 ^ k / B) and ceil(2 ^ k / B).
* So it checks for this case and extracts floor(2 ^ k / B).
*
* A simple but important optimization for this approach is to truncate
* multiplications (i.e., calculate only the higher bits of the product) in the
* early iterations of the Newton - Raphson method. This is done so the results
* of the early iterations are far from the quotient. Then it doesn't matter if
* they are done inaccurately.
* It's important to pick a good starting value for x. Knowing how many
* digits the divisor has, it can be estimated:
*
* 2^k / x = 2 ^ log2(2^k / x)
* 2^k / x = 2 ^(log2(2^k)-log2(x))
* 2^k / x = 2 ^(k*log2(2)-log2(x))
* 2^k / x = 2 ^ (k-log2(x))
* 2^k / x >= 2 ^ (k-floor(log2(x)))
* floor(log2(x)) is simply the index of the most significant bit set.
*
* If this estimation can be improved even further the number of iterations can be
* reduced a lot, saving valuable execution time.
* The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
* Research, Silicon Valley,August 26, 2008, available at
* https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
* suggests, for its integer division algorithm, using a table to supply the first
* 8 bits of precision, then, due to the quadratic convergence nature of the
* Newton-Raphon iteration, just 2 iterations should be enough to get maximum
* precision of the division.
* By precomputing values of inverses for small denominator values, just one
* Newton-Raphson iteration is enough to reach full precision.
* This code uses the top 9 bits of the denominator as index.
*
* The AVR assembly function implements this C code using the data below:
*
* // For small divisors, it is best to directly retrieve the results
* if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
*
* // Compute initial estimation of 0x1000000/x -
* // Get most significant bit set on divider
* uint8_t idx = 0;
* uint32_t nr = d;
* if (!(nr & 0xFF0000)) {
* nr <<= 8; idx += 8;
* if (!(nr & 0xFF0000)) { nr <<= 8; idx += 8; }
* }
* if (!(nr & 0xF00000)) { nr <<= 4; idx += 4; }
* if (!(nr & 0xC00000)) { nr <<= 2; idx += 2; }
* if (!(nr & 0x800000)) { nr <<= 1; idx += 1; }
*
* // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
* uint32_t tidx = nr >> 15, // top 9 bits. bit8 is always set
* ie = inv_tab[tidx & 0xFF] + 256, // Get the table value. bit9 is always set
* x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place
*
* x = uint32_t((x * uint64_t(_BV(25) - x * d)) >> 24); // Refine estimation by newton-raphson. 1 iteration is enough
* const uint32_t r = _BV(24) - x * d; // Estimate remainder
* if (r >= d) x++; // Check whether to adjust result
* return uint32_t(x); // x holds the proper estimation
*
*/
static uint32_t get_period_inverse(uint32_t d) {
static const uint8_t inv_tab[256] PROGMEM = {
255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
};
// For small denominators, it is cheaper to directly store the result.
// For bigger ones, just ONE Newton-Raphson iteration is enough to get
// maximum precision we need
static const uint32_t small_inv_tab[111] PROGMEM = {
16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
};
// For small divisors, it is best to directly retrieve the results
if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
uint8_t r8 = d & 0xFF,
r9 = (d >> 8) & 0xFF,
r10 = (d >> 16) & 0xFF,
r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
const uint8_t* ptab = inv_tab;
__asm__ __volatile__(
// %8:%7:%6 = interval
// r31:r30: MUST be those registers, and they must point to the inv_tab
A("clr %13") // %13 = 0
// Now we must compute
// result = 0xFFFFFF / d
// %8:%7:%6 = interval
// %16:%15:%14 = nr
// %13 = 0
// A plain division of 24x24 bits should take 388 cycles to complete. We will
// use Newton-Raphson for the calculation, and will strive to get way less cycles
// for the same result - Using C division, it takes 500cycles to complete .
A("clr %3") // idx = 0
A("mov %14,%6")
A("mov %15,%7")
A("mov %16,%8") // nr = interval
A("tst %16") // nr & 0xFF0000 == 0 ?
A("brne 2f") // No, skip this
A("mov %16,%15")
A("mov %15,%14") // nr <<= 8, %14 not needed
A("subi %3,-8") // idx += 8
A("tst %16") // nr & 0xFF0000 == 0 ?
A("brne 2f") // No, skip this
A("mov %16,%15") // nr <<= 8, %14 not needed
A("clr %15") // We clear %14
A("subi %3,-8") // idx += 8
// here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
L("2")
A("cpi %16,0x10") // (nr & 0xF00000) == 0 ?
A("brcc 3f") // No, skip this
A("swap %15") // Swap nibbles
A("swap %16") // Swap nibbles. Low nibble is 0
A("mov %14, %15")
A("andi %14,0x0F") // Isolate low nibble
A("andi %15,0xF0") // Keep proper nibble in %15
A("or %16, %14") // %16:%15 <<= 4
A("subi %3,-4") // idx += 4
L("3")
A("cpi %16,0x40") // (nr & 0xC00000) == 0 ?
A("brcc 4f") // No, skip this
A("add %15,%15")
A("adc %16,%16")
A("add %15,%15")
A("adc %16,%16") // %16:%15 <<= 2
A("subi %3,-2") // idx += 2
L("4")
A("cpi %16,0x80") // (nr & 0x800000) == 0 ?
A("brcc 5f") // No, skip this
A("add %15,%15")
A("adc %16,%16") // %16:%15 <<= 1
A("inc %3") // idx += 1
// Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
// we have at least 9 MSBits available to enter the initial estimation table
L("5")
A("add %15,%15")
A("adc %16,%16") // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table)
A("add r30,%16") // Only use top 8 bits
A("adc r31,%13") // r31:r30 = inv_tab + (tidx)
A("lpm %14, Z") // %14 = inv_tab[tidx]
A("ldi %15, 1") // %15 = 1 %15:%14 = inv_tab[tidx] + 256
// We must scale the approximation to the proper place
A("clr %16") // %16 will always be 0 here
A("subi %3,8") // idx == 8 ?
A("breq 6f") // yes, no need to scale
A("brcs 7f") // If C=1, means idx < 8, result was negative!
// idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
A("sbrs %3,0") // shift by 1bit position?
A("rjmp 8f") // No
A("add %14,%14")
A("adc %15,%15") // %15:16 <<= 1
L("8")
A("sbrs %3,1") // shift by 2bit position?
A("rjmp 9f") // No
A("add %14,%14")
A("adc %15,%15")
A("add %14,%14")
A("adc %15,%15") // %15:16 <<= 1
L("9")
A("sbrs %3,2") // shift by 4bits position?
A("rjmp 16f") // No
A("swap %15") // Swap nibbles. lo nibble of %15 will always be 0
A("swap %14") // Swap nibbles
A("mov %12,%14")
A("andi %12,0x0F") // isolate low nibble
A("andi %14,0xF0") // and clear it
A("or %15,%12") // %15:%16 <<= 4
L("16")
A("sbrs %3,3") // shift by 8bits position?
A("rjmp 6f") // No, we are done
A("mov %16,%15")
A("mov %15,%14")
A("clr %14")
A("jmp 6f")
// idx < 8, now %3 = idx - 8. Get the count of bits
L("7")
A("neg %3") // %3 = -idx = count of bits to move right. idx range:[1...8]
A("sbrs %3,0") // shift by 1 bit position ?
A("rjmp 10f") // No, skip it
A("asr %15") // (bit7 is always 0 here)
A("ror %14")
L("10")
A("sbrs %3,1") // shift by 2 bit position ?
A("rjmp 11f") // No, skip it
A("asr %15") // (bit7 is always 0 here)
A("ror %14")
A("asr %15") // (bit7 is always 0 here)
A("ror %14")
L("11")
A("sbrs %3,2") // shift by 4 bit position ?
A("rjmp 12f") // No, skip it
A("swap %15") // Swap nibbles
A("andi %14, 0xF0") // Lose the lowest nibble
A("swap %14") // Swap nibbles. Upper nibble is 0
A("or %14,%15") // Pass nibble from upper byte
A("andi %15, 0x0F") // And get rid of that nibble
L("12")
A("sbrs %3,3") // shift by 8 bit position ?
A("rjmp 6f") // No, skip it
A("mov %14,%15")
A("clr %15")
L("6") // %16:%15:%14 = initial estimation of 0x1000000 / d
// Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
// of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
// to get more than 18bits of precision (the initial table lookup gives 9 bits of
// precision to start from). 18bits of precision is all what is needed here for result
// %8:%7:%6 = d = interval
// %16:%15:%14 = x = initial estimation of 0x1000000 / d
// %13 = 0
// %3:%2:%1:%0 = working accumulator
// Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
A("clr %0")
A("clr %1")
A("clr %2")
A("ldi %3,2") // %3:%2:%1:%0 = 0x2000000
A("mul %6,%14") // r1:r0 = LO(d) * LO(x)
A("sub %0,r0")
A("sbc %1,r1")
A("sbc %2,%13")
A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
A("mul %7,%14") // r1:r0 = MI(d) * LO(x)
A("sub %1,r0")
A("sbc %2,r1" )
A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
A("mul %8,%14") // r1:r0 = HI(d) * LO(x)
A("sub %2,r0")
A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
A("mul %6,%15") // r1:r0 = LO(d) * MI(x)
A("sub %1,r0")
A("sbc %2,r1")
A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
A("mul %7,%15") // r1:r0 = MI(d) * MI(x)
A("sub %2,r0")
A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
A("mul %8,%15") // r1:r0 = HI(d) * MI(x)
A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
A("mul %6,%16") // r1:r0 = LO(d) * HI(x)
A("sub %2,r0")
A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
A("mul %7,%16") // r1:r0 = MI(d) * HI(x)
A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
// %3:%2:%1:%0 = (1<<25) - x*d [169]
// We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
// %16:%15:%14 = x = initial estimation of 0x1000000 / d
// %3:%2:%1:%0 = (1<<25) - x*d = acc
// %13 = 0
// result = %11:%10:%9:%5:%4
A("mul %14,%0") // r1:r0 = LO(x) * LO(acc)
A("mov %4,r1")
A("clr %5")
A("clr %9")
A("clr %10")
A("clr %11") // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
A("mul %15,%0") // r1:r0 = MI(x) * LO(acc)
A("add %4,r0")
A("adc %5,r1")
A("adc %9,%13")
A("adc %10,%13")
A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
A("mul %16,%0") // r1:r0 = HI(x) * LO(acc)
A("add %5,r0")
A("adc %9,r1")
A("adc %10,%13")
A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
A("mul %14,%1") // r1:r0 = LO(x) * MIL(acc)
A("add %4,r0")
A("adc %5,r1")
A("adc %9,%13")
A("adc %10,%13")
A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
A("mul %15,%1") // r1:r0 = MI(x) * MIL(acc)
A("add %5,r0")
A("adc %9,r1")
A("adc %10,%13")
A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8
A("mul %16,%1") // r1:r0 = HI(x) * MIL(acc)
A("add %9,r0")
A("adc %10,r1")
A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
A("mul %14,%2") // r1:r0 = LO(x) * MIH(acc)
A("add %5,r0")
A("adc %9,r1")
A("adc %10,%13")
A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
A("mul %15,%2") // r1:r0 = MI(x) * MIH(acc)
A("add %9,r0")
A("adc %10,r1")
A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
A("mul %16,%2") // r1:r0 = HI(x) * MIH(acc)
A("add %10,r0")
A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
A("mul %14,%3") // r1:r0 = LO(x) * HI(acc)
A("add %9,r0")
A("adc %10,r1")
A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
A("mul %15,%3") // r1:r0 = MI(x) * HI(acc)
A("add %10,r0")
A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
A("mul %16,%3") // r1:r0 = HI(x) * HI(acc)
A("add %11,r0") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
// At this point, %11:%10:%9 contains the new estimation of x.
// Finally, we must correct the result. Estimate remainder as
// (1<<24) - x*d
// %11:%10:%9 = x
// %8:%7:%6 = d = interval" "\n\t"
A("ldi %3,1")
A("clr %2")
A("clr %1")
A("clr %0") // %3:%2:%1:%0 = 0x1000000
A("mul %6,%9") // r1:r0 = LO(d) * LO(x)
A("sub %0,r0")
A("sbc %1,r1")
A("sbc %2,%13")
A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
A("mul %7,%9") // r1:r0 = MI(d) * LO(x)
A("sub %1,r0")
A("sbc %2,r1")
A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
A("mul %8,%9") // r1:r0 = HI(d) * LO(x)
A("sub %2,r0")
A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
A("mul %6,%10") // r1:r0 = LO(d) * MI(x)
A("sub %1,r0")
A("sbc %2,r1")
A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
A("mul %7,%10") // r1:r0 = MI(d) * MI(x)
A("sub %2,r0")
A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
A("mul %8,%10") // r1:r0 = HI(d) * MI(x)
A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
A("mul %6,%11") // r1:r0 = LO(d) * HI(x)
A("sub %2,r0")
A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
A("mul %7,%11") // r1:r0 = MI(d) * HI(x)
A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
// %3:%2:%1:%0 = r = (1<<24) - x*d
// %8:%7:%6 = d = interval
// Perform the final correction
A("sub %0,%6")
A("sbc %1,%7")
A("sbc %2,%8") // r -= d
A("brcs 14f") // if ( r >= d)
// %11:%10:%9 = x
A("ldi %3,1")
A("add %9,%3")
A("adc %10,%13")
A("adc %11,%13") // x++
L("14")
// Estimation is done. %11:%10:%9 = x
A("clr __zero_reg__") // Make C runtime happy
// [211 cycles total]
: "=r" (r2),
"=r" (r3),
"=r" (r4),
"=d" (r5),
"=r" (r6),
"=r" (r7),
"+r" (r8),
"+r" (r9),
"+r" (r10),
"=d" (r11),
"=r" (r12),
"=r" (r13),
"=d" (r14),
"=d" (r15),
"=d" (r16),
"=d" (r17),
"=d" (r18),
"+z" (ptab)
:
: "r0", "r1", "cc"
);
// Return the result
return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
}
#else
// All other 32-bit MPUs can easily do inverse using hardware division,
// so we don't need to reduce precision or to use assembly language at all.
// This routine, for all other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d
static FORCE_INLINE uint32_t get_period_inverse(const uint32_t d) {
return d ? 0xFFFFFFFF / d : 0xFFFFFFFF;
}
#endif
#endif
#define MINIMAL_STEP_RATE 120
/**
* Calculate trapezoid parameters, multiplying the entry- and exit-speeds
* by the provided factors.
**
* ############ VERY IMPORTANT ############
* NOTE that the PRECONDITION to call this function is that the block is
* NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR
* is not and will not use the block while we modify it, so it is safe to
* alter its values.
*/
void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
// Limit minimal step rate (Otherwise the timer will overflow.)
NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE));
NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE));
#if ENABLED(S_CURVE_ACCELERATION)
uint32_t cruise_rate = initial_rate;
#endif
const int32_t accel = block->acceleration_steps_per_s2;
// Steps required for acceleration, deceleration to/from nominal rate
uint32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
// Steps between acceleration and deceleration, if any
int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
// Does accelerate_steps + decelerate_steps exceed step_event_count?
// Then we can't possibly reach the nominal rate, there will be no cruising.
// Use intersection_distance() to calculate accel / braking time in order to
// reach the final_rate exactly at the end of this block.
if (plateau_steps < 0) {
const float accelerate_steps_float = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
accelerate_steps = MIN(uint32_t(MAX(accelerate_steps_float, 0)), block->step_event_count);
plateau_steps = 0;
#if ENABLED(S_CURVE_ACCELERATION)
// We won't reach the cruising rate. Let's calculate the speed we will reach
cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
#endif
}
#if ENABLED(S_CURVE_ACCELERATION)
else // We have some plateau time, so the cruise rate will be the nominal rate
cruise_rate = block->nominal_rate;
#endif
#if ENABLED(S_CURVE_ACCELERATION)
// Jerk controlled speed requires to express speed versus time, NOT steps
uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * (STEPPER_TIMER_RATE),
deceleration_time = ((float)(cruise_rate - final_rate) / accel) * (STEPPER_TIMER_RATE);
// And to offload calculations from the ISR, we also calculate the inverse of those times here
uint32_t acceleration_time_inverse = get_period_inverse(acceleration_time);
uint32_t deceleration_time_inverse = get_period_inverse(deceleration_time);
#endif
// Store new block parameters
block->accelerate_until = accelerate_steps;
block->decelerate_after = accelerate_steps + plateau_steps;
block->initial_rate = initial_rate;
#if ENABLED(S_CURVE_ACCELERATION)
block->acceleration_time = acceleration_time;
block->deceleration_time = deceleration_time;
block->acceleration_time_inverse = acceleration_time_inverse;
block->deceleration_time_inverse = deceleration_time_inverse;
block->cruise_rate = cruise_rate;
#endif
block->final_rate = final_rate;
}
/* PLANNER SPEED DEFINITION
+--------+ <- current->nominal_speed
/ \
current->entry_speed -> + \
| + <- next->entry_speed (aka exit speed)
+-------------+
time -->
Recalculates the motion plan according to the following basic guidelines:
1. Go over every feasible block sequentially in reverse order and calculate the junction speeds
(i.e. current->entry_speed) such that:
a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of
neighboring blocks.
b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed)
with a maximum allowable deceleration over the block travel distance.
c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero).
2. Go over every block in chronological (forward) order and dial down junction speed values if
a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable
acceleration over the block travel distance.
When these stages are complete, the planner will have maximized the velocity profiles throughout the all
of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In
other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements
are possible. If a new block is added to the buffer, the plan is recomputed according to the said
guidelines for a new optimal plan.
To increase computational efficiency of these guidelines, a set of planner block pointers have been
created to indicate stop-compute points for when the planner guidelines cannot logically make any further
changes or improvements to the plan when in normal operation and new blocks are streamed and added to the
planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are
bracketed by junction velocities at their maximums (or by the first planner block as well), no new block
added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute
them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute
point) are all accelerating, they are all optimal and can not be altered by a new block added to the
planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum
junction velocity is reached. However, if the operational conditions of the plan changes from infrequently
used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is
recomputed as stated in the general guidelines.
Planner buffer index mapping:
- block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed.
- block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether
the buffer is full or empty. As described for standard ring buffers, this block is always empty.
- block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal
streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the
planner buffer that don't change with the addition of a new block, as describe above. In addition,
this block can never be less than block_buffer_tail and will always be pushed forward and maintain
this requirement when encountered by the Planner::discard_current_block() routine during a cycle.
NOTE: Since the planner only computes on what's in the planner buffer, some motions with lots of short
line segments, like G2/3 arcs or complex curves, may seem to move slow. This is because there simply isn't
enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and then
decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this happens and
becomes an annoyance, there are a few simple solutions: (1) Maximize the machine acceleration. The planner
will be able to compute higher velocity profiles within the same combined distance. (2) Maximize line
motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
for the planner to compute over. It also increases the number of computations the planner has to perform
to compute an optimal plan, so select carefully.
*/
// The kernel called by recalculate() when scanning the plan from last to first entry.
void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
if (current) {
// If entry speed is already at the maximum entry speed, and there was no change of speed
// in the next block, there is no need to recheck. Block is cruising and there is no need to
// compute anything for this block,
// If not, block entry speed needs to be recalculated to ensure maximum possible planned speed.
const float max_entry_speed_sqr = current->max_entry_speed_sqr;
// Compute maximum entry speed decelerating over the current block from its exit speed.
// If not at the maximum entry speed, or the previous block entry speed changed
if (current->entry_speed_sqr != max_entry_speed_sqr || (next && TEST(next->flag, BLOCK_BIT_RECALCULATE))) {
// If nominal length true, max junction speed is guaranteed to be reached.
// If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
// the current block and next block junction speeds are guaranteed to always be at their maximum
// junction speeds in deceleration and acceleration, respectively. This is due to how the current
// block nominal speed limits both the current and next maximum junction speeds. Hence, in both
// the reverse and forward planners, the corresponding block junction speed will always be at the
// the maximum junction speed and may always be ignored for any speed reduction checks.
const float new_entry_speed_sqr = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
? max_entry_speed_sqr
: MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next ? next->entry_speed_sqr : sq(float(MINIMUM_PLANNER_SPEED)), current->millimeters));
if (current->entry_speed_sqr != new_entry_speed_sqr) {
// Need to recalculate the block speed - Mark it now, so the stepper
// ISR does not consume the block before being recalculated
SBI(current->flag, BLOCK_BIT_RECALCULATE);
// But there is an inherent race condition here, as the block may have
// become BUSY just before being marked RECALCULATE, so check for that!
if (stepper.is_block_busy(current)) {
// Block became busy. Clear the RECALCULATE flag (no point in
// recalculating BUSY blocks). And don't set its speed, as it can't
// be updated at this time.
CBI(current->flag, BLOCK_BIT_RECALCULATE);
}
else {
// Block is not BUSY so this is ahead of the Stepper ISR:
// Just Set the new entry speed.
current->entry_speed_sqr = new_entry_speed_sqr;
}
}
}
}
}
/**
* recalculate() needs to go over the current plan twice.
* Once in reverse and once forward. This implements the reverse pass.
*/
void Planner::reverse_pass() {
// Initialize block index to the last block in the planner buffer.
uint8_t block_index = prev_block_index(block_buffer_head);
// Read the index of the last buffer planned block.
// The ISR may change it so get a stable local copy.
uint8_t planned_block_index = block_buffer_planned;
// If there was a race condition and block_buffer_planned was incremented
// or was pointing at the head (queue empty) break loop now and avoid
// planning already consumed blocks
if (planned_block_index == block_buffer_head) return;
// Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
// block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
// NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
const block_t *next = nullptr;
while (block_index != planned_block_index) {
// Perform the reverse pass
block_t *current = &block_buffer[block_index];
// Only consider non sync blocks
if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
reverse_pass_kernel(current, next);
next = current;
}
// Advance to the next
block_index = prev_block_index(block_index);
// The ISR could advance the block_buffer_planned while we were doing the reverse pass.
// We must try to avoid using an already consumed block as the last one - So follow
// changes to the pointer and make sure to limit the loop to the currently busy block
while (planned_block_index != block_buffer_planned) {
// If we reached the busy block or an already processed block, break the loop now
if (block_index == planned_block_index) return;
// Advance the pointer, following the busy block
planned_block_index = next_block_index(planned_block_index);
}
}
}
// The kernel called by recalculate() when scanning the plan from first to last entry.
void Planner::forward_pass_kernel(const block_t* const previous, block_t* const current, const uint8_t block_index) {
if (previous) {
// If the previous block is an acceleration block, too short to complete the full speed
// change, adjust the entry speed accordingly. Entry speeds have already been reset,
// maximized, and reverse-planned. If nominal length is set, max junction speed is
// guaranteed to be reached. No need to recheck.
if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH) &&
previous->entry_speed_sqr < current->entry_speed_sqr) {
// Compute the maximum allowable speed
const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters);
// If true, current block is full-acceleration and we can move the planned pointer forward.
if (new_entry_speed_sqr < current->entry_speed_sqr) {
// Mark we need to recompute the trapezoidal shape, and do it now,
// so the stepper ISR does not consume the block before being recalculated
SBI(current->flag, BLOCK_BIT_RECALCULATE);
// But there is an inherent race condition here, as the block maybe
// became BUSY, just before it was marked as RECALCULATE, so check
// if that is the case!
if (stepper.is_block_busy(current)) {
// Block became busy. Clear the RECALCULATE flag (no point in
// recalculating BUSY blocks and don't set its speed, as it can't
// be updated at this time.
CBI(current->flag, BLOCK_BIT_RECALCULATE);
}
else {
// Block is not BUSY, we won the race against the Stepper ISR:
// Always <= max_entry_speed_sqr. Backward pass sets this.
current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this.
// Set optimal plan pointer.
block_buffer_planned = block_index;
}
}
}
// Any block set at its maximum entry speed also creates an optimal plan up to this
// point in the buffer. When the plan is bracketed by either the beginning of the
// buffer and a maximum entry speed or two maximum entry speeds, every block in between
// cannot logically be further improved. Hence, we don't have to recompute them anymore.
if (current->entry_speed_sqr == current->max_entry_speed_sqr)
block_buffer_planned = block_index;
}
}
/**
* recalculate() needs to go over the current plan twice.
* Once in reverse and once forward. This implements the forward pass.
*/
void Planner::forward_pass() {
// Forward Pass: Forward plan the acceleration curve from the planned pointer onward.
// Also scans for optimal plan breakpoints and appropriately updates the planned pointer.
// Begin at buffer planned pointer. Note that block_buffer_planned can be modified
// by the stepper ISR, so read it ONCE. It it guaranteed that block_buffer_planned
// will never lead head, so the loop is safe to execute. Also note that the forward
// pass will never modify the values at the tail.
uint8_t block_index = block_buffer_planned;
block_t *current;
const block_t * previous = nullptr;
while (block_index != block_buffer_head) {
// Perform the forward pass
current = &block_buffer[block_index];
// Skip SYNC blocks
if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
// If there's no previous block or the previous block is not
// BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise,
// the previous block became BUSY, so assume the current block's
// entry speed can't be altered (since that would also require
// updating the exit speed of the previous block).
if (!previous || !stepper.is_block_busy(previous))
forward_pass_kernel(previous, current, block_index);
previous = current;
}
// Advance to the previous
block_index = next_block_index(block_index);
}
}
/**
* Recalculate the trapezoid speed profiles for all blocks in the plan
* according to the entry_factor for each junction. Must be called by
* recalculate() after updating the blocks.
*/
void Planner::recalculate_trapezoids() {
// The tail may be changed by the ISR so get a local copy.
uint8_t block_index = block_buffer_tail,
head_block_index = block_buffer_head;
// Since there could be a sync block in the head of the queue, and the
// next loop must not recalculate the head block (as it needs to be
// specially handled), scan backwards to the first non-SYNC block.
while (head_block_index != block_index) {
// Go back (head always point to the first free block)
const uint8_t prev_index = prev_block_index(head_block_index);
// Get the pointer to the block
block_t *prev = &block_buffer[prev_index];
// If not dealing with a sync block, we are done. The last block is not a SYNC block
if (!TEST(prev->flag, BLOCK_BIT_SYNC_POSITION)) break;
// Examine the previous block. This and all following are SYNC blocks
head_block_index = prev_index;
}
// Go from the tail (currently executed block) to the first block, without including it)
block_t *current = nullptr, *next = nullptr;
float current_entry_speed = 0.0, next_entry_speed = 0.0;
while (block_index != head_block_index) {
next = &block_buffer[block_index];
// Skip sync blocks
if (!TEST(next->flag, BLOCK_BIT_SYNC_POSITION)) {
next_entry_speed = SQRT(next->entry_speed_sqr);
if (current) {
// Recalculate if current block entry or exit junction speed has changed.
if (TEST(current->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
// Mark the current block as RECALCULATE, to protect it from the Stepper ISR running it.
// Note that due to the above condition, there's a chance the current block isn't marked as
// RECALCULATE yet, but the next one is. That's the reason for the following line.
SBI(current->flag, BLOCK_BIT_RECALCULATE);
// But there is an inherent race condition here, as the block maybe
// became BUSY, just before it was marked as RECALCULATE, so check
// if that is the case!
if (!stepper.is_block_busy(current)) {
// Block is not BUSY, we won the race against the Stepper ISR:
// NOTE: Entry and exit factors always > 0 by all previous logic operations.
const float current_nominal_speed = SQRT(current->nominal_speed_sqr),
nomr = 1.0f / current_nominal_speed;
calculate_trapezoid_for_block(current, current_entry_speed * nomr, next_entry_speed * nomr);
#if ENABLED(LIN_ADVANCE)
if (current->use_advance_lead) {
const float comp = current->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
current->max_adv_steps = current_nominal_speed * comp;
current->final_adv_steps = next_entry_speed * comp;
}
#endif
}
// Reset current only to ensure next trapezoid is computed - The
// stepper is free to use the block from now on.
CBI(current->flag, BLOCK_BIT_RECALCULATE);
}
}
current = next;
current_entry_speed = next_entry_speed;
}
block_index = next_block_index(block_index);
}
// Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
if (next) {
// Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it.
// As the last block is always recalculated here, there is a chance the block isn't
// marked as RECALCULATE yet. That's the reason for the following line.
SBI(next->flag, BLOCK_BIT_RECALCULATE);
// But there is an inherent race condition here, as the block maybe
// became BUSY, just before it was marked as RECALCULATE, so check
// if that is the case!
if (!stepper.is_block_busy(current)) {
// Block is not BUSY, we won the race against the Stepper ISR:
const float next_nominal_speed = SQRT(next->nominal_speed_sqr),
nomr = 1.0f / next_nominal_speed;
calculate_trapezoid_for_block(next, next_entry_speed * nomr, float(MINIMUM_PLANNER_SPEED) * nomr);
#if ENABLED(LIN_ADVANCE)
if (next->use_advance_lead) {
const float comp = next->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
next->max_adv_steps = next_nominal_speed * comp;
next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
}
#endif
}
// Reset next only to ensure its trapezoid is computed - The stepper is free to use
// the block from now on.
CBI(next->flag, BLOCK_BIT_RECALCULATE);
}
}
void Planner::recalculate() {
// Initialize block index to the last block in the planner buffer.
const uint8_t block_index = prev_block_index(block_buffer_head);
// If there is just one block, no planning can be done. Avoid it!
if (block_index != block_buffer_planned) {
reverse_pass();
forward_pass();
}
recalculate_trapezoids();
}
#if ENABLED(AUTOTEMP)
void Planner::getHighESpeed() {
static float oldt = 0;
if (!autotemp_enabled) return;
if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
float high = 0.0;
for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
block_t* block = &block_buffer[b];
if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
const float se = (float)block->steps[E_AXIS] / block->step_event_count * SQRT(block->nominal_speed_sqr); // mm/sec;
NOLESS(high, se);
}
}
float t = autotemp_min + high * autotemp_factor;
t = constrain(t, autotemp_min, autotemp_max);
if (t < oldt) t = t * (1 - float(AUTOTEMP_OLDWEIGHT)) + oldt * float(AUTOTEMP_OLDWEIGHT);
oldt = t;
thermalManager.setTargetHotend(t, 0);
}
#endif // AUTOTEMP
/**
* Maintain fans, paste extruder pressure,
*/
void Planner::check_axes_activity() {
uint8_t axis_active[NUM_AXIS] = { 0 },
tail_fan_speed[FAN_COUNT];
#if ENABLED(BARICUDA)
#if HAS_HEATER_1
uint8_t tail_valve_pressure;
#endif
#if HAS_HEATER_2
uint8_t tail_e_to_p_pressure;
#endif
#endif
if (has_blocks_queued()) {
#if FAN_COUNT > 0
FANS_LOOP(i)
tail_fan_speed[i] = (block_buffer[block_buffer_tail].fan_speed[i] * uint16_t(thermalManager.fan_speed_scaler[i])) >> 7;
#endif
block_t* block;
#if ENABLED(BARICUDA)
block = &block_buffer[block_buffer_tail];
#if HAS_HEATER_1
tail_valve_pressure = block->valve_pressure;
#endif
#if HAS_HEATER_2
tail_e_to_p_pressure = block->e_to_p_pressure;
#endif
#endif
for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
block = &block_buffer[b];
LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
}
}
else {
#if FAN_COUNT > 0
FANS_LOOP(i)
tail_fan_speed[i] = (thermalManager.fan_speed[i] * uint16_t(thermalManager.fan_speed_scaler[i])) >> 7;
#endif
#if ENABLED(BARICUDA)
#if HAS_HEATER_1
tail_valve_pressure = baricuda_valve_pressure;
#endif
#if HAS_HEATER_2
tail_e_to_p_pressure = baricuda_e_to_p_pressure;
#endif
#endif
}
#if ENABLED(DISABLE_X)
if (!axis_active[X_AXIS]) disable_X();
#endif
#if ENABLED(DISABLE_Y)
if (!axis_active[Y_AXIS]) disable_Y();
#endif
#if ENABLED(DISABLE_Z)
if (!axis_active[Z_AXIS]) disable_Z();
#endif
#if ENABLED(DISABLE_E)
if (!axis_active[E_AXIS]) disable_e_steppers();
#endif
#if FAN_COUNT > 0
#if FAN_KICKSTART_TIME > 0
static millis_t fan_kick_end[FAN_COUNT] = { 0 };
#define KICKSTART_FAN(f) \
if (tail_fan_speed[f]) { \
millis_t ms = millis(); \
if (fan_kick_end[f] == 0) { \
fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
tail_fan_speed[f] = 255; \
} else if (PENDING(ms, fan_kick_end[f])) \
tail_fan_speed[f] = 255; \
} else fan_kick_end[f] = 0
#if HAS_FAN0
KICKSTART_FAN(0);
#endif
#if HAS_FAN1
KICKSTART_FAN(1);
#endif
#if HAS_FAN2
KICKSTART_FAN(2);
#endif
#endif // FAN_KICKSTART_TIME > 0
#if FAN_MIN_PWM != 0 || FAN_MAX_PWM != 255
#define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? map(tail_fan_speed[f], 1, 255, FAN_MIN_PWM, FAN_MAX_PWM) : 0)
#else
#define CALC_FAN_SPEED(f) tail_fan_speed[f]
#endif
#if ENABLED(FAN_SOFT_PWM)
#if HAS_FAN0
thermalManager.soft_pwm_amount_fan[0] = CALC_FAN_SPEED(0);
#endif
#if HAS_FAN1
thermalManager.soft_pwm_amount_fan[1] = CALC_FAN_SPEED(1);
#endif
#if HAS_FAN2
thermalManager.soft_pwm_amount_fan[2] = CALC_FAN_SPEED(2);
#endif
#elif ENABLED(FAST_PWM_FAN)
#if HAS_FAN0
set_pwm_duty(FAN_PIN, CALC_FAN_SPEED(0));
#endif
#if HAS_FAN1
set_pwm_duty(FAN1_PIN, CALC_FAN_SPEED(1));
#endif
#if HAS_FAN2
set_pwm_duty(FAN2_PIN, CALC_FAN_SPEED(2));
#endif
#else
#if HAS_FAN0
analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
#endif
#if HAS_FAN1
analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
#endif
#if HAS_FAN2
analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
#endif
#endif
#endif // FAN_COUNT > 0
#if ENABLED(AUTOTEMP)
getHighESpeed();
#endif
#if ENABLED(BARICUDA)
#if HAS_HEATER_1
analogWrite(HEATER_1_PIN, tail_valve_pressure);
#endif
#if HAS_HEATER_2
analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
#endif
#endif
}
#if DISABLED(NO_VOLUMETRICS)
/**
* Get a volumetric multiplier from a filament diameter.
* This is the reciprocal of the circular cross-section area.
* Return 1.0 with volumetric off or a diameter of 0.0.
*/
inline float calculate_volumetric_multiplier(const float &diameter) {
return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5f) : 1;
}
/**
* Convert the filament sizes into volumetric multipliers.
* The multiplier converts a given E value into a length.
*/
void Planner::calculate_volumetric_multipliers() {
for (uint8_t i = 0; i < COUNT(filament_size); i++) {
volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
refresh_e_factor(i);
}
}
#endif // !NO_VOLUMETRICS
#if ENABLED(FILAMENT_WIDTH_SENSOR)
/**
* Convert the ratio value given by the filament width sensor
* into a volumetric multiplier. Conversion differs when using
* linear extrusion vs volumetric extrusion.
*/
void Planner::calculate_volumetric_for_width_sensor(const int8_t encoded_ratio) {
// Reconstitute the nominal/measured ratio
const float nom_meas_ratio = 1 + 0.01f * encoded_ratio,
ratio_2 = sq(nom_meas_ratio);
volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
? ratio_2 / CIRCLE_AREA(filament_width_nominal * 0.5f) // Volumetric uses a true volumetric multiplier
: ratio_2; // Linear squares the ratio, which scales the volume
refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
}
#endif
#if HAS_LEVELING
/**
* rx, ry, rz - Cartesian positions in mm
* Leveled XYZ on completion
*/
void Planner::apply_leveling(float &rx, float &ry, float &rz) {
if (!leveling_active) return;
#if ABL_PLANAR
float dx = rx - (X_TILT_FULCRUM),
dy = ry - (Y_TILT_FULCRUM);
apply_rotation_xyz(bed_level_matrix, dx, dy, rz);
rx = dx + X_TILT_FULCRUM;
ry = dy + Y_TILT_FULCRUM;
#elif HAS_MESH
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
const float fade_scaling_factor = fade_scaling_factor_for_z(rz);
#else
constexpr float fade_scaling_factor = 1.0;
#endif
#if ENABLED(AUTO_BED_LEVELING_BILINEAR)
const float raw[XYZ] = { rx, ry, 0 };
#endif
rz += (
#if ENABLED(MESH_BED_LEVELING)
mbl.get_z(rx, ry
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
, fade_scaling_factor
#endif
)
#elif ENABLED(AUTO_BED_LEVELING_UBL)
fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(rx, ry) : 0.0
#elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
#endif
);
#endif
}
void Planner::unapply_leveling(float raw[XYZ]) {
if (leveling_active) {
#if ABL_PLANAR
matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
float dx = raw[X_AXIS] - (X_TILT_FULCRUM),
dy = raw[Y_AXIS] - (Y_TILT_FULCRUM);
apply_rotation_xyz(inverse, dx, dy, raw[Z_AXIS]);
raw[X_AXIS] = dx + X_TILT_FULCRUM;
raw[Y_AXIS] = dy + Y_TILT_FULCRUM;
#elif HAS_MESH
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
const float fade_scaling_factor = fade_scaling_factor_for_z(raw[Z_AXIS]);
#else
constexpr float fade_scaling_factor = 1.0;
#endif
raw[Z_AXIS] -= (
#if ENABLED(MESH_BED_LEVELING)
mbl.get_z(raw[X_AXIS], raw[Y_AXIS]
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
, fade_scaling_factor
#endif
)
#elif ENABLED(AUTO_BED_LEVELING_UBL)
fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw[X_AXIS], raw[Y_AXIS]) : 0.0
#elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
#endif
);
#endif
}
#if ENABLED(SKEW_CORRECTION)
unskew(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]);
#endif
}
#endif // HAS_LEVELING
#if ENABLED(FWRETRACT)
/**
* rz, e - Cartesian positions in mm
*/
void Planner::apply_retract(float &rz, float &e) {
rz += fwretract.current_hop;
e -= fwretract.current_retract[active_extruder];
}
void Planner::unapply_retract(float &rz, float &e) {
rz -= fwretract.current_hop;
e += fwretract.current_retract[active_extruder];
}
#endif
void Planner::quick_stop() {
// Remove all the queued blocks. Note that this function is NOT
// called from the Stepper ISR, so we must consider tail as readonly!
// that is why we set head to tail - But there is a race condition that
// must be handled: The tail could change between the read and the assignment
// so this must be enclosed in a critical section
const bool was_enabled = STEPPER_ISR_ENABLED();
if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
// Drop all queue entries
block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail;
// Restart the block delay for the first movement - As the queue was
// forced to empty, there's no risk the ISR will touch this.
delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
#if ENABLED(ULTRA_LCD)
// Clear the accumulated runtime
clear_block_buffer_runtime();
#endif
// Make sure to drop any attempt of queuing moves for at least 1 second
cleaning_buffer_counter = 1000;
// Reenable Stepper ISR
if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
// And stop the stepper ISR
stepper.quick_stop();
}
void Planner::endstop_triggered(const AxisEnum axis) {
// Record stepper position and discard the current block
stepper.endstop_triggered(axis);
}
float Planner::triggered_position_mm(const AxisEnum axis) {
return stepper.triggered_position(axis) * steps_to_mm[axis];
}
void Planner::finish_and_disable() {
while (has_blocks_queued() || cleaning_buffer_counter) idle();
disable_all_steppers();
}
/**
* Get an axis position according to stepper position(s)
* For CORE machines apply translation from ABC to XYZ.
*/
float Planner::get_axis_position_mm(const AxisEnum axis) {
float axis_steps;
#if IS_CORE
// Requesting one of the "core" axes?
if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
// Protect the access to the position.
const bool was_enabled = STEPPER_ISR_ENABLED();
if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
// ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
// ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
axis_steps = 0.5f * (
axis == CORE_AXIS_2 ? CORESIGN(stepper.position(CORE_AXIS_1) - stepper.position(CORE_AXIS_2))
: stepper.position(CORE_AXIS_1) + stepper.position(CORE_AXIS_2)
);
if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
}
else
axis_steps = stepper.position(axis);
#else
axis_steps = stepper.position(axis);
#endif
return axis_steps * steps_to_mm[axis];
}
/**
* Block until all buffered steps are executed / cleaned
*/
void Planner::synchronize() {
while (
has_blocks_queued() || cleaning_buffer_counter
#if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
|| (READ(CLOSED_LOOP_ENABLE_PIN) && !READ(CLOSED_LOOP_MOVE_COMPLETE_PIN))
#endif
) idle();
}
/**
* Planner::_buffer_steps
*
* Add a new linear movement to the planner queue (in terms of steps).
*
* target - target position in steps units
* target_float - target position in direct (mm, degrees) units. optional
* fr_mm_s - (target) speed of the move
* extruder - target extruder
* millimeters - the length of the movement, if known
*
* Returns true if movement was properly queued, false otherwise
*/
bool Planner::_buffer_steps(const int32_t (&target)[XYZE]
#if HAS_POSITION_FLOAT
, const float (&target_float)[ABCE]
#endif
#if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
, const float (&delta_mm_cart)[XYZE]
#endif
, float fr_mm_s, const uint8_t extruder, const float &millimeters
) {
// If we are cleaning, do not accept queuing of movements
if (cleaning_buffer_counter) return false;
// Wait for the next available block
uint8_t next_buffer_head;
block_t * const block = get_next_free_block(next_buffer_head);
// Fill the block with the specified movement
if (!_populate_block(block, false, target
#if HAS_POSITION_FLOAT
, target_float
#endif
#if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
, delta_mm_cart
#endif
, fr_mm_s, extruder, millimeters
)) {
// Movement was not queued, probably because it was too short.
// Simply accept that as movement queued and done
return true;
}
// If this is the first added movement, reload the delay, otherwise, cancel it.
if (block_buffer_head == block_buffer_tail) {
// If it was the first queued block, restart the 1st block delivery delay, to
// give the planner an opportunity to queue more movements and plan them
// As there are no queued movements, the Stepper ISR will not touch this
// variable, so there is no risk setting this here (but it MUST be done
// before the following line!!)
delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
}
// Move buffer head
block_buffer_head = next_buffer_head;
// Recalculate and optimize trapezoidal speed profiles
recalculate();
// Movement successfully queued!
return true;
}
/**
* Planner::_populate_block
*
* Fills a new linear movement in the block (in terms of steps).
*
* target - target position in steps units
* fr_mm_s - (target) speed of the move
* extruder - target extruder
*
* Returns true is movement is acceptable, false otherwise
*/
bool Planner::_populate_block(block_t * const block, bool split_move,
const int32_t (&target)[ABCE]
#if HAS_POSITION_FLOAT
, const float (&target_float)[ABCE]
#endif
#if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
, const float (&delta_mm_cart)[XYZE]
#endif
, float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
) {
const int32_t da = target[A_AXIS] - position[A_AXIS],
db = target[B_AXIS] - position[B_AXIS],
dc = target[C_AXIS] - position[C_AXIS];
int32_t de = target[E_AXIS] - position[E_AXIS];
/* <-- add a slash to enable
SERIAL_ECHOPAIR(" _populate_block FR:", fr_mm_s);
SERIAL_ECHOPAIR(" A:", target[A_AXIS]);
SERIAL_ECHOPAIR(" (", da);
SERIAL_ECHOPAIR(" steps) B:", target[B_AXIS]);
SERIAL_ECHOPAIR(" (", db);
SERIAL_ECHOPAIR(" steps) C:", target[C_AXIS]);
SERIAL_ECHOPAIR(" (", dc);
SERIAL_ECHOPAIR(" steps) E:", target[E_AXIS]);
SERIAL_ECHOPAIR(" (", de);
SERIAL_ECHOLNPGM(" steps)");
//*/
#if EITHER(PREVENT_COLD_EXTRUSION, PREVENT_LENGTHY_EXTRUDE)
if (de) {
#if ENABLED(PREVENT_COLD_EXTRUSION)
if (thermalManager.tooColdToExtrude(extruder)) {
position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
#if HAS_POSITION_FLOAT
position_float[E_AXIS] = target_float[E_AXIS];
#endif
de = 0; // no difference
SERIAL_ECHO_MSG(MSG_ERR_COLD_EXTRUDE_STOP);
}
#endif // PREVENT_COLD_EXTRUSION
#if ENABLED(PREVENT_LENGTHY_EXTRUDE)
const float e_steps = ABS(de * e_factor[extruder]);
const float max_e_steps = settings.axis_steps_per_mm[E_AXIS_N(extruder)] * (EXTRUDE_MAXLENGTH);
if (e_steps > max_e_steps) {
#if ENABLED(MIXING_EXTRUDER)
bool ignore_e = false;
float collector[MIXING_STEPPERS];
mixer.refresh_collector(1.0, mixer.get_current_vtool(), collector);
MIXER_STEPPER_LOOP(e)
if (e_steps * collector[e] > max_e_steps) { ignore_e = true; break; }
#else
constexpr bool ignore_e = true;
#endif
if (ignore_e) {
position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
#if HAS_POSITION_FLOAT
position_float[E_AXIS] = target_float[E_AXIS];
#endif
de = 0; // no difference
SERIAL_ECHO_MSG(MSG_ERR_LONG_EXTRUDE_STOP);
}
}
#endif // PREVENT_LENGTHY_EXTRUDE
}
#endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
// Compute direction bit-mask for this block
uint8_t dm = 0;
#if CORE_IS_XY
if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
if (db < 0) SBI(dm, Y_HEAD); // ...and Y
if (dc < 0) SBI(dm, Z_AXIS);
if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
#elif CORE_IS_XZ
if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
if (db < 0) SBI(dm, Y_AXIS);
if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
#elif CORE_IS_YZ
if (da < 0) SBI(dm, X_AXIS);
if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
#else
if (da < 0) SBI(dm, X_AXIS);
if (db < 0) SBI(dm, Y_AXIS);
if (dc < 0) SBI(dm, Z_AXIS);
#endif
if (de < 0) SBI(dm, E_AXIS);
const float esteps_float = de * e_factor[extruder];
const uint32_t esteps = ABS(esteps_float) + 0.5f;
// Clear all flags, including the "busy" bit
block->flag = 0x00;
// Set direction bits
block->direction_bits = dm;
// Number of steps for each axis
// See http://www.corexy.com/theory.html
#if CORE_IS_XY
block->steps[A_AXIS] = ABS(da + db);
block->steps[B_AXIS] = ABS(da - db);
block->steps[Z_AXIS] = ABS(dc);
#elif CORE_IS_XZ
block->steps[A_AXIS] = ABS(da + dc);
block->steps[Y_AXIS] = ABS(db);
block->steps[C_AXIS] = ABS(da - dc);
#elif CORE_IS_YZ
block->steps[X_AXIS] = ABS(da);
block->steps[B_AXIS] = ABS(db + dc);
block->steps[C_AXIS] = ABS(db - dc);
#elif IS_SCARA
block->steps[A_AXIS] = ABS(da);
block->steps[B_AXIS] = ABS(db);
block->steps[Z_AXIS] = ABS(dc);
#else
// default non-h-bot planning
block->steps[A_AXIS] = ABS(da);
block->steps[B_AXIS] = ABS(db);
block->steps[C_AXIS] = ABS(dc);
#endif
/**
* This part of the code calculates the total length of the movement.
* For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
* But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
* and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
* So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
* Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
*/
#if IS_CORE
float delta_mm[Z_HEAD + 1];
#if CORE_IS_XY
delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
#elif CORE_IS_XZ
delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
#elif CORE_IS_YZ
delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
#endif
#else
float delta_mm[ABCE];
delta_mm[A_AXIS] = da * steps_to_mm[A_AXIS];
delta_mm[B_AXIS] = db * steps_to_mm[B_AXIS];
delta_mm[C_AXIS] = dc * steps_to_mm[C_AXIS];
#endif
delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS_N(extruder)];
if (block->steps[A_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[B_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[C_AXIS] < MIN_STEPS_PER_SEGMENT) {
block->millimeters = ABS(delta_mm[E_AXIS]);
}
else {
if (millimeters)
block->millimeters = millimeters;
else
block->millimeters = SQRT(
#if CORE_IS_XY
sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
#elif CORE_IS_XZ
sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
#elif CORE_IS_YZ
sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
#else
sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
#endif
);
/**
* At this point at least one of the axes has more steps than
* MIN_STEPS_PER_SEGMENT, ensuring the segment won't get dropped as
* zero-length. It's important to not apply corrections
* to blocks that would get dropped!
*
* A correction function is permitted to add steps to an axis, it
* should *never* remove steps!
*/
#if ENABLED(BACKLASH_COMPENSATION)
backlash.add_correction_steps(da, db, dc, dm, block);
#endif
}
block->steps[E_AXIS] = esteps;
block->step_event_count = MAX(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], esteps);
// Bail if this is a zero-length block
if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false;
#if ENABLED(MIXING_EXTRUDER)
MIXER_POPULATE_BLOCK();
#endif
#if FAN_COUNT > 0
FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
#endif
#if ENABLED(BARICUDA)
block->valve_pressure = baricuda_valve_pressure;
block->e_to_p_pressure = baricuda_e_to_p_pressure;
#endif
#if EXTRUDERS > 1
block->extruder = extruder;
#endif
#if ENABLED(AUTO_POWER_CONTROL)
if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS])
powerManager.power_on();
#endif
// Enable active axes
#if CORE_IS_XY
if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
enable_X();
enable_Y();
}
#if DISABLED(Z_LATE_ENABLE)
if (block->steps[Z_AXIS]) enable_Z();
#endif
#elif CORE_IS_XZ
if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
enable_X();
enable_Z();
}
if (block->steps[Y_AXIS]) enable_Y();
#elif CORE_IS_YZ
if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
enable_Y();
enable_Z();
}
if (block->steps[X_AXIS]) enable_X();
#else
if (block->steps[X_AXIS]) enable_X();
if (block->steps[Y_AXIS]) enable_Y();
#if DISABLED(Z_LATE_ENABLE)
if (block->steps[Z_AXIS]) enable_Z();
#endif
#endif
// Enable extruder(s)
if (esteps) {
#if ENABLED(AUTO_POWER_CONTROL)
powerManager.power_on();
#endif
#if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
#define DISABLE_IDLE_E(N) if (!g_uc_extruder_last_move[N]) disable_E##N();
for (uint8_t i = 0; i < EXTRUDERS; i++)
if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
switch (extruder) {
case 0:
#if EXTRUDERS > 1
DISABLE_IDLE_E(1);
#if EXTRUDERS > 2
DISABLE_IDLE_E(2);
#if EXTRUDERS > 3
DISABLE_IDLE_E(3);
#if EXTRUDERS > 4
DISABLE_IDLE_E(4);
#if EXTRUDERS > 5
DISABLE_IDLE_E(5);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#endif // EXTRUDERS > 1
enable_E0();
g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
#if HAS_DUPLICATION_MODE
if (extruder_duplication_enabled) {
enable_E1();
g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
}
#endif
break;
#if EXTRUDERS > 1
case 1:
DISABLE_IDLE_E(0);
#if EXTRUDERS > 2
DISABLE_IDLE_E(2);
#if EXTRUDERS > 3
DISABLE_IDLE_E(3);
#if EXTRUDERS > 4
DISABLE_IDLE_E(4);
#if EXTRUDERS > 5
DISABLE_IDLE_E(5);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
enable_E1();
g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
break;
#if EXTRUDERS > 2
case 2:
DISABLE_IDLE_E(0);
DISABLE_IDLE_E(1);
#if EXTRUDERS > 3
DISABLE_IDLE_E(3);
#if EXTRUDERS > 4
DISABLE_IDLE_E(4);
#if EXTRUDERS > 5
DISABLE_IDLE_E(5);
#endif
#endif
#endif
enable_E2();
g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
break;
#if EXTRUDERS > 3
case 3:
DISABLE_IDLE_E(0);
DISABLE_IDLE_E(1);
DISABLE_IDLE_E(2);
#if EXTRUDERS > 4
DISABLE_IDLE_E(4);
#if EXTRUDERS > 5
DISABLE_IDLE_E(5);
#endif
#endif
enable_E3();
g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
break;
#if EXTRUDERS > 4
case 4:
DISABLE_IDLE_E(0);
DISABLE_IDLE_E(1);
DISABLE_IDLE_E(2);
DISABLE_IDLE_E(3);
#if EXTRUDERS > 5
DISABLE_IDLE_E(5);
#endif
enable_E4();
g_uc_extruder_last_move[4] = (BLOCK_BUFFER_SIZE) * 2;
break;
#if EXTRUDERS > 5
case 5:
DISABLE_IDLE_E(0);
DISABLE_IDLE_E(1);
DISABLE_IDLE_E(2);
DISABLE_IDLE_E(3);
DISABLE_IDLE_E(4);
enable_E5();
g_uc_extruder_last_move[5] = (BLOCK_BUFFER_SIZE) * 2;
break;
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#endif // EXTRUDERS > 1
}
#else
enable_E0();
enable_E1();
enable_E2();
enable_E3();
enable_E4();
enable_E5();
#endif
}
if (esteps)
NOLESS(fr_mm_s, settings.min_feedrate_mm_s);
else
NOLESS(fr_mm_s, settings.min_travel_feedrate_mm_s);
const float inverse_millimeters = 1.0f / block->millimeters; // Inverse millimeters to remove multiple divides
// Calculate inverse time for this move. No divide by zero due to previous checks.
// Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
float inverse_secs = fr_mm_s * inverse_millimeters;
// Get the number of non busy movements in queue (non busy means that they can be altered)
const uint8_t moves_queued = nonbusy_movesplanned();
// Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
#if EITHER(SLOWDOWN, ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
// Segment time im micro seconds
uint32_t segment_time_us = LROUND(1000000.0f / inverse_secs);
#endif
#if ENABLED(SLOWDOWN)
if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / 2 - 1)) {
if (segment_time_us < settings.min_segment_time_us) {
// buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
const uint32_t nst = segment_time_us + LROUND(2 * (settings.min_segment_time_us - segment_time_us) / moves_queued);
inverse_secs = 1000000.0f / nst;
#if defined(XY_FREQUENCY_LIMIT) || ENABLED(ULTRA_LCD)
segment_time_us = nst;
#endif
}
}
#endif
#if ENABLED(ULTRA_LCD)
// Protect the access to the position.
const bool was_enabled = STEPPER_ISR_ENABLED();
if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
block_buffer_runtime_us += segment_time_us;
if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
#endif
block->nominal_speed_sqr = sq(block->millimeters * inverse_secs); // (mm/sec)^2 Always > 0
block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
#if ENABLED(FILAMENT_WIDTH_SENSOR)
static float filwidth_e_count = 0, filwidth_delay_dist = 0;
//FMM update ring buffer used for delay with filament measurements
if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index[1] >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
// increment counters with next move in e axis
filwidth_e_count += delta_mm[E_AXIS];
filwidth_delay_dist += delta_mm[E_AXIS];
// Only get new measurements on forward E movement
if (!UNEAR_ZERO(filwidth_e_count)) {
// Loop the delay distance counter (modulus by the mm length)
while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
// Convert into an index into the measurement array
filwidth_delay_index[0] = int8_t(filwidth_delay_dist * 0.1f);
// If the index has changed (must have gone forward)...
if (filwidth_delay_index[0] != filwidth_delay_index[1]) {
filwidth_e_count = 0; // Reset the E movement counter
const int8_t meas_sample = thermalManager.widthFil_to_size_ratio();
do {
filwidth_delay_index[1] = (filwidth_delay_index[1] + 1) % MMD_CM; // The next unused slot
measurement_delay[filwidth_delay_index[1]] = meas_sample; // Store the measurement
} while (filwidth_delay_index[0] != filwidth_delay_index[1]); // More slots to fill?
}
}
}
#endif
// Calculate and limit speed in mm/sec for each axis
float current_speed[NUM_AXIS], speed_factor = 1.0f; // factor <1 decreases speed
LOOP_XYZE(i) {
#if BOTH(MIXING_EXTRUDER, RETRACT_SYNC_MIXING)
// In worst case, only one extruder running, no change is needed.
// In best case, all extruders run the same amount, we can divide by MIXING_STEPPERS
float delta_mm_i = 0;
if (i == E_AXIS && mixer.get_current_vtool() == MIXER_AUTORETRACT_TOOL)
delta_mm_i = delta_mm[i] / MIXING_STEPPERS;
else
delta_mm_i = delta_mm[i];
#else
const float delta_mm_i = delta_mm[i];
#endif
const float cs = ABS(current_speed[i] = delta_mm_i * inverse_secs);
#if ENABLED(DISTINCT_E_FACTORS)
if (i == E_AXIS) i += extruder;
#endif
if (cs > settings.max_feedrate_mm_s[i]) NOMORE(speed_factor, settings.max_feedrate_mm_s[i] / cs);
}
// Max segment time in µs.
#ifdef XY_FREQUENCY_LIMIT
// Check and limit the xy direction change frequency
const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
old_direction_bits = block->direction_bits;
segment_time_us = LROUND((float)segment_time_us / speed_factor);
uint32_t xs0 = axis_segment_time_us[X_AXIS][0],
xs1 = axis_segment_time_us[X_AXIS][1],
xs2 = axis_segment_time_us[X_AXIS][2],
ys0 = axis_segment_time_us[Y_AXIS][0],
ys1 = axis_segment_time_us[Y_AXIS][1],
ys2 = axis_segment_time_us[Y_AXIS][2];
if (TEST(direction_change, X_AXIS)) {
xs2 = axis_segment_time_us[X_AXIS][2] = xs1;
xs1 = axis_segment_time_us[X_AXIS][1] = xs0;
xs0 = 0;
}
xs0 = axis_segment_time_us[X_AXIS][0] = xs0 + segment_time_us;
if (TEST(direction_change, Y_AXIS)) {
ys2 = axis_segment_time_us[Y_AXIS][2] = axis_segment_time_us[Y_AXIS][1];
ys1 = axis_segment_time_us[Y_AXIS][1] = axis_segment_time_us[Y_AXIS][0];
ys0 = 0;
}
ys0 = axis_segment_time_us[Y_AXIS][0] = ys0 + segment_time_us;
const uint32_t max_x_segment_time = MAX(xs0, xs1, xs2),
max_y_segment_time = MAX(ys0, ys1, ys2),
min_xy_segment_time = MIN(max_x_segment_time, max_y_segment_time);
if (min_xy_segment_time < MAX_FREQ_TIME_US) {
const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
NOMORE(speed_factor, low_sf);
}
#endif // XY_FREQUENCY_LIMIT
// Correct the speed
if (speed_factor < 1.0f) {
LOOP_XYZE(i) current_speed[i] *= speed_factor;
block->nominal_rate *= speed_factor;
block->nominal_speed_sqr = block->nominal_speed_sqr * sq(speed_factor);
}
// Compute and limit the acceleration rate for the trapezoid generator.
const float steps_per_mm = block->step_event_count * inverse_millimeters;
uint32_t accel;
if (!block->steps[A_AXIS] && !block->steps[B_AXIS] && !block->steps[C_AXIS]) {
// convert to: acceleration steps/sec^2
accel = CEIL(settings.retract_acceleration * steps_per_mm);
#if ENABLED(LIN_ADVANCE)
block->use_advance_lead = false;
#endif
}
else {
#define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
} \
}while(0)
#define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
} \
}while(0)
// Start with print or travel acceleration
accel = CEIL((esteps ? settings.acceleration : settings.travel_acceleration) * steps_per_mm);
#if ENABLED(LIN_ADVANCE)
#if ENABLED(JUNCTION_DEVIATION)
#if ENABLED(DISTINCT_E_FACTORS)
#define MAX_E_JERK max_e_jerk[extruder]
#else
#define MAX_E_JERK max_e_jerk
#endif
#else
#define MAX_E_JERK max_jerk[E_AXIS]
#endif
/**
*
* Use LIN_ADVANCE for blocks if all these are true:
*
* esteps : This is a print move, because we checked for A, B, C steps before.
*
* extruder_advance_K[active_extruder] : There is an advance factor set for this extruder.
*
* de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
*/
block->use_advance_lead = esteps
&& extruder_advance_K[active_extruder]
&& de > 0;
if (block->use_advance_lead) {
block->e_D_ratio = (target_float[E_AXIS] - position_float[E_AXIS]) /
#if IS_KINEMATIC
block->millimeters
#else
SQRT(sq(target_float[X_AXIS] - position_float[X_AXIS])
+ sq(target_float[Y_AXIS] - position_float[Y_AXIS])
+ sq(target_float[Z_AXIS] - position_float[Z_AXIS]))
#endif
;
// Check for unusual high e_D ratio to detect if a retract move was combined with the last print move due to min. steps per segment. Never execute this with advance!
// This assumes no one will use a retract length of 0mm < retr_length < ~0.2mm and no one will print 100mm wide lines using 3mm filament or 35mm wide lines using 1.75mm filament.
if (block->e_D_ratio > 3.0f)
block->use_advance_lead = false;
else {
const uint32_t max_accel_steps_per_s2 = MAX_E_JERK / (extruder_advance_K[active_extruder] * block->e_D_ratio) * steps_per_mm;
#if ENABLED(LA_DEBUG)
if (accel > max_accel_steps_per_s2) SERIAL_ECHOLNPGM("Acceleration limited.");
#endif
NOMORE(accel, max_accel_steps_per_s2);
}
}
#endif
#if ENABLED(DISTINCT_E_FACTORS)
#define ACCEL_IDX extruder
#else
#define ACCEL_IDX 0
#endif
// Limit acceleration per axis
if (block->step_event_count <= cutoff_long) {
LIMIT_ACCEL_LONG(A_AXIS, 0);
LIMIT_ACCEL_LONG(B_AXIS, 0);
LIMIT_ACCEL_LONG(C_AXIS, 0);
LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
}
else {
LIMIT_ACCEL_FLOAT(A_AXIS, 0);
LIMIT_ACCEL_FLOAT(B_AXIS, 0);
LIMIT_ACCEL_FLOAT(C_AXIS, 0);
LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
}
}
block->acceleration_steps_per_s2 = accel;
block->acceleration = accel / steps_per_mm;
#if DISABLED(S_CURVE_ACCELERATION)
block->acceleration_rate = (uint32_t)(accel * (4096.0f * 4096.0f / (STEPPER_TIMER_RATE)));
#endif
#if ENABLED(LIN_ADVANCE)
if (block->use_advance_lead) {
block->advance_speed = (STEPPER_TIMER_RATE) / (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * settings.axis_steps_per_mm[E_AXIS_N(extruder)]);
#if ENABLED(LA_DEBUG)
if (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * 2 < SQRT(block->nominal_speed_sqr) * block->e_D_ratio)
SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
if (block->advance_speed < 200)
SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
#endif
}
#endif
float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2
#if ENABLED(JUNCTION_DEVIATION)
/**
* Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
* Let a circle be tangent to both previous and current path line segments, where the junction
* deviation is defined as the distance from the junction to the closest edge of the circle,
* colinear with the circle center. The circular segment joining the two paths represents the
* path of centripetal acceleration. Solve for max velocity based on max acceleration about the
* radius of the circle, defined indirectly by junction deviation. This may be also viewed as
* path width or max_jerk in the previous Grbl version. This approach does not actually deviate
* from path, but used as a robust way to compute cornering speeds, as it takes into account the
* nonlinearities of both the junction angle and junction velocity.
*
* NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path
* mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact
* stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here
* is exactly the same. Instead of motioning all the way to junction point, the machine will
* just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
* a continuous mode path, but ARM-based microcontrollers most certainly do.
*
* NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
* changed dynamically during operation nor can the line move geometry. This must be kept in
* memory in the event of a feedrate override changing the nominal speeds of blocks, which can
* change the overall maximum entry speed conditions of all blocks.
*
* #######
* https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754
*
* hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin:
Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm
on then on anything with less sides than an octagon. With this, and the
reverse pass actually recalculating things, a corner acceleration value
of 1000 junction deviation of .05 are pretty reasonable. If the cycles
can be spared, a better acos could be used. For all I know, it may be
already calculated in a different place. */
// Unit vector of previous path line segment
static float previous_unit_vec[XYZE];
#if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
float unit_vec[] = {
delta_mm_cart[X_AXIS] * inverse_millimeters,
delta_mm_cart[Y_AXIS] * inverse_millimeters,
delta_mm_cart[Z_AXIS] * inverse_millimeters,
delta_mm_cart[E_AXIS] * inverse_millimeters
};
#else
float unit_vec[] = {
delta_mm[X_AXIS] * inverse_millimeters,
delta_mm[Y_AXIS] * inverse_millimeters,
delta_mm[Z_AXIS] * inverse_millimeters,
delta_mm[E_AXIS] * inverse_millimeters
};
#endif
#if IS_CORE && ENABLED(JUNCTION_DEVIATION)
/**
* On CoreXY the length of the vector [A,B] is SQRT(2) times the length of the head movement vector [X,Y].
* So taking Z and E into account, we cannot scale to a unit vector with "inverse_millimeters".
* => normalize the complete junction vector
*/
normalize_junction_vector(unit_vec);
#endif
// Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
// Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
// NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
float junction_cos_theta = -previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
-previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
-previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS]
-previous_unit_vec[E_AXIS] * unit_vec[E_AXIS]
;
// NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
if (junction_cos_theta > 0.999999f) {
// For a 0 degree acute junction, just set minimum junction speed.
vmax_junction_sqr = sq(float(MINIMUM_PLANNER_SPEED));
}
else {
NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero.
// Convert delta vector to unit vector
float junction_unit_vec[XYZE] = {
unit_vec[X_AXIS] - previous_unit_vec[X_AXIS],
unit_vec[Y_AXIS] - previous_unit_vec[Y_AXIS],
unit_vec[Z_AXIS] - previous_unit_vec[Z_AXIS],
unit_vec[E_AXIS] - previous_unit_vec[E_AXIS]
};
normalize_junction_vector(junction_unit_vec);
const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec),
sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive.
vmax_junction_sqr = (junction_acceleration * junction_deviation_mm * sin_theta_d2) / (1.0f - sin_theta_d2);
if (block->millimeters < 1) {
// Fast acos approximation, minus the error bar to be safe
const float junction_theta = (RADIANS(-40) * sq(junction_cos_theta) - RADIANS(50)) * junction_cos_theta + RADIANS(90) - 0.18f;
// If angle is greater than 135 degrees (octagon), find speed for approximate arc
if (junction_theta > RADIANS(135)) {
const float limit_sqr = block->millimeters / (RADIANS(180) - junction_theta) * junction_acceleration;
NOMORE(vmax_junction_sqr, limit_sqr);
}
}
}
// Get the lowest speed
vmax_junction_sqr = MIN(vmax_junction_sqr, block->nominal_speed_sqr, previous_nominal_speed_sqr);
}
else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later.
vmax_junction_sqr = 0;
COPY(previous_unit_vec, unit_vec);
#endif
#if HAS_CLASSIC_JERK
/**
* Adapted from Průša MKS firmware
* https://github.com/prusa3d/Prusa-Firmware
*/
const float nominal_speed = SQRT(block->nominal_speed_sqr);
// Exit speed limited by a jerk to full halt of a previous last segment
static float previous_safe_speed;
// Start with a safe speed (from which the machine may halt to stop immediately).
float safe_speed = nominal_speed;
uint8_t limited = 0;
#if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
LOOP_XYZ(i)
#else
LOOP_XYZE(i)
#endif
{
const float jerk = ABS(current_speed[i]), // cs : Starting from zero, change in speed for this axis
maxj = max_jerk[i]; // mj : The max jerk setting for this axis
if (jerk > maxj) { // cs > mj : New current speed too fast?
if (limited) { // limited already?
const float mjerk = nominal_speed * maxj; // ns*mj
if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk; // ns*mj/cs
}
else {
safe_speed *= maxj / jerk; // Initial limit: ns*mj/cs
++limited; // Initially limited
}
}
}
float vmax_junction;
if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
// Estimate a maximum velocity allowed at a joint of two successive segments.
// If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
// then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
// Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
float v_factor = 1;
limited = 0;
// The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
// Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
const float previous_nominal_speed = SQRT(previous_nominal_speed_sqr);
vmax_junction = MIN(nominal_speed, previous_nominal_speed);
// Now limit the jerk in all axes.
const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
#if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
LOOP_XYZ(axis)
#else
LOOP_XYZE(axis)
#endif
{
// Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
float v_exit = previous_speed[axis] * smaller_speed_factor,
v_entry = current_speed[axis];
if (limited) {
v_exit *= v_factor;
v_entry *= v_factor;
}
// Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
const float jerk = (v_exit > v_entry)
? // coasting axis reversal
( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : MAX(v_exit, -v_entry) )
: // v_exit <= v_entry coasting axis reversal
( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : MAX(-v_exit, v_entry) );
if (jerk > max_jerk[axis]) {
v_factor *= max_jerk[axis] / jerk;
++limited;
}
}
if (limited) vmax_junction *= v_factor;
// Now the transition velocity is known, which maximizes the shared exit / entry velocity while
// respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
const float vmax_junction_threshold = vmax_junction * 0.99f;
if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
vmax_junction = safe_speed;
}
else
vmax_junction = safe_speed;
previous_safe_speed = safe_speed;
#if ENABLED(JUNCTION_DEVIATION)
vmax_junction_sqr = MIN(vmax_junction_sqr, sq(vmax_junction));
#else
vmax_junction_sqr = sq(vmax_junction);
#endif
#endif // Classic Jerk Limiting
// Max entry speed of this block equals the max exit speed of the previous block.
block->max_entry_speed_sqr = vmax_junction_sqr;
// Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, sq(float(MINIMUM_PLANNER_SPEED)), block->millimeters);
// If we are trying to add a split block, start with the
// max. allowed speed to avoid an interrupted first move.
block->entry_speed_sqr = !split_move ? sq(float(MINIMUM_PLANNER_SPEED)) : MIN(vmax_junction_sqr, v_allowable_sqr);
// Initialize planner efficiency flags
// Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
// If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
// the current block and next block junction speeds are guaranteed to always be at their maximum
// junction speeds in deceleration and acceleration, respectively. This is due to how the current
// block nominal speed limits both the current and next maximum junction speeds. Hence, in both
// the reverse and forward planners, the corresponding block junction speed will always be at the
// the maximum junction speed and may always be ignored for any speed reduction checks.
block->flag |= block->nominal_speed_sqr <= v_allowable_sqr ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
// Update previous path unit_vector and nominal speed
COPY(previous_speed, current_speed);
previous_nominal_speed_sqr = block->nominal_speed_sqr;
// Update the position
static_assert(COUNT(target) > 1, "Parameter to _buffer_steps must be (&target)[XYZE]!");
COPY(position, target);
#if HAS_POSITION_FLOAT
COPY(position_float, target_float);
#endif
#if ENABLED(GRADIENT_MIX)
mixer.gradient_control(target_float[Z_AXIS]);
#endif
// Movement was accepted
return true;
} // _populate_block()
/**
* Planner::buffer_sync_block
* Add a block to the buffer that just updates the position
*/
void Planner::buffer_sync_block() {
// Wait for the next available block
uint8_t next_buffer_head;
block_t * const block = get_next_free_block(next_buffer_head);
// Clear block
memset(block, 0, sizeof(block_t));
block->flag = BLOCK_FLAG_SYNC_POSITION;
block->position[A_AXIS] = position[A_AXIS];
block->position[B_AXIS] = position[B_AXIS];
block->position[C_AXIS] = position[C_AXIS];
block->position[E_AXIS] = position[E_AXIS];
// If this is the first added movement, reload the delay, otherwise, cancel it.
if (block_buffer_head == block_buffer_tail) {
// If it was the first queued block, restart the 1st block delivery delay, to
// give the planner an opportunity to queue more movements and plan them
// As there are no queued movements, the Stepper ISR will not touch this
// variable, so there is no risk setting this here (but it MUST be done
// before the following line!!)
delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
}
block_buffer_head = next_buffer_head;
stepper.wake_up();
} // buffer_sync_block()
/**
* Planner::buffer_segment
*
* Add a new linear movement to the buffer in axis units.
*
* Leveling and kinematics should be applied ahead of calling this.
*
* a,b,c,e - target positions in mm and/or degrees
* fr_mm_s - (target) speed of the move
* extruder - target extruder
* millimeters - the length of the movement, if known
*/
bool Planner::buffer_segment(const float &a, const float &b, const float &c, const float &e
#if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
, const float (&delta_mm_cart)[XYZE]
#endif
, const float &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
) {
// If we are cleaning, do not accept queuing of movements
if (cleaning_buffer_counter) return false;
// When changing extruders recalculate steps corresponding to the E position
#if ENABLED(DISTINCT_E_FACTORS)
if (last_extruder != extruder && settings.axis_steps_per_mm[E_AXIS_N(extruder)] != settings.axis_steps_per_mm[E_AXIS_N(last_extruder)]) {
position[E_AXIS] = LROUND(position[E_AXIS] * settings.axis_steps_per_mm[E_AXIS_N(extruder)] * steps_to_mm[E_AXIS_N(last_extruder)]);
last_extruder = extruder;
}
#endif
// The target position of the tool in absolute steps
// Calculate target position in absolute steps
const int32_t target[ABCE] = {
LROUND(a * settings.axis_steps_per_mm[A_AXIS]),
LROUND(b * settings.axis_steps_per_mm[B_AXIS]),
LROUND(c * settings.axis_steps_per_mm[C_AXIS]),
LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(extruder)])
};
#if HAS_POSITION_FLOAT
const float target_float[XYZE] = { a, b, c, e };
#endif
// DRYRUN prevents E moves from taking place
if (DEBUGGING(DRYRUN)) {
position[E_AXIS] = target[E_AXIS];
#if HAS_POSITION_FLOAT
position_float[E_AXIS] = e;
#endif
}
/* <-- add a slash to enable
SERIAL_ECHOPAIR(" buffer_segment FR:", fr_mm_s);
#if IS_KINEMATIC
SERIAL_ECHOPAIR(" A:", a);
SERIAL_ECHOPAIR(" (", position[A_AXIS]);
SERIAL_ECHOPAIR("->", target[A_AXIS]);
SERIAL_ECHOPAIR(") B:", b);
#else
SERIAL_ECHOPAIR(" X:", a);
SERIAL_ECHOPAIR(" (", position[X_AXIS]);
SERIAL_ECHOPAIR("->", target[X_AXIS]);
SERIAL_ECHOPAIR(") Y:", b);
#endif
SERIAL_ECHOPAIR(" (", position[Y_AXIS]);
SERIAL_ECHOPAIR("->", target[Y_AXIS]);
#if ENABLED(DELTA)
SERIAL_ECHOPAIR(") C:", c);
#else
SERIAL_ECHOPAIR(") Z:", c);
#endif
SERIAL_ECHOPAIR(" (", position[Z_AXIS]);
SERIAL_ECHOPAIR("->", target[Z_AXIS]);
SERIAL_ECHOPAIR(") E:", e);
SERIAL_ECHOPAIR(" (", position[E_AXIS]);
SERIAL_ECHOPAIR("->", target[E_AXIS]);
SERIAL_ECHOLNPGM(")");
//*/
// Queue the movement
if (
!_buffer_steps(target
#if HAS_POSITION_FLOAT
, target_float
#endif
#if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
, delta_mm_cart
#endif
, fr_mm_s, extruder, millimeters
)
) return false;
stepper.wake_up();
return true;
} // buffer_segment()
/**
* Add a new linear movement to the buffer.
* The target is cartesian, it's translated to delta/scara if
* needed.
*
*
* rx,ry,rz,e - target position in mm or degrees
* fr_mm_s - (target) speed of the move (mm/s)
* extruder - target extruder
* millimeters - the length of the movement, if known
* inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
*/
bool Planner::buffer_line(const float &rx, const float &ry, const float &rz, const float &e, const float &fr_mm_s, const uint8_t extruder, const float millimeters
#if ENABLED(SCARA_FEEDRATE_SCALING)
, const float &inv_duration
#endif
) {
float raw[XYZE] = { rx, ry, rz, e };
#if HAS_POSITION_MODIFIERS
apply_modifiers(raw);
#endif
#if IS_KINEMATIC
const float delta_mm_cart[] = {
rx - position_cart[X_AXIS],
ry - position_cart[Y_AXIS],
rz - position_cart[Z_AXIS]
#if ENABLED(JUNCTION_DEVIATION)
, e - position_cart[E_AXIS]
#endif
};
float mm = millimeters;
if (mm == 0.0)
mm = (delta_mm_cart[X_AXIS] != 0.0 || delta_mm_cart[Y_AXIS] != 0.0) ? SQRT(sq(delta_mm_cart[X_AXIS]) + sq(delta_mm_cart[Y_AXIS]) + sq(delta_mm_cart[Z_AXIS])) : ABS(delta_mm_cart[Z_AXIS]);
inverse_kinematics(raw);
#if ENABLED(SCARA_FEEDRATE_SCALING)
// For SCARA scale the feed rate from mm/s to degrees/s
// i.e., Complete the angular vector in the given time.
const float duration_recip = inv_duration ? inv_duration : fr_mm_s / mm,
feedrate = HYPOT(delta[A_AXIS] - position_float[A_AXIS], delta[B_AXIS] - position_float[B_AXIS]) * duration_recip;
#else
const float feedrate = fr_mm_s;
#endif
if (buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS]
#if ENABLED(JUNCTION_DEVIATION)
, delta_mm_cart
#endif
, feedrate, extruder, mm
)) {
position_cart[X_AXIS] = rx;
position_cart[Y_AXIS] = ry;
position_cart[Z_AXIS] = rz;
position_cart[E_AXIS] = e;
return true;
}
else
return false;
#else
return buffer_segment(raw, fr_mm_s, extruder, millimeters);
#endif
} // buffer_line()
/**
* Directly set the planner ABC position (and stepper positions)
* converting mm (or angles for SCARA) into steps.
*
* The provided ABC position is in machine units.
*/
void Planner::set_machine_position_mm(const float &a, const float &b, const float &c, const float &e) {
#if ENABLED(DISTINCT_E_FACTORS)
last_extruder = active_extruder;
#endif
position[A_AXIS] = LROUND(a * settings.axis_steps_per_mm[A_AXIS]);
position[B_AXIS] = LROUND(b * settings.axis_steps_per_mm[B_AXIS]);
position[C_AXIS] = LROUND(c * settings.axis_steps_per_mm[C_AXIS]);
position[E_AXIS] = LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(active_extruder)]);
#if HAS_POSITION_FLOAT
position_float[A_AXIS] = a;
position_float[B_AXIS] = b;
position_float[C_AXIS] = c;
position_float[E_AXIS] = e;
#endif
if (has_blocks_queued()) {
//previous_nominal_speed_sqr = 0.0; // Reset planner junction speeds. Assume start from rest.
//ZERO(previous_speed);
buffer_sync_block();
}
else
stepper.set_position(position[A_AXIS], position[B_AXIS], position[C_AXIS], position[E_AXIS]);
}
void Planner::set_position_mm(const float &rx, const float &ry, const float &rz, const float &e) {
float raw[XYZE] = { rx, ry, rz, e };
#if HAS_POSITION_MODIFIERS
apply_modifiers(raw
#if HAS_LEVELING
, true
#endif
);
#endif
#if IS_KINEMATIC
position_cart[X_AXIS] = rx;
position_cart[Y_AXIS] = ry;
position_cart[Z_AXIS] = rz;
position_cart[E_AXIS] = e;
inverse_kinematics(raw);
set_machine_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS]);
#else
set_machine_position_mm(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], raw[E_AXIS]);
#endif
}
/**
* Setters for planner position (also setting stepper position).
*/
void Planner::set_e_position_mm(const float &e) {
const uint8_t axis_index = E_AXIS_N(active_extruder);
#if ENABLED(DISTINCT_E_FACTORS)
last_extruder = active_extruder;
#endif
#if ENABLED(FWRETRACT)
float e_new = e - fwretract.current_retract[active_extruder];
#else
const float e_new = e;
#endif
position[E_AXIS] = LROUND(settings.axis_steps_per_mm[axis_index] * e_new);
#if HAS_POSITION_FLOAT
position_float[E_AXIS] = e_new;
#endif
#if IS_KINEMATIC
position_cart[E_AXIS] = e;
#endif
if (has_blocks_queued())
buffer_sync_block();
else
stepper.set_position(E_AXIS, position[E_AXIS]);
}
// Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
void Planner::reset_acceleration_rates() {
#if ENABLED(DISTINCT_E_FACTORS)
#define AXIS_CONDITION (i < E_AXIS || i == E_AXIS_N(active_extruder))
#else
#define AXIS_CONDITION true
#endif
uint32_t highest_rate = 1;
LOOP_XYZE_N(i) {
max_acceleration_steps_per_s2[i] = settings.max_acceleration_mm_per_s2[i] * settings.axis_steps_per_mm[i];
if (AXIS_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
}
cutoff_long = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
#if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
recalculate_max_e_jerk();
#endif
}
// Recalculate position, steps_to_mm if settings.axis_steps_per_mm changes!
void Planner::refresh_positioning() {
LOOP_XYZE_N(i) steps_to_mm[i] = 1.0f / settings.axis_steps_per_mm[i];
set_position_mm(current_position);
reset_acceleration_rates();
}
#if ENABLED(AUTOTEMP)
void Planner::autotemp_M104_M109() {
if ((autotemp_enabled = parser.seen('F'))) autotemp_factor = parser.value_float();
if (parser.seen('S')) autotemp_min = parser.value_celsius();
if (parser.seen('B')) autotemp_max = parser.value_celsius();
}
#endif
|
/*
Algoritmo para criação de uma MST (Árvore Geradora de Custo Mínimo), ou seja,
garante a conexão de todos os nós do grafo com o menor custo de arestas
* implementação quase igual a dijkstra
Izabella Melo ~imcm
imcm@cin.ufpe.br
*/
#include <bits/stdc++.h>
using namespace std;
#define NODES 10
#define INF 1e8
typedef pair<int, int> ii;
// pair<distância, vértice>
vector<ii> graph[NODES];
int D[NODES], visit[NODES];
// implementação da min heap
priority_queue<ii, vector<ii>, greater<ii> > min_heap;
void prim(int v){
D[v] = 0;
min_heap.push(ii(0, v));
while(!min_heap.empty()){
ii now = min_heap.top();
min_heap.pop();
visit[now.second] = 1;
for(int i = 0; i < graph[now.second].size(); i++){
ii next = graph[now.second][i];
if(visit[next.second] == 0){
// verifica se a aresta [now.second-next.second] possui peso menor que a anteriormente armazenada
if(D[next.second] > next.first){
D[next.second] = next.first;
min_heap.push(ii(D[next.second], next.second));
}
}
}
}
}
int main(){
for(int i = 0; i < SizeNodes; i++) // atribui infinito para todos os nós
D[i] = INF;
// chama a função a partir do que será a raiz da árvore
// prim(root);
return 0;
}
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill_assistant/browser/field_formatter.h"
#include "base/i18n/case_conversion.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/autofill_data_util.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill/core/browser/geo/state_names.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill_assistant/browser/generic_ui.pb.h"
#include "third_party/re2/src/re2/re2.h"
#include "third_party/re2/src/re2/stringpiece.h"
namespace autofill_assistant {
namespace field_formatter {
namespace {
// Regex to find placeholders of the form ${key}, where key is an arbitrary
// string that does not contain curly braces. The first capture group is for
// the prefix before the key, the second for the key itself.
const char kPlaceholderExtractor[] = R"re((.*?)\$\{([^{}]+)\})re";
template <typename T>
absl::optional<std::string> GetFieldValue(
const std::map<T, std::string>& mappings,
const T& key) {
auto it = mappings.find(key);
if (it == mappings.end()) {
return absl::nullopt;
}
return it->second;
}
std::map<Key, std::string> CreateFormGroupMappings(
const autofill::FormGroup& form_group,
const std::string& locale) {
std::map<Key, std::string> mappings;
autofill::ServerFieldTypeSet available_fields;
form_group.GetNonEmptyTypes(locale, &available_fields);
for (const auto field : available_fields) {
mappings.emplace(Key(field), base::UTF16ToUTF8(form_group.GetInfo(
autofill::AutofillType(field), locale)));
}
return mappings;
}
void GetNameAndAbbreviationViaAlternativeStateNameMap(
const std::string& country_code,
const std::u16string& state_from_profile,
std::u16string* name,
std::u16string* abbreviation) {
absl::optional<autofill::StateEntry> state_entry =
autofill::AlternativeStateNameMap::GetInstance()->GetEntry(
autofill::AlternativeStateNameMap::CountryCode(country_code),
autofill::AlternativeStateNameMap::StateName(state_from_profile));
if (!state_entry) {
// Name and abbreviation are already prefilled.
return;
}
if (state_entry->has_canonical_name() &&
!state_entry->canonical_name().empty()) {
std::u16string full = base::ASCIIToUTF16(state_entry->canonical_name());
std::u16string abbr;
size_t curr_min_abbr_size = INT_MAX;
for (const auto& it_abbr : state_entry->abbreviations()) {
if (!it_abbr.empty() && it_abbr.size() < curr_min_abbr_size) {
abbr = base::ASCIIToUTF16(it_abbr);
curr_min_abbr_size = it_abbr.size();
}
}
if (name) {
name->swap(full);
}
if (abbreviation) {
abbreviation->swap(abbr);
}
}
}
std::string ApplyChunkReplacement(
const google::protobuf::Map<std::string, std::string>& replacements,
const std::string& value) {
const auto& it = replacements.find(value);
if (it != replacements.end()) {
return it->second;
}
return value;
}
std::string GetMaybeQuotedChunk(const std::string& value, bool quote_meta) {
if (quote_meta) {
return re2::RE2::QuoteMeta(value);
}
return value;
}
} // namespace
Key::Key(int key) : int_key(key) {}
Key::Key(AutofillFormatProto::AutofillAssistantCustomField custom_field)
: int_key(static_cast<int>(custom_field)) {}
Key::Key(autofill::ServerFieldType autofill_field)
: int_key(static_cast<int>(autofill_field)) {}
Key::Key(std::string key) : string_key(key) {}
Key::~Key() = default;
Key::Key(const Key&) = default;
bool Key::operator<(const Key& other) const {
return std::make_tuple(this->int_key.value_or(0),
this->string_key.value_or(std::string())) <
std::make_tuple(other.int_key.value_or(0),
other.string_key.value_or(std::string()));
}
bool Key::operator==(const Key& other) const {
return !(*this < other) && !(other < *this);
}
absl::optional<std::string> FormatString(
const std::string& pattern,
const std::map<std::string, std::string>& mappings,
bool strict) {
if (pattern.empty()) {
return std::string();
}
std::string out;
re2::StringPiece input(pattern);
std::string prefix;
std::string key;
while (
re2::RE2::FindAndConsume(&input, kPlaceholderExtractor, &prefix, &key)) {
auto rewrite_value = GetFieldValue(mappings, key);
if (!rewrite_value.has_value()) {
if (strict) {
VLOG(2) << "No value for " << key << " in " << pattern;
return absl::nullopt;
}
// Leave placeholder unchanged.
rewrite_value = "${" + key + "}";
}
out = out + prefix + *rewrite_value;
}
// Append remaining unmatched suffix (if any).
out = out + input.ToString();
return out;
}
ClientStatus FormatExpression(const ValueExpression& value_expression,
const std::map<Key, std::string>& mappings,
bool quote_meta,
std::string* out_value) {
out_value->clear();
for (const auto& chunk : value_expression.chunk()) {
std::string chunk_value;
switch (chunk.chunk_case()) {
case ValueExpression::Chunk::kText:
chunk_value = chunk.text();
break;
case ValueExpression::Chunk::kKey: {
auto rewrite_value = GetFieldValue(mappings, Key(chunk.key()));
if (!rewrite_value.has_value()) {
return ClientStatus(AUTOFILL_INFO_NOT_AVAILABLE);
}
chunk_value = GetMaybeQuotedChunk(*rewrite_value, quote_meta);
break;
}
case ValueExpression::Chunk::kMemoryKey: {
auto rewrite_value = GetFieldValue(mappings, Key(chunk.memory_key()));
if (!rewrite_value.has_value()) {
return ClientStatus(CLIENT_MEMORY_KEY_NOT_AVAILABLE);
}
chunk_value = GetMaybeQuotedChunk(*rewrite_value, quote_meta);
break;
}
case ValueExpression::Chunk::CHUNK_NOT_SET:
return ClientStatus(INVALID_ACTION);
}
out_value->append(ApplyChunkReplacement(chunk.replacements(), chunk_value));
}
return OkClientStatus();
}
std::string GetHumanReadableValueExpression(
const ValueExpression& value_expression) {
std::string out;
for (const auto& chunk : value_expression.chunk()) {
switch (chunk.chunk_case()) {
case ValueExpression::Chunk::kText:
out += chunk.text();
break;
case ValueExpression::Chunk::kKey:
out += base::StrCat({"${", base::NumberToString(chunk.key()), "}"});
break;
case ValueExpression::Chunk::kMemoryKey:
out += base::StrCat({"${", chunk.memory_key(), "}"});
break;
case ValueExpression::Chunk::CHUNK_NOT_SET:
out += "<CHUNK_NOT_SET>";
break;
}
}
return out;
}
template <>
std::map<Key, std::string> CreateAutofillMappings<autofill::AutofillProfile>(
const autofill::AutofillProfile& profile,
const std::string& locale) {
auto mappings = CreateFormGroupMappings(profile, locale);
std::string country_code =
base::UTF16ToUTF8(profile.GetRawInfo(autofill::ADDRESS_HOME_COUNTRY));
if (!country_code.empty()) {
mappings.emplace(Key(AutofillFormatProto::ADDRESS_HOME_COUNTRY_CODE),
country_code);
}
auto state = profile.GetInfo(
autofill::AutofillType(autofill::ADDRESS_HOME_STATE), locale);
if (!state.empty()) {
std::u16string full_name;
std::u16string abbreviation;
autofill::state_names::GetNameAndAbbreviation(state, &full_name,
&abbreviation);
DCHECK(!full_name.empty());
full_name = full_name.length() > 1
? base::StrCat({base::i18n::ToUpper(full_name.substr(0, 1)),
full_name.substr(1)})
: base::i18n::ToUpper(full_name);
if (abbreviation.empty() && !country_code.empty() &&
base::FeatureList::IsEnabled(
autofill::features::kAutofillUseAlternativeStateNameMap)) {
GetNameAndAbbreviationViaAlternativeStateNameMap(
country_code, state, &full_name, &abbreviation);
}
mappings.emplace(Key(AutofillFormatProto::ADDRESS_HOME_STATE_NAME),
base::UTF16ToUTF8(full_name));
if (abbreviation.empty()) {
mappings.erase(Key(autofill::ADDRESS_HOME_STATE));
} else {
mappings[Key(autofill::ADDRESS_HOME_STATE)] =
base::UTF16ToUTF8(base::i18n::ToUpper(abbreviation));
}
}
return mappings;
}
template <>
std::map<Key, std::string> CreateAutofillMappings<autofill::CreditCard>(
const autofill::CreditCard& credit_card,
const std::string& locale) {
auto mappings = CreateFormGroupMappings(credit_card, locale);
auto network = std::string(
autofill::data_util::GetPaymentRequestData(credit_card.network())
.basic_card_issuer_network);
if (!network.empty()) {
mappings.emplace(Key(AutofillFormatProto::CREDIT_CARD_NETWORK), network);
}
auto network_for_display = base::UTF16ToUTF8(credit_card.NetworkForDisplay());
if (!network_for_display.empty()) {
mappings.emplace(Key(AutofillFormatProto::CREDIT_CARD_NETWORK_FOR_DISPLAY),
network_for_display);
}
auto last_four_digits = base::UTF16ToUTF8(credit_card.LastFourDigits());
if (!last_four_digits.empty()) {
mappings.emplace(
Key(AutofillFormatProto::CREDIT_CARD_NUMBER_LAST_FOUR_DIGITS),
last_four_digits);
}
int month;
if (base::StringToInt(
credit_card.GetInfo(autofill::CREDIT_CARD_EXP_MONTH, locale),
&month)) {
mappings.emplace(Key(AutofillFormatProto::CREDIT_CARD_NON_PADDED_EXP_MONTH),
base::NumberToString(month));
}
return mappings;
}
} // namespace field_formatter
std::ostream& operator<<(std::ostream& out,
const ValueExpression& value_expression) {
return out << field_formatter::GetHumanReadableValueExpression(
value_expression);
}
} // namespace autofill_assistant
|
#include <utility>
#include "input_handler.hh"
#include "buffer_manager.hh"
#include "buffer_utils.hh"
#include "command_manager.hh"
#include "client.hh"
#include "event_manager.hh"
#include "face_registry.hh"
#include "insert_completer.hh"
#include "normal.hh"
#include "regex.hh"
#include "register_manager.hh"
#include "hash_map.hh"
#include "user_interface.hh"
#include "utf8.hh"
#include "window.hh"
namespace Kakoune
{
class InputMode : public RefCountable
{
public:
InputMode(InputHandler& input_handler) : m_input_handler(input_handler) {}
~InputMode() override = default;
InputMode(const InputMode&) = delete;
InputMode& operator=(const InputMode&) = delete;
void handle_key(Key key) { RefPtr<InputMode> keep_alive{this}; on_key(key); }
virtual void on_enabled() {}
virtual void on_disabled(bool temporary) {}
bool enabled() const { return &m_input_handler.current_mode() == this; }
Context& context() const { return m_input_handler.context(); }
virtual DisplayLine mode_line() const = 0;
virtual KeymapMode keymap_mode() const = 0;
virtual StringView name() const = 0;
virtual std::pair<CursorMode, DisplayCoord> get_cursor_info() const
{
const auto cursor = context().selections().main().cursor();
auto coord = context().window().display_position(cursor).value_or(DisplayCoord{});
return {CursorMode::Buffer, coord};
}
using Insertion = InputHandler::Insertion;
Insertion& last_insert() { return m_input_handler.m_last_insert; }
protected:
virtual void on_key(Key key) = 0;
void push_mode(InputMode* new_mode)
{
m_input_handler.push_mode(new_mode);
}
void pop_mode()
{
m_input_handler.pop_mode(this);
}
private:
InputHandler& m_input_handler;
};
namespace InputModes
{
std::chrono::milliseconds get_idle_timeout(const Context& context)
{
return std::chrono::milliseconds{context.options()["idle_timeout"].get<int>()};
}
std::chrono::milliseconds get_fs_check_timeout(const Context& context)
{
return std::chrono::milliseconds{context.options()["fs_check_timeout"].get<int>()};
}
struct MouseHandler
{
bool handle_key(Key key, Context& context)
{
if (not context.has_window())
return false;
Buffer& buffer = context.buffer();
BufferCoord cursor;
auto& selections = context.selections();
switch ((Key::Modifiers)(key.modifiers & Key::Modifiers::MouseEvent))
{
case Key::Modifiers::MousePress:
m_dragging = true;
m_anchor = context.window().buffer_coord(key.coord());
if (not (key.modifiers & Key::Modifiers::Control))
context.selections_write_only() = { buffer, m_anchor};
else
{
size_t main = selections.size();
selections.push_back({m_anchor});
selections.set_main_index(main);
selections.sort_and_merge_overlapping();
}
return true;
case Key::Modifiers::MouseRelease:
if (not m_dragging)
return true;
m_dragging = false;
cursor = context.window().buffer_coord(key.coord());
selections.main() = {buffer.clamp(m_anchor), cursor};
selections.sort_and_merge_overlapping();
return true;
case Key::Modifiers::MousePos:
if (not m_dragging)
return true;
cursor = context.window().buffer_coord(key.coord());
selections.main() = {buffer.clamp(m_anchor), cursor};
selections.sort_and_merge_overlapping();
return true;
case Key::Modifiers::MouseWheelDown:
m_dragging = false;
scroll_window(context, 3);
return true;
case Key::Modifiers::MouseWheelUp:
m_dragging = false;
scroll_window(context, -3);
return true;
default: return false;
}
}
private:
bool m_dragging = false;
BufferCoord m_anchor;
};
constexpr StringView register_doc =
"Special registers:\n"
"[0-9]: selections capture group\n"
"%: buffer name\n"
".: selection contents\n"
"#: selection index\n"
"_: null register\n"
"\": default yank/paste register\n"
"@: default macro register\n"
"/: default search register\n"
"^: default mark register\n"
"|: default shell command register\n"
":: last entered command\n";
class Normal : public InputMode
{
public:
Normal(InputHandler& input_handler, bool single_command = false)
: InputMode(input_handler),
m_idle_timer{TimePoint::max(),
context().flags() & Context::Flags::Transient ?
Timer::Callback{} : [this](Timer&) {
context().hooks().run_hook("NormalIdle", "", context());
}},
m_fs_check_timer{TimePoint::max(),
context().flags() & Context::Flags::Transient ?
Timer::Callback{} : Timer::Callback{[this](Timer& timer) {
if (context().has_client())
context().client().check_if_buffer_needs_reloading();
timer.set_next_date(Clock::now() + get_fs_check_timeout(context()));
}}},
m_single_command(single_command)
{}
void on_enabled() override
{
if (not (context().flags() & Context::Flags::Transient))
{
if (context().has_client())
context().client().check_if_buffer_needs_reloading();
m_fs_check_timer.set_next_date(Clock::now() + get_fs_check_timeout(context()));
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
if (m_hooks_disabled and not m_in_on_key)
{
context().hooks_disabled().unset();
m_hooks_disabled = false;
}
context().hooks().run_hook("NormalBegin", "", context());
}
void on_disabled(bool temporary) override
{
m_idle_timer.set_next_date(TimePoint::max());
m_fs_check_timer.set_next_date(TimePoint::max());
if (not temporary and m_hooks_disabled)
{
context().hooks_disabled().unset();
m_hooks_disabled = false;
}
context().hooks().run_hook("NormalEnd", "", context());
}
void on_key(Key key) override
{
ScopedSetBool set_in_on_key{m_in_on_key};
// Hack to parse keys sent by terminals using the 8th bit to mark the
// meta key. In normal mode, give priority to a potential alt-key than
// the accentuated character.
if (not (key.modifiers & Key::Modifiers::MouseEvent) and
key.key >= 127 and key.key < 256)
{
key.modifiers |= Key::Modifiers::Alt;
key.key &= 0x7f;
}
bool do_restore_hooks = false;
auto restore_hooks = on_scope_end([&, this]{
if (m_hooks_disabled and enabled() and do_restore_hooks)
{
context().hooks_disabled().unset();
m_hooks_disabled = false;
}
});
const bool transient = context().flags() & Context::Flags::Transient;
auto cp = key.codepoint();
if (m_mouse_handler.handle_key(key, context()))
{
context().print_status({});
if (context().has_client())
context().client().info_hide();
if (not transient)
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
else if (cp and isdigit(*cp))
{
long long new_val = (long long)m_params.count * 10 + *cp - '0';
if (new_val > std::numeric_limits<int>::max())
context().print_status({ "parameter overflowed", context().faces()["Error"] });
else
m_params.count = new_val;
}
else if (key == Key::Backspace)
m_params.count /= 10;
else if (key == '\\')
{
if (not m_hooks_disabled)
{
m_hooks_disabled = true;
context().hooks_disabled().set();
}
}
else if (key == '"')
{
on_next_key_with_autoinfo(context(), KeymapMode::None,
[this](Key key, Context& context) {
auto cp = key.codepoint();
if (not cp or key == Key::Escape)
return;
if (*cp <= 127)
m_params.reg = *cp;
else
context.print_status(
{ format("invalid register '{}'", *cp),
context.faces()["Error"] });
}, "enter target register", register_doc);
}
else
{
// Preserve hooks disabled for the whole execution prior to pop_mode
ScopedSetBool disable_hooks{context().hooks_disabled(),
m_single_command and m_hooks_disabled};
if (m_single_command)
pop_mode();
context().print_status({});
if (context().has_client())
context().client().info_hide();
do_restore_hooks = true;
if (auto command = get_normal_command(key))
{
auto autoinfo = context().options()["autoinfo"].get<AutoInfo>();
if (autoinfo & AutoInfo::Normal and context().has_client())
context().client().info_show(key_to_str(key), command->docstring.str(),
{}, InfoStyle::Prompt);
// reset m_params now to be reentrant
NormalParams params = m_params;
m_params = { 0, 0 };
command->func(context(), params);
}
}
context().hooks().run_hook("NormalKey", key_to_str(key), context());
if (enabled() and not transient) // The hook might have changed mode
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
DisplayLine mode_line() const override
{
AtomList atoms;
auto num_sel = context().selections().size();
auto main_index = context().selections().main_index();
if (num_sel == 1)
atoms.emplace_back(format("{} sel", num_sel), context().faces()["StatusLineInfo"]);
else
atoms.emplace_back(format("{} sels ({})", num_sel, main_index + 1), context().faces()["StatusLineInfo"]);
if (m_params.count != 0)
{
atoms.emplace_back(" param=", context().faces()["StatusLineInfo"]);
atoms.emplace_back(to_string(m_params.count), context().faces()["StatusLineValue"]);
}
if (m_params.reg)
{
atoms.emplace_back(" reg=", context().faces()["StatusLineInfo"]);
atoms.emplace_back(StringView(m_params.reg).str(), context().faces()["StatusLineValue"]);
}
return atoms;
}
KeymapMode keymap_mode() const override { return KeymapMode::Normal; }
StringView name() const override { return "normal"; }
private:
friend struct InputHandler::ScopedForceNormal;
NormalParams m_params = { 0, 0 };
bool m_hooks_disabled = false;
NestedBool m_in_on_key;
Timer m_idle_timer;
Timer m_fs_check_timer;
MouseHandler m_mouse_handler;
const bool m_single_command;
};
template<WordType word_type>
void to_next_word_begin(CharCount& pos, StringView line)
{
const CharCount len = line.char_length();
if (pos == len)
return;
if (word_type == Word and is_punctuation(line[pos]))
{
while (pos != len and is_punctuation(line[pos]))
++pos;
}
else if (is_word<word_type>(line[pos]))
{
while (pos != len and is_word<word_type>(line[pos]))
++pos;
}
while (pos != len and is_horizontal_blank(line[pos]))
++pos;
}
template<WordType word_type>
void to_next_word_end(CharCount& pos, StringView line)
{
const CharCount len = line.char_length();
if (pos + 1 >= len)
return;
++pos;
while (pos != len and is_horizontal_blank(line[pos]))
++pos;
if (word_type == Word and is_punctuation(line[pos]))
{
while (pos != len and is_punctuation(line[pos]))
++pos;
}
else if (is_word<word_type>(line[pos]))
{
while (pos != len and is_word<word_type>(line[pos]))
++pos;
}
--pos;
}
template<WordType word_type>
void to_prev_word_begin(CharCount& pos, StringView line)
{
if (pos == 0_char)
return;
--pos;
while (pos != 0_char and is_horizontal_blank(line[pos]))
--pos;
if (word_type == Word and is_punctuation(line[pos]))
{
while (pos != 0_char and is_punctuation(line[pos]))
--pos;
if (!is_punctuation(line[pos]))
++pos;
}
else if (is_word<word_type>(line[pos]))
{
while (pos != 0_char and is_word<word_type>(line[pos]))
--pos;
if (!is_word<word_type>(line[pos]))
++pos;
}
}
class LineEditor
{
public:
LineEditor(const FaceRegistry& faces) : m_faces{faces} {}
void handle_key(Key key)
{
if (key == Key::Left or key == alt('h'))
{
if (m_cursor_pos > 0)
--m_cursor_pos;
}
else if (key == Key::Right or key == alt('l'))
{
if (m_cursor_pos < m_line.char_length())
++m_cursor_pos;
}
else if (key == Key::Home)
m_cursor_pos = 0;
else if (key == Key::End)
m_cursor_pos = m_line.char_length();
else if (key == Key::Backspace or key == alt('x'))
{
if (m_cursor_pos != 0)
{
m_line = m_line.substr(0_char, m_cursor_pos - 1)
+ m_line.substr(m_cursor_pos);
--m_cursor_pos;
}
}
else if (key == Key::Delete or key == alt('d'))
{
if (m_cursor_pos != m_line.char_length())
m_line = m_line.substr(0, m_cursor_pos)
+ m_line.substr(m_cursor_pos+1);
}
else if (key == ctrl('w'))
to_next_word_begin<Word>(m_cursor_pos, m_line);
else if (key == ctrl(alt('w')))
to_next_word_begin<WORD>(m_cursor_pos, m_line);
else if (key == ctrl('b'))
to_prev_word_begin<Word>(m_cursor_pos, m_line);
else if (key == ctrl(alt('b')))
to_prev_word_begin<WORD>(m_cursor_pos, m_line);
else if (key == ctrl('e'))
to_next_word_end<Word>(m_cursor_pos, m_line);
else if (key == ctrl(alt('e')))
to_next_word_end<WORD>(m_cursor_pos, m_line);
else if (key == ctrl('k'))
m_line = m_line.substr(0_char, m_cursor_pos).str();
else if (key == ctrl('u'))
{
m_line = m_line.substr(m_cursor_pos).str();
m_cursor_pos = 0;
}
else if (auto cp = key.codepoint())
insert(*cp);
}
void insert(Codepoint cp)
{
m_line = m_line.substr(0, m_cursor_pos) + String{cp}
+ m_line.substr(m_cursor_pos);
++m_cursor_pos;
}
void insert(StringView str)
{
insert_from(m_cursor_pos, str);
}
void insert_from(CharCount start, StringView str)
{
kak_assert(start <= m_cursor_pos);
m_line = m_line.substr(0, start) + str
+ m_line.substr(m_cursor_pos);
m_cursor_pos = start + str.char_length();
}
void reset(String line, StringView empty_text)
{
m_line = std::move(line);
m_empty_text = empty_text;
m_cursor_pos = m_line.char_length();
m_display_pos = 0;
}
const String& line() const { return m_line; }
CharCount cursor_pos() const { return m_cursor_pos; }
ColumnCount cursor_display_column() const
{
return m_line.substr(m_display_pos, m_cursor_pos).column_length();
}
DisplayLine build_display_line(ColumnCount in_width)
{
CharCount width = (int)in_width; // Todo: proper handling of char/column
kak_assert(m_cursor_pos <= m_line.char_length());
if (m_cursor_pos < m_display_pos)
m_display_pos = m_cursor_pos;
if (m_cursor_pos >= m_display_pos + width)
m_display_pos = m_cursor_pos + 1 - width;
const bool empty = m_line.empty();
StringView str = empty ? m_empty_text : m_line;
const Face line_face = m_faces[empty ? "StatusLineInfo" : "StatusLine"];
const Face cursor_face = m_faces["StatusCursor"];
if (m_cursor_pos == str.char_length())
return DisplayLine{{ { fix_atom_text(str.substr(m_display_pos, width-1)), line_face },
{ " "_str, cursor_face} } };
else
return DisplayLine({ { fix_atom_text(str.substr(m_display_pos, m_cursor_pos - m_display_pos)), line_face },
{ fix_atom_text(str.substr(m_cursor_pos,1)), cursor_face },
{ fix_atom_text(str.substr(m_cursor_pos+1, width - m_cursor_pos + m_display_pos - 1)), line_face } });
}
private:
CharCount m_cursor_pos = 0;
CharCount m_display_pos = 0;
String m_line;
StringView m_empty_text = {};
const FaceRegistry& m_faces;
};
class Menu : public InputMode
{
public:
Menu(InputHandler& input_handler, Vector<DisplayLine> choices,
MenuCallback callback)
: InputMode(input_handler),
m_callback(std::move(callback)), m_choices(choices.begin(), choices.end()),
m_selected(m_choices.begin()),
m_filter_editor{context().faces()}
{
if (not context().has_client())
return;
context().client().menu_show(std::move(choices), {}, MenuStyle::Prompt);
context().client().menu_select(0);
}
void on_key(Key key) override
{
auto match_filter = [this](const DisplayLine& choice) {
for (auto& atom : choice)
{
const auto& contents = atom.content();
if (regex_match(contents.begin(), contents.end(), m_filter))
return true;
}
return false;
};
if (key == Key::Return)
{
if (context().has_client())
context().client().menu_hide();
context().print_status(DisplayLine{});
// Maintain hooks disabled in callback if they were before pop_mode
ScopedSetBool disable_hooks(context().hooks_disabled(),
context().hooks_disabled());
pop_mode();
int selected = m_selected - m_choices.begin();
m_callback(selected, MenuEvent::Validate, context());
return;
}
else if (key == Key::Escape or key == ctrl('c'))
{
if (m_edit_filter)
{
m_edit_filter = false;
m_filter = Regex{".*"};
m_filter_editor.reset("", "");
context().print_status(DisplayLine{});
}
else
{
if (context().has_client())
context().client().menu_hide();
// Maintain hooks disabled in callback if they were before pop_mode
ScopedSetBool disable_hooks(context().hooks_disabled(),
context().hooks_disabled());
pop_mode();
int selected = m_selected - m_choices.begin();
m_callback(selected, MenuEvent::Abort, context());
}
}
else if (key == Key::Down or key == Key::Tab or
key == ctrl('n') or (not m_edit_filter and key == 'j'))
{
auto it = std::find_if(m_selected+1, m_choices.end(), match_filter);
if (it == m_choices.end())
it = std::find_if(m_choices.begin(), m_selected, match_filter);
select(it);
}
else if (key == Key::Up or key == shift(Key::Tab) or
key == ctrl('p') or (not m_edit_filter and key == 'k'))
{
ChoiceList::const_reverse_iterator selected(m_selected+1);
auto it = std::find_if(selected+1, m_choices.rend(), match_filter);
if (it == m_choices.rend())
it = std::find_if(m_choices.rbegin(), selected, match_filter);
select(it.base()-1);
}
else if (key == '/' and not m_edit_filter)
{
m_edit_filter = true;
}
else if (m_edit_filter)
{
m_filter_editor.handle_key(key);
auto search = ".*" + m_filter_editor.line() + ".*";
m_filter = Regex{search};
auto it = std::find_if(m_selected, m_choices.end(), match_filter);
if (it == m_choices.end())
it = std::find_if(m_choices.begin(), m_selected, match_filter);
select(it);
}
if (m_edit_filter and context().has_client())
{
auto prompt = "filter:"_str;
auto width = context().client().dimensions().column - prompt.column_length();
auto display_line = m_filter_editor.build_display_line(width);
display_line.insert(display_line.begin(), { prompt, context().faces()["Prompt"] });
context().print_status(display_line);
}
}
DisplayLine mode_line() const override
{
return { "menu", context().faces()["StatusLineMode"] };
}
KeymapMode keymap_mode() const override { return KeymapMode::Menu; }
StringView name() const override { return "menu"; }
private:
MenuCallback m_callback;
using ChoiceList = Vector<DisplayLine>;
const ChoiceList m_choices;
ChoiceList::const_iterator m_selected;
void select(ChoiceList::const_iterator it)
{
m_selected = it;
int selected = m_selected - m_choices.begin();
if (context().has_client())
context().client().menu_select(selected);
m_callback(selected, MenuEvent::Select, context());
}
Regex m_filter = Regex{".*"};
bool m_edit_filter = false;
LineEditor m_filter_editor;
};
static Optional<Codepoint> get_raw_codepoint(Key key)
{
if (auto cp = key.codepoint())
return cp;
else if (key.modifiers == Key::Modifiers::Control and
((key.key >= '@' and key.key <= '_') or
(key.key >= 'a' and key.key <= 'z')))
return {(Codepoint)(to_upper((char)key.key) - '@')};
return {};
}
class Prompt : public InputMode
{
public:
Prompt(InputHandler& input_handler, StringView prompt,
String initstr, String emptystr, Face face, PromptFlags flags,
Completer completer, PromptCallback callback)
: InputMode(input_handler), m_prompt(prompt.str()), m_prompt_face(face),
m_empty_text{std::move(emptystr)},
m_flags(flags), m_completer(std::move(completer)), m_callback(std::move(callback)),
m_autoshowcompl{context().options()["autoshowcompl"].get<bool>()},
m_idle_timer{TimePoint::max(), context().flags() & Context::Flags::Transient ?
Timer::Callback{} : [this](Timer&) {
if (m_autoshowcompl and m_refresh_completion_pending)
refresh_completions(CompletionFlags::Fast);
if (m_line_changed)
{
m_callback(m_line_editor.line(), PromptEvent::Change, context());
m_line_changed = false;
}
context().hooks().run_hook("PromptIdle", "", context());
}},
m_line_editor{context().faces()}
{
m_history_it = ms_history[m_prompt].end();
m_line_editor.reset(std::move(initstr), m_empty_text);
}
void on_key(Key key) override
{
History& history = ms_history[m_prompt];
const String& line = m_line_editor.line();
if (key == Key::Return)
{
if (not context().history_disabled())
history_push(history, line);
context().print_status(DisplayLine{});
if (context().has_client())
context().client().menu_hide();
// Maintain hooks disabled in callback if they were before pop_mode
ScopedSetBool disable_hooks(context().hooks_disabled(),
context().hooks_disabled());
pop_mode();
// call callback after pop_mode so that callback
// may change the mode
m_callback(line, PromptEvent::Validate, context());
return;
}
else if (key == Key::Escape or key == ctrl('c'))
{
if (not context().history_disabled())
history_push(history, line);
context().print_status(DisplayLine{});
if (context().has_client())
context().client().menu_hide();
// Maintain hooks disabled in callback if they were before pop_mode
ScopedSetBool disable_hooks(context().hooks_disabled(),
context().hooks_disabled());
pop_mode();
m_callback(line, PromptEvent::Abort, context());
return;
}
else if (key == ctrl('r'))
{
on_next_key_with_autoinfo(context(), KeymapMode::None,
[this](Key key, Context&) {
auto cp = key.codepoint();
if (not cp or key == Key::Escape)
return;
StringView reg = context().main_sel_register_value(String{*cp});
m_line_editor.insert(reg);
display();
m_line_changed = true;
m_refresh_completion_pending = true;
}, "enter register name", register_doc);
display();
return;
}
else if (key == ctrl('v'))
{
on_next_key_with_autoinfo(context(), KeymapMode::None,
[this](Key key, Context&) {
if (auto cp = get_raw_codepoint(key))
{
m_line_editor.insert(*cp);
display();
m_line_changed = true;
m_refresh_completion_pending = true;
}
}, "raw insert", "enter key to insert");
display();
return;
}
else if (key == Key::Up or key == ctrl('p'))
{
if (m_history_it != history.begin())
{
if (m_history_it == history.end())
m_prefix = line;
auto it = m_history_it;
// search for the previous history entry matching typed prefix
do
{
--it;
if (prefix_match(*it, m_prefix))
{
m_history_it = it;
m_line_editor.reset(*it, m_empty_text);
break;
}
} while (it != history.begin());
clear_completions();
m_refresh_completion_pending = true;
}
}
else if (key == Key::Down or key == ctrl('n')) // next
{
if (m_history_it != history.end())
{
// search for the next history entry matching typed prefix
++m_history_it;
while (m_history_it != history.end() and
not prefix_match(*m_history_it, m_prefix))
++m_history_it;
if (m_history_it != history.end())
m_line_editor.reset(*m_history_it, m_empty_text);
else
m_line_editor.reset(m_prefix, m_empty_text);
clear_completions();
m_refresh_completion_pending = true;
}
}
else if (key == Key::Tab or key == shift(Key::Tab) or key.modifiers == Key::Modifiers::MenuSelect) // completion
{
CandidateList& candidates = m_completions.candidates;
// first try, we need to ask our completer for completions
if (candidates.empty())
{
refresh_completions(CompletionFlags::None);
if ((not m_prefix_in_completions and candidates.size() > 1) or
candidates.size() > 2)
return;
}
if (candidates.empty())
return;
const bool reverse = (key == shift(Key::Tab));
if (key.modifiers == Key::Modifiers::MenuSelect)
m_current_completion = clamp<int>(key.key, 0, candidates.size() - 1);
else if (not reverse and ++m_current_completion >= candidates.size())
m_current_completion = 0;
else if (reverse and --m_current_completion < 0)
m_current_completion = candidates.size()-1;
const String& completion = candidates[m_current_completion];
if (context().has_client())
context().client().menu_select(m_current_completion);
m_line_editor.insert_from(line.char_count_to(m_completions.start),
completion);
// when we have only one completion candidate, make next tab complete
// from the new content.
if (candidates.size() == 1 or
(m_prefix_in_completions and candidates.size() == 2))
{
m_current_completion = -1;
candidates.clear();
m_refresh_completion_pending = true;
}
}
else if (key == ctrl('o'))
{
m_autoshowcompl = false;
clear_completions();
if (context().has_client())
context().client().menu_hide();
}
else if (key == alt('!'))
{
try
{
m_line_editor.reset(expand(m_line_editor.line(), context()), m_empty_text);
}
catch (std::runtime_error& error)
{
context().print_status({error.what(), context().faces()["Error"]});
return;
}
}
else
{
m_line_editor.handle_key(key);
clear_completions();
m_refresh_completion_pending = true;
}
display();
m_line_changed = true;
if (enabled() and not (context().flags() & Context::Flags::Transient)) // The callback might have disabled us
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
void set_prompt_face(Face face)
{
if (face != m_prompt_face)
{
m_prompt_face = face;
display();
}
}
DisplayLine mode_line() const override
{
return { "prompt", context().faces()["StatusLineMode"] };
}
KeymapMode keymap_mode() const override { return KeymapMode::Prompt; }
StringView name() const override { return "prompt"; }
std::pair<CursorMode, DisplayCoord> get_cursor_info() const override
{
DisplayCoord coord{0_line, m_prompt.column_length() + m_line_editor.cursor_display_column()};
return { CursorMode::Prompt, coord };
}
private:
void refresh_completions(CompletionFlags flags)
{
try
{
m_refresh_completion_pending = false;
if (not m_completer)
return;
m_current_completion = -1;
const String& line = m_line_editor.line();
m_completions = m_completer(context(), flags, line,
line.byte_count_to(m_line_editor.cursor_pos()));
if (context().has_client())
{
if (m_completions.candidates.empty())
return context().client().menu_hide();
Vector<DisplayLine> items;
for (auto& candidate : m_completions.candidates)
items.push_back({ candidate, {} });
context().client().menu_show(items, {}, MenuStyle::Prompt);
auto prefix = line.substr(m_completions.start, m_completions.end - m_completions.start);
if (not contains(m_completions.candidates, prefix))
{
m_completions.candidates.push_back(prefix.str());
m_prefix_in_completions = true;
}
else
m_prefix_in_completions = false;
}
} catch (runtime_error&) {}
}
void clear_completions()
{
m_current_completion = -1;
m_completions.candidates.clear();
}
void display()
{
if (not context().has_client())
return;
auto width = context().client().dimensions().column - m_prompt.column_length();
DisplayLine display_line;
if (not (m_flags & PromptFlags::Password))
display_line = m_line_editor.build_display_line(width);
display_line.insert(display_line.begin(), { m_prompt, m_prompt_face });
context().print_status(display_line);
}
void on_enabled() override
{
display();
m_line_changed = true;
if (not (context().flags() & Context::Flags::Transient))
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
void on_disabled(bool) override
{
context().print_status({});
m_idle_timer.set_next_date(TimePoint::max());
if (context().has_client())
context().client().menu_hide();
}
PromptCallback m_callback;
Completer m_completer;
const String m_prompt;
Face m_prompt_face;
Completions m_completions;
int m_current_completion = -1;
bool m_prefix_in_completions = false;
String m_prefix;
String m_empty_text;
LineEditor m_line_editor;
bool m_line_changed = false;
PromptFlags m_flags;
bool m_autoshowcompl;
bool m_refresh_completion_pending = true;
Timer m_idle_timer;
using History = Vector<String, MemoryDomain::History>;
static HashMap<String, History, MemoryDomain::History> ms_history;
History::iterator m_history_it;
void history_push(History& history, StringView entry)
{
if (entry.empty() or
(m_flags & PromptFlags::DropHistoryEntriesWithBlankPrefix and
is_horizontal_blank(entry[0_byte])))
return;
history.erase(std::remove(history.begin(), history.end(), entry),
history.end());
history.push_back(entry.str());
}
};
HashMap<String, Prompt::History, MemoryDomain::History> Prompt::ms_history;
class NextKey : public InputMode
{
public:
NextKey(InputHandler& input_handler, KeymapMode keymap_mode, KeyCallback callback)
: InputMode(input_handler), m_keymap_mode(keymap_mode), m_callback(std::move(callback)) {}
void on_key(Key key) override
{
// maintain hooks disabled in the callback if they were before pop_mode
ScopedSetBool disable_hooks(context().hooks_disabled(),
context().hooks_disabled());
pop_mode();
m_callback(key, context());
}
DisplayLine mode_line() const override
{
return { "enter key", context().faces()["StatusLineMode"] };
}
KeymapMode keymap_mode() const override { return m_keymap_mode; }
StringView name() const override { return "next-key"; }
private:
KeyCallback m_callback;
KeymapMode m_keymap_mode;
};
class Insert : public InputMode
{
public:
Insert(InputHandler& input_handler, InsertMode mode, int count)
: InputMode(input_handler),
m_restore_cursor(mode == InsertMode::Append),
m_edition(context()),
m_completer(context()),
m_autoshowcompl{context().options()["autoshowcompl"].get<bool>()},
m_disable_hooks{context().hooks_disabled(), context().hooks_disabled()},
m_idle_timer{TimePoint::max(), context().flags() & Context::Flags::Transient ?
Timer::Callback{} : [this](Timer&) {
if (m_autoshowcompl)
m_completer.update();
context().hooks().run_hook("InsertIdle", "", context());
}}
{
context().buffer().throw_if_read_only();
last_insert().recording.set();
last_insert().mode = mode;
last_insert().keys.clear();
last_insert().disable_hooks = context().hooks_disabled();
last_insert().count = count;
context().hooks().run_hook("InsertBegin", "", context());
prepare(mode, count);
}
void on_enabled() override
{
if (not (context().flags() & Context::Flags::Transient))
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
void on_disabled(bool temporary) override
{
m_idle_timer.set_next_date(TimePoint::max());
if (not temporary)
{
last_insert().recording.unset();
auto& selections = context().selections();
if (m_restore_cursor)
{
for (auto& sel : selections)
{
if (sel.cursor() > sel.anchor() and sel.cursor().column > 0)
sel.cursor() = context().buffer().char_prev(sel.cursor());
}
}
}
}
void on_key(Key key) override
{
auto& buffer = context().buffer();
const bool transient = context().flags() & Context::Flags::Transient;
bool update_completions = true;
bool moved = false;
if (m_mouse_handler.handle_key(key, context()))
{
if (not transient)
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
else if (key == Key::Escape or key == ctrl('c'))
{
if (m_in_end)
throw runtime_error("asked to exit insert mode while running InsertEnd hook");
m_in_end = true;
context().hooks().run_hook("InsertEnd", "", context());
m_completer.reset();
pop_mode();
}
else if (key == Key::Backspace)
{
Vector<Selection> sels;
for (auto& sel : context().selections())
{
if (sel.cursor() == BufferCoord{0,0})
continue;
auto pos = sel.cursor();
sels.emplace_back(buffer.char_prev(pos));
}
auto& main = context().selections().main();
String main_char;
if (main.cursor() != BufferCoord{0, 0})
main_char = buffer.string(buffer.char_prev(main.cursor()),
main.cursor());
if (not sels.empty())
SelectionList{buffer, std::move(sels)}.erase();
if (not main_char.empty())
context().hooks().run_hook("InsertDelete", main_char, context());
}
else if (key == Key::Delete)
{
Vector<Selection> sels;
for (auto& sel : context().selections())
sels.emplace_back(sel.cursor());
SelectionList{buffer, std::move(sels)}.erase();
}
else if (key == Key::Left)
{
move(-1_char);
moved = true;
}
else if (key == Key::Right)
{
move(1_char);
moved = true;
}
else if (key == Key::Up)
{
move(-1_line);
moved = true;
}
else if (key == Key::Down)
{
move(1_line);
moved = true;
}
else if (key == Key::Home)
{
auto& selections = context().selections();
for (auto& sel : selections)
sel.anchor() = sel.cursor() = BufferCoord{sel.cursor().line, 0};
selections.sort_and_merge_overlapping();
}
else if (key == Key::End)
{
auto& buffer = context().buffer();
auto& selections = context().selections();
for (auto& sel : selections)
{
const LineCount line = sel.cursor().line;
sel.anchor() = sel.cursor() = buffer.clamp({line, buffer[line].length()});
}
selections.sort_and_merge_overlapping();
}
else if (auto cp = key.codepoint())
insert(*cp);
else if (key == ctrl('r'))
{
on_next_key_with_autoinfo(context(), KeymapMode::None,
[this](Key key, Context&) {
auto cp = key.codepoint();
if (not cp or key == Key::Escape)
return;
insert(RegisterManager::instance()[*cp].get(context()));
}, "enter register name", register_doc);
update_completions = false;
}
else if (key == ctrl('n'))
{
last_insert().keys.pop_back();
m_completer.select(1, true, last_insert().keys);
update_completions = false;
}
else if (key == ctrl('p'))
{
last_insert().keys.pop_back();
m_completer.select(-1, true, last_insert().keys);
update_completions = false;
}
else if (key.modifiers == Key::Modifiers::MenuSelect)
{
last_insert().keys.pop_back();
m_completer.select(key.key, false, last_insert().keys);
update_completions = false;
}
else if (key == ctrl('x'))
{
on_next_key_with_autoinfo(context(), KeymapMode::None,
[this](Key key, Context&) {
if (key.key == 'f')
m_completer.explicit_file_complete();
if (key.key == 'w')
m_completer.explicit_word_buffer_complete();
if (key.key == 'W')
m_completer.explicit_word_all_complete();
if (key.key == 'l')
m_completer.explicit_line_buffer_complete();
if (key.key == 'L')
m_completer.explicit_line_all_complete();
}, "enter completion type",
"f: filename\n"
"w: word (current buffer)\n"
"W: word (all buffers)\n"
"l: line (current buffer)\n"
"L: line (all buffers)\n");
update_completions = false;
}
else if (key == ctrl('o'))
{
m_autoshowcompl = false;
m_completer.reset();
}
else if (key == ctrl('u'))
{
context().buffer().commit_undo_group();
context().print_status({ format("committed change #{}",
(size_t)context().buffer().current_history_id()),
context().faces()["Information"] });
}
else if (key == ctrl('v'))
{
on_next_key_with_autoinfo(context(), KeymapMode::None,
[this, transient](Key key, Context&) {
if (auto cp = get_raw_codepoint(key))
{
insert(*cp);
context().hooks().run_hook("InsertKey", key_to_str(key), context());
if (enabled() and not transient)
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
}, "raw insert", "enter key to insert");
update_completions = false;
}
else if (key == alt(';'))
{
push_mode(new Normal(context().input_handler(), true));
return;
}
context().hooks().run_hook("InsertKey", key_to_str(key), context());
if (moved)
context().hooks().run_hook("InsertMove", key_to_str(key), context());
if (update_completions and enabled() and not transient) // Hooks might have disabled us
m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
}
DisplayLine mode_line() const override
{
auto num_sel = context().selections().size();
auto main_index = context().selections().main_index();
return {AtomList{ { "insert", context().faces()["StatusLineMode"] },
{ " ", context().faces()["StatusLine"] },
{ format( "{} sels ({})", num_sel, main_index + 1),
context().faces()["StatusLineInfo"] } }};
}
KeymapMode keymap_mode() const override { return KeymapMode::Insert; }
StringView name() const override { return "insert"; }
private:
template<typename Type>
void move(Type offset)
{
auto& selections = context().selections();
const ColumnCount tabstop = context().options()["tabstop"].get<int>();
for (auto& sel : selections)
{
auto cursor = context().buffer().offset_coord(sel.cursor(), offset, tabstop, false);
sel.anchor() = sel.cursor() = cursor;
}
selections.sort_and_merge_overlapping();
}
void insert(ConstArrayView<String> strings)
{
context().selections().insert(strings, InsertMode::InsertCursor);
}
void insert(Codepoint key)
{
String str{key};
context().selections().insert(str, InsertMode::InsertCursor);
context().hooks().run_hook("InsertChar", str, context());
}
void prepare(InsertMode mode, int count)
{
SelectionList& selections = context().selections();
Buffer& buffer = context().buffer();
switch (mode)
{
case InsertMode::Insert:
for (auto& sel : selections)
sel.set(sel.max(), sel.min());
break;
case InsertMode::Replace:
selections.erase();
break;
case InsertMode::Append:
for (auto& sel : selections)
{
sel.set(sel.min(), sel.max());
auto& cursor = sel.cursor();
// special case for end of lines, append to current line instead
if (cursor.column != buffer[cursor.line].length() - 1)
cursor = buffer.char_next(cursor);
}
break;
case InsertMode::AppendAtLineEnd:
for (auto& sel : selections)
sel.set({sel.max().line, buffer[sel.max().line].length() - 1});
break;
case InsertMode::OpenLineBelow:
{
Vector<Selection> new_sels;
count = count > 0 ? count : 1;
LineCount inserted_count = 0;
for (auto sel : selections)
{
buffer.insert(sel.max().line + inserted_count + 1,
String{'\n', CharCount{count}});
for (int i = 0; i < count; ++i)
new_sels.push_back({sel.max().line + inserted_count + i + 1});
inserted_count += count;
}
selections.set(std::move(new_sels),
selections.main_index() * count + count - 1);
context().hooks().run_hook("InsertChar", "\n", context());
break;
}
case InsertMode::OpenLineAbove:
{
Vector<Selection> new_sels;
count = count > 0 ? count : 1;
LineCount inserted_count = 0;
for (auto sel : selections)
{
buffer.insert(sel.min().line + inserted_count,
String{'\n', CharCount{count}});
for (int i = 0; i < count; ++i)
new_sels.push_back({sel.min().line + inserted_count + i});
inserted_count += count;
}
selections.set(std::move(new_sels),
selections.main_index() * count + count - 1);
context().hooks().run_hook("InsertChar", "\n", context());
break;
}
case InsertMode::InsertAtLineBegin:
for (auto& sel : selections)
{
BufferCoord pos = sel.min().line;
auto pos_non_blank = buffer.iterator_at(pos);
while (*pos_non_blank == ' ' or *pos_non_blank == '\t')
++pos_non_blank;
if (*pos_non_blank != '\n')
pos = pos_non_blank.coord();
sel.set(pos);
}
break;
case InsertMode::InsertAtNextLineBegin:
case InsertMode::InsertCursor:
kak_assert(false); // invalid for interactive insert
break;
}
if (mode != InsertMode::Append and mode != InsertMode::Replace)
selections.sort_and_merge_overlapping();
selections.check_invariant();
buffer.check_invariant();
}
ScopedEdition m_edition;
InsertCompleter m_completer;
bool m_restore_cursor;
bool m_autoshowcompl;
Timer m_idle_timer;
bool m_in_end = false;
MouseHandler m_mouse_handler;
ScopedSetBool m_disable_hooks;
};
}
InputHandler::InputHandler(SelectionList selections, Context::Flags flags, String name)
: m_context(*this, std::move(selections), flags, std::move(name))
{
m_mode_stack.emplace_back(new InputModes::Normal(*this));
current_mode().on_enabled();
}
InputHandler::~InputHandler() = default;
void InputHandler::push_mode(InputMode* new_mode)
{
StringView prev_name = current_mode().name();
current_mode().on_disabled(true);
m_mode_stack.emplace_back(new_mode);
new_mode->on_enabled();
context().hooks().run_hook("ModeChange", format("{}:{}", prev_name, new_mode->name()), context());
}
void InputHandler::pop_mode(InputMode* mode)
{
kak_assert(m_mode_stack.back().get() == mode);
kak_assert(m_mode_stack.size() > 1);
StringView prev_name = mode->name();
current_mode().on_disabled(false);
m_mode_stack.pop_back();
current_mode().on_enabled();
context().hooks().run_hook("ModeChange", format("{}:{}", prev_name, current_mode().name()), context());
}
void InputHandler::reset_normal_mode()
{
kak_assert(dynamic_cast<InputModes::Normal*>(m_mode_stack[0].get()) != nullptr);
if (m_mode_stack.size() == 1)
return;
StringView prev_name = current_mode().name();
current_mode().on_disabled(false);
m_mode_stack.resize(1);
current_mode().on_enabled();
context().hooks().run_hook("ModeChange", format("{}:{}", prev_name, current_mode().name()), context());
}
void InputHandler::insert(InsertMode mode, int count)
{
push_mode(new InputModes::Insert(*this, mode, count));
}
void InputHandler::repeat_last_insert()
{
if (m_last_insert.keys.empty())
return;
if (dynamic_cast<InputModes::Normal*>(¤t_mode()) == nullptr or
m_last_insert.recording)
throw runtime_error{"repeating last insert not available in this context"};
Vector<Key> keys;
swap(keys, m_last_insert.keys);
ScopedSetBool disable_hooks(context().hooks_disabled(),
m_last_insert.disable_hooks);
push_mode(new InputModes::Insert(*this, m_last_insert.mode, m_last_insert.count));
for (auto& key : keys)
{
// refill last_insert, this is very inefficient, but necesary at the moment
// to properly handle insert completion
m_last_insert.keys.push_back(key);
current_mode().handle_key(key);
}
kak_assert(dynamic_cast<InputModes::Normal*>(¤t_mode()) != nullptr);
}
void InputHandler::prompt(StringView prompt, String initstr, String emptystr,
Face prompt_face, PromptFlags flags,
Completer completer, PromptCallback callback)
{
push_mode(new InputModes::Prompt(*this, prompt, std::move(initstr), std::move(emptystr),
prompt_face, flags, std::move(completer), std::move(callback)));
}
void InputHandler::set_prompt_face(Face prompt_face)
{
InputModes::Prompt* prompt = dynamic_cast<InputModes::Prompt*>(¤t_mode());
if (prompt)
prompt->set_prompt_face(prompt_face);
}
void InputHandler::menu(Vector<DisplayLine> choices, MenuCallback callback)
{
push_mode(new InputModes::Menu(*this, std::move(choices), std::move(callback)));
}
void InputHandler::on_next_key(KeymapMode keymap_mode, KeyCallback callback)
{
push_mode(new InputModes::NextKey(*this, keymap_mode, std::move(callback)));
}
InputHandler::ScopedForceNormal::ScopedForceNormal(InputHandler& handler, NormalParams params)
: m_handler(handler), m_mode(nullptr)
{
if (handler.m_mode_stack.size() != 1)
{
handler.push_mode(new InputModes::Normal(handler));
m_mode = handler.m_mode_stack.back().get();
}
static_cast<InputModes::Normal*>(handler.m_mode_stack.back().get())->m_params = params;
}
InputHandler::ScopedForceNormal::~ScopedForceNormal()
{
if (not m_mode)
return;
kak_assert(m_handler.m_mode_stack.size() > 1);
if (m_mode == m_handler.m_mode_stack.back().get())
m_handler.pop_mode(m_mode);
else
{
auto it = find_if(m_handler.m_mode_stack,
[this](const RefPtr<InputMode>& m)
{ return m.get() == m_mode; });
kak_assert(it != m_handler.m_mode_stack.end());
m_handler.m_mode_stack.erase(it);
}
}
static bool is_valid(Key key)
{
constexpr Key::Modifiers valid_mods = (Key::Modifiers::Control | Key::Modifiers::Alt | Key::Modifiers::Shift);
return key != Key::Invalid and
((key.modifiers & ~valid_mods) or key.key <= 0x10FFFF);
}
void InputHandler::handle_key(Key key)
{
if (not is_valid(key))
return;
const bool was_recording = is_recording();
++m_handle_key_level;
auto dec = on_scope_end([this]{ --m_handle_key_level; });
auto process_key = [&](Key key) {
if (m_last_insert.recording)
m_last_insert.keys.push_back(key);
current_mode().handle_key(key);
};
const auto keymap_mode = current_mode().keymap_mode();
KeymapManager& keymaps = m_context.keymaps();
if (keymaps.is_mapped(key, keymap_mode) and not m_context.keymaps_disabled())
{
ScopedSetBool disable_history{context().history_disabled()};
for (auto& k : keymaps.get_mapping(key, keymap_mode).keys)
process_key(k);
}
else
process_key(key);
// do not record the key that made us enter or leave recording mode,
// and the ones that are triggered recursively by previous keys.
if (was_recording and is_recording() and m_handle_key_level == m_recording_level)
m_recorded_keys += key_to_str(key);
if (m_handle_key_level < m_recording_level)
{
write_to_debug_buffer("Macro recording started but not finished");
m_recording_reg = 0;
m_recording_level = -1;
}
}
void InputHandler::start_recording(char reg)
{
kak_assert(m_recording_reg == 0);
m_recording_level = m_handle_key_level;
m_recorded_keys = "";
m_recording_reg = reg;
}
bool InputHandler::is_recording() const
{
return m_recording_reg != 0;
}
void InputHandler::stop_recording()
{
kak_assert(m_recording_reg != 0);
if (not m_recorded_keys.empty())
RegisterManager::instance()[m_recording_reg].set(
context(), {m_recorded_keys});
m_recording_reg = 0;
m_recording_level = -1;
}
DisplayLine InputHandler::mode_line() const
{
return current_mode().mode_line();
}
std::pair<CursorMode, DisplayCoord> InputHandler::get_cursor_info() const
{
return current_mode().get_cursor_info();
}
bool show_auto_info_ifn(StringView title, StringView info, AutoInfo mask, const Context& context)
{
if (not (context.options()["autoinfo"].get<AutoInfo>() & mask) or
not context.has_client())
return false;
context.client().info_show(title.str(), info.str(), {}, InfoStyle::Prompt);
return true;
}
void hide_auto_info_ifn(const Context& context, bool hide)
{
if (hide)
context.client().info_hide();
}
void scroll_window(Context& context, LineCount offset)
{
Window& window = context.window();
Buffer& buffer = context.buffer();
DisplayCoord win_pos = window.position();
DisplayCoord win_dim = window.dimensions();
const DisplayCoord max_offset{(win_dim.line - 1)/2, (win_dim.column - 1)/2};
const DisplayCoord scrolloff =
std::min(context.options()["scrolloff"].get<DisplayCoord>(), max_offset);
const LineCount line_count = buffer.line_count();
win_pos.line = clamp(win_pos.line + offset, 0_line, line_count-1);
SelectionList& selections = context.selections();
const BufferCoord cursor = selections.main().cursor();
auto line = clamp(cursor.line, win_pos.line + scrolloff.line,
win_pos.line + win_dim.line - 1 - scrolloff.line);
line = clamp(line, 0_line, line_count-1);
using std::min; using std::max;
// This is not exactly a clamp, and must be done in this order as
// byte_count_to could return line length
auto col = min(max(cursor.column, buffer[line].byte_count_to(win_pos.column)),
buffer[line].length()-1);
selections = SelectionList{buffer, BufferCoord{line, col}};
window.set_position(win_pos);
}
}
|
// Generated from argmin_2.mod.py
// DO NOT EDIT
// clang-format off
#include "TestHarness.h"
using namespace test_helper; // NOLINT(google-build-using-namespace)
namespace generated_tests::argmin_2 {
const TestModel& get_test_model() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f, 4.0f, 3.0f})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}},
.operations = {{
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {0},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model = TestModelManager::get().add("argmin_2", get_test_model());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f, 4.0f, 3.0f})
}, { // placeholder
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {3, 4, 5},
.outputs = {0}
}, {
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {3},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_all_inputs_as_internal = TestModelManager::get().add("argmin_2_all_inputs_as_internal", get_test_model_all_inputs_as_internal());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_relaxed() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f, 4.0f, 3.0f})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}},
.operations = {{
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {0},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = true,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::UNKNOWN
};
return model;
}
const auto dummy_test_model_relaxed = TestModelManager::get().add("argmin_2_relaxed", get_test_model_relaxed());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_relaxed_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f, 4.0f, 3.0f})
}, { // placeholder1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {3, 4, 5},
.outputs = {0}
}, {
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {3},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = true,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::UNKNOWN
};
return model;
}
const auto dummy_test_model_relaxed_all_inputs_as_internal = TestModelManager::get().add("argmin_2_relaxed_all_inputs_as_internal", get_test_model_relaxed_all_inputs_as_internal());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_float16() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({1.0f, 2.0f, 4.0f, 3.0f})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}},
.operations = {{
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {0},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16 = TestModelManager::get().add("argmin_2_float16", get_test_model_float16());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_float16_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({1.0f, 2.0f, 4.0f, 3.0f})
}, { // placeholder2
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param2
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {3, 4, 5},
.outputs = {0}
}, {
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {3},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_all_inputs_as_internal = TestModelManager::get().add("argmin_2_float16_all_inputs_as_internal", get_test_model_float16_all_inputs_as_internal());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_int32() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({1, 2, 4, 3})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}},
.operations = {{
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {0},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_int32 = TestModelManager::get().add("argmin_2_int32", get_test_model_int32());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_quant8() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 1.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({1, 2, 4, 3})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}},
.operations = {{
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {0},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_quant8 = TestModelManager::get().add("argmin_2_quant8", get_test_model_quant8());
} // namespace generated_tests::argmin_2
namespace generated_tests::argmin_2 {
const TestModel& get_test_model_quant8_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 1.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({})
}, { // axis
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output
.type = TestOperandType::TENSOR_INT32,
.dimensions = {2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0, 0})
}, { // input0_new
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 2},
.numberOfConsumers = 1,
.scale = 1.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({1, 2, 4, 3})
}, { // placeholder3
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 1.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({0})
}, { // param3
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {3, 4, 5},
.outputs = {0}
}, {
.type = TestOperationType::ARGMIN,
.inputs = {0, 1},
.outputs = {2}
}},
.inputIndexes = {3},
.outputIndexes = {2}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_quant8_all_inputs_as_internal = TestModelManager::get().add("argmin_2_quant8_all_inputs_as_internal", get_test_model_quant8_all_inputs_as_internal());
} // namespace generated_tests::argmin_2
|
#include "Server.h"
Server::~Server()
{
}
int Server::get_id()
{
return id_;
}
int Server::get_size()
{
#ifdef QUEUE_SIM
assert(jobs_queue_size_ == (int)jobs_queue_.size() && "queue size missmatch");
#endif
return jobs_queue_size_;
}
void Server::add_jobs(int arrived_jobs, int arrival_time)
{
#ifdef QUEUE_SIM
for (int i = 0; i < arrived_jobs; i++)
{
Job job{ arrival_time };
jobs_queue_.push(job);
}
#endif
jobs_queue_size_ += arrived_jobs;
}
bool Server::complete_jobs(int departure_time)
{
int offered_service = completed_jobs_(generator_);
int num_completed = std::min(jobs_queue_size_, offered_service);
#ifdef QUEUE_SIM
for (int i = 0; i < num_completed; i++)
{
int jct = departure_time - jobs_queue_.front().get_time() + 1;
#ifdef JOB_COMPLETION_TIME
if (jct_map_.find(jct) == jct_map_.end()) {
// not found
jct_map_[jct] = 1;
}
else {
// found
jct_map_[jct] += 1;
}
#endif // JOB_COMPLETION_TIME
job_delays_ += jct;
jobs_queue_.pop();
}
#endif
jobs_queue_size_ -= num_completed;
job_commulative_ += jobs_queue_size_;
job_departures_ += num_completed;
return true;
}
double Server::get_commulative_job_delays()
{
return job_delays_;
}
double Server::get_commulative_size()
{
return job_commulative_;
}
double Server::get_commulative_departures()
{
return job_departures_;
}
#ifdef JOB_COMPLETION_TIME
unordered_map<int, int>* Server::get_jct_map()
{
return &jct_map_;
}
#endif
bool JIQ_Server::complete_jobs(int departure_time)
{
int offered_service = completed_jobs_(generator_);
int num_completed = std::min(jobs_queue_size_, offered_service);
#ifdef QUEUE_SIM
for (int i = 0; i < num_completed; i++)
{
int jct = departure_time - jobs_queue_.front().get_time() + 1;
#ifdef JOB_COMPLETION_TIME
if (jct_map_.find(jct) == jct_map_.end()) {
// not found
jct_map_[jct] = 1;
}
else {
// found
jct_map_[jct] += 1;
}
#endif // JOB_COMPLETION_TIME
job_delays_ += jct;
jobs_queue_.pop();
}
#endif
jobs_queue_size_ -= num_completed;
job_commulative_ += jobs_queue_size_;
job_departures_ += num_completed;
if (num_completed > 0 && jobs_queue_size_ == 0)
{
return true;
}
return false;
}
bool Smart_Server::complete_jobs(int departure_time)
{
int offered_service = completed_jobs_(generator_);
int num_completed = std::min(jobs_queue_size_, offered_service);
#ifdef QUEUE_SIM
for (int i = 0; i < num_completed; i++)
{
int jct = departure_time - jobs_queue_.front().get_time() + 1;
#ifdef JOB_COMPLETION_TIME
if (jct_map_.find(jct) == jct_map_.end()) {
// not found
jct_map_[jct] = 1;
}
else {
// found
jct_map_[jct] += 1;
}
#endif // JOB_COMPLETION_TIME
job_delays_ += jct;
jobs_queue_.pop();
}
#endif
jobs_queue_size_ -= num_completed;
job_commulative_ += jobs_queue_size_;
job_departures_ += num_completed;
// consider sending a message only if jobs were completed
if (num_completed > 0)
{
return true;
}
return false;
}
double Smart_Server::get_expected_delay()
{
return (double)jobs_queue_size_ / ((1.0 - mu_) / mu_);
}
|
/**
* @file Params.cpp
*
* @brief Parameter class for Zerocoin.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017 The SEOCOIN developers
#include "Params.h"
#include "ParamGeneration.h"
namespace libzerocoin {
ZerocoinParams::ZerocoinParams(CBigNum N, uint32_t securityLevel) {
this->zkp_hash_len = securityLevel;
this->zkp_iterations = securityLevel;
this->accumulatorParams.k_prime = ACCPROOF_KPRIME;
this->accumulatorParams.k_dprime = ACCPROOF_KDPRIME;
// Generate the parameters
CalculateParams(*this, N, ZEROCOIN_PROTOCOL_VERSION, securityLevel);
this->accumulatorParams.initialized = true;
this->initialized = true;
}
AccumulatorAndProofParams::AccumulatorAndProofParams() {
this->initialized = false;
}
IntegerGroupParams::IntegerGroupParams() {
this->initialized = false;
}
CBigNum IntegerGroupParams::randomElement() const {
// The generator of the group raised
// to a random number less than the order of the group
// provides us with a uniformly distributed random number.
return this->g.pow_mod(CBigNum::randBignum(this->groupOrder),this->modulus);
}
} /* namespace libzerocoin */
|
#pragma once
#define _USE_MATH_DEFINES
#include <cmath>
#include <cppsim/simulator.hpp>
#include "parametric_circuit.hpp"
#include "parametric_simulator.hpp"
#include "problem.hpp"
class DllExport QuantumCircuitGradientDifferentiation {
public:
virtual double compute_gradient(ParametricQuantumCircuitSimulator* sim, const EnergyMinimizationProblem* instance, const std::vector<double>& parameter, std::vector<double>* gradient) = 0;
};
class DllExport GradientByHalfPi : public QuantumCircuitGradientDifferentiation {
public:
virtual double compute_gradient(ParametricQuantumCircuitSimulator* sim, const EnergyMinimizationProblem* instance, const std::vector<double>& parameter, std::vector<double>* gradient) override;
};
|
#include <iostream>
#include <toolbelt/unit_tests.hpp>
#include "tests/crc32_test.hpp"
#include "tests/make_smart_test.hpp"
#include "tests/string_test.hpp"
int main(int argc, char** argv) {
toolbelt::test_suite s;
add_crc32_tests(s);
add_make_smart_tests(s);
add_string_tests(s);
return s.run_tests();
}
|
/**
* Find all divisors of a natural number
*
* Given a natural number n, print all distinct divisors of it.
*
* Examples:
* Input : n = 10
* Output: 1 2 5 10
*
* Input: n = 100
* Output: 1 2 4 5 10 20 25 50 100
*
* Input: n = 125
* Output: 1 5 25 125
*
* URL: https://www.geeksforgeeks.org/find-divisors-natural-number-set-1/
* https://www.geeksforgeeks.org/find-all-divisors-of-a-natural-number-set-2/
*
*/
#include <iostream>
void getDivisors(int n)
{
for (int i = 1; i * i <= n; i++) { // time complexity: sqrt(n)
if (n % i == 0) {
if (n/i == i)
std::cout << i << " ";
else std::cout << i << " " << n/i << " ";
}
}
}
int main()
{
int n = 100;
getDivisors(n);
return 0;
}
|
/*
*
* Copyright (c) 1998-2002
* Dr John Maddock
*
* Use, modification and distribution are subject to 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)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE regex_format.hpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: Provides formatting output routines for search and replace
* operations. Note this is an internal header file included
* by regex.hpp, do not include on its own.
*/
#ifndef BOOST_REGEX_V4_REGEX_MERGE_HPP
#define BOOST_REGEX_V4_REGEX_MERGE_HPP
namespace boost{
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_PREFIX
#endif
template <class OutputIterator, class Iterator, class traits, class Allocator, class charT>
inline OutputIterator regex_merge(OutputIterator out,
Iterator first,
Iterator last,
const reg_expression<charT, traits, Allocator>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
return regex_replace(out, first, last, e, fmt, flags);
}
template <class OutputIterator, class Iterator, class traits, class Allocator, class charT>
inline OutputIterator regex_merge(OutputIterator out,
Iterator first,
Iterator last,
const reg_expression<charT, traits, Allocator>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
return regex_merge(out, first, last, e, fmt.c_str(), flags);
}
template <class traits, class Allocator, class charT>
inline std::basic_string<charT> regex_merge(const std::basic_string<charT>& s,
const reg_expression<charT, traits, Allocator>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
return regex_replace(s, e, fmt, flags);
}
template <class traits, class Allocator, class charT>
inline std::basic_string<charT> regex_merge(const std::basic_string<charT>& s,
const reg_expression<charT, traits, Allocator>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
return regex_replace(s, e, fmt, flags);
}
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_SUFFIX
#endif
} // namespace boost
#endif // BOOST_REGEX_V4_REGEX_MERGE_HPP
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/feature_engagement_tracker/internal/feature_config_condition_validator.h"
#include "base/feature_list.h"
#include "components/feature_engagement_tracker/internal/availability_model.h"
#include "components/feature_engagement_tracker/internal/configuration.h"
#include "components/feature_engagement_tracker/internal/model.h"
#include "components/feature_engagement_tracker/internal/proto/event.pb.h"
#include "components/feature_engagement_tracker/public/feature_list.h"
namespace feature_engagement_tracker {
FeatureConfigConditionValidator::FeatureConfigConditionValidator()
: currently_showing_(false), times_shown_(0u) {}
FeatureConfigConditionValidator::~FeatureConfigConditionValidator() = default;
ConditionValidator::Result FeatureConfigConditionValidator::MeetsConditions(
const base::Feature& feature,
const FeatureConfig& config,
const Model& model,
const AvailabilityModel& availability_model,
uint32_t current_day) const {
ConditionValidator::Result result(true);
result.event_model_ready_ok = model.IsReady();
result.currently_showing_ok = !currently_showing_;
result.feature_enabled_ok = base::FeatureList::IsEnabled(feature);
result.config_ok = config.valid;
result.used_ok = EventConfigMeetsConditions(config.used, model, current_day);
result.trigger_ok =
EventConfigMeetsConditions(config.trigger, model, current_day);
for (const auto& event_config : config.event_configs) {
result.preconditions_ok &=
EventConfigMeetsConditions(event_config, model, current_day);
}
result.session_rate_ok = config.session_rate.MeetsCriteria(times_shown_);
result.availability_model_ready_ok = availability_model.IsReady();
result.availability_ok = AvailabilityMeetsConditions(
feature, config.availability, availability_model, current_day);
return result;
}
void FeatureConfigConditionValidator::NotifyIsShowing(
const base::Feature& feature) {
DCHECK(!currently_showing_);
DCHECK(base::FeatureList::IsEnabled(feature));
currently_showing_ = true;
++times_shown_;
}
void FeatureConfigConditionValidator::NotifyDismissed(
const base::Feature& feature) {
currently_showing_ = false;
}
bool FeatureConfigConditionValidator::EventConfigMeetsConditions(
const EventConfig& event_config,
const Model& model,
uint32_t current_day) const {
const Event* event = model.GetEvent(event_config.name);
// If no events are found, the requirement must be met with 0 elements.
// Also, if the window is 0 days, there will never be any events.
if (event == nullptr || event_config.window == 0u)
return event_config.comparator.MeetsCriteria(0u);
DCHECK(event_config.window >= 0);
// A window of N=0: Nothing should be counted.
// A window of N=1: |current_day| should be counted.
// A window of N=2+: |current_day| plus |N-1| more days should be counted.
uint32_t oldest_accepted_day = current_day - event_config.window + 1;
// Cap |oldest_accepted_day| to UNIX epoch.
if (event_config.window > current_day)
oldest_accepted_day = 0u;
// Calculate the number of events within the window.
uint32_t event_count = 0;
for (const auto& event_day : event->events()) {
if (event_day.day() < oldest_accepted_day)
continue;
event_count += event_day.count();
}
return event_config.comparator.MeetsCriteria(event_count);
}
bool FeatureConfigConditionValidator::AvailabilityMeetsConditions(
const base::Feature& feature,
Comparator comparator,
const AvailabilityModel& availability_model,
uint32_t current_day) const {
if (comparator.type == ANY)
return true;
base::Optional<uint32_t> availability_day =
availability_model.GetAvailability(feature);
if (!availability_day.has_value())
return false;
uint32_t days_available = current_day - availability_day.value();
// Ensure that availability days never wrap around.
if (availability_day.value() > current_day)
days_available = 0u;
return comparator.MeetsCriteria(days_available);
}
} // namespace feature_engagement_tracker
|
/*
* Copyright 2014-present IVK JSC. All 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.
*/
#include "Less.h"
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_EngramEntry_Narcotic_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function EngramEntry_Narcotic.EngramEntry_Narcotic_C.ExecuteUbergraph_EngramEntry_Narcotic
struct UEngramEntry_Narcotic_C_ExecuteUbergraph_EngramEntry_Narcotic_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
/*
* Copyright (c) 2011-2021, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* 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.
* 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 <dart/dart.hpp>
const double default_height = 1.0; // m
const double default_width = 0.2; // m
const double default_depth = 0.2; // m
const double default_torque = 15.0; // N-m
const double default_force = 15.0; // N
const int default_countdown = 200; // Number of timesteps for applying force
const double default_rest_position = 0.0;
const double delta_rest_position = dart::math::toRadian(10.0);
const double default_stiffness = 0.0;
const double delta_stiffness = 10;
const double default_damping = 5.0;
const double delta_damping = 1.0;
using namespace dart::dynamics;
using namespace dart::simulation;
class MyWindow : public dart::gui::glut::SimWindow
{
public:
/// Constructor
MyWindow(WorldPtr world)
: mBallConstraint(nullptr), mPositiveSign(true), mBodyForce(false)
{
setWorld(world);
// Find the Skeleton named "pendulum" within the World
mPendulum = world->getSkeleton("pendulum");
// Make sure that the pendulum was found in the World
assert(mPendulum != nullptr);
mForceCountDown.resize(mPendulum->getNumDofs(), 0);
ArrowShape::Properties arrow_properties;
arrow_properties.mRadius = 0.05;
mArrow = std::shared_ptr<ArrowShape>(new ArrowShape(
Eigen::Vector3d(-default_height, 0.0, default_height / 2.0),
Eigen::Vector3d(-default_width / 2.0, 0.0, default_height / 2.0),
arrow_properties,
dart::Color::Orange(1.0)));
}
void changeDirection()
{
mPositiveSign = !mPositiveSign;
if (mPositiveSign)
{
mArrow->setPositions(
Eigen::Vector3d(-default_height, 0.0, default_height / 2.0),
Eigen::Vector3d(-default_width / 2.0, 0.0, default_height / 2.0));
}
else
{
mArrow->setPositions(
Eigen::Vector3d(default_height, 0.0, default_height / 2.0),
Eigen::Vector3d(default_width / 2.0, 0.0, default_height / 2.0));
}
}
void applyForce(std::size_t index)
{
if (index < mForceCountDown.size())
mForceCountDown[index] = default_countdown;
}
void changeRestPosition(double /*delta*/)
{
// Lesson 2a
}
void changeStiffness(double /*delta*/)
{
// Lesson 2b
}
void changeDamping(double /*delta*/)
{
// Lesson 2c
}
/// Add a constraint to attach the final link to the world
void addConstraint()
{
// Lesson 3
}
/// Remove any existing constraint, allowing the pendulum to flail freely
void removeConstraint()
{
// Lesson 3
}
/// Handle keyboard input
void keyboard(unsigned char key, int x, int y) override
{
switch (key)
{
case '-':
changeDirection();
break;
case '1':
applyForce(0);
break;
case '2':
applyForce(1);
break;
case '3':
applyForce(2);
break;
case '4':
applyForce(3);
break;
case '5':
applyForce(4);
break;
case '6':
applyForce(5);
break;
case '7':
applyForce(6);
break;
case '8':
applyForce(7);
break;
case '9':
applyForce(8);
break;
case '0':
applyForce(9);
break;
case 'q':
changeRestPosition(delta_rest_position);
break;
case 'a':
changeRestPosition(-delta_rest_position);
break;
case 'w':
changeStiffness(delta_stiffness);
break;
case 's':
changeStiffness(-delta_stiffness);
break;
case 'e':
changeDamping(delta_damping);
break;
case 'd':
changeDamping(-delta_damping);
break;
case 'r':
{
if (mBallConstraint)
removeConstraint();
else
addConstraint();
break;
}
case 'f':
mBodyForce = !mBodyForce;
break;
default:
SimWindow::keyboard(key, x, y);
}
}
void timeStepping() override
{
// Reset all the shapes to be Blue
// Lesson 1a
if (!mBodyForce)
{
// Apply joint torques based on user input, and color the Joint shape red
for (std::size_t i = 0; i < mPendulum->getNumDofs(); ++i)
{
if (mForceCountDown[i] > 0)
{
// Lesson 1b
--mForceCountDown[i];
}
}
}
else
{
// Apply body forces based on user input, and color the body shape red
for (std::size_t i = 0; i < mPendulum->getNumBodyNodes(); ++i)
{
if (mForceCountDown[i] > 0)
{
// Lesson 1c
--mForceCountDown[i];
}
}
}
// Step the simulation forward
SimWindow::timeStepping();
}
protected:
/// An arrow shape that we will use to visualize applied forces
std::shared_ptr<ArrowShape> mArrow;
/// The pendulum that we will be perturbing
SkeletonPtr mPendulum;
/// Pointer to the ball constraint that we will be turning on and off
dart::dynamics::BallJointConstraint* mBallConstraint;
/// Number of iterations before clearing a force entry
std::vector<int> mForceCountDown;
/// Whether a force should be applied in the positive or negative direction
bool mPositiveSign;
/// True if 1-9 should be used to apply a body force. Otherwise, 1-9 will be
/// used to apply a joint torque.
bool mBodyForce;
};
void setGeometry(const BodyNodePtr& bn)
{
// Create a BoxShape to be used for both visualization and collision checking
std::shared_ptr<BoxShape> box(new BoxShape(
Eigen::Vector3d(default_width, default_depth, default_height)));
// Create a shape node for visualization and collision checking
auto shapeNode
= bn->createShapeNodeWith<VisualAspect, CollisionAspect, DynamicsAspect>(
box);
shapeNode->getVisualAspect()->setColor(dart::Color::Blue());
// Set the location of the shape node
Eigen::Isometry3d box_tf(Eigen::Isometry3d::Identity());
Eigen::Vector3d center = Eigen::Vector3d(0, 0, default_height / 2.0);
box_tf.translation() = center;
shapeNode->setRelativeTransform(box_tf);
// Move the center of mass to the center of the object
bn->setLocalCOM(center);
}
BodyNode* makeRootBody(const SkeletonPtr& pendulum, const std::string& name)
{
BallJoint::Properties properties;
properties.mName = name + "_joint";
properties.mRestPositions = Eigen::Vector3d::Constant(default_rest_position);
properties.mSpringStiffnesses = Eigen::Vector3d::Constant(default_stiffness);
properties.mDampingCoefficients = Eigen::Vector3d::Constant(default_damping);
BodyNodePtr bn
= pendulum
->createJointAndBodyNodePair<BallJoint>(
nullptr, properties, BodyNode::AspectProperties(name))
.second;
// Make a shape for the Joint
const double& R = default_width;
std::shared_ptr<EllipsoidShape> ball(
new EllipsoidShape(sqrt(2) * Eigen::Vector3d(R, R, R)));
auto shapeNode = bn->createShapeNodeWith<VisualAspect>(ball);
shapeNode->getVisualAspect()->setColor(dart::Color::Blue());
// Set the geometry of the Body
setGeometry(bn);
return bn;
}
BodyNode* addBody(
const SkeletonPtr& pendulum, BodyNode* parent, const std::string& name)
{
// Set up the properties for the Joint
RevoluteJoint::Properties properties;
properties.mName = name + "_joint";
properties.mAxis = Eigen::Vector3d::UnitY();
properties.mT_ParentBodyToJoint.translation()
= Eigen::Vector3d(0, 0, default_height);
properties.mRestPositions[0] = default_rest_position;
properties.mSpringStiffnesses[0] = default_stiffness;
properties.mDampingCoefficients[0] = default_damping;
// Create a new BodyNode, attached to its parent by a RevoluteJoint
BodyNodePtr bn = pendulum
->createJointAndBodyNodePair<RevoluteJoint>(
parent, properties, BodyNode::AspectProperties(name))
.second;
// Make a shape for the Joint
const double R = default_width / 2.0;
const double h = default_depth;
std::shared_ptr<CylinderShape> cyl(new CylinderShape(R, h));
// Line up the cylinder with the Joint axis
Eigen::Isometry3d tf(Eigen::Isometry3d::Identity());
tf.linear() = dart::math::eulerXYZToMatrix(
Eigen::Vector3d(dart::math::toRadian(90.0), 0, 0));
auto shapeNode = bn->createShapeNodeWith<VisualAspect>(cyl);
shapeNode->getVisualAspect()->setColor(dart::Color::Blue());
shapeNode->setRelativeTransform(tf);
// Set the geometry of the Body
setGeometry(bn);
return bn;
}
int main(int argc, char* argv[])
{
// Create an empty Skeleton with the name "pendulum"
SkeletonPtr pendulum = Skeleton::create("pendulum");
// Add each body to the last BodyNode in the pendulum
BodyNode* bn = makeRootBody(pendulum, "body1");
bn = addBody(pendulum, bn, "body2");
bn = addBody(pendulum, bn, "body3");
bn = addBody(pendulum, bn, "body4");
bn = addBody(pendulum, bn, "body5");
// Set the initial position of the first DegreeOfFreedom so that the pendulum
// starts to swing right away
pendulum->getDof(1)->setPosition(dart::math::toRadian(120.0));
// Create a world and add the pendulum to the world
WorldPtr world = World::create();
world->addSkeleton(pendulum);
// Create a window for rendering the world and handling user input
MyWindow window(world);
// Print instructions
std::cout << "space bar: simulation on/off" << std::endl;
std::cout << "'p': replay simulation" << std::endl;
std::cout << "'1' -> '9': apply torque to a pendulum body" << std::endl;
std::cout << "'-': Change sign of applied joint torques" << std::endl;
std::cout << "'q': Increase joint rest positions" << std::endl;
std::cout << "'a': Decrease joint rest positions" << std::endl;
std::cout << "'w': Increase joint spring stiffness" << std::endl;
std::cout << "'s': Decrease joint spring stiffness" << std::endl;
std::cout << "'e': Increase joint damping" << std::endl;
std::cout << "'d': Decrease joint damping" << std::endl;
std::cout << "'r': add/remove constraint on the end of the chain"
<< std::endl;
std::cout << "'f': switch between applying joint torques and body forces"
<< std::endl;
// Initialize glut, initialize the window, and begin the glut event loop
glutInit(&argc, argv);
window.initWindow(640, 480, "Multi-Pendulum Tutorial");
glutMainLoop();
}
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_window.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/browser/api/atom_api_browser_view.h"
#include "atom/browser/api/atom_api_menu.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "ui/gfx/geometry/rect.h"
#if defined(TOOLKIT_VIEWS)
#include "atom/browser/native_window_views.h"
#endif
#if defined(OS_WIN)
#include "atom/browser/ui/win/taskbar_host.h"
#include "ui/base/win/shell.h"
#endif
#include "atom/common/node_includes.h"
#if defined(OS_WIN)
namespace mate {
template<>
struct Converter<atom::TaskbarHost::ThumbarButton> {
static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val,
atom::TaskbarHost::ThumbarButton* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("click", &(out->clicked_callback));
dict.Get("tooltip", &(out->tooltip));
dict.Get("flags", &out->flags);
return dict.Get("icon", &(out->icon));
}
};
} // namespace mate
#endif
namespace atom {
namespace api {
namespace {
// Converts binary data to Buffer.
v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) {
auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size);
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
} // namespace
Window::Window(v8::Isolate* isolate, v8::Local<v8::Object> wrapper,
const mate::Dictionary& options) {
mate::Handle<class WebContents> web_contents;
// Use options.webPreferences in WebContents.
mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
// Copy the backgroundColor to webContents.
v8::Local<v8::Value> value;
if (options.Get(options::kBackgroundColor, &value))
web_preferences.Set(options::kBackgroundColor, value);
v8::Local<v8::Value> transparent;
if (options.Get("transparent", &transparent))
web_preferences.Set("transparent", transparent);
#if defined(ENABLE_OSR)
// Offscreen windows are always created frameless.
bool offscreen;
if (web_preferences.Get("offscreen", &offscreen) && offscreen) {
auto window_options = const_cast<mate::Dictionary&>(options);
window_options.Set(options::kFrame, false);
}
#endif
if (options.Get("webContents", &web_contents)) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::FromWebContents(web_contents->web_contents());
base::DictionaryValue web_preferences_dict;
if (mate::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->web_preferences()->Clear();
existing_preferences->Merge(web_preferences_dict);
}
} else {
// Creates the WebContents used by BrowserWindow.
web_contents = WebContents::Create(isolate, web_preferences);
}
Init(isolate, wrapper, options, web_contents);
}
void Window::Init(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options,
mate::Handle<class WebContents> web_contents) {
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
// Keep a copy of the options for later use.
mate::Dictionary(isolate, web_contents->GetWrapper()).Set(
"browserWindowOptions", options);
// The parent window.
mate::Handle<Window> parent;
if (options.Get("parent", &parent))
parent_window_.Reset(isolate, parent.ToV8());
// Creates BrowserWindow.
window_.reset(NativeWindow::Create(
web_contents->managed_web_contents(),
options,
parent.IsEmpty() ? nullptr : parent->window_.get()));
web_contents->SetOwnerWindow(window_.get());
#if defined(TOOLKIT_VIEWS)
// Sets the window icon.
mate::Handle<NativeImage> icon;
if (options.Get(options::kIcon, &icon))
SetIcon(icon);
#endif
window_->InitFromOptions(options);
window_->AddObserver(this);
InitWith(isolate, wrapper);
AttachAsUserData(window_.get());
// We can only append this window to parent window's child windows after this
// window's JS wrapper gets initialized.
if (!parent.IsEmpty())
parent->child_windows_.Set(isolate, ID(), wrapper);
}
Window::~Window() {
if (!window_->IsClosed())
window_->CloseContents(nullptr);
// Destroy the native window in next tick because the native code might be
// iterating all windows.
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, window_.release());
}
void Window::WillCloseWindow(bool* prevent_default) {
*prevent_default = Emit("close");
}
void Window::WillDestroyNativeObject() {
// Close all child windows before closing current window.
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
for (v8::Local<v8::Value> value : child_windows_.Values(isolate())) {
mate::Handle<Window> child;
if (mate::ConvertFromV8(isolate(), value, &child))
child->window_->CloseImmediately();
}
}
void Window::OnWindowClosed() {
api_web_contents_->DestroyWebContents(true /* async */);
RemoveFromWeakMap();
window_->RemoveObserver(this);
// We can not call Destroy here because we need to call Emit first, but we
// also do not want any method to be used, so just mark as destroyed here.
MarkDestroyed();
Emit("closed");
RemoveFromParentChildWindows();
ResetBrowserView();
// Destroy the native class when window is closed.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, GetDestroyClosure());
}
void Window::OnWindowEndSession() {
Emit("session-end");
}
void Window::OnWindowBlur() {
Emit("blur");
}
void Window::OnWindowFocus() {
Emit("focus");
}
void Window::OnWindowShow() {
Emit("show");
}
void Window::OnWindowHide() {
Emit("hide");
}
void Window::OnReadyToShow() {
Emit("ready-to-show");
}
void Window::OnWindowMaximize() {
Emit("maximize");
}
void Window::OnWindowUnmaximize() {
Emit("unmaximize");
}
void Window::OnWindowMinimize() {
Emit("minimize");
}
void Window::OnWindowRestore() {
Emit("restore");
}
void Window::OnWindowResize() {
Emit("resize");
}
void Window::OnWindowMove() {
Emit("move");
}
void Window::OnWindowMoved() {
Emit("moved");
}
void Window::OnWindowEnterFullScreen() {
Emit("enter-full-screen");
}
void Window::OnWindowLeaveFullScreen() {
Emit("leave-full-screen");
}
void Window::OnWindowScrollTouchBegin() {
Emit("scroll-touch-begin");
}
void Window::OnWindowScrollTouchEnd() {
Emit("scroll-touch-end");
}
void Window::OnWindowScrollTouchEdge() {
Emit("scroll-touch-edge");
}
void Window::OnWindowSwipe(const std::string& direction) {
Emit("swipe", direction);
}
void Window::OnWindowSheetBegin() {
Emit("sheet-begin");
}
void Window::OnWindowSheetEnd() {
Emit("sheet-end");
}
void Window::OnWindowEnterHtmlFullScreen() {
Emit("enter-html-full-screen");
}
void Window::OnWindowLeaveHtmlFullScreen() {
Emit("leave-html-full-screen");
}
void Window::OnRendererUnresponsive() {
Emit("unresponsive");
}
void Window::OnRendererResponsive() {
Emit("responsive");
}
void Window::OnExecuteWindowsCommand(const std::string& command_name) {
Emit("app-command", command_name);
}
void Window::OnTouchBarItemResult(const std::string& item_id,
const base::DictionaryValue& details) {
Emit("-touch-bar-interaction", item_id, details);
}
void Window::OnNewWindowForTab() {
Emit("new-window-for-tab");
}
#if defined(OS_WIN)
void Window::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) {
if (IsWindowMessageHooked(message)) {
messages_callback_map_[message].Run(
ToBuffer(isolate(), static_cast<void*>(&w_param), sizeof(WPARAM)),
ToBuffer(isolate(), static_cast<void*>(&l_param), sizeof(LPARAM)));
}
}
#endif
// static
mate::WrappableBase* Window::New(mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
args->ThrowError("Cannot create BrowserWindow before app is ready");
return nullptr;
}
if (args->Length() > 1) {
args->ThrowError();
return nullptr;
}
mate::Dictionary options;
if (!(args->Length() == 1 && args->GetNext(&options))) {
options = mate::Dictionary::CreateEmpty(args->isolate());
}
return new Window(args->isolate(), args->GetThis(), options);
}
void Window::Close() {
window_->Close();
}
void Window::Focus() {
window_->Focus(true);
}
void Window::Blur() {
window_->Focus(false);
}
bool Window::IsFocused() {
return window_->IsFocused();
}
void Window::Show() {
window_->Show();
}
void Window::ShowInactive() {
// This method doesn't make sense for modal window..
if (IsModal())
return;
window_->ShowInactive();
}
void Window::Hide() {
window_->Hide();
}
bool Window::IsVisible() {
return window_->IsVisible();
}
bool Window::IsEnabled() {
return window_->IsEnabled();
}
void Window::Maximize() {
window_->Maximize();
}
void Window::Unmaximize() {
window_->Unmaximize();
}
bool Window::IsMaximized() {
return window_->IsMaximized();
}
void Window::Minimize() {
window_->Minimize();
}
void Window::Restore() {
window_->Restore();
}
bool Window::IsMinimized() {
return window_->IsMinimized();
}
void Window::SetFullScreen(bool fullscreen) {
window_->SetFullScreen(fullscreen);
}
bool Window::IsFullscreen() {
return window_->IsFullscreen();
}
void Window::SetBounds(const gfx::Rect& bounds, mate::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetBounds(bounds, animate);
}
gfx::Rect Window::GetBounds() {
return window_->GetBounds();
}
void Window::SetContentBounds(const gfx::Rect& bounds, mate::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetContentBounds(bounds, animate);
}
gfx::Rect Window::GetContentBounds() {
return window_->GetContentBounds();
}
void Window::SetSize(int width, int height, mate::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetSize(gfx::Size(width, height), animate);
}
std::vector<int> Window::GetSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void Window::SetContentSize(int width, int height, mate::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetContentSize(gfx::Size(width, height), animate);
}
std::vector<int> Window::GetContentSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetContentSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void Window::SetMinimumSize(int width, int height) {
window_->SetMinimumSize(gfx::Size(width, height));
}
std::vector<int> Window::GetMinimumSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetMinimumSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void Window::SetMaximumSize(int width, int height) {
window_->SetMaximumSize(gfx::Size(width, height));
}
std::vector<int> Window::GetMaximumSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetMaximumSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void Window::SetSheetOffset(double offsetY, mate::Arguments* args) {
double offsetX = 0.0;
args->GetNext(&offsetX);
window_->SetSheetOffset(offsetX, offsetY);
}
void Window::SetResizable(bool resizable) {
window_->SetResizable(resizable);
}
bool Window::IsResizable() {
return window_->IsResizable();
}
void Window::SetMovable(bool movable) {
window_->SetMovable(movable);
}
bool Window::IsMovable() {
return window_->IsMovable();
}
void Window::SetMinimizable(bool minimizable) {
window_->SetMinimizable(minimizable);
}
bool Window::IsMinimizable() {
return window_->IsMinimizable();
}
void Window::SetMaximizable(bool maximizable) {
window_->SetMaximizable(maximizable);
}
bool Window::IsMaximizable() {
return window_->IsMaximizable();
}
void Window::SetFullScreenable(bool fullscreenable) {
window_->SetFullScreenable(fullscreenable);
}
bool Window::IsFullScreenable() {
return window_->IsFullScreenable();
}
void Window::SetClosable(bool closable) {
window_->SetClosable(closable);
}
bool Window::IsClosable() {
return window_->IsClosable();
}
void Window::SetAlwaysOnTop(bool top, mate::Arguments* args) {
std::string level = "floating";
int relativeLevel = 0;
std::string error;
args->GetNext(&level);
args->GetNext(&relativeLevel);
window_->SetAlwaysOnTop(top, level, relativeLevel, &error);
if (!error.empty()) {
args->ThrowError(error);
}
}
bool Window::IsAlwaysOnTop() {
return window_->IsAlwaysOnTop();
}
void Window::Center() {
window_->Center();
}
void Window::SetPosition(int x, int y, mate::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetPosition(gfx::Point(x, y), animate);
}
std::vector<int> Window::GetPosition() {
std::vector<int> result(2);
gfx::Point pos = window_->GetPosition();
result[0] = pos.x();
result[1] = pos.y();
return result;
}
void Window::SetTitle(const std::string& title) {
window_->SetTitle(title);
}
std::string Window::GetTitle() {
return window_->GetTitle();
}
void Window::FlashFrame(bool flash) {
window_->FlashFrame(flash);
}
void Window::SetSkipTaskbar(bool skip) {
window_->SetSkipTaskbar(skip);
}
void Window::SetKiosk(bool kiosk) {
window_->SetKiosk(kiosk);
}
bool Window::IsKiosk() {
return window_->IsKiosk();
}
void Window::SetBackgroundColor(const std::string& color_name) {
window_->SetBackgroundColor(color_name);
}
void Window::SetHasShadow(bool has_shadow) {
window_->SetHasShadow(has_shadow);
}
bool Window::HasShadow() {
return window_->HasShadow();
}
void Window::FocusOnWebView() {
window_->FocusOnWebView();
}
void Window::BlurWebView() {
window_->BlurWebView();
}
bool Window::IsWebViewFocused() {
return window_->IsWebViewFocused();
}
void Window::SetRepresentedFilename(const std::string& filename) {
window_->SetRepresentedFilename(filename);
}
std::string Window::GetRepresentedFilename() {
return window_->GetRepresentedFilename();
}
void Window::SetDocumentEdited(bool edited) {
window_->SetDocumentEdited(edited);
}
bool Window::IsDocumentEdited() {
return window_->IsDocumentEdited();
}
void Window::SetIgnoreMouseEvents(bool ignore, mate::Arguments* args) {
mate::Dictionary options;
bool forward = false;
args->GetNext(&options) && options.Get("forward", &forward);
return window_->SetIgnoreMouseEvents(ignore, forward);
}
void Window::SetContentProtection(bool enable) {
return window_->SetContentProtection(enable);
}
void Window::SetFocusable(bool focusable) {
return window_->SetFocusable(focusable);
}
void Window::SetProgressBar(double progress, mate::Arguments* args) {
mate::Dictionary options;
std::string mode;
NativeWindow::ProgressState state = NativeWindow::PROGRESS_NORMAL;
args->GetNext(&options) && options.Get("mode", &mode);
if (mode == "error") {
state = NativeWindow::PROGRESS_ERROR;
} else if (mode == "paused") {
state = NativeWindow::PROGRESS_PAUSED;
} else if (mode == "indeterminate") {
state = NativeWindow::PROGRESS_INDETERMINATE;
} else if (mode == "none") {
state = NativeWindow::PROGRESS_NONE;
}
window_->SetProgressBar(progress, state);
}
void Window::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {
window_->SetOverlayIcon(overlay, description);
}
bool Window::SetThumbarButtons(mate::Arguments* args) {
#if defined(OS_WIN)
std::vector<TaskbarHost::ThumbarButton> buttons;
if (!args->GetNext(&buttons)) {
args->ThrowError();
return false;
}
auto window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbarButtons(
window_->GetAcceleratedWidget(), buttons);
#else
return false;
#endif
}
void Window::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) {
mate::Handle<Menu> menu;
if (value->IsObject() &&
mate::V8ToString(value->ToObject()->GetConstructorName()) == "Menu" &&
mate::ConvertFromV8(isolate, value, &menu)) {
menu_.Reset(isolate, menu.ToV8());
window_->SetMenu(menu->model());
} else if (value->IsNull()) {
menu_.Reset();
window_->SetMenu(nullptr);
} else {
isolate->ThrowException(v8::Exception::TypeError(
mate::StringToV8(isolate, "Invalid Menu")));
}
}
void Window::SetAutoHideMenuBar(bool auto_hide) {
window_->SetAutoHideMenuBar(auto_hide);
}
bool Window::IsMenuBarAutoHide() {
return window_->IsMenuBarAutoHide();
}
void Window::SetMenuBarVisibility(bool visible) {
window_->SetMenuBarVisibility(visible);
}
bool Window::IsMenuBarVisible() {
return window_->IsMenuBarVisible();
}
#if defined(OS_WIN)
bool Window::HookWindowMessage(UINT message,
const MessageCallback& callback) {
messages_callback_map_[message] = callback;
return true;
}
void Window::UnhookWindowMessage(UINT message) {
if (!ContainsKey(messages_callback_map_, message))
return;
messages_callback_map_.erase(message);
}
bool Window::IsWindowMessageHooked(UINT message) {
return ContainsKey(messages_callback_map_, message);
}
void Window::UnhookAllWindowMessages() {
messages_callback_map_.clear();
}
bool Window::SetThumbnailClip(const gfx::Rect& region) {
auto window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbnailClip(
window_->GetAcceleratedWidget(), region);
}
bool Window::SetThumbnailToolTip(const std::string& tooltip) {
auto window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbnailToolTip(
window_->GetAcceleratedWidget(), tooltip);
}
void Window::SetAppDetails(const mate::Dictionary& options) {
base::string16 app_id;
base::FilePath app_icon_path;
int app_icon_index = 0;
base::string16 relaunch_command;
base::string16 relaunch_display_name;
options.Get("appId", &app_id);
options.Get("appIconPath", &app_icon_path);
options.Get("appIconIndex", &app_icon_index);
options.Get("relaunchCommand", &relaunch_command);
options.Get("relaunchDisplayName", &relaunch_display_name);
ui::win::SetAppDetailsForWindow(
app_id, app_icon_path, app_icon_index,
relaunch_command, relaunch_display_name,
window_->GetAcceleratedWidget());
}
#endif
#if defined(TOOLKIT_VIEWS)
void Window::SetIcon(mate::Handle<NativeImage> icon) {
#if defined(OS_WIN)
static_cast<NativeWindowViews*>(window_.get())->SetIcon(
icon->GetHICON(GetSystemMetrics(SM_CXSMICON)),
icon->GetHICON(GetSystemMetrics(SM_CXICON)));
#elif defined(USE_X11)
static_cast<NativeWindowViews*>(window_.get())->SetIcon(
icon->image().AsImageSkia());
#endif
}
#endif
void Window::SetAspectRatio(double aspect_ratio, mate::Arguments* args) {
gfx::Size extra_size;
args->GetNext(&extra_size);
window_->SetAspectRatio(aspect_ratio, extra_size);
}
void Window::PreviewFile(const std::string& path, mate::Arguments* args) {
std::string display_name;
if (!args->GetNext(&display_name))
display_name = path;
window_->PreviewFile(path, display_name);
}
void Window::CloseFilePreview() {
window_->CloseFilePreview();
}
void Window::SetParentWindow(v8::Local<v8::Value> value,
mate::Arguments* args) {
if (IsModal()) {
args->ThrowError("Can not be called for modal window");
return;
}
mate::Handle<Window> parent;
if (value->IsNull()) {
RemoveFromParentChildWindows();
parent_window_.Reset();
window_->SetParentWindow(nullptr);
} else if (mate::ConvertFromV8(isolate(), value, &parent)) {
parent_window_.Reset(isolate(), value);
window_->SetParentWindow(parent->window_.get());
parent->child_windows_.Set(isolate(), ID(), GetWrapper());
} else {
args->ThrowError("Must pass BrowserWindow instance or null");
}
}
v8::Local<v8::Value> Window::GetParentWindow() const {
if (parent_window_.IsEmpty())
return v8::Null(isolate());
else
return v8::Local<v8::Value>::New(isolate(), parent_window_);
}
std::vector<v8::Local<v8::Object>> Window::GetChildWindows() const {
return child_windows_.Values(isolate());
}
v8::Local<v8::Value> Window::GetBrowserView() const {
if (browser_view_.IsEmpty()) {
return v8::Null(isolate());
}
return v8::Local<v8::Value>::New(isolate(), browser_view_);
}
void Window::SetBrowserView(v8::Local<v8::Value> value) {
ResetBrowserView();
mate::Handle<BrowserView> browser_view;
if (value->IsNull()) {
window_->SetBrowserView(nullptr);
} else if (mate::ConvertFromV8(isolate(), value, &browser_view)) {
window_->SetBrowserView(browser_view->view());
browser_view->web_contents()->SetOwnerWindow(window_.get());
browser_view_.Reset(isolate(), value);
}
}
void Window::ResetBrowserView() {
if (browser_view_.IsEmpty()) {
return;
}
mate::Handle<BrowserView> browser_view;
if (mate::ConvertFromV8(isolate(), GetBrowserView(), &browser_view)) {
browser_view->web_contents()->SetOwnerWindow(nullptr);
}
browser_view_.Reset();
}
bool Window::IsModal() const {
return window_->is_modal();
}
v8::Local<v8::Value> Window::GetNativeWindowHandle() {
gfx::AcceleratedWidget handle = window_->GetAcceleratedWidget();
return ToBuffer(
isolate(), static_cast<void*>(&handle), sizeof(gfx::AcceleratedWidget));
}
void Window::SetVisibleOnAllWorkspaces(bool visible) {
return window_->SetVisibleOnAllWorkspaces(visible);
}
bool Window::IsVisibleOnAllWorkspaces() {
return window_->IsVisibleOnAllWorkspaces();
}
void Window::SetAutoHideCursor(bool auto_hide) {
window_->SetAutoHideCursor(auto_hide);
}
void Window::SetVibrancy(mate::Arguments* args) {
std::string type;
args->GetNext(&type);
window_->SetVibrancy(type);
}
void Window::SetTouchBar(const std::vector<mate::PersistentDictionary>& items) {
window_->SetTouchBar(items);
}
void Window::RefreshTouchBarItem(const std::string& item_id) {
window_->RefreshTouchBarItem(item_id);
}
void Window::SetEscapeTouchBarItem(const mate::PersistentDictionary& item) {
window_->SetEscapeTouchBarItem(item);
}
int32_t Window::ID() const {
return weak_map_id();
}
v8::Local<v8::Value> Window::WebContents(v8::Isolate* isolate) {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate);
}
return v8::Local<v8::Value>::New(isolate, web_contents_);
}
void Window::RemoveFromParentChildWindows() {
if (parent_window_.IsEmpty())
return;
mate::Handle<Window> parent;
if (!mate::ConvertFromV8(isolate(), GetParentWindow(), &parent))
return;
parent->child_windows_.Remove(ID());
}
// static
void Window::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "BrowserWindow"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("close", &Window::Close)
.SetMethod("focus", &Window::Focus)
.SetMethod("blur", &Window::Blur)
.SetMethod("isFocused", &Window::IsFocused)
.SetMethod("show", &Window::Show)
.SetMethod("showInactive", &Window::ShowInactive)
.SetMethod("hide", &Window::Hide)
.SetMethod("isVisible", &Window::IsVisible)
.SetMethod("isEnabled", &Window::IsEnabled)
.SetMethod("maximize", &Window::Maximize)
.SetMethod("unmaximize", &Window::Unmaximize)
.SetMethod("isMaximized", &Window::IsMaximized)
.SetMethod("minimize", &Window::Minimize)
.SetMethod("restore", &Window::Restore)
.SetMethod("isMinimized", &Window::IsMinimized)
.SetMethod("setFullScreen", &Window::SetFullScreen)
.SetMethod("isFullScreen", &Window::IsFullscreen)
.SetMethod("setAspectRatio", &Window::SetAspectRatio)
.SetMethod("previewFile", &Window::PreviewFile)
.SetMethod("closeFilePreview", &Window::CloseFilePreview)
#if !defined(OS_WIN)
.SetMethod("setParentWindow", &Window::SetParentWindow)
#endif
.SetMethod("getParentWindow", &Window::GetParentWindow)
.SetMethod("getChildWindows", &Window::GetChildWindows)
.SetMethod("getBrowserView", &Window::GetBrowserView)
.SetMethod("setBrowserView", &Window::SetBrowserView)
.SetMethod("isModal", &Window::IsModal)
.SetMethod("getNativeWindowHandle", &Window::GetNativeWindowHandle)
.SetMethod("getBounds", &Window::GetBounds)
.SetMethod("setBounds", &Window::SetBounds)
.SetMethod("getSize", &Window::GetSize)
.SetMethod("setSize", &Window::SetSize)
.SetMethod("getContentBounds", &Window::GetContentBounds)
.SetMethod("setContentBounds", &Window::SetContentBounds)
.SetMethod("getContentSize", &Window::GetContentSize)
.SetMethod("setContentSize", &Window::SetContentSize)
.SetMethod("setMinimumSize", &Window::SetMinimumSize)
.SetMethod("getMinimumSize", &Window::GetMinimumSize)
.SetMethod("setMaximumSize", &Window::SetMaximumSize)
.SetMethod("getMaximumSize", &Window::GetMaximumSize)
.SetMethod("setSheetOffset", &Window::SetSheetOffset)
.SetMethod("setResizable", &Window::SetResizable)
.SetMethod("isResizable", &Window::IsResizable)
.SetMethod("setMovable", &Window::SetMovable)
.SetMethod("isMovable", &Window::IsMovable)
.SetMethod("setMinimizable", &Window::SetMinimizable)
.SetMethod("isMinimizable", &Window::IsMinimizable)
.SetMethod("setMaximizable", &Window::SetMaximizable)
.SetMethod("isMaximizable", &Window::IsMaximizable)
.SetMethod("setFullScreenable", &Window::SetFullScreenable)
.SetMethod("isFullScreenable", &Window::IsFullScreenable)
.SetMethod("setClosable", &Window::SetClosable)
.SetMethod("isClosable", &Window::IsClosable)
.SetMethod("setAlwaysOnTop", &Window::SetAlwaysOnTop)
.SetMethod("isAlwaysOnTop", &Window::IsAlwaysOnTop)
.SetMethod("center", &Window::Center)
.SetMethod("setPosition", &Window::SetPosition)
.SetMethod("getPosition", &Window::GetPosition)
.SetMethod("setTitle", &Window::SetTitle)
.SetMethod("getTitle", &Window::GetTitle)
.SetMethod("flashFrame", &Window::FlashFrame)
.SetMethod("setSkipTaskbar", &Window::SetSkipTaskbar)
.SetMethod("setKiosk", &Window::SetKiosk)
.SetMethod("isKiosk", &Window::IsKiosk)
.SetMethod("setBackgroundColor", &Window::SetBackgroundColor)
.SetMethod("setHasShadow", &Window::SetHasShadow)
.SetMethod("hasShadow", &Window::HasShadow)
.SetMethod("setRepresentedFilename", &Window::SetRepresentedFilename)
.SetMethod("getRepresentedFilename", &Window::GetRepresentedFilename)
.SetMethod("setDocumentEdited", &Window::SetDocumentEdited)
.SetMethod("isDocumentEdited", &Window::IsDocumentEdited)
.SetMethod("setIgnoreMouseEvents", &Window::SetIgnoreMouseEvents)
.SetMethod("setContentProtection", &Window::SetContentProtection)
.SetMethod("setFocusable", &Window::SetFocusable)
.SetMethod("focusOnWebView", &Window::FocusOnWebView)
.SetMethod("blurWebView", &Window::BlurWebView)
.SetMethod("isWebViewFocused", &Window::IsWebViewFocused)
.SetMethod("setProgressBar", &Window::SetProgressBar)
.SetMethod("setOverlayIcon", &Window::SetOverlayIcon)
.SetMethod("setThumbarButtons", &Window::SetThumbarButtons)
.SetMethod("setMenu", &Window::SetMenu)
.SetMethod("setAutoHideMenuBar", &Window::SetAutoHideMenuBar)
.SetMethod("isMenuBarAutoHide", &Window::IsMenuBarAutoHide)
.SetMethod("setMenuBarVisibility", &Window::SetMenuBarVisibility)
.SetMethod("isMenuBarVisible", &Window::IsMenuBarVisible)
.SetMethod("setVisibleOnAllWorkspaces",
&Window::SetVisibleOnAllWorkspaces)
.SetMethod("isVisibleOnAllWorkspaces",
&Window::IsVisibleOnAllWorkspaces)
#if defined(OS_MACOSX)
.SetMethod("setAutoHideCursor", &Window::SetAutoHideCursor)
#endif
.SetMethod("setVibrancy", &Window::SetVibrancy)
.SetMethod("_setTouchBarItems", &Window::SetTouchBar)
.SetMethod("_refreshTouchBarItem", &Window::RefreshTouchBarItem)
.SetMethod("_setEscapeTouchBarItem", &Window::SetEscapeTouchBarItem)
#if defined(OS_WIN)
.SetMethod("hookWindowMessage", &Window::HookWindowMessage)
.SetMethod("isWindowMessageHooked", &Window::IsWindowMessageHooked)
.SetMethod("unhookWindowMessage", &Window::UnhookWindowMessage)
.SetMethod("unhookAllWindowMessages", &Window::UnhookAllWindowMessages)
.SetMethod("setThumbnailClip", &Window::SetThumbnailClip)
.SetMethod("setThumbnailToolTip", &Window::SetThumbnailToolTip)
.SetMethod("setAppDetails", &Window::SetAppDetails)
#endif
#if defined(TOOLKIT_VIEWS)
.SetMethod("setIcon", &Window::SetIcon)
#endif
.SetProperty("id", &Window::ID)
.SetProperty("webContents", &Window::WebContents);
}
// static
v8::Local<v8::Value> Window::From(v8::Isolate* isolate,
NativeWindow* native_window) {
auto existing = TrackableObject::FromWrappedClass(isolate, native_window);
if (existing)
return existing->GetWrapper();
else
return v8::Null(isolate);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Window;
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
Window::SetConstructor(isolate, base::Bind(&Window::New));
mate::Dictionary browser_window(
isolate, Window::GetConstructor(isolate)->GetFunction());
browser_window.SetMethod("fromId",
&mate::TrackableObject<Window>::FromWeakMapID);
browser_window.SetMethod("getAllWindows",
&mate::TrackableObject<Window>::GetAll);
mate::Dictionary dict(isolate, exports);
dict.Set("BrowserWindow", browser_window);
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_window, Initialize)
|
#include "stdafx.h"
void CopyToCircleStruct(ON_CIRCLE_STRUCT& cs, const ON_Circle& circle)
{
RHCHECK_LICENSE
memcpy(&cs, &circle, sizeof(ON_CIRCLE_STRUCT));
}
ON_Circle FromCircleStruct(const ON_CIRCLE_STRUCT& cs)
{
RHCHECK_LICENSE
ON_Circle circle;
memcpy(&circle, &cs, sizeof(ON_CIRCLE_STRUCT));
circle.plane.UpdateEquation();
return circle;
}
RH_C_FUNCTION void ON_Circle_Create3Pt(ON_CIRCLE_STRUCT* c, ON_3DPOINT_STRUCT p, ON_3DPOINT_STRUCT q, ON_3DPOINT_STRUCT r)
{
RHCHECK_LICENSE
if( c )
{
const ON_3dPoint* _p = (const ON_3dPoint*)&p;
const ON_3dPoint* _q = (const ON_3dPoint*)&q;
const ON_3dPoint* _r = (const ON_3dPoint*)&r;
ON_Circle _c(*_p, *_q, *_r);
_c.plane.UpdateEquation();
CopyToCircleStruct(*c, _c);
}
}
RH_C_FUNCTION bool ON_Circle_CreatePtVecPt(ON_CIRCLE_STRUCT* c, ON_3DPOINT_STRUCT p, ON_3DVECTOR_STRUCT tan_at_p, ON_3DPOINT_STRUCT q)
{
RHCHECK_LICENSE
bool rc = false;
if( c )
{
const ON_3dPoint* _p = (const ON_3dPoint*)&p;
const ON_3dVector* _tan_at_p = (const ON_3dVector*)&tan_at_p;
const ON_3dPoint* _q = (const ON_3dPoint*)&q;
ON_Circle _c;
rc = _c.Create( *_p, *_tan_at_p, *_q );
_c.plane.UpdateEquation();
CopyToCircleStruct(*c, _c);
}
return rc;
}
RH_C_FUNCTION bool ON_Circle_IsInPlane(const ON_CIRCLE_STRUCT* c, const ON_PLANE_STRUCT* plane, double tolerance)
{
bool rc = false;
if ( c && plane )
{
ON_Plane temp = FromPlaneStruct(*plane);
ON_Circle circle = FromCircleStruct(*c);
rc = circle.IsInPlane(temp, tolerance);
}
return rc;
}
RH_C_FUNCTION void ON_Circle_BoundingBox(const ON_CIRCLE_STRUCT* c, ON_BoundingBox* bbox)
{
if( c && bbox )
{
ON_Circle circle = FromCircleStruct(*c);
*bbox = circle.BoundingBox();
}
}
RH_C_FUNCTION bool ON_Circle_Transform( ON_CIRCLE_STRUCT* c, ON_Xform* xf)
{
bool rc = false;
if( c && xf )
{
ON_Circle circle = FromCircleStruct(*c);
rc = circle.Transform(*xf);
CopyToCircleStruct(*c, circle);
}
return rc;
}
RH_C_FUNCTION bool ON_Circle_ClosestPointTo( const ON_CIRCLE_STRUCT* c,
ON_3DPOINT_STRUCT testPoint,
double* t)
{
bool rc = false;
const ON_3dPoint* _testPoint = (const ON_3dPoint*)&testPoint;
if (c)
{
ON_Circle circle = FromCircleStruct(*c);
rc = circle.ClosestPointTo(*_testPoint, t);
}
return rc;
}
RH_C_FUNCTION int ON_Circle_GetNurbForm(const ON_CIRCLE_STRUCT* pCircle, ON_NurbsCurve* nurbs_curve)
{
RHCHECK_LICENSE
int rc = 0;
if( pCircle && nurbs_curve )
{
ON_Circle circle = FromCircleStruct(*pCircle);
rc = circle.GetNurbForm(*nurbs_curve);
}
return rc;
}
RH_C_FUNCTION bool ON_Circle_TryFitTTT(const ON_Curve* c1, const ON_Curve* c2, const ON_Curve* c3,
double seed1, double seed2, double seed3,
ON_CIRCLE_STRUCT* circleFit)
{
RHCHECK_LICENSE
#if !defined(RHINO3DM_BUILD)
if (!c1 || !c2 || !c3) { return false; }
if (!circleFit) { return false; }
// 2-Sep-2015 Dale Fugier, http://mcneel.myjetbrains.com/youtrack/issue/RH-31084
// Moved this calculation code into a Rhino SDK function.
ON_Circle circle;
if (RhinoCalculateCircleTanTanTan(c1, c2, c3, seed1, seed2, seed3, circle))
{
if (circle.IsValid())
{
CopyToCircleStruct(*circleFit, circle);
return true;
}
}
#endif
return false;
}
RH_C_FUNCTION bool ON_Circle_TryFitTT(const ON_Curve* c1, const ON_Curve* c2,
double seed1, double seed2,
ON_CIRCLE_STRUCT* circleFit)
{
#if !defined(RHINO3DM_BUILD)
if (!c1 || !c2) { return false; }
if (!circleFit) { return false; }
// 2-Sep-2015 Dale Fugier, http://mcneel.myjetbrains.com/youtrack/issue/RH-31084
// Moved this calculation code into a Rhino SDK function.
ON_Circle circle;
if (RhinoCalculateCircleTanTan(c1, c2, seed1, seed2, circle))
{
if (circle.IsValid())
{
CopyToCircleStruct(*circleFit, circle);
return true;
}
}
#endif
return false;
}
|
#include "glfw_window.hpp"
using namespace std ;
glfwRenderWindow::~glfwRenderWindow()
{
}
bool glfwRenderWindow::run(size_t width, size_t height, const string &wname) {
glfwSetErrorCallback(errorCallback);
if( !glfwInit() ) return false ;
// With an intel card with this glxinfo I have replaced GLFW_OPENGL_COMPAT_PROFILE
// to GLFW_OPENGL_CORE_PROFILE
// OpenGL renderer string: Mesa DRI Intel(R) HD Graphics 5500 (Broadwell GT2)
// OpenGL core profile version string: 3.3 (Core Profile) Mesa 10.5.9
// OpenGL core profile shading language version string: 3.30
// glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);\
if ( !( handle_ = glfwCreateWindow(width, height, wname.c_str(), 0, 0) )) {
glfwTerminate();
return false ;
}
glfwSetWindowUserPointer(handle_, this) ;
glfwMakeContextCurrent(handle_);
glfwSwapInterval(1);
glfwSetCursorPosCallback(handle_, moveCallback);
glfwSetKeyCallback(handle_, keyCallback);
glfwSetMouseButtonCallback(handle_, buttonCallback);
glfwSetScrollCallback(handle_, scrollCallback);
glfwSetWindowSizeCallback(handle_, sizeCallback);
onInit() ;
sizeCallback(handle_, width, height); // Set initial size.
while (!glfwWindowShouldClose(handle_)) {
onRender() ;
glfwSwapBuffers(handle_);
glfwPollEvents();
}
glfwDestroyWindow(handle_);
glfwTerminate();
return true ;
}
void glfwRenderWindow::buttonCallback(GLFWwindow *window, int button, int action, int mods) {
glfwRenderWindow *instance = (glfwRenderWindow *)glfwGetWindowUserPointer(window) ;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
switch(action)
{
case GLFW_PRESS:
instance->onMouseButtonPressed(button, xpos, ypos, mods) ;
break ;
case GLFW_RELEASE:
instance->onMouseButtonReleased(button, xpos, ypos, mods) ;
break ;
default: break;
}
}
void glfwRenderWindow::errorCallback(int error, const char *description) {
}
void glfwRenderWindow::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
glfwRenderWindow *instance = (glfwRenderWindow *)glfwGetWindowUserPointer(window) ;
switch(action) {
case GLFW_PRESS:
switch(key)
{
case GLFW_KEY_ESCAPE:
// Exit app on ESC key.
glfwSetWindowShouldClose(window, GL_TRUE);
break;
default:
instance->onKeyPressed(key, mods);
}
break;
case GLFW_RELEASE:
instance->onKeyReleased(key, mods) ;
default: break;
}
}
void glfwRenderWindow::moveCallback(GLFWwindow *window, double xpos, double ypos) {
glfwRenderWindow *instance = (glfwRenderWindow *)glfwGetWindowUserPointer(window) ;
instance->onMouseMoved(xpos, ypos);
}
void glfwRenderWindow::scrollCallback(GLFWwindow *window, double xpos, double ypos) {
glfwRenderWindow *instance = (glfwRenderWindow *)glfwGetWindowUserPointer(window) ;
instance->onMouseWheel(xpos + ypos);
}
void glfwRenderWindow::sizeCallback(GLFWwindow *window, int width, int height) {
glfwRenderWindow *instance = (glfwRenderWindow *)glfwGetWindowUserPointer(window) ;
instance->onResize(width, height) ;
}
|
// Copyright (c) 2019 The BitcoinV Core developers
// Copyright (c) 2011-2018 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 <qt/walletframe.h>
#include <qt/walletmodel.h>
#include <qt/bitcoingui.h>
#include <qt/walletview.h>
#include <cassert>
#include <cstdio>
#include <QHBoxLayout>
#include <QLabel>
WalletFrame::WalletFrame(const PlatformStyle *_platformStyle, BitcoinGUI *_gui) :
QFrame(_gui),
gui(_gui),
platformStyle(_platformStyle)
{
// Leave HBox hook for adding a list view later
QHBoxLayout *walletFrameLayout = new QHBoxLayout(this);
setContentsMargins(0,0,0,0);
walletStack = new QStackedWidget(this);
walletFrameLayout->setContentsMargins(0,0,0,0);
walletFrameLayout->addWidget(walletStack);
QLabel *noWallet = new QLabel(tr("No wallet has been loaded."));
noWallet->setAlignment(Qt::AlignCenter);
walletStack->addWidget(noWallet);
}
WalletFrame::~WalletFrame()
{
}
void WalletFrame::setClientModel(ClientModel *_clientModel)
{
this->clientModel = _clientModel;
}
bool WalletFrame::addWallet(WalletModel *walletModel)
{
if (!gui || !clientModel || !walletModel) {
return false;
}
const QString name = walletModel->getWalletName();
if (mapWalletViews.count(name) > 0) {
return false;
}
WalletView *walletView = new WalletView(platformStyle, this);
walletView->setBitcoinGUI(gui);
walletView->setClientModel(clientModel);
walletView->setWalletModel(walletModel);
walletView->showOutOfSyncWarning(bOutOfSync);
WalletView* current_wallet_view = currentWalletView();
if (current_wallet_view) {
walletView->setCurrentIndex(current_wallet_view->currentIndex());
} else {
walletView->gotoOverviewPage();
}
walletStack->addWidget(walletView);
mapWalletViews[name] = walletView;
// Ensure a walletView is able to show the main window
connect(walletView, SIGNAL(showNormalIfMinimized()), gui, SLOT(showNormalIfMinimized()));
connect(walletView, SIGNAL(outOfSyncWarningClicked()), this, SLOT(outOfSyncWarningClicked()));
return true;
}
bool WalletFrame::setCurrentWallet(const QString& name)
{
if (mapWalletViews.count(name) == 0)
return false;
WalletView *walletView = mapWalletViews.value(name);
walletStack->setCurrentWidget(walletView);
assert(walletView);
walletView->updateEncryptionStatus();
return true;
}
bool WalletFrame::removeWallet(const QString &name)
{
if (mapWalletViews.count(name) == 0)
return false;
WalletView *walletView = mapWalletViews.take(name);
walletStack->removeWidget(walletView);
delete walletView;
return true;
}
void WalletFrame::removeAllWallets()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
walletStack->removeWidget(i.value());
mapWalletViews.clear();
}
bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient)
{
WalletView *walletView = currentWalletView();
if (!walletView)
return false;
return walletView->handlePaymentRequest(recipient);
}
void WalletFrame::showOutOfSyncWarning(bool fShow)
{
bOutOfSync = fShow;
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->showOutOfSyncWarning(fShow);
}
void WalletFrame::gotoOverviewPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoOverviewPage();
}
void WalletFrame::gotoMinerPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoMinerPage();
}
void WalletFrame::gotoHistoryPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoHistoryPage();
}
void WalletFrame::gotoReceiveCoinsPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoReceiveCoinsPage();
}
void WalletFrame::gotoSendCoinsPage(QString addr)
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoSendCoinsPage(addr);
}
void WalletFrame::gotoSignMessageTab(QString addr)
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->gotoSignMessageTab(addr);
}
void WalletFrame::gotoVerifyMessageTab(QString addr)
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->gotoVerifyMessageTab(addr);
}
void WalletFrame::encryptWallet(bool status)
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->encryptWallet(status);
}
void WalletFrame::backupWallet()
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->backupWallet();
}
void WalletFrame::changePassphrase()
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->changePassphrase();
}
void WalletFrame::unlockWallet()
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->unlockWallet();
}
void WalletFrame::usedSendingAddresses()
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->usedSendingAddresses();
}
void WalletFrame::usedReceivingAddresses()
{
WalletView *walletView = currentWalletView();
if (walletView)
walletView->usedReceivingAddresses();
}
WalletView *WalletFrame::currentWalletView()
{
return qobject_cast<WalletView*>(walletStack->currentWidget());
}
void WalletFrame::outOfSyncWarningClicked()
{
Q_EMIT requestedSyncWarningInfo();
}
|
#pragma once
#include <xgt/schema/abstract_schema.hpp>
#include <xgt/schema/schema_impl.hpp>
#include <fc/optional.hpp>
#include <utility>
namespace xgt { namespace schema { namespace detail {
//////////////////////////////////////////////
// optional //
//////////////////////////////////////////////
template< typename E >
struct schema_optional_impl
: public abstract_schema
{
XGT_SCHEMA_TEMPLATE_CLASS_BODY( schema_optional_impl )
};
template< typename E >
void schema_optional_impl< E >::get_deps( std::vector< std::shared_ptr< abstract_schema > >& deps )
{
deps.push_back( get_schema_for_type<E>() );
}
template< typename E >
void schema_optional_impl< E >::get_str_schema( std::string& s )
{
if( str_schema != "" )
{
s = str_schema;
return;
}
std::vector< std::shared_ptr< abstract_schema > > deps;
get_deps( deps );
std::string e_type;
deps[0]->get_name(e_type);
std::string my_name;
get_name( my_name );
fc::mutable_variant_object mvo;
mvo("name", my_name)
("type", "optional")
("etype", e_type)
;
str_schema = fc::json::to_string( mvo );
s = str_schema;
return;
}
}
template< typename E >
struct schema_reflect< fc::optional< E > >
{
typedef detail::schema_optional_impl< E > schema_impl_type;
};
} }
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core Developers
// Copyright (c) 2018 Curve Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "chain.h"
#include "core_io.h"
#include "init.h"
#include "instantx.h"
#include "net.h"
#include "policy/rbf.h"
#include "rpc/server.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validation.h"
#include "wallet.h"
#include "walletdb.h"
#include "keepass.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nRequires wallet passphrase to be set with walletpassphrase call."
: "";
}
bool EnsureWalletIsAvailable(bool avoidException)
{
if (!pwalletMain)
{
if (!avoidException)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
else
return false;
}
return true;
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain(false);
bool fLocked = instantsend.IsLockedInstantSendTransaction(wtx.GetHash());
entry.push_back(Pair("confirmations", confirms));
entry.push_back(Pair("instantlock", fLocked));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
} else {
entry.push_back(Pair("trusted", wtx.IsTrusted()));
}
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
UniValue conflicts(UniValue::VARR);
BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
// Add opt-in RBF status
std::string rbfStatus = "no";
if (confirms <= 0) {
LOCK(mempool.cs);
if (!mempool.exists(hash)) {
if (SignalsOptInRBF(wtx)) {
rbfStatus = "yes";
} else {
rbfStatus = "unknown";
}
} else if (IsRBFOptIn(*mempool.mapTx.find(hash), mempool)) {
rbfStatus = "yes";
}
}
entry.push_back(Pair("bip125-replaceable", rbfStatus));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const UniValue& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
UniValue getnewaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress ( \"account\" )\n"
"\nReturns a new Curve address for receiving payments.\n"
"If 'account' is specified (DEPRECATED), it is added to the address book \n"
"so payments received with the address will be credited to 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
"\nResult:\n"
"\"curveaddress\" (string) The new curve address\n"
"\nExamples:\n"
+ HelpExampleCli("getnewaddress", "")
+ HelpExampleRpc("getnewaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked(true))
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
UniValue getaccountaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress \"account\"\n"
"\nDEPRECATED. Returns the current Curve address for receiving payments to this account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
"\nResult:\n"
"\"curveaddress\" (string) The account curve address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccountaddress", "")
+ HelpExampleCli("getaccountaddress", "\"\"")
+ HelpExampleCli("getaccountaddress", "\"myaccount\"")
+ HelpExampleRpc("getaccountaddress", "\"myaccount\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
UniValue ret(UniValue::VSTR);
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
UniValue getrawchangeaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawchangeaddress\n"
"\nReturns a new Curve address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n"
+ HelpExampleCli("getrawchangeaddress", "")
+ HelpExampleRpc("getrawchangeaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!pwalletMain->IsLocked(true))
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey, true))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CBitcoinAddress(keyID).ToString();
}
UniValue setaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount \"curveaddress\" \"account\"\n"
"\nDEPRECATED. Sets the account associated with the given address.\n"
"\nArguments:\n"
"1. \"curveaddress\" (string, required) The curve address to be associated with an account.\n"
"2. \"account\" (string, required) The account to assign the address to.\n"
"\nExamples:\n"
+ HelpExampleCli("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"tabby\"")
+ HelpExampleRpc("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Curve address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Only add the account if the address is yours.
if (IsMine(*pwalletMain, address.Get()))
{
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
}
else
throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
return NullUniValue;
}
UniValue getaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount \"curveaddress\"\n"
"\nDEPRECATED. Returns the account associated with the given address.\n"
"\nArguments:\n"
"1. \"curveaddress\" (string, required) The curve address for account lookup.\n"
"\nResult:\n"
"\"accountname\" (string) the account address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"")
+ HelpExampleRpc("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Curve address");
string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
UniValue getaddressesbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount \"account\"\n"
"\nDEPRECATED. Returns the list of addresses for the given account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"curveaddress\" (string) a curve address associated with the given account\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressesbyaccount", "\"tabby\"")
+ HelpExampleRpc("getaddressesbyaccount", "\"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
UniValue ret(UniValue::VARR);
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, bool fUseInstantSend=false, bool fUsePrivateSend=false)
{
CAmount curBalance = pwalletMain->GetBalance();
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > curBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
if (pwalletMain->GetBroadcastTransactions() && !g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
// Parse Curve address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
std::string strError;
vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet,
strError, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend)) {
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey, g_connman.get(), fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
UniValue sendtoaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 7)
throw runtime_error(
"sendtoaddress \"curveaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount use_is use_ps )\n"
"\nSend an amount to a given address.\n"
+ HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"curveaddress\" (string, required) The curve address to send to.\n"
"2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less amount of Curve than you enter in the amount field.\n"
"6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n"
"7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1")
+ HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"\" \"\" true")
+ HelpExampleRpc("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Curve address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (params.size() > 4)
fSubtractFeeFromAmount = params[4].get_bool();
bool fUseInstantSend = false;
bool fUsePrivateSend = false;
if (params.size() > 5)
fUseInstantSend = params[5].get_bool();
if (params.size() > 6)
fUsePrivateSend = params[6].get_bool();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, fUseInstantSend, fUsePrivateSend);
return wtx.GetHash().GetHex();
}
UniValue instantsendtoaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 5)
throw runtime_error(
"instantsendtoaddress \"curveaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n"
+ HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"curveaddress\" (string, required) The curve address to send to.\n"
"2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less amount of Curve than you enter in the amount field.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1")
+ HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"\" \"\" true")
+ HelpExampleRpc("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Curve address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (params.size() > 4)
fSubtractFeeFromAmount = params[4].get_bool();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, true);
return wtx.GetHash().GetHex();
}
UniValue listaddressgroupings(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"curveaddress\", (string) The curve address\n"
" amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"account\" (string, optional) The account (DEPRECATED)\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listaddressgroupings", "")
+ HelpExampleRpc("listaddressgroupings", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
UniValue jsonGrouping(UniValue::VARR);
BOOST_FOREACH(CTxDestination address, grouping)
{
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
UniValue signmessage(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage \"curveaddress\" \"message\"\n"
"\nSign a message with the private key of an address"
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"curveaddress\" (string, required) The curve address to use for the private key.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"my message\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
UniValue getreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"getreceivedbyaddress \"curveaddress\" ( minconf addlockconf )\n"
"\nReturns the total amount received by the given curveaddress in transactions with specified minimum number of confirmations.\n"
"\nArguments:\n"
"1. \"curveaddress\" (string, required) The curve address for transactions.\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n"
+ HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Curve address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Curve address");
CScript scriptPubKey = GetScriptForDestination(address.Get());
if (!IsMine(*pwalletMain, scriptPubKey))
return ValueFromAmount(0);
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
bool fAddLockConf = (params.size() > 2 && params[2].get_bool());
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
UniValue getreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"getreceivedbyaccount \"account\" ( minconf addlockconf )\n"
"\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with specified minimum number of confirmations.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nAmount received by the default account with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaccount", "\"\"") +
"\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
bool fAddLockConf = (params.size() > 2 && params[2].get_bool());
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth)
nAmount += txout.nValue;
}
}
return ValueFromAmount(nAmount);
}
CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf)
{
CAmount nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain(fAddLockConf) < 0)
continue;
CAmount nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
if (nReceived != 0 && wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth, filter, fAddLockConf);
}
UniValue getbalance(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"getbalance ( \"account\" minconf addlockconf includeWatchonly )\n"
"\nIf account is not specified, returns the server's total available balance.\n"
"If account is specified (DEPRECATED), returns the balance in the account.\n"
"Note that the account \"\" is not the same as leaving the parameter out.\n"
"The server total may be different to the balance in the default \"\" account.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"4. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nThe total amount in the wallet\n"
+ HelpExampleCli("getbalance", "") +
"\nThe total amount in the wallet at least 5 blocks confirmed\n"
+ HelpExampleCli("getbalance", "\"*\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getbalance", "\"*\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
bool fAddLockConf = (params.size() > 2 && params[2].get_bool());
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 3)
if(params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and "getbalance * 1 true" should return the same number
CAmount nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
nBalance += r.amount;
}
BOOST_FOREACH(const COutputEntry& s, listSent)
nBalance -= s.amount;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter, fAddLockConf);
return ValueFromAmount(nBalance);
}
UniValue getunconfirmedbalance(const UniValue ¶ms, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw runtime_error(
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
LOCK2(cs_main, pwalletMain->cs_wallet);
return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
}
UniValue movecmd(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
"\nExamples:\n"
"\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n"
+ HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
"\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n"
+ HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
pwalletMain->AddAccountingEntry(debit, walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
pwalletMain->AddAccountingEntry(credit, walletdb);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
UniValue sendfrom(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 7)
throw runtime_error(
"sendfrom \"fromaccount\" \"tocurveaddress\" amount ( minconf addlockconf \"comment\" \"comment-to\" )\n"
"\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a curve address."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
"2. \"tocurveaddress\" (string, required) The curve address to send funds to.\n"
"3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"6. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"7. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the transaction, \n"
" it is just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
"\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n"
+ HelpExampleCli("sendfrom", "\"\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01") +
"\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n"
+ HelpExampleCli("sendfrom", "\"tabby\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01 6 false \"donation\" \"seans outpost\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendfrom", "\"tabby\", \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.01, 6, false, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Curve address");
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
bool fAddLockConf = (params.size() > 4 && params[4].get_bool());
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty())
wtx.mapValue["comment"] = params[5].get_str();
if (params.size() > 6 && !params[6].isNull() && !params[6].get_str().empty())
wtx.mapValue["to"] = params[6].get_str();
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
SendMoney(address.Get(), nAmount, false, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendmany(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 8)
throw runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf addlockconf \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n"
"2. \"amounts\" (string, required) A json object with addresses and amounts\n"
" {\n"
" \"address\":amount (numeric or string) The curve address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n"
" ,...\n"
" }\n"
"3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
"4. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"5. \"comment\" (string, optional) A comment\n"
"6. subtractfeefromamount (string, optional) A json array with addresses.\n"
" The fee will be equally deducted from the amount of each selected address.\n"
" Those recipients will receive less curves than you enter in their corresponding amount field.\n"
" If no addresses are specified here, the sender pays the fee.\n"
" [\n"
" \"address\" (string) Subtract fee from this address\n"
" ,...\n"
" ]\n"
"7. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n"
"8. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
"\nExamples:\n"
"\nSend two amounts to two different addresses:\n"
+ HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n"
+ HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\" 6 false \"testing\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\", 6, false, \"testing\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (pwalletMain->GetBroadcastTransactions() && !g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
string strAccount = AccountFromValue(params[0]);
UniValue sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
bool fAddLockConf = (params.size() > 3 && params[3].get_bool());
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
if (params.size() > 5)
subtractFeeFromAmount = params[5].get_array();
set<CBitcoinAddress> setAddress;
vector<CRecipient> vecSend;
CAmount totalAmount = 0;
vector<string> keys = sendTo.getKeys();
BOOST_FOREACH(const string& name_, keys)
{
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Curve address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
totalAmount += nAmount;
bool fSubtractFeeFromAmount = false;
for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
const UniValue& addr = subtractFeeFromAmount[idx];
if (addr.get_str() == name_)
fSubtractFeeFromAmount = true;
}
CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
string strFailReason;
bool fUseInstantSend = false;
bool fUsePrivateSend = false;
if (params.size() > 6)
fUseInstantSend = params[6].get_bool();
if (params.size() > 7)
fUsePrivateSend = params[7].get_bool();
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason,
NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange, g_connman.get(), fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
// Defined in rpc/misc.cpp
extern CScript _createmultisig_redeemScript(const UniValue& params);
UniValue addmultisigaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a Curve address or hex-encoded public key.\n"
"If 'account' is specified (DEPRECATED), assign address to that account.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keysobject\" (string, required) A json array of curve addresses or hex-encoded public keys\n"
" [\n"
" \"address\" (string) curve address or hex-encoded public key\n"
" ...,\n"
" ]\n"
"3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n"
"\nResult:\n"
"\"curveaddress\" (string) A curve address associated with the keys.\n"
"\nExamples:\n"
"\nAdd a multisig address from 2 addresses\n"
+ HelpExampleCli("addmultisigaddress", "2 \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") +
"\nAs json rpc call\n"
+ HelpExampleRpc("addmultisigaddress", "2, \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"")
;
throw runtime_error(msg);
}
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
CAmount nAmount;
int nConf;
vector<uint256> txids;
bool fIsWatchonly;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
fIsWatchonly = false;
}
};
UniValue ListReceived(const UniValue& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
bool fAddLockConf = (params.size() > 1 && params[1].get_bool());
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 2)
fIncludeEmpty = params[2].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 3)
if(params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain(fAddLockConf);
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
isminefilter mine = IsMine(*pwalletMain, address);
if(!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
UniValue ret(UniValue::VARR);
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second.name;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
isminefilter mine = IsMine(*pwalletMain, address.Get());
if(!(mine & filter))
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
item.fIsWatchonly = fIsWatchonly;
}
else
{
UniValue obj(UniValue::VOBJ);
if(fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
if (!fByAccounts)
obj.push_back(Pair("label", strAccount));
UniValue transactions(UniValue::VARR);
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
UniValue obj(UniValue::VOBJ);
if((*it).second.fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
UniValue listreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"listreceivedbyaddress ( minconf addlockconf includeempty includeWatchonly)\n"
"\nList balances by receiving address.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"3. includeempty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n"
"4. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n"
" \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included.\n"
" If 'addlockconf' is true, the minimum number of confirmations is calculated\n"
" including additional " + std::to_string(nInstantSendDepth) + " confirmations for transactions locked via InstantSend\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaddress", "")
+ HelpExampleCli("listreceivedbyaddress", "6 false true")
+ HelpExampleRpc("listreceivedbyaddress", "6, false, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, false);
}
UniValue listreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"listreceivedbyaccount ( minconf addlockconf includeempty includeWatchonly)\n"
"\nDEPRECATED. List balances by account.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"3. includeempty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n"
"4. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"account\" : \"accountname\", (string) The account name of the receiving account\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
" \"confirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaccount", "")
+ HelpExampleCli("listreceivedbyaccount", "6 false true")
+ HelpExampleRpc("listreceivedbyaccount", "6, false, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, true);
}
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
{
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const COutputEntry& s, listSent)
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.destination);
std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("DS");
entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "privatesend" : "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
if (pwalletMain->mapAddressBook.count(s.destination))
entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name));
entry.push_back(Pair("vout", s.vout));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
entry.push_back(Pair("abandoned", wtx.isAbandoned()));
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.destination))
account = pwalletMain->mapAddressBook[r.destination].name;
if (fAllAccounts || (account == strAccount))
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
if (pwalletMain->mapAddressBook.count(r.destination))
entry.push_back(Pair("label", account));
entry.push_back(Pair("vout", r.vout));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
UniValue listtransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"listtransactions ( \"account\" count from includeWatchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n"
"2. count (numeric, optional, default=10) The number of transactions to return\n"
"3. from (numeric, optional, default=0) The number of transactions to skip\n"
"4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"[\n"
" {\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n"
" It will be \"\" for the default account.\n"
" \"address\":\"curveaddress\", (string) The curve address of the transaction. Not present for \n"
" move transactions (category = move).\n"
" \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
" transaction between accounts, and not associated with an address,\n"
" transaction id or block. 'send' and 'receive' transactions are \n"
" associated with an address, transaction id and block details\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n"
" 'move' category for moves outbound. It is positive for the 'receive' category,\n"
" and for the 'move' category for inbound funds.\n"
" \"vout\": n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"instantlock\" : true|false, (bool) Current transaction lock state. Available for 'send' and 'receive' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions. Negative confirmations indicate the\n"
" transation conflicts with the block chain\n"
" \"trusted\": xxx (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
" for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\": \"label\" (string) A comment for the address/transaction, if any\n"
" \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n"
" from (for receiving funds, positive amounts), or went to (for sending funds,\n"
" negative amounts).\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" }\n"
"]\n"
"\nExamples:\n"
"\nList the most recent 10 transactions in the systems\n"
+ HelpExampleCli("listtransactions", "") +
"\nList transactions 100 to 120\n"
+ HelpExampleCli("listtransactions", "\"*\" 20 100") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listtransactions", "\"*\", 20, 100")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 3)
if(params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
UniValue ret(UniValue::VARR);
const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered;
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
vector<UniValue> arrTmp = ret.getValues();
vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom);
vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
ret.clear();
ret.setArray();
ret.push_backV(arrTmp);
return ret;
}
UniValue listaccounts(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listaccounts ( minconf addlockconf includeWatchonly)\n"
"\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
"2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n"
"3. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"{ (json object where keys are account names, and values are numeric balances\n"
" \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
" ...\n"
"}\n"
"\nExamples:\n"
"\nList account balances where there at least 1 confirmation\n"
+ HelpExampleCli("listaccounts", "") +
"\nList account balances including zero confirmation transactions\n"
+ HelpExampleCli("listaccounts", "0") +
"\nList account balances for 6 or more confirmations\n"
+ HelpExampleCli("listaccounts", "6") +
"\nAs json rpc call\n"
+ HelpExampleRpc("listaccounts", "6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
bool fAddLockConf = (params.size() > 1 && params[1].get_bool());
isminefilter includeWatchonly = ISMINE_SPENDABLE;
if(params.size() > 2)
if(params[2].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
map<string, CAmount> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain(fAddLockConf);
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const COutputEntry& s, listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.destination))
mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
else
mapAccountBalances[""] += r.amount;
}
}
const list<CAccountingEntry> & acentries = pwalletMain->laccentries;
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ);
BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
UniValue listsinceblock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw runtime_error(
"listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n"
"1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
"2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n"
"3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
"\nResult:\n"
"{\n"
" \"transactions\": [\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n"
" \"address\":\"curveaddress\", (string) The curve address of the transaction. Not present for move transactions (category = move).\n"
" \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n"
" outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n"
" \"instantlock\" : true|false, (bool) Current transaction lock state. Available for 'send' and 'receive' category of transactions.\n"
" \"confirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("listsinceblock", "")
+ HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
+ HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBlockIndex *pindex = NULL;
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 0)
{
uint256 blockId;
blockId.SetHex(params[0].get_str());
BlockMap::iterator it = mapBlockIndex.find(blockId);
if (it != mapBlockIndex.end())
pindex = it->second;
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid blockhash");
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
UniValue transactions(UniValue::VARR);
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain(false) < depth)
ListTransactions(tx, "*", 0, true, transactions, filter);
}
CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256();
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
UniValue gettransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"gettransaction \"txid\" ( includeWatchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
"\nResult:\n"
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
" \"instantlock\" : true|false, (bool) Current transaction lock state\n"
" \"confirmations\" : n, (numeric) The number of blockchain confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"curveaddress\", (string) The curve address involved in the transaction\n"
" \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
" \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
" \"vout\" : n, (numeric) the vout value\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
+ HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 1)
if(params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
UniValue entry(UniValue::VOBJ);
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe(filter))
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
UniValue details(UniValue::VARR);
ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex));
return entry;
}
UniValue abandontransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"abandontransaction \"txid\"\n"
"\nMark in-wallet transaction <txid> as abandoned\n"
"This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
"for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n"
"It only works on transactions which are not included in a block and are not currently in the mempool.\n"
"It has no effect on transactions which are already conflicted or abandoned.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
if (!pwalletMain->AbandonTransaction(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
return NullUniValue;
}
UniValue backupwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet \"destination\"\n"
"\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n"
"1. \"destination\" (string) The destination directory or file\n"
"\nExamples:\n"
+ HelpExampleCli("backupwallet", "\"backup.dat\"")
+ HelpExampleRpc("backupwallet", "\"backup.dat\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return NullUniValue;
}
UniValue keypoolrefill(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill ( newsize )\n"
"\nFills the keypool."
+ HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. newsize (numeric, optional, default=" + itostr(DEFAULT_KEYPOOL_SIZE) + ") The new keypool size\n"
"\nExamples:\n"
+ HelpExampleCli("keypoolrefill", "")
+ HelpExampleRpc("keypoolrefill", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < (pwalletMain->IsHDEnabled() ? kpSize * 2 : kpSize))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return NullUniValue;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
UniValue walletpassphrase(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase \"passphrase\" timeout ( mixingonly )\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending curves\n"
"\nArguments:\n"
"1. \"passphrase\" (string, required) The wallet passphrase\n"
"2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
"3. mixingonly (boolean, optional, default=false) If is true sending functions are disabled."
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one.\n"
"\nExamples:\n"
"\nUnlock the wallet for 60 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nUnlock the wallet for 60 seconds but allow PrivateSend mixing only\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") +
"\nLock the wallet again (before 60 seconds)\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
int64_t nSleepTime = params[1].get_int64();
bool fForMixingOnly = false;
if (params.size() >= 3)
fForMixingOnly = params[2].get_bool();
if (fForMixingOnly && !pwalletMain->IsLocked(true) && pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked for mixing only.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already fully unlocked.");
if (!pwalletMain->Unlock(strWalletPass, fForMixingOnly))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
pwalletMain->TopUpKeyPool();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
return NullUniValue;
}
UniValue walletpassphrasechange(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n"
"1. \"oldpassphrase\" (string) The current passphrase\n"
"2. \"newpassphrase\" (string) The new passphrase\n"
"\nExamples:\n"
+ HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
+ HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return NullUniValue;
}
UniValue walletlock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n"
"\nExamples:\n"
"\nSet the passphrase for 2 minutes to perform a transaction\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n"
+ HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletlock", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return NullUniValue;
}
UniValue encryptwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n"
"Note that this will shutdown the server.\n"
"\nArguments:\n"
"1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
"\nExamples:\n"
"\nEncrypt you wallet\n"
+ HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending curve\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can so something like sign\n"
+ HelpExampleCli("signmessage", "\"curveaddress\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n"
+ HelpExampleCli("walletlock", "") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "Wallet encrypted; Curve Core server stopping, restart to run with encrypted wallet. The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup.";
}
UniValue lockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending curves.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n"
"\nArguments:\n"
"1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
"2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
" [ (json array of json objects)\n"
" {\n"
" \"txid\":\"id\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"true|false (boolean) Whether the command was successful or not\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 1)
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL));
else
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
UniValue outputs = params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
if (!output.isObject())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const UniValue& o = output.get_obj();
RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256S(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
UniValue listlockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listlockunspent", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR);
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
UniValue settxfee(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee amount\n"
"\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n"
"\nArguments:\n"
"1. amount (numeric or sting, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n"
"\nResult\n"
"true|false (boolean) Returns true if successful\n"
"\nExamples:\n"
+ HelpExampleCli("settxfee", "0.00001")
+ HelpExampleRpc("settxfee", "0.00001")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Amount
CAmount nAmount = AmountFromValue(params[0]);
payTxFee = CFeeRate(nAmount, 1000);
return true;
}
UniValue getwalletinfo(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw runtime_error(
"getwalletinfo\n"
"Returns an object containing various wallet state info.\n"
"\nResult:\n"
"{\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n"
" \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n"
" \"keys_left\": xxxx, (numeric) how many new keys are left since last automatic backup\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
" \"hdchainid\": \"<hash>\", (string) the ID of the HD chain\n"
" \"hdaccountcount\": xxx, (numeric) how many accounts of the HD chain are in this wallet\n"
" [\n"
" {\n"
" \"hdaccountindex\": xxx, (numeric) the index of the account\n"
" \"hdexternalkeyindex\": xxxx, (numeric) current external childkey index\n"
" \"hdinternalkeyindex\": xxxx, (numeric) current internal childkey index\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getwalletinfo", "")
+ HelpExampleRpc("getwalletinfo", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CHDChain hdChainCurrent;
bool fHDEnabled = pwalletMain->GetHDChain(hdChainCurrent);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance())));
obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance())));
obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size()));
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int64_t)pwalletMain->KeypoolCountExternalKeys()));
if (fHDEnabled) {
obj.push_back(Pair("keypoolsize_hd_internal", (int64_t)(pwalletMain->KeypoolCountInternalKeys())));
}
obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
if (fHDEnabled) {
obj.push_back(Pair("hdchainid", hdChainCurrent.GetID().GetHex()));
obj.push_back(Pair("hdaccountcount", (int64_t)hdChainCurrent.CountAccounts()));
UniValue accounts(UniValue::VARR);
for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i)
{
CHDAccount acc;
UniValue account(UniValue::VOBJ);
account.push_back(Pair("hdaccountindex", (int64_t)i));
if(hdChainCurrent.GetAccount(i, acc)) {
account.push_back(Pair("hdexternalkeyindex", (int64_t)acc.nExternalChainCounter));
account.push_back(Pair("hdinternalkeyindex", (int64_t)acc.nInternalChainCounter));
} else {
account.push_back(Pair("error", strprintf("account %d is missing", i)));
}
accounts.push_back(account);
}
obj.push_back(Pair("hdaccounts", accounts));
}
return obj;
}
UniValue keepass(const UniValue& params, bool fHelp) {
string strCommand;
if (params.size() >= 1)
strCommand = params[0].get_str();
if (fHelp ||
(strCommand != "genkey" && strCommand != "init" && strCommand != "setpassphrase"))
throw runtime_error(
"keepass <genkey|init|setpassphrase>\n");
if (strCommand == "genkey")
{
SecureString sResult;
// Generate RSA key
SecureString sKey = CKeePassIntegrator::generateKeePassKey();
sResult = "Generated Key: ";
sResult += sKey;
return sResult.c_str();
}
else if(strCommand == "init")
{
// Generate base64 encoded 256 bit RSA key and associate with KeePassHttp
SecureString sResult;
SecureString sKey;
std::string strId;
keePassInt.rpcAssociate(strId, sKey);
sResult = "Association successful. Id: ";
sResult += strId.c_str();
sResult += " - Key: ";
sResult += sKey.c_str();
return sResult.c_str();
}
else if(strCommand == "setpassphrase")
{
if(params.size() != 2) {
return "setlogin: invalid number of parameters. Requires a passphrase";
}
SecureString sPassphrase = SecureString(params[1].get_str().c_str());
keePassInt.updatePassphrase(sPassphrase);
return "setlogin: Updated credentials.";
}
return "Invalid command";
}
UniValue resendwallettransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw runtime_error(
"resendwallettransactions\n"
"Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
"Intended only for testing; the wallet code periodically re-broadcasts\n"
"automatically.\n"
"Returns array of transaction ids that were re-broadcast.\n"
);
if (!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
LOCK2(cs_main, pwalletMain->cs_wallet);
std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime(), g_connman.get());
UniValue result(UniValue::VARR);
BOOST_FOREACH(const uint256& txid, txids)
{
result.push_back(txid.ToString());
}
return result;
}
UniValue listunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of curve addresses to filter\n"
" [\n"
" \"address\" (string) curve address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the curve address\n"
" \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" \"ps_rounds\" : n (numeric) The number of PS round\n"
" \"spendable\" : xxx, (bool) Whether we have the private keys to spend this output\n"
" \"solvable\" : xxx (bool) Whether we know how to spend this output, ignoring the lack of keys\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "6 9999999 \"[\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"")
+ HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2) {
UniValue inputs = params[2].get_array();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Curve address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
UniValue results(UniValue::VARR);
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->AvailableCoins(vecOutputs, false, NULL, true);
BOOST_FOREACH(const COutput& out, vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
entry.push_back(Pair("ps_rounds", pwalletMain->GetOutpointPrivateSendRounds(COutPoint(out.tx->GetHash(), out.i))));
entry.push_back(Pair("spendable", out.fSpendable));
entry.push_back(Pair("solvable", out.fSolvable));
results.push_back(entry);
}
return results;
}
UniValue fundrawtransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"fundrawtransaction \"hexstring\" includeWatching\n"
"\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
"This will not modify existing inputs, and will add one change output to the outputs.\n"
"Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
"The inputs added will not be signed, use signrawtransaction for that.\n"
"Note that all existing inputs must have their previous output transaction be in the wallet.\n"
"Note that all inputs selected must be of standard form and P2SH scripts must be"
"in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
"You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
"Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction\n"
"2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n"
" \"fee\": n, (numeric) Fee the resulting transaction pays\n"
" \"changepos\": n (numeric) The position of the added change output, or -1\n"
"}\n"
"\"hex\" \n"
"\nExamples:\n"
"\nCreate a transaction with no inputs\n"
+ HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
"\nAdd sufficient unsigned inputs to meet the output value\n"
+ HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
"\nSign the transaction\n"
+ HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") +
"\nSend the transaction\n"
+ HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction origTx;
if (!DecodeHexTx(origTx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
if (origTx.vout.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
bool includeWatching = false;
if (params.size() > 1)
includeWatching = params[1].get_bool();
CMutableTransaction tx(origTx);
CAmount nFee;
string strFailReason;
int nChangePos = -1;
if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching))
throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(tx)));
result.push_back(Pair("changepos", nChangePos));
result.push_back(Pair("fee", ValueFromAmount(nFee)));
return result;
}
|
/**
* > Author: UncP
* > Github: www.github.com/UncP/Mushroom
* > License: BSD-3
* > Time: 2017-04-25 22:11:01
**/
#ifndef _CONNECTION_HPP_
#define _CONNECTION_HPP_
#include "../include/utility.hpp"
#include "callback.hpp"
#include "socket.hpp"
#include "endpoint.hpp"
#include "buffer.hpp"
namespace Mushroom {
class Channel;
class Poller;
class Connection : private NoCopy
{
public:
Connection(const Socket &socket, Poller *poller);
Connection(const EndPoint &server, Poller *poller);
virtual ~Connection();
bool Success() const;
Buffer& GetInput();
Buffer& GetOutput();
void HandleRead();
void HandleWrite();
void OnRead(const ReadCallBack &readcb);
void OnWrite(const WriteCallBack &writecb);
bool Close();
void Send(const char *str);
void Send(Buffer &buffer);
void Send(const char *str, uint32_t len);
void SendOutput();
protected:
Socket socket_;
bool connected_;
Channel *channel_;
Buffer input_;
Buffer output_;
ReadCallBack readcb_;
WriteCallBack writecb_;
};
} // namespace Mushroom
#endif /* _CONNECTION_HPP_ */
|
/**
* File : virtual_secure_popc_search_node.cc
* Author : Clement Valentin (clementval)
* Description : Implementation file of the Secure POP-C++ Search Node (resources discovery)
* Creation date : 2010/12/07
*
* Modifications :
* Authors Date Description
* clementval 2010/12/07 Creation of the virtual version of the PSN
*/
#include "secure_popc_search_node.ph"
#include "secure_jobmgr.ph"
#include "popc_security_manager.ph"
#include "nodethread.h"
using namespace std;
/**
* ViSaG : clementval
* Secure POPCSearchNode's constructor
* @param challenge Challenge string used to stop the services
* @param deamon If TRUE, the parallel object will run in deamon mode
*/
SecurePOPCSearchNode::SecurePOPCSearchNode(const paroc_string &challenge,
bool deamon) : POPCSearchNode(challenge, deamon) {
popc_node_log("SecurePOPCSearchNode Created ...");
}
/**
* ViSaG : clementval
* Destructor of SecurePOPCSearchNode
*/
SecurePOPCSearchNode::~SecurePOPCSearchNode(){
popc_node_log("SecurePOPCSearchNode destroyed ...");
}
/**
* ViSaG : clementval
* Setter for the local POPCSecurityNode reference
* @param The local reference of the PSM
*/
void SecurePOPCSearchNode::setPSMRef(paroc_accesspoint psm){
_localPSM = psm;
}
/**
* ViSaG : clementval
* Getter for the local POPCSecurityManager reference
* @return The local reference to the PSM
*/
paroc_accesspoint SecurePOPCSearchNode::getPSMRef(){
return _localPSM;
}
/**
* ViSaG : clementval
* Set the PKI to the node info
* @param pk The PKI
*/
void SecurePOPCSearchNode::setPKI(POPString pk){
nodeInfo.pki=pk;
}
/**
* ViSaG : clementval
* Get the PKI to the node info
* @return The PKI
*/
POPString SecurePOPCSearchNode::getPKI(){
return nodeInfo.pki;
}
/*
* OVERWRITTEN METHOD
*/
// Service's entry point for resources discovery. This method will return an
// object of type "POPCSearchNodeInfos" containing information about nodes which fit the
// request
POPCSearchNodeInfos SecurePOPCSearchNode::launchDiscovery(Request req, int timeout){
gettimeofday(&start, NULL); //This line is just for test purpose so it can be removed in production release
//Log
sprintf(log, "[SPSN] LDISCOVERY;TIMEOUT;%d", timeout);
popc_node_log(log);
//Add the main PKI in the request
POPCSecurityManager psm(_localPSM);
paroc_string mainPKI = psm.getMainPKIFromMapping(req.getPOPAppId());
if(strcmp(mainPKI, "") == 0){
popc_node_log("SET_SAME_KEY");
req.setMainPKI(req.getPKI());
} else {
popc_node_log("SET_KEY_FROM_MAPPING");
req.setMainPKI(mainPKI);
}
//Add the mapping to the main PSM AP
psm.addMainAPMapping(req.getPOPAppId(), _localPSM);
if(req.isEndRequest())
timeout = 1;
// create a new unique request id with the name of the node and its
// logical clock. This uniqueId is added to the request
char uId[MAXREQUNIQUEIDLENGTH];
sprintf(uId,"%s__%d", getPOPCSearchNodeId().GetString(), logicalClock);
POPString uniqueId(uId);
req.setUniqueId(uniqueId);
logicalClock++;
// "network" self-reference to current node for callback results
// prepare results place for current request in the currently running
// request's list.
POPCSearchNodeInfos nInfos;
actualReqSyn.lock();
actualReq[req.getUniqueId()] = nInfos;
actualReqSyn.unlock();
// begin resources discovery locally
askResourcesDiscovery(req, GetAccessPoint(), GetAccessPoint(), _localPSM);
// wait until timeout
if(timeout == 0){
sem_init(pt_locker, 0, 0);
NodeThread *timer = new NodeThread(UNLOCK_TIMEOUT, GetAccessPoint());
timer->create();
sem_wait(pt_locker);
timer->stop();
popc_node_log("Unlocker timer started ...");
} else {
sleep(timeout);
}
// getting results for current request and construct of POPCSearchNodeInfos object
actualReqSyn.lock();
POPCSearchNodeInfos results;
map<paroc_string, POPCSearchNodeInfos>::iterator i;
// ! for-statement because of problem with map comparison and paroc_string !
for(i=actualReq.begin(); i != actualReq.end(); i++){
paroc_string id = (*i).first;
if(strcmp(id.GetString(), req.getUniqueId().GetString()) == 0){
results = i->second;
break;
}
}
// erase the place for this request disallowing adding more results for this
// request in the future
actualReq.erase(req.getUniqueId());
actualReqSyn.unlock();
sprintf(log, "RESULTS;%d", results.getNodeInfos().size());
popc_node_log(log);
return results;
}
// POPCSearchNode's entry point to propagate request in the grid
// asker is the node which will receive positiv result
void SecurePOPCSearchNode::askResourcesDiscovery(Request req, paroc_accesspoint node_ap, paroc_accesspoint sender, paroc_accesspoint _psm){
popc_node_log("[SPSN] Ask resource discovery");
if(req.isEndRequest()){
popc_node_log("[SPSN] Recieve application end request");
ExplorationList oldEL(req.getExplorationList());
// Adding the node's neighbors in the exploration list
req.addNodeToExplorationList(getPOPCSearchNodeId(), getNeighbors());
if(req.getMaxHops() >= 0 || req.getMaxHops() == UNLIMITED_HOPS){
list<POPCSearchNode *>::iterator i;
// check if the local neighbors are already asked with the originally
// received exploration list
for(i = neighborsList.begin(); i != neighborsList.end(); i++){
if(!oldEL.isIn((*i)->getPOPCSearchNodeId())){
paroc_string nid;
nid = (*i)->getPOPCSearchNodeId();
sprintf(log, "FORWARD;DEST;%s", nid.GetString());
popc_node_log(log);
(*i)->askResourcesDiscovery(req, node_ap, GetAccessPoint(), _psm);
}
}
}
JobMgr jmg(getJobMgrRef());
jmg.ApplicationEnd(req.getPOPAppId(), false);
} else {
sprintf(log, "[SPSN] ASKRDISCOVERY;ASKER;%s;REQID;%s", node_ap.GetAccessString(), req.getUniqueId().GetString());
popc_node_log(log);
/**
* ViSaG : clementval
* Add the main PKI in the mapping for future resource discovery from this node
* Add the main PSM AP in the mapping for routing PKI
*/
POPCSecurityManager psm(_localPSM);
psm.addMainPKIMapping(req.getPOPAppId(), req.getMainPKI());
psm.addMainAPMapping(req.getPOPAppId(), _psm);
// check if the request has already been asked
list<paroc_string>::iterator k;
for(k = knownRequests.begin(); k != knownRequests.end(); k++){
if(strcmp(k->GetString(),req.getUniqueId().GetString()) == 0){
sprintf(log, "ALREADY_ASKED_REQUEST;%s", req.getUniqueId().GetString());
popc_node_log(log);
POPCSearchNode nsender(sender);
JobMgr jsender(nsender.getJobMgrRef());
jsender.UnregisterNode(GetAccessPoint());
removeNeighbor(nsender);
return;
}
}
// save current request's uniqueId in the history
knownRequests.push_back(req.getUniqueId());
// check the maximum length of the history
if(knownRequests.size() > MAXREQTOSAVE){
knownRequests.pop_front();
}
// save the received exploration list
ExplorationList oldEL(req.getExplorationList());
// Adding the node's neighbors in the exploration list
req.addNodeToExplorationList(getPOPCSearchNodeId(), getNeighbors());
// Check local resources
bool isResourcesOk = checkResource(req);
sprintf(log, "CHECK;%s", (isResourcesOk)?"OK":"FAILED");
popc_node_log(log);
if(isResourcesOk){
// If local resources are OK, build the response and give it back to
// 'asker' node
Response* resp = new Response(req.getUniqueId(), POPCSearchNodeInfo(nodeInfo), req.getExplorationList(), req.getPOPAppId());
/* If it's the local node or it's the last node, send directly the answer. Otherwise, send to the next node to reroute
the message */
if(!req.getWayBack().isLastNode()){
paroc_string listwb = req.getWayBack().getAsString();
sprintf(log, "NEED_REROUTE;WAYBACK;%s", listwb.GetString());
popc_node_log(log);
rerouteResponse(*resp, req.getWayBack());
} else {
POPCSearchNode asker(node_ap);
sprintf(log, "SEND_REP;DEST;%s", node_ap.GetAccessString());
popc_node_log(log);
asker.callbackResult(*resp);
}
//Add main PKI
popc_node_log("ADD_KEYS_FROM_REQUEST");
POPCSecurityManager psm(_localPSM);
paroc_string mainPki(req.getMainPKI());
paroc_string initPki(req.getPKI());
psm.writePKI(req.getPOPAppId(), mainPki);
if(!(sender == GetAccessPoint())){
psm.writePKI(req.getPOPAppId(), initPki);
}
}
// Continue the propagation if more hops are allowed. It continues if the
// max hops is zero to avoid counting "initial node" discovery.
if(req.getMaxHops() >= 0 || req.getMaxHops() == UNLIMITED_HOPS){
list<POPCSearchNode *>::iterator i;
// check if the local neighbors are already asked with the originally
// received exploration list
for(i = neighborsList.begin(); i != neighborsList.end(); i++){
if(!oldEL.isIn((*i)->getPOPCSearchNodeId())){
paroc_string nid;
nid = (*i)->getPOPCSearchNodeId();
sprintf(log, "FORWARD;DEST;%s", nid.GetString());
popc_node_log(log);
(*i)->askResourcesDiscovery(req, node_ap, GetAccessPoint(), _psm);
}
}
}
}
}
// POPCSearchNode's return point to give back the response to the initial node
void SecurePOPCSearchNode::callbackResult(Response resp){
//Just for test purpose, must be removed in production release
gettimeofday(&end, NULL);
long msec_start;
msec_start = (start.tv_sec)*1000000;
msec_start += (start.tv_usec);
long msec_end;
msec_end = (end.tv_sec)*1000000;
msec_end += (end.tv_usec);
long diff = msec_end-msec_start;
POPCSearchNodeInfo dni = resp.getFoundNodeInfo();
sprintf(log, "RESP;REQID;%s;SENDER;%s;TIME;START;%ld;END;%ld;DIFF;%ld", resp.getReqUniqueId().GetString(),
dni.nodeId.GetString(), msec_start, msec_end, diff);
popc_node_log(log);
//End for test
actualReqSyn.lock();
map<paroc_string, POPCSearchNodeInfos>::iterator i;
// visit the currently running list
for(i=actualReq.begin(); i != actualReq.end(); i++){
paroc_string id = (*i).first;
// if the request's uniqueId is present, add the response to the list
// and break the for-statement.
if(strcmp(id.GetString(), resp.getReqUniqueId().GetString()) == 0){
i->second.addANodeInfo(resp.getFoundNodeInfo());
break;
}
}
actualReqSyn.unlock();
sem_post(pt_locker);
/**
* ViSaG : clementval
* Route the PKI to the Main Node
*/
POPCSecurityManager psm(_localPSM);
psm.reroutePKIToMain(resp.getPOPAppId(), resp.getFoundNodeInfo().getPKI());
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root == NULL) return "null,";
string leftSubtree = serialize(root->left);
string rightSubtree = serialize(root->right);
return to_string(root->val) + "," + leftSubtree + rightSubtree;
}
queue<string> dataToQueue(string data) {
if(data.empty()) return {};
queue<string> q;
int start = 0;
for(int i=0;i<data.size();i++) {
if(data[i] == ',') {
q.push(data.substr(start,i-start));
start = i+1;
}
}
return q;
}
TreeNode* helper(queue<string> &q) {
string f = q.front();
q.pop();
if(f == "null") return NULL;
TreeNode* newNode = new TreeNode(stoi(f));
newNode->left = helper(q);
newNode->right = helper(q);
return newNode;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty()) return NULL;
queue<string> q = dataToQueue(data);
// cout << q.size() << endl;
return helper(q);
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
|
/**
* @file nystroem_method_impl.hpp
* @author Ryan Curtin
* @author Marcus Edel
*
* Implementation of the Nystroem method for approximating a kernel matrix.
*
* 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.
*/
#ifndef MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP
#define MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP
// In case it hasn't been included yet.
#include "nystroem_method.hpp"
namespace mlpack {
namespace kernel {
template<typename KernelType, typename PointSelectionPolicy>
NystroemMethod<KernelType, PointSelectionPolicy>::NystroemMethod(
const arma::mat& data,
KernelType& kernel,
const size_t rank) :
data(data),
kernel(kernel),
rank(rank)
{ }
template<typename KernelType, typename PointSelectionPolicy>
void NystroemMethod<KernelType, PointSelectionPolicy>::GetKernelMatrix(
const arma::mat* selectedData,
arma::mat& miniKernel,
arma::mat& semiKernel)
{
// Assemble mini-kernel matrix.
for (size_t i = 0; i < rank; ++i)
for (size_t j = 0; j < rank; ++j)
miniKernel(i, j) = kernel.Evaluate(selectedData->col(i),
selectedData->col(j));
// Construct semi-kernel matrix with interactions between selected data and
// all points.
for (size_t i = 0; i < data.n_cols; ++i)
for (size_t j = 0; j < rank; ++j)
semiKernel(i, j) = kernel.Evaluate(data.col(i),
selectedData->col(j));
// Clean the memory.
delete selectedData;
}
template<typename KernelType, typename PointSelectionPolicy>
void NystroemMethod<KernelType, PointSelectionPolicy>::GetKernelMatrix(
const arma::Col<size_t>& selectedPoints,
arma::mat& miniKernel,
arma::mat& semiKernel)
{
// Assemble mini-kernel matrix.
for (size_t i = 0; i < rank; ++i)
{
for (size_t j = 0; j < rank; ++j)
{
miniKernel(i, j) = kernel.Evaluate(data.col(selectedPoints(i)),
data.col(selectedPoints(j)));
}
}
// Construct semi-kernel matrix with interactions between selected points and
// all points.
for (size_t i = 0; i < data.n_cols; ++i)
for (size_t j = 0; j < rank; ++j)
semiKernel(i, j) = kernel.Evaluate(data.col(i),
data.col(selectedPoints(j)));
}
template<typename KernelType, typename PointSelectionPolicy>
void NystroemMethod<KernelType, PointSelectionPolicy>::Apply(arma::mat& output)
{
arma::mat miniKernel(rank, rank);
arma::mat semiKernel(data.n_cols, rank);
GetKernelMatrix(PointSelectionPolicy::Select(data, rank), miniKernel,
semiKernel);
// Singular value decomposition mini-kernel matrix.
arma::mat U, V;
arma::vec s;
arma::svd(U, s, V, miniKernel);
// Construct the output matrix. We need to have special handling when
// miniKernel ended up being low-rank.
arma::mat normalization = arma::diagmat(1.0 / sqrt(s));
for (size_t i = 0; i < s.n_elem; ++i)
if (std::abs(s[i]) <= 1e-20)
normalization(i, i) = 0.0;
output = semiKernel * U * normalization * V;
}
} // namespace kernel
} // namespace mlpack
#endif
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_console_popen_84_goodG2B.cpp
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-84_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: console Read input from the console
* GoodSource: Fixed string
* Sinks: popen
* BadSink : Execute command in data using popen()
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE78_OS_Command_Injection__wchar_t_console_popen_84.h"
/* define POPEN as _popen on Windows and popen otherwise */
#ifdef _WIN32
#define POPEN _wpopen
#define PCLOSE _pclose
#else /* NOT _WIN32 */
#define POPEN popen
#define PCLOSE pclose
#endif
namespace CWE78_OS_Command_Injection__wchar_t_console_popen_84
{
CWE78_OS_Command_Injection__wchar_t_console_popen_84_goodG2B::CWE78_OS_Command_Injection__wchar_t_console_popen_84_goodG2B(wchar_t * dataCopy)
{
data = dataCopy;
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
}
CWE78_OS_Command_Injection__wchar_t_console_popen_84_goodG2B::~CWE78_OS_Command_Injection__wchar_t_console_popen_84_goodG2B()
{
{
FILE *pipe;
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
pipe = POPEN(data, L"w");
if (pipe != NULL)
{
PCLOSE(pipe);
}
}
}
}
#endif /* OMITGOOD */
|
/*
******************************************************************************
* $RCSfile: mdp_allo.cpp,v $
* $Author: hkmoffa $
* $Date: 2004/08/27 20:08:10 $
* $Revision: 1.3 $
* $Name: HEAD $
******************************************************************************
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <new>
#include <stdarg.h>
#include "mdp_allo.h"
/*
* Allocate global storage for 2 debugging ints that are used in IO of
* error information.
*/
#ifdef MDP_MPDEBUGIO
int MDP_MP_Nprocs = 1;
int MDP_MP_myproc = 0;
#endif
/*
* Error Handling
* 7 print and exit
* 6 exit
* 5 print and create a divide by zero for stack trace analysis.
* 4 create a divide by zero for stack trace analysis.
* 3 print a message and throw the bad_alloc exception.
* 2 throw the bad_alloc exception and be quite
* 1 print a message and return from package with the NULL pointer
* 0 Keep completely silent about the matter and return with
* a null pointer.
*
* -> Right now, the only way to change this option is to right here
*/
int MDP_ALLO_errorOption = 3;
#ifndef MIN
# define MIN(x,y) (( (x) < (y) ) ? (x) : (y))
#endif
#ifndef MAX
# define MAX(x,y) (( (x) > (y) ) ? (x) : (y))
#endif
#define MDP_ALLOC_INTERFACE_ERROR -230346
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
static void mdp_alloc_eh(const char *rname, int bytes)
/*************************************************************************
*
* mdp_alloc_eh:
*
* Error Handling
* 7 print and exit
* 6 exit
* 5 print and create a divide by zero for stack trace analysis.
* 4 create a divide by zero for stack trace analysis.
* 3 print a message and throw the bad_alloc exception.
* 2 throw the bad_alloc exception and be quite
* 1 print a message and return from package with the NULL pointer
* 0 Keep completely silent about the matter and return with
* a null pointer.
**************************************************************************/
{
double cd = 0.0;
static char mesg[64];
if (bytes == MDP_ALLOC_INTERFACE_ERROR) {
#ifdef MDP_MPDEBUGIO
sprintf(mesg,"MDP_ALLOC Interface ERROR P_%d: %s", MDP_MP_my_proc,
rname);
#else
sprintf(mesg,"MDP_ALLOC Interface ERROR: %s", rname);
#endif
} else {
sprintf(mesg,"%s ERROR: out of memory while mallocing %d bytes",
rname, bytes);
}
if (MDP_ALLO_errorOption % 2 == 1) {
fprintf(stderr, "\n%s", mesg);
#ifdef MDP_MPDEBUGIO
if (MDP_MP_Nprocs > 1) {
fprintf(stderr,": proc = %d\n", MDP_MP_myproc);
} else {
fprintf(stderr,"\n");
}
#else
fprintf(stderr,"\n");
#endif
}
fflush(stderr);
if (MDP_ALLO_errorOption == 2 || MDP_ALLO_errorOption == 3) {
throw std::bad_alloc();
}
if (MDP_ALLO_errorOption == 4 || MDP_ALLO_errorOption == 5) cd = 1.0 / cd;
if (MDP_ALLO_errorOption > 5) exit(-1);
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
static void mdp_alloc_eh2(const char * rname)
/*************************************************************************
*
* mdp_alloc_eh2:
*
* Second Level Error Handling
* This routine is used at the second level.
* It will be triggered after mdp_allo_eh() has
* been triggered. Thus, it only needs to deal with 1 -> print mess
*
* 3 create a divide by zero for stack trace analysis.
* 2 or above ->
* 1 print a message and return with the NULL pointer
* 0 Keep completely silent about the matter.
**************************************************************************/
{
if (MDP_ALLO_errorOption == 1) {
fprintf(stderr,"%s ERROR: returning with null pointer", rname);
#ifdef MDP_MPDEBUGIO
if (MDP_MP_Nprocs > 1) {
fprintf(stderr,": proc = %d", MDP_MP_myproc);
}
#endif
fprintf(stderr,"\n");
}
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
#define Fprintf (void) fprintf
/****************************************************************************/
#ifndef HAVE_ARRAY_ALLOC
/****************************************************************************/
static double *smalloc(size_t n);
/*****************************************************************************
*
* Dynamic Allocation of Multidimensional Arrays
*----------------------------------------------------------------------------
*
* Example Usage:
*
* typedef struct
* { int bus1;
* int bus2;
* int dest;
* } POINT;
*
* POINT **points, corner;
*
* points = (POINT **) array_alloc (2, x, y, sizeof(POINT));
* ^ ^ ^
* | | |
* number of dimensions--+ | |
* | |
* first dimension max----+ |
* |
* second dimension max------+
*
* (points may be now be used as if it were declared
* POINT points[x][y])
*
* This particular version is limited to dimensions of 3 or less.
*
* corner = points[2][3]; (refer to the structure as you would any array)
*
* free (points); (frees the entire structure in one fell swoop)
*
****************************************************************************/
/*****************************************************************************
* The following section is a commented section containing
* an example main code:
******************************************************************************
*double *array_alloc();
*main()
*{
* int ***temp;
* int *temp2;
* int i, j, k;
* int il, jl, kl;
*
* malloc_debug(2);
* il = 2;
* jl = 3;
* kl = 3;
* temp = (int ***) array_alloc(3,il,jl,kl,sizeof(int));
* for (i=0; i<il; i++) {
* for (j=0; j<jl; j++) {
* for (k=0; k<kl; k++) temp[i][j][k] = 1;
* }
* }
*
* temp2 = (int *) malloc(10*sizeof(int));
* for (i=0; i<10; i++) temp2[i] = 0;
*
* for (i=0; i<il; i++) {
* for (j=0; j<jl; j++) {
* for (k=0; k<kl; k++) (void) printf(" %d\n", temp[i][j][k]);
* }
* }
* malloc_verify();
*}
*****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
double *mdp_array_alloc(int numdim, ...)
{
int i, j;
struct dim {
long index; /* Number of elements in the dimension */
long total; /* Total number of elements */
long size; /* Size of a single element in bytes */
long off; /* offset from beginning of array */
} dim[4]; /* Info about each dimension */
long total; /* Total size of the array */
double *dfield; /* ptr to avoid lint complaints */
char *field; /* The multi-dimensional array */
char **ptr; /* Pointer offset */
char *data; /* Data offset */
va_list va; /* Current pointer in the argument list */
va_start(va, numdim);
if (numdim <= 0) {
Fprintf(stderr,
"mdp_array_alloc ERROR: number of dimensions, %d, is <=0\n",
numdim);
return NULL;
}
else if (numdim > 4) {
Fprintf(stderr,
"mdp_array_alloc ERROR: number of dimensions, %d, is > 4\n",
numdim);
return NULL;
}
dim[0].index = va_arg(va, int);
if (dim[0].index <= 0) {
#ifdef DEBUG
Fprintf(stderr, "WARNING: mdp_array_alloc called with first "
"dimension <= 0, %d\n\twill return the nil pointer\n",
(int) (dim[0].index));
#endif
return((double *) NULL);
}
dim[0].total = dim[0].index;
dim[0].size = sizeof(void *);
dim[0].off = 0;
for (i = 1; i < numdim; i++) {
dim[i].index = va_arg(va, int);
if (dim[i].index <= 0) {
Fprintf(stderr,
"WARNING: mdp_array_alloc called with dimension %d <= 0, "
"%d\n", i+1, (int) (dim[i].index));
Fprintf(stderr, "\twill return the nil pointer\n");
return((double *) NULL);
}
dim[i].total = dim[i-1].total * dim[i].index;
dim[i].size = sizeof(void *);
dim[i].off = dim[i-1].off + dim[i-1].total * dim[i-1].size;
}
dim[numdim-1].size = va_arg(va, int);
va_end(va);
/*
* Round up the last offset value so data is properly aligned.
*/
dim[numdim-1].off = dim[numdim-1].size *
((dim[numdim-1].off+dim[numdim-1].size-1)/dim[numdim-1].size);
total = dim[numdim-1].off + dim[numdim-1].total * dim[numdim-1].size;
dfield = (double *) smalloc((size_t) total);
field = (char *) dfield;
for (i = 0; i < numdim - 1; i++) {
ptr = (char **) (field + dim[i].off);
data = (char *) (field + dim[i+1].off);
for (j = 0; j < dim[i].total; j++) {
ptr[j] = data + j * dim[i+1].size * dim[i+1].index;
}
}
return dfield;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
static double *smalloc(size_t n)
/**************************************************************************
* smalloc: safe version of malloc
*
* This version of smalloc assigns space in even chunks of 8 bytes only
**************************************************************************/
{
#ifdef MDP_MEMDEBUG
static int firsttime = 1;
FILE *file;
#endif
double *pntr;
if (n < 0) {
Fprintf(stderr, "smalloc ERROR: Non-positive argument. (%d)\n", int(n));
return NULL;
}
else if (n == 0) pntr = NULL;
else {
n = ((n - 1) / 8);
n = (n + 1) * 8;
pntr = (double *) malloc((size_t) n);
}
if (pntr == NULL && n != 0) {
Fprintf(stderr, "smalloc : Out of space - number of bytes "
"requested = %d\n", int(n));
}
#ifdef MDP_MEMDEBUG
if (firsttime) {
firsttime = 0;
file = fopen("memops.txt", "w");
} else {
file = fopen("memops.txt", "a");
}
Fprintf(file, "%x %d malloc\n", pntr, n);
if ( (int) pntr == 0x00000001) {
Fprintf(stderr, "FOUND IT!\n");
exit(-1);
}
fclose(file);
#endif
return pntr;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_free (void **ptr)
/*************************************************************************
*
* mdp_safe_free():
*
* This version of free calls the system's free function
* with maximum error checking. It also doesn't call free if ptr is
* the NULL pointer already.
* It will then set the freed pointer to NULL. Thus, a convention may
* be established wherein all pointers that can be malloced can be
* set to NULL if they are not malloced.
**************************************************************************/
{
#ifdef MDP_MEMDEBUG
FILE *file;
#endif
if (ptr == NULL) {
mdp_alloc_eh("mdp_safe_free: handle is NULL", MDP_ALLOC_INTERFACE_ERROR);
}
if (*ptr != NULL) {
#ifdef MDP_MEMDEBUG
file = fopen("memops.txt", "a");
Fprintf(file, "%x free\n", *ptr);
fflush(file);
if ( (int) *ptr == 0x00000001) {
Fprintf(stderr, "FOUND IT!\n");
exit(-1);
}
fclose(file);
#endif
free(*ptr);
/*
* Set the value of ptr to NULL, so that further references
* to it will be flagged.
*/
*ptr = NULL;
}
}
/****************************************************************************/
#endif
/*****************************************************************************
*
* Wrapper Functions
* --------------------
*
* The function definitions below are wrappers around array_alloc for
* common operations. The following principles are followed:
*
* Argument dimensions le 0 are increased to 1 before calling array_alloc.
* Thus, something is always malloced during a call. The reason for this is
* that it minimizes the number of special cases in the calling program.
*
* A pointer to something else other than NULL indicates that that pointer
* has been previously malloced. Thus, it can be freed. Note, after a free
* operation, this package always sets the pointer to NULL before returning.
*
* "safe_alloc" routines try to free the pointer if nonNULL, before calling
* the base alloc_int_#() routines.
*
* The regular routines always initialize the previously malloced space.
*
*****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
int *mdp_alloc_int_1(int nvalues, const int val)
/**************************************************************************
*
* mdp_alloc_int_1:
*
* Allocate and initialize a one dimensional array of integers.
*
* Input
* -------
* nvalues = Length of the array
* val = intialization value
* Return
* ------
* Pointer to the intialized integer array
* Failures are indicated by returning the NULL pointer.
**************************************************************************/
{
int *array;
if (nvalues <= 0) nvalues = 1;
array= (int *) mdp_array_alloc(1, nvalues, sizeof(int));
if (array != NULL) {
if (val != MDP_INT_NOINIT) {
if (val == 0) {
(void) memset(array, 0, sizeof(int)*nvalues);
} else {
for (int i = 0; i < nvalues; i++) array[i] = val;
}
}
} else {
mdp_alloc_eh("mdp_alloc_int_1", nvalues * sizeof(int));
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_alloc_int_1(int **array_hdl, int nvalues, const int val)
/*************************************************************************
*
* mdp_safe_alloc_int_1:
*
* Allocates and/or initializse a one dimensional array of integers.
*
* Input
* -------
* *array_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* nvalues = Length of the array
* val = intialization value
* Output
* ------
* *array_hdl = This value is initialized to the correct address
* of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_int_1: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*array_hdl != NULL) mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_int_1(nvalues, val);
if (*array_hdl == NULL) mdp_alloc_eh2("mdp_safe_alloc_int_1");
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void
mdp_realloc_int_1(int **array_hdl, int new_length, int old_length,
const int defval)
/*************************************************************************
*
* mdp_realloc_int_1_(array_hdl, new_num_ptrs, old_num_ptrs);
*
* Reallocates a one dimensional array of ints.
* This routine always allocates space for at least one int.
* Calls the smalloc() routine to ensure that all malloc
* calls go through one location. This routine will then copy
* the pertinent information from the old array to the
* new array.
*
* Input
* -------
* array_hdl = Pointer to the global variable that
* holds the old and (eventually new)
* address of the array of integers to be reallocated
* new_length = Length of the array
* old_length = Length of the old array
**************************************************************************/
{
if (new_length == old_length) return;
if (new_length <= 0) {
#ifdef MDP_MPDEBUGIO
fprintf(stderr,
"Warning: mdp_realloc_int_1 P_%d: called with n = %d ",
MDP_MP_myproc, new_length);
#else
fprintf(stderr,
"Warning: mdp_realloc_int_1: called with n = %d ",
new_length);
#endif
new_length = 1;
}
if (old_length < 0) old_length = 0;
if (new_length == old_length) return;
size_t bytenum = new_length * sizeof(int);
int *array = (int *) smalloc(bytenum);
if (array != NULL) {
if (*array_hdl) {
if (old_length > 0) bytenum = sizeof(int) * old_length;
else bytenum = 0;
if (new_length < old_length) bytenum = sizeof(int) * new_length;
(void) memcpy((void *) array, (void *) *array_hdl, bytenum);
mdp_safe_free((void **) array_hdl);
} else {
old_length = 0;
}
*array_hdl = array;
if ((defval != MDP_INT_NOINIT) && (new_length > old_length)) {
if (defval == 0) {
bytenum = sizeof(int) * (new_length - old_length);
(void) memset((void *)(array+old_length), 0, bytenum);
} else {
for (int i = old_length; i < new_length; i++) {
array[i] = defval;
}
}
}
} else {
mdp_alloc_eh("mdp_realloc_int_1", bytenum);
}
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
int **mdp_alloc_int_2(int ndim1, int ndim2, const int val)
/*************************************************************************
*
* mdp_alloc_int_2:
*
* Allocate and initialize a two dimensional array of ints.
*
* Input
* -------
* ndim1 = Length of the first dimension of the array
* ndim2 = Length of the second dimension of the array
* val = intialization value
* Return
* ------
* Pointer to the intialized integer array
* Failures are indicated by returning the NULL pointer.
**************************************************************************/
{
int i;
int **array, *dptr;
if (ndim1 <= 0) ndim1 = 1;
if (ndim2 <= 0) ndim2 = 1;
array = (int **) mdp_array_alloc(2, ndim1, ndim2, sizeof(int));
if (array != NULL) {
if (val != MDP_INT_NOINIT) {
if (val == 0) {
(void) memset((void *) array[0], 0, ndim1 * ndim2 * sizeof(int));
} else {
dptr = &(array[0][0]);
for (i = 0; i < ndim1 * ndim2; i++) dptr[i] = val;
}
}
} else {
mdp_alloc_eh("mdp_alloc_int_2",
sizeof(int) * ndim1 * ndim2 +
ndim1 * sizeof(void *));
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
double *mdp_alloc_dbl_1(int nvalues, const double val)
/*************************************************************************
*
* mdp_alloc_dbl_1:
*
* Allocate and initialize a one dimensional array of doubles.
*
* Input
* -------
* nvalues = Length of the array
* val = intialization value
* Return
* ------
* Pointer to the intialized integer array
* Failures are indicated by returning the NULL pointer.
**************************************************************************/
{
int i;
double *array;
if (nvalues <= 0) nvalues = 1;
array = (double *) mdp_array_alloc(1, nvalues, sizeof(double));
if (array != NULL) {
if (val != MDP_DBL_NOINIT) {
if (val == 0.0) {
(void) memset((void *) array, 0, nvalues * sizeof(double));
} else {
for (i = 0; i < nvalues; i++) array[i] = val;
}
}
} else {
mdp_alloc_eh("mdp_alloc_dbl_1", nvalues * sizeof(double));
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_alloc_dbl_1(double **array_hdl, int nvalues, const double val)
/*************************************************************************
*
* mdp_safe_alloc_dbl_1:
*
* Allocates and/or initializse a one dimensional array of doubles.
*
* Input
* -------
* *array_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* nvalues = Length of the array
* val = intialization value
* Output
* ------
* *array_hdl = This value is initialized to the correct address
* of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_dbl_1: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*array_hdl != NULL) mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_dbl_1(nvalues, val);
if (*array_hdl == NULL) mdp_alloc_eh2("mdp_safe_alloc_dbl_1");
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_realloc_dbl_1(double **array_hdl, int new_length,
int old_length, const double defval)
/*************************************************************************
*
* mdp_realloc_dbl_1_(array_hdl, new_num_ptrs, old_num_ptrs);
*
* Reallocates a one dimensional array of doubles.
* This routine always allocates space for at least one dbl.
* Calls the smalloc() routine to ensure that all malloc
* calls go through one location. This routine will then copy
* the pertinent information from the old array to the
* new array.
*
* Input
* -------
* array_hdl = Pointer to the global variable that
* holds the old and (eventually new)
* address of the array of doubles to be reallocated
* new_length = Length of the array
* old_length = Length of the old array
**************************************************************************/
{
if (new_length == old_length) return;
if (new_length <= 0) {
#ifdef MDP_MPDEBUGIO
fprintf(stderr, "Warning: mdp_realloc_dbl_1 P_%d: called with n = %d ",
MDP_MP_myproc, new_length);
#else
fprintf(stderr, "Warning: mdp_realloc_dbl_1: called with n = %d ",
new_length);
#endif
new_length = 1;
}
if (old_length < 0) old_length = 0;
if (new_length == old_length) return;
size_t bytenum = new_length * sizeof(double);
double *array = (double *) smalloc(bytenum);
if (array != NULL) {
if (*array_hdl) {
if (old_length > 0) bytenum = sizeof(double) * old_length;
else bytenum = 0;
if (new_length < old_length) bytenum = sizeof(double) * new_length;
(void) memcpy((void *) array, (void *) *array_hdl, bytenum);
mdp_safe_free((void **) array_hdl);
} else {
old_length = 0;
}
*array_hdl = array;
if ((defval != MDP_DBL_NOINIT) && (new_length > old_length)) {
if (defval == 0) {
bytenum = sizeof(double) * (new_length - old_length);
(void) memset((void *)(array+old_length), 0, bytenum);
} else {
for (int i = old_length; i < new_length; i++) {
array[i] = defval;
}
}
}
} else {
mdp_alloc_eh("mdp_realloc_dbl_1", bytenum);
}
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
char *mdp_alloc_char_1(int nvalues, const char val)
/*************************************************************************
*
* mdp_alloc_char_1:
*
* Allocate and initialize a one dimensional array of characters.
*
* Input
* -------
* nvalues = Length of the array
* val = intialization value
* Return
* ------
* Pointer to the intialized character array
* Failures are indicated by returning the NULL pointer.
**************************************************************************/
{
int i;
char *array;
if (nvalues <= 0) nvalues = 1;
array = (char *) mdp_array_alloc(1, nvalues, sizeof(char));
if (array != NULL) {
for (i = 0; i < nvalues; i++) array[i] = val;
} else {
mdp_alloc_eh("mdp_alloc_char_1", nvalues * sizeof(char));
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_alloc_char_1(char **array_hdl, int nvalues, const char val)
/*************************************************************************
*
* mdp_safe_alloc_char_1:
*
* Allocates and/or initializse a one dimensional array of characters.
*
* Input
* -------
* array_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* nvalues = Length of the array
* val = intialization value
* Output
* ------
* *array_hdl = This value is initialized to the correct address
* of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_char_1: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*array_hdl != NULL) mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_char_1(nvalues, val);
if (*array_hdl == NULL) mdp_alloc_eh2("mdp_safe_alloc_char_1");
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
double **mdp_alloc_dbl_2(int ndim1, int ndim2, const double val)
/*************************************************************************
*
* mdp_alloc_dbl_2:
*
* Allocate and initialize a two dimensional array of doubles.
*
* Input
* -------
* ndim1 = Length of the first dimension of the array
* ndim2 = Length of the second dimension of the array
* val = intialization value
* Return
* ------
* Pointer to the intialized integer array
* Failures are indicated by returning the NULL pointer.
**************************************************************************/
{
int i;
double **array, *dptr;
if (ndim1 <= 0) ndim1 = 1;
if (ndim2 <= 0) ndim2 = 1;
array = (double **) mdp_array_alloc(2, ndim1, ndim2, sizeof(double));
if (array != NULL) {
if (val != MDP_DBL_NOINIT) {
if (val == 0.0) {
(void) memset((void *) array[0], 0, ndim1*ndim2 * sizeof(double));
} else {
dptr = &(array[0][0]);
for (i = 0; i < ndim1*ndim2; i++) dptr[i] = val;
}
}
} else {
mdp_alloc_eh("mdp_alloc_dbl_2",
sizeof(double) * ndim1 * ndim2 +
ndim1 * sizeof(void *));
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_alloc_dbl_2(double ***array_hdl, int ndim1, int ndim2,
const double val)
/*************************************************************************
*
* mdp_safe_alloc_dbl_2:
*
* Allocate and initialize a two dimensional array of doubles.
*
* Input
* -------
* *array_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* ndim1 = Length of the array
* ndim2 = Length of inner loop of the array
* val = intialization value
* Return
* ------
* *array_hdl = This value is initialized to the correct address
* of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_dbl_2: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*array_hdl != NULL) mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_dbl_2(ndim1, ndim2, val);
if (*array_hdl == NULL) mdp_alloc_eh2("mdp_safe_alloc_dbl_2");
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_realloc_dbl_2(double ***array_hdl, int ndim1, int ndim2,
int ndim1Old, int ndim2Old, const double val)
/*************************************************************************
*
* mdp_realloc_dbl_2:
*
* mdp_realloc_dbl_2(array_hdl, int ndim1, int ndim2,
* int ndim1Old, int ndim2Old, const double val)
*
* Reallocates a two dimensional array of doubles.
* This routine will then copy the pertinent information from
* the old array to the new array.
*
* If both old dimensions are set to zero or less, then this routine
* will free the old memory before mallocing the new memory. This may
* be a benefit for extremely large mallocs.
* In all other cases, the new and the old malloced arrays will
* exist for a short time together.
*
* Input
* -------
* array_hdl = Pointer to the global variable that
* holds the old and (eventually new)
* address of the array of doubles to be reallocated
* ndim1 = First dimension of the new array
* ndim2 = Second dimension of the new array
* ndim1Old = First dimension of the old array
* ndim2Old = Second dimension of the old array
* val = Default fill value.
**************************************************************************/
{
if (ndim1 <= 0) ndim1 = 1;
if (ndim2 <= 0) ndim2 = 1;
ndim1Old = MAX(ndim1Old, 0);
ndim2Old = MAX(ndim2Old, 0);
/*
* One way to do it, if old information isn't needed. In this algorithm
* the arrays are never malloced at the same time.
*/
if ((*array_hdl == NULL) || (ndim1Old <= 0 && ndim2Old <= 0)) {
mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_dbl_2(ndim1, ndim2, val);
if (*array_hdl == NULL) mdp_alloc_eh2("mdp_realloc_dbl_2");
}
/*
* Other way to do when old information is available and needed
*/
else {
double **array_old = *array_hdl;
*array_hdl = (double **) mdp_array_alloc(2, ndim1, ndim2, sizeof(double));
if (*array_hdl == NULL) {
mdp_alloc_eh2("mdp_realloc_dbl_2");
} else {
/*
* Now, let's initialize the arrays
*/
int ndim1Min = MIN(ndim1, ndim1Old);
int ndim2Min = MIN(ndim2, ndim2Old);
double **array_new = *array_hdl;
/*
* When the second dimensions are equal, we can copy blocks
* using the very efficient bit moving kernels.
*/
if (ndim2 == ndim2Old) {
size_t sz = ndim1Min * ndim2 * sizeof(double);
(void) memcpy((void *) array_new[0], (void *) array_old[0], sz);
}
/*
* If the second dimensions aren't equal, then we have to
* break up the bit operations even more
*/
else {
size_t sz = ndim2Min * sizeof(double);
size_t sz2 = (ndim2 - ndim2Min) * sizeof(double);
for (int i = 0; i < ndim1Min; i++) {
(void) memcpy((void *) array_new[i], (void *) array_old[i], sz);
if (ndim2 > ndim2Min && val != MDP_DBL_NOINIT) {
if (val == 0.0) {
(void) memset((void *) (array_new[i] + ndim2Min), 0, sz2);
} else {
double *dptr = array_new[i];
for (int j = ndim2Min; j < ndim2; j++) dptr[j] = val;
}
}
}
}
/*
* finish up initializing the rest of the array
*/
if (ndim1 > ndim1Min && val != MDP_DBL_NOINIT) {
if (val == 0.0) {
size_t sz = (ndim1 - ndim1Min) * ndim2 * sizeof(double);
(void) memset((void *) array_new[ndim1Min], 0, sz);
} else {
double *dptr = array_new[ndim1Min];
int num = (ndim1 - ndim1Min) * ndim2;
for (int i = 0; i < num; i++) {
dptr[i] = val;
}
}
}
/*
* Free the old array
*/
mdp_safe_free((void **) &array_old);
}
}
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
char **mdp_alloc_VecFixedStrings(int numStrings, int lenString)
/*************************************************************************
*
* mdp_alloc_VecFixedStrings:
*
* Allocate and initialize a vector of fixed-length
* strings. Each string is initialized to the NULL string.
*
* Input
* -------
* numStrings = Number of strings
* lenString = Length of each string including the trailing null
* character
* Return
* ------
* This value is initialized to the correct address of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
int i;
char **array;
if (numStrings <= 0) numStrings = 1;
if (lenString <= 0) lenString = 1;
array = (char **) mdp_array_alloc(2, numStrings, lenString, sizeof(char));
if (array != NULL) {
for (i = 0; i < numStrings; i++) array[i][0] = '\0';
} else {
mdp_alloc_eh("mdp_alloc_VecFixedStrings",
sizeof(char) * numStrings * lenString +
numStrings * sizeof(void *));
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_realloc_VecFixedStrings(char ***array_hdl, int numStrings,
int numOldStrings, int lenString)
/*************************************************************************
*
* mdp_realloc_VecFixedStrings:
*
* Reallocate and initialize a vector of fixed-length
* strings. Each new string is initialized to the NULL string.
* old strings are copied.
*
* Input
* -------
* ***array_hdl = The pointer to the char ** location holding
* the data to be reallocated.
* numStrings = Number of strings
* numOldStrings = Number of old strings
* lenString = Length of each string including the trailing null
* character
**************************************************************************/
{
int i;
char **array, **ao;
if (numStrings <= 0) numStrings = 1;
if (numStrings == numOldStrings) return;
if (lenString <= 0) lenString = 1;
array = (char **) mdp_array_alloc(2, numStrings, lenString, sizeof(char));
if (array != NULL) {
int len = MIN(numStrings, numOldStrings);
ao = *array_hdl;
if (ao) {
for (i = 0; i < len; i++) {
strncpy(array[i], ao[i], lenString);
}
}
if (numStrings > numOldStrings) {
for (i = numOldStrings; i < numStrings; i++) array[i][0] = '\0';
}
mdp_safe_free((void **) array_hdl);
*array_hdl = array;
} else {
mdp_alloc_eh("mdp_realloc_VecFixedStrings",
sizeof(char) * numStrings * lenString +
numStrings * sizeof(void *));
}
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_alloc_VecFixedStrings(char ***array_hdl,
int numStrings, int lenString)
/*************************************************************************
*
* mdp_safe_alloc_VecFixedStrings
*
* Allocate and initialize an array of strings of fixed length
*
* Input
* -------
* *array_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* numStrings = Number of strings
* lenString = Length of each string including the trailing null
* character
* Output
* ------
* *array_hdl = This value is initialized to the correct address
* of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_VecFixedStrings: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*array_hdl != NULL) mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_VecFixedStrings(numStrings, lenString);
if (*array_hdl == NULL)
mdp_alloc_eh2("mdp_safe_alloc_VecFixedStrings");
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
C16_NAME *mdp_alloc_C16_NAME_1(int numStrings, const int init)
/**************************************************************************
*
* mdp_alloc_C16_NAME_1:
*
* Allocate and initialize a vector of fixed-length
* strings of type C16_NAME
*
* Input
* -------
* numStrings = Number of strings
* init = If true, this routine initializes the space to the
* space character.
* Return
* ------
* This value is initialized to the correct address of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
int i, j;
char *c_ptr;
if (numStrings <= 0) numStrings = 1;
C16_NAME *array = (C16_NAME *) mdp_array_alloc(1, numStrings, sizeof(C16_NAME));
if (array != NULL) {
if (init) {
for (i = 0; i < numStrings; i++) {
c_ptr = (char *) (array + i);
for (j = 0; j < (int) sizeof(C16_NAME); j++) c_ptr[j] = ' ';
}
}
} else {
mdp_alloc_eh("mdp_alloc_C16_NAME_1",
sizeof(C16_NAME) * numStrings);
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_alloc_C16_NAME_1(C16_NAME **array_hdl, int numStrings,
const int init)
/*************************************************************************
*
* mdp_safe_alloc_C16_NAME_1:
*
* Allocate and initialize a vector of fixed-length
* strings of type C16_NAME
*
* Input
* -------
* *array_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* numStrings = Number of strings
* init = If true, this routine initializes the space to the
* space character.
* Output
* ------
* *array_hdl = This value is initialized to the correct address
* of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_C16_NAME_1: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*array_hdl != NULL) mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_C16_NAME_1(numStrings, init);
if (*array_hdl == NULL) mdp_alloc_eh2("mdp_safe_alloc_C16_NAME_1");
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void **mdp_alloc_ptr_1(int numPointers)
/*************************************************************************
*
* mdp_alloc_ptr_1:
*
* Allocate and initialize a vector of pointers
* of type pointer to void. All pointers are initialized to the NULL
* value.
*
* Input
* -------
* numPointers = Number of pointers
* Return
* ------
* This value is initialized to the correct address of the vector.
* A NULL value in the position indicates an error.
**************************************************************************/
{
int i;
void **array;
if (numPointers <= 0) numPointers = 1;
array = (void **) mdp_array_alloc(1, numPointers, sizeof(void *));
if (array != NULL) {
for (i = 0; i < numPointers; i++) {
array[i] = NULL;
}
} else {
mdp_alloc_eh("mdp_alloc_ptr_1",
sizeof(void *) * numPointers);
}
return array;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_alloc_ptr_1(void ***array_hdl, int numPointers)
/**************************************************************************
*
* mdp_safe_alloc_ptr_1:
*
* Allocate and initialize a vector of pointers
* of type pointer to void. All pointers are initialized to the NULL
* value.
*
* Input
* -------
* *array_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* numPointers = Number of pointers
* Output
* ------
* *array_hdl = This value is initialized to the correct address
* of the array.
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_ptr_1: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*array_hdl != NULL) mdp_safe_free((void **) array_hdl);
*array_hdl = mdp_alloc_ptr_1(numPointers);
if (*array_hdl == NULL) mdp_alloc_eh2("mdp_safe_alloc_ptr_1");
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_realloc_ptr_1(void ***array_hdl, int numLen, int numOldLen)
/*************************************************************************
*
* mdp_realloc__ptr_1:
*
* Reallocate and initialize a vector of pointers
* Each new pointer is initialized to NULL.
* old Pointers are copied.
*
* Input
* -------
* ***array_hdl = The pointer to the char ** location holding
* the data to be reallocated.
* numLen = Number of strings
* numOldLen = Number of old strings
**************************************************************************/
{
if (array_hdl == NULL) {
mdp_alloc_eh("mdp_safe_alloc_ptr_1: handle is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (numLen <= 0) numLen = 1;
if (numOldLen < 0) numOldLen = 0;
if (numLen == numOldLen) return;
size_t bytenum = sizeof(void *) * numLen;
void **array = (void **) smalloc(bytenum);
if (array != NULL) {
int len = MIN(numLen, numOldLen);
if (*array_hdl) {
void **ao = *array_hdl;
for (int i = 0; i < len; i++) array[i] = ao[i];
} else {
numOldLen = 0;
}
if (numLen > numOldLen) {
bytenum = sizeof(void *) * (numLen - numOldLen);
(void) memset((void *) (array + numOldLen), 0, bytenum);
}
mdp_safe_free((void **) array_hdl);
*array_hdl = array;
} else {
mdp_alloc_eh("mdp_realloc_ptr_1", sizeof(void *) * numLen);
}
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
char *mdp_copy_C16_NAME_to_string(const C16_NAME copyFrom)
/*************************************************************************
*
* mdp_copy_C16_NAME_to_string:
*
* Allocates space for and copies a C16_NAME
*
* Input
* -------
* copyFrom = C16_NAME string (note, this doesn't necessarily have
* to be null terminate. This is the reason for this
* subroutine.
* If NULL is supplied, then nothing is malloced and
* a NULL value is returned.
* Return
* ------
* This value is initialized to the correct address of the array.
* A NULL value in the position either indicates an error, or
* that the original pointer to the string was NULL.
**************************************************************************/
{
/*
* This routine creates a temporary string with a null terminator at the
* end (assured). Then it uses mdp_copy_string() to do the work
*/
C16_NAME_STR tmpString;
if (copyFrom == NULL) return NULL;
tmpString[sizeof(C16_NAME)] = '\0';
(void) strncpy(tmpString, copyFrom, sizeof(C16_NAME));
return mdp_copy_string(tmpString);
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
char *mdp_copy_string(const char *copyFrom)
/*************************************************************************
*
* mdp_copy_string:
*
* Allocates space for and copies a string
*
* Input
* -------
* copyFrom = null terminated string. If NULL is supplied, then
* nothing is malloced and a NULL value is returned.
* Return
* ------
* This value is initialized to the correct address of the array.
* A NULL value in the position either indicates an error, or
* that the original pointer to the string was NULL.
**************************************************************************/
{
char *cptr;
if (copyFrom == NULL) return NULL;
cptr = (char *) mdp_array_alloc(1, strlen(copyFrom) + 1, sizeof(char));
if (cptr != NULL) {
(void) strcpy(cptr, copyFrom);
} else {
mdp_alloc_eh("mdp_copy_string", sizeof(char) * (strlen(copyFrom) + 1));
}
return cptr;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
void mdp_safe_copy_string(char **string_hdl, const char *copyFrom)
/*************************************************************************
*
* mdp_safe_copy_string:
*
* Allocates space for and copies a string
*
* Input
* -------
* *string_hdl = Previous value of pointer. If non-NULL will try
* to free the memory at this address.
* *copyFrom = String to be copied
* Output
* ------
* *string_hdl = Pointer to the copied string
* A NULL value in the position indicates an error.
**************************************************************************/
{
if (string_hdl == NULL) {
mdp_alloc_eh("mdp_safe_copy_string: string_hdl is NULL",
MDP_ALLOC_INTERFACE_ERROR);
return;
}
if (*string_hdl != NULL) mdp_safe_free((void **) string_hdl);
if (copyFrom == NULL) {
*string_hdl = NULL;
return;
}
*string_hdl = mdp_copy_string(copyFrom);
if (*string_hdl == NULL) {
mdp_alloc_eh2("mdp_safe_copy_string");
}
return;
}
/****************************************************************************/
/* END of mdp_allo.cpp */
/****************************************************************************/
|
// Copyright (c) 2020 PaddlePaddle Authors. All 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.
#include "paddle/fluid/imperative/amp_auto_cast.h"
#include <memory>
#include <string>
#include "paddle/fluid/eager/eager_tensor.h"
#include "paddle/fluid/imperative/tracer.h"
#include "paddle/fluid/imperative/type_defs.h"
#include "paddle/fluid/imperative/var_helper.h"
namespace paddle {
namespace imperative {
class VarBase;
// According to the input `place` and `dtype`, this function returns a tuple
// consists of three sets:
// 1) All operators registered in the Paddle framework.
// 2) All operators supported for `place` and `dtype`.
// 3) All operators unsupported for `place` and `dtype`.
// The input `place` is a type of string, which can only be `GPU` or `CPU`.
// The input `dtype` is a type of paddle::framework::proto::VarType::Type,
// which can be paddle::framework::proto::VarType::FP16,
// paddle::framework::proto::VarType::FP32 and so on.
std::tuple<std::unordered_set<std::string>, std::unordered_set<std::string>,
std::unordered_set<std::string>>
OpSupportedInfos(const std::string& place,
framework::proto::VarType::Type dtype) {
std::string query_place;
std::transform(place.begin(), place.end(), std::back_inserter(query_place),
[](unsigned char c) { return std::toupper(c); });
using fn_type = std::add_pointer<bool(const platform::Place&)>::type;
std::unordered_map<std::string, fn_type> is_target_place{
{"GPU", &platform::is_gpu_place}, {"CPU", &platform::is_cpu_place},
{"XPU", &platform::is_xpu_place}, {"NPU", &platform::is_npu_place},
{"MLU", &platform::is_mlu_place},
};
PADDLE_ENFORCE_NE(is_target_place.count(query_place), 0,
platform::errors::InvalidArgument(
"The argument `place` should be 'GPU', 'CPU', 'XPU', "
"'NPU', 'MLU', but got '%s'.",
place));
std::unordered_set<std::string> all_ops;
const auto& op_info = framework::OpInfoMap::Instance().map();
for (auto it = op_info.begin(); it != op_info.end(); it++) {
all_ops.emplace(it->first);
}
std::unordered_set<std::string> supported_ops;
auto& all_kernels = framework::OperatorWithKernel::AllOpKernels();
for (auto it = all_kernels.begin(); it != all_kernels.end(); it++) {
for (auto& kernel_type : it->second) {
if (is_target_place[query_place](kernel_type.first.place_) &&
kernel_type.first.data_type_ == dtype) {
supported_ops.emplace(it->first);
}
}
}
auto phi_kernels = phi::KernelFactory::Instance().kernels();
for (auto& kernel_pair : phi_kernels) {
auto op_type = phi::TransToFluidOpName(kernel_pair.first);
for (auto& info_pair : kernel_pair.second) {
framework::OpKernelType kernel_type =
framework::TransPhiKernelKeyToOpKernelType(info_pair.first);
if (is_target_place[query_place](kernel_type.place_) &&
kernel_type.data_type_ == dtype && all_ops.count(op_type)) {
VLOG(4) << op_type << " " << supported_ops.size();
supported_ops.emplace(op_type);
}
}
}
std::unordered_set<std::string> unsupported_ops;
for (auto& op : all_ops) {
if (!supported_ops.count(op)) {
unsupported_ops.emplace(op);
}
}
VLOG(4) << "-- The size of all_ops: " << all_ops.size() << " --";
VLOG(4) << "-- The size of supported_ops: " << supported_ops.size() << " --";
VLOG(4) << "-- The size of unsupported_ops: " << unsupported_ops.size()
<< " --";
return std::make_tuple(std::move(all_ops), std::move(supported_ops),
std::move(unsupported_ops));
}
AutoCastGuard::AutoCastGuard(std::shared_ptr<Tracer> tracer, AmpLevel level)
: tracer_(tracer) {
pre_amp_level_ = tracer_->GetAmpLevel();
if (pre_amp_level_ != level) {
tracer_->SetAmpLevel(level);
}
}
AutoCastGuard::~AutoCastGuard() { tracer_->SetAmpLevel(pre_amp_level_); }
AmpOperators::AmpOperators()
: allow_ops_(new std::unordered_set<std::string>()),
block_ops_(new std::unordered_set<std::string>()),
unsupported_fp16_ops_(new std::unordered_set<std::string>()),
unsupported_bf16_ops_(new std::unordered_set<std::string>()) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
auto unsupported_ops_gpu_fp16 = std::get<2>(
OpSupportedInfos("GPU", paddle::framework::proto::VarType::FP16));
unsupported_fp16_ops_->insert(unsupported_ops_gpu_fp16.begin(),
unsupported_ops_gpu_fp16.end());
auto unsupported_ops_gpu_bf16 = std::get<2>(
OpSupportedInfos("GPU", paddle::framework::proto::VarType::BF16));
unsupported_bf16_ops_->insert(unsupported_ops_gpu_bf16.begin(),
unsupported_ops_gpu_bf16.end());
// NOTE: GPU/NPU/XPU/MLU is compiled seperatly.
#elif defined(PADDLE_WITH_ASCEND_CL)
auto unsupported_ops_npu_fp16 = std::get<2>(
OpSupportedInfos("NPU", paddle::framework::proto::VarType::FP16));
unsupported_fp16_ops_->insert(unsupported_ops_npu_fp16.begin(),
unsupported_ops_npu_fp16.end());
auto unsupported_ops_npu_bf16 = std::get<2>(
OpSupportedInfos("NPU", paddle::framework::proto::VarType::BF16));
unsupported_bf16_ops_->insert(unsupported_ops_npu_bf16.begin(),
unsupported_ops_npu_bf16.end());
#elif defined(PADDLE_WITH_XPU)
auto unsupported_ops_xpu_fp16 = std::get<2>(
OpSupportedInfos("XPU", paddle::framework::proto::VarType::FP16));
unsupported_fp16_ops_->insert(unsupported_ops_xpu_fp16.begin(),
unsupported_ops_xpu_fp16.end());
auto unsupported_ops_xpu_bf16 = std::get<2>(
OpSupportedInfos("XPU", paddle::framework::proto::VarType::BF16));
unsupported_bf16_ops_->insert(unsupported_ops_xpu_bf16.begin(),
unsupported_ops_xpu_bf16.end());
#elif defined(PADDLE_WITH_MLU)
auto unsupported_ops_mlu_fp16 = std::get<2>(
OpSupportedInfos("MLU", paddle::framework::proto::VarType::FP16));
unsupported_fp16_ops_->insert(unsupported_ops_mlu_fp16.begin(),
unsupported_ops_mlu_fp16.end());
auto unsupported_ops_mlu_bf16 = std::get<2>(
OpSupportedInfos("MLU", paddle::framework::proto::VarType::BF16));
unsupported_bf16_ops_->insert(unsupported_ops_mlu_bf16.begin(),
unsupported_ops_mlu_bf16.end());
#endif
VLOG(4) << allow_ops_->size() << " " << block_ops_->size() << " "
<< unsupported_fp16_ops_->size() << " "
<< unsupported_bf16_ops_->size();
}
AmpOperators::~AmpOperators() {}
AmpOperators& AmpOperators::Instance() {
static AmpOperators instance;
return instance;
}
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableAllowOps() {
return allow_ops_;
}
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableBlockOps() {
return block_ops_;
}
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableUnsupportedFp16Ops() {
return unsupported_fp16_ops_;
}
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableUnsupportedBf16Ops() {
return unsupported_bf16_ops_;
}
std::ostream& operator<<(std::ostream& os, AmpOperators& ops) {
os << "allow ops: ";
auto allow_ops = ops.GetMutableAllowOps();
std::copy((*allow_ops).begin(), (*allow_ops).end(),
std::ostream_iterator<std::string>(os, " "));
os << "\n";
os << "block ops: ";
auto block_ops = ops.GetMutableBlockOps();
std::copy((*block_ops).begin(), (*block_ops).end(),
std::ostream_iterator<std::string>(os, " "));
os << "\n";
os << "unsupported fp16 ops: ";
auto unsupported_fp16_ops = ops.GetMutableUnsupportedFp16Ops();
std::copy((*unsupported_fp16_ops).begin(), (*unsupported_fp16_ops).end(),
std::ostream_iterator<std::string>(os, " "));
os << "\n";
os << "unsupported bf16 ops: ";
auto unsupported_bf16_ops = ops.GetMutableUnsupportedBf16Ops();
std::copy((*unsupported_bf16_ops).begin(), (*unsupported_bf16_ops).end(),
std::ostream_iterator<std::string>(os, " "));
return os;
}
template <typename VarType>
inline std::string GetDtypeStr(const std::shared_ptr<VarType>& var) {
return framework::DataTypeToString(GetDataType<VarType>(var));
}
template <typename VarType>
inline bool NeedCast(const std::shared_ptr<VarType>& var) {
auto place = GetPlace(var);
auto data_type = GetDataType<VarType>(var);
if (paddle::platform::is_gpu_place(place) ||
paddle::platform::is_cuda_pinned_place(place) ||
paddle::platform::is_xpu_place(place) ||
paddle::platform::is_mlu_place(place) ||
paddle::platform::is_custom_place(place) ||
paddle::platform::is_npu_place(place) ||
paddle::platform::is_npu_pinned_place(place)) {
// CudaPinndePlace is added for varbase created by dataloader
if (data_type == paddle::framework::proto::VarType::FP32 ||
data_type == paddle::framework::proto::VarType::FP16 ||
data_type == paddle::framework::proto::VarType::BF16) {
return true;
}
}
return false;
}
// NOTE: Trace a cast op, so if a var is casted from fp32 to fp16, then the grad
// var will be cast back from fp16 to fp32 during backward phase.
template <typename VarType>
static inline std::shared_ptr<VarType> CastToType(
const std::shared_ptr<VarType>& var,
const framework::proto::VarType::Type dst_type) {
const auto& tracer = imperative::GetCurrentTracer();
imperative::NameVarMap<VarType> ins = {{"X", {var}}};
framework::AttributeMap attrs = {{"in_dtype", GetDataType<VarType>(var)},
{"out_dtype", dst_type}};
auto out =
std::shared_ptr<VarType>(new VarType(tracer->GenerateUniqueName()));
imperative::NameVarMap<VarType> outs = {{"Out", {out}}};
{
AutoCastGuard guard(tracer, AmpLevel::O0);
tracer->TraceOp("cast", ins, outs, std::move(attrs));
}
return out;
}
template <typename VarType>
static inline std::shared_ptr<VarType> CastToFP16(
const std::shared_ptr<VarType>& var) {
auto dst_type = framework::proto::VarType::FP16;
if (NeedCast(var) && (GetDataType<VarType>(var) != dst_type)) {
return CastToType(var, dst_type);
}
return var;
}
template <typename VarType>
static inline std::shared_ptr<VarType> CastToFP32(
const std::shared_ptr<VarType>& var) {
auto dst_type = framework::proto::VarType::FP32;
if (NeedCast(var) && (GetDataType<VarType>(var) != dst_type)) {
return CastToType(var, dst_type);
}
return var;
}
template <typename VarType>
static inline std::shared_ptr<VarType> CastToBF16(
const std::shared_ptr<VarType>& var) {
auto dst_type = framework::proto::VarType::BF16;
if (NeedCast(var) && (GetDataType<VarType>(var) != dst_type)) {
return CastToType(var, dst_type);
}
return var;
}
template <typename VarType>
static inline framework::proto::VarType::Type GetPromoteType(
const std::string& op_type, const NameVarMap<VarType>& ins,
const framework::proto::VarType::Type amp_dtype) {
auto dst_type = amp_dtype;
for (const auto& pair : ins) {
for (const auto& var : pair.second) {
if (GetDataType<VarType>(var) == framework::proto::VarType::FP32) {
dst_type = GetDataType<VarType>(var);
break;
}
}
}
// NOTE(juncai): moving_average_abs_max_scale only consider the
// dtype of input(X)
if (op_type == "moving_average_abs_max_scale") {
for (const auto& pair : ins) {
if (pair.first == "X" && GetDataType<VarType>(pair.second.front()) ==
framework::proto::VarType::FP16) {
dst_type = framework::proto::VarType::FP16;
}
}
}
return dst_type;
}
template <typename VarType>
NameVarMap<VarType> AutoCastInputs(const std::string& op_type,
const NameVarMap<VarType>& ins) {
NameVarMap<VarType> new_ins(ins);
if (AmpOperators::Instance().GetMutableAllowOps()->count(op_type)) {
for (auto& pair : new_ins) {
// NOTE(zhiqiu): batch_norm and layer_norm support only input x is fp16.
if ((op_type == "batch_norm" || op_type == "layer_norm" ||
op_type == "sync_batch_norm") &&
pair.first != "X") {
continue;
}
if ((op_type == "fused_attention" || op_type == "fused_feedforward")) {
if (pair.first == "LnScale" || pair.first == "LnBias" ||
pair.first == "Ln2Scale" || pair.first == "Ln2Bias" ||
pair.first == "Ln1Scale" || pair.first == "Ln1Bias") {
continue;
}
}
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to float16";
for (auto& var : pair.second) {
var = CastToFP16<VarType>(var);
}
}
return new_ins;
} else if (AmpOperators::Instance().GetMutableBlockOps()->count(op_type)) {
for (auto& pair : new_ins) {
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to float";
for (auto& var : pair.second) {
var = CastToFP32<VarType>(var);
}
}
return new_ins;
} else {
auto dst_type =
GetPromoteType<VarType>(op_type, ins, framework::proto::VarType::FP16);
// NOTE(zhiqiu): if the op has op fp16 kernel, fall back to fp32.
if (dst_type == framework::proto::VarType::FP16 &&
AmpOperators::Instance().GetMutableUnsupportedFp16Ops()->count(
op_type)) {
dst_type = framework::proto::VarType::FP32;
}
for (auto& pair : new_ins) {
// NOTE(zhiqiu): batch_norm and layer_norm support only input x is fp16.
if ((op_type == "batch_norm" || op_type == "layer_norm" ||
op_type == "sync_batch_norm") &&
pair.first == "X" && dst_type == framework::proto::VarType::FP32) {
continue;
}
if ((op_type == "fused_attention" || op_type == "fused_feedforwad") &&
dst_type == framework::proto::VarType::FP32) {
if (pair.first != "LnScale" && pair.first != "LnBias" &&
pair.first != "Ln2Scale" && pair.first != "Ln2Bias" &&
pair.first != "Ln1Scale" && pair.first != "Ln1Bias") {
continue;
}
}
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to "
<< framework::DataTypeToString(dst_type);
for (auto& var : pair.second) {
var = (dst_type == framework::proto::VarType::FP32
? CastToFP32<VarType>(var)
: CastToFP16<VarType>(var));
}
}
return new_ins;
}
return new_ins;
}
template NameVarMap<VarBase> AutoCastInputs<VarBase>(
const std::string& op_type, const NameVarMap<VarBase>& ins);
template NameVarMap<egr::EagerVariable> AutoCastInputs<egr::EagerVariable>(
const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);
template <typename VarType>
NameVarMap<VarType> CastPureFp16Inputs(const std::string& op_type,
const NameVarMap<VarType>& ins) {
NameVarMap<VarType> new_ins(ins);
auto dst_type = framework::proto::VarType::FP16;
if (AmpOperators::Instance().GetMutableUnsupportedFp16Ops()->count(op_type) ||
AmpOperators::Instance().GetMutableBlockOps()->count(op_type)) {
dst_type = framework::proto::VarType::FP32;
}
for (auto& pair : new_ins) {
// NOTE: The run_program OP only has FP32 kernel. In dy2stat pure fp16
// training, we have correctly cast the inputs of run_program OP before,
// so here should avoid casting for run_program OP.
if (op_type == "run_program") {
continue;
}
if ((op_type == "batch_norm" || op_type == "layer_norm" ||
op_type == "sync_batch_norm") &&
pair.first != "X") {
continue;
}
if ((op_type == "fused_attention" || op_type == "fused_feedforward")) {
if (pair.first == "LnScale" || pair.first == "LnBias" ||
pair.first == "Ln2Scale" || pair.first == "Ln2Bias" ||
pair.first == "Ln1Scale" || pair.first == "Ln1Bias") {
continue;
}
}
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to "
<< framework::DataTypeToString(dst_type);
for (auto& var : pair.second) {
var = (dst_type == framework::proto::VarType::FP32
? CastToFP32<VarType>(var)
: CastToFP16<VarType>(var));
}
}
return new_ins;
}
template NameVarMap<VarBase> CastPureFp16Inputs<VarBase>(
const std::string& op_type, const NameVarMap<VarBase>& ins);
template NameVarMap<egr::EagerVariable> CastPureFp16Inputs<egr::EagerVariable>(
const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);
template <typename VarType>
NameVarMap<VarType> AutoCastBF16Inputs(const std::string& op_type,
const NameVarMap<VarType>& ins) {
NameVarMap<VarType> new_ins(ins);
if (AmpOperators::Instance().GetMutableAllowOps()->count(op_type)) {
for (auto& pair : new_ins) {
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to bfloat16";
for (auto& var : pair.second) {
var = CastToBF16<VarType>(var);
}
}
return new_ins;
} else if (AmpOperators::Instance().GetMutableBlockOps()->count(op_type)) {
for (auto& pair : new_ins) {
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to float";
for (auto& var : pair.second) {
var = CastToFP32<VarType>(var);
}
}
return new_ins;
} else {
auto dst_type =
GetPromoteType<VarType>(op_type, ins, framework::proto::VarType::BF16);
// NOTE(zhangbo): if the op has op fp16 kernel, fall back to fp32.
if (dst_type == framework::proto::VarType::BF16 &&
AmpOperators::Instance().GetMutableUnsupportedBf16Ops()->count(
op_type)) {
dst_type = framework::proto::VarType::FP32;
}
for (auto& pair : new_ins) {
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to "
<< framework::DataTypeToString(dst_type);
for (auto& var : pair.second) {
var = (dst_type == framework::proto::VarType::FP32
? CastToFP32<VarType>(var)
: CastToBF16<VarType>(var));
}
}
return new_ins;
}
return new_ins;
}
template NameVarMap<VarBase> AutoCastBF16Inputs<VarBase>(
const std::string& op_type, const NameVarMap<VarBase>& ins);
template NameVarMap<egr::EagerVariable> AutoCastBF16Inputs<egr::EagerVariable>(
const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);
template <typename VarType>
NameVarMap<VarType> CastPureBf16Inputs(const std::string& op_type,
const NameVarMap<VarType>& ins) {
NameVarMap<VarType> new_ins(ins);
auto dst_type = framework::proto::VarType::BF16;
if (AmpOperators::Instance().GetMutableUnsupportedBf16Ops()->count(op_type) ||
AmpOperators::Instance().GetMutableBlockOps()->count(op_type)) {
dst_type = framework::proto::VarType::FP32;
}
for (auto& pair : new_ins) {
VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
<< GetDtypeStr(*pair.second.cbegin()) << " to "
<< framework::DataTypeToString(dst_type);
for (auto& var : pair.second) {
var = (dst_type == framework::proto::VarType::FP32
? CastToFP32<VarType>(var)
: CastToBF16<VarType>(var));
}
}
return new_ins;
}
template NameVarMap<VarBase> CastPureBf16Inputs<VarBase>(
const std::string& op_type, const NameVarMap<VarBase>& ins);
template NameVarMap<egr::EagerVariable> CastPureBf16Inputs<egr::EagerVariable>(
const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);
} // namespace imperative
} // namespace paddle
|
#include "transactionrecord.h"
#include "wallet.h"
#include "base58.h"
/* Return positive answer if transaction should be shown in list.
*/
bool TransactionRecord::showTransaction(const CWalletTx &wtx)
{
if (wtx.IsCoinBase())
{
// Ensures we show generated coins / mined transactions at depth 1
if (!wtx.IsInMainChain())
{
return false;
}
}
return true;
}
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.GetTxTime();
int64_t nCredit = wtx.GetCredit(ISMINE_ALL); //Updated Watch Only
int64_t nDebit = wtx.GetDebit(ISMINE_ALL);
int64_t nNet = nCredit - nDebit;
uint256 hash = wtx.GetHash(), hashPrev = 0;
std::map<std::string, std::string> mapValue = wtx.mapValue;
char cbuf[256];
if (nNet > 0 || wtx.IsCoinBase() || wtx.IsCoinStake())
{
//
// Credit
//
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
isminetype mine = wallet->IsMine(txout);
if(mine)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
sub.credit = txout.nValue;
sub.involvesWatchAddress = mine == ISMINE_WATCH_ONLY;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
{
// Received by Bitcoin Address
sub.type = TransactionRecord::RecvWithAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
snprintf(cbuf, sizeof(cbuf), "n_%u", nOut);
mapValue_t::const_iterator mi = wtx.mapValue.find(cbuf);
if (mi != wtx.mapValue.end() && !mi->second.empty())
sub.narration = mi->second;
if (wtx.IsCoinBase())
{
// Generated (proof-of-work)
sub.type = TransactionRecord::Generated;
}
if (wtx.IsCoinStake())
{
// Generated (proof-of-stake)
if (hashPrev == hash)
continue; // last coinstake output
CAmount nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (IsMine(*wallet,txout.scriptPubKey))
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
sub.type = TransactionRecord::Generated;
sub.credit = nNet > 0 ? nNet : nValueOut - nDebit;
hashPrev = hash;
}
parts.append(sub);
}
}
}
else
{
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
isminetype mine = wallet->IsMine(txin);
if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
isminetype mine = wallet->IsMine(txout);
if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllToMe > mine) fAllToMe = mine;
}
if (fAllFromMe && fAllToMe)
{
// Payment to self
int64_t nChange = wtx.GetChange();
std::string narration("");
mapValue_t::const_iterator mi;
for (mi = wtx.mapValue.begin(); mi != wtx.mapValue.end(); ++mi)
{
if (mi->first.compare(0, 2, "n_") != 0)
continue;
narration = mi->second;
break;
};
parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", narration,
-(nDebit - nChange), nCredit - nChange));
parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument
}
else if (fAllFromMe)
{
//
// Debit
//
int64_t nTxFee = nDebit - wtx.GetValueOut();
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
TransactionRecord sub(hash, nTime);
sub.idx = parts.size();
sub.involvesWatchAddress = involvesWatchAddress;
opcodetype firstOpCode;
CScript::const_iterator pc = txout.scriptPubKey.begin();
if (txout.scriptPubKey.GetOp(pc, firstOpCode)
&& firstOpCode == OP_RETURN)
continue;
if (wallet->IsMine(txout))
{
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
// Sent to Bitcoin Address
sub.type = TransactionRecord::SendToAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Sent to IP, or other non-address transaction like OP_EVAL
sub.type = TransactionRecord::SendToOther;
sub.address = mapValue["to"];
}
snprintf(cbuf, sizeof(cbuf), "n_%u", nOut);
mapValue_t::const_iterator mi = wtx.mapValue.find(cbuf);
if (mi != wtx.mapValue.end() && !mi->second.empty())
sub.narration = mi->second;
int64_t nValue = txout.nValue;
/* Add fee to first output */
if (nTxFee > 0)
{
nValue += nTxFee;
nTxFee = 0;
}
sub.debit = -nValue;
parts.append(sub);
}
}
else
{
//
// Mixed debit transaction, can't break down payees
//
parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", "", nNet, 0));
parts.last().involvesWatchAddress = involvesWatchAddress;
}
}
return parts;
}
void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
AssertLockHeld(cs_main);
// Determine transaction status
int nHeight = std::numeric_limits<int>::max();
// Find the block the tx is in
CBlockIndex* pindex = NULL;
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
{
pindex = (*mi).second;
nHeight = pindex->nHeight;
};
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
nHeight,
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived,
idx);
status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
status.depth = wtx.GetDepthInMainChain();
status.cur_num_blocks = nBestHeight;
if (!wtx.IsFinal())
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
{
status.status = TransactionStatus::OpenUntilBlock;
status.open_for = nBestHeight - wtx.nLockTime;
}
else
{
status.status = TransactionStatus::OpenUntilDate;
status.open_for = wtx.nLockTime;
}
}
// For generated transactions, determine maturity
else if(type == TransactionRecord::Generated)
{
if (wtx.GetBlocksToMaturity() > 0)
{
status.status = TransactionStatus::Immature;
if (wtx.IsInMainChain())
{
status.matures_in = wtx.GetBlocksToMaturity();
// Check if the block was requested by anyone
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
status.status = TransactionStatus::MaturesWarning;
}
else
{
status.status = TransactionStatus::NotAccepted;
}
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
else
{
if (status.depth < 0)
{
status.status = TransactionStatus::Conflicted;
}
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
{
status.status = TransactionStatus::Offline;
}
else if (status.depth == 0)
{
status.status = TransactionStatus::Unconfirmed;
}
else if (status.depth < RecommendedNumConfirmations)
{
status.status = TransactionStatus::Confirming;
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
}
bool TransactionRecord::statusUpdateNeeded()
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != nBestHeight;
}
std::string TransactionRecord::getTxID()
{
return hash.ToString() + strprintf("-%03d", idx);
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 <unistd.h>
#include <gmock/gmock.h>
#include <iostream>
#include <string>
#include <vector>
#include <mesos/resources.hpp>
#include <mesos/module/isolator.hpp>
#include <mesos/slave/isolator.hpp>
#include <process/future.hpp>
#include <process/owned.hpp>
#include <process/reap.hpp>
#include <stout/abort.hpp>
#include <stout/gtest.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#ifdef __linux__
#include "linux/ns.hpp"
#endif // __linux__
#include "master/master.hpp"
#include "master/detector.hpp"
#include "slave/flags.hpp"
#include "slave/slave.hpp"
#ifdef __linux__
#include "slave/containerizer/isolators/cgroups/constants.hpp"
#include "slave/containerizer/isolators/cgroups/cpushare.hpp"
#include "slave/containerizer/isolators/cgroups/mem.hpp"
#include "slave/containerizer/isolators/cgroups/perf_event.hpp"
#include "slave/containerizer/isolators/filesystem/shared.hpp"
#endif // __linux__
#include "slave/containerizer/isolators/posix.hpp"
#include "slave/containerizer/launcher.hpp"
#ifdef __linux__
#include "slave/containerizer/fetcher.hpp"
#include "slave/containerizer/linux_launcher.hpp"
#include "slave/containerizer/mesos/containerizer.hpp"
#include "slave/containerizer/mesos/launch.hpp"
#endif // __linux__
#include "tests/flags.hpp"
#include "tests/mesos.hpp"
#include "tests/module.hpp"
#include "tests/utils.hpp"
#include "tests/containerizer/memory_test_helper.hpp"
using namespace process;
using mesos::internal::master::Master;
#ifdef __linux__
using mesos::internal::slave::CgroupsCpushareIsolatorProcess;
using mesos::internal::slave::CgroupsMemIsolatorProcess;
using mesos::internal::slave::CgroupsPerfEventIsolatorProcess;
using mesos::internal::slave::CPU_SHARES_PER_CPU_REVOCABLE;
using mesos::internal::slave::Fetcher;
using mesos::internal::slave::LinuxLauncher;
using mesos::internal::slave::SharedFilesystemIsolatorProcess;
#endif // __linux__
using mesos::internal::slave::Launcher;
using mesos::internal::slave::MesosContainerizer;
using mesos::internal::slave::PosixLauncher;
using mesos::internal::slave::PosixCpuIsolatorProcess;
using mesos::internal::slave::PosixMemIsolatorProcess;
using mesos::internal::slave::Slave;
using mesos::slave::ContainerPrepareInfo;
using mesos::slave::Isolator;
using std::ostringstream;
using std::set;
using std::string;
using std::vector;
using testing::_;
using testing::DoAll;
using testing::Return;
using testing::SaveArg;
namespace mesos {
namespace internal {
namespace tests {
static int childSetup(int pipes[2])
{
// In child process.
while (::close(pipes[1]) == -1 && errno == EINTR);
// Wait until the parent signals us to continue.
char dummy;
ssize_t length;
while ((length = ::read(pipes[0], &dummy, sizeof(dummy))) == -1 &&
errno == EINTR);
if (length != sizeof(dummy)) {
ABORT("Failed to synchronize with parent");
}
while (::close(pipes[0]) == -1 && errno == EINTR);
return 0;
}
template <typename T>
class CpuIsolatorTest : public MesosTest {};
typedef ::testing::Types<
PosixCpuIsolatorProcess,
#ifdef __linux__
CgroupsCpushareIsolatorProcess,
#endif // __linux__
tests::Module<Isolator, TestCpuIsolator>> CpuIsolatorTypes;
TYPED_TEST_CASE(CpuIsolatorTest, CpuIsolatorTypes);
TYPED_TEST(CpuIsolatorTest, UserCpuUsage)
{
slave::Flags flags;
Try<Isolator*> isolator = TypeParam::create(flags);
CHECK_SOME(isolator);
// A PosixLauncher is sufficient even when testing a cgroups isolator.
Try<Launcher*> launcher = PosixLauncher::create(flags);
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("cpus:1.0").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
dir.get(),
None(),
None()));
const string& file = path::join(dir.get(), "mesos_isolator_test_ready");
// Max out a single core in userspace. This will run for at most one second.
string command = "while true ; do true ; done &"
"touch " + file + "; " // Signals the command is running.
"sleep 60";
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
vector<string> argv(3);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sh",
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
lambda::bind(&childSetup, pipes));
ASSERT_SOME(pid);
// Reap the forked child.
Future<Option<int> > status = process::reap(pid.get());
// Continue in the parent.
ASSERT_SOME(os::close(pipes[0]));
// Isolate the forked child.
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// Now signal the child to continue.
char dummy;
ASSERT_LT(0, ::write(pipes[1], &dummy, sizeof(dummy)));
ASSERT_SOME(os::close(pipes[1]));
// Wait for the command to start.
while (!os::exists(file));
// Wait up to 1 second for the child process to induce 1/8 of a second of
// user cpu time.
ResourceStatistics statistics;
Duration waited = Duration::zero();
do {
Future<ResourceStatistics> usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
statistics = usage.get();
// If we meet our usage expectations, we're done!
if (statistics.cpus_user_time_secs() >= 0.125) {
break;
}
os::sleep(Milliseconds(200));
waited += Milliseconds(200);
} while (waited < Seconds(1));
EXPECT_LE(0.125, statistics.cpus_user_time_secs());
// Ensure all processes are killed.
AWAIT_READY(launcher.get()->destroy(containerId));
// Make sure the child was reaped.
AWAIT_READY(status);
// Let the isolator clean up.
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
delete launcher.get();
}
TYPED_TEST(CpuIsolatorTest, SystemCpuUsage)
{
slave::Flags flags;
Try<Isolator*> isolator = TypeParam::create(flags);
CHECK_SOME(isolator);
// A PosixLauncher is sufficient even when testing a cgroups isolator.
Try<Launcher*> launcher = PosixLauncher::create(flags);
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("cpus:1.0").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
dir.get(),
None(),
None()));
const string& file = path::join(dir.get(), "mesos_isolator_test_ready");
// Generating random numbers is done by the kernel and will max out a single
// core and run almost exclusively in the kernel, i.e., system time.
string command = "cat /dev/urandom > /dev/null & "
"touch " + file + "; " // Signals the command is running.
"sleep 60";
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
vector<string> argv(3);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sh",
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
lambda::bind(&childSetup, pipes));
ASSERT_SOME(pid);
// Reap the forked child.
Future<Option<int> > status = process::reap(pid.get());
// Continue in the parent.
ASSERT_SOME(os::close(pipes[0]));
// Isolate the forked child.
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// Now signal the child to continue.
char dummy;
ASSERT_LT(0, ::write(pipes[1], &dummy, sizeof(dummy)));
ASSERT_SOME(os::close(pipes[1]));
// Wait for the command to start.
while (!os::exists(file));
// Wait up to 1 second for the child process to induce 1/8 of a second of
// system cpu time.
ResourceStatistics statistics;
Duration waited = Duration::zero();
do {
Future<ResourceStatistics> usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
statistics = usage.get();
// If we meet our usage expectations, we're done!
if (statistics.cpus_system_time_secs() >= 0.125) {
break;
}
os::sleep(Milliseconds(200));
waited += Milliseconds(200);
} while (waited < Seconds(1));
EXPECT_LE(0.125, statistics.cpus_system_time_secs());
// Ensure all processes are killed.
AWAIT_READY(launcher.get()->destroy(containerId));
// Make sure the child was reaped.
AWAIT_READY(status);
// Let the isolator clean up.
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
delete launcher.get();
}
#ifdef __linux__
class RevocableCpuIsolatorTest : public MesosTest {};
TEST_F(RevocableCpuIsolatorTest, ROOT_CGROUPS_RevocableCpu)
{
slave::Flags flags;
Try<Isolator*> isolator = CgroupsCpushareIsolatorProcess::create(flags);
CHECK_SOME(isolator);
Try<Launcher*> launcher = PosixLauncher::create(flags);
// Include revocable CPU in the executor's resources.
Resource cpu = Resources::parse("cpus", "1", "*").get();
cpu.mutable_revocable();
ExecutorInfo executorInfo;
executorInfo.add_resources()->CopyFrom(cpu);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
os::getcwd(),
None(),
None()));
vector<string> argv{"sleep", "100"};
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sleep",
argv,
Subprocess::PATH("/dev/null"),
Subprocess::PATH("/dev/null"),
Subprocess::PATH("/dev/null"),
None(),
None(),
None());
ASSERT_SOME(pid);
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// Executor should have proper cpu.shares for revocable containers.
Result<string> cpuHierarchy = cgroups::hierarchy("cpu");
ASSERT_SOME(cpuHierarchy);
Result<string> cpuCgroup = cgroups::cpu::cgroup(pid.get());
ASSERT_SOME(cpuCgroup);
EXPECT_SOME_EQ(
CPU_SHARES_PER_CPU_REVOCABLE,
cgroups::cpu::shares(cpuHierarchy.get(), cpuCgroup.get()));
// Kill the container and clean up.
Future<Option<int>> status = process::reap(pid.get());
AWAIT_READY(launcher.get()->destroy(containerId));
AWAIT_READY(status);
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
delete launcher.get();
}
#endif // __linux__
#ifdef __linux__
class LimitedCpuIsolatorTest : public MesosTest {};
TEST_F(LimitedCpuIsolatorTest, ROOT_CGROUPS_Cfs)
{
slave::Flags flags;
// Enable CFS to cap CPU utilization.
flags.cgroups_enable_cfs = true;
Try<Isolator*> isolator = CgroupsCpushareIsolatorProcess::create(flags);
CHECK_SOME(isolator);
Try<Launcher*> launcher =
LinuxLauncher::create(flags, isolator.get()->namespaces().get());
CHECK_SOME(launcher);
// Set the executor's resources to 0.5 cpu.
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("cpus:0.5").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
dir.get(),
None(),
None()));
// Generate random numbers to max out a single core. We'll run this for 0.5
// seconds of wall time so it should consume approximately 250 ms of total
// cpu time when limited to 0.5 cpu. We use /dev/urandom to prevent blocking
// on Linux when there's insufficient entropy.
string command = "cat /dev/urandom > /dev/null & "
"export MESOS_TEST_PID=$! && "
"sleep 0.5 && "
"kill $MESOS_TEST_PID";
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
vector<string> argv(3);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sh",
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
lambda::bind(&childSetup, pipes));
ASSERT_SOME(pid);
// Reap the forked child.
Future<Option<int> > status = process::reap(pid.get());
// Continue in the parent.
ASSERT_SOME(os::close(pipes[0]));
// Isolate the forked child.
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// Now signal the child to continue.
char dummy;
ASSERT_LT(0, ::write(pipes[1], &dummy, sizeof(dummy)));
ASSERT_SOME(os::close(pipes[1]));
// Wait for the command to complete.
AWAIT_READY(status);
Future<ResourceStatistics> usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
// Expect that no more than 300 ms of cpu time has been consumed. We also
// check that at least 50 ms of cpu time has been consumed so this test will
// fail if the host system is very heavily loaded. This behavior is correct
// because under such conditions we aren't actually testing the CFS cpu
// limiter.
double cpuTime = usage.get().cpus_system_time_secs() +
usage.get().cpus_user_time_secs();
EXPECT_GE(0.30, cpuTime);
EXPECT_LE(0.05, cpuTime);
// Ensure all processes are killed.
AWAIT_READY(launcher.get()->destroy(containerId));
// Let the isolator clean up.
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
delete launcher.get();
}
// This test verifies that we can successfully launch a container with
// a big (>= 10 cpus) cpu quota. This is to catch the regression
// observed in MESOS-1049.
// TODO(vinod): Revisit this if/when the isolator restricts the number
// of cpus that an executor can use based on the slave cpus.
TEST_F(LimitedCpuIsolatorTest, ROOT_CGROUPS_Cfs_Big_Quota)
{
slave::Flags flags;
// Enable CFS to cap CPU utilization.
flags.cgroups_enable_cfs = true;
Try<Isolator*> isolator = CgroupsCpushareIsolatorProcess::create(flags);
CHECK_SOME(isolator);
Try<Launcher*> launcher =
LinuxLauncher::create(flags, isolator.get()->namespaces().get());
CHECK_SOME(launcher);
// Set the executor's resources to 100.5 cpu.
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("cpus:100.5").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
dir.get(),
None(),
None()));
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
vector<string> argv(3);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = "exit 0";
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sh",
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
lambda::bind(&childSetup, pipes));
ASSERT_SOME(pid);
// Reap the forked child.
Future<Option<int> > status = process::reap(pid.get());
// Continue in the parent.
ASSERT_SOME(os::close(pipes[0]));
// Isolate the forked child.
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// Now signal the child to continue.
char dummy;
ASSERT_LT(0, ::write(pipes[1], &dummy, sizeof(dummy)));
ASSERT_SOME(os::close(pipes[1]));
// Wait for the command to complete successfully.
AWAIT_READY(status);
ASSERT_SOME_EQ(0, status.get());
// Ensure all processes are killed.
AWAIT_READY(launcher.get()->destroy(containerId));
// Let the isolator clean up.
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
delete launcher.get();
}
// A test to verify the number of processes and threads in a
// container.
TEST_F(LimitedCpuIsolatorTest, ROOT_CGROUPS_Pids_and_Tids)
{
slave::Flags flags;
flags.cgroups_cpu_enable_pids_and_tids_count = true;
Try<Isolator*> isolator = CgroupsCpushareIsolatorProcess::create(flags);
CHECK_SOME(isolator);
Try<Launcher*> launcher =
LinuxLauncher::create(flags, isolator.get()->namespaces().get());
CHECK_SOME(launcher);
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("cpus:0.5;mem:512").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
dir.get(),
None(),
None()));
// Right after the creation of the cgroup, which happens in
// 'prepare', we check that it is empty.
Future<ResourceStatistics> usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
EXPECT_EQ(0U, usage.get().processes());
EXPECT_EQ(0U, usage.get().threads());
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
vector<string> argv(3);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = "while true; do sleep 1; done;";
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sh",
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
lambda::bind(&childSetup, pipes));
ASSERT_SOME(pid);
// Reap the forked child.
Future<Option<int>> status = process::reap(pid.get());
// Continue in the parent.
ASSERT_SOME(os::close(pipes[0]));
// Before isolation, the cgroup is empty.
usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
EXPECT_EQ(0U, usage.get().processes());
EXPECT_EQ(0U, usage.get().threads());
// Isolate the forked child.
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// After the isolation, the cgroup is not empty, even though the
// process hasn't exec'd yet.
usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
EXPECT_EQ(1U, usage.get().processes());
EXPECT_EQ(1U, usage.get().threads());
// Now signal the child to continue.
char dummy;
ASSERT_LT(0, ::write(pipes[1], &dummy, sizeof(dummy)));
ASSERT_SOME(os::close(pipes[1]));
// Process count should be 1 since 'sleep' is still sleeping.
usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
EXPECT_EQ(1U, usage.get().processes());
EXPECT_EQ(1U, usage.get().threads());
// Ensure all processes are killed.
AWAIT_READY(launcher.get()->destroy(containerId));
// Wait for the command to complete.
AWAIT_READY(status);
// After the process is killed, the cgroup should be empty again.
usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
EXPECT_EQ(0U, usage.get().processes());
EXPECT_EQ(0U, usage.get().threads());
// Let the isolator clean up.
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
delete launcher.get();
}
#endif // __linux__
template <typename T>
class MemIsolatorTest : public MesosTest {};
typedef ::testing::Types<
PosixMemIsolatorProcess,
#ifdef __linux__
CgroupsMemIsolatorProcess,
#endif // __linux__
tests::Module<Isolator, TestMemIsolator>> MemIsolatorTypes;
TYPED_TEST_CASE(MemIsolatorTest, MemIsolatorTypes);
TYPED_TEST(MemIsolatorTest, MemUsage)
{
slave::Flags flags;
Try<Isolator*> isolator = TypeParam::create(flags);
CHECK_SOME(isolator);
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("mem:1024").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
dir.get(),
None(),
None()));
MemoryTestHelper helper;
ASSERT_SOME(helper.spawn());
ASSERT_SOME(helper.pid());
// Set up the reaper to wait on the subprocess.
Future<Option<int>> status = process::reap(helper.pid().get());
// Isolate the subprocess.
AWAIT_READY(isolator.get()->isolate(containerId, helper.pid().get()));
const Bytes allocation = Megabytes(128);
EXPECT_SOME(helper.increaseRSS(allocation));
Future<ResourceStatistics> usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
EXPECT_GE(usage.get().mem_rss_bytes(), allocation.bytes());
// Ensure the process is killed.
helper.cleanup();
// Make sure the subprocess was reaped.
AWAIT_READY(status);
// Let the isolator clean up.
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
}
#ifdef __linux__
class PerfEventIsolatorTest : public MesosTest {};
TEST_F(PerfEventIsolatorTest, ROOT_CGROUPS_Sample)
{
slave::Flags flags;
flags.perf_events = "cycles,task-clock";
flags.perf_duration = Milliseconds(250);
flags.perf_interval = Milliseconds(500);
Try<Isolator*> isolator = CgroupsPerfEventIsolatorProcess::create(flags);
ASSERT_SOME(isolator);
ExecutorInfo executorInfo;
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
dir.get(),
None(),
None()));
// This first sample is likely to be empty because perf hasn't
// completed yet but we should still have the required fields.
Future<ResourceStatistics> statistics1 = isolator.get()->usage(containerId);
AWAIT_READY(statistics1);
ASSERT_TRUE(statistics1.get().has_perf());
EXPECT_TRUE(statistics1.get().perf().has_timestamp());
EXPECT_TRUE(statistics1.get().perf().has_duration());
// Wait until we get the next sample. We use a generous timeout of
// two seconds because we currently have a one second reap interval;
// when running perf with perf_duration of 250ms we won't notice the
// exit for up to one second.
ResourceStatistics statistics2;
Duration waited = Duration::zero();
do {
Future<ResourceStatistics> statistics = isolator.get()->usage(containerId);
AWAIT_READY(statistics);
statistics2 = statistics.get();
ASSERT_TRUE(statistics2.has_perf());
if (statistics1.get().perf().timestamp() !=
statistics2.perf().timestamp()) {
break;
}
os::sleep(Milliseconds(250));
waited += Milliseconds(250);
} while (waited < Seconds(2));
sleep(2);
EXPECT_NE(statistics1.get().perf().timestamp(),
statistics2.perf().timestamp());
EXPECT_TRUE(statistics2.perf().has_cycles());
EXPECT_LE(0u, statistics2.perf().cycles());
EXPECT_TRUE(statistics2.perf().has_task_clock());
EXPECT_LE(0.0, statistics2.perf().task_clock());
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
}
class SharedFilesystemIsolatorTest : public MesosTest {};
// Test that a container can create a private view of a system
// directory (/var/tmp). Check that a file written by a process inside
// the container doesn't appear on the host filesystem but does appear
// under the container's work directory.
// This test is disabled since we're planning to remove the shared
// filesystem isolator and this test is not working on other distros
// such as CentOS 7.1
// TODO(tnachen): Remove this test when shared filesystem isolator
// is removed.
TEST_F(SharedFilesystemIsolatorTest, DISABLED_ROOT_RelativeVolume)
{
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/shared";
Try<Isolator*> isolator = SharedFilesystemIsolatorProcess::create(flags);
CHECK_SOME(isolator);
Try<Launcher*> launcher =
LinuxLauncher::create(flags, isolator.get()->namespaces().get());
CHECK_SOME(launcher);
// Use /var/tmp so we don't mask the work directory (under /tmp).
const string containerPath = "/var/tmp";
ASSERT_TRUE(os::stat::isdir(containerPath));
// Use a host path relative to the container work directory.
const string hostPath = strings::remove(containerPath, "/", strings::PREFIX);
ContainerInfo containerInfo;
containerInfo.set_type(ContainerInfo::MESOS);
containerInfo.add_volumes()->CopyFrom(
CREATE_VOLUME(containerPath, hostPath, Volume::RW));
ExecutorInfo executorInfo;
executorInfo.mutable_container()->CopyFrom(containerInfo);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
Future<Option<ContainerPrepareInfo> > prepare =
isolator.get()->prepare(
containerId,
executorInfo,
flags.work_dir,
None(),
None());
AWAIT_READY(prepare);
ASSERT_SOME(prepare.get());
ASSERT_EQ(1, prepare.get().get().commands().size());
// The test will touch a file in container path.
const string file = path::join(containerPath, UUID::random().toString());
ASSERT_FALSE(os::exists(file));
// Manually run the isolator's preparation command first, then touch
// the file.
vector<string> args;
args.push_back("/bin/sh");
args.push_back("-x");
args.push_back("-c");
args.push_back(prepare.get().get().commands(0).value() + " && touch " + file);
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sh",
args,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
None());
ASSERT_SOME(pid);
// Set up the reaper to wait on the forked child.
Future<Option<int> > status = process::reap(pid.get());
AWAIT_READY(status);
EXPECT_SOME_EQ(0, status.get());
// Check the correct hierarchy was created under the container work
// directory.
string dir = "/";
foreach (const string& subdir, strings::tokenize(containerPath, "/")) {
dir = path::join(dir, subdir);
struct stat hostStat;
EXPECT_EQ(0, ::stat(dir.c_str(), &hostStat));
struct stat containerStat;
EXPECT_EQ(0,
::stat(path::join(flags.work_dir, dir).c_str(), &containerStat));
EXPECT_EQ(hostStat.st_mode, containerStat.st_mode);
EXPECT_EQ(hostStat.st_uid, containerStat.st_uid);
EXPECT_EQ(hostStat.st_gid, containerStat.st_gid);
}
// Check it did *not* create a file in the host namespace.
EXPECT_FALSE(os::exists(file));
// Check it did create the file under the container's work directory
// on the host.
EXPECT_TRUE(os::exists(path::join(flags.work_dir, file)));
delete launcher.get();
delete isolator.get();
}
// This test is disabled since we're planning to remove the shared
// filesystem isolator and this test is not working on other distros
// such as CentOS 7.1
// TODO(tnachen): Remove this test when shared filesystem isolator
// is removed.
TEST_F(SharedFilesystemIsolatorTest, DISABLED_ROOT_AbsoluteVolume)
{
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/shared";
Try<Isolator*> isolator = SharedFilesystemIsolatorProcess::create(flags);
CHECK_SOME(isolator);
Try<Launcher*> launcher =
LinuxLauncher::create(flags, isolator.get()->namespaces().get());
CHECK_SOME(launcher);
// We'll mount the absolute test work directory as /var/tmp in the
// container.
const string hostPath = flags.work_dir;
const string containerPath = "/var/tmp";
ContainerInfo containerInfo;
containerInfo.set_type(ContainerInfo::MESOS);
containerInfo.add_volumes()->CopyFrom(
CREATE_VOLUME(containerPath, hostPath, Volume::RW));
ExecutorInfo executorInfo;
executorInfo.mutable_container()->CopyFrom(containerInfo);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
Future<Option<ContainerPrepareInfo> > prepare =
isolator.get()->prepare(
containerId,
executorInfo,
flags.work_dir,
None(),
None());
AWAIT_READY(prepare);
ASSERT_SOME(prepare.get());
ASSERT_EQ(1, prepare.get().get().commands().size());
// Test the volume mounting by touching a file in the container's
// /tmp, which should then be in flags.work_dir.
const string filename = UUID::random().toString();
ASSERT_FALSE(os::exists(path::join(containerPath, filename)));
vector<string> args;
args.push_back("/bin/sh");
args.push_back("-x");
args.push_back("-c");
args.push_back(prepare.get().get().commands(0).value() +
" && touch " +
path::join(containerPath, filename));
Try<pid_t> pid = launcher.get()->fork(
containerId,
"/bin/sh",
args,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
None());
ASSERT_SOME(pid);
// Set up the reaper to wait on the forked child.
Future<Option<int> > status = process::reap(pid.get());
AWAIT_READY(status);
EXPECT_SOME_EQ(0, status.get());
// Check the file was created in flags.work_dir.
EXPECT_TRUE(os::exists(path::join(hostPath, filename)));
// Check it didn't get created in the host's view of containerPath.
EXPECT_FALSE(os::exists(path::join(containerPath, filename)));
delete launcher.get();
delete isolator.get();
}
class NamespacesPidIsolatorTest : public MesosTest {};
TEST_F(NamespacesPidIsolatorTest, ROOT_PidNamespace)
{
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "namespaces/pid";
string directory = os::getcwd(); // We're inside a temporary sandbox.
Fetcher fetcher;
Try<MesosContainerizer*> containerizer =
MesosContainerizer::create(flags, false, &fetcher);
ASSERT_SOME(containerizer);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Write the command's pid namespace inode and init name to files.
const string command =
"stat -c %i /proc/self/ns/pid > ns && (cat /proc/1/comm > init)";
process::Future<bool> launch = containerizer.get()->launch(
containerId,
CREATE_EXECUTOR_INFO("executor", command),
directory,
None(),
SlaveID(),
process::PID<Slave>(),
false);
AWAIT_READY(launch);
ASSERT_TRUE(launch.get());
// Wait on the container.
process::Future<containerizer::Termination> wait =
containerizer.get()->wait(containerId);
AWAIT_READY(wait);
// Check the executor exited correctly.
EXPECT_TRUE(wait.get().has_status());
EXPECT_EQ(0, wait.get().status());
// Check that the command was run in a different pid namespace.
Try<ino_t> testPidNamespace = ns::getns(::getpid(), "pid");
ASSERT_SOME(testPidNamespace);
Try<string> containerPidNamespace = os::read(path::join(directory, "ns"));
ASSERT_SOME(containerPidNamespace);
EXPECT_NE(stringify(testPidNamespace.get()),
strings::trim(containerPidNamespace.get()));
// Check that 'sh' is the container's 'init' process.
// This verifies that /proc has been correctly mounted for the container.
Try<string> init = os::read(path::join(directory, "init"));
ASSERT_SOME(init);
EXPECT_EQ("sh", strings::trim(init.get()));
delete containerizer.get();
}
// Username for the unprivileged user that will be created to test
// unprivileged cgroup creation. It will be removed after the tests.
// It is presumed this user does not normally exist.
const string UNPRIVILEGED_USERNAME = "mesos.test.unprivileged.user";
template <typename T>
class UserCgroupIsolatorTest : public MesosTest
{
public:
static void SetUpTestCase()
{
// Remove the user in case it wasn't cleaned up from a previous
// test.
os::system("userdel -r " + UNPRIVILEGED_USERNAME + " > /dev/null");
ASSERT_EQ(0, os::system("useradd " + UNPRIVILEGED_USERNAME));
}
static void TearDownTestCase()
{
ASSERT_EQ(0, os::system("userdel -r " + UNPRIVILEGED_USERNAME));
}
};
// Test all isolators that use cgroups.
typedef ::testing::Types<
CgroupsMemIsolatorProcess,
CgroupsCpushareIsolatorProcess,
CgroupsPerfEventIsolatorProcess> CgroupsIsolatorTypes;
TYPED_TEST_CASE(UserCgroupIsolatorTest, CgroupsIsolatorTypes);
TYPED_TEST(UserCgroupIsolatorTest, ROOT_CGROUPS_UserCgroup)
{
slave::Flags flags;
flags.perf_events = "cpu-cycles"; // Needed for CgroupsPerfEventIsolator.
Try<Isolator*> isolator = TypeParam::create(flags);
ASSERT_SOME(isolator);
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("mem:1024;cpus:1").get()); // For cpu/mem isolators.
ContainerID containerId;
containerId.set_value(UUID::random().toString());
AWAIT_READY(isolator.get()->prepare(
containerId,
executorInfo,
os::getcwd(),
None(),
UNPRIVILEGED_USERNAME));
// Isolators don't provide a way to determine the cgroups they use
// so we'll inspect the cgroups for an isolated dummy process.
pid_t pid = fork();
if (pid == 0) {
// Child just sleeps.
::sleep(100);
ABORT("Child process should not reach here");
}
ASSERT_GT(pid, 0);
AWAIT_READY(isolator.get()->isolate(containerId, pid));
// Get the container's cgroups from /proc/$PID/cgroup. We're only
// interested in the cgroups that this isolator has created which we
// can do explicitly by selecting those that have the path that
// corresponds to the 'cgroups_root' slave flag. For example:
//
// $ cat /proc/pid/cgroup
// 6:blkio:/
// 5:perf_event:/
// 4:memory:/mesos/b7410ed8-c85b-445e-b50e-3a1698d0e18c
// 3:freezer:/
// 2:cpuacct:/
// 1:cpu:/
//
// Our 'grep' will only select the 'memory' line and then 'awk' will
// output 'memory/mesos/b7410ed8-c85b-445e-b50e-3a1698d0e18c'.
ostringstream output;
Try<int> status = os::shell(
&output,
"grep '" + path::join("/", flags.cgroups_root) + "' /proc/" +
stringify(pid) + "/cgroup | awk -F ':' '{print $2$3}'");
ASSERT_SOME(status);
// Kill the dummy child process.
::kill(pid, SIGKILL);
int exitStatus;
EXPECT_NE(-1, ::waitpid(pid, &exitStatus, 0));
vector<string> cgroups = strings::tokenize(output.str(), "\n");
ASSERT_FALSE(cgroups.empty());
foreach (const string& cgroup, cgroups) {
// Check the user cannot manipulate the container's cgroup control
// files.
EXPECT_NE(0, os::system(
"su - " + UNPRIVILEGED_USERNAME +
" -c 'echo $$ >" +
path::join(flags.cgroups_hierarchy, cgroup, "cgroup.procs") +
"'"));
// Check the user can create a cgroup under the container's
// cgroup.
string userCgroup = path::join(cgroup, "user");
EXPECT_EQ(0, os::system(
"su - " +
UNPRIVILEGED_USERNAME +
" -c 'mkdir " +
path::join(flags.cgroups_hierarchy, userCgroup) +
"'"));
// Check the user can manipulate control files in the created
// cgroup.
EXPECT_EQ(0, os::system(
"su - " +
UNPRIVILEGED_USERNAME +
" -c 'echo $$ >" +
path::join(flags.cgroups_hierarchy, userCgroup, "cgroup.procs") +
"'"));
}
// Clean up the container. This will also remove the nested cgroups.
AWAIT_READY(isolator.get()->cleanup(containerId));
delete isolator.get();
}
#endif // __linux__
} // namespace tests {
} // namespace internal {
} // namespace mesos {
|
#include <any>
#include <common/logger_useful.h>
#include <Columns/ColumnConst.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnNullable.h>
#include <DataTypes/DataTypeNullable.h>
#include <Interpreters/Join.h>
#include <Interpreters/join_common.h>
#include <Interpreters/AnalyzedJoin.h>
#include <Interpreters/joinDispatch.h>
#include <Interpreters/NullableUtils.h>
#include <DataStreams/IBlockInputStream.h>
#include <DataStreams/materializeBlock.h>
#include <Core/ColumnNumbers.h>
#include <Common/typeid_cast.h>
#include <Common/assert_cast.h>
#include <DataTypes/DataTypeLowCardinality.h>
namespace DB
{
namespace ErrorCodes
{
extern const int UNSUPPORTED_JOIN_KEYS;
extern const int LOGICAL_ERROR;
extern const int SET_SIZE_LIMIT_EXCEEDED;
extern const int TYPE_MISMATCH;
extern const int ILLEGAL_COLUMN;
}
static ColumnPtr filterWithBlanks(ColumnPtr src_column, const IColumn::Filter & filter, bool inverse_filter = false)
{
ColumnPtr column = src_column->convertToFullColumnIfConst();
MutableColumnPtr mut_column = column->cloneEmpty();
mut_column->reserve(column->size());
if (inverse_filter)
{
for (size_t row = 0; row < filter.size(); ++row)
{
if (filter[row])
mut_column->insertDefault();
else
mut_column->insertFrom(*column, row);
}
}
else
{
for (size_t row = 0; row < filter.size(); ++row)
{
if (filter[row])
mut_column->insertFrom(*column, row);
else
mut_column->insertDefault();
}
}
return mut_column;
}
static ColumnWithTypeAndName correctNullability(ColumnWithTypeAndName && column, bool nullable)
{
if (nullable)
{
JoinCommon::convertColumnToNullable(column);
}
else
{
/// We have to replace values masked by NULLs with defaults.
if (column.column)
if (auto * nullable_column = checkAndGetColumn<ColumnNullable>(*column.column))
column.column = filterWithBlanks(column.column, nullable_column->getNullMapColumn().getData(), true);
JoinCommon::removeColumnNullability(column);
}
return std::move(column);
}
static ColumnWithTypeAndName correctNullability(ColumnWithTypeAndName && column, bool nullable, const ColumnUInt8 & negative_null_map)
{
if (nullable)
{
JoinCommon::convertColumnToNullable(column);
if (column.type->isNullable() && negative_null_map.size())
{
MutableColumnPtr mutable_column = (*std::move(column.column)).mutate();
assert_cast<ColumnNullable &>(*mutable_column).applyNegatedNullMap(negative_null_map);
column.column = std::move(mutable_column);
}
}
else
JoinCommon::removeColumnNullability(column);
return std::move(column);
}
static void changeNullability(MutableColumnPtr & mutable_column)
{
ColumnPtr column = std::move(mutable_column);
if (auto * nullable = checkAndGetColumn<ColumnNullable>(*column))
column = nullable->getNestedColumnPtr();
else
column = makeNullable(column);
mutable_column = (*std::move(column)).mutate();
}
Join::Join(std::shared_ptr<AnalyzedJoin> table_join_, const Block & right_sample_block, bool any_take_last_row_)
: table_join(table_join_)
, kind(table_join->kind())
, strictness(table_join->strictness())
, key_names_right(table_join->keyNamesRight())
, nullable_right_side(table_join->forceNullableRight())
, nullable_left_side(table_join->forceNullableLeft())
, any_take_last_row(any_take_last_row_)
, asof_inequality(table_join->getAsofInequality())
, data(std::make_shared<RightTableData>())
, log(&Logger::get("Join"))
{
setSampleBlock(right_sample_block);
}
Join::Type Join::chooseMethod(const ColumnRawPtrs & key_columns, Sizes & key_sizes)
{
size_t keys_size = key_columns.size();
if (keys_size == 0)
return Type::CROSS;
bool all_fixed = true;
size_t keys_bytes = 0;
key_sizes.resize(keys_size);
for (size_t j = 0; j < keys_size; ++j)
{
if (!key_columns[j]->isFixedAndContiguous())
{
all_fixed = false;
break;
}
key_sizes[j] = key_columns[j]->sizeOfValueIfFixed();
keys_bytes += key_sizes[j];
}
/// If there is one numeric key that fits in 64 bits
if (keys_size == 1 && key_columns[0]->isNumeric())
{
size_t size_of_field = key_columns[0]->sizeOfValueIfFixed();
if (size_of_field == 1)
return Type::key8;
if (size_of_field == 2)
return Type::key16;
if (size_of_field == 4)
return Type::key32;
if (size_of_field == 8)
return Type::key64;
if (size_of_field == 16)
return Type::keys128;
throw Exception("Logical error: numeric column has sizeOfField not in 1, 2, 4, 8, 16.", ErrorCodes::LOGICAL_ERROR);
}
/// If the keys fit in N bits, we will use a hash table for N-bit-packed keys
if (all_fixed && keys_bytes <= 16)
return Type::keys128;
if (all_fixed && keys_bytes <= 32)
return Type::keys256;
/// If there is single string key, use hash table of it's values.
if (keys_size == 1
&& (typeid_cast<const ColumnString *>(key_columns[0])
|| (isColumnConst(*key_columns[0]) && typeid_cast<const ColumnString *>(&assert_cast<const ColumnConst *>(key_columns[0])->getDataColumn()))))
return Type::key_string;
if (keys_size == 1 && typeid_cast<const ColumnFixedString *>(key_columns[0]))
return Type::key_fixed_string;
/// Otherwise, will use set of cryptographic hashes of unambiguously serialized values.
return Type::hashed;
}
static const IColumn * extractAsofColumn(const ColumnRawPtrs & key_columns)
{
return key_columns.back();
}
template<typename KeyGetter, bool is_asof_join>
static KeyGetter createKeyGetter(const ColumnRawPtrs & key_columns, const Sizes & key_sizes)
{
if constexpr (is_asof_join)
{
auto key_column_copy = key_columns;
auto key_size_copy = key_sizes;
key_column_copy.pop_back();
key_size_copy.pop_back();
return KeyGetter(key_column_copy, key_size_copy, nullptr);
}
else
return KeyGetter(key_columns, key_sizes, nullptr);
}
template <Join::Type type, typename Value, typename Mapped>
struct KeyGetterForTypeImpl;
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::key8, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt8, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::key16, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt16, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::key32, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt32, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::key64, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt64, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::key_string, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodString<Value, Mapped, true, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::key_fixed_string, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodFixedString<Value, Mapped, true, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::keys128, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodKeysFixed<Value, UInt128, Mapped, false, false, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::keys256, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodKeysFixed<Value, UInt256, Mapped, false, false, false>;
};
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<Join::Type::hashed, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodHashed<Value, Mapped, false>;
};
template <Join::Type type, typename Data>
struct KeyGetterForType
{
using Value = typename Data::value_type;
using Mapped_t = typename Data::mapped_type;
using Mapped = std::conditional_t<std::is_const_v<Data>, const Mapped_t, Mapped_t>;
using Type = typename KeyGetterForTypeImpl<type, Value, Mapped>::Type;
};
void Join::init(Type type_)
{
data->type = type_;
if (kind == ASTTableJoin::Kind::Cross)
return;
joinDispatchInit(kind, strictness, data->maps);
joinDispatch(kind, strictness, data->maps, [&](auto, auto, auto & map) { map.create(data->type); });
}
size_t Join::getTotalRowCount() const
{
size_t res = 0;
if (data->type == Type::CROSS)
{
for (const auto & block : data->blocks)
res += block.rows();
}
else
{
joinDispatch(kind, strictness, data->maps, [&](auto, auto, auto & map) { res += map.getTotalRowCount(data->type); });
}
return res;
}
size_t Join::getTotalByteCount() const
{
size_t res = 0;
if (data->type == Type::CROSS)
{
for (const auto & block : data->blocks)
res += block.bytes();
}
else
{
joinDispatch(kind, strictness, data->maps, [&](auto, auto, auto & map) { res += map.getTotalByteCountImpl(data->type); });
res += data->pool.size();
}
return res;
}
void Join::setSampleBlock(const Block & block)
{
/// You have to restore this lock if you call the fuction outside of ctor.
//std::unique_lock lock(rwlock);
LOG_DEBUG(log, "setSampleBlock: " << block.dumpStructure());
if (!empty())
return;
ColumnRawPtrs key_columns = JoinCommon::extractKeysForJoin(key_names_right, block, right_table_keys, sample_block_with_columns_to_add);
initRightBlockStructure();
initRequiredRightKeys();
JoinCommon::createMissedColumns(sample_block_with_columns_to_add);
if (nullable_right_side)
JoinCommon::convertColumnsToNullable(sample_block_with_columns_to_add);
if (strictness == ASTTableJoin::Strictness::Asof)
{
if (kind != ASTTableJoin::Kind::Left and kind != ASTTableJoin::Kind::Inner)
throw Exception("ASOF only supports LEFT and INNER as base joins", ErrorCodes::NOT_IMPLEMENTED);
const IColumn * asof_column = key_columns.back();
size_t asof_size;
asof_type = AsofRowRefs::getTypeSize(asof_column, asof_size);
if (!asof_type)
{
std::string msg = "ASOF join not supported for type: ";
msg += asof_column->getFamilyName();
throw Exception(msg, ErrorCodes::BAD_TYPE_OF_FIELD);
}
key_columns.pop_back();
if (key_columns.empty())
throw Exception("ASOF join cannot be done without a joining column", ErrorCodes::LOGICAL_ERROR);
/// this is going to set up the appropriate hash table for the direct lookup part of the join
/// However, this does not depend on the size of the asof join key (as that goes into the BST)
/// Therefore, add it back in such that it can be extracted appropriately from the full stored
/// key_columns and key_sizes
init(chooseMethod(key_columns, key_sizes));
key_sizes.push_back(asof_size);
}
else
{
/// Choose data structure to use for JOIN.
init(chooseMethod(key_columns, key_sizes));
}
}
namespace
{
/// Inserting an element into a hash table of the form `key -> reference to a string`, which will then be used by JOIN.
template <typename Map, typename KeyGetter>
struct Inserter
{
static ALWAYS_INLINE void insertOne(const Join & join, Map & map, KeyGetter & key_getter, Block * stored_block, size_t i,
Arena & pool)
{
auto emplace_result = key_getter.emplaceKey(map, i, pool);
if (emplace_result.isInserted() || join.anyTakeLastRow())
new (&emplace_result.getMapped()) typename Map::mapped_type(stored_block, i);
}
static ALWAYS_INLINE void insertAll(const Join &, Map & map, KeyGetter & key_getter, Block * stored_block, size_t i, Arena & pool)
{
auto emplace_result = key_getter.emplaceKey(map, i, pool);
if (emplace_result.isInserted())
new (&emplace_result.getMapped()) typename Map::mapped_type(stored_block, i);
else
{
/// The first element of the list is stored in the value of the hash table, the rest in the pool.
emplace_result.getMapped().insert({stored_block, i}, pool);
}
}
static ALWAYS_INLINE void insertAsof(Join & join, Map & map, KeyGetter & key_getter, Block * stored_block, size_t i, Arena & pool,
const IColumn * asof_column)
{
auto emplace_result = key_getter.emplaceKey(map, i, pool);
typename Map::mapped_type * time_series_map = &emplace_result.getMapped();
if (emplace_result.isInserted())
time_series_map = new (time_series_map) typename Map::mapped_type(join.getAsofType());
time_series_map->insert(join.getAsofType(), asof_column, stored_block, i);
}
};
template <ASTTableJoin::Strictness STRICTNESS, typename KeyGetter, typename Map, bool has_null_map>
void NO_INLINE insertFromBlockImplTypeCase(
Join & join, Map & map, size_t rows, const ColumnRawPtrs & key_columns,
const Sizes & key_sizes, Block * stored_block, ConstNullMapPtr null_map, Arena & pool)
{
[[maybe_unused]] constexpr bool mapped_one = std::is_same_v<typename Map::mapped_type, JoinStuff::MappedOne> ||
std::is_same_v<typename Map::mapped_type, JoinStuff::MappedOneFlagged>;
constexpr bool is_asof_join = STRICTNESS == ASTTableJoin::Strictness::Asof;
const IColumn * asof_column [[maybe_unused]] = nullptr;
if constexpr (is_asof_join)
asof_column = extractAsofColumn(key_columns);
auto key_getter = createKeyGetter<KeyGetter, is_asof_join>(key_columns, key_sizes);
for (size_t i = 0; i < rows; ++i)
{
if (has_null_map && (*null_map)[i])
continue;
if constexpr (is_asof_join)
Inserter<Map, KeyGetter>::insertAsof(join, map, key_getter, stored_block, i, pool, asof_column);
else if constexpr (mapped_one)
Inserter<Map, KeyGetter>::insertOne(join, map, key_getter, stored_block, i, pool);
else
Inserter<Map, KeyGetter>::insertAll(join, map, key_getter, stored_block, i, pool);
}
}
template <ASTTableJoin::Strictness STRICTNESS, typename KeyGetter, typename Map>
void insertFromBlockImplType(
Join & join, Map & map, size_t rows, const ColumnRawPtrs & key_columns,
const Sizes & key_sizes, Block * stored_block, ConstNullMapPtr null_map, Arena & pool)
{
if (null_map)
insertFromBlockImplTypeCase<STRICTNESS, KeyGetter, Map, true>(join, map, rows, key_columns, key_sizes, stored_block, null_map, pool);
else
insertFromBlockImplTypeCase<STRICTNESS, KeyGetter, Map, false>(join, map, rows, key_columns, key_sizes, stored_block, null_map, pool);
}
template <ASTTableJoin::Strictness STRICTNESS, typename Maps>
void insertFromBlockImpl(
Join & join, Join::Type type, Maps & maps, size_t rows, const ColumnRawPtrs & key_columns,
const Sizes & key_sizes, Block * stored_block, ConstNullMapPtr null_map, Arena & pool)
{
switch (type)
{
case Join::Type::EMPTY: break;
case Join::Type::CROSS: break; /// Do nothing. We have already saved block, and it is enough.
#define M(TYPE) \
case Join::Type::TYPE: \
insertFromBlockImplType<STRICTNESS, typename KeyGetterForType<Join::Type::TYPE, std::remove_reference_t<decltype(*maps.TYPE)>>::Type>(\
join, *maps.TYPE, rows, key_columns, key_sizes, stored_block, null_map, pool); \
break;
APPLY_FOR_JOIN_VARIANTS(M)
#undef M
}
}
}
void Join::initRequiredRightKeys()
{
const Names & left_keys = table_join->keyNamesLeft();
const Names & right_keys = table_join->keyNamesRight();
NameSet required_keys(table_join->requiredRightKeys().begin(), table_join->requiredRightKeys().end());
for (size_t i = 0; i < right_keys.size(); ++i)
{
const String & right_key_name = right_keys[i];
if (required_keys.count(right_key_name) && !required_right_keys.has(right_key_name))
{
const auto & right_key = right_table_keys.getByName(right_key_name);
required_right_keys.insert(right_key);
required_right_keys_sources.push_back(left_keys[i]);
}
}
}
void Join::initRightBlockStructure()
{
auto & saved_block_sample = data->sample_block;
if (isRightOrFull(kind))
{
/// Save keys for NonJoinedBlockInputStream
saved_block_sample = right_table_keys.cloneEmpty();
}
else if (strictness == ASTTableJoin::Strictness::Asof)
{
/// Save ASOF key
saved_block_sample.insert(right_table_keys.safeGetByPosition(right_table_keys.columns() - 1));
}
/// Save non key columns
for (auto & column : sample_block_with_columns_to_add)
saved_block_sample.insert(column);
if (nullable_right_side)
JoinCommon::convertColumnsToNullable(saved_block_sample, (isFull(kind) ? right_table_keys.columns() : 0));
}
Block Join::structureRightBlock(const Block & block) const
{
Block structured_block;
for (auto & sample_column : savedBlockSample().getColumnsWithTypeAndName())
{
ColumnWithTypeAndName column = block.getByName(sample_column.name);
if (sample_column.column->isNullable())
JoinCommon::convertColumnToNullable(column);
structured_block.insert(column);
}
return structured_block;
}
bool Join::addJoinedBlock(const Block & source_block)
{
if (empty())
throw Exception("Logical error: Join was not initialized", ErrorCodes::LOGICAL_ERROR);
/// There's no optimization for right side const columns. Remove constness if any.
Block block = materializeBlock(source_block);
size_t rows = block.rows();
ColumnRawPtrs key_columns = JoinCommon::materializeColumnsInplace(block, key_names_right);
/// We will insert to the map only keys, where all components are not NULL.
ConstNullMapPtr null_map{};
ColumnPtr null_map_holder = extractNestedColumnsAndNullMap(key_columns, null_map);
/// If RIGHT or FULL save blocks with nulls for NonJoinedBlockInputStream
UInt8 save_nullmap = 0;
if (isRightOrFull(kind) && null_map)
{
for (size_t i = 0; !save_nullmap && i < null_map->size(); ++i)
save_nullmap |= (*null_map)[i];
}
Block structured_block = structureRightBlock(block);
size_t total_rows = 0;
size_t total_bytes = 0;
{
std::unique_lock lock(data->rwlock);
data->blocks.emplace_back(std::move(structured_block));
Block * stored_block = &data->blocks.back();
if (rows)
data->empty = false;
if (kind != ASTTableJoin::Kind::Cross)
{
joinDispatch(kind, strictness, data->maps, [&](auto, auto strictness_, auto & map)
{
insertFromBlockImpl<strictness_>(*this, data->type, map, rows, key_columns, key_sizes, stored_block, null_map, data->pool);
});
}
if (save_nullmap)
data->blocks_nullmaps.emplace_back(stored_block, null_map_holder);
/// TODO: Do not calculate them every time
total_rows = getTotalRowCount();
total_bytes = getTotalByteCount();
}
return table_join->sizeLimits().check(total_rows, total_bytes, "JOIN", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED);
}
namespace
{
class AddedColumns
{
public:
using TypeAndNames = std::vector<std::pair<decltype(ColumnWithTypeAndName::type), decltype(ColumnWithTypeAndName::name)>>;
AddedColumns(const Block & sample_block_with_columns_to_add,
const Block & block_with_columns_to_add,
const Block & block,
const Block & saved_block_sample,
const ColumnsWithTypeAndName & extras,
const Join & join_,
const ColumnRawPtrs & key_columns_,
const Sizes & key_sizes_)
: join(join_)
, key_columns(key_columns_)
, key_sizes(key_sizes_)
, rows_to_add(block.rows())
, need_filter(false)
{
size_t num_columns_to_add = sample_block_with_columns_to_add.columns();
columns.reserve(num_columns_to_add);
type_name.reserve(num_columns_to_add);
right_indexes.reserve(num_columns_to_add);
for (size_t i = 0; i < num_columns_to_add; ++i)
{
const ColumnWithTypeAndName & src_column = sample_block_with_columns_to_add.safeGetByPosition(i);
/// Don't insert column if it's in left block or not explicitly required.
if (!block.has(src_column.name) && block_with_columns_to_add.has(src_column.name))
addColumn(src_column);
}
for (auto & extra : extras)
addColumn(extra);
for (auto & tn : type_name)
right_indexes.push_back(saved_block_sample.getPositionByName(tn.second));
}
size_t size() const { return columns.size(); }
ColumnWithTypeAndName moveColumn(size_t i)
{
return ColumnWithTypeAndName(std::move(columns[i]), type_name[i].first, type_name[i].second);
}
template <bool has_defaults>
void appendFromBlock(const Block & block, size_t row_num)
{
if constexpr (has_defaults)
applyLazyDefaults();
for (size_t j = 0; j < right_indexes.size(); ++j)
columns[j]->insertFrom(*block.getByPosition(right_indexes[j]).column, row_num);
}
void appendDefaultRow()
{
++lazy_defaults_count;
}
void applyLazyDefaults()
{
if (lazy_defaults_count)
{
for (size_t j = 0; j < right_indexes.size(); ++j)
columns[j]->insertManyDefaults(lazy_defaults_count);
lazy_defaults_count = 0;
}
}
const Join & join;
const ColumnRawPtrs & key_columns;
const Sizes & key_sizes;
size_t rows_to_add;
std::unique_ptr<IColumn::Offsets> offsets_to_replicate;
bool need_filter;
private:
TypeAndNames type_name;
MutableColumns columns;
std::vector<size_t> right_indexes;
size_t lazy_defaults_count = 0;
void addColumn(const ColumnWithTypeAndName & src_column)
{
columns.push_back(src_column.column->cloneEmpty());
columns.back()->reserve(src_column.column->size());
type_name.emplace_back(src_column.type, src_column.name);
}
};
template <typename Map, bool add_missing>
void addFoundRowAll(const typename Map::mapped_type & mapped, AddedColumns & added, IColumn::Offset & current_offset)
{
if constexpr (add_missing)
added.applyLazyDefaults();
for (auto it = mapped.begin(); it.ok(); ++it)
{
added.appendFromBlock<false>(*it->block, it->row_num);
++current_offset;
}
};
template <bool add_missing, bool need_offset>
void addNotFoundRow(AddedColumns & added [[maybe_unused]], IColumn::Offset & current_offset [[maybe_unused]])
{
if constexpr (add_missing)
{
added.appendDefaultRow();
if constexpr (need_offset)
++current_offset;
}
}
template <bool need_filter>
void setUsed(IColumn::Filter & filter [[maybe_unused]], size_t pos [[maybe_unused]])
{
if constexpr (need_filter)
filter[pos] = 1;
}
/// Joins right table columns which indexes are present in right_indexes using specified map.
/// Makes filter (1 if row presented in right table) and returns offsets to replicate (for ALL JOINS).
template <ASTTableJoin::Kind KIND, ASTTableJoin::Strictness STRICTNESS, typename KeyGetter, typename Map, bool need_filter, bool has_null_map>
NO_INLINE IColumn::Filter joinRightColumns(const Map & map, AddedColumns & added_columns, const ConstNullMapPtr & null_map [[maybe_unused]])
{
constexpr bool is_any_join = STRICTNESS == ASTTableJoin::Strictness::Any;
constexpr bool is_all_join = STRICTNESS == ASTTableJoin::Strictness::All;
constexpr bool is_asof_join = STRICTNESS == ASTTableJoin::Strictness::Asof;
constexpr bool is_semi_join = STRICTNESS == ASTTableJoin::Strictness::Semi;
constexpr bool is_anti_join = STRICTNESS == ASTTableJoin::Strictness::Anti;
constexpr bool left = KIND == ASTTableJoin::Kind::Left;
constexpr bool right = KIND == ASTTableJoin::Kind::Right;
constexpr bool full = KIND == ASTTableJoin::Kind::Full;
constexpr bool add_missing = (left || full) && !is_semi_join;
constexpr bool need_replication = is_all_join || (is_any_join && right) || (is_semi_join && right);
size_t rows = added_columns.rows_to_add;
IColumn::Filter filter;
if constexpr (need_filter)
filter = IColumn::Filter(rows, 0);
Arena pool;
if constexpr (need_replication)
added_columns.offsets_to_replicate = std::make_unique<IColumn::Offsets>(rows);
const IColumn * asof_column [[maybe_unused]] = nullptr;
if constexpr (is_asof_join)
asof_column = extractAsofColumn(added_columns.key_columns);
auto key_getter = createKeyGetter<KeyGetter, is_asof_join>(added_columns.key_columns, added_columns.key_sizes);
IColumn::Offset current_offset = 0;
for (size_t i = 0; i < rows; ++i)
{
if constexpr (has_null_map)
{
if ((*null_map)[i])
{
addNotFoundRow<add_missing, need_replication>(added_columns, current_offset);
if constexpr (need_replication)
(*added_columns.offsets_to_replicate)[i] = current_offset;
continue;
}
}
auto find_result = key_getter.findKey(map, i, pool);
if (find_result.isFound())
{
auto & mapped = find_result.getMapped();
if constexpr (is_asof_join)
{
const Join & join = added_columns.join;
if (const RowRef * found = mapped.findAsof(join.getAsofType(), join.getAsofInequality(), asof_column, i))
{
setUsed<need_filter>(filter, i);
mapped.setUsed();
added_columns.appendFromBlock<add_missing>(*found->block, found->row_num);
}
else
addNotFoundRow<add_missing, need_replication>(added_columns, current_offset);
}
else if constexpr (is_all_join)
{
setUsed<need_filter>(filter, i);
mapped.setUsed();
addFoundRowAll<Map, add_missing>(mapped, added_columns, current_offset);
}
else if constexpr ((is_any_join || is_semi_join) && right)
{
/// Use first appered left key + it needs left columns replication
if (mapped.setUsedOnce())
{
setUsed<need_filter>(filter, i);
addFoundRowAll<Map, add_missing>(mapped, added_columns, current_offset);
}
}
else if constexpr (is_any_join && KIND == ASTTableJoin::Kind::Inner)
{
/// Use first appered left key only
if (mapped.setUsedOnce())
{
setUsed<need_filter>(filter, i);
added_columns.appendFromBlock<add_missing>(*mapped.block, mapped.row_num);
}
}
else if constexpr (is_any_join && full)
{
/// TODO
}
else if constexpr (is_anti_join)
{
if constexpr (right)
mapped.setUsed();
}
else /// ANY LEFT, SEMI LEFT, old ANY (RightAny)
{
setUsed<need_filter>(filter, i);
mapped.setUsed();
added_columns.appendFromBlock<add_missing>(*mapped.block, mapped.row_num);
}
}
else
{
if constexpr (is_anti_join && left)
setUsed<need_filter>(filter, i);
addNotFoundRow<add_missing, need_replication>(added_columns, current_offset);
}
if constexpr (need_replication)
(*added_columns.offsets_to_replicate)[i] = current_offset;
}
added_columns.applyLazyDefaults();
return filter;
}
template <ASTTableJoin::Kind KIND, ASTTableJoin::Strictness STRICTNESS, typename KeyGetter, typename Map>
IColumn::Filter joinRightColumnsSwitchNullability(const Map & map, AddedColumns & added_columns, const ConstNullMapPtr & null_map)
{
if (added_columns.need_filter)
{
if (null_map)
return joinRightColumns<KIND, STRICTNESS, KeyGetter, Map, true, true>(map, added_columns, null_map);
else
return joinRightColumns<KIND, STRICTNESS, KeyGetter, Map, true, false>(map, added_columns, nullptr);
}
else
{
if (null_map)
return joinRightColumns<KIND, STRICTNESS, KeyGetter, Map, false, true>(map, added_columns, null_map);
else
return joinRightColumns<KIND, STRICTNESS, KeyGetter, Map, false, false>(map, added_columns, nullptr);
}
}
template <ASTTableJoin::Kind KIND, ASTTableJoin::Strictness STRICTNESS, typename Maps>
IColumn::Filter switchJoinRightColumns(const Maps & maps_, AddedColumns & added_columns, Join::Type type, const ConstNullMapPtr & null_map)
{
switch (type)
{
#define M(TYPE) \
case Join::Type::TYPE: \
return joinRightColumnsSwitchNullability<KIND, STRICTNESS,\
typename KeyGetterForType<Join::Type::TYPE, const std::remove_reference_t<decltype(*maps_.TYPE)>>::Type>(\
*maps_.TYPE, added_columns, null_map);\
break;
APPLY_FOR_JOIN_VARIANTS(M)
#undef M
default:
throw Exception("Unsupported JOIN keys. Type: " + toString(static_cast<UInt32>(type)), ErrorCodes::UNSUPPORTED_JOIN_KEYS);
}
}
} /// nameless
template <ASTTableJoin::Kind KIND, ASTTableJoin::Strictness STRICTNESS, typename Maps>
void Join::joinBlockImpl(
Block & block,
const Names & key_names_left,
const Block & block_with_columns_to_add,
const Maps & maps_) const
{
constexpr bool is_any_join = STRICTNESS == ASTTableJoin::Strictness::Any;
constexpr bool is_all_join = STRICTNESS == ASTTableJoin::Strictness::All;
constexpr bool is_asof_join = STRICTNESS == ASTTableJoin::Strictness::Asof;
constexpr bool is_semi_join = STRICTNESS == ASTTableJoin::Strictness::Semi;
constexpr bool is_anti_join = STRICTNESS == ASTTableJoin::Strictness::Anti;
constexpr bool left = KIND == ASTTableJoin::Kind::Left;
constexpr bool right = KIND == ASTTableJoin::Kind::Right;
constexpr bool inner = KIND == ASTTableJoin::Kind::Inner;
constexpr bool full = KIND == ASTTableJoin::Kind::Full;
constexpr bool need_replication = is_all_join || (is_any_join && right) || (is_semi_join && right);
constexpr bool need_filter = !need_replication && (inner || right || (is_semi_join && left) || (is_anti_join && left));
/// Rare case, when keys are constant or low cardinality. To avoid code bloat, simply materialize them.
Columns materialized_keys = JoinCommon::materializeColumns(block, key_names_left);
ColumnRawPtrs key_columns = JoinCommon::getRawPointers(materialized_keys);
/// Keys with NULL value in any column won't join to anything.
ConstNullMapPtr null_map{};
ColumnPtr null_map_holder = extractNestedColumnsAndNullMap(key_columns, null_map);
size_t existing_columns = block.columns();
/** If you use FULL or RIGHT JOIN, then the columns from the "left" table must be materialized.
* Because if they are constants, then in the "not joined" rows, they may have different values
* - default values, which can differ from the values of these constants.
*/
if constexpr (right || full)
{
materializeBlockInplace(block);
if (nullable_left_side)
JoinCommon::convertColumnsToNullable(block);
}
/** For LEFT/INNER JOIN, the saved blocks do not contain keys.
* For FULL/RIGHT JOIN, the saved blocks contain keys;
* but they will not be used at this stage of joining (and will be in `AdderNonJoined`), and they need to be skipped.
* For ASOF, the last column is used as the ASOF column
*/
ColumnsWithTypeAndName extras;
if constexpr (is_asof_join)
extras.push_back(right_table_keys.getByName(key_names_right.back()));
AddedColumns added_columns(sample_block_with_columns_to_add, block_with_columns_to_add, block, savedBlockSample(),
extras, *this, key_columns, key_sizes);
bool has_required_right_keys = (required_right_keys.columns() != 0);
added_columns.need_filter = need_filter || has_required_right_keys;
IColumn::Filter row_filter = switchJoinRightColumns<KIND, STRICTNESS>(maps_, added_columns, data->type, null_map);
for (size_t i = 0; i < added_columns.size(); ++i)
block.insert(added_columns.moveColumn(i));
std::vector<size_t> right_keys_to_replicate [[maybe_unused]];
if constexpr (need_filter)
{
/// If ANY INNER | RIGHT JOIN - filter all the columns except the new ones.
for (size_t i = 0; i < existing_columns; ++i)
block.safeGetByPosition(i).column = block.safeGetByPosition(i).column->filter(row_filter, -1);
/// Add join key columns from right block if needed.
for (size_t i = 0; i < required_right_keys.columns(); ++i)
{
const auto & right_key = required_right_keys.getByPosition(i);
const auto & left_name = required_right_keys_sources[i];
const auto & col = block.getByName(left_name);
bool is_nullable = nullable_right_side || right_key.type->isNullable();
block.insert(correctNullability({col.column, col.type, right_key.name}, is_nullable));
}
}
else if (has_required_right_keys)
{
/// Some trash to represent IColumn::Filter as ColumnUInt8 needed for ColumnNullable::applyNullMap()
auto null_map_filter_ptr = ColumnUInt8::create();
ColumnUInt8 & null_map_filter = assert_cast<ColumnUInt8 &>(*null_map_filter_ptr);
null_map_filter.getData().swap(row_filter);
const IColumn::Filter & filter = null_map_filter.getData();
/// Add join key columns from right block if needed.
for (size_t i = 0; i < required_right_keys.columns(); ++i)
{
const auto & right_key = required_right_keys.getByPosition(i);
const auto & left_name = required_right_keys_sources[i];
const auto & col = block.getByName(left_name);
bool is_nullable = nullable_right_side || right_key.type->isNullable();
ColumnPtr thin_column = filterWithBlanks(col.column, filter);
block.insert(correctNullability({thin_column, col.type, right_key.name}, is_nullable, null_map_filter));
if constexpr (need_replication)
right_keys_to_replicate.push_back(block.getPositionByName(right_key.name));
}
}
if constexpr (need_replication)
{
std::unique_ptr<IColumn::Offsets> & offsets_to_replicate = added_columns.offsets_to_replicate;
/// If ALL ... JOIN - we replicate all the columns except the new ones.
for (size_t i = 0; i < existing_columns; ++i)
block.safeGetByPosition(i).column = block.safeGetByPosition(i).column->replicate(*offsets_to_replicate);
/// Replicate additional right keys
for (size_t pos : right_keys_to_replicate)
block.safeGetByPosition(pos).column = block.safeGetByPosition(pos).column->replicate(*offsets_to_replicate);
}
}
void Join::joinBlockImplCross(Block & block) const
{
/// Add new columns to the block.
size_t num_existing_columns = block.columns();
size_t num_columns_to_add = sample_block_with_columns_to_add.columns();
size_t rows_left = block.rows();
ColumnRawPtrs src_left_columns(num_existing_columns);
MutableColumns dst_columns(num_existing_columns + num_columns_to_add);
for (size_t i = 0; i < num_existing_columns; ++i)
{
src_left_columns[i] = block.getByPosition(i).column.get();
dst_columns[i] = src_left_columns[i]->cloneEmpty();
}
for (size_t i = 0; i < num_columns_to_add; ++i)
{
const ColumnWithTypeAndName & src_column = sample_block_with_columns_to_add.getByPosition(i);
dst_columns[num_existing_columns + i] = src_column.column->cloneEmpty();
block.insert(src_column);
}
/// NOTE It would be better to use `reserve`, as well as `replicate` methods to duplicate the values of the left block.
for (size_t i = 0; i < rows_left; ++i)
{
for (const Block & block_right : data->blocks)
{
size_t rows_right = block_right.rows();
for (size_t col_num = 0; col_num < num_existing_columns; ++col_num)
for (size_t j = 0; j < rows_right; ++j)
dst_columns[col_num]->insertFrom(*src_left_columns[col_num], i);
for (size_t col_num = 0; col_num < num_columns_to_add; ++col_num)
{
const IColumn * column_right = block_right.getByPosition(col_num).column.get();
for (size_t j = 0; j < rows_right; ++j)
dst_columns[num_existing_columns + col_num]->insertFrom(*column_right, j);
}
}
}
block = block.cloneWithColumns(std::move(dst_columns));
}
static void checkTypeOfKey(const Block & block_left, const Block & block_right)
{
auto & [c1, left_type_origin, left_name] = block_left.safeGetByPosition(0);
auto & [c2, right_type_origin, right_name] = block_right.safeGetByPosition(0);
auto left_type = removeNullable(left_type_origin);
auto right_type = removeNullable(right_type_origin);
if (!left_type->equals(*right_type))
throw Exception("Type mismatch of columns to joinGet by: "
+ left_name + " " + left_type->getName() + " at left, "
+ right_name + " " + right_type->getName() + " at right",
ErrorCodes::TYPE_MISMATCH);
}
DataTypePtr Join::joinGetReturnType(const String & column_name) const
{
std::shared_lock lock(data->rwlock);
if (!sample_block_with_columns_to_add.has(column_name))
throw Exception("StorageJoin doesn't contain column " + column_name, ErrorCodes::LOGICAL_ERROR);
return sample_block_with_columns_to_add.getByName(column_name).type;
}
template <typename Maps>
void Join::joinGetImpl(Block & block, const String & column_name, const Maps & maps_) const
{
joinBlockImpl<ASTTableJoin::Kind::Left, ASTTableJoin::Strictness::RightAny>(
block, {block.getByPosition(0).name}, {sample_block_with_columns_to_add.getByName(column_name)}, maps_);
}
// TODO: support composite key
// TODO: return multiple columns as named tuple
// TODO: return array of values when strictness == ASTTableJoin::Strictness::All
void Join::joinGet(Block & block, const String & column_name) const
{
std::shared_lock lock(data->rwlock);
if (key_names_right.size() != 1)
throw Exception("joinGet only supports StorageJoin containing exactly one key", ErrorCodes::LOGICAL_ERROR);
checkTypeOfKey(block, right_table_keys);
if ((strictness == ASTTableJoin::Strictness::Any || strictness == ASTTableJoin::Strictness::RightAny) &&
kind == ASTTableJoin::Kind::Left)
{
joinGetImpl(block, column_name, std::get<MapsOne>(data->maps));
}
else
throw Exception("joinGet only supports StorageJoin of type Left Any", ErrorCodes::LOGICAL_ERROR);
}
void Join::joinBlock(Block & block)
{
std::shared_lock lock(data->rwlock);
const Names & key_names_left = table_join->keyNamesLeft();
JoinCommon::checkTypesOfKeys(block, key_names_left, right_table_keys, key_names_right);
if (joinDispatch(kind, strictness, data->maps, [&](auto kind_, auto strictness_, auto & map)
{
joinBlockImpl<kind_, strictness_>(block, key_names_left, sample_block_with_columns_to_add, map);
}))
{
/// Joined
}
else if (kind == ASTTableJoin::Kind::Cross)
joinBlockImplCross(block);
else
throw Exception("Logical error: unknown combination of JOIN", ErrorCodes::LOGICAL_ERROR);
}
void Join::joinTotals(Block & block) const
{
JoinCommon::joinTotals(totals, sample_block_with_columns_to_add, key_names_right, block);
}
template <typename Mapped>
struct AdderNonJoined
{
static void add(const Mapped & mapped, size_t & rows_added, MutableColumns & columns_right)
{
constexpr bool mapped_asof = std::is_same_v<Mapped, JoinStuff::MappedAsof>;
[[maybe_unused]] constexpr bool mapped_one = std::is_same_v<Mapped, JoinStuff::MappedOne> || std::is_same_v<Mapped, JoinStuff::MappedOneFlagged>;
if constexpr (mapped_asof)
{
/// Do nothing
}
else if constexpr (mapped_one)
{
for (size_t j = 0; j < columns_right.size(); ++j)
{
const auto & mapped_column = mapped.block->getByPosition(j).column;
columns_right[j]->insertFrom(*mapped_column, mapped.row_num);
}
++rows_added;
}
else
{
for (auto it = mapped.begin(); it.ok(); ++it)
{
for (size_t j = 0; j < columns_right.size(); ++j)
{
const auto & mapped_column = it->block->getByPosition(j).column;
columns_right[j]->insertFrom(*mapped_column, it->row_num);
}
++rows_added;
}
}
}
};
/// Stream from not joined earlier rows of the right table.
class NonJoinedBlockInputStream : public IBlockInputStream
{
public:
NonJoinedBlockInputStream(const Join & parent_, const Block & result_sample_block_, UInt64 max_block_size_)
: parent(parent_)
, max_block_size(max_block_size_)
, result_sample_block(materializeBlock(result_sample_block_))
{
bool remap_keys = parent.table_join->hasUsing();
std::unordered_map<size_t, size_t> left_to_right_key_remap;
for (size_t i = 0; i < parent.table_join->keyNamesLeft().size(); ++i)
{
const String & left_key_name = parent.table_join->keyNamesLeft()[i];
const String & right_key_name = parent.table_join->keyNamesRight()[i];
size_t left_key_pos = result_sample_block.getPositionByName(left_key_name);
size_t right_key_pos = parent.savedBlockSample().getPositionByName(right_key_name);
if (remap_keys && !parent.required_right_keys.has(right_key_name))
left_to_right_key_remap[left_key_pos] = right_key_pos;
}
/// result_sample_block: left_sample_block + left expressions, right not key columns, required right keys
size_t left_columns_count = result_sample_block.columns() -
parent.sample_block_with_columns_to_add.columns() - parent.required_right_keys.columns();
for (size_t left_pos = 0; left_pos < left_columns_count; ++left_pos)
{
/// We need right 'x' for 'RIGHT JOIN ... USING(x)'.
if (left_to_right_key_remap.count(left_pos))
{
size_t right_key_pos = left_to_right_key_remap[left_pos];
setRightIndex(right_key_pos, left_pos);
}
else
column_indices_left.emplace_back(left_pos);
}
const auto & saved_block_sample = parent.savedBlockSample();
for (size_t right_pos = 0; right_pos < saved_block_sample.columns(); ++right_pos)
{
const String & name = saved_block_sample.getByPosition(right_pos).name;
if (!result_sample_block.has(name))
continue;
size_t result_position = result_sample_block.getPositionByName(name);
/// Don't remap left keys twice. We need only qualified right keys here
if (result_position < left_columns_count)
continue;
setRightIndex(right_pos, result_position);
}
if (column_indices_left.size() + column_indices_right.size() + same_result_keys.size() != result_sample_block.columns())
throw Exception("Error in columns mapping in RIGHT|FULL JOIN. Left: " + toString(column_indices_left.size()) +
", right: " + toString(column_indices_right.size()) +
", same: " + toString(same_result_keys.size()) +
", result: " + toString(result_sample_block.columns()),
ErrorCodes::LOGICAL_ERROR);
}
String getName() const override { return "NonJoined"; }
Block getHeader() const override { return result_sample_block; }
protected:
Block readImpl() override
{
if (parent.data->blocks.empty())
return Block();
return createBlock();
}
private:
const Join & parent;
UInt64 max_block_size;
Block result_sample_block;
/// Indices of columns in result_sample_block that should be generated
std::vector<size_t> column_indices_left;
/// Indices of columns that come from the right-side table: right_pos -> result_pos
std::unordered_map<size_t, size_t> column_indices_right;
///
std::unordered_map<size_t, size_t> same_result_keys;
/// Which right columns (saved in parent) need nullability change before placing them in result block
std::vector<size_t> right_nullability_changes;
std::any position;
std::optional<Join::BlockNullmapList::const_iterator> nulls_position;
void setRightIndex(size_t right_pos, size_t result_position)
{
if (!column_indices_right.count(right_pos))
{
column_indices_right[right_pos] = result_position;
if (hasNullabilityChange(right_pos, result_position))
right_nullability_changes.push_back(right_pos);
}
else
same_result_keys[result_position] = column_indices_right[right_pos];
}
bool hasNullabilityChange(size_t right_pos, size_t result_pos) const
{
const auto & src = parent.savedBlockSample().getByPosition(right_pos).column;
const auto & dst = result_sample_block.getByPosition(result_pos).column;
return src->isNullable() != dst->isNullable();
}
Block createBlock()
{
MutableColumns columns_right = parent.savedBlockSample().cloneEmptyColumns();
size_t rows_added = 0;
auto fill_callback = [&](auto, auto strictness, auto & map)
{
rows_added = fillColumnsFromMap<strictness>(map, columns_right);
};
if (!joinDispatch(parent.kind, parent.strictness, parent.data->maps, fill_callback))
throw Exception("Logical error: unknown JOIN strictness (must be on of: ANY, ALL, ASOF)", ErrorCodes::LOGICAL_ERROR);
fillNullsFromBlocks(columns_right, rows_added);
if (!rows_added)
return {};
for (size_t pos : right_nullability_changes)
changeNullability(columns_right[pos]);
Block res = result_sample_block.cloneEmpty();
/// @note it's possible to make ColumnConst here and materialize it later
for (size_t pos : column_indices_left)
res.getByPosition(pos).column = res.getByPosition(pos).column->cloneResized(rows_added);
for (auto & pr : column_indices_right)
{
auto & right_column = columns_right[pr.first];
auto & result_column = res.getByPosition(pr.second).column;
#ifndef NDEBUG
if (result_column->getName() != right_column->getName())
throw Exception("Wrong columns assign in RIGHT|FULL JOIN: " + result_column->getName() +
" " + right_column->getName(), ErrorCodes::LOGICAL_ERROR);
#endif
result_column = std::move(right_column);
}
for (auto & pr : same_result_keys)
{
auto & src_column = res.getByPosition(pr.second).column;
auto & dst_column = res.getByPosition(pr.first).column;
if (src_column->isNullable() && !dst_column->isNullable())
{
auto * nullable = checkAndGetColumn<ColumnNullable>(*src_column);
dst_column = nullable->getNestedColumnPtr();
}
else if (!src_column->isNullable() && dst_column->isNullable())
dst_column = makeNullable(src_column);
else
dst_column = src_column;
}
return res;
}
template <ASTTableJoin::Strictness STRICTNESS, typename Maps>
size_t fillColumnsFromMap(const Maps & maps, MutableColumns & columns_keys_and_right)
{
switch (parent.data->type)
{
#define M(TYPE) \
case Join::Type::TYPE: \
return fillColumns<STRICTNESS>(*maps.TYPE, columns_keys_and_right);
APPLY_FOR_JOIN_VARIANTS(M)
#undef M
default:
throw Exception("Unsupported JOIN keys. Type: " + toString(static_cast<UInt32>(parent.data->type)),
ErrorCodes::UNSUPPORTED_JOIN_KEYS);
}
__builtin_unreachable();
}
template <ASTTableJoin::Strictness STRICTNESS, typename Map>
size_t fillColumns(const Map & map, MutableColumns & columns_keys_and_right)
{
using Mapped = typename Map::mapped_type;
using Iterator = typename Map::const_iterator;
size_t rows_added = 0;
if (!position.has_value())
position = std::make_any<Iterator>(map.begin());
Iterator & it = std::any_cast<Iterator &>(position);
auto end = map.end();
for (; it != end; ++it)
{
const Mapped & mapped = it->getMapped();
if (mapped.getUsed())
continue;
AdderNonJoined<Mapped>::add(mapped, rows_added, columns_keys_and_right);
if (rows_added >= max_block_size)
{
++it;
break;
}
}
return rows_added;
}
void fillNullsFromBlocks(MutableColumns & columns_keys_and_right, size_t & rows_added)
{
if (!nulls_position.has_value())
nulls_position = parent.data->blocks_nullmaps.begin();
auto end = parent.data->blocks_nullmaps.end();
for (auto & it = *nulls_position; it != end && rows_added < max_block_size; ++it)
{
const Block * block = it->first;
const NullMap & nullmap = assert_cast<const ColumnUInt8 &>(*it->second).getData();
for (size_t row = 0; row < nullmap.size(); ++row)
{
if (nullmap[row])
{
for (size_t col = 0; col < columns_keys_and_right.size(); ++col)
columns_keys_and_right[col]->insertFrom(*block->getByPosition(col).column, row);
++rows_added;
}
}
}
}
};
BlockInputStreamPtr Join::createStreamWithNonJoinedRows(const Block & result_sample_block, UInt64 max_block_size) const
{
if (table_join->strictness() == ASTTableJoin::Strictness::Asof ||
table_join->strictness() == ASTTableJoin::Strictness::Semi)
return {};
if (isRightOrFull(table_join->kind()))
return std::make_shared<NonJoinedBlockInputStream>(*this, result_sample_block, max_block_size);
return {};
}
}
|
// Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/parser/cpdf_simple_parser.h"
#include "core/fpdfapi/parser/fpdf_parser_utility.h"
CPDF_SimpleParser::CPDF_SimpleParser(pdfium::span<const uint8_t> input)
: data_(input) {}
CPDF_SimpleParser::~CPDF_SimpleParser() = default;
ByteStringView CPDF_SimpleParser::GetWord() {
uint8_t ch;
// Skip whitespace and comment lines.
while (1) {
if (data_.size() <= cur_pos_)
return ByteStringView();
ch = data_[cur_pos_++];
while (PDFCharIsWhitespace(ch)) {
if (data_.size() <= cur_pos_)
return ByteStringView();
ch = data_[cur_pos_++];
}
if (ch != '%')
break;
while (1) {
if (data_.size() <= cur_pos_)
return ByteStringView();
ch = data_[cur_pos_++];
if (PDFCharIsLineEnding(ch))
break;
}
}
uint8_t dwSize = 0;
uint32_t start_pos = cur_pos_ - 1;
if (PDFCharIsDelimiter(ch)) {
// Find names
if (ch == '/') {
while (1) {
if (data_.size() <= cur_pos_)
break;
ch = data_[cur_pos_++];
if (!PDFCharIsOther(ch) && !PDFCharIsNumeric(ch)) {
cur_pos_--;
dwSize = cur_pos_ - start_pos;
break;
}
}
return data_.subspan(start_pos, dwSize);
}
dwSize = 1;
if (ch == '<') {
if (data_.size() <= cur_pos_)
return data_.subspan(start_pos, dwSize);
ch = data_[cur_pos_++];
if (ch == '<') {
dwSize = 2;
} else {
while (cur_pos_ < data_.size() && data_[cur_pos_] != '>')
cur_pos_++;
if (cur_pos_ < data_.size())
cur_pos_++;
dwSize = cur_pos_ - start_pos;
}
} else if (ch == '>') {
if (data_.size() <= cur_pos_)
return data_.subspan(start_pos, dwSize);
ch = data_[cur_pos_++];
if (ch == '>')
dwSize = 2;
else
cur_pos_--;
} else if (ch == '(') {
int level = 1;
while (cur_pos_ < data_.size()) {
if (data_[cur_pos_] == ')') {
level--;
if (level == 0)
break;
}
if (data_[cur_pos_] == '\\') {
if (data_.size() <= cur_pos_)
break;
cur_pos_++;
} else if (data_[cur_pos_] == '(') {
level++;
}
if (data_.size() <= cur_pos_)
break;
cur_pos_++;
}
if (cur_pos_ < data_.size())
cur_pos_++;
dwSize = cur_pos_ - start_pos;
}
return data_.subspan(start_pos, dwSize);
}
dwSize = 1;
while (cur_pos_ < data_.size()) {
ch = data_[cur_pos_++];
if (PDFCharIsDelimiter(ch) || PDFCharIsWhitespace(ch)) {
cur_pos_--;
break;
}
dwSize++;
}
return data_.subspan(start_pos, dwSize);
}
|
//
// serial_port.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include "asio/serial_port.hpp"
#include "archetypes/async_result.hpp"
#include "asio/io_context.hpp"
#include "unit_test.hpp"
//------------------------------------------------------------------------------
// serial_port_compile test
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that all public member functions on the class
// serial_port compile and link correctly. Runtime failures are ignored.
namespace serial_port_compile {
struct write_some_handler
{
write_some_handler() {}
void operator()(const asio::error_code&, std::size_t) {}
#if defined(ASIO_HAS_MOVE)
write_some_handler(write_some_handler&&) {}
private:
write_some_handler(const write_some_handler&);
#endif // defined(ASIO_HAS_MOVE)
};
struct read_some_handler
{
read_some_handler() {}
void operator()(const asio::error_code&, std::size_t) {}
#if defined(ASIO_HAS_MOVE)
read_some_handler(read_some_handler&&) {}
private:
read_some_handler(const read_some_handler&);
#endif // defined(ASIO_HAS_MOVE)
};
void test()
{
#if defined(ASIO_HAS_SERIAL_PORT)
using namespace asio;
try
{
io_context ioc;
char mutable_char_buffer[128] = "";
const char const_char_buffer[128] = "";
serial_port::baud_rate serial_port_option;
archetypes::lazy_handler lazy;
asio::error_code ec;
// basic_serial_port constructors.
serial_port port1(ioc);
serial_port port2(ioc, "null");
serial_port::native_handle_type native_port1 = port1.native_handle();
serial_port port3(ioc, native_port1);
#if defined(ASIO_HAS_MOVE)
serial_port port4(std::move(port3));
#endif // defined(ASIO_HAS_MOVE)
// basic_serial_port operators.
#if defined(ASIO_HAS_MOVE)
port1 = serial_port(ioc);
port1 = std::move(port2);
#endif // defined(ASIO_HAS_MOVE)
// basic_io_object functions.
serial_port::executor_type ex = port1.get_executor();
(void)ex;
#if !defined(ASIO_NO_DEPRECATED)
io_context& ioc_ref = port1.get_io_context();
(void)ioc_ref;
io_context& ioc_ref2 = port1.get_io_service();
(void)ioc_ref2;
#endif // !defined(ASIO_NO_DEPRECATED)
// basic_serial_port functions.
serial_port::lowest_layer_type& lowest_layer = port1.lowest_layer();
(void)lowest_layer;
const serial_port& port5 = port1;
const serial_port::lowest_layer_type& lowest_layer2 = port5.lowest_layer();
(void)lowest_layer2;
port1.open("null");
port1.open("null", ec);
serial_port::native_handle_type native_port2 = port1.native_handle();
port1.assign(native_port2);
serial_port::native_handle_type native_port3 = port1.native_handle();
port1.assign(native_port3, ec);
bool is_open = port1.is_open();
(void)is_open;
port1.close();
port1.close(ec);
serial_port::native_handle_type native_port4 = port1.native_handle();
(void)native_port4;
port1.cancel();
port1.cancel(ec);
port1.set_option(serial_port_option);
port1.set_option(serial_port_option, ec);
port1.get_option(serial_port_option);
port1.get_option(serial_port_option, ec);
port1.send_break();
port1.send_break(ec);
port1.write_some(buffer(mutable_char_buffer));
port1.write_some(buffer(const_char_buffer));
port1.write_some(buffer(mutable_char_buffer), ec);
port1.write_some(buffer(const_char_buffer), ec);
port1.async_write_some(buffer(mutable_char_buffer), write_some_handler());
port1.async_write_some(buffer(const_char_buffer), write_some_handler());
int i1 = port1.async_write_some(buffer(mutable_char_buffer), lazy);
(void)i1;
int i2 = port1.async_write_some(buffer(const_char_buffer), lazy);
(void)i2;
port1.read_some(buffer(mutable_char_buffer));
port1.read_some(buffer(mutable_char_buffer), ec);
port1.async_read_some(buffer(mutable_char_buffer), read_some_handler());
int i3 = port1.async_read_some(buffer(mutable_char_buffer), lazy);
(void)i3;
}
catch (std::exception&)
{
}
#endif // defined(ASIO_HAS_SERIAL_PORT)
}
} // namespace serial_port_compile
//------------------------------------------------------------------------------
ASIO_TEST_SUITE
(
"serial_port",
ASIO_TEST_CASE(serial_port_compile::test)
)
|
// Copyright (c) YugaByte, Inc.
//
// 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 "yb/yql/pggate/ybc_pggate_tool.h"
#include "yb/common/ybc-internal.h"
#include "yb/yql/pggate/ybc_pggate.h"
#include "yb/server/server_base_options.h"
#include "yb/tserver/tserver_service.proxy.h"
#include "yb/tserver/tserver_shared_mem.h"
#include "yb/util/memory/mc_types.h"
#include "yb/yql/pggate/pg_env.h"
#include "yb/yql/pggate/pggate.h"
#include "yb/yql/pggate/pggate_flags.h"
namespace yb {
namespace pggate {
namespace {
// Fetches relation's unique constraint name to specified buffer.
// If relation is not an index and it has primary key the name of primary key index is returned.
// In other cases, relation name is used.
//
// Not implemented for tools.
void FetchUniqueConstraintName(PgOid relation_id, char* dest, size_t max_size) {
CHECK(false) << "Not implemented";
}
YBCPgMemctx GetCurrentToolYbMemctx() {
static YBCPgMemctx tool_memctx = nullptr;
if (!tool_memctx) {
tool_memctx = YBCPgCreateMemctx();
}
return tool_memctx;
}
// Conversion Table.
// Contain function pointers for conversion between PostgreSQL Datum to YugaByte data.
// Currently it is not used in the tools and can be empty.
static const YBCPgTypeEntity YBCEmptyTypeEntityTable[] = {};
CHECKED_STATUS PrepareInitPgGateBackend() {
server::MasterAddresses master_addresses;
std::string resolved_str;
RETURN_NOT_OK(server::DetermineMasterAddresses(
"pggate_master_addresses", FLAGS_pggate_master_addresses, 0, &master_addresses,
&resolved_str));
PgApiContext context;
struct Data {
boost::optional<tserver::TServerSharedObject> tserver_shared_object;
std::atomic<bool> flag{false};
CountDownLatch latch{1};
std::atomic<size_t> running{0};
Status failure;
};
static std::shared_ptr<Data> data = std::make_shared<Data>();
data->tserver_shared_object.emplace(VERIFY_RESULT(tserver::TServerSharedObject::Create()));
data->running = 0;
for (const auto& list : master_addresses) {
data->running += list.size();
}
for (const auto& list : master_addresses) {
for (const auto& host_port : list) {
tserver::TabletServerServiceProxy proxy(context.proxy_cache.get(), host_port);
struct ReqData {
tserver::GetSharedDataRequestPB req;
tserver::GetSharedDataResponsePB resp;
rpc::RpcController controller;
};
auto req_data = std::make_shared<ReqData>();
req_data->controller.set_timeout(std::chrono::seconds(60));
proxy.GetSharedDataAsync(
req_data->req, &req_data->resp, &req_data->controller, [req_data] {
if (req_data->controller.status().ok()) {
bool expected = false;
if (data->flag.compare_exchange_strong(expected, true)) {
memcpy(pointer_cast<char*>(&**data->tserver_shared_object),
req_data->resp.data().c_str(), req_data->resp.data().size());
data->latch.CountDown();
}
} else if (--data->running == 0) {
data->failure = req_data->controller.status();
data->latch.CountDown();
}
});
}
}
data->latch.Wait();
RETURN_NOT_OK(data->failure);
FLAGS_pggate_tserver_shm_fd = data->tserver_shared_object->GetFd();
YBCPgCallbacks callbacks;
callbacks.FetchUniqueConstraintName = &FetchUniqueConstraintName;
callbacks.GetCurrentYbMemctx = &GetCurrentToolYbMemctx;
YBCInitPgGateEx(YBCEmptyTypeEntityTable, 0, callbacks, &context);
return Status::OK();
}
} // anonymous namespace
//--------------------------------------------------------------------------------------------------
// C API.
//--------------------------------------------------------------------------------------------------
extern "C" {
void YBCSetMasterAddresses(const char* hosts) {
LOG(INFO) << "Setting custom master addresses: " << hosts;
FLAGS_pggate_master_addresses = hosts;
}
YBCStatus YBCInitPgGateBackend() {
auto status = PrepareInitPgGateBackend();
if (!status.ok()) {
return ToYBCStatus(status);
}
return YBCPgInitSession(/* pg_env */ nullptr, /* database_name */ nullptr);
}
void YBCShutdownPgGateBackend() {
YBCDestroyPgGate();
YBCPgDestroyMemctx(GetCurrentToolYbMemctx());
}
} // extern "C"
} // namespace pggate
} // namespace yb
|
// Copyright (c) 2019 by Robert Bosch GmbH. All 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_UTILS_TESTUTILS_ROUDI_GTEST_HPP
#define IOX_UTILS_TESTUTILS_ROUDI_GTEST_HPP
#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace ::testing;
using ::testing::Return;
class RouDi_GTest : public iox::roudi::RouDiEnvironment, public Test
{
public:
RouDi_GTest() = default;
RouDi_GTest(iox::RouDiConfig_t& roudiConfig)
: iox::roudi::RouDiEnvironment(roudiConfig)
{
}
};
#endif // IOX_UTILS_TESTUTILS_ROUDI_GTEST_HPP
|
//
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// 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 <cassert>
#include <boost/thread.hpp>
#include "component/service/service_component.h"
#include "entity/entity.h"
#include "thread/thread_util.h"
#include "utility/value.h"
namespace eja
{
// Operator
service_component& service_component::operator=(const service_component& comp)
{
if (this != &comp)
{
component::operator=(comp);
m_service = comp.m_service;
m_strand = comp.m_strand;
m_thread_group = comp.m_thread_group;
m_timers = comp.m_timers;
m_work = comp.m_work;
m_threads = comp.m_threads;
m_state.store(comp.m_state);
}
return *this;
}
// Utility
void service_component::start()
{
assert(m_threads && invalid());
if (invalid())
{
m_service = std::make_shared<boost::asio::io_service>();
m_strand = std::make_shared<boost::asio::io_service::strand>(*m_service);
m_thread_group = std::make_shared<boost::thread_group>();
m_work = std::make_shared<boost::asio::io_service::work>(*m_service);
// Threads
const auto self = shared_from_this();
for (size_t i = 0; i < m_threads; ++i)
m_thread_group->create_thread([self]() { self->run(); });
}
}
void service_component::restart()
{
if (valid())
{
service_component::stop();
service_component::start();
}
}
void service_component::stop()
{
if (valid())
{
// 1) Stop new work requests
m_work.reset();
// 2) Close asio objects (must happen BEFORE io_service stop)
close();
// 3) Stop
m_service->stop();
m_strand.reset();
// 4) Wait on the remaining threads
if (m_thread_group)
{
try
{
m_thread_group->interrupt_all();
m_thread_group->join_all();
m_thread_group.reset();
}
catch (const std::exception& ex)
{
log(ex);
assert(false);
}
}
// 5) Clear UI
clear();
}
}
void service_component::close()
{
// NOTE: We must cancel all outstanding timers to prevent leaking threads
boost::system::error_code error;
thread_lock(m_timers);
for (const auto& timer : *m_timers)
timer->cancel(error);
m_timers->clear();
}
void service_component::run()
{
try
{
WIN32_ONLY(srand(static_cast<unsigned int>(time(0)));)
const auto service = get_service();
service->run();
}
catch (const std::exception& ex)
{
log(ex);
}
}
// Set
void service_component::set_status(const status value) const
{
const auto owner = get_owner();
set_status(owner, value);
}
void service_component::set_status(const entity::ptr& entity, const status value) const
{
const auto status = entity->get<status_component>();
status->set_status(value);
}
bool service_component::set_state(const state next, const state value)
{
state expected = value;
return m_state.compare_exchange_strong(expected, next);
}
}
|
/*
// Copyright (C) 2020-2022 Intel Corporation
//
// 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 "models/detection_model_retinaface.h"
#include <stddef.h>
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <opencv2/core.hpp>
#include <openvino/openvino.hpp>
#include <utils/common.hpp>
#include <utils/nms.hpp>
#include "models/internal_model_data.h"
#include "models/results.h"
ModelRetinaFace::ModelRetinaFace(const std::string& modelFileName,
float confidenceThreshold,
bool useAutoResize,
float boxIOUThreshold,
const std::string& layout)
: DetectionModel(modelFileName, confidenceThreshold, useAutoResize, {"Face"}, layout), // Default label is "Face"
shouldDetectMasks(false),
shouldDetectLandmarks(false),
boxIOUThreshold(boxIOUThreshold),
maskThreshold(0.8f),
landmarkStd(1.0f),
anchorCfg({{32, {32, 16}, 16, {1}}, {16, {8, 4}, 16, {1}}, {8, {2, 1}, 16, {1}}}) {
generateAnchorsFpn();
}
void ModelRetinaFace::prepareInputsOutputs(std::shared_ptr<ov::Model>& model) {
// --------------------------- Configure input & output -------------------------------------------------
// --------------------------- Prepare input ------------------------------------------------------
if (model->inputs().size() != 1) {
throw std::logic_error("RetinaFace model wrapper expects models that have only 1 input");
}
const ov::Shape& inputShape = model->input().get_shape();
const ov::Layout& inputLayout = getInputLayout(model->input());
if (inputShape[ov::layout::channels_idx(inputLayout)] != 3) {
throw std::logic_error("Expected 3-channel input");
}
ov::preprocess::PrePostProcessor ppp(model);
ppp.input().tensor().set_element_type(ov::element::u8).set_layout({"NHWC"});
if (useAutoResize) {
ppp.input().tensor().set_spatial_dynamic_shape();
ppp.input()
.preprocess()
.convert_element_type(ov::element::f32)
.resize(ov::preprocess::ResizeAlgorithm::RESIZE_LINEAR);
}
ppp.input().model().set_layout(inputLayout);
// --------------------------- Reading image input parameters -------------------------------------------
inputsNames.push_back(model->input().get_any_name());
netInputWidth = inputShape[ov::layout::width_idx(inputLayout)];
netInputHeight = inputShape[ov::layout::height_idx(inputLayout)];
// --------------------------- Prepare output -----------------------------------------------------
const ov::OutputVector& outputs = model->outputs();
if (outputs.size() != 6 && outputs.size() != 9 && outputs.size() != 12) {
throw std::logic_error("RetinaFace model wrapper expects models that have 6, 9 or 12 outputs");
}
const ov::Layout outputLayout{"NCHW"};
std::vector<size_t> outputsSizes[OUT_MAX];
for (const auto& output : model->outputs()) {
auto outTensorName = output.get_any_name();
outputsNames.push_back(outTensorName);
ppp.output(outTensorName).tensor().set_element_type(ov::element::f32).set_layout(outputLayout);
OutputType type = OUT_MAX;
if (outTensorName.find("box") != std::string::npos) {
type = OUT_BOXES;
} else if (outTensorName.find("cls") != std::string::npos) {
type = OUT_SCORES;
} else if (outTensorName.find("landmark") != std::string::npos) {
type = OUT_LANDMARKS;
shouldDetectLandmarks = true;
} else if (outTensorName.find("type") != std::string::npos) {
type = OUT_MASKSCORES;
labels.clear();
labels.push_back("No Mask");
labels.push_back("Mask");
shouldDetectMasks = true;
landmarkStd = 0.2f;
} else {
continue;
}
size_t num = output.get_shape()[ov::layout::height_idx(outputLayout)];
size_t i = 0;
for (; i < outputsSizes[type].size(); ++i) {
if (num < outputsSizes[type][i]) {
break;
}
}
separateOutputsNames[type].insert(separateOutputsNames[type].begin() + i, outTensorName);
outputsSizes[type].insert(outputsSizes[type].begin() + i, num);
}
model = ppp.build();
for (size_t idx = 0; idx < outputsSizes[OUT_BOXES].size(); ++idx) {
size_t width = outputsSizes[OUT_BOXES][idx];
size_t height = outputsSizes[OUT_BOXES][idx];
auto s = anchorCfg[idx].stride;
auto anchorNum = anchorsFpn[s].size();
anchors.push_back(std::vector<ModelRetinaFace::Anchor>(height * width * anchorNum));
for (size_t iw = 0; iw < width; ++iw) {
size_t sw = iw * s;
for (size_t ih = 0; ih < height; ++ih) {
size_t sh = ih * s;
for (size_t k = 0; k < anchorNum; ++k) {
Anchor& anc = anchors[idx][(ih * width + iw) * anchorNum + k];
anc.left = anchorsFpn[s][k].left + sw;
anc.top = anchorsFpn[s][k].top + sh;
anc.right = anchorsFpn[s][k].right + sw;
anc.bottom = anchorsFpn[s][k].bottom + sh;
}
}
}
}
}
std::vector<ModelRetinaFace::Anchor> ratioEnum(const ModelRetinaFace::Anchor& anchor, const std::vector<int>& ratios) {
std::vector<ModelRetinaFace::Anchor> retVal;
const auto w = anchor.getWidth();
const auto h = anchor.getHeight();
const auto xCtr = anchor.getXCenter();
const auto yCtr = anchor.getYCenter();
for (const auto ratio : ratios) {
const auto size = w * h;
const auto sizeRatio = static_cast<float>(size) / ratio;
const auto ws = sqrt(sizeRatio);
const auto hs = ws * ratio;
retVal.push_back({static_cast<float>(xCtr - 0.5f * (ws - 1.0f)),
static_cast<float>(yCtr - 0.5f * (hs - 1.0f)),
static_cast<float>(xCtr + 0.5f * (ws - 1.0f)),
static_cast<float>(yCtr + 0.5f * (hs - 1.0f))});
}
return retVal;
}
std::vector<ModelRetinaFace::Anchor> scaleEnum(const ModelRetinaFace::Anchor& anchor, const std::vector<int>& scales) {
std::vector<ModelRetinaFace::Anchor> retVal;
const auto w = anchor.getWidth();
const auto h = anchor.getHeight();
const auto xCtr = anchor.getXCenter();
const auto yCtr = anchor.getYCenter();
for (auto scale : scales) {
const auto ws = w * scale;
const auto hs = h * scale;
retVal.push_back({static_cast<float>(xCtr - 0.5f * (ws - 1.0f)),
static_cast<float>(yCtr - 0.5f * (hs - 1.0f)),
static_cast<float>(xCtr + 0.5f * (ws - 1.0f)),
static_cast<float>(yCtr + 0.5f * (hs - 1.0f))});
}
return retVal;
}
std::vector<ModelRetinaFace::Anchor> generateAnchors(const int baseSize,
const std::vector<int>& ratios,
const std::vector<int>& scales) {
ModelRetinaFace::Anchor baseAnchor{0.0f, 0.0f, baseSize - 1.0f, baseSize - 1.0f};
auto ratioAnchors = ratioEnum(baseAnchor, ratios);
std::vector<ModelRetinaFace::Anchor> retVal;
for (const auto& ra : ratioAnchors) {
auto addon = scaleEnum(ra, scales);
retVal.insert(retVal.end(), addon.begin(), addon.end());
}
return retVal;
}
void ModelRetinaFace::generateAnchorsFpn() {
auto cfg = anchorCfg;
std::sort(cfg.begin(), cfg.end(), [](const AnchorCfgLine& x, const AnchorCfgLine& y) {
return x.stride > y.stride;
});
for (const auto& cfgLine : cfg) {
anchorsFpn.emplace(cfgLine.stride, generateAnchors(cfgLine.baseSize, cfgLine.ratios, cfgLine.scales));
}
}
std::vector<size_t> thresholding(const ov::Tensor& scoresTensor, const int anchorNum, const float confidenceThreshold) {
std::vector<size_t> indices;
indices.reserve(ModelRetinaFace::INIT_VECTOR_SIZE);
auto shape = scoresTensor.get_shape();
size_t restAnchors = shape[1] - anchorNum;
const float* scoresPtr = scoresTensor.data<float>();
for (size_t x = anchorNum; x < shape[1]; ++x) {
for (size_t y = 0; y < shape[2]; ++y) {
for (size_t z = 0; z < shape[3]; ++z) {
auto idx = (x * shape[2] + y) * shape[3] + z;
auto score = scoresPtr[idx];
if (score >= confidenceThreshold) {
indices.push_back((y * shape[3] + z) * restAnchors + (x - anchorNum));
}
}
}
}
return indices;
}
void filterScores(std::vector<float>& scores,
const std::vector<size_t>& indices,
const ov::Tensor& scoresTensor,
const int anchorNum) {
const auto& shape = scoresTensor.get_shape();
const float* scoresPtr = scoresTensor.data<float>();
const auto start = shape[2] * shape[3] * anchorNum;
for (auto i : indices) {
auto offset = (i % anchorNum) * shape[2] * shape[3] + i / anchorNum;
scores.push_back(scoresPtr[start + offset]);
}
}
void filterBoxes(std::vector<ModelRetinaFace::Anchor>& boxes,
const std::vector<size_t>& indices,
const ov::Tensor& boxesTensor,
int anchorNum,
const std::vector<ModelRetinaFace::Anchor>& anchors) {
const auto& shape = boxesTensor.get_shape();
const float* boxesPtr = boxesTensor.data<float>();
const auto boxPredLen = shape[1] / anchorNum;
const auto blockWidth = shape[2] * shape[3];
for (auto i : indices) {
auto offset = blockWidth * boxPredLen * (i % anchorNum) + (i / anchorNum);
const auto dx = boxesPtr[offset];
const auto dy = boxesPtr[offset + blockWidth];
const auto dw = boxesPtr[offset + blockWidth * 2];
const auto dh = boxesPtr[offset + blockWidth * 3];
const auto predCtrX = dx * anchors[i].getWidth() + anchors[i].getXCenter();
const auto predCtrY = dy * anchors[i].getHeight() + anchors[i].getYCenter();
const auto predW = exp(dw) * anchors[i].getWidth();
const auto predH = exp(dh) * anchors[i].getHeight();
boxes.push_back({static_cast<float>(predCtrX - 0.5f * (predW - 1.0f)),
static_cast<float>(predCtrY - 0.5f * (predH - 1.0f)),
static_cast<float>(predCtrX + 0.5f * (predW - 1.0f)),
static_cast<float>(predCtrY + 0.5f * (predH - 1.0f))});
}
}
void filterLandmarks(std::vector<cv::Point2f>& landmarks,
const std::vector<size_t>& indices,
const ov::Tensor& landmarksTensor,
int anchorNum,
const std::vector<ModelRetinaFace::Anchor>& anchors,
const float landmarkStd) {
const auto& shape = landmarksTensor.get_shape();
const float* landmarksPtr = landmarksTensor.data<float>();
const auto landmarkPredLen = shape[1] / anchorNum;
const auto blockWidth = shape[2] * shape[3];
for (auto i : indices) {
for (int j = 0; j < ModelRetinaFace::LANDMARKS_NUM; ++j) {
auto offset = (i % anchorNum) * landmarkPredLen * shape[2] * shape[3] + i / anchorNum;
auto deltaX = landmarksPtr[offset + j * 2 * blockWidth] * landmarkStd;
auto deltaY = landmarksPtr[offset + (j * 2 + 1) * blockWidth] * landmarkStd;
landmarks.push_back({deltaX * anchors[i].getWidth() + anchors[i].getXCenter(),
deltaY * anchors[i].getHeight() + anchors[i].getYCenter()});
}
}
}
void filterMasksScores(std::vector<float>& masks,
const std::vector<size_t>& indices,
const ov::Tensor& maskScoresTensor,
const int anchorNum) {
auto shape = maskScoresTensor.get_shape();
const float* maskScoresPtr = maskScoresTensor.data<float>();
auto start = shape[2] * shape[3] * anchorNum * 2;
for (auto i : indices) {
auto offset = (i % anchorNum) * shape[2] * shape[3] + i / anchorNum;
masks.push_back(maskScoresPtr[start + offset]);
}
}
std::unique_ptr<ResultBase> ModelRetinaFace::postprocess(InferenceResult& infResult) {
std::vector<float> scores;
scores.reserve(INIT_VECTOR_SIZE);
std::vector<Anchor> boxes;
boxes.reserve(INIT_VECTOR_SIZE);
std::vector<cv::Point2f> landmarks;
std::vector<float> masks;
if (shouldDetectLandmarks) {
landmarks.reserve(INIT_VECTOR_SIZE);
}
if (shouldDetectMasks) {
masks.reserve(INIT_VECTOR_SIZE);
}
// --------------------------- Gather & Filter output from all levels
// ----------------------------------------------------------
for (size_t idx = 0; idx < anchorCfg.size(); ++idx) {
const auto boxRaw = infResult.outputsData[separateOutputsNames[OUT_BOXES][idx]];
const auto scoresRaw = infResult.outputsData[separateOutputsNames[OUT_SCORES][idx]];
auto s = anchorCfg[idx].stride;
auto anchorNum = anchorsFpn[s].size();
auto validIndices = thresholding(scoresRaw, anchorNum, confidenceThreshold);
filterScores(scores, validIndices, scoresRaw, anchorNum);
filterBoxes(boxes, validIndices, boxRaw, anchorNum, anchors[idx]);
if (shouldDetectLandmarks) {
const auto landmarksRaw = infResult.outputsData[separateOutputsNames[OUT_LANDMARKS][idx]];
filterLandmarks(landmarks, validIndices, landmarksRaw, anchorNum, anchors[idx], landmarkStd);
}
if (shouldDetectMasks) {
const auto masksRaw = infResult.outputsData[separateOutputsNames[OUT_MASKSCORES][idx]];
filterMasksScores(masks, validIndices, masksRaw, anchorNum);
}
}
// --------------------------- Apply Non-maximum Suppression
// ---------------------------------------------------------- !shouldDetectLandmarks determines nms behavior, if
// true - boundaries are included in areas calculation
const auto keep = nms(boxes, scores, boxIOUThreshold, !shouldDetectLandmarks);
// --------------------------- Create detection result objects
// --------------------------------------------------------
RetinaFaceDetectionResult* result = new RetinaFaceDetectionResult(infResult.frameId, infResult.metaData);
const auto imgWidth = infResult.internalModelData->asRef<InternalImageModelData>().inputImgWidth;
const auto imgHeight = infResult.internalModelData->asRef<InternalImageModelData>().inputImgHeight;
const auto scaleX = static_cast<float>(netInputWidth) / imgWidth;
const auto scaleY = static_cast<float>(netInputHeight) / imgHeight;
result->objects.reserve(keep.size());
result->landmarks.reserve(keep.size() * ModelRetinaFace::LANDMARKS_NUM);
for (auto i : keep) {
DetectedObject desc;
desc.confidence = scores[i];
//--- Scaling coordinates
boxes[i].left /= scaleX;
boxes[i].top /= scaleY;
boxes[i].right /= scaleX;
boxes[i].bottom /= scaleY;
desc.x = clamp(boxes[i].left, 0.f, static_cast<float>(imgWidth));
desc.y = clamp(boxes[i].top, 0.f, static_cast<float>(imgHeight));
desc.width = clamp(boxes[i].getWidth(), 0.f, static_cast<float>(imgWidth));
desc.height = clamp(boxes[i].getHeight(), 0.f, static_cast<float>(imgHeight));
//--- Default label 0 - Face. If detecting masks then labels would be 0 - No Mask, 1 - Mask
desc.labelID = shouldDetectMasks ? (masks[i] > maskThreshold) : 0;
desc.label = labels[desc.labelID];
result->objects.push_back(desc);
//--- Scaling landmarks coordinates
for (size_t l = 0; l < ModelRetinaFace::LANDMARKS_NUM && shouldDetectLandmarks; ++l) {
landmarks[i * ModelRetinaFace::LANDMARKS_NUM + l].x =
clamp(landmarks[i * ModelRetinaFace::LANDMARKS_NUM + l].x / scaleX, 0.f, static_cast<float>(imgWidth));
landmarks[i * ModelRetinaFace::LANDMARKS_NUM + l].y =
clamp(landmarks[i * ModelRetinaFace::LANDMARKS_NUM + l].y / scaleY, 0.f, static_cast<float>(imgHeight));
result->landmarks.push_back(landmarks[i * ModelRetinaFace::LANDMARKS_NUM + l]);
}
}
return std::unique_ptr<ResultBase>(result);
}
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/util/util.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/expression/assignment_expression.h"
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/expression/array_element_expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/function_call.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/util/hash.h"
#include "hphp/runtime/base/array/array_iterator.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
#define DEC_EXPR_NAMES(x,t) #x
const char *Expression::Names[] = {
DECLARE_EXPRESSION_TYPES(DEC_EXPR_NAMES)
};
#define DEC_EXPR_CLASSES(x,t) Expression::t
Expression::ExprClass Expression::Classes[] = {
DECLARE_EXPRESSION_TYPES(DEC_EXPR_CLASSES)
};
Expression::Expression(EXPRESSION_CONSTRUCTOR_BASE_PARAMETERS)
: Construct(scope, loc), m_context(RValue), m_kindOf(kindOf),
m_originalScopeSet(false), m_unused(false), m_canon_id(0), m_error(0),
m_canonPtr() {
}
ExpressionPtr Expression::replaceValue(ExpressionPtr rep) {
if (hasContext(Expression::RefValue) &&
isRefable(true) && !rep->isRefable(true)) {
/*
An assignment isRefable, but the rhs may not be. Need this to
prevent "bad pass by reference" errors.
*/
ExpressionListPtr el(new ExpressionList(getScope(), getLocation(),
ExpressionList::ListKindWrapped));
el->addElement(rep);
rep->clearContext(AssignmentRHS);
rep = el;
}
if (rep->is(KindOfSimpleVariable) && !is(KindOfSimpleVariable)) {
static_pointer_cast<SimpleVariable>(rep)->setAlwaysStash();
}
rep->copyContext(m_context & ~(DeadStore|AccessContext));
if (TypePtr t1 = getType()) {
if (TypePtr t2 = rep->getType()) {
if (!Type::SameType(t1, t2)) {
rep->setExpectedType(t1);
}
}
}
if (rep->getScope() != getScope()) {
rep->resetScope(getScope());
}
return rep;
}
void Expression::copyContext(int contexts) {
unsigned val = contexts;
while (val) {
unsigned next = val & (val - 1);
unsigned low = val ^ next; // lowest set bit
setContext((Context)low);
val = next;
}
}
void Expression::clearContext() {
unsigned val = m_context;
while (val) {
unsigned next = val & (val - 1);
unsigned low = val ^ next; // lowest set bit
clearContext((Context)low);
val = next;
}
}
void Expression::setArgNum(int n) {
m_argNum = n;
int kc = getKidCount();
for (int i=0; i < kc; i++) {
ExpressionPtr kid = getNthExpr(i);
if (kid) {
kid->setArgNum(n);
}
}
}
void Expression::deepCopy(ExpressionPtr exp) {
exp->m_actualType = m_actualType;
exp->m_expectedType = m_expectedType;
exp->m_implementedType = m_implementedType;
exp->m_assertedType = m_assertedType;
exp->m_canon_id = 0;
exp->m_unused = false;
exp->m_canonPtr.reset();
exp->m_replacement.reset();
exp->clearVisited();
};
bool Expression::hasSubExpr(ExpressionPtr sub) const {
if (this == sub.get()) return true;
for (int i = getKidCount(); i--; ) {
ExpressionPtr kid = getNthExpr(i);
if (kid && kid->hasSubExpr(sub)) return true;
}
return false;
}
Expression::ExprClass Expression::getExprClass() const {
ExprClass cls = Classes[m_kindOf];
if (cls == Update) {
ExpressionPtr k = getStoreVariable();
if (!k || !(k->hasContext(OprLValue))) cls = Expression::None;
}
return cls;
}
FileScopeRawPtr Expression::getUsedScalarScope(CodeGenerator& cg) {
return cg.getLiteralScope() ?
cg.getLiteralScope() : getFileScope();
}
bool Expression::getEffectiveScalar(Variant &v) {
if (is(KindOfExpressionList)) {
ExpressionRawPtr sub = static_cast<ExpressionList*>(this)->listValue();
if (!sub) return false;
return sub->getEffectiveScalar(v);
}
return getScalarValue(v);
}
void Expression::addElement(ExpressionPtr exp) {
assert(false);
}
void Expression::insertElement(ExpressionPtr exp, int index /* = 0 */) {
assert(false);
}
ExpressionPtr Expression::unneededHelper() {
ExpressionListPtr elist = ExpressionListPtr
(new ExpressionList(getScope(), getLocation(),
ExpressionList::ListKindWrapped));
bool change = false;
for (int i=0, n = getKidCount(); i < n; i++) {
ExpressionPtr kid = getNthExpr(i);
if (kid && kid->getContainedEffects()) {
ExpressionPtr rep = kid->unneeded();
if (rep != kid) change = true;
if (rep->is(Expression::KindOfExpressionList)) {
for (int j=0, m = rep->getKidCount(); j < m; j++) {
elist->addElement(rep->getNthExpr(j));
}
} else {
elist->addElement(rep);
}
}
}
if (change) {
getScope()->addUpdates(BlockScope::UseKindCaller);
}
int n = elist->getCount();
assert(n);
if (n == 1) {
return elist->getNthExpr(0);
} else {
return elist;
}
}
ExpressionPtr Expression::unneeded() {
if (getLocalEffects() || is(KindOfScalarExpression) || isNoRemove()) {
return static_pointer_cast<Expression>(shared_from_this());
}
if (!getContainedEffects()) {
getScope()->addUpdates(BlockScope::UseKindCaller);
return ScalarExpressionPtr
(new ScalarExpression(getScope(), getLocation(),
T_LNUMBER, string("0")));
}
return unneededHelper();
}
///////////////////////////////////////////////////////////////////////////////
bool Expression::IsIdentifier(const string &value) {
if (value.empty()) {
return false;
}
unsigned char ch = value[0];
if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') &&
ch < '\x7f' && ch != '_') {
return false;
}
for (unsigned int i = 1; i < value.size(); i++) {
unsigned char ch = value[i];
if (((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') &&
(ch < '0' || ch > '9') && ch < '\x7f' && ch != '_')) {
if (ch == '\\' && i < value.size() - 1 && value[i+1] != '\\') {
continue;
}
return false;
}
}
return true;
}
TypePtr Expression::getType() {
if (m_expectedType) return m_expectedType;
if (m_actualType) return m_actualType;
return Type::Any;
}
TypePtr Expression::getGenType() {
if (m_expectedType) return m_expectedType;
if (m_implementedType) return m_implementedType;
if (m_actualType) return m_actualType;
return Type::Any;
}
TypePtr Expression::getCPPType() {
if (m_implementedType) return m_implementedType;
if (m_actualType) return m_actualType;
return Type::Variant;
}
TypePtr Expression::propagateTypes(AnalysisResultConstPtr ar, TypePtr inType) {
ExpressionPtr e = getCanonTypeInfPtr();
TypePtr ret = inType;
while (e) {
if (e->getAssertedType() && !getAssertedType()) {
setAssertedType(e->getAssertedType());
}
TypePtr inferred = Type::Inferred(ar, ret, e->m_actualType);
if (!inferred) {
break;
}
ret = inferred;
e = e->getCanonTypeInfPtr();
}
return ret;
}
void Expression::analyzeProgram(AnalysisResultPtr ar) {
}
BlockScopeRawPtr Expression::getOriginalScope() {
if (!m_originalScopeSet) {
m_originalScopeSet = true;
m_originalScope = getScope();
}
return m_originalScope;
}
void Expression::setOriginalScope(BlockScopeRawPtr scope) {
m_originalScope = scope;
m_originalScopeSet = true;
}
ClassScopeRawPtr Expression::getOriginalClass() {
BlockScopeRawPtr scope = getOriginalScope();
return scope ? scope->getContainingClass() : ClassScopeRawPtr();
}
FunctionScopeRawPtr Expression::getOriginalFunction() {
BlockScopeRawPtr scope = getOriginalScope();
return scope ? scope->getContainingFunction() : FunctionScopeRawPtr();
}
void Expression::resetTypes() {
m_actualType .reset();
m_expectedType .reset();
m_implementedType.reset();
}
TypePtr Expression::inferAndCheck(AnalysisResultPtr ar, TypePtr type,
bool coerce) {
IMPLEMENT_INFER_AND_CHECK_ASSERT(getScope());
assert(type);
resetTypes();
TypePtr actualType = inferTypes(ar, type, coerce);
if (type->is(Type::KindOfSome) || type->is(Type::KindOfAny)) {
m_actualType = actualType;
m_expectedType.reset();
return actualType;
}
return checkTypesImpl(ar, type, actualType, coerce);
}
TypePtr Expression::checkTypesImpl(AnalysisResultConstPtr ar,
TypePtr expectedType,
TypePtr actualType, bool coerce) {
TypePtr ret;
actualType = propagateTypes(ar, actualType);
assert(actualType);
if (coerce) {
ret = Type::Coerce(ar, expectedType, actualType);
setTypes(ar, actualType, expectedType);
} else {
ret = Type::Intersection(ar, actualType, expectedType);
setTypes(ar, actualType, ret);
}
assert(ret);
return ret;
}
void Expression::setTypes(AnalysisResultConstPtr ar, TypePtr actualType,
TypePtr expectedType) {
assert(actualType);
assert(expectedType);
m_actualType = actualType;
if (!expectedType->is(Type::KindOfAny) &&
!expectedType->is(Type::KindOfSome)) {
// store the expected type if it is not Any nor Some,
// regardless of the actual type
m_expectedType = expectedType;
} else {
m_expectedType.reset();
}
// This is a special case where Type::KindOfObject means any object.
if (m_expectedType && m_expectedType->is(Type::KindOfObject) &&
!m_expectedType->isSpecificObject() &&
m_actualType->isSpecificObject()) {
m_expectedType.reset();
}
if (m_actualType->isSpecificObject()) {
boost::const_pointer_cast<AnalysisResult>(ar)->
addClassDependency(getFileScope(), m_actualType->getName());
}
}
void Expression::setDynamicByIdentifier(AnalysisResultPtr ar,
const std::string &value) {
string id = Util::toLower(value);
size_t c = id.find("::");
FunctionScopePtr fi;
ClassScopePtr ci;
if (c != 0 && c != string::npos && c+2 < id.size()) {
string cl = id.substr(0, c);
string fn = id.substr(c+2);
if (IsIdentifier(cl) && IsIdentifier(fn)) {
ci = ar->findClass(cl);
if (ci) {
fi = ci->findFunction(ar, fn, false);
if (fi) fi->setDynamic();
}
}
} else if (IsIdentifier(id)) {
fi = ar->findFunction(id);
if (fi) fi->setDynamic();
ClassScopePtr ci = ar->findClass(id, AnalysisResult::MethodName);
if (ci) {
fi = ci->findFunction(ar, id, false);
if (fi) fi->setDynamic();
}
}
}
bool Expression::CheckNeededRHS(ExpressionPtr value) {
bool needed = true;
always_assert(value);
while (value->is(KindOfAssignmentExpression)) {
value = dynamic_pointer_cast<AssignmentExpression>(value)->getValue();
}
if (value->isScalar()) {
needed = false;
} else {
TypePtr type = value->getType();
if (type && (type->is(Type::KindOfSome) || type->is(Type::KindOfAny))) {
type = value->getActualType();
}
if (type && type->isNoObjectInvolved()) needed = false;
}
return needed;
}
bool Expression::CheckNeeded(ExpressionPtr variable, ExpressionPtr value) {
// if the value may involve object, consider the variable as "needed"
// so that objects are not destructed prematurely.
bool needed = true;
if (value) needed = CheckNeededRHS(value);
if (variable->is(Expression::KindOfSimpleVariable)) {
SimpleVariablePtr var =
dynamic_pointer_cast<SimpleVariable>(variable);
const std::string &name = var->getName();
VariableTablePtr variables = var->getScope()->getVariables();
if (needed) {
variables->addNeeded(name);
} else {
needed = variables->isNeeded(name);
}
}
return needed;
}
bool Expression::CheckVarNR(ExpressionPtr value,
TypePtr expectedType /* = TypePtr */) {
if (!expectedType) expectedType = value->getExpectedType();
return (!value->hasContext(Expression::RefValue) &&
expectedType && expectedType->is(Type::KindOfVariant) &&
(value->getCPPType()->is(Type::KindOfArray) ||
value->getCPPType()->is(Type::KindOfString) ||
value->getCPPType()->is(Type::KindOfObject) ||
value->getCPPType()->isPrimitive() ||
value->isScalar()));
}
TypePtr Expression::inferAssignmentTypes(AnalysisResultPtr ar, TypePtr type,
bool coerce, ExpressionPtr variable,
ExpressionPtr
value /* =ExpressionPtr() */) {
assert(type);
TypePtr ret = type;
if (value) {
ret = value->inferAndCheck(ar, Type::Some, false);
if (value->isLiteralNull()) {
ret = Type::Null;
}
assert(ret);
}
BlockScopePtr scope = getScope();
if (variable->is(Expression::KindOfConstantExpression)) {
// ...as in ClassConstant statement
ConstantExpressionPtr exp =
dynamic_pointer_cast<ConstantExpression>(variable);
BlockScope *defScope = nullptr;
std::vector<std::string> bases;
scope->getConstants()->check(getScope(), exp->getName(), ret,
true, ar, variable,
bases, defScope);
}
m_implementedType.reset();
TypePtr vt = variable->inferAndCheck(ar, ret, true);
if (!coerce && type->is(Type::KindOfAny)) {
ret = vt;
} else {
TypePtr it = variable->getCPPType();
if (!Type::SameType(it, ret)) {
m_implementedType = it;
}
}
if (value) {
TypePtr vat(value->getActualType());
TypePtr vet(value->getExpectedType());
TypePtr vit(value->getImplementedType());
if (vat && !vet && vit &&
Type::IsMappedToVariant(vit) &&
Type::HasFastCastMethod(vat)) {
value->setExpectedType(vat);
}
}
return ret;
}
ExpressionPtr Expression::MakeConstant(AnalysisResultConstPtr ar,
BlockScopePtr scope,
LocationPtr loc,
const std::string &value) {
ConstantExpressionPtr exp(new ConstantExpression(
scope, loc,
value, false));
if (value == "true" || value == "false") {
if (ar->getPhase() >= AnalysisResult::PostOptimize) {
exp->m_actualType = Type::Boolean;
}
} else if (value == "null") {
if (ar->getPhase() >= AnalysisResult::PostOptimize) {
exp->m_actualType = Type::Variant;
}
} else {
assert(false);
}
return exp;
}
void Expression::CheckPassByReference(AnalysisResultPtr ar,
ExpressionPtr param) {
if (param->hasContext(Expression::RefValue) &&
!param->isRefable(true)) {
param->setError(Expression::BadPassByRef);
Compiler::Error(Compiler::BadPassByReference, param);
}
}
unsigned Expression::getCanonHash() const {
int64_t val = hash_int64(getKindOf());
for (int i = getKidCount(); i--; ) {
ExpressionPtr k = getNthExpr(i);
if (k) {
val = hash_int64(val ^ (((int64_t)k->getKindOf()<<32)+k->getCanonID()));
}
}
return (unsigned)val ^ (unsigned)(val >> 32);
}
bool Expression::canonCompare(ExpressionPtr e) const {
if (e->getKindOf() != getKindOf()) {
return false;
}
int kk = getKidCount();
if (kk != e->getKidCount()) {
return false;
}
for (int i = kk; i--; ) {
ExpressionPtr k1 = getNthExpr(i);
ExpressionPtr k2 = e->getNthExpr(i);
if (k1 != k2) {
if (!k1 || !k2) {
return false;
}
if (k1->getCanonID() != k2->getCanonID()) {
return false;
}
}
}
return true;
}
bool Expression::equals(ExpressionPtr other) {
if (!other) return false;
// So that we can leverage canonCompare()
setCanonID(0);
other->setCanonID(0);
if (other->getKindOf() != getKindOf()) {
return false;
}
int nKids = getKidCount();
if (nKids != other->getKidCount()) {
return false;
}
for (int i = 0; i < nKids; i++) {
ExpressionPtr thisKid = getNthExpr(i);
ExpressionPtr otherKid = other->getNthExpr(i);
if (!thisKid || !otherKid) {
if (thisKid == otherKid) continue;
return false;
}
if (!thisKid->equals(otherKid)) {
return false;
}
}
return canonCompare(other);
}
ExpressionPtr Expression::getCanonTypeInfPtr() const {
if (!m_canonPtr) return ExpressionPtr();
if (!(m_context & (LValue|RefValue|UnsetContext|DeepReference))) {
return m_canonPtr;
}
if (!hasAnyContext(AccessContext|ObjectContext) ||
!m_canonPtr->getActualType()) {
return ExpressionPtr();
}
switch (m_canonPtr->getActualType()->getKindOf()) {
case Type::KindOfArray:
{
if (!hasContext(AccessContext)) break;
if (m_canonPtr->getAssertedType()) return m_canonPtr;
if (!is(Expression::KindOfSimpleVariable)) break;
SimpleVariableConstPtr sv(
static_pointer_cast<const SimpleVariable>(shared_from_this()));
if (sv->couldBeAliased()) return ExpressionPtr();
if (hasContext(LValue) &&
!(m_context & (RefValue | UnsetContext | DeepReference))) {
return m_canonPtr;
}
}
break;
case Type::KindOfObject:
{
if (!hasContext(ObjectContext)) break;
if (m_canonPtr->getAssertedType()) return m_canonPtr;
if (!is(Expression::KindOfSimpleVariable)) break;
SimpleVariableConstPtr sv(
static_pointer_cast<const SimpleVariable>(shared_from_this()));
if (sv->couldBeAliased()) return ExpressionPtr();
if (hasContext(LValue) &&
!(m_context & (RefValue | UnsetContext | DeepReference))) {
return m_canonPtr;
}
}
default:
break;
}
return ExpressionPtr();
}
ExpressionPtr Expression::fetchReplacement() {
ExpressionPtr t = m_replacement;
m_replacement.reset();
return t;
}
void Expression::computeLocalExprAltered() {
// if no kids, do nothing
if (getKidCount() == 0) return;
bool res = false;
for (int i = 0; i < getKidCount(); i++) {
ExpressionPtr k = getNthExpr(i);
if (k) {
k->computeLocalExprAltered();
res |= k->isLocalExprAltered();
}
}
if (res) {
setLocalExprAltered();
}
}
bool Expression::isArray() const {
if (is(KindOfUnaryOpExpression)) {
return static_cast<const UnaryOpExpression*>(this)->getOp() == T_ARRAY;
}
return false;
}
bool Expression::isUnquotedScalar() const {
if (!is(KindOfScalarExpression)) return false;
return !((ScalarExpression*)this)->isQuoted();
}
ExpressionPtr Expression::MakeScalarExpression(AnalysisResultConstPtr ar,
BlockScopePtr scope,
LocationPtr loc,
CVarRef value) {
if (value.isArray()) {
ExpressionListPtr el(new ExpressionList(scope, loc,
ExpressionList::ListKindParam));
for (ArrayIter iter(value); iter; ++iter) {
ExpressionPtr k(MakeScalarExpression(ar, scope, loc, iter.first()));
ExpressionPtr v(MakeScalarExpression(ar, scope, loc, iter.second()));
if (!k || !v) return ExpressionPtr();
ArrayPairExpressionPtr ap(
new ArrayPairExpression(scope, loc, k, v, false));
el->addElement(ap);
}
if (!el->getCount()) el.reset();
return ExpressionPtr(
new UnaryOpExpression(scope, loc, el, T_ARRAY, true));
} else if (value.isNull()) {
return MakeConstant(ar, scope, loc, "null");
} else if (value.isBoolean()) {
return MakeConstant(ar, scope, loc, value ? "true" : "false");
} else {
return ScalarExpressionPtr
(new ScalarExpression(scope, loc, value));
}
}
///////////////////////////////////////////////////////////////////////////////
void Expression::collectCPPTemps(ExpressionPtrVec &collection) {
if (isChainRoot()) {
collection.push_back(static_pointer_cast<Expression>(shared_from_this()));
} else {
for (int i = 0; i < getKidCount(); i++) {
ExpressionPtr kid = getNthExpr(i);
if (kid) kid->collectCPPTemps(collection);
}
}
}
void Expression::disableCSE() {
ExpressionPtrVec v;
collectCPPTemps(v);
ExpressionPtrVec::iterator it(v.begin());
for (; it != v.end(); ++it) {
ExpressionPtr p(*it);
p->clearChainRoot();
}
}
bool Expression::hasChainRoots() {
ExpressionPtrVec v;
collectCPPTemps(v);
return !v.empty();
}
bool Expression::GetCseTempInfo(
AnalysisResultPtr ar,
ExpressionPtr p,
TypePtr &t) {
assert(p);
switch (p->getKindOf()) {
case Expression::KindOfArrayElementExpression:
{
ArrayElementExpressionPtr ap(
static_pointer_cast<ArrayElementExpression>(p));
ExpressionPtr var(ap->getVariable());
TypePtr srcType, dstType;
bool needsCast =
var->getTypeCastPtrs(ar, srcType, dstType);
TypePtr testType(needsCast ? dstType : srcType);
if (testType) {
t = testType;
return !testType->is(Type::KindOfArray);
}
return true;
}
break;
default:
break;
}
return true;
}
ExpressionPtr Expression::getNextCanonCsePtr() const {
bool dAccessCtx =
hasContext(AccessContext);
bool dLval =
hasContext(LValue);
bool dExistCtx =
hasContext(ExistContext);
bool dUnsetCtx =
hasContext(UnsetContext);
bool dGlobals = false;
if (is(KindOfArrayElementExpression)) {
ArrayElementExpressionConstPtr a(
static_pointer_cast<const ArrayElementExpression>(
shared_from_this()));
dGlobals = a->isSuperGlobal() || a->isDynamicGlobal();
}
// see rules below - no hope to find CSE candidate
if (dExistCtx || dUnsetCtx || dGlobals || (!dAccessCtx && dLval)) {
return ExpressionPtr();
}
KindOf dKindOf = getKindOf();
ExpressionPtr match;
ExpressionPtr p(getCanonLVal());
for (; p; p = p->getCanonLVal()) {
// check if p is a suitable candidate for CSE of
// downstream. the rules are:
// A) rvals can always be CSE-ed regardless of access context,
// except for unset context, which it never can be CSE-ed for
// B) lvals can only be CSE-ed if in AccessContext
// C) rvals and lvals cannot be CSE-ed for each other
// D) for now, ExistContext is not optimized
// E) no CSE for $GLOBALS[...]
// F) node types need to match
bool pLval = p->hasContext(LValue);
KindOf pKindOf = p->getKindOf();
if (dKindOf != pKindOf) continue;
if (dLval) {
assert(dAccessCtx);
bool pAccessCtx = p->hasContext(AccessContext);
if (pLval && pAccessCtx) {
// match found
match = p;
break;
}
} else {
bool pExistCtx = p->hasContext(ExistContext);
bool pUnsetCtx = p->hasContext(UnsetContext);
if (!pLval && !pExistCtx && !pUnsetCtx) {
// match found
match = p;
break;
}
}
}
return match;
}
ExpressionPtr Expression::getCanonCsePtr() const {
ExpressionPtr next(getNextCanonCsePtr());
if (next) {
if (next->isChainRoot()) return next;
return next->getCanonCsePtr();
}
return ExpressionPtr();
}
bool Expression::getTypeCastPtrs(
AnalysisResultPtr ar, TypePtr &srcType, TypePtr &dstType) {
srcType = m_actualType;
dstType = m_expectedType;
if (m_implementedType && srcType &&
!Type::SameType(m_implementedType, srcType)) {
srcType = m_implementedType;
}
if (!srcType && dstType && Type::IsCastNeeded(ar, Type::Variant, dstType)) {
srcType = Type::Variant;
return true;
}
return dstType && srcType && ((m_context & LValue) == 0) &&
Type::IsCastNeeded(ar, srcType, dstType);
}
|
// Copyright (c) 2014-2018 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 <crypto/aes.h>
#include <crypto/chacha20.h>
#include <crypto/ripemd160.h>
#include <crypto/sha1.h>
#include <crypto/sha256.h>
#include <crypto/sha512.h>
#include <crypto/hmac_sha256.h>
#include <crypto/hmac_sha512.h>
#include <random.h>
#include <utilstrencodings.h>
#include <test/test_dollar.h>
#include <vector>
#include <boost/test/unit_test.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>
BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup)
template<typename Hasher, typename In, typename Out>
static void TestVector(const Hasher &h, const In &in, const Out &out) {
Out hash;
BOOST_CHECK(out.size() == h.OUTPUT_SIZE);
hash.resize(out.size());
{
// Test that writing the whole input string at once works.
Hasher(h).Write((unsigned char*)&in[0], in.size()).Finalize(&hash[0]);
BOOST_CHECK(hash == out);
}
for (int i=0; i<32; i++) {
// Test that writing the string broken up in random pieces works.
Hasher hasher(h);
size_t pos = 0;
while (pos < in.size()) {
size_t len = InsecureRandRange((in.size() - pos + 1) / 2 + 1);
hasher.Write((unsigned char*)&in[pos], len);
pos += len;
if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) {
// Test that writing the rest at once to a copy of a hasher works.
Hasher(hasher).Write((unsigned char*)&in[pos], in.size() - pos).Finalize(&hash[0]);
BOOST_CHECK(hash == out);
}
}
hasher.Finalize(&hash[0]);
BOOST_CHECK(hash == out);
}
}
static void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));}
static void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));}
static void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));}
static void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));}
static void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) {
std::vector<unsigned char> key = ParseHex(hexkey);
TestVector(CHMAC_SHA256(key.data(), key.size()), ParseHex(hexin), ParseHex(hexout));
}
static void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) {
std::vector<unsigned char> key = ParseHex(hexkey);
TestVector(CHMAC_SHA512(key.data(), key.size()), ParseHex(hexin), ParseHex(hexout));
}
static void TestAES128(const std::string &hexkey, const std::string &hexin, const std::string &hexout)
{
std::vector<unsigned char> key = ParseHex(hexkey);
std::vector<unsigned char> in = ParseHex(hexin);
std::vector<unsigned char> correctout = ParseHex(hexout);
std::vector<unsigned char> buf, buf2;
assert(key.size() == 16);
assert(in.size() == 16);
assert(correctout.size() == 16);
AES128Encrypt enc(key.data());
buf.resize(correctout.size());
buf2.resize(correctout.size());
enc.Encrypt(buf.data(), in.data());
BOOST_CHECK_EQUAL(HexStr(buf), HexStr(correctout));
AES128Decrypt dec(key.data());
dec.Decrypt(buf2.data(), buf.data());
BOOST_CHECK_EQUAL(HexStr(buf2), HexStr(in));
}
static void TestAES256(const std::string &hexkey, const std::string &hexin, const std::string &hexout)
{
std::vector<unsigned char> key = ParseHex(hexkey);
std::vector<unsigned char> in = ParseHex(hexin);
std::vector<unsigned char> correctout = ParseHex(hexout);
std::vector<unsigned char> buf;
assert(key.size() == 32);
assert(in.size() == 16);
assert(correctout.size() == 16);
AES256Encrypt enc(key.data());
buf.resize(correctout.size());
enc.Encrypt(buf.data(), in.data());
BOOST_CHECK(buf == correctout);
AES256Decrypt dec(key.data());
dec.Decrypt(buf.data(), buf.data());
BOOST_CHECK(buf == in);
}
static void TestAES128CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout)
{
std::vector<unsigned char> key = ParseHex(hexkey);
std::vector<unsigned char> iv = ParseHex(hexiv);
std::vector<unsigned char> in = ParseHex(hexin);
std::vector<unsigned char> correctout = ParseHex(hexout);
std::vector<unsigned char> realout(in.size() + AES_BLOCKSIZE);
// Encrypt the plaintext and verify that it equals the cipher
AES128CBCEncrypt enc(key.data(), iv.data(), pad);
int size = enc.Encrypt(in.data(), in.size(), realout.data());
realout.resize(size);
BOOST_CHECK(realout.size() == correctout.size());
BOOST_CHECK_MESSAGE(realout == correctout, HexStr(realout) + std::string(" != ") + hexout);
// Decrypt the cipher and verify that it equals the plaintext
std::vector<unsigned char> decrypted(correctout.size());
AES128CBCDecrypt dec(key.data(), iv.data(), pad);
size = dec.Decrypt(correctout.data(), correctout.size(), decrypted.data());
decrypted.resize(size);
BOOST_CHECK(decrypted.size() == in.size());
BOOST_CHECK_MESSAGE(decrypted == in, HexStr(decrypted) + std::string(" != ") + hexin);
// Encrypt and re-decrypt substrings of the plaintext and verify that they equal each-other
for(std::vector<unsigned char>::iterator i(in.begin()); i != in.end(); ++i)
{
std::vector<unsigned char> sub(i, in.end());
std::vector<unsigned char> subout(sub.size() + AES_BLOCKSIZE);
int _size = enc.Encrypt(sub.data(), sub.size(), subout.data());
if (_size != 0)
{
subout.resize(_size);
std::vector<unsigned char> subdecrypted(subout.size());
_size = dec.Decrypt(subout.data(), subout.size(), subdecrypted.data());
subdecrypted.resize(_size);
BOOST_CHECK(decrypted.size() == in.size());
BOOST_CHECK_MESSAGE(subdecrypted == sub, HexStr(subdecrypted) + std::string(" != ") + HexStr(sub));
}
}
}
static void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout)
{
std::vector<unsigned char> key = ParseHex(hexkey);
std::vector<unsigned char> iv = ParseHex(hexiv);
std::vector<unsigned char> in = ParseHex(hexin);
std::vector<unsigned char> correctout = ParseHex(hexout);
std::vector<unsigned char> realout(in.size() + AES_BLOCKSIZE);
// Encrypt the plaintext and verify that it equals the cipher
AES256CBCEncrypt enc(key.data(), iv.data(), pad);
int size = enc.Encrypt(in.data(), in.size(), realout.data());
realout.resize(size);
BOOST_CHECK(realout.size() == correctout.size());
BOOST_CHECK_MESSAGE(realout == correctout, HexStr(realout) + std::string(" != ") + hexout);
// Decrypt the cipher and verify that it equals the plaintext
std::vector<unsigned char> decrypted(correctout.size());
AES256CBCDecrypt dec(key.data(), iv.data(), pad);
size = dec.Decrypt(correctout.data(), correctout.size(), decrypted.data());
decrypted.resize(size);
BOOST_CHECK(decrypted.size() == in.size());
BOOST_CHECK_MESSAGE(decrypted == in, HexStr(decrypted) + std::string(" != ") + hexin);
// Encrypt and re-decrypt substrings of the plaintext and verify that they equal each-other
for(std::vector<unsigned char>::iterator i(in.begin()); i != in.end(); ++i)
{
std::vector<unsigned char> sub(i, in.end());
std::vector<unsigned char> subout(sub.size() + AES_BLOCKSIZE);
int _size = enc.Encrypt(sub.data(), sub.size(), subout.data());
if (_size != 0)
{
subout.resize(_size);
std::vector<unsigned char> subdecrypted(subout.size());
_size = dec.Decrypt(subout.data(), subout.size(), subdecrypted.data());
subdecrypted.resize(_size);
BOOST_CHECK(decrypted.size() == in.size());
BOOST_CHECK_MESSAGE(subdecrypted == sub, HexStr(subdecrypted) + std::string(" != ") + HexStr(sub));
}
}
}
static void TestChaCha20(const std::string &hexkey, uint64_t nonce, uint64_t seek, const std::string& hexout)
{
std::vector<unsigned char> key = ParseHex(hexkey);
ChaCha20 rng(key.data(), key.size());
rng.SetIV(nonce);
rng.Seek(seek);
std::vector<unsigned char> out = ParseHex(hexout);
std::vector<unsigned char> outres;
outres.resize(out.size());
rng.Output(outres.data(), outres.size());
BOOST_CHECK(out == outres);
}
static std::string LongTestString(void) {
std::string ret;
for (int i=0; i<200000; i++) {
ret += (unsigned char)(i);
ret += (unsigned char)(i >> 4);
ret += (unsigned char)(i >> 8);
ret += (unsigned char)(i >> 12);
ret += (unsigned char)(i >> 16);
}
return ret;
}
const std::string test1 = LongTestString();
BOOST_AUTO_TEST_CASE(ripemd160_testvectors) {
TestRIPEMD160("", "9c1185a5c5e9fc54612808977ee8f548b2258d31");
TestRIPEMD160("abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc");
TestRIPEMD160("message digest", "5d0689ef49d2fae572b881b123a85ffa21595f36");
TestRIPEMD160("secure hash algorithm", "20397528223b6a5f4cbc2808aba0464e645544f9");
TestRIPEMD160("RIPEMD160 is considered to be safe", "a7d78608c7af8a8e728778e81576870734122b66");
TestRIPEMD160("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"12a053384a9c0c88e405a06c27dcf49ada62eb2b");
TestRIPEMD160("For this sample, this 63-byte string will be used as input data",
"de90dbfee14b63fb5abf27c2ad4a82aaa5f27a11");
TestRIPEMD160("This is exactly 64 bytes long, not counting the terminating byte",
"eda31d51d3a623b81e19eb02e24ff65d27d67b37");
TestRIPEMD160(std::string(1000000, 'a'), "52783243c1697bdbe16d37f97f68f08325dc1528");
TestRIPEMD160(test1, "464243587bd146ea835cdf57bdae582f25ec45f1");
}
BOOST_AUTO_TEST_CASE(sha1_testvectors) {
TestSHA1("", "da39a3ee5e6b4b0d3255bfef95601890afd80709");
TestSHA1("abc", "a9993e364706816aba3e25717850c26c9cd0d89d");
TestSHA1("message digest", "c12252ceda8be8994d5fa0290a47231c1d16aae3");
TestSHA1("secure hash algorithm", "d4d6d2f0ebe317513bbd8d967d89bac5819c2f60");
TestSHA1("SHA1 is considered to be safe", "f2b6650569ad3a8720348dd6ea6c497dee3a842a");
TestSHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"84983e441c3bd26ebaae4aa1f95129e5e54670f1");
TestSHA1("For this sample, this 63-byte string will be used as input data",
"4f0ea5cd0585a23d028abdc1a6684e5a8094dc49");
TestSHA1("This is exactly 64 bytes long, not counting the terminating byte",
"fb679f23e7d1ce053313e66e127ab1b444397057");
TestSHA1(std::string(1000000, 'a'), "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
TestSHA1(test1, "b7755760681cbfd971451668f32af5774f4656b5");
}
BOOST_AUTO_TEST_CASE(sha256_testvectors) {
TestSHA256("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
TestSHA256("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
TestSHA256("message digest",
"f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650");
TestSHA256("secure hash algorithm",
"f30ceb2bb2829e79e4ca9753d35a8ecc00262d164cc077080295381cbd643f0d");
TestSHA256("SHA256 is considered to be safe",
"6819d915c73f4d1e77e4e1b52d1fa0f9cf9beaead3939f15874bd988e2a23630");
TestSHA256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
TestSHA256("For this sample, this 63-byte string will be used as input data",
"f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342");
TestSHA256("This is exactly 64 bytes long, not counting the terminating byte",
"ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8");
TestSHA256("As Dollar relies on 80 byte header hashes, we want to have an example for that.",
"7406e8de7d6e4fffc573daef05aefb8806e7790f55eab5576f31349743cca743");
TestSHA256(std::string(1000000, 'a'),
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
TestSHA256(test1, "a316d55510b49662420f49d145d42fb83f31ef8dc016aa4e32df049991a91e26");
}
BOOST_AUTO_TEST_CASE(sha512_testvectors) {
TestSHA512("",
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
TestSHA512("abc",
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
TestSHA512("message digest",
"107dbf389d9e9f71a3a95f6c055b9251bc5268c2be16d6c13492ea45b0199f33"
"09e16455ab1e96118e8a905d5597b72038ddb372a89826046de66687bb420e7c");
TestSHA512("secure hash algorithm",
"7746d91f3de30c68cec0dd693120a7e8b04d8073cb699bdce1a3f64127bca7a3"
"d5db502e814bb63c063a7a5043b2df87c61133395f4ad1edca7fcf4b30c3236e");
TestSHA512("SHA512 is considered to be safe",
"099e6468d889e1c79092a89ae925a9499b5408e01b66cb5b0a3bd0dfa51a9964"
"6b4a3901caab1318189f74cd8cf2e941829012f2449df52067d3dd5b978456c2");
TestSHA512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335"
"96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445");
TestSHA512("For this sample, this 63-byte string will be used as input data",
"b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e"
"6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766");
TestSHA512("This is exactly 64 bytes long, not counting the terminating byte",
"70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38"
"7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030");
TestSHA512("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"
"501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");
TestSHA512(std::string(1000000, 'a'),
"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"
"de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b");
TestSHA512(test1,
"40cac46c147e6131c5193dd5f34e9d8bb4951395f27b08c558c65ff4ba2de594"
"37de8c3ef5459d76a52cedc02dc499a3c9ed9dedbfb3281afd9653b8a112fafc");
}
BOOST_AUTO_TEST_CASE(hmac_sha256_testvectors) {
// test cases 1, 2, 3, 4, 6 and 7 of RFC 4231
TestHMACSHA256("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
"4869205468657265",
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7");
TestHMACSHA256("4a656665",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");
TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
"dddddddddddddddddddddddddddddddddddd",
"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe");
TestHMACSHA256("0102030405060708090a0b0c0d0e0f10111213141516171819",
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
"82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b");
TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a"
"65204b6579202d2048617368204b6579204669727374",
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54");
TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"5468697320697320612074657374207573696e672061206c6172676572207468"
"616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074"
"68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565"
"647320746f20626520686173686564206265666f7265206265696e6720757365"
"642062792074686520484d414320616c676f726974686d2e",
"9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2");
// Test case with key length 63 bytes.
TestHMACSHA256("4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a6566",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"9de4b546756c83516720a4ad7fe7bdbeac4298c6fdd82b15f895a6d10b0769a6");
// Test case with key length 64 bytes.
TestHMACSHA256("4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"528c609a4c9254c274585334946b7c2661bad8f1fc406b20f6892478d19163dd");
// Test case with key length 65 bytes.
TestHMACSHA256("4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"d06af337f359a2330deffb8e3cbe4b5b7aa8ca1f208528cdbd245d5dc63c4483");
}
BOOST_AUTO_TEST_CASE(hmac_sha512_testvectors) {
// test cases 1, 2, 3, 4, 6 and 7 of RFC 4231
TestHMACSHA512("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
"4869205468657265",
"87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde"
"daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854");
TestHMACSHA512("4a656665",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554"
"9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737");
TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
"dddddddddddddddddddddddddddddddddddd",
"fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39"
"bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb");
TestHMACSHA512("0102030405060708090a0b0c0d0e0f10111213141516171819",
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
"b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3db"
"a91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd");
TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a"
"65204b6579202d2048617368204b6579204669727374",
"80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352"
"6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598");
TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"5468697320697320612074657374207573696e672061206c6172676572207468"
"616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074"
"68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565"
"647320746f20626520686173686564206265666f7265206265696e6720757365"
"642062792074686520484d414320616c676f726974686d2e",
"e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944"
"b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58");
// Test case with key length 127 bytes.
TestHMACSHA512("4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a6566",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"267424dfb8eeb999f3e5ec39a4fe9fd14c923e6187e0897063e5c9e02b2e624a"
"c04413e762977df71a9fb5d562b37f89dfdfb930fce2ed1fa783bbc2a203d80e");
// Test case with key length 128 bytes.
TestHMACSHA512("4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"43aaac07bb1dd97c82c04df921f83b16a68d76815cd1a30d3455ad43a3d80484"
"2bb35462be42cc2e4b5902de4d204c1c66d93b47d1383e3e13a3788687d61258");
// Test case with key length 129 bytes.
TestHMACSHA512("4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665"
"4a",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"0b273325191cfc1b4b71d5075c8fcad67696309d292b1dad2cd23983a35feb8e"
"fb29795e79f2ef27f68cb1e16d76178c307a67beaad9456fac5fdffeadb16e2c");
}
BOOST_AUTO_TEST_CASE(aes_testvectors) {
// AES test vectors from FIPS 197.
TestAES128("000102030405060708090a0b0c0d0e0f", "00112233445566778899aabbccddeeff", "69c4e0d86a7b0430d8cdb78070b4c55a");
TestAES256("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "00112233445566778899aabbccddeeff", "8ea2b7ca516745bfeafc49904b496089");
// AES-ECB test vectors from NIST sp800-38a.
TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "6bc1bee22e409f96e93d7e117393172a", "3ad77bb40d7a3660a89ecaf32466ef97");
TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "ae2d8a571e03ac9c9eb76fac45af8e51", "f5d3d58503b9699de785895a96fdbaaf");
TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "30c81c46a35ce411e5fbc1191a0a52ef", "43b1cd7f598ece23881b00e3ed030688");
TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "f69f2445df4f9b17ad2b417be66c3710", "7b0c785e27e8ad3f8223207104725dd4");
TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "6bc1bee22e409f96e93d7e117393172a", "f3eed1bdb5d2a03c064b5a7e3db181f8");
TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "ae2d8a571e03ac9c9eb76fac45af8e51", "591ccb10d410ed26dc5ba74a31362870");
TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "30c81c46a35ce411e5fbc1191a0a52ef", "b6ed21b99ca6f4f9f153e7b1beafed1d");
TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "f69f2445df4f9b17ad2b417be66c3710", "23304b7a39f9f3ff067d8d8f9e24ecc7");
}
BOOST_AUTO_TEST_CASE(aes_cbc_testvectors) {
// NIST AES CBC 128-bit encryption test-vectors
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "000102030405060708090A0B0C0D0E0F", false, \
"6bc1bee22e409f96e93d7e117393172a", "7649abac8119b246cee98e9b12e9197d");
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "7649ABAC8119B246CEE98E9B12E9197D", false, \
"ae2d8a571e03ac9c9eb76fac45af8e51", "5086cb9b507219ee95db113a917678b2");
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "5086cb9b507219ee95db113a917678b2", false, \
"30c81c46a35ce411e5fbc1191a0a52ef", "73bed6b8e3c1743b7116e69e22229516");
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "73bed6b8e3c1743b7116e69e22229516", false, \
"f69f2445df4f9b17ad2b417be66c3710", "3ff1caa1681fac09120eca307586e1a7");
// The same vectors with padding enabled
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "000102030405060708090A0B0C0D0E0F", true, \
"6bc1bee22e409f96e93d7e117393172a", "7649abac8119b246cee98e9b12e9197d8964e0b149c10b7b682e6e39aaeb731c");
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "7649ABAC8119B246CEE98E9B12E9197D", true, \
"ae2d8a571e03ac9c9eb76fac45af8e51", "5086cb9b507219ee95db113a917678b255e21d7100b988ffec32feeafaf23538");
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "5086cb9b507219ee95db113a917678b2", true, \
"30c81c46a35ce411e5fbc1191a0a52ef", "73bed6b8e3c1743b7116e69e22229516f6eccda327bf8e5ec43718b0039adceb");
TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "73bed6b8e3c1743b7116e69e22229516", true, \
"f69f2445df4f9b17ad2b417be66c3710", "3ff1caa1681fac09120eca307586e1a78cb82807230e1321d3fae00d18cc2012");
// NIST AES CBC 256-bit encryption test-vectors
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"000102030405060708090A0B0C0D0E0F", false, "6bc1bee22e409f96e93d7e117393172a", \
"f58c4c04d6e5f1ba779eabfb5f7bfbd6");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"F58C4C04D6E5F1BA779EABFB5F7BFBD6", false, "ae2d8a571e03ac9c9eb76fac45af8e51", \
"9cfc4e967edb808d679f777bc6702c7d");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"9CFC4E967EDB808D679F777BC6702C7D", false, "30c81c46a35ce411e5fbc1191a0a52ef",
"39f23369a9d9bacfa530e26304231461");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"39F23369A9D9BACFA530E26304231461", false, "f69f2445df4f9b17ad2b417be66c3710", \
"b2eb05e2c39be9fcda6c19078c6a9d1b");
// The same vectors with padding enabled
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"000102030405060708090A0B0C0D0E0F", true, "6bc1bee22e409f96e93d7e117393172a", \
"f58c4c04d6e5f1ba779eabfb5f7bfbd6485a5c81519cf378fa36d42b8547edc0");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"F58C4C04D6E5F1BA779EABFB5F7BFBD6", true, "ae2d8a571e03ac9c9eb76fac45af8e51", \
"9cfc4e967edb808d679f777bc6702c7d3a3aa5e0213db1a9901f9036cf5102d2");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"9CFC4E967EDB808D679F777BC6702C7D", true, "30c81c46a35ce411e5fbc1191a0a52ef",
"39f23369a9d9bacfa530e263042314612f8da707643c90a6f732b3de1d3f5cee");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"39F23369A9D9BACFA530E26304231461", true, "f69f2445df4f9b17ad2b417be66c3710", \
"b2eb05e2c39be9fcda6c19078c6a9d1b3f461796d6b0d6b2e0c2a72b4d80e644");
}
BOOST_AUTO_TEST_CASE(chacha20_testvector)
{
// Test vector from RFC 7539
TestChaCha20("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 0x4a000000UL, 1,
"224f51f3401bd9e12fde276fb8631ded8c131f823d2c06e27e4fcaec9ef3cf788a3b0aa372600a92b57974cded2b9334794cb"
"a40c63e34cdea212c4cf07d41b769a6749f3f630f4122cafe28ec4dc47e26d4346d70b98c73f3e9c53ac40c5945398b6eda1a"
"832c89c167eacd901d7e2bf363");
// Test vectors from https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7
TestChaCha20("0000000000000000000000000000000000000000000000000000000000000000", 0, 0,
"76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b"
"8f41518a11cc387b669b2ee6586");
TestChaCha20("0000000000000000000000000000000000000000000000000000000000000001", 0, 0,
"4540f05a9f1fb296d7736e7b208e3c96eb4fe1834688d2604f450952ed432d41bbe2a0b6ea7566d2a5d1e7e20d42af2c53d79"
"2b1c43fea817e9ad275ae546963");
TestChaCha20("0000000000000000000000000000000000000000000000000000000000000000", 0x0100000000000000ULL, 0,
"de9cba7bf3d69ef5e786dc63973f653a0b49e015adbff7134fcb7df137821031e85a050278a7084527214f73efc7fa5b52770"
"62eb7a0433e445f41e3");
TestChaCha20("0000000000000000000000000000000000000000000000000000000000000000", 1, 0,
"ef3fdfd6c61578fbf5cf35bd3dd33b8009631634d21e42ac33960bd138e50d32111e4caf237ee53ca8ad6426194a88545ddc4"
"97a0b466e7d6bbdb0041b2f586b");
TestChaCha20("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 0x0706050403020100ULL, 0,
"f798a189f195e66982105ffb640bb7757f579da31602fc93ec01ac56f85ac3c134a4547b733b46413042c9440049176905d3b"
"e59ea1c53f15916155c2be8241a38008b9a26bc35941e2444177c8ade6689de95264986d95889fb60e84629c9bd9a5acb1cc1"
"18be563eb9b3a4a472f82e09a7e778492b562ef7130e88dfe031c79db9d4f7c7a899151b9a475032b63fc385245fe054e3dd5"
"a97a5f576fe064025d3ce042c566ab2c507b138db853e3d6959660996546cc9c4a6eafdc777c040d70eaf46f76dad3979e5c5"
"360c3317166a1c894c94a371876a94df7628fe4eaaf2ccb27d5aaae0ad7ad0f9d4b6ad3b54098746d4524d38407a6deb3ab78"
"fab78c9");
}
BOOST_AUTO_TEST_CASE(countbits_tests)
{
FastRandomContext ctx;
for (unsigned int i = 0; i <= 64; ++i) {
if (i == 0) {
// Check handling of zero.
BOOST_CHECK_EQUAL(CountBits(0), 0U);
} else if (i < 10) {
for (uint64_t j = 1 << (i - 1); (j >> i) == 0; ++j) {
// Exhaustively test up to 10 bits
BOOST_CHECK_EQUAL(CountBits(j), i);
}
} else {
for (int k = 0; k < 1000; k++) {
// Randomly test 1000 samples of each length above 10 bits.
uint64_t j = ((uint64_t)1) << (i - 1) | ctx.randbits(i - 1);
BOOST_CHECK_EQUAL(CountBits(j), i);
}
}
}
}
BOOST_AUTO_TEST_CASE(sha256d64)
{
for (int i = 0; i <= 32; ++i) {
unsigned char in[64 * 32];
unsigned char out1[32 * 32], out2[32 * 32];
for (int j = 0; j < 64 * i; ++j) {
in[j] = InsecureRandBits(8);
}
for (int j = 0; j < i; ++j) {
CHash256().Write(in + 64 * j, 64).Finalize(out1 + 32 * j);
}
SHA256D64(out2, in, i);
BOOST_CHECK(memcmp(out1, out2, 32 * i) == 0);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
*
* Copyright (c) 2020 Project CHIP 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.
*/
/**
* @file
* Provides an implementation of the PlatformManager object
* for Qorvo QPG platforms
*/
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>
#include <platform/PlatformManager.h>
#include <platform/internal/GenericPlatformManagerImpl_FreeRTOS.cpp>
#include <lwip/tcpip.h>
namespace chip {
namespace DeviceLayer {
PlatformManagerImpl PlatformManagerImpl::sInstance;
CHIP_ERROR PlatformManagerImpl::_InitChipStack(void)
{
CHIP_ERROR err;
// Initialize the configuration system.
err = Internal::QPGConfig::Init();
SuccessOrExit(err);
SetConfigurationMgr(&ConfigurationManagerImpl::GetDefaultInstance());
// Initialize LwIP.
tcpip_init(NULL, NULL);
// Call _InitChipStack() on the generic implementation base class
// to finish the initialization process.
err = Internal::GenericPlatformManagerImpl_FreeRTOS<PlatformManagerImpl>::_InitChipStack();
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR PlatformManagerImpl::_GetCurrentHeapFree(uint64_t & currentHeapFree)
{
size_t freeHeapSize;
size_t usedHeapSize;
size_t highWatermarkHeapSize;
qvCHIP_GetHeapStats(&freeHeapSize, &usedHeapSize, &highWatermarkHeapSize);
currentHeapFree = static_cast<uint64_t>(freeHeapSize);
return CHIP_NO_ERROR;
}
CHIP_ERROR PlatformManagerImpl::_GetCurrentHeapUsed(uint64_t & currentHeapUsed)
{
size_t freeHeapSize;
size_t usedHeapSize;
size_t highWatermarkHeapSize;
qvCHIP_GetHeapStats(&freeHeapSize, &usedHeapSize, &highWatermarkHeapSize);
currentHeapUsed = static_cast<uint64_t>(usedHeapSize);
return CHIP_NO_ERROR;
}
CHIP_ERROR PlatformManagerImpl::_GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark)
{
size_t freeHeapSize;
size_t usedHeapSize;
size_t highWatermarkHeapSize;
qvCHIP_GetHeapStats(&freeHeapSize, &usedHeapSize, &highWatermarkHeapSize);
currentHeapHighWatermark = static_cast<uint64_t>(highWatermarkHeapSize);
return CHIP_NO_ERROR;
}
} // namespace DeviceLayer
} // namespace chip
|
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/BoundFunction.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/GlobalObject.h>
namespace JS {
FunctionObject::FunctionObject(Object& prototype)
: Object(prototype)
{
}
FunctionObject::~FunctionObject()
{
}
BoundFunction* FunctionObject::bind(Value bound_this_value, Vector<Value> arguments)
{
auto& vm = this->vm();
FunctionObject& target_function = is<BoundFunction>(*this) ? static_cast<BoundFunction&>(*this).bound_target_function() : *this;
auto get_bound_this_object = [&vm, bound_this_value, this]() -> ThrowCompletionOr<Value> {
if (is<BoundFunction>(*this) && !static_cast<BoundFunction&>(*this).bound_this().is_empty())
return static_cast<BoundFunction&>(*this).bound_this();
switch (bound_this_value.type()) {
case Value::Type::Undefined:
case Value::Type::Null:
if (vm.in_strict_mode())
return bound_this_value;
return &global_object();
default:
return TRY(bound_this_value.to_object(global_object()));
}
};
auto bound_this_object = TRY_OR_DISCARD(get_bound_this_object());
i32 computed_length = 0;
auto length_property = TRY_OR_DISCARD(get(vm.names.length));
if (length_property.is_number())
computed_length = max(0, length_property.as_i32() - static_cast<i32>(arguments.size()));
Object* constructor_prototype = nullptr;
auto prototype_property = TRY_OR_DISCARD(target_function.get(vm.names.prototype));
if (prototype_property.is_object())
constructor_prototype = &prototype_property.as_object();
Vector<Value> all_bound_arguments;
if (is<BoundFunction>(*this))
all_bound_arguments.extend(static_cast<BoundFunction&>(*this).bound_arguments());
all_bound_arguments.extend(move(arguments));
return heap().allocate<BoundFunction>(global_object(), global_object(), target_function, bound_this_object, move(all_bound_arguments), computed_length, constructor_prototype);
}
}
|
#include <boost/program_options.hpp>
#include "CalculateDR.hpp"
namespace po = boost::program_options;
po::variables_map parse_args(int argc, char **argv) {
// Define command line options
po::variables_map vm;
po::options_description desc("Allowed Options");
desc.add_options()("help,h", po::bool_switch()->default_value(false),
"Display this information.")(
"write_more,w", po::bool_switch()->default_value(false),
"Write source, flux, and current data to HDF5.")(
"num_threads,j", po::value<int>()->default_value(1),
"Number of threads to use.");
// Parse arguments and look for invalid options
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
} catch (std::exception &e) {
std::cout << "Error: " << e.what() << std::endl;
std::cout << desc << std::endl;
exit(1);
}
// Display help message if requested
if (vm["help"].as<bool>()) {
std::cout << desc << std::endl;
exit(0);
}
// Set number of OMP threads and error-check
int num_threads = vm["num_threads"].as<int>();
#ifdef _OPENMP
if (num_threads < 1) {
std::cout << "Error: number of threads must be positive." << std::endl;
exit(1);
}
omp_set_num_threads(num_threads);
#else
if (num_threads != 1) {
std::cout << "Warning: the program was not compiled with OMP support but "
"multiple threads were requested in the command line. "
"Calculation will proceed with a single thread."
<< std::endl;
}
#endif
// Return options
return vm;
}
int main(int argc, char **argv) {
po::variables_map vm = parse_args(argc, argv);
CalculateDR p = CalculateDR(vm["write_more"].as<bool>());
p.run_all();
return 0;
}
|
#include "sum.h"
int sum(int N,int M){
int sum = 0;
for(int i=N; i<=M; ++i)
sum += i;
return sum;
}
|
////////////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2021, Wiktor Kasjaniuk
// 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 of the copyright holder 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.
////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Event.hpp"
#include "../Vector2.hpp"
#include "../../Structure/Input.hpp"
#include "KeyboardModifiers.hpp"
namespace ae {
class Event;
namespace internal {
class MouseButtonEvent : public Event {
public:
MouseButton GetButton() const { return m_button; }
KeyboardModifiers GetModifiers() const { return m_modifiers; }
protected:
MouseButtonEvent(MouseButton button, KeyboardModifiers modifiers) : Event(), m_button(button), m_modifiers(modifiers) {}
private:
MouseButton m_button;
KeyboardModifiers m_modifiers;
};
}
class EventMouseButtonReleased : public internal::MouseButtonEvent {
friend class ae::Event;
public:
EventMouseButtonReleased(MouseButton button, KeyboardModifiers modifiers) : internal::MouseButtonEvent(button, modifiers) {}
protected:
AE_EVENT_TYPE_FUNCTIONS(EventType::MouseButtonReleased);
};
class EventMouseButtonPressed : public internal::MouseButtonEvent {
friend class ae::Event;
public:
EventMouseButtonPressed(MouseButton button, KeyboardModifiers modifiers, bool double_click) : internal::MouseButtonEvent(button, modifiers), m_double_click(double_click) {}
bool IsDoubleClicked() const { return m_double_click; }
protected:
AE_EVENT_TYPE_FUNCTIONS(EventType::MouseButtonPressed);
private:
bool m_double_click;
};
class EventMouseScrolled : public Event {
friend class ae::Event;
public:
EventMouseScrolled(const Vector2f& offset) : Event(), m_offset(offset) {}
const Vector2f& GetOffset() const { return m_offset; }
protected:
AE_EVENT_TYPE_FUNCTIONS(EventType::MouseScrolled);
private:
Vector2f m_offset;
};
class EventMouseMoved : public Event {
friend class ae::Event;
public:
EventMouseMoved(const Vector2f& position) : Event(), m_position(position) {}
const Vector2f& GetPosition() const { return m_position; }
protected:
AE_EVENT_TYPE_FUNCTIONS(EventType::MouseMoved);
private:
Vector2f m_position;
};
class EventMouseEnteredContext : public Event {
friend class ae::Event;
public:
EventMouseEnteredContext() : Event() {}
protected:
AE_EVENT_TYPE_FUNCTIONS(EventType::MouseEnteredContext);
};
class EventMouseLeftContext : public Event {
friend class ae::Event;
public:
EventMouseLeftContext() : Event() {}
protected:
AE_EVENT_TYPE_FUNCTIONS(EventType::MouseLeftContext);
};
}
|
//////////////////////////////////////////////////////////////////////////
#include "Resources/Monitors/Manual.hpp"
#include "Resources/Locator.hpp"
#include "Resources/ID.hpp"
using namespace CPF;
using namespace Resources;
using namespace Monitors;
GOM::Result CPF_STDCALL Manual::QueryInterface(uint64_t id, void** outIface)
{
if (outIface)
{
switch (id)
{
case iUnknown::kIID.GetID():
*outIface = static_cast<iUnknown*>(this);
break;
case kIID.GetID():
*outIface = static_cast<iMonitor*>(this);
break;
default:
return GOM::kUnknownInterface;
}
AddRef();
return GOM::kOK;
}
return GOM::kInvalidParameter;
}
bool Manual::Touch(ID id)
{
if (GetLocator())
return GetLocator()->Touch(id);
return false;
}
void Manual::TouchAll()
{
if (GetLocator())
GetLocator()->TouchAll();
}
Manual::Manual(Plugin::iRegistry*, iUnknown*)
{}
Manual::~Manual()
{}
|
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2017
// MIT License
#include <ArduinoJson/Polyfills/isInteger.hpp>
#include <catch.hpp>
using namespace ArduinoJson::Polyfills;
TEST_CASE("isInteger()") {
SECTION("Null") {
REQUIRE_FALSE(isInteger(NULL));
}
SECTION("FloatNotInteger") {
REQUIRE_FALSE(isInteger("3.14"));
REQUIRE_FALSE(isInteger("-3.14"));
REQUIRE_FALSE(isInteger("+3.14"));
}
SECTION("Spaces") {
REQUIRE_FALSE(isInteger("42 "));
REQUIRE_FALSE(isInteger(" 42"));
}
SECTION("Valid") {
REQUIRE(isInteger("42"));
REQUIRE(isInteger("-42"));
REQUIRE(isInteger("+42"));
}
SECTION("ExtraSign") {
REQUIRE_FALSE(isInteger("--42"));
REQUIRE_FALSE(isInteger("++42"));
}
}
|
/**
* This file is part of the CernVM File System
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include "cvmfs_config.h"
#include "uri_map.h"
#include <inttypes.h>
#include <cassert>
using namespace std; // NOLINT
WebRequest::WebRequest(const struct mg_request_info *req) {
string method = req->request_method;
if (method == "GET")
verb_ = WebRequest::kGet;
else if (method == "PUT")
verb_ = WebRequest::kPut;
else if (method == "POST")
verb_ = WebRequest::kPost;
else if (method == "DELETE")
verb_ = WebRequest::kDelete;
else
verb_ = WebRequest::kUnknown;
uri_ = req->uri;
}
//------------------------------------------------------------------------------
void WebReply::Send(Code code, const string &msg, struct mg_connection *conn) {
string header;
switch (code) {
case k200: header = "HTTP/1.1 200 OK\r\n"; break;
case k400: header = "HTTP/1.1 400 Bad Request\r\n"; break;
case k404: header = "HTTP/1.1 404 Not Found\r\n"; break;
case k405: header = "HTTP/1.1 405 Method Not Allowed\r\n"; break;
case k500: header = "HTTP/1.1 500 Internal Server Error\r\n"; break;
default: assert(false);
}
mg_printf(conn,
"%s"
"Content-Type: text/plain\r\n"
"Content-Length: %" PRIuPTR "\r\n"
"\r\n"
"%s", header.c_str(), msg.length(), msg.c_str());
}
//------------------------------------------------------------------------------
void UriMap::Clear() {
rules_.clear();
}
void UriMap::Register(const WebRequest &request, UriHandler *handler) {
Pathspec path_spec(request.uri());
assert(path_spec.IsValid() && path_spec.IsAbsolute());
rules_.push_back(Match(path_spec, request.verb(), handler));
}
UriHandler *UriMap::Route(const WebRequest &request) {
for (unsigned i = 0; i < rules_.size(); ++i) {
if ( (rules_[i].uri_spec.IsPrefixMatching(request.uri())) &&
(rules_[i].verb == request.verb()) )
{
return rules_[i].handler;
}
}
return NULL;
}
bool UriMap::IsKnownUri(const std::string &uri) {
for (unsigned i = 0; i < rules_.size(); ++i) {
if (rules_[i].uri_spec.IsPrefixMatching(uri))
return true;
}
return false;
}
|
#include "CScriptCompilerKeyWordEntry.hpp"
#include "API/Functions.hpp"
#include "Platform/ASLR.hpp"
namespace NWNXLib {
namespace API {
}
}
|
/**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* 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 "glow/Runtime/HostManager/HostManager.h"
#include "glow/Backends/DeviceManager.h"
#include "glow/Exporter/ONNXModelWriter.h"
#include "glow/Flags/Flags.h"
#include "glow/Graph/PlaceholderBindings.h"
#include "glow/Optimizer/GraphOptimizer/GraphOptimizer.h"
#include "glow/Partitioner/Partitioner.h"
#include "glow/Runtime/DeferredWeightLoader.h"
#include "glow/Runtime/DeviceHealthMonitor.h"
#include "glow/Runtime/ErrorReporter.h"
#include "glow/Runtime/Executor/ThreadPoolExecutor.h"
#include "glow/Runtime/Provisioner/Provisioner.h"
#include "glow/Runtime/RequestData.h"
#include "glow/Runtime/RuntimeTypes.h"
#include "glow/Support/Support.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormatVariadic.h"
#include <glog/logging.h>
#include "folly/String.h"
#include "folly/executors/CPUThreadPoolExecutor.h"
#include <algorithm>
#include <future>
#include <queue>
#include <shared_mutex>
constexpr uint64_t P2PInputLimit = 256;
using namespace glow;
using namespace runtime;
namespace {
llvm::cl::OptionCategory hostManagerCat("HostManager Options");
llvm::cl::opt<std::string> loadBackendSpecificOptionsOpt(
"load-backend-specific-opts",
llvm::cl::desc("Load backend-specific options for compilation."),
llvm::cl::value_desc("options.yaml"), llvm::cl::Optional,
llvm::cl::cat(hostManagerCat));
} // namespace
namespace glow {
#if FACEBOOK_INTERNAL
Error optimizeDAG(DAGListTy &nodeList, const Provisioner &provisioner,
Module &mod, const std::vector<DeviceInfo> &devices,
CompilationContext &cctx,
ConstantFoldingRecordMap &constFoldRecord);
extern const char *revisionHash;
#endif /* FACEBOOK_INTERNAL */
} // namespace glow
/// The device configs file used for Runtime.
llvm::cl::opt<std::string> loadDeviceConfigsFileOpt(
"load-device-configs",
llvm::cl::desc("Load device configs used in Runtime"),
llvm::cl::value_desc("configs.yaml"), llvm::cl::Optional,
llvm::cl::cat(hostManagerCat));
/// The value that should be used for device initialization timeout, default:
/// 5000 milliseconds.
llvm::cl::opt<unsigned, /* ExternalStorage */ true> deviceInitTimeout(
"device_init_timeout_ms",
llvm::cl::desc("Set device init timout in milliseconds"),
llvm::cl::Optional,
llvm::cl::location(glow::runtime::flags::DeviceInitTimeoutMs),
llvm::cl::cat(hostManagerCat));
HostManager::HostManager() : HostManager(HostConfig{}) {}
HostManager::HostManager(const HostConfig &hostConfig)
: config_(hostConfig),
statsExporterRegistry_(StatsExporterRegistry::Stats()) {
statsExporterRegistry_->setCounter(kMaxQueueSize, hostConfig.maxQueueSize);
}
HostManager::HostManager(
std::vector<std::unique_ptr<DeviceConfig>> deviceConfigs)
: HostManager(std::move(deviceConfigs), HostConfig{}) {}
HostManager::HostManager(
std::vector<std::unique_ptr<DeviceConfig>> deviceConfigs,
const HostConfig &hostConfig)
: config_(hostConfig),
statsExporterRegistry_(StatsExporterRegistry::Stats()) {
// TODO: move all initialization out of constructor.
REPORT_AND_EXIT_ON_ERR(init(std::move(deviceConfigs)));
statsExporterRegistry_->setCounter(kMaxQueueSize, hostConfig.maxQueueSize);
}
Expected<DAG *> HostManager::getNetworkDAG(llvm::StringRef network) {
auto it = networks_.find(network.str());
if (it == networks_.end()) {
return MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_ERROR, "Network not found.");
}
return &it->second.dag;
}
Error HostManager::startDeviceTrace() {
LOG(INFO) << "start device tracing" << std::endl;
for (auto &dev : devices_) {
Error err = dev.second->startDeviceTrace(hostTraceContext_.get());
RETURN_IF_ERR(err);
}
return Error::success();
}
Error HostManager::stopDeviceTrace() {
auto *traceContext = hostTraceContext_.get();
if (!traceContext) {
LOG(INFO) << "No HostManager TraceContext registered, skipping call to "
"stopDeviceTrace";
return Error::success();
} else {
LOG(INFO) << "stop device tracing";
}
for (auto &dev : devices_) {
Error err = dev.second->stopDeviceTrace(traceContext);
RETURN_IF_ERR(err);
}
return Error::success();
}
Error HostManager::init(std::vector<std::unique_ptr<DeviceConfig>> configs) {
static std::once_flag monitorFlag;
std::call_once(monitorFlag, []() {
auto monitors = DeviceHealthMonitorRegistry::Monitors();
if (monitors) {
monitors->start();
}
});
DeviceIDTy deviceCount = 0;
for (auto &config : configs) {
if (!config->hasName()) {
config->name = "device_" + std::to_string(deviceCount);
}
devices_[deviceCount] = std::unique_ptr<DeviceManager>(
DeviceManager::createDeviceManager(*config));
std::promise<Error> devPromise;
auto devFuture = devPromise.get_future();
auto *dev = devices_[deviceCount].get();
threadPool_.submit([&devPromise, dev] {
auto err = dev->init();
devPromise.set_value(std::move(err));
});
if (devFuture.wait_for(std::chrono::milliseconds(
flags::DeviceInitTimeoutMs)) != std::future_status::timeout) {
RETURN_IF_ERR(devFuture.get());
} else {
// Device initialization is taking longer than expected, return an error.
return MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_ERROR,
"Timeout encountered when initializing device: " +
std::string(config->name));
}
availableDevices_.push_back(deviceCount);
deviceCount++;
}
#ifdef FACEBOOK_INTERNAL
LOG(INFO) << "Initialized " << deviceCount << " device(s)";
#endif
provisioner_.reset(new Provisioner(devices_));
executor_.reset(
new ThreadPoolExecutor(devices_, config_.executorThreads, "HostManager"));
exportMemoryCounters();
if (flags::AvailableDevices.length()) {
std::vector<unsigned> devices;
folly::split<char, std::string, unsigned>(',', flags::AvailableDevices,
devices,
/* ignoreEmpty */ true);
std::vector<runtime::DeviceIDTy> convertedDevs(devices.begin(),
devices.end());
setAvailableDevices(convertedDevs);
}
// If no HostManager is registered yet, register this one.
if (!ManagerRegistry()->getHostManager()) {
ManagerRegistry()->registerHostManager(this);
}
return Error::success();
}
void HostManager::setAvailableDevices(const std::vector<DeviceIDTy> &devices) {
// Validate new device list.
availableDevices_.clear();
std::vector<DeviceIDTy> mapping;
std::vector<DeviceManager *> availableDevices;
// Grab a lock to prevent devices_ getting changed concurrently.
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
for (auto dev : devices) {
auto it = devices_.find(dev);
if (it != devices_.end()) {
availableDevices_.push_back(dev);
availableDevices.push_back(devices_[dev].get());
mapping.push_back(it->first);
}
}
// Update the provisioner.
provisioner_->updateAvailableDevices(availableDevices, mapping);
}
void HostManager::exportMemoryCounters() {
uint64_t maxMem = 0;
uint64_t availableMem = 0;
for (auto &dev : devices_) {
maxMem += dev.second->getMaximumMemory();
availableMem += dev.second->getAvailableMemory();
}
statsExporterRegistry_->setCounter(kDeviceMemoryUsed, maxMem - availableMem);
statsExporterRegistry_->setCounter(kDeviceMemoryAvailable, availableMem);
statsExporterRegistry_->setCounter(kDeviceMemoryMax, maxMem);
}
HostManager::~HostManager() {
LOG(INFO) << "Destroying host manager...";
ERR_TO_VOID(clearHost());
exportMemoryCounters();
}
void HostManager::cleanupAddNetwork(llvm::ArrayRef<std::string> names) {
for (auto &name : names) {
processingNetworks_.erase(name);
}
exportMemoryCounters();
}
Error HostManager::addNetwork(std::unique_ptr<Module> module,
CompilationContext &cctx) {
#ifdef FACEBOOK_INTERNAL
LOG(INFO) << "Adding Glow network built with revision hash: " << revisionHash;
#endif /* FACEBOOK_INTERNAL */
VLOG(1) << "addNetwork";
ScopeGuard debugDumpDAGGuard([&]() {
if (cctx.dumpFinalGraph) {
for (Function *F : module->getFunctions()) {
auto fname = strFormat("%sfinal_graph_dbg_err_%s.dot",
cctx.dumpGraphPath.c_str(), F->getName().data());
LOG(INFO) << "Dumping final graph due to error to " << fname;
F->dumpDAG(fname);
}
}
});
/// If specified in the cctx, this will prevent Constants from being modified
/// until the current scope ends or the preventer is dismissed. Does so by
/// swapping in temporary Placeholders instead of Constants.
ConstantModificationPreventer constModPreventer(*module, cctx);
if (cctx.optimizationOpts.delayAndRecordConstantModification) {
constModPreventer.activate();
}
std::vector<std::string> names;
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
auto functions = module->getFunctions();
for (auto &F : functions) {
std::string name = F->getName().str();
auto it = networks_.find(name);
if (it != networks_.end() ||
processingNetworks_.find(name) != processingNetworks_.end()) {
cleanupAddNetwork(names);
return MAKE_ERR(
ErrorValue::ErrorCode::RUNTIME_ERROR,
"Failed to add network: already have a function called " + name);
}
// Add the network to processingNetworks_ so we know it's being worked on.
processingNetworks_.insert(name);
names.push_back(name);
}
}
// Issue a warning when loading backend specific options from the command line
// and the compile context also contains backend specific options.
if (!loadBackendSpecificOptionsOpt.empty()) {
if (cctx.backendOpts.backendSpecificOpts.size() != 0) {
VLOG_EVERY_N(1, 1000) << "Warning: backendSpecificOpts is set via the "
"HostManager, ignoring previously set options.";
}
cctx.backendOpts.backendSpecificOpts =
deserializeStrStrMapFromYaml(loadBackendSpecificOptionsOpt);
} else {
auto ctxLoadBackendSpecificOpt =
cctx.backendOpts.backendSpecificOpts.find("loadBackendSpecificOptions");
if (ctxLoadBackendSpecificOpt !=
cctx.backendOpts.backendSpecificOpts.end()) {
cctx.backendOpts.backendSpecificOpts =
deserializeStrStrMapFromYaml(ctxLoadBackendSpecificOpt->second);
}
}
std::vector<DeviceInfo> deviceInfo;
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
for (auto &device : availableDevices_) {
DeviceInfo info = devices_[device]->getDeviceInfo();
info.availableMemory = devices_[device]->getAvailableMemory();
info.backendName = devices_[device]->getBackendName().str();
info.nonSupportedNodes =
devices_[device]->getParamByName("nonSupportedNodes").str();
info.supportedNodes =
devices_[device]->getParamByName("supportedNodes").str();
// If p2p is enabled update the inputCount limit.
if (cctx.enableP2P) {
info.inputCountMax = P2PInputLimit;
}
deviceInfo.push_back(info);
}
}
// Optimize Functions only if we don't have any backendSpecificNodeInfo,
// because if we do then the Functions were already optimized and Nodes had
// extra info mapped to them, so we don't want to mutate the Function. Also
// skip optimizations if we're loading an AOT optimized model.
const bool skipOptimizations =
cctx.loadingAOTModel || !cctx.backendOpts.backendSpecificNodeInfo.empty();
// Perform a round of target-independent graph optimizations. This helps the
// partitioner to do its job more efficiently.
if (!skipOptimizations) {
for (Function *F : module->getFunctions()) {
auto err = optimizeFunctionBeforeLowering(F, cctx);
if (err) {
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
cleanupAddNetwork(names);
}
RETURN_ERR(err);
}
}
}
VLOG(1) << "Before partitioner";
Partitioner partitioner(module.get(), deviceInfo, skipOptimizations);
auto backendName = devices_[0]->getBackendName();
const auto &backend = provisioner_->getBackend(backendName);
auto contextCount = backend.getContextCount(cctx);
partitioner.setContextCount(contextCount);
DAGListTy nodeList;
auto result = partitioner.partition(cctx);
VLOG(1) << "After partitioner";
if (result) {
nodeList = std::move(result.get());
} else {
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
cleanupAddNetwork(names);
RETURN_ERR(result.takeError());
}
VLOG(1) << "Before quantmode";
if (cctx.precisionConfig.quantMode == QuantizationMode::Profile) {
// Since for profiling the provisioner will be reset, we only allow one
// network in one HM.
if (networks_.size() > 0) {
return MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_ERROR,
"For quantization profiling flow, there can't be other "
"registered networks before this one");
}
// For profiling, we use CPU backend. Overwrite Provisioner and Executor
// to force the network is compiled and run in profilingBackend. backend.
size_t devicesNum = devices_.size();
for (size_t i = 0; i < devicesNum; i++) {
auto name = devices_[i]->getDeviceConfig().name;
auto config = glow::make_unique<DeviceConfig>(profilingBackend, name);
devices_[i] = std::unique_ptr<DeviceManager>(
DeviceManager::createDeviceManager(*config));
RETURN_IF_ERR(devices_[i]->init());
}
provisioner_.reset(new Provisioner(devices_));
executor_.reset(new ThreadPoolExecutor(devices_, config_.executorThreads));
}
VLOG(1) << "Before replace dummy TQPs";
// Now that we've partitioned and optimized, do some verification based on the
// dummy mode we're using, if any.
if (cctx.precisionConfig.replaceDummyTQPs ||
cctx.precisionConfig.loadUniquedDummyQParams) {
RETURN_IF_ERR(module->verifyDummyQParams(
cctx.precisionConfig.loadUniquedDummyQParams));
}
// If we are loading an AOT model where we are replacing dummy TQPs, then we
// may need to update Relu output types on FCs, since they should be set to
// use zero as min but the correct qparams could not be calculated AOT.
if (cctx.loadingAOTModel && cctx.precisionConfig.replaceDummyTQPs) {
LOG(INFO) << "Updating quantized Relu types given real TQPs";
for (Function *F : module->getFunctions()) {
updateQuantReluTypes(F);
}
}
VLOG(1) << "Before constant folding";
// If we prevented constant modification then run constant folding with
// recording now. Record so that if we are going to serialize we can embed the
// constant folding subgraphs in the Glow ONNX model.
ConstantFoldingRecordMap record;
if (cctx.optimizationOpts.delayAndRecordConstantModification) {
constModPreventer.deactivateAndCleanup();
RETURN_ERR_IF_NOT(nodeList.size() == 1, "Expect only one DAG.");
const auto &dag = *nodeList.begin();
for (auto &dagNode : dag.nodes) {
Function *F = module->getFunction(dagNode->name);
RETURN_ERR_IF_NOT(
F, strFormat("Function %s not found", dagNode->name.data()));
ConstantFoldingRecordMap currRecord = constantFoldAndRecord(F, cctx);
record.insert(currRecord.begin(), currRecord.end());
runDCEPass(F, cctx);
// Verify the Function is valid after constant folding takes place.
Backend &B = provisioner_->getBackend(dagNode->backendName);
RETURN_ERR_IF_NOT(
B.verify(*F, cctx.verboseCompile),
"Unsupported node(s) found after delayed constant folding Function " +
F->getName().str() + " for backend " + B.getBackendName());
}
}
VLOG(1) << "Before loading AOT";
if (!cctx.loadingAOTModel) {
if (cctx.callDAGOptimizer) {
#if FACEBOOK_INTERNAL
auto optDagErr = optimizeDAG(nodeList, *provisioner_, *module, deviceInfo,
cctx, record);
if (optDagErr) {
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
cleanupAddNetwork(names);
RETURN_ERR(optDagErr);
}
#endif /* FACEBOOK_INTERNAL */
} else {
// If not using the DAG optimizer, iterate over the DAGs and call
// transformPostOptPipeline() on the Functions.
VLOG(1) << "No DAG optimizer";
for (const auto &dag : nodeList) {
for (auto &dagNode : dag.nodes) {
Function *F = module->getFunction(dagNode->name);
RETURN_ERR_IF_NOT(
F, strFormat("Function %s not found", dagNode->name.data()));
if (cctx.optimizationOpts.onlyLowerFuns.count(F)) {
continue;
}
Backend &B = provisioner_->getBackend(dagNode->backendName);
RETURN_IF_EXPECTED_IS_ERR(B.transformPostOptPipeline(F, cctx));
RETURN_ERR_IF_NOT(
B.verify(*F, cctx.verboseCompile),
"Unsupported node(s) found after transformPostOptPipeline() " +
F->getName().str() + " for backend " + B.getBackendName());
}
}
}
}
VLOG(1) << "Before serialize compile DAG";
// If requested, serialize the resulting DAG that was just optimized and
// partitioned.
if (cctx.serializeCompiledDAG) {
std::string loc;
char *envSpecifiedSerializationPath = getenv("GLOW_DAG_SERIALIZATION_LOC");
if (!envSpecifiedSerializationPath) {
loc = nodeList.begin()->root->name + ".onnxtxt";
} else {
loc = std::string(envSpecifiedSerializationPath);
}
LOG(INFO) << "Serializing final compiled DAG to " << loc;
{
llvm::StringMap<std::string> extraMetadataProps;
if (cctx.precisionConfig.originNameToTQPMap) {
RETURN_IF_ERR(ONNXModelWriter::insertLoaderNameUniqueOffsetMetadata(
extraMetadataProps, *cctx.precisionConfig.originNameToTQPMap));
}
if (cctx.precisionConfig.clipQuantRangeToFP16) {
extraMetadataProps[clipQuantRangeToFP16Key] = "1";
}
Error writeErr = Error::empty();
// Note: If cctx.skipProvisioning then we want to serialize all meta info
// as we are likely doing AOT optimization. Otherwise do not provide the
// meta info as the model does not need to be reloaded.
ONNXModelWriter onnxWR(
loc, nodeList, 7, 9, &writeErr,
/* textMode */ true,
/* zipMode */ cctx.useZipModeForSerializeCompiledDAG,
/* includeConstantData */ cctx.saveConstantInSerializeCompiledDAG,
extraMetadataProps, record, cctx.backendOpts.backendSpecificNodeInfo,
cctx.skipProvisioning ? &cctx.loadedPHNames : nullptr,
cctx.skipProvisioning ? &cctx.staticPlaceholderTypesForAOT : nullptr,
cctx.returnGlowSerializedModelStr
? cctx.glowAOTSerializationModelStrPtr.get()
: nullptr);
RETURN_IF_ERR(writeErr);
}
// If we're using AOT DAG optimizer then skip provisioning.
if (cctx.skipProvisioning ||
(cctx.callDAGOptimizer && cctx.useDAGOptimizerAOTMode)) {
LOG(INFO) << "Host manager skipping provisioning";
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
cleanupAddNetwork(names);
}
debugDumpDAGGuard.dismiss();
cleanupConstantFolding(*module, record);
if (cctx.dumpFinalGraph) {
for (Function *F : module->getFunctions()) {
auto fname =
strFormat("%sfinal_graph_aot_%s.dot", cctx.dumpGraphPath.c_str(),
F->getName().data());
LOG(INFO) << "Dumping final graph to " << fname;
F->dumpDAG(fname);
}
}
return Error::success();
}
}
// Now that we've serialized the model if requested, cleanup the temporary
// Functions and PHs used for constant folding.
cleanupConstantFolding(*module, record);
VLOG(1) << "Before provisioning";
auto err = provisioner_->provision(nodeList, *module, cctx);
if (err) {
if (err.peekErrorValue()->isFatalError()) {
statsExporterRegistry_->setCounter(kDeviceFatalError, 1);
}
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
cleanupAddNetwork(names);
}
RETURN_ERR(err);
}
debugDumpDAGGuard.dismiss();
VLOG(1) << "Calculation of maxActiveRequests";
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
/// Calculate networkMaxActive requests. Then update
/// config_.maxActiveRequests This will be maxActiveRequestsPerInstance *
/// instanceCount * minReplications or config_.maxActiveRequests whichever
/// is smaller.
// Find the minimum on device replication.
unsigned minReplications{1};
for (auto &node : nodeList) {
for (auto &dag : node.nodes) {
minReplications = std::min(dag->replicationCount, minReplications);
}
}
unsigned product{0};
if (nodeList.size() && nodeList[0].nodes.size()) {
product = nodeList[0].nodes[0]->instanceCount *
cctx.maxActiveRequestsPerInstance * minReplications;
} else {
return MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_ERROR,
"NodeList is empty.");
}
unsigned maxActiveRequests = config_.maxActiveRequests;
config_.maxActiveRequests = std::min(product, maxActiveRequests);
// Create pool of cachedExecutionStates.
for (auto &node : nodeList) {
// Note: currently getNextNetworkExecutionState assumes that pool size is
// >= currentInFlight requests, so we set pool size to maxActiveRequests.
executor_->createPool(node.root.get(), config_.maxActiveRequests,
cctx.enableP2P, cctx.enableDRT);
}
}
// Clear constants contents from the module then put it in a
// shared_ptr to be shared between all of the networks created from each
// function in the module.
auto targetBackendName = std::string(devices_[0]->getBackendName());
const auto &targetBackend = provisioner_->getBackend(targetBackendName);
if (targetBackend.shouldStripModule() && !cctx.skipModuleStrip) {
module->strip();
}
VLOG(1) << "Cleanup";
auto sharedModule = std::shared_ptr<Module>(std::move(module));
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
for (auto &node : nodeList) {
#if FACEBOOK_INTERNAL
LOG(INFO) << "Successfully compiled and provisioned " << node.root->name;
#endif
auto &networkData = networks_[(node.root)->name];
networkData.dag = std::move(node);
networkData.module = sharedModule;
}
cleanupAddNetwork(names);
}
VLOG(1) << "After cleanup";
return Error::success();
}
#if FACEBOOK_INTERNAL
Error HostManager::addNetworkFX(
std::unique_ptr<Module> module, CompilationContext &cctx,
DAGListTy &networks, const folly::dynamic &FXIR,
const llvm::StringMap<const void *> &constants) {
LOG(INFO) << "Adding Glow network built with revision hash: " << revisionHash;
VLOG(1) << "addNetwork";
std::vector<std::string> names;
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
auto functions = module->getFunctions();
for (auto &F : functions) {
const auto name = F->getName().str();
auto it = networks_.find(name);
if (it != networks_.end() ||
processingNetworks_.find(name) != processingNetworks_.end()) {
cleanupAddNetwork(names);
return MAKE_ERR(
ErrorValue::ErrorCode::RUNTIME_ERROR,
"Failed to add network: already have a function called " + name);
}
// Add the network to processingNetworks_ so we know it's being worked on.
processingNetworks_.insert(name);
names.push_back(name);
}
}
// Issue a warning when loading backend specific options from the command line
// and the compile context also contains backend specific options.
if (!loadBackendSpecificOptionsOpt.empty()) {
if (cctx.backendOpts.backendSpecificOpts.size() != 0) {
VLOG_EVERY_N(1, 1000) << "Warning: backendSpecificOpts is set via the "
"HostManager, ignoring previously set options.";
}
cctx.backendOpts.backendSpecificOpts =
deserializeStrStrMapFromYaml(loadBackendSpecificOptionsOpt);
} else {
auto ctxLoadBackendSpecificOpt =
cctx.backendOpts.backendSpecificOpts.find("loadBackendSpecificOptions");
if (ctxLoadBackendSpecificOpt !=
cctx.backendOpts.backendSpecificOpts.end()) {
cctx.backendOpts.backendSpecificOpts =
deserializeStrStrMapFromYaml(ctxLoadBackendSpecificOpt->second);
}
}
std::vector<DeviceInfo> deviceInfo;
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
for (auto &device : availableDevices_) {
DeviceInfo info = devices_[device]->getDeviceInfo();
info.availableMemory = devices_[device]->getAvailableMemory();
info.backendName = devices_[device]->getBackendName();
info.nonSupportedNodes =
devices_[device]->getParamByName("nonSupportedNodes");
info.supportedNodes = devices_[device]->getParamByName("supportedNodes");
// If p2p is enabled update the inputCount limit.
if (cctx.enableP2P) {
info.inputCountMax = P2PInputLimit;
}
deviceInfo.push_back(info);
}
}
VLOG(1) << "Before provisioning";
auto err =
provisioner_->provisionFX(networks, *module, FXIR, constants, cctx);
if (err) {
if (err.peekErrorValue()->isFatalError()) {
statsExporterRegistry_->setCounter(kDeviceFatalError, 1);
}
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
cleanupAddNetwork(names);
}
RETURN_ERR(err);
}
VLOG(1) << "Calculation of maxActiveRequests";
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
/// Calculate networkMaxActive requests. Then update
/// config_.maxActiveRequests This will be maxActiveRequestsPerInstance *
/// instanceCount * minReplications or config_.maxActiveRequests whichever
/// is smaller.
// Find the minimum on device replication.
unsigned minReplications{1};
for (auto &node : networks) {
for (auto &dag : node.nodes) {
minReplications = std::min(dag->replicationCount, minReplications);
}
}
unsigned product{0};
if (networks.size() && networks[0].nodes.size()) {
product = networks[0].nodes[0]->instanceCount *
cctx.maxActiveRequestsPerInstance * minReplications;
} else {
return MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_ERROR,
"NodeList is empty.");
}
unsigned maxActiveRequests = config_.maxActiveRequests;
config_.maxActiveRequests = std::min(product, maxActiveRequests);
// Create pool of cachedExecutionStates.
for (auto &node : networks) {
// Note: currently getNextNetworkExecutionState assumes that pool size is
// >= currentInFlight requests, so we set pool size to maxActiveRequests.
executor_->createPool(node.root.get(), config_.maxActiveRequests,
cctx.enableP2P, cctx.enableDRT);
}
}
// Clear constants contents from the module then put it in a
// shared_ptr to be shared between all of the networks created from each
// function in the module.
auto targetBackendName = std::string(devices_[0]->getBackendName());
const auto &targetBackend = provisioner_->getBackend(targetBackendName);
if (targetBackend.shouldStripModule() && !cctx.skipModuleStrip) {
module->strip();
}
VLOG(1) << "Cleanup";
auto sharedModule = std::shared_ptr<Module>(std::move(module));
{
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
for (auto &node : networks) {
LOG(INFO) << "Successfully compiled and provisioned " << node.root->name;
auto &networkData = networks_[(node.root)->name];
networkData.dag = std::move(node);
networkData.module = sharedModule;
}
cleanupAddNetwork(names);
}
VLOG(1) << "After cleanup";
return Error::success();
}
#endif
std::unordered_map<std::string, std::vector<DeviceIDTy>>
HostManager::getDevicePartitionMapping(llvm::StringRef network) {
std::unordered_map<std::string, std::vector<DeviceIDTy>> mapping;
auto it = networks_.find(network.str());
if (it != networks_.end()) {
auto &nodeList = it->second.dag.nodes;
for (auto &node : nodeList) {
std::vector<DeviceIDTy> devices;
for (auto &dev : node->deviceRuntimeInfos) {
devices.push_back(dev.first);
}
mapping[node->name] = devices;
}
}
return mapping;
}
Error HostManager::removeNetwork(llvm::StringRef networkName) {
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
auto networkIterator = networks_.find(networkName.str());
if (networkIterator == networks_.end()) {
return Error::success();
}
if (processingNetworks_.find(networkName.str()) !=
processingNetworks_.end()) {
// Return an error, the network is in an incomplete state likely because
// it is still being added by a different call.
return MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_NET_BUSY,
llvm::formatv("Cannot remove the network {0}, as it is "
"currently being modified.",
networkName)
.str());
}
// Issue an error as there are outstanding runs for the network
if (networkIterator->second.refcount != 0) {
return MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_NET_BUSY,
llvm::formatv("Cannot remove the network {0}, as there are "
"still outstanding runs",
networkName)
.str());
}
OneErrOnly err;
auto &nodes = networkIterator->second.dag.nodes;
// Free the pool of executionStates.
executor_->freePool(networkIterator->second.dag.root.get());
for (auto &node : nodes) {
for (auto device : node->deviceRuntimeInfos) {
Error evictErr = provisioner_->evictFunction(
node->name, devices_[device.first].get(), node->replicationCount);
err.set(std::move(evictErr));
}
// Also remove compiledFunction from Provisioner.
err.set(provisioner_->removeFunction(node->name));
}
networks_.erase(networkIterator);
exportMemoryCounters();
RETURN_ERR(err.get());
}
bool HostManager::networkAdded(llvm::StringRef networkName) {
std::shared_lock<std::shared_timed_mutex> networkLock(networkLock_);
return networks_.find(networkName.str()) != networks_.end();
}
Error HostManager::clearHost() {
// shutdown the executor, blocking on any current inflight and prevent new
// requests from being serviced.
executor_->shutdown();
DCHECK_EQ(activeRequestCount_, 0)
<< "All requests should be finished when shutting down HostManager.";
// Remove all networks from the host and device(s).
while (networks_.size() != 0) {
RETURN_IF_ERR(removeNetwork(networks_.begin()->first));
}
// Now it's safe to stop the DeviceManagers.
std::unique_lock<std::shared_timed_mutex> networkLock(networkLock_);
OneErrOnly errContainer;
for (auto &it : devices_) {
errContainer.set(it.second->stop());
}
// Zero out counters.
statsExporterRegistry_->setCounter(kDeviceMemoryUsed, 0);
statsExporterRegistry_->setCounter(kDeviceMemoryAvailable, 0);
statsExporterRegistry_->setCounter(kDeviceMemoryMax, 0);
RETURN_ERR(errContainer.get());
}
Error HostManager::runNetworkBlocking(llvm::StringRef networkName,
PlaceholderBindings &bindings) {
std::unique_ptr<PlaceholderBindings> phBindings(&bindings);
std::unique_ptr<ExecutionContext> context =
glow::make_unique<ExecutionContext>(std::move(phBindings));
std::promise<void> runPromise;
auto fut = runPromise.get_future();
std::unique_ptr<Error> runErr;
runNetwork(
networkName, std::move(context),
[&runPromise, &runErr](runtime::RunIdentifierTy, Error err,
std::unique_ptr<ExecutionContext> contextPtr) {
// Don't delete ph bindings since they were created from a passed in
// reference.
std::unique_ptr<PlaceholderBindings> phBind =
contextPtr->movePlaceholderBindings();
phBind.release();
runErr = glow::make_unique<Error>(std::move(err));
runPromise.set_value();
});
fut.wait();
return std::move(*DCHECK_NOTNULL(runErr.get()));
}
Error HostManager::runNetworkBlocking(
llvm::StringRef networkName, std::unique_ptr<ExecutionContext> &context) {
std::promise<void> runPromise;
auto fut = runPromise.get_future();
Error runErr = Error::empty();
std::unique_ptr<ExecutionContext> tempContext;
runNetwork(networkName, std::move(context),
[&runPromise, &runErr,
&tempContext](runtime::RunIdentifierTy, Error err,
std::unique_ptr<ExecutionContext> resultCtxt) {
runErr = std::move(err);
tempContext = std::move(resultCtxt);
runPromise.set_value();
});
fut.wait();
context = std::move(tempContext);
return runErr;
}
void HostManager::dispatchNextRun() {
int requestId = -1;
llvm::Optional<InferRequest> pRequest;
std::shared_lock<std::shared_timed_mutex> networkLock(networkLock_);
{
// hmm this lock is hot but I still have it as a unique lock because
// we always need to pop inferQueue and inferQueue is not thread safe
std::unique_lock<std::shared_timed_mutex> queueLock(inferQueueLock_);
if (inferQueue_.size()) {
// Get the next request, unfortunately priority_queue only
// provides a const ref to the top element, since we need to move
// it we first cast it to remove the const.
pRequest = std::move(const_cast<InferRequest &>(inferQueue_.top()));
requestId = static_cast<int>(pRequest->requestID);
inferQueue_.pop();
} else {
// Decrement the activeRequest counter so new requests can
// launched.
--activeRequestCount_;
return;
}
}
assert(pRequest.hasValue());
InferRequest request = std::move(pRequest.getValue());
auto startTime = TraceEvent::now();
auto requestReceived = request.startTime;
executor_->run(
networks_[request.networkName].dag.root.get(), std::move(request.context),
request.requestID,
[this, callback = request.callback, name = request.networkName, startTime,
requestReceived](RunIdentifierTy runID, Error err,
std::unique_ptr<ExecutionContext> context) mutable {
{
std::shared_lock<std::shared_timed_mutex> netLock(networkLock_);
auto it = networks_.find(name);
if (it != networks_.end()) {
it->second.refcount--;
}
}
updateExecutionStats(startTime, context, name, err);
// Update request runtime.
auto requestData = ::glow::runtime::RequestData::get();
if (requestData) {
uint64_t end = TraceEvent::now();
requestData->startTime = requestReceived;
requestData->stopTime = end;
}
callback(runID, std::move(err), std::move(context));
dispatchNextRun();
});
}
RunIdentifierTy
HostManager::runNetwork(llvm::StringRef networkName,
std::unique_ptr<ExecutionContext> context,
ResultCBTy callback, uint64_t priority) {
DCHECK(callback != nullptr);
TRACE_EVENT_SCOPE_NAMED(context->getTraceContext(), TraceLevel::RUNTIME,
"HostManager::runNetwork", traceBlock);
auto currentRun = totalRequestCount_++;
traceBlock.addArg("glowRequestId", llvm::formatv("{0}", currentRun).str());
uint64_t requestReceived = TraceEvent::now();
size_t queueSize = 0;
NetworkData *network = nullptr;
{
std::shared_lock<std::shared_timed_mutex> networkLock(networkLock_);
auto it = networks_.find(networkName.str());
if (it != networks_.end()) {
network = &it->second;
network->refcount++;
}
if (network == nullptr) {
TRACE_EVENT_SCOPE_END_NAMED(traceBlock);
callback(
currentRun,
MAKE_ERR(ErrorValue::ErrorCode::RUNTIME_NET_NOT_FOUND,
llvm::formatv("Function {0} not found", networkName).str()),
std::move(context));
return currentRun;
}
// Put the request in the queue.
{
std::shared_lock<std::shared_timed_mutex> lock(inferQueueLock_);
queueSize = inferQueue_.size();
if (queueSize >= config_.maxQueueSize) {
// The queue is full, return an error.
network->refcount--;
TRACE_EVENT_SCOPE_END_NAMED(traceBlock);
callback(
currentRun,
MAKE_ERR(
ErrorValue::ErrorCode::RUNTIME_REQUEST_REFUSED,
strFormat(
"The number of allowed queued requests has been exceeded. "
"queued requests: %lu allowed requests: %zu",
queueSize, config_.maxQueueSize)),
std::move(context));
return currentRun;
}
}
reportCurrentQueueSize(queueSize);
// Setup the request
InferRequest queuedRequest(networkName.str(), std::move(context), callback,
priority, currentRun, requestReceived);
{
std::unique_lock<std::shared_timed_mutex> lock(inferQueueLock_);
TRACE_EVENT_SCOPE_END_NAMED(traceBlock);
inferQueue_.push(std::move(queuedRequest));
}
}
// If we haven't reached maxActiveRequests kick off next request.
size_t activeRequestCount = activeRequestCount_++;
if (activeRequestCount < config_.maxActiveRequests) {
dispatchNextRun();
return currentRun;
}
activeRequestCount_--;
return currentRun;
}
/// Helper to report current queue size
void HostManager::reportCurrentQueueSize(int32_t queueSize) {
statsExporterRegistry_->setCounter(
kCurrentQueueSize10k, static_cast<float>(queueSize) /
static_cast<float>(config_.maxQueueSize) *
100000);
}
/// Helper to update execution stats
void HostManager::updateExecutionStats(
uint64_t startTime, std::unique_ptr<ExecutionContext> &context,
llvm::StringRef networkName, const Error &error) {
auto duration = TraceEvent::now() - startTime;
auto updateCountersFn = [&](llvm::StringRef s) {
statsExporterRegistry_->addTimeSeriesValue(
("glow.execution_duration_e2e." + s).str(), duration);
statsExporterRegistry_->incrementCounter(
("glow.requests_processed." + s).str());
if (error.peekErrorValue()) {
statsExporterRegistry_->incrementCounter(
("glow.requests_failed." + s).str());
} else {
statsExporterRegistry_->incrementCounter(
("glow.requests_succeeded." + s).str());
}
};
updateCountersFn(networkName);
updateCountersFn("global");
}
/// Helper to get the parameters in DeviceConfig from \p str. The \p str has
/// multiple lines, and each line with this format : "str1" : "str2".
static llvm::StringMap<std::string> getBackendParams(std::string &str) {
llvm::StringMap<std::string> ret{};
std::string s;
std::istringstream f(str.c_str());
while (getline(f, s, '\n')) {
// Abstract the mapping from each line's string:
// ""str1" : "str2"" => ret["str1"] = "str2";
size_t pos1, pos2, pos3, pos4;
pos1 = s.find('"');
assert(pos1 != std::string::npos && "invalid string format");
pos2 = s.find('"', pos1 + 1);
assert(pos2 != std::string::npos && "invalid string format");
pos3 = s.find('"', pos2 + 1);
assert(pos3 != std::string::npos && "invalid string format");
pos4 = s.find('"', pos3 + 1);
assert(pos4 != std::string::npos && "invalid string format");
ret[s.substr(pos1 + 1, pos2 - pos1 - 1)] =
s.substr(pos3 + 1, pos4 - pos3 - 1);
}
return ret;
}
/// If the device config file \p loadDeviceDoncfigsFile available, load \p
/// configs from the file. Otherwise, create \p numDevices number of devices
/// based on \p backendName.
std::vector<std::unique_ptr<runtime::DeviceConfig>>
runtime::generateDeviceConfigs(unsigned int numDevices,
llvm::StringRef backendName, size_t memSize) {
std::vector<std::unique_ptr<runtime::DeviceConfig>> configs;
if (!loadDeviceConfigsFromFile(configs, memSize)) {
// If there is no device config file, use numDevices to generate the
// configs.
std::vector<unsigned> available_device_ids;
if (glow::flags::ScanDevices) {
const auto &factories =
FactoryRegistry<std::string, Backend>::factories();
auto it = factories.find(backendName.str());
if (it != factories.end()) {
available_device_ids = it->second->scanDeviceIDs();
}
CHECK_GE(available_device_ids.size(), 0) << "No devices found.";
CHECK_GE(available_device_ids.size(), numDevices)
<< "Not enough devices found.";
}
for (unsigned int i = 0; i < numDevices; ++i) {
auto config = glow::make_unique<runtime::DeviceConfig>(backendName);
config->setDeviceMemory(memSize);
if (glow::flags::ScanDevices) {
config->deviceID = available_device_ids.back();
available_device_ids.pop_back();
} else {
config->deviceID = i;
}
configs.push_back(std::move(config));
}
}
return configs;
}
bool runtime::loadDeviceConfigsFromFile(
std::vector<std::unique_ptr<runtime::DeviceConfig>> &configs,
size_t memSize) {
if (loadDeviceConfigsFileOpt.empty()) {
return false;
}
std::vector<DeviceConfigHelper> lists;
lists = deserializeDeviceConfigFromYaml(loadDeviceConfigsFileOpt);
for (unsigned int i = 0; i < lists.size(); ++i) {
std::string configBackendName = lists[i].backendName_;
std::string name = lists[i].name_;
auto parameters = getBackendParams(lists[i].parameters_.str);
auto config = glow::make_unique<runtime::DeviceConfig>(configBackendName,
name, parameters);
config->deviceID = i;
config->setDeviceMemory(memSize);
configs.push_back(std::move(config));
}
return true;
}
Backend &HostManager::getBackend(llvm::StringRef backendName) const {
return provisioner_->getBackend(backendName);
}
Expected<Backend *> HostManager::getBackend() const {
return provisioner_->getBackend();
}
std::unique_ptr<
std::unordered_map<std::string, std::unique_ptr<BlockStreamBase>>>
HostManager::getAllSerializedFunctions() {
return provisioner_->getAllSerializedFunctionsMap();
}
HostManager *HostManagerRegistry::getHostManager() { return hostManager_; }
void HostManagerRegistry::registerHostManager(HostManager *hostManager) {
hostManager_ = hostManager;
}
std::shared_ptr<HostManagerRegistry> glow::runtime::ManagerRegistry() {
static auto hostManager = std::make_shared<HostManagerRegistry>();
return hostManager;
}
|
// Test host codegen.
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// Test target codegen - host bc file has to be created first.
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// SIMD-ONLY1-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
// CHECK-DAG: [[TT:%.+]] = type { i64, i8 }
// CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 }
// CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* }
// CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* }
// TCHECK: [[ENTTY:%.+]] = type { i8*, i8*, i{{32|64}}, i32, i32 }
// CHECK-DAG: $[[REGFN:\.omp_offloading\..+]] = comdat
// CHECK-DAG: [[SIZET:@.+]] = private unnamed_addr constant [2 x i64] [i64 0, i64 4]
// CHECK-DAG: [[MAPT:@.+]] = private unnamed_addr constant [2 x i64] [i64 544, i64 800]
// CHECK-DAG: @{{.*}} = weak constant i8 0
// TCHECK: @{{.+}} = weak constant [[ENTTY]]
// TCHECK: @{{.+}} = {{.*}}constant [[ENTTY]]
// TCHECK-NOT: @{{.+}} = weak constant [[ENTTY]]
// Check if offloading descriptor is created.
// CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]]
// CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]]
// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8
// CHECK: [[DEVEND:@.+]] = extern_weak constant i8
// CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]])
// CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]])
// Check target registration is registered as a Ctor.
// CHECK: appending global [2 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* @.omp_offloading.requires_reg, i8* null }, { i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
template<typename tx, typename ty>
struct TT{
tx X;
ty Y;
};
int global;
extern int global;
// CHECK: define {{.*}}[[FOO:@.+]](
int foo(int n) {
int a = 0;
short aa = 0;
float b[10];
float bn[n];
double c[5][10];
double cn[5][n];
TT<long long, char> d;
static long *plocal;
// CHECK: [[ADD:%.+]] = add nsw i32
// CHECK: store i32 [[ADD]], i32* [[DEVICE_CAP:%.+]],
// CHECK: [[GEP:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i32 0, i32 0
// CHECK: [[DEV:%.+]] = load i32, i32* [[DEVICE_CAP]],
// CHECK: store i32 [[DEV]], i32* [[GEP]],
// CHECK: [[TASK:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* [[ID:@.+]], i32 [[GTID:%.+]], i32 1, i[[SZ]] {{20|40}}, i[[SZ]] 4, i32 (i32, i8*)* bitcast (i32 (i32, %{{.+}}*)* [[TASK_ENTRY0:@.+]] to i32 (i32, i8*)*))
// CHECK: [[BC_TASK:%.+]] = bitcast i8* [[TASK]] to [[TASK_TY0:%.+]]*
// CHECK: getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 1
// CHECK: getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 2
// CHECK: getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 3
// CHECK: [[DEP_START:%.+]] = getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: [[DEP:%.+]] = bitcast %struct.kmp_depend_info* [[DEP_START]] to i8*
// CHECK: call void @__kmpc_omp_wait_deps(%struct.ident_t* [[ID]], i32 [[GTID]], i32 4, i8* [[DEP]], i32 0, i8* null)
// CHECK: call void @__kmpc_omp_task_begin_if0(%struct.ident_t* [[ID]], i32 [[GTID]], i8* [[TASK]])
// CHECK: call i32 [[TASK_ENTRY0]](i32 [[GTID]], [[TASK_TY0]]* [[BC_TASK]])
// CHECK: call void @__kmpc_omp_task_complete_if0(%struct.ident_t* [[ID]], i32 [[GTID]], i8* [[TASK]])
#pragma omp target teams distribute device(global + a) depend(in: global) depend(out: a, b, cn[4])
for (int i = 0; i < 10; ++i) {
}
// CHECK: [[ADD:%.+]] = add nsw i32
// CHECK: store i32 [[ADD]], i32* [[DEVICE_CAP:%.+]],
// CHECK: [[BOOL:%.+]] = icmp ne i32 %{{.+}}, 0
// CHECK: br i1 [[BOOL]], label %[[THEN:.+]], label %[[ELSE:.+]]
// CHECK: [[THEN]]:
// CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP:%.+]], i32 0, i32 0
// CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P:%.+]], i32 0, i32 0
// CHECK-DAG: [[CBPADDR0:%.+]] = bitcast i8** [[BPADDR0]] to i[[SZ]]**
// CHECK-DAG: [[CPADDR0:%.+]] = bitcast i8** [[PADDR0]] to i[[SZ]]**
// CHECK-DAG: store i[[SZ]]* [[BP0:%[^,]+]], i[[SZ]]** [[CBPADDR0]]
// CHECK-DAG: store i[[SZ]]* [[BP0]], i[[SZ]]** [[CPADDR0]]
// CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 1
// CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 1
// CHECK-DAG: [[CBPADDR1:%.+]] = bitcast i8** [[BPADDR1]] to i[[SZ]]*
// CHECK-DAG: [[CPADDR1:%.+]] = bitcast i8** [[PADDR1]] to i[[SZ]]*
// CHECK-DAG: store i[[SZ]] [[BP1:%[^,]+]], i[[SZ]]* [[CBPADDR1]]
// CHECK-DAG: store i[[SZ]] [[BP1]], i[[SZ]]* [[CPADDR1]]
// CHECK-DAG: getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 0
// CHECK-DAG: getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 0
// CHECK: [[GEP:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i32 0, i32 2
// CHECK: [[DEV:%.+]] = load i32, i32* [[DEVICE_CAP]],
// CHECK: store i32 [[DEV]], i32* [[GEP]],
// CHECK: [[DEV1:%.+]] = load i32, i32* [[DEVICE_CAP]],
// CHECK: [[DEV2:%.+]] = sext i32 [[DEV1]] to i64
// CHECK: [[TASK:%.+]] = call i8* @__kmpc_omp_target_task_alloc(%struct.ident_t* [[ID]], i32 [[GTID]], i32 1, i[[SZ]] {{104|60}}, i[[SZ]] {{16|12}}, i32 (i32, i8*)* bitcast (i32 (i32, %{{.+}}*)* [[TASK_ENTRY1_:@.+]] to i32 (i32, i8*)*), i64 [[DEV2]])
// CHECK: [[BC_TASK:%.+]] = bitcast i8* [[TASK]] to [[TASK_TY1_:%.+]]*
// CHECK: getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 1
// CHECK: getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 2
// CHECK: [[DEP_START:%.+]] = getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: [[DEP:%.+]] = bitcast %struct.kmp_depend_info* [[DEP_START]] to i8*
// CHECK: call i32 @__kmpc_omp_task_with_deps(%struct.ident_t* [[ID]], i32 [[GTID]], i8* [[TASK]], i32 3, i8* [[DEP]], i32 0, i8* null)
// CHECK: br label %[[EXIT:.+]]
// CHECK: [[ELSE]]:
// CHECK-NOT: getelementptr inbounds [2 x i8*], [2 x i8*]*
// CHECK: [[GEP:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i32 0, i32 2
// CHECK: [[DEV:%.+]] = load i32, i32* [[DEVICE_CAP]],
// CHECK: store i32 [[DEV]], i32* [[GEP]],
// CHECK: [[DEV1:%.+]] = load i32, i32* [[DEVICE_CAP]],
// CHECK: [[DEV2:%.+]] = sext i32 [[DEV1]] to i64
// CHECK: [[TASK:%.+]] = call i8* @__kmpc_omp_target_task_alloc(%struct.ident_t* [[ID]], i32 [[GTID]], i32 1, i[[SZ]] {{56|28}}, i[[SZ]] {{16|12}}, i32 (i32, i8*)* bitcast (i32 (i32, %{{.+}}*)* [[TASK_ENTRY1__:@.+]] to i32 (i32, i8*)*), i64 [[DEV2]])
// CHECK: [[BC_TASK:%.+]] = bitcast i8* [[TASK]] to [[TASK_TY1__:%.+]]*
// CHECK: getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 1
// CHECK: getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 2
// CHECK: [[DEP_START:%.+]] = getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: [[DEP:%.+]] = bitcast %struct.kmp_depend_info* [[DEP_START]] to i8*
// CHECK: call i32 @__kmpc_omp_task_with_deps(%struct.ident_t* [[ID]], i32 [[GTID]], i8* [[TASK]], i32 3, i8* [[DEP]], i32 0, i8* null)
// CHECK: br label %[[EXIT:.+]]
// CHECK: [[EXIT]]:
#pragma omp target teams distribute device(global + a) nowait depend(inout: global, a, bn) if(a)
for (int i = 0; i < *plocal; ++i) {
static int local1;
*plocal = global;
local1 = global;
}
// CHECK: [[TASK:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* [[ID]], i32 [[GTID]], i32 1, i[[SZ]] {{48|24}}, i[[SZ]] 4, i32 (i32, i8*)* bitcast (i32 (i32, %{{.+}}*)* [[TASK_ENTRY2:@.+]] to i32 (i32, i8*)*))
// CHECK: [[BC_TASK:%.+]] = bitcast i8* [[TASK]] to [[TASK_TY2:%.+]]*
// CHECK: getelementptr inbounds [1 x %struct.kmp_depend_info], [1 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: [[DEP_START:%.+]] = getelementptr inbounds [1 x %struct.kmp_depend_info], [1 x %struct.kmp_depend_info]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: [[DEP:%.+]] = bitcast %struct.kmp_depend_info* [[DEP_START]] to i8*
// CHECK: call void @__kmpc_omp_wait_deps(%struct.ident_t* [[ID]], i32 [[GTID]], i32 1, i8* [[DEP]], i32 0, i8* null)
// CHECK: call void @__kmpc_omp_task_begin_if0(%struct.ident_t* [[ID]], i32 [[GTID]], i8* [[TASK]])
// CHECK: call i32 [[TASK_ENTRY2]](i32 [[GTID]], [[TASK_TY2]]* [[BC_TASK]])
// CHECK: call void @__kmpc_omp_task_complete_if0(%struct.ident_t* [[ID]], i32 [[GTID]], i8* [[TASK]])
#pragma omp target teams distribute if(0) firstprivate(global) depend(out:global)
for (int i = 0; i < global; ++i) {
global += 1;
}
return a;
}
// Check that the offloading functions are emitted and that the arguments are
// correct and loaded correctly for the target regions in foo().
// CHECK: define internal void [[HVT0:@.+]]()
// CHECK: define internal{{.*}} i32 [[TASK_ENTRY0]](i32{{.*}}, [[TASK_TY0]]* noalias)
// CHECK: store void (i8*, ...)* null, void (i8*, ...)** %
// CHECK: [[DEVICE_CAP:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i32 0, i32 0
// CHECK: [[DEV:%.+]] = load i32, i32* [[DEVICE_CAP]],
// CHECK: [[DEVICE:%.+]] = sext i32 [[DEV]] to i64
// CHECK: [[RET:%.+]] = call i32 @__tgt_target_teams(i64 [[DEVICE]], i8* @{{[^,]+}}, i32 0, i8** null, i8** null, i64* null, i64* null, i32 0, i32 0)
// CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET]], 0
// CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]]
// CHECK: [[FAIL]]
// CHECK: call void [[HVT0]]()
// CHECK-NEXT: br label %[[END]]
// CHECK: [[END]]
// CHECK: ret i32 0
// CHECK: define internal void [[HVT1:@.+]](i[[SZ]]* %{{.+}}, i[[SZ]] %{{.+}})
// CHECK: define internal{{.*}} i32 [[TASK_ENTRY1_]](i32{{.*}}, [[TASK_TY1_]]* noalias)
// CHECK: call void (i8*, ...) %
// CHECK: [[SZT:%.+]] = getelementptr inbounds [2 x i64], [2 x i64]* %{{.+}}, i[[SZ]] 0, i[[SZ]] 0
// CHECK: [[DEVICE_CAP:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i32 0, i32 2
// CHECK: [[DEV:%.+]] = load i32, i32* [[DEVICE_CAP]],
// CHECK: [[DEVICE:%.+]] = sext i32 [[DEV]] to i64
// CHECK: [[RET:%.+]] = call i32 @__tgt_target_teams_nowait(i64 [[DEVICE]], i8* @{{[^,]+}}, i32 2, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i64* [[SZT]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* [[MAPT]], i32 0, i32 0), i32 0, i32 0)
// CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET]], 0
// CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]]
// CHECK: [[FAIL]]
// CHECK: [[BP0:%.+]] = load i[[SZ]]*, i[[SZ]]** %
// CHECK: [[BP1_I32:%.+]] = load i32, i32* %
// CHECK-64: [[BP1_CAST:%.+]] = bitcast i[[SZ]]* [[BP1_PTR:%.+]] to i32*
// CHECK-64: store i32 [[BP1_I32]], i32* [[BP1_CAST]],
// CHECK-32: store i32 [[BP1_I32]], i32* [[BP1_PTR:%.+]],
// CHECK: [[BP1:%.+]] = load i[[SZ]], i[[SZ]]* [[BP1_PTR]],
// CHECK: call void [[HVT1]](i[[SZ]]* [[BP0]], i[[SZ]] [[BP1]])
// CHECK-NEXT: br label %[[END]]
// CHECK: [[END]]
// CHECK: ret i32 0
// CHECK: define internal{{.*}} i32 [[TASK_ENTRY1__]](i32{{.*}}, [[TASK_TY1__]]* noalias)
// CHECK: call void (i8*, ...) %
// CHECK: [[DEVICE_CAP:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i32 0, i32 2
// CHECK: [[BP0:%.+]] = load i[[SZ]]*, i[[SZ]]** %
// CHECK: [[BP1_I32:%.+]] = load i32, i32* %
// CHECK-64: [[BP1_CAST:%.+]] = bitcast i[[SZ]]* [[BP1_PTR:%.+]] to i32*
// CHECK-64: store i32 [[BP1_I32]], i32* [[BP1_CAST]],
// CHECK-32: store i32 [[BP1_I32]], i32* [[BP1_PTR:%.+]],
// CHECK: [[BP1:%.+]] = load i[[SZ]], i[[SZ]]* [[BP1_PTR]],
// CHECK: call void [[HVT1]](i[[SZ]]* [[BP0]], i[[SZ]] [[BP1]])
// CHECK: ret i32 0
// CHECK: define internal void [[HVT2:@.+]](i[[SZ]] %{{.+}})
// Create stack storage and store argument in there.
// CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align
// CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align
// CHECK-64: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i32*
// CHECK-64: load i32, i32* [[AA_CADDR]], align
// CHECK-32: load i32, i32* [[AA_ADDR]], align
// CHECK: define internal{{.*}} i32 [[TASK_ENTRY2]](i32{{.*}}, [[TASK_TY2]]* noalias)
// CHECK: call void (i8*, ...) %
// CHECK: [[BP1_I32:%.+]] = load i32, i32* %
// CHECK-64: [[BP1_CAST:%.+]] = bitcast i[[SZ]]* [[BP1_PTR:%.+]] to i32*
// CHECK-64: store i32 [[BP1_I32]], i32* [[BP1_CAST]],
// CHECK-32: store i32 [[BP1_I32]], i32* [[BP1_PTR:%.+]],
// CHECK: [[BP1:%.+]] = load i[[SZ]], i[[SZ]]* [[BP1_PTR]],
// CHECK: call void [[HVT2]](i[[SZ]] [[BP1]])
// CHECK: ret i32 0
#endif
|
/*
* Copyright 2021, Rein Appeldoorn
*
* 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 <stdexcept>
#include "./porcupine_recognizer.h"
#include "./util.h"
namespace picovoice_driver
{
std::ostream& operator<<(std::ostream& os, const PorcupineRecognizerData::Parameters& p)
{
os << "Parameters(keywords_=" << toString(p.keywords_) << ", model_path=" << p.model_path_
<< ", sensitivity=" << p.sensitivity_ << ")";
return os;
}
std::ostream& operator<<(std::ostream& os, const PorcupineRecognizerData::Result& r)
{
os << "Result(is_understood=" << r.is_understood_ << ", keyword=" << r.keyword_name_ << ")";
return os;
}
PorcupineRecognizer::~PorcupineRecognizer()
{
if (porcupine_ != NULL)
{
pv_porcupine_delete(porcupine_);
}
}
void PorcupineRecognizer::configure(const PorcupineRecognizerData::Parameters& parameters)
{
keyword_names_.clear();
keyword_paths_.clear();
keyword_sensitivities_.clear();
for (const auto& kv : parameters.keywords_)
{
keyword_names_.push_back(kv.first);
keyword_paths_.push_back(kv.second.c_str());
keyword_sensitivities_.push_back(static_cast<float>(parameters.sensitivity_));
}
pv_status_t status = pv_porcupine_init(parameters.model_path_.data(), keyword_names_.size(), keyword_paths_.data(),
keyword_sensitivities_.data(), &porcupine_);
if (status != PV_STATUS_SUCCESS)
{
throw std::runtime_error("Failed to initialize picovoice porcupine with parameters " + toString(parameters) + ":" +
std::string(pv_status_to_string(status)));
}
}
PorcupineRecognizerData::Result PorcupineRecognizer::getResult()
{
return result_;
}
Recognizer::RecordSettings PorcupineRecognizer::getRecordSettings()
{
Recognizer::RecordSettings settings;
settings.frame_length_ = pv_porcupine_frame_length();
settings.sample_rate_ = pv_sample_rate();
return settings;
}
void PorcupineRecognizer::recognizeInit()
{
result_ = PorcupineRecognizerData::Result();
}
bool PorcupineRecognizer::recognizeProcess(int16_t* frames)
{
int32_t keyword_index = -1;
pv_status_t status = pv_porcupine_process(porcupine_, frames, &keyword_index);
if (status != PV_STATUS_SUCCESS)
{
throw std::runtime_error("Porcupine process failed: " + std::string(pv_status_to_string(status)));
}
if (keyword_index < 0)
{
return false;
}
if (static_cast<size_t>(keyword_index) >= keyword_names_.size())
{
throw std::runtime_error("Keyword index " + std::to_string(keyword_index) + " out of bound for keywords " +
toString(keyword_names_));
}
result_.is_understood_ = true;
result_.keyword_name_ = keyword_names_.at(keyword_index);
return true;
}
} // namespace picovoice_driver
|
#include "hough.h"
#include <libutils/rasserts.h>
#include <iostream>
cv::Mat buildHough(cv::Mat sobel) {// единственный аргумент - это результат свертки Собелем изначальной картинки
// проверяем что входная картинка - одноканальная и вещественная:
rassert(sobel.type() == CV_32FC1, 237128273918006);
int width = sobel.cols;
int height = sobel.rows;
// решаем какое максимальное значение у параметра theta в нашем пространстве прямых
int max_theta = 360;
// решаем какое максимальное значение у параметра r в нашем пространстве прямых:
int max_r = sqrt(width*width+height*height); // TODO замените это число так как вам кажется правильным (отталкиваясь от разрешения картинки - ее ширины и высоты)
// создаем картинку-аккумулятор, в которой мы будем накапливать суммарные голоса за прямые
// так же известна как пространство Хафа
cv::Mat accumulator(max_r, max_theta, CV_32FC1); // TODO подумайте какого разрешения она должна быть и поправьте ее размер
// TODO не забудьте заполнить эту матрицу-картинку-аккумулятор нулями (очистить)
for (int y0 = 0; y0 < accumulator.rows; ++y0) {
for (int x0 = 0; x0 < accumulator.cols; ++x0) {
accumulator.at<float>(y0,x0) = 0.0f;
}
}
// проходим по всем пикселям нашей картинки (уже свернутой оператором Собеля)
for (int y0 = 0; y0 < height; ++y0) {
// std::cout << y0 << " " << height << std::endl;
for (int x0 = 0; x0 < width; ++x0) {
// смотрим на пиксель с координатами (x0, y0)
float strength = sobel.at<float>(y0,x0);// TODO считайте его "силу градиента" из картинки sobel
// теперь для текущего пикселя надо найти все возможные прямые которые через него проходят
// переберем параметр theta по всему возможному диапазону (в градусах):
for (int theta0 = 0; theta0 < max_theta; ++theta0) {
// TODO рассчитайте на базе информации о том какие координаты у пикселя - (x0, y0) и какой параметр theta0 мы сейчас рассматриваем
// TODO обратите внимание что функции sin/cos принимают углы в радианах, поэтому сначала нужно пересчитать theta0 в радианы (воспользуйтесь константой PI)
const double PI = 3.14159265358979323846264338327950288;
double teta = theta0*PI/180;
float r0 = x0*cos(teta)+y0*sin(teta);
// TODO теперь рассчитайте координаты пикслея в пространстве Хафа (в картинке-аккумуляторе) соответсвующего параметрам theta0, r0
int i = theta0;
int j = r0;
// чтобы проверить не вышли ли мы за пределы картинки-аккумулятора - давайте явно это проверим:
// rassert(i >= 0, 237891731289044);
// rassert(i < accumulator.cols, 237891731289045);
// rassert(j >= 0, 237891731289046);
// rassert(j < accumulator.rows, 237891731289047);
// теперь легко отладить случай выхода за пределы картинки
// TODO просто поставьте точку остановки внутри rassert:
// нажмите Ctrl+Shift+N -> rasserts.cpp
// и поставьте точку остановки на 8 строке: "return line;"
// TODO и добавьте в картинку-аккумулятор наш голос с весом strength (взятый из картинки свернутой Собелем)
if(r0 >= 0){
accumulator.at<float>(j, i) += strength;
}
}
}
}
return accumulator;
}
|
#include <bits/stdc++.h>
#define MAX 5000
using namespace std;
vector<int> G[MAX];
int n, m;
bool V[MAX];
map<string, int> A;
struct Step {
int x, v;
Step() {}
Step(int x, int v) : x(x), v(v) {}
};
queue<Step> Q;
int author(const string& a) {
if (A.find(a) != A.end())
return A[a];
else
return A[a] = A.size()-1;
}
char C[MAX];
void parseAuthors(const string& s) {
vector<int> TA;
int commas = 0, chars=0;
for(int i=0;i<s.size();i++) {
char c = s[i];
if (chars == 0 && c == ' ') continue;
if ((c==',' || c==':') && ++commas == 2) {
TA.push_back(author(string(C, chars)));
chars = commas = 0;
} else {
C[chars++] = c;
}
}
for(int i=0;i<TA.size(); i++) {
for(int j=i+1;j<TA.size(); j++) {
G[TA[i]].push_back(TA[j]);
G[TA[j]].push_back(TA[i]);
}
}
}
int main() {
string s;
int t=0, tt;
cin >> tt;
while(t++ < tt) {
cin >> n >> m;
memset(G, 0, sizeof(G));
A.clear();
getline(cin, s);
while(n--) {
getline(cin, s);
parseAuthors(s);
}
cout << "Scenario " << t << endl;
for(int i=0;i<m;i++) {
bool stop;
memset(V, 0, sizeof(V));
getline(cin, s);
int b = author(s);
Q = queue<Step>();
Q.push(Step(author("Erdos, P."), 0));
bool found = false;
while(!Q.empty()) {
Step it = Q.front(); Q.pop();
if (it.x == b) {
cout << s << " " << it.v << endl;
found = true;
break;
}
V[it.x] = true;
for(int i=0; i<G[it.x].size(); i++)
if (!V[G[it.x][i]]) Q.push(Step(G[it.x][i], it.v+1));
}
if (!found) cout << s << " infinity" << endl;
}
}
return 0;
}
|
#include "wildstar/data/c_archive.h"
#include <cstring>
#include <QByteArray>
#include <QBuffer>
#include <QDataStream>
#include <QStringList>
#include <QDebug>
#include "wildstar/data/exception.h"
namespace wildstar
{
namespace data
{
//----------------------------------------------------------------------
CArchive::CArchive()
{
clear();
}
//----------------------------------------------------------------------
CArchive::~CArchive()
{
}
//----------------------------------------------------------------------
void
CArchive::read( const QString& file_name )
{
clear();
package_.read( file_name );
loadHeader();
checkHeader();
loadFiles();
}
//----------------------------------------------------------------------
void
CArchive::writeBlock( quint32 block, QIODevice& destination )
{
// TODO: to extract large blocks / files forward the io device
// to package and implement writing in smaller chunks there
destination.write( package_.readBlock( block ) );
}
//----------------------------------------------------------------------
void
CArchive::extractFile( const CIndexFileNode& node, QIODevice& destination )
{
if( !files_.contains( node.hash() ) )
{
// throw EFileNotFound
}
const File& file( files_.value( node.hash() ) );
QByteArray data_out( package_.readBlock( file.block_index ) );
if( node.compressedSize() < node.size() )
{
QByteArray data;
QDataStream stream( &data, QIODevice::WriteOnly );
stream << (quint32)node.size();
data.append( data_out );
data_out = qUncompress( data );
}
destination.write( data_out );
}
//----------------------------------------------------------------------
bool
CArchive::contains( const CHash& hash ) const
{
return files_.contains( hash );
}
//----------------------------------------------------------------------
void
CArchive::clear()
{
std::memset( &header_, 0, sizeof( header_ ) );
files_.clear();
}
//----------------------------------------------------------------------
void
CArchive::loadHeader()
{
QDataStream stream( package_.readTypeBlock() );
stream.setByteOrder( QDataStream::LittleEndian );
stream >> header_;
}
//----------------------------------------------------------------------
void
CArchive::loadFiles()
{
QDataStream stream( package_.readBlock( header_.file_descriptions_block_index ) );
stream.setByteOrder( QDataStream::LittleEndian );
for( quint32 i(0); i < header_.file_count; ++i )
{
File file;
stream >> file;
if( files_.contains( file.hash ) )
{
throw EDuplicatedHash();
}
files_.insert( file.hash, file );
}
}
//----------------------------------------------------------------------
void
CArchive::checkHeader() const
{
if( header_.magic != MAGIC )
{
throw EInvalidFileSignature();
}
if( header_.version != VERSION )
{
throw EInvalidFileVersion();
}
}
//----------------------------------------------------------------------
QDataStream&
operator>>( QDataStream& stream, CArchive::Header& header )
{
stream >> header.magic >> header.version
>> header.file_count >> header.file_descriptions_block_index
;
return stream;
}
//----------------------------------------------------------------------
QDataStream&
operator>>( QDataStream& stream, CArchive::File& file )
{
stream >> file.block_index >> file.hash >> file.size;
return stream;
}
//----------------------------------------------------------------------
}
}
|
////////////////////////////////////////////////////////////////////////////
// Module : eatable_item.cpp
// Created : 24.03.2003
// Modified : 29.01.2004
// Author : Yuri Dobronravin
// Description : Eatable item
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "eatable_item.h"
#include "physic_item.h"
#include "Level.h"
#include "entity_alive.h"
#include "EntityCondition.h"
#include "InventoryOwner.h"
CEatableItem::CEatableItem()
{
m_fHealthInfluence = 0;
m_fPowerInfluence = 0;
m_fSatietyInfluence = 0;
m_fRadiationInfluence = 0;
m_fPsyHealthInfluence = 0;
m_iPortionsNum = -1;
m_physic_item = 0;
}
CEatableItem::~CEatableItem()
{
}
DLL_Pure *CEatableItem::_construct ()
{
m_physic_item = smart_cast<CPhysicItem*>(this);
return (inherited::_construct());
}
void CEatableItem::Load(LPCSTR section)
{
inherited::Load(section);
m_fHealthInfluence = pSettings->r_float(section, "eat_health");
m_fPowerInfluence = pSettings->r_float(section, "eat_power");
m_fSatietyInfluence = pSettings->r_float(section, "eat_satiety");
m_fRadiationInfluence = pSettings->r_float(section, "eat_radiation");
m_fWoundsHealPerc = pSettings->r_float(section, "wounds_heal_perc");
clamp (m_fWoundsHealPerc, 0.f, 1.f);
m_fPsyHealthInfluence = READ_IF_EXISTS(pSettings, r_float, section, "eat_psy_health", 0.0f);
m_iStartPortionsNum = pSettings->r_s32 (section, "eat_portions_num");
m_fMaxPowerUpInfluence = READ_IF_EXISTS (pSettings,r_float,section,"eat_max_power",0.0f);
VERIFY (m_iPortionsNum<10000);
}
BOOL CEatableItem::net_Spawn (CSE_Abstract* DC)
{
if (!inherited::net_Spawn(DC)) return FALSE;
m_iPortionsNum = m_iStartPortionsNum;
return TRUE;
};
bool CEatableItem::Useful() const
{
if(!inherited::Useful()) return false;
//проверить не все ли еще съедено
if(Empty()) return false;
return true;
}
void CEatableItem::OnH_B_Independent(bool just_before_destroy)
{
if(!Useful())
{
object().setVisible(FALSE);
object().setEnabled(FALSE);
if (m_physic_item)
m_physic_item->m_ready_to_destroy = true;
}
inherited::OnH_B_Independent(just_before_destroy);
}
void CEatableItem::UseBy (CEntityAlive* entity_alive)
{
CInventoryOwner* IO = smart_cast<CInventoryOwner*>(entity_alive);
R_ASSERT (IO);
R_ASSERT (m_pCurrentInventory==IO->m_inventory);
R_ASSERT (object().H_Parent()->ID()==entity_alive->ID());
entity_alive->conditions().ChangeHealth (m_fHealthInfluence);
entity_alive->conditions().ChangePower (m_fPowerInfluence);
entity_alive->conditions().ChangeSatiety (m_fSatietyInfluence);
entity_alive->conditions().ChangeRadiation (m_fRadiationInfluence);
entity_alive->conditions().ChangeBleeding (m_fWoundsHealPerc);
entity_alive->conditions().ChangePsyHealth (m_fPsyHealthInfluence);
entity_alive->conditions().SetMaxPower( entity_alive->conditions().GetMaxPower()+m_fMaxPowerUpInfluence );
//уменьшить количество порций
if(m_iPortionsNum > 0)
--(m_iPortionsNum);
else
m_iPortionsNum = 0;
}
void CEatableItem::ZeroAllEffects()
{
m_fHealthInfluence = 0.f;
m_fPowerInfluence = 0.f;
m_fSatietyInfluence = 0.f;
m_fRadiationInfluence = 0.f;
m_fMaxPowerUpInfluence = 0.f;
m_fPsyHealthInfluence = 0.f;
m_fWoundsHealPerc = 0.f;
}
void CEatableItem::SetRadiation(float _rad)
{
m_fRadiationInfluence = _rad;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.