text
stringlengths
5
1.04M
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../FrameWorkCode/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.8. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[54]; char stringdata0[1533]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 22), // "on_actionNew_triggered" QT_MOC_LITERAL(2, 34, 0), // "" QT_MOC_LITERAL(3, 35, 23), // "on_actionOpen_triggered" QT_MOC_LITERAL(4, 59, 23), // "on_actionSave_triggered" QT_MOC_LITERAL(5, 83, 26), // "on_actionSave_As_triggered" QT_MOC_LITERAL(6, 110, 30), // "on_actionSpell_Check_triggered" QT_MOC_LITERAL(7, 141, 15), // "mousePressEvent" QT_MOC_LITERAL(8, 157, 12), // "QMouseEvent*" QT_MOC_LITERAL(9, 170, 2), // "ev" QT_MOC_LITERAL(10, 173, 13), // "menuSelection" QT_MOC_LITERAL(11, 187, 8), // "QAction*" QT_MOC_LITERAL(12, 196, 6), // "action" QT_MOC_LITERAL(13, 203, 33), // "on_actionLoad_Next_Page_trigg..." QT_MOC_LITERAL(14, 237, 33), // "on_actionLoad_Prev_Page_trigg..." QT_MOC_LITERAL(15, 271, 31), // "on_actionLoadGDocPage_triggered" QT_MOC_LITERAL(16, 303, 31), // "on_actionToDevanagari_triggered" QT_MOC_LITERAL(17, 335, 27), // "on_actionLoadData_triggered" QT_MOC_LITERAL(18, 363, 27), // "on_actionLoadDict_triggered" QT_MOC_LITERAL(19, 391, 31), // "on_actionLoadOCRWords_triggered" QT_MOC_LITERAL(20, 423, 29), // "on_actionLoadDomain_triggered" QT_MOC_LITERAL(21, 453, 28), // "on_actionLoadSubPS_triggered" QT_MOC_LITERAL(22, 482, 33), // "on_actionLoadConfusions_trigg..." QT_MOC_LITERAL(23, 516, 23), // "on_actionSugg_triggered" QT_MOC_LITERAL(24, 540, 33), // "on_actionCreateBest2OCR_trigg..." QT_MOC_LITERAL(25, 574, 25), // "on_actionToSlp1_triggered" QT_MOC_LITERAL(26, 600, 38), // "on_actionCreateSuggestionLog_..." QT_MOC_LITERAL(27, 639, 53), // "on_actionCreateSuggestionLogN..." QT_MOC_LITERAL(28, 693, 36), // "on_actionErrorDetectionRep_tr..." QT_MOC_LITERAL(29, 730, 47), // "on_actionErrorDetectWithoutAd..." QT_MOC_LITERAL(30, 778, 24), // "on_actionCPair_triggered" QT_MOC_LITERAL(31, 803, 27), // "on_actionToSlp1_2_triggered" QT_MOC_LITERAL(32, 831, 24), // "on_actionToDev_triggered" QT_MOC_LITERAL(33, 856, 29), // "on_actionExtractDev_triggered" QT_MOC_LITERAL(34, 886, 36), // "on_actionPrimarySecOCRPair_tr..." QT_MOC_LITERAL(35, 923, 39), // "on_actionCPairIEROcrVsCorrect..." QT_MOC_LITERAL(36, 963, 30), // "on_actionEditDistRep_triggered" QT_MOC_LITERAL(37, 994, 36), // "on_actionConfusionFreqHist_tr..." QT_MOC_LITERAL(38, 1031, 39), // "on_actionCPairGEROcrVsCorrect..." QT_MOC_LITERAL(39, 1071, 44), // "on_actionFilterOutGT50EditDis..." QT_MOC_LITERAL(40, 1116, 34), // "on_actionPrepareFeatures_trig..." QT_MOC_LITERAL(41, 1151, 40), // "on_actionErrorDetectionRepUni..." QT_MOC_LITERAL(42, 1192, 27), // "on_actionSanskrit_triggered" QT_MOC_LITERAL(43, 1220, 24), // "on_actionHindi_triggered" QT_MOC_LITERAL(44, 1245, 26), // "on_actionEnglish_triggered" QT_MOC_LITERAL(45, 1272, 23), // "on_actionBold_triggered" QT_MOC_LITERAL(46, 1296, 25), // "on_actionUnbold_triggered" QT_MOC_LITERAL(47, 1322, 28), // "on_actionSubscript_triggered" QT_MOC_LITERAL(48, 1351, 30), // "on_actionSuperscript_triggered" QT_MOC_LITERAL(49, 1382, 33), // "on_actionBack_to_Normal_trigg..." QT_MOC_LITERAL(50, 1416, 25), // "on_actionBold_2_triggered" QT_MOC_LITERAL(51, 1442, 30), // "on_actionSuperScript_triggered" QT_MOC_LITERAL(52, 1473, 28), // "on_actionSubScript_triggered" QT_MOC_LITERAL(53, 1502, 30) // "on_actionNormal_Form_triggered" }, "MainWindow\0on_actionNew_triggered\0\0" "on_actionOpen_triggered\0on_actionSave_triggered\0" "on_actionSave_As_triggered\0" "on_actionSpell_Check_triggered\0" "mousePressEvent\0QMouseEvent*\0ev\0" "menuSelection\0QAction*\0action\0" "on_actionLoad_Next_Page_triggered\0" "on_actionLoad_Prev_Page_triggered\0" "on_actionLoadGDocPage_triggered\0" "on_actionToDevanagari_triggered\0" "on_actionLoadData_triggered\0" "on_actionLoadDict_triggered\0" "on_actionLoadOCRWords_triggered\0" "on_actionLoadDomain_triggered\0" "on_actionLoadSubPS_triggered\0" "on_actionLoadConfusions_triggered\0" "on_actionSugg_triggered\0" "on_actionCreateBest2OCR_triggered\0" "on_actionToSlp1_triggered\0" "on_actionCreateSuggestionLog_triggered\0" "on_actionCreateSuggestionLogNearestPriority_triggered\0" "on_actionErrorDetectionRep_triggered\0" "on_actionErrorDetectWithoutAdaptation_triggered\0" "on_actionCPair_triggered\0" "on_actionToSlp1_2_triggered\0" "on_actionToDev_triggered\0" "on_actionExtractDev_triggered\0" "on_actionPrimarySecOCRPair_triggered\0" "on_actionCPairIEROcrVsCorrect_triggered\0" "on_actionEditDistRep_triggered\0" "on_actionConfusionFreqHist_triggered\0" "on_actionCPairGEROcrVsCorrect_triggered\0" "on_actionFilterOutGT50EditDisPairs_triggered\0" "on_actionPrepareFeatures_triggered\0" "on_actionErrorDetectionRepUniq_triggered\0" "on_actionSanskrit_triggered\0" "on_actionHindi_triggered\0" "on_actionEnglish_triggered\0" "on_actionBold_triggered\0" "on_actionUnbold_triggered\0" "on_actionSubscript_triggered\0" "on_actionSuperscript_triggered\0" "on_actionBack_to_Normal_triggered\0" "on_actionBold_2_triggered\0" "on_actionSuperScript_triggered\0" "on_actionSubScript_triggered\0" "on_actionNormal_Form_triggered" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 48, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 254, 2, 0x08 /* Private */, 3, 0, 255, 2, 0x08 /* Private */, 4, 0, 256, 2, 0x08 /* Private */, 5, 0, 257, 2, 0x08 /* Private */, 6, 0, 258, 2, 0x08 /* Private */, 7, 1, 259, 2, 0x08 /* Private */, 10, 1, 262, 2, 0x08 /* Private */, 13, 0, 265, 2, 0x08 /* Private */, 14, 0, 266, 2, 0x08 /* Private */, 15, 0, 267, 2, 0x08 /* Private */, 16, 0, 268, 2, 0x08 /* Private */, 17, 0, 269, 2, 0x08 /* Private */, 18, 0, 270, 2, 0x08 /* Private */, 19, 0, 271, 2, 0x08 /* Private */, 20, 0, 272, 2, 0x08 /* Private */, 21, 0, 273, 2, 0x08 /* Private */, 22, 0, 274, 2, 0x08 /* Private */, 23, 0, 275, 2, 0x08 /* Private */, 24, 0, 276, 2, 0x08 /* Private */, 25, 0, 277, 2, 0x08 /* Private */, 26, 0, 278, 2, 0x08 /* Private */, 27, 0, 279, 2, 0x08 /* Private */, 28, 0, 280, 2, 0x08 /* Private */, 29, 0, 281, 2, 0x08 /* Private */, 30, 0, 282, 2, 0x08 /* Private */, 31, 0, 283, 2, 0x08 /* Private */, 32, 0, 284, 2, 0x08 /* Private */, 33, 0, 285, 2, 0x08 /* Private */, 34, 0, 286, 2, 0x08 /* Private */, 35, 0, 287, 2, 0x08 /* Private */, 36, 0, 288, 2, 0x08 /* Private */, 37, 0, 289, 2, 0x08 /* Private */, 38, 0, 290, 2, 0x08 /* Private */, 39, 0, 291, 2, 0x08 /* Private */, 40, 0, 292, 2, 0x08 /* Private */, 41, 0, 293, 2, 0x08 /* Private */, 42, 0, 294, 2, 0x08 /* Private */, 43, 0, 295, 2, 0x08 /* Private */, 44, 0, 296, 2, 0x08 /* Private */, 45, 0, 297, 2, 0x08 /* Private */, 46, 0, 298, 2, 0x08 /* Private */, 47, 0, 299, 2, 0x08 /* Private */, 48, 0, 300, 2, 0x08 /* Private */, 49, 0, 301, 2, 0x08 /* Private */, 50, 0, 302, 2, 0x08 /* Private */, 51, 0, 303, 2, 0x08 /* Private */, 52, 0, 304, 2, 0x08 /* Private */, 53, 0, 305, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 8, 9, QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_actionNew_triggered(); break; case 1: _t->on_actionOpen_triggered(); break; case 2: _t->on_actionSave_triggered(); break; case 3: _t->on_actionSave_As_triggered(); break; case 4: _t->on_actionSpell_Check_triggered(); break; case 5: _t->mousePressEvent((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 6: _t->menuSelection((*reinterpret_cast< QAction*(*)>(_a[1]))); break; case 7: _t->on_actionLoad_Next_Page_triggered(); break; case 8: _t->on_actionLoad_Prev_Page_triggered(); break; case 9: _t->on_actionLoadGDocPage_triggered(); break; case 10: _t->on_actionToDevanagari_triggered(); break; case 11: _t->on_actionLoadData_triggered(); break; case 12: _t->on_actionLoadDict_triggered(); break; case 13: _t->on_actionLoadOCRWords_triggered(); break; case 14: _t->on_actionLoadDomain_triggered(); break; case 15: _t->on_actionLoadSubPS_triggered(); break; case 16: _t->on_actionLoadConfusions_triggered(); break; case 17: _t->on_actionSugg_triggered(); break; case 18: _t->on_actionCreateBest2OCR_triggered(); break; case 19: _t->on_actionToSlp1_triggered(); break; case 20: _t->on_actionCreateSuggestionLog_triggered(); break; case 21: _t->on_actionCreateSuggestionLogNearestPriority_triggered(); break; case 22: _t->on_actionErrorDetectionRep_triggered(); break; case 23: _t->on_actionErrorDetectWithoutAdaptation_triggered(); break; case 24: _t->on_actionCPair_triggered(); break; case 25: _t->on_actionToSlp1_2_triggered(); break; case 26: _t->on_actionToDev_triggered(); break; case 27: _t->on_actionExtractDev_triggered(); break; case 28: _t->on_actionPrimarySecOCRPair_triggered(); break; case 29: _t->on_actionCPairIEROcrVsCorrect_triggered(); break; case 30: _t->on_actionEditDistRep_triggered(); break; case 31: _t->on_actionConfusionFreqHist_triggered(); break; case 32: _t->on_actionCPairGEROcrVsCorrect_triggered(); break; case 33: _t->on_actionFilterOutGT50EditDisPairs_triggered(); break; case 34: _t->on_actionPrepareFeatures_triggered(); break; case 35: _t->on_actionErrorDetectionRepUniq_triggered(); break; case 36: _t->on_actionSanskrit_triggered(); break; case 37: _t->on_actionHindi_triggered(); break; case 38: _t->on_actionEnglish_triggered(); break; case 39: _t->on_actionBold_triggered(); break; case 40: _t->on_actionUnbold_triggered(); break; case 41: _t->on_actionSuperScript_triggered(); break; case 42: _t->on_actionSubScript_triggered(); break; case 43: _t->on_actionNormal_Form_triggered(); break; default: ; } } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 6: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QAction* >(); break; } break; } } } QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 48) qt_static_metacall(this, _c, _id, _a); _id -= 48; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 48) qt_static_metacall(this, _c, _id, _a); _id -= 48; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
// Copyright 2012 Cloudera 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 "rpc/rpc-trace.h" #include <boost/bind.hpp> #include <boost/scoped_ptr.hpp> #include <boost/foreach.hpp> #include <gutil/strings/substitute.h> #include "common/logging.h" #include "util/debug-util.h" #include "util/time.h" #include "util/webserver.h" using namespace impala; using namespace boost; using namespace rapidjson; using namespace std; using namespace strings; // Singleton class to keep track of all RpcEventHandlers, and to render them to a // web-based summary page. class RpcEventHandlerManager { public: // Adds an event handler to the list of those tracked void RegisterEventHandler(RpcEventHandler* event_handler); // Produces Json for /rpcz with summary information for all Rpc methods. // { "servers": [ // .. list of output from RpcEventHandler::ToJson() // ] } void JsonCallback(const Webserver::ArgumentMap& args, Document* document); // Resets method statistics. Takes two optional arguments: 'server' and 'method'. If // neither are specified, all server statistics are reset. If only the former is // specified, all statistics for that server are reset. If both arguments are present, // resets the statistics for a single method only. Produces no JSON output. void ResetCallback(const Webserver::ArgumentMap& args, Document* document); private: // Protects event_handlers_ mutex lock_; // List of all event handlers in the system - once an event handler is registered, it // should never be deleted. Event handlers are owned by the TProcessor which calls them, // which are themselves owned by a ThriftServer. Since we do not terminate ThriftServers // after they are started, event handlers have a lifetime equivalent to the length of // the process. vector<RpcEventHandler*> event_handlers_; }; // Only instance of RpcEventHandlerManager scoped_ptr<RpcEventHandlerManager> handler_manager; void impala::InitRpcEventTracing(Webserver* webserver) { handler_manager.reset(new RpcEventHandlerManager()); if (webserver != NULL) { Webserver::UrlCallback json = bind<void>( mem_fn(&RpcEventHandlerManager::JsonCallback), handler_manager.get(), _1, _2); webserver->RegisterUrlCallback("/rpcz", "rpcz.tmpl", json); Webserver::UrlCallback reset = bind<void>( mem_fn(&RpcEventHandlerManager::ResetCallback), handler_manager.get(), _1, _2); webserver->RegisterUrlCallback("/rpcz_reset", "", reset, false); } } void RpcEventHandlerManager::RegisterEventHandler(RpcEventHandler* event_handler) { DCHECK(event_handler != NULL); lock_guard<mutex> l(lock_); event_handlers_.push_back(event_handler); } void RpcEventHandlerManager::JsonCallback(const Webserver::ArgumentMap& args, Document* document) { lock_guard<mutex> l(lock_); Value servers(kArrayType); BOOST_FOREACH(RpcEventHandler* handler, event_handlers_) { Value server(kObjectType); handler->ToJson(&server, document); servers.PushBack(server, document->GetAllocator()); } document->AddMember("servers", servers, document->GetAllocator()); } void RpcEventHandlerManager::ResetCallback(const Webserver::ArgumentMap& args, Document* document) { Webserver::ArgumentMap::const_iterator server_it = args.find("server"); bool reset_all_servers = (server_it == args.end()); Webserver::ArgumentMap::const_iterator method_it = args.find("method"); bool reset_all_in_server = (method_it == args.end()); lock_guard<mutex> l(lock_); BOOST_FOREACH(RpcEventHandler* handler, event_handlers_) { if (reset_all_servers || handler->server_name() == server_it->second) { if (reset_all_in_server) { handler->ResetAll(); } else { handler->Reset(method_it->second); } if (!reset_all_servers) return; } } } void RpcEventHandler::Reset(const string& method_name) { lock_guard<mutex> l(method_map_lock_); MethodMap::iterator it = method_map_.find(method_name); if (it == method_map_.end()) return; it->second->time_stats->Reset(); it->second->num_in_flight = 0L; } void RpcEventHandler::ResetAll() { lock_guard<mutex> l(method_map_lock_); BOOST_FOREACH(const MethodMap::value_type& method, method_map_) { method.second->time_stats->Reset(); method.second->num_in_flight = 0L; } } RpcEventHandler::RpcEventHandler(const string& server_name, MetricGroup* metrics) : server_name_(server_name), metrics_(metrics) { if (handler_manager.get() != NULL) handler_manager->RegisterEventHandler(this); } void RpcEventHandler::ToJson(Value* server, Document* document) { lock_guard<mutex> l(method_map_lock_); Value name(server_name_.c_str(), document->GetAllocator()); server->AddMember("name", name, document->GetAllocator()); Value methods(kArrayType); BOOST_FOREACH(const MethodMap::value_type& rpc, method_map_) { Value method(kObjectType); Value method_name(rpc.first.c_str(), document->GetAllocator()); method.AddMember("name", method_name, document->GetAllocator()); const string& human_readable = rpc.second->time_stats->ToHumanReadable(); Value summary(human_readable.c_str(), document->GetAllocator()); method.AddMember("summary", summary, document->GetAllocator()); method.AddMember("in_flight", rpc.second->num_in_flight, document->GetAllocator()); Value server_name(server_name_.c_str(), document->GetAllocator()); method.AddMember("server_name", server_name, document->GetAllocator()); methods.PushBack(method, document->GetAllocator()); } server->AddMember("methods", methods, document->GetAllocator()); } void* RpcEventHandler::getContext(const char* fn_name, void* server_context) { ThriftServer::ConnectionContext* cnxn_ctx = reinterpret_cast<ThriftServer::ConnectionContext*>(server_context); MethodMap::iterator it; { lock_guard<mutex> l(method_map_lock_); it = method_map_.find(fn_name); if (it == method_map_.end()) { MethodDescriptor* descriptor = new MethodDescriptor(); descriptor->name = fn_name; const string& time_metric_name = Substitute("rpc-method.$0.$1.call_duration", server_name_, descriptor->name); descriptor->time_stats = metrics_->RegisterMetric( new StatsMetric<double>(time_metric_name, TUnit::TIME_MS)); it = method_map_.insert(make_pair(descriptor->name, descriptor)).first; } } ++(it->second->num_in_flight); // TODO: Consider pooling these InvocationContext* ctxt_ptr = new InvocationContext(MonotonicMillis(), cnxn_ctx, it->second); VLOG_RPC << "RPC call: " << string(fn_name) << "(from " << ctxt_ptr->cnxn_ctx->network_address << ")"; return reinterpret_cast<void*>(ctxt_ptr); } void RpcEventHandler::postWrite(void* ctx, const char* fn_name, uint32_t bytes) { InvocationContext* rpc_ctx = reinterpret_cast<InvocationContext*>(ctx); int64_t elapsed_time = MonotonicMillis() - rpc_ctx->start_time_ms; const string& call_name = string(fn_name); // TODO: bytes is always 0, how come? VLOG_RPC << "RPC call: " << server_name_ << ":" << call_name << " from " << rpc_ctx->cnxn_ctx->network_address << " took " << PrettyPrinter::Print(elapsed_time * 1000L * 1000L, TUnit::TIME_NS); MethodDescriptor* descriptor = rpc_ctx->method_descriptor; delete rpc_ctx; --descriptor->num_in_flight; descriptor->time_stats->Update(elapsed_time); }
#pragma once #include "Common.hpp" namespace ib { using Offset = intptr_t; // size_t can't be negative class Addr { public: Byte* p; Addr(void* p) : p((Byte*)p) { } Addr(uintptr_t p) : p((Byte*)p) { } template<typename T> operator T*() const { return (T*)p; } // For method chaining. Same as operator T*(). // Non-static data members can't have templates, so it has to be a function. template<typename T> T* ptr() const { return (T*)p; }; explicit operator uintptr_t() const { return (uintptr_t)p; } Addr operator+(Offset offset) const { return p + offset; } Addr operator-(Offset offset) const { return p - offset; } // For method chaining. Same as operator+(). [[nodiscard]] Addr offset(Offset offset) const { return p + offset; } //Equals to offset(sizeof(T) * num). template<typename T> [[nodiscard]] Addr offset(size_t num = 1) const { return p + sizeof(T) * num; } constexpr Addr& operator+=(Offset offset) { p += offset; return *this; } constexpr Addr& operator-=(Offset offset) { p -= offset; return *this; } // Read the pointer at (p + offset). // addr[off] equals to *(Addr*)(addr + off). ([addr + off] in assembly language) Addr operator[](Offset offset) const { return *(void**)(p + offset); } // Function as operator bool, operator<=>, operator delete constexpr operator void* () const { return p; } Offset operator-(Addr addr) const { return p - addr.p; } [[nodiscard]] Addr align_up(size_t alignment) const { --alignment; return ((uintptr_t)p + alignment) & ~alignment; } [[nodiscard]] Addr align_down(size_t alignment) const { --alignment; return (uintptr_t)p & ~alignment; } template<typename T> T read() const { return *(T*)p; } constexpr auto read() const { return read_return_auto{ *this }; } private: struct read_return_auto { const Addr& addr; constexpr read_return_auto(const Addr& addr) : addr(addr) {} template<typename T> operator T() const { return addr.read<T>(); } }; public: template<typename T> void write(T value) const { *(T*)p = value; } // Return (size_t)-1 if fails. size_t heap_size(HANDLE heap = GetProcessHeap()) const { return HeapSize(heap, 0, p); } }; namespace mem { // **It does not equal to Windows's flProtect.** using ProtectFlags = DWORD; class Protect { public: using T = const ProtectFlags; /// <summary> /// Converted to false (others are true). /// Cannot be used with other flags. /// Not supported by CreateFileMapping. /// </summary> static T NoAccess = PAGE_NOACCESS - 1; static T Read = PAGE_READONLY - 1; static T Write = PAGE_READWRITE - 1; // Includes Read static T WriteCopy = PAGE_WRITECOPY - 1; // Includes Read and Write. Not supported by VirtualAlloc(Ex). static T Execute = PAGE_EXECUTE; // Not supported by CreateFileMapping if used without Read, Write or WriteCopy. static T Guard = PAGE_GUARD; // Cannot be used with NoAccess, NoCache or WriteCombine static T NoCache = PAGE_NOCACHE; // Cannot be used with NoAccess, Guard or WriteCombine static T WriteCombine = PAGE_WRITECOMBINE; // Cannot be used with NoAccess, Guard or NoCache static T Targets_Invalid = PAGE_TARGETS_INVALID; // Not supported by VirtualProtect or CreateFileMapping. Equals to Targets_NoUpdate. static T Targets_NoUpdate = PAGE_TARGETS_NO_UPDATE; // Supported by VirtualProtect. Equals to Targets_Invalid. constexpr static DWORD to_flProtect(ProtectFlags protect) { DWORD h = protect & ~0xFF; Byte l = (Byte)protect; ++l; if (l & Execute) { l = l << 4; } return h | l; } constexpr static ProtectFlags to_protect(DWORD flProtect) { DWORD h = flProtect & ~0xFF; Byte l = (Byte)flProtect; --l; if (l & 0x8) { l = l >> 4 | Execute; } return h | l; } }; // Example: change_protect(addr, 5, Protect::Write | Protect::Execute); inline ProtectFlags change_protect(Addr addr, size_t size, ProtectFlags protect) { DWORD flProtect; VirtualProtect(addr, size, Protect::to_flProtect(protect), &flProtect); return Protect::to_protect(flProtect); } // Change protect, call f, and then change protect back. inline bool protect_changed(Addr addr, size_t size, ProtectFlags protect, function<void(Addr)> f) { DWORD flProtect; if (!VirtualProtect(addr, size, Protect::to_flProtect(protect), &flProtect)) return false; f(addr); //lpflOldProtect can't be nullptr return VirtualProtect(addr, size, flProtect, &flProtect); } } }
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/byte_array/byte_array.hpp" #include "core/macros.hpp" #include "core/random/lcg.hpp" #include "ledger/transaction_status_cache_impl.hpp" #include "gmock/gmock.h" #include <memory> namespace { using namespace fetch; using namespace fetch::ledger; using fetch::byte_array::ByteArray; using fetch::random::LinearCongruentialGenerator; using StatusCachePtr = TransactionStatusCache::ShrdPtr; using RngWord = LinearCongruentialGenerator::RandomType; using testing::Return; using testing::HasSubstr; struct ClockSystemClockMock; struct ClockMock : public std::chrono::steady_clock { static std::shared_ptr<ClockSystemClockMock> mock; static time_point now() noexcept; }; std::shared_ptr<ClockSystemClockMock> ClockMock::mock; struct ClockSystemClockMock { MOCK_CONST_METHOD0(now, ClockMock::time_point()); }; ClockMock::time_point ClockMock::now() noexcept { return mock->now(); } using TransactionStatusCacheForTest = TransactionStatusCacheImpl<ClockMock>; using Clock = TransactionStatusCacheForTest::Clock; using Timepoint = TransactionStatusCacheForTest::Timepoint; class TransactionStatusCacheTests : public ::testing::Test { protected: void SetUp() override { clock_mock_ = std::make_shared<ClockSystemClockMock>(); ClockMock::mock = clock_mock_; EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(Timepoint::min())); cache_ = std::make_shared<TransactionStatusCacheForTest>(); } void TearDown() override { ClockMock::mock.reset(); clock_mock_.reset(); cache_.reset(); } Digest GenerateDigest() { static constexpr std::size_t DIGEST_BIT_LENGTH = 256u; static constexpr std::size_t DIGEST_BYTE_LENGTH = DIGEST_BIT_LENGTH / 8u; static constexpr std::size_t RNG_WORD_SIZE = sizeof(RngWord); static constexpr std::size_t NUM_WORDS = DIGEST_BYTE_LENGTH / RNG_WORD_SIZE; static_assert((DIGEST_BYTE_LENGTH % RNG_WORD_SIZE) == 0, ""); ByteArray digest; digest.Resize(DIGEST_BYTE_LENGTH); auto *digest_raw = reinterpret_cast<RngWord *>(digest.pointer()); for (std::size_t i = 0; i < NUM_WORDS; ++i) { *digest_raw++ = rng_(); } return Digest{digest}; } StatusCachePtr cache_{}; LinearCongruentialGenerator rng_{}; std::shared_ptr<ClockSystemClockMock> clock_mock_{}; }; TEST_F(TransactionStatusCacheTests, CheckBasicUpdate) { auto tx1 = GenerateDigest(); auto tx2 = GenerateDigest(); auto tx3 = GenerateDigest(); EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(Timepoint::min())); cache_->Update(tx1, TransactionStatus::SUBMITTED); EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(Timepoint::min())); cache_->Update(tx2, TransactionStatus::PENDING); EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(Timepoint::min())); cache_->Update(tx3, TransactionStatus::MINED); ASSERT_EQ(TransactionStatus::SUBMITTED, cache_->Query(tx1).status); ASSERT_EQ(TransactionStatus::PENDING, cache_->Query(tx2).status); ASSERT_EQ(TransactionStatus::MINED, cache_->Query(tx3).status); EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(Timepoint::min())); cache_->Update(tx1, TransactionStatus::PENDING); EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(Timepoint::min())); cache_->Update(tx2, TransactionStatus::MINED); EXPECT_EQ(TransactionStatus::PENDING, cache_->Query(tx1).status); EXPECT_EQ(TransactionStatus::MINED, cache_->Query(tx2).status); EXPECT_EQ(TransactionStatus::MINED, cache_->Query(tx3).status); } TEST_F(TransactionStatusCacheTests, CheckTxStatusUpdateFailsForExecutedStatus) { auto tx1 = GenerateDigest(); Timepoint start{ClockMock::time_point::min()}; EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(start)); cache_->Update(tx1, TransactionStatus::PENDING); ASSERT_EQ(TransactionStatus::PENDING, cache_->Query(tx1).status); EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(start)); bool ex_thrown{false}; try { cache_->Update(tx1, TransactionStatus::EXECUTED); } catch (std::runtime_error const &ex) { EXPECT_THAT(ex.what(), HasSubstr("Using inappropriate method to update")); ex_thrown = true; } EXPECT_TRUE(ex_thrown); } TEST_F(TransactionStatusCacheTests, CheckUpdateForContractExecutionResult) { auto tx1 = GenerateDigest(); Timepoint start{ClockMock::time_point::min()}; EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(start)); cache_->Update(tx1, TransactionStatus::PENDING); ASSERT_EQ(TransactionStatus::PENDING, cache_->Query(tx1).status); ContractExecutionResult const expected_result{ ContractExecutionStatus::INEXPLICABLE_FAILURE, 1, 2, 3, 4, -2}; EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(start)); cache_->Update(tx1, expected_result); auto const received_result{cache_->Query(tx1)}; EXPECT_EQ(TransactionStatus::EXECUTED, received_result.status); EXPECT_EQ(expected_result.status, received_result.contract_exec_result.status); EXPECT_EQ(expected_result.return_value, received_result.contract_exec_result.return_value); EXPECT_EQ(expected_result.fee, received_result.contract_exec_result.fee); EXPECT_EQ(expected_result.charge_limit, received_result.contract_exec_result.charge_limit); EXPECT_EQ(expected_result.charge_rate, received_result.contract_exec_result.charge_rate); EXPECT_EQ(expected_result.charge, received_result.contract_exec_result.charge); } TEST_F(TransactionStatusCacheTests, CheckPruning) { auto tx1 = GenerateDigest(); auto tx2 = GenerateDigest(); auto tx3 = GenerateDigest(); Timepoint start{ClockMock::time_point::min()}; EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(start)); cache_->Update(tx1, TransactionStatus::PENDING); EXPECT_CALL(*clock_mock_, now()).WillOnce(Return(start)); cache_->Update(tx2, TransactionStatus::MINED); ASSERT_EQ(TransactionStatus::PENDING, cache_->Query(tx1).status); ASSERT_EQ(TransactionStatus::MINED, cache_->Query(tx2).status); Timepoint const future_time_point = start + std::chrono::hours{25}; EXPECT_CALL(*clock_mock_, now()).WillRepeatedly(Return(future_time_point)); cache_->Update(tx3, TransactionStatus::SUBMITTED); EXPECT_EQ(TransactionStatus::UNKNOWN, cache_->Query(tx1).status); EXPECT_EQ(TransactionStatus::UNKNOWN, cache_->Query(tx2).status); EXPECT_EQ(TransactionStatus::SUBMITTED, cache_->Query(tx3).status); } } // namespace
// 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 "kudu/util/logging.h" #include <unistd.h> #include <cstdint> #include <cstdio> #include <cstdlib> #include <ctime> #include <fstream> #include <functional> #include <initializer_list> #include <mutex> #include <utility> #include <boost/uuid/random_generator.hpp> #include <boost/uuid/uuid_io.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include "kudu/gutil/basictypes.h" #include "kudu/gutil/port.h" #include "kudu/gutil/spinlock.h" #include "kudu/gutil/stringprintf.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/util/async_logger.h" #include "kudu/util/debug-util.h" #include "kudu/util/debug/leakcheck_disabler.h" #include "kudu/util/env_util.h" #include "kudu/util/flag_tags.h" #include "kudu/util/logging_callback.h" #include "kudu/util/minidump.h" #include "kudu/util/signal.h" #include "kudu/util/status.h" // Defined in Impala. DECLARE_string(log_filename); TAG_FLAG(log_filename, stable); DEFINE_bool(log_async, true, "Enable asynchronous writing to log files. This improves " "latency and stability."); TAG_FLAG(log_async, hidden); DEFINE_int32(log_async_buffer_bytes_per_level, 2 * 1024 * 1024, "The number of bytes of buffer space used by each log " "level. Only relevant when --log_async is enabled."); TAG_FLAG(log_async_buffer_bytes_per_level, hidden); // Defined in Impala. DECLARE_int32(max_log_files); TAG_FLAG(max_log_files, runtime); TAG_FLAG(max_log_files, stable); #define PROJ_NAME "kudu" bool logging_initialized = false; using base::SpinLock; using base::SpinLockHolder; using boost::uuids::random_generator; using std::string; using std::ofstream; using std::ostream; using std::ostringstream; namespace kudu { __thread bool tls_redact_user_data = true; kudu::RedactContext g_should_redact; const char* const kRedactionMessage = "<redacted>"; namespace { class SimpleSink : public google::LogSink { public: explicit SimpleSink(LoggingCallback cb) : cb_(std::move(cb)) {} virtual ~SimpleSink() OVERRIDE { } virtual void send(google::LogSeverity severity, const char* full_filename, const char* base_filename, int line, const struct ::tm* tm_time, const char* message, size_t message_len) OVERRIDE { LogSeverity kudu_severity; switch (severity) { case google::INFO: kudu_severity = SEVERITY_INFO; break; case google::WARNING: kudu_severity = SEVERITY_WARNING; break; case google::ERROR: kudu_severity = SEVERITY_ERROR; break; case google::FATAL: kudu_severity = SEVERITY_FATAL; break; default: LOG(FATAL) << "Unknown glog severity: " << severity; } cb_(kudu_severity, full_filename, line, tm_time, message, message_len); } private: LoggingCallback cb_; }; SpinLock logging_mutex(base::LINKER_INITIALIZED); // There can only be a single instance of a SimpleSink. // // Protected by 'logging_mutex'. SimpleSink* registered_sink = nullptr; // Records the logging severity after the first call to // InitGoogleLoggingSafe{Basic}. Calls to UnregisterLoggingCallback() // will restore stderr logging back to this severity level. // // Protected by 'logging_mutex'. int initial_stderr_severity; void EnableAsyncLogging() { debug::ScopedLeakCheckDisabler leaky; // Enable Async for every level except for FATAL. Fatal should be synchronous // to ensure that we get the fatal log message written before exiting. for (auto level : { google::INFO, google::WARNING, google::ERROR }) { auto* orig = google::base::GetLogger(level); auto* async = new AsyncLogger(orig, FLAGS_log_async_buffer_bytes_per_level); async->Start(); google::base::SetLogger(level, async); } } void UnregisterLoggingCallbackUnlocked() { CHECK(logging_mutex.IsHeld()); CHECK(registered_sink); // Restore logging to stderr, then remove our sink. This ordering ensures // that no log messages are missed. google::SetStderrLogging(initial_stderr_severity); google::RemoveLogSink(registered_sink); delete registered_sink; registered_sink = nullptr; } void FlushCoverageOnExit() { // Coverage flushing is not re-entrant, but this might be called from a // crash signal context, so avoid re-entrancy. static __thread bool in_call = false; if (in_call) return; in_call = true; // The failure writer will be called multiple times per exit. // We only need to flush coverage once. We use a 'once' here so that, // if another thread is already flushing, we'll block and wait for them // to finish before allowing this thread to call abort(). static std::once_flag once; std::call_once(once, [] { static const char msg[] = "Flushing coverage data before crash...\n"; ignore_result(write(STDERR_FILENO, msg, arraysize(msg))); TryFlushCoverage(); }); in_call = false; } // On SEGVs, etc, glog will call this function to write the error to stderr. This // implementation is copied from glog with the exception that we also flush coverage // the first time it's called. // // NOTE: this is only used in coverage builds! void FailureWriterWithCoverage(const char* data, int size) { FlushCoverageOnExit(); // Original implementation from glog: if (write(STDERR_FILENO, data, size) < 0) { // Ignore errors. } } // GLog "failure function". This is called in the case of LOG(FATAL) to // ensure that we flush coverage even on crashes. // // NOTE: this is only used in coverage builds! void FlushCoverageAndAbort() { FlushCoverageOnExit(); abort(); } } // anonymous namespace void InitGoogleLoggingSafe(const char* arg) { SpinLockHolder l(&logging_mutex); if (logging_initialized) return; google::InstallFailureSignalHandler(); if (!FLAGS_log_filename.empty()) { for (int severity = google::INFO; severity <= google::FATAL; ++severity) { google::SetLogSymlink(severity, FLAGS_log_filename.c_str()); } } // This forces our logging to default to /tmp rather than looking for a // temporary directory if none is specified. This is done so that we // can reliably construct the log file name without duplicating the // complex logic that glog uses to guess at a temporary dir. CHECK_NE("", google::SetCommandLineOptionWithMode("log_dir", "/tmp", google::FlagSettingMode::SET_FLAGS_DEFAULT)); if (!FLAGS_logtostderr) { // Verify that a log file can be created in log_dir by creating a tmp file. ostringstream ss; random_generator uuid_generator; ss << FLAGS_log_dir << "/" << PROJ_NAME "_test_log." << uuid_generator(); const string file_name = ss.str(); ofstream test_file(file_name.c_str()); if (!test_file.is_open()) { ostringstream error_msg; error_msg << "Could not open file in log_dir " << FLAGS_log_dir; perror(error_msg.str().c_str()); // Unlock the mutex before exiting the program to avoid mutex d'tor assert. logging_mutex.Unlock(); exit(1); } remove(file_name.c_str()); } google::InitGoogleLogging(arg); // In coverage builds, we should flush coverage before exiting on crash. // This way, fault injection tests still capture coverage of the daemon // that "crashed". if (IsCoverageBuild()) { // We have to use both the "failure writer" and the "FailureFunction". // This allows us to handle both LOG(FATAL) and unintended crashes like // SEGVs. google::InstallFailureWriter(FailureWriterWithCoverage); google::InstallFailureFunction(FlushCoverageAndAbort); } // Needs to be done after InitGoogleLogging if (FLAGS_log_filename.empty()) { CHECK_STRNE(google::ProgramInvocationShortName(), "UNKNOWN") << ": must initialize gflags before glog"; FLAGS_log_filename = google::ProgramInvocationShortName(); } // File logging: on. // Stderr logging threshold: FLAGS_stderrthreshold. // Sink logging: off. initial_stderr_severity = FLAGS_stderrthreshold; // Ignore SIGPIPE early in the startup process so that threads writing to TLS // sockets do not crash when writing to a closed socket. See KUDU-1910. IgnoreSigPipe(); // For minidump support. Must be called before logging threads started. // Disabled by Impala, which does not link Kudu's minidump library. //CHECK_OK(BlockSigUSR1()); if (FLAGS_log_async) { EnableAsyncLogging(); } logging_initialized = true; } void InitGoogleLoggingSafeBasic(const char* arg) { SpinLockHolder l(&logging_mutex); if (logging_initialized) return; google::InitGoogleLogging(arg); // This also disables file-based logging. google::LogToStderr(); // File logging: off. // Stderr logging threshold: INFO. // Sink logging: off. initial_stderr_severity = google::INFO; logging_initialized = true; } void RegisterLoggingCallback(const LoggingCallback& cb) { SpinLockHolder l(&logging_mutex); CHECK(logging_initialized); if (registered_sink) { LOG(WARNING) << "Cannot register logging callback: one already registered"; return; } // AddLogSink() claims to take ownership of the sink, but it doesn't // really; it actually expects it to remain valid until // google::ShutdownGoogleLogging() is called. registered_sink = new SimpleSink(cb); google::AddLogSink(registered_sink); // Even when stderr logging is ostensibly off, it's still emitting // ERROR-level stuff. This is the default. google::SetStderrLogging(google::ERROR); // File logging: yes, if InitGoogleLoggingSafe() was called earlier. // Stderr logging threshold: ERROR. // Sink logging: on. } void UnregisterLoggingCallback() { SpinLockHolder l(&logging_mutex); CHECK(logging_initialized); if (!registered_sink) { LOG(WARNING) << "Cannot unregister logging callback: none registered"; return; } UnregisterLoggingCallbackUnlocked(); // File logging: yes, if InitGoogleLoggingSafe() was called earlier. // Stderr logging threshold: initial_stderr_severity. // Sink logging: off. } void GetFullLogFilename(google::LogSeverity severity, string* filename) { ostringstream ss; ss << FLAGS_log_dir << "/" << FLAGS_log_filename << "." << google::GetLogSeverityName(severity); *filename = ss.str(); } std::string FormatTimestampForLog(MicrosecondsInt64 micros_since_epoch) { time_t secs_since_epoch = micros_since_epoch / 1000000; int usecs = micros_since_epoch % 1000000; struct tm tm_time; localtime_r(&secs_since_epoch, &tm_time); return StringPrintf("%02d%02d %02d:%02d:%02d.%06d", 1 + tm_time.tm_mon, tm_time.tm_mday, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, usecs); } void ShutdownLoggingSafe() { SpinLockHolder l(&logging_mutex); if (!logging_initialized) return; if (registered_sink) { UnregisterLoggingCallbackUnlocked(); } google::ShutdownGoogleLogging(); logging_initialized = false; } Status DeleteExcessLogFiles(Env* env) { int32_t max_log_files = FLAGS_max_log_files; // Ignore bad input or disable log rotation. if (max_log_files <= 0) return Status::OK(); for (int severity = 0; severity < google::NUM_SEVERITIES; ++severity) { // Build glob pattern for input // e.g. /var/log/kudu/kudu-master.*.INFO.* string pattern = strings::Substitute("$0/$1.*.$2.*", FLAGS_log_dir, FLAGS_log_filename, google::GetLogSeverityName(severity)); // Keep the 'max_log_files' most recent log files, as compared by // modification time. Glog files contain a second-granularity timestamp in // the name, so this could potentially use the filename sort order as // guaranteed by glob, however this code has been adapted from Impala which // uses mtime to determine which files to delete, and there haven't been any // issues in production settings. RETURN_NOT_OK(env_util::DeleteExcessFilesByPattern(env, pattern, max_log_files)); } return Status::OK(); } // Support for the special THROTTLE_MSG token in a log message stream. ostream& operator<<(ostream &os, const PRIVATE_ThrottleMsg& /*unused*/) { using google::LogMessage; #ifdef DISABLE_RTTI LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os); #else LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os); #endif CHECK(log && log == log->self()) << "You must not use COUNTER with non-glog ostream"; int ctr = log->ctr(); if (ctr > 0) { os << " [suppressed " << ctr << " similar messages]"; } return os; } } // namespace kudu
/* * Part of WCM Commander * https://github.com/corporateshark/WCMCommander * wcm@linderdaum.com */ #include <algorithm> #include <wal.h> #include "wcm-config.h" #include "color-style.h" #include "string-util.h" #include "vfs.h" #include "fontdlg.h" #include "ncfonts.h" #include "ncwin.h" #include "ltext.h" #include "globals.h" #include "folder-history.h" #include "view-history.h" #include "nchistory.h" #ifdef _WIN32 # include "w32util.h" #endif #define __STDC_FORMAT_MACROS #include <stdint.h> #if !defined(_MSC_VER) || _MSC_VER >= 1700 # include <inttypes.h> #endif #include <map> std::string* IniHash::Find( const char* section, const char* var ) { cstrhash< std::string >* h = hash.exist( section ); if ( !h ) { return 0; } return h->exist( var ); } std::string* IniHash::Create( const char* section, const char* var ) { return &(hash[section][var]); } void IniHash::Delete( const char* section, const char* var ) { hash[section].del( var, false ); } void IniHash::SetStrValue( const char* section, const char* var, const char* value ) { if ( !value ) { Delete( section, var ); return; } std::string* p = Create( section, var ); if ( p ) { *p = value; } } void IniHash::SetIntValue( const char* section, const char* var, int value ) { SetStrValue( section, var, ToString(value).c_str() ); } void IniHash::SetBoolValue( const char* section, const char* var, bool value ) { SetIntValue( section, var, value ? 1 : 0 ); } const char* IniHash::GetStrValue( const char* section, const char* var, const char* def ) { std::string* p = Find( section, var ); return (p && p->data()) ? p->data() : def; } int IniHash::GetIntValue( const char* section, const char* var, int def ) { std::string* p = Find( section, var ); return (p && p->data()) ? atoi( p->data() ) : def; } bool IniHash::GetBoolValue( const char* section, const char* var, bool def ) { const int n = GetIntValue( section, var, def ? 1 : 0 ); return n ? true : false; } #ifndef _WIN32 #define DEFAULT_CONFIG_PATH UNIX_CONFIG_DIR_PATH "/config.default" class TextInStream { private: int bufSize; std::vector<char> buffer; int pos; int count; bool FillBuffer() { if ( pos < count ) { return true; } if ( count <= 0 ) { return false; } count = Read( buffer.data(), bufSize ); pos = 0; return count > 0; } public: TextInStream( int _bSize = 1024 ) : bufSize( _bSize > 0 ? _bSize : 1024 ) , pos( 1 ) , count( 1 ) { buffer.resize( bufSize ); } ~TextInStream() {} int GetC() { FillBuffer(); return pos < count ? buffer[pos++] : EOF; } bool GetLine( char* s, int size ); protected: virtual int Read( char* buf, int size ) = 0; //can throw }; bool TextInStream::GetLine( char* s, int size ) { if ( size <= 0 ) { return true; } if ( !FillBuffer() ) { return false; } if ( size == 1 ) { *s = 0; return true; } size--; while ( true ) { if ( pos >= count && !FillBuffer() ) { break; } char* b = buffer.data() + pos; char* e = buffer.data() + count; for ( ; b < e; b++ ) if ( *b == '\n' ) { break; } if ( size > 0 ) { int n = b - ( buffer.data() + pos ); if ( n > size ) { n = size; } memcpy( s, buffer.data() + pos, n ); size -= n; s += n; } pos = b - buffer.data(); if ( b < e ) { pos++; break; } } *s = 0; return true; } class TextOutStream { private: int bufSize; std::vector<char> buffer; int pos; public: TextOutStream( int _bSize = 1024 ): bufSize( _bSize > 0 ? _bSize : 1024 ), pos( 0 ) { buffer.resize( bufSize ); } void Flush() { if ( pos > 0 ) { Write( buffer.data(), pos ); pos = 0; } } void PutC( int c ) { if ( pos >= bufSize ) { Flush(); } buffer[pos++] = c; } void Put( const char* s, int size ); void Put( const char* s ) { Put( s, strlen( s ) ); } ~TextOutStream() {} protected: virtual void Write( char* buf, int size ) = 0; //can throw void Clear() { pos = 0; } }; void TextOutStream::Put( const char* s, int size ) { while ( size > 0 ) { if ( pos >= bufSize ) { Flush(); } int n = bufSize - pos; if ( n > size ) { n = size; } memcpy( buffer.data() + pos, s, n ); pos += n; size -= n; s += n; } } class SysTextFileIn: public TextInStream { File f; public: SysTextFileIn( int bSize = 4096 ): TextInStream( bSize ) {} void Open( const sys_char_t* fileName ) { f.Open( fileName, FOPEN_READ ); } void Close() { f.Close(); } ~SysTextFileIn() {} protected: virtual int Read( char* buf, int size ); }; int SysTextFileIn::Read( char* buf, int size ) { return f.Read( buf, size ); } class SysTextFileOut: public TextOutStream { File f; public: SysTextFileOut( int bSize = 4096 ): TextOutStream( bSize ) {} void Open( const sys_char_t* fileName ) { Clear(); f.Open( fileName, FOPEN_WRITE | FOPEN_CREATE | FOPEN_TRUNC ); } void Close() { f.Close(); } ~SysTextFileOut() {} protected: virtual void Write( char* buf, int size ); }; void SysTextFileOut::Write( char* buf, int size ) { f.Write( buf, size ); } static FSPath configDirPath( CS_UTF8, "???" ); void LoadIniHash( IniHash& iniHash, const sys_char_t* fileName ) { SysTextFileIn in; try { in.Open( fileName ); } catch ( csyserr* ex ) { if ( SysErrorIsFileNotFound( ex->code ) ) { ex->destroy(); return; } throw; } char buf[4096]; std::string section; while ( in.GetLine( buf, sizeof( buf ) ) ) { char* s = buf; while ( IsSpace( *s ) ) { s++; } if ( !*s || *s == '#' ) { continue; } if ( *s == '[' ) { s++; while ( IsSpace( *s ) ) { s++; } char* t = s; while ( *t && *t != ']' ) { t++; } if ( *t != ']' ) { continue; } while ( t > s && IsSpace( *( t - 1 ) ) ) { t--; } *t = 0; section = s; } else { if ( section.empty() ) { continue; } char* t = s; while ( *t && *t != '=' ) { t++; } if ( *t != '=' ) { continue; } char* v = t + 1; while ( t > s && IsSpace( *( t - 1 ) ) ) { t--; } *t = 0; while ( IsSpace( *v ) ) { v++; } t = v; while ( *t ) { t++; } while ( t > v && IsSpace( *( t - 1 ) ) ) { t--; } *t = 0; iniHash.SetStrValue( section.data(), s, v ); } } in.Close(); } void IniHashLoad( IniHash& iniHash, const char* sectName ) { FSPath path = configDirPath; path.Push( CS_UTF8, carray_cat<char>( sectName, ".cfg" ).data() ); LoadIniHash( iniHash, (sys_char_t*) path.GetString( sys_charset_id ) ); } inline bool strless( const char* a, const char* b ) { const char* s1 = a; const char* s2 = b; while ( *s1 && *s1 == *s2 ) { s1++; s2++; }; return *s1 <= *s2; } void SaveIniHash( IniHash& iniHash, const sys_char_t* fileName ) { SysTextFileOut out; out.Open( fileName ); if ( iniHash.Size() > 0 ) { std::vector<const char*> secList = iniHash.Keys(); std::sort( secList.begin(), secList.end(), strless ); for ( int i = 0, count = secList.size(); i < count; i++ ) { out.Put( "\n[" ); out.Put( secList[i] ); out.Put( "]\n" ); cstrhash< std::string >* h = iniHash.Exist( secList[i] ); if ( !h ) { continue; } std::vector<const char*> varList = h->keys(); std::sort( varList.begin(), varList.end(), strless ); for ( int j = 0; j < h->count(); j++ ) { out.Put( varList[j] ); out.PutC( '=' ); std::string* p = h->exist( varList[j] ); if ( p && p->data() ) { out.Put( p->data() ); } out.PutC( '\n' ); } } } out.Flush(); out.Close(); } void IniHashSave( IniHash& iniHash, const char* sectName ) { FSPath path = configDirPath; path.Push( CS_UTF8, carray_cat<char>( sectName, ".cfg" ).data() ); SaveIniHash( iniHash, (sys_char_t*) path.GetString( sys_charset_id ) ); } bool LoadStringList( const char* section, std::vector< std::string >& list ) { try { SysTextFileIn in; FSPath path = configDirPath; path.Push( CS_UTF8, carray_cat<char>( section, ".cfg" ).data() ); in.Open( ( sys_char_t* )path.GetString( sys_charset_id ) ); char buf[4096]; while ( in.GetLine( buf, sizeof( buf ) ) ) { char* s = buf; while ( *s > 0 && *s <= ' ' ) { s++; } if ( *s ) { list.push_back( std::string( s ) ); } } } catch ( cexception* ex ) { ex->destroy(); return false; } return true; } void SaveStringList( const char* section, std::vector< std::string >& list ) { try { SysTextFileOut out; FSPath path = configDirPath; path.Push( CS_UTF8, carray_cat<char>( section, ".cfg" ).data() ); out.Open( ( sys_char_t* )path.GetString( sys_charset_id ) ); for ( int i = 0; i < ( int )list.size(); i++ ) { if ( list[i].c_str() && list[i][0] ) { out.Put( list[i].c_str() ); out.PutC( '\n' ); } } out.Flush(); out.Close(); } catch ( cexception* ex ) { ex->destroy(); return ; } } #else //старый клочек, надо перепроверить static const char* regapp = "WCM commander"; static const char* regcomp = "WCM"; #define COMPANY regcomp #define APPNAME regapp static HKEY GetAppProfileKey() { if ( !regapp || !regcomp ) { return NULL; } HKEY hsoft = NULL; HKEY hcomp = NULL; HKEY happ = NULL; if ( RegOpenKeyExA( HKEY_CURRENT_USER, "software", 0, KEY_WRITE | KEY_READ, &hsoft ) == ERROR_SUCCESS ) { DWORD dw; if ( RegCreateKeyExA( hsoft, COMPANY, 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_READ, NULL, &hcomp, &dw ) == ERROR_SUCCESS ) { RegCreateKeyExA( hcomp, APPNAME, 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_READ, NULL, &happ, &dw ); } } if ( hsoft != NULL ) { RegCloseKey( hsoft ); } if ( hcomp != NULL ) { RegCloseKey( hcomp ); } return happ; } HKEY GetSection( HKEY hKey, const char* sectname ) { ASSERT( sectname && *sectname ); if ( !hKey ) { return NULL; } DWORD dw; HKEY hsect; RegCreateKeyEx( hKey, sectname, 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_READ | KEY_QUERY_VALUE, NULL, &hsect, &dw ); return hsect; } HKEY GetSection( const char* sectname ) { ASSERT( sectname && *sectname ); HKEY happ = GetAppProfileKey(); if ( !happ ) { return NULL; } HKEY hsect = GetSection( happ, sectname ); RegCloseKey( happ ); return hsect; } std::vector<std::string> RegReadKeys( HKEY hKey ) { if ( !hKey ) { return std::vector<std::string>(); } std::vector<std::string> keys; DWORD dwIndex = 0, dwSize; char buf[256]; while ( RegEnumKeyEx( hKey, dwIndex++, buf, &(dwSize = 256), NULL, NULL, NULL, NULL ) == ERROR_SUCCESS ) { std::string str( buf ); keys.push_back( str ); } return keys; } void RegReadIniHash( HKEY hKey, IniHash& iniHash ) { char bufName[256]; char bufValue[4096]; std::vector<std::string> keys = RegReadKeys( hKey ); for ( int i = 0, count = keys.size(); i < count; i++ ) { std::string section = keys.at( i ); HKEY hSect = GetSection( hKey, section.c_str() ); DWORD dwIndex = 0, dwNameSize, dwValueSize; while ( RegEnumValue( hSect, dwIndex++, bufName, &(dwNameSize = 256), NULL, NULL, (LPBYTE) bufValue, &(dwValueSize = 4096) ) == ERROR_SUCCESS ) { iniHash.SetStrValue( section.c_str(), bufName, bufValue ); } RegCloseKey( hSect ); } } void RegWriteIniHash( HKEY hKey, IniHash& iniHash ) { std::vector<const char*> secList = iniHash.Keys(); //std::sort( secList.begin(), secList.end(), strless ); for ( int i = 0, sectCount = secList.size(); i < sectCount; i++ ) { const char* section = secList[i]; cstrhash<std::string>* h = iniHash.Exist( section ); if ( !h ) { continue; } std::vector<const char*> varList = h->keys(); //std::sort( varList.begin(), varList.end(), strless ); HKEY hSect = GetSection( hKey, section ); if ( !hSect ) { continue; } for ( int j = 0, varCount = varList.size(); j < varCount; j++ ) { const char* var = varList[j]; std::string* p = h->exist( var ); if ( p && p->c_str() ) { RegSetValueEx( hSect, var, 0, REG_SZ, (LPBYTE) p->c_str(), p->size() + 1 ); } } RegCloseKey( hSect ); } } DWORD RegReadInt( const char* sect, const char* what, DWORD def ) { HKEY hsect = GetSection( sect ); if ( !hsect ) { return def; } DWORD dwValue; DWORD dwType; DWORD dwCount = sizeof( DWORD ); LONG lResult = RegQueryValueEx( hsect, ( LPTSTR )what, NULL, &dwType, ( LPBYTE )&dwValue, &dwCount ); RegCloseKey( hsect ); if ( lResult == ERROR_SUCCESS ) { ASSERT( dwType == REG_DWORD ); ASSERT( dwCount == sizeof( dwValue ) ); return ( UINT )dwValue; } return def; } std::string RegReadString( char const* sect, const char* what, const char* def ) { HKEY hsect = GetSection( sect ); if ( !hsect ) { return def ? def : std::string(); } std::string strValue; DWORD dwType, dwCount; LONG lResult = RegQueryValueEx( hsect, ( LPTSTR )what, NULL, &dwType, NULL, &dwCount ); if ( lResult == ERROR_SUCCESS ) { ASSERT( dwType == REG_SZ ); //TODO: possible memory leak, needs to be checked!!! char* Buf = (char*)alloca( dwCount + 1 ); Buf[dwCount] = 0; lResult = RegQueryValueEx( hsect, ( LPTSTR )what, NULL, &dwType, ( LPBYTE )Buf, &dwCount ); strValue = std::string( Buf ); } RegCloseKey( hsect ); if ( lResult == ERROR_SUCCESS ) { ASSERT( dwType == REG_SZ ); return strValue; } return def ? def : std::string(); } int RegGetBinSize( const char* sect, const char* what ) { HKEY hsect = GetSection( sect ); if ( hsect == NULL ) { return -1; } DWORD dwType, dwCount; LONG lResult = RegQueryValueEx( hsect, ( LPTSTR )what, NULL, &dwType, NULL, &dwCount ); RegCloseKey( hsect ); if ( lResult != ERROR_SUCCESS ) { return -1; } return dwCount; } bool RegReadBin( const char* sect, const char* what, const void* data, int size ) { HKEY hsect = GetSection( sect ); if ( hsect == NULL ) { return false; } DWORD dwType, dwCount; LONG lResult = RegQueryValueEx( hsect, ( LPTSTR )what, NULL, &dwType, NULL, &dwCount ); if ( lResult != ERROR_SUCCESS || dwCount != ( DWORD )size ) { RegCloseKey( hsect ); return false; } ASSERT( dwType == REG_BINARY ); lResult = RegQueryValueEx( hsect, ( LPTSTR )what, NULL, &dwType, ( LPBYTE )data, &dwCount ); RegCloseKey( hsect ); return ( lResult == ERROR_SUCCESS ); } bool RegWriteInt( const char* sect, const char* what, DWORD data ) { HKEY hsect = GetSection( sect ); if ( hsect == NULL ) { return false; } LONG lResult = RegSetValueEx( hsect, what, 0, REG_DWORD, ( LPBYTE )&data, sizeof( data ) ); RegCloseKey( hsect ); return lResult == ERROR_SUCCESS; } bool RegWriteString( const char* sect, const char* what, const char* data ) { if ( !data ) { return false; } HKEY hsect = GetSection( sect ); if ( hsect == NULL ) { return false; } LONG lResult = RegSetValueEx( hsect, what, 0, REG_SZ, ( LPBYTE )data, strlen( data ) + 1 ); RegCloseKey( hsect ); return lResult == ERROR_SUCCESS; } bool RegWriteBin( const char* sect, const char* what, const void* data, int size ) { HKEY hsect = GetSection( sect ); if ( hsect == NULL ) { return false; } LONG lResult = RegSetValueEx( hsect, what, 0, REG_BINARY, ( LPBYTE )data, size ); RegCloseKey( hsect ); return lResult == ERROR_SUCCESS; } bool LoadStringList( const char* section, std::vector< std::string >& list ) { char name[64]; list.clear(); for ( int i = 1; ; i++ ) { Lsnprintf( name, sizeof( name ), "v%i", i ); std::string s = RegReadString( section, name, "" ); if ( s.empty() ) { break; } list.push_back( s ); } return true; } void SaveStringList( const char* section, std::vector< std::string >& list ) { int n = 1; char name[64]; for ( size_t i = 0; i < list.size(); i++ ) { if ( list[i].data() && list[i][0] ) { Lsnprintf( name, sizeof( name ), "v%i", n ); if ( !RegWriteString( section, name, list[i].data() ) ) { break; } n++; } } Lsnprintf( name, sizeof( name ), "v%i", n ); RegWriteString( section, name, "" ); } void IniHashLoad( IniHash& iniHash, const char* sectName ) { HKEY hKey = GetSection( sectName ); if ( hKey ) { RegReadIniHash( hKey, iniHash ); RegCloseKey( hKey ); } } void IniHashSave( IniHash& iniHash, const char* sectName ) { HKEY hKey = GetSection( sectName ); if ( hKey ) { RegWriteIniHash( hKey, iniHash ); RegCloseKey( hKey ); } } #endif const char* sectionSystem = "system"; const char* sectionPanel = "panel"; const char* sectionEditor = "editor"; const char* sectionViewer = "viewer"; const char* sectionTerminal = "terminal"; const char* sectionFonts = "fonts"; static const char* CommandsHistorySection = "CommandsHistory"; static const char* FilesAssociationsSection = "FilesAssociations"; static const char* HighlightingRulesSection = "HighlightingRules"; static const char* UserMenuSection = "UserMenu"; clWcmConfig::clWcmConfig() : systemAskOpenExec( true ) , systemEscPanel( true ) , systemEscCommandLine( true ) , systemBackSpaceUpDir( false ) , systemAutoComplete( true ) , systemAutoSaveSetup( true ) , systemShowHostName( false ) , systemStorePasswords( false ) , systemTotalProgressIndicator(false) , systemLang( "+" ) , panelShowHiddenFiles( true ) , panelCaseSensitive( false ) , panelSelectFolders( false ) , panelShowDotsInRoot( false ) , panelShowFolderIcons( true ) , panelShowExecutableIcons( true ) , panelShowLinkIcons( true ) , panelShowScrollbar( true ) , panelShowSpacesMode( ePanelSpacesMode_Trailing ) , panelModeLeft( 0 ) , panelModeRight( 0 ) , editSavePos( true ) , editAutoIdent( false ) , editTabSize( 3 ) , editShl( true ) , editClearHistoryAfterSaving( true ) , terminalBackspaceKey( 0 ) , styleShow3DUI( false ) , styleColorTheme( "" ) , styleShowToolBar( true ) , styleShowButtonBar( true ) , styleShowButtonBarIcons( true ) , styleShowMenuBar( true ) , windowX( 0 ) , windowY( 0 ) , windowWidth( 0 ) , windowHeight( 0 ) { #ifndef _WIN32 MapBool( sectionSystem, "ask_open_exec", &systemAskOpenExec, systemAskOpenExec ); #endif MapBool( sectionSystem, "esc_panel", &systemEscPanel, systemEscPanel ); MapBool( sectionSystem, "esc_panel", &systemEscCommandLine, systemEscCommandLine ); MapBool( sectionSystem, "back_updir", &systemBackSpaceUpDir, systemBackSpaceUpDir ); MapBool( sectionSystem, "auto_complete", &systemAutoComplete, systemAutoComplete ); MapBool( sectionSystem, "auto_save_setup", &systemAutoSaveSetup, systemAutoSaveSetup ); MapBool( sectionSystem, "show_hostname", &systemShowHostName, systemShowHostName ); MapBool( sectionSystem, "store_passwords", &systemStorePasswords, systemStorePasswords ); MapBool( sectionSystem, "total_progress_indicator", &systemTotalProgressIndicator, systemTotalProgressIndicator ); MapStr( sectionSystem, "lang", &systemLang ); MapBool( sectionSystem, "show_toolbar", &styleShowToolBar, styleShowToolBar ); MapBool( sectionSystem, "show_buttonbar", &styleShowButtonBar, styleShowButtonBar ); MapBool( sectionSystem, "show_buttonbaricons", &styleShowButtonBarIcons, styleShowButtonBarIcons ); MapBool( sectionSystem, "show_menubar", &styleShowMenuBar, styleShowMenuBar ); MapBool( sectionPanel, "show_3d_ui", &styleShow3DUI, styleShow3DUI ); MapStr( sectionPanel, "color_theme", &styleColorTheme, "" ); MapBool( sectionPanel, "show_hidden_files", &panelShowHiddenFiles, panelShowHiddenFiles ); MapBool( sectionPanel, "case_sensitive_sort", &panelCaseSensitive, panelCaseSensitive ); MapBool( sectionPanel, "select_folders", &panelSelectFolders, panelSelectFolders ); MapBool( sectionPanel, "show_dots", &panelShowDotsInRoot, panelShowDotsInRoot ); MapBool( sectionPanel, "show_foldericons", &panelShowFolderIcons, panelShowFolderIcons ); MapBool( sectionPanel, "show_executableicons", &panelShowExecutableIcons, panelShowExecutableIcons ); MapBool( sectionPanel, "show_linkicons", &panelShowLinkIcons, panelShowLinkIcons ); MapBool( sectionPanel, "show_scrollbar", &panelShowScrollbar, panelShowScrollbar ); MapInt( sectionPanel, "show_spaces_mode", ( int* )&panelShowSpacesMode, panelShowSpacesMode ); MapInt( sectionPanel, "mode_left", &panelModeLeft, panelModeLeft ); MapInt( sectionPanel, "mode_right", &panelModeRight, panelModeRight ); #ifdef _WIN32 const char* defPanelPath = "C:\\"; #else const char* defPanelPath = "/"; #endif MapStr( sectionPanel, "left_panel_path", &leftPanelPath, defPanelPath ); MapStr( sectionPanel, "right_panel_path", &rightPanelPath, defPanelPath ); MapBool( sectionEditor, "save_file_position", &editSavePos, editSavePos ); MapBool( sectionEditor, "auto_ident", &editAutoIdent, editAutoIdent ); MapInt( sectionEditor, "tab_size", &editTabSize, editTabSize ); MapBool( sectionEditor, "highlighting", &editShl, editShl ); MapBool( sectionEditor, "editClearHistoryAfterSaving", &editClearHistoryAfterSaving, editClearHistoryAfterSaving ); MapInt( sectionTerminal, "backspace_key", &terminalBackspaceKey, terminalBackspaceKey ); MapStr( sectionFonts, "panel_font", &panelFontUri ); MapStr( sectionFonts, "viewer_font", &viewerFontUri ); MapStr( sectionFonts, "editor_font", &editorFontUri ); MapStr( sectionFonts, "dialog_font", &dialogFontUri ); MapStr( sectionFonts, "terminal_font", &terminalFontUri ); MapStr( sectionFonts, "helptext_font", &helpTextFontUri ); MapStr( sectionFonts, "helpbold_font", &helpBoldFontUri ); MapStr( sectionFonts, "helphead_font", &helpHeadFontUri ); MapInt( sectionSystem, "windowX", &windowX, windowX ); MapInt( sectionSystem, "windowY", &windowY, windowY ); MapInt( sectionSystem, "windowWidth", &windowWidth, windowWidth ); MapInt( sectionSystem, "windowHeight", &windowHeight, windowHeight ); } void clWcmConfig::ImpCurrentFonts() { panelFontUri = g_PanelFont.ptr() ? g_PanelFont->uri() : ""; viewerFontUri = g_ViewerFont.ptr() ? g_ViewerFont->uri() : ""; editorFontUri = g_EditorFont.ptr() ? g_EditorFont->uri() : ""; dialogFontUri = g_DialogFont.ptr() ? g_DialogFont->uri() : ""; terminalFontUri = g_TerminalFont.ptr() ? g_TerminalFont->uri() : ""; helpTextFontUri = g_HelpTextFont.ptr() ? g_HelpTextFont->uri() : ""; helpBoldFontUri = g_HelpBoldFont.ptr() ? g_HelpBoldFont->uri() : ""; helpHeadFontUri = g_HelpHeadFont.ptr() ? g_HelpHeadFont->uri() : ""; } void clWcmConfig::MapInt( const char* Section, const char* Name, int* pInt, int def ) { sNode Node = sNode::CreateIntNode( Section, Name, pInt, def ); m_MapList.push_back( Node ); } void clWcmConfig::MapBool( const char* Section, const char* Name, bool* pBool, bool def ) { sNode Node = sNode::CreateBoolNode( Section, Name, pBool, def ); m_MapList.push_back( Node ); } void clWcmConfig::MapStr( const char* Section, const char* Name, std::string* pStr, const char* def ) { sNode Node = sNode::CreateStrNode( Section, Name, pStr, def ); m_MapList.push_back( Node ); } class clConfigHelper { public: clConfigHelper() : m_SectionName( "" ) {} void SetSectionName( const char* SectionName ) { m_SectionName = SectionName; } protected: const char* m_SectionName; }; class clConfigWriter: public clConfigHelper { public: #if defined(_WIN32) clConfigWriter() {} #else explicit clConfigWriter( IniHash& hash ) : m_Hash( hash ) {} #endif void Write( const char* KeyNamePattern, int i, const std::string& Data ) { this->Write( KeyNamePattern, i, Data.c_str() ); } void Write( const char* KeyNamePattern, int i, const char* Data ) { char Buf[4096]; Lsnprintf( Buf, sizeof( Buf ), KeyNamePattern, i ); #ifdef _WIN32 RegWriteString( m_SectionName, Buf, Data ); #else m_Hash.SetStrValue( m_SectionName, Buf, Data ); #endif } void WriteBool( const char* KeyNamePattern, int i, bool Data ) { char Buf[4096]; Lsnprintf( Buf, sizeof( Buf ), KeyNamePattern, i ); #ifdef _WIN32 RegWriteInt( m_SectionName, Buf, ( int )Data ); #else m_Hash.SetBoolValue( m_SectionName, Buf, Data ); #endif } void WriteInt( const char* KeyNamePattern, int i, int Data ) { char Buf[4096]; Lsnprintf( Buf, sizeof( Buf ), KeyNamePattern, i ); #ifdef _WIN32 RegWriteInt( m_SectionName, Buf, Data ); #else m_Hash.SetIntValue( m_SectionName, Buf, Data ); #endif } private: #if !defined(_WIN32) IniHash& m_Hash; #endif }; class clConfigReader: public clConfigHelper { public: #if defined(_WIN32) clConfigReader() {} #else explicit clConfigReader( IniHash& hash ): m_Hash( hash ) {} #endif std::string Read( const char* KeyNamePattern, int i ) { char Buf[4096]; Lsnprintf( Buf, sizeof( Buf ), KeyNamePattern, i ); #ifdef _WIN32 std::string Result = RegReadString( m_SectionName, Buf, "" ); #else std::string Result = m_Hash.GetStrValue( m_SectionName, Buf, "" ); #endif return Result; } bool ReadBool( const char* KeyNamePattern, int i, bool DefaultValue ) { char Buf[4096]; Lsnprintf( Buf, sizeof( Buf ), KeyNamePattern, i ); #ifdef _WIN32 bool Result = RegReadInt( m_SectionName, Buf, DefaultValue ) != 0; #else bool Result = m_Hash.GetBoolValue( m_SectionName, Buf, DefaultValue ); #endif return Result; } int ReadInt( const char* KeyNamePattern, int i, int DefaultValue ) { char Buf[4096]; Lsnprintf( Buf, sizeof( Buf ), KeyNamePattern, i ); #ifdef _WIN32 int Result = RegReadInt( m_SectionName, Buf, DefaultValue ); #else int Result = m_Hash.GetIntValue( m_SectionName, Buf, DefaultValue ); #endif return Result; } private: #if !defined(_WIN32) IniHash& m_Hash; #endif }; void SaveFileAssociations( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigWriter Cfg; #else clConfigWriter Cfg( hash ); #endif Cfg.SetSectionName( FilesAssociationsSection ); const std::vector<clNCFileAssociation>& Assoc = g_Env.GetFileAssociations(); for ( size_t i = 0; i < Assoc.size(); i++ ) { const clNCFileAssociation& A = Assoc[i]; std::string Mask_utf8 = unicode_to_utf8_string( A.GetMask().data() ); std::string Description_utf8 = unicode_to_utf8_string( A.GetDescription().data() ); std::string Execute_utf8 = unicode_to_utf8_string( A.GetExecuteCommand().data() ); std::string ExecuteSecondary_utf8 = unicode_to_utf8_string( A.GetExecuteCommandSecondary().data() ); std::string View_utf8 = unicode_to_utf8_string( A.GetViewCommand().data() ); std::string ViewSecondary_utf8 = unicode_to_utf8_string( A.GetViewCommandSecondary().data() ); std::string Edit_utf8 = unicode_to_utf8_string( A.GetEditCommand().data() ); std::string EditSecondary_utf8 = unicode_to_utf8_string( A.GetEditCommandSecondary().data() ); Cfg.Write( "Mask%i", i, Mask_utf8 ); Cfg.Write( "Description%i", i, Description_utf8 ); Cfg.Write( "Execute%i", i, Execute_utf8 ); Cfg.Write( "ExecuteSecondary%i", i, ExecuteSecondary_utf8 ); Cfg.Write( "View%i", i, View_utf8 ); Cfg.Write( "ViewSecondary%i", i, ViewSecondary_utf8 ); Cfg.Write( "Edit%i", i, Edit_utf8 ); Cfg.Write( "EditSecondary%i", i, EditSecondary_utf8 ); Cfg.WriteBool( "HasTerminal%i", i, A.GetHasTerminal() ); } // end marker Cfg.Write( "Mask%i", Assoc.size(), "" ); } void LoadFileAssociations( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigReader Cfg; #else clConfigReader Cfg( hash ); #endif Cfg.SetSectionName( FilesAssociationsSection ); int i = 0; std::vector<clNCFileAssociation> Assoc; while ( true ) { std::string Mask = Cfg.Read( "Mask%i", i ); std::string Description = Cfg.Read( "Description%i", i ); std::string Execute = Cfg.Read( "Execute%i", i ); std::string ExecuteSecondary = Cfg.Read( "ExecuteSecondary%i", i ); std::string View = Cfg.Read( "View%i", i ); std::string ViewSecondary = Cfg.Read( "ViewSecondary%i", i ); std::string Edit = Cfg.Read( "Edit%i", i ); std::string EditSecondary = Cfg.Read( "EditSecondary%i", i ); bool HasTerminal = Cfg.ReadBool( "HasTerminal%i", i, true ); if ( Mask.empty() ) { break; } clNCFileAssociation A; A.SetMask( utf8str_to_unicode( Mask ) ); A.SetDescription( utf8str_to_unicode( Description ) ); A.SetExecuteCommand( utf8str_to_unicode( Execute ) ); A.SetExecuteCommandSecondary( utf8str_to_unicode( ExecuteSecondary ) ); A.SetViewCommand( utf8str_to_unicode( View ) ); A.SetViewCommandSecondary( utf8str_to_unicode( ViewSecondary ) ); A.SetEditCommand( utf8str_to_unicode( Edit ) ); A.SetEditCommandSecondary( utf8str_to_unicode( EditSecondary ) ); A.SetHasTerminal( HasTerminal ); Assoc.push_back( A ); i++; } g_Env.SetFileAssociations( Assoc ); } void SaveUserMenu( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigWriter Cfg; #else clConfigWriter Cfg( hash ); #endif Cfg.SetSectionName( UserMenuSection ); const std::vector<clNCUserMenuItem>& Items = g_Env.GetUserMenuItems(); for ( size_t i = 0; i < Items.size(); i++ ) { const clNCUserMenuItem& A = Items[i]; std::string Description_utf8 = unicode_to_utf8_string( A.GetDescription().GetRawText() ); std::string Execute_utf8 = unicode_to_utf8_string( A.GetCommand().data() ); Cfg.Write( "Description%i", i, Description_utf8 ); Cfg.Write( "Execute%i", i, Execute_utf8 ); } // end marker Cfg.Write( "Mask%i", Items.size(), "" ); } void LoadUserMenu( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigReader Cfg; #else clConfigReader Cfg( hash ); #endif Cfg.SetSectionName( UserMenuSection ); int i = 0; std::vector<clNCUserMenuItem> Items; while ( true ) { std::string Description = Cfg.Read( "Description%i", i ); std::string Execute = Cfg.Read( "Execute%i", i ); if ( Description.empty() ) { break; } clNCUserMenuItem A; A.SetDescription( utf8str_to_unicode( Description ) ); A.SetCommand( utf8str_to_unicode( Execute ) ); Items.push_back( A ); i++; } g_Env.SetUserMenuItems( Items ); } void SaveFileHighlightingRules( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigWriter Cfg; #else clConfigWriter Cfg( hash ); #endif Cfg.SetSectionName( HighlightingRulesSection ); const std::vector<clNCFileHighlightingRule>& Rules = g_Env.GetFileHighlightingRules(); for ( size_t i = 0; i < Rules.size(); i++ ) { const clNCFileHighlightingRule& A = Rules[i]; std::string Mask_utf8 = unicode_to_utf8_string( A.GetMask().data() ); std::string Description_utf8 = unicode_to_utf8_string( A.GetDescription().data() ); char Buf[0xFFFF]; Lsnprintf( Buf, sizeof( Buf ) - 1, "Min = %" PRIu64 " Max = %" PRIu64 " Attribs = %" PRIu64, A.GetSizeMin(), A.GetSizeMax(), A.GetAttributesMask() ); Cfg.Write( "Mask%i", i, Mask_utf8 ); Cfg.Write( "Description%i", i, Description_utf8 ); Cfg.Write( "SizeAttribs%i", i, Buf ); Cfg.WriteInt( "ColorNormal%i", i, A.GetColorNormal() ); Cfg.WriteInt( "ColorNormalBackground%i", i, A.GetColorNormalBackground() ); Cfg.WriteInt( "ColorSelected%i", i, A.GetColorSelected() ); Cfg.WriteInt( "ColorSelectedBackground%i", i, A.GetColorSelectedBackground() ); Cfg.WriteInt( "ColorUnderCursorNormal%i", i, A.GetColorUnderCursorNormal() ); Cfg.WriteInt( "ColorUnderCursorNormalBackground%i", i, A.GetColorUnderCursorNormalBackground() ); Cfg.WriteInt( "ColorUnderCursorSelected%i", i, A.GetColorUnderCursorSelected() ); Cfg.WriteInt( "ColorUnderCursorSelectedBackground%i", i, A.GetColorUnderCursorSelectedBackground() ); Cfg.WriteBool( "MaskEnabled%i", i, A.IsMaskEnabled() ); } // end marker Cfg.Write( "Mask%i", Rules.size(), "" ); } void LoadFileHighlightingRules( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigReader Cfg; #else clConfigReader Cfg( hash ); #endif Cfg.SetSectionName( HighlightingRulesSection ); int i = 0; std::vector<clNCFileHighlightingRule> Rules; while ( true ) { std::string Mask = Cfg.Read( "Mask%i", i ); std::string Description = Cfg.Read( "Description%i", i ); std::string Line = Cfg.Read( "SizeAttribs%i", i ); uint64_t SizeMin, SizeMax, AttribsMask; int NumRead = 0; if ( !Line.empty() ) { NumRead = Lsscanf( Line.c_str(), "Min = %" PRIu64 " Max = %" PRIu64 " Attribs = %" PRIu64, &SizeMin, &SizeMax, &AttribsMask ); } if ( NumRead != 3 ) { SizeMin = 0; SizeMax = 0; AttribsMask = 0; } if ( !Mask.data() || !*Mask.data() ) { break; } clNCFileHighlightingRule R; R.SetMask( utf8str_to_unicode( Mask ) ); R.SetDescription( utf8str_to_unicode( Description ) ); R.SetSizeMin( SizeMin ); R.SetSizeMax( SizeMax ); R.SetAttributesMask( AttribsMask ); R.SetColorNormal( Cfg.ReadInt( "ColorNormal%i", i, R.GetColorNormal() ) ); R.SetColorNormalBackground( Cfg.ReadInt( "ColorNormalBackground%i", i, R.GetColorNormalBackground() ) ); R.SetColorSelected( Cfg.ReadInt( "ColorSelected%i", i, R.GetColorSelected() ) ); R.SetColorSelectedBackground( Cfg.ReadInt( "ColorSelectedBackground%i", i, R.GetColorSelectedBackground() ) ); R.SetColorUnderCursorNormal( Cfg.ReadInt( "ColorUnderCursorNormal%i", i, R.GetColorUnderCursorNormal() ) ); R.SetColorUnderCursorNormalBackground( Cfg.ReadInt( "ColorUnderCursorNormalBackground%i", i, R.GetColorUnderCursorNormalBackground( ) ) ); R.SetColorUnderCursorSelected( Cfg.ReadInt( "ColorUnderCursorSelected%i", i, R.GetColorUnderCursorSelected() ) ); R.SetColorUnderCursorSelectedBackground( Cfg.ReadInt( "ColorUnderCursorSelectedBackground%i", i, R.GetColorUnderCursorSelectedBackground() ) ); Rules.push_back( R ); i++; } g_Env.SetFileHighlightingRules( Rules ); } void SaveCommandsHistory( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigWriter Cfg; #else clConfigWriter Cfg( hash ); #endif Cfg.SetSectionName( CommandsHistorySection ); int Count = nc->GetHistory()->Count(); for ( int i = 0; i < Count; i++ ) { const unicode_t* Hist = ( *nc->GetHistory() )[Count - i - 1]; Cfg.Write( "Command%i", i, unicode_to_utf8_string( Hist ) ); } } void LoadCommandsHistory( NCWin* nc #ifndef _WIN32 , IniHash& hash #endif ) { if ( !nc ) { return; } #if defined(_WIN32) clConfigReader Cfg; #else clConfigReader Cfg( hash ); #endif Cfg.SetSectionName( CommandsHistorySection ); nc->GetHistory()->Clear(); int i = 0; while ( true ) { std::string Cmd = Cfg.Read( "Command%i", i ); if ( Cmd.empty() ) { break; } nc->GetHistory()->Put( utf8str_to_unicode( Cmd ).data() ); i++; } } bool FileExists( const char* name ) { struct stat sb; if ( stat( name, &sb ) ) { return false; } return true; } void clWcmConfig::Load( NCWin* nc, const std::string& StartupDir ) { #ifdef _WIN32 for ( size_t i = 0; i < m_MapList.size(); i++ ) { sNode& Node = m_MapList[i]; if ( Node.m_Type == MT_BOOL && Node.m_Current.m_Bool != 0 ) { *Node.m_Current.m_Bool = RegReadInt( Node.m_Section, Node.m_Name, Node.GetDefaultBool() ) != 0; } else if ( Node.m_Type == MT_INT && Node.m_Current.m_Int != 0 ) { *Node.m_Current.m_Int = RegReadInt( Node.m_Section, Node.m_Name, Node.GetDefaultInt() ); } else if ( Node.m_Type == MT_STR && Node.m_Current.m_Str != 0 ) { *Node.m_Current.m_Str = RegReadString( Node.m_Section, Node.m_Name, Node.GetDefaultStr() ); } } LoadCommandsHistory( nc ); LoadFileAssociations( nc ); LoadFileHighlightingRules( nc ); LoadUserMenu( nc ); #else IniHash hash; FSPath path = configDirPath; path.Push( CS_UTF8, "config" ); LoadIniHash( hash, DEFAULT_CONFIG_PATH ); LoadIniHash( hash, ( sys_char_t* )path.GetString( sys_charset_id ) ); for ( size_t i = 0; i < m_MapList.size(); i++ ) { sNode& Node = m_MapList[i]; if ( Node.m_Type == MT_BOOL && Node.m_Current.m_Bool != 0 ) { *Node.m_Current.m_Bool = hash.GetBoolValue( Node.m_Section, Node.m_Name, Node.GetDefaultBool() ); } else if ( Node.m_Type == MT_INT && Node.m_Current.m_Int != 0 ) { *Node.m_Current.m_Int = hash.GetIntValue( Node.m_Section, Node.m_Name, Node.GetDefaultInt() ); } else if ( Node.m_Type == MT_STR && Node.m_Current.m_Str != 0 ) { const char* s = hash.GetStrValue( Node.m_Section, Node.m_Name, Node.GetDefaultStr() ); if ( s ) { *Node.m_Current.m_Str = s; } else { ( *Node.m_Current.m_Str ).clear(); } } } LoadCommandsHistory( nc, hash ); LoadFileAssociations( nc, hash ); LoadFileHighlightingRules( nc, hash ); LoadUserMenu( nc, hash ); #endif if ( editTabSize <= 0 || editTabSize > 64 ) { editTabSize = 3; } LoadFoldersHistory(); LoadViewHistory(); LoadFieldsHistory(); } void clWcmConfig::Save( NCWin* nc ) { if ( nc ) { // do not save locations on non-persistent FS leftPanelPath = nc->GetLeftPanel()->GetLastPersistentPath(); rightPanelPath = nc->GetRightPanel()->GetLastPersistentPath(); crect Rect = nc->ScreenRect(); windowX = Rect.top; windowY = Rect.left; windowWidth = Rect.Width(); windowHeight = Rect.Height(); } #ifdef _WIN32 for ( size_t i = 0; i < m_MapList.size( ); i++ ) { sNode& Node = m_MapList[i]; if ( Node.m_Type == MT_BOOL && Node.m_Current.m_Bool != 0 ) { RegWriteInt( Node.m_Section, Node.m_Name, *Node.m_Current.m_Bool ); } else if ( Node.m_Type == MT_INT && Node.m_Current.m_Int != 0 ) { RegWriteInt( Node.m_Section, Node.m_Name, *Node.m_Current.m_Int ); } else if ( Node.m_Type == MT_STR && Node.m_Current.m_Str != 0 ) { RegWriteString( Node.m_Section, Node.m_Name, Node.m_Current.m_Str->data() ); } } SaveCommandsHistory( nc ); SaveFileAssociations( nc ); SaveFileHighlightingRules( nc ); SaveUserMenu( nc ); #else IniHash hash; FSPath path = configDirPath; path.Push( CS_UTF8, "config" ); LoadIniHash( hash, ( sys_char_t* )path.GetString( sys_charset_id ) ); for ( size_t i = 0; i < m_MapList.size(); i++ ) { sNode& Node = m_MapList[i]; if ( Node.m_Type == MT_BOOL && Node.m_Current.m_Bool != 0 ) { hash.SetBoolValue( Node.m_Section, Node.m_Name, *Node.m_Current.m_Bool ); } else if ( Node.m_Type == MT_INT && Node.m_Current.m_Int != 0 ) { hash.SetIntValue( Node.m_Section, Node.m_Name, *Node.m_Current.m_Int ); } else if ( Node.m_Type == MT_STR && Node.m_Current.m_Str != 0 ) { hash.SetStrValue( Node.m_Section, Node.m_Name, Node.m_Current.m_Str->data() ); } } SaveCommandsHistory( nc, hash ); SaveFileAssociations( nc, hash ); SaveFileHighlightingRules( nc, hash ); SaveUserMenu( nc, hash ); SaveIniHash( hash,( sys_char_t* ) path.GetString( sys_charset_id ) ); #endif SaveFoldersHistory(); SaveViewHistory(); SaveFieldsHistory(); } void InitConfigPath() { #if !defined( _WIN32 ) const sys_char_t* home = ( sys_char_t* ) getenv( "HOME" ); if ( home ) { FSPath path( sys_charset_id, home ); path.Push( CS_UTF8, ".wcm" ); FSSys fs; FSStat st; int err; if ( fs.Stat( path, &st, &err, 0 ) ) { if ( fs.IsENOENT( err ) ) //директорий не существует { if ( fs.MkDir( path, 0700, &err, 0 ) ) { fprintf( stderr, "can`t create config directory %s (%s)", path.GetUtf8(), fs.StrError( err ).GetUtf8() ); return; } } else { fprintf( stderr, "can`t create config directory statuc %s (%s)", path.GetUtf8(), fs.StrError( err ).GetUtf8() ); return; } } else if ( !st.IsDir() ) { fprintf( stderr, "err: '%s' is not directory", path.GetUtf8() ); return; } configDirPath = path; } else { fprintf( stderr, "err: HOME env value not found" ); } #endif } //////////////////////////////// PanelOptDlg class PanelOptDialog: public NCVertDialog { Layout iL; public: SButton showHiddenButton; SButton caseSensitive; SButton selectFolders; SButton showDotsInRoot; SButton showFolderIcons; SButton showExecutableIcons; SButton showLinkIcons; SButton showScrollbar; StaticLine showSpacesStatic; SButton showSpacesNoneButton; SButton showSpacesAllButton; SButton showSpacesTrailingButton; PanelOptDialog( NCDialogParent* parent ); virtual ~PanelOptDialog(); }; PanelOptDialog::~PanelOptDialog() {} PanelOptDialog::PanelOptDialog( NCDialogParent* parent ) : NCVertDialog( ::createDialogAsChild, 0, parent, utf8_to_unicode( _LT( "Panel settings" ) ).data(), bListOkCancel ) , iL( 16, 3 ) , showHiddenButton( 0, this, utf8_to_unicode( _LT( "Show &hidden files" ) ).data(), 0, g_WcmConfig.panelShowHiddenFiles ) , caseSensitive( 0, this, utf8_to_unicode( _LT( "C&ase sensitive sort" ) ).data(), 0, g_WcmConfig.panelCaseSensitive ) , selectFolders( 0, this, utf8_to_unicode( _LT( "Select &folders" ) ).data(), 0, g_WcmConfig.panelSelectFolders ) , showDotsInRoot( 0, this, utf8_to_unicode( _LT( "Show .. in the &root folder" ) ).data(), 0, g_WcmConfig.panelShowDotsInRoot ) , showFolderIcons( 0, this, utf8_to_unicode( _LT( "Show folder &icons" ) ).data(), 0, g_WcmConfig.panelShowFolderIcons ) , showExecutableIcons( 0, this, utf8_to_unicode( _LT( "Show &executable icons" ) ).data(), 0, g_WcmConfig.panelShowExecutableIcons ) , showLinkIcons( 0, this, utf8_to_unicode( _LT( "Show &link icons" ) ).data(), 0, g_WcmConfig.panelShowLinkIcons ) , showScrollbar( 0, this, utf8_to_unicode( _LT( "Show &scrollbar" ) ).data(), 0, g_WcmConfig.panelShowScrollbar ) , showSpacesStatic( 0, this, utf8_to_unicode( _LT( "Show spaces as · in names:" ) ).data() ) , showSpacesNoneButton( 0, this, utf8_to_unicode( _LT( "No" ) ).data(), 1, g_WcmConfig.panelShowSpacesMode != 1 && g_WcmConfig.panelShowSpacesMode != 2 ) , showSpacesAllButton( 0, this, utf8_to_unicode( _LT( "All" ) ).data(), 1, g_WcmConfig.panelShowSpacesMode == 1 ) , showSpacesTrailingButton( 0, this, utf8_to_unicode( _LT( "Trailing only" ) ).data(), 1, g_WcmConfig.panelShowSpacesMode == 2 ) { iL.AddWinAndEnable( &showHiddenButton, 0, 0 ); showHiddenButton.SetFocus(); iL.AddWinAndEnable( &caseSensitive, 1, 0 ); iL.AddWinAndEnable( &selectFolders, 2, 0 ); iL.AddWinAndEnable( &showDotsInRoot, 3, 0 ); iL.AddWinAndEnable( &showFolderIcons, 4, 0 ); iL.AddWinAndEnable( &showExecutableIcons, 5, 0 ); iL.AddWinAndEnable( &showLinkIcons, 6, 0 ); iL.AddWinAndEnable( &showScrollbar, 7, 0 ); iL.AddWinAndEnable( &showSpacesStatic, 8, 0 ); iL.AddWinAndEnable( &showSpacesNoneButton, 9, 0 ); iL.AddWinAndEnable( &showSpacesAllButton, 10, 0 ); iL.AddWinAndEnable( &showSpacesTrailingButton, 11, 0 ); AddLayout( &iL ); SetEnterCmd( CMD_OK ); showHiddenButton.SetFocus(); order.append( &showHiddenButton ); order.append( &caseSensitive ); order.append( &selectFolders ); order.append( &showDotsInRoot ); order.append( &showFolderIcons ); order.append( &showExecutableIcons ); order.append( &showLinkIcons ); order.append( &showScrollbar ); order.append( &showSpacesNoneButton ); order.append( &showSpacesAllButton ); order.append( &showSpacesTrailingButton ); SetPosition(); } bool DoPanelConfigDialog( NCDialogParent* parent ) { PanelOptDialog dlg( parent ); if ( dlg.DoModal() == CMD_OK ) { g_WcmConfig.panelShowHiddenFiles = dlg.showHiddenButton.IsSet(); g_WcmConfig.panelCaseSensitive = dlg.caseSensitive.IsSet(); g_WcmConfig.panelSelectFolders = dlg.selectFolders.IsSet(); g_WcmConfig.panelShowDotsInRoot = dlg.showDotsInRoot.IsSet(); g_WcmConfig.panelShowFolderIcons = dlg.showFolderIcons.IsSet(); g_WcmConfig.panelShowExecutableIcons = dlg.showExecutableIcons.IsSet(); g_WcmConfig.panelShowLinkIcons = dlg.showLinkIcons.IsSet(); g_WcmConfig.panelShowScrollbar = dlg.showScrollbar.IsSet(); if ( dlg.showSpacesTrailingButton.IsSet() ) { g_WcmConfig.panelShowSpacesMode = ePanelSpacesMode_Trailing; } else if ( dlg.showSpacesAllButton.IsSet() ) { g_WcmConfig.panelShowSpacesMode = ePanelSpacesMode_All; } else { g_WcmConfig.panelShowSpacesMode = ePanelSpacesMode_None; } return true; } return false; } //////////////////////////////// EditOptDlg class EditOptDialog: public NCVertDialog { Layout iL; public: SButton saveFilePosButton; SButton autoIdentButton; SButton shlButton; SButton clearHistoryButton; StaticLabel tabText; EditLine tabEdit; EditOptDialog( NCDialogParent* parent ); // virtual bool EventChildKey(Win* child, cevent_key* pEvent); // virtual bool Command(int id, int subId, Win *win, void *data); virtual ~EditOptDialog(); }; EditOptDialog::~EditOptDialog() {} EditOptDialog::EditOptDialog( NCDialogParent* parent ) : NCVertDialog( ::createDialogAsChild, 0, parent, utf8_to_unicode( _LT( "Editor" ) ).data(), bListOkCancel ), iL( 16, 2 ), saveFilePosButton( 0, this, utf8_to_unicode( _LT( "Save file &position" ) ).data(), 0, g_WcmConfig.editSavePos ), autoIdentButton( 0, this, utf8_to_unicode( _LT( "Auto &indent" ) ).data(), 0, g_WcmConfig.editAutoIdent ), shlButton( 0, this, utf8_to_unicode( _LT( "Syntax &highlighting" ) ).data(), 0, g_WcmConfig.editShl ), clearHistoryButton( 0, this, utf8_to_unicode( _LT( "&Clear history after saving" ) ).data(), 0, g_WcmConfig.editClearHistoryAfterSaving ), tabText( 0, this, utf8_to_unicode( _LT( "&Tab size:" ) ).data(), &tabEdit ), tabEdit( 0, this, 0, 0, 16 ) { char buf[0x100]; Lsnprintf( buf, sizeof( buf ) - 1, "%i", g_WcmConfig.editTabSize ); tabEdit.SetText( utf8_to_unicode( buf ).data(), true ); iL.AddWinAndEnable( &saveFilePosButton, 0, 0, 0, 1 ); iL.AddWinAndEnable( &autoIdentButton, 1, 0, 1, 1 ); iL.AddWinAndEnable( &shlButton, 2, 0, 2, 1 ); iL.AddWinAndEnable( &clearHistoryButton, 3, 0, 3, 1 ); iL.AddWinAndEnable( &tabText, 4, 0, 4, 0 ); iL.AddWinAndEnable( &tabEdit, 4, 1, 5, 1 ); AddLayout( &iL ); SetEnterCmd( CMD_OK ); saveFilePosButton.SetFocus(); order.append( &saveFilePosButton ); order.append( &autoIdentButton ); order.append( &shlButton ); order.append( &clearHistoryButton ); order.append( &tabEdit ); SetPosition(); } bool DoEditConfigDialog( NCDialogParent* parent ) { EditOptDialog dlg( parent ); if ( dlg.DoModal() == CMD_OK ) { g_WcmConfig.editSavePos = dlg.saveFilePosButton.IsSet(); g_WcmConfig.editAutoIdent = dlg.autoIdentButton.IsSet(); g_WcmConfig.editShl = dlg.shlButton.IsSet(); g_WcmConfig.editClearHistoryAfterSaving = dlg.clearHistoryButton.IsSet(); int tabSize = atoi( unicode_to_utf8( dlg.tabEdit.GetText().data() ).data() ); if ( tabSize > 0 && tabSize <= 64 ) { g_WcmConfig.editTabSize = tabSize; } return true; } return false; } ////////////////////////// StyleOptDialog class StyleOptDialog: public NCVertDialog { void RefreshFontInfo(); Layout iL; public: struct Node { std::string name; cfont* oldFont; std::string* pUri; clPtr<cfont> newFont; bool fixed; Node(): oldFont( 0 ) {} Node( const char* n, bool fix, cfont* old, std::string* uri ) : name( n ) , oldFont( old ) , pUri( uri ) , fixed( fix ) {} }; ccollect<Node>* pList; SButton styleShow3DUIButton; StaticLine colorStatic; ComboBox styleList; StaticLine showStatic; SButton showToolbarButton; SButton showButtonbarButton; SButton showButtonbarIconsButton; SButton showMenubarButton; StaticLine fontsStatic; TextList fontList; StaticLine fontNameStatic; Button changeButton; Button changeX11Button; StyleOptDialog( NCDialogParent* parent, ccollect<Node>* p ); virtual bool EventChildKey( Win* child, cevent_key* pEvent ); virtual bool Command( int id, int subId, Win* win, void* data ); virtual ~StyleOptDialog(); }; StyleOptDialog::~StyleOptDialog() {} void StyleOptDialog::RefreshFontInfo() { int count = pList->count(); int cur = fontList.GetCurrent(); const char* s = ""; if ( count >= 0 && cur >= 0 && cur < count ) { int n = fontList.GetCurrentInt(); if ( pList->get( n ).newFont.ptr() ) { s = pList->get( n ).newFont->printable_name(); } else if ( pList->get( n ).oldFont ) { s = pList->get( n ).oldFont->printable_name(); } } fontNameStatic.SetText( utf8_to_unicode( s ).data() ); } #define CMD_CHFONT 1000 #define CMD_CHFONTX11 1001 StyleOptDialog::StyleOptDialog( NCDialogParent* parent, ccollect<Node>* p ) : NCVertDialog( ::createDialogAsChild, 0, parent, utf8_to_unicode( _LT( "Style" ) ).data(), bListOkCancel ), iL( 16, 3 ), pList( p ), styleShow3DUIButton( 0, this, utf8_to_unicode( _LT( "&3D buttons" ) ).data(), 0, g_WcmConfig.styleShow3DUI ), colorStatic( 0, this, utf8_to_unicode( _LT( "Colors:" ) ).data() ), styleList( 0, this, 1, 5, ComboBox::READONLY ), showStatic( 0, this, utf8_to_unicode( _LT( "Items:" ) ).data() ), showToolbarButton( 0, this, utf8_to_unicode( _LT( "Show &toolbar" ) ).data(), 0, g_WcmConfig.styleShowToolBar ), showButtonbarButton( 0, this, utf8_to_unicode( _LT( "Show b&uttonbar" ) ).data(), 0, g_WcmConfig.styleShowButtonBar ), showButtonbarIconsButton( 0, this, utf8_to_unicode( _LT( "Show buttonbar &icons" ) ).data(), 0, g_WcmConfig.styleShowButtonBarIcons ), showMenubarButton( 0, this, utf8_to_unicode( _LT( "Show &menubar" ) ).data(), 0, g_WcmConfig.styleShowMenuBar ), fontsStatic( 0, this, utf8_to_unicode( _LT( "Fonts:" ) ).data() ), fontList( Win::WT_CHILD, WH_TABFOCUS | WH_CLICKFOCUS, 0, this, VListWin::SINGLE_SELECT, VListWin::BORDER_3D, 0 ), fontNameStatic( 0, this, utf8_to_unicode( "--------------------------------------------------" ).data() ), changeButton( 0, this, utf8_to_unicode( _LT( "Set &font..." ) ).data(), CMD_CHFONT ), changeX11Button( 0, this, utf8_to_unicode( _LT( "Set &X11 font..." ) ).data(), CMD_CHFONTX11 ) { iL.AddWinAndEnable( &styleShow3DUIButton, 0, 1 ); iL.AddWinAndEnable( &colorStatic, 1, 0 ); iL.AddWinAndEnable( &styleList, 2, 1 ); iL.AddWinAndEnable( &showStatic, 5, 0 ); iL.AddWinAndEnable( &showToolbarButton, 6, 1 ); iL.AddWinAndEnable( &showButtonbarButton, 7, 1 ); iL.AddWinAndEnable( &showButtonbarIconsButton, 8, 1 ); iL.AddWinAndEnable( &showMenubarButton, 9, 1 ); iL.LineSet( 10, 10 ); iL.AddWinAndEnable( &fontsStatic, 11, 0 ); iL.ColSet( 0, 12, 12, 12 ); iL.SetColGrowth( 1 ); for ( int i = 0; i < pList->count(); i++ ) { fontList.Append( utf8_to_unicode( pList->get( i ).name.data() ).data(), i ); } fontList.MoveCurrent( 0 ); RefreshFontInfo(); LSize lsize = fontList.GetLSize(); lsize.y.minimal = lsize.y.ideal = 100; lsize.y.maximal = 1000; lsize.x.minimal = lsize.x.ideal = 300; lsize.x.maximal = 1000; fontList.SetLSize( lsize ); iL.AddWinAndEnable( &fontList, 11, 1 ); fontNameStatic.Enable(); fontNameStatic.Show(); lsize = fontNameStatic.GetLSize(); lsize.x.minimal = 500; lsize.x.maximal = 1000; fontNameStatic.SetLSize( lsize ); iL.AddWin( &fontNameStatic, 12, 1 ); #ifdef USEFREETYPE iL.AddWinAndEnable( &changeButton, 13, 1 ); #endif #ifdef _WIN32 iL.AddWinAndEnable( &changeButton, 13, 1 ); #else iL.AddWinAndEnable( &changeX11Button, 14, 1 ); iL.LineSet( 13, 10 ); #endif #ifdef USEFREETYPE LSize l1 = changeButton.GetLSize(); LSize l2 = changeX11Button.GetLSize(); if ( l1.x.minimal < l2.x.minimal ) { l1.x.minimal = l2.x.minimal; } l1.x.maximal = l1.x.minimal; changeButton.SetLSize( l1 ); changeX11Button.SetLSize( l1 ); #endif AddLayout( &iL ); SetEnterCmd( CMD_OK ); auto styles = GetColorStyles(); for ( auto style : styles ) { styleList.Append( style.c_str() ); } auto it = std::find( styles.begin(), styles.end(), g_WcmConfig.styleColorTheme); int index = it == styles.end() ? 0 : (int) std::distance(styles.begin(), it); styleList.MoveCurrent( index ); styleList.SetFocus(); order.append( &styleShow3DUIButton ); order.append( &styleList ); order.append( &showToolbarButton ); order.append( &showButtonbarButton ); order.append( &showButtonbarIconsButton ); order.append( &showMenubarButton ); order.append( &fontList ); order.append( &changeButton ); order.append( &changeX11Button ); SetPosition(); } bool StyleOptDialog::Command( int id, int subId, Win* win, void* data ) { if ( win == &fontList ) { RefreshFontInfo(); return true; } #ifdef _WIN32 if ( id == CMD_CHFONT ) { int count = pList->count(); int cur = fontList.GetCurrent(); if ( count <= 0 || cur < 0 || cur >= count ) { return true; } LOGFONT lf; std::string* pUri = pList->get( fontList.GetCurrentInt() ).pUri; cfont::UriToLogFont( &lf, pUri && pUri->data() ? pUri->data() : 0 ); CHOOSEFONT cf; memset( &cf, 0, sizeof( cf ) ); cf.lStructSize = sizeof( cf ); cf.hwndOwner = GetID(); cf.lpLogFont = &lf; cf.Flags = CF_SCREENFONTS | CF_EFFECTS | CF_INITTOLOGFONTSTRUCT ; if ( pList->get( fontList.GetCurrentInt() ).fixed ) { cf.Flags |= CF_FIXEDPITCHONLY; } if ( ChooseFont( &cf ) ) { clPtr<cfont> p = new cfont( cfont::LogFontToUru( lf ).data() ); if ( p.ptr() ) { pList->get( fontList.GetCurrentInt() ).newFont = p; RefreshFontInfo(); } } return true; } #else if ( id == CMD_CHFONT ) { int count = pList->count(); int cur = fontList.GetCurrent(); if ( count <= 0 || cur < 0 || cur >= count ) { return true; } std::string* pUri = pList->get( fontList.GetCurrentInt() ).pUri; clPtr<cfont> p = SelectFTFont( ( NCDialogParent* )Parent(), pList->get( fontList.GetCurrentInt() ).fixed, ( pUri && !pUri->empty() ) ? pUri->c_str() : nullptr ); if ( p.ptr() ) { pList->get( fontList.GetCurrentInt() ).newFont = p; RefreshFontInfo(); } return true; } if ( id == CMD_CHFONTX11 ) { int count = pList->count(); int cur = fontList.GetCurrent(); if ( count <= 0 || cur < 0 || cur >= count ) { return true; } clPtr<cfont> p = SelectX11Font( ( NCDialogParent* )Parent(), pList->get( fontList.GetCurrentInt() ).fixed ); if ( p.ptr() ) { pList->get( fontList.GetCurrentInt() ).newFont = p; RefreshFontInfo(); } return true; } #endif return NCVertDialog::Command( id, subId, win, data ); } bool StyleOptDialog::EventChildKey( Win* child, cevent_key* pEvent ) { if ( pEvent->Type() == EV_KEYDOWN ) { bool IsReturn = ( pEvent->Key() == VK_RETURN ) && ( child == &changeButton || child == &changeX11Button ); bool IsUpDown = ( pEvent->Key() == VK_UP || pEvent->Key() == VK_DOWN ) && child == &fontList; if ( IsReturn || IsUpDown ) { return false; } }; return NCVertDialog::EventChildKey( child, pEvent ); } bool DoStyleConfigDialog( NCDialogParent* parent ) { g_WcmConfig.ImpCurrentFonts(); ccollect<StyleOptDialog::Node> list; list.append( StyleOptDialog::Node( _LT( "Panel" ) , false, g_PanelFont.ptr(), &g_WcmConfig.panelFontUri ) ); list.append( StyleOptDialog::Node( _LT( "Dialog" ), false, g_DialogFont.ptr(), &g_WcmConfig.dialogFontUri ) ); list.append( StyleOptDialog::Node( _LT( "Viewer" ), true, g_ViewerFont.ptr(), &g_WcmConfig.viewerFontUri ) ); list.append( StyleOptDialog::Node( _LT( "Editor" ), true, g_EditorFont.ptr(), &g_WcmConfig.editorFontUri ) ); list.append( StyleOptDialog::Node( _LT( "Terminal" ), true, g_TerminalFont.ptr(), &g_WcmConfig.terminalFontUri ) ); list.append( StyleOptDialog::Node( _LT( "Help text" ), false, g_HelpTextFont.ptr(), &g_WcmConfig.helpTextFontUri ) ); list.append( StyleOptDialog::Node( _LT( "Help bold text" ), false, g_HelpBoldFont.ptr(), &g_WcmConfig.helpBoldFontUri ) ); list.append( StyleOptDialog::Node( _LT( "Help header text" ), false, g_HelpHeadFont.ptr(), &g_WcmConfig.helpHeadFontUri ) ); StyleOptDialog dlg( parent, &list ); if ( dlg.DoModal() == CMD_OK ) { g_WcmConfig.styleColorTheme = dlg.styleList.GetTextStr(); SetColorStyle( g_WcmConfig.styleColorTheme); g_WcmConfig.styleShow3DUI = dlg.styleShow3DUIButton.IsSet(); g_WcmConfig.styleShowToolBar = dlg.showToolbarButton.IsSet( ); g_WcmConfig.styleShowButtonBar = dlg.showButtonbarButton.IsSet( ); g_WcmConfig.styleShowButtonBarIcons = dlg.showButtonbarIconsButton.IsSet( ); g_WcmConfig.styleShowMenuBar = dlg.showMenubarButton.IsSet( ); for ( int i = 0; i < list.count(); i++ ) { if ( list[i].newFont.ptr() && list[i].newFont->uri()[0] && list[i].pUri ) { *( list[i].pUri ) = list[i].newFont->uri(); } } if ( parent ) { parent->Command( CMD_MENU_INFO, SCMD_MENU_CANCEL, nullptr, nullptr ); } return true; } return false; } struct LangListNode { std::string id; std::string name; LangListNode() {} LangListNode( const char* i, const char* n ): id( i ), name( n ) {} }; class CfgLangDialog: public NCDialog { TextList _list; ccollect<LangListNode>* nodeList; public: CfgLangDialog( NCDialogParent* parent, const char* id, ccollect<LangListNode>* nl ) : NCDialog( createDialogAsChild, 0, parent, utf8_to_unicode( _LT( "Language" ) ).data(), bListOkCancel ), _list( Win::WT_CHILD, Win::WH_TABFOCUS | WH_CLICKFOCUS, 0, this, VListWin::SINGLE_SELECT, VListWin::BORDER_3D, 0 ), nodeList( nl ) { _list.Append( utf8_to_unicode( _LT( "Autodetect" ) ).data() ); //0 _list.Append( utf8_to_unicode( _LT( "English" ) ).data() ); //1 for ( int i = 0; i < nl->count(); i++ ) { _list.Append( utf8_to_unicode( nl->get( i ).name.data() ).data() ); } int cur = 0; if ( id[0] == '+' ) { cur = 0; } else if ( id[0] == '-' ) { cur = 1; } else { for ( int i = 0; i < nl->count(); i++ ) if ( !strcmp( id, nl->get( i ).id.data() ) ) { cur = i + 2; break; } } _list.MoveCurrent( cur ); _list.Enable(); _list.Show(); _list.SetFocus(); LSRange h( 10, 1000, 10 ); LSRange w( 50, 1000, 30 ); _list.SetHeightRange( h ); //in characters _list.SetWidthRange( w ); //in characters AddWin( &_list ); SetEnterCmd( CMD_OK ); SetPosition(); }; const char* GetId(); virtual bool Command( int id, int subId, Win* win, void* data ); virtual ~CfgLangDialog(); }; const char* CfgLangDialog::GetId() { int n = _list.GetCurrent(); if ( n <= 0 ) { return "+"; } if ( n == 1 ) { return "-"; } n -= 2; if ( n >= nodeList->count() ) { return "+"; } return nodeList->get( n ).id.data(); } bool CfgLangDialog::Command( int id, int subId, Win* win, void* data ) { if ( id == CMD_ITEM_CLICK && win == &_list ) { EndModal( CMD_OK ); } return NCDialog::Command( id, subId, win, data ); } CfgLangDialog::~CfgLangDialog() {} inline bool IsSpace( char c ) { return c > 0 && c <= 0x20; } static bool LangListLoad( sys_char_t* fileName, ccollect<LangListNode>& list ) { list.clear(); try { BFile f; f.Open( fileName ); char buf[4096]; while ( f.GetStr( buf, sizeof( buf ) ) ) { char* s = buf; while ( IsSpace( *s ) ) { s++; } if ( *s == '#' ) { continue; } if ( !*s ) { continue; } ccollect<char, 0x100> id; ccollect<char, 0x100> name; while ( *s && !IsSpace( *s ) ) { id.append( *s ); s++; } while ( IsSpace( *s ) ) { s++; } int lastNs = -1; for ( int i = 0; *s; i++, s++ ) { if ( *s == '#' ) { break; } if ( !IsSpace( *s ) ) { lastNs = i; } name.append( *s ); } if ( id.count() <= 0 || lastNs < 0 ) { continue; } id.append( 0 ); name.append( 0 ); name[lastNs + 1] = 0; LangListNode( id.ptr(), name.ptr() ); list.append( LangListNode( id.ptr(), name.ptr() ) ); } } catch ( cexception* ex ) { ex->destroy(); return false; } return true; } //////////////////////////////// SysOptDlg class SysOptDialog: public NCVertDialog { Layout m_iL; public: std::string m_CurLangId; ccollect<LangListNode> m_List; void SetCurLang( const char* id ); SButton m_AskOpenExecButton; SButton m_EscPanelButton; SButton m_EscCommandLineButton; SButton m_BackUpDirButton; SButton m_AutoCompleteButton; SButton m_AutoSaveSetupButton; SButton m_ShowHostNameButton; SButton m_StorePasswordsButton; SButton m_TotalProgressIndicatorButton; StaticLabel m_LangStatic; StaticLine m_LangVal; Button m_LangButton; SysOptDialog( NCDialogParent* parent ); virtual bool Command( int id, int subId, Win* win, void* data ); virtual bool EventChildKey( Win* child, cevent_key* pEvent ); virtual ~SysOptDialog(); }; void SysOptDialog::SetCurLang( const char* id ) { m_CurLangId = std::string( id ); if ( id[0] == '-' ) { m_LangVal.SetText( utf8_to_unicode( _LT( "English" ) ).data() ); } else if ( id[0] == '+' ) { m_LangVal.SetText( utf8_to_unicode( _LT( "Autodetect" ) ).data() ); } else { for ( int i = 0; i < m_List.count(); i++ ) { if ( !strcmp( m_List[i].id.data(), id ) ) { m_LangVal.SetText( utf8_to_unicode( m_List[i].name.data( ) ).data( ) ); return; } } m_LangVal.SetText( utf8_to_unicode( id ).data( ) ); } } SysOptDialog::~SysOptDialog() {} SysOptDialog::SysOptDialog( NCDialogParent* parent ) : NCVertDialog( ::createDialogAsChild, 0, parent, utf8_to_unicode( _LT( "System settings" ) ).data(), bListOkCancel ) , m_iL( 16, 3 ) , m_AskOpenExecButton( 0, this, utf8_to_unicode( _LT( "Ask user if Exec/Open conflict" ) ).data(), 0, g_WcmConfig.systemAskOpenExec ) , m_EscPanelButton( 0, this, utf8_to_unicode( _LT( "Enable &ESC key to show/hide panels" ) ).data(), 0, g_WcmConfig.systemEscPanel ) , m_EscCommandLineButton( 0, this, utf8_to_unicode( _LT( "Enable &ESC key to clear the command line" ) ).data(), 0, g_WcmConfig.systemEscCommandLine ) , m_BackUpDirButton( 0, this, utf8_to_unicode( _LT( "Enable &BACKSPACE key to go up dir" ) ).data(), 0, g_WcmConfig.systemBackSpaceUpDir ) , m_AutoCompleteButton( 0, this, utf8_to_unicode( _LT( "Enable &autocomplete" ) ).data(), 0, g_WcmConfig.systemAutoComplete ) , m_AutoSaveSetupButton( 0, this, utf8_to_unicode( _LT( "Auto &save setup" ) ).data(), 0, g_WcmConfig.systemAutoSaveSetup ) , m_ShowHostNameButton( 0, this, utf8_to_unicode( _LT( "Show &host name" ) ).data(), 0, g_WcmConfig.systemShowHostName ) , m_StorePasswordsButton( 0, this, utf8_to_unicode( _LT( "Store &passwords" ) ).data(), 0, g_WcmConfig.systemStorePasswords ) , m_TotalProgressIndicatorButton( 0, this, utf8_to_unicode( _LT( "Enable total progress indicator" ) ).data(), 0, g_WcmConfig.systemTotalProgressIndicator ) , m_LangStatic( 0, this, utf8_to_unicode( _LT( "&Language:" ) ).data( ), &m_LangButton ) , m_LangVal( 0, this, utf8_to_unicode( "______________________" ).data( ) ) , m_LangButton( 0, this, utf8_to_unicode( ">" ).data( ), 1000 ) { #ifndef _WIN32 m_iL.AddWinAndEnable( &m_AskOpenExecButton, 0, 0, 0, 2 ); #endif m_iL.AddWinAndEnable( &m_EscPanelButton, 1, 0, 1, 2 ); m_iL.AddWinAndEnable( &m_EscCommandLineButton, 2, 0, 2, 2 ); m_iL.AddWinAndEnable( &m_BackUpDirButton, 3, 0, 3, 2 ); m_iL.AddWinAndEnable( &m_AutoCompleteButton, 4, 0, 4, 2 ); m_iL.AddWinAndEnable( &m_AutoSaveSetupButton, 5, 0, 5, 2 ); m_iL.AddWinAndEnable( &m_ShowHostNameButton, 6, 0, 6, 2 ); m_iL.AddWinAndEnable( &m_StorePasswordsButton, 7, 0, 7, 2 ); m_iL.AddWinAndEnable( &m_TotalProgressIndicatorButton, 8, 0, 8, 2 ); m_iL.AddWinAndEnable( &m_LangStatic, 9, 0 ); m_iL.AddWinAndEnable( &m_LangVal, 9, 2 ); m_iL.AddWinAndEnable( &m_LangButton, 9, 1 ); m_iL.SetColGrowth( 2 ); AddLayout( &m_iL ); SetEnterCmd( CMD_OK ); #ifndef _WIN32 m_AskOpenExecButton.SetFocus(); order.append( &m_AskOpenExecButton ); #endif order.append( &m_EscPanelButton ); order.append( &m_EscCommandLineButton ); order.append( &m_BackUpDirButton ); order.append( &m_AutoCompleteButton ); order.append( &m_AutoSaveSetupButton ); order.append( &m_ShowHostNameButton ); order.append( &m_StorePasswordsButton ); order.append( &m_TotalProgressIndicatorButton ); order.append( &m_LangButton ); SetPosition(); #ifdef _WIN32 LangListLoad( carray_cat<sys_char_t>( GetAppPath( ).data( ), utf8_to_sys( "\\lang\\list" ).data( ) ).data( ), m_List ); #else if ( !LangListLoad( utf8_to_sys( "install-files/share/wcm/lang/list" ).data(), m_List ) ) { LangListLoad( utf8_to_sys( UNIX_CONFIG_DIR_PATH "/lang/list" ).data(), m_List ); } #endif SetCurLang( g_WcmConfig.systemLang.data() ? g_WcmConfig.systemLang.data() : "+" ); } bool SysOptDialog::Command( int id, int subId, Win* win, void* data ) { if ( id == 1000 ) { CfgLangDialog dlg( ( NCDialogParent* )Parent(), m_CurLangId.c_str(), &m_List ); if ( dlg.DoModal() == CMD_OK ) { SetCurLang( dlg.GetId() ); } return true; } return NCVertDialog::Command( id, subId, win, data ); } bool SysOptDialog::EventChildKey( Win* child, cevent_key* pEvent ) { if ( pEvent->Type() == EV_KEYDOWN ) { if ( pEvent->Key() == VK_RETURN && m_LangButton.InFocus() ) //prevent autoenter { return false; } }; return NCVertDialog::EventChildKey( child, pEvent ); } bool DoSystemConfigDialog( NCDialogParent* parent ) { SysOptDialog dlg( parent ); if ( dlg.DoModal() == CMD_OK ) { g_WcmConfig.systemAskOpenExec = dlg.m_AskOpenExecButton.IsSet(); g_WcmConfig.systemEscPanel = dlg.m_EscPanelButton.IsSet(); g_WcmConfig.systemEscCommandLine = dlg.m_EscCommandLineButton.IsSet(); g_WcmConfig.systemBackSpaceUpDir = dlg.m_BackUpDirButton.IsSet( ); g_WcmConfig.systemAutoComplete = dlg.m_AutoCompleteButton.IsSet( ); g_WcmConfig.systemAutoSaveSetup = dlg.m_AutoSaveSetupButton.IsSet( ); g_WcmConfig.systemShowHostName = dlg.m_ShowHostNameButton.IsSet( ); g_WcmConfig.systemStorePasswords = dlg.m_StorePasswordsButton.IsSet( ); g_WcmConfig.systemTotalProgressIndicator = dlg.m_TotalProgressIndicatorButton.IsSet( ); const char* s = g_WcmConfig.systemLang.data(); if ( !s ) { s = "+"; } bool langChanged = strcmp( dlg.m_CurLangId.data( ), s ) != 0; g_WcmConfig.systemLang = dlg.m_CurLangId.data( ); if ( langChanged ) { NCMessageBox( parent, _LT( "Note" ), _LT( "Language changed. \nFor effect you must save config and restart" ), false ); } return true; } return false; } ////////////////////////// TerminalOptDialog class TerminalOptDialog: public NCVertDialog { Layout iL; public: StaticLine backspaceKeyStatic; SButton backspaceAsciiButton; SButton backspaceCtrlHButton; TerminalOptDialog( NCDialogParent* parent ); //virtual bool EventChildKey(Win* child, cevent_key* pEvent); //virtual bool Command(int id, int subId, Win *win, void *data); virtual ~TerminalOptDialog(); }; TerminalOptDialog::TerminalOptDialog( NCDialogParent* parent ) : NCVertDialog( ::createDialogAsChild, 0, parent, utf8_to_unicode( _LT( "Terminal options" ) ).data(), bListOkCancel ), iL( 16, 3 ), backspaceKeyStatic( 0, this, utf8_to_unicode( _LT( "Backspace key:" ) ).data() ), backspaceAsciiButton( 0, this, utf8_to_unicode( "ASCII DEL" ).data(), 1, g_WcmConfig.terminalBackspaceKey == 0 ), backspaceCtrlHButton( 0, this, utf8_to_unicode( "Ctrl H" ).data(), 1, g_WcmConfig.terminalBackspaceKey == 1 ) { iL.AddWin( &backspaceKeyStatic, 0, 0, 0, 1 ); backspaceKeyStatic.Enable(); backspaceKeyStatic.Show(); iL.AddWin( &backspaceAsciiButton, 1, 1 ); backspaceAsciiButton.Enable(); backspaceAsciiButton.Show(); iL.AddWin( &backspaceCtrlHButton, 2, 1 ); backspaceCtrlHButton.Enable(); backspaceCtrlHButton.Show(); iL.ColSet( 0, 10, 10, 10 ); iL.SetColGrowth( 1 ); AddLayout( &iL ); SetEnterCmd( CMD_OK ); backspaceAsciiButton.SetFocus(); order.append( &backspaceAsciiButton ); order.append( &backspaceCtrlHButton ); SetPosition(); } TerminalOptDialog::~TerminalOptDialog() {} bool DoTerminalConfigDialog( NCDialogParent* parent ) { TerminalOptDialog dlg( parent ); if ( dlg.DoModal() == CMD_OK ) { g_WcmConfig.terminalBackspaceKey = dlg.backspaceCtrlHButton.IsSet() ? 1 : 0; return true; } return false; }
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemConsumable_Egg_Allo_Gen2_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass PrimalItemConsumable_Egg_Allo_Gen2.PrimalItemConsumable_Egg_Allo_Gen2_C // 0x0000 (0x0AF8 - 0x0AF8) class UPrimalItemConsumable_Egg_Allo_Gen2_C : public UPrimalItemConsumable_Egg_Allo_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItemConsumable_Egg_Allo_Gen2.PrimalItemConsumable_Egg_Allo_Gen2_C"); return ptr; } void ExecuteUbergraph_PrimalItemConsumable_Egg_Allo_Gen2(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
#include"../localedef.h" namespace fast_io_i18n { namespace { inline constexpr std::size_t numeric_grouping_storage[]{3}; inline constexpr lc_all lc_all_global{.identification={.name=tsc("mai_NP"),.encoding=tsc(FAST_IO_LOCALE_ENCODING),.title=tsc("Maithili language locale for Nepal"),.source=tsc("Samsung Electronics Co., Ltd.\t\t;\t\tfast_io"),.address=tsc("https://gitee.com/qabeowjbtkwb/fast_io\t\t;\t\thttps://github.com/cppfastio/fast_io"),.contact=tsc("fast_io"),.email=tsc("akhilesh.k@samusng.com;euloanty@live.com"),.tel=tsc(""),.fax=tsc(""),.language=tsc("Maithili"),.territory=tsc("Nepal"),.revision=tsc("1.0"),.date=tsc("2017-07-24")},.monetary={.int_curr_symbol=tsc("NPR "),.currency_symbol=tsc("रू"),.mon_decimal_point=tsc("."),.mon_thousands_sep=tsc(","),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(""),.negative_sign=tsc("-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc("."),.thousands_sep=tsc(","),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc("रवि"),tsc("सोम"),tsc("मंगल"),tsc("बुध"),tsc("बृहस्पती"),tsc("शुक्र"),tsc("शनी")},.day={tsc("रविदिन"),tsc("सोमदिन"),tsc("मंगलदिन"),tsc("बुधदिन"),tsc("बृहस्पतीदिन"),tsc("शुक्रदिन"),tsc("शनीदिन")},.abmon={tsc("बैसाख"),tsc("जेठ"),tsc("अषाढ़"),tsc("सावोन"),tsc("भादो"),tsc("आसिन"),tsc("कातिक"),tsc("अगहन"),tsc("पूस"),tsc("माघ"),tsc("फागुन"),tsc("चैति")},.mon={tsc("बैसाख"),tsc("जेठ"),tsc("अषाढ़"),tsc("सावोन"),tsc("भादो"),tsc("आसिन"),tsc("कातिक"),tsc("अगहन"),tsc("पूस"),tsc("माघ"),tsc("फागुन"),tsc("चैति")},.d_t_fmt=tsc("%A %d %b %Y %I:%M:%S %p"),.d_fmt=tsc("%-d//%-m//%y"),.t_fmt=tsc("%I:%M:%S %p %Z"),.t_fmt_ampm=tsc("%I:%M:%S %p %Z"),.date_fmt=tsc("%A %d %b %Y %I:%M:%S %p %Z"),.am_pm={tsc("पूर्वाह्न"),tsc("अपराह्न")},.week={7,19971130,1}},.messages={.yesexpr=tsc("^[+1yYह]"),.noexpr=tsc("^[-0nNन]"),.yesstr=tsc("हाँ"),.nostr=tsc("नहीं")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc("+%c %a%t%l"),.int_select=tsc("00"),.int_prefix=tsc("977")},.name={.name_fmt=tsc("%p%t%f%t%g"),.name_gen=tsc(""),.name_miss=tsc("कुमारी"),.name_mr=tsc("श्रीमान्"),.name_mrs=tsc("श्रीमती"),.name_ms=tsc("सुश्री")},.address={.postal_fmt=tsc("%f%N%h%s%N%T"),.country_name=tsc("नेपाल"),.country_ab2=tsc("NP"),.country_ab3=tsc("NPL"),.country_num=524,.country_car=tsc("NEP"),.lang_name=tsc("मैथिली"),.lang_term=tsc("mai"),.lang_lib=tsc("mai")},.measurement={.measurement=1}}; inline constexpr wlc_all wlc_all_global{.identification={.name=tsc(L"mai_NP"),.encoding=tsc(FAST_IO_LOCALE_LENCODING),.title=tsc(L"Maithili language locale for Nepal"),.source=tsc(L"Samsung Electronics Co., Ltd.\t\t;\t\tfast_io"),.address=tsc(L"https://gitee.com/qabeowjbtkwb/fast_io\t\t;\t\thttps://github.com/cppfastio/fast_io"),.contact=tsc(L"fast_io"),.email=tsc(L"akhilesh.k@samusng.com;euloanty@live.com"),.tel=tsc(L""),.fax=tsc(L""),.language=tsc(L"Maithili"),.territory=tsc(L"Nepal"),.revision=tsc(L"1.0"),.date=tsc(L"2017-07-24")},.monetary={.int_curr_symbol=tsc(L"NPR "),.currency_symbol=tsc(L"रू"),.mon_decimal_point=tsc(L"."),.mon_thousands_sep=tsc(L","),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(L""),.negative_sign=tsc(L"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(L"."),.thousands_sep=tsc(L","),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(L"रवि"),tsc(L"सोम"),tsc(L"मंगल"),tsc(L"बुध"),tsc(L"बृहस्पती"),tsc(L"शुक्र"),tsc(L"शनी")},.day={tsc(L"रविदिन"),tsc(L"सोमदिन"),tsc(L"मंगलदिन"),tsc(L"बुधदिन"),tsc(L"बृहस्पतीदिन"),tsc(L"शुक्रदिन"),tsc(L"शनीदिन")},.abmon={tsc(L"बैसाख"),tsc(L"जेठ"),tsc(L"अषाढ़"),tsc(L"सावोन"),tsc(L"भादो"),tsc(L"आसिन"),tsc(L"कातिक"),tsc(L"अगहन"),tsc(L"पूस"),tsc(L"माघ"),tsc(L"फागुन"),tsc(L"चैति")},.mon={tsc(L"बैसाख"),tsc(L"जेठ"),tsc(L"अषाढ़"),tsc(L"सावोन"),tsc(L"भादो"),tsc(L"आसिन"),tsc(L"कातिक"),tsc(L"अगहन"),tsc(L"पूस"),tsc(L"माघ"),tsc(L"फागुन"),tsc(L"चैति")},.d_t_fmt=tsc(L"%A %d %b %Y %I:%M:%S %p"),.d_fmt=tsc(L"%-d//%-m//%y"),.t_fmt=tsc(L"%I:%M:%S %p %Z"),.t_fmt_ampm=tsc(L"%I:%M:%S %p %Z"),.date_fmt=tsc(L"%A %d %b %Y %I:%M:%S %p %Z"),.am_pm={tsc(L"पूर्वाह्न"),tsc(L"अपराह्न")},.week={7,19971130,1}},.messages={.yesexpr=tsc(L"^[+1yYह]"),.noexpr=tsc(L"^[-0nNन]"),.yesstr=tsc(L"हाँ"),.nostr=tsc(L"नहीं")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(L"+%c %a%t%l"),.int_select=tsc(L"00"),.int_prefix=tsc(L"977")},.name={.name_fmt=tsc(L"%p%t%f%t%g"),.name_gen=tsc(L""),.name_miss=tsc(L"कुमारी"),.name_mr=tsc(L"श्रीमान्"),.name_mrs=tsc(L"श्रीमती"),.name_ms=tsc(L"सुश्री")},.address={.postal_fmt=tsc(L"%f%N%h%s%N%T"),.country_name=tsc(L"नेपाल"),.country_ab2=tsc(L"NP"),.country_ab3=tsc(L"NPL"),.country_num=524,.country_car=tsc(L"NEP"),.lang_name=tsc(L"मैथिली"),.lang_term=tsc(L"mai"),.lang_lib=tsc(L"mai")},.measurement={.measurement=1}}; inline constexpr u8lc_all u8lc_all_global{.identification={.name=tsc(u8"mai_NP"),.encoding=tsc(FAST_IO_LOCALE_u8ENCODING),.title=tsc(u8"Maithili language locale for Nepal"),.source=tsc(u8"Samsung Electronics Co., Ltd.\t\t;\t\tfast_io"),.address=tsc(u8"https://gitee.com/qabeowjbtkwb/fast_io\t\t;\t\thttps://github.com/cppfastio/fast_io"),.contact=tsc(u8"fast_io"),.email=tsc(u8"akhilesh.k@samusng.com;euloanty@live.com"),.tel=tsc(u8""),.fax=tsc(u8""),.language=tsc(u8"Maithili"),.territory=tsc(u8"Nepal"),.revision=tsc(u8"1.0"),.date=tsc(u8"2017-07-24")},.monetary={.int_curr_symbol=tsc(u8"NPR "),.currency_symbol=tsc(u8"रू"),.mon_decimal_point=tsc(u8"."),.mon_thousands_sep=tsc(u8","),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(u8""),.negative_sign=tsc(u8"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u8"."),.thousands_sep=tsc(u8","),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(u8"रवि"),tsc(u8"सोम"),tsc(u8"मंगल"),tsc(u8"बुध"),tsc(u8"बृहस्पती"),tsc(u8"शुक्र"),tsc(u8"शनी")},.day={tsc(u8"रविदिन"),tsc(u8"सोमदिन"),tsc(u8"मंगलदिन"),tsc(u8"बुधदिन"),tsc(u8"बृहस्पतीदिन"),tsc(u8"शुक्रदिन"),tsc(u8"शनीदिन")},.abmon={tsc(u8"बैसाख"),tsc(u8"जेठ"),tsc(u8"अषाढ़"),tsc(u8"सावोन"),tsc(u8"भादो"),tsc(u8"आसिन"),tsc(u8"कातिक"),tsc(u8"अगहन"),tsc(u8"पूस"),tsc(u8"माघ"),tsc(u8"फागुन"),tsc(u8"चैति")},.mon={tsc(u8"बैसाख"),tsc(u8"जेठ"),tsc(u8"अषाढ़"),tsc(u8"सावोन"),tsc(u8"भादो"),tsc(u8"आसिन"),tsc(u8"कातिक"),tsc(u8"अगहन"),tsc(u8"पूस"),tsc(u8"माघ"),tsc(u8"फागुन"),tsc(u8"चैति")},.d_t_fmt=tsc(u8"%A %d %b %Y %I:%M:%S %p"),.d_fmt=tsc(u8"%-d//%-m//%y"),.t_fmt=tsc(u8"%I:%M:%S %p %Z"),.t_fmt_ampm=tsc(u8"%I:%M:%S %p %Z"),.date_fmt=tsc(u8"%A %d %b %Y %I:%M:%S %p %Z"),.am_pm={tsc(u8"पूर्वाह्न"),tsc(u8"अपराह्न")},.week={7,19971130,1}},.messages={.yesexpr=tsc(u8"^[+1yYह]"),.noexpr=tsc(u8"^[-0nNन]"),.yesstr=tsc(u8"हाँ"),.nostr=tsc(u8"नहीं")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u8"+%c %a%t%l"),.int_select=tsc(u8"00"),.int_prefix=tsc(u8"977")},.name={.name_fmt=tsc(u8"%p%t%f%t%g"),.name_gen=tsc(u8""),.name_miss=tsc(u8"कुमारी"),.name_mr=tsc(u8"श्रीमान्"),.name_mrs=tsc(u8"श्रीमती"),.name_ms=tsc(u8"सुश्री")},.address={.postal_fmt=tsc(u8"%f%N%h%s%N%T"),.country_name=tsc(u8"नेपाल"),.country_ab2=tsc(u8"NP"),.country_ab3=tsc(u8"NPL"),.country_num=524,.country_car=tsc(u8"NEP"),.lang_name=tsc(u8"मैथिली"),.lang_term=tsc(u8"mai"),.lang_lib=tsc(u8"mai")},.measurement={.measurement=1}}; inline constexpr u16lc_all u16lc_all_global{.identification={.name=tsc(u"mai_NP"),.encoding=tsc(FAST_IO_LOCALE_uENCODING),.title=tsc(u"Maithili language locale for Nepal"),.source=tsc(u"Samsung Electronics Co., Ltd.\t\t;\t\tfast_io"),.address=tsc(u"https://gitee.com/qabeowjbtkwb/fast_io\t\t;\t\thttps://github.com/cppfastio/fast_io"),.contact=tsc(u"fast_io"),.email=tsc(u"akhilesh.k@samusng.com;euloanty@live.com"),.tel=tsc(u""),.fax=tsc(u""),.language=tsc(u"Maithili"),.territory=tsc(u"Nepal"),.revision=tsc(u"1.0"),.date=tsc(u"2017-07-24")},.monetary={.int_curr_symbol=tsc(u"NPR "),.currency_symbol=tsc(u"रू"),.mon_decimal_point=tsc(u"."),.mon_thousands_sep=tsc(u","),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(u""),.negative_sign=tsc(u"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u"."),.thousands_sep=tsc(u","),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(u"रवि"),tsc(u"सोम"),tsc(u"मंगल"),tsc(u"बुध"),tsc(u"बृहस्पती"),tsc(u"शुक्र"),tsc(u"शनी")},.day={tsc(u"रविदिन"),tsc(u"सोमदिन"),tsc(u"मंगलदिन"),tsc(u"बुधदिन"),tsc(u"बृहस्पतीदिन"),tsc(u"शुक्रदिन"),tsc(u"शनीदिन")},.abmon={tsc(u"बैसाख"),tsc(u"जेठ"),tsc(u"अषाढ़"),tsc(u"सावोन"),tsc(u"भादो"),tsc(u"आसिन"),tsc(u"कातिक"),tsc(u"अगहन"),tsc(u"पूस"),tsc(u"माघ"),tsc(u"फागुन"),tsc(u"चैति")},.mon={tsc(u"बैसाख"),tsc(u"जेठ"),tsc(u"अषाढ़"),tsc(u"सावोन"),tsc(u"भादो"),tsc(u"आसिन"),tsc(u"कातिक"),tsc(u"अगहन"),tsc(u"पूस"),tsc(u"माघ"),tsc(u"फागुन"),tsc(u"चैति")},.d_t_fmt=tsc(u"%A %d %b %Y %I:%M:%S %p"),.d_fmt=tsc(u"%-d//%-m//%y"),.t_fmt=tsc(u"%I:%M:%S %p %Z"),.t_fmt_ampm=tsc(u"%I:%M:%S %p %Z"),.date_fmt=tsc(u"%A %d %b %Y %I:%M:%S %p %Z"),.am_pm={tsc(u"पूर्वाह्न"),tsc(u"अपराह्न")},.week={7,19971130,1}},.messages={.yesexpr=tsc(u"^[+1yYह]"),.noexpr=tsc(u"^[-0nNन]"),.yesstr=tsc(u"हाँ"),.nostr=tsc(u"नहीं")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u"+%c %a%t%l"),.int_select=tsc(u"00"),.int_prefix=tsc(u"977")},.name={.name_fmt=tsc(u"%p%t%f%t%g"),.name_gen=tsc(u""),.name_miss=tsc(u"कुमारी"),.name_mr=tsc(u"श्रीमान्"),.name_mrs=tsc(u"श्रीमती"),.name_ms=tsc(u"सुश्री")},.address={.postal_fmt=tsc(u"%f%N%h%s%N%T"),.country_name=tsc(u"नेपाल"),.country_ab2=tsc(u"NP"),.country_ab3=tsc(u"NPL"),.country_num=524,.country_car=tsc(u"NEP"),.lang_name=tsc(u"मैथिली"),.lang_term=tsc(u"mai"),.lang_lib=tsc(u"mai")},.measurement={.measurement=1}}; inline constexpr u32lc_all u32lc_all_global{.identification={.name=tsc(U"mai_NP"),.encoding=tsc(FAST_IO_LOCALE_UENCODING),.title=tsc(U"Maithili language locale for Nepal"),.source=tsc(U"Samsung Electronics Co., Ltd.\t\t;\t\tfast_io"),.address=tsc(U"https://gitee.com/qabeowjbtkwb/fast_io\t\t;\t\thttps://github.com/cppfastio/fast_io"),.contact=tsc(U"fast_io"),.email=tsc(U"akhilesh.k@samusng.com;euloanty@live.com"),.tel=tsc(U""),.fax=tsc(U""),.language=tsc(U"Maithili"),.territory=tsc(U"Nepal"),.revision=tsc(U"1.0"),.date=tsc(U"2017-07-24")},.monetary={.int_curr_symbol=tsc(U"NPR "),.currency_symbol=tsc(U"रू"),.mon_decimal_point=tsc(U"."),.mon_thousands_sep=tsc(U","),.mon_grouping={numeric_grouping_storage,1},.positive_sign=tsc(U""),.negative_sign=tsc(U"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=1,.p_sep_by_space=1,.n_cs_precedes=1,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(U"."),.thousands_sep=tsc(U","),.grouping={numeric_grouping_storage,1}},.time={.abday={tsc(U"रवि"),tsc(U"सोम"),tsc(U"मंगल"),tsc(U"बुध"),tsc(U"बृहस्पती"),tsc(U"शुक्र"),tsc(U"शनी")},.day={tsc(U"रविदिन"),tsc(U"सोमदिन"),tsc(U"मंगलदिन"),tsc(U"बुधदिन"),tsc(U"बृहस्पतीदिन"),tsc(U"शुक्रदिन"),tsc(U"शनीदिन")},.abmon={tsc(U"बैसाख"),tsc(U"जेठ"),tsc(U"अषाढ़"),tsc(U"सावोन"),tsc(U"भादो"),tsc(U"आसिन"),tsc(U"कातिक"),tsc(U"अगहन"),tsc(U"पूस"),tsc(U"माघ"),tsc(U"फागुन"),tsc(U"चैति")},.mon={tsc(U"बैसाख"),tsc(U"जेठ"),tsc(U"अषाढ़"),tsc(U"सावोन"),tsc(U"भादो"),tsc(U"आसिन"),tsc(U"कातिक"),tsc(U"अगहन"),tsc(U"पूस"),tsc(U"माघ"),tsc(U"फागुन"),tsc(U"चैति")},.d_t_fmt=tsc(U"%A %d %b %Y %I:%M:%S %p"),.d_fmt=tsc(U"%-d//%-m//%y"),.t_fmt=tsc(U"%I:%M:%S %p %Z"),.t_fmt_ampm=tsc(U"%I:%M:%S %p %Z"),.date_fmt=tsc(U"%A %d %b %Y %I:%M:%S %p %Z"),.am_pm={tsc(U"पूर्वाह्न"),tsc(U"अपराह्न")},.week={7,19971130,1}},.messages={.yesexpr=tsc(U"^[+1yYह]"),.noexpr=tsc(U"^[-0nNन]"),.yesstr=tsc(U"हाँ"),.nostr=tsc(U"नहीं")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(U"+%c %a%t%l"),.int_select=tsc(U"00"),.int_prefix=tsc(U"977")},.name={.name_fmt=tsc(U"%p%t%f%t%g"),.name_gen=tsc(U""),.name_miss=tsc(U"कुमारी"),.name_mr=tsc(U"श्रीमान्"),.name_mrs=tsc(U"श्रीमती"),.name_ms=tsc(U"सुश्री")},.address={.postal_fmt=tsc(U"%f%N%h%s%N%T"),.country_name=tsc(U"नेपाल"),.country_ab2=tsc(U"NP"),.country_ab3=tsc(U"NPL"),.country_num=524,.country_car=tsc(U"NEP"),.lang_name=tsc(U"मैथिली"),.lang_term=tsc(U"mai"),.lang_lib=tsc(U"mai")},.measurement={.measurement=1}}; } } #include"../main.h"
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/providers/nuphar/kernel.h" #include "core/codegen/passes/utils/codegen_context.h" #include "core/codegen/common/profile.h" #include "core/framework/tensorprotoutils.h" #include "core/providers/nuphar/common/analysis/subgraph_codegen_stats.h" #include "core/providers/nuphar/compiler/initializer_info.h" #include "core/providers/nuphar/nuphar_execution_provider.h" #include "core/providers/nuphar/partition/subgraph_partitioner.h" #include "core/providers/nuphar/runtime/sequential/basic.h" #include "core/providers/nuphar/runtime/sequential/loop.h" namespace onnxruntime { namespace nuphar { thread_local std::unique_ptr<NupharFuncStateToComputeCtxMap> NupharKernelState::nuphar_compute_ctx_map_; NupharKernelState::NupharKernelState( const Node& node, const ComputeContext& ctx, const NupharExecutionProvider& provider) : provider_(provider), ctx_(ctx) { partition_info_ = onnxruntime::make_unique<OrtSubgraphAllocationInfo>(node); std::vector<NupharSubgraphUnit> subgraphs; // create a partitioner SubgraphPartitioner subgraph_partitioner; subgraph_partitioner.Partition( node, subgraphs, [&](const std::string& name) { return provider_.GetConstantInitializer(name); }); for (auto& subgraph : subgraphs) { Compile(subgraph); if (!codegen_status_.IsOK()) { return; // early return } } // Currently BuildExecBlocksAndCalls is inserted here // TODO: after AOT support, we should move it to a proper location BuildExecBlocksAndCalls(subgraphs); } void NupharKernelState::Compile(const NupharSubgraphUnit& subgraph) { // TODO: rename tvm_target to a proper name auto tvm_target = provider_.GetTVMTarget(); NupharCompiler tvm_compiler(subgraph, generated_initializers_, provider_.GetNupharCodeGenHandle()); codegen_status_ = tvm_compiler.Build(subgraph); if (codegen_status_.IsOK()) { func_infos_.emplace_back(onnxruntime::make_unique<NupharFuncInfo>()); codegen_status_ = tvm_compiler.Lower(subgraph, tvm_target, provider_.GetTVMHostTarget(), func_infos_.back().get(), partition_info_.get()); } } void NupharKernelState::BuildExecBlocksAndCalls(const std::vector<NupharSubgraphUnit>& subgraphs) { // create ExecBlocks for (size_t idx = 0; idx < subgraphs.size(); ++idx) { CreateExecBlock(exec_blocks_, func_infos_[idx].get(), subgraphs[idx], provider_.GetNupharRuntimeHandle()->enable_model_parallelism); } // create calls for (const auto& eb : exec_blocks_) { exec_block_calls_.push_back(eb.get()); } } NupharKernelState::~NupharKernelState() { if (nullptr != nuphar_compute_ctx_map_) nuphar_compute_ctx_map_->erase(this); } Status NupharKernelState::Compute(OpKernelContext* op_kernel_context) const { if (!codegen_status_.IsOK()) { return codegen_status_; } // Create the unordered_map if it not exist if (nullptr == nuphar_compute_ctx_map_) { nuphar_compute_ctx_map_ = onnxruntime::make_unique<NupharFuncStateToComputeCtxMap>(); } // Create KernelComputeCtx if it not exist if (nuphar_compute_ctx_map_->find(this) == nuphar_compute_ctx_map_->end()) { std::function<void*(size_t)> data_alloc_func = [this](size_t bytes) { return provider_.GetNupharRuntimeHandle()->allocator->Alloc(bytes); }; nuphar_compute_ctx_map_->emplace( std::make_pair(this, onnxruntime::make_unique<KernelComputeCtx>( provider_.GetNupharRuntimeHandle(), provider_.GetTLSRealizedDims(), data_alloc_func, partition_info_->offset_count))); } KernelComputeCtx* compute_ctx = nuphar_compute_ctx_map_->find(this)->second.get(); ORT_ENFORCE_DEBUG(nullptr != compute_ctx); compute_ctx->Bind(op_kernel_context); for (auto* call : exec_block_calls_) { CODEGEN_PROFILER_EVENT(call->Name()); call->Run(compute_ctx); } return Status::OK(); } // dummy kernel for single node, for registration purpose only class NupharKernel : public OpKernel { public: explicit NupharKernel(const OpKernelInfo& info) : OpKernel(info) { ORT_ENFORCE(false); // not supposed to instantiate } Status Compute(OpKernelContext* context) const override { return Status::OK(); } }; } // namespace nuphar #define NUPHAR_OP(name, ver, types) \ ONNX_OPERATOR_KERNEL_EX( \ name, \ kOnnxDomain, \ ver, \ kNupharExecutionProvider, \ KernelDefBuilder().TypeConstraint("T", types), \ nuphar::NupharKernel); #define NUPHAR_VERSIONED_OP(name, start_ver, end_ver, types) \ ONNX_OPERATOR_VERSIONED_KERNEL_EX( \ name, \ kOnnxDomain, \ start_ver, \ end_ver, \ kNupharExecutionProvider, \ KernelDefBuilder().TypeConstraint("T", types), \ nuphar::NupharKernel); LIST_NUPHAR_OPS() #undef NUPHAR_OP ONNX_OPERATOR_VERSIONED_KERNEL_EX( Cast, kOnnxDomain, 6, 8, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T1", DataTypeImpl::AllFixedSizeTensorTypes()) .TypeConstraint("T2", DataTypeImpl::AllFixedSizeTensorExceptHalfTypes()), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( Cast, kOnnxDomain, 9, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T1", DataTypeImpl::AllFixedSizeTensorExceptHalfTypes()) .TypeConstraint("T2", DataTypeImpl::AllFixedSizeTensorExceptHalfTypes()), nuphar::NupharKernel); ONNX_OPERATOR_VERSIONED_KERNEL_EX( Gather, kOnnxDomain, 1, 10, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()) .TypeConstraint("Tind", std::vector<MLDataType>{DataTypeImpl::GetTensorType<int32_t>(), DataTypeImpl::GetTensorType<int64_t>()}), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( Gather, kOnnxDomain, 11, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()) .TypeConstraint("Tind", std::vector<MLDataType>{DataTypeImpl::GetTensorType<int32_t>(), DataTypeImpl::GetTensorType<int64_t>()}), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( GatherElements, kOnnxDomain, 11, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()) .TypeConstraint("Tind", std::vector<MLDataType>{DataTypeImpl::GetTensorType<int32_t>(), DataTypeImpl::GetTensorType<int64_t>()}), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( MatMulInteger, kOnnxDomain, 10, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T1", {DataTypeImpl::GetTensorType<int8_t>(), DataTypeImpl::GetTensorType<uint8_t>()}) .TypeConstraint("T2", {DataTypeImpl::GetTensorType<int8_t>(), DataTypeImpl::GetTensorType<uint8_t>()}) .TypeConstraint("T3", DataTypeImpl::GetTensorType<int32_t>()), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( MatMulInteger16, kMSDomain, 1, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T1", {DataTypeImpl::GetTensorType<int16_t>()}) .TypeConstraint("T2", {DataTypeImpl::GetTensorType<int16_t>()}) .TypeConstraint("T3", DataTypeImpl::GetTensorType<int32_t>()), nuphar::NupharKernel); ONNX_OPERATOR_VERSIONED_KERNEL_EX( Scan, kOnnxDomain, 9, 10, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("I", DataTypeImpl::GetTensorType<int64_t>()) .TypeConstraint("V", DataTypeImpl::AllTensorTypes()), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( Scan, kOnnxDomain, 11, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("I", DataTypeImpl::GetTensorType<int64_t>()) .TypeConstraint("V", DataTypeImpl::AllTensorTypes()), nuphar::NupharKernel); ONNX_OPERATOR_VERSIONED_KERNEL_EX( Scatter, kOnnxDomain, 9, 10, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()) .TypeConstraint("Tind", std::vector<MLDataType>{DataTypeImpl::GetTensorType<int32_t>(), DataTypeImpl::GetTensorType<int64_t>()}), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( Scatter, kOnnxDomain, 11, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()) .TypeConstraint("Tind", std::vector<MLDataType>{DataTypeImpl::GetTensorType<int32_t>(), DataTypeImpl::GetTensorType<int64_t>()}), nuphar::NupharKernel); ONNX_OPERATOR_KERNEL_EX( ScatterElements, kOnnxDomain, 11, kNupharExecutionProvider, KernelDefBuilder() .TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()) .TypeConstraint("Tind", std::vector<MLDataType>{DataTypeImpl::GetTensorType<int32_t>(), DataTypeImpl::GetTensorType<int64_t>()}), nuphar::NupharKernel); } // namespace onnxruntime
#include <sal/__bits/platform_sdk.hpp> #include <sal/net/__bits/socket.hpp> #if __sal_os_macos || __sal_os_linux #include <fcntl.h> #include <poll.h> #include <sys/ioctl.h> #include <unistd.h> #elif __sal_os_windows #include <mutex> #endif __sal_begin namespace net::__bits { #if __sal_os_windows // {{{1 winsock_t winsock{}; namespace { template <typename T> inline T check_call (T result, std::error_code &error) noexcept { if (result != SOCKET_ERROR) { error.clear(); } else { auto e = ::WSAGetLastError(); if (e == WSAENOTSOCK) { e = WSAEBADF; } error.assign(e, std::system_category()); } return result; } #define call(func,error,...) check_call(func(__VA_ARGS__), error) template <typename F> void load (F *fn, GUID id, SOCKET socket, std::error_code &error) noexcept { if (!error) { DWORD bytes; call(::WSAIoctl, error, socket, SIO_GET_EXTENSION_FUNCTION_POINTER, &id, sizeof(id), fn, sizeof(fn), &bytes, nullptr, nullptr ); } } void init_winsock (std::error_code &init_result, winsock_t &fn) noexcept { WSADATA wsa; init_result.assign( ::WSAStartup(MAKEWORD(2, 2), &wsa), std::system_category() ); if (!init_result) { auto s = ::socket(AF_INET, SOCK_STREAM, 0); load(&fn.ConnectEx, WSAID_CONNECTEX, s, init_result); load(&fn.AcceptEx, WSAID_ACCEPTEX, s, init_result); (void)::closesocket(s); } } } // namespace const std::error_code &init_lib () noexcept { static std::once_flag once; static std::error_code init_result; std::call_once(once, &init_winsock, std::ref(init_result), std::ref(winsock) ); return init_result; } winsock_t::winsock_t () noexcept { init_lib(); } winsock_t::~winsock_t () noexcept { (void)::WSACleanup(); } void socket_t::open (int domain, int type, int protocol, std::error_code &error) noexcept { handle = call(::WSASocketW, error, domain, type, protocol, nullptr, 0, WSA_FLAG_OVERLAPPED ); if (handle != SOCKET_ERROR) { ::SetFileCompletionNotificationModes( reinterpret_cast<HANDLE>(handle), FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE ); if (type == SOCK_DGRAM) { bool new_behaviour = false; DWORD ignored; ::WSAIoctl(handle, SIO_UDP_CONNRESET, &new_behaviour, sizeof(new_behaviour), nullptr, 0, &ignored, nullptr, nullptr ); } } } void socket_t::close (std::error_code &error) noexcept { call(::closesocket, error, handle); handle = invalid; } void socket_t::bind (const void *address, size_t address_size, std::error_code &error) noexcept { call(::bind, error, handle, static_cast<const sockaddr *>(address), static_cast<socklen_t>(address_size) ); } void socket_t::listen (int backlog, std::error_code &error) noexcept { call(::listen, error, handle, backlog); } socket_t::handle_t socket_t::accept (void *address, size_t *address_size, bool enable_connection_aborted, std::error_code &error) noexcept { socklen_t size{}, *size_p = nullptr; if (address_size) { size = static_cast<socklen_t>(*address_size); size_p = &size; } retry: auto new_socket = call(::accept, error, handle, static_cast<sockaddr *>(address), size_p ); if (new_socket != invalid) { if (address_size) { *address_size = size; } return new_socket; } if (error == std::errc::connection_aborted && !enable_connection_aborted) { goto retry; } return 0; } void socket_t::connect (const void *address, size_t address_size, std::error_code &error) noexcept { call(::connect, error, handle, static_cast<const sockaddr *>(address), static_cast<socklen_t>(address_size) ); } bool socket_t::wait (wait_t what, int timeout_ms, std::error_code &error) noexcept { pollfd fd{}; fd.fd = handle; fd.events = what == wait_t::read ? POLLIN : POLLOUT; auto event_count = ::WSAPoll(&fd, 1, timeout_ms); if (event_count == 1) { return (fd.revents & fd.events) != 0; } else if (event_count == -1) { check_call(invalid, error); } return false; } size_t socket_t::receive (void *data, size_t data_size, message_flags_t flags, std::error_code &error) noexcept { WSABUF buf; buf.buf = static_cast<char *>(data); buf.len = static_cast<ULONG>(data_size); DWORD transferred{}; DWORD recv_flags = flags; auto result = call(::WSARecv, error, handle, &buf, 1, &transferred, &recv_flags, nullptr, nullptr ); if (result != SOCKET_ERROR || error.value() == WSAESHUTDOWN) { if (transferred) { return transferred; } error = make_error_code(std::errc::broken_pipe); } return 0; } size_t socket_t::receive_from (void *data, size_t data_size, void *address, size_t *address_size, message_flags_t flags, std::error_code &error) noexcept { WSABUF buf; buf.buf = static_cast<char *>(data); buf.len = static_cast<ULONG>(data_size); auto tmp_address_size = static_cast<INT>(*address_size); DWORD transferred{}; DWORD recv_flags = flags; auto result = call(::WSARecvFrom, error, handle, &buf, 1, &transferred, &recv_flags, static_cast<sockaddr *>(address), (address ? &tmp_address_size : nullptr), nullptr, nullptr ); if (result != SOCKET_ERROR) { *address_size = tmp_address_size; } return transferred; } size_t socket_t::send (const void *data, size_t data_size, message_flags_t flags, std::error_code &error) noexcept { WSABUF buf; buf.buf = static_cast<char *>(const_cast<void *>(data)); buf.len = static_cast<ULONG>(data_size); DWORD transferred{}; auto result = call(::WSASend, error, handle, &buf, 1, &transferred, flags, nullptr, nullptr ); if (result != SOCKET_ERROR) { return transferred; } else if (error.value() == WSAESHUTDOWN) { error = make_error_code(std::errc::broken_pipe); } return 0; } size_t socket_t::send_to (const void *data, size_t data_size, const void *address, size_t address_size, message_flags_t flags, std::error_code &error) noexcept { WSABUF buf; buf.buf = static_cast<char *>(const_cast<void *>(data)); buf.len = static_cast<ULONG>(data_size); DWORD transferred{}; auto result = call(::WSASendTo, error, handle, &buf, 1, &transferred, flags, static_cast<const sockaddr *>(address), static_cast<int>(address_size), nullptr, nullptr ); if (result != SOCKET_ERROR) { return transferred; } return 0; } void socket_t::shutdown (shutdown_t what, std::error_code &error) noexcept { call(::shutdown, error, handle, static_cast<int>(what)); } void socket_t::remote_endpoint (void *address, size_t *address_size, std::error_code &error) const noexcept { auto size = static_cast<socklen_t>(*address_size); auto result = call(::getpeername, error, handle, static_cast<sockaddr *>(address), &size ); if (result != -1) { *address_size = size; } } void socket_t::local_endpoint (void *address, size_t *address_size, std::error_code &error) const noexcept { auto size = static_cast<socklen_t>(*address_size); auto result = call(::getsockname, error, handle, static_cast<sockaddr *>(address), &size ); if (result != -1) { *address_size = size; } } void socket_t::get_opt (int level, int name, void *data, size_t *size, std::error_code &error) const noexcept { auto data_size = static_cast<socklen_t>(*size); auto result = call(::getsockopt, error, handle, level, name, static_cast<char *>(data), &data_size ); if (result != -1) { *size = data_size; } } void socket_t::set_opt (int level, int name, const void *data, size_t size, std::error_code &error) noexcept { call(::setsockopt, error, handle, level, name, static_cast<const char *>(data), static_cast<socklen_t>(size) ); } bool socket_t::non_blocking (std::error_code &error) const noexcept { error.assign(WSAEOPNOTSUPP, std::system_category()); return true; } void socket_t::non_blocking (bool mode, std::error_code &error) noexcept { unsigned long arg = mode ? 1 : 0; call(::ioctlsocket, error, handle, FIONBIO, &arg); } size_t socket_t::available (std::error_code &error) const noexcept { unsigned long value{}; if (call(::ioctlsocket, error, handle, FIONBIO, &value) == SOCKET_ERROR) { value = 0; } return value; } #elif __sal_os_macos || __sal_os_linux // {{{1 namespace { template <typename T> inline T check_call (T result, std::error_code &error) noexcept { if (result != -1) { error.clear(); } else { if (errno == EDESTADDRREQ) { errno = ENOTCONN; } error.assign(errno, std::generic_category()); } return result; } #define call(func,error,...) check_call(func(__VA_ARGS__), error) } // namspace const std::error_code &init_lib () noexcept { static const std::error_code no_error{}; return no_error; } void socket_t::open (int domain, int type, int protocol, std::error_code &error) noexcept { handle = call(::socket, error, domain, type, protocol); #if __sal_os_macos if (handle != invalid) { int optval = 1; (void)::setsockopt(handle, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval) ); } #endif } void socket_t::close (std::error_code &error) noexcept { for (;;) { if (call(::close, error, handle) == 0 || errno != EINTR) { handle = invalid; return; } } } void socket_t::bind (const void *address, size_t address_size, std::error_code &error) noexcept { call(::bind, error, handle, static_cast<const sockaddr *>(address), static_cast<socklen_t>(address_size) ); } void socket_t::listen (int backlog, std::error_code &error) noexcept { call(::listen, error, handle, backlog); } socket_t::handle_t socket_t::accept (void *address, size_t *address_size, bool enable_connection_aborted, std::error_code &error) noexcept { socklen_t size{}, *size_p = nullptr; if (address_size) { size = static_cast<socklen_t>(*address_size); size_p = &size; } retry: auto new_socket = call(::accept, error, handle, static_cast<sockaddr *>(address), size_p ); if (new_socket != invalid) { if (address_size) { #if __sal_os_macos // LCOV_EXCL_START // kernel bug: instead of ECONNABORTED, we might get size=0 if (!size) { if (enable_connection_aborted) { error.assign(ECONNABORTED, std::generic_category()); return invalid; } size = static_cast<socklen_t>(*address_size); goto retry; } // LCOV_EXCL_STOP #endif *address_size = size; } #if __sal_os_macos int optval = 1; ::setsockopt(new_socket, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval) ); #endif return new_socket; } // LCOV_EXCL_START // OS-dependent section #if __sal_os_linux // see accept(2), these are already pending errors if (errno == ENETDOWN || errno == EPROTO || errno == ENOPROTOOPT || errno == EHOSTDOWN || errno == ENONET || errno == EHOSTUNREACH || errno == EOPNOTSUPP || errno == ENETUNREACH) { goto retry; } #endif if (error == std::errc::connection_aborted && !enable_connection_aborted) { goto retry; } // LCOV_EXCL_STOP return invalid; } void socket_t::connect (const void *address, size_t address_size, std::error_code &error) noexcept { call(::connect, error, handle, static_cast<const sockaddr *>(address), static_cast<socklen_t>(address_size) ); } bool socket_t::wait (wait_t what, int timeout_ms, std::error_code &error) noexcept { if (handle == invalid) { error.assign(EBADF, std::generic_category()); return false; } pollfd fd{}; fd.fd = handle; fd.events = what == wait_t::read ? POLLIN : POLLOUT; auto event_count = ::poll(&fd, 1, timeout_ms); if (event_count == 1) { #if __sal_os_linux // Linux does the "right thing", setting POLLHUP on non-connected sockets // unfortunately Darwin & Windows disagree and no way to detect such // situation, so simply align after their behaviour if (fd.revents & POLLHUP) { return false; } #endif return (fd.revents & fd.events) != 0; } // LCOV_EXCL_START // can't reach this case by feeding incorrect parameters else if (event_count == -1) { check_call(invalid, error); } // LCOV_EXCL_STOP return false; } size_t socket_t::receive (void *data, size_t data_size, message_flags_t flags, std::error_code &error) noexcept { iovec iov; iov.iov_base = data; iov.iov_len = data_size; msghdr msg{}; msg.msg_iov = &iov; msg.msg_iovlen = 1; #if __sal_os_linux flags |= MSG_NOSIGNAL; #endif auto size = call(::recvmsg, error, handle, &msg, flags); if (!size && data_size) { error = make_error_code(std::errc::broken_pipe); } else if (size == -1) { size = 0; } else if (msg.msg_flags & MSG_TRUNC) { error.assign(EMSGSIZE, std::generic_category()); } return size; } size_t socket_t::receive_from (void *data, size_t data_size, void *address, size_t *address_size, message_flags_t flags, std::error_code &error) noexcept { iovec iov; iov.iov_base = data; iov.iov_len = data_size; msghdr msg{}; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_name = address; msg.msg_namelen = *address_size; #if __sal_os_linux flags |= MSG_NOSIGNAL; #endif auto size = call(::recvmsg, error, handle, &msg, flags); if (size >= 0) { if (msg.msg_flags & MSG_TRUNC) { error.assign(EMSGSIZE, std::generic_category()); } else { *address_size = msg.msg_namelen; } } else { size = 0; } return size; } size_t socket_t::send (const void *data, size_t data_size, message_flags_t flags, std::error_code &error) noexcept { iovec iov; iov.iov_base = const_cast<void *>(data); iov.iov_len = data_size; msghdr msg{}; msg.msg_iov = &iov; msg.msg_iovlen = 1; #if __sal_os_linux flags |= MSG_NOSIGNAL; #endif auto size = call(::sendmsg, error, handle, &msg, flags); if (size == -1) { size = 0; } return size; } size_t socket_t::send_to (const void *data, size_t data_size, const void *address, size_t address_size, message_flags_t flags, std::error_code &error) noexcept { iovec iov; iov.iov_base = const_cast<void *>(data); iov.iov_len = data_size; msghdr msg{}; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_name = const_cast<void *>(address); msg.msg_namelen = address_size; #if __sal_os_linux flags |= MSG_NOSIGNAL; #endif auto size = call(::sendmsg, error, handle, &msg, flags); if (size == -1) { size = 0; } return size; } void socket_t::shutdown (shutdown_t what, std::error_code &error) noexcept { call(::shutdown, error, handle, static_cast<int>(what)); } void socket_t::remote_endpoint (void *address, size_t *address_size, std::error_code &error) const noexcept { auto size = static_cast<socklen_t>(*address_size); auto result = call(::getpeername, error, handle, static_cast<sockaddr *>(address), &size ); if (result != -1) { *address_size = size; } } void socket_t::local_endpoint (void *address, size_t *address_size, std::error_code &error) const noexcept { auto size = static_cast<socklen_t>(*address_size); auto result = call(::getsockname, error, handle, static_cast<sockaddr *>(address), &size ); if (result != -1) { *address_size = size; } } void socket_t::get_opt (int level, int name, void *data, size_t *size, std::error_code &error) const noexcept { auto data_size = static_cast<socklen_t>(*size); auto result = call(::getsockopt, error, handle, level, name, static_cast<char *>(data), &data_size ); if (result != -1) { *size = data_size; } } void socket_t::set_opt (int level, int name, const void *data, size_t size, std::error_code &error) noexcept { call(::setsockopt, error, handle, level, name, static_cast<const char *>(data), static_cast<socklen_t>(size) ); } bool socket_t::non_blocking (std::error_code &error) const noexcept { // on error, returned value is undefined return O_NONBLOCK & call(::fcntl, error, handle, F_GETFL, 0); } void socket_t::non_blocking (bool mode, std::error_code &error) noexcept { int flags = call(::fcntl, error, handle, F_GETFL, 0); if (flags >= 0) { if (mode) { flags |= O_NONBLOCK; } else { flags &= ~O_NONBLOCK; } call(::fcntl, error, handle, F_SETFL, flags); } } size_t socket_t::available (std::error_code &error) const noexcept { unsigned long value{}; if (call(::ioctl, error, handle, FIONREAD, &value) == -1) { value = 0; } return value; } #endif // }}}1 } // namespace net::__bits __sal_end
/* Copyright 2015 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. ==============================================================================*/ // See docs in ../ops/array_ops.cc. #include "tensorflow/core/framework/bounds_check.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/variant.h" #include "tensorflow/core/framework/variant_encode_decode.h" #include "tensorflow/core/kernels/gather_functor.h" #include "tensorflow/core/platform/mem.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/util.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; typedef Eigen::DenseIndex IndexType; template <typename Device, typename T, typename Index> class GatherOp : public OpKernel { public: // QUESTION: It'd be nice to support DT_INT16, DT_UINT8, // etc. here for the type of the second input argument. Should // we have the framework do some sort of integer promotion // automatically, or should that be something that users have to // do explicitly with a conversion operator in the graph? explicit GatherOp(OpKernelConstruction* c) : OpKernel(c) { // Set batch_dims_ to 0 if the attribute does not exist. if (c->HasAttr("batch_dims")) { OP_REQUIRES_OK(c, c->GetAttr("batch_dims", &batch_dims_)); } else { batch_dims_ = 0; } } void Compute(OpKernelContext* c) override { const Tensor& params = c->input(0); const Tensor& indices = c->input(1); OP_REQUIRES( c, TensorShapeUtils::IsVectorOrHigher(params.shape()), errors::InvalidArgument("params must be at least 1 dimensional")); // GatherV2 added an axis argument. For backwards compatibility with Gather, // fall back to axis 0 if the op does not have an axis input. int64 axis = 0; bool axis_is_set = false; // Indicates whether the axis argument was set. if (c->num_inputs() == 3) { axis_is_set = true; const Tensor& axis_tensor = c->input(2); OP_REQUIRES(c, TensorShapeUtils::IsScalar(axis_tensor.shape()), errors::InvalidArgument("axis must be scalar")); if (axis_tensor.dtype() == DT_INT32) { axis = axis_tensor.scalar<int32>()(); } else if (axis_tensor.dtype() == DT_INT64) { axis = axis_tensor.scalar<int64>()(); } else { OP_REQUIRES(c, false, errors::InvalidArgument("axis must be int32 or int64.")); } } OP_REQUIRES( c, axis >= -params.dims() && axis < params.dims(), errors::InvalidArgument("Expected axis in the range [", -params.dims(), ", ", params.dims(), "), but got ", axis)); if (axis < 0) { axis = params.dims() + axis; } if (batch_dims_ != 0) { if (batch_dims_ < 0) { batch_dims_ = indices.dims() + batch_dims_; } if (!axis_is_set) axis = batch_dims_; OP_REQUIRES( c, batch_dims_ >= -indices.dims() && batch_dims_ < indices.dims(), errors::InvalidArgument("Expected batch_dims in the range [", -indices.dims(), ", ", indices.dims(), "), but got ", batch_dims_)); OP_REQUIRES(c, batch_dims_ < params.dims(), errors::InvalidArgument("batch_dims (", batch_dims_, ") must be less than rank(params) (", params.dims(), ").")); OP_REQUIRES(c, axis >= batch_dims_, errors::InvalidArgument("batch_dims (", batch_dims_, ") must be less than or equal to ", "axis (", axis, ").")); } // Check that we have enough index space int64 gather_dim_size = params.dim_size(axis); const int64 N = indices.NumElements(); OP_REQUIRES( c, gather_dim_size <= std::numeric_limits<Index>::max(), errors::InvalidArgument("params.shape[", axis, "] too large for ", DataTypeString(DataTypeToEnum<Index>::v()), " indexing: ", gather_dim_size, " > ", std::numeric_limits<Index>::max())); // The result shape is params.shape[:axis] + indices.shape[batch_dims:] + // params.shape[axis + 1:]. TensorShape result_shape; int64 outer_size = 1; int64 inner_size = 1; for (int i = 0; i < axis; i++) { result_shape.AddDim(params.dim_size(i)); outer_size *= params.dim_size(i); } for (int i = batch_dims_; i < indices.dims(); ++i) { result_shape.AddDim(indices.dim_size(i)); } for (int i = axis + 1; i < params.dims(); i++) { result_shape.AddDim(params.dim_size(i)); inner_size *= params.dim_size(i); } Tensor* out = nullptr; OP_REQUIRES_OK(c, c->allocate_output(0, result_shape, &out)); if (N == 0) return; if (batch_dims_ > 0) { // TODO(virimia): Switch to transpose / gather with axis=0 / transpose // on GPU, to avoid launching a lot of small kernels. // To avoid copying params (by transposing), run gather for each batch. int64 batch_size = 1; for (int i = 0; i < batch_dims_; ++i) { batch_size *= params.dim_size(i); } outer_size /= batch_size; auto batched_params = params.shaped<T, 2>({batch_size, params.NumElements() / batch_size}); auto batched_indices = indices.shaped<Index, 2>({batch_size, N / batch_size}); auto batched_out = out->shaped<T, 2>({batch_size, out->NumElements() / batch_size}); // TODO(virimia): Investigate the best performance, when the number of // batches is large, between parallel vs sequential runs. for (int64 batch = 0; batch < batch_size; ++batch) { auto params_flat = typename TTypes<T, 3>::ConstTensor( &batched_params(batch, 0), static_cast<IndexType>(outer_size), static_cast<IndexType>(gather_dim_size), static_cast<IndexType>(inner_size)); auto indices_flat = typename TTypes<Index>::ConstFlat( &batched_indices(batch, 0), batched_indices.dimension(1)); auto out_flat = typename TTypes<T, 3>::Tensor( &batched_out(batch, 0), static_cast<IndexType>(outer_size), static_cast<IndexType>(N), static_cast<IndexType>(inner_size)); functor::GatherFunctor<Device, T, Index> functor; const int64 bad_i = functor(c, params_flat, indices_flat, out_flat); OP_REQUIRES( c, bad_i < 0, errors::InvalidArgument( "indices", SliceDebugString(indices.shape(), bad_i), " = ", indices_flat(bad_i), " is not in [0, ", gather_dim_size, ")")); } } else { auto params_flat = params.shaped<T, 3>({outer_size, gather_dim_size, inner_size}); auto indices_flat = indices.flat<Index>(); auto out_flat = out->shaped<T, 3>({outer_size, N, inner_size}); functor::GatherFunctor<Device, T, Index> functor; const int64 bad_i = functor(c, params_flat, indices_flat, out_flat); OP_REQUIRES( c, bad_i < 0, errors::InvalidArgument( "indices", SliceDebugString(indices.shape(), bad_i), " = ", indices_flat(bad_i), " is not in [0, ", gather_dim_size, ")")); } } private: // The number of batch dimensions, as passed in the batch_dims attribute. // It must be less than rank(indices). int32 batch_dims_ = 0; }; #define REGISTER_GATHER_FULL(dev, type, index_type) \ REGISTER_KERNEL_BUILDER(Name("Gather") \ .Device(DEVICE_##dev) \ .TypeConstraint<type>("Tparams") \ .TypeConstraint<index_type>("Tindices"), \ GatherOp<dev##Device, type, index_type>); \ REGISTER_KERNEL_BUILDER(Name("GatherV2") \ .Device(DEVICE_##dev) \ .TypeConstraint<type>("Tparams") \ .TypeConstraint<index_type>("Tindices") \ .HostMemory("axis"), \ GatherOp<dev##Device, type, index_type>) #define REGISTER_GATHER_ALL_INDICES(dev, type) \ REGISTER_GATHER_FULL(dev, type, int32); \ REGISTER_GATHER_FULL(dev, type, int64) #define REGISTER_GATHER_CPU(type) REGISTER_GATHER_ALL_INDICES(CPU, type) // Registration of the CPU implementations. TF_CALL_ALL_TYPES(REGISTER_GATHER_CPU); TF_CALL_QUANTIZED_TYPES(REGISTER_GATHER_CPU); TF_CALL_quint16(REGISTER_GATHER_CPU); TF_CALL_qint16(REGISTER_GATHER_CPU); TF_CALL_uint32(REGISTER_GATHER_CPU); TF_CALL_uint64(REGISTER_GATHER_CPU); #undef REGISTER_GATHER_CPU #if GOOGLE_CUDA // Registration of the GPU implementations. #define REGISTER_GATHER_GPU(type) REGISTER_GATHER_ALL_INDICES(GPU, type) TF_CALL_bool(REGISTER_GATHER_GPU); TF_CALL_int32(REGISTER_GATHER_GPU); TF_CALL_int64(REGISTER_GATHER_GPU); TF_CALL_GPU_NUMBER_TYPES(REGISTER_GATHER_GPU); TF_CALL_complex64(REGISTER_GATHER_GPU); TF_CALL_complex128(REGISTER_GATHER_GPU); #undef REGISTER_GATHER_GPU #endif // GOOGLE_CUDA #undef REGISTER_GATHER_ALL_INDICES #undef REGISTER_GATHER_FULL } // namespace tensorflow
/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/utility/cascaded_biquad_filter.h" #include <vector> #include "test/gtest.h" namespace webrtc { namespace { // Coefficients for a second order Butterworth high-pass filter with cutoff // frequency 100 Hz. const CascadedBiQuadFilter::BiQuadCoefficients kHighPassFilterCoefficients = { {0.97261f, -1.94523f, 0.97261f}, {-1.94448f, 0.94598f}}; const CascadedBiQuadFilter::BiQuadCoefficients kTransparentCoefficients = { {1.f, 0.f, 0.f}, {0.f, 0.f}}; const CascadedBiQuadFilter::BiQuadCoefficients kBlockingCoefficients = { {0.f, 0.f, 0.f}, {0.f, 0.f}}; std::vector<float> CreateInputWithIncreasingValues(size_t vector_length) { std::vector<float> v(vector_length); for (size_t k = 0; k < v.size(); ++k) { v[k] = k; } return v; } } // namespace // Verifies that the filter applies an effect which removes the input signal. // The test also verifies that the in-place Process API call works as intended. TEST(CascadedBiquadFilter, BlockingConfiguration) { std::vector<float> values = CreateInputWithIncreasingValues(1000); CascadedBiQuadFilter filter(kBlockingCoefficients, 1); filter.Process(values); EXPECT_EQ(std::vector<float>(1000, 0.f), values); } // Verifies that the filter is able to form a zero-mean output from a // non-zeromean input signal when coefficients for a high-pass filter are // applied. The test also verifies that the filter works with multiple biquads. TEST(CascadedBiquadFilter, HighPassConfiguration) { std::vector<float> values(1000); for (size_t k = 0; k < values.size(); ++k) { values[k] = 1.f; } CascadedBiQuadFilter filter(kHighPassFilterCoefficients, 2); filter.Process(values); for (size_t k = values.size() / 2; k < values.size(); ++k) { EXPECT_NEAR(0.f, values[k], 1e-4); } } // Verifies that the reset functionality works as intended. TEST(CascadedBiquadFilter, HighPassConfigurationResetFunctionality) { CascadedBiQuadFilter filter(kHighPassFilterCoefficients, 2); std::vector<float> values1(100, 1.f); filter.Process(values1); filter.Reset(); std::vector<float> values2(100, 1.f); filter.Process(values2); for (size_t k = 0; k < values1.size(); ++k) { EXPECT_EQ(values1[k], values2[k]); } } // Verifies that the filter is able to produce a transparent effect with no // impact on the data when the proper coefficients are applied. The test also // verifies that the non-in-place Process API call works as intended. TEST(CascadedBiquadFilter, TransparentConfiguration) { const std::vector<float> input = CreateInputWithIncreasingValues(1000); std::vector<float> output(input.size()); CascadedBiQuadFilter filter(kTransparentCoefficients, 1); filter.Process(input, output); EXPECT_EQ(input, output); } #if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID) // Verifies that the check of the lengths for the input and output works for the // non-in-place call. TEST(CascadedBiquadFilterDeathTest, InputSizeCheckVerification) { const std::vector<float> input = CreateInputWithIncreasingValues(10); std::vector<float> output(input.size() - 1); CascadedBiQuadFilter filter(kTransparentCoefficients, 1); EXPECT_DEATH(filter.Process(input, output), ""); } #endif // Verifies the conversion from zero, pole, gain to filter coefficients for // lowpass filter. TEST(CascadedBiquadFilter, BiQuadParamLowPass) { CascadedBiQuadFilter::BiQuadParam param( {-1.0f, 0.0f}, {0.23146901f, 0.39514232f}, 0.1866943331163784f); CascadedBiQuadFilter::BiQuad filter(param); const float epsilon = 1e-6f; EXPECT_NEAR(filter.coefficients.b[0], 0.18669433f, epsilon); EXPECT_NEAR(filter.coefficients.b[1], 0.37338867f, epsilon); EXPECT_NEAR(filter.coefficients.b[2], 0.18669433f, epsilon); EXPECT_NEAR(filter.coefficients.a[0], -0.46293803f, epsilon); EXPECT_NEAR(filter.coefficients.a[1], 0.20971536f, epsilon); } // Verifies the conversion from zero, pole, gain to filter coefficients for // highpass filter. TEST(CascadedBiquadFilter, BiQuadParamHighPass) { CascadedBiQuadFilter::BiQuadParam param( {1.0f, 0.0f}, {0.72712179f, 0.21296904f}, 0.75707637533388494f); CascadedBiQuadFilter::BiQuad filter(param); const float epsilon = 1e-6f; EXPECT_NEAR(filter.coefficients.b[0], 0.75707638f, epsilon); EXPECT_NEAR(filter.coefficients.b[1], -1.51415275f, epsilon); EXPECT_NEAR(filter.coefficients.b[2], 0.75707638f, epsilon); EXPECT_NEAR(filter.coefficients.a[0], -1.45424359f, epsilon); EXPECT_NEAR(filter.coefficients.a[1], 0.57406192f, epsilon); } // Verifies the conversion from zero, pole, gain to filter coefficients for // bandpass filter. TEST(CascadedBiquadFilter, BiQuadParamBandPass) { CascadedBiQuadFilter::BiQuadParam param( {1.0f, 0.0f}, {1.11022302e-16f, 0.71381051f}, 0.2452372752527856f, true); CascadedBiQuadFilter::BiQuad filter(param); const float epsilon = 1e-6f; EXPECT_NEAR(filter.coefficients.b[0], 0.24523728f, epsilon); EXPECT_NEAR(filter.coefficients.b[1], 0.f, epsilon); EXPECT_NEAR(filter.coefficients.b[2], -0.24523728f, epsilon); EXPECT_NEAR(filter.coefficients.a[0], -2.22044605e-16f, epsilon); EXPECT_NEAR(filter.coefficients.a[1], 5.09525449e-01f, epsilon); } } // namespace webrtc
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2017 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 20.33Release // Tag = production/akw/20.33.01-0-gdd6ece0 //////////////////////////////////////////////////////////////////////////////// #if !defined(FIT_HRV_MESG_HPP) #define FIT_HRV_MESG_HPP #include "fit_mesg.hpp" namespace fit { class HrvMesg : public Mesg { public: class FieldDefNum final { public: static const FIT_UINT8 Time = 0; static const FIT_UINT8 Invalid = FIT_FIELD_NUM_INVALID; }; HrvMesg(void) : Mesg(Profile::MESG_HRV) { } HrvMesg(const Mesg &mesg) : Mesg(mesg) { } /////////////////////////////////////////////////////////////////////// // Returns number of time /////////////////////////////////////////////////////////////////////// FIT_UINT8 GetNumTime(void) const { return GetFieldNumValues(0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Checks the validity of time field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsTimeValid(FIT_UINT8 index) const { const Field* field = GetField(0); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(index); } /////////////////////////////////////////////////////////////////////// // Returns time field // Units: s // Comment: Time between beats /////////////////////////////////////////////////////////////////////// FIT_FLOAT32 GetTime(FIT_UINT8 index) const { return GetFieldFLOAT32Value(0, index, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set time field // Units: s // Comment: Time between beats /////////////////////////////////////////////////////////////////////// void SetTime(FIT_UINT8 index, FIT_FLOAT32 time) { SetFieldFLOAT32Value(0, time, index, FIT_SUBFIELD_INDEX_MAIN_FIELD); } }; } // namespace fit #endif // !defined(FIT_HRV_MESG_HPP)
#include<iostream> using namespace std; int main() { int n, ix, f0, f1, aux; cout << "Ingrese un numero: "; cin >> n; f0 = ix = 0; f1 = 1; while(ix <= n) { if(ix == 0 || ix == 1) { cout << ix << " --> " << ix << endl; } else { aux = f0 + f1; f0 = f1; f1 = aux; cout << ix << " --> " << aux << endl; } ix++; } return 0; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.TestTools.TestRunner.GUI.RuntimeTestRunnerFilter #include "UnityEngine/TestTools/TestRunner/GUI/RuntimeTestRunnerFilter.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Func`2<T, TResult> template<typename T, typename TResult> class Func_2; } // Forward declaring namespace: NUnit::Framework::Internal namespace NUnit::Framework::Internal { // Forward declaring type: TestFilter class TestFilter; } // Forward declaring namespace: NUnit::Framework::Interfaces namespace NUnit::Framework::Interfaces { // Forward declaring type: ITestFilter class ITestFilter; } // Completed forward declares // Type namespace: UnityEngine.TestTools.TestRunner.GUI namespace UnityEngine::TestTools::TestRunner::GUI { // Forward declaring type: <>c__DisplayClass7_0 class $$c__DisplayClass7_0; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0); DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0*, "UnityEngine.TestTools.TestRunner.GUI", "RuntimeTestRunnerFilter/<>c__DisplayClass7_0"); // Type namespace: UnityEngine.TestTools.TestRunner.GUI namespace UnityEngine::TestTools::TestRunner::GUI { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: UnityEngine.TestTools.TestRunner.GUI.RuntimeTestRunnerFilter/UnityEngine.TestTools.TestRunner.GUI.<>c__DisplayClass7_0 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class RuntimeTestRunnerFilter::$$c__DisplayClass7_0 : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // public System.Func`2<System.String,NUnit.Framework.Internal.TestFilter> builder // Size: 0x8 // Offset: 0x10 System::Func_2<::Il2CppString*, NUnit::Framework::Internal::TestFilter*>* builder; // Field size check static_assert(sizeof(System::Func_2<::Il2CppString*, NUnit::Framework::Internal::TestFilter*>*) == 0x8); public: // Creating conversion operator: operator System::Func_2<::Il2CppString*, NUnit::Framework::Internal::TestFilter*>* constexpr operator System::Func_2<::Il2CppString*, NUnit::Framework::Internal::TestFilter*>*() const noexcept { return builder; } // Get instance field reference: public System.Func`2<System.String,NUnit.Framework.Internal.TestFilter> builder System::Func_2<::Il2CppString*, NUnit::Framework::Internal::TestFilter*>*& dyn_builder(); // NUnit.Framework.Interfaces.ITestFilter <AddFilters>b__1(System.String v) // Offset: 0x16598DC NUnit::Framework::Interfaces::ITestFilter* $AddFilters$b__1(::Il2CppString* v); // NUnit.Framework.Interfaces.ITestFilter <AddFilters>b__3(System.String v) // Offset: 0x1659944 NUnit::Framework::Interfaces::ITestFilter* $AddFilters$b__3(::Il2CppString* v); // public System.Void .ctor() // Offset: 0x1659660 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeTestRunnerFilter::$$c__DisplayClass7_0* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeTestRunnerFilter::$$c__DisplayClass7_0*, creationType>())); } }; // UnityEngine.TestTools.TestRunner.GUI.RuntimeTestRunnerFilter/UnityEngine.TestTools.TestRunner.GUI.<>c__DisplayClass7_0 #pragma pack(pop) static check_size<sizeof(RuntimeTestRunnerFilter::$$c__DisplayClass7_0), 16 + sizeof(System::Func_2<::Il2CppString*, NUnit::Framework::Internal::TestFilter*>*)> __UnityEngine_TestTools_TestRunner_GUI_RuntimeTestRunnerFilter_$$c__DisplayClass7_0SizeCheck; static_assert(sizeof(RuntimeTestRunnerFilter::$$c__DisplayClass7_0) == 0x18); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::$AddFilters$b__1 // Il2CppName: <AddFilters>b__1 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<NUnit::Framework::Interfaces::ITestFilter* (UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::*)(::Il2CppString*)>(&UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::$AddFilters$b__1)> { static const MethodInfo* get() { static auto* v = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0*), "<AddFilters>b__1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{v}); } }; // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::$AddFilters$b__3 // Il2CppName: <AddFilters>b__3 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<NUnit::Framework::Interfaces::ITestFilter* (UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::*)(::Il2CppString*)>(&UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::$AddFilters$b__3)> { static const MethodInfo* get() { static auto* v = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0*), "<AddFilters>b__3", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{v}); } }; // Writing MetadataGetter for method: UnityEngine::TestTools::TestRunner::GUI::RuntimeTestRunnerFilter::$$c__DisplayClass7_0::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
/* Copyright 2021 MacKenzie Strand 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. */ #pragma once #include "utilities/Common.h" #include "core/ModuleBase.hpp" #include "DeviceBackendLayer.hpp" #if CITRUS_INCLUDE_AUDITION #include "audition/HotReloadDetection.hpp" #endif /* --------------------------- Virtual Directory --------------------------- */ enum ctInteractionNodeType { CT_INTERACT_NODETYPE_NULL = 0, CT_INTERACT_NODETYPE_SCALAR = 1, /* Data points to a float */ CT_INTERACT_NODETYPE_BOOL = 2, /* Data points to a boolean */ CT_INTERACT_NODETYPE_BINDING = 127, /* Data points to a binding structure */ CT_INTERACT_NODETYPE_ACTIONSET = 128, /* Data points to an action set */ CT_INTERACT_NODETYPE_MAX = UINT8_MAX }; struct CT_API ctInteractPath { ctInteractPath(); ctInteractPath(const char* ptr, size_t count); ctInteractPath(const char* ptr); ctInteractPath(const ctStringUtf8& ctStr); bool operator==(const ctInteractPath other) { return ctCStrEql(str, other.str); } char str[CT_MAX_INTERACT_PATH_SIZE]; }; struct CT_API ctInteractNode { inline ctInteractNode() { path = ctInteractPath(); type = CT_INTERACT_NODETYPE_NULL; accessible = true; pData = NULL; } float GetScalar(); bool SetScalar(float value); class ctInteractBinding* GetAsBinding(); class ctInteractActionSet* GetAsActionSet(); ctInteractPath path; ctInteractionNodeType type; bool accessible; void* pData; }; class CT_API ctInteractDirectorySystem { public: ~ctInteractDirectorySystem(); ctResults CreateActionSetsFromFile(ctFile& file); ctResults CreateBindingsFromFile(ctFile& file); ctResults Update(); ctResults AddNode(ctInteractNode& node); ctResults RemoveNode(ctInteractPath& path); void EnableActionSet(ctInteractPath& path); void DisableActionSet(ctInteractPath& path); ctResults SetNodeAccessible(ctInteractPath& path, bool accessible); ctResults GetNode(ctInteractPath& path, ctInteractNode*& pOutNode, bool forceAccess = false); float GetSignal(ctInteractPath& path); void FireActions(enum ctInteractActionDispatchPhase phase, void (*callback)(const char* path, float value, void* user), void* userdata = NULL); void LogContents(); void DebugImGui(); void _ReloadClear(); #if CITRUS_INCLUDE_AUDITION ctHotReloadCategory configHotReload; #endif private: ctDynamicArray<ctInteractPath> activeActionSets; ctHashTable<ctInteractNode, uint64_t> nodes; }; /* --------------------------- Bindings --------------------------- */ struct ctInteractBindingEntry { ctInteractPath path; float scale; float clampMin = -FLT_MAX; float clampMax = FLT_MAX; bool required; bool invert; }; class CT_API ctInteractBinding { public: float value; void Process(ctInteractDirectorySystem& dir); ctDynamicArray<ctInteractBindingEntry> inputs; ctInteractPath output; }; /* --------------------------- Actions --------------------------- */ enum ctInteractActionDispatchPhase { CT_INTERACT_ACTIONDISPATCH_NONE, CT_INTERACT_ACTIONDISPATCH_UPDATE, CT_INTERACT_ACTIONDISPATCH_TICK, CT_INTERACT_ACTIONDISPATCH_COUNT, CT_INTERACT_ACTIONDISPATCH_MAX = UINT8_MAX }; struct ctInteractActionEntry { ctInteractPath path; ctInteractPath velocityPath; ctInteractActionDispatchPhase phase; }; /* --------------------------- Action Sets --------------------------- */ class CT_API ctInteractActionSet { public: ctDynamicArray<ctInteractPath> bindings; ctDynamicArray<ctInteractActionEntry> actions; ctDynamicArray<float> actionOutputs; ctDynamicArray<float> actionPrevious; ctDynamicArray<float> actionVelocities; }; /* ---------------------------------- Engine ---------------------------------- */ class CT_API ctInteractionEngine : public ctModuleBase { public: ctResults Startup() final; ctResults Shutdown() final; ctResults RegisterAll(); ctResults PumpInput(); void DebugImGui(); ctInteractDirectorySystem Directory; bool isFrameActive; protected: ctDynamicArray<class ctInteractAbstractBackend*> pBackends; };
/* * ViaStation.hpp * * Created on: 2-apr.-2013 * Author: Sam */ #ifndef VIASTATION_HPP_ #define VIASTATION_HPP_ #include <QObject> #include <QDateTime> class ViaStation : public QObject { Q_OBJECT Q_SIGNALS: void nameChanged(const QString &name); void directionChanged(const QString &direction); void arrivalTimeChanged(const QDateTime &arrivalTime); void arrivalPlatformChanged(const int platform); void departureTimeChanged(const QDateTime &departureTime); void departurePlatformChanged(const int platform); private: QString name; QString direction; QDateTime arrivalTime; int arrivalPlatform; QDateTime departureTime; int departurePlatform; public: ViaStation(const QString &name, const QString &direction, const QDateTime &arrival, int arrivalPlatform, const QDateTime &departure, int departurePlatform); QString getName() const; void setName(const QString &name); QString getDirection() const; void setDirection(const QString &direction); QDateTime getArrivalTime() const; void setArrivalTime(const QDateTime &arrivalTime); int getArrivalPlatform() const; void setArrivalPlatform(int arrivalPlatform); QDateTime getDepartureTime() const; void setDepartureTime(const QDateTime &departureTime); int getDeparturePlatform() const; void setDeparturePlatform(int departurePlatform); }; #endif /* VIASTATION_HPP_ */
//-***************************************************************************** // Copyright (c) 2001-2013, Christopher Jon Horvath. 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 Christopher Jon Horvath nor the names of his // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <EmldCore/Util/All.h> #include <vector> #include <stdio.h> #include <stdlib.h> #include <iostream> namespace hu = EmldCore::Util; int main(int argc, char* argv[]) { hu::V3d g; hu::set_zero(g); hu::UniformRand rand; std::vector<float> v; for (int i = 0; i < 100; ++i) { v.push_back(static_cast<float>(rand())); } const float* vdata = hu::vector_cdata(v); for (int i = 0; i < 100; ++i) { std::cout << vdata[i] << std::endl; } hu::VectorHashKey vkey = hu::ComputeVectorHashKey(v); std::cout << "Vector hash key: " << vkey << std::endl; return 0; }
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "common/base/Base.h" #include "common/base/SignalHandler.h" #include "common/webservice/Router.h" #include "common/webservice/WebService.h" #include "common/network/NetworkUtils.h" #include "common/process/ProcessUtils.h" #include "common/hdfs/HdfsHelper.h" #include "common/hdfs/HdfsCommandHelper.h" #include "common/thread/GenericThreadPool.h" #include <thrift/lib/cpp2/server/ThriftServer.h> #include "kvstore/PartManager.h" #include "kvstore/NebulaStore.h" #include "meta/MetaServiceHandler.h" #include "meta/MetaHttpIngestHandler.h" #include "meta/MetaHttpDownloadHandler.h" #include "meta/MetaHttpReplaceHostHandler.h" #include "meta/KVBasedClusterIdMan.h" #include "meta/ActiveHostsMan.h" #include "meta/processors/jobMan/JobManager.h" #include "meta/RootUserMan.h" #include "meta/MetaServiceUtils.h" using nebula::operator<<; using nebula::ProcessUtils; using nebula::Status; using nebula::web::PathParams; DEFINE_string(local_ip, "", "Local ip specified for NetworkUtils::getLocalIP"); DEFINE_int32(port, 45500, "Meta daemon listening port"); DEFINE_bool(reuse_port, true, "Whether to turn on the SO_REUSEPORT option"); DEFINE_string(data_path, "", "Root data path"); DEFINE_string(meta_server_addrs, "", "It is a list of IPs split by comma, used in cluster deployment" "the ips number is equal to the replica number." "If empty, it means it's a single node"); // DEFINE_string(local_ip, "", "Local ip specified for NetworkUtils::getLocalIP"); DEFINE_int32(num_io_threads, 16, "Number of IO threads"); DEFINE_int32(meta_http_thread_num, 3, "Number of meta daemon's http thread"); DEFINE_int32(num_worker_threads, 32, "Number of workers"); DEFINE_string(pid_file, "pids/nebula-metad.pid", "File to hold the process id"); DEFINE_bool(daemonize, true, "Whether run as a daemon process"); DECLARE_bool(check_leader); DEFINE_bool(upgrade_meta_data, false, "old stored meta data may have different format " " set to true to do meta data upgrade"); static std::unique_ptr<apache::thrift::ThriftServer> gServer; static std::unique_ptr<nebula::kvstore::KVStore> gKVStore; static void signalHandler(int sig); static Status setupSignalHandler(); namespace nebula { namespace meta { const std::string kClusterIdKey = "__meta_cluster_id_key__"; // NOLINT } // namespace meta } // namespace nebula nebula::ClusterID gClusterId = 0; std::unique_ptr<nebula::kvstore::KVStore> initKV(std::vector<nebula::HostAddr> peers, nebula::HostAddr localhost) { auto partMan = std::make_unique<nebula::kvstore::MemPartManager>(); // The meta server has only one space (0), one part (0) partMan->addPart(nebula::meta::kDefaultSpaceId, nebula::meta::kDefaultPartId, std::move(peers)); // folly IOThreadPoolExecutor auto ioPool = std::make_shared<folly::IOThreadPoolExecutor>(FLAGS_num_io_threads); std::shared_ptr<apache::thrift::concurrency::ThreadManager> threadManager( apache::thrift::concurrency::PriorityThreadManager::newPriorityThreadManager( FLAGS_num_worker_threads, true /*stats*/)); threadManager->setNamePrefix("executor"); threadManager->start(); // On metad, we are allowed to read on follower FLAGS_check_leader = false; nebula::kvstore::KVOptions options; options.dataPaths_ = {FLAGS_data_path}; options.partMan_ = std::move(partMan); auto kvstore = std::make_unique<nebula::kvstore::NebulaStore>( std::move(options), ioPool, localhost, threadManager); if (!(kvstore->init())) { LOG(ERROR) << "Nebula store init failed"; return nullptr; } LOG(INFO) << "Waiting for the leader elected..."; nebula::HostAddr leader; while (true) { auto ret = kvstore->partLeader(nebula::meta::kDefaultSpaceId, nebula::meta::kDefaultPartId); if (!nebula::ok(ret)) { LOG(ERROR) << "Nebula store init failed"; return nullptr; } leader = nebula::value(ret); if (leader != nebula::HostAddr("", 0)) { break; } LOG(INFO) << "Leader has not been elected, sleep 1s"; sleep(1); } gClusterId = nebula::meta::ClusterIdMan::getClusterIdFromKV(kvstore.get(), nebula::meta::kClusterIdKey); if (gClusterId == 0) { if (leader == localhost) { LOG(INFO) << "I am leader, create cluster Id"; gClusterId = nebula::meta::ClusterIdMan::create(FLAGS_meta_server_addrs); if (!nebula::meta::ClusterIdMan::persistInKV(kvstore.get(), nebula::meta::kClusterIdKey, gClusterId)) { LOG(ERROR) << "Persist cluster failed!"; return nullptr; } } else { LOG(INFO) << "I am follower, wait for the leader's clusterId"; while (gClusterId == 0) { LOG(INFO) << "Waiting for the leader's clusterId"; sleep(1); gClusterId = nebula::meta::ClusterIdMan::getClusterIdFromKV( kvstore.get(), nebula::meta::kClusterIdKey); } } } if (FLAGS_upgrade_meta_data) { nebula::meta::MetaServiceUtils::upgradeMetaDataV1toV2(kvstore.get()); } LOG(INFO) << "Nebula store init succeeded, clusterId " << gClusterId; return kvstore; } Status initWebService(nebula::WebService* svc, nebula::kvstore::KVStore* kvstore, nebula::hdfs::HdfsCommandHelper* helper, nebula::thread::GenericThreadPool* pool) { LOG(INFO) << "Starting Meta HTTP Service"; auto& router = svc->router(); router.get("/download-dispatch").handler([kvstore, helper, pool](PathParams&&) { auto handler = new nebula::meta::MetaHttpDownloadHandler(); handler->init(kvstore, helper, pool); return handler; }); router.get("/ingest-dispatch").handler([kvstore, pool](PathParams&&) { auto handler = new nebula::meta::MetaHttpIngestHandler(); handler->init(kvstore, pool); return handler; }); router.get("/replace").handler([kvstore](PathParams &&) { auto handler = new nebula::meta::MetaHttpReplaceHostHandler(); handler->init(kvstore); return handler; }); return svc->start(); } int main(int argc, char *argv[]) { // Detect if the server has already been started // Check pid before glog init, in case of user may start daemon twice // the 2nd will make the 1st failed to output log anymore gflags::ParseCommandLineFlags(&argc, &argv, false); auto pidPath = FLAGS_pid_file; auto status = ProcessUtils::isPidAvailable(pidPath); if (!status.ok()) { LOG(ERROR) << status; return EXIT_FAILURE; } google::SetVersionString(nebula::versionString()); folly::init(&argc, &argv, true); if (FLAGS_data_path.empty()) { LOG(ERROR) << "Meta Data Path should not empty"; return EXIT_FAILURE; } if (FLAGS_daemonize) { google::SetStderrLogging(google::FATAL); } else { google::SetStderrLogging(google::INFO); } if (FLAGS_daemonize) { status = ProcessUtils::daemonize(pidPath); if (!status.ok()) { LOG(ERROR) << status; return EXIT_FAILURE; } } else { status = ProcessUtils::makePidFile(pidPath); if (!status.ok()) { LOG(ERROR) << status; return EXIT_FAILURE; } } auto hostIdentity = FLAGS_local_ip == "" ? nebula::network::NetworkUtils::getHostname() : FLAGS_local_ip; nebula::HostAddr localhost{hostIdentity, FLAGS_port}; LOG(INFO) << "identify myself as " << localhost; auto peersRet = nebula::network::NetworkUtils::toHosts(FLAGS_meta_server_addrs); if (!peersRet.ok()) { LOG(ERROR) << "Can't get peers address, status:" << peersRet.status(); return EXIT_FAILURE; } gKVStore = initKV(peersRet.value(), localhost); if (gKVStore == nullptr) { LOG(ERROR) << "Init kv failed!"; return EXIT_FAILURE; } LOG(INFO) << "Start http service"; auto helper = std::make_unique<nebula::hdfs::HdfsCommandHelper>(); auto pool = std::make_unique<nebula::thread::GenericThreadPool>(); pool->start(FLAGS_meta_http_thread_num, "http thread pool"); auto webSvc = std::make_unique<nebula::WebService>(); status = initWebService(webSvc.get(), gKVStore.get(), helper.get(), pool.get()); if (!status.ok()) { LOG(ERROR) << "Init web service failed: " << status; return EXIT_FAILURE; } { nebula::meta::JobManager* jobMgr = nebula::meta::JobManager::getInstance(); if (!jobMgr->init(gKVStore.get())) { LOG(ERROR) << "Init job manager failed"; return EXIT_FAILURE; } } { /** * Only leader part needed. */ auto ret = gKVStore->partLeader(nebula::meta::kDefaultSpaceId, nebula::meta::kDefaultPartId); if (!nebula::ok(ret)) { LOG(ERROR) << "Part leader get failed"; return EXIT_FAILURE; } if (nebula::value(ret) == localhost) { LOG(INFO) << "Check and init root user"; if (!nebula::meta::RootUserMan::isUserExists(gKVStore.get())) { if (!nebula::meta::RootUserMan::initRootUser(gKVStore.get())) { LOG(ERROR) << "Init root user failed"; return EXIT_FAILURE; } } } } // Setup the signal handlers status = setupSignalHandler(); if (!status.ok()) { LOG(ERROR) << status; return EXIT_FAILURE; } auto handler = std::make_shared<nebula::meta::MetaServiceHandler>(gKVStore.get(), gClusterId); LOG(INFO) << "The meta deamon start on " << localhost; try { gServer = std::make_unique<apache::thrift::ThriftServer>(); gServer->setPort(FLAGS_port); gServer->setReusePort(FLAGS_reuse_port); gServer->setIdleTimeout(std::chrono::seconds(0)); // No idle timeout on client connection gServer->setInterface(std::move(handler)); gServer->serve(); // Will wait until the server shuts down } catch (const std::exception &e) { LOG(ERROR) << "Exception thrown: " << e.what(); return EXIT_FAILURE; } LOG(INFO) << "The meta Daemon stopped"; return EXIT_SUCCESS; } Status setupSignalHandler() { return nebula::SignalHandler::install( {SIGINT, SIGTERM}, [](nebula::SignalHandler::GeneralSignalInfo *info) { signalHandler(info->sig()); }); } void signalHandler(int sig) { switch (sig) { case SIGINT: case SIGTERM: FLOG_INFO("Signal %d(%s) received, stopping this server", sig, ::strsignal(sig)); if (gServer) { gServer->stop(); } { auto gJobMgr = nebula::meta::JobManager::getInstance(); if (gJobMgr) { gJobMgr->shutDown(); } } if (gKVStore) { gKVStore->stop(); gKVStore.reset(); } break; default: FLOG_ERROR("Signal %d(%s) received but ignored", sig, ::strsignal(sig)); } }
/*Unary is a minimalistic Brainfuck dialect in which programs are written using only one token. Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table: ">"  →  1000, "<"  →  1001, "+"  →  1010, "-"  →  1011, "."  →  1100, ","  →  1101, "["  →  1110, "]"  →  1111. Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system — this is the Unary program equivalent to the original Brainfuck one. You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo 1000003 (106 + 3). Input The input will consist of a single line p which gives a Brainfuck program. String p will contain between 1 and 100 characters, inclusive. Each character of p will be "+", "-", "[", "]", "<", ">", "." or ",". Output Output the size of the equivalent Unary program modulo 1000003 (106 + 3). Examples Input Copy ,. Output Copy 220 Input Copy ++++[>,.<-] Output Copy 61425 Note To write a number n in unary numeral system, one simply has to write 1 n times. For example, 5 written in unary system will be 11111. In the first example replacing Brainfuck commands with binary code will give us 1101 1100. After we concatenate the codes, we'll get 11011100 in binary system, or 220 in decimal. That's exactly the number of tokens in the equivalent Unary program. */ #include <cstdio> int main() { char p[101]; scanf("%s", p); int size(0); for (size_t i = 0; p[i] != 0; ++i) { size *= 16; switch (p[i]) { case '>': size += 8; break; case '<': size += 9; break; case '+': size += 10; break; case '-': size += 11; break; case '.': size += 12; break; case ',': size += 13; break; case '[': size += 14; break; case ']': size += 15; break; default: break; } size %= 1000003; } printf("%d\n", size); return 0; }
#ifndef CHAIN_HANDLER_HPP #define CHAIN_HANDLER_HPP #include "handler.hpp" namespace coap { template<class First, class Second> class ChainHandler : public Handler { protected: First& _first; Second& _second; public: ChainHandler(First& first, Second& second) : _first(first), _second(second) { } inline ReturnCode handle(const PacketReader& req, PacketBuilder& res) { { ReturnCode rc = _first.handle(req, res); if(rc != ReturnCode::NEXT_HANDLER) { return rc; } } { ReturnCode rc = _second.handle(req, res); if(rc != ReturnCode::NEXT_HANDLER) { return rc; } } return ReturnCode::NEXT_HANDLER; } }; } #endif//CHAIN_HANDLER_HPP
#pragma once #include <vector> #include <GL/glew.h> #include <glm/glm.hpp> #include "Object3D.hpp" #define PI 3.1415927f void printVec(glm::vec3 v); void addDebugVector(Mesh& mesh, const glm::vec3 start, const glm::vec3 end, const glm::vec4 color); const glm::vec3 ClosestCirlePoint(const glm::vec3 mid, const float r, const glm::vec3 p);
#include <algorithm> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; // https://www.reddit.com/r/dailyprogrammer/comments/4xy6i1/20160816_challenge_279_easy_uuencoding/ // INCOMPLETE string decToBinaryString(int decimal, int requiredLength) { string out = ""; while (decimal) { out = to_string(decimal & 1) + out; decimal >>= 1; } out = string(max(0, (requiredLength - (int)out.size()) ), '0') + out; return out; } int stringBinaryToDec(string binary) { int out; for (size_t i=0; i<binary.size(); i++) { if (binary[i] == '1') { out += pow(2, binary.size() - 1 - i); } } return out; } string uuencode(string message) { string encoded = "begin 644 file.txt\n"; string totalBinaryStr; // Break it down first for (int c : message) { string binaryStr = decToBinaryString(c, 8); totalBinaryStr += binaryStr; cout << c << " : " << binaryStr << endl; } cout << endl; cout << "totalBinaryStr: " << totalBinaryStr << endl; // Break totalBinaryStr into four groups of binary int quarterSize = totalBinaryStr.size() / 4; string lineString; for (int i=0; i<totalBinaryStr.size(); i += quarterSize) { string stringQuarter = totalBinaryStr.substr(i, quarterSize); // cout << "stringQuarter: " << stringQuarter << endl; int decimalQuarter = stringBinaryToDec(stringQuarter) + 32; lineString += decimalQuarter; cout << (char)decimalQuarter << endl; } lineString = char(45 + (int)lineString.size()) + lineString; cout << "lineString: " << lineString << endl; encoded += "`\nend\n"; cout << "Encoded: \n" << encoded << endl; return "A"; } int main() { string message; getline(cin, message); // if looksLikePath(message) open a file cout << uuencode(message) << endl; }
// Copyright (c) 2020 The Widecoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <chainparamsbase.h> #include <net.h> #include <net_permissions.h> #include <netaddress.h> #include <optional.h> #include <protocol.h> #include <random.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <cstdint> #include <string> #include <vector> void initialize() { static const BasicTestingSetup basic_testing_setup; } void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::optional<CAddress> address = ConsumeDeserializable<CAddress>(fuzzed_data_provider); if (!address) { return; } const std::optional<CAddress> address_bind = ConsumeDeserializable<CAddress>(fuzzed_data_provider); if (!address_bind) { return; } CNode node{fuzzed_data_provider.ConsumeIntegral<NodeId>(), static_cast<ServiceFlags>(fuzzed_data_provider.ConsumeIntegral<uint64_t>()), fuzzed_data_provider.ConsumeIntegral<int>(), INVALID_SOCKET, *address, fuzzed_data_provider.ConsumeIntegral<uint64_t>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>(), *address_bind, fuzzed_data_provider.ConsumeRandomLengthString(32), fuzzed_data_provider.PickValueInArray({ConnectionType::INBOUND, ConnectionType::OUTBOUND_FULL_RELAY, ConnectionType::MANUAL, ConnectionType::FEELER, ConnectionType::BLOCK_RELAY, ConnectionType::ADDR_FETCH}), fuzzed_data_provider.ConsumeBool()}; while (fuzzed_data_provider.ConsumeBool()) { switch (fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 11)) { case 0: { node.CloseSocketDisconnect(); break; } case 1: { node.MaybeSetAddrName(fuzzed_data_provider.ConsumeRandomLengthString(32)); break; } case 2: { node.SetCommonVersion(fuzzed_data_provider.ConsumeIntegral<int>()); break; } case 3: { const std::vector<bool> asmap = ConsumeRandomLengthBitVector(fuzzed_data_provider); if (!SanityCheckASMap(asmap)) { break; } CNodeStats stats; node.copyStats(stats, asmap); break; } case 4: { const CNode* add_ref_node = node.AddRef(); assert(add_ref_node == &node); break; } case 5: { if (node.GetRefCount() > 0) { node.Release(); } break; } case 6: { if (node.m_addr_known == nullptr) { break; } const std::optional<CAddress> addr_opt = ConsumeDeserializable<CAddress>(fuzzed_data_provider); if (!addr_opt) { break; } node.AddAddressKnown(*addr_opt); break; } case 7: { if (node.m_addr_known == nullptr) { break; } const std::optional<CAddress> addr_opt = ConsumeDeserializable<CAddress>(fuzzed_data_provider); if (!addr_opt) { break; } FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)}; node.PushAddress(*addr_opt, fast_random_context); break; } case 8: { const std::optional<CInv> inv_opt = ConsumeDeserializable<CInv>(fuzzed_data_provider); if (!inv_opt) { break; } node.AddKnownTx(inv_opt->hash); break; } case 9: { node.PushTxInventory(ConsumeUInt256(fuzzed_data_provider)); break; } case 10: { const std::optional<CService> service_opt = ConsumeDeserializable<CService>(fuzzed_data_provider); if (!service_opt) { break; } node.SetAddrLocal(*service_opt); break; } case 11: { const std::vector<uint8_t> b = ConsumeRandomLengthByteVector(fuzzed_data_provider); bool complete; node.ReceiveMsgBytes((const char*)b.data(), b.size(), complete); break; } } } (void)node.GetAddrLocal(); (void)node.GetAddrName(); (void)node.GetId(); (void)node.GetLocalNonce(); (void)node.GetLocalServices(); (void)node.GetMyStartingHeight(); const int ref_count = node.GetRefCount(); assert(ref_count >= 0); (void)node.GetCommonVersion(); (void)node.RelayAddrsWithConn(); const NetPermissionFlags net_permission_flags = fuzzed_data_provider.ConsumeBool() ? fuzzed_data_provider.PickValueInArray<NetPermissionFlags>({NetPermissionFlags::PF_NONE, NetPermissionFlags::PF_BLOOMFILTER, NetPermissionFlags::PF_RELAY, NetPermissionFlags::PF_FORCERELAY, NetPermissionFlags::PF_NOBAN, NetPermissionFlags::PF_MEMPOOL, NetPermissionFlags::PF_ISIMPLICIT, NetPermissionFlags::PF_ALL}) : static_cast<NetPermissionFlags>(fuzzed_data_provider.ConsumeIntegral<uint32_t>()); (void)node.HasPermission(net_permission_flags); (void)node.ConnectedThroughNetwork(); }
#include <bits/stdc++.h> #define lc (rt<<1) #define rc (rt<<1|1) #define nl (tree[rt].l) #define nr (tree[rt].r) #define m ((nl+nr)>>1) #define gc getchar_unlocked() #define pc(x) putchar_unlocked(x) template<typename T> void scan(T &x) {x = 0;register bool _=0;register T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;} template<typename T> void print(T n) {register bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=n%10+48;n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);pc(32);} template<typename First, typename ... Ints> void scan(First &arg, Ints&... rest) {scan(arg);scan(rest...);} using namespace std; const int MM = 1e5+1; int N, M, K, a[MM], order[21], cnt[21]; struct node{ int l, r, lp, cnt[21]; } tree[MM*3]; void push_up(int rt){ for(int i = 1; i <= K; i++) tree[rt].cnt[i] = tree[lc].cnt[i] + tree[rc].cnt[i]; } void push_down(int rt){ int &v = tree[rt].lp; if(v){ memset(tree[rt].cnt, 0, sizeof tree[rt].cnt); tree[rt].cnt[v] = nr-nl+1; if(nl ^ nr) tree[lc].lp = tree[rc].lp = v; v = 0; } } void build(int l, int r, int rt = 1){ nl = l, nr = r; if(l == r){ tree[rt].cnt[a[l]] = 1; return; } build(l, m, lc); build(m+1, r, rc); push_up(rt); } void update(int l, int r, int n, int rt = 1){ push_down(rt); if(r < nl || l > nr) return; if(l <= nl && r >= nr){ tree[rt].lp = n; push_down(rt); return; } update(l, r, n, lc); update(l, r, n, rc); push_up(rt); } int query(int l, int r, int n, int rt = 1){ if(r < nl || l > nr) return 0; push_down(rt); if(l <= nl && r >= nr) return tree[rt].cnt[n]; int ret = query(l, r, n, lc) + query(l, r, n, rc); return ret; } int main(){ scan(N, M, K); for(int i = 1; i <= N; i++) scan(a[i]); build(1, N); for(int i = 0,l,r; i < M; i++){ memset(cnt, 0, sizeof cnt); scan(l, r); for(int k = 1; k <= K; k++){ scan(order[k]); cnt[k] = query(l, r, k); } if(l == r) continue; int last = l; for(int j = 1,k; j <= K; j++){ k = order[j]; if(cnt[k]){ update(last, last+cnt[k]-1, k); last += cnt[k]; } } } for(int i = 1; i <= N; i++){ for(int k = 1; k <= K; k++){ if(query(i, i, k)){ print(k); break; } } } return 0; }
#include "driver.h" extern "C" __declspec( dllexport ) UINT_PTR DriverControl( ULONG uCode, UINT_PTR uParam1, UINT_PTR uParam2, UINT_PTR uParam3 ) { UNREFERENCED_PARAMETER( uParam1 ); UNREFERENCED_PARAMETER( uParam2 ); UNREFERENCED_PARAMETER( uParam3 ); DbgPrint( "control code: %d\n", uCode ); // Main switch struct switch ( uCode ) { case ID_READ_PROCESS_MEMORY: return read_virtual_memory( reinterpret_cast<PMEMORY_STRUCT>( uParam1 ) ); case ID_READ_KERNEL_MEMORY: return read_kernel_memory( reinterpret_cast<PVOID>( uParam1 ), // address reinterpret_cast<PVOID>( uParam2 ), // buffer uParam3 ); // size case ID_WRITE_PROCESS_MEMORY: return write_virtual_memory( reinterpret_cast<PMEMORY_STRUCT>( uParam1 ) ); case ID_GET_PROCESS: return reinterpret_cast<UINT_PTR>( get_process( reinterpret_cast<HANDLE>( uParam1 ) ) ); // process id case ID_GET_PROCESS_BASE: return reinterpret_cast<UINT_PTR>( get_process_base( reinterpret_cast<HANDLE>( uParam1 ) ) ); // process id case ID_GET_PROCESS_MODULE: return reinterpret_cast<UINT_PTR>( get_process_module_base( reinterpret_cast<HANDLE>( uParam1 ), // process id L"kernel32.dll" // module name ) ); default: break; } return 0; } NTSTATUS DriverEntry( struct _DRIVER_OBJECT* DriverObject, PUNICODE_STRING RegistryPath ) { UNREFERENCED_PARAMETER( DriverObject ); UNREFERENCED_PARAMETER( RegistryPath ); // this function will be hooked in kernel to point to the control routine above UINT_PTR hook_function = reinterpret_cast<UINT_PTR>( get_system_module_export( L"win32kbase.sys", "NtGdiDdDDINetDispQueryMiracastDisplayDeviceStatus" ) ); DbgPrint( "> hook_function %llx\n", hook_function ); // parse offset // .text : 00000001C00DA5B0 48 83 EC 28 sub rsp, 28h // .text : 00000001C00DA5B4 48 8B 05 AD 8E 0D 00 mov rax, cs : qword_1C01B3468; UINT_PTR hook_pointer = *( DWORD *)( hook_function + 7 ); hook_pointer += 0xB; hook_pointer += hook_function; DbgPrint( "> hook_pointer offset %llx\n", hook_pointer ); // //memcpy( reinterpret_cast<PVOID>( hook_pointer ), &DriverControl, sizeof( PVOID ) ); //DbgPrint( "> hooked\n" ); return STATUS_SUCCESS; }
/** * 3.4.1 使用迭代器 * @Author Bob * @Eamil 0haizhu0@gmail.com * @Date 2017/7/24 */ #include <string> #include <vector> #include <iostream> using std::string; using std::vector; using std::cout; using std::endl; int main() { vector<string> v; auto b = v.begin(), e = v.end(); // begin 获取指向第一个元素的迭代器,end获取尾元素下一个位置的迭代器;当vector为空时,两者相等 // cout << b << endl; // TODO 为什么不能打印b? cout << (b == e) << endl; /** * *iter 返回迭代器iter所指元素的引用 * iter -> men 解引用iter,并获取该元素的名为mem成员,等价于(*iter).mem * ++iter 令iter指示容器中的下一个元素 * --iter 令iter指示容器中的上一个元素 * iter1 == iter2 如果两者指示的是同一个元素或者是同一个元素的尾后迭代器,则相等 * iter1 != iter2 反之,不相等 */ string s("some string"); // string 和 vector一样,可以使用迭代器 if (s.begin() != s.end()) { auto it = s.begin(); // 获取到it,这是拷贝还是引用? *it = toupper(*it); // 为什么获取到it之后,还可以定义 *it ? cout << "it=" << *it << endl; } cout << "s = " << s << endl; // 将迭代器从一个元素移动到另外一个元素 for (auto it = s.begin(); it != s.end() & !isspace(*it); ++it) { // 依次处理直至结束或者遇到空白字符 *it = toupper(*it); } cout << "s = " << s << endl; // 迭代器类型 vector<int>::iterator it; // it 能读写 vector<int> 中的元素 string::iterator it2; // it2 能读写 string 中的字符 vector<int>::const_iterator it3; // it3 只能读元素不能写元素 string::const_iterator it4; // it4 只能读字符,不能写字符 // begin 和 end 运算符 vector<int> v2; const vector<int> v3; auto it2 = v2.begin(); // it2 的类型是 vector<int>::iterator auto it3 = v3.begin(); // it3 的类型是 vector<int>::const_iterator // 为了便于获取到 const——iterator类型,C++11 引入了两个新函数 auto it4 = v2.cbegin(); // it4 的类型是 vector<int>::const_iterator // 结合解引用和成员访问操作:iter -> men // 谨记:但凡使用了迭代器的循环体,都不要向迭代器所属的容器添加元素 return 0; }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2018 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Tobias Gödderz //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <typeinfo> #include "gtest/gtest.h" #include <boost/core/demangle.hpp> #include <boost/date_time.hpp> #include <boost/range/combine.hpp> #include "Mocks/LogLevels.h" #include "Agency/AddFollower.h" #include "Agency/FailedLeader.h" #include "Agency/MoveShard.h" #include "Basics/ScopeGuard.h" #include "Cluster/ClusterRepairs.h" #include "Cluster/ResultT.h" #include "Cluster/ServerState.h" #include "Random/RandomGenerator.h" using namespace arangodb; using namespace arangodb::consensus; using namespace arangodb::cluster_repairs; namespace arangodb { bool operator==(AgencyWriteTransaction const& left, AgencyWriteTransaction const& right) { VPackBuilder leftBuilder; VPackBuilder rightBuilder; left.toVelocyPack(leftBuilder); right.toVelocyPack(rightBuilder); return velocypack::NormalizedCompare::equals(leftBuilder.slice(), rightBuilder.slice()); } std::ostream& operator<<(std::ostream& ostream, AgencyWriteTransaction const& trx) { Options optPretty = VPackOptions::Defaults; optPretty.prettyPrint = true; VPackBuilder builder; trx.toVelocyPack(builder); ostream << builder.slice().toJson(&optPretty); return ostream; } std::ostream& operator<<(std::ostream& ostream, std::list<RepairOperation> const& list) { ostream << "std::list<RepairOperation> {\n"; if (!list.empty()) { auto it = list.begin(); ostream << *it << "\n"; for (++it; it != list.end(); ++it) { ostream << ", " << *it << "\n"; } } ostream << "}" << std::endl; return ostream; } std::ostream& operator<<(std::ostream& ostream, std::vector<RepairOperation> const& vector) { ostream << "std::vector<RepairOperation> {\n"; if (!vector.empty()) { auto it = vector.begin(); ostream << *it << "\n"; for (++it; it != vector.end(); ++it) { ostream << ", " << *it << "\n"; } } ostream << "}" << std::endl; return ostream; } template <typename K, typename V> std::ostream& operator<<(std::ostream& ostream, std::map<K, V> const& map) { std::string const typeNameK = boost::core::demangle(typeid(K).name()); std::string const typeNameV = boost::core::demangle(typeid(V).name()); ostream << "std::map<" << typeNameK << ", " << typeNameV << "> {\n"; if (!map.empty()) { auto it = map.begin(); ostream << it->first << " => " << it->second << "\n"; for (++it; it != map.end(); ++it) { ostream << ", " << it->first << " => " << it->second << "\n"; } } ostream << "}" << std::endl; return ostream; } template <typename T> std::ostream& operator<<(std::ostream& stream, ResultT<T> const& result) { // clang-format off std::string const typeName = typeid(T) == typeid(RepairOperation) ? "RepairOperation" : typeid(T) == typeid(std::list<RepairOperation>) ? "std::list<RepairOperation>" : typeid(T) == typeid(std::vector<RepairOperation>) ? "std::vector<RepairOperation>" : boost::core::demangle(typeid(T).name()); // clang-format on if (result.ok()) { return stream << "ResultT<" << typeName << "> {" << "val = " << result.get() << " }"; } return stream << "ResultT<" << typeName << "> {" << "errorNumber = " << result.errorNumber() << ", " << "errorMessage = \"" << result.errorMessage() << "\" }"; } namespace tests { namespace cluster_repairs_test { VPackBufferPtr vpackFromJsonString(char const* c) { Options options; options.checkAttributeUniqueness = true; VPackParser parser(&options); parser.parse(c); std::shared_ptr<VPackBuilder> builder = parser.steal(); return builder->steal(); } VPackBufferPtr operator"" _vpack(const char* json, size_t) { return vpackFromJsonString(json); } class ClusterRepairsTest : public ::testing::Test { protected: void checkAgainstExpectedOperations( VPackBufferPtr const& planCollections, VPackBufferPtr const& supervisionHealth, std::map<CollectionID, ResultT<std::vector<RepairOperation>>> expectedRepairOperationsByCollection) { ResultT<std::map<CollectionID, ResultT<std::list<RepairOperation>>>> repairOperationsByCollectionResult = DistributeShardsLikeRepairer::repairDistributeShardsLike( VPackSlice(planCollections->data()), VPackSlice(supervisionHealth->data())); ASSERT_TRUE(repairOperationsByCollectionResult.ok()); std::map<CollectionID, ResultT<std::list<RepairOperation>>>& repairOperationsByCollection = repairOperationsByCollectionResult.get(); { std::stringstream expectedOperationsStringStream; expectedOperationsStringStream << "{" << std::endl; for (auto const& it : expectedRepairOperationsByCollection) { std::string const& collection = it.first; ResultT<std::vector<RepairOperation>> const& expectedRepairResult = it.second; expectedOperationsStringStream << "\"" << collection << "\": \n"; expectedOperationsStringStream << expectedRepairResult << std::endl; } expectedOperationsStringStream << "}"; std::stringstream repairOperationsStringStream; repairOperationsStringStream << "{" << std::endl; for (auto const& it : repairOperationsByCollection) { std::string const& collection = it.first; ResultT<std::list<RepairOperation>> const repairOperationsResult = it.second; repairOperationsStringStream << "\"" << collection << "\": \n"; repairOperationsStringStream << repairOperationsResult << std::endl; } repairOperationsStringStream << "}"; ASSERT_TRUE(repairOperationsByCollection.size() == expectedRepairOperationsByCollection.size()); for (auto const& it : boost::combine(expectedRepairOperationsByCollection, repairOperationsByCollection)) { auto const& expectedResult = it.get<0>().second; auto const& actualResult = it.get<1>().second; ASSERT_EQ(expectedResult.ok(), actualResult.ok()); if (expectedResult.ok()) { ASSERT_EQ(expectedResult.get().size(), actualResult.get().size()); } } } for (auto const& it : boost::combine(repairOperationsByCollection, expectedRepairOperationsByCollection)) { std::string const& collection = it.get<0>().first; ResultT<std::list<RepairOperation>> const repairResult = it.get<0>().second; std::string const& expectedCollection = it.get<1>().first; ResultT<std::vector<RepairOperation>> const& expectedResult = it.get<1>().second; ASSERT_EQ(collection, expectedCollection); ASSERT_EQ(repairResult.ok(), expectedResult.ok()); if (expectedResult.ok()) { std::list<RepairOperation> const& repairOperations = repairResult.get(); std::vector<RepairOperation> const& expectedOperations = expectedResult.get(); for (auto const& it : boost::combine(repairOperations, expectedOperations)) { auto const& repairOpIt = it.get<0>(); auto const& expectedRepairOpIt = it.get<1>(); ASSERT_EQ(repairOpIt, expectedRepairOpIt); } } else { ASSERT_EQ(repairResult, expectedResult); } } } }; class ClusterRepairsTestBrokenDistribution : public ClusterRepairsTest, public tests::LogSuppressor<Logger::CLUSTER, LogLevel::FATAL>, public tests::LogSuppressor<Logger::FIXME, LogLevel::FATAL> { protected: // save old manager (may be null) std::unique_ptr<AgencyCommManager> oldManager; ClusterRepairsTestBrokenDistribution() : oldManager(std::move(AgencyCommManager::MANAGER)) { // get a new manager AgencyCommManager::initialize("testArangoAgencyPrefix"); } ~ClusterRepairsTestBrokenDistribution() { // restore old manager AgencyCommManager::MANAGER = std::move(oldManager); } }; TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_where_on_two_shards_the_dbservers_are_swapped_one_unused_dbserver_is_free_to_exchange_the_leader) { #include "ClusterRepairsTest.swapWithLeader.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth3Healthy0Bad, expectedResultsWithTwoSwappedDBServers); } TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_where_on_two_shards_the_dbservers_are_swapped_the_unused_dbserver_is_marked_as_nonhealthy) { #include "ClusterRepairsTest.unusedServerUnhealthy.cpp" auto result = DistributeShardsLikeRepairer::repairDistributeShardsLike( VPackSlice(planCollections->data()), VPackSlice(supervisionHealth2Healthy1Bad->data())); ASSERT_TRUE(result.ok()); std::map<CollectionID, ResultT<std::list<RepairOperation>>> operationResultByCollectionId = result.get(); ASSERT_EQ(operationResultByCollectionId.size(), 1); ASSERT_TRUE(operationResultByCollectionId.find("11111111") != operationResultByCollectionId.end()); ResultT<std::list<RepairOperation>> collectionResult = operationResultByCollectionId.at("11111111"); ASSERT_EQ(collectionResult.errorNumber(), TRI_ERROR_CLUSTER_REPAIRS_NOT_ENOUGH_HEALTHY); ASSERT_TRUE(0 == strcmp(TRI_errno_string(collectionResult.errorNumber()), "not enough (healthy) db servers")); ASSERT_TRUE(collectionResult.fail()); } TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_where_on_two_shards_the_dbservers_are_swapped_the_replicationfactor_equals_the_number_of_dbservers) { #include "ClusterRepairsTest.replicationFactorTooHigh.cpp" auto result = DistributeShardsLikeRepairer::repairDistributeShardsLike( VPackSlice(planCollections->data()), VPackSlice(supervisionHealth2Healthy0Bad->data())); ASSERT_TRUE(result.ok()); std::map<CollectionID, ResultT<std::list<RepairOperation>>> operationResultByCollectionId = result.get(); ASSERT_EQ(operationResultByCollectionId.size(), 1); ASSERT_TRUE(operationResultByCollectionId.find("11111111") != operationResultByCollectionId.end()); ResultT<std::list<RepairOperation>> collectionResult = operationResultByCollectionId.at("11111111"); ASSERT_EQ(collectionResult.errorNumber(), TRI_ERROR_CLUSTER_REPAIRS_NOT_ENOUGH_HEALTHY); ASSERT_TRUE(0 == strcmp(TRI_errno_string(collectionResult.errorNumber()), "not enough (healthy) db servers")); ASSERT_TRUE(collectionResult.fail()); } TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_where_differently_ordered_followers_have_to_be_moved) { #include "ClusterRepairsTest.moveFollower.cpp" // This test should ensure that the (internal) order in the repairer // after a shard move resembles the one after a real shard move. // i.e., moving a follower puts it to the end of the list, e.g., given // [a, b, c, d] (where a is the leader), moving b to e results in // [a, c, d, e] rather than [a, e, c, d]. checkAgainstExpectedOperations(planCollections, supervisionHealth4Healthy0Bad, expectedResultsWithFollowerOrder); } TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_where_a_follower_shard_has_erroneously_ordered_dbservers) { #include "ClusterRepairsTest.unorderedFollowers.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth4Healthy0Bad, expectedResultsWithWronglyOrderedFollowers); } TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_where_a_collection_has_repairing_distributshardslike_but_nothing_else_is_broken) { #include "ClusterRepairsTest.repairingDistributeShardsLike.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth4Healthy0Bad, expectedResultsWithRepairingDistributeShardsLike); } TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_where_a_collection_has_repairing_distributshardslike_but_the_replicationfactor_differs) { #include "ClusterRepairsTest.repairingDslChangedRf.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth4Healthy0Bad, expectedResultsWithRepairingDistributeShardsLike); } TEST_F(ClusterRepairsTestBrokenDistribution, an_agency_with_multiple_collections) { #include "ClusterRepairsTest.multipleCollections.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth4Healthy0Bad, expectedResultsWithMultipleCollections); } TEST_F(ClusterRepairsTestBrokenDistribution, a_collection_with_multiple_shards) { #include "ClusterRepairsTest.multipleShards.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth3Healthy0Bad, expectedResultsWithMultipleShards); } TEST_F(ClusterRepairsTestBrokenDistribution, a_collection_where_the_replicationfactor_doesnt_conform_with_its_prototype) { #include "ClusterRepairsTest.unequalReplicationFactor.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth3Healthy0Bad, expectedResultsWithUnequalReplicationFactor); } TEST_F(ClusterRepairsTestBrokenDistribution, a_smart_graph_with_some_broken_collections) { #include "ClusterRepairsTest.smartCollections.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth3Healthy0Bad, expectedResultsWithSmartGraph); } TEST_F(ClusterRepairsTestBrokenDistribution, a_satellite_collection) { #include "ClusterRepairsTest.satelliteCollection.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth3Healthy0Bad, expectedResultsWithSatelliteCollection); } TEST_F(ClusterRepairsTestBrokenDistribution, a_collection_that_should_usually_be_fixed_but_is_deleted) { #include "ClusterRepairsTest.deletedCollection.cpp" checkAgainstExpectedOperations(planCollections, supervisionHealth3Healthy0Bad, expectedResultsWithDeletedCollection); } #ifdef ARANGODB_ENABLE_FAILURE_TESTS TEST_F(ClusterRepairsTestBrokenDistribution, collections_with_triggered_failures) { // NOTE: Some of the collection names used in in the following file would // usually be invalid because they are too long. #include "ClusterRepairsTest.triggeredFailures.cpp" TRI_AddFailurePointDebugging( "DistributeShardsLikeRepairer::createFixServerOrderOperation/" "TRI_ERROR_CLUSTER_REPAIRS_MISMATCHING_LEADERS"); TRI_AddFailurePointDebugging( "DistributeShardsLikeRepairer::createFixServerOrderOperation/" "TRI_ERROR_CLUSTER_REPAIRS_MISMATCHING_FOLLOWERS"); TRI_AddFailurePointDebugging( "DistributeShardsLikeRepairer::repairDistributeShardsLike/" "TRI_ERROR_CLUSTER_REPAIRS_INCONSISTENT_ATTRIBUTES"); TRI_AddFailurePointDebugging( "DistributeShardsLikeRepairer::createBeginRepairsOperation/" "TRI_ERROR_CLUSTER_REPAIRS_INCONSISTENT_ATTRIBUTES"); TRI_AddFailurePointDebugging( "DistributeShardsLikeRepairer::createFinishRepairsOperation/" "TRI_ERROR_CLUSTER_REPAIRS_INCONSISTENT_ATTRIBUTES"); TRI_AddFailurePointDebugging( "DistributeShardsLikeRepairer::repairDistributeShardsLike/" "TRI_ERROR_CLUSTER_REPAIRS_NO_DBSERVERS"); try { checkAgainstExpectedOperations(planCollections, supervisionHealth2Healthy0Bad, expectedResultsWithTriggeredFailures); TRI_ClearFailurePointsDebugging(); } catch (...) { TRI_ClearFailurePointsDebugging(); throw; } } #endif TEST(ClusterRepairsTestVersionSort, different_version_strings) { // Disable cluster logging arangodb::tests::LogSuppressor<Logger::CLUSTER, LogLevel::FATAL> suppressor; // General functionality check EXPECT_TRUE(VersionSort()("s2", "s10")); EXPECT_FALSE(VersionSort()("s10", "s2")); EXPECT_TRUE(VersionSort()("s5", "s7")); EXPECT_FALSE(VersionSort()("s7", "s5")); // Make sure sorting by the last char works EXPECT_TRUE(VersionSort()("s100a", "s0100b")); EXPECT_FALSE(VersionSort()("s0100b", "s100a")); // Make sure the ints aren't casted into signed chars and overflow EXPECT_TRUE(VersionSort()("s126", "s129")); EXPECT_FALSE(VersionSort()("s129", "s126")); // Make sure the ints aren't casted into unsigned chars and overflow EXPECT_TRUE(VersionSort()("s254", "s257")); EXPECT_FALSE(VersionSort()("s257", "s254")); // Regression test EXPECT_TRUE(VersionSort()("s1000057", "s1000065")); EXPECT_FALSE(VersionSort()("s1000065", "s1000057")); EXPECT_TRUE(VersionSort()("s1000050", "s1000064")); EXPECT_FALSE(VersionSort()("s1000064", "s1000050")); } class ClusterRepairsTestOperations : public ClusterRepairsTest, public tests::LogSuppressor<Logger::CLUSTER, LogLevel::FATAL> { protected: std::unique_ptr<AgencyCommManager> oldManager; std::string const oldServerId; RepairOperationToTransactionVisitor conversionVisitor; static uint64_t mockJobIdGenerator() { EXPECT_TRUE(false); return 0ul; } static std::chrono::system_clock::time_point mockJobCreationTimestampGenerator() { EXPECT_TRUE(false); return std::chrono::system_clock::now(); } ClusterRepairsTestOperations() : oldManager(std::move(AgencyCommManager::MANAGER)), oldServerId(ServerState::instance()->getId()), conversionVisitor(mockJobIdGenerator, mockJobCreationTimestampGenerator) { // get a new manager AgencyCommManager::initialize("testArangoAgencyPrefix"); } ~ClusterRepairsTestOperations() { // restore old manager AgencyCommManager::MANAGER = std::move(oldManager); } }; TEST_F(ClusterRepairsTestOperations, a_beginrepairsoperation_with_equal_replicationfactors_and_rename_true_converted_into_an_agencytransaction) { BeginRepairsOperation operation{_database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _collectionReplicationFactor = 3, _protoReplicationFactor = 3, _renameDistributeShardsLike = true}; AgencyWriteTransaction trx; boost::optional<uint64_t> jobid; std::tie(trx, jobid) = conversionVisitor(operation); ASSERT_FALSE(jobid.is_initialized()); VPackBufferPtr protoCollIdVPack = R"=("789876")="_vpack; Slice protoCollIdSlice = Slice(protoCollIdVPack->data()); VPackBufferPtr replicationFactorVPack = R"=(3)="_vpack; Slice replicationFactorSlice = Slice(replicationFactorVPack->data()); AgencyWriteTransaction expectedTrx{ std::vector<AgencyOperation>{ AgencyOperation{ "Plan/Collections/myDbName/123456/distributeShardsLike", AgencySimpleOperationType::DELETE_OP}, AgencyOperation{"Plan/Collections/myDbName/123456/" "repairingDistributeShardsLike", AgencyValueOperationType::SET, protoCollIdSlice}, AgencyOperation{"Plan/Collections/myDbName/123456/replicationFactor", AgencyValueOperationType::SET, replicationFactorSlice}, AgencyOperation{"Plan/Version", AgencySimpleOperationType::INCREMENT_OP}}, std::vector<AgencyPrecondition>{ AgencyPrecondition{"Plan/Collections/myDbName/123456/" "repairingDistributeShardsLike", AgencyPrecondition::Type::EMPTY, true}, AgencyPrecondition{ "Plan/Collections/myDbName/123456/distributeShardsLike", AgencyPrecondition::Type::VALUE, protoCollIdSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/123456/replicationFactor", AgencyPrecondition::Type::VALUE, replicationFactorSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/789876/replicationFactor", AgencyPrecondition::Type::VALUE, replicationFactorSlice}}}; trx.clientId = expectedTrx.clientId = "dummy-client-id"; ASSERT_EQ(trx, expectedTrx); } TEST_F(ClusterRepairsTestOperations, a_beginrepairsoperation_with_equal_replicationfactors_and_rename_true_compared_via_eqeq) { BeginRepairsOperation operation{_database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _collectionReplicationFactor = 3, _protoReplicationFactor = 3, _renameDistributeShardsLike = true}; BeginRepairsOperation other = operation; ASSERT_EQ(operation, other); (other = operation).database = "differing database"; ASSERT_FALSE(operation == other); (other = operation).collectionId = "differing collectionId"; ASSERT_FALSE(operation == other); (other = operation).collectionName = "differing collectionName"; ASSERT_FALSE(operation == other); (other = operation).protoCollectionId = "differing protoCollectionId"; ASSERT_FALSE(operation == other); (other = operation).protoCollectionName = "differing protoCollectionName"; ASSERT_FALSE(operation == other); (other = operation).collectionReplicationFactor = 42; ASSERT_FALSE(operation == other); (other = operation).protoReplicationFactor = 23; ASSERT_FALSE(operation == other); (other = operation).renameDistributeShardsLike = !operation.renameDistributeShardsLike; ASSERT_FALSE(operation == other); } TEST_F(ClusterRepairsTestOperations, a_beginrepairsoperation_with_differing_replicationfactors_and_rename_false_converted_into_an_agencytransaction) { BeginRepairsOperation operation{_database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _collectionReplicationFactor = 5, _protoReplicationFactor = 4, _renameDistributeShardsLike = false}; AgencyWriteTransaction trx; boost::optional<uint64_t> jobid; std::tie(trx, jobid) = conversionVisitor(operation); ASSERT_FALSE(jobid.is_initialized()); VPackBufferPtr protoCollIdVPack = R"=("789876")="_vpack; Slice protoCollIdSlice = Slice(protoCollIdVPack->data()); VPackBufferPtr replicationFactorVPack = R"=(4)="_vpack; Slice replicationFactorSlice = Slice(replicationFactorVPack->data()); AgencyWriteTransaction expectedTrx{ {AgencyOperation{"Plan/Version", AgencySimpleOperationType::INCREMENT_OP}}, std::vector<AgencyPrecondition>{ AgencyPrecondition{ "Plan/Collections/myDbName/123456/distributeShardsLike", AgencyPrecondition::Type::EMPTY, true}, AgencyPrecondition{"Plan/Collections/myDbName/123456/" "repairingDistributeShardsLike", AgencyPrecondition::Type::VALUE, protoCollIdSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/123456/replicationFactor", AgencyPrecondition::Type::VALUE, replicationFactorSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/789876/replicationFactor", AgencyPrecondition::Type::VALUE, replicationFactorSlice}}}; trx.clientId = expectedTrx.clientId = "dummy-client-id"; ASSERT_EQ(trx, expectedTrx); } TEST_F(ClusterRepairsTestOperations, a_beginrepairsoperation_with_differing_replicationfactors_and_rename_true_converted_into_an_agency_transaction) { BeginRepairsOperation operation{_database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _collectionReplicationFactor = 2, _protoReplicationFactor = 5, _renameDistributeShardsLike = true}; AgencyWriteTransaction trx; boost::optional<uint64_t> jobid; std::tie(trx, jobid) = conversionVisitor(operation); ASSERT_FALSE(jobid.is_initialized()); VPackBufferPtr protoCollIdVPack = R"=("789876")="_vpack; Slice protoCollIdSlice = Slice(protoCollIdVPack->data()); VPackBufferPtr replicationFactorVPack = R"=(5)="_vpack; Slice replicationFactorSlice = Slice(replicationFactorVPack->data()); VPackBufferPtr prevReplicationFactorVPack = R"=(2)="_vpack; Slice prevReplicationFactorSlice = Slice(prevReplicationFactorVPack->data()); AgencyWriteTransaction expectedTrx{ std::vector<AgencyOperation>{ AgencyOperation{ "Plan/Collections/myDbName/123456/distributeShardsLike", AgencySimpleOperationType::DELETE_OP}, AgencyOperation{"Plan/Collections/myDbName/123456/" "repairingDistributeShardsLike", AgencyValueOperationType::SET, protoCollIdSlice}, AgencyOperation{"Plan/Collections/myDbName/123456/replicationFactor", AgencyValueOperationType::SET, replicationFactorSlice}, AgencyOperation{"Plan/Version", AgencySimpleOperationType::INCREMENT_OP}}, std::vector<AgencyPrecondition>{ AgencyPrecondition{"Plan/Collections/myDbName/123456/" "repairingDistributeShardsLike", AgencyPrecondition::Type::EMPTY, true}, AgencyPrecondition{ "Plan/Collections/myDbName/123456/distributeShardsLike", AgencyPrecondition::Type::VALUE, protoCollIdSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/123456/replicationFactor", AgencyPrecondition::Type::VALUE, prevReplicationFactorSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/789876/replicationFactor", AgencyPrecondition::Type::VALUE, replicationFactorSlice}}}; trx.clientId = expectedTrx.clientId = "dummy-client-id"; ASSERT_EQ(trx, expectedTrx); } TEST_F(ClusterRepairsTestOperations, a_finishrepairsoperation_converted_into_an_agencytransaction) { FinishRepairsOperation operation{ _database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _shards = std::vector<ShardWithProtoAndDbServers>{ std::make_tuple<ShardID, ShardID, DBServers>( "shard1", "protoShard1", {"dbServer1", "dbServer2"}), std::make_tuple<ShardID, ShardID, DBServers>( "shard2", "protoShard2", {"dbServer2", "dbServer3"})}, _replicationFactor = 3}; AgencyWriteTransaction trx; boost::optional<uint64_t> jobid; std::tie(trx, jobid) = conversionVisitor(operation); ASSERT_FALSE(jobid.is_initialized()); VPackBufferPtr protoIdVPack = R"=("789876")="_vpack; Slice protoIdSlice = Slice(protoIdVPack->data()); VPackBufferPtr replicationFactorVPack = R"=(3)="_vpack; Slice replicationFactorSlice = Slice(replicationFactorVPack->data()); VPackBufferPtr serverOrderVPack1 = R"=(["dbServer1", "dbServer2"])="_vpack; VPackBufferPtr serverOrderVPack2 = R"=(["dbServer2", "dbServer3"])="_vpack; Slice serverOrderSlice1 = Slice(serverOrderVPack1->data()); Slice serverOrderSlice2 = Slice(serverOrderVPack2->data()); AgencyWriteTransaction expectedTrx{ std::vector<AgencyOperation>{ AgencyOperation{"Plan/Collections/myDbName/123456/" "repairingDistributeShardsLike", AgencySimpleOperationType::DELETE_OP}, AgencyOperation{ "Plan/Collections/myDbName/123456/distributeShardsLike", AgencyValueOperationType::SET, protoIdSlice}, AgencyOperation{"Plan/Version", AgencySimpleOperationType::INCREMENT_OP}}, std::vector<AgencyPrecondition>{ AgencyPrecondition{ "Plan/Collections/myDbName/123456/distributeShardsLike", AgencyPrecondition::Type::EMPTY, true}, AgencyPrecondition{"Plan/Collections/myDbName/123456/" "repairingDistributeShardsLike", AgencyPrecondition::Type::VALUE, protoIdSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/123456/replicationFactor", AgencyPrecondition::Type::VALUE, replicationFactorSlice}, AgencyPrecondition{ "Plan/Collections/myDbName/789876/replicationFactor", AgencyPrecondition::Type::VALUE, replicationFactorSlice}, AgencyPrecondition{"Plan/Collections/myDbName/123456/shards/shard1", AgencyPrecondition::Type::VALUE, serverOrderSlice1}, AgencyPrecondition{ "Plan/Collections/myDbName/789876/shards/protoShard1", AgencyPrecondition::Type::VALUE, serverOrderSlice1}, AgencyPrecondition{"Plan/Collections/myDbName/123456/shards/shard2", AgencyPrecondition::Type::VALUE, serverOrderSlice2}, AgencyPrecondition{ "Plan/Collections/myDbName/789876/shards/protoShard2", AgencyPrecondition::Type::VALUE, serverOrderSlice2}}}; trx.clientId = expectedTrx.clientId = "dummy-client-id"; ASSERT_EQ(trx, expectedTrx); } TEST_F(ClusterRepairsTestOperations, a_finishrepairsoperation_compared_via_eqeq) { FinishRepairsOperation operation{ _database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _shards = std::vector<ShardWithProtoAndDbServers>{ std::make_tuple<ShardID, ShardID, DBServers>( "shard1", "protoShard1", {"dbServer1", "dbServer2"}), std::make_tuple<ShardID, ShardID, DBServers>( "shard2", "protoShard2", {"dbServer2", "dbServer3"})}, _replicationFactor = 3}; FinishRepairsOperation other = operation; ASSERT_EQ(operation, other); (other = operation).database = "differing database"; ASSERT_FALSE(operation == other); (other = operation).collectionId = "differing collectionId"; ASSERT_FALSE(operation == other); (other = operation).collectionName = "differing collectionName"; ASSERT_FALSE(operation == other); (other = operation).protoCollectionId = "differing protoCollectionId"; ASSERT_FALSE(operation == other); (other = operation).protoCollectionName = "differing protoCollectionName"; ASSERT_FALSE(operation == other); (other = operation).shards = { std::make_tuple<ShardID, ShardID, DBServers>("differing", "shards", {"vector"})}; ASSERT_FALSE(operation == other); (other = operation).replicationFactor = 42; ASSERT_FALSE(operation == other); } TEST_F(ClusterRepairsTestOperations, a_moveshardoperation_converted_into_an_agencytransaction) { ServerState::instance()->setId("CurrentCoordinatorServerId"); MoveShardOperation operation{_database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _shard = "s1", _from = "db-from-server", _to = "db-to-server", _isLeader = true}; uint64_t nextJobId = 41; auto jobIdGenerator = [&nextJobId]() { return nextJobId++; }; auto jobCreationTimestampGenerator = []() { std::tm tm = {}; tm.tm_year = 2018 - 1900; // years since 1900 tm.tm_mon = 3 - 1; // March, counted from january tm.tm_mday = 7; tm.tm_hour = 15; tm.tm_min = 20; tm.tm_sec = 1; tm.tm_isdst = 0; std::chrono::system_clock::time_point tp = std::chrono::system_clock::from_time_t(TRI_timegm(&tm)); return tp; }; conversionVisitor = RepairOperationToTransactionVisitor(jobIdGenerator, jobCreationTimestampGenerator); AgencyWriteTransaction trx; boost::optional<uint64_t> jobId; std::tie(trx, jobId) = conversionVisitor(operation); ASSERT_TRUE(jobId.is_initialized()); // "timeCreated": "2018-03-07T15:20:01.284Z", VPackBufferPtr todoVPack = R"=( { "type": "moveShard", "database": "myDbName", "collection": "123456", "shard": "s1", "fromServer": "db-from-server", "toServer": "db-to-server", "jobId": "41", "timeCreated": "2018-03-07T15:20:01Z", "creator": "CurrentCoordinatorServerId", "isLeader": true } )="_vpack; Slice todoSlice = Slice(todoVPack->data()); AgencyWriteTransaction expectedTrx{ AgencyOperation{"Target/ToDo/" + std::to_string(jobId.get()), AgencyValueOperationType::SET, todoSlice}, AgencyPrecondition{"Target/ToDo/" + std::to_string(jobId.get()), AgencyPrecondition::Type::EMPTY, true}}; trx.clientId = expectedTrx.clientId = "dummy-client-id"; ASSERT_EQ(trx, expectedTrx); } TEST_F(ClusterRepairsTestOperations, a_moveshardoperation_compared_via_eqeq) { ServerState::instance()->setId("CurrentCoordinatorServerId"); MoveShardOperation operation{_database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _shard = "s1", _from = "db-from-server", _to = "db-to-server", _isLeader = true}; MoveShardOperation other = operation; ASSERT_EQ(operation, other); (other = operation).database = "differing database"; ASSERT_FALSE(operation == other); (other = operation).collectionId = "differing collectionId"; ASSERT_FALSE(operation == other); (other = operation).collectionName = "differing collectionName"; ASSERT_FALSE(operation == other); (other = operation).shard = "differing shard"; ASSERT_FALSE(operation == other); (other = operation).from = "differing from"; ASSERT_FALSE(operation == other); (other = operation).to = "differing to"; ASSERT_FALSE(operation == other); (other = operation).isLeader = !operation.isLeader; ASSERT_FALSE(operation == other); } TEST_F(ClusterRepairsTestOperations, a_fixserverorderoperation_converted_into_an_agencytransaction) { FixServerOrderOperation operation{ _database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _shard = "s1", _protoShard = "s7", _leader = "db-leader-server", _followers = {"db-follower-3-server", "db-follower-2-server", "db-follower-4-server", "db-follower-1-server"}, _protoFollowers = {"db-follower-1-server", "db-follower-2-server", "db-follower-3-server", "db-follower-4-server"}}; VPackBufferPtr previousServerOrderVPack = R"=([ "db-leader-server", "db-follower-3-server", "db-follower-2-server", "db-follower-4-server", "db-follower-1-server" ])="_vpack; VPackBufferPtr correctServerOrderVPack = R"=([ "db-leader-server", "db-follower-1-server", "db-follower-2-server", "db-follower-3-server", "db-follower-4-server" ])="_vpack; Slice previousServerOrderSlice = Slice(previousServerOrderVPack->data()); Slice correctServerOrderSlice = Slice(correctServerOrderVPack->data()); AgencyWriteTransaction trx; boost::optional<uint64_t> jobid; std::tie(trx, jobid) = conversionVisitor(operation); ASSERT_FALSE(jobid.is_initialized()); AgencyWriteTransaction expectedTrx{ AgencyOperation{"Plan/Collections/myDbName/123456/shards/s1", AgencyValueOperationType::SET, correctServerOrderSlice}, {AgencyPrecondition{"Plan/Collections/myDbName/123456/shards/s1", AgencyPrecondition::Type::VALUE, previousServerOrderSlice}, AgencyPrecondition{"Plan/Collections/myDbName/789876/shards/s7", AgencyPrecondition::Type::VALUE, correctServerOrderSlice}}}; trx.clientId = expectedTrx.clientId = "dummy-client-id"; ASSERT_EQ(trx, expectedTrx); } TEST_F(ClusterRepairsTestOperations, a_fixserverorderoperation_compared_via_eqeq) { FixServerOrderOperation operation{ _database = "myDbName", _collectionId = "123456", _collectionName = "myCollection", _protoCollectionId = "789876", _protoCollectionName = "myProtoCollection", _shard = "s1", _protoShard = "s7", _leader = "db-leader-server", _followers = {"db-follower-3-server", "db-follower-2-server", "db-follower-4-server", "db-follower-1-server"}, _protoFollowers = {"db-follower-1-server", "db-follower-2-server", "db-follower-3-server", "db-follower-4-server"}}; FixServerOrderOperation other = operation; ASSERT_EQ(operation, other); (other = operation).database = "differing database"; ASSERT_FALSE(operation == other); (other = operation).collectionId = "differing collectionId"; ASSERT_FALSE(operation == other); (other = operation).collectionName = "differing collectionName"; ASSERT_FALSE(operation == other); (other = operation).protoCollectionId = "differing protoCollectionId"; ASSERT_FALSE(operation == other); (other = operation).protoCollectionName = "differing protoCollectionName"; ASSERT_FALSE(operation == other); (other = operation).shard = "differing shard"; ASSERT_FALSE(operation == other); (other = operation).protoShard = "differing protoShard"; ASSERT_FALSE(operation == other); (other = operation).leader = "differing leader"; ASSERT_FALSE(operation == other); (other = operation).followers = {"differing", "followers"}; ASSERT_FALSE(operation == other); (other = operation).protoFollowers = {"differing", "protoFollowers"}; ASSERT_FALSE(operation == other); } } // namespace cluster_repairs_test } // namespace tests } // namespace arangodb
// Copyright 2010-2015 RethinkDB, all rights reserved. #include "rdb_protocol/terms/terms.hpp" #include <algorithm> #include <map> #include <string> #include "clustering/administration/admin_op_exc.hpp" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "rdb_protocol/datum_stream.hpp" #include "rdb_protocol/error.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/math_utils.hpp" #include "rdb_protocol/op.hpp" namespace ql { // TODO: Make this whole file not suck. // Some Problems: // * The method of constructing a canonical type from supertype * MAX_TYPE + // subtype is brittle. // * Everything is done with nested ifs. Ideally we'd build some sort of graph // structure and walk it. static const int MAX_TYPE = 10; static const int DB_TYPE = val_t::type_t::DB * MAX_TYPE; static const int TABLE_TYPE = val_t::type_t::TABLE * MAX_TYPE; static const int TABLE_SLICE_TYPE = val_t::type_t::TABLE_SLICE * MAX_TYPE; static const int SELECTION_TYPE = val_t::type_t::SELECTION * MAX_TYPE; static const int ARRAY_SELECTION_TYPE = SELECTION_TYPE + datum_t::R_ARRAY; static const int SEQUENCE_TYPE = val_t::type_t::SEQUENCE * MAX_TYPE; static const int SINGLE_SELECTION_TYPE = val_t::type_t::SINGLE_SELECTION * MAX_TYPE; static const int DATUM_TYPE = val_t::type_t::DATUM * MAX_TYPE; static const int FUNC_TYPE = val_t::type_t::FUNC * MAX_TYPE; static const int GROUPED_DATA_TYPE = val_t::type_t::GROUPED_DATA * MAX_TYPE; static const int R_NULL_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::R_NULL; static const int R_BINARY_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::R_BINARY; static const int R_BOOL_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::R_BOOL; static const int R_NUM_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::R_NUM; static const int R_STR_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::R_STR; static const int R_ARRAY_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::R_ARRAY; static const int R_OBJECT_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::R_OBJECT; static const int MINVAL_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::MINVAL; static const int MAXVAL_TYPE = val_t::type_t::DATUM * MAX_TYPE + datum_t::MAXVAL; class coerce_map_t { public: coerce_map_t() { map["DB"] = DB_TYPE; map["TABLE"] = TABLE_TYPE; map["TABLE_SLICE"] = TABLE_SLICE_TYPE; map["SELECTION<STREAM>"] = SELECTION_TYPE; map["SELECTION<ARRAY>"] = ARRAY_SELECTION_TYPE; map["STREAM"] = SEQUENCE_TYPE; map["SELECTION<OBJECT>"] = SINGLE_SELECTION_TYPE; map["DATUM"] = DATUM_TYPE; map["FUNCTION"] = FUNC_TYPE; map["GROUPED_DATA"] = GROUPED_DATA_TYPE; CT_ASSERT(val_t::type_t::GROUPED_DATA < MAX_TYPE); map["NULL"] = R_NULL_TYPE; map["BINARY"] = R_BINARY_TYPE; map["BOOL"] = R_BOOL_TYPE; map["NUMBER"] = R_NUM_TYPE; map["STRING"] = R_STR_TYPE; map["ARRAY"] = R_ARRAY_TYPE; map["OBJECT"] = R_OBJECT_TYPE; map["MINVAL"] = MINVAL_TYPE; map["MAXVAL"] = MAXVAL_TYPE; CT_ASSERT(datum_t::MAXVAL < MAX_TYPE); for (std::map<std::string, int>::iterator it = map.begin(); it != map.end(); ++it) { rmap[it->second] = it->first; } guarantee(map.size() == rmap.size()); } int get_type(const std::string &s, const rcheckable_t *caller) const { std::map<std::string, int>::const_iterator it = map.find(s); rcheck_target(caller, it != map.end(), base_exc_t::LOGIC, strprintf("Unknown Type: %s", s.c_str())); return it->second; } std::string get_name(int type) const { std::map<int, std::string>::const_iterator it = rmap.find(type); r_sanity_check(it != rmap.end()); return it->second; } private: std::map<std::string, int> map; std::map<int, std::string> rmap; // These functions are here so that if you add a new type you have to update // this file. // THINGS TO DO: // * Update the coerce_map_t. // * Add the various coercions. // * Update the `switch` in `info_term_t`. // * !!! CHECK WHETHER WE HAVE MORE THAN MAX_TYPE TYPES AND INCREASE !!! // !!! MAX_TYPE IF WE DO !!! void NOCALL_ct_catch_new_types(val_t::type_t::raw_type_t t, datum_t::type_t t2) { switch (t) { case val_t::type_t::DB: case val_t::type_t::TABLE: case val_t::type_t::TABLE_SLICE: case val_t::type_t::SELECTION: case val_t::type_t::SEQUENCE: case val_t::type_t::SINGLE_SELECTION: case val_t::type_t::DATUM: case val_t::type_t::FUNC: case val_t::type_t::GROUPED_DATA: default: break; } switch (t2) { case datum_t::UNINITIALIZED: case datum_t::R_NULL: case datum_t::R_BINARY: case datum_t::R_BOOL: case datum_t::R_NUM: case datum_t::R_STR: case datum_t::R_ARRAY: case datum_t::R_OBJECT: case datum_t::MINVAL: case datum_t::MAXVAL: default: break; } } }; static const coerce_map_t _coerce_map; static int get_type(std::string s, const rcheckable_t *caller) { std::transform(s.begin(), s.end(), s.begin(), ::toupper); return _coerce_map.get_type(s, caller); } static std::string get_name(int type) { return _coerce_map.get_name(type); } static val_t::type_t::raw_type_t supertype(int type) { return static_cast<val_t::type_t::raw_type_t>(type / MAX_TYPE); } static datum_t::type_t subtype(int type) { return static_cast<datum_t::type_t>(type % MAX_TYPE); } static int merge_types(int supertype, int subtype) { return supertype * MAX_TYPE + subtype; } class coerce_term_t : public op_term_t { public: coerce_term_t(compile_env_t *env, const raw_term_t &term) : op_term_t(env, term, argspec_t(2)) { } private: virtual scoped_ptr_t<val_t> eval_impl( scope_env_t *env, args_t *args, eval_flags_t) const { scoped_ptr_t<val_t> val = args->arg(env, 0); val_t::type_t opaque_start_type = val->get_type(); int start_supertype = opaque_start_type.raw_type; int start_subtype = 0; if (opaque_start_type.is_convertible(val_t::type_t::DATUM)) { start_supertype = val_t::type_t::DATUM; start_subtype = val->as_datum().get_type(); } int start_type = merge_types(start_supertype, start_subtype); std::string end_type_name = args->arg(env, 1)->as_str().to_std(); int end_type = get_type(end_type_name, this); // Identity if ((!subtype(end_type) && opaque_start_type.is_convertible(supertype(end_type))) || start_type == end_type) { return val; } // * -> BOOL if (end_type == R_BOOL_TYPE) { if (start_type == R_NULL_TYPE) { return new_val(datum_t::boolean(false)); } return new_val(datum_t::boolean(true)); } // DATUM -> * if (opaque_start_type.is_convertible(val_t::type_t::DATUM)) { datum_t d = val->as_datum(); // DATUM -> DATUM if (supertype(end_type) == val_t::type_t::DATUM) { if (start_type == R_BINARY_TYPE && end_type == R_STR_TYPE) { return new_val(datum_t::utf8(d.as_binary())); } if (start_type == R_STR_TYPE && end_type == R_BINARY_TYPE) { return new_val(datum_t::binary(d.as_str())); } // DATUM -> STR if (end_type == R_STR_TYPE) { if (env->env->reql_version() < reql_version_t::v2_1) { return new_val(datum_t( datum_string_t(d.print(env->env->reql_version())))); } else { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.write_json(&writer); return new_val(datum_t( datum_string_t(buffer.GetSize(), buffer.GetString()))); } } // OBJECT -> ARRAY if (start_type == R_OBJECT_TYPE && end_type == R_ARRAY_TYPE) { std::vector<datum_t> arr; arr.reserve(d.obj_size()); for (size_t i = 0; i < d.obj_size(); ++i) { std::pair<datum_string_t, datum_t> pair_in = d.get_pair(i); std::vector<datum_t> pair_out; pair_out.reserve(2); pair_out.push_back(datum_t(pair_in.first)); pair_out.push_back(pair_in.second); arr.push_back(datum_t(std::move(pair_out), env->env->limits())); } return new_val(datum_t(std::move(arr), env->env->limits())); } // STR -> NUM if (start_type == R_STR_TYPE && end_type == R_NUM_TYPE) { const datum_string_t &s = d.as_str(); double dbl; char end; // Used to ensure that there's no trailing garbage. if (sscanf(s.to_std().c_str(), "%lf%c", &dbl, &end) == 1) { return new_val(datum_t(dbl)); } else { rfail(base_exc_t::LOGIC, "Could not coerce `%s` to NUMBER.", s.to_std().c_str()); } } } // TODO: Object to sequence? } if (opaque_start_type.is_convertible(val_t::type_t::SEQUENCE) && !(start_supertype == val_t::type_t::DATUM && start_type != R_ARRAY_TYPE)) { counted_t<datum_stream_t> ds; try { ds = val->as_seq(env->env); } catch (const base_exc_t &e) { rfail(base_exc_t::LOGIC, "Cannot coerce %s to %s (failed to produce intermediate stream).", get_name(start_type).c_str(), get_name(end_type).c_str()); } // SEQUENCE -> ARRAY if (end_type == R_ARRAY_TYPE || end_type == DATUM_TYPE) { return ds->to_array(env->env); } // SEQUENCE -> OBJECT if (end_type == R_OBJECT_TYPE) { datum_object_builder_t obj; batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env->env); { profile::sampler_t sampler("Coercing to object.", env->env->trace); datum_t pair; while (pair = ds->next(env->env, batchspec), pair.has()) { rcheck(pair.arr_size() == 2, base_exc_t::LOGIC, strprintf("Expected array of size 2, but got size %zu.", pair.arr_size())); datum_string_t key = pair.get(0).as_str(); datum_t keyval = pair.get(1); bool b = obj.add(key, keyval); rcheck(!b, base_exc_t::LOGIC, strprintf("Duplicate key %s in coerced object. " "(got %s and %s as values)", datum_t(key).print().c_str(), obj.at(key).trunc_print().c_str(), keyval.trunc_print().c_str())); sampler.new_sample(); } } return new_val(std::move(obj).to_datum()); } } rfail_typed_target(val, "Cannot coerce %s to %s.", get_name(start_type).c_str(), get_name(end_type).c_str()); } virtual const char *name() const { return "coerce_to"; } }; class ungroup_term_t : public op_term_t { public: ungroup_term_t(compile_env_t *env, const raw_term_t &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual scoped_ptr_t<val_t> eval_impl( scope_env_t *env, args_t *args, eval_flags_t) const { counted_t<grouped_data_t> groups = args->arg(env, 0)->as_promiscuous_grouped_data(env->env); std::vector<datum_t> v; v.reserve(groups->size()); for (auto &&pair : *groups) { r_sanity_check(pair.first.has() && pair.second.has()); std::map<datum_string_t, datum_t> m = {{datum_string_t("group"), pair.first}, {datum_string_t("reduction"), std::move(pair.second)}}; v.push_back(datum_t(std::move(m))); } return new_val(datum_t(std::move(v), env->env->limits())); } virtual const char *name() const { return "ungroup"; } virtual bool can_be_grouped() const { return false; } }; int val_type(const scoped_ptr_t<val_t> &v) { int t = v->get_type().raw_type * MAX_TYPE; if (t == DATUM_TYPE) { t += v->as_datum().get_type(); } else if (t == SELECTION_TYPE) { if (v->selection()->seq->is_array()) { t += datum_t::R_ARRAY; } } return t; } datum_t typename_of(const scoped_ptr_t<val_t> &v, scope_env_t *env) { if (v->get_type().get_raw_type() == val_t::type_t::DATUM) { datum_t d = v->as_datum(); return datum_t(datum_string_t(d.get_type_name())); } else if (v->get_type().get_raw_type() == val_t::type_t::SEQUENCE && v->as_seq(env->env)->is_grouped()) { return datum_t(datum_string_t("GROUPED_STREAM")); } else { return datum_t(datum_string_t(get_name(val_type(v)))); } } class typeof_term_t : public op_term_t { public: typeof_term_t(compile_env_t *env, const raw_term_t &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual scoped_ptr_t<val_t> eval_impl(scope_env_t *env, args_t *args, eval_flags_t) const { return new_val(typename_of(args->arg(env, 0), env)); } virtual const char *name() const { return "typeof"; } virtual bool can_be_grouped() const { return false; } }; class info_term_t : public op_term_t { public: info_term_t(compile_env_t *env, const raw_term_t &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual scoped_ptr_t<val_t> eval_impl( scope_env_t *env, args_t *args, eval_flags_t) const { return new_val(val_info(env, args->arg(env, 0))); } datum_t val_info(scope_env_t *env, scoped_ptr_t<val_t> v) const { datum_object_builder_t info; int type = val_type(v); bool b = info.add("type", typename_of(v, env)); switch (type) { case DB_TYPE: { counted_t<const db_t> database = v->as_db(); r_sanity_check(!database->id.is_nil()); b |= info.add("name", datum_t(database->name.str())); b |= info.add("id", datum_t(uuid_to_str(database->id))); } break; case TABLE_TYPE: { counted_t<table_t> table = v->as_table(); r_sanity_check(!table->get_id().is_nil()); b |= info.add("name", datum_t(table->name)); b |= info.add("primary_key", datum_t(table->get_pkey())); b |= info.add("db", val_info(env, new_val(table->db))); b |= info.add("id", datum_t(uuid_to_str(table->get_id()))); name_string_t table_name = name_string_t::guarantee_valid(table->name.c_str()); { std::vector<int64_t> doc_counts; try { admin_err_t error; if (!env->env->reql_cluster_interface()->table_estimate_doc_counts( env->env->get_user_context(), table->db, table_name, env->env, &doc_counts, &error)) { REQL_RETHROW(error); } } catch (auth::permission_error_t const &permission_error) { rfail(ql::base_exc_t::PERMISSION_ERROR, "%s", permission_error.what()); } datum_array_builder_t arr(configured_limits_t::unlimited); for (int64_t i : doc_counts) { arr.add(datum_t(static_cast<double>(i))); } b |= info.add("doc_count_estimates", std::move(arr).to_datum()); } { admin_err_t error; std::map<std::string, std::pair<sindex_config_t, sindex_status_t> > configs_and_statuses; if (!env->env->reql_cluster_interface()->sindex_list( table->db, table_name, env->env->interruptor, &error, &configs_and_statuses)) { REQL_RETHROW(error); } ql::datum_array_builder_t res(ql::configured_limits_t::unlimited); for (const auto &pair : configs_and_statuses) { res.add(ql::datum_t(datum_string_t(pair.first))); } b |= info.add("indexes", std::move(res).to_datum()); } } break; case TABLE_SLICE_TYPE: { counted_t<table_slice_t> ts = v->as_table_slice(); b |= info.add("table", val_info(env, new_val(ts->get_tbl()))); b |= info.add("index", ts->idx ? datum_t(ts->idx->c_str()) : datum_t::null()); switch (ts->sorting) { case sorting_t::UNORDERED: b |= info.add("sorting", datum_t("UNORDERED")); break; case sorting_t::ASCENDING: b |= info.add("sorting", datum_t("ASCENDING")); break; case sorting_t::DESCENDING: b |= info.add("sorting", datum_t("DESCENDING")); break; default: unreachable(); } if (ts->bounds.left_bound.get_type() == datum_t::type_t::MINVAL) { b |= info.add("left_bound_type", datum_t("unbounded")); } else if (ts->bounds.left_bound.get_type() == datum_t::type_t::MAXVAL) { b |= info.add("left_bound_type", datum_t("unachievable")); } else { b |= info.add("left_bound", ts->bounds.left_bound); b |= info.add("left_bound_type", datum_t(ts->bounds.left_bound_type == key_range_t::open ? "open" : "closed")); } if (ts->bounds.right_bound.get_type() == datum_t::type_t::MAXVAL) { b |= info.add("right_bound_type", datum_t("unbounded")); } else if (ts->bounds.right_bound.get_type() == datum_t::type_t::MINVAL) { b |= info.add("right_bound_type", datum_t("unachievable")); } else { b |= info.add("right_bound", ts->bounds.right_bound); b |= info.add("right_bound_type", datum_t(ts->bounds.right_bound_type == key_range_t::open ? "open" : "closed")); } } break; case SELECTION_TYPE: { b |= info.add("table", val_info(env, new_val(v->as_selection(env->env)->table))); } break; case ARRAY_SELECTION_TYPE: { b |= info.add("table", val_info(env, new_val(v->as_selection(env->env)->table))); } break; case SEQUENCE_TYPE: { if (v->as_seq(env->env)->is_grouped()) { bool res = info.add("type", datum_t("GROUPED_STREAM")); r_sanity_check(res); } } break; case SINGLE_SELECTION_TYPE: { b |= info.add("table", val_info(env, new_val(v->as_single_selection()->get_tbl()))); } break; case FUNC_TYPE: { b |= info.add("source_code", datum_t(datum_string_t(v->as_func()->print_source()))); } break; case GROUPED_DATA_TYPE: break; // No more info case R_BINARY_TYPE: b |= info.add("count", datum_t(safe_to_double(v->as_datum().as_binary().size()))); // fallthru case R_BOOL_TYPE: // fallthru case R_NUM_TYPE: // fallthru case R_STR_TYPE: // fallthru case R_ARRAY_TYPE: // fallthru case R_OBJECT_TYPE: // fallthru case DATUM_TYPE: { b |= info.add("value", datum_t(datum_string_t( v->as_datum().print(env->env->reql_version())))); } // fallthru case R_NULL_TYPE: // fallthru case MINVAL_TYPE: // fallthru case MAXVAL_TYPE: break; default: r_sanity_check(false); } r_sanity_check(!b); return std::move(info).to_datum(); } virtual const char *name() const { return "info"; } virtual bool can_be_grouped() const { return false; } }; counted_t<term_t> make_coerce_term( compile_env_t *env, const raw_term_t &term) { return make_counted<coerce_term_t>(env, term); } counted_t<term_t> make_ungroup_term( compile_env_t *env, const raw_term_t &term) { return make_counted<ungroup_term_t>(env, term); } counted_t<term_t> make_typeof_term( compile_env_t *env, const raw_term_t &term) { return make_counted<typeof_term_t>(env, term); } counted_t<term_t> make_info_term( compile_env_t *env, const raw_term_t &term) { return make_counted<info_term_t>(env, term); } } // namespace ql
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser 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) =============================================================================*/ #if !defined(BOOST_SPIRIT_CHAR_CLASS_NOVEMBER_10_2006_0907AM) #define BOOST_SPIRIT_CHAR_CLASS_NOVEMBER_10_2006_0907AM #if defined(_MSC_VER) #pragma once #endif #include <string> #include <boost/proto/proto.hpp> #include <boost/config.hpp> #include <boost/mpl/bool.hpp> #include <boost/spirit/home/support/unused.hpp> #include <boost/type_traits/is_signed.hpp> #include <boost/type_traits/make_unsigned.hpp> #include <boost/type_traits/make_signed.hpp> #if defined(BOOST_MSVC) # pragma warning(push) # pragma warning(disable: 4800) // 'int' : forcing value to bool 'true' or 'false' warning #endif namespace boost { namespace spirit { namespace detail { // Here's the thing... typical encodings (except ASCII) deal with unsigned // integers > 127. ASCII uses only 127. Yet, most char and wchar_t are signed. // Thus, a char with value > 127 is negative (e.g. char 233 is -23). When you // cast this to an unsigned int with 32 bits, you get 4294967273! // // The trick is to cast to an unsigned version of the source char first // before casting to the target. {P.S. Don't worry about the code, the // optimizer will optimize the if-else branches} template <typename TargetChar, typename SourceChar> TargetChar cast_char(SourceChar ch) { if (is_signed<TargetChar>::value != is_signed<SourceChar>::value) { if (is_signed<SourceChar>::value) { // source is signed, target is unsigned typedef typename make_unsigned<SourceChar>::type USourceChar; return TargetChar(USourceChar(ch)); } else { // source is unsigned, target is signed typedef typename make_signed<SourceChar>::type SSourceChar; return TargetChar(SSourceChar(ch)); } } else { // source and target has same signedness return TargetChar(ch); // just cast } } }}} namespace boost { namespace spirit { namespace tag { struct char_ {}; struct string {}; /////////////////////////////////////////////////////////////////////////// // classification tags struct alnum {}; struct alpha {}; struct digit {}; struct xdigit {}; struct cntrl {}; struct graph {}; struct print {}; struct punct {}; struct space {}; struct blank {}; /////////////////////////////////////////////////////////////////////////// // classification/conversion tags struct no_case {}; struct lower {}; struct upper {}; struct lowernum {}; struct uppernum {}; struct ucs4 {}; struct encoding {}; #if defined(BOOST_SPIRIT_UNICODE) /////////////////////////////////////////////////////////////////////////// // Unicode Major Categories /////////////////////////////////////////////////////////////////////////// struct letter {}; struct mark {}; struct number {}; struct separator {}; struct other {}; struct punctuation {}; struct symbol {}; /////////////////////////////////////////////////////////////////////////// // Unicode General Categories /////////////////////////////////////////////////////////////////////////// struct uppercase_letter {}; struct lowercase_letter {}; struct titlecase_letter {}; struct modifier_letter {}; struct other_letter {}; struct nonspacing_mark {}; struct enclosing_mark {}; struct spacing_mark {}; struct decimal_number {}; struct letter_number {}; struct other_number {}; struct space_separator {}; struct line_separator {}; struct paragraph_separator {}; struct control {}; struct format {}; struct private_use {}; struct surrogate {}; struct unassigned {}; struct dash_punctuation {}; struct open_punctuation {}; struct close_punctuation {}; struct connector_punctuation {}; struct other_punctuation {}; struct initial_punctuation {}; struct final_punctuation {}; struct math_symbol {}; struct currency_symbol {}; struct modifier_symbol {}; struct other_symbol {}; /////////////////////////////////////////////////////////////////////////// // Unicode Derived Categories /////////////////////////////////////////////////////////////////////////// struct alphabetic {}; struct uppercase {}; struct lowercase {}; struct white_space {}; struct hex_digit {}; struct noncharacter_code_point {}; struct default_ignorable_code_point {}; /////////////////////////////////////////////////////////////////////////// // Unicode Scripts /////////////////////////////////////////////////////////////////////////// struct arabic {}; struct imperial_aramaic {}; struct armenian {}; struct avestan {}; struct balinese {}; struct bamum {}; struct bengali {}; struct bopomofo {}; struct braille {}; struct buginese {}; struct buhid {}; struct canadian_aboriginal {}; struct carian {}; struct cham {}; struct cherokee {}; struct coptic {}; struct cypriot {}; struct cyrillic {}; struct devanagari {}; struct deseret {}; struct egyptian_hieroglyphs {}; struct ethiopic {}; struct georgian {}; struct glagolitic {}; struct gothic {}; struct greek {}; struct gujarati {}; struct gurmukhi {}; struct hangul {}; struct han {}; struct hanunoo {}; struct hebrew {}; struct hiragana {}; struct katakana_or_hiragana {}; struct old_italic {}; struct javanese {}; struct kayah_li {}; struct katakana {}; struct kharoshthi {}; struct khmer {}; struct kannada {}; struct kaithi {}; struct tai_tham {}; struct lao {}; struct latin {}; struct lepcha {}; struct limbu {}; struct linear_b {}; struct lisu {}; struct lycian {}; struct lydian {}; struct malayalam {}; struct mongolian {}; struct meetei_mayek {}; struct myanmar {}; struct nko {}; struct ogham {}; struct ol_chiki {}; struct old_turkic {}; struct oriya {}; struct osmanya {}; struct phags_pa {}; struct inscriptional_pahlavi {}; struct phoenician {}; struct inscriptional_parthian {}; struct rejang {}; struct runic {}; struct samaritan {}; struct old_south_arabian {}; struct saurashtra {}; struct shavian {}; struct sinhala {}; struct sundanese {}; struct syloti_nagri {}; struct syriac {}; struct tagbanwa {}; struct tai_le {}; struct new_tai_lue {}; struct tamil {}; struct tai_viet {}; struct telugu {}; struct tifinagh {}; struct tagalog {}; struct thaana {}; struct thai {}; struct tibetan {}; struct ugaritic {}; struct vai {}; struct old_persian {}; struct cuneiform {}; struct yi {}; struct inherited {}; struct common {}; struct unknown {}; #endif /////////////////////////////////////////////////////////////////////////// // This composite tag type encodes both the character // set and the specific char tag (used for classification // or conversion). char_code_base and char_encoding_base // can be used to test for modifier membership (see modifier.hpp) template <typename CharClass> struct char_code_base {}; template <typename CharEncoding> struct char_encoding_base {}; template <typename CharClass, typename CharEncoding> struct char_code : char_code_base<CharClass>, char_encoding_base<CharEncoding> { typedef CharEncoding char_encoding; // e.g. ascii typedef CharClass char_class; // e.g. tag::alnum }; }}} namespace boost { namespace spirit { namespace char_class { /////////////////////////////////////////////////////////////////////////// // Test characters for classification template <typename CharEncoding> struct classify { typedef typename CharEncoding::char_type char_type; #define BOOST_SPIRIT_CLASSIFY(name, isname) \ template <typename Char> \ static bool \ is(tag::name, Char ch) \ { \ return CharEncoding::isname \ BOOST_PREVENT_MACRO_SUBSTITUTION \ (detail::cast_char<char_type>(ch)); \ } \ /***/ BOOST_SPIRIT_CLASSIFY(char_, ischar) BOOST_SPIRIT_CLASSIFY(alnum, isalnum) BOOST_SPIRIT_CLASSIFY(alpha, isalpha) BOOST_SPIRIT_CLASSIFY(digit, isdigit) BOOST_SPIRIT_CLASSIFY(xdigit, isxdigit) BOOST_SPIRIT_CLASSIFY(cntrl, iscntrl) BOOST_SPIRIT_CLASSIFY(graph, isgraph) BOOST_SPIRIT_CLASSIFY(lower, islower) BOOST_SPIRIT_CLASSIFY(print, isprint) BOOST_SPIRIT_CLASSIFY(punct, ispunct) BOOST_SPIRIT_CLASSIFY(space, isspace) BOOST_SPIRIT_CLASSIFY(blank, isblank) BOOST_SPIRIT_CLASSIFY(upper, isupper) #undef BOOST_SPIRIT_CLASSIFY template <typename Char> static bool is(tag::lowernum, Char ch) { return CharEncoding::islower(detail::cast_char<char_type>(ch)) || CharEncoding::isdigit(detail::cast_char<char_type>(ch)); } template <typename Char> static bool is(tag::uppernum, Char ch) { return CharEncoding::isupper(detail::cast_char<char_type>(ch)) || CharEncoding::isdigit(detail::cast_char<char_type>(ch)); } #if defined(BOOST_SPIRIT_UNICODE) #define BOOST_SPIRIT_UNICODE_CLASSIFY(name) \ template <typename Char> \ static bool \ is(tag::name, Char ch) \ { \ return CharEncoding::is_##name(detail::cast_char<char_type>(ch)); \ } \ /***/ /////////////////////////////////////////////////////////////////////////// // Unicode Major Categories /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY(letter) BOOST_SPIRIT_UNICODE_CLASSIFY(mark) BOOST_SPIRIT_UNICODE_CLASSIFY(number) BOOST_SPIRIT_UNICODE_CLASSIFY(separator) BOOST_SPIRIT_UNICODE_CLASSIFY(other) BOOST_SPIRIT_UNICODE_CLASSIFY(punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(symbol) /////////////////////////////////////////////////////////////////////////// // Unicode General Categories /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY(uppercase_letter) BOOST_SPIRIT_UNICODE_CLASSIFY(lowercase_letter) BOOST_SPIRIT_UNICODE_CLASSIFY(titlecase_letter) BOOST_SPIRIT_UNICODE_CLASSIFY(modifier_letter) BOOST_SPIRIT_UNICODE_CLASSIFY(other_letter) BOOST_SPIRIT_UNICODE_CLASSIFY(nonspacing_mark) BOOST_SPIRIT_UNICODE_CLASSIFY(enclosing_mark) BOOST_SPIRIT_UNICODE_CLASSIFY(spacing_mark) BOOST_SPIRIT_UNICODE_CLASSIFY(decimal_number) BOOST_SPIRIT_UNICODE_CLASSIFY(letter_number) BOOST_SPIRIT_UNICODE_CLASSIFY(other_number) BOOST_SPIRIT_UNICODE_CLASSIFY(space_separator) BOOST_SPIRIT_UNICODE_CLASSIFY(line_separator) BOOST_SPIRIT_UNICODE_CLASSIFY(paragraph_separator) BOOST_SPIRIT_UNICODE_CLASSIFY(control) BOOST_SPIRIT_UNICODE_CLASSIFY(format) BOOST_SPIRIT_UNICODE_CLASSIFY(private_use) BOOST_SPIRIT_UNICODE_CLASSIFY(surrogate) BOOST_SPIRIT_UNICODE_CLASSIFY(unassigned) BOOST_SPIRIT_UNICODE_CLASSIFY(dash_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(open_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(close_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(connector_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(other_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(initial_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(final_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY(math_symbol) BOOST_SPIRIT_UNICODE_CLASSIFY(currency_symbol) BOOST_SPIRIT_UNICODE_CLASSIFY(modifier_symbol) BOOST_SPIRIT_UNICODE_CLASSIFY(other_symbol) /////////////////////////////////////////////////////////////////////////// // Unicode Derived Categories /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY(alphabetic) BOOST_SPIRIT_UNICODE_CLASSIFY(uppercase) BOOST_SPIRIT_UNICODE_CLASSIFY(lowercase) BOOST_SPIRIT_UNICODE_CLASSIFY(white_space) BOOST_SPIRIT_UNICODE_CLASSIFY(hex_digit) BOOST_SPIRIT_UNICODE_CLASSIFY(noncharacter_code_point) BOOST_SPIRIT_UNICODE_CLASSIFY(default_ignorable_code_point) /////////////////////////////////////////////////////////////////////////// // Unicode Scripts /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY(arabic) BOOST_SPIRIT_UNICODE_CLASSIFY(imperial_aramaic) BOOST_SPIRIT_UNICODE_CLASSIFY(armenian) BOOST_SPIRIT_UNICODE_CLASSIFY(avestan) BOOST_SPIRIT_UNICODE_CLASSIFY(balinese) BOOST_SPIRIT_UNICODE_CLASSIFY(bamum) BOOST_SPIRIT_UNICODE_CLASSIFY(bengali) BOOST_SPIRIT_UNICODE_CLASSIFY(bopomofo) BOOST_SPIRIT_UNICODE_CLASSIFY(braille) BOOST_SPIRIT_UNICODE_CLASSIFY(buginese) BOOST_SPIRIT_UNICODE_CLASSIFY(buhid) BOOST_SPIRIT_UNICODE_CLASSIFY(canadian_aboriginal) BOOST_SPIRIT_UNICODE_CLASSIFY(carian) BOOST_SPIRIT_UNICODE_CLASSIFY(cham) BOOST_SPIRIT_UNICODE_CLASSIFY(cherokee) BOOST_SPIRIT_UNICODE_CLASSIFY(coptic) BOOST_SPIRIT_UNICODE_CLASSIFY(cypriot) BOOST_SPIRIT_UNICODE_CLASSIFY(cyrillic) BOOST_SPIRIT_UNICODE_CLASSIFY(devanagari) BOOST_SPIRIT_UNICODE_CLASSIFY(deseret) BOOST_SPIRIT_UNICODE_CLASSIFY(egyptian_hieroglyphs) BOOST_SPIRIT_UNICODE_CLASSIFY(ethiopic) BOOST_SPIRIT_UNICODE_CLASSIFY(georgian) BOOST_SPIRIT_UNICODE_CLASSIFY(glagolitic) BOOST_SPIRIT_UNICODE_CLASSIFY(gothic) BOOST_SPIRIT_UNICODE_CLASSIFY(greek) BOOST_SPIRIT_UNICODE_CLASSIFY(gujarati) BOOST_SPIRIT_UNICODE_CLASSIFY(gurmukhi) BOOST_SPIRIT_UNICODE_CLASSIFY(hangul) BOOST_SPIRIT_UNICODE_CLASSIFY(han) BOOST_SPIRIT_UNICODE_CLASSIFY(hanunoo) BOOST_SPIRIT_UNICODE_CLASSIFY(hebrew) BOOST_SPIRIT_UNICODE_CLASSIFY(hiragana) BOOST_SPIRIT_UNICODE_CLASSIFY(katakana_or_hiragana) BOOST_SPIRIT_UNICODE_CLASSIFY(old_italic) BOOST_SPIRIT_UNICODE_CLASSIFY(javanese) BOOST_SPIRIT_UNICODE_CLASSIFY(kayah_li) BOOST_SPIRIT_UNICODE_CLASSIFY(katakana) BOOST_SPIRIT_UNICODE_CLASSIFY(kharoshthi) BOOST_SPIRIT_UNICODE_CLASSIFY(khmer) BOOST_SPIRIT_UNICODE_CLASSIFY(kannada) BOOST_SPIRIT_UNICODE_CLASSIFY(kaithi) BOOST_SPIRIT_UNICODE_CLASSIFY(tai_tham) BOOST_SPIRIT_UNICODE_CLASSIFY(lao) BOOST_SPIRIT_UNICODE_CLASSIFY(latin) BOOST_SPIRIT_UNICODE_CLASSIFY(lepcha) BOOST_SPIRIT_UNICODE_CLASSIFY(limbu) BOOST_SPIRIT_UNICODE_CLASSIFY(linear_b) BOOST_SPIRIT_UNICODE_CLASSIFY(lisu) BOOST_SPIRIT_UNICODE_CLASSIFY(lycian) BOOST_SPIRIT_UNICODE_CLASSIFY(lydian) BOOST_SPIRIT_UNICODE_CLASSIFY(malayalam) BOOST_SPIRIT_UNICODE_CLASSIFY(mongolian) BOOST_SPIRIT_UNICODE_CLASSIFY(meetei_mayek) BOOST_SPIRIT_UNICODE_CLASSIFY(myanmar) BOOST_SPIRIT_UNICODE_CLASSIFY(nko) BOOST_SPIRIT_UNICODE_CLASSIFY(ogham) BOOST_SPIRIT_UNICODE_CLASSIFY(ol_chiki) BOOST_SPIRIT_UNICODE_CLASSIFY(old_turkic) BOOST_SPIRIT_UNICODE_CLASSIFY(oriya) BOOST_SPIRIT_UNICODE_CLASSIFY(osmanya) BOOST_SPIRIT_UNICODE_CLASSIFY(phags_pa) BOOST_SPIRIT_UNICODE_CLASSIFY(inscriptional_pahlavi) BOOST_SPIRIT_UNICODE_CLASSIFY(phoenician) BOOST_SPIRIT_UNICODE_CLASSIFY(inscriptional_parthian) BOOST_SPIRIT_UNICODE_CLASSIFY(rejang) BOOST_SPIRIT_UNICODE_CLASSIFY(runic) BOOST_SPIRIT_UNICODE_CLASSIFY(samaritan) BOOST_SPIRIT_UNICODE_CLASSIFY(old_south_arabian) BOOST_SPIRIT_UNICODE_CLASSIFY(saurashtra) BOOST_SPIRIT_UNICODE_CLASSIFY(shavian) BOOST_SPIRIT_UNICODE_CLASSIFY(sinhala) BOOST_SPIRIT_UNICODE_CLASSIFY(sundanese) BOOST_SPIRIT_UNICODE_CLASSIFY(syloti_nagri) BOOST_SPIRIT_UNICODE_CLASSIFY(syriac) BOOST_SPIRIT_UNICODE_CLASSIFY(tagbanwa) BOOST_SPIRIT_UNICODE_CLASSIFY(tai_le) BOOST_SPIRIT_UNICODE_CLASSIFY(new_tai_lue) BOOST_SPIRIT_UNICODE_CLASSIFY(tamil) BOOST_SPIRIT_UNICODE_CLASSIFY(tai_viet) BOOST_SPIRIT_UNICODE_CLASSIFY(telugu) BOOST_SPIRIT_UNICODE_CLASSIFY(tifinagh) BOOST_SPIRIT_UNICODE_CLASSIFY(tagalog) BOOST_SPIRIT_UNICODE_CLASSIFY(thaana) BOOST_SPIRIT_UNICODE_CLASSIFY(thai) BOOST_SPIRIT_UNICODE_CLASSIFY(tibetan) BOOST_SPIRIT_UNICODE_CLASSIFY(ugaritic) BOOST_SPIRIT_UNICODE_CLASSIFY(vai) BOOST_SPIRIT_UNICODE_CLASSIFY(old_persian) BOOST_SPIRIT_UNICODE_CLASSIFY(cuneiform) BOOST_SPIRIT_UNICODE_CLASSIFY(yi) BOOST_SPIRIT_UNICODE_CLASSIFY(inherited) BOOST_SPIRIT_UNICODE_CLASSIFY(common) BOOST_SPIRIT_UNICODE_CLASSIFY(unknown) #undef BOOST_SPIRIT_UNICODE_CLASSIFY #endif }; /////////////////////////////////////////////////////////////////////////// // Convert characters template <typename CharEncoding> struct convert { typedef typename CharEncoding::char_type char_type; template <typename Char> static Char to(tag::lower, Char ch) { return static_cast<Char>( CharEncoding::tolower(detail::cast_char<char_type>(ch))); } template <typename Char> static Char to(tag::upper, Char ch) { return static_cast<Char>( CharEncoding::toupper(detail::cast_char<char_type>(ch))); } template <typename Char> static Char to(tag::ucs4, Char ch) { return static_cast<Char>( CharEncoding::toucs4(detail::cast_char<char_type>(ch))); } template <typename Char> static Char to(unused_type, Char ch) { return ch; } }; /////////////////////////////////////////////////////////////////////////// // Info on character classification template <typename CharEncoding> struct what { #define BOOST_SPIRIT_CLASSIFY_WHAT(name, isname) \ static char const* is(tag::name) \ { \ return isname; \ } \ /***/ BOOST_SPIRIT_CLASSIFY_WHAT(char_, "char") BOOST_SPIRIT_CLASSIFY_WHAT(alnum, "alnum") BOOST_SPIRIT_CLASSIFY_WHAT(alpha, "alpha") BOOST_SPIRIT_CLASSIFY_WHAT(digit, "digit") BOOST_SPIRIT_CLASSIFY_WHAT(xdigit, "xdigit") BOOST_SPIRIT_CLASSIFY_WHAT(cntrl, "cntrl") BOOST_SPIRIT_CLASSIFY_WHAT(graph, "graph") BOOST_SPIRIT_CLASSIFY_WHAT(lower, "lower") BOOST_SPIRIT_CLASSIFY_WHAT(lowernum, "lowernum") BOOST_SPIRIT_CLASSIFY_WHAT(print, "print") BOOST_SPIRIT_CLASSIFY_WHAT(punct, "punct") BOOST_SPIRIT_CLASSIFY_WHAT(space, "space") BOOST_SPIRIT_CLASSIFY_WHAT(blank, "blank") BOOST_SPIRIT_CLASSIFY_WHAT(upper, "upper") BOOST_SPIRIT_CLASSIFY_WHAT(uppernum, "uppernum") BOOST_SPIRIT_CLASSIFY_WHAT(ucs4, "ucs4") #undef BOOST_SPIRIT_CLASSIFY_WHAT #if defined(BOOST_SPIRIT_UNICODE) #define BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(name) \ static char const* is(tag::name) \ { \ return BOOST_PP_STRINGIZE(name); \ } \ /***/ /////////////////////////////////////////////////////////////////////////// // Unicode Major Categories /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(letter) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(mark) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(number) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(separator) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(other) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(symbol) /////////////////////////////////////////////////////////////////////////// // Unicode General Categories /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(uppercase_letter) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(lowercase_letter) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(titlecase_letter) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(modifier_letter) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(other_letter) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(nonspacing_mark) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(enclosing_mark) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(spacing_mark) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(decimal_number) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(letter_number) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(other_number) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(space_separator) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(line_separator) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(paragraph_separator) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(control) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(format) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(private_use) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(surrogate) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(unassigned) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(dash_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(open_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(close_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(connector_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(other_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(initial_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(final_punctuation) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(math_symbol) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(currency_symbol) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(modifier_symbol) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(other_symbol) /////////////////////////////////////////////////////////////////////////// // Unicode Derived Categories /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(alphabetic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(uppercase) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(lowercase) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(white_space) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(hex_digit) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(noncharacter_code_point) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(default_ignorable_code_point) /////////////////////////////////////////////////////////////////////////// // Unicode Scripts /////////////////////////////////////////////////////////////////////////// BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(arabic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(imperial_aramaic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(armenian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(avestan) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(balinese) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(bamum) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(bengali) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(bopomofo) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(braille) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(buginese) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(buhid) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(canadian_aboriginal) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(carian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(cham) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(cherokee) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(coptic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(cypriot) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(cyrillic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(devanagari) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(deseret) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(egyptian_hieroglyphs) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(ethiopic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(georgian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(glagolitic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(gothic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(greek) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(gujarati) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(gurmukhi) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(hangul) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(han) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(hanunoo) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(hebrew) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(hiragana) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(katakana_or_hiragana) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(old_italic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(javanese) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(kayah_li) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(katakana) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(kharoshthi) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(khmer) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(kannada) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(kaithi) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tai_tham) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(lao) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(latin) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(lepcha) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(limbu) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(linear_b) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(lisu) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(lycian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(lydian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(malayalam) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(mongolian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(meetei_mayek) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(myanmar) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(nko) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(ogham) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(ol_chiki) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(old_turkic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(oriya) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(osmanya) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(phags_pa) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(inscriptional_pahlavi) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(phoenician) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(inscriptional_parthian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(rejang) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(runic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(samaritan) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(old_south_arabian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(saurashtra) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(shavian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(sinhala) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(sundanese) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(syloti_nagri) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(syriac) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tagbanwa) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tai_le) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(new_tai_lue) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tamil) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tai_viet) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(telugu) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tifinagh) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tagalog) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(thaana) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(thai) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(tibetan) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(ugaritic) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(vai) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(old_persian) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(cuneiform) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(yi) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(inherited) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(common) BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT(unknown) #undef BOOST_SPIRIT_UNICODE_CLASSIFY_WHAT #endif }; }}} namespace boost { namespace spirit { namespace traits { /////////////////////////////////////////////////////////////////////////// // This meta-function evaluates to mpl::true_ if the function // char_encoding::ischar() needs to be called to ensure correct matching. // This happens mainly if the character type returned from the underlying // iterator is larger than the character type of the used character // encoding. Additionally, this meta-function provides a customization // point for the lexer library to enforce this behavior while parsing // a token stream. template <typename Char, typename BaseChar> struct mustcheck_ischar : mpl::bool_<(sizeof(Char) > sizeof(BaseChar)) ? true : false> {}; /////////////////////////////////////////////////////////////////////////// // The following template calls char_encoding::ischar, if necessary template <typename CharParam, typename CharEncoding , bool MustCheck = mustcheck_ischar< CharParam, typename CharEncoding::char_type>::value> struct ischar { static bool call(CharParam) { return true; } }; template <typename CharParam, typename CharEncoding> struct ischar<CharParam, CharEncoding, true> { static bool call(CharParam const& ch) { return CharEncoding::ischar(int(ch)); } }; }}} #if defined(BOOST_MSVC) # pragma warning(pop) #endif #endif
//===- InstCombineVectorOps.cpp -------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements instcombine for ExtractElement, InsertElement and // ShuffleVector. // //===----------------------------------------------------------------------===// #include "InstCombineInternal.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/VectorUtils.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Operator.h" #include "llvm/IR/PatternMatch.h" #include "llvm/IR/Type.h" #include "llvm/IR/User.h" #include "llvm/IR/Value.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" #include <cassert> #include <cstdint> #include <iterator> #include <utility> using namespace llvm; using namespace PatternMatch; #define DEBUG_TYPE "instcombine" /// Return true if the value is cheaper to scalarize than it is to leave as a /// vector operation. IsConstantExtractIndex indicates whether we are extracting /// one known element from a vector constant. /// /// FIXME: It's possible to create more instructions than previously existed. static bool cheapToScalarize(Value *V, bool IsConstantExtractIndex) { // If we can pick a scalar constant value out of a vector, that is free. if (auto *C = dyn_cast<Constant>(V)) return IsConstantExtractIndex || C->getSplatValue(); // An insertelement to the same constant index as our extract will simplify // to the scalar inserted element. An insertelement to a different constant // index is irrelevant to our extract. if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt()))) return IsConstantExtractIndex; if (match(V, m_OneUse(m_Load(m_Value())))) return true; if (match(V, m_OneUse(m_UnOp()))) return true; Value *V0, *V1; if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1))))) if (cheapToScalarize(V0, IsConstantExtractIndex) || cheapToScalarize(V1, IsConstantExtractIndex)) return true; CmpInst::Predicate UnusedPred; if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1))))) if (cheapToScalarize(V0, IsConstantExtractIndex) || cheapToScalarize(V1, IsConstantExtractIndex)) return true; return false; } // If we have a PHI node with a vector type that is only used to feed // itself and be an operand of extractelement at a constant location, // try to replace the PHI of the vector type with a PHI of a scalar type. Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) { SmallVector<Instruction *, 2> Extracts; // The users we want the PHI to have are: // 1) The EI ExtractElement (we already know this) // 2) Possibly more ExtractElements with the same index. // 3) Another operand, which will feed back into the PHI. Instruction *PHIUser = nullptr; for (auto U : PN->users()) { if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { if (EI.getIndexOperand() == EU->getIndexOperand()) Extracts.push_back(EU); else return nullptr; } else if (!PHIUser) { PHIUser = cast<Instruction>(U); } else { return nullptr; } } if (!PHIUser) return nullptr; // Verify that this PHI user has one use, which is the PHI itself, // and that it is a binary operation which is cheap to scalarize. // otherwise return nullptr. if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true)) return nullptr; // Create a scalar PHI node that will replace the vector PHI node // just before the current PHI node. PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); // Scalarize each PHI operand. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { Value *PHIInVal = PN->getIncomingValue(i); BasicBlock *inBB = PN->getIncomingBlock(i); Value *Elt = EI.getIndexOperand(); // If the operand is the PHI induction variable: if (PHIInVal == PHIUser) { // Scalarize the binary operation. Its first operand is the // scalar PHI, and the second operand is extracted from the other // vector operand. BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; Value *Op = InsertNewInstWith( ExtractElementInst::Create(B0->getOperand(opId), Elt, B0->getOperand(opId)->getName() + ".Elt"), *B0); Value *newPHIUser = InsertNewInstWith( BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), scalarPHI, Op, B0), *B0); scalarPHI->addIncoming(newPHIUser, inBB); } else { // Scalarize PHI input: Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); // Insert the new instruction into the predecessor basic block. Instruction *pos = dyn_cast<Instruction>(PHIInVal); BasicBlock::iterator InsertPos; if (pos && !isa<PHINode>(pos)) { InsertPos = ++pos->getIterator(); } else { InsertPos = inBB->getFirstInsertionPt(); } InsertNewInstWith(newEI, *InsertPos); scalarPHI->addIncoming(newEI, inBB); } } for (auto E : Extracts) replaceInstUsesWith(*E, scalarPHI); return &EI; } static Instruction *foldBitcastExtElt(ExtractElementInst &Ext, InstCombiner::BuilderTy &Builder, bool IsBigEndian) { Value *X; uint64_t ExtIndexC; if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) || !X->getType()->isVectorTy() || !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC))) return nullptr; // If this extractelement is using a bitcast from a vector of the same number // of elements, see if we can find the source element from the source vector: // extelt (bitcast VecX), IndexC --> bitcast X[IndexC] auto *SrcTy = cast<VectorType>(X->getType()); Type *DestTy = Ext.getType(); unsigned NumSrcElts = SrcTy->getNumElements(); unsigned NumElts = Ext.getVectorOperandType()->getNumElements(); if (NumSrcElts == NumElts) if (Value *Elt = findScalarElement(X, ExtIndexC)) return new BitCastInst(Elt, DestTy); // If the source elements are wider than the destination, try to shift and // truncate a subset of scalar bits of an insert op. if (NumSrcElts < NumElts) { Value *Scalar; uint64_t InsIndexC; if (!match(X, m_InsertElt(m_Value(), m_Value(Scalar), m_ConstantInt(InsIndexC)))) return nullptr; // The extract must be from the subset of vector elements that we inserted // into. Example: if we inserted element 1 of a <2 x i64> and we are // extracting an i16 (narrowing ratio = 4), then this extract must be from 1 // of elements 4-7 of the bitcasted vector. unsigned NarrowingRatio = NumElts / NumSrcElts; if (ExtIndexC / NarrowingRatio != InsIndexC) return nullptr; // We are extracting part of the original scalar. How that scalar is // inserted into the vector depends on the endian-ness. Example: // Vector Byte Elt Index: 0 1 2 3 4 5 6 7 // +--+--+--+--+--+--+--+--+ // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3| // extelt <4 x i16> V', 3: | |S2|S3| // +--+--+--+--+--+--+--+--+ // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value. // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value. // In this example, we must right-shift little-endian. Big-endian is just a // truncate. unsigned Chunk = ExtIndexC % NarrowingRatio; if (IsBigEndian) Chunk = NarrowingRatio - 1 - Chunk; // Bail out if this is an FP vector to FP vector sequence. That would take // more instructions than we started with unless there is no shift, and it // may not be handled as well in the backend. bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy(); bool NeedDestBitcast = DestTy->isFloatingPointTy(); if (NeedSrcBitcast && NeedDestBitcast) return nullptr; unsigned SrcWidth = SrcTy->getScalarSizeInBits(); unsigned DestWidth = DestTy->getPrimitiveSizeInBits(); unsigned ShAmt = Chunk * DestWidth; // TODO: This limitation is more strict than necessary. We could sum the // number of new instructions and subtract the number eliminated to know if // we can proceed. if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse()) if (NeedSrcBitcast || NeedDestBitcast) return nullptr; if (NeedSrcBitcast) { Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth); Scalar = Builder.CreateBitCast(Scalar, SrcIntTy); } if (ShAmt) { // Bail out if we could end with more instructions than we started with. if (!Ext.getVectorOperand()->hasOneUse()) return nullptr; Scalar = Builder.CreateLShr(Scalar, ShAmt); } if (NeedDestBitcast) { Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth); return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy); } return new TruncInst(Scalar, DestTy); } return nullptr; } /// Find elements of V demanded by UserInstr. static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) { unsigned VWidth = cast<VectorType>(V->getType())->getNumElements(); // Conservatively assume that all elements are needed. APInt UsedElts(APInt::getAllOnesValue(VWidth)); switch (UserInstr->getOpcode()) { case Instruction::ExtractElement: { ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr); assert(EEI->getVectorOperand() == V); ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand()); if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) { UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue()); } break; } case Instruction::ShuffleVector: { ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr); unsigned MaskNumElts = cast<VectorType>(UserInstr->getType())->getNumElements(); UsedElts = APInt(VWidth, 0); for (unsigned i = 0; i < MaskNumElts; i++) { unsigned MaskVal = Shuffle->getMaskValue(i); if (MaskVal == -1u || MaskVal >= 2 * VWidth) continue; if (Shuffle->getOperand(0) == V && (MaskVal < VWidth)) UsedElts.setBit(MaskVal); if (Shuffle->getOperand(1) == V && ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth))) UsedElts.setBit(MaskVal - VWidth); } break; } default: break; } return UsedElts; } /// Find union of elements of V demanded by all its users. /// If it is known by querying findDemandedEltsBySingleUser that /// no user demands an element of V, then the corresponding bit /// remains unset in the returned value. static APInt findDemandedEltsByAllUsers(Value *V) { unsigned VWidth = cast<VectorType>(V->getType())->getNumElements(); APInt UnionUsedElts(VWidth, 0); for (const Use &U : V->uses()) { if (Instruction *I = dyn_cast<Instruction>(U.getUser())) { UnionUsedElts |= findDemandedEltsBySingleUser(V, I); } else { UnionUsedElts = APInt::getAllOnesValue(VWidth); break; } if (UnionUsedElts.isAllOnesValue()) break; } return UnionUsedElts; } Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { Value *SrcVec = EI.getVectorOperand(); Value *Index = EI.getIndexOperand(); if (Value *V = SimplifyExtractElementInst(SrcVec, Index, SQ.getWithInstruction(&EI))) return replaceInstUsesWith(EI, V); // If extracting a specified index from the vector, see if we can recursively // find a previously computed scalar that was inserted into the vector. auto *IndexC = dyn_cast<ConstantInt>(Index); if (IndexC) { ElementCount EC = EI.getVectorOperandType()->getElementCount(); unsigned NumElts = EC.Min; // InstSimplify should handle cases where the index is invalid. // For fixed-length vector, it's invalid to extract out-of-range element. if (!EC.Scalable && IndexC->getValue().uge(NumElts)) return nullptr; // This instruction only demands the single element from the input vector. // Skip for scalable type, the number of elements is unknown at // compile-time. if (!EC.Scalable && NumElts != 1) { // If the input vector has a single use, simplify it based on this use // property. if (SrcVec->hasOneUse()) { APInt UndefElts(NumElts, 0); APInt DemandedElts(NumElts, 0); DemandedElts.setBit(IndexC->getZExtValue()); if (Value *V = SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts)) return replaceOperand(EI, 0, V); } else { // If the input vector has multiple uses, simplify it based on a union // of all elements used. APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec); if (!DemandedElts.isAllOnesValue()) { APInt UndefElts(NumElts, 0); if (Value *V = SimplifyDemandedVectorElts( SrcVec, DemandedElts, UndefElts, 0 /* Depth */, true /* AllowMultipleUsers */)) { if (V != SrcVec) { SrcVec->replaceAllUsesWith(V); return &EI; } } } } } if (Instruction *I = foldBitcastExtElt(EI, Builder, DL.isBigEndian())) return I; // If there's a vector PHI feeding a scalar use through this extractelement // instruction, try to scalarize the PHI. if (auto *Phi = dyn_cast<PHINode>(SrcVec)) if (Instruction *ScalarPHI = scalarizePHI(EI, Phi)) return ScalarPHI; } // TODO come up with a n-ary matcher that subsumes both unary and // binary matchers. UnaryOperator *UO; if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, IndexC)) { // extelt (unop X), Index --> unop (extelt X, Index) Value *X = UO->getOperand(0); Value *E = Builder.CreateExtractElement(X, Index); return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO); } BinaryOperator *BO; if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, IndexC)) { // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index) Value *X = BO->getOperand(0), *Y = BO->getOperand(1); Value *E0 = Builder.CreateExtractElement(X, Index); Value *E1 = Builder.CreateExtractElement(Y, Index); return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO); } Value *X, *Y; CmpInst::Predicate Pred; if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) && cheapToScalarize(SrcVec, IndexC)) { // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index) Value *E0 = Builder.CreateExtractElement(X, Index); Value *E1 = Builder.CreateExtractElement(Y, Index); return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1); } if (auto *I = dyn_cast<Instruction>(SrcVec)) { if (auto *IE = dyn_cast<InsertElementInst>(I)) { // Extracting the inserted element? if (IE->getOperand(2) == Index) return replaceInstUsesWith(EI, IE->getOperand(1)); // If the inserted and extracted elements are constants, they must not // be the same value, extract from the pre-inserted value instead. if (isa<Constant>(IE->getOperand(2)) && IndexC) return replaceOperand(EI, 0, IE->getOperand(0)); } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) { // If this is extracting an element from a shufflevector, figure out where // it came from and extract from the appropriate input element instead. // Restrict the following transformation to fixed-length vector. if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) { int SrcIdx = SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue()); Value *Src; unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType()) ->getNumElements(); if (SrcIdx < 0) return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); if (SrcIdx < (int)LHSWidth) Src = SVI->getOperand(0); else { SrcIdx -= LHSWidth; Src = SVI->getOperand(1); } Type *Int32Ty = Type::getInt32Ty(EI.getContext()); return ExtractElementInst::Create( Src, ConstantInt::get(Int32Ty, SrcIdx, false)); } } else if (auto *CI = dyn_cast<CastInst>(I)) { // Canonicalize extractelement(cast) -> cast(extractelement). // Bitcasts can change the number of vector elements, and they cost // nothing. if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index); return CastInst::Create(CI->getOpcode(), EE, EI.getType()); } } } return nullptr; } /// If V is a shuffle of values that ONLY returns elements from either LHS or /// RHS, return the shuffle mask and true. Otherwise, return false. static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, SmallVectorImpl<int> &Mask) { assert(LHS->getType() == RHS->getType() && "Invalid CollectSingleShuffleElements"); unsigned NumElts = cast<VectorType>(V->getType())->getNumElements(); if (isa<UndefValue>(V)) { Mask.assign(NumElts, -1); return true; } if (V == LHS) { for (unsigned i = 0; i != NumElts; ++i) Mask.push_back(i); return true; } if (V == RHS) { for (unsigned i = 0; i != NumElts; ++i) Mask.push_back(i + NumElts); return true; } if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { // If this is an insert of an extract from some other vector, include it. Value *VecOp = IEI->getOperand(0); Value *ScalarOp = IEI->getOperand(1); Value *IdxOp = IEI->getOperand(2); if (!isa<ConstantInt>(IdxOp)) return false; unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. // We can handle this if the vector we are inserting into is // transitively ok. if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { // If so, update the mask to reflect the inserted undef. Mask[InsertedIdx] = -1; return true; } } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ if (isa<ConstantInt>(EI->getOperand(1))) { unsigned ExtractedIdx = cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); unsigned NumLHSElts = cast<VectorType>(LHS->getType())->getNumElements(); // This must be extracting from either LHS or RHS. if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { // We can handle this if the vector we are inserting into is // transitively ok. if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { // If so, update the mask to reflect the inserted value. if (EI->getOperand(0) == LHS) { Mask[InsertedIdx % NumElts] = ExtractedIdx; } else { assert(EI->getOperand(0) == RHS); Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts; } return true; } } } } } return false; } /// If we have insertion into a vector that is wider than the vector that we /// are extracting from, try to widen the source vector to allow a single /// shufflevector to replace one or more insert/extract pairs. static void replaceExtractElements(InsertElementInst *InsElt, ExtractElementInst *ExtElt, InstCombiner &IC) { VectorType *InsVecType = InsElt->getType(); VectorType *ExtVecType = ExtElt->getVectorOperandType(); unsigned NumInsElts = InsVecType->getNumElements(); unsigned NumExtElts = ExtVecType->getNumElements(); // The inserted-to vector must be wider than the extracted-from vector. if (InsVecType->getElementType() != ExtVecType->getElementType() || NumExtElts >= NumInsElts) return; // Create a shuffle mask to widen the extended-from vector using undefined // values. The mask selects all of the values of the original vector followed // by as many undefined values as needed to create a vector of the same length // as the inserted-to vector. SmallVector<int, 16> ExtendMask; for (unsigned i = 0; i < NumExtElts; ++i) ExtendMask.push_back(i); for (unsigned i = NumExtElts; i < NumInsElts; ++i) ExtendMask.push_back(-1); Value *ExtVecOp = ExtElt->getVectorOperand(); auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) ? ExtVecOpInst->getParent() : ExtElt->getParent(); // TODO: This restriction matches the basic block check below when creating // new extractelement instructions. If that limitation is removed, this one // could also be removed. But for now, we just bail out to ensure that we // will replace the extractelement instruction that is feeding our // insertelement instruction. This allows the insertelement to then be // replaced by a shufflevector. If the insertelement is not replaced, we can // induce infinite looping because there's an optimization for extractelement // that will delete our widening shuffle. This would trigger another attempt // here to create that shuffle, and we spin forever. if (InsertionBlock != InsElt->getParent()) return; // TODO: This restriction matches the check in visitInsertElementInst() and // prevents an infinite loop caused by not turning the extract/insert pair // into a shuffle. We really should not need either check, but we're lacking // folds for shufflevectors because we're afraid to generate shuffle masks // that the backend can't handle. if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) return; auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), ExtendMask); // Insert the new shuffle after the vector operand of the extract is defined // (as long as it's not a PHI) or at the start of the basic block of the // extract, so any subsequent extracts in the same basic block can use it. // TODO: Insert before the earliest ExtractElementInst that is replaced. if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) WideVec->insertAfter(ExtVecOpInst); else IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); // Replace extracts from the original narrow vector with extracts from the new // wide vector. for (User *U : ExtVecOp->users()) { ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); if (!OldExt || OldExt->getParent() != WideVec->getParent()) continue; auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); NewExt->insertAfter(OldExt); IC.replaceInstUsesWith(*OldExt, NewExt); } } /// We are building a shuffle to create V, which is a sequence of insertelement, /// extractelement pairs. If PermittedRHS is set, then we must either use it or /// not rely on the second vector source. Return a std::pair containing the /// left and right vectors of the proposed shuffle (or 0), and set the Mask /// parameter as required. /// /// Note: we intentionally don't try to fold earlier shuffles since they have /// often been chosen carefully to be efficiently implementable on the target. using ShuffleOps = std::pair<Value *, Value *>; static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask, Value *PermittedRHS, InstCombiner &IC) { assert(V->getType()->isVectorTy() && "Invalid shuffle!"); unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements(); if (isa<UndefValue>(V)) { Mask.assign(NumElts, -1); return std::make_pair( PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); } if (isa<ConstantAggregateZero>(V)) { Mask.assign(NumElts, 0); return std::make_pair(V, nullptr); } if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { // If this is an insert of an extract from some other vector, include it. Value *VecOp = IEI->getOperand(0); Value *ScalarOp = IEI->getOperand(1); Value *IdxOp = IEI->getOperand(2); if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { unsigned ExtractedIdx = cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); // Either the extracted from or inserted into vector must be RHSVec, // otherwise we'd end up with a shuffle of three inputs. if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { Value *RHS = EI->getOperand(0); ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); assert(LR.second == nullptr || LR.second == RHS); if (LR.first->getType() != RHS->getType()) { // Although we are giving up for now, see if we can create extracts // that match the inserts for another round of combining. replaceExtractElements(IEI, EI, IC); // We tried our best, but we can't find anything compatible with RHS // further up the chain. Return a trivial shuffle. for (unsigned i = 0; i < NumElts; ++i) Mask[i] = i; return std::make_pair(V, nullptr); } unsigned NumLHSElts = cast<VectorType>(RHS->getType())->getNumElements(); Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx; return std::make_pair(LR.first, RHS); } if (VecOp == PermittedRHS) { // We've gone as far as we can: anything on the other side of the // extractelement will already have been converted into a shuffle. unsigned NumLHSElts = cast<VectorType>(EI->getOperand(0)->getType())->getNumElements(); for (unsigned i = 0; i != NumElts; ++i) Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i); return std::make_pair(EI->getOperand(0), PermittedRHS); } // If this insertelement is a chain that comes from exactly these two // vectors, return the vector and the effective shuffle. if (EI->getOperand(0)->getType() == PermittedRHS->getType() && collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, Mask)) return std::make_pair(EI->getOperand(0), PermittedRHS); } } } // Otherwise, we can't do anything fancy. Return an identity vector. for (unsigned i = 0; i != NumElts; ++i) Mask.push_back(i); return std::make_pair(V, nullptr); } /// Try to find redundant insertvalue instructions, like the following ones: /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 /// Here the second instruction inserts values at the same indices, as the /// first one, making the first one redundant. /// It should be transformed to: /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { bool IsRedundant = false; ArrayRef<unsigned int> FirstIndices = I.getIndices(); // If there is a chain of insertvalue instructions (each of them except the // last one has only one use and it's another insertvalue insn from this // chain), check if any of the 'children' uses the same indices as the first // instruction. In this case, the first one is redundant. Value *V = &I; unsigned Depth = 0; while (V->hasOneUse() && Depth < 10) { User *U = V->user_back(); auto UserInsInst = dyn_cast<InsertValueInst>(U); if (!UserInsInst || U->getOperand(0) != V) break; if (UserInsInst->getIndices() == FirstIndices) { IsRedundant = true; break; } V = UserInsInst; Depth++; } if (IsRedundant) return replaceInstUsesWith(I, I.getOperand(0)); return nullptr; } static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { // Can not analyze scalable type, the number of elements is not a compile-time // constant. if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType())) return false; int MaskSize = Shuf.getShuffleMask().size(); int VecSize = cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements(); // A vector select does not change the size of the operands. if (MaskSize != VecSize) return false; // Each mask element must be undefined or choose a vector element from one of // the source operands without crossing vector lanes. for (int i = 0; i != MaskSize; ++i) { int Elt = Shuf.getMaskValue(i); if (Elt != -1 && Elt != i && Elt != i + VecSize) return false; } return true; } /// Turn a chain of inserts that splats a value into an insert + shuffle: /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... -> /// shufflevector(insertelt(X, %k, 0), undef, zero) static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) { // We are interested in the last insert in a chain. So if this insert has a // single user and that user is an insert, bail. if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back())) return nullptr; VectorType *VecTy = InsElt.getType(); // Can not handle scalable type, the number of elements is not a compile-time // constant. if (isa<ScalableVectorType>(VecTy)) return nullptr; unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); // Do not try to do this for a one-element vector, since that's a nop, // and will cause an inf-loop. if (NumElements == 1) return nullptr; Value *SplatVal = InsElt.getOperand(1); InsertElementInst *CurrIE = &InsElt; SmallBitVector ElementPresent(NumElements, false); InsertElementInst *FirstIE = nullptr; // Walk the chain backwards, keeping track of which indices we inserted into, // until we hit something that isn't an insert of the splatted value. while (CurrIE) { auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2)); if (!Idx || CurrIE->getOperand(1) != SplatVal) return nullptr; auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0)); // Check none of the intermediate steps have any additional uses, except // for the root insertelement instruction, which can be re-used, if it // inserts at position 0. if (CurrIE != &InsElt && (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero()))) return nullptr; ElementPresent[Idx->getZExtValue()] = true; FirstIE = CurrIE; CurrIE = NextIE; } // If this is just a single insertelement (not a sequence), we are done. if (FirstIE == &InsElt) return nullptr; // If we are not inserting into an undef vector, make sure we've seen an // insert into every element. // TODO: If the base vector is not undef, it might be better to create a splat // and then a select-shuffle (blend) with the base vector. if (!isa<UndefValue>(FirstIE->getOperand(0))) if (!ElementPresent.all()) return nullptr; // Create the insert + shuffle. Type *Int32Ty = Type::getInt32Ty(InsElt.getContext()); UndefValue *UndefVec = UndefValue::get(VecTy); Constant *Zero = ConstantInt::get(Int32Ty, 0); if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero()) FirstIE = InsertElementInst::Create(UndefVec, SplatVal, Zero, "", &InsElt); // Splat from element 0, but replace absent elements with undef in the mask. SmallVector<int, 16> Mask(NumElements, 0); for (unsigned i = 0; i != NumElements; ++i) if (!ElementPresent[i]) Mask[i] = -1; return new ShuffleVectorInst(FirstIE, UndefVec, Mask); } /// Try to fold an insert element into an existing splat shuffle by changing /// the shuffle's mask to include the index of this insert element. static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) { // Check if the vector operand of this insert is a canonical splat shuffle. auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0)); if (!Shuf || !Shuf->isZeroEltSplat()) return nullptr; // Bail out early if shuffle is scalable type. The number of elements in // shuffle mask is unknown at compile-time. if (isa<ScalableVectorType>(Shuf->getType())) return nullptr; // Check for a constant insertion index. uint64_t IdxC; if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC))) return nullptr; // Check if the splat shuffle's input is the same as this insert's scalar op. Value *X = InsElt.getOperand(1); Value *Op0 = Shuf->getOperand(0); if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt()))) return nullptr; // Replace the shuffle mask element at the index of this insert with a zero. // For example: // inselt (shuf (inselt undef, X, 0), undef, <0,undef,0,undef>), X, 1 // --> shuf (inselt undef, X, 0), undef, <0,0,0,undef> unsigned NumMaskElts = Shuf->getType()->getNumElements(); SmallVector<int, 16> NewMask(NumMaskElts); for (unsigned i = 0; i != NumMaskElts; ++i) NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i); return new ShuffleVectorInst(Op0, UndefValue::get(Op0->getType()), NewMask); } /// Try to fold an extract+insert element into an existing identity shuffle by /// changing the shuffle's mask to include the index of this insert element. static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) { // Check if the vector operand of this insert is an identity shuffle. auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0)); if (!Shuf || !isa<UndefValue>(Shuf->getOperand(1)) || !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding())) return nullptr; // Bail out early if shuffle is scalable type. The number of elements in // shuffle mask is unknown at compile-time. if (isa<ScalableVectorType>(Shuf->getType())) return nullptr; // Check for a constant insertion index. uint64_t IdxC; if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC))) return nullptr; // Check if this insert's scalar op is extracted from the identity shuffle's // input vector. Value *Scalar = InsElt.getOperand(1); Value *X = Shuf->getOperand(0); if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC)))) return nullptr; // Replace the shuffle mask element at the index of this extract+insert with // that same index value. // For example: // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask' unsigned NumMaskElts = Shuf->getType()->getNumElements(); SmallVector<int, 16> NewMask(NumMaskElts); ArrayRef<int> OldMask = Shuf->getShuffleMask(); for (unsigned i = 0; i != NumMaskElts; ++i) { if (i != IdxC) { // All mask elements besides the inserted element remain the same. NewMask[i] = OldMask[i]; } else if (OldMask[i] == (int)IdxC) { // If the mask element was already set, there's nothing to do // (demanded elements analysis may unset it later). return nullptr; } else { assert(OldMask[i] == UndefMaskElem && "Unexpected shuffle mask element for identity shuffle"); NewMask[i] = IdxC; } } return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask); } /// If we have an insertelement instruction feeding into another insertelement /// and the 2nd is inserting a constant into the vector, canonicalize that /// constant insertion before the insertion of a variable: /// /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 --> /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1 /// /// This has the potential of eliminating the 2nd insertelement instruction /// via constant folding of the scalar constant into a vector constant. static Instruction *hoistInsEltConst(InsertElementInst &InsElt2, InstCombiner::BuilderTy &Builder) { auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0)); if (!InsElt1 || !InsElt1->hasOneUse()) return nullptr; Value *X, *Y; Constant *ScalarC; ConstantInt *IdxC1, *IdxC2; if (match(InsElt1->getOperand(0), m_Value(X)) && match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) && match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) && match(InsElt2.getOperand(1), m_Constant(ScalarC)) && match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) { Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2); return InsertElementInst::Create(NewInsElt1, Y, IdxC1); } return nullptr; } /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex /// --> shufflevector X, CVec', Mask' static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); // Bail out if the parent has more than one use. In that case, we'd be // replacing the insertelt with a shuffle, and that's not a clear win. if (!Inst || !Inst->hasOneUse()) return nullptr; if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { // The shuffle must have a constant vector operand. The insertelt must have // a constant scalar being inserted at a constant position in the vector. Constant *ShufConstVec, *InsEltScalar; uint64_t InsEltIndex; if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) return nullptr; // Adding an element to an arbitrary shuffle could be expensive, but a // shuffle that selects elements from vectors without crossing lanes is // assumed cheap. // If we're just adding a constant into that shuffle, it will still be // cheap. if (!isShuffleEquivalentToSelect(*Shuf)) return nullptr; // From the above 'select' check, we know that the mask has the same number // of elements as the vector input operands. We also know that each constant // input element is used in its lane and can not be used more than once by // the shuffle. Therefore, replace the constant in the shuffle's constant // vector with the insertelt constant. Replace the constant in the shuffle's // mask vector with the insertelt index plus the length of the vector // (because the constant vector operand of a shuffle is always the 2nd // operand). ArrayRef<int> Mask = Shuf->getShuffleMask(); unsigned NumElts = Mask.size(); SmallVector<Constant *, 16> NewShufElts(NumElts); SmallVector<int, 16> NewMaskElts(NumElts); for (unsigned I = 0; I != NumElts; ++I) { if (I == InsEltIndex) { NewShufElts[I] = InsEltScalar; NewMaskElts[I] = InsEltIndex + NumElts; } else { // Copy over the existing values. NewShufElts[I] = ShufConstVec->getAggregateElement(I); NewMaskElts[I] = Mask[I]; } } // Create new operands for a shuffle that includes the constant of the // original insertelt. The old shuffle will be dead now. return new ShuffleVectorInst(Shuf->getOperand(0), ConstantVector::get(NewShufElts), NewMaskElts); } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { // Transform sequences of insertelements ops with constant data/indexes into // a single shuffle op. // Can not handle scalable type, the number of elements needed to create // shuffle mask is not a compile-time constant. if (isa<ScalableVectorType>(InsElt.getType())) return nullptr; unsigned NumElts = cast<FixedVectorType>(InsElt.getType())->getNumElements(); uint64_t InsertIdx[2]; Constant *Val[2]; if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || !match(InsElt.getOperand(1), m_Constant(Val[0])) || !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || !match(IEI->getOperand(1), m_Constant(Val[1]))) return nullptr; SmallVector<Constant *, 16> Values(NumElts); SmallVector<int, 16> Mask(NumElts); auto ValI = std::begin(Val); // Generate new constant vector and mask. // We have 2 values/masks from the insertelements instructions. Insert them // into new value/mask vectors. for (uint64_t I : InsertIdx) { if (!Values[I]) { Values[I] = *ValI; Mask[I] = NumElts + I; } ++ValI; } // Remaining values are filled with 'undef' values. for (unsigned I = 0; I < NumElts; ++I) { if (!Values[I]) { Values[I] = UndefValue::get(InsElt.getType()->getElementType()); Mask[I] = I; } } // Create new operands for a shuffle that includes the constant of the // original insertelt. return new ShuffleVectorInst(IEI->getOperand(0), ConstantVector::get(Values), Mask); } return nullptr; } Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { Value *VecOp = IE.getOperand(0); Value *ScalarOp = IE.getOperand(1); Value *IdxOp = IE.getOperand(2); if (auto *V = SimplifyInsertElementInst( VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE))) return replaceInstUsesWith(IE, V); // If the scalar is bitcast and inserted into undef, do the insert in the // source type followed by bitcast. // TODO: Generalize for insert into any constant, not just undef? Value *ScalarSrc; if (match(VecOp, m_Undef()) && match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) && (ScalarSrc->getType()->isIntegerTy() || ScalarSrc->getType()->isFloatingPointTy())) { // inselt undef, (bitcast ScalarSrc), IdxOp --> // bitcast (inselt undef, ScalarSrc, IdxOp) Type *ScalarTy = ScalarSrc->getType(); Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount()); UndefValue *NewUndef = UndefValue::get(VecTy); Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp); return new BitCastInst(NewInsElt, IE.getType()); } // If the vector and scalar are both bitcast from the same element type, do // the insert in that source type followed by bitcast. Value *VecSrc; if (match(VecOp, m_BitCast(m_Value(VecSrc))) && match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) && (VecOp->hasOneUse() || ScalarOp->hasOneUse()) && VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() && cast<VectorType>(VecSrc->getType())->getElementType() == ScalarSrc->getType()) { // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp --> // bitcast (inselt VecSrc, ScalarSrc, IdxOp) Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp); return new BitCastInst(NewInsElt, IE.getType()); } // If the inserted element was extracted from some other fixed-length vector // and both indexes are valid constants, try to turn this into a shuffle. // Can not handle scalable vector type, the number of elements needed to // create shuffle mask is not a compile-time constant. uint64_t InsertedIdx, ExtractedIdx; Value *ExtVecOp; if (isa<FixedVectorType>(IE.getType()) && match(IdxOp, m_ConstantInt(InsertedIdx)) && match(ScalarOp, m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) && isa<FixedVectorType>(ExtVecOp->getType()) && ExtractedIdx < cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) { // TODO: Looking at the user(s) to determine if this insert is a // fold-to-shuffle opportunity does not match the usual instcombine // constraints. We should decide if the transform is worthy based only // on this instruction and its operands, but that may not work currently. // // Here, we are trying to avoid creating shuffles before reaching // the end of a chain of extract-insert pairs. This is complicated because // we do not generally form arbitrary shuffle masks in instcombine // (because those may codegen poorly), but collectShuffleElements() does // exactly that. // // The rules for determining what is an acceptable target-independent // shuffle mask are fuzzy because they evolve based on the backend's // capabilities and real-world impact. auto isShuffleRootCandidate = [](InsertElementInst &Insert) { if (!Insert.hasOneUse()) return true; auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back()); if (!InsertUser) return true; return false; }; // Try to form a shuffle from a chain of extract-insert ops. if (isShuffleRootCandidate(IE)) { SmallVector<int, 16> Mask; ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); // The proposed shuffle may be trivial, in which case we shouldn't // perform the combine. if (LR.first != &IE && LR.second != &IE) { // We now have a shuffle of LHS, RHS, Mask. if (LR.second == nullptr) LR.second = UndefValue::get(LR.first->getType()); return new ShuffleVectorInst(LR.first, LR.second, Mask); } } } if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) { unsigned VWidth = VecTy->getNumElements(); APInt UndefElts(VWidth, 0); APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { if (V != &IE) return replaceInstUsesWith(IE, V); return &IE; } } if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) return Shuf; if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder)) return NewInsElt; if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE)) return Broadcast; if (Instruction *Splat = foldInsEltIntoSplat(IE)) return Splat; if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE)) return IdentityShuf; return nullptr; } /// Return true if we can evaluate the specified expression tree if the vector /// elements were shuffled in a different order. static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask, unsigned Depth = 5) { // We can always reorder the elements of a constant. if (isa<Constant>(V)) return true; // We won't reorder vector arguments. No IPO here. Instruction *I = dyn_cast<Instruction>(V); if (!I) return false; // Two users may expect different orders of the elements. Don't try it. if (!I->hasOneUse()) return false; if (Depth == 0) return false; switch (I->getOpcode()) { case Instruction::UDiv: case Instruction::SDiv: case Instruction::URem: case Instruction::SRem: // Propagating an undefined shuffle mask element to integer div/rem is not // allowed because those opcodes can create immediate undefined behavior // from an undefined element in an operand. if (llvm::any_of(Mask, [](int M){ return M == -1; })) return false; LLVM_FALLTHROUGH; case Instruction::Add: case Instruction::FAdd: case Instruction::Sub: case Instruction::FSub: case Instruction::Mul: case Instruction::FMul: case Instruction::FDiv: case Instruction::FRem: case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: case Instruction::And: case Instruction::Or: case Instruction::Xor: case Instruction::ICmp: case Instruction::FCmp: case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::GetElementPtr: { // Bail out if we would create longer vector ops. We could allow creating // longer vector ops, but that may result in more expensive codegen. Type *ITy = I->getType(); if (ITy->isVectorTy() && Mask.size() > cast<VectorType>(ITy)->getNumElements()) return false; for (Value *Operand : I->operands()) { if (!canEvaluateShuffled(Operand, Mask, Depth - 1)) return false; } return true; } case Instruction::InsertElement: { ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); if (!CI) return false; int ElementNumber = CI->getLimitedValue(); // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' // can't put an element into multiple indices. bool SeenOnce = false; for (int i = 0, e = Mask.size(); i != e; ++i) { if (Mask[i] == ElementNumber) { if (SeenOnce) return false; SeenOnce = true; } } return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1); } } return false; } /// Rebuild a new instruction just like 'I' but with the new operands given. /// In the event of type mismatch, the type of the operands is correct. static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { // We don't want to use the IRBuilder here because we want the replacement // instructions to appear next to 'I', not the builder's insertion point. switch (I->getOpcode()) { case Instruction::Add: case Instruction::FAdd: case Instruction::Sub: case Instruction::FSub: case Instruction::Mul: case Instruction::FMul: case Instruction::UDiv: case Instruction::SDiv: case Instruction::FDiv: case Instruction::URem: case Instruction::SRem: case Instruction::FRem: case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: case Instruction::And: case Instruction::Or: case Instruction::Xor: { BinaryOperator *BO = cast<BinaryOperator>(I); assert(NewOps.size() == 2 && "binary operator with #ops != 2"); BinaryOperator *New = BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), NewOps[0], NewOps[1], "", BO); if (isa<OverflowingBinaryOperator>(BO)) { New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); New->setHasNoSignedWrap(BO->hasNoSignedWrap()); } if (isa<PossiblyExactOperator>(BO)) { New->setIsExact(BO->isExact()); } if (isa<FPMathOperator>(BO)) New->copyFastMathFlags(I); return New; } case Instruction::ICmp: assert(NewOps.size() == 2 && "icmp with #ops != 2"); return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), NewOps[0], NewOps[1]); case Instruction::FCmp: assert(NewOps.size() == 2 && "fcmp with #ops != 2"); return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), NewOps[0], NewOps[1]); case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPTrunc: case Instruction::FPExt: { // It's possible that the mask has a different number of elements from // the original cast. We recompute the destination type to match the mask. Type *DestTy = VectorType::get( I->getType()->getScalarType(), cast<VectorType>(NewOps[0]->getType())->getElementCount()); assert(NewOps.size() == 1 && "cast with #ops != 1"); return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, "", I); } case Instruction::GetElementPtr: { Value *Ptr = NewOps[0]; ArrayRef<Value*> Idx = NewOps.slice(1); GetElementPtrInst *GEP = GetElementPtrInst::Create( cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); return GEP; } } llvm_unreachable("failed to rebuild vector instructions"); } static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { // Mask.size() does not need to be equal to the number of vector elements. assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); Type *EltTy = V->getType()->getScalarType(); Type *I32Ty = IntegerType::getInt32Ty(V->getContext()); if (isa<UndefValue>(V)) return UndefValue::get(FixedVectorType::get(EltTy, Mask.size())); if (isa<ConstantAggregateZero>(V)) return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size())); if (Constant *C = dyn_cast<Constant>(V)) return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), Mask); Instruction *I = cast<Instruction>(V); switch (I->getOpcode()) { case Instruction::Add: case Instruction::FAdd: case Instruction::Sub: case Instruction::FSub: case Instruction::Mul: case Instruction::FMul: case Instruction::UDiv: case Instruction::SDiv: case Instruction::FDiv: case Instruction::URem: case Instruction::SRem: case Instruction::FRem: case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: case Instruction::And: case Instruction::Or: case Instruction::Xor: case Instruction::ICmp: case Instruction::FCmp: case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::Select: case Instruction::GetElementPtr: { SmallVector<Value*, 8> NewOps; bool NeedsRebuild = (Mask.size() != cast<VectorType>(I->getType())->getNumElements()); for (int i = 0, e = I->getNumOperands(); i != e; ++i) { Value *V; // Recursively call evaluateInDifferentElementOrder on vector arguments // as well. E.g. GetElementPtr may have scalar operands even if the // return value is a vector, so we need to examine the operand type. if (I->getOperand(i)->getType()->isVectorTy()) V = evaluateInDifferentElementOrder(I->getOperand(i), Mask); else V = I->getOperand(i); NewOps.push_back(V); NeedsRebuild |= (V != I->getOperand(i)); } if (NeedsRebuild) { return buildNew(I, NewOps); } return I; } case Instruction::InsertElement: { int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); // The insertelement was inserting at Element. Figure out which element // that becomes after shuffling. The answer is guaranteed to be unique // by CanEvaluateShuffled. bool Found = false; int Index = 0; for (int e = Mask.size(); Index != e; ++Index) { if (Mask[Index] == Element) { Found = true; break; } } // If element is not in Mask, no need to handle the operand 1 (element to // be inserted). Just evaluate values in operand 0 according to Mask. if (!Found) return evaluateInDifferentElementOrder(I->getOperand(0), Mask); Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask); return InsertElementInst::Create(V, I->getOperand(1), ConstantInt::get(I32Ty, Index), "", I); } } llvm_unreachable("failed to reorder elements of vector instruction!"); } // Returns true if the shuffle is extracting a contiguous range of values from // LHS, for example: // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| // Shuffles to: |EE|FF|GG|HH| // +--+--+--+--+ static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, ArrayRef<int> Mask) { unsigned LHSElems = cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements(); unsigned MaskElems = Mask.size(); unsigned BegIdx = Mask.front(); unsigned EndIdx = Mask.back(); if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) return false; for (unsigned I = 0; I != MaskElems; ++I) if (static_cast<unsigned>(Mask[I]) != BegIdx + I) return false; return true; } /// These are the ingredients in an alternate form binary operator as described /// below. struct BinopElts { BinaryOperator::BinaryOps Opcode; Value *Op0; Value *Op1; BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0, Value *V0 = nullptr, Value *V1 = nullptr) : Opcode(Opc), Op0(V0), Op1(V1) {} operator bool() const { return Opcode != 0; } }; /// Binops may be transformed into binops with different opcodes and operands. /// Reverse the usual canonicalization to enable folds with the non-canonical /// form of the binop. If a transform is possible, return the elements of the /// new binop. If not, return invalid elements. static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) { Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1); Type *Ty = BO->getType(); switch (BO->getOpcode()) { case Instruction::Shl: { // shl X, C --> mul X, (1 << C) Constant *C; if (match(BO1, m_Constant(C))) { Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C); return { Instruction::Mul, BO0, ShlOne }; } break; } case Instruction::Or: { // or X, C --> add X, C (when X and C have no common bits set) const APInt *C; if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL)) return { Instruction::Add, BO0, BO1 }; break; } default: break; } return {}; } static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) { assert(Shuf.isSelect() && "Must have select-equivalent shuffle"); // Are we shuffling together some value and that same value after it has been // modified by a binop with a constant? Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); Constant *C; bool Op0IsBinop; if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C)))) Op0IsBinop = true; else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C)))) Op0IsBinop = false; else return nullptr; // The identity constant for a binop leaves a variable operand unchanged. For // a vector, this is a splat of something like 0, -1, or 1. // If there's no identity constant for this binop, we're done. auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1); BinaryOperator::BinaryOps BOpcode = BO->getOpcode(); Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true); if (!IdC) return nullptr; // Shuffle identity constants into the lanes that return the original value. // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4} // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4} // The existing binop constant vector remains in the same operand position. ArrayRef<int> Mask = Shuf.getShuffleMask(); Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) : ConstantExpr::getShuffleVector(IdC, C, Mask); bool MightCreatePoisonOrUB = is_contained(Mask, UndefMaskElem) && (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode)); if (MightCreatePoisonOrUB) NewC = getSafeVectorConstantForBinop(BOpcode, NewC, true); // shuf (bop X, C), X, M --> bop X, C' // shuf X, (bop X, C), M --> bop X, C' Value *X = Op0IsBinop ? Op1 : Op0; Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC); NewBO->copyIRFlags(BO); // An undef shuffle mask element may propagate as an undef constant element in // the new binop. That would produce poison where the original code might not. // If we already made a safe constant, then there's no danger. if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB) NewBO->dropPoisonGeneratingFlags(); return NewBO; } /// If we have an insert of a scalar to a non-zero element of an undefined /// vector and then shuffle that value, that's the same as inserting to the zero /// element and shuffling. Splatting from the zero element is recognized as the /// canonical form of splat. static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder) { Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); ArrayRef<int> Mask = Shuf.getShuffleMask(); Value *X; uint64_t IndexC; // Match a shuffle that is a splat to a non-zero element. if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X), m_ConstantInt(IndexC)))) || !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0) return nullptr; // Insert into element 0 of an undef vector. UndefValue *UndefVec = UndefValue::get(Shuf.getType()); Constant *Zero = Builder.getInt32(0); Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero); // Splat from element 0. Any mask element that is undefined remains undefined. // For example: // shuf (inselt undef, X, 2), undef, <2,2,undef> // --> shuf (inselt undef, X, 0), undef, <0,0,undef> unsigned NumMaskElts = Shuf.getType()->getNumElements(); SmallVector<int, 16> NewMask(NumMaskElts, 0); for (unsigned i = 0; i != NumMaskElts; ++i) if (Mask[i] == UndefMaskElem) NewMask[i] = Mask[i]; return new ShuffleVectorInst(NewIns, UndefVec, NewMask); } /// Try to fold shuffles that are the equivalent of a vector select. static Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder, const DataLayout &DL) { if (!Shuf.isSelect()) return nullptr; // Canonicalize to choose from operand 0 first unless operand 1 is undefined. // Commuting undef to operand 0 conflicts with another canonicalization. unsigned NumElts = Shuf.getType()->getNumElements(); if (!isa<UndefValue>(Shuf.getOperand(1)) && Shuf.getMaskValue(0) >= (int)NumElts) { // TODO: Can we assert that both operands of a shuffle-select are not undef // (otherwise, it would have been folded by instsimplify? Shuf.commute(); return &Shuf; } if (Instruction *I = foldSelectShuffleWith1Binop(Shuf)) return I; BinaryOperator *B0, *B1; if (!match(Shuf.getOperand(0), m_BinOp(B0)) || !match(Shuf.getOperand(1), m_BinOp(B1))) return nullptr; Value *X, *Y; Constant *C0, *C1; bool ConstantsAreOp1; if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) && match(B1, m_BinOp(m_Value(Y), m_Constant(C1)))) ConstantsAreOp1 = true; else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) && match(B1, m_BinOp(m_Constant(C1), m_Value(Y)))) ConstantsAreOp1 = false; else return nullptr; // We need matching binops to fold the lanes together. BinaryOperator::BinaryOps Opc0 = B0->getOpcode(); BinaryOperator::BinaryOps Opc1 = B1->getOpcode(); bool DropNSW = false; if (ConstantsAreOp1 && Opc0 != Opc1) { // TODO: We drop "nsw" if shift is converted into multiply because it may // not be correct when the shift amount is BitWidth - 1. We could examine // each vector element to determine if it is safe to keep that flag. if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl) DropNSW = true; if (BinopElts AltB0 = getAlternateBinop(B0, DL)) { assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop"); Opc0 = AltB0.Opcode; C0 = cast<Constant>(AltB0.Op1); } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) { assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop"); Opc1 = AltB1.Opcode; C1 = cast<Constant>(AltB1.Op1); } } if (Opc0 != Opc1) return nullptr; // The opcodes must be the same. Use a new name to make that clear. BinaryOperator::BinaryOps BOpc = Opc0; // Select the constant elements needed for the single binop. ArrayRef<int> Mask = Shuf.getShuffleMask(); Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask); // We are moving a binop after a shuffle. When a shuffle has an undefined // mask element, the result is undefined, but it is not poison or undefined // behavior. That is not necessarily true for div/rem/shift. bool MightCreatePoisonOrUB = is_contained(Mask, UndefMaskElem) && (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc)); if (MightCreatePoisonOrUB) NewC = getSafeVectorConstantForBinop(BOpc, NewC, ConstantsAreOp1); Value *V; if (X == Y) { // Remove a binop and the shuffle by rearranging the constant: // shuffle (op V, C0), (op V, C1), M --> op V, C' // shuffle (op C0, V), (op C1, V), M --> op C', V V = X; } else { // If there are 2 different variable operands, we must create a new shuffle // (select) first, so check uses to ensure that we don't end up with more // instructions than we started with. if (!B0->hasOneUse() && !B1->hasOneUse()) return nullptr; // If we use the original shuffle mask and op1 is *variable*, we would be // putting an undef into operand 1 of div/rem/shift. This is either UB or // poison. We do not have to guard against UB when *constants* are op1 // because safe constants guarantee that we do not overflow sdiv/srem (and // there's no danger for other opcodes). // TODO: To allow this case, create a new shuffle mask with no undefs. if (MightCreatePoisonOrUB && !ConstantsAreOp1) return nullptr; // Note: In general, we do not create new shuffles in InstCombine because we // do not know if a target can lower an arbitrary shuffle optimally. In this // case, the shuffle uses the existing mask, so there is no additional risk. // Select the variable vectors first, then perform the binop: // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C' // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M) V = Builder.CreateShuffleVector(X, Y, Mask); } Instruction *NewBO = ConstantsAreOp1 ? BinaryOperator::Create(BOpc, V, NewC) : BinaryOperator::Create(BOpc, NewC, V); // Flags are intersected from the 2 source binops. But there are 2 exceptions: // 1. If we changed an opcode, poison conditions might have changed. // 2. If the shuffle had undef mask elements, the new binop might have undefs // where the original code did not. But if we already made a safe constant, // then there's no danger. NewBO->copyIRFlags(B0); NewBO->andIRFlags(B1); if (DropNSW) NewBO->setHasNoSignedWrap(false); if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB) NewBO->dropPoisonGeneratingFlags(); return NewBO; } /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate. /// Example (little endian): /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8> static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf, bool IsBigEndian) { // This must be a bitcasted shuffle of 1 vector integer operand. Type *DestType = Shuf.getType(); Value *X; if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) || !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy()) return nullptr; // The source type must have the same number of elements as the shuffle, // and the source element type must be larger than the shuffle element type. Type *SrcType = X->getType(); if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() || cast<VectorType>(SrcType)->getNumElements() != cast<VectorType>(DestType)->getNumElements() || SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0) return nullptr; assert(Shuf.changesLength() && !Shuf.increasesLength() && "Expected a shuffle that decreases length"); // Last, check that the mask chooses the correct low bits for each narrow // element in the result. uint64_t TruncRatio = SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits(); ArrayRef<int> Mask = Shuf.getShuffleMask(); for (unsigned i = 0, e = Mask.size(); i != e; ++i) { if (Mask[i] == UndefMaskElem) continue; uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio; assert(LSBIndex <= std::numeric_limits<int32_t>::max() && "Overflowed 32-bits"); if (Mask[i] != (int)LSBIndex) return nullptr; } return new TruncInst(X, DestType); } /// Match a shuffle-select-shuffle pattern where the shuffles are widening and /// narrowing (concatenating with undef and extracting back to the original /// length). This allows replacing the wide select with a narrow select. static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder) { // This must be a narrowing identity shuffle. It extracts the 1st N elements // of the 1st vector operand of a shuffle. if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract()) return nullptr; // The vector being shuffled must be a vector select that we can eliminate. // TODO: The one-use requirement could be eased if X and/or Y are constants. Value *Cond, *X, *Y; if (!match(Shuf.getOperand(0), m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y))))) return nullptr; // We need a narrow condition value. It must be extended with undef elements // and have the same number of elements as this shuffle. unsigned NarrowNumElts = Shuf.getType()->getNumElements(); Value *NarrowCond; if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) || cast<VectorType>(NarrowCond->getType())->getNumElements() != NarrowNumElts || !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding()) return nullptr; // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) --> // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask) Value *Undef = UndefValue::get(X->getType()); Value *NarrowX = Builder.CreateShuffleVector(X, Undef, Shuf.getShuffleMask()); Value *NarrowY = Builder.CreateShuffleVector(Y, Undef, Shuf.getShuffleMask()); return SelectInst::Create(NarrowCond, NarrowX, NarrowY); } /// Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask. static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) { Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); if (!Shuf.isIdentityWithExtract() || !isa<UndefValue>(Op1)) return nullptr; Value *X, *Y; ArrayRef<int> Mask; if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) return nullptr; // Be conservative with shuffle transforms. If we can't kill the 1st shuffle, // then combining may result in worse codegen. if (!Op0->hasOneUse()) return nullptr; // We are extracting a subvector from a shuffle. Remove excess elements from // the 1st shuffle mask to eliminate the extract. // // This transform is conservatively limited to identity extracts because we do // not allow arbitrary shuffle mask creation as a target-independent transform // (because we can't guarantee that will lower efficiently). // // If the extracting shuffle has an undef mask element, it transfers to the // new shuffle mask. Otherwise, copy the original mask element. Example: // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> --> // shuf X, Y, <C0, undef, C2, undef> unsigned NumElts = Shuf.getType()->getNumElements(); SmallVector<int, 16> NewMask(NumElts); assert(NumElts < Mask.size() && "Identity with extract must have less elements than its inputs"); for (unsigned i = 0; i != NumElts; ++i) { int ExtractMaskElt = Shuf.getMaskValue(i); int MaskElt = Mask[i]; NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt; } return new ShuffleVectorInst(X, Y, NewMask); } /// Try to replace a shuffle with an insertelement or try to replace a shuffle /// operand with the operand of an insertelement. static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf, InstCombiner &IC) { Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1); SmallVector<int, 16> Mask; Shuf.getShuffleMask(Mask); // The shuffle must not change vector sizes. // TODO: This restriction could be removed if the insert has only one use // (because the transform would require a new length-changing shuffle). int NumElts = Mask.size(); if (NumElts != (int)(cast<VectorType>(V0->getType())->getNumElements())) return nullptr; // This is a specialization of a fold in SimplifyDemandedVectorElts. We may // not be able to handle it there if the insertelement has >1 use. // If the shuffle has an insertelement operand but does not choose the // inserted scalar element from that value, then we can replace that shuffle // operand with the source vector of the insertelement. Value *X; uint64_t IdxC; if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) { // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask if (none_of(Mask, [IdxC](int MaskElt) { return MaskElt == (int)IdxC; })) return IC.replaceOperand(Shuf, 0, X); } if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) { // Offset the index constant by the vector width because we are checking for // accesses to the 2nd vector input of the shuffle. IdxC += NumElts; // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask if (none_of(Mask, [IdxC](int MaskElt) { return MaskElt == (int)IdxC; })) return IC.replaceOperand(Shuf, 1, X); } // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC' auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) { // We need an insertelement with a constant index. if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar), m_ConstantInt(IndexC)))) return false; // Test the shuffle mask to see if it splices the inserted scalar into the // operand 1 vector of the shuffle. int NewInsIndex = -1; for (int i = 0; i != NumElts; ++i) { // Ignore undef mask elements. if (Mask[i] == -1) continue; // The shuffle takes elements of operand 1 without lane changes. if (Mask[i] == NumElts + i) continue; // The shuffle must choose the inserted scalar exactly once. if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue()) return false; // The shuffle is placing the inserted scalar into element i. NewInsIndex = i; } assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?"); // Index is updated to the potentially translated insertion lane. IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex); return true; }; // If the shuffle is unnecessary, insert the scalar operand directly into // operand 1 of the shuffle. Example: // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0 Value *Scalar; ConstantInt *IndexC; if (isShufflingScalarIntoOp1(Scalar, IndexC)) return InsertElementInst::Create(V1, Scalar, IndexC); // Try again after commuting shuffle. Example: // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> --> // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3 std::swap(V0, V1); ShuffleVectorInst::commuteShuffleMask(Mask, NumElts); if (isShufflingScalarIntoOp1(Scalar, IndexC)) return InsertElementInst::Create(V1, Scalar, IndexC); return nullptr; } static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) { // Match the operands as identity with padding (also known as concatenation // with undef) shuffles of the same source type. The backend is expected to // recreate these concatenations from a shuffle of narrow operands. auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0)); auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1)); if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() || !Shuffle1 || !Shuffle1->isIdentityWithPadding()) return nullptr; // We limit this transform to power-of-2 types because we expect that the // backend can convert the simplified IR patterns to identical nodes as the // original IR. // TODO: If we can verify the same behavior for arbitrary types, the // power-of-2 checks can be removed. Value *X = Shuffle0->getOperand(0); Value *Y = Shuffle1->getOperand(0); if (X->getType() != Y->getType() || !isPowerOf2_32(Shuf.getType()->getNumElements()) || !isPowerOf2_32(Shuffle0->getType()->getNumElements()) || !isPowerOf2_32(cast<VectorType>(X->getType())->getNumElements()) || isa<UndefValue>(X) || isa<UndefValue>(Y)) return nullptr; assert(isa<UndefValue>(Shuffle0->getOperand(1)) && isa<UndefValue>(Shuffle1->getOperand(1)) && "Unexpected operand for identity shuffle"); // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source // operands directly by adjusting the shuffle mask to account for the narrower // types: // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask' int NarrowElts = cast<VectorType>(X->getType())->getNumElements(); int WideElts = Shuffle0->getType()->getNumElements(); assert(WideElts > NarrowElts && "Unexpected types for identity with padding"); ArrayRef<int> Mask = Shuf.getShuffleMask(); SmallVector<int, 16> NewMask(Mask.size(), -1); for (int i = 0, e = Mask.size(); i != e; ++i) { if (Mask[i] == -1) continue; // If this shuffle is choosing an undef element from 1 of the sources, that // element is undef. if (Mask[i] < WideElts) { if (Shuffle0->getMaskValue(Mask[i]) == -1) continue; } else { if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1) continue; } // If this shuffle is choosing from the 1st narrow op, the mask element is // the same. If this shuffle is choosing from the 2nd narrow op, the mask // element is offset down to adjust for the narrow vector widths. if (Mask[i] < WideElts) { assert(Mask[i] < NarrowElts && "Unexpected shuffle mask"); NewMask[i] = Mask[i]; } else { assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask"); NewMask[i] = Mask[i] - (WideElts - NarrowElts); } } return new ShuffleVectorInst(X, Y, NewMask); } Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { Value *LHS = SVI.getOperand(0); Value *RHS = SVI.getOperand(1); SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI); if (auto *V = SimplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(), SVI.getType(), ShufQuery)) return replaceInstUsesWith(SVI, V); // shuffle x, x, mask --> shuffle x, undef, mask' unsigned VWidth = SVI.getType()->getNumElements(); unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements(); ArrayRef<int> Mask = SVI.getShuffleMask(); Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); // Peek through a bitcasted shuffle operand by scaling the mask. If the // simulated shuffle can simplify, then this shuffle is unnecessary: // shuf (bitcast X), undef, Mask --> bitcast X' // TODO: This could be extended to allow length-changing shuffles. // The transform might also be obsoleted if we allowed canonicalization // of bitcasted shuffles. Value *X; if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) && X->getType()->isVectorTy() && VWidth == LHSWidth) { // Try to create a scaled mask constant. auto *XType = cast<VectorType>(X->getType()); unsigned XNumElts = XType->getNumElements(); SmallVector<int, 16> ScaledMask; if (XNumElts >= VWidth) { assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast"); narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask); } else { assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast"); if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask)) ScaledMask.clear(); } if (!ScaledMask.empty()) { // If the shuffled source vector simplifies, cast that value to this // shuffle's type. if (auto *V = SimplifyShuffleVectorInst(X, UndefValue::get(XType), ScaledMask, XType, ShufQuery)) return BitCastInst::Create(Instruction::BitCast, V, SVI.getType()); } } if (LHS == RHS) { assert(!isa<UndefValue>(RHS) && "Shuffle with 2 undef ops not simplified?"); // Remap any references to RHS to use LHS. SmallVector<int, 16> Elts; for (unsigned i = 0; i != VWidth; ++i) { // Propagate undef elements or force mask to LHS. if (Mask[i] < 0) Elts.push_back(UndefMaskElem); else Elts.push_back(Mask[i] % LHSWidth); } return new ShuffleVectorInst(LHS, UndefValue::get(RHS->getType()), Elts); } // shuffle undef, x, mask --> shuffle x, undef, mask' if (isa<UndefValue>(LHS)) { SVI.commute(); return &SVI; } if (Instruction *I = canonicalizeInsertSplat(SVI, Builder)) return I; if (Instruction *I = foldSelectShuffle(SVI, Builder, DL)) return I; if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian())) return I; if (Instruction *I = narrowVectorSelect(SVI, Builder)) return I; APInt UndefElts(VWidth, 0); APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { if (V != &SVI) return replaceInstUsesWith(SVI, V); return &SVI; } if (Instruction *I = foldIdentityExtractShuffle(SVI)) return I; // These transforms have the potential to lose undef knowledge, so they are // intentionally placed after SimplifyDemandedVectorElts(). if (Instruction *I = foldShuffleWithInsert(SVI, *this)) return I; if (Instruction *I = foldIdentityPaddedShuffles(SVI)) return I; if (isa<UndefValue>(RHS) && canEvaluateShuffled(LHS, Mask)) { Value *V = evaluateInDifferentElementOrder(LHS, Mask); return replaceInstUsesWith(SVI, V); } // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to // a non-vector type. We can instead bitcast the original vector followed by // an extract of the desired element: // // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, // <4 x i32> <i32 0, i32 1, i32 2, i32 3> // %1 = bitcast <4 x i8> %sroa to i32 // Becomes: // %bc = bitcast <16 x i8> %in to <4 x i32> // %ext = extractelement <4 x i32> %bc, i32 0 // // If the shuffle is extracting a contiguous range of values from the input // vector then each use which is a bitcast of the extracted size can be // replaced. This will work if the vector types are compatible, and the begin // index is aligned to a value in the casted vector type. If the begin index // isn't aligned then we can shuffle the original vector (keeping the same // vector type) before extracting. // // This code will bail out if the target type is fundamentally incompatible // with vectors of the source type. // // Example of <16 x i8>, target type i32: // Index range [4,8): v-----------v Will work. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // <16 x i8>: | | | | | | | | | | | | | | | | | // <4 x i32>: | | | | | // +-----------+-----------+-----------+-----------+ // Index range [6,10): ^-----------^ Needs an extra shuffle. // Target type i40: ^--------------^ Won't work, bail. bool MadeChange = false; if (isShuffleExtractingFromLHS(SVI, Mask)) { Value *V = LHS; unsigned MaskElems = Mask.size(); VectorType *SrcTy = cast<VectorType>(V->getType()); unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedSize(); unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); assert(SrcElemBitWidth && "vector elements must have a bitwidth"); unsigned SrcNumElems = SrcTy->getNumElements(); SmallVector<BitCastInst *, 8> BCs; DenseMap<Type *, Value *> NewBCs; for (User *U : SVI.users()) if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) if (!BC->use_empty()) // Only visit bitcasts that weren't previously handled. BCs.push_back(BC); for (BitCastInst *BC : BCs) { unsigned BegIdx = Mask.front(); Type *TgtTy = BC->getDestTy(); unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); if (!TgtElemBitWidth) continue; unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); if (!VecBitWidthsEqual) continue; if (!VectorType::isValidElementType(TgtTy)) continue; auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems); if (!BegIsAligned) { // Shuffle the input so [0,NumElements) contains the output, and // [NumElems,SrcNumElems) is undef. SmallVector<int, 16> ShuffleMask(SrcNumElems, -1); for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) ShuffleMask[I] = Idx; V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()), ShuffleMask, SVI.getName() + ".extract"); BegIdx = 0; } unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; assert(SrcElemsPerTgtElem); BegIdx /= SrcElemsPerTgtElem; bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); auto *NewBC = BCAlreadyExists ? NewBCs[CastSrcTy] : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); if (!BCAlreadyExists) NewBCs[CastSrcTy] = NewBC; auto *Ext = Builder.CreateExtractElement( NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); // The shufflevector isn't being replaced: the bitcast that used it // is. InstCombine will visit the newly-created instructions. replaceInstUsesWith(*BC, Ext); MadeChange = true; } } // If the LHS is a shufflevector itself, see if we can combine it with this // one without producing an unusual shuffle. // Cases that might be simplified: // 1. // x1=shuffle(v1,v2,mask1) // x=shuffle(x1,undef,mask) // ==> // x=shuffle(v1,undef,newMask) // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 // 2. // x1=shuffle(v1,undef,mask1) // x=shuffle(x1,x2,mask) // where v1.size() == mask1.size() // ==> // x=shuffle(v1,x2,newMask) // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] // 3. // x2=shuffle(v2,undef,mask2) // x=shuffle(x1,x2,mask) // where v2.size() == mask2.size() // ==> // x=shuffle(x1,v2,newMask) // newMask[i] = (mask[i] < x1.size()) // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() // 4. // x1=shuffle(v1,undef,mask1) // x2=shuffle(v2,undef,mask2) // x=shuffle(x1,x2,mask) // where v1.size() == v2.size() // ==> // x=shuffle(v1,v2,newMask) // newMask[i] = (mask[i] < x1.size()) // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() // // Here we are really conservative: // we are absolutely afraid of producing a shuffle mask not in the input // program, because the code gen may not be smart enough to turn a merged // shuffle into two specific shuffles: it may produce worse code. As such, // we only merge two shuffles if the result is either a splat or one of the // input shuffle masks. In this case, merging the shuffles just removes // one instruction, which we know is safe. This is good for things like // turning: (splat(splat)) -> splat, or // merge(V[0..n], V[n+1..2n]) -> V[0..2n] ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); if (LHSShuffle) if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) LHSShuffle = nullptr; if (RHSShuffle) if (!isa<UndefValue>(RHSShuffle->getOperand(1))) RHSShuffle = nullptr; if (!LHSShuffle && !RHSShuffle) return MadeChange ? &SVI : nullptr; Value* LHSOp0 = nullptr; Value* LHSOp1 = nullptr; Value* RHSOp0 = nullptr; unsigned LHSOp0Width = 0; unsigned RHSOp0Width = 0; if (LHSShuffle) { LHSOp0 = LHSShuffle->getOperand(0); LHSOp1 = LHSShuffle->getOperand(1); LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements(); } if (RHSShuffle) { RHSOp0 = RHSShuffle->getOperand(0); RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements(); } Value* newLHS = LHS; Value* newRHS = RHS; if (LHSShuffle) { // case 1 if (isa<UndefValue>(RHS)) { newLHS = LHSOp0; newRHS = LHSOp1; } // case 2 or 4 else if (LHSOp0Width == LHSWidth) { newLHS = LHSOp0; } } // case 3 or 4 if (RHSShuffle && RHSOp0Width == LHSWidth) { newRHS = RHSOp0; } // case 4 if (LHSOp0 == RHSOp0) { newLHS = LHSOp0; newRHS = nullptr; } if (newLHS == LHS && newRHS == RHS) return MadeChange ? &SVI : nullptr; ArrayRef<int> LHSMask; ArrayRef<int> RHSMask; if (newLHS != LHS) LHSMask = LHSShuffle->getShuffleMask(); if (RHSShuffle && newRHS != RHS) RHSMask = RHSShuffle->getShuffleMask(); unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; SmallVector<int, 16> newMask; bool isSplat = true; int SplatElt = -1; // Create a new mask for the new ShuffleVectorInst so that the new // ShuffleVectorInst is equivalent to the original one. for (unsigned i = 0; i < VWidth; ++i) { int eltMask; if (Mask[i] < 0) { // This element is an undef value. eltMask = -1; } else if (Mask[i] < (int)LHSWidth) { // This element is from left hand side vector operand. // // If LHS is going to be replaced (case 1, 2, or 4), calculate the // new mask value for the element. if (newLHS != LHS) { eltMask = LHSMask[Mask[i]]; // If the value selected is an undef value, explicitly specify it // with a -1 mask value. if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) eltMask = -1; } else eltMask = Mask[i]; } else { // This element is from right hand side vector operand // // If the value selected is an undef value, explicitly specify it // with a -1 mask value. (case 1) if (isa<UndefValue>(RHS)) eltMask = -1; // If RHS is going to be replaced (case 3 or 4), calculate the // new mask value for the element. else if (newRHS != RHS) { eltMask = RHSMask[Mask[i]-LHSWidth]; // If the value selected is an undef value, explicitly specify it // with a -1 mask value. if (eltMask >= (int)RHSOp0Width) { assert(isa<UndefValue>(RHSShuffle->getOperand(1)) && "should have been check above"); eltMask = -1; } } else eltMask = Mask[i]-LHSWidth; // If LHS's width is changed, shift the mask value accordingly. // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. // If newRHS == newLHS, we want to remap any references from newRHS to // newLHS so that we can properly identify splats that may occur due to // obfuscation across the two vectors. if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) eltMask += newLHSWidth; } // Check if this could still be a splat. if (eltMask >= 0) { if (SplatElt >= 0 && SplatElt != eltMask) isSplat = false; SplatElt = eltMask; } newMask.push_back(eltMask); } // If the result mask is equal to one of the original shuffle masks, // or is a splat, do the replacement. if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { SmallVector<Constant*, 16> Elts; for (unsigned i = 0, e = newMask.size(); i != e; ++i) { if (newMask[i] < 0) { Elts.push_back(UndefValue::get(Int32Ty)); } else { Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); } } if (!newRHS) newRHS = UndefValue::get(newLHS->getType()); return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); } return MadeChange ? &SVI : nullptr; }
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #define BOOST_TEST_MODULE unity Test Suite #include "main.h" #include "random.h" #include "txdb.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "db.h" #include "wallet.h" #endif #include <boost/filesystem.hpp> #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> CClientUIInterface uiInterface; CWallet* pwalletMain; extern bool fPrintToConsole; extern void noui_connect(); struct TestingSetup { CCoinsViewDB *pcoinsdbview; boost::filesystem::path pathTemp; boost::thread_group threadGroup; TestingSetup() { SetupEnvironment(); fPrintToDebugLog = false; // don't want to write to debug.log file fCheckBlockIndex = true; SelectParams(CBaseChainParams::UNITTEST); noui_connect(); #ifdef ENABLE_WALLET bitdb.MakeMock(); #endif pathTemp = GetTempPath() / strprintf("test_unity_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); boost::filesystem::create_directories(pathTemp); mapArgs["-datadir"] = pathTemp.string(); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(pcoinsdbview); InitBlockIndex(); #ifdef ENABLE_WALLET bool fFirstRun; pwalletMain = new CWallet("wallet.dat"); pwalletMain->LoadWallet(fFirstRun); RegisterValidationInterface(pwalletMain); #endif nScriptCheckThreads = 3; for (int i=0; i < nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); RegisterNodeSignals(GetNodeSignals()); } ~TestingSetup() { threadGroup.interrupt_all(); threadGroup.join_all(); UnregisterNodeSignals(GetNodeSignals()); #ifdef ENABLE_WALLET delete pwalletMain; pwalletMain = NULL; #endif delete pcoinsTip; delete pcoinsdbview; delete pblocktree; #ifdef ENABLE_WALLET bitdb.Flush(true); #endif boost::filesystem::remove_all(pathTemp); } }; BOOST_GLOBAL_FIXTURE(TestingSetup); void Shutdown(void* parg) { exit(0); } void StartShutdown() { exit(0); } bool ShutdownRequested() { return false; }
/******************************************************************************* * This file was auto-generated using the AutoGemm.py python script. * DO NOT modify this file! Instead, make changes to scripts in * clBLAS/src/library/blas/AutoGemm/ then re-generate files * (otherwise local changes will be lost after re-generation). ******************************************************************************/ #ifndef KERNEL_CGEMM_COL_CC_B0_MX064_NL064_KX01_SRC_H #define KERNEL_CGEMM_COL_CC_B0_MX064_NL064_KX01_SRC_H const unsigned int cgemm_Col_CC_B0_MX064_NL064_KX01_workGroupNumRows = 16; const unsigned int cgemm_Col_CC_B0_MX064_NL064_KX01_workGroupNumCols = 16; const unsigned int cgemm_Col_CC_B0_MX064_NL064_KX01_microTileNumRows = 4; const unsigned int cgemm_Col_CC_B0_MX064_NL064_KX01_microTileNumCols = 4; const unsigned int cgemm_Col_CC_B0_MX064_NL064_KX01_unroll = 1; const char * const cgemm_Col_CC_B0_MX064_NL064_KX01_src ="\n" "/* cgemm_Col_CC_B0_MX064_NL064_KX01 */\n" "\n" "/* kernel parameters */\n" "#define WG_NUM_ROWS 16\n" "#define WG_NUM_COLS 16\n" "#define MICRO_TILE_NUM_ROWS 4\n" "#define MICRO_TILE_NUM_COLS 4\n" "#define MACRO_TILE_NUM_ROWS 64\n" "#define MACRO_TILE_NUM_COLS 64\n" "#define NUM_UNROLL_ITER 1\n" "\n" "#define LOCAL_ROW_PAD 0\n" "#define LOCAL_COL_PAD 0\n" "\n" "/* global memory indices */\n" "#define GET_GLOBAL_INDEX_A(ROW,COL) ((ROW)*lda+(COL))\n" "#define GET_GLOBAL_INDEX_B(ROW,COL) ((ROW)*ldb+(COL))\n" "#define GET_GLOBAL_INDEX_C(ROW,COL) ((COL)*ldc+(ROW))\n" "\n" "/* local memory indices */\n" "#define GET_LOCAL_INDEX_A(ROW,COL) ((ROW) + (COL)*((MACRO_TILE_NUM_ROWS)+(LOCAL_COL_PAD)) )\n" "#define GET_LOCAL_INDEX_B(ROW,COL) ((COL) + (ROW)*((MACRO_TILE_NUM_COLS)+(LOCAL_ROW_PAD)) )\n" "\n" "/* data types */\n" "#define DATA_TYPE_STR float2\n" "#define TYPE_MAD(MULA,MULB,DST) \\\n" " DST.s0 = mad( MULA.s0, MULB.s0, DST.s0 ); \\\n" " DST.s0 = mad( MULA.s1, -MULB.s1, DST.s0 ); \\\n" " DST.s1 = mad( MULA.s0, -MULB.s1, DST.s1 ); \\\n" " DST.s1 = mad( -MULA.s1, MULB.s0, DST.s1 );\n" "#define TYPE_MAD_WRITE( DST, ALPHA, REG, BETA ) \\\n" " /* (1) */ \\\n" " type_mad_tmp = REG.s0; \\\n" " REG.s0 *= ALPHA.s0; \\\n" " REG.s0 = mad( -ALPHA.s1, REG.s1, REG.s0 ); \\\n" " REG.s1 *= ALPHA.s0; \\\n" " REG.s1 = mad( ALPHA.s1, type_mad_tmp, REG.s1 ); \\\n" " DST = REG;\n" "\n" "/* 4x4 micro-tile */\n" "#define MICRO_TILE \\\n" " rA[0] = localA[offA + 0*WG_NUM_ROWS]; \\\n" " rA[1] = localA[offA + 1*WG_NUM_ROWS]; \\\n" " rA[2] = localA[offA + 2*WG_NUM_ROWS]; \\\n" " rA[3] = localA[offA + 3*WG_NUM_ROWS]; \\\n" " rB[0] = localB[offB + 0*WG_NUM_COLS]; \\\n" " rB[1] = localB[offB + 1*WG_NUM_COLS]; \\\n" " rB[2] = localB[offB + 2*WG_NUM_COLS]; \\\n" " rB[3] = localB[offB + 3*WG_NUM_COLS]; \\\n" " offA += (MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD); \\\n" " offB += (MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD); \\\n" " TYPE_MAD(rA[0],rB[0],rC[0][0]); \\\n" " TYPE_MAD(rA[0],rB[1],rC[0][1]); \\\n" " TYPE_MAD(rA[0],rB[2],rC[0][2]); \\\n" " TYPE_MAD(rA[0],rB[3],rC[0][3]); \\\n" " TYPE_MAD(rA[1],rB[0],rC[1][0]); \\\n" " TYPE_MAD(rA[1],rB[1],rC[1][1]); \\\n" " TYPE_MAD(rA[1],rB[2],rC[1][2]); \\\n" " TYPE_MAD(rA[1],rB[3],rC[1][3]); \\\n" " TYPE_MAD(rA[2],rB[0],rC[2][0]); \\\n" " TYPE_MAD(rA[2],rB[1],rC[2][1]); \\\n" " TYPE_MAD(rA[2],rB[2],rC[2][2]); \\\n" " TYPE_MAD(rA[2],rB[3],rC[2][3]); \\\n" " TYPE_MAD(rA[3],rB[0],rC[3][0]); \\\n" " TYPE_MAD(rA[3],rB[1],rC[3][1]); \\\n" " TYPE_MAD(rA[3],rB[2],rC[3][2]); \\\n" " TYPE_MAD(rA[3],rB[3],rC[3][3]); \\\n" " mem_fence(CLK_LOCAL_MEM_FENCE);\n" "\n" "__attribute__((reqd_work_group_size(WG_NUM_COLS,WG_NUM_ROWS,1)))\n" "__kernel void cgemm_Col_CC_B0_MX064_NL064_KX01(\n" " __global DATA_TYPE_STR const * restrict A,\n" " __global DATA_TYPE_STR const * restrict B,\n" " __global DATA_TYPE_STR * C,\n" " DATA_TYPE_STR const alpha,\n" " DATA_TYPE_STR const beta,\n" " uint const M,\n" " uint const N,\n" " uint const K,\n" " uint const lda,\n" " uint const ldb,\n" " uint const ldc,\n" " uint const offsetA,\n" " uint const offsetB,\n" " uint const offsetC\n" ") {\n" "\n" " /* apply offsets */\n" " A += offsetA;\n" " B += offsetB;\n" " C += offsetC;\n" "\n" " /* allocate registers */\n" " DATA_TYPE_STR rC[MICRO_TILE_NUM_ROWS][MICRO_TILE_NUM_COLS] = { {0} };\n" " DATA_TYPE_STR rA[MICRO_TILE_NUM_ROWS];\n" " DATA_TYPE_STR rB[MICRO_TILE_NUM_COLS];\n" "\n" " /* allocate local memory */\n" " __local DATA_TYPE_STR localA[NUM_UNROLL_ITER*(MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD)];\n" " __local DATA_TYPE_STR localB[NUM_UNROLL_ITER*(MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD)];\n" "\n" " /* work item indices */\n" " uint groupRow = get_group_id(0);\n" " uint groupCol = N / 64; // last column\n" " uint localRow = get_local_id(0);\n" " uint localCol = get_local_id(1);\n" " uint localSerial = localRow + localCol*WG_NUM_ROWS;\n" "\n" " /* global indices being loaded */\n" "#define globalARow(LID) (groupRow*MACRO_TILE_NUM_ROWS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/NUM_UNROLL_ITER)\n" "#define globalACol(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%NUM_UNROLL_ITER)\n" "#define globalBRow(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/MACRO_TILE_NUM_COLS)\n" "#define globalBCol(LID) (groupCol*MACRO_TILE_NUM_COLS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%MACRO_TILE_NUM_COLS)\n" "\n" " /* loop over k */\n" " uint block_k = K / NUM_UNROLL_ITER;\n" " do {\n" "\n" " /* local indices being written */\n" "#define localARow (localSerial / NUM_UNROLL_ITER)\n" "#define localACol (localSerial % NUM_UNROLL_ITER)\n" "#define localAStride (WG_NUM_ROWS*WG_NUM_COLS/NUM_UNROLL_ITER)\n" "#define localBRow ( localSerial / MACRO_TILE_NUM_COLS )\n" "#define localBCol ( localSerial % MACRO_TILE_NUM_COLS )\n" "#define localBStride (WG_NUM_ROWS*WG_NUM_COLS)\n" " __local DATA_TYPE_STR *lA = localA + GET_LOCAL_INDEX_A(localARow, localACol);\n" " __local DATA_TYPE_STR *lB = localB + GET_LOCAL_INDEX_B(localBRow, localBCol);\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "\n" " /* load global -> local */\n" " if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_ROWS*MICRO_TILE_NUM_ROWS*NUM_UNROLL_ITER) ) {\n" " lA[ 0*localAStride ] = A[ GET_GLOBAL_INDEX_A( globalARow(0), globalACol(0) ) ];\n" " }\n" " if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_COLS*MICRO_TILE_NUM_COLS*NUM_UNROLL_ITER) ) {\n" " lB[ 0*localBStride ] = (globalBCol(0) >= N) ? (float2)(0.f, 0.f) : B[ GET_GLOBAL_INDEX_B( globalBRow(0), globalBCol(0) ) ];\n" " }\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" " uint offA = localRow;\n" " uint offB = localCol;\n" "\n" " /* do mads */\n" " MICRO_TILE\n" "\n" " /* shift to next k block */\n" " A += NUM_UNROLL_ITER;\n" " B += ldb*NUM_UNROLL_ITER;\n" "\n" " } while (--block_k > 0);\n" "\n" "\n" " /* which global Cij index */\n" " uint globalCRow = groupRow * MACRO_TILE_NUM_ROWS + localRow;\n" " uint globalCCol = groupCol * MACRO_TILE_NUM_COLS + localCol;\n" "\n" " /* write global Cij */\n" " float type_mad_tmp;\n" " if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[0][0], beta )}\n" " if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[0][1], beta )}\n" " if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[0][2], beta )}\n" " if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[0][3], beta )}\n" " if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[1][0], beta )}\n" " if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[1][1], beta )}\n" " if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[1][2], beta )}\n" " if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[1][3], beta )}\n" " if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[2][0], beta )}\n" " if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[2][1], beta )}\n" " if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[2][2], beta )}\n" " if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[2][3], beta )}\n" " if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[3][0], beta )}\n" " if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[3][1], beta )}\n" " if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[3][2], beta )}\n" " if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[3][3], beta )}\n" "\n" "}\n" ""; #else #endif
/** * @file * @copyright defined in eos/LICENSE */ #include <eosio/http_plugin/http_plugin.hpp> #include <eosio/http_plugin/local_endpoint.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/thread_utils.hpp> #include <fc/network/ip.hpp> #include <fc/log/logger_config.hpp> #include <fc/reflect/variant.hpp> #include <fc/io/json.hpp> #include <fc/io/raw.hpp> #include <fc/crypto/openssl.hpp> #include <boost/asio.hpp> #include <boost/optional.hpp> #include <websocketpp/config/asio_client.hpp> #include <websocketpp/config/asio.hpp> #include <websocketpp/server.hpp> #include <websocketpp/config/asio_client.hpp> #include <websocketpp/client.hpp> #include <websocketpp/logger/stub.hpp> #include <thread> #include <memory> #include <regex> namespace eosio { static appbase::abstract_plugin& _http_plugin = app().register_plugin<http_plugin>(); namespace asio = boost::asio; using std::map; using std::vector; using std::set; using std::string; using std::regex; using boost::optional; using boost::asio::ip::tcp; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using std::shared_ptr; using websocketpp::connection_hdl; enum https_ecdh_curve_t { SECP384R1, PRIME256V1 }; static http_plugin_defaults current_http_plugin_defaults; void http_plugin::set_defaults(const http_plugin_defaults config) { current_http_plugin_defaults = config; } namespace detail { template<class T> struct asio_with_stub_log : public websocketpp::config::asio { typedef asio_with_stub_log type; typedef asio base; typedef base::concurrency_type concurrency_type; typedef base::request_type request_type; typedef base::response_type response_type; typedef base::message_type message_type; typedef base::con_msg_manager_type con_msg_manager_type; typedef base::endpoint_msg_manager_type endpoint_msg_manager_type; typedef websocketpp::log::stub elog_type; typedef websocketpp::log::stub alog_type; typedef base::rng_type rng_type; struct transport_config : public base::transport_config { typedef type::concurrency_type concurrency_type; typedef type::alog_type alog_type; typedef type::elog_type elog_type; typedef type::request_type request_type; typedef type::response_type response_type; typedef T socket_type; }; typedef websocketpp::transport::asio::endpoint<transport_config> transport_type; static const long timeout_open_handshake = 0; }; struct asio_local_with_stub_log : public websocketpp::config::asio { typedef asio_local_with_stub_log type; typedef asio base; typedef base::concurrency_type concurrency_type; typedef base::request_type request_type; typedef base::response_type response_type; typedef base::message_type message_type; typedef base::con_msg_manager_type con_msg_manager_type; typedef base::endpoint_msg_manager_type endpoint_msg_manager_type; typedef websocketpp::log::stub elog_type; typedef websocketpp::log::stub alog_type; typedef base::rng_type rng_type; struct transport_config : public base::transport_config { typedef type::concurrency_type concurrency_type; typedef type::alog_type alog_type; typedef type::elog_type elog_type; typedef type::request_type request_type; typedef type::response_type response_type; typedef websocketpp::transport::asio::basic_socket::local_endpoint socket_type; }; typedef websocketpp::transport::asio::local_endpoint<transport_config> transport_type; static const long timeout_open_handshake = 0; }; } using websocket_server_type = websocketpp::server<detail::asio_with_stub_log<websocketpp::transport::asio::basic_socket::endpoint>>; using websocket_local_server_type = websocketpp::server<detail::asio_local_with_stub_log>; using websocket_server_tls_type = websocketpp::server<detail::asio_with_stub_log<websocketpp::transport::asio::tls_socket::endpoint>>; using ssl_context_ptr = websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context>; static bool verbose_http_errors = false; class http_plugin_impl { public: map<string,url_handler> url_handlers; optional<tcp::endpoint> listen_endpoint; string access_control_allow_origin; string access_control_allow_headers; string access_control_max_age; bool access_control_allow_credentials = false; size_t max_body_size{1024*1024}; websocket_server_type server; uint16_t thread_pool_size = 2; optional<eosio::chain::named_thread_pool> thread_pool; std::atomic<size_t> bytes_in_flight{0}; size_t max_bytes_in_flight = 0; fc::microseconds max_response_time{30*1000}; optional<tcp::endpoint> https_listen_endpoint; string https_cert_chain; string https_key; https_ecdh_curve_t https_ecdh_curve = SECP384R1; websocket_server_tls_type https_server; optional<asio::local::stream_protocol::endpoint> unix_endpoint; websocket_local_server_type unix_server; bool validate_host; set<string> valid_hosts; bool host_port_is_valid( const std::string& header_host_port, const string& endpoint_local_host_port ) { return !validate_host || header_host_port == endpoint_local_host_port || valid_hosts.find(header_host_port) != valid_hosts.end(); } bool host_is_valid( const std::string& host, const string& endpoint_local_host_port, bool secure) { if (!validate_host) { return true; } // normalise the incoming host so that it always has the explicit port static auto has_port_expr = regex("[^:]:[0-9]+$"); /// ends in :<number> without a preceeding colon which implies ipv6 if (std::regex_search(host, has_port_expr)) { return host_port_is_valid( host, endpoint_local_host_port ); } else { // according to RFC 2732 ipv6 addresses should always be enclosed with brackets so we shouldn't need to special case here return host_port_is_valid( host + ":" + std::to_string(secure ? websocketpp::uri_default_secure_port : websocketpp::uri_default_port ), endpoint_local_host_port); } } ssl_context_ptr on_tls_init(websocketpp::connection_hdl hdl) { ssl_context_ptr ctx = websocketpp::lib::make_shared<websocketpp::lib::asio::ssl::context>(asio::ssl::context::sslv23_server); try { ctx->set_options(asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3 | asio::ssl::context::no_tlsv1 | asio::ssl::context::no_tlsv1_1 | asio::ssl::context::single_dh_use); ctx->use_certificate_chain_file(https_cert_chain); ctx->use_private_key_file(https_key, asio::ssl::context::pem); //going for the A+! Do a few more things on the native context to get ECDH in use fc::ec_key ecdh = EC_KEY_new_by_curve_name(https_ecdh_curve == SECP384R1 ? NID_secp384r1 : NID_X9_62_prime256v1); if (!ecdh) EOS_THROW(chain::http_exception, "Failed to set NID_secp384r1"); if(SSL_CTX_set_tmp_ecdh(ctx->native_handle(), (EC_KEY*)ecdh) != 1) EOS_THROW(chain::http_exception, "Failed to set ECDH PFS"); if(SSL_CTX_set_cipher_list(ctx->native_handle(), \ "EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:AES256:" \ "!DHE:!RSA:!AES128:!RC4:!DES:!3DES:!DSS:!SRP:!PSK:!EXP:!MD5:!LOW:!aNULL:!eNULL") != 1) EOS_THROW(chain::http_exception, "Failed to set HTTPS cipher list"); } catch (const fc::exception& e) { elog("https server initialization error: ${w}", ("w", e.to_detail_string())); } catch(std::exception& e) { elog("https server initialization error: ${w}", ("w", e.what())); } return ctx; } template<class T> static void handle_exception(typename websocketpp::server<T>::connection_ptr con) { string err = "Internal Service error, http: "; const auto deadline = fc::time_point::now() + fc::exception::format_time_limit; try { con->set_status( websocketpp::http::status_code::internal_server_error ); try { throw; } catch (const fc::exception& e) { err += e.to_detail_string(); elog( "${e}", ("e", err)); error_results results{websocketpp::http::status_code::internal_server_error, "Internal Service Error", error_results::error_info( e, verbose_http_errors )}; con->set_body( fc::json::to_string( results, deadline )); } catch (const std::exception& e) { err += e.what(); elog( "${e}", ("e", err)); error_results results{websocketpp::http::status_code::internal_server_error, "Internal Service Error", error_results::error_info( fc::exception( FC_LOG_MESSAGE( error, e.what())), verbose_http_errors )}; con->set_body( fc::json::to_string( results, deadline )); } catch (...) { err += "Unknown Exception"; error_results results{websocketpp::http::status_code::internal_server_error, "Internal Service Error", error_results::error_info( fc::exception( FC_LOG_MESSAGE( error, "Unknown Exception" )), verbose_http_errors )}; con->set_body( fc::json::to_string( results, deadline )); } } catch (fc::timeout_exception& e) { con->set_body( R"xxx({"message": "Internal Server Error"})xxx" ); elog( "Timeout exception ${te} attempting to handle exception: ${e}", ("te", e.to_detail_string())("e", err) ); } catch (...) { con->set_body( R"xxx({"message": "Internal Server Error"})xxx" ); std::cerr << "Exception attempting to handle exception: " << err << std::endl; } } template<class T> bool allow_host(const typename T::request_type& req, typename websocketpp::server<T>::connection_ptr con) { bool is_secure = con->get_uri()->get_secure(); const auto& local_endpoint = con->get_socket().lowest_layer().local_endpoint(); auto local_socket_host_port = local_endpoint.address().to_string() + ":" + std::to_string(local_endpoint.port()); const auto& host_str = req.get_header("Host"); if (host_str.empty() || !host_is_valid(host_str, local_socket_host_port, is_secure)) { con->set_status(websocketpp::http::status_code::bad_request); return false; } return true; } template<typename T> bool verify_max_bytes_in_flight( const T& con ) { if( bytes_in_flight > max_bytes_in_flight ) { dlog( "503 - too many bytes in flight: ${bytes}", ("bytes", bytes_in_flight.load()) ); error_results results{websocketpp::http::status_code::too_many_requests, "Busy", error_results::error_info()}; con->set_body( fc::json::to_string( results, fc::time_point::maximum() )); con->set_status( websocketpp::http::status_code::too_many_requests ); return false; } return true; } template<class T> void handle_http_request(typename websocketpp::server<T>::connection_ptr con) { try { auto& req = con->get_request(); if(!allow_host<T>(req, con)) return; if( !access_control_allow_origin.empty()) { con->append_header( "Access-Control-Allow-Origin", access_control_allow_origin ); } if( !access_control_allow_headers.empty()) { con->append_header( "Access-Control-Allow-Headers", access_control_allow_headers ); } if( !access_control_max_age.empty()) { con->append_header( "Access-Control-Max-Age", access_control_max_age ); } if( access_control_allow_credentials ) { con->append_header( "Access-Control-Allow-Credentials", "true" ); } if(req.get_method() == "OPTIONS") { con->set_status(websocketpp::http::status_code::ok); return; } con->append_header( "Content-type", "application/json" ); if( !verify_max_bytes_in_flight( con ) ) return; std::string body = con->get_request_body(); std::string resource = con->get_uri()->get_resource(); auto handler_itr = url_handlers.find( resource ); if( handler_itr != url_handlers.end()) { con->defer_http_response(); bytes_in_flight += body.size(); app().post( appbase::priority::low, [&ioc = thread_pool->get_executor(), &bytes_in_flight = this->bytes_in_flight, handler_itr, this, resource{std::move( resource )}, body{std::move( body )}, con]() mutable { const size_t body_size = body.size(); if( !verify_max_bytes_in_flight( con ) ) { con->send_http_response(); bytes_in_flight -= body_size; return; } try { handler_itr->second( std::move( resource ), std::move( body ), [&ioc, &bytes_in_flight, con, this]( int code, fc::variant response_body ) { size_t response_size = 0; try { response_size = fc::raw::pack_size( response_body ); } catch(...) {} bytes_in_flight += response_size; if( !verify_max_bytes_in_flight( con ) ) { con->send_http_response(); bytes_in_flight -= response_size; } else { boost::asio::post( ioc, [response_body{std::move( response_body )}, response_size, &bytes_in_flight, con, code, max_response_time=max_response_time]() mutable { std::string json; try { json = fc::json::to_string( response_body, fc::time_point::now() + max_response_time ); con->set_body( std::move( json ) ); con->set_status( websocketpp::http::status_code::value( code ) ); } catch( ... ) { handle_exception<T>( con ); } response_body.clear(); const size_t json_size = json.size(); bytes_in_flight += json_size; con->send_http_response(); bytes_in_flight -= (json_size + response_size); } ); } }); } catch( ... ) { handle_exception<T>( con ); con->send_http_response(); } bytes_in_flight -= body_size; } ); } else { dlog( "404 - not found: ${ep}", ("ep", resource)); error_results results{websocketpp::http::status_code::not_found, "Not Found", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, "Unknown Endpoint" )), verbose_http_errors )}; con->set_body( fc::json::to_string( results, fc::time_point::now() + max_response_time )); con->set_status( websocketpp::http::status_code::not_found ); } } catch( ... ) { handle_exception<T>( con ); } } template<class T> void create_server_for_endpoint(const tcp::endpoint& ep, websocketpp::server<detail::asio_with_stub_log<T>>& ws) { try { ws.clear_access_channels(websocketpp::log::alevel::all); ws.init_asio( &thread_pool->get_executor() ); ws.set_reuse_addr(true); ws.set_max_http_body_size(max_body_size); // capture server_ioc shared_ptr in http handler to keep it alive while in use ws.set_http_handler([&](connection_hdl hdl) { handle_http_request<detail::asio_with_stub_log<T>>(ws.get_con_from_hdl(hdl)); }); } catch ( const fc::exception& e ){ elog( "http: ${e}", ("e",e.to_detail_string())); } catch ( const std::exception& e ){ elog( "http: ${e}", ("e",e.what())); } catch (...) { elog("error thrown from http io service"); } } void add_aliases_for_endpoint( const tcp::endpoint& ep, string host, string port ) { auto resolved_port_str = std::to_string(ep.port()); valid_hosts.emplace(host + ":" + port); valid_hosts.emplace(host + ":" + resolved_port_str); } }; template<> bool http_plugin_impl::allow_host<detail::asio_local_with_stub_log>(const detail::asio_local_with_stub_log::request_type& req, websocketpp::server<detail::asio_local_with_stub_log>::connection_ptr con) { return true; } http_plugin::http_plugin():my(new http_plugin_impl()){ app().register_config_type<https_ecdh_curve_t>(); } http_plugin::~http_plugin(){} void http_plugin::set_program_options(options_description&, options_description& cfg) { if(current_http_plugin_defaults.default_unix_socket_path.length()) cfg.add_options() ("unix-socket-path", bpo::value<string>()->default_value(current_http_plugin_defaults.default_unix_socket_path), "The filename (relative to data-dir) to create a unix socket for HTTP RPC; set blank to disable."); if(current_http_plugin_defaults.default_http_port) cfg.add_options() ("http-server-address", bpo::value<string>()->default_value("127.0.0.1:" + std::to_string(current_http_plugin_defaults.default_http_port)), "The local IP and port to listen for incoming http connections; set blank to disable."); else cfg.add_options() ("http-server-address", bpo::value<string>(), "The local IP and port to listen for incoming http connections; leave blank to disable."); cfg.add_options() ("https-server-address", bpo::value<string>(), "The local IP and port to listen for incoming https connections; leave blank to disable.") ("https-certificate-chain-file", bpo::value<string>(), "Filename with the certificate chain to present on https connections. PEM format. Required for https.") ("https-private-key-file", bpo::value<string>(), "Filename with https private key in PEM format. Required for https") ("https-ecdh-curve", bpo::value<https_ecdh_curve_t>()->notifier([this](https_ecdh_curve_t c) { my->https_ecdh_curve = c; })->default_value(SECP384R1), "Configure https ECDH curve to use: secp384r1 or prime256v1") ("access-control-allow-origin", bpo::value<string>()->notifier([this](const string& v) { my->access_control_allow_origin = v; ilog("configured http with Access-Control-Allow-Origin: ${o}", ("o", my->access_control_allow_origin)); }), "Specify the Access-Control-Allow-Origin to be returned on each request.") ("access-control-allow-headers", bpo::value<string>()->notifier([this](const string& v) { my->access_control_allow_headers = v; ilog("configured http with Access-Control-Allow-Headers : ${o}", ("o", my->access_control_allow_headers)); }), "Specify the Access-Control-Allow-Headers to be returned on each request.") ("access-control-max-age", bpo::value<string>()->notifier([this](const string& v) { my->access_control_max_age = v; ilog("configured http with Access-Control-Max-Age : ${o}", ("o", my->access_control_max_age)); }), "Specify the Access-Control-Max-Age to be returned on each request.") ("access-control-allow-credentials", bpo::bool_switch()->notifier([this](bool v) { my->access_control_allow_credentials = v; if (v) ilog("configured http with Access-Control-Allow-Credentials: true"); })->default_value(false), "Specify if Access-Control-Allow-Credentials: true should be returned on each request.") ("max-body-size", bpo::value<uint32_t>()->default_value(1024*1024), "The maximum body size in bytes allowed for incoming RPC requests") ("http-max-bytes-in-flight-mb", bpo::value<uint32_t>()->default_value(500), "Maximum size in megabytes http_plugin should use for processing http requests. 503 error response when exceeded." ) ("http-max-response-time-ms", bpo::value<uint32_t>()->default_value(30), "Maximum time for processing a request.") ("verbose-http-errors", bpo::bool_switch()->default_value(false), "Append the error log to HTTP responses") ("http-validate-host", boost::program_options::value<bool>()->default_value(true), "If set to false, then any incoming \"Host\" header is considered valid") ("http-alias", bpo::value<std::vector<string>>()->composing(), "Additionaly acceptable values for the \"Host\" header of incoming HTTP requests, can be specified multiple times. Includes http/s_server_address by default.") ("http-threads", bpo::value<uint16_t>()->default_value( my->thread_pool_size ), "Number of worker threads in http thread pool") ; } void http_plugin::plugin_initialize(const variables_map& options) { try { my->validate_host = options.at("http-validate-host").as<bool>(); if( options.count( "http-alias" )) { const auto& aliases = options["http-alias"].as<vector<string>>(); my->valid_hosts.insert(aliases.begin(), aliases.end()); } tcp::resolver resolver( app().get_io_service()); if( options.count( "http-server-address" ) && options.at( "http-server-address" ).as<string>().length()) { string lipstr = options.at( "http-server-address" ).as<string>(); string host = lipstr.substr( 0, lipstr.find( ':' )); string port = lipstr.substr( host.size() + 1, lipstr.size()); tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str()); try { my->listen_endpoint = *resolver.resolve( query ); ilog( "configured http to listen on ${h}:${p}", ("h", host)( "p", port )); } catch ( const boost::system::system_error& ec ) { elog( "failed to configure http to listen on ${h}:${p} (${m})", ("h", host)( "p", port )( "m", ec.what())); } // add in resolved hosts and ports as well if (my->listen_endpoint) { my->add_aliases_for_endpoint(*my->listen_endpoint, host, port); } } if( options.count( "unix-socket-path" ) && !options.at( "unix-socket-path" ).as<string>().empty()) { boost::filesystem::path sock_path = options.at("unix-socket-path").as<string>(); if (sock_path.is_relative()) sock_path = app().data_dir() / sock_path; my->unix_endpoint = asio::local::stream_protocol::endpoint(sock_path.string()); } if( options.count( "https-server-address" ) && options.at( "https-server-address" ).as<string>().length()) { if( !options.count( "https-certificate-chain-file" ) || options.at( "https-certificate-chain-file" ).as<string>().empty()) { elog( "https-certificate-chain-file is required for HTTPS" ); return; } if( !options.count( "https-private-key-file" ) || options.at( "https-private-key-file" ).as<string>().empty()) { elog( "https-private-key-file is required for HTTPS" ); return; } string lipstr = options.at( "https-server-address" ).as<string>(); string host = lipstr.substr( 0, lipstr.find( ':' )); string port = lipstr.substr( host.size() + 1, lipstr.size()); tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str()); try { my->https_listen_endpoint = *resolver.resolve( query ); ilog( "configured https to listen on ${h}:${p} (TLS configuration will be validated momentarily)", ("h", host)( "p", port )); my->https_cert_chain = options.at( "https-certificate-chain-file" ).as<string>(); my->https_key = options.at( "https-private-key-file" ).as<string>(); } catch ( const boost::system::system_error& ec ) { elog( "failed to configure https to listen on ${h}:${p} (${m})", ("h", host)( "p", port )( "m", ec.what())); } // add in resolved hosts and ports as well if (my->https_listen_endpoint) { my->add_aliases_for_endpoint(*my->https_listen_endpoint, host, port); } } my->max_body_size = options.at( "max-body-size" ).as<uint32_t>(); verbose_http_errors = options.at( "verbose-http-errors" ).as<bool>(); my->thread_pool_size = options.at( "http-threads" ).as<uint16_t>(); EOS_ASSERT( my->thread_pool_size > 0, chain::plugin_config_exception, "http-threads ${num} must be greater than 0", ("num", my->thread_pool_size)); my->max_bytes_in_flight = options.at( "http-max-bytes-in-flight-mb" ).as<uint32_t>() * 1024 * 1024; my->max_response_time = fc::microseconds( options.at("http-max-response-time-ms").as<uint32_t>() * 1000 ); //watch out for the returns above when adding new code here } FC_LOG_AND_RETHROW() } void http_plugin::plugin_startup() { my->thread_pool.emplace( "http", my->thread_pool_size ); if(my->listen_endpoint) { try { my->create_server_for_endpoint(*my->listen_endpoint, my->server); ilog("start listening for http requests"); my->server.listen(*my->listen_endpoint); my->server.start_accept(); } catch ( const fc::exception& e ){ elog( "http service failed to start: ${e}", ("e",e.to_detail_string())); throw; } catch ( const std::exception& e ){ elog( "http service failed to start: ${e}", ("e",e.what())); throw; } catch (...) { elog("error thrown from http io service"); throw; } } if(my->unix_endpoint) { try { my->unix_server.clear_access_channels(websocketpp::log::alevel::all); my->unix_server.init_asio( &my->thread_pool->get_executor() ); my->unix_server.set_max_http_body_size(my->max_body_size); my->unix_server.listen(*my->unix_endpoint); my->unix_server.set_http_handler([&, &ioc = my->thread_pool->get_executor()](connection_hdl hdl) { my->handle_http_request<detail::asio_local_with_stub_log>( my->unix_server.get_con_from_hdl(hdl)); }); my->unix_server.start_accept(); } catch ( const fc::exception& e ){ elog( "unix socket service failed to start: ${e}", ("e",e.to_detail_string())); throw; } catch ( const std::exception& e ){ elog( "unix socket service failed to start: ${e}", ("e",e.what())); throw; } catch (...) { elog("error thrown from unix socket io service"); throw; } } if(my->https_listen_endpoint) { try { my->create_server_for_endpoint(*my->https_listen_endpoint, my->https_server); my->https_server.set_tls_init_handler([this](websocketpp::connection_hdl hdl) -> ssl_context_ptr{ return my->on_tls_init(hdl); }); ilog("start listening for https requests"); my->https_server.listen(*my->https_listen_endpoint); my->https_server.start_accept(); } catch ( const fc::exception& e ){ elog( "https service failed to start: ${e}", ("e",e.to_detail_string())); throw; } catch ( const std::exception& e ){ elog( "https service failed to start: ${e}", ("e",e.what())); throw; } catch (...) { elog("error thrown from https io service"); throw; } } add_api({{ std::string("/v1/node/get_supported_apis"), [&](string, string body, url_response_callback cb) mutable { try { if (body.empty()) body = "{}"; auto result = (*this).get_supported_apis(); cb(200, fc::variant(result)); } catch (...) { handle_exception("node", "get_supported_apis", body, cb); } } }}); } void http_plugin::plugin_shutdown() { if(my->server.is_listening()) my->server.stop_listening(); if(my->https_server.is_listening()) my->https_server.stop_listening(); if(my->unix_server.is_listening()) my->unix_server.stop_listening(); if( my->thread_pool ) { my->thread_pool->stop(); } } void http_plugin::add_handler(const string& url, const url_handler& handler) { ilog( "add api url: ${c}", ("c",url) ); my->url_handlers.insert(std::make_pair(url,handler)); } void http_plugin::handle_exception( const char *api_name, const char *call_name, const string& body, url_response_callback cb ) { try { try { throw; } catch (chain::unknown_block_exception& e) { error_results results{400, "Unknown Block", error_results::error_info(e, verbose_http_errors)}; cb( 400, fc::variant( results )); } catch (chain::unsatisfied_authorization& e) { error_results results{401, "UnAuthorized", error_results::error_info(e, verbose_http_errors)}; cb( 401, fc::variant( results )); } catch (chain::tx_duplicate& e) { error_results results{409, "Conflict", error_results::error_info(e, verbose_http_errors)}; cb( 409, fc::variant( results )); } catch (fc::eof_exception& e) { error_results results{422, "Unprocessable Entity", error_results::error_info(e, verbose_http_errors)}; cb( 422, fc::variant( results )); elog( "Unable to parse arguments to ${api}.${call}", ("api", api_name)( "call", call_name )); dlog("Bad arguments: ${args}", ("args", body)); } catch (fc::exception& e) { error_results results{500, "Internal Service Error", error_results::error_info(e, verbose_http_errors)}; cb( 500, fc::variant( results )); if (e.code() != chain::greylist_net_usage_exceeded::code_value && e.code() != chain::greylist_cpu_usage_exceeded::code_value) { elog( "FC Exception encountered while processing ${api}.${call}", ("api", api_name)( "call", call_name )); dlog( "Exception Details: ${e}", ("e", e.to_detail_string())); } } catch (std::exception& e) { error_results results{500, "Internal Service Error", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, e.what())), verbose_http_errors)}; cb( 500, fc::variant( results )); elog( "STD Exception encountered while processing ${api}.${call}", ("api", api_name)( "call", call_name )); dlog( "Exception Details: ${e}", ("e", e.what())); } catch (...) { error_results results{500, "Internal Service Error", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, "Unknown Exception" )), verbose_http_errors)}; cb( 500, fc::variant( results )); elog( "Unknown Exception encountered while processing ${api}.${call}", ("api", api_name)( "call", call_name )); } } catch (...) { std::cerr << "Exception attempting to handle exception for " << api_name << "." << call_name << std::endl; } } bool http_plugin::is_on_loopback() const { return (!my->listen_endpoint || my->listen_endpoint->address().is_loopback()) && (!my->https_listen_endpoint || my->https_listen_endpoint->address().is_loopback()); } bool http_plugin::is_secure() const { return (!my->listen_endpoint || my->listen_endpoint->address().is_loopback()); } bool http_plugin::verbose_errors()const { return verbose_http_errors; } http_plugin::get_supported_apis_result http_plugin::get_supported_apis()const { get_supported_apis_result result; for (const auto& handler : my->url_handlers) { if (handler.first != "/v1/node/get_supported_apis") result.apis.emplace_back(handler.first); } return result; } std::istream& operator>>(std::istream& in, https_ecdh_curve_t& curve) { std::string s; in >> s; if (s == "secp384r1") curve = SECP384R1; else if (s == "prime256v1") curve = PRIME256V1; else in.setstate(std::ios_base::failbit); return in; } std::ostream& operator<<(std::ostream& osm, https_ecdh_curve_t curve) { if (curve == SECP384R1) { osm << "secp384r1"; } else if (curve == PRIME256V1) { osm << "prime256v1"; } return osm; } }
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/core/utils/crypto/Cipher.h> #include <aws/core/utils/crypto/Factories.h> #include <aws/core/utils/crypto/SecureRandom.h> #include <aws/core/utils/logging/LogMacros.h> #include <cstdlib> #include <climits> //if you are reading this, you are witnessing pure brilliance. #define IS_BIG_ENDIAN (*(uint16_t*)"\0\xff" < 0x100) using namespace Aws::Utils::Crypto; using namespace Aws::Utils; namespace Aws { namespace Utils { namespace Crypto { static const char* LOG_TAG = "Cipher"; //swap byte ordering template<class T> typename std::enable_if<std::is_unsigned<T>::value, T>::type bswap(T i, T j = 0u, std::size_t n = 0u) { return n == sizeof(T) ? j : bswap<T>(i >> CHAR_BIT, (j << CHAR_BIT) | (i & (T)(unsigned char)(-1)), n + 1); } CryptoBuffer IncrementCTRCounter(const CryptoBuffer& counter, uint32_t numberOfBlocks) { // minium counter size is 12 bytes. This isn't a variable because some compilers // are stupid and thing that variable is unused. assert(counter.GetLength() >= 12); CryptoBuffer incrementedCounter(counter); //get the last 4 bytes and manipulate them as an integer. uint32_t* ctrPtr = (uint32_t*)(incrementedCounter.GetUnderlyingData() + incrementedCounter.GetLength() - sizeof(int32_t)); if(IS_BIG_ENDIAN) { //you likely are not Big Endian, but //if it's big endian, just go ahead and increment it... done *ctrPtr += numberOfBlocks; } else { //otherwise, swap the byte ordering of the integer we loaded from the buffer (because it is backwards). However, the number of blocks is already properly //aligned. Once we compute the new value, swap it back so that the mirroring operation goes back to the actual buffer. *ctrPtr = bswap<uint32_t>(bswap<uint32_t>(*ctrPtr) + numberOfBlocks); } return incrementedCounter; } CryptoBuffer GenerateXRandomBytes(size_t lengthBytes, bool ctrMode) { std::shared_ptr<SecureRandomBytes> rng = CreateSecureRandomBytesImplementation(); CryptoBuffer bytes(lengthBytes); size_t lengthToGenerate = ctrMode ? (3 * bytes.GetLength()) / 4 : bytes.GetLength(); rng->GetBytes(bytes.GetUnderlyingData(), lengthToGenerate); if(!*rng) { AWS_LOGSTREAM_FATAL(LOG_TAG, "Random Number generation failed. Abort all crypto operations."); assert(false); abort(); } return bytes; } void SymmetricCipher::Validate() { assert(m_key.GetLength() >= SYMMETRIC_KEY_LENGTH); assert(m_initializationVector.GetLength() == 0 || m_initializationVector.GetLength() >= MIN_IV_LENGTH); if(m_key.GetLength() < SYMMETRIC_KEY_LENGTH || (m_initializationVector.GetLength() > 0 && m_initializationVector.GetLength() < MIN_IV_LENGTH)) { m_failure = true; AWS_LOGSTREAM_FATAL(LOG_TAG, "Invalid state for symmetric cipher, key length is " << m_key.GetLength() << " iv length is " << m_initializationVector.GetLength()); } } /** * Generate random number per 4 bytes and use each byte for the byte in the iv */ CryptoBuffer SymmetricCipher::GenerateIV(size_t ivLengthBytes, bool ctrMode) { CryptoBuffer iv(GenerateXRandomBytes(ivLengthBytes, ctrMode)); if(iv.GetLength() == 0) { AWS_LOGSTREAM_ERROR(LOG_TAG, "Unable to generate iv of length " << ivLengthBytes); return iv; } if(ctrMode) { //init the counter size_t length = iv.GetLength(); //[ nonce 1/4] [ iv 1/2 ] [ ctr 1/4 ] size_t ctrStart = (length / 2) + (length / 4); for(; ctrStart < iv.GetLength() - 1; ++ ctrStart) { iv[ctrStart] = 0; } iv[length - 1] = 1; } return iv; } CryptoBuffer SymmetricCipher::GenerateKey(size_t keyLengthBytes) { CryptoBuffer&& key = GenerateXRandomBytes(keyLengthBytes, false); if(key.GetLength() == 0) { AWS_LOGSTREAM_ERROR(LOG_TAG, "Unable to generate key of length " << keyLengthBytes); } return key; } } } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/app_runtime/app_runtime_api.h" #include "base/json/json_writer.h" #include "base/string16.h" #include "base/strings/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/extensions/event_router.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/extension.h" #include "content/public/browser/web_contents.h" #include "googleurl/src/gurl.h" namespace extensions { namespace { const char kOnLaunchedEvent[] = "app.runtime.onLaunched"; const char kOnRestartedEvent[] = "app.runtime.onRestarted"; void DispatchOnLaunchedEventImpl(const std::string& extension_id, scoped_ptr<base::ListValue> args, Profile* profile) { extensions::ExtensionSystem* system = extensions::ExtensionSystem::Get(profile); // Special case: normally, extensions add their own lazy event listeners. // However, since the extension might have just been enabled, it hasn't had a // chance to register for events. So we register on its behalf. If the // extension does not actually have a listener, the event will just be // ignored (but an app that doesn't listen for the onLaunched event doesn't // make sense anyway). system->event_router()->AddLazyEventListener(kOnLaunchedEvent, extension_id); scoped_ptr<Event> event(new Event(kOnLaunchedEvent, args.Pass())); event->restrict_to_profile = profile; system->event_router()->DispatchEventToExtension(extension_id, event.Pass()); system->event_router()->RemoveLazyEventListener(kOnLaunchedEvent, extension_id); } } // anonymous namespace // static. void AppEventRouter::DispatchOnLaunchedEvent( Profile* profile, const Extension* extension) { scoped_ptr<ListValue> arguments(new ListValue()); DispatchOnLaunchedEventImpl(extension->id(), arguments.Pass(), profile); } // static. void AppEventRouter::DispatchOnRestartedEvent( Profile* profile, const Extension* extension) { scoped_ptr<ListValue> arguments(new ListValue()); scoped_ptr<Event> event(new Event(kOnRestartedEvent, arguments.Pass())); event->restrict_to_profile = profile; extensions::ExtensionSystem::Get(profile)->event_router()-> DispatchEventToExtension(extension->id(), event.Pass()); } // static. void AppEventRouter::DispatchOnLaunchedEventWithFileEntry( Profile* profile, const Extension* extension, const std::string& handler_id, const std::string& mime_type, const std::string& file_system_id, const std::string& base_name) { scoped_ptr<ListValue> args(new ListValue()); DictionaryValue* launch_data = new DictionaryValue(); launch_data->SetString("id", handler_id); DictionaryValue* launch_item = new DictionaryValue; launch_item->SetString("fileSystemId", file_system_id); launch_item->SetString("baseName", base_name); launch_item->SetString("mimeType", mime_type); ListValue* items = new ListValue; items->Append(launch_item); launch_data->Set("items", items); args->Append(launch_data); DispatchOnLaunchedEventImpl(extension->id(), args.Pass(), profile); } } // namespace extensions
// Copyright Daniel Wallin 2009. 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 LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP # define LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP # include <boost/type_traits/is_polymorphic.hpp> # include <luabind/detail/inheritance.hpp> # include <luabind/detail/object_rep.hpp> namespace luabind { namespace detail { template <class T> std::pair<class_id, void*> get_dynamic_class_aux( lua_State* L, T const* p, mpl::true_) { lua_pushliteral(L, "__luabind_class_id_map"); lua_rawget(L, LUA_REGISTRYINDEX); class_id_map& class_ids = *static_cast<class_id_map*>( lua_touserdata(L, -1)); lua_pop(L, 1); return std::make_pair( class_ids.get_local(typeid(*p)) , dynamic_cast<void*>(const_cast<T*>(p)) ); } template <class T> std::pair<class_id, void*> get_dynamic_class_aux( lua_State*, T const* p, mpl::false_) { return std::make_pair(registered_class<T>::id, (void*)p); } template <class T> std::pair<class_id, void*> get_dynamic_class(lua_State* L, T* p) { return get_dynamic_class_aux(L, p, boost::is_polymorphic<T>()); } template <class T> class_rep* get_pointee_class(class_map const& classes, T*) { return classes.get(registered_class<T>::id); } template <class P> class_rep* get_pointee_class(lua_State* L, P const& p, class_id dynamic_id) { lua_pushliteral(L, "__luabind_class_map"); lua_rawget(L, LUA_REGISTRYINDEX); class_map const& classes = *static_cast<class_map*>( lua_touserdata(L, -1)); lua_pop(L, 1); class_rep* cls = classes.get(dynamic_id); if (!cls) cls = get_pointee_class(classes, get_pointer(p)); return cls; } // Create an appropriate instance holder for the given pointer like object. template <class P> void make_instance(lua_State* L, P p) { std::pair<class_id, void*> dynamic = get_dynamic_class(L, get_pointer(p)); class_rep* cls = get_pointee_class(L, p, dynamic.first); if (!cls) { //throw std::runtime_error("Trying to use unregistered class"); } object_rep* instance = push_new_instance(L, cls); typedef pointer_holder<P> holder_type; void* storage = instance->allocate(sizeof(holder_type)); try { new (storage) holder_type(p, dynamic.first, dynamic.second); } catch (...) { instance->deallocate(storage); lua_pop(L, 1); throw; } instance->set_instance(static_cast<holder_type*>(storage)); } }} // namespace luabind::detail #endif // LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP
/* Copyright (c) 2009-2013, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef CORE_TIMER_DECL_HPP #define CORE_TIMER_DECL_HPP namespace elem { class Timer { public: Timer(); Timer( const std::string name ); void Start(); void Stop(); void Reset(); const std::string Name() const; double Time() const; private: bool running_; double lastStartTime_; double time_; const std::string name_; }; } // namespace elem #endif // ifndef CORE_TIMER_DECL_HPP
// Copyright (c) 2015 Matthias Noack (ma.noack.pr@gmail.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) #include "common.hpp" // NOTE: real_vec_t maps to a C++ equivalent to OpenCLs vector types // NOTE: this manually vectorised kernel uses the same arithmetic with another // indexing scheme and without the SIMD-loop void commutator_omp_manual_aosoa_constants_direct_perm_unrollhints(real_vec_t const* restrict sigma_in, real_vec_t* restrict sigma_out, real_t const* restrict hamiltonian, const int num, const int dim, const real_t hbar, const real_t dt) { // OpenCL work-groups are mapped to threads #pragma omp parallel for #pragma novector // NOTE: we do not want any implicit vectorisation in this kernel for (int global_id = 0; global_id < (num / VEC_LENGTH); ++global_id) { // original OpenCL kernel begins here #define package_id (global_id * DIM * DIM * 2) #define sigma_real(i, j) (package_id + 2*(DIM * (i) + (j))) #define sigma_imag(i, j) (package_id + 2*(DIM * (i) + (j)) + 1) #define ham_real(i, j) ((i) * DIM + (j)) #define ham_imag(i, j) (DIM * DIM + (i) * DIM + (j)) #pragma novector for (int i = 0; i < DIM; ++i) { // manually permuted j and k (makes no difference in OpenCL, but does with OpenMP) #pragma novector #pragma nounroll_and_jam for (int k = 0; k < DIM; ++k) { #pragma novector #pragma unroll(DIM) for (int j = 0; j < DIM; ++j) { // reordered operands (there is no scalar-times-vector operator in micvec.h) sigma_out[sigma_imag(i,j)] -= sigma_in[sigma_real(k,j)] * hamiltonian[ham_real(i,k)]; sigma_out[sigma_imag(i,j)] += sigma_in[sigma_real(i,k)] * hamiltonian[ham_real(k,j)]; sigma_out[sigma_imag(i,j)] += sigma_in[sigma_imag(k,j)] * hamiltonian[ham_imag(i,k)]; sigma_out[sigma_imag(i,j)] -= sigma_in[sigma_imag(i,k)] * hamiltonian[ham_imag(k,j)]; sigma_out[sigma_real(i,j)] += sigma_in[sigma_imag(k,j)] * hamiltonian[ham_real(i,k)]; sigma_out[sigma_real(i,j)] -= sigma_in[sigma_real(i,k)] * hamiltonian[ham_imag(k,j)]; sigma_out[sigma_real(i,j)] += sigma_in[sigma_real(k,j)] * hamiltonian[ham_imag(i,k)]; sigma_out[sigma_real(i,j)] -= sigma_in[sigma_imag(i,k)] * hamiltonian[ham_real(k,j)]; } } } } // for global }
/* * Fledge OSI Soft OMF interface to PI Server. * * Copyright (c) 2018 Dianomic Systems * * Released under the Apache 2.0 Licence * * Author: Massimiliano Pinto */ #include <utility> #include <iostream> #include <string> #include <cstring> #include <omf.h> #include <OMFHint.h> #include <logger.h> #include <zlib.h> #include <rapidjson/document.h> #include "rapidjson/error/en.h" #include "string_utils.h" #include <plugin_api.h> #include <string_utils.h> #include <datapoint.h> #include <thread> using namespace std; using namespace rapidjson; static bool isTypeSupported(DatapointValue& dataPoint); // 1 enable performance tracking #define INSTRUMENT 0 #define AFHierarchySeparator '/' #define AF_TYPES_SUFFIX "-type" // Handling escapes for AF Hierarchies #define AFH_SLASH "/" #define AFH_SLASH_ESCAPE "@/" #define AFH_SLASH_ESCAPE_TMP "##" #define AFH_ESCAPE_SEQ "@@" #define AFH_ESCAPE_CHAR "@" // Structures to generate and assign the 1st level of AF hierarchy if the end point is PI Web API const char *AF_HIERARCHY_1LEVEL_TYPE = QUOTE( [ { "id": "_placeholder_typeid_", "version": "1.0.0.0", "type": "object", "classification": "static", "properties": { "Name": { "type": "string", "isname": true }, "AssetId": { "type": "string", "isindex": true } } } ] ); const char *AF_HIERARCHY_1LEVEL_STATIC = QUOTE( [ { "typeid": "_placeholder_typeid_", "values": [ { "Name": "_placeholder_Name_", "AssetId": "_placeholder_AssetId_" } ] } ] ); const char *AF_HIERARCHY_LEVEL_LINK = QUOTE( [ { "typeid": "__Link", "values": [ { "source": { "typeid": "_placeholder_src_type_", "index": "_placeholder_src_idx_" }, "target": { "typeid": "_placeholder_tgt_type_", "index": "_placeholder_tgt_idx_" } } ] } ] ); const char *AF_HIERARCHY_1LEVEL_LINK = QUOTE( { "source": { "typeid": "_placeholder_src_type_", "index": "_placeholder_src_idx_" }, "target": { "typeid": "_placeholder_tgt_type_", "index": "_placeholder_tgt_idx_" } } ); /** * OMFData constructor */ OMFData::OMFData(const Reading& reading, const long typeId, const OMF_ENDPOINT PIServerEndpoint,const string& AFHierarchyPrefix, OMFHints *hints) { string outData; string measurementId; measurementId = to_string(typeId) + "measurement_" + reading.getAssetName(); // Add the 1st level of AFHierarchy as a prefix to the name in case of PI Web API if (PIServerEndpoint == ENDPOINT_PIWEB_API) { measurementId = AFHierarchyPrefix + "_" + measurementId; } // Apply any TagName hints to modify the containerid if (hints) { const std::vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTagNameHint)) { measurementId = (*it)->getHint(); Logger::getLogger()->info("Using OMF TagName hint: %s", measurementId.c_str()); } if (typeid(**it) == typeid(OMFTagHint)) { measurementId = (*it)->getHint(); Logger::getLogger()->info("Using OMF TagName hint: %s", measurementId.c_str()); } } } // Convert reading data into the OMF JSON string outData.append("{\"containerid\": \"" + measurementId); outData.append("\", \"values\": [{"); // Get reading data const vector<Datapoint*> data = reading.getReadingData(); unsigned long skipDatapoints = 0; /** * This loop creates: * "dataName": {"type": "dataType"}, */ for (vector<Datapoint*>::const_iterator it = data.begin(); it != data.end(); ++it) { string dpName = (*it)->getName(); if (dpName.compare(OMF_HINT) == 0) { // Don't send the OMF Hint to the PI Server continue; } if (!isTypeSupported((*it)->getData())) { skipDatapoints++;; continue; } else { // Add datapoint Name outData.append("\"" + dpName + "\": " + (*it)->getData().toString()); outData.append(", "); } } // Append Z to getAssetDateTime(FMT_STANDARD) outData.append("\"Time\": \"" + reading.getAssetDateUserTime(Reading::FMT_STANDARD) + "Z" + "\""); outData.append("}]}"); // Append all, some or no datapoins if (!skipDatapoints || skipDatapoints < data.size()) { m_value.append(outData); } } /** * Return the (reference) JSON data in m_value */ const string& OMFData::OMFdataVal() const { return m_value; } /** * OMF constructor */ OMF::OMF(HttpSender& sender, const string& path, const long id, const string& token) : m_path(path), m_typeId(id), m_producerToken(token), m_sender(sender) { m_lastError = false; m_changeTypeId = false; m_OMFDataTypes = NULL; } /** * OMF constructor with per asset data types */ OMF::OMF(HttpSender& sender, const string& path, map<string, OMFDataTypes>& types, const string& token) : m_path(path), m_OMFDataTypes(&types), m_producerToken(token), m_sender(sender) { // Get starting type-id sequence or set the default value auto it = (*m_OMFDataTypes).find(FAKE_ASSET_KEY); m_typeId = (it != (*m_OMFDataTypes).end()) ? (*it).second.typeId : TYPE_ID_DEFAULT; m_lastError = false; m_changeTypeId = false; } // Destructor OMF::~OMF() { } /** * Compress a string * * @param str Input STL string that is to be compressed * @param compressionlevel zlib/gzip Compression level * @return str gzip compressed binary data */ std::string OMF::compress_string(const std::string& str, int compressionlevel) { const int windowBits = 15; const int GZIP_ENCODING = 16; z_stream zs; // z_stream is zlib's control structure memset(&zs, 0, sizeof(zs)); if (deflateInit2(&zs, compressionlevel, Z_DEFLATED, windowBits | GZIP_ENCODING, 8, Z_DEFAULT_STRATEGY) != Z_OK) throw(std::runtime_error("deflateInit failed while compressing.")); zs.next_in = (Bytef*)str.data(); zs.avail_in = str.size(); // set the z_stream's input int ret; char outbuffer[32768]; std::string outstring; // retrieve the compressed bytes blockwise do { zs.next_out = reinterpret_cast<Bytef*>(outbuffer); zs.avail_out = sizeof(outbuffer); ret = deflate(&zs, Z_FINISH); if (outstring.size() < zs.total_out) { // append the block to the output string outstring.append(outbuffer, zs.total_out - outstring.size()); } } while (ret == Z_OK); deflateEnd(&zs); if (ret != Z_STREAM_END) { // an error occurred that was not EOF std::ostringstream oss; oss << "Exception during zlib compression: (" << ret << ") " << zs.msg; throw(std::runtime_error(oss.str())); } return outstring; } /** * Sends all the data type messages for a Reading data row * * @param row The current Reading data row * @return True is all data types have been sent (HTTP 2xx OK) * False when first error occurs. */ bool OMF::sendDataTypes(const Reading& row, OMFHints *hints) { int res; m_changeTypeId = false; // Create header for Type vector<pair<string, string>> resType = OMF::createMessageHeader("Type"); // Create data for Type message string typeData = OMF::createTypeData(row, hints); // If Datatyope in Reading row is not supported, just return true if (typeData.empty()) { return true; } else { // TODO: ADD LOG } // Build an HTTPS POST with 'resType' headers // and 'typeData' JSON payload // Then get HTTPS POST ret code and return 0 to client on error try { res = m_sender.sendRequest("POST", m_path, resType, typeData); if ( ! (res >= 200 && res <= 299) ) { Logger::getLogger()->error("Sending JSON dataType message 'Type' " "- error: HTTP code |%d| - HostPort |%s| - path |%s| - OMF message |%s|", res, m_sender.getHostPort().c_str(), m_path.c_str(), typeData.c_str() ); return false; } } // Exception raised for HTTP 400 Bad Request catch (const BadRequest& e) { if (OMF::isDataTypeError(e.what())) { // Data type error: force type-id change m_changeTypeId = true; } Logger::getLogger()->warn("Sending JSON dataType message 'Type', " "not blocking issue: |%s| - message |%s| - HostPort |%s| - path |%s| - OMF message |%s|", (m_changeTypeId ? "Data Type " : "" ), e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeData.c_str() ); return false; } catch (const std::exception& e) { Logger::getLogger()->error("Sending JSON dataType message 'Type' " "- generic error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeData.c_str() ); return false; } // Create header for Container vector<pair<string, string>> resContainer = OMF::createMessageHeader("Container"); // Create data for Container message string typeContainer = OMF::createContainerData(row, hints); // Build an HTTPS POST with 'resContainer' headers // and 'typeContainer' JSON payload // Then get HTTPS POST ret code and return 0 to client on error try { res = m_sender.sendRequest("POST", m_path, resContainer, typeContainer); if ( ! (res >= 200 && res <= 299) ) { Logger::getLogger()->error("Sending JSON dataType message 'Container' " "- error: HTTP code |%d| - HostPort |%s| - path |%s| - OMF message |%s|", res, m_sender.getHostPort().c_str(), m_path.c_str(), typeContainer.c_str() ); return false; } } // Exception raised fof HTTP 400 Bad Request catch (const BadRequest& e) { if (OMF::isDataTypeError(e.what())) { // Data type error: force type-id change m_changeTypeId = true; } Logger::getLogger()->warn("Sending JSON dataType message 'Container' " "not blocking issue: |%s| - message |%s| - HostPort |%s| - path |%s| - OMF message |%s|", (m_changeTypeId ? "Data Type " : "" ), e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeContainer.c_str() ); return false; } catch (const std::exception& e) { Logger::getLogger()->error("Sending JSON dataType message 'Container' " "- generic error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeContainer.c_str() ); return false; } // Create header for Static data vector<pair<string, string>> resStaticData = OMF::createMessageHeader("Data"); // Create data for Static Data message string typeStaticData = OMF::createStaticData(row); // Build an HTTPS POST with 'resStaticData' headers // and 'typeStaticData' JSON payload // Then get HTTPS POST ret code and return 0 to client on error try { res = m_sender.sendRequest("POST", m_path, resStaticData, typeStaticData); if ( ! (res >= 200 && res <= 299) ) { Logger::getLogger()->error("Sending JSON dataType message 'StaticData' " "- error: HTTP code |%d| - HostPort |%s| - path |%s| - OMF message |%s|", res, m_sender.getHostPort().c_str(), m_path.c_str(), typeStaticData.c_str() ); return false; } } // Exception raised fof HTTP 400 Bad Request catch (const BadRequest& e) { if (OMF::isDataTypeError(e.what())) { // Data type error: force type-id change m_changeTypeId = true; } Logger::getLogger()->warn("Sending JSON dataType message 'StaticData'" "not blocking issue: |%s| - message |%s| - HostPort |%s| - path |%s| - OMF message |%s|", (m_changeTypeId ? "Data Type " : "" ), e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeStaticData.c_str() ); return false; } catch (const std::exception& e) { Logger::getLogger()->error("Sending JSON dataType message 'StaticData'" "- generic error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeStaticData.c_str() ); return false; } // Create header for Link data vector<pair<string, string>> resLinkData = OMF::createMessageHeader("Data"); string assetName = row.getAssetName(); string AFHierarchyLevel; string prefix; string objectPrefix; auto rule = m_AssetNamePrefix.find(assetName); if (rule != m_AssetNamePrefix.end()) { auto itemArray = rule->second; objectPrefix = ""; for(auto &item : itemArray) { AFHierarchyLevel = std::get<0>(item); prefix =std::get<1>(item); if (objectPrefix.empty()) { objectPrefix = prefix; } // Create data for Static Data message string typeLinkData = OMF::createLinkData(row, AFHierarchyLevel, prefix, objectPrefix, hints); // Build an HTTPS POST with 'resLinkData' headers // and 'typeLinkData' JSON payload // Then get HTTPS POST ret code and return 0 to client on error try { res = m_sender.sendRequest("POST", m_path, resLinkData, typeLinkData); if ( ! (res >= 200 && res <= 299) ) { Logger::getLogger()->error("Sending JSON dataType message 'Data' (lynk) " "- error: HTTP code |%d| - HostPort |%s| - path |%s| - OMF message |%s|", res, m_sender.getHostPort().c_str(), m_path.c_str(), typeLinkData.c_str() ); return false; } } // Exception raised fof HTTP 400 Bad Request catch (const BadRequest& e) { if (OMF::isDataTypeError(e.what())) { // Data type error: force type-id change m_changeTypeId = true; } Logger::getLogger()->warn("Sending JSON dataType message 'Data' (lynk) " "not blocking issue: |%s| - message |%s| - HostPort |%s| - path |%s| - OMF message |%s|", (m_changeTypeId ? "Data Type " : "" ), e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeLinkData.c_str() ); return false; } catch (const std::exception& e) { Logger::getLogger()->error("Sending JSON dataType message 'Data' (lynk) " "- generic error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), typeLinkData.c_str() ); return false; } } } else { Logger::getLogger()->error("AF hiererachy is not defined for the asset Name |%s|",assetName.c_str()); } // All data types sent: success return true; } /** * AFHierarchy - send an OMF message * * @param msgType message type : Type, Data * @param jsonData OMF message to send */ bool OMF::AFHierarchySendMessage(const string& msgType, string& jsonData) { bool success = true; int res = 0; string errorMessage; vector<pair<string, string>> resType = OMF::createMessageHeader(msgType); try { res = m_sender.sendRequest("POST", m_path, resType, jsonData); if ( ! (res >= 200 && res <= 299) ) { success = false; } } catch (const BadRequest& ex) { success = false; errorMessage = ex.what(); } catch (const std::exception& ex) { success = false; errorMessage = ex.what(); } if (! success) { if (res != 0) Logger::getLogger()->error("Sending JSON Asset Framework hierarchy, " "- HTTP code |%d| - error message |%s| - HostPort |%s| - path |%s| message type |%s| - OMF message |%s|", res, errorMessage.c_str(), m_sender.getHostPort().c_str(), m_path.c_str(), msgType.c_str(), jsonData.c_str() ); else Logger::getLogger()->error("Sending JSON Asset Framework hierarchy, " "- error message |%s| - HostPort |%s| - path |%s| message type |%s| - OMF message |%s|", errorMessage.c_str(), m_sender.getHostPort().c_str(), m_path.c_str(), msgType.c_str(), jsonData.c_str() ); } return success; } /** * AFHierarchy - handles OMF types definition * */ bool OMF::sendAFHierarchyTypes(const std::string AFHierarchyLevel, const std::string prefix) { bool success; string jsonData; string tmpStr; jsonData = ""; tmpStr = AF_HIERARCHY_1LEVEL_TYPE; StringReplace(tmpStr, "_placeholder_typeid_", prefix + "_" + AFHierarchyLevel + "_typeid"); jsonData.append(tmpStr); success = AFHierarchySendMessage("Type", jsonData); return success; } /** * AFHierarchy - handles OMF static data * */ bool OMF::sendAFHierarchyStatic(const std::string AFHierarchyLevel, const std::string prefix) { bool success; string jsonData; string tmpStr; jsonData = ""; tmpStr = AF_HIERARCHY_1LEVEL_STATIC; StringReplace(tmpStr, "_placeholder_typeid_" , prefix + "_" + AFHierarchyLevel + "_typeid"); StringReplace(tmpStr, "_placeholder_Name_" , AFHierarchyLevel); StringReplace(tmpStr, "_placeholder_AssetId_" , prefix + "_" + AFHierarchyLevel); jsonData.append(tmpStr); success = AFHierarchySendMessage("Data", jsonData); return success; } /** * AFHierarchy - creates the link between 2 elements in the AF hierarchy * */ bool OMF::sendAFHierarchyLink(std::string parent, std::string child, std::string prefixIdParent, std::string prefixId) { bool success; string jsonData; string tmpStr; jsonData = ""; tmpStr = AF_HIERARCHY_LEVEL_LINK; StringReplace(tmpStr, "_placeholder_src_type_", prefixIdParent + "_" + parent + "_typeid"); StringReplace(tmpStr, "_placeholder_src_idx_", prefixIdParent + "_" + parent ); StringReplace(tmpStr, "_placeholder_tgt_type_", prefixId + "_" + child + "_typeid"); StringReplace(tmpStr, "_placeholder_tgt_idx_", prefixId + "_" + child); jsonData.append(tmpStr); success = AFHierarchySendMessage("Data", jsonData); return success; } /** * Creates the hierarchies tree in the AF as defined in the configuration item DefaultAFLocation * each level is separated by / * the implementation is available for PI Web API only * The hierarchy is created/recreated if an OMF type message is sent* * */ bool OMF::handleAFHierarchySystemWide() { bool success = true; std::string level; std::string previousLevel; string parentPath; parentPath = evaluateParentPath(m_DefaultAFLocation, AFHierarchySeparator); success = sendAFHierarchyLevels(parentPath, m_DefaultAFLocation, m_AFHierarchyLevel); return success; } /** * Creates all the AF hierarchies levels as requested by the input parameter * * @param AFHierarchy Hierarchies levels to be created as relative or absolute path * @param out true if succeded */ bool OMF::sendAFHierarchy(string AFHierarchy) { bool success = true; string path; string dummy; string parentPath; if (AFHierarchy.at(0) == '/') { // Absolute path path = AFHierarchy; parentPath = evaluateParentPath(path, AFHierarchySeparator); } else { // relative path path = m_DefaultAFLocation + "/" + AFHierarchy; parentPath = m_DefaultAFLocation; } success = sendAFHierarchyLevels(parentPath, path, dummy); return success; } /** * Creates all the AF hierarchies level as requested by the input parameter * * @param path Full path of hierarchies to create * @param out last level of the created hierarchy */ bool OMF::sendAFHierarchyLevels(string parentPath, string path, std::string &lastLevel) { bool success; std::string level; std::string previousLevel; StringReplaceAll(path, AFH_ESCAPE_SEQ ,AFH_ESCAPE_CHAR); StringReplaceAll(path, AFH_SLASH_ESCAPE ,AFH_SLASH_ESCAPE_TMP); if (path.find(AFHierarchySeparator) == string::npos) { string prefixId; // only 1 single level of hierarchy StringReplaceAll(path, AFH_SLASH_ESCAPE_TMP ,AFH_SLASH); prefixId = generateUniquePrefixId(path); success = sendAFHierarchyTypes(path, prefixId); if (success) { success = sendAFHierarchyStatic(path,prefixId); } lastLevel = path; } else { string pathFixed; string parentPathFixed; string prefixId; string prefixIdParent; string previousLevelPath; string AFHierarchyLevel; string levelPath; pathFixed = StringSlashFix(path); std::stringstream pathStream(pathFixed); // multiple hierarchy levels while (std::getline(pathStream, level, AFHierarchySeparator)) { StringReplaceAll(level, AFH_SLASH_ESCAPE_TMP ,AFH_SLASH); levelPath = previousLevelPath + AFHierarchySeparator + level; levelPath = StringSlashFix(levelPath); prefixId = generateUniquePrefixId(levelPath); success = sendAFHierarchyTypes(level, prefixId); if (success) { success = sendAFHierarchyStatic(level, prefixId); } // Creates the link between the AF level if (previousLevel != "") { parentPathFixed = StringSlashFix(previousLevelPath); prefixIdParent = generateUniquePrefixId(parentPathFixed); sendAFHierarchyLink(previousLevel, level, prefixIdParent, prefixId); } previousLevelPath = levelPath; previousLevel = level; } lastLevel = level; } return success; } /** * Creates all the hierarcies defined in the Names map rules * * @param out true if succeded */ bool OMF::handleAFHierarchiesNamesMap() { bool success = true; string asset_name; string hierarchy; for (auto itr = m_NamesRules.begin(); itr != m_NamesRules.end(); ++itr) { asset_name = itr->first.c_str(); hierarchy = itr->second.c_str(); Logger::getLogger()->debug("handleAFHierarchiesNamesMap - asset_name :%s: hierarchy :%s:", asset_name.c_str(), hierarchy.c_str()); success = sendAFHierarchy(hierarchy.c_str()); } return success; } /** * Handle the AF hierarchies for the Metadata Map * * @param out true if succeded */ bool OMF::handleAFHierarchiesMetadataMap() { bool success = true; Document JSon; string name; string value; ParseResult ok = JSon.Parse(m_AFMap.c_str()); if (!ok) { Logger::getLogger()->error("MetadataMap - Invalid Asset Framework Map, error :%s:", GetParseError_En(JSon.GetParseError())); return false; } if (!JSon.HasMember("metadata")) { Logger::getLogger()->debug("MetadataMap - metadata section not defined"); return true; } Value &JsonMetadata = JSon["metadata"]; // --- Handling exit section if (JsonMetadata.HasMember("exist")) { Value &JSonExist = JsonMetadata["exist"]; for (Value::ConstMemberIterator itr = JSonExist.MemberBegin(); itr != JSonExist.MemberEnd(); ++itr) { name = itr->name.GetString(); value = itr->value.GetString(); Logger::getLogger()->debug("AFHierarchiesMetadataMap - exist name :%s: value :%s:", name.c_str(), value.c_str()); sendAFHierarchy(value.c_str()); } } // --- Handling nonexist section if (JsonMetadata.HasMember("nonexist")) { Value &JSonNonExist = JsonMetadata["nonexist"]; for (Value::ConstMemberIterator itr = JSonNonExist.MemberBegin(); itr != JSonNonExist.MemberEnd(); ++itr) { name = itr->name.GetString(); value = itr->value.GetString(); Logger::getLogger()->debug("AFHierarchiesMetadataMap - nonexist name :%s: value :%s:", name.c_str(), value.c_str()); sendAFHierarchy(value.c_str()); } } // --- Handling equal section if (JsonMetadata.HasMember("equal")) { Value &JSonEqual = JsonMetadata["equal"]; for (Value::ConstMemberIterator itr = JSonEqual.MemberBegin(); itr != JSonEqual.MemberEnd(); ++itr) { name = itr->name.GetString(); for (Value::ConstMemberIterator itrL2 = itr->value.MemberBegin(); itrL2 != itr->value.MemberEnd(); ++itrL2) { name = itrL2->name.GetString(); value = itrL2->value.GetString(); Logger::getLogger()->debug("AFHierarchiesMetadataMap - equal name :%s: value :%s:", name.c_str(), value.c_str()); sendAFHierarchy(value.c_str()); } } } // --- Handling notequal section if (JsonMetadata.HasMember("notequal")) { Value &JSonNotEqual = JsonMetadata["notequal"]; for (Value::ConstMemberIterator itr = JSonNotEqual.MemberBegin(); itr != JSonNotEqual.MemberEnd(); ++itr) { name = itr->name.GetString(); for (Value::ConstMemberIterator itrL2 = itr->value.MemberBegin(); itrL2 != itr->value.MemberEnd(); ++itrL2) { name = itrL2->name.GetString(); value = itrL2->value.GetString(); Logger::getLogger()->debug("AFHierarchiesMetadataMap - notequal name :%s: value :%s:", name.c_str(), value.c_str()); sendAFHierarchy(value.c_str()); } } } return success; } /** * Handle the creation of AF hierarchies * * @param out true if succeded */ bool OMF::handleAFHierarchy() { bool success = true; if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { success = handleAFHierarchySystemWide(); if (success and ! m_AFMapEmptyNames) { success = handleAFHierarchiesNamesMap(); } if (success and ! m_AFMapEmptyMetadata) { success = handleAFHierarchiesMetadataMap(); } } return success; } /** * Sets the value of the prefix used for the objects naming * */ void OMF::setAFHierarchy() { std::string level; std::string AFLocation; AFLocation = m_DefaultAFLocation; if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { // Implementation onfly for PI Web API StringReplaceAll(AFLocation, AFH_ESCAPE_SEQ, AFH_ESCAPE_CHAR); StringReplaceAll(AFLocation, AFH_SLASH_ESCAPE ,AFH_SLASH_ESCAPE_TMP); std::stringstream defaultAFLocation(AFLocation); if (AFLocation.find(AFHierarchySeparator) == string::npos) { // only 1 single level of hierarchy m_AFHierarchyLevel = AFLocation; } else { // multiple hierarchy levels while (std::getline(defaultAFLocation, level, AFHierarchySeparator)) { ; } m_AFHierarchyLevel = level; } StringReplaceAll(m_AFHierarchyLevel, AFH_SLASH_ESCAPE_TMP ,AFH_SLASH); } } /** * Send all the readings to the PI Server * * @param readings A vector of readings data pointers * @param skipSendDataTypes Send datatypes only once (default is true) * @return != on success, 0 otherwise * xxx */ uint32_t OMF::sendToServer(const vector<Reading *>& readings, bool compression, bool skipSentDataTypes) { bool AFHierarchySent = false; bool sendDataTypes; string keyComplete; string AFHierarchyPrefix; string AFHierarchyLevel; #if INSTRUMENT ostringstream threadId; threadId << std::this_thread::get_id(); struct timeval start, t1, t2, t3, t4, t5; #endif #if INSTRUMENT gettimeofday(&start, NULL); #endif // Create a superset of all found datapoints for each assetName // the superset[assetName] is then passed to routines which handle // creation of OMF data types OMF::setMapObjectTypes(readings, m_SuperSetDataPoints); #if INSTRUMENT gettimeofday(&t1, NULL); #endif /* * Iterate over readings: * - Send/cache Types * - transform a reading to OMF format * - add OMF data to new vector */ // Used for logging string json_not_compressed; bool pendingSeparator = false; ostringstream jsonData; jsonData << "["; // Fetch Reading* data for (vector<Reading *>::const_iterator elem = readings.begin(); elem != readings.end(); ++elem) { Reading *reading = *elem; // Fetch and parse any OMFHint for this reading Datapoint *hintsdp = reading->getDatapoint("OMFHint"); OMFHints *hints = NULL; bool usingTagHint = false; long typeId = 0; if (hintsdp) { hints = new OMFHints(hintsdp->getData().toString()); const vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTagHint)) { Logger::getLogger()->info("Using OMF Tag hint: %s", (*it)->getHint().c_str()); keyComplete.append("_" + (*it)->getHint()); usingTagHint = true; break; } } } // Add into JSON string the OMF transformed Reading data string assetName(reading->getAssetName()); evaluateAFHierarchyRules(assetName, *reading); if (m_PIServerEndpoint == ENDPOINT_CR || m_PIServerEndpoint == ENDPOINT_OCS || m_PIServerEndpoint == ENDPOINT_EDS ) { keyComplete = assetName; } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { retrieveAFHierarchyPrefixAssetName(assetName, AFHierarchyPrefix, AFHierarchyLevel); keyComplete = AFHierarchyPrefix + "_" + assetName; } if (! usingTagHint) { /* * Check the OMFHints, if there are any, to see if we have a * type name that should be used for this asset. * We will still create the tyope, but the name will be fixed * as the value of this hint. */ bool usingTypeNameHint = false; if (hints) { const vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTypeNameHint)) { Logger::getLogger()->info("Using OMF TypeName hint: %s", (*it)->getHint().c_str()); keyComplete.append("_" + (*it)->getHint()); usingTypeNameHint = true; break; } } } if (! AFHierarchySent) { setAFHierarchy(); } sendDataTypes = (m_lastError == false && skipSentDataTypes == true) ? // Send if not already sent !OMF::getCreatedTypes(keyComplete, *reading, hints) : // Always send types true; Reading* datatypeStructure = NULL; if (sendDataTypes && !usingTypeNameHint) { // Increment type-id of assetName in in memory cache OMF::incrementAssetTypeIdOnly(keyComplete); // Remove data and keep type-id OMF::clearCreatedTypes(keyComplete); // Get the supersetDataPoints for current assetName auto it = m_SuperSetDataPoints.find(assetName); if (it != m_SuperSetDataPoints.end()) { datatypeStructure = (*it).second; } } // The AF hierarchy is created/recreated if an OMF type message is sent // it sends the hierarchy once if (sendDataTypes and ! AFHierarchySent) { handleAFHierarchy(); AFHierarchySent = true; } if (usingTypeNameHint) { if (sendDataTypes && !OMF::handleDataTypes(keyComplete, *reading, skipSentDataTypes, hints)) { // Failure m_lastError = true; return 0; } } else { // Check first we have supersetDataPoints for the current reading if ((sendDataTypes && datatypeStructure == NULL) || // Handle the data types of the current reading (sendDataTypes && // Send data type !OMF::handleDataTypes(keyComplete, *datatypeStructure, skipSentDataTypes, hints) && // Data type not sent: (!m_changeTypeId || // Increment type-id and re-send data types !OMF::handleTypeErrors(keyComplete, *datatypeStructure, hints)))) { // Remove all assets supersetDataPoints OMF::unsetMapObjectTypes(m_SuperSetDataPoints); // Failure m_lastError = true; return 0; } } // Create the key for dataTypes sending once typeId = OMF::getAssetTypeId(assetName); } string outData = OMFData(*reading, typeId, m_PIServerEndpoint, AFHierarchyPrefix, hints ).OMFdataVal(); if (!outData.empty()) { jsonData << (pendingSeparator ? ", " : "") << outData; pendingSeparator = true; } if (hints) { delete hints; } } #if INSTRUMENT gettimeofday(&t2, NULL); #endif // Remove all assets supersetDataPoints OMF::unsetMapObjectTypes(m_SuperSetDataPoints); jsonData << "]"; string json = jsonData.str(); json_not_compressed = json; if (compression) { json = compress_string(json); } #if INSTRUMENT gettimeofday(&t3, NULL); #endif /** * Types messages sent, now transform each reading to OMF format. * * After formatting the new vector of data can be sent * with one message only */ // Create header for Readings data vector<pair<string, string>> readingData = OMF::createMessageHeader("Data"); if (compression) readingData.push_back(pair<string, string>("compression", "gzip")); // Build an HTTPS POST with 'readingData headers // and 'allReadings' JSON payload // Then get HTTPS POST ret code and return 0 to client on error try { int res = m_sender.sendRequest("POST", m_path, readingData, json); if ( ! (res >= 200 && res <= 299) ) { Logger::getLogger()->error("Sending JSON readings, " "- error: HTTP code |%d| - HostPort |%s| - path |%s| - OMF message |%s|", res, m_sender.getHostPort().c_str(), m_path.c_str(), json_not_compressed.c_str() ); m_lastError = true; return 0; } // Reset error indicator m_lastError = false; #if INSTRUMENT gettimeofday(&t4, NULL); #endif #if INSTRUMENT struct timeval tm; double timeT1, timeT2, timeT3, timeT4, timeT5; timersub(&t1, &start, &tm); timeT1 = tm.tv_sec + ((double)tm.tv_usec / 1000000); timersub(&t2, &t1, &tm); timeT2 = tm.tv_sec + ((double)tm.tv_usec / 1000000); timersub(&t3, &t2, &tm); timeT3 = tm.tv_sec + ((double)tm.tv_usec / 1000000); timersub(&t4, &t3, &tm); timeT4 = tm.tv_sec + ((double)tm.tv_usec / 1000000); timersub(&t5, &t4, &tm); timeT5 = tm.tv_sec + ((double)tm.tv_usec / 1000000); Logger::getLogger()->debug("Timing seconds - thread :%s: - superSet :%6.3f: - Loop :%6.3f: - compress :%6.3f: - send data :%6.3f: - msg size |%d| - msg size compressed |%d| ", threadId.str().c_str(), timeT1, timeT2, timeT3, timeT4, json_not_compressed.length(), json.length() ); #endif // Return number of sent readings to the caller return readings.size(); } // Exception raised fof HTTP 400 Bad Request catch (const BadRequest& e) { if (OMF::isDataTypeError(e.what())) { // Some assets have invalid or redefined data type // NOTE: // // 1- We consider this a NOT blocking issue. // 2- Type-id is not incremented // 3- Data Types cache is cleared: next sendData call // will send data types again. Logger::getLogger()->warn("Sending JSON readings, " "not blocking issue: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), json_not_compressed.c_str() ); // Extract assetName from error message string assetName; if (m_PIServerEndpoint == ENDPOINT_CR) { assetName = OMF::getAssetNameFromError(e.what()); } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { // Currently not implemented/supported as PI WEB API does not // report in the error message the asset causing the problem assetName = ""; } if (assetName.empty()) { Logger::getLogger()->warn("Sending JSON readings, " "not blocking issue: assetName not found in error message, " " no types redefinition"); } else { // Remove data and keep type-id OMF::clearCreatedTypes(assetName); Logger::getLogger()->warn("Sending JSON readings, " "not blocking issue: 'type-id' of assetName '%s' " "has been set to %d " "- HostPort |%s| - path |%s| - OMF message |%s|", assetName.c_str(), OMF::getAssetTypeId(assetName), m_sender.getHostPort().c_str(), m_path.c_str(), json_not_compressed.c_str()); } // Reset error indicator m_lastError = false; // It returns size instead of 0 as the rows in the block should be skipped in case of an error // as it is considered a not blocking ones. return readings.size(); } else { Logger::getLogger()->error("Sending JSON data error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), json_not_compressed.c_str()); } // Failure m_lastError = true; return 0; } catch (const std::exception& e) { Logger::getLogger()->error("Sending JSON data error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), json_not_compressed.c_str() ); // Failure m_lastError = true; return 0; } } /** * Send all the readings to the PI Server * * @param readings A vector of readings data * @param skipSendDataTypes Send datatypes only once (default is true) * @return != on success, 0 otherwise */ uint32_t OMF::sendToServer(const vector<Reading>& readings, bool skipSentDataTypes) { /* * Iterate over readings: * - Send/cache Types * - transform a reading to OMF format * - add OMF data to new vector */ ostringstream jsonData; jsonData << "["; // Fetch Reading data for (vector<Reading>::const_iterator elem = readings.begin(); elem != readings.end(); ++elem) { bool sendDataTypes; OMFHints *hints = NULL; Datapoint *hintsdp = elem->getDatapoint(OMF_HINT); if (hintsdp) { hints = new OMFHints(hintsdp->getData().toString()); } // Create the key for dataTypes sending once long typeId = OMF::getAssetTypeId((*elem).getAssetName()); string key((*elem).getAssetName()); sendDataTypes = (m_lastError == false && skipSentDataTypes == true) ? // Send if not already sent !OMF::getCreatedTypes(key, (*elem), hints) : // Always send types true; // Handle the data types of the current reading if (sendDataTypes && !OMF::handleDataTypes(key, *elem, skipSentDataTypes, hints)) { // Failure m_lastError = true; return 0; } // Add into JSON string the OMF transformed Reading data jsonData << OMFData(*elem, typeId, m_PIServerEndpoint, m_AFHierarchyLevel, hints).OMFdataVal() << (elem < (readings.end() -1 ) ? ", " : ""); } jsonData << "]"; // Build headers for Readings data vector<pair<string, string>> readingData = OMF::createMessageHeader("Data"); // Build an HTTPS POST with 'readingData headers and 'allReadings' JSON payload // Then get HTTPS POST ret code and return 0 to client on error try { int res = m_sender.sendRequest("POST", m_path, readingData, jsonData.str()); if ( ! (res >= 200 && res <= 299) ) { Logger::getLogger()->error("Sending JSON readings data " "- error: HTTP code |%d| - HostPort |%s| - path |%s| - OMF message |%s|", res, m_sender.getHostPort().c_str(), m_path.c_str(), jsonData.str().c_str() ); m_lastError = true; return 0; } } catch (const std::exception& e) { Logger::getLogger()->error("Sending JSON readings data " "- generic error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), jsonData.str().c_str() ); return false; } m_lastError = false; // Return number of sen t readings to the caller return readings.size(); } /** * Send a single reading to the PI Server * * @param reading A reading to send * @return != on success, 0 otherwise */ uint32_t OMF::sendToServer(const Reading& reading, bool skipSentDataTypes) { return OMF::sendToServer(&reading, skipSentDataTypes); } /** * Send a single reading pointer to the PI Server * * @param reading A reading pointer to send * @return != on success, 0 otherwise */ uint32_t OMF::sendToServer(const Reading* reading, bool skipSentDataTypes) { ostringstream jsonData; jsonData << "["; string key(reading->getAssetName()); Datapoint *hintsdp = reading->getDatapoint("OMFHint"); OMFHints *hints = NULL; if (hintsdp) { hints = new OMFHints(hintsdp->getData().toString()); } if (!OMF::handleDataTypes(key, *reading, skipSentDataTypes, hints)) { // Failure return 0; } long typeId = OMF::getAssetTypeId((*reading).getAssetName()); // Add into JSON string the OMF transformed Reading data jsonData << OMFData(*reading, typeId, m_PIServerEndpoint, m_AFHierarchyLevel, hints).OMFdataVal(); jsonData << "]"; // Build headers for Readings data vector<pair<string, string>> readingData = OMF::createMessageHeader("Data"); // Build an HTTPS POST with 'readingData headers and 'allReadings' JSON payload // Then get HTTPS POST ret code and return 0 to client on error try { int res = m_sender.sendRequest("POST", m_path, readingData, jsonData.str()); if ( ! (res >= 200 && res <= 299) ) { Logger::getLogger()->error("Sending JSON readings data " "- error: HTTP code |%d| - HostPort |%s| - path |%s| - OMF message |%s|", res, m_sender.getHostPort().c_str(), m_path.c_str(), jsonData.str().c_str() ); return 0; } } catch (const std::exception& e) { Logger::getLogger()->error("Sending JSON readings data " "- generic error: |%s| - HostPort |%s| - path |%s| - OMF message |%s|", e.what(), m_sender.getHostPort().c_str(), m_path.c_str(), jsonData.str().c_str() ); return false; } // Return number of sent readings to the caller return 1; } /** * Creates a vector of HTTP header to be sent to Server * * @param type The message type ('Type', 'Container', 'Data') * @return A vector of HTTP Header string pairs */ const vector<pair<string, string>> OMF::createMessageHeader(const std::string& type) const { vector<pair<string, string>> res; res.push_back(pair<string, string>("messagetype", type)); res.push_back(pair<string, string>("producertoken", m_producerToken)); res.push_back(pair<string, string>("omfversion", "1.0")); res.push_back(pair<string, string>("messageformat", "JSON")); res.push_back(pair<string, string>("action", "create")); return res; } /** * Creates the Type message for data type definition * * @param reading A reading data * @return Type JSON message as string */ const std::string OMF::createTypeData(const Reading& reading, OMFHints *hints) { // Build the Type data message (JSON Array) // Add the Static data part string tData="["; tData.append("{ \"type\": \"object\", \"properties\": { "); for (auto it = m_staticData->cbegin(); it != m_staticData->cend(); ++it) { tData.append("\""); tData.append(it->first.c_str()); tData.append("\": {\"type\": \"string\"},"); } // Connector relay / ODS / EDS if (m_PIServerEndpoint == ENDPOINT_CR || m_PIServerEndpoint == ENDPOINT_OCS || m_PIServerEndpoint == ENDPOINT_EDS ) { tData.append("\"Name\": { \"type\": \"string\", \"isindex\": true } }, " "\"classification\": \"static\", \"id\": \""); } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { tData.append("\"Name\": { \"type\": \"string\", \"isname\": true }, "); tData.append("\"AssetId\": { \"type\": \"string\", \"isindex\": true } "); tData.append(" }, \"classification\": \"static\", \"id\": \""); } // Add type_id + '_' + asset_name + '_typename_sensor' OMF::setAssetTypeTag(reading.getAssetName(), "typename_sensor", tData); tData.append("\" }, { \"type\": \"object\", \"properties\": {"); // Add the Dynamic data part /* We add for each reading * the DataPoint name & type * type is 'integer' for INT * 'number' for FLOAT * 'string' for STRING */ bool ret = true; const vector<Datapoint*> data = reading.getReadingData(); /** * This loop creates: * "dataName": {"type": "dataType"}, */ for (vector<Datapoint*>::const_iterator it = data.begin(); it != data.end(); ++it) { string dpName = (*it)->getName(); if (dpName.compare(OMF_HINT) == 0) { // We never include OMF hints in the data we send to PI continue; } string omfType; if (!isTypeSupported( (*it)->getData())) { omfType = OMF_TYPE_UNSUPPORTED; } else { omfType = omfTypes[((*it)->getData()).getType()]; } string format = OMF::getFormatType(omfType); if (hints && (omfType == OMF_TYPE_FLOAT || omfType == OMF_TYPE_INTEGER)) { const vector<OMFHint *> omfHints = hints->getHints(dpName); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFNumberHint)) { format = (*it)->getHint(); break; } if (typeid(**it) == typeid(OMFIntegerHint)) { omfType = OMF_TYPE_INTEGER; format = (*it)->getHint(); break; } } } if (format.compare(OMF_TYPE_UNSUPPORTED) == 0) { //TO DO: ADD LOG ret = false; continue; } // Add datapoint Name tData.append("\"" + dpName + "\""); tData.append(": {\"type\": \""); // Add datapoint Type tData.append(omfType); // Applies a format if it is defined if (! format.empty() ) { tData.append("\", \"format\": \""); tData.append(format); } tData.append("\"}, "); } // Add time field tData.append("\"Time\": {\"type\": \"string\", \"isindex\": true, \"format\": \"date-time\"}}, " "\"classification\": \"dynamic\", \"id\": \""); bool typeNameSet = false; if (hints) { const vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTypeNameHint)) { Logger::getLogger()->info("Using OMF TypeName hint: %s", (*it)->getHint().c_str()); tData.append((*it)->getHint()); typeNameSet = true; break; } } } if (!typeNameSet) { // Add type_id + '_' + asset_name + '__typename_measurement' OMF::setAssetTypeTag(reading.getAssetName(), "typename_measurement", tData); } tData.append("\" }]"); // Check we have to return empty data or not if (!ret && data.size() == 1) { // TODO: ADD LOGGING return string(""); } else { // Return JSON string return tData; } } /** * Creates the Container message for data type definition * * @param reading A reading data * @return Type JSON message as string */ const std::string OMF::createContainerData(const Reading& reading, OMFHints *hints) { string AFHierarchyPrefix; string AFHierarchyLevel; string assetName = reading.getAssetName(); string measurementId; // Build the Container data (JSON Array) string cData = "[{\"typeid\": \""; string typeName = ""; if (hints) { const std::vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTypeNameHint)) { typeName = (*it)->getHint(); Logger::getLogger()->info("Using OMF TypeName hint: %s", typeName.c_str()); } } } if (typeName.length()) { cData.append(typeName); } else { // Add type_id + '_' + asset_name + '__typename_measurement' OMF::setAssetTypeTag(assetName, "typename_measurement", cData); } measurementId = to_string(OMF::getAssetTypeId(assetName)) + "measurement_" + assetName; // Add the 1st level of AFHierarchy as a prefix to the name in case of PI Web API if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { retrieveAFHierarchyPrefixAssetName(assetName, AFHierarchyPrefix, AFHierarchyLevel); measurementId = AFHierarchyPrefix + "_" + measurementId; } // Apply any TagName hints to modify the containerid if (hints) { const std::vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTagNameHint)) { measurementId = (*it)->getHint(); Logger::getLogger()->info("Using OMF TagName hint: %s", measurementId.c_str()); break; } } } cData.append("\", \"id\": \"" + measurementId); cData.append("\"}]"); // Return JSON string return cData; } /** * Creates the Static Data message for data type definition * * Note: type is 'Data' * * @param reading A reading data * @return Type JSON message as string */ const std::string OMF::createStaticData(const Reading& reading) { string assetName; // Build the Static data (JSON Array) string sData = "["; sData.append("{\"typeid\": \""); assetName = reading.getAssetName(); long typeId = getAssetTypeId(assetName); // Add type_id + '_' + asset_name + '_typename_sensor' OMF::setAssetTypeTag(assetName, "typename_sensor", sData); sData.append("\", \"values\": [{"); for (auto it = m_staticData->cbegin(); it != m_staticData->cend(); ++it) { sData.append("\""); sData.append(it->first.c_str()); sData.append("\": \""); sData.append(it->second.c_str()); sData.append("\", "); } sData.append(" \"Name\": \""); // Add asset_name // Connector relay / ODS / EDS if (m_PIServerEndpoint == ENDPOINT_CR) { sData.append(assetName); } else if (m_PIServerEndpoint == ENDPOINT_OCS || m_PIServerEndpoint == ENDPOINT_EDS) { sData.append(assetName); } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { string AFHierarchyPrefix; string AFHierarchyLevel; retrieveAFHierarchyPrefixAssetName(assetName, AFHierarchyPrefix, AFHierarchyLevel); sData.append(assetName + AF_TYPES_SUFFIX + to_string(typeId)); sData.append("\", \"AssetId\": \""); sData.append("A_" + AFHierarchyPrefix + "_" + assetName + AF_TYPES_SUFFIX + to_string(typeId)); } sData.append("\"}]}]"); // Return JSON string return sData; } /** * Creates the Link Data message for data type definition * * Note: type is 'Data' * * @param reading A reading data * @return Type JSON message as string */ std::string OMF::createLinkData(const Reading& reading, std::string& AFHierarchyLevel, std::string& AFHierarchyPrefix, std::string& objectPrefix, OMFHints *hints) { string targetTypeId; string measurementId; string assetName = reading.getAssetName(); // Build the Link data (JSON Array) long typeId = getAssetTypeId(assetName); string lData = "[{\"typeid\": \"__Link\", \"values\": ["; // Handles the structure for the Connector Relay // not supported by PI Web API // Connector relay / ODS / EDS if (m_PIServerEndpoint == ENDPOINT_CR || m_PIServerEndpoint == ENDPOINT_OCS || m_PIServerEndpoint == ENDPOINT_EDS ) { lData.append("{\"source\": {\"typeid\": \""); // Add type_id + '_' + asset_name + '__typename_sensor' OMF::setAssetTypeTag(assetName, "typename_sensor", lData); lData.append("\", \"index\": \"_ROOT\"},"); lData.append("\"target\": {\"typeid\": \""); // Add type_id + '_' + asset_name + '__typename_sensor' OMF::setAssetTypeTag(assetName, "typename_sensor", lData); lData.append("\", \"index\": \""); // Add asset_name lData.append(assetName); lData.append("\"}},"); } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { // Link the asset to the 1st level of AF hierarchy if the end point is PI Web API string tmpStr = AF_HIERARCHY_1LEVEL_LINK; OMF::setAssetTypeTag(assetName, "typename_sensor", targetTypeId); StringReplace(tmpStr, "_placeholder_src_type_", AFHierarchyPrefix + "_" + AFHierarchyLevel + "_typeid"); StringReplace(tmpStr, "_placeholder_src_idx_", AFHierarchyPrefix + "_" + AFHierarchyLevel ); StringReplace(tmpStr, "_placeholder_tgt_type_", targetTypeId); StringReplace(tmpStr, "_placeholder_tgt_idx_", "A_" + objectPrefix + "_" + assetName + AF_TYPES_SUFFIX + to_string(typeId)); lData.append(tmpStr); lData.append(","); } lData.append("{\"source\": {\"typeid\": \""); // Add type_id + '_' + asset_name + '__typename_sensor' OMF::setAssetTypeTag(assetName, "typename_sensor", lData); lData.append("\", \"index\": \""); if (m_PIServerEndpoint == ENDPOINT_CR) { // Add asset_name lData.append(assetName); } else if (m_PIServerEndpoint == ENDPOINT_OCS || m_PIServerEndpoint == ENDPOINT_EDS) { // Add asset_name lData.append(assetName); } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { lData.append("A_" + objectPrefix + "_" + assetName + AF_TYPES_SUFFIX + to_string(typeId)); } measurementId = to_string(OMF::getAssetTypeId(assetName)) + "measurement_" + assetName; // Add the 1st level of AFHierarchy as a prefix to the name in case of PI Web API if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { measurementId = objectPrefix + "_" + measurementId; } // Apply any TagName hints to modify the containerid if (hints) { const std::vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTagNameHint)) { measurementId = (*it)->getHint(); Logger::getLogger()->info("Using OMF TagName hint: %s", measurementId.c_str()); break; } } } lData.append("\"}, \"target\": {\"containerid\": \"" + measurementId); lData.append("\"}}]}]"); // Return JSON string return lData; } /** * Calculate the prefix to be used for AF objects and the last level of the hiererachies * from a given AF path * * @param path Path to evaluate * @param out/prefix Calculated prefix * @param out/AFHierarchyLevel last level of the hiererachies evaluated form the path */ void OMF::generateAFHierarchyPrefixLevel(string& path, string& prefix, string& AFHierarchyLevel) { string pathFixed; AFHierarchyLevel = extractLastLevel(path, AFHierarchySeparator); pathFixed = StringSlashFix(path); prefix = generateUniquePrefixId(pathFixed); } /** * Retrieve from the map the prefix and the hiererachy name from a given assetname * * @param path assetName to evaluate * @param out/prefix Calculated prefix * @param out/AFHierarchyLevel hiererachy name */ void OMF::retrieveAFHierarchyPrefixAssetName(const string& assetName, string& prefix, string& AFHierarchyLevel) { string path; // Metadata Rules - Exist auto rule = m_AssetNamePrefix.find(assetName); if (rule != m_AssetNamePrefix.end()) { AFHierarchyLevel = std::get<0>(rule->second[0]); prefix =std::get<1>(rule->second[0]); } } /** * Evaluated the maps containing the Named and Metadata rules to fill the map m_AssetNamePrefix * containing for each assetname the related prefix and hierarchy name * * @param path assetName to evaluate * @param reading reading row from which will be extracted the datapoint for the evaluation of the rules */ void OMF::evaluateAFHierarchyRules(const string& assetName, const Reading& reading) { bool ruleMatched = false; bool ruleMatchedNames = false; // names rules - Check if there are any rules defined or not if (! m_AFMapEmptyNames) { if (m_NamesRules.size() > 0) { string path; string prefix; string AFHierarchyLevel; auto it = m_NamesRules.find(assetName); if (it != m_NamesRules.end()) { path = it->second; if (path.at(0) != '/') { // relative path path = m_DefaultAFLocation + "/" + path; } generateAFHierarchyPrefixLevel(path, prefix, AFHierarchyLevel); ruleMatched = true; ruleMatchedNames = true; auto item = make_pair(AFHierarchyLevel, prefix); m_AssetNamePrefix[assetName].push_back(item); } } } // Meta rules - Check if there are any rules defined or not if (! m_AFMapEmptyMetadata && ! ruleMatchedNames) { auto values = reading.getReadingData(); // Metadata Rules - Exist if (m_MetadataRulesExist.size() > 0) { string path; string propertyName; string prefix; string AFHierarchyLevel; for (auto it = values.begin(); it != values.end(); it++) { propertyName = (*it)->getName(); auto rule = m_MetadataRulesExist.find(propertyName); if (rule != m_MetadataRulesExist.end()) { path = rule->second;; if (path.at(0) != '/') { // relative path path = m_DefaultAFLocation + "/" + path; } generateAFHierarchyPrefixLevel(path, prefix, AFHierarchyLevel); ruleMatched = true; auto item = make_pair(AFHierarchyLevel, prefix); m_AssetNamePrefix[assetName].push_back(item); } } } // Metadata Rules - NonExist if (m_MetadataRulesNonExist.size() > 0) { string path; string propertyName; string prefix; string AFHierarchyLevel; bool found; string rule; for (auto it = m_MetadataRulesNonExist.begin(); it != m_MetadataRulesNonExist.end(); it++) { found = false; rule = it->first; path = it->second; for (auto itL2 = values.begin(); found == false && itL2 != values.end(); itL2++) { propertyName = (*itL2)->getName(); if (propertyName.compare(rule) == 0) { found = true; } } if (!found) { if (path.at(0) != '/') { // relative path path = m_DefaultAFLocation + "/" + path; } generateAFHierarchyPrefixLevel(path, prefix, AFHierarchyLevel); ruleMatched = true; auto item = make_pair(AFHierarchyLevel, prefix); m_AssetNamePrefix[assetName].push_back(item); } } } // Metadata Rules - equal if (m_MetadataRulesEqual.size() > 0) { string path; string propertyName; string prefix; string AFHierarchyLevel; bool found; string rule; for (auto it = m_MetadataRulesEqual.begin(); it != m_MetadataRulesEqual.end(); it++) { found = false; rule = it->first; for (auto itL2 = values.begin(); found == false && itL2 != values.end(); itL2++) { propertyName = (*itL2)->getName(); DatapointValue data = (*itL2)->getData(); string dataValue = data.toString(); if (propertyName.compare(rule) == 0) { for (auto itL3 = it->second.begin(); found == false && itL3 != it->second.end(); itL3++) { auto value = itL3->first; path = itL3->second; if (value.compare(dataValue) == 0) { found = true; } } } } if (found) { if (path.at(0) != '/') { // relative path path = m_DefaultAFLocation + "/" + path; } generateAFHierarchyPrefixLevel(path, prefix, AFHierarchyLevel); ruleMatched = true; auto item = make_pair(AFHierarchyLevel, prefix); m_AssetNamePrefix[assetName].push_back(item); } } } // Metadata Rules - Not equal if (m_MetadataRulesNotEqual.size() > 0) { string path; string propertyName; string prefix; string AFHierarchyLevel; string rule; bool NotEqual; for (auto it = m_MetadataRulesNotEqual.begin(); it != m_MetadataRulesNotEqual.end(); it++) { NotEqual = false; rule = it->first; for (auto itL2 = values.begin(); NotEqual == false && itL2 != values.end(); itL2++) { propertyName = (*itL2)->getName(); if (propertyName.compare(rule) == 0) { DatapointValue data = (*itL2)->getData(); string dataValue = data.toString(); StringReplaceAll(dataValue, "\"", ""); for (auto itL3 = it->second.begin(); NotEqual == false && itL3 != it->second.end(); itL3++) { auto value = itL3->first; path = itL3->second; if (value.compare(dataValue) != 0) { NotEqual = true; } } } } if (NotEqual) { if (path.at(0) != '/') { // relative path path = m_DefaultAFLocation + "/" + path; } generateAFHierarchyPrefixLevel(path, prefix, AFHierarchyLevel); ruleMatched = true; auto item = make_pair(AFHierarchyLevel, prefix); m_AssetNamePrefix[assetName].push_back(item); } } } } // If no rules matched se the AF default location if (!ruleMatched) { string prefix; string AFHierarchyLevel; generateAFHierarchyPrefixLevel(m_DefaultAFLocation, prefix, AFHierarchyLevel); auto item = make_pair(AFHierarchyLevel, prefix); m_AssetNamePrefix[assetName].push_back(item); } } /** * Set the tag ID_XYZ_typename_sensor|typename_measurement * * @param assetName The assetName * @param tagName The tagName to append * @param data The string to append result tag */ void OMF::setAssetTypeTag(const string& assetName, const string& tagName, string& data) { string AFHierarchyPrefix; string AFHierarchyLevel; string keyComplete; // Add the 1st level of AFHierarchy as a prefix to the name in case of PI Web API if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { retrieveAFHierarchyPrefixAssetName (assetName, AFHierarchyPrefix, AFHierarchyLevel); keyComplete = AFHierarchyPrefix + "_" + assetName; } else { keyComplete = assetName; } string AssetTypeTag = to_string(this->getAssetTypeId(assetName)) + "_" + assetName + "_" + tagName; // Add the 1st level of AFHierarchy as a prefix to the name in case of PI Web API if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { AssetTypeTag = "A_" + AFHierarchyPrefix + "_" + AFHierarchyLevel + "_" + AssetTypeTag; } // Add type-id + '_' + asset_name + '_' + tagName' data.append(AssetTypeTag); } /** * Handles the OMF data types for the current Reading row * DataTypoes are created and sent only once per assetName + typeId * if skipSending is true * * @param row The current Reading row with data * @param skipSending Send once or always the data types * @return True if data types have been sent or already sent. * False if the sending has failed. */ bool OMF::handleDataTypes(const string keyComplete, const Reading& row, bool skipSending, OMFHints *hints) { // Create the key for dataTypes sending once const string key(skipSending ? (keyComplete) : ""); // Check whether to create and send Data Types bool sendTypes = (skipSending == true) ? // Send if not already sent !OMF::getCreatedTypes(key, row, hints) : // Always send types true; // Handle the data types of the current reading if (sendTypes && !OMF::sendDataTypes(row, hints)) { // Failure return false; } // We have sent types, we might save this. if (skipSending && sendTypes) { // Save datatypes key OMF::setCreatedTypes(row, hints); } // Success return true; } /** * Get from m_formatTypes map the key (OMF type + OMF format) * * @param key The OMF type for which the format is requested * @return The defined OMF format for the requested type * */ std::string OMF::getFormatType(const string &key) const { string value; try { auto pos = m_formatTypes.find(key); value = pos->second; } catch (const std::exception& e) { Logger::getLogger()->error("Unable to find the OMF format for the type :" + key + ": - error: %s", e.what()); } return value; } /** * Add the key (OMF type + OMF format) into a map * * @param key The OMF type, key of the map * @param value The OMF format to set for the specific OMF type * */ void OMF::setFormatType(const string &key, string &value) { m_formatTypes[key] = value; } /** * Set which PIServer component should be used for the communication */ void OMF::setPIServerEndpoint(const OMF_ENDPOINT PIServerEndpoint) { m_PIServerEndpoint = PIServerEndpoint; } /** * Set the first level of hierarchy in Asset Framework in which the assets will be created, PI Web API only. */ void OMF::setDefaultAFLocation(const string &DefaultAFLocation) { m_DefaultAFLocation = StringSlashFix(DefaultAFLocation); } /** * Set the rules to address where assets should be placed in the AF hierarchy. * Decodes the JSON and assign to the structures the values about the Names rulues * */ bool OMF::HandleAFMapNames(Document& JSon) { bool success = true; string name; string value; Value &JsonNames = JSon["names"]; for (Value::ConstMemberIterator itr = JsonNames.MemberBegin(); itr != JsonNames.MemberEnd(); ++itr) { name = itr->name.GetString(); value = itr->value.GetString(); Logger::getLogger()->debug("HandleAFMapNames - Exist name :%s: value :%s:", name.c_str(), value.c_str()); auto newMapValue = make_pair(name,value); m_NamesRules.insert (newMapValue); m_AFMapEmptyNames = false; } return success; } /** * Set the rules to address where assets should be placed in the AF hierarchy. * Decodes the JSON and assign to the structures the values about the Metadata rulues * */ bool OMF::HandleAFMapMetedata(Document& JSon) { bool success = true; string name; string value; Value &JsonMetadata = JSon["metadata"]; // --- Handling Exist section if (JsonMetadata.HasMember("exist")) { Value &JSonExist = JsonMetadata["exist"]; for (Value::ConstMemberIterator itr = JSonExist.MemberBegin(); itr != JSonExist.MemberEnd(); ++itr) { name = itr->name.GetString(); value = itr->value.GetString(); Logger::getLogger()->debug("HandleAFMapMetedata - Exist name :%s: value :%s:", name.c_str(), value.c_str()); auto newMapValue = make_pair(name,value); m_MetadataRulesExist.insert (newMapValue); m_AFMapEmptyMetadata = false; } } // --- Handling Non Exist section if (JsonMetadata.HasMember("nonexist")) { Value &JSonNonExist = JsonMetadata["nonexist"]; for (Value::ConstMemberIterator itr = JSonNonExist.MemberBegin(); itr != JSonNonExist.MemberEnd(); ++itr) { name = itr->name.GetString(); value = itr->value.GetString(); Logger::getLogger()->debug("HandleAFMapMetedata - Non Exist name :%s: value :%s:", name.c_str(), value.c_str()); auto newMapValue = make_pair(name,value); m_MetadataRulesNonExist.insert (newMapValue); m_AFMapEmptyMetadata = false; } } // --- Handling Equal section if (JsonMetadata.HasMember("equal")) { string property; string value; string path; Value &JSonEqual = JsonMetadata["equal"]; for (Value::ConstMemberIterator itr = JSonEqual.MemberBegin(); itr != JSonEqual.MemberEnd(); ++itr) { property = itr->name.GetString(); for (Value::ConstMemberIterator itrL2 = itr->value.MemberBegin(); itrL2 != itr->value.MemberEnd(); ++itrL2) { value = itrL2->name.GetString(); path = itrL2->value.GetString(); Logger::getLogger()->debug("HandleAFMapMetedata - equal property :%s: name :%s: value :%s:", property.c_str() , value.c_str(), path.c_str()); auto item = make_pair(value,path); m_MetadataRulesEqual[property].push_back(item); m_AFMapEmptyMetadata = false; } } } // --- Handling Not Equal section if (JsonMetadata.HasMember("notequal")) { string property; string value; string path; Value &JSonEqual = JsonMetadata["notequal"]; for (Value::ConstMemberIterator itr = JSonEqual.MemberBegin(); itr != JSonEqual.MemberEnd(); ++itr) { property = itr->name.GetString(); for (Value::ConstMemberIterator itrL2 = itr->value.MemberBegin(); itrL2 != itr->value.MemberEnd(); ++itrL2) { value = itrL2->name.GetString(); path = itrL2->value.GetString(); Logger::getLogger()->debug("HandleAFMapMetedata - Not equal property :%s: name :%s: value :%s:", property.c_str() , value.c_str(), path.c_str()); auto item = make_pair(value,path); m_MetadataRulesNotEqual[property].push_back(item); m_AFMapEmptyMetadata = false; } } } return success; } /** * Set the Names and Metadata rules to address where assets should be placed in the AF hierarchy. * */ bool OMF::setAFMap(const string &AFMap) { bool success = true; Document JSon; m_AFMapEmptyNames = true; m_AFMapEmptyMetadata = true; m_AFMap = AFMap; ParseResult ok = JSon.Parse(m_AFMap.c_str()); if (!ok) { Logger::getLogger()->error("setAFMap - Invalid Asset Framework Map, error :%s:", GetParseError_En(JSon.GetParseError())); return false; } if (JSon.HasMember("names")) { HandleAFMapNames(JSon); } if (JSon.HasMember("metadata")) { HandleAFMapMetedata(JSon); } return success; } /** * Set the first level of hierarchy in Asset Framework in which the assets will be created, PI Web API only. */ void OMF::setPrefixAFAsset(const string &prefixAFAsset) { m_prefixAFAsset = prefixAFAsset; } /** * Generate an unique prefix for AF objects */ string OMF::generateUniquePrefixId(const string &path) { string prefix; std::size_t hierarchyHash = std::hash<std::string>{}(path); prefix = std::to_string(hierarchyHash); return prefix; } /** * Set the list of errors considered not blocking in the communication * with the PI Server */ void OMF::setNotBlockingErrors(std::vector<std::string>& notBlockingErrors) { m_notBlockingErrors = notBlockingErrors; } /** * Increment type-id */ void OMF::incrementTypeId() { ++m_typeId; } /** * Clear OMF types cache */ void OMF::clearCreatedTypes() { if (m_OMFDataTypes) { m_OMFDataTypes->clear(); } } /** * Check for invalid/redefinition data type error * * @param message Server reply message for data type creation * @return True for data type error, false otherwise */ bool OMF::isDataTypeError(const char* message) { if (message) { string serverReply(message); for(string &item : m_notBlockingErrors) { if (serverReply.find(item) != std::string::npos) { return true; } } } return false; } /** * Send again Data Types of current readind data * with a new type-id * * NOTE: the m_typeId member variable value is incremented. * * @param reading The current reading data * @return True if data types with new-id * have been sent, false otherwise. */ bool OMF::handleTypeErrors(const string& keyComplete, const Reading& reading, OMFHints *hints) { Logger::getLogger()->debug("handleTypeErrors keyComplete :%s:", keyComplete.c_str()); bool ret = true; string assetName = reading.getAssetName(); // Reset change type-id indicator m_changeTypeId = false; // Increment per asset type-id in memory cache: // Note: if key is not found the global type-id is incremented OMF::incrementAssetTypeId(keyComplete); // Clear per asset data (but keep the type-id) if key found // or remove all data otherwise auto it = m_OMFDataTypes->find(keyComplete); if (it != m_OMFDataTypes->end()) { // Clear teh OMF types cache per asset, keep type-id OMF::clearCreatedTypes(keyComplete); } else { // Remove all cached data, any asset OMF::clearCreatedTypes(); } // Force re-send data types with a new type-id if (!OMF::handleDataTypes(keyComplete, reading, false, hints)) { Logger::getLogger()->error("Failure re-sending JSON dataType messages " "with new type-id=%d for asset %s", OMF::getAssetTypeId(assetName), assetName.c_str()); // Failure m_lastError = true; ret = false; } return ret; } /** * Create a superset data map for each reading and found datapoints * * The output map is filled with a Reading object containing * all the datapoints found for each asset in the inoput reading set. * The datapoint have a fake value based on the datapoint type * * @param readings Current input readings data * @param dataSuperSet Map to store all datapoints for an assetname */ void OMF::setMapObjectTypes(const vector<Reading*>& readings, std::map<std::string, Reading*>& dataSuperSet) const { // Temporary map for [asset][datapoint] = type std::map<string, map<string, string>> readingAllDataPoints; // Fetch ALL Reading pointers in the input vector // and create a map of [assetName][datapoint1 .. datapointN] = type for (vector<Reading *>::const_iterator elem = readings.begin(); elem != readings.end(); ++elem) { // Get asset name string assetName = (**elem).getAssetName(); // Get all datapoints const vector<Datapoint*> data = (**elem).getReadingData(); // Iterate through datapoints for (vector<Datapoint*>::const_iterator it = data.begin(); it != data.end(); ++it) { string omfType; if (!isTypeSupported((*it)->getData())) { omfType = OMF_TYPE_UNSUPPORTED; } else { omfType = omfTypes[((*it)->getData()).getType()]; } string datapointName = (*it)->getName(); // if a OMF hint is applied the type may change { Reading *reading = *elem; // Fetch and parse any OMFHint for this reading Datapoint *hintsdp = reading->getDatapoint("OMFHint"); OMFHints *hints = NULL; if (hintsdp && (omfType == OMF_TYPE_FLOAT || omfType == OMF_TYPE_INTEGER)) { hints = new OMFHints(hintsdp->getData().toString()); const vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFIntegerHint)) { omfType = OMF_TYPE_INTEGER; break; } } } } auto itr = readingAllDataPoints.find(assetName); // Asset not found in the map if (itr == readingAllDataPoints.end()) { // Set type of current datapoint for ssetName readingAllDataPoints[assetName][datapointName] = omfType; } else { // Asset found auto dpItr = (*itr).second.find(datapointName); // Datapoint not found if (dpItr == (*itr).second.end()) { // Add datapointName/type to map with key assetName (*itr).second.emplace(datapointName, omfType); } else { if ((*dpItr).second.compare(omfType) != 0) { // Datapoint already set has changed type Logger::getLogger()->info("Datapoint '" + datapointName + \ "' in asset '" + assetName + \ "' has changed type from '" + (*dpItr).second + \ " to " + omfType); } // Update datapointName/type to map with key assetName // 1- remove element (*itr).second.erase(dpItr); // 2- Add new value readingAllDataPoints[assetName][datapointName] = omfType; } } } } // Loop now only the elements found in the per asset types map for (auto it = readingAllDataPoints.begin(); it != readingAllDataPoints.end(); ++it) { string assetName = (*it).first; vector<Datapoint *> values; // Set fake datapoints values for (auto dp = (*it).second.begin(); dp != (*it).second.end(); ++dp) { if ((*dp).second.compare(OMF_TYPE_FLOAT) == 0) { DatapointValue vDouble(0.1); values.push_back(new Datapoint((*dp).first, vDouble)); } else if ((*dp).second.compare(OMF_TYPE_INTEGER) == 0) { DatapointValue vInt((long)1); values.push_back(new Datapoint((*dp).first, vInt)); } else if ((*dp).second.compare(OMF_TYPE_STRING) == 0) { DatapointValue vString("v_str"); values.push_back(new Datapoint((*dp).first, vString)); } else if ((*dp).second.compare(OMF_TYPE_UNSUPPORTED) == 0) { std::vector<double> vData = {0}; DatapointValue vArray(vData); values.push_back(new Datapoint((*dp).first, vArray)); } } // Add the superset Reading data with fake values dataSuperSet.emplace(assetName, new Reading(assetName, values)); } } /** * Cleanup the mapped object types for input data * * @param dataSuperSet The mapped object to cleanup */ void OMF::unsetMapObjectTypes(std::map<std::string, Reading*>& dataSuperSet) const { // Remove all assets supersetDataPoints for (auto m = dataSuperSet.begin(); m != dataSuperSet.end(); ++m) { (*m).second->removeAllDatapoints(); delete (*m).second; } dataSuperSet.clear(); } /** * Extract assetName from error message * * Currently handled cases * (1) $datasource + "." + $id + "_" + $assetName + "_typename_measurement" + ... * (2) $id + "measurement_" + $assetName * * @param message OMF error message (JSON) * @return The found assetName if found, or empty string */ string OMF::getAssetNameFromError(const char* message) { string assetName; Document error; error.Parse(message); if (!error.HasParseError() && error.HasMember("source") && error["source"].IsString()) { string tmp = error["source"].GetString(); // (1) $datasource + "." + $id + "_" + $assetName + "_typename_measurement" + ... size_t found = tmp.find("_typename_measurement"); if (found != std::string::npos) { tmp = tmp.substr(0, found); found = tmp.find_first_of('.'); if (found != std::string::npos && found < tmp.length()) { tmp = tmp.substr(found + 1); found = tmp.find_first_of('_'); if (found != std::string::npos && found < tmp.length()) { // bug fixed //assetName = assetName.substr(found + 1 ); assetName = tmp.substr(found + 1 ); } } } else { // (2) $id + "measurement_" + $assetName found = tmp.find_first_of('_'); if (found != std::string::npos && found < tmp.length()) { assetName = tmp.substr(found + 1); } } } return assetName; } /** * Return the asset type-id * * @param assetName The asset name * @return The found type-id * or the generic value */ long OMF::getAssetTypeId(const string& assetName) { long typeId; string keyComplete; string AFHierarchyPrefix; string AFHierarchyLevel; // Connector relay / ODS / EDS if (m_PIServerEndpoint == ENDPOINT_CR || m_PIServerEndpoint == ENDPOINT_OCS || m_PIServerEndpoint == ENDPOINT_EDS ) { keyComplete = assetName; } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { retrieveAFHierarchyPrefixAssetName(assetName, AFHierarchyPrefix, AFHierarchyLevel); keyComplete = AFHierarchyPrefix + "_" + assetName; } if (!m_OMFDataTypes) { // Use current value of m_typeId typeId = m_typeId; } else { auto it = m_OMFDataTypes->find(keyComplete); if (it != m_OMFDataTypes->end()) { // Set the type-id of found element typeId = ((*it).second).typeId; } else { // Use current value of m_typeId typeId = m_typeId; } } return typeId; } /** * Increment the type-id for the given asset name * * If cached data pointer is NULL or asset name is not set * the global m_typeId is incremented. * * @param keyComplete The asset name * which type-id sequence * has to be incremented. */ void OMF::incrementAssetTypeId(const std::string& keyComplete) { long typeId; if (!m_OMFDataTypes) { // Increment current value of m_typeId OMF::incrementTypeId(); } else { auto it = m_OMFDataTypes->find(keyComplete); if (it != m_OMFDataTypes->end()) { // Increment value of found type-id ++((*it).second).typeId; } else { // Increment current value of m_typeId OMF::incrementTypeId(); } } } /** * Increment the type-id for the given asset name * * If cached data pointer is NULL or asset name is not set * the global m_typeId is incremented. * * @param keyComplete The asset name * which type-id sequence * has to be incremented. */ void OMF::incrementAssetTypeIdOnly(const std::string& keyComplete) { long typeId; if (m_OMFDataTypes) { auto it = m_OMFDataTypes->find(keyComplete); if (it != m_OMFDataTypes->end()) { // Increment value of found type-id ++((*it).second).typeId; } } } /** * Generate a 64 bit number containing a set of counts, * number of datapoint in an asset and the number of datapoint of each type we support. * */ unsigned long OMF::calcTypeShort(const Reading& row) { union t_typeCount { struct { unsigned char tTotal; unsigned char tFloat; unsigned char tString; unsigned char spare0; unsigned char spare1; unsigned char spare2; unsigned char spare3; unsigned char spare4; } cnt; unsigned long valueLong = 0; } typeCount; int type; const vector<Datapoint*> data = row.getReadingData(); for (vector<Datapoint*>::const_iterator it = data.begin(); (it != data.end() && isTypeSupported((*it)->getData())); ++it) { if (!isTypeSupported((*it)->getData())) { continue; } type = ((*it)->getData()).getType(); // Integer is handled as float in the OMF integration if (type == DatapointValue::dataTagType::T_INTEGER) { typeCount.cnt.tFloat++; } if (type == DatapointValue::dataTagType::T_FLOAT) { typeCount.cnt.tFloat++; } if (type == DatapointValue::dataTagType::T_STRING) { typeCount.cnt.tString++; } typeCount.cnt.tTotal++; } return typeCount.valueLong; } /** * Add the reading asset namekey into a map * That key is checked by getCreatedTypes in order * to send dataTypes only once * * @param row The reading data row * @return True, false if map pointer is NULL */ bool OMF::setCreatedTypes(const Reading& row, OMFHints *hints) { if (!m_OMFDataTypes) { return false; } string types; string keyComplete; // Connector relay / ODS / EDS if (m_PIServerEndpoint == ENDPOINT_CR || m_PIServerEndpoint == ENDPOINT_OCS || m_PIServerEndpoint == ENDPOINT_EDS ) { keyComplete = row.getAssetName(); } else if (m_PIServerEndpoint == ENDPOINT_PIWEB_API) { string assetName; string AFHierarchyPrefix; string AFHierarchyLevel; assetName = row.getAssetName(); retrieveAFHierarchyPrefixAssetName(assetName, AFHierarchyPrefix, AFHierarchyLevel); keyComplete = AFHierarchyPrefix + "_" + assetName; } // We may need to add the hint to the key if we have a TypeName key if (hints) { const vector<OMFHint *> omfHints = hints->getHints(); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFTypeNameHint)) { Logger::getLogger()->info("Using OMF TypeName hint: %s", (*it)->getHint().c_str()); keyComplete.append("_" + (*it)->getHint()); break; } } } long typeId = OMF::getAssetTypeId(keyComplete); const vector<Datapoint*> data = row.getReadingData(); types.append("{"); bool first = true; for (vector<Datapoint*>::const_iterator it = data.begin(); (it != data.end() && isTypeSupported((*it)->getData())); ++it) { string dpName = (*it)->getName(); if (dpName.compare(OMF_HINT) == 0) { // We never include OMF hints in the data we send to PI continue; } if (!first) { types.append(", "); } else { first = false; } string omfType; if (!isTypeSupported((*it)->getData())) { omfType = OMF_TYPE_UNSUPPORTED; continue; } else { omfType = omfTypes[((*it)->getData()).getType()]; } string format = OMF::getFormatType(omfType); if (hints && (omfType == OMF_TYPE_FLOAT || omfType == OMF_TYPE_INTEGER)) { const vector<OMFHint *> omfHints = hints->getHints(dpName); for (auto it = omfHints.cbegin(); it != omfHints.cend(); it++) { if (typeid(**it) == typeid(OMFNumberHint)) { format = (*it)->getHint(); break; } if (typeid(**it) == typeid(OMFIntegerHint)) { omfType = OMF_TYPE_INTEGER; format = (*it)->getHint(); break; } } } // Add datapoint Name types.append("\"" + dpName + "\""); types.append(": {\"type\": \""); // Add datapoint Type types.append(omfType); // Applies a format if it is defined if (!format.empty()) { types.append("\", \"format\": \""); types.append(format); } types.append("\"}"); } types.append("}"); if (m_OMFDataTypes->find(keyComplete) == m_OMFDataTypes->end()) { // New entry OMFDataTypes newData; // Start from default as we don't have anything in the cache newData.typeId = m_typeId; newData.types = types; (*m_OMFDataTypes)[keyComplete] = newData; } else { // Just update dataTypes and keep the typeId (*m_OMFDataTypes)[keyComplete].types = types; } (*m_OMFDataTypes)[keyComplete].typesShort = calcTypeShort(row); (*m_OMFDataTypes)[keyComplete].hintChkSum = hints ? hints->getChecksum() : 0; return true; } /** * Set a new value for global type-id * * new value is the maximum value of * type-id among all asset datatypes * or * the current value of m_typeId */ void OMF::setTypeId() { long maxId = m_typeId; for (auto it = m_OMFDataTypes->begin(); it != m_OMFDataTypes->end(); ++it) { if ((*it).second.typeId > maxId) { maxId = (*it).second.typeId; } } m_typeId = maxId; } /** * Clear OMF types cache for given asset name * but keep the type-id */ void OMF::clearCreatedTypes(const string& keyComplete) { if (m_OMFDataTypes) { auto it = m_OMFDataTypes->find(keyComplete); if (it != m_OMFDataTypes->end()) { // Just clear data types (*it).second.types = ""; } } } /** * Check the key (assetName) is set and not empty * in the per asset data types cache. * * @param keyComplete The data type key (assetName) from the Reading row * @return True is the key exists and data value is not empty: * this means the dataTypes were already sent * Found key with empty value means the data types * must be sent again with the new type-id. * Return false if the key is not found or found but empty. */ bool OMF::getCreatedTypes(const string& keyComplete, const Reading& row, OMFHints *hints) { unsigned long typesDefinition; bool ret = false; bool found = false; if (!m_OMFDataTypes) { ret = false; } else { auto it = m_OMFDataTypes->find(keyComplete); if (it != m_OMFDataTypes->end()) { OMFDataTypes& type = it->second; ret = ! type.types.empty(); if (ret) { // Considers empty also the case "{}" if (type.types.compare("{}") == 0) { ret = false; } else { // The Connector Relay recreates the type only when an error is received from the PI-Server // not in advance if (m_PIServerEndpoint != ENDPOINT_CR) { if (hints && type.hintChkSum != hints->getChecksum()) { ret = false; } else { // Check if the defined type has changed respect the superset type Reading* datatypeStructure = NULL; auto itSuper = m_SuperSetDataPoints.find(row.getAssetName()); if (itSuper != m_SuperSetDataPoints.end()) { datatypeStructure = (*itSuper).second; // Check if the types are changed typesDefinition = calcTypeShort(*datatypeStructure); if (type.typesShort != typesDefinition) { ret = false; } } } } } } } } return ret; } /** * Check whether input Datapoint type is supported by OMF class * * @param dataPoint Input data * @return True is fupported, false otherwise */ static bool isTypeSupported(DatapointValue& dataPoint) { if (dataPoint.getType() == DatapointValue::DatapointTag::T_FLOAT_ARRAY || dataPoint.getType() == DatapointValue::DatapointTag::T_DP_DICT || dataPoint.getType() == DatapointValue::DatapointTag::T_DP_LIST) { return false; } else { return true; } }
/* See LICENSE file in root folder */ #ifndef ___C3D_MeshLightPass_H___ #define ___C3D_MeshLightPass_H___ #include "LightPass.hpp" namespace castor3d { class MeshLightPass { public: static ShaderPtr getVertexShaderSource(); }; } #endif
#include <Python.h> #include <iostream> #include <ackward/logging/Initialize.hpp> #include <ackward/logging/Logger.hpp> #include <ackward/logging/LogRecord.hpp> #include <ackward/logging/Module.hpp> #include <ackward/logging/UserHandler.hpp> using namespace ackward::logging; struct ExampleHandlerImpl { void emit(const LogRecord& r) { std::wcout << L"[ExampleHandler] " << r.getMessage() << std::endl; } }; typedef UserHandler<ExampleHandlerImpl> ExampleHandler; int main(int, char**) { Py_Initialize(); ackward::logging::initialize(); Logger l = getLogger(L"my_logger"); ExampleHandler h; l.addHandler(h); l.error(L"They've shut down the main reactor. We'll be destroyed for sure."); return 0; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/file_manager/url_util.h" #include "base/json/json_writer.h" #include "base/values.h" #include "chrome/browser/chromeos/file_manager/app_id.h" #include "net/base/escape.h" namespace file_manager { namespace util { namespace { // Returns a file manager URL for the given |path|. GURL GetFileManagerUrl(const char* path) { return GURL(std::string("chrome-extension://") + kFileManagerAppId + path); } // Converts a numeric dialog type to a string. std::string GetDialogTypeAsString( ui::SelectFileDialog::Type dialog_type) { std::string type_str; switch (dialog_type) { case ui::SelectFileDialog::SELECT_NONE: type_str = "full-page"; break; case ui::SelectFileDialog::SELECT_FOLDER: type_str = "folder"; break; case ui::SelectFileDialog::SELECT_UPLOAD_FOLDER: type_str = "upload-folder"; break; case ui::SelectFileDialog::SELECT_SAVEAS_FILE: type_str = "saveas-file"; break; case ui::SelectFileDialog::SELECT_OPEN_FILE: type_str = "open-file"; break; case ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE: type_str = "open-multi-file"; break; default: NOTREACHED(); } return type_str; } } // namespace GURL GetFileManagerBaseUrl() { return GetFileManagerUrl("/"); } GURL GetFileManagerMainPageUrl() { return GetFileManagerUrl("/main.html"); } GURL GetFileManagerMainPageUrlWithParams( ui::SelectFileDialog::Type type, const string16& title, const base::FilePath& default_virtual_path, const ui::SelectFileDialog::FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension) { base::DictionaryValue arg_value; arg_value.SetString("type", GetDialogTypeAsString(type)); arg_value.SetString("title", title); arg_value.SetString("defaultPath", default_virtual_path.value()); arg_value.SetString("defaultExtension", default_extension); if (file_types) { base::ListValue* types_list = new base::ListValue(); for (size_t i = 0; i < file_types->extensions.size(); ++i) { base::ListValue* extensions_list = new base::ListValue(); for (size_t j = 0; j < file_types->extensions[i].size(); ++j) { extensions_list->Append( new base::StringValue(file_types->extensions[i][j])); } base::DictionaryValue* dict = new base::DictionaryValue(); dict->Set("extensions", extensions_list); if (i < file_types->extension_description_overrides.size()) { string16 desc = file_types->extension_description_overrides[i]; dict->SetString("description", desc); } // file_type_index is 1-based. 0 means no selection at all. dict->SetBoolean("selected", (static_cast<size_t>(file_type_index) == (i + 1))); types_list->Set(i, dict); } arg_value.Set("typeList", types_list); arg_value.SetBoolean("includeAllFiles", file_types->include_all_files); } // If the caller cannot handle Drive path, the file chooser dialog need to // return resolved local native paths to the selected files. arg_value.SetBoolean("shouldReturnLocalPath", !file_types || !file_types->support_drive); std::string json_args; base::JSONWriter::Write(&arg_value, &json_args); std::string url = GetFileManagerMainPageUrl().spec() + '?' + net::EscapeUrlEncodedData(json_args, false); // Space to %20 instead of +. return GURL(url); } GURL GetActionChoiceUrl(const base::FilePath& virtual_path, bool advanced_mode) { std::string url = GetFileManagerUrl("/action_choice.html").spec(); if (advanced_mode) url += "?advanced-mode"; url += "#/" + net::EscapeUrlEncodedData(virtual_path.value(), false); // Space to %20 instead of +. return GURL(url); } } // namespace util } // namespace file_manager
// // immer: immutable data structures for C++ // Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #pragma once #include <algorithm> #include <memory> #include <numeric> #include <utility> #include <immer/config.hpp> #include <immer/detail/rbts/position.hpp> #include <immer/detail/rbts/visitor.hpp> #include <immer/detail/util.hpp> #include <immer/heap/tags.hpp> namespace immer { namespace detail { namespace rbts { template <typename T> struct array_for_visitor : visitor_base<array_for_visitor<T>> { using this_t = array_for_visitor; template <typename PosT> static T* visit_inner(PosT&& pos, size_t idx) { return pos.descend(this_t{}, idx); } template <typename PosT> static T* visit_leaf(PosT&& pos, size_t) { return pos.node()->leaf(); } }; template <typename T> struct region_for_visitor : visitor_base<region_for_visitor<T>> { using this_t = region_for_visitor; using result_t = std::tuple<T*, size_t, size_t>; template <typename PosT> static result_t visit_inner(PosT&& pos, size_t idx) { return pos.towards(this_t{}, idx); } template <typename PosT> static result_t visit_leaf(PosT&& pos, size_t idx) { return std::make_tuple(pos.node()->leaf(), pos.index(idx), pos.count()); } }; template <typename T> struct get_visitor : visitor_base<get_visitor<T>> { using this_t = get_visitor; template <typename PosT> static const T& visit_inner(PosT&& pos, size_t idx) { return pos.descend(this_t{}, idx); } template <typename PosT> static const T& visit_leaf(PosT&& pos, size_t idx) { return pos.node()->leaf()[pos.index(idx)]; } }; struct for_each_chunk_visitor : visitor_base<for_each_chunk_visitor> { using this_t = for_each_chunk_visitor; template <typename Pos, typename Fn> static void visit_inner(Pos&& pos, Fn&& fn) { pos.each(this_t{}, fn); } template <typename Pos, typename Fn> static void visit_leaf(Pos&& pos, Fn&& fn) { auto data = pos.node()->leaf(); fn(data, data + pos.count()); } }; struct for_each_chunk_p_visitor : visitor_base<for_each_chunk_p_visitor> { using this_t = for_each_chunk_p_visitor; template <typename Pos, typename Fn> static bool visit_inner(Pos&& pos, Fn&& fn) { return pos.each_pred(this_t{}, fn); } template <typename Pos, typename Fn> static bool visit_leaf(Pos&& pos, Fn&& fn) { auto data = pos.node()->leaf(); return fn(data, data + pos.count()); } }; struct for_each_chunk_left_visitor : visitor_base<for_each_chunk_left_visitor> { using this_t = for_each_chunk_left_visitor; template <typename Pos, typename Fn> static void visit_inner(Pos&& pos, size_t last, Fn&& fn) { auto l = pos.index(last); pos.each_left(for_each_chunk_visitor{}, l, fn); pos.towards_oh(this_t{}, last, l, fn); } template <typename Pos, typename Fn> static void visit_leaf(Pos&& pos, size_t last, Fn&& fn) { auto data = pos.node()->leaf(); auto l = pos.index(last); fn(data, data + l + 1); } }; struct for_each_chunk_right_visitor : visitor_base<for_each_chunk_right_visitor> { using this_t = for_each_chunk_right_visitor; template <typename Pos, typename Fn> static void visit_inner(Pos&& pos, size_t first, Fn&& fn) { auto f = pos.index(first); pos.towards_oh(this_t{}, first, f, fn); pos.each_right(for_each_chunk_visitor{}, f + 1, fn); } template <typename Pos, typename Fn> static void visit_leaf(Pos&& pos, size_t first, Fn&& fn) { auto data = pos.node()->leaf(); auto f = pos.index(first); fn(data + f, data + pos.count()); } }; struct for_each_chunk_i_visitor : visitor_base<for_each_chunk_i_visitor> { using this_t = for_each_chunk_i_visitor; template <typename Pos, typename Fn> static void visit_relaxed(Pos&& pos, size_t first, size_t last, Fn&& fn) { // we are going towards *two* indices, so we need to do the // relaxed as a special case to correct the second index if (first < last) { auto f = pos.index(first); auto l = pos.index(last - 1); if (f == l) { auto sbh = pos.size_before(f); pos.towards_oh_sbh(this_t{}, first, f, sbh, last - sbh, fn); } else { assert(f < l); pos.towards_oh(for_each_chunk_right_visitor{}, first, f, fn); pos.each_i(for_each_chunk_visitor{}, f + 1, l, fn); pos.towards_oh(for_each_chunk_left_visitor{}, last - 1, l, fn); } } } template <typename Pos, typename Fn> static void visit_regular(Pos&& pos, size_t first, size_t last, Fn&& fn) { if (first < last) { auto f = pos.index(first); auto l = pos.index(last - 1); if (f == l) pos.towards_oh(this_t{}, first, f, last, fn); else { assert(f < l); pos.towards_oh(for_each_chunk_right_visitor{}, first, f, fn); pos.each_i(for_each_chunk_visitor{}, f + 1, l, fn); pos.towards_oh(for_each_chunk_left_visitor{}, last - 1, l, fn); } } } template <typename Pos, typename Fn> static void visit_leaf(Pos&& pos, size_t first, size_t last, Fn&& fn) { auto data = pos.node()->leaf(); if (first < last) { auto f = pos.index(first); auto l = pos.index(last - 1); fn(data + f, data + l + 1); } } }; struct for_each_chunk_p_left_visitor : visitor_base<for_each_chunk_p_left_visitor> { using this_t = for_each_chunk_p_left_visitor; template <typename Pos, typename Fn> static bool visit_inner(Pos&& pos, size_t last, Fn&& fn) { auto l = pos.index(last); return pos.each_pred_left(for_each_chunk_p_visitor{}, l, fn) && pos.towards_oh(this_t{}, last, l, fn); } template <typename Pos, typename Fn> static bool visit_leaf(Pos&& pos, size_t last, Fn&& fn) { auto data = pos.node()->leaf(); auto l = pos.index(last); return fn(data, data + l + 1); } }; struct for_each_chunk_p_right_visitor : visitor_base<for_each_chunk_p_right_visitor> { using this_t = for_each_chunk_p_right_visitor; template <typename Pos, typename Fn> static bool visit_inner(Pos&& pos, size_t first, Fn&& fn) { auto f = pos.index(first); return pos.towards_oh(this_t{}, first, f, fn) && pos.each_pred_right(for_each_chunk_p_visitor{}, f + 1, fn); } template <typename Pos, typename Fn> static bool visit_leaf(Pos&& pos, size_t first, Fn&& fn) { auto data = pos.node()->leaf(); auto f = pos.index(first); return fn(data + f, data + pos.count()); } }; struct for_each_chunk_p_i_visitor : visitor_base<for_each_chunk_p_i_visitor> { using this_t = for_each_chunk_p_i_visitor; template <typename Pos, typename Fn> static bool visit_relaxed(Pos&& pos, size_t first, size_t last, Fn&& fn) { // we are going towards *two* indices, so we need to do the // relaxed as a special case to correct the second index if (first < last) { auto f = pos.index(first); auto l = pos.index(last - 1); if (f == l) { auto sbh = pos.size_before(f); return pos.towards_oh_sbh( this_t{}, first, f, sbh, last - sbh, fn); } else { assert(f < l); return pos.towards_oh( for_each_chunk_p_right_visitor{}, first, f, fn) && pos.each_pred_i( for_each_chunk_p_visitor{}, f + 1, l, fn) && pos.towards_oh( for_each_chunk_p_left_visitor{}, last - 1, l, fn); } } return true; } template <typename Pos, typename Fn> static bool visit_regular(Pos&& pos, size_t first, size_t last, Fn&& fn) { if (first < last) { auto f = pos.index(first); auto l = pos.index(last - 1); if (f == l) return pos.towards_oh(this_t{}, first, f, last, fn); else { assert(f < l); return pos.towards_oh( for_each_chunk_p_right_visitor{}, first, f, fn) && pos.each_pred_i( for_each_chunk_p_visitor{}, f + 1, l, fn) && pos.towards_oh( for_each_chunk_p_left_visitor{}, last - 1, l, fn); } } return true; } template <typename Pos, typename Fn> static bool visit_leaf(Pos&& pos, size_t first, size_t last, Fn&& fn) { auto data = pos.node()->leaf(); if (first < last) { auto f = pos.index(first); auto l = pos.index(last - 1); return fn(data + f, data + l + 1); } return true; } }; struct equals_visitor : visitor_base<equals_visitor> { using this_t = equals_visitor; struct this_aux_t : visitor_base<this_aux_t> { template <typename PosR, typename PosL, typename Iter> static bool visit_inner( PosR&& posr, count_t i, PosL&& posl, Iter&& first, size_t idx) { return posl.nth_sub(i, this_t{}, posr, first, idx); } template <typename PosR, typename PosL, typename Iter> static bool visit_leaf( PosR&& posr, count_t i, PosL&& posl, Iter&& first, size_t idx) { return posl.nth_sub_leaf(i, this_t{}, posr, first, idx); } }; struct rrb : visitor_base<rrb> { template <typename PosR, typename Iter, typename Node> static bool visit_node(PosR&& posr, Iter&& first, Node* rootl, shift_t shiftl, size_t sizel) { assert(shiftl <= posr.shift()); return shiftl == posr.shift() ? visit_maybe_relaxed_sub(rootl, shiftl, sizel, this_t{}, posr, first, size_t{}) : posr.first_sub_inner( rrb{}, first, rootl, shiftl, sizel); } }; template <typename Iter> static auto equal_chunk_p(Iter&& iter) { return [iter](auto f, auto e) mutable { if (f == &*iter) { iter += e - f; return true; } for (; f != e; ++f, ++iter) if (*f != *iter) return false; return true; }; } template <typename PosL, typename PosR, typename Iter> static bool visit_relaxed(PosL&& posl, PosR&& posr, Iter&& first, size_t idx) { auto nl = posl.node(); auto nr = posr.node(); if (nl == nr) return true; auto cl = posl.count(); auto cr = posr.count(); assert(cr > 0); auto sbr = size_t{}; auto i = count_t{}; auto j = count_t{}; for (; i < cl; ++i) { auto sbl = posl.size_before(i); for (; j + 1 < cr && (sbr = posr.size_before(j)) < sbl; ++j) ; auto res = sbl == sbr ? posr.nth_sub(j, this_aux_t{}, i, posl, first, idx + sbl) : posl.nth_sub(i, for_each_chunk_p_visitor{}, this_t::equal_chunk_p(first + (idx + sbl))); if (!res) return false; } return true; } template <typename PosL, typename PosR, typename Iter> static std::enable_if_t<is_relaxed_v<PosR>, bool> visit_regular(PosL&& posl, PosR&& posr, Iter&& first, size_t idx) { return this_t::visit_relaxed(posl, posr, first, idx); } template <typename PosL, typename PosR, typename Iter> static std::enable_if_t<!is_relaxed_v<PosR>, bool> visit_regular(PosL&& posl, PosR&& posr, Iter&& first, size_t idx) { return posl.count() >= posr.count() ? this_t::visit_regular(posl, posr.node()) : this_t::visit_regular(posr, posl.node()); } template <typename PosL, typename PosR, typename Iter> static bool visit_leaf(PosL&& posl, PosR&& posr, Iter&& first, size_t idx) { if (posl.node() == posr.node()) return true; auto cl = posl.count(); auto cr = posr.count(); auto mp = std::min(cl, cr); return std::equal(posl.node()->leaf(), posl.node()->leaf() + mp, posr.node()->leaf()) && std::equal(posl.node()->leaf() + mp, posl.node()->leaf() + posl.count(), first + (idx + mp)); } template <typename Pos, typename NodeT> static bool visit_regular(Pos&& pos, NodeT* other) { auto node = pos.node(); return node == other || pos.each_pred_zip(this_t{}, other); } template <typename Pos, typename NodeT> static bool visit_leaf(Pos&& pos, NodeT* other) { auto node = pos.node(); return node == other || std::equal(node->leaf(), node->leaf() + pos.count(), other->leaf()); } }; template <typename NodeT> struct update_visitor : visitor_base<update_visitor<NodeT>> { using node_t = NodeT; using this_t = update_visitor; template <typename Pos, typename Fn> static node_t* visit_relaxed(Pos&& pos, size_t idx, Fn&& fn) { auto offset = pos.index(idx); auto count = pos.count(); auto node = node_t::make_inner_sr_n(count, pos.relaxed()); try { auto child = pos.towards_oh(this_t{}, idx, offset, fn); node_t::do_copy_inner_sr(node, pos.node(), count); node->inner()[offset]->dec_unsafe(); node->inner()[offset] = child; return node; } catch (...) { node_t::delete_inner_r(node, count); throw; } } template <typename Pos, typename Fn> static node_t* visit_regular(Pos&& pos, size_t idx, Fn&& fn) { auto offset = pos.index(idx); auto count = pos.count(); auto node = node_t::make_inner_n(count); try { auto child = pos.towards_oh_ch(this_t{}, idx, offset, count, fn); node_t::do_copy_inner(node, pos.node(), count); node->inner()[offset]->dec_unsafe(); node->inner()[offset] = child; return node; } catch (...) { node_t::delete_inner(node, count); throw; } } template <typename Pos, typename Fn> static node_t* visit_leaf(Pos&& pos, size_t idx, Fn&& fn) { auto offset = pos.index(idx); auto node = node_t::copy_leaf(pos.node(), pos.count()); try { node->leaf()[offset] = std::forward<Fn>(fn)(std::move(node->leaf()[offset])); return node; } catch (...) { node_t::delete_leaf(node, pos.count()); throw; } } }; struct dec_visitor : visitor_base<dec_visitor> { using this_t = dec_visitor; template <typename Pos> static void visit_relaxed(Pos&& p) { using node_t = node_type<Pos>; auto node = p.node(); if (node->dec()) { p.each(this_t{}); node_t::delete_inner_r(node, p.count()); } } template <typename Pos> static void visit_regular(Pos&& p) { using node_t = node_type<Pos>; auto node = p.node(); if (node->dec()) { p.each(this_t{}); node_t::delete_inner(node, p.count()); } } template <typename Pos> static void visit_leaf(Pos&& p) { using node_t = node_type<Pos>; auto node = p.node(); if (node->dec()) { node_t::delete_leaf(node, p.count()); } } }; template <typename NodeT> void dec_leaf(NodeT* node, count_t n) { make_leaf_sub_pos(node, n).visit(dec_visitor{}); } template <typename NodeT> void dec_inner(NodeT* node, shift_t shift, size_t size) { visit_maybe_relaxed_sub(node, shift, size, dec_visitor()); } template <typename NodeT> void dec_relaxed(NodeT* node, shift_t shift) { make_relaxed_pos(node, shift, node->relaxed()).visit(dec_visitor()); } template <typename NodeT> void dec_regular(NodeT* node, shift_t shift, size_t size) { make_regular_pos(node, shift, size).visit(dec_visitor()); } template <typename NodeT> void dec_empty_regular(NodeT* node) { make_empty_regular_pos(node).visit(dec_visitor()); } template <typename NodeT> struct get_mut_visitor : visitor_base<get_mut_visitor<NodeT>> { using node_t = NodeT; using this_t = get_mut_visitor; using value_t = typename NodeT::value_t; using edit_t = typename NodeT::edit_t; template <typename Pos> static value_t& visit_relaxed(Pos&& pos, size_t idx, edit_t e, node_t** location) { auto offset = pos.index(idx); auto count = pos.count(); auto node = pos.node(); if (node->can_mutate(e)) { return pos.towards_oh( this_t{}, idx, offset, e, &node->inner()[offset]); } else { auto new_node = node_t::copy_inner_sr_e(e, node, count); try { auto& res = pos.towards_oh( this_t{}, idx, offset, e, &new_node->inner()[offset]); pos.visit(dec_visitor{}); *location = new_node; return res; } catch (...) { dec_relaxed(new_node, pos.shift()); throw; } } } template <typename Pos> static value_t& visit_regular(Pos&& pos, size_t idx, edit_t e, node_t** location) { assert(pos.node() == *location); auto offset = pos.index(idx); auto count = pos.count(); auto node = pos.node(); if (node->can_mutate(e)) { return pos.towards_oh_ch( this_t{}, idx, offset, count, e, &node->inner()[offset]); } else { auto new_node = node_t::copy_inner_e(e, node, count); try { auto& res = pos.towards_oh_ch(this_t{}, idx, offset, count, e, &new_node->inner()[offset]); pos.visit(dec_visitor{}); *location = new_node; return res; } catch (...) { dec_regular(new_node, pos.shift(), pos.size()); throw; } } } template <typename Pos> static value_t& visit_leaf(Pos&& pos, size_t idx, edit_t e, node_t** location) { assert(pos.node() == *location); auto node = pos.node(); if (node->can_mutate(e)) { return node->leaf()[pos.index(idx)]; } else { auto new_node = node_t::copy_leaf_e(e, pos.node(), pos.count()); pos.visit(dec_visitor{}); *location = new_node; return new_node->leaf()[pos.index(idx)]; } } }; template <typename NodeT, bool Mutating = true> struct push_tail_mut_visitor : visitor_base<push_tail_mut_visitor<NodeT, Mutating>> { static constexpr auto B = NodeT::bits; static constexpr auto BL = NodeT::bits_leaf; using this_t = push_tail_mut_visitor; using this_no_mut_t = push_tail_mut_visitor<NodeT, false>; using node_t = NodeT; using edit_t = typename NodeT::edit_t; template <typename Pos> static node_t* visit_relaxed(Pos&& pos, edit_t e, node_t* tail, count_t ts) { auto node = pos.node(); auto level = pos.shift(); auto idx = pos.count() - 1; auto children = pos.size(idx); auto new_idx = children == size_t{1} << level || level == BL ? idx + 1 : idx; auto new_child = static_cast<node_t*>(nullptr); auto mutate = Mutating && node->can_mutate(e); if (new_idx >= branches<B>) return nullptr; else if (idx == new_idx) { new_child = mutate ? pos.last_oh_csh(this_t{}, idx, children, e, tail, ts) : pos.last_oh_csh( this_no_mut_t{}, idx, children, e, tail, ts); if (!new_child) { if (++new_idx < branches<B>) new_child = node_t::make_path_e(e, level - B, tail); else return nullptr; } } else new_child = node_t::make_path_e(e, level - B, tail); if (mutate) { auto count = new_idx + 1; auto relaxed = node->ensure_mutable_relaxed_n(e, new_idx); node->inner()[new_idx] = new_child; relaxed->d.sizes[new_idx] = pos.size() + ts; relaxed->d.count = count; return node; } else { try { auto count = new_idx + 1; auto new_node = node_t::copy_inner_r_e(e, pos.node(), new_idx); auto relaxed = new_node->relaxed(); new_node->inner()[new_idx] = new_child; relaxed->d.sizes[new_idx] = pos.size() + ts; relaxed->d.count = count; if (Mutating) pos.visit(dec_visitor{}); return new_node; } catch (...) { auto shift = pos.shift(); auto size = new_idx == idx ? children + ts : ts; if (shift > BL) { tail->inc(); dec_inner(new_child, shift - B, size); } throw; } } } template <typename Pos, typename... Args> static node_t* visit_regular(Pos&& pos, edit_t e, node_t* tail, Args&&...) { assert((pos.size() & mask<BL>) == 0); auto node = pos.node(); auto idx = pos.index(pos.size() - 1); auto new_idx = pos.index(pos.size() + branches<BL> - 1); auto mutate = Mutating && node->can_mutate(e); if (mutate) { node->inner()[new_idx] = idx == new_idx ? pos.last_oh(this_t{}, idx, e, tail) /* otherwise */ : node_t::make_path_e(e, pos.shift() - B, tail); return node; } else { auto new_parent = node_t::make_inner_e(e); try { new_parent->inner()[new_idx] = idx == new_idx ? pos.last_oh(this_no_mut_t{}, idx, e, tail) /* otherwise */ : node_t::make_path_e(e, pos.shift() - B, tail); node_t::do_copy_inner(new_parent, node, new_idx); if (Mutating) pos.visit(dec_visitor{}); return new_parent; } catch (...) { node_t::delete_inner_e(new_parent); throw; } } } template <typename Pos, typename... Args> static node_t* visit_leaf(Pos&& pos, edit_t e, node_t* tail, Args&&...) { IMMER_UNREACHABLE; } }; template <typename NodeT> struct push_tail_visitor : visitor_base<push_tail_visitor<NodeT>> { static constexpr auto B = NodeT::bits; static constexpr auto BL = NodeT::bits_leaf; using this_t = push_tail_visitor; using node_t = NodeT; template <typename Pos> static node_t* visit_relaxed(Pos&& pos, node_t* tail, count_t ts) { auto level = pos.shift(); auto idx = pos.count() - 1; auto children = pos.size(idx); auto new_idx = children == size_t{1} << level || level == BL ? idx + 1 : idx; auto new_child = static_cast<node_t*>(nullptr); if (new_idx >= branches<B>) return nullptr; else if (idx == new_idx) { new_child = pos.last_oh_csh(this_t{}, idx, children, tail, ts); if (!new_child) { if (++new_idx < branches<B>) new_child = node_t::make_path(level - B, tail); else return nullptr; } } else new_child = node_t::make_path(level - B, tail); try { auto count = new_idx + 1; auto new_parent = node_t::copy_inner_r_n(count, pos.node(), new_idx); auto new_relaxed = new_parent->relaxed(); new_parent->inner()[new_idx] = new_child; new_relaxed->d.sizes[new_idx] = pos.size() + ts; new_relaxed->d.count = count; return new_parent; } catch (...) { auto shift = pos.shift(); auto size = new_idx == idx ? children + ts : ts; if (shift > BL) { tail->inc(); dec_inner(new_child, shift - B, size); } throw; } } template <typename Pos, typename... Args> static node_t* visit_regular(Pos&& pos, node_t* tail, Args&&...) { assert((pos.size() & mask<BL>) == 0); auto idx = pos.index(pos.size() - 1); auto new_idx = pos.index(pos.size() + branches<BL> - 1); auto count = new_idx + 1; auto new_parent = node_t::make_inner_n(count); try { new_parent->inner()[new_idx] = idx == new_idx ? pos.last_oh(this_t{}, idx, tail) /* otherwise */ : node_t::make_path(pos.shift() - B, tail); } catch (...) { node_t::delete_inner(new_parent, count); throw; } return node_t::do_copy_inner(new_parent, pos.node(), new_idx); } template <typename Pos, typename... Args> static node_t* visit_leaf(Pos&& pos, node_t* tail, Args&&...) { IMMER_UNREACHABLE; } }; struct dec_right_visitor : visitor_base<dec_right_visitor> { using this_t = dec_right_visitor; using dec_t = dec_visitor; template <typename Pos> static void visit_relaxed(Pos&& p, count_t idx) { using node_t = node_type<Pos>; auto node = p.node(); if (node->dec()) { p.each_right(dec_t{}, idx); node_t::delete_inner_r(node, p.count()); } } template <typename Pos> static void visit_regular(Pos&& p, count_t idx) { using node_t = node_type<Pos>; auto node = p.node(); if (node->dec()) { p.each_right(dec_t{}, idx); node_t::delete_inner(node, p.count()); } } template <typename Pos> static void visit_leaf(Pos&& p, count_t idx) { IMMER_UNREACHABLE; } }; template <typename NodeT, bool Collapse = true, bool Mutating = true> struct slice_right_mut_visitor : visitor_base<slice_right_mut_visitor<NodeT, Collapse, Mutating>> { using node_t = NodeT; using this_t = slice_right_mut_visitor; using edit_t = typename NodeT::edit_t; // returns a new shift, new root, the new tail size and the new tail using result_t = std::tuple<shift_t, NodeT*, count_t, NodeT*>; using no_collapse_t = slice_right_mut_visitor<NodeT, false, true>; using no_collapse_no_mut_t = slice_right_mut_visitor<NodeT, false, false>; using no_mut_t = slice_right_mut_visitor<NodeT, Collapse, false>; static constexpr auto B = NodeT::bits; static constexpr auto BL = NodeT::bits_leaf; template <typename PosT> static result_t visit_relaxed(PosT&& pos, size_t last, edit_t e) { auto idx = pos.index(last); auto node = pos.node(); auto mutate = Mutating && node->can_mutate(e); if (Collapse && idx == 0) { auto res = mutate ? pos.towards_oh(this_t{}, last, idx, e) : pos.towards_oh(no_mut_t{}, last, idx, e); if (Mutating) pos.visit(dec_right_visitor{}, count_t{1}); return res; } else { using std::get; auto subs = mutate ? pos.towards_oh(no_collapse_t{}, last, idx, e) : pos.towards_oh(no_collapse_no_mut_t{}, last, idx, e); auto next = get<1>(subs); auto ts = get<2>(subs); auto tail = get<3>(subs); try { if (next) { if (mutate) { auto nodr = node->ensure_mutable_relaxed_n(e, idx); pos.each_right(dec_visitor{}, idx + 1); node->inner()[idx] = next; nodr->d.sizes[idx] = last + 1 - ts; nodr->d.count = idx + 1; return std::make_tuple(pos.shift(), node, ts, tail); } else { auto newn = node_t::copy_inner_r_e(e, node, idx); auto newr = newn->relaxed(); newn->inner()[idx] = next; newr->d.sizes[idx] = last + 1 - ts; newr->d.count = idx + 1; if (Mutating) pos.visit(dec_visitor{}); return std::make_tuple(pos.shift(), newn, ts, tail); } } else if (idx == 0) { if (Mutating) pos.visit(dec_right_visitor{}, count_t{1}); return std::make_tuple(pos.shift(), nullptr, ts, tail); } else if (Collapse && idx == 1 && pos.shift() > BL) { auto newn = pos.node()->inner()[0]; if (!mutate) newn->inc(); if (Mutating) pos.visit(dec_right_visitor{}, count_t{2}); return std::make_tuple(pos.shift() - B, newn, ts, tail); } else { if (mutate) { pos.each_right(dec_visitor{}, idx + 1); node->ensure_mutable_relaxed_n(e, idx)->d.count = idx; return std::make_tuple(pos.shift(), node, ts, tail); } else { auto newn = node_t::copy_inner_r_e(e, node, idx); if (Mutating) pos.visit(dec_visitor{}); return std::make_tuple(pos.shift(), newn, ts, tail); } } } catch (...) { assert(!mutate); assert(!next || pos.shift() > BL); if (next) dec_inner(next, pos.shift() - B, last + 1 - ts - pos.size_before(idx)); dec_leaf(tail, ts); throw; } } } template <typename PosT> static result_t visit_regular(PosT&& pos, size_t last, edit_t e) { auto idx = pos.index(last); auto node = pos.node(); auto mutate = Mutating && node->can_mutate(e); if (Collapse && idx == 0) { auto res = mutate ? pos.towards_oh(this_t{}, last, idx, e) : pos.towards_oh(no_mut_t{}, last, idx, e); if (Mutating) pos.visit(dec_right_visitor{}, count_t{1}); return res; } else { using std::get; auto subs = mutate ? pos.towards_oh(no_collapse_t{}, last, idx, e) : pos.towards_oh(no_collapse_no_mut_t{}, last, idx, e); auto next = get<1>(subs); auto ts = get<2>(subs); auto tail = get<3>(subs); try { if (next) { if (mutate) { node->inner()[idx] = next; pos.each_right(dec_visitor{}, idx + 1); return std::make_tuple(pos.shift(), node, ts, tail); } else { auto newn = node_t::copy_inner_e(e, node, idx); newn->inner()[idx] = next; if (Mutating) pos.visit(dec_visitor{}); return std::make_tuple(pos.shift(), newn, ts, tail); } } else if (idx == 0) { if (Mutating) pos.visit(dec_right_visitor{}, count_t{1}); return std::make_tuple(pos.shift(), nullptr, ts, tail); } else if (Collapse && idx == 1 && pos.shift() > BL) { auto newn = pos.node()->inner()[0]; if (!mutate) newn->inc(); if (Mutating) pos.visit(dec_right_visitor{}, count_t{2}); return std::make_tuple(pos.shift() - B, newn, ts, tail); } else { if (mutate) { pos.each_right(dec_visitor{}, idx + 1); return std::make_tuple(pos.shift(), node, ts, tail); } else { auto newn = node_t::copy_inner_e(e, node, idx); if (Mutating) pos.visit(dec_visitor{}); return std::make_tuple(pos.shift(), newn, ts, tail); } } } catch (...) { assert(!mutate); assert(!next || pos.shift() > BL); assert(tail); if (next) dec_regular(next, pos.shift() - B, last + 1 - ts); dec_leaf(tail, ts); throw; } } } template <typename PosT> static result_t visit_leaf(PosT&& pos, size_t last, edit_t e) { auto old_tail_size = pos.count(); auto new_tail_size = pos.index(last) + 1; auto node = pos.node(); auto mutate = Mutating && node->can_mutate(e); if (new_tail_size == old_tail_size) { if (!Mutating) node->inc(); return std::make_tuple(0, nullptr, new_tail_size, node); } else if (mutate) { destroy_n(node->leaf() + new_tail_size, old_tail_size - new_tail_size); return std::make_tuple(0, nullptr, new_tail_size, node); } else { auto new_tail = node_t::copy_leaf_e(e, node, new_tail_size); if (Mutating) pos.visit(dec_visitor{}); return std::make_tuple(0, nullptr, new_tail_size, new_tail); } } }; template <typename NodeT, bool Collapse = true> struct slice_right_visitor : visitor_base<slice_right_visitor<NodeT, Collapse>> { using node_t = NodeT; using this_t = slice_right_visitor; // returns a new shift, new root, the new tail size and the new tail using result_t = std::tuple<shift_t, NodeT*, count_t, NodeT*>; using no_collapse_t = slice_right_visitor<NodeT, false>; static constexpr auto B = NodeT::bits; static constexpr auto BL = NodeT::bits_leaf; template <typename PosT> static result_t visit_relaxed(PosT&& pos, size_t last) { auto idx = pos.index(last); if (Collapse && idx == 0) { return pos.towards_oh(this_t{}, last, idx); } else { using std::get; auto subs = pos.towards_oh(no_collapse_t{}, last, idx); auto next = get<1>(subs); auto ts = get<2>(subs); auto tail = get<3>(subs); try { if (next) { auto count = idx + 1; auto newn = node_t::copy_inner_r_n(count, pos.node(), idx); auto newr = newn->relaxed(); newn->inner()[idx] = next; newr->d.sizes[idx] = last + 1 - ts; newr->d.count = count; return std::make_tuple(pos.shift(), newn, ts, tail); } else if (idx == 0) { return std::make_tuple(pos.shift(), nullptr, ts, tail); } else if (Collapse && idx == 1 && pos.shift() > BL) { auto newn = pos.node()->inner()[0]; return std::make_tuple( pos.shift() - B, newn->inc(), ts, tail); } else { auto newn = node_t::copy_inner_r(pos.node(), idx); return std::make_tuple(pos.shift(), newn, ts, tail); } } catch (...) { assert(!next || pos.shift() > BL); if (next) dec_inner(next, pos.shift() - B, last + 1 - ts - pos.size_before(idx)); if (tail) dec_leaf(tail, ts); throw; } } } template <typename PosT> static result_t visit_regular(PosT&& pos, size_t last) { auto idx = pos.index(last); if (Collapse && idx == 0) { return pos.towards_oh(this_t{}, last, idx); } else { using std::get; auto subs = pos.towards_oh(no_collapse_t{}, last, idx); auto next = get<1>(subs); auto ts = get<2>(subs); auto tail = get<3>(subs); try { if (next) { auto newn = node_t::copy_inner_n(idx + 1, pos.node(), idx); newn->inner()[idx] = next; return std::make_tuple(pos.shift(), newn, ts, tail); } else if (idx == 0) { return std::make_tuple(pos.shift(), nullptr, ts, tail); } else if (Collapse && idx == 1 && pos.shift() > BL) { auto newn = pos.node()->inner()[0]; return std::make_tuple( pos.shift() - B, newn->inc(), ts, tail); } else { auto newn = node_t::copy_inner_n(idx, pos.node(), idx); return std::make_tuple(pos.shift(), newn, ts, tail); } } catch (...) { assert(!next || pos.shift() > BL); assert(tail); if (next) dec_regular(next, pos.shift() - B, last + 1 - ts); dec_leaf(tail, ts); throw; } } } template <typename PosT> static result_t visit_leaf(PosT&& pos, size_t last) { auto old_tail_size = pos.count(); auto new_tail_size = pos.index(last) + 1; auto new_tail = new_tail_size == old_tail_size ? pos.node()->inc() : node_t::copy_leaf(pos.node(), new_tail_size); return std::make_tuple(0, nullptr, new_tail_size, new_tail); } }; struct dec_left_visitor : visitor_base<dec_left_visitor> { using this_t = dec_left_visitor; using dec_t = dec_visitor; template <typename Pos> static void visit_relaxed(Pos&& p, count_t idx) { using node_t = node_type<Pos>; auto node = p.node(); if (node->dec()) { p.each_left(dec_t{}, idx); node_t::delete_inner_r(node, p.count()); } } template <typename Pos> static void visit_regular(Pos&& p, count_t idx) { using node_t = node_type<Pos>; auto node = p.node(); if (node->dec()) { p.each_left(dec_t{}, idx); node_t::delete_inner(node, p.count()); } } template <typename Pos> static void visit_leaf(Pos&& p, count_t idx) { IMMER_UNREACHABLE; } }; template <typename NodeT, bool Collapse = true, bool Mutating = true> struct slice_left_mut_visitor : visitor_base<slice_left_mut_visitor<NodeT, Collapse, Mutating>> { using node_t = NodeT; using this_t = slice_left_mut_visitor; using edit_t = typename NodeT::edit_t; using value_t = typename NodeT::value_t; using relaxed_t = typename NodeT::relaxed_t; // returns a new shift and new root using result_t = std::tuple<shift_t, NodeT*>; using no_collapse_t = slice_left_mut_visitor<NodeT, false, true>; using no_collapse_no_mut_t = slice_left_mut_visitor<NodeT, false, false>; using no_mut_t = slice_left_mut_visitor<NodeT, Collapse, false>; static constexpr auto B = NodeT::bits; static constexpr auto BL = NodeT::bits_leaf; template <typename PosT> static result_t visit_relaxed(PosT&& pos, size_t first, edit_t e) { auto idx = pos.subindex(first); auto count = pos.count(); auto node = pos.node(); auto mutate = Mutating && node->can_mutate(e); auto left_size = pos.size_before(idx); auto child_size = pos.size_sbh(idx, left_size); auto dropped_size = first; auto child_dropped_size = dropped_size - left_size; if (Collapse && pos.shift() > BL && idx == pos.count() - 1) { auto r = mutate ? pos.towards_sub_oh(this_t{}, first, idx, e) : pos.towards_sub_oh(no_mut_t{}, first, idx, e); if (Mutating) pos.visit(dec_left_visitor{}, idx); return r; } else { using std::get; auto newn = mutate ? (node->ensure_mutable_relaxed(e), node) : node_t::make_inner_r_e(e); auto newr = newn->relaxed(); auto newcount = count - idx; auto new_child_size = child_size - child_dropped_size; try { auto subs = mutate ? pos.towards_sub_oh(no_collapse_t{}, first, idx, e) : pos.towards_sub_oh( no_collapse_no_mut_t{}, first, idx, e); if (mutate) pos.each_left(dec_visitor{}, idx); pos.copy_sizes( idx + 1, newcount - 1, new_child_size, newr->d.sizes + 1); std::uninitialized_copy(node->inner() + idx + 1, node->inner() + count, newn->inner() + 1); newn->inner()[0] = get<1>(subs); newr->d.sizes[0] = new_child_size; newr->d.count = newcount; if (!mutate) { node_t::inc_nodes(newn->inner() + 1, newcount - 1); if (Mutating) pos.visit(dec_visitor{}); } return std::make_tuple(pos.shift(), newn); } catch (...) { if (!mutate) node_t::delete_inner_r_e(newn); throw; } } } template <typename PosT> static result_t visit_regular(PosT&& pos, size_t first, edit_t e) { auto idx = pos.subindex(first); auto count = pos.count(); auto node = pos.node(); auto mutate = Mutating // this is more restrictive than actually needed because // it causes the algorithm to also avoid mutating the leaf // in place && !node_t::embed_relaxed && node->can_mutate(e); auto left_size = pos.size_before(idx); auto child_size = pos.size_sbh(idx, left_size); auto dropped_size = first; auto child_dropped_size = dropped_size - left_size; if (Collapse && pos.shift() > BL && idx == pos.count() - 1) { auto r = mutate ? pos.towards_sub_oh(this_t{}, first, idx, e) : pos.towards_sub_oh(no_mut_t{}, first, idx, e); if (Mutating) pos.visit(dec_left_visitor{}, idx); return r; } else { using std::get; // if possible, we convert the node to a relaxed one // simply by allocating a `relaxed_t` size table for // it... maybe some of this magic should be moved as a // `node<...>` static method... auto newcount = count - idx; auto newn = mutate ? (node->impl.d.data.inner.relaxed = new ( node_t::heap::allocate(node_t::max_sizeof_relaxed, norefs_tag{})) relaxed_t, node) : node_t::make_inner_r_e(e); auto newr = newn->relaxed(); try { auto subs = mutate ? pos.towards_sub_oh(no_collapse_t{}, first, idx, e) : pos.towards_sub_oh( no_collapse_no_mut_t{}, first, idx, e); if (mutate) pos.each_left(dec_visitor{}, idx); newr->d.sizes[0] = child_size - child_dropped_size; pos.copy_sizes( idx + 1, newcount - 1, newr->d.sizes[0], newr->d.sizes + 1); newr->d.count = newcount; newn->inner()[0] = get<1>(subs); std::uninitialized_copy(node->inner() + idx + 1, node->inner() + count, newn->inner() + 1); if (!mutate) { node_t::inc_nodes(newn->inner() + 1, newcount - 1); if (Mutating) pos.visit(dec_visitor{}); } return std::make_tuple(pos.shift(), newn); } catch (...) { if (!mutate) node_t::delete_inner_r_e(newn); else { // restore the regular node that we were // attempting to relax... node_t::heap::deallocate(node_t::max_sizeof_relaxed, node->impl.d.data.inner.relaxed); node->impl.d.data.inner.relaxed = nullptr; } throw; } } } template <typename PosT> static result_t visit_leaf(PosT&& pos, size_t first, edit_t e) { auto node = pos.node(); auto idx = pos.index(first); auto count = pos.count(); auto mutate = Mutating && std::is_nothrow_move_constructible<value_t>::value && node->can_mutate(e); if (mutate) { auto data = node->leaf(); auto newcount = count - idx; std::move(data + idx, data + count, data); destroy_n(data + newcount, idx); return std::make_tuple(0, node); } else { auto newn = node_t::copy_leaf_e(e, node, idx, count); if (Mutating) pos.visit(dec_visitor{}); return std::make_tuple(0, newn); } } }; template <typename NodeT, bool Collapse = true> struct slice_left_visitor : visitor_base<slice_left_visitor<NodeT, Collapse>> { using node_t = NodeT; using this_t = slice_left_visitor; // returns a new shift and new root using result_t = std::tuple<shift_t, NodeT*>; using no_collapse_t = slice_left_visitor<NodeT, false>; static constexpr auto B = NodeT::bits; static constexpr auto BL = NodeT::bits_leaf; template <typename PosT> static result_t visit_inner(PosT&& pos, size_t first) { auto idx = pos.subindex(first); auto count = pos.count(); auto left_size = pos.size_before(idx); auto child_size = pos.size_sbh(idx, left_size); auto dropped_size = first; auto child_dropped_size = dropped_size - left_size; if (Collapse && pos.shift() > BL && idx == pos.count() - 1) { return pos.towards_sub_oh(this_t{}, first, idx); } else { using std::get; auto n = pos.node(); auto newc = count - idx; auto newn = node_t::make_inner_r_n(newc); try { auto subs = pos.towards_sub_oh(no_collapse_t{}, first, idx); auto newr = newn->relaxed(); newr->d.count = count - idx; newr->d.sizes[0] = child_size - child_dropped_size; pos.copy_sizes(idx + 1, newr->d.count - 1, newr->d.sizes[0], newr->d.sizes + 1); assert(newr->d.sizes[newr->d.count - 1] == pos.size() - dropped_size); newn->inner()[0] = get<1>(subs); std::uninitialized_copy(n->inner() + idx + 1, n->inner() + count, newn->inner() + 1); node_t::inc_nodes(newn->inner() + 1, newr->d.count - 1); return std::make_tuple(pos.shift(), newn); } catch (...) { node_t::delete_inner_r(newn, newc); throw; } } } template <typename PosT> static result_t visit_leaf(PosT&& pos, size_t first) { auto n = node_t::copy_leaf(pos.node(), pos.index(first), pos.count()); return std::make_tuple(0, n); } }; template <typename Node> struct concat_center_pos { static constexpr auto B = Node::bits; static constexpr auto BL = Node::bits_leaf; static constexpr count_t max_children = 3; using node_t = Node; using edit_t = typename Node::edit_t; shift_t shift_ = 0u; count_t count_ = 0u; node_t* nodes_[max_children]; size_t sizes_[max_children]; auto shift() const { return shift_; } concat_center_pos(shift_t s, Node* n0, size_t s0) : shift_{s} , count_{1} , nodes_{n0} , sizes_{s0} {} concat_center_pos(shift_t s, Node* n0, size_t s0, Node* n1, size_t s1) : shift_{s} , count_{2} , nodes_{n0, n1} , sizes_{s0, s1} {} concat_center_pos(shift_t s, Node* n0, size_t s0, Node* n1, size_t s1, Node* n2, size_t s2) : shift_{s} , count_{3} , nodes_{n0, n1, n2} , sizes_{s0, s1, s2} {} template <typename Visitor, typename... Args> void each_sub(Visitor v, Args&&... args) { if (shift_ == BL) { for (auto i = count_t{0}; i < count_; ++i) make_leaf_sub_pos(nodes_[i], sizes_[i]).visit(v, args...); } else { for (auto i = count_t{0}; i < count_; ++i) make_relaxed_pos(nodes_[i], shift_ - B, nodes_[i]->relaxed()) .visit(v, args...); } } relaxed_pos<Node> realize() && { if (count_ > 1) { try { auto result = node_t::make_inner_r_n(count_); auto r = result->relaxed(); r->d.count = count_; std::copy(nodes_, nodes_ + count_, result->inner()); std::copy(sizes_, sizes_ + count_, r->d.sizes); return {result, shift_, r}; } catch (...) { each_sub(dec_visitor{}); throw; } } else { assert(shift_ >= B + BL); return {nodes_[0], shift_ - B, nodes_[0]->relaxed()}; } } relaxed_pos<Node> realize_e(edit_t e) { if (count_ > 1) { auto result = node_t::make_inner_r_e(e); auto r = result->relaxed(); r->d.count = count_; std::copy(nodes_, nodes_ + count_, result->inner()); std::copy(sizes_, sizes_ + count_, r->d.sizes); return {result, shift_, r}; } else { assert(shift_ >= B + BL); return {nodes_[0], shift_ - B, nodes_[0]->relaxed()}; } } }; template <typename Node> struct concat_merger { using node_t = Node; static constexpr auto B = Node::bits; static constexpr auto BL = Node::bits_leaf; using result_t = concat_center_pos<Node>; count_t* curr_; count_t n_; result_t result_; concat_merger(shift_t shift, count_t* counts, count_t n) : curr_{counts} , n_{n} , result_{ shift + B, node_t::make_inner_r_n(std::min(n_, branches<B>)), 0} {} node_t* to_ = {}; count_t to_offset_ = {}; size_t to_size_ = {}; void add_child(node_t* p, size_t size) { ++curr_; auto parent = result_.nodes_[result_.count_ - 1]; auto relaxed = parent->relaxed(); if (relaxed->d.count == branches<B>) { assert(result_.count_ < result_t::max_children); n_ -= branches<B>; parent = node_t::make_inner_r_n(std::min(n_, branches<B>)); relaxed = parent->relaxed(); result_.nodes_[result_.count_] = parent; result_.sizes_[result_.count_] = result_.sizes_[result_.count_ - 1]; ++result_.count_; } auto idx = relaxed->d.count++; result_.sizes_[result_.count_ - 1] += size; relaxed->d.sizes[idx] = size + (idx ? relaxed->d.sizes[idx - 1] : 0); parent->inner()[idx] = p; }; template <typename Pos> void merge_leaf(Pos&& p) { auto from = p.node(); auto from_size = p.size(); auto from_count = p.count(); assert(from_size); if (!to_ && *curr_ == from_count) { add_child(from, from_size); from->inc(); } else { auto from_offset = count_t{}; auto from_data = from->leaf(); do { if (!to_) { to_ = node_t::make_leaf_n(*curr_); to_offset_ = 0; } auto data = to_->leaf(); auto to_copy = std::min(from_count - from_offset, *curr_ - to_offset_); std::uninitialized_copy(from_data + from_offset, from_data + from_offset + to_copy, data + to_offset_); to_offset_ += to_copy; from_offset += to_copy; if (*curr_ == to_offset_) { add_child(to_, to_offset_); to_ = nullptr; } } while (from_offset != from_count); } } template <typename Pos> void merge_inner(Pos&& p) { auto from = p.node(); auto from_size = p.size(); auto from_count = p.count(); assert(from_size); if (!to_ && *curr_ == from_count) { add_child(from, from_size); from->inc(); } else { auto from_offset = count_t{}; auto from_data = from->inner(); do { if (!to_) { to_ = node_t::make_inner_r_n(*curr_); to_offset_ = 0; to_size_ = 0; } auto data = to_->inner(); auto to_copy = std::min(from_count - from_offset, *curr_ - to_offset_); std::uninitialized_copy(from_data + from_offset, from_data + from_offset + to_copy, data + to_offset_); node_t::inc_nodes(from_data + from_offset, to_copy); auto sizes = to_->relaxed()->d.sizes; p.copy_sizes( from_offset, to_copy, to_size_, sizes + to_offset_); to_offset_ += to_copy; from_offset += to_copy; to_size_ = sizes[to_offset_ - 1]; if (*curr_ == to_offset_) { to_->relaxed()->d.count = to_offset_; add_child(to_, to_size_); to_ = nullptr; } } while (from_offset != from_count); } } concat_center_pos<Node> finish() const { assert(!to_); return result_; } void abort() { auto shift = result_.shift_ - B; if (to_) { if (shift == BL) node_t::delete_leaf(to_, to_offset_); else { to_->relaxed()->d.count = to_offset_; dec_relaxed(to_, shift - B); } } result_.each_sub(dec_visitor()); } }; struct concat_merger_visitor : visitor_base<concat_merger_visitor> { using this_t = concat_merger_visitor; template <typename Pos, typename Merger> static void visit_inner(Pos&& p, Merger& merger) { merger.merge_inner(p); } template <typename Pos, typename Merger> static void visit_leaf(Pos&& p, Merger& merger) { merger.merge_leaf(p); } }; struct concat_rebalance_plan_fill_visitor : visitor_base<concat_rebalance_plan_fill_visitor> { using this_t = concat_rebalance_plan_fill_visitor; template <typename Pos, typename Plan> static void visit_node(Pos&& p, Plan& plan) { auto count = p.count(); assert(plan.n < Plan::max_children); plan.counts[plan.n++] = count; plan.total += count; } }; template <bits_t B, bits_t BL> struct concat_rebalance_plan { static constexpr auto max_children = 2 * branches<B> + 1; count_t counts[max_children]; count_t n = 0u; count_t total = 0u; template <typename LPos, typename CPos, typename RPos> void fill(LPos&& lpos, CPos&& cpos, RPos&& rpos) { assert(n == 0u); assert(total == 0u); using visitor_t = concat_rebalance_plan_fill_visitor; lpos.each_left_sub(visitor_t{}, *this); cpos.each_sub(visitor_t{}, *this); rpos.each_right_sub(visitor_t{}, *this); } void shuffle(shift_t shift) { // gcc seems to not really understand this code... :( #if !defined(_MSC_VER) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" #endif constexpr count_t rrb_extras = 2; constexpr count_t rrb_invariant = 1; const auto bits = shift == BL ? BL : B; const auto branches = count_t{1} << bits; const auto optimal = ((total - 1) >> bits) + 1; count_t i = 0; while (n >= optimal + rrb_extras) { // skip ok nodes while (counts[i] > branches - rrb_invariant) i++; // short node, redistribute auto remaining = counts[i]; do { auto count = std::min(remaining + counts[i + 1], branches); counts[i] = count; remaining += counts[i + 1] - count; ++i; } while (remaining > 0); // remove node std::move(counts + i + 1, counts + n, counts + i); --n; --i; } #if !defined(_MSC_VER) #pragma GCC diagnostic pop #endif } template <typename LPos, typename CPos, typename RPos> concat_center_pos<node_type<CPos>> merge(LPos&& lpos, CPos&& cpos, RPos&& rpos) { using node_t = node_type<CPos>; using merger_t = concat_merger<node_t>; using visitor_t = concat_merger_visitor; auto merger = merger_t{cpos.shift(), counts, n}; try { lpos.each_left_sub(visitor_t{}, merger); cpos.each_sub(visitor_t{}, merger); rpos.each_right_sub(visitor_t{}, merger); cpos.each_sub(dec_visitor{}); return merger.finish(); } catch (...) { merger.abort(); throw; } } }; template <typename Node, typename LPos, typename CPos, typename RPos> concat_center_pos<Node> concat_rebalance(LPos&& lpos, CPos&& cpos, RPos&& rpos) { auto plan = concat_rebalance_plan<Node::bits, Node::bits_leaf>{}; plan.fill(lpos, cpos, rpos); plan.shuffle(cpos.shift()); try { return plan.merge(lpos, cpos, rpos); } catch (...) { cpos.each_sub(dec_visitor{}); throw; } } template <typename Node, typename LPos, typename TPos, typename RPos> concat_center_pos<Node> concat_leafs(LPos&& lpos, TPos&& tpos, RPos&& rpos) { static_assert(Node::bits >= 2, ""); assert(lpos.shift() == tpos.shift()); assert(lpos.shift() == rpos.shift()); assert(lpos.shift() == 0); if (tpos.count() > 0) return { Node::bits_leaf, lpos.node()->inc(), lpos.count(), tpos.node()->inc(), tpos.count(), rpos.node()->inc(), rpos.count(), }; else return { Node::bits_leaf, lpos.node()->inc(), lpos.count(), rpos.node()->inc(), rpos.count(), }; } template <typename Node> struct concat_left_visitor; template <typename Node> struct concat_right_visitor; template <typename Node> struct concat_both_visitor; template <typename Node, typename LPos, typename TPos, typename RPos> concat_center_pos<Node> concat_inners(LPos&& lpos, TPos&& tpos, RPos&& rpos) { auto lshift = lpos.shift(); auto rshift = rpos.shift(); if (lshift > rshift) { auto cpos = lpos.last_sub(concat_left_visitor<Node>{}, tpos, rpos); return concat_rebalance<Node>(lpos, cpos, null_sub_pos{}); } else if (lshift < rshift) { auto cpos = rpos.first_sub(concat_right_visitor<Node>{}, lpos, tpos); return concat_rebalance<Node>(null_sub_pos{}, cpos, rpos); } else { assert(lshift == rshift); assert(Node::bits_leaf == 0u || lshift > 0); auto cpos = lpos.last_sub(concat_both_visitor<Node>{}, tpos, rpos); return concat_rebalance<Node>(lpos, cpos, rpos); } } template <typename Node> struct concat_left_visitor : visitor_base<concat_left_visitor<Node>> { using this_t = concat_left_visitor; template <typename LPos, typename TPos, typename RPos> static concat_center_pos<Node> visit_inner(LPos&& lpos, TPos&& tpos, RPos&& rpos) { return concat_inners<Node>(lpos, tpos, rpos); } template <typename LPos, typename TPos, typename RPos> static concat_center_pos<Node> visit_leaf(LPos&& lpos, TPos&& tpos, RPos&& rpos) { IMMER_UNREACHABLE; } }; template <typename Node> struct concat_right_visitor : visitor_base<concat_right_visitor<Node>> { using this_t = concat_right_visitor; template <typename RPos, typename LPos, typename TPos> static concat_center_pos<Node> visit_inner(RPos&& rpos, LPos&& lpos, TPos&& tpos) { return concat_inners<Node>(lpos, tpos, rpos); } template <typename RPos, typename LPos, typename TPos> static concat_center_pos<Node> visit_leaf(RPos&& rpos, LPos&& lpos, TPos&& tpos) { return concat_leafs<Node>(lpos, tpos, rpos); } }; template <typename Node> struct concat_both_visitor : visitor_base<concat_both_visitor<Node>> { using this_t = concat_both_visitor; template <typename LPos, typename TPos, typename RPos> static concat_center_pos<Node> visit_inner(LPos&& lpos, TPos&& tpos, RPos&& rpos) { return rpos.first_sub(concat_right_visitor<Node>{}, lpos, tpos); } template <typename LPos, typename TPos, typename RPos> static concat_center_pos<Node> visit_leaf(LPos&& lpos, TPos&& tpos, RPos&& rpos) { return rpos.first_sub_leaf(concat_right_visitor<Node>{}, lpos, tpos); } }; template <typename Node> struct concat_trees_right_visitor : visitor_base<concat_trees_right_visitor<Node>> { using this_t = concat_trees_right_visitor; template <typename RPos, typename LPos, typename TPos> static concat_center_pos<Node> visit_node(RPos&& rpos, LPos&& lpos, TPos&& tpos) { return concat_inners<Node>(lpos, tpos, rpos); } }; template <typename Node> struct concat_trees_left_visitor : visitor_base<concat_trees_left_visitor<Node>> { using this_t = concat_trees_left_visitor; template <typename LPos, typename TPos, typename... Args> static concat_center_pos<Node> visit_node(LPos&& lpos, TPos&& tpos, Args&&... args) { return visit_maybe_relaxed_sub( args..., concat_trees_right_visitor<Node>{}, lpos, tpos); } }; template <typename Node> relaxed_pos<Node> concat_trees(Node* lroot, shift_t lshift, size_t lsize, Node* ltail, count_t ltcount, Node* rroot, shift_t rshift, size_t rsize) { return visit_maybe_relaxed_sub(lroot, lshift, lsize, concat_trees_left_visitor<Node>{}, make_leaf_pos(ltail, ltcount), rroot, rshift, rsize) .realize(); } template <typename Node> relaxed_pos<Node> concat_trees( Node* ltail, count_t ltcount, Node* rroot, shift_t rshift, size_t rsize) { return make_singleton_regular_sub_pos(ltail, ltcount) .visit(concat_trees_left_visitor<Node>{}, empty_leaf_pos<Node>{}, rroot, rshift, rsize) .realize(); } template <typename Node> using concat_center_mut_pos = concat_center_pos<Node>; template <typename Node> struct concat_merger_mut { using node_t = Node; using edit_t = typename Node::edit_t; static constexpr auto B = Node::bits; static constexpr auto BL = Node::bits_leaf; using result_t = concat_center_pos<Node>; edit_t ec_ = {}; count_t* curr_; count_t n_; result_t result_; count_t count_ = 0; node_t* candidate_ = nullptr; edit_t candidate_e_ = Node::memory::transience_t::noone; concat_merger_mut(edit_t ec, shift_t shift, count_t* counts, count_t n, edit_t candidate_e, node_t* candidate) : ec_{ec} , curr_{counts} , n_{n} , result_{shift + B, nullptr, 0} { if (candidate) { candidate->ensure_mutable_relaxed_e(candidate_e, ec); result_.nodes_[0] = candidate; } else { result_.nodes_[0] = node_t::make_inner_r_e(ec); } } node_t* to_ = {}; count_t to_offset_ = {}; size_t to_size_ = {}; void set_candidate(edit_t candidate_e, node_t* candidate) { candidate_ = candidate; candidate_e_ = candidate_e; } void add_child(node_t* p, size_t size) { ++curr_; auto parent = result_.nodes_[result_.count_ - 1]; auto relaxed = parent->relaxed(); if (count_ == branches<B>) { parent->relaxed()->d.count = count_; assert(result_.count_ < result_t::max_children); n_ -= branches<B>; if (candidate_) { parent = candidate_; parent->ensure_mutable_relaxed_e(candidate_e_, ec_); candidate_ = nullptr; } else parent = node_t::make_inner_r_e(ec_); count_ = 0; relaxed = parent->relaxed(); result_.nodes_[result_.count_] = parent; result_.sizes_[result_.count_] = result_.sizes_[result_.count_ - 1]; ++result_.count_; } auto idx = count_++; result_.sizes_[result_.count_ - 1] += size; relaxed->d.sizes[idx] = size + (idx ? relaxed->d.sizes[idx - 1] : 0); parent->inner()[idx] = p; }; template <typename Pos> void merge_leaf(Pos&& p, edit_t e) { auto from = p.node(); auto from_size = p.size(); auto from_count = p.count(); assert(from_size); if (!to_ && *curr_ == from_count) { add_child(from, from_size); } else { auto from_offset = count_t{}; auto from_data = from->leaf(); auto from_mutate = from->can_mutate(e); do { if (!to_) { if (from_mutate) { node_t::ownee(from) = ec_; to_ = from->inc(); assert(from_count); } else { to_ = node_t::make_leaf_e(ec_); } to_offset_ = 0; } auto data = to_->leaf(); auto to_copy = std::min(from_count - from_offset, *curr_ - to_offset_); if (from == to_) { if (from_offset != to_offset_) std::move(from_data + from_offset, from_data + from_offset + to_copy, data + to_offset_); } else { if (!from_mutate) std::uninitialized_copy(from_data + from_offset, from_data + from_offset + to_copy, data + to_offset_); else detail::uninitialized_move(from_data + from_offset, from_data + from_offset + to_copy, data + to_offset_); } to_offset_ += to_copy; from_offset += to_copy; if (*curr_ == to_offset_) { add_child(to_, to_offset_); to_ = nullptr; } } while (from_offset != from_count); } } template <typename Pos> void merge_inner(Pos&& p, edit_t e) { auto from = p.node(); auto from_size = p.size(); auto from_count = p.count(); assert(from_size); if (!to_ && *curr_ == from_count) { add_child(from, from_size); } else { auto from_offset = count_t{}; auto from_data = from->inner(); auto from_mutate = from->can_relax() && from->can_mutate(e); do { if (!to_) { if (from_mutate) { node_t::ownee(from) = ec_; from->ensure_mutable_relaxed_e(e, ec_); to_ = from; } else { to_ = node_t::make_inner_r_e(ec_); } to_offset_ = 0; to_size_ = 0; } auto data = to_->inner(); auto to_copy = std::min(from_count - from_offset, *curr_ - to_offset_); auto sizes = to_->relaxed()->d.sizes; if (from != to_ || from_offset != to_offset_) { std::copy(from_data + from_offset, from_data + from_offset + to_copy, data + to_offset_); p.copy_sizes( from_offset, to_copy, to_size_, sizes + to_offset_); } to_offset_ += to_copy; from_offset += to_copy; to_size_ = sizes[to_offset_ - 1]; if (*curr_ == to_offset_) { to_->relaxed()->d.count = to_offset_; add_child(to_, to_size_); to_ = nullptr; } } while (from_offset != from_count); } } concat_center_pos<Node> finish() const { assert(!to_); result_.nodes_[result_.count_ - 1]->relaxed()->d.count = count_; return result_; } void abort() { // We may have mutated stuff the tree in place, leaving // everything in a corrupted state... It should be possible // to define cleanup properly, but that is a task for some // other day... ;) std::terminate(); } }; struct concat_merger_mut_visitor : visitor_base<concat_merger_mut_visitor> { using this_t = concat_merger_mut_visitor; template <typename Pos, typename Merger> static void visit_inner(Pos&& p, Merger& merger, edit_type<Pos> e) { merger.merge_inner(p, e); } template <typename Pos, typename Merger> static void visit_leaf(Pos&& p, Merger& merger, edit_type<Pos> e) { merger.merge_leaf(p, e); } }; template <bits_t B, bits_t BL> struct concat_rebalance_plan_mut : concat_rebalance_plan<B, BL> { using this_t = concat_rebalance_plan_mut; template <typename LPos, typename CPos, typename RPos> concat_center_mut_pos<node_type<CPos>> merge(edit_type<CPos> ec, edit_type<CPos> el, LPos&& lpos, CPos&& cpos, edit_type<CPos> er, RPos&& rpos) { using node_t = node_type<CPos>; using merger_t = concat_merger_mut<node_t>; using visitor_t = concat_merger_mut_visitor; auto lnode = ((node_t*) lpos.node()); auto rnode = ((node_t*) rpos.node()); auto lmut2 = lnode && lnode->can_relax() && lnode->can_mutate(el); auto rmut2 = rnode && rnode->can_relax() && rnode->can_mutate(er); auto merger = merger_t{ec, cpos.shift(), this->counts, this->n, el, lmut2 ? lnode : nullptr}; try { lpos.each_left_sub(visitor_t{}, merger, el); cpos.each_sub(visitor_t{}, merger, ec); if (rmut2) merger.set_candidate(er, rnode); rpos.each_right_sub(visitor_t{}, merger, er); return merger.finish(); } catch (...) { merger.abort(); throw; } } }; template <typename Node, typename LPos, typename CPos, typename RPos> concat_center_pos<Node> concat_rebalance_mut(edit_type<Node> ec, edit_type<Node> el, LPos&& lpos, CPos&& cpos, edit_type<Node> er, RPos&& rpos) { auto plan = concat_rebalance_plan_mut<Node::bits, Node::bits_leaf>{}; plan.fill(lpos, cpos, rpos); plan.shuffle(cpos.shift()); return plan.merge(ec, el, lpos, cpos, er, rpos); } template <typename Node, typename LPos, typename TPos, typename RPos> concat_center_mut_pos<Node> concat_leafs_mut(edit_type<Node> ec, edit_type<Node> el, LPos&& lpos, TPos&& tpos, edit_type<Node> er, RPos&& rpos) { static_assert(Node::bits >= 2, ""); assert(lpos.shift() == tpos.shift()); assert(lpos.shift() == rpos.shift()); assert(lpos.shift() == 0); if (tpos.count() > 0) return { Node::bits_leaf, lpos.node(), lpos.count(), tpos.node(), tpos.count(), rpos.node(), rpos.count(), }; else return { Node::bits_leaf, lpos.node(), lpos.count(), rpos.node(), rpos.count(), }; } template <typename Node> struct concat_left_mut_visitor; template <typename Node> struct concat_right_mut_visitor; template <typename Node> struct concat_both_mut_visitor; template <typename Node, typename LPos, typename TPos, typename RPos> concat_center_mut_pos<Node> concat_inners_mut(edit_type<Node> ec, edit_type<Node> el, LPos&& lpos, TPos&& tpos, edit_type<Node> er, RPos&& rpos) { auto lshift = lpos.shift(); auto rshift = rpos.shift(); // lpos.node() can be null it is a singleton_regular_sub_pos<...>, // this is, when the tree is just a tail... if (lshift > rshift) { auto cpos = lpos.last_sub( concat_left_mut_visitor<Node>{}, ec, el, tpos, er, rpos); return concat_rebalance_mut<Node>( ec, el, lpos, cpos, er, null_sub_pos{}); } else if (lshift < rshift) { auto cpos = rpos.first_sub( concat_right_mut_visitor<Node>{}, ec, el, lpos, tpos, er); return concat_rebalance_mut<Node>( ec, el, null_sub_pos{}, cpos, er, rpos); } else { assert(lshift == rshift); assert(Node::bits_leaf == 0u || lshift > 0); auto cpos = lpos.last_sub( concat_both_mut_visitor<Node>{}, ec, el, tpos, er, rpos); return concat_rebalance_mut<Node>(ec, el, lpos, cpos, er, rpos); } } template <typename Node> struct concat_left_mut_visitor : visitor_base<concat_left_mut_visitor<Node>> { using this_t = concat_left_mut_visitor; using edit_t = typename Node::edit_t; template <typename LPos, typename TPos, typename RPos> static concat_center_mut_pos<Node> visit_inner( LPos&& lpos, edit_t ec, edit_t el, TPos&& tpos, edit_t er, RPos&& rpos) { return concat_inners_mut<Node>(ec, el, lpos, tpos, er, rpos); } template <typename LPos, typename TPos, typename RPos> static concat_center_mut_pos<Node> visit_leaf( LPos&& lpos, edit_t ec, edit_t el, TPos&& tpos, edit_t er, RPos&& rpos) { IMMER_UNREACHABLE; } }; template <typename Node> struct concat_right_mut_visitor : visitor_base<concat_right_mut_visitor<Node>> { using this_t = concat_right_mut_visitor; using edit_t = typename Node::edit_t; template <typename RPos, typename LPos, typename TPos> static concat_center_mut_pos<Node> visit_inner( RPos&& rpos, edit_t ec, edit_t el, LPos&& lpos, TPos&& tpos, edit_t er) { return concat_inners_mut<Node>(ec, el, lpos, tpos, er, rpos); } template <typename RPos, typename LPos, typename TPos> static concat_center_mut_pos<Node> visit_leaf( RPos&& rpos, edit_t ec, edit_t el, LPos&& lpos, TPos&& tpos, edit_t er) { return concat_leafs_mut<Node>(ec, el, lpos, tpos, er, rpos); } }; template <typename Node> struct concat_both_mut_visitor : visitor_base<concat_both_mut_visitor<Node>> { using this_t = concat_both_mut_visitor; using edit_t = typename Node::edit_t; template <typename LPos, typename TPos, typename RPos> static concat_center_mut_pos<Node> visit_inner( LPos&& lpos, edit_t ec, edit_t el, TPos&& tpos, edit_t er, RPos&& rpos) { return rpos.first_sub( concat_right_mut_visitor<Node>{}, ec, el, lpos, tpos, er); } template <typename LPos, typename TPos, typename RPos> static concat_center_mut_pos<Node> visit_leaf( LPos&& lpos, edit_t ec, edit_t el, TPos&& tpos, edit_t er, RPos&& rpos) { return rpos.first_sub_leaf( concat_right_mut_visitor<Node>{}, ec, el, lpos, tpos, er); } }; template <typename Node> struct concat_trees_right_mut_visitor : visitor_base<concat_trees_right_mut_visitor<Node>> { using this_t = concat_trees_right_mut_visitor; using edit_t = typename Node::edit_t; template <typename RPos, typename LPos, typename TPos> static concat_center_mut_pos<Node> visit_node( RPos&& rpos, edit_t ec, edit_t el, LPos&& lpos, TPos&& tpos, edit_t er) { return concat_inners_mut<Node>(ec, el, lpos, tpos, er, rpos); } }; template <typename Node> struct concat_trees_left_mut_visitor : visitor_base<concat_trees_left_mut_visitor<Node>> { using this_t = concat_trees_left_mut_visitor; using edit_t = typename Node::edit_t; template <typename LPos, typename TPos, typename... Args> static concat_center_mut_pos<Node> visit_node(LPos&& lpos, edit_t ec, edit_t el, TPos&& tpos, edit_t er, Args&&... args) { return visit_maybe_relaxed_sub(args..., concat_trees_right_mut_visitor<Node>{}, ec, el, lpos, tpos, er); } }; template <typename Node> relaxed_pos<Node> concat_trees_mut(edit_type<Node> ec, edit_type<Node> el, Node* lroot, shift_t lshift, size_t lsize, Node* ltail, count_t ltcount, edit_type<Node> er, Node* rroot, shift_t rshift, size_t rsize) { return visit_maybe_relaxed_sub(lroot, lshift, lsize, concat_trees_left_mut_visitor<Node>{}, ec, el, make_leaf_pos(ltail, ltcount), er, rroot, rshift, rsize) .realize_e(ec); } template <typename Node> relaxed_pos<Node> concat_trees_mut(edit_type<Node> ec, edit_type<Node> el, Node* ltail, count_t ltcount, edit_type<Node> er, Node* rroot, shift_t rshift, size_t rsize) { return make_singleton_regular_sub_pos(ltail, ltcount) .visit(concat_trees_left_mut_visitor<Node>{}, ec, el, empty_leaf_pos<Node>{}, er, rroot, rshift, rsize) .realize_e(ec); } } // namespace rbts } // namespace detail } // namespace immer
// 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 "runtime/plan_fragment_executor.h" #include <thrift/protocol/TDebugProtocol.h> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/unordered_map.hpp> #include <boost/foreach.hpp> #include "codegen/llvm_codegen.h" #include "common/logging.h" #include "common/object_pool.h" #include "exec/data_sink.h" #include "exec/exec_node.h" #include "exec/exchange_node.h" #include "exec/scan_node.h" #include "exprs/expr.h" #include "runtime/exec_env.h" #include "runtime/descriptors.h" #include "runtime/data_stream_mgr.h" #include "runtime/result_buffer_mgr.h" #include "runtime/result_queue_mgr.h" #include "runtime/row_batch.h" #include "runtime/mem_tracker.h" #include "util/cpu_info.h" #include "util/uid_util.h" #include "util/container_util.hpp" #include "util/parse_util.h" #include "util/pretty_printer.h" #include "util/mem_info.h" namespace doris { PlanFragmentExecutor::PlanFragmentExecutor( ExecEnv* exec_env, const report_status_callback& report_status_cb) : _exec_env(exec_env), _report_status_cb(report_status_cb), _report_thread_active(false), _done(false), _prepared(false), _closed(false), _has_thread_token(false), _is_report_success(true), _is_report_on_cancel(true), _collect_query_statistics_with_every_batch(false) { } PlanFragmentExecutor::~PlanFragmentExecutor() { // if (_prepared) { close(); // } // at this point, the report thread should have been stopped DCHECK(!_report_thread_active); } Status PlanFragmentExecutor::prepare(const TExecPlanFragmentParams& request) { const TPlanFragmentExecParams& params = request.params; _query_id = params.query_id; LOG(INFO) << "Prepare(): query_id=" << print_id(_query_id) << " fragment_instance_id=" << print_id(params.fragment_instance_id) << " backend_num=" << request.backend_num; // VLOG(2) << "request:\n" << apache::thrift::ThriftDebugString(request); _runtime_state.reset(new RuntimeState( request, request.query_options, request.query_globals, _exec_env)); RETURN_IF_ERROR(_runtime_state->init_mem_trackers(_query_id)); _runtime_state->set_be_number(request.backend_num); if (request.__isset.import_label) { _runtime_state->set_import_label(request.import_label); } if (request.__isset.db_name) { _runtime_state->set_db_name(request.db_name); } if (request.__isset.load_job_id) { _runtime_state->set_load_job_id(request.load_job_id); } if (request.__isset.load_error_hub_info) { _runtime_state->set_load_error_hub_info(request.load_error_hub_info); } if (request.query_options.__isset.is_report_success) { _is_report_success = request.query_options.is_report_success; } // Reserve one main thread from the pool _runtime_state->resource_pool()->acquire_thread_token(); _has_thread_token = true; _average_thread_tokens = profile()->add_sampling_counter( "AverageThreadTokens", boost::bind<int64_t>(boost::mem_fn( &ThreadResourceMgr::ResourcePool::num_threads), _runtime_state->resource_pool())); // if (_exec_env->process_mem_tracker() != NULL) { // // we have a global limit // _runtime_state->mem_trackers()->push_back(_exec_env->process_mem_tracker()); // } if (request.query_options.mem_limit > 0) { // we have a per-query limit int64_t bytes_limit = request.query_options.mem_limit; // NOTE: this MemTracker only for olap _mem_tracker.reset( new MemTracker(bytes_limit, "fragment mem-limit", _exec_env->process_mem_tracker())); _runtime_state->set_fragment_mem_tracker(_mem_tracker.get()); if (bytes_limit > MemInfo::physical_mem()) { LOG(WARNING) << "Memory limit " << PrettyPrinter::print(bytes_limit, TUnit::BYTES) << " exceeds physical memory of " << PrettyPrinter::print(MemInfo::physical_mem(), TUnit::BYTES); } LOG(INFO) << "Using query memory limit: " << PrettyPrinter::print(bytes_limit, TUnit::BYTES); } RETURN_IF_ERROR(_runtime_state->create_block_mgr()); // set up desc tbl DescriptorTbl* desc_tbl = NULL; DCHECK(request.__isset.desc_tbl); RETURN_IF_ERROR(DescriptorTbl::create(obj_pool(), request.desc_tbl, &desc_tbl)); _runtime_state->set_desc_tbl(desc_tbl); // set up plan DCHECK(request.__isset.fragment); RETURN_IF_ERROR( ExecNode::create_tree(_runtime_state.get(), obj_pool(), request.fragment.plan, *desc_tbl, &_plan)); _runtime_state->set_fragment_root_id(_plan->id()); if (request.params.__isset.debug_node_id) { DCHECK(request.params.__isset.debug_action); DCHECK(request.params.__isset.debug_phase); ExecNode::set_debug_options( request.params.debug_node_id, request.params.debug_phase, request.params.debug_action, _plan); } // set #senders of exchange nodes before calling Prepare() std::vector<ExecNode*> exch_nodes; _plan->collect_nodes(TPlanNodeType::EXCHANGE_NODE, &exch_nodes); BOOST_FOREACH(ExecNode * exch_node, exch_nodes) { DCHECK_EQ(exch_node->type(), TPlanNodeType::EXCHANGE_NODE); int num_senders = find_with_default(params.per_exch_num_senders, exch_node->id(), 0); DCHECK_GT(num_senders, 0); static_cast<ExchangeNode*>(exch_node)->set_num_senders(num_senders); } RETURN_IF_ERROR(_plan->prepare(_runtime_state.get())); // set scan ranges std::vector<ExecNode*> scan_nodes; std::vector<TScanRangeParams> no_scan_ranges; _plan->collect_scan_nodes(&scan_nodes); VLOG(1) << "scan_nodes.size()=" << scan_nodes.size(); VLOG(1) << "params.per_node_scan_ranges.size()=" << params.per_node_scan_ranges.size(); _plan->try_do_aggregate_serde_improve(); for (int i = 0; i < scan_nodes.size(); ++i) { ScanNode* scan_node = static_cast<ScanNode*>(scan_nodes[i]); const std::vector<TScanRangeParams>& scan_ranges = find_with_default(params.per_node_scan_ranges, scan_node->id(), no_scan_ranges); scan_node->set_scan_ranges(scan_ranges); VLOG(1) << "scan_node_Id=" << scan_node->id() << " size=" << scan_ranges.size(); } print_volume_ids(params.per_node_scan_ranges); _runtime_state->set_per_fragment_instance_idx(params.sender_id); _runtime_state->set_num_per_fragment_instances(params.num_senders); // set up sink, if required if (request.fragment.__isset.output_sink) { RETURN_IF_ERROR(DataSink::create_data_sink(obj_pool(), request.fragment.output_sink, request.fragment.output_exprs, params, row_desc(), &_sink)); RETURN_IF_ERROR(_sink->prepare(runtime_state())); RuntimeProfile* sink_profile = _sink->profile(); if (sink_profile != NULL) { profile()->add_child(sink_profile, true, NULL); } _collect_query_statistics_with_every_batch = params.__isset.send_query_statistics_with_every_batch ? params.send_query_statistics_with_every_batch : false; } else { _sink.reset(NULL); } // set up profile counters profile()->add_child(_plan->runtime_profile(), true, NULL); _rows_produced_counter = ADD_COUNTER(profile(), "RowsProduced", TUnit::UNIT); #if 0 // After preparing the plan and initializing the output sink, all functions should // have been code-generated. At this point we optimize all the functions. if (_runtime_state->llvm_codegen() != NULL) { Status status = _runtime_state->llvm_codegen()->optimize_module(); if (!status.ok()) { LOG(ERROR) << "Error with codegen for this query: " << status.get_error_msg(); // TODO: propagate this to the coordinator and user? Not really actionable // for them but we'd like them to let us know. } // If codegen failed, we automatically fall back to not using codegen. } #endif _row_batch.reset(new RowBatch( _plan->row_desc(), _runtime_state->batch_size(), _runtime_state->instance_mem_tracker())); // _row_batch->tuple_data_pool()->set_limits(*_runtime_state->mem_trackers()); VLOG(3) << "plan_root=\n" << _plan->debug_string(); _prepared = true; _query_statistics.reset(new QueryStatistics()); _sink->set_query_statistics(_query_statistics); return Status::OK(); } void PlanFragmentExecutor::optimize_llvm_module() { if (!_runtime_state->codegen_created()) { return; } LlvmCodeGen* codegen = NULL; Status status = _runtime_state->get_codegen(&codegen, /* initalize */ false); DCHECK(status.ok()); DCHECK(codegen != NULL); status = codegen->finalize_module(); if (!status.ok()) { std::stringstream ss; ss << "Error with codegen for this query: "; _runtime_state->log_error(status.get_error_msg()); } } void PlanFragmentExecutor::print_volume_ids( const PerNodeScanRanges& per_node_scan_ranges) { if (per_node_scan_ranges.empty()) { return; } } Status PlanFragmentExecutor::open() { LOG(INFO) << "Open(): fragment_instance_id=" << print_id(_runtime_state->fragment_instance_id()); // we need to start the profile-reporting thread before calling Open(), since it // may block // TODO: if no report thread is started, make sure to send a final profile // at end, otherwise the coordinator hangs in case we finish w/ an error if (!_report_status_cb.empty() && config::status_report_interval > 0) { boost::unique_lock<boost::mutex> l(_report_thread_lock); _report_thread = boost::thread(&PlanFragmentExecutor::report_profile, this); // make sure the thread started up, otherwise report_profile() might get into a race // with stop_report_thread() _report_thread_started_cv.wait(l); _report_thread_active = true; } optimize_llvm_module(); Status status = open_internal(); if (!status.ok() && !status.is_cancelled() && _runtime_state->log_has_space()) { // Log error message in addition to returning in Status. Queries that do not // fetch results (e.g. insert) may not receive the message directly and can // only retrieve the log. _runtime_state->log_error(status.get_error_msg()); } update_status(status); return status; } Status PlanFragmentExecutor::open_internal() { { SCOPED_TIMER(profile()->total_time_counter()); RETURN_IF_ERROR(_plan->open(_runtime_state.get())); } if (_sink.get() == NULL) { return Status::OK(); } RETURN_IF_ERROR(_sink->open(runtime_state())); // If there is a sink, do all the work of driving it here, so that // when this returns the query has actually finished RowBatch* batch = NULL; while (true) { RETURN_IF_ERROR(get_next_internal(&batch)); if (batch == NULL) { break; } if (VLOG_ROW_IS_ON) { VLOG_ROW << "open_internal: #rows=" << batch->num_rows() << " desc=" << row_desc().debug_string(); for (int i = 0; i < batch->num_rows(); ++i) { TupleRow* row = batch->get_row(i); VLOG_ROW << row->to_string(row_desc()); } } SCOPED_TIMER(profile()->total_time_counter()); // Collect this plan and sub plan statisticss, and send to parent plan. if (_collect_query_statistics_with_every_batch) { collect_query_statistics(); } RETURN_IF_ERROR(_sink->send(runtime_state(), batch)); } // Close the sink *before* stopping the report thread. Close may // need to add some important information to the last report that // gets sent. (e.g. table sinks record the files they have written // to in this method) // The coordinator report channel waits until all backends are // either in error or have returned a status report with done = // true, so tearing down any data stream state (a separate // channel) in Close is safe. // TODO: If this returns an error, the d'tor will call Close again. We should // audit the sinks to check that this is ok, or change that behaviour. { SCOPED_TIMER(profile()->total_time_counter()); collect_query_statistics(); Status status = _sink->close(runtime_state(), _status); RETURN_IF_ERROR(status); } // Setting to NULL ensures that the d'tor won't double-close the sink. _sink.reset(NULL); _done = true; release_thread_token(); stop_report_thread(); send_report(true); return Status::OK(); } void PlanFragmentExecutor::collect_query_statistics() { _query_statistics->clear(); _plan->collect_query_statistics(_query_statistics.get()); } void PlanFragmentExecutor::report_profile() { VLOG_FILE << "report_profile(): instance_id=" << _runtime_state->fragment_instance_id(); DCHECK(!_report_status_cb.empty()); boost::unique_lock<boost::mutex> l(_report_thread_lock); // tell Open() that we started _report_thread_started_cv.notify_one(); // Jitter the reporting time of remote fragments by a random amount between // 0 and the report_interval. This way, the coordinator doesn't get all the // updates at once so its better for contention as well as smoother progress // reporting. int report_fragment_offset = rand() % config::status_report_interval; boost::system_time timeout = boost::get_system_time() + boost::posix_time::seconds(report_fragment_offset); // We don't want to wait longer than it takes to run the entire fragment. _stop_report_thread_cv.timed_wait(l, timeout); bool is_report_profile_interval = _is_report_success && config::status_report_interval > 0; while (_report_thread_active) { if (is_report_profile_interval) { boost::system_time timeout = boost::get_system_time() + boost::posix_time::seconds(config::status_report_interval); // timed_wait can return because the timeout occurred or the condition variable // was signaled. We can't rely on its return value to distinguish between the // two cases (e.g. there is a race here where the wait timed out but before grabbing // the lock, the condition variable was signaled). Instead, we will use an external // flag, _report_thread_active, to coordinate this. _stop_report_thread_cv.timed_wait(l, timeout); } else { // Artificial triggering, such as show proc "/current_queries". _stop_report_thread_cv.wait(l); } if (VLOG_FILE_IS_ON) { VLOG_FILE << "Reporting " << (!_report_thread_active ? "final " : " ") << "profile for instance " << _runtime_state->fragment_instance_id(); std::stringstream ss; profile()->pretty_print(&ss); VLOG_FILE << ss.str(); } if (!_report_thread_active) { break; } send_report(false); } VLOG_FILE << "exiting reporting thread: instance_id=" << _runtime_state->fragment_instance_id(); } void PlanFragmentExecutor::send_report(bool done) { if (_report_status_cb.empty()) { return; } Status status; { boost::lock_guard<boost::mutex> l(_status_lock); status = _status; } // If plan is done successfully, but _is_report_success is false, // no need to send report. if (!_is_report_success && done && status.ok()) { return; } // If both _is_report_success and _is_report_on_cancel are false, // which means no matter query is success or failed, no report is needed. // This may happen when the query limit reached and // a internal cancellation being processed if (!_is_report_success && !_is_report_on_cancel) { return; } // This will send a report even if we are cancelled. If the query completed correctly // but fragments still need to be cancelled (e.g. limit reached), the coordinator will // be waiting for a final report and profile. _report_status_cb(status, profile(), done || !status.ok()); } void PlanFragmentExecutor::stop_report_thread() { if (!_report_thread_active) { return; } { boost::lock_guard<boost::mutex> l(_report_thread_lock); _report_thread_active = false; } _stop_report_thread_cv.notify_one(); _report_thread.join(); } Status PlanFragmentExecutor::get_next(RowBatch** batch) { VLOG_FILE << "GetNext(): instance_id=" << _runtime_state->fragment_instance_id(); Status status = get_next_internal(batch); update_status(status); if (_done) { LOG(INFO) << "Finished executing fragment query_id=" << print_id(_query_id) << " instance_id=" << print_id(_runtime_state->fragment_instance_id()); // Query is done, return the thread token release_thread_token(); stop_report_thread(); send_report(true); } return status; } Status PlanFragmentExecutor::get_next_internal(RowBatch** batch) { if (_done) { *batch = NULL; return Status::OK(); } while (!_done) { _row_batch->reset(); SCOPED_TIMER(profile()->total_time_counter()); RETURN_IF_ERROR(_plan->get_next(_runtime_state.get(), _row_batch.get(), &_done)); if (_row_batch->num_rows() > 0) { COUNTER_UPDATE(_rows_produced_counter, _row_batch->num_rows()); *batch = _row_batch.get(); break; } *batch = NULL; } return Status::OK(); } void PlanFragmentExecutor::update_status(const Status& status) { if (status.ok()) { return; } { boost::lock_guard<boost::mutex> l(_status_lock); if (_status.ok()) { if (status.is_mem_limit_exceeded()) { _runtime_state->set_mem_limit_exceeded(status.get_error_msg()); } _status = status; if (_runtime_state->query_options().query_type == TQueryType::EXTERNAL) { TUniqueId fragment_instance_id = _runtime_state->fragment_instance_id(); _exec_env->result_queue_mgr()->update_queue_status(fragment_instance_id, status); } } } stop_report_thread(); send_report(true); } void PlanFragmentExecutor::cancel() { LOG(INFO) << "cancel(): fragment_instance_id=" << print_id(_runtime_state->fragment_instance_id()); DCHECK(_prepared); _runtime_state->set_is_cancelled(true); _runtime_state->exec_env()->stream_mgr()->cancel(_runtime_state->fragment_instance_id()); _runtime_state->exec_env()->result_mgr()->cancel(_runtime_state->fragment_instance_id()); } const RowDescriptor& PlanFragmentExecutor::row_desc() { return _plan->row_desc(); } RuntimeProfile* PlanFragmentExecutor::profile() { return _runtime_state->runtime_profile(); } void PlanFragmentExecutor::release_thread_token() { if (_has_thread_token) { _has_thread_token = false; _runtime_state->resource_pool()->release_thread_token(true); profile()->stop_sampling_counters_updates(_average_thread_tokens); } } void PlanFragmentExecutor::close() { if (_closed) { return; } _row_batch.reset(NULL); // Prepare may not have been called, which sets _runtime_state if (_runtime_state.get() != NULL) { // _runtime_state init failed if (_plan != nullptr) { _plan->close(_runtime_state.get()); } if (_sink.get() != NULL) { if (_prepared) { _sink->close(runtime_state(), _status); } else { _sink->close(runtime_state(), Status::InternalError("prepare failed")); } } _exec_env->thread_mgr()->unregister_pool(_runtime_state->resource_pool()); { std::stringstream ss; _runtime_state->runtime_profile()->pretty_print(&ss); LOG(INFO) << ss.str(); } } // _mem_tracker init failed if (_mem_tracker.get() != nullptr) { _mem_tracker->release(_mem_tracker->consumption()); } _closed = true; } }
#include <xpp/event.hpp> #include "x11/connection.hpp" #include "x11/extensions/all.hpp" #include "x11/registry.hpp" POLYBAR_NS registry::registry(connection& conn) : xpp::event::registry<connection&, XPP_EXTENSION_LIST>(conn) {} POLYBAR_NS_END
/* * 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/vod/v20180717/model/MediaAnimatedGraphicsItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Vod::V20180717::Model; using namespace std; MediaAnimatedGraphicsItem::MediaAnimatedGraphicsItem() : m_urlHasBeenSet(false), m_definitionHasBeenSet(false), m_containerHasBeenSet(false), m_heightHasBeenSet(false), m_widthHasBeenSet(false), m_bitrateHasBeenSet(false), m_sizeHasBeenSet(false), m_md5HasBeenSet(false), m_startTimeOffsetHasBeenSet(false), m_endTimeOffsetHasBeenSet(false) { } CoreInternalOutcome MediaAnimatedGraphicsItem::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Url") && !value["Url"].IsNull()) { if (!value["Url"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Url` IsString=false incorrectly").SetRequestId(requestId)); } m_url = string(value["Url"].GetString()); m_urlHasBeenSet = true; } if (value.HasMember("Definition") && !value["Definition"].IsNull()) { if (!value["Definition"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Definition` IsInt64=false incorrectly").SetRequestId(requestId)); } m_definition = value["Definition"].GetInt64(); m_definitionHasBeenSet = true; } if (value.HasMember("Container") && !value["Container"].IsNull()) { if (!value["Container"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Container` IsString=false incorrectly").SetRequestId(requestId)); } m_container = string(value["Container"].GetString()); m_containerHasBeenSet = true; } if (value.HasMember("Height") && !value["Height"].IsNull()) { if (!value["Height"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Height` IsInt64=false incorrectly").SetRequestId(requestId)); } m_height = value["Height"].GetInt64(); m_heightHasBeenSet = true; } if (value.HasMember("Width") && !value["Width"].IsNull()) { if (!value["Width"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Width` IsInt64=false incorrectly").SetRequestId(requestId)); } m_width = value["Width"].GetInt64(); m_widthHasBeenSet = true; } if (value.HasMember("Bitrate") && !value["Bitrate"].IsNull()) { if (!value["Bitrate"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Bitrate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_bitrate = value["Bitrate"].GetInt64(); m_bitrateHasBeenSet = true; } if (value.HasMember("Size") && !value["Size"].IsNull()) { if (!value["Size"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Size` IsInt64=false incorrectly").SetRequestId(requestId)); } m_size = value["Size"].GetInt64(); m_sizeHasBeenSet = true; } if (value.HasMember("Md5") && !value["Md5"].IsNull()) { if (!value["Md5"].IsString()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.Md5` IsString=false incorrectly").SetRequestId(requestId)); } m_md5 = string(value["Md5"].GetString()); m_md5HasBeenSet = true; } if (value.HasMember("StartTimeOffset") && !value["StartTimeOffset"].IsNull()) { if (!value["StartTimeOffset"].IsLosslessDouble()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.StartTimeOffset` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_startTimeOffset = value["StartTimeOffset"].GetDouble(); m_startTimeOffsetHasBeenSet = true; } if (value.HasMember("EndTimeOffset") && !value["EndTimeOffset"].IsNull()) { if (!value["EndTimeOffset"].IsLosslessDouble()) { return CoreInternalOutcome(Core::Error("response `MediaAnimatedGraphicsItem.EndTimeOffset` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_endTimeOffset = value["EndTimeOffset"].GetDouble(); m_endTimeOffsetHasBeenSet = true; } return CoreInternalOutcome(true); } void MediaAnimatedGraphicsItem::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_urlHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Url"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_url.c_str(), allocator).Move(), allocator); } if (m_definitionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Definition"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_definition, allocator); } if (m_containerHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Container"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_container.c_str(), allocator).Move(), allocator); } if (m_heightHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Height"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_height, allocator); } if (m_widthHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Width"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_width, allocator); } if (m_bitrateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Bitrate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_bitrate, allocator); } if (m_sizeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Size"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_size, allocator); } if (m_md5HasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Md5"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_md5.c_str(), allocator).Move(), allocator); } if (m_startTimeOffsetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StartTimeOffset"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_startTimeOffset, allocator); } if (m_endTimeOffsetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EndTimeOffset"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_endTimeOffset, allocator); } } string MediaAnimatedGraphicsItem::GetUrl() const { return m_url; } void MediaAnimatedGraphicsItem::SetUrl(const string& _url) { m_url = _url; m_urlHasBeenSet = true; } bool MediaAnimatedGraphicsItem::UrlHasBeenSet() const { return m_urlHasBeenSet; } int64_t MediaAnimatedGraphicsItem::GetDefinition() const { return m_definition; } void MediaAnimatedGraphicsItem::SetDefinition(const int64_t& _definition) { m_definition = _definition; m_definitionHasBeenSet = true; } bool MediaAnimatedGraphicsItem::DefinitionHasBeenSet() const { return m_definitionHasBeenSet; } string MediaAnimatedGraphicsItem::GetContainer() const { return m_container; } void MediaAnimatedGraphicsItem::SetContainer(const string& _container) { m_container = _container; m_containerHasBeenSet = true; } bool MediaAnimatedGraphicsItem::ContainerHasBeenSet() const { return m_containerHasBeenSet; } int64_t MediaAnimatedGraphicsItem::GetHeight() const { return m_height; } void MediaAnimatedGraphicsItem::SetHeight(const int64_t& _height) { m_height = _height; m_heightHasBeenSet = true; } bool MediaAnimatedGraphicsItem::HeightHasBeenSet() const { return m_heightHasBeenSet; } int64_t MediaAnimatedGraphicsItem::GetWidth() const { return m_width; } void MediaAnimatedGraphicsItem::SetWidth(const int64_t& _width) { m_width = _width; m_widthHasBeenSet = true; } bool MediaAnimatedGraphicsItem::WidthHasBeenSet() const { return m_widthHasBeenSet; } int64_t MediaAnimatedGraphicsItem::GetBitrate() const { return m_bitrate; } void MediaAnimatedGraphicsItem::SetBitrate(const int64_t& _bitrate) { m_bitrate = _bitrate; m_bitrateHasBeenSet = true; } bool MediaAnimatedGraphicsItem::BitrateHasBeenSet() const { return m_bitrateHasBeenSet; } int64_t MediaAnimatedGraphicsItem::GetSize() const { return m_size; } void MediaAnimatedGraphicsItem::SetSize(const int64_t& _size) { m_size = _size; m_sizeHasBeenSet = true; } bool MediaAnimatedGraphicsItem::SizeHasBeenSet() const { return m_sizeHasBeenSet; } string MediaAnimatedGraphicsItem::GetMd5() const { return m_md5; } void MediaAnimatedGraphicsItem::SetMd5(const string& _md5) { m_md5 = _md5; m_md5HasBeenSet = true; } bool MediaAnimatedGraphicsItem::Md5HasBeenSet() const { return m_md5HasBeenSet; } double MediaAnimatedGraphicsItem::GetStartTimeOffset() const { return m_startTimeOffset; } void MediaAnimatedGraphicsItem::SetStartTimeOffset(const double& _startTimeOffset) { m_startTimeOffset = _startTimeOffset; m_startTimeOffsetHasBeenSet = true; } bool MediaAnimatedGraphicsItem::StartTimeOffsetHasBeenSet() const { return m_startTimeOffsetHasBeenSet; } double MediaAnimatedGraphicsItem::GetEndTimeOffset() const { return m_endTimeOffset; } void MediaAnimatedGraphicsItem::SetEndTimeOffset(const double& _endTimeOffset) { m_endTimeOffset = _endTimeOffset; m_endTimeOffsetHasBeenSet = true; } bool MediaAnimatedGraphicsItem::EndTimeOffsetHasBeenSet() const { return m_endTimeOffsetHasBeenSet; }
// Copyright (c) 2017 The Dash Core developers // Copyright (c) 2020 The SEED2NEED Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "tiertwo/specialtx_validation.h" #include "chain.h" #include "chainparams.h" #include "clientversion.h" #include "consensus/validation.h" #include "primitives/block.h" bool CheckSpecialTx(const CTransaction& tx, CValidationState& state, bool fIsSaplingActive) { bool hasExtraPayload = tx.hasExtraPayload(); // Before Sapling activation, the tx has a single 32bit version and no type. // Versions > 1 are not standard, but still accepted. No TX can have extra payload. if (!fIsSaplingActive) { return !hasExtraPayload; } // After Sapling activation. // v1/v2 can only be Type=0 if (!tx.isSaplingVersion() && tx.nType != CTransaction::TxType::NORMAL) { return state.DoS(100, error("%s: Type %d not supported with version %d", __func__, tx.nType, tx.nVersion), REJECT_INVALID, "bad-txns-type-version"); } if (tx.nType == CTransaction::TxType::NORMAL) { // Type-0 txes don't have extra payload if (hasExtraPayload) { return state.DoS(100, error("%s: Type 0 doesn't support extra payload", __func__), REJECT_INVALID, "bad-txns-type-payload"); } // Normal transaction. Nothing to check return true; } // --- From here on, tx has nVersion>=2 and nType!=0 // Special txes must have a non-empty payload if (!hasExtraPayload) { return state.DoS(100, error("%s: Special tx (type=%d) without extra payload", __func__, tx.nType), REJECT_INVALID, "bad-txns-payload-empty"); } // Size limits if (tx.extraPayload->size() > MAX_SPECIALTX_EXTRAPAYLOAD) { return state.DoS(100, error("%s: Special tx payload oversize (%d)", __func__, tx.extraPayload->size()), REJECT_INVALID, "bad-txns-payload-oversize"); } switch (tx.nType) { /* per-tx-type checking */ } return state.DoS(10, error("%s : special tx %s with invalid type %d", __func__, tx.GetHash().ToString(), tx.nType), REJECT_INVALID, "bad-tx-type"); } bool ProcessSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindexPrev, CValidationState& state) { /* process special txes in batches */ return true; } bool UndoSpecialTxsInBlock(const CBlock& block, const CBlockIndex* pindexPrev) { /* undo special txes in batches */ return true; }
#ifndef BOOST_METAPARSE_V1_FAIL_AT_FIRST_CHAR_EXPECTED_HPP #define BOOST_METAPARSE_V1_FAIL_AT_FIRST_CHAR_EXPECTED_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2015. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/metaparse/v1/impl/void_.hpp> #include <boost/metaparse/v1/accept.hpp> #include <boost/metaparse/v1/reject.hpp> #include <boost/metaparse/v1/is_error.hpp> #include <boost/metaparse/v1/get_position.hpp> #include <boost/metaparse/v1/error/expected_to_fail.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/equal_to.hpp> namespace boost { namespace metaparse { namespace v1 { template <class P> struct fail_at_first_char_expected { private: template <class S, class Pos> struct apply_err : boost::mpl::eval_if< typename boost::mpl::equal_to< Pos, typename get_position<typename P::template apply<S, Pos> >::type >::type, accept<impl::void_, S, Pos>, typename P::template apply<S, Pos> > {}; public: typedef fail_at_first_char_expected type; template <class S, class Pos> struct apply : boost::mpl::eval_if< typename is_error<typename P::template apply<S, Pos> >::type, apply_err<S, Pos>, reject<error::expected_to_fail, Pos> > {}; }; } } } #endif
/* -------------------------------------------------------------------------- * * OpenSim: AbstractTool.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include <OpenSim/Common/XMLDocument.h> #include "AbstractTool.h" #include <OpenSim/Common/IO.h> #include "ForceSet.h" #include "Model.h" #include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h> #include <OpenSim/Simulation/Control/ControlSetController.h> using namespace OpenSim; using namespace SimTK; using namespace std; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Destructor. */ AbstractTool::~AbstractTool() { //if (_toolOwnsModel) // delete _model; } //_____________________________________________________________________________ /** * Default constructor. */ AbstractTool::AbstractTool(): _modelFile(_modelFileProp.getValueStr()), _replaceForceSet(_replaceForceSetProp.getValueBool()), _forceSetFiles(_forceSetFilesProp.getValueStrArray()), _resultsDir(_resultsDirProp.getValueStr()), _outputPrecision(_outputPrecisionProp.getValueInt()), _ti(_tiProp.getValueDbl()), _tf(_tfProp.getValueDbl()), _solveForEquilibriumForAuxiliaryStates(_solveForEquilibriumForAuxiliaryStatesProp.getValueBool()), _maxSteps(_maxStepsProp.getValueInt()), _maxDT(_maxDTProp.getValueDbl()), _minDT(_minDTProp.getValueDbl()), _errorTolerance(_errorToleranceProp.getValueDbl()), _analysisSetProp(PropertyObj("Analyses",AnalysisSet())), _analysisSet((AnalysisSet&)_analysisSetProp.getValueObj()), _controllerSetProp(PropertyObj("Controllers", ControllerSet())), _controllerSet((ControllerSet&)_controllerSetProp.getValueObj()), _toolOwnsModel(true), _externalLoadsFileName(_externalLoadsFileNameProp.getValueStr()) { setNull(); } /** * Construct from file, and an optional GuiModel * * The object is constructed from the root element of the XML document. * The type of object is the tag name of the XML root element. * * @param aFileName File name of the document. */ AbstractTool::AbstractTool(const string &aFileName, bool aUpdateFromXMLNode): Object(aFileName, false), _modelFile(_modelFileProp.getValueStr()), _replaceForceSet(_replaceForceSetProp.getValueBool()), _forceSetFiles(_forceSetFilesProp.getValueStrArray()), _resultsDir(_resultsDirProp.getValueStr()), _outputPrecision(_outputPrecisionProp.getValueInt()), _ti(_tiProp.getValueDbl()), _tf(_tfProp.getValueDbl()), _solveForEquilibriumForAuxiliaryStates(_solveForEquilibriumForAuxiliaryStatesProp.getValueBool()), _maxSteps(_maxStepsProp.getValueInt()), _maxDT(_maxDTProp.getValueDbl()), _minDT(_minDTProp.getValueDbl()), _errorTolerance(_errorToleranceProp.getValueDbl()), _analysisSetProp(PropertyObj("Analyses",AnalysisSet())), _analysisSet((AnalysisSet&)_analysisSetProp.getValueObj()), _controllerSetProp(PropertyObj("Controllers", ControllerSet())), _controllerSet((ControllerSet&)_controllerSetProp.getValueObj()), _toolOwnsModel(true), _externalLoadsFileName(_externalLoadsFileNameProp.getValueStr()) { _analysisSet.setMemoryOwner(false); setNull(); if(aUpdateFromXMLNode) updateFromXMLDocument(); } //_____________________________________________________________________________ /** * Copy constructor. * * Copy constructors for all SimulationTools only copy the non-XML variable * members of the object; that is, the object's DOMnode and XMLDocument * are not copied but set to NULL. The reason for this is that for the * object and all its derived classes to establish the correct connection * to the XML document nodes, the object would need to reconstruct based * on the XML document not the values of the object's member variables. * * There are three proper ways to generate an XML document for a AbstractTool: * * 1) Construction based on XML file (@see AbstractTool(const char *aFileName)). * In this case, the XML document is created by parsing the XML file. * * 2) Construction by AbstractTool(const XMLDocument *aDocument). * This constructor explicitly requests construction based on an * XML document. In this way the proper connection between an object's node * and the corresponding node within the XML document is established. * This constructor is a copy constructor of sorts because all essential * AbstractTool member variables should be held within the XML document. * The advantage of this style of construction is that nodes * within the XML document, such as comments that may not have any * associated AbstractTool member variable, are preserved. * * 3) A call to generateXMLDocument(). * This method generates an XML document for the AbstractTool from scratch. * Only the essential document nodes are created (that is, nodes that * correspond directly to member variables.). * * @param aTool Object to be copied. * @see AbstractTool(const XMLDocument *aDocument) * @see AbstractTool(const char *aFileName) * @see generateXMLDocument() */ AbstractTool::AbstractTool(const AbstractTool &aTool): Object(aTool), _modelFile(_modelFileProp.getValueStr()), _replaceForceSet(_replaceForceSetProp.getValueBool()), _forceSetFiles(_forceSetFilesProp.getValueStrArray()), _resultsDir(_resultsDirProp.getValueStr()), _outputPrecision(_outputPrecisionProp.getValueInt()), _ti(_tiProp.getValueDbl()), _tf(_tfProp.getValueDbl()), _solveForEquilibriumForAuxiliaryStates(_solveForEquilibriumForAuxiliaryStatesProp.getValueBool()), _maxSteps(_maxStepsProp.getValueInt()), _maxDT(_maxDTProp.getValueDbl()), _minDT(_minDTProp.getValueDbl()), _errorTolerance(_errorToleranceProp.getValueDbl()), _analysisSetProp(PropertyObj("Analyses",AnalysisSet())), _analysisSet((AnalysisSet&)_analysisSetProp.getValueObj()), _controllerSetProp(PropertyObj("Controllers", ControllerSet())), _controllerSet((ControllerSet&)_controllerSetProp.getValueObj()), _toolOwnsModel(true), _externalLoadsFileName(_externalLoadsFileNameProp.getValueStr()) { _analysisSet.setMemoryOwner(false); setNull(); *this = aTool; } //_____________________________________________________________________________ /** * Set all member variables to their null or default values. */ void AbstractTool:: setNull() { setupProperties(); _model = NULL; _modelFile = ""; _replaceForceSet = true; _resultsDir = "./"; _outputPrecision = 8; _ti = 0.0; _tf = 1.0; _solveForEquilibriumForAuxiliaryStates = false; _maxSteps = 20000; _maxDT = 1.0; _minDT = 1.0e-8; _errorTolerance = 1.0e-5; _toolOwnsModel=true; _externalLoadsFileName = ""; } //_____________________________________________________________________________ /** * Connect properties to local pointers. */ void AbstractTool::setupProperties() { string comment; comment = "Name of the .osim file used to construct a model."; _modelFileProp.setComment(comment); _modelFileProp.setName("model_file"); _propertySet.append( &_modelFileProp ); comment = "Replace the model's force set with sets specified in <force_set_files>? " "If false, the force set is appended to."; _replaceForceSetProp.setComment(comment); _replaceForceSetProp.setName("replace_force_set"); _propertySet.append( &_replaceForceSetProp ); comment = "List of xml files used to construct a force set for the model."; _forceSetFilesProp.setComment(comment); _forceSetFilesProp.setValue(Array<string>("")); _forceSetFilesProp.setName("force_set_files"); _propertySet.append( &_forceSetFilesProp ); comment = "Directory used for writing results."; _resultsDirProp.setComment(comment); _resultsDirProp.setName("results_directory"); _propertySet.append( &_resultsDirProp ); comment = "Output precision. It is 8 by default."; _outputPrecisionProp.setComment(comment); _outputPrecisionProp.setName("output_precision"); _propertySet.append( &_outputPrecisionProp ); comment = "Initial time for the simulation."; _tiProp.setComment(comment); _tiProp.setName("initial_time"); _propertySet.append( &_tiProp ); comment = "Final time for the simulation."; _tfProp.setComment(comment); _tfProp.setName("final_time"); _propertySet.append( &_tfProp ); comment = "Flag indicating whether or not to compute equilibrium values for states other than the coordinates or speeds. " "For example, equilibrium muscle fiber lengths or muscle forces."; _solveForEquilibriumForAuxiliaryStatesProp.setComment(comment); _solveForEquilibriumForAuxiliaryStatesProp.setName("solve_for_equilibrium_for_auxiliary_states"); _propertySet.append( &_solveForEquilibriumForAuxiliaryStatesProp ); comment = "Maximum number of integrator steps."; _maxStepsProp.setComment(comment); _maxStepsProp.setName("maximum_number_of_integrator_steps"); _propertySet.append( &_maxStepsProp ); comment = "Maximum integration step size."; _maxDTProp.setComment(comment); _maxDTProp.setName("maximum_integrator_step_size"); _propertySet.append( &_maxDTProp ); comment = "Minimum integration step size."; _minDTProp.setComment(comment); _minDTProp.setName("minimum_integrator_step_size"); _propertySet.append( &_minDTProp ); comment = "Integrator error tolerance. When the error is greater, the integrator step size is decreased."; _errorToleranceProp.setComment(comment); _errorToleranceProp.setName("integrator_error_tolerance"); _propertySet.append( &_errorToleranceProp ); comment = "Set of analyses to be run during the investigation."; _analysisSetProp.setComment(comment); _analysisSetProp.setName("Analyses"); _propertySet.append( &_analysisSetProp ); _controllerSetProp.setComment("Controller objects in the model."); _controllerSetProp.setName("ControllerSet"); _propertySet.append(&_controllerSetProp); comment = "XML file (.xml) containing the forces applied to the model as ExternalLoads."; _externalLoadsFileNameProp.setComment(comment); _externalLoadsFileNameProp.setName("external_loads_file"); _propertySet.append( &_externalLoadsFileNameProp ); } //============================================================================= // OPERATORS //============================================================================= //_____________________________________________________________________________ /** * Assignment operator. * * @return Reference to this object. */ AbstractTool& AbstractTool:: operator=(const AbstractTool &aTool) { // BASE CLASS Object::operator=(aTool); // MEMBER VARIABLES _model = aTool._model; _modelFile = aTool._modelFile; _replaceForceSet = aTool._replaceForceSet; _forceSetFiles = aTool._forceSetFiles; _resultsDir = aTool._resultsDir; _outputPrecision = aTool._outputPrecision; _ti = aTool._ti; _tf = aTool._tf; _solveForEquilibriumForAuxiliaryStates = aTool._solveForEquilibriumForAuxiliaryStates; _maxSteps = aTool._maxSteps; _maxDT = aTool._maxDT; _minDT = aTool._minDT; _errorTolerance = aTool._errorTolerance; _analysisSet = aTool._analysisSet; _toolOwnsModel = aTool._toolOwnsModel; _externalLoadsFileName = aTool._externalLoadsFileName; // CONTROLLER _controllerSet = aTool._controllerSet; return(*this); } //============================================================================= // GET AND SET //============================================================================= //----------------------------------------------------------------------------- // MODEL //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set the model to be investigated. * NOTE: setup() should have been called on the model prior to calling this method */ void AbstractTool:: setModel(Model& aModel) { _model = &aModel; //_toolOwnsModel=false; if(_model) { addAnalysisSetToModel(); addControllerSetToModel(); } } //_____________________________________________________________________________ /** * Get the model to be investigated. */ Model& AbstractTool:: getModel() const { if (_model==NULL) throw Exception("AbstractTool::getModel(): Model has not been set"); return(*_model); } //============================================================================= // LOAD MODEL //============================================================================= //_____________________________________________________________________________ /** * Load and construct a model based on the property settings of * this investigation. */ void AbstractTool:: loadModel(const string &aToolSetupFileName, ForceSet *rOriginalForceSet ) { OPENSIM_THROW_IF_FRMOBJ(_modelFile.empty(), Exception, "No model file was specified (<model_file> element is empty) in " "the Tool's Setup file. Consider passing `false` for the " "constructor's `aLoadModel` parameter"); auto cwd = IO::CwdChanger::changeToParentOf(aToolSetupFileName); log_info("AbstractTool {} loading model {}", getName(), _modelFile); auto model = std::unique_ptr<Model>{new Model{_modelFile}}; model->finalizeFromProperties(); if (rOriginalForceSet!=NULL) { *rOriginalForceSet = model->getForceSet(); } _model = model.release(); } void AbstractTool:: updateModelForces(Model& model, const string &aToolSetupFileName, ForceSet *rOriginalForceSet ) { auto cwd = IO::CwdChanger::changeToParentOf(aToolSetupFileName); if (rOriginalForceSet) { *rOriginalForceSet = model.getForceSet(); } // If replacing force set read in from model file, clear it here if (_replaceForceSet){ // Can no longer just remove the model's forces. // If the model is connected, then the model will // maintain a list of subcomponents that refer to garbage. model.cleanup(); model.updForceSet().setSize(0); } // Load force set(s) for(int i=0; i<_forceSetFiles.getSize(); i++) { log_info("Adding force object set from {}", _forceSetFiles[i]); ForceSet *forceSet=new ForceSet(_forceSetFiles[i], true); model.updForceSet().append(*forceSet); } } //_____________________________________________________________________________ /** * Adds Analysis objects from analysis set to model. * * NOTE: Makes copies of analyses. Also, both this tool and the model have ownership of their analysis * objects, so making a copy is necessary so a single analysis won't be deleted twice. * * To avoid leaking when the tool is run from the GUI, pointers to the model's copy of the analyses * are kept around so that they can be removed at the end of tool execution. * _analysisCopies is used to do this book keeping. */ void AbstractTool:: addAnalysisSetToModel() { if (!_model) { string msg = "ERROR- A model has not been set."; log_error("AbstractTool: {}",msg); throw(Exception(msg,__FILE__,__LINE__)); } int size = _analysisSet.getSize(); _analysisCopies.setMemoryOwner(false); for(int i=0;i<size;i++) { Analysis *analysis = _analysisSet.get(i).clone(); _model->addAnalysis(analysis); _analysisCopies.adoptAndAppend(analysis); } } //_____________________________________________________________________________ /** * Adds Controller objects from Controller set to model. * * NOTE: Makes copies of Controller. Also, both this tool and the model have ownership of their Controller * objects, so making a copy is necessary so a single analysis won't be deleted twice. * * To avoid leaking when the tool is run from the GUI, pointers to the model's copy of the Controller * are kept around so that they can be removed at the end of tool execution. * _controllerCopies is used to do this book keeping. */ void AbstractTool:: addControllerSetToModel() { if (!_model) { string msg = "ERROR- A model has not been set."; log_error("AbstractTool: {}", msg); throw(Exception(msg,__FILE__,__LINE__)); } int size = _controllerSet.getSize(); _controllerCopies.setMemoryOwner(false); for(int i=0;i<size;i++) { Controller *controller = _controllerSet.get(i).clone(); _model->addController(controller); _controllerCopies.adoptAndAppend(controller); } } //_____________________________________________________________________________ //_____________________________________________________________________________ /** * Remove Analysis objects that were added earlier from analysis set to model. * * NOTE: Pointers to the . */ void AbstractTool:: removeAnalysisSetFromModel() { if (!_model) { return; } int size = _analysisCopies.getSize(); for(int i=size-1;i>=0;i--) { Analysis& analysis = (Analysis&)_analysisCopies.get(i); _model->removeAnalysis(&analysis); } } void AbstractTool:: removeControllerSetFromModel() { if (!_model) { return; } int size = _controllerCopies.getSize(); for(int i=size-1;i>=0;i--) { Controller& controller = (Controller&)_controllerCopies.get(i); _model->removeController(&controller); } } //============================================================================= // IO //============================================================================= //_____________________________________________________________________________ /** * Print the results of the analysis. * * @param aFileName File to which to print the data. * @param aDT Time interval between results (linear interpolation is used). * If not included as an argument or negative, all time steps are printed * without interpolation. * @param aExtension Extension for written files. */ void AbstractTool:: printResults(const string &aBaseName,const string &aDir,double aDT, const string &aExtension) { log_info("Printing results of investigation {} to {}", getName(), aDir); IO::makeDir(aDir); _model->updAnalysisSet().printResults(aBaseName,aDir,aDT,aExtension); } // NOTE: The implementation here should be verbatim that of DynamicsTool:: // createExternalLoads to ensure consistent behavior of Tools in the GUI // TODO: Unify the code bases. bool AbstractTool::createExternalLoads( const string& aExternalLoadsFileName, Model& aModel) { if(aExternalLoadsFileName==""||aExternalLoadsFileName=="Unassigned") { log_info("No external loads will be applied (external loads file not specified)."); return false; } Model copyModel = aModel; // speedup realize position calculations by removing all force elements // including muscles whose path calculations are most intensive copyModel.updForceSet().clearAndDestroy(); copyModel.updControllerSet().clearAndDestroy(); // Create external forces ExternalLoads* externalLoads = nullptr; try { externalLoads = new ExternalLoads(aExternalLoadsFileName, true); copyModel.addModelComponent(externalLoads); } catch (const Exception &ex) { // Important to catch exceptions here so we can restore current working directory... // And then we can re-throw the exception log_error("Failed to construct ExternalLoads from file {}." " Please make sure the file exists and that it contains an ExternalLoads" " object or create a fresh one.", aExternalLoadsFileName); throw(ex); } //Now add the ExternalLoads (transformed or not) to the Model to be analyzed ExternalLoads* exLoadsClone = externalLoads->clone(); aModel.addModelComponent(exLoadsClone); // copy over created external loads to the external loads owned by the tool _externalLoads = *externalLoads; // tool holds on to a reference of the external loads in the model so it can // be removed afterwards _modelExternalLoads = exLoadsClone; return true; } void AbstractTool::removeExternalLoadsFromModel() { // If ExternalLoads were added to the model by the Tool, then remove them if (modelHasExternalLoads()) { _model->updMiscModelComponentSet().remove(_modelExternalLoads.release()); } } //_____________________________________________________________________________ /** * Override default implementation by object to intercept and fix the XML node * underneath the tool to match current version */ /*virtual*/ void AbstractTool::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber) { std::string controlsFileName =""; if ( versionNumber < XMLDocument::getLatestVersion()){ // Replace names of properties if (versionNumber<10900){ XMLDocument::renameChildNode(aNode, "replace_actuator_set", "replace_force_set"); } if (versionNumber<10904){ XMLDocument::renameChildNode(aNode, "actuator_set_files", "force_set_files"); // Get name of controls_file of any and use it to build a ControlSetController later SimTK::Xml::element_iterator controlsFileNode = aNode.element_begin("controls_file"); if (controlsFileNode!=aNode.element_end()){ SimTK::String transcoded=controlsFileNode->getValueAs<SimTK::String>(); if (transcoded.length()>0) controlsFileName = transcoded; aNode.eraseNode(controlsFileNode); } } if (versionNumber<20001){ // if external loads .mot file has been specified, create // an XML file corresponding to it and set it as new external loads file SimTK::Xml::element_iterator it = aNode.element_begin("external_loads_file"); if (it != aNode.element_end()){ string oldFile = it->getValueAs<string>(); if (oldFile!="" && oldFile!="Unassigned"){ if (oldFile.substr(oldFile.length()-4, 4)!=".xml"){ // get names of bodies for external loads and create an xml file for the forceSet string body1, body2; body1 = aNode.element_begin("external_loads_body1")->getValueAs<string>(); body2 = aNode.element_begin("external_loads_body2")->getValueAs<string>(); string newFileName=createExternalLoadsFile(oldFile, body1, body2); SimTK::Xml::element_iterator pNode = aNode.element_begin("external_loads_file"); if(pNode!=aNode.element_end()) { pNode->setValue(newFileName); } } } } } if (versionNumber<20201){ // Move ExternalLoadKinematics and Filtering into ExternalLoads object // Get nodes for "external_loads_model_kinematics_file" and // "lowpass_cutoff_frequency_for_load_kinematics" and if either is not null // AND "external_loads_file" is not null then move these two nodes under it // and change top level object type from ForceSet to ExternalLoads SimTK::Xml::element_iterator iter = aNode.element_begin("external_loads_file"); if (iter!= aNode.element_end()){ string fileName=""; iter->getValueAs(fileName); if (fileName!="" && fileName != "Unassigned") { auto cwd = IO::CwdChanger::changeToParentOf(getDocumentFileName()); SimTK::Xml::Document doc(fileName); doc.setIndentString("\t"); Xml::Element root = doc.getRootElement(); if (root.getElementTag()=="OpenSimDocument"){ //int curVersion = root.getRequiredAttributeValueAs<int>("Version"); Xml::element_iterator rootIter(root.element_begin("ForceSet")); if (rootIter!=root.element_end()){ rootIter->setElementTag("ExternalLoads"); } Xml::element_iterator iter(root.element_begin("ExternalLoads")); Xml::Element extLoadsElem = *iter; SimTK::Xml::element_iterator kIter = aNode.element_begin("external_loads_model_kinematics_file"); if (kIter !=aNode.element_end()){ string kinFileName= ""; kIter->getValueAs(kinFileName); aNode.removeNode(kIter); // Make sure no node already exist Xml::element_iterator iter2(extLoadsElem.element_begin("external_loads_model_kinematics_file")); if (iter2 == extLoadsElem.element_end()) iter->insertNodeAfter(iter->element_end(), Xml::Element("external_loads_model_kinematics_file", kinFileName)); else iter2->setValue(kinFileName); } SimTK::Xml::element_iterator fIter = aNode.element_begin("lowpass_cutoff_frequency_for_load_kinematics"); if (fIter !=aNode.element_end()){ SimTK::String freq; fIter->getValueAs(freq); Xml::element_iterator iter2(extLoadsElem.element_begin("lowpass_cutoff_frequency_for_load_kinematics")); if (iter2 == extLoadsElem.element_end()) iter->insertNodeAfter(iter->element_end(), Xml::Element("lowpass_cutoff_frequency_for_load_kinematics", freq)); else iter2->setValue(freq); } doc.writeToFile(fileName); } } } } } Object::updateFromXMLNode(aNode, 20303); // Create controllers and add them as needed. if (controlsFileName!="" && controlsFileName!="Unassigned"){ // controls_file was specified, create a ControlSetController for it ControlSetController* csc = new ControlSetController(); csc->setControlSetFileName(controlsFileName); _controllerSet.adoptAndAppend(csc); } } void AbstractTool::loadQStorage (const std::string& statesFileName, Storage& rQStore) const { // Initial states if(statesFileName!="") { log_info("Loading q's from file {}.", statesFileName); Storage temp(statesFileName); _model->formQStorage(temp, rQStore); log_info("Found {} q's with time stamps ranging from {} to {}.", rQStore.getSize(), rQStore.getFirstTime(), rQStore.getLastTime()); } } //_____________________________________________________________________________ /** * Interfaces to build controller from a file and add it to the tool * */ std::string AbstractTool::getControlsFileName() const { int numControllers = _controllerSet.getSize(); if (numControllers>=1){ // We have potentially more than one, make sure there's controlset controller for(int i=0; i<numControllers; i++){ OpenSim::Controller& controller= _controllerSet.get(i); if (dynamic_cast<OpenSim::ControlSetController *>(&controller)==0) continue; OpenSim::ControlSetController& dController = (OpenSim::ControlSetController&) _controllerSet.get(i); return (dController.getControlSetFileName()); } } return ("Unassigned"); } //_____________________________________________________________________________ /** * A Convenience method to add a ControlSetController from a file and add it * to the model */ void AbstractTool::setControlsFileName(const std::string& controlsFilename) { if (controlsFilename=="" || controlsFilename=="Unassigned") return; int numControllers = _controllerSet.getSize(); for(int i=0; i<numControllers;i++){ OpenSim::Controller& controller= _controllerSet.get(i); if (dynamic_cast<OpenSim::ControlSetController *>(&controller)==0) continue; OpenSim::ControlSetController& dController = (OpenSim::ControlSetController&)_controllerSet[i]; dController.setControlSetFileName(controlsFilename); return; } // Create a new controlsetController and add it to the tool ControlSetController* csc = new ControlSetController(); csc->setControlSetFileName(controlsFilename); _controllerSet.adoptAndAppend(csc); } //_____________________________________________________________________________ /** * A Convenience method to verify that ColumnLabels are unique */ bool AbstractTool::verifyUniqueColumnLabels(const Storage& aStore) const { const Array<string>& lbls = aStore.getColumnLabels(); bool isUnique = true; for(int i=0; i< lbls.getSize() && isUnique; i++){ isUnique= (lbls.findIndex(lbls[i])==i); } return isUnique; } //_____________________________________________________________________________ /** * A Convenience method to get the next unique */ std::string AbstractTool::getNextAvailableForceName(const std::string prefix) const { int candidate = 0; std::string candidateName; bool found = false; while (!found) { candidate++; candidateName = fmt::format("{}_{}", prefix, candidate); if (_model) { if (_model->getForceSet().contains(candidateName)) continue; } found = !(_externalLoads.contains(candidateName)); }; return candidateName; } std::string AbstractTool::createExternalLoadsFile(const std::string& oldFile, const std::string& body1, const std::string& body2) { bool oldFileValid = !(oldFile=="" || oldFile=="Unassigned"); auto cwd = getDocument() != nullptr ? IO::CwdChanger::changeToParentOf(getDocument()->getFileName()) : IO::CwdChanger::noop(); if (oldFileValid) { if(!ifstream(oldFile.c_str(), ios_base::in).good()) { string msg = "Object: ERR- Could not open file " + oldFile+ ". It may not exist or you don't have permission to read it."; throw Exception(msg,__FILE__,__LINE__); } } Storage dataFile(oldFile); const Array<string>& labels=dataFile.getColumnLabels(); bool body1Valid = !(body1=="" || body1=="Unassigned"); bool body2Valid = !(body2=="" || body2=="Unassigned"); std::string forceLabels[9] = {"ground_force_vx", "ground_force_vy", "ground_force_vz", "ground_force_px", "ground_force_py", "ground_force_pz", "ground_torque_x", "ground_torque_y", "ground_torque_z"}; // We'll create up to 2 PrescribedForces if (body1Valid && body2Valid){ // Find first occurrence of ground_force_vx int indices[9][2]; for(int i=0; i<9; i++){ indices[i][0]= labels.findIndex(forceLabels[i]); if (indices[i][0]==-1){ // Something went wrong, abort here string msg = "Object: ERR- Could not find label "+forceLabels[i]+ "in file " + oldFile+ ". Aborting."; throw Exception(msg,__FILE__,__LINE__); } for(int j=indices[i][0]+1; j<labels.getSize(); j++){ if (labels[j]==forceLabels[i]){ indices[i][1]=j; break; } } } for(int f=0; f<2; f++){ ExternalForce* xf = new ExternalForce(); xf->setAppliedToBodyName((f==0)?body1:body2); char pad[3]; sprintf(pad,"%d", f+1); std::string suffix = "ExternalForce_"+string(pad); xf->setName(suffix); _externalLoads.adoptAndAppend(xf); } _externalLoads.setDataFileName(oldFile); std::string newName=oldFile.substr(0, oldFile.length()-4)+".xml"; _externalLoads.print(newName); log_cout("Created ForceSet file {} to apply forces from {}.", newName, oldFile); return newName; } else { string msg = "Object: ERR- Only one body is specified in " + oldFile+ "."; throw Exception(msg,__FILE__,__LINE__); } } std::string AbstractTool::getTimeString(const time_t& t) const { const auto time = localtime(&t); std::string str(asctime(time)); // Remove newline. str.pop_back(); return str; }
#include <bits/stdc++.h> using namespace std; using LL = long long; using Pii = pair<int, int>; using Pll = pair<LL, LL>; using VI = vector<int>; using VP = vector<pair<int, int>>; #define rep(i, a, b) for (auto i = (a); i < (b); ++i) #define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i) #define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i]) #define mem(x, v) memset(x, v, sizeof(x)) #define cpy(x, y) memcpy(x, y, sizeof(x)) #define SZ(V) static_cast<int>(V.size()) #define pb push_back #define mp make_pair constexpr int maxn = 2e5 + 7; int gh[maxn], gn[maxn], gv[maxn], total; void add(int u, int v) { gv[total] = v; gn[total] = gh[u]; gh[u] = total++; } int outd[maxn], dep[maxn], fa[maxn]; void dfs(int u, int f, int d) { outd[u] = 0; dep[u] = d; fa[u] = f; grep(i, u) { int v = gv[i]; if (v != f) { dfs(v, u, d + 1); ++outd[u]; } } } int query[maxn], white[maxn]; int main() { int T; scanf("%d", &T); rep(index, 1, T + 1) { int n, q; scanf("%d%d", &n, &q); total = 0; fill(gh + 1, gh + n + 1, -1); printf("Case #%d:\n", index); rep(i, 1, n) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } dfs(1, 1, 0); while (q--) { int m, ans = 0; scanf("%d", &m); rep(i, 0, m) scanf("%d", &query[i]); sort(query, query + m, [](int u, int v) { return dep[u] > dep[v]; }); rep(i, 0, m) { int u = query[i]; int black = outd[u] - white[u]; if (black <= 1) { ++ans; if (!black) white[fa[u]]++; } } printf("%d\n", n - ans); rep(i, 0, m) white[fa[query[i]]] = 0; } } }
// 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/browser/chromeos/extensions/file_manager/private_api_file_system.h" #include <sys/statvfs.h> #include "base/posix/eintr_wrapper.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/task_runner_util.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/drive/drive.pb.h" #include "chrome/browser/chromeos/drive/file_system_interface.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/extensions/file_manager/event_router.h" #include "chrome/browser/chromeos/extensions/file_manager/file_browser_private_api.h" #include "chrome/browser/chromeos/extensions/file_manager/private_api_util.h" #include "chrome/browser/chromeos/file_manager/fileapi_util.h" #include "chrome/browser/chromeos/file_manager/volume_manager.h" #include "chrome/browser/chromeos/fileapi/file_system_backend.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/extensions/api/file_browser_private.h" #include "chrome/common/extensions/api/file_browser_private_internal.h" #include "chromeos/disks/disk_mount_manager.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "webkit/browser/fileapi/file_system_context.h" #include "webkit/browser/fileapi/file_system_file_util.h" #include "webkit/browser/fileapi/file_system_operation_context.h" #include "webkit/browser/fileapi/file_system_operation_runner.h" #include "webkit/browser/fileapi/file_system_url.h" #include "webkit/common/fileapi/file_system_info.h" #include "webkit/common/fileapi/file_system_types.h" #include "webkit/common/fileapi/file_system_util.h" using chromeos::disks::DiskMountManager; using content::BrowserThread; using content::ChildProcessSecurityPolicy; using file_manager::util::EntryDefinition; using file_manager::util::FileDefinition; using fileapi::FileSystemURL; namespace extensions { namespace { // Retrieves total and remaining available size on |mount_path|. void GetSizeStatsOnBlockingPool(const std::string& mount_path, uint64* total_size, uint64* remaining_size) { struct statvfs stat = {}; // Zero-clear if (HANDLE_EINTR(statvfs(mount_path.c_str(), &stat)) == 0) { *total_size = static_cast<uint64>(stat.f_blocks) * stat.f_frsize; *remaining_size = static_cast<uint64>(stat.f_bavail) * stat.f_frsize; } } // Retrieves the maximum file name length of the file system of |path|. // Returns 0 if it could not be queried. size_t GetFileNameMaxLengthOnBlockingPool(const std::string& path) { struct statvfs stat = {}; if (HANDLE_EINTR(statvfs(path.c_str(), &stat)) != 0) { // The filesystem seems not supporting statvfs(). Assume it to be a commonly // used bound 255, and log the failure. LOG(ERROR) << "Cannot statvfs() the name length limit for: " << path; return 255; } return stat.f_namemax; } // Returns EventRouter for the |profile_id| if available. file_manager::EventRouter* GetEventRouterByProfileId(void* profile_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // |profile_id| needs to be checked with ProfileManager::IsValidProfile // before using it. Profile* profile = reinterpret_cast<Profile*>(profile_id); if (!g_browser_process->profile_manager()->IsValidProfile(profile)) return NULL; return file_manager::FileBrowserPrivateAPI::Get(profile)->event_router(); } // Notifies the copy progress to extensions via event router. void NotifyCopyProgress( void* profile_id, fileapi::FileSystemOperationRunner::OperationID operation_id, fileapi::FileSystemOperation::CopyProgressType type, const FileSystemURL& source_url, const FileSystemURL& destination_url, int64 size) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); file_manager::EventRouter* event_router = GetEventRouterByProfileId(profile_id); if (event_router) { event_router->OnCopyProgress( operation_id, type, source_url.ToGURL(), destination_url.ToGURL(), size); } } // Callback invoked periodically on progress update of Copy(). void OnCopyProgress( void* profile_id, fileapi::FileSystemOperationRunner::OperationID* operation_id, fileapi::FileSystemOperation::CopyProgressType type, const FileSystemURL& source_url, const FileSystemURL& destination_url, int64 size) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&NotifyCopyProgress, profile_id, *operation_id, type, source_url, destination_url, size)); } // Notifies the copy completion to extensions via event router. void NotifyCopyCompletion( void* profile_id, fileapi::FileSystemOperationRunner::OperationID operation_id, const FileSystemURL& source_url, const FileSystemURL& destination_url, base::File::Error error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); file_manager::EventRouter* event_router = GetEventRouterByProfileId(profile_id); if (event_router) event_router->OnCopyCompleted( operation_id, source_url.ToGURL(), destination_url.ToGURL(), error); } // Callback invoked upon completion of Copy() (regardless of succeeded or // failed). void OnCopyCompleted( void* profile_id, fileapi::FileSystemOperationRunner::OperationID* operation_id, const FileSystemURL& source_url, const FileSystemURL& destination_url, base::File::Error error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&NotifyCopyCompletion, profile_id, *operation_id, source_url, destination_url, error)); } // Starts the copy operation via FileSystemOperationRunner. fileapi::FileSystemOperationRunner::OperationID StartCopyOnIOThread( void* profile_id, scoped_refptr<fileapi::FileSystemContext> file_system_context, const FileSystemURL& source_url, const FileSystemURL& destination_url) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Note: |operation_id| is owned by the callback for // FileSystemOperationRunner::Copy(). It is always called in the next message // loop or later, so at least during this invocation it should alive. fileapi::FileSystemOperationRunner::OperationID* operation_id = new fileapi::FileSystemOperationRunner::OperationID; *operation_id = file_system_context->operation_runner()->Copy( source_url, destination_url, fileapi::FileSystemOperation::OPTION_PRESERVE_LAST_MODIFIED, base::Bind(&OnCopyProgress, profile_id, base::Unretained(operation_id)), base::Bind(&OnCopyCompleted, profile_id, base::Owned(operation_id), source_url, destination_url)); return *operation_id; } void OnCopyCancelled(base::File::Error error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // We just ignore the status if the copy is actually cancelled or not, // because failing cancellation means the operation is not running now. DLOG_IF(WARNING, error != base::File::FILE_OK) << "Failed to cancel copy: " << error; } // Cancels the running copy operation identified by |operation_id|. void CancelCopyOnIOThread( scoped_refptr<fileapi::FileSystemContext> file_system_context, fileapi::FileSystemOperationRunner::OperationID operation_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); file_system_context->operation_runner()->Cancel( operation_id, base::Bind(&OnCopyCancelled)); } } // namespace void FileBrowserPrivateRequestFileSystemFunction::DidFail( base::File::Error error_code) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); SetError(base::StringPrintf("File error %d", static_cast<int>(error_code))); SendResponse(false); } bool FileBrowserPrivateRequestFileSystemFunction:: SetupFileSystemAccessPermissions( scoped_refptr<fileapi::FileSystemContext> file_system_context, int child_id, Profile* profile, scoped_refptr<const extensions::Extension> extension) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!extension.get()) return false; // Make sure that only component extension can access the entire // local file system. if (extension_->location() != extensions::Manifest::COMPONENT) { NOTREACHED() << "Private method access by non-component extension " << extension->id(); return false; } fileapi::ExternalFileSystemBackend* backend = file_system_context->external_backend(); if (!backend) return false; // Grant full access to File API from this component extension. backend->GrantFullAccessToExtension(extension_->id()); // Grant R/W file permissions to the renderer hosting component // extension for all paths exposed by our local file system backend. std::vector<base::FilePath> root_dirs = backend->GetRootDirectories(); for (size_t i = 0; i < root_dirs.size(); ++i) { ChildProcessSecurityPolicy::GetInstance()->GrantCreateReadWriteFile( child_id, root_dirs[i]); } // Grant R/W permissions to profile-specific directories (Drive, Downloads) // from other profiles. Those directories may not be mounted at this moment // yet, so we need to do this separately from the above loop over // GetRootDirectories(). const std::vector<Profile*>& profiles = g_browser_process->profile_manager()->GetLoadedProfiles(); for (size_t i = 0; i < profiles.size(); ++i) { if (!profiles[i]->IsOffTheRecord()) { file_manager::util::SetupProfileFileAccessPermissions(child_id, profiles[i]); } } return true; } bool FileBrowserPrivateRequestFileSystemFunction::RunAsync() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); using extensions::api::file_browser_private::RequestFileSystem::Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); if (!dispatcher() || !render_view_host() || !render_view_host()->GetProcess()) return false; set_log_on_completion(true); using file_manager::VolumeManager; using file_manager::VolumeInfo; VolumeManager* volume_manager = VolumeManager::Get(GetProfile()); if (!volume_manager) return false; VolumeInfo volume_info; if (!volume_manager->FindVolumeInfoById(params->volume_id, &volume_info)) { DidFail(base::File::FILE_ERROR_NOT_FOUND); return false; } scoped_refptr<fileapi::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderViewHost( GetProfile(), render_view_host()); // Set up file permission access. const int child_id = render_view_host()->GetProcess()->GetID(); if (!SetupFileSystemAccessPermissions(file_system_context, child_id, GetProfile(), GetExtension())) { DidFail(base::File::FILE_ERROR_SECURITY); return false; } FileDefinition file_definition; if (!file_manager::util::ConvertAbsoluteFilePathToRelativeFileSystemPath( GetProfile(), extension_id(), volume_info.mount_path, &file_definition.virtual_path)) { DidFail(base::File::FILE_ERROR_INVALID_OPERATION); return false; } file_definition.is_directory = true; file_manager::util::ConvertFileDefinitionToEntryDefinition( GetProfile(), extension_id(), file_definition, base::Bind( &FileBrowserPrivateRequestFileSystemFunction::OnEntryDefinition, this)); return true; } void FileBrowserPrivateRequestFileSystemFunction::OnEntryDefinition( const EntryDefinition& entry_definition) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (entry_definition.error != base::File::FILE_OK) { DidFail(entry_definition.error); return; } if (!entry_definition.is_directory) { DidFail(base::File::FILE_ERROR_NOT_A_DIRECTORY); return; } base::DictionaryValue* dict = new base::DictionaryValue(); SetResult(dict); dict->SetString("name", entry_definition.file_system_name); dict->SetString("root_url", entry_definition.file_system_root_url); dict->SetInteger("error", drive::FILE_ERROR_OK); SendResponse(true); } void FileWatchFunctionBase::Respond(bool success) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); SetResult(new base::FundamentalValue(success)); SendResponse(success); } bool FileWatchFunctionBase::RunAsync() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!render_view_host() || !render_view_host()->GetProcess()) return false; // First param is url of a file to watch. std::string url; if (!args_->GetString(0, &url) || url.empty()) return false; scoped_refptr<fileapi::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderViewHost( GetProfile(), render_view_host()); FileSystemURL file_watch_url = file_system_context->CrackURL(GURL(url)); base::FilePath local_path = file_watch_url.path(); base::FilePath virtual_path = file_watch_url.virtual_path(); if (local_path.empty()) { Respond(false); return true; } PerformFileWatchOperation(local_path, virtual_path, extension_id()); return true; } void FileBrowserPrivateAddFileWatchFunction::PerformFileWatchOperation( const base::FilePath& local_path, const base::FilePath& virtual_path, const std::string& extension_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); file_manager::EventRouter* event_router = file_manager::FileBrowserPrivateAPI::Get(GetProfile())->event_router(); event_router->AddFileWatch( local_path, virtual_path, extension_id, base::Bind(&FileBrowserPrivateAddFileWatchFunction::Respond, this)); } void FileBrowserPrivateRemoveFileWatchFunction::PerformFileWatchOperation( const base::FilePath& local_path, const base::FilePath& unused, const std::string& extension_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); file_manager::EventRouter* event_router = file_manager::FileBrowserPrivateAPI::Get(GetProfile())->event_router(); event_router->RemoveFileWatch(local_path, extension_id); Respond(true); } bool FileBrowserPrivateGetSizeStatsFunction::RunAsync() { using extensions::api::file_browser_private::GetSizeStats::Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); using file_manager::VolumeManager; using file_manager::VolumeInfo; VolumeManager* volume_manager = VolumeManager::Get(GetProfile()); if (!volume_manager) return false; VolumeInfo volume_info; if (!volume_manager->FindVolumeInfoById(params->volume_id, &volume_info)) return false; if (volume_info.type == file_manager::VOLUME_TYPE_GOOGLE_DRIVE) { drive::FileSystemInterface* file_system = drive::util::GetFileSystemByProfile(GetProfile()); if (!file_system) { // |file_system| is NULL if Drive is disabled. // If stats couldn't be gotten for drive, result should be left // undefined. See comments in GetDriveAvailableSpaceCallback(). SendResponse(true); return true; } file_system->GetAvailableSpace( base::Bind(&FileBrowserPrivateGetSizeStatsFunction:: GetDriveAvailableSpaceCallback, this)); } else { uint64* total_size = new uint64(0); uint64* remaining_size = new uint64(0); BrowserThread::PostBlockingPoolTaskAndReply( FROM_HERE, base::Bind(&GetSizeStatsOnBlockingPool, volume_info.mount_path.value(), total_size, remaining_size), base::Bind(&FileBrowserPrivateGetSizeStatsFunction:: GetSizeStatsCallback, this, base::Owned(total_size), base::Owned(remaining_size))); } return true; } void FileBrowserPrivateGetSizeStatsFunction::GetDriveAvailableSpaceCallback( drive::FileError error, int64 bytes_total, int64 bytes_used) { if (error == drive::FILE_ERROR_OK) { const uint64 bytes_total_unsigned = bytes_total; const uint64 bytes_remaining_unsigned = bytes_total - bytes_used; GetSizeStatsCallback(&bytes_total_unsigned, &bytes_remaining_unsigned); } else { // If stats couldn't be gotten for drive, result should be left undefined. SendResponse(true); } } void FileBrowserPrivateGetSizeStatsFunction::GetSizeStatsCallback( const uint64* total_size, const uint64* remaining_size) { base::DictionaryValue* sizes = new base::DictionaryValue(); SetResult(sizes); sizes->SetDouble("totalSize", static_cast<double>(*total_size)); sizes->SetDouble("remainingSize", static_cast<double>(*remaining_size)); SendResponse(true); } bool FileBrowserPrivateValidatePathNameLengthFunction::RunAsync() { using extensions::api::file_browser_private::ValidatePathNameLength::Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); scoped_refptr<fileapi::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderViewHost( GetProfile(), render_view_host()); fileapi::FileSystemURL filesystem_url( file_system_context->CrackURL(GURL(params->parent_directory_url))); if (!chromeos::FileSystemBackend::CanHandleURL(filesystem_url)) return false; // No explicit limit on the length of Drive file names. if (filesystem_url.type() == fileapi::kFileSystemTypeDrive) { SetResult(new base::FundamentalValue(true)); SendResponse(true); return true; } base::PostTaskAndReplyWithResult( BrowserThread::GetBlockingPool(), FROM_HERE, base::Bind(&GetFileNameMaxLengthOnBlockingPool, filesystem_url.path().AsUTF8Unsafe()), base::Bind(&FileBrowserPrivateValidatePathNameLengthFunction:: OnFilePathLimitRetrieved, this, params->name.size())); return true; } void FileBrowserPrivateValidatePathNameLengthFunction::OnFilePathLimitRetrieved( size_t current_length, size_t max_length) { SetResult(new base::FundamentalValue(current_length <= max_length)); SendResponse(true); } bool FileBrowserPrivateFormatVolumeFunction::RunAsync() { using extensions::api::file_browser_private::FormatVolume::Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); using file_manager::VolumeManager; using file_manager::VolumeInfo; VolumeManager* volume_manager = VolumeManager::Get(GetProfile()); if (!volume_manager) return false; VolumeInfo volume_info; if (!volume_manager->FindVolumeInfoById(params->volume_id, &volume_info)) return false; DiskMountManager::GetInstance()->FormatMountedDevice( volume_info.mount_path.AsUTF8Unsafe()); SendResponse(true); return true; } bool FileBrowserPrivateStartCopyFunction::RunAsync() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); using extensions::api::file_browser_private::StartCopy::Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); if (params->source_url.empty() || params->parent.empty() || params->new_name.empty()) { // Error code in format of DOMError.name. SetError("EncodingError"); return false; } scoped_refptr<fileapi::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderViewHost( GetProfile(), render_view_host()); // |parent| may have a trailing slash if it is a root directory. std::string destination_url_string = params->parent; if (destination_url_string[destination_url_string.size() - 1] != '/') destination_url_string += '/'; destination_url_string += net::EscapePath(params->new_name); fileapi::FileSystemURL source_url( file_system_context->CrackURL(GURL(params->source_url))); fileapi::FileSystemURL destination_url( file_system_context->CrackURL(GURL(destination_url_string))); if (!source_url.is_valid() || !destination_url.is_valid()) { // Error code in format of DOMError.name. SetError("EncodingError"); return false; } return BrowserThread::PostTaskAndReplyWithResult( BrowserThread::IO, FROM_HERE, base::Bind(&StartCopyOnIOThread, GetProfile(), file_system_context, source_url, destination_url), base::Bind(&FileBrowserPrivateStartCopyFunction::RunAfterStartCopy, this)); } void FileBrowserPrivateStartCopyFunction::RunAfterStartCopy( int operation_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); SetResult(new base::FundamentalValue(operation_id)); SendResponse(true); } bool FileBrowserPrivateCancelCopyFunction::RunAsync() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); using extensions::api::file_browser_private::CancelCopy::Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); scoped_refptr<fileapi::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderViewHost( GetProfile(), render_view_host()); // We don't much take care about the result of cancellation. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&CancelCopyOnIOThread, file_system_context, params->copy_id)); SendResponse(true); return true; } bool FileBrowserPrivateInternalResolveIsolatedEntriesFunction::RunAsync() { using extensions::api::file_browser_private_internal::ResolveIsolatedEntries:: Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); scoped_refptr<fileapi::FileSystemContext> file_system_context = file_manager::util::GetFileSystemContextForRenderViewHost( GetProfile(), render_view_host()); DCHECK(file_system_context); const fileapi::ExternalFileSystemBackend* external_backend = file_system_context->external_backend(); DCHECK(external_backend); file_manager::util::FileDefinitionList file_definition_list; for (size_t i = 0; i < params->urls.size(); ++i) { FileSystemURL fileSystemUrl = file_system_context->CrackURL(GURL(params->urls[i])); DCHECK(external_backend->CanHandleType(fileSystemUrl.type())); FileDefinition file_definition; const bool result = file_manager::util::ConvertAbsoluteFilePathToRelativeFileSystemPath( GetProfile(), extension_->id(), fileSystemUrl.path(), &file_definition.virtual_path); if (!result) continue; // The API only supports isolated files. file_definition.is_directory = false; file_definition_list.push_back(file_definition); } file_manager::util::ConvertFileDefinitionListToEntryDefinitionList( GetProfile(), extension_->id(), file_definition_list, // Safe, since copied internally. base::Bind( &FileBrowserPrivateInternalResolveIsolatedEntriesFunction:: RunAsyncAfterConvertFileDefinitionListToEntryDefinitionList, this)); return true; } void FileBrowserPrivateInternalResolveIsolatedEntriesFunction:: RunAsyncAfterConvertFileDefinitionListToEntryDefinitionList(scoped_ptr< file_manager::util::EntryDefinitionList> entry_definition_list) { using extensions::api::file_browser_private_internal::EntryDescription; std::vector<linked_ptr<EntryDescription> > entries; for (size_t i = 0; i < entry_definition_list->size(); ++i) { if (entry_definition_list->at(i).error != base::File::FILE_OK) continue; linked_ptr<EntryDescription> entry(new EntryDescription); entry->file_system_name = entry_definition_list->at(i).file_system_name; entry->file_system_root = entry_definition_list->at(i).file_system_root_url; entry->file_full_path = "/" + entry_definition_list->at(i).full_path.AsUTF8Unsafe(); entry->file_is_directory = entry_definition_list->at(i).is_directory; entries.push_back(entry); } results_ = extensions::api::file_browser_private_internal:: ResolveIsolatedEntries::Results::Create(entries); SendResponse(true); } } // namespace extensions
#include <windows.h> #include <multimon.h> static void getViewport(RECT *r, POINT *p, RECT *sr, HWND wnd, int full) { if (p || sr || wnd) { HINSTANCE h=LoadLibrary("user32.dll"); if (h) { HMONITOR (WINAPI *Mfp)(POINT pt, DWORD dwFlags) = (HMONITOR (WINAPI *)(POINT,DWORD)) GetProcAddress(h,"MonitorFromPoint"); HMONITOR (WINAPI *Mfr)(LPCRECT lpcr, DWORD dwFlags) = (HMONITOR (WINAPI *)(LPCRECT, DWORD)) GetProcAddress(h, "MonitorFromRect"); HMONITOR (WINAPI *Mfw)(HWND wnd, DWORD dwFlags)=(HMONITOR (WINAPI *)(HWND, DWORD)) GetProcAddress(h, "MonitorFromWindow"); BOOL (WINAPI *Gmi)(HMONITOR mon, LPMONITORINFO lpmi) = (BOOL (WINAPI *)(HMONITOR,LPMONITORINFO)) GetProcAddress(h,"GetMonitorInfoA"); if (Mfp && Mfr && Mfw && Gmi) { HMONITOR hm; if (p) hm=Mfp(*p,MONITOR_DEFAULTTONULL); else if (sr) hm=Mfr(sr,MONITOR_DEFAULTTONULL); else if (wnd) hm=Mfw(wnd,MONITOR_DEFAULTTONULL); if (hm) { MONITORINFOEX mi; ZeroMemory(&mi, sizeof(MONITORINFOEX)); mi.cbSize=sizeof(mi); if (Gmi(hm,&mi)) { if(!full) *r=mi.rcWork; else *r=mi.rcMonitor; FreeLibrary(h); return; } } } FreeLibrary(h); } } SystemParametersInfo(SPI_GETWORKAREA,0,r,0); } void getViewport(RECT *r, HWND wnd, int full) { getViewport(r, NULL, NULL, wnd, full); }
//================================================================================================= /*! // \file src/mathtest/smatsmatadd/MIaUCa.cpp // \brief Source file for the MIaUCa sparse matrix/sparse matrix addition math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/IdentityMatrix.h> #include <blaze/math/UpperMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatsmatadd/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MIaUCa'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions using MIa = blaze::IdentityMatrix<TypeA>; using UCa = blaze::UpperMatrix< blaze::CompressedMatrix<TypeA> >; // Creator type definitions using CMIa = blazetest::Creator<MIa>; using CUCa = blazetest::Creator<UCa>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=UCa::maxNonZeros( i ); ++j ) { RUN_SMATSMATADD_OPERATION_TEST( CMIa( i ), CUCa( i, j ) ); } } // Running tests with large matrices RUN_SMATSMATADD_OPERATION_TEST( CMIa( 67UL ), CUCa( 67UL, 13UL ) ); RUN_SMATSMATADD_OPERATION_TEST( CMIa( 128UL ), CUCa( 128UL, 8UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix addition:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
#include "lazy_value.h" #include <library/unittest/registar.h> Y_UNIT_TEST_SUITE(TLazyValueTestSuite) { Y_UNIT_TEST(TestLazyValue) { TLazyValue<int> value([]() { return 5; }); UNIT_ASSERT(!value); UNIT_ASSERT_EQUAL(*value, 5); UNIT_ASSERT(value); } Y_UNIT_TEST(TestLazyValueInitialization) { TLazyValue<int> value1([]() { return 5;}); TLazyValue<int> value2 = [](){ return 5;}; TLazyValue<int> notInitialized{}; TLazyValue<int> copy1(value1); copy1 = value2; } Y_UNIT_TEST(TestLazyValueCopy) { TLazyValue<int> value([]() { return 5;}); UNIT_ASSERT(!value); TLazyValue<int> emptyCopy = value; UNIT_ASSERT(!emptyCopy); UNIT_ASSERT_EQUAL(*emptyCopy, 5); UNIT_ASSERT(emptyCopy); UNIT_ASSERT(!value); UNIT_ASSERT_EQUAL(*value, 5); TLazyValue<int> notEmptyCopy = value; UNIT_ASSERT(notEmptyCopy); UNIT_ASSERT_EQUAL(*notEmptyCopy, 5) } class TValueProvider { public: static size_t CountParseDataCalled; TValueProvider() : Data([&] { return this->ParseData(); }) { } const TString& GetData() const { return *Data; } private: TLazyValue<TString> Data; TString ParseData() { CountParseDataCalled++; return "hi"; } }; size_t TValueProvider::CountParseDataCalled = 0; Y_UNIT_TEST(TestValueProvider) { TValueProvider provider; UNIT_ASSERT(provider.GetData() == "hi"); } Y_UNIT_TEST(TestValueProviderCopy) { TValueProvider provider; provider.GetData(); const auto countParsed = TValueProvider::CountParseDataCalled; provider.GetData(); UNIT_ASSERT_EQUAL(countParsed, TValueProvider::CountParseDataCalled); TValueProvider providerCopy; providerCopy = provider; providerCopy.GetData(); UNIT_ASSERT_EQUAL(countParsed, TValueProvider::CountParseDataCalled); } Y_UNIT_TEST(TestEmptyProviderCopy) { TValueProvider provider; TValueProvider copy(provider); const auto countParsed = TValueProvider::CountParseDataCalled; provider.GetData(); UNIT_ASSERT_EQUAL(countParsed + 1, TValueProvider::CountParseDataCalled); copy.GetData(); UNIT_ASSERT_EQUAL(countParsed + 2, TValueProvider::CountParseDataCalled); const TValueProvider notEmptyCopy(copy); notEmptyCopy.GetData(); UNIT_ASSERT_EQUAL(countParsed + 2, TValueProvider::CountParseDataCalled); } Y_UNIT_TEST(TestMakeLazy) { auto lv = MakeLazy([] { return 100500; }); UNIT_ASSERT(!lv); UNIT_ASSERT(lv.GetRef() == 100500); UNIT_ASSERT(lv); } }
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // 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: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/TextFile.h> #include <OpenMS/APPLICATIONS/TOPPBase.h> #include <OpenMS/FILTERING/CALIBRATION/TOFCalibration.h> using namespace OpenMS; using namespace std; //------------------------------------------------------------- //Doxygen docu //------------------------------------------------------------- /** @page TOPP_TOFCalibration TOFCalibration @brief Performs an external calibration for tof spectra. <CENTER> <table> <tr> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. predecessor tools </td> <td VALIGN="middle" ROWSPAN=3> \f$ \longrightarrow \f$ TOFCalibration \f$ \longrightarrow \f$</td> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. successor tools </td> </tr> <tr> <td VALIGN="middle" ALIGN = "center" ROWSPAN=2> - </td> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_InternalCalibration </td> </tr> <tr> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_PeakPickerWavelet </td> </tr> </table> </CENTER> Given one or more calibrant spectra containing flight times, the instrument's calibration constants and the expected masses the quadratic function \f$y_i = a + bx_i + cx_i^2\f$ is fitted, where \f$x_i\f$ is the ith flight time. If there are more than one calibrant spectra the coefficients \f$a\f$, \f$b\f$ and \f$c\f$ are averaged. The fitted function is then used to convert the flight times of the given experiment to m/z-values. You can choose to calibrate picked or raw data. If you use picked data, set the flag peak_data. If you have raw data an additional peak picking step for the calibrant spectra is needed, the parameters for the peak picker can be set in the ini-file. <B>The command line parameters of this tool are:</B> @verbinclude TOPP_TOFCalibration.cli <B>INI file documentation of this tool:</B> @htmlinclude TOPP_TOFCalibration.html */ // We do not want this class to show up in the docu: /// @cond TOPPCLASSES class TOPPTOFCalibration : public TOPPBase { public: TOPPTOFCalibration() : TOPPBase("TOFCalibration", "Applies time of flight calibration.") { } protected: void registerOptionsAndFlags_() override { registerInputFile_("in", "<file>", "", "input peak or raw data file "); setValidFormats_("in", ListUtils::create<String>("mzML")); registerOutputFile_("out", "<file>", "", "output file "); setValidFormats_("out", ListUtils::create<String>("mzML")); addEmptyLine_(); registerInputFile_("ext_calibrants", "<file>", "", "input file containing the external calibrant spectra (peak or raw data)\n"); setValidFormats_("ext_calibrants", ListUtils::create<String>("mzML")); registerInputFile_("ref_masses", "<file>", "", "input file containing reference masses of the external calibrant spectra (one per line)", true); setValidFormats_("ref_masses", ListUtils::create<String>("txt")); registerInputFile_("tof_const", "<file>", "", "File containing TOF conversion constants." " These can be either two or three constants\n" "per set, depending on the conversion type. Either one set for all calibrant spectra \n" "(tab separated), or one for each spectrum.\n" "For a detailed description, please have a look at the doxygen documentation." "(one set, tab separated, per line)", true); setValidFormats_("tof_const", ListUtils::create<String>("csv")); registerFlag_("peak_data", "set this flag, if you have peak data, not raw data (the picking parameters are accessible only from the INI file)."); registerSubsection_("algorithm", "Algorithm section for peak picking"); } Param getSubsectionDefaults_(const String& /*section*/) const override { // there is only one subsection: 'algorithm' (s.a) .. and in it belongs the PeakPicker param Param tmp; tmp.insert("PeakPicker:", PeakPickerCWT().getDefaults()); return tmp; } ExitCodes main_(int, const char**) override { //------------------------------------------------------------- // parameter handling //------------------------------------------------------------- String in = getStringOption_("in"); String out = getStringOption_("out"); String in_calib = getStringOption_("ext_calibrants"); String ref = getStringOption_("ref_masses"); String conv = getStringOption_("tof_const"); //------------------------------------------------------------- // init TOFCalibration //------------------------------------------------------------- TOFCalibration calib; calib.setLogType(log_type_); Param param = getParam_().copy("algorithm:", true); calib.setParameters(param); //------------------------------------------------------------- // loading input //------------------------------------------------------------- PeakMap ms_exp_calib, ms_exp_raw; MzMLFile mz_data_file; mz_data_file.setLogType(log_type_); mz_data_file.load(in_calib, ms_exp_calib); mz_data_file.load(in, ms_exp_raw); vector<double> ref_masses; TextFile ref_file; ref_file.load(ref, true); for (TextFile::ConstIterator iter = ref_file.begin(); iter != ref_file.end(); ++iter) { ref_masses.push_back(String(iter->c_str()).toDouble()); } TextFile const_file; const_file.load(conv, true); std::vector<String> vec; TextFile::ConstIterator iter = const_file.begin(); iter->split('\t', vec); std::vector<double> ml1, ml2, ml3; ml1.push_back(String(vec[0].c_str()).toDouble()); ml2.push_back(String(vec[1].c_str()).toDouble()); if (vec.size() == 3) { ml3.push_back(String(vec[2].c_str()).toDouble()); } ++iter; for (; iter != const_file.end(); ++iter) { iter->split('\t', vec); ml1.push_back(String(vec[0].c_str()).toDouble()); ml2.push_back(String(vec[1].c_str()).toDouble()); if (vec.size() == 3) { ml3.push_back(String(vec[2].c_str()).toDouble()); } } if (ml1.size() != 1 && ml1.size() != ms_exp_calib.size()) { writeLog_("Incorrect number of calibration constants given. Aborting!"); return INPUT_FILE_CORRUPT; } calib.setML1s(ml1); calib.setML2s(ml2); if (!ml3.empty()) calib.setML3s(ml3); //------------------------------------------------------------- // perform calibration //------------------------------------------------------------- if (getFlag_("peak_data")) { calib.calibrate(ms_exp_calib, ms_exp_raw, ref_masses); } else { calib.pickAndCalibrate(ms_exp_calib, ms_exp_raw, ref_masses); } //------------------------------------------------------------- // writing output //------------------------------------------------------------- //annotate output with data processing info addDataProcessing_(ms_exp_raw, getProcessingInfo_(DataProcessing::CALIBRATION)); mz_data_file.store(out, ms_exp_raw); return EXECUTION_OK; } }; int main(int argc, const char** argv) { TOPPTOFCalibration tool; return tool.main(argc, argv); } /// @endcond
#ifndef STAN_MATH_REV_FUN_TYPEDEFS_HPP #define STAN_MATH_REV_FUN_TYPEDEFS_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/fun/Eigen.hpp> namespace stan { namespace math { using size_type = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Index; /** * The type of a matrix holding <code>var</code> * values. */ using matrix_v = Eigen::Matrix<var, Eigen::Dynamic, Eigen::Dynamic>; /** * The type of a (column) vector holding <code>var</code> * values. */ using vector_v = Eigen::Matrix<var, Eigen::Dynamic, 1>; /** * The type of a row vector holding <code>var</code> * values. */ using row_vector_v = Eigen::Matrix<var, 1, Eigen::Dynamic>; /** * The type of a matrix holding <code>vari*</code> * values. */ using matrix_vi = Eigen::Matrix<vari*, Eigen::Dynamic, Eigen::Dynamic>; /** * The type of a (column) vector holding <code>vari*</code> * values. */ using vector_vi = Eigen::Matrix<vari*, Eigen::Dynamic, 1>; /** * The type of a row vector holding <code>vari*</code> * values. */ using row_vector_vi = Eigen::Matrix<vari*, 1, Eigen::Dynamic>; } // namespace math } // namespace stan #endif
/* * Copyright 2019 Azavea * * 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 <cstdint> #include <exception> #include <random> #include <boost/optional.hpp> #include <boost/compute/detail/lru_cache.hpp> #include <pthread.h> #include "bindings.h" #include "tokens.hpp" typedef boost::compute::detail::lru_cache<token_t, uri_options_t> lru_cache; static pthread_mutex_t token_lock; static lru_cache *cache = nullptr; static std::mt19937_64 g; static std::uniform_int_distribution<token_t> dist; /** * Initialize the token-management part of the library. */ void token_init(size_t size) { g = std::mt19937_64(std::random_device{}()); #if defined(_GNU_SOURCE) token_lock = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; #else token_lock = PTHREAD_MUTEX_INITIALIZER; #endif cache = new lru_cache(size); } /** * Deinitialize the token-management part of the library. */ void token_deinit() { if (cache != nullptr) { delete cache; } cache = nullptr; } /** * Generate a token. * * @return A (possibly used, possibly unused) token */ static token_t generate_token() { return dist(g); } /** * Return an unused token for the given uri ⨯ options pair. This is * not a function: two subsequent calls to it with the same pair as * input may produce different output. * * @param _uri A C-style string containing the URI * @param _options An array of C-style strings contains the warp options * @return A token that was not in use prior to the call */ uint64_t get_token(const char *_uri, const char **_options) { auto token = static_cast<token_t>(33); auto uri_options = std::make_pair(uri_t(_uri), options_t()); // Construct uri_options object from uri and options while (*_options != nullptr) { uri_options.second.push_back(std::string(*_options)); _options++; } if (pthread_mutex_lock(&token_lock) != 0) { fprintf(stderr, "%s:%d\n", __FILE__, __LINE__); return BAD_TOKEN; } while (cache->contains(token) || token == BAD_TOKEN) { token = generate_token(); } cache->insert(token, uri_options); pthread_mutex_unlock(&token_lock); return static_cast<uint64_t>(token); } /** * Get the uri ⨯ options pair associated with a token (if one exists). * * @param token The token of interest * @return An optional of type uri_options_t */ boost::optional<uri_options_t> query_token(uint64_t _token) { if (_token == BAD_TOKEN) { return boost::optional<uri_options_t>(); } else if (pthread_mutex_lock(&token_lock) != 0) { fprintf(stderr, "%s:%d\n", __FILE__, __LINE__); return boost::optional<uri_options_t>(); } else { auto token = static_cast<token_t>(_token); auto maybe_uri_options = cache->get(token); pthread_mutex_unlock(&token_lock); return maybe_uri_options; } }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2018 The PIVX developers // Copyright (c) 2020-2021 The The Masternode Hype Coin Exchange developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/sign.h" #include "primitives/transaction.h" #include "key.h" #include "keystore.h" #include "script/standard.h" #include "uint256.h" #include "util.h" #include <boost/foreach.hpp> using namespace std; typedef vector<unsigned char> valtype; bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet) { CKey key; if (!keystore.GetKey(address, key)) return false; vector<unsigned char> vchSig; if (!key.Sign(hash, vchSig)) return false; vchSig.push_back((unsigned char)nHashType); scriptSigRet << vchSig; return true; } bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet) { int nSigned = 0; int nRequired = multisigdata.front()[0]; for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++) { const valtype& pubkey = multisigdata[i]; CKeyID keyID = CPubKey(pubkey).GetID(); if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet)) ++nSigned; } return nSigned==nRequired; } /** * Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type. * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed), * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script. * Returns false if scriptPubKey could not be completely satisfied. */ bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet, txnouttype& whichTypeRet) { scriptSigRet.clear(); vector<valtype> vSolutions; if (!Solver(scriptPubKey, whichTypeRet, vSolutions)) { LogPrintf("*** solver solver failed \n"); return false; } CKeyID keyID; switch (whichTypeRet) { case TX_NONSTANDARD: case TX_NULL_DATA: { LogPrintf("*** null data \n"); return false; } case TX_ZEROCOINMINT: return false; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); if(!Sign1(keyID, keystore, hash, nHashType, scriptSigRet)) { LogPrintf("*** Sign1 failed \n"); return false; } return true; case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet)) { LogPrintf("*** solver failed to sign \n"); return false; } else { CPubKey vch; keystore.GetPubKey(keyID, vch); scriptSigRet << ToByteVector(vch); } return true; case TX_SCRIPTHASH: return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet); case TX_MULTISIG: scriptSigRet << OP_0; // workaround CHECKMULTISIG bug return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet)); } LogPrintf("*** solver no case met \n"); return false; } bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, int nHashType) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; // Leave out the signature from the hash, since a signature can't sign itself. // The checksig op will also drop the signatures from its hash. uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType); txnouttype whichType; if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType)) return false; if (whichType == TX_SCRIPTHASH) { // Solver returns the subscript that need to be evaluated; // the final scriptSig is the signatures from that // and then the serialized subscript: CScript subscript = txin.scriptSig; // Recompute txn hash using subscript in place of scriptPubKey: uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType); txnouttype subType; bool fSolved = Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH; // Append serialized subscript whether or not it is completely signed: txin.scriptSig << static_cast<valtype>(subscript); if (!fSolved) return false; } // Test solution return VerifyScript(txin.scriptSig, fromPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&txTo, nIn)); } bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; assert(txin.prevout.n < txFrom.vout.size()); const CTxOut& txout = txFrom.vout[txin.prevout.n]; return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType); } static CScript PushAll(const vector<valtype>& values) { CScript result; BOOST_FOREACH(const valtype& v, values) result << v; return result; } static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const vector<valtype>& vSolutions, const vector<valtype>& sigs1, const vector<valtype>& sigs2) { // Combine all the signatures we've got: set<valtype> allsigs; BOOST_FOREACH(const valtype& v, sigs1) { if (!v.empty()) allsigs.insert(v); } BOOST_FOREACH(const valtype& v, sigs2) { if (!v.empty()) allsigs.insert(v); } // Build a map of pubkey -> signature by matching sigs to pubkeys: assert(vSolutions.size() > 1); unsigned int nSigsRequired = vSolutions.front()[0]; unsigned int nPubKeys = vSolutions.size()-2; map<valtype, valtype> sigs; BOOST_FOREACH(const valtype& sig, allsigs) { for (unsigned int i = 0; i < nPubKeys; i++) { const valtype& pubkey = vSolutions[i+1]; if (sigs.count(pubkey)) continue; // Already got a sig for this pubkey if (TransactionSignatureChecker(&txTo, nIn).CheckSig(sig, pubkey, scriptPubKey)) { sigs[pubkey] = sig; break; } } } // Now build a merged CScript: unsigned int nSigsHave = 0; CScript result; result << OP_0; // pop-one-too-many workaround for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++) { if (sigs.count(vSolutions[i+1])) { result << sigs[vSolutions[i+1]]; ++nSigsHave; } } // Fill any missing with OP_0: for (unsigned int i = nSigsHave; i < nSigsRequired; i++) result << OP_0; return result; } static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const txnouttype txType, const vector<valtype>& vSolutions, vector<valtype>& sigs1, vector<valtype>& sigs2) { switch (txType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_ZEROCOINMINT: // Don't know anything about this, assume bigger one is correct: if (sigs1.size() >= sigs2.size()) return PushAll(sigs1); return PushAll(sigs2); case TX_PUBKEY: case TX_PUBKEYHASH: // Signatures are bigger than placeholders or empty scripts: if (sigs1.empty() || sigs1[0].empty()) return PushAll(sigs2); return PushAll(sigs1); case TX_SCRIPTHASH: if (sigs1.empty() || sigs1.back().empty()) return PushAll(sigs2); else if (sigs2.empty() || sigs2.back().empty()) return PushAll(sigs1); else { // Recur to combine: valtype spk = sigs1.back(); CScript pubKey2(spk.begin(), spk.end()); txnouttype txType2; vector<vector<unsigned char> > vSolutions2; Solver(pubKey2, txType2, vSolutions2); sigs1.pop_back(); sigs2.pop_back(); CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2); result << spk; return result; } case TX_MULTISIG: return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2); } return CScript(); } CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2) { txnouttype txType; vector<vector<unsigned char> > vSolutions; Solver(scriptPubKey, txType, vSolutions); vector<valtype> stack1; EvalScript(stack1, scriptSig1, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker()); vector<valtype> stack2; EvalScript(stack2, scriptSig2, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker()); return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2); }
/// \file MppDictionary2D.cpp /// \brief MppDictionary2D class /// \author Sylvain Prigent /// \version 0.1 /// \date 2018 #include "MppDictionary2DCircle.h" #include "MppShapeCircle.h" MppDictionary2DCircle::MppDictionary2DCircle(unsigned int min_r, unsigned int max_r, unsigned int step){ m_min_r = min_r; m_max_r = max_r; m_step = step; } MppDictionary2DCircle::~MppDictionary2DCircle(){ } void MppDictionary2DCircle::run() { m_dictionary = new std::vector<MppShape2D*>(m_max_r-m_min_r+1); for (int r = m_min_r ; r <= m_max_r ; r += m_step){ (*m_dictionary)[r-m_min_r] = new MppShapeCircle(0, 0, r); } }
/* src/common/port/inet_aton.cpp * * This inet_aton() function was taken from the GNU C library and * incorporated into Postgres for those systems which do not have this * routine in their standard C libraries. * * The function was been extracted whole from the file inet_aton.c in * Release 5.3.12 of the Linux C library, which is derived from the * GNU C library, by Bryan Henderson in October 1996. The copyright * notice from that file is below. */ /* * Copyright (c) 1983, 1990, 1993 * The Regents of the University of California. 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 University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "c.h" #include <netinet/in.h> #include <ctype.h> /* * Check whether "cp" is a valid ascii representation * of an Internet address and convert to a binary address. * Returns 1 if the address is valid, 0 if not. * This replaces inet_addr, the return value from which * cannot distinguish between failure and a local broadcast address. */ int inet_aton(const char* cp, struct in_addr* addr) { unsigned int val; int base, n; char c; u_int parts[4]; u_int* pp = parts; for (;;) { /* * Collect number up to ``.''. Values are specified as for C: 0x=hex, * 0=octal, other=decimal. */ val = 0; base = 10; if (*cp == '0') { if (*++cp == 'x' || *cp == 'X') { base = 16, cp++; } else { base = 8; } } while ((c = *cp) != '\0') { if (isdigit((unsigned char)c)) { val = (val * base) + (c - '0'); cp++; continue; } if (base == 16 && isxdigit((unsigned char)c)) { val = (val << 4) + (c + 10 - (islower((unsigned char)c) ? 'a' : 'A')); cp++; continue; } break; } if (*cp == '.') { /* * Internet format: a.b.c.d a.b.c (with c treated as 16-bits) * a.b (with b treated as 24 bits) */ if (pp >= parts + 3 || val > 0xff) { return 0; } *pp++ = val, cp++; } else { break; } } /* * Check for trailing junk. */ while (*cp) { if (!isspace((unsigned char)*cp++)) { return 0; } } /* * Concoct the address according to the number of parts specified. */ n = pp - parts + 1; switch (n) { case 1: /* a -- 32 bits */ break; case 2: /* a.b -- 8.24 bits */ if (val > 0xffffff) { return 0; } val |= parts[0] << 24; break; case 3: /* a.b.c -- 8.8.16 bits */ if (val > 0xffff) { return 0; } val |= (parts[0] << 24) | (parts[1] << 16); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ if (val > 0xff) { return 0; } val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); break; default: break; } if (addr != NULL) { addr->s_addr = htonl(val); } return 1; }
#include <algorithm> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/bias_layer.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" namespace caffe { template <typename TypeParam> class BiasLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: BiasLayerTest() : blob_bottom_(new Blob<Dtype>(2, 3, 4, 5)), blob_bottom_eltwise_(new Blob<Dtype>(2, 3, 4, 5)), blob_bottom_broadcast_0_(new Blob<Dtype>()), blob_bottom_broadcast_1_(new Blob<Dtype>()), blob_bottom_broadcast_2_(new Blob<Dtype>()), blob_bottom_bias_(new Blob<Dtype>(vector<int>())), blob_top_(new Blob<Dtype>()) { Caffe::set_random_seed(1701); vector<int> broadcast_shape(2); broadcast_shape[0] = 2; broadcast_shape[1] = 3; this->blob_bottom_broadcast_0_->Reshape(broadcast_shape); broadcast_shape[0] = 3; broadcast_shape[1] = 4; this->blob_bottom_broadcast_1_->Reshape(broadcast_shape); broadcast_shape[0] = 4; broadcast_shape[1] = 5; this->blob_bottom_broadcast_2_->Reshape(broadcast_shape); FillerParameter filler_param; filler_param.set_min(1); filler_param.set_max(10); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_bottom_eltwise_); filler.Fill(this->blob_bottom_broadcast_0_); filler.Fill(this->blob_bottom_broadcast_1_); filler.Fill(this->blob_bottom_broadcast_2_); filler.Fill(this->blob_bottom_bias_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~BiasLayerTest() { delete blob_bottom_; delete blob_bottom_eltwise_; delete blob_bottom_broadcast_0_; delete blob_bottom_broadcast_1_; delete blob_bottom_broadcast_2_; delete blob_bottom_bias_; delete blob_top_; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_bottom_eltwise_; Blob<Dtype>* const blob_bottom_broadcast_0_; Blob<Dtype>* const blob_bottom_broadcast_1_; Blob<Dtype>* const blob_bottom_broadcast_2_; Blob<Dtype>* const blob_bottom_bias_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(BiasLayerTest, TestDtypesAndDevices); TYPED_TEST(BiasLayerTest, TestForwardEltwise) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_eltwise_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(0); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* data = this->blob_top_->cpu_data(); const int count = this->blob_top_->count(); const Dtype* in_data_a = this->blob_bottom_->cpu_data(); const Dtype* in_data_b = this->blob_bottom_eltwise_->cpu_data(); for (int i = 0; i < count; ++i) { EXPECT_NEAR(data[i], in_data_a[i] + in_data_b[i], 1e-5); } } TYPED_TEST(BiasLayerTest, TestForwardEltwiseInPlace) { typedef typename TypeParam::Dtype Dtype; this->blob_top_vec_[0] = this->blob_bottom_; // in-place computation Blob<Dtype> orig_bottom(this->blob_bottom_->shape()); orig_bottom.CopyFrom(*this->blob_bottom_); this->blob_bottom_vec_.push_back(this->blob_bottom_eltwise_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(0); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* data = this->blob_bottom_->cpu_data(); const int count = this->blob_bottom_->count(); const Dtype* in_data_a = orig_bottom.cpu_data(); const Dtype* in_data_b = this->blob_bottom_eltwise_->cpu_data(); for (int i = 0; i < count; ++i) { EXPECT_NEAR(data[i], in_data_a[i] + in_data_b[i], 1e-5); } } TYPED_TEST(BiasLayerTest, TestBackwardEltwiseInPlace) { typedef typename TypeParam::Dtype Dtype; Blob<Dtype> orig_bottom(this->blob_bottom_->shape()); orig_bottom.CopyFrom(*this->blob_bottom_); this->blob_bottom_vec_.push_back(this->blob_bottom_eltwise_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(0); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); Blob<Dtype> top_diff(this->blob_bottom_->shape()); FillerParameter filler_param; filler_param.set_type("gaussian"); filler_param.set_std(1); GaussianFiller<Dtype> filler(filler_param); filler.Fill(&top_diff); vector<bool> propagate_down(2, true); // Run forward + backward without in-place computation; // save resulting bottom diffs. layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); caffe_copy(top_diff.count(), top_diff.cpu_data(), this->blob_top_->mutable_cpu_diff()); layer->Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); const bool kReshape = true; const bool kCopyDiff = true; Blob<Dtype> orig_bottom_diff; orig_bottom_diff.CopyFrom(*this->blob_bottom_, kCopyDiff, kReshape); Blob<Dtype> orig_bias_diff; orig_bias_diff.CopyFrom(*this->blob_bottom_eltwise_, kCopyDiff, kReshape); // Rerun forward + backward with in-place computation; // check that resulting bottom diffs are the same. this->blob_top_vec_[0] = this->blob_bottom_; // in-place computation layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); caffe_copy(top_diff.count(), top_diff.cpu_data(), this->blob_bottom_->mutable_cpu_diff()); layer->Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); for (int i = 0; i < this->blob_bottom_->count(); ++i) { EXPECT_NEAR(orig_bottom_diff.cpu_diff()[i], this->blob_bottom_->cpu_diff()[i], 1e-5); } for (int i = 0; i < this->blob_bottom_eltwise_->count(); ++i) { EXPECT_NEAR(orig_bias_diff.cpu_diff()[i], this->blob_bottom_eltwise_->cpu_diff()[i], 1e-5); } } TYPED_TEST(BiasLayerTest, TestForwardEltwiseWithParam) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; BiasParameter* bias_param = layer_param.mutable_bias_param(); bias_param->set_axis(0); bias_param->set_num_axes(-1); bias_param->mutable_filler()->set_type("gaussian"); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* data = this->blob_top_->cpu_data(); const int count = this->blob_top_->count(); const Dtype* in_data_a = this->blob_bottom_->cpu_data(); const Dtype* in_data_b = layer->blobs()[0]->cpu_data(); for (int i = 0; i < count; ++i) { EXPECT_NEAR(data[i], in_data_a[i] + in_data_b[i], 1e-5); } } TYPED_TEST(BiasLayerTest, TestForwardBroadcastBegin) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_0_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(0); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < this->blob_bottom_->num(); ++n) { for (int c = 0; c < this->blob_bottom_->channels(); ++c) { for (int h = 0; h < this->blob_bottom_->height(); ++h) { for (int w = 0; w < this->blob_bottom_->width(); ++w) { EXPECT_NEAR(this->blob_top_->data_at(n, c, h, w), this->blob_bottom_->data_at(n, c, h, w) + this->blob_bottom_broadcast_0_->data_at(n, c, 0, 0), 1e-5); } } } } } TYPED_TEST(BiasLayerTest, TestForwardBroadcastMiddle) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_1_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(1); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < this->blob_bottom_->num(); ++n) { for (int c = 0; c < this->blob_bottom_->channels(); ++c) { for (int h = 0; h < this->blob_bottom_->height(); ++h) { for (int w = 0; w < this->blob_bottom_->width(); ++w) { EXPECT_NEAR(this->blob_top_->data_at(n, c, h, w), this->blob_bottom_->data_at(n, c, h, w) + this->blob_bottom_broadcast_1_->data_at(c, h, 0, 0), 1e-5); } } } } } TYPED_TEST(BiasLayerTest, TestForwardBroadcastMiddleInPlace) { typedef typename TypeParam::Dtype Dtype; this->blob_top_vec_[0] = this->blob_bottom_; // in-place computation Blob<Dtype> orig_bottom(this->blob_bottom_->shape()); orig_bottom.CopyFrom(*this->blob_bottom_); this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_1_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(1); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < this->blob_bottom_->num(); ++n) { for (int c = 0; c < this->blob_bottom_->channels(); ++c) { for (int h = 0; h < this->blob_bottom_->height(); ++h) { for (int w = 0; w < this->blob_bottom_->width(); ++w) { EXPECT_NEAR(this->blob_bottom_->data_at(n, c, h, w), orig_bottom.data_at(n, c, h, w) + this->blob_bottom_broadcast_1_->data_at(c, h, 0, 0), 1e-5); } } } } } TYPED_TEST(BiasLayerTest, TestBackwardBroadcastMiddleInPlace) { typedef typename TypeParam::Dtype Dtype; Blob<Dtype> orig_bottom(this->blob_bottom_->shape()); orig_bottom.CopyFrom(*this->blob_bottom_); this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_1_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(1); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); Blob<Dtype> top_diff(this->blob_bottom_->shape()); FillerParameter filler_param; filler_param.set_type("gaussian"); filler_param.set_std(1); GaussianFiller<Dtype> filler(filler_param); filler.Fill(&top_diff); vector<bool> propagate_down(2, true); // Run forward + backward without in-place computation; // save resulting bottom diffs. layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); caffe_copy(top_diff.count(), top_diff.cpu_data(), this->blob_top_->mutable_cpu_diff()); layer->Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); const bool kReshape = true; const bool kCopyDiff = true; Blob<Dtype> orig_bottom_diff; orig_bottom_diff.CopyFrom(*this->blob_bottom_, kCopyDiff, kReshape); Blob<Dtype> orig_bias_diff; orig_bias_diff.CopyFrom(*this->blob_bottom_broadcast_1_, kCopyDiff, kReshape); // Rerun forward + backward with in-place computation; // check that resulting bottom diffs are the same. this->blob_top_vec_[0] = this->blob_bottom_; // in-place computation layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); caffe_copy(top_diff.count(), top_diff.cpu_data(), this->blob_bottom_->mutable_cpu_diff()); layer->Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); for (int i = 0; i < this->blob_bottom_->count(); ++i) { EXPECT_NEAR(orig_bottom_diff.cpu_diff()[i], this->blob_bottom_->cpu_diff()[i], 1e-5); } for (int i = 0; i < this->blob_bottom_broadcast_1_->count(); ++i) { EXPECT_NEAR(orig_bias_diff.cpu_diff()[i], this->blob_bottom_broadcast_1_->cpu_diff()[i], 1e-5); } } TYPED_TEST(BiasLayerTest, TestForwardBroadcastMiddleWithParam) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; BiasParameter* bias_param = layer_param.mutable_bias_param(); bias_param->set_axis(1); bias_param->set_num_axes(2); bias_param->mutable_filler()->set_type("gaussian"); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < this->blob_bottom_->num(); ++n) { for (int c = 0; c < this->blob_bottom_->channels(); ++c) { for (int h = 0; h < this->blob_bottom_->height(); ++h) { for (int w = 0; w < this->blob_bottom_->width(); ++w) { EXPECT_NEAR(this->blob_top_->data_at(n, c, h, w), this->blob_bottom_->data_at(n, c, h, w) + layer->blobs()[0]->data_at(c, h, 0, 0), 1e-5); } } } } } TYPED_TEST(BiasLayerTest, TestForwardBroadcastEnd) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_2_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(2); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < this->blob_bottom_->num(); ++n) { for (int c = 0; c < this->blob_bottom_->channels(); ++c) { for (int h = 0; h < this->blob_bottom_->height(); ++h) { for (int w = 0; w < this->blob_bottom_->width(); ++w) { EXPECT_NEAR(this->blob_top_->data_at(n, c, h, w), this->blob_bottom_->data_at(n, c, h, w) + this->blob_bottom_broadcast_2_->data_at(h, w, 0, 0), 1e-5); } } } } } TYPED_TEST(BiasLayerTest, TestForwardBias) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_bias_); LayerParameter layer_param; shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* data = this->blob_top_->cpu_data(); const int count = this->blob_top_->count(); const Dtype* in_data = this->blob_bottom_->cpu_data(); const Dtype bias = *this->blob_bottom_bias_->cpu_data(); for (int i = 0; i < count; ++i) { EXPECT_NEAR(data[i], in_data[i] + bias, 1e-5); } } TYPED_TEST(BiasLayerTest, TestForwardBiasAxis2) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_bias_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(2); shared_ptr<BiasLayer<Dtype> > layer(new BiasLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(this->blob_bottom_->shape(), this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* data = this->blob_top_->cpu_data(); const int count = this->blob_top_->count(); const Dtype* in_data = this->blob_bottom_->cpu_data(); const Dtype bias = *this->blob_bottom_bias_->cpu_data(); for (int i = 0; i < count; ++i) { EXPECT_NEAR(data[i], in_data[i] + bias, 1e-5); } } TYPED_TEST(BiasLayerTest, TestGradientEltwise) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_eltwise_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(0); BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientEltwise(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(BiasLayerTest, TestGradientEltwiseWithParam) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; BiasParameter* bias_param = layer_param.mutable_bias_param(); bias_param->set_axis(0); bias_param->set_num_axes(-1); bias_param->mutable_filler()->set_type("gaussian"); BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(BiasLayerTest, TestGradientBroadcastBegin) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_0_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(0); BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(BiasLayerTest, TestGradientBroadcastMiddle) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_1_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(1); BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(BiasLayerTest, TestGradientBroadcastMiddleWithParam) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_1_); LayerParameter layer_param; BiasParameter* bias_param = layer_param.mutable_bias_param(); bias_param->set_axis(1); bias_param->set_num_axes(2); bias_param->mutable_filler()->set_type("gaussian"); BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(BiasLayerTest, TestGradientBroadcastEnd) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_broadcast_2_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(2); BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(BiasLayerTest, TestGradientBias) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_bias_); LayerParameter layer_param; BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(BiasLayerTest, TestGradientBiasAxis2) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_bias_); LayerParameter layer_param; layer_param.mutable_bias_param()->set_axis(2); BiasLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } } // namespace caffe
#include "absl/strings/internal/str_format/parser.h" #include <string.h> #include "gtest/gtest.h" #include "absl/base/macros.h" namespace absl { namespace str_format_internal { namespace { TEST(LengthModTest, Names) { struct Expectation { int line; LengthMod::Id id; const char *name; }; const Expectation kExpect[] = { {__LINE__, LengthMod::none, "" }, {__LINE__, LengthMod::h, "h" }, {__LINE__, LengthMod::hh, "hh"}, {__LINE__, LengthMod::l, "l" }, {__LINE__, LengthMod::ll, "ll"}, {__LINE__, LengthMod::L, "L" }, {__LINE__, LengthMod::j, "j" }, {__LINE__, LengthMod::z, "z" }, {__LINE__, LengthMod::t, "t" }, {__LINE__, LengthMod::q, "q" }, }; EXPECT_EQ(ABSL_ARRAYSIZE(kExpect), LengthMod::kNumValues); for (auto e : kExpect) { SCOPED_TRACE(e.line); LengthMod mod = LengthMod::FromId(e.id); EXPECT_EQ(e.id, mod.id()); EXPECT_EQ(e.name, mod.name()); } } TEST(ConversionCharTest, Names) { struct Expectation { ConversionChar::Id id; char name; }; // clang-format off const Expectation kExpect[] = { #define X(c) {ConversionChar::c, #c[0]} X(c), X(C), X(s), X(S), // text X(d), X(i), X(o), X(u), X(x), X(X), // int X(f), X(F), X(e), X(E), X(g), X(G), X(a), X(A), // float X(n), X(p), // misc #undef X {ConversionChar::none, '\0'}, }; // clang-format on EXPECT_EQ(ABSL_ARRAYSIZE(kExpect), ConversionChar::kNumValues); for (auto e : kExpect) { SCOPED_TRACE(e.name); ConversionChar v = ConversionChar::FromId(e.id); EXPECT_EQ(e.id, v.id()); EXPECT_EQ(e.name, v.Char()); } } class ConsumeUnboundConversionTest : public ::testing::Test { public: typedef UnboundConversion Props; string_view Consume(string_view* src) { int next = 0; const char* prev_begin = src->data(); o = UnboundConversion(); // refresh ConsumeUnboundConversion(src, &o, &next); return {prev_begin, static_cast<size_t>(src->data() - prev_begin)}; } bool Run(const char *fmt, bool force_positional = false) { string_view src = fmt; int next = force_positional ? -1 : 0; o = UnboundConversion(); // refresh return ConsumeUnboundConversion(&src, &o, &next) && src.empty(); } UnboundConversion o; }; TEST_F(ConsumeUnboundConversionTest, ConsumeSpecification) { struct Expectation { int line; string_view src; string_view out; string_view src_post; }; const Expectation kExpect[] = { {__LINE__, "", "", "" }, {__LINE__, "b", "", "b" }, // 'b' is invalid {__LINE__, "ba", "", "ba"}, // 'b' is invalid {__LINE__, "l", "", "l" }, // just length mod isn't okay {__LINE__, "d", "d", "" }, // basic {__LINE__, "d ", "d", " " }, // leave suffix {__LINE__, "dd", "d", "d" }, // don't be greedy {__LINE__, "d9", "d", "9" }, // leave non-space suffix {__LINE__, "dzz", "d", "zz"}, // length mod as suffix {__LINE__, "1$*2$d", "1$*2$d", "" }, // arg indexing and * allowed. {__LINE__, "0-14.3hhd", "0-14.3hhd", ""}, // precision, width {__LINE__, " 0-+#14.3hhd", " 0-+#14.3hhd", ""}, // flags }; for (const auto& e : kExpect) { SCOPED_TRACE(e.line); string_view src = e.src; EXPECT_EQ(e.src, src); string_view out = Consume(&src); EXPECT_EQ(e.out, out); EXPECT_EQ(e.src_post, src); } } TEST_F(ConsumeUnboundConversionTest, BasicConversion) { EXPECT_FALSE(Run("")); EXPECT_FALSE(Run("z")); EXPECT_FALSE(Run("dd")); // no excess allowed EXPECT_TRUE(Run("d")); EXPECT_EQ('d', o.conv.Char()); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_LT(o.precision.value(), 0); EXPECT_EQ(1, o.arg_position); EXPECT_EQ(LengthMod::none, o.length_mod.id()); } TEST_F(ConsumeUnboundConversionTest, ArgPosition) { EXPECT_TRUE(Run("d")); EXPECT_EQ(1, o.arg_position); EXPECT_TRUE(Run("3$d")); EXPECT_EQ(3, o.arg_position); EXPECT_TRUE(Run("1$d")); EXPECT_EQ(1, o.arg_position); EXPECT_TRUE(Run("1$d", true)); EXPECT_EQ(1, o.arg_position); EXPECT_TRUE(Run("123$d")); EXPECT_EQ(123, o.arg_position); EXPECT_TRUE(Run("123$d", true)); EXPECT_EQ(123, o.arg_position); EXPECT_TRUE(Run("10$d")); EXPECT_EQ(10, o.arg_position); EXPECT_TRUE(Run("10$d", true)); EXPECT_EQ(10, o.arg_position); // Position can't be zero. EXPECT_FALSE(Run("0$d")); EXPECT_FALSE(Run("0$d", true)); EXPECT_FALSE(Run("1$*0$d")); EXPECT_FALSE(Run("1$.*0$d")); // Position can't start with a zero digit at all. That is not a 'decimal'. EXPECT_FALSE(Run("01$p")); EXPECT_FALSE(Run("01$p", true)); EXPECT_FALSE(Run("1$*01$p")); EXPECT_FALSE(Run("1$.*01$p")); } TEST_F(ConsumeUnboundConversionTest, WidthAndPrecision) { EXPECT_TRUE(Run("14d")); EXPECT_EQ('d', o.conv.Char()); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_EQ(14, o.width.value()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_LT(o.precision.value(), 0); EXPECT_TRUE(Run("14.d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(14, o.width.value()); EXPECT_EQ(0, o.precision.value()); EXPECT_TRUE(Run(".d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(0, o.precision.value()); EXPECT_TRUE(Run(".5d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(5, o.precision.value()); EXPECT_TRUE(Run(".0d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(0, o.precision.value()); EXPECT_TRUE(Run("14.5d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(14, o.width.value()); EXPECT_EQ(5, o.precision.value()); EXPECT_TRUE(Run("*.*d")); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(1, o.width.get_from_arg()); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(2, o.precision.get_from_arg()); EXPECT_EQ(3, o.arg_position); EXPECT_TRUE(Run("*d")); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(1, o.width.get_from_arg()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_LT(o.precision.value(), 0); EXPECT_EQ(2, o.arg_position); EXPECT_TRUE(Run(".*d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(1, o.precision.get_from_arg()); EXPECT_EQ(2, o.arg_position); // mixed implicit and explicit: didn't specify arg position. EXPECT_FALSE(Run("*23$.*34$d")); EXPECT_TRUE(Run("12$*23$.*34$d")); EXPECT_EQ(12, o.arg_position); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(23, o.width.get_from_arg()); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(34, o.precision.get_from_arg()); EXPECT_TRUE(Run("2$*5$.*9$d")); EXPECT_EQ(2, o.arg_position); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(5, o.width.get_from_arg()); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(9, o.precision.get_from_arg()); EXPECT_FALSE(Run(".*0$d")) << "no arg 0"; // Large values EXPECT_TRUE(Run("999999999.999999999d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_EQ(999999999, o.width.value()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(999999999, o.precision.value()); EXPECT_FALSE(Run("1000000000.999999999d")); EXPECT_FALSE(Run("999999999.1000000000d")); EXPECT_FALSE(Run("9999999999d")); EXPECT_FALSE(Run(".9999999999d")); } TEST_F(ConsumeUnboundConversionTest, Flags) { static const char kAllFlags[] = "-+ #0"; static const int kNumFlags = ABSL_ARRAYSIZE(kAllFlags) - 1; for (int rev = 0; rev < 2; ++rev) { for (int i = 0; i < 1 << kNumFlags; ++i) { std::string fmt; for (int k = 0; k < kNumFlags; ++k) if ((i >> k) & 1) fmt += kAllFlags[k]; // flag order shouldn't matter if (rev == 1) { std::reverse(fmt.begin(), fmt.end()); } fmt += 'd'; SCOPED_TRACE(fmt); EXPECT_TRUE(Run(fmt.c_str())); EXPECT_EQ(fmt.find('-') == std::string::npos, !o.flags.left); EXPECT_EQ(fmt.find('+') == std::string::npos, !o.flags.show_pos); EXPECT_EQ(fmt.find(' ') == std::string::npos, !o.flags.sign_col); EXPECT_EQ(fmt.find('#') == std::string::npos, !o.flags.alt); EXPECT_EQ(fmt.find('0') == std::string::npos, !o.flags.zero); } } } TEST_F(ConsumeUnboundConversionTest, BasicFlag) { // Flag is on for (const char* fmt : {"d", "llx", "G", "1$X"}) { SCOPED_TRACE(fmt); EXPECT_TRUE(Run(fmt)); EXPECT_TRUE(o.flags.basic); } // Flag is off for (const char* fmt : {"3d", ".llx", "-G", "1$#X"}) { SCOPED_TRACE(fmt); EXPECT_TRUE(Run(fmt)); EXPECT_FALSE(o.flags.basic); } } struct SummarizeConsumer { std::string* out; explicit SummarizeConsumer(std::string* out) : out(out) {} bool Append(string_view s) { *out += "[" + std::string(s) + "]"; return true; } bool ConvertOne(const UnboundConversion& conv, string_view s) { *out += "{"; *out += std::string(s); *out += ":"; *out += std::to_string(conv.arg_position) + "$"; if (conv.width.is_from_arg()) { *out += std::to_string(conv.width.get_from_arg()) + "$*"; } if (conv.precision.is_from_arg()) { *out += "." + std::to_string(conv.precision.get_from_arg()) + "$*"; } *out += conv.conv.Char(); *out += "}"; return true; } }; std::string SummarizeParsedFormat(const ParsedFormatBase& pc) { std::string out; if (!pc.ProcessFormat(SummarizeConsumer(&out))) out += "!"; return out; } class ParsedFormatTest : public testing::Test {}; TEST_F(ParsedFormatTest, ValueSemantics) { ParsedFormatBase p1({}, true, {}); // empty format EXPECT_EQ("", SummarizeParsedFormat(p1)); ParsedFormatBase p2 = p1; // copy construct (empty) EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p2)); p1 = ParsedFormatBase("hello%s", true, {Conv::s}); // move assign EXPECT_EQ("[hello]{s:1$s}", SummarizeParsedFormat(p1)); ParsedFormatBase p3 = p1; // copy construct (nonempty) EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p3)); using std::swap; swap(p1, p2); EXPECT_EQ("", SummarizeParsedFormat(p1)); EXPECT_EQ("[hello]{s:1$s}", SummarizeParsedFormat(p2)); swap(p1, p2); // undo p2 = p1; // copy assign EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p2)); } struct ExpectParse { const char* in; std::initializer_list<Conv> conv_set; const char* out; }; TEST_F(ParsedFormatTest, Parsing) { // Parse should be equivalent to that obtained by ConversionParseIterator. // No need to retest the parsing edge cases here. const ExpectParse kExpect[] = { {"", {}, ""}, {"ab", {}, "[ab]"}, {"a%d", {Conv::d}, "[a]{d:1$d}"}, {"a%+d", {Conv::d}, "[a]{+d:1$d}"}, {"a% d", {Conv::d}, "[a]{ d:1$d}"}, {"a%b %d", {}, "[a]!"}, // stop after error }; for (const auto& e : kExpect) { SCOPED_TRACE(e.in); EXPECT_EQ(e.out, SummarizeParsedFormat(ParsedFormatBase(e.in, false, e.conv_set))); } } TEST_F(ParsedFormatTest, ParsingFlagOrder) { const ExpectParse kExpect[] = { {"a%+ 0d", {Conv::d}, "[a]{+ 0d:1$d}"}, {"a%+0 d", {Conv::d}, "[a]{+0 d:1$d}"}, {"a%0+ d", {Conv::d}, "[a]{0+ d:1$d}"}, {"a% +0d", {Conv::d}, "[a]{ +0d:1$d}"}, {"a%0 +d", {Conv::d}, "[a]{0 +d:1$d}"}, {"a% 0+d", {Conv::d}, "[a]{ 0+d:1$d}"}, {"a%+ 0+d", {Conv::d}, "[a]{+ 0+d:1$d}"}, }; for (const auto& e : kExpect) { SCOPED_TRACE(e.in); EXPECT_EQ(e.out, SummarizeParsedFormat(ParsedFormatBase(e.in, false, e.conv_set))); } } } // namespace } // namespace str_format_internal } // namespace absl
/** @file VfrCompiler main class and main function. Copyright (c) 2004 - 2016, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "stdio.h" #include "stdlib.h" #include "string.h" #include "VfrCompiler.h" #include "CommonLib.h" #include "EfiUtilityMsgs.h" PACKAGE_DATA gCBuffer; PACKAGE_DATA gRBuffer; CVfrStringDB gCVfrStringDB; VOID CVfrCompiler::DebugError ( IN CHAR8 *FileName, IN UINT32 LineNumber, IN UINT32 MessageCode, IN CONST CHAR8 *Text, IN CONST CHAR8 *MsgFmt, ... ) { va_list List; va_start (List, MsgFmt); PrintMessage ((CHAR8 *) "ERROR", FileName, LineNumber, MessageCode, (CHAR8 *) Text, (CHAR8 *) MsgFmt, List); va_end (List); } VOID CVfrCompiler::SET_RUN_STATUS ( IN COMPILER_RUN_STATUS Status ) { mRunStatus = Status; } BOOLEAN CVfrCompiler::IS_RUN_STATUS ( IN COMPILER_RUN_STATUS Status ) { return mRunStatus == Status; } VOID CVfrCompiler::OptionInitialization ( IN INT32 Argc, IN CHAR8 **Argv ) { INT32 Index; EFI_STATUS Status; Status = EFI_SUCCESS; SetUtilityName ((CHAR8*) PROGRAM_NAME); mOptions.VfrFileName = NULL; mOptions.RecordListFile = NULL; mOptions.CreateRecordListFile = FALSE; mOptions.CreateIfrPkgFile = FALSE; mOptions.PkgOutputFileName = NULL; mOptions.COutputFileName = NULL; mOptions.OutputDirectory = NULL; mOptions.PreprocessorOutputFileName = NULL; mOptions.VfrBaseFileName = NULL; mOptions.IncludePaths = NULL; mOptions.SkipCPreprocessor = TRUE; mOptions.CPreprocessorOptions = NULL; mOptions.CompatibleMode = FALSE; mOptions.HasOverrideClassGuid = FALSE; mOptions.WarningAsError = FALSE; mOptions.AutoDefault = FALSE; mOptions.CheckDefault = FALSE; memset (&mOptions.OverrideClassGuid, 0, sizeof (EFI_GUID)); if (Argc == 1) { Usage (); SET_RUN_STATUS (STATUS_DEAD); return; } for (Index = 1; (Index < Argc) && (Argv[Index][0] == '-'); Index++) { if ((stricmp(Argv[Index], "-h") == 0) || (stricmp(Argv[Index], "--help") == 0)) { Usage (); SET_RUN_STATUS (STATUS_DEAD); return; } else if (stricmp(Argv[Index], "--version") == 0) { Version (); SET_RUN_STATUS (STATUS_DEAD); return; } else if (stricmp(Argv[Index], "-l") == 0) { mOptions.CreateRecordListFile = TRUE; gCIfrRecordInfoDB.TurnOn (); } else if (stricmp(Argv[Index], "-i") == 0) { Index++; if ((Index >= Argc) || (Argv[Index][0] == '-')) { DebugError (NULL, 0, 1001, "Missing option", "-i missing path argument"); goto Fail; } AppendIncludePath(Argv[Index]); } else if (stricmp(Argv[Index], "-o") == 0 || stricmp(Argv[Index], "--output-directory") == 0 || stricmp(Argv[Index], "-od") == 0) { Index++; if ((Index >= Argc) || (Argv[Index][0] == '-')) { DebugError (NULL, 0, 1001, "Missing option", "-o missing output directory name"); goto Fail; } if (strlen (Argv[Index]) > MAX_PATH - 1) { DebugError (NULL, 0, 1003, "Invalid option value", "Output directory name %s is too long", Argv[Index]); goto Fail; } mOptions.OutputDirectory = (CHAR8 *) malloc (strlen (Argv[Index]) + strlen ("\\") + 1); if (mOptions.OutputDirectory == NULL) { DebugError (NULL, 0, 4001, "Resource: memory can't be allocated", NULL); goto Fail; } strcpy (mOptions.OutputDirectory, Argv[Index]); CHAR8 lastChar = mOptions.OutputDirectory[strlen(mOptions.OutputDirectory) - 1]; if ((lastChar != '/') && (lastChar != '\\')) { if (strchr(mOptions.OutputDirectory, '/') != NULL) { strcat (mOptions.OutputDirectory, "/"); } else { strcat (mOptions.OutputDirectory, "\\"); } } DebugMsg (NULL, 0, 9, (CHAR8 *) "Output Directory", (CHAR8 *) "%s", mOptions.OutputDirectory); } else if (stricmp(Argv[Index], "-b") == 0 || stricmp(Argv[Index], "--create-ifr-package") == 0 || stricmp(Argv[Index], "-ibin") == 0) { mOptions.CreateIfrPkgFile = TRUE; } else if (stricmp(Argv[Index], "-n") == 0 || stricmp(Argv[Index], "--no-pre-processing") == 0 || stricmp(Argv[Index], "-nopp") == 0) { mOptions.SkipCPreprocessor = TRUE; } else if (stricmp(Argv[Index], "-f") == 0 || stricmp(Argv[Index], "--pre-processing-flag") == 0 || stricmp(Argv[Index], "-ppflag") == 0) { Index++; if ((Index >= Argc) || (Argv[Index][0] == '-')) { DebugError (NULL, 0, 1001, "Missing option", "-od - missing C-preprocessor argument"); goto Fail; } AppendCPreprocessorOptions (Argv[Index]); } else if (stricmp(Argv[Index], "-c") == 0 || stricmp(Argv[Index], "--compatible-framework") == 0) { mOptions.CompatibleMode = TRUE; } else if (stricmp(Argv[Index], "-s") == 0|| stricmp(Argv[Index], "--string-db") == 0) { Index++; if ((Index >= Argc) || (Argv[Index][0] == '-')) { DebugError (NULL, 0, 1001, "Missing option", "-s missing input string file name"); goto Fail; } gCVfrStringDB.SetStringFileName(Argv[Index]); DebugMsg (NULL, 0, 9, (CHAR8 *) "Input string file path", (CHAR8 *) "%s", Argv[Index]); } else if ((stricmp (Argv[Index], "-g") == 0) || (stricmp (Argv[Index], "--guid") == 0)) { Index++; Status = StringToGuid (Argv[Index], &mOptions.OverrideClassGuid); if (EFI_ERROR (Status)) { DebugError (NULL, 0, 1000, "Invalid format:", "%s", Argv[Index]); goto Fail; } mOptions.HasOverrideClassGuid = TRUE; } else if (stricmp(Argv[Index], "-w") == 0 || stricmp(Argv[Index], "--warning-as-error") == 0) { mOptions.WarningAsError = TRUE; } else if (stricmp(Argv[Index], "-a") == 0 ||stricmp(Argv[Index], "--autodefault") == 0) { mOptions.AutoDefault = TRUE; } else if (stricmp(Argv[Index], "-d") == 0 ||stricmp(Argv[Index], "--checkdefault") == 0) { mOptions.CheckDefault = TRUE; } else { DebugError (NULL, 0, 1000, "Unknown option", "unrecognized option %s", Argv[Index]); goto Fail; } } if (Index != Argc - 1) { DebugError (NULL, 0, 1001, "Missing option", "VFR file name is not specified."); goto Fail; } else { if (strlen (Argv[Index]) > MAX_PATH) { DebugError (NULL, 0, 1003, "Invalid option value", "VFR file name %s is too long.", Argv[Index]); goto Fail; } mOptions.VfrFileName = (CHAR8 *) malloc (strlen (Argv[Index]) + 1); if (mOptions.VfrFileName == NULL) { DebugError (NULL, 0, 4001, "Resource: memory can't be allocated", NULL); goto Fail; } strcpy (mOptions.VfrFileName, Argv[Index]); if (mOptions.OutputDirectory == NULL) { mOptions.OutputDirectory = (CHAR8 *) malloc (1); if (mOptions.OutputDirectory == NULL) { DebugError (NULL, 0, 4001, "Resource: memory can't be allocated", NULL); goto Fail; } mOptions.OutputDirectory[0] = '\0'; } } if (SetBaseFileName() != 0) { goto Fail; } if (SetPkgOutputFileName () != 0) { goto Fail; } if (SetCOutputFileName() != 0) { goto Fail; } if (SetPreprocessorOutputFileName () != 0) { goto Fail; } if (SetRecordListFileName () != 0) { goto Fail; } return; Fail: SET_RUN_STATUS (STATUS_DEAD); mOptions.CreateRecordListFile = FALSE; mOptions.CreateIfrPkgFile = FALSE; if (mOptions.VfrFileName != NULL) { free (mOptions.VfrFileName); mOptions.VfrFileName = NULL; } if (mOptions.VfrBaseFileName != NULL) { free (mOptions.VfrBaseFileName); mOptions.VfrBaseFileName = NULL; } if (mOptions.OutputDirectory != NULL) { free (mOptions.OutputDirectory); mOptions.OutputDirectory = NULL; } if (mOptions.PkgOutputFileName != NULL) { free (mOptions.PkgOutputFileName); mOptions.PkgOutputFileName = NULL; } if (mOptions.COutputFileName != NULL) { free (mOptions.COutputFileName); mOptions.COutputFileName = NULL; } if (mOptions.PreprocessorOutputFileName != NULL) { free (mOptions.PreprocessorOutputFileName); mOptions.PreprocessorOutputFileName = NULL; } if (mOptions.RecordListFile != NULL) { free (mOptions.RecordListFile); mOptions.RecordListFile = NULL; } if (mOptions.IncludePaths != NULL) { delete mOptions.IncludePaths; mOptions.IncludePaths = NULL; } if (mOptions.CPreprocessorOptions != NULL) { delete mOptions.CPreprocessorOptions; mOptions.CPreprocessorOptions = NULL; } } VOID CVfrCompiler::AppendIncludePath ( IN CHAR8 *PathStr ) { UINT32 Len = 0; CHAR8 *IncludePaths = NULL; Len = strlen (" -I ") + strlen (PathStr) + 1; if (mOptions.IncludePaths != NULL) { Len += strlen (mOptions.IncludePaths); } IncludePaths = new CHAR8[Len]; if (IncludePaths == NULL) { DebugError (NULL, 0, 4001, "Resource: memory can't be allocated", NULL); return; } IncludePaths[0] = '\0'; if (mOptions.IncludePaths != NULL) { strcat (IncludePaths, mOptions.IncludePaths); } strcat (IncludePaths, " -I "); strcat (IncludePaths, PathStr); if (mOptions.IncludePaths != NULL) { delete mOptions.IncludePaths; } mOptions.IncludePaths = IncludePaths; } VOID CVfrCompiler::AppendCPreprocessorOptions ( IN CHAR8 *Options ) { UINT32 Len = 0; CHAR8 *Opt = NULL; Len = strlen (Options) + strlen (" ") + 1; if (mOptions.CPreprocessorOptions != NULL) { Len += strlen (mOptions.CPreprocessorOptions); } Opt = new CHAR8[Len]; if (Opt == NULL) { DebugError (NULL, 0, 4001, "Resource: memory can't be allocated", NULL); return; } Opt[0] = 0; if (mOptions.CPreprocessorOptions != NULL) { strcat (Opt, mOptions.CPreprocessorOptions); } strcat (Opt, " "); strcat (Opt, Options); if (mOptions.CPreprocessorOptions != NULL) { delete mOptions.CPreprocessorOptions; } mOptions.CPreprocessorOptions = Opt; } INT8 CVfrCompiler::SetBaseFileName ( VOID ) { CHAR8 *pFileName, *pPath, *pExt; if (mOptions.VfrFileName == NULL) { return -1; } pFileName = mOptions.VfrFileName; while ( ((pPath = strchr (pFileName, '\\')) != NULL) || ((pPath = strchr (pFileName, '/')) != NULL) ) { pFileName = pPath + 1; } if (pFileName == NULL) { return -1; } if ((pExt = strchr (pFileName, '.')) == NULL) { return -1; } *pExt = '\0'; if (strlen (pFileName) > MAX_PATH - 1) { *pExt = '.'; return -1; } mOptions.VfrBaseFileName = (CHAR8 *) malloc (strlen (pFileName) + 1); if (mOptions.VfrBaseFileName == NULL) { *pExt = '.'; return -1; } strcpy (mOptions.VfrBaseFileName, pFileName); *pExt = '.'; return 0; } INT8 CVfrCompiler::SetPkgOutputFileName ( VOID ) { INTN Length; if (mOptions.VfrBaseFileName == NULL) { return -1; } Length = strlen (mOptions.OutputDirectory) + strlen (mOptions.VfrBaseFileName) + strlen (VFR_PACKAGE_FILENAME_EXTENSION) + 1; if (Length > MAX_PATH) { return -1; } mOptions.PkgOutputFileName = (CHAR8 *) malloc (Length); if (mOptions.PkgOutputFileName == NULL) { return -1; } strcpy (mOptions.PkgOutputFileName, mOptions.OutputDirectory); strcat (mOptions.PkgOutputFileName, mOptions.VfrBaseFileName); strcat (mOptions.PkgOutputFileName, VFR_PACKAGE_FILENAME_EXTENSION); return 0; } INT8 CVfrCompiler::SetCOutputFileName ( VOID ) { INTN Length; if (mOptions.VfrBaseFileName == NULL) { return -1; } Length = strlen (mOptions.OutputDirectory) + strlen (mOptions.VfrBaseFileName) + strlen (".c") + 1; if (Length > MAX_PATH) { return -1; } mOptions.COutputFileName = (CHAR8 *) malloc (Length); if (mOptions.COutputFileName == NULL) { return -1; } strcpy (mOptions.COutputFileName, mOptions.OutputDirectory); strcat (mOptions.COutputFileName, mOptions.VfrBaseFileName); strcat (mOptions.COutputFileName, ".c"); return 0; } INT8 CVfrCompiler::SetPreprocessorOutputFileName ( VOID ) { INTN Length; if (mOptions.VfrBaseFileName == NULL) { return -1; } Length = strlen (mOptions.OutputDirectory) + strlen (mOptions.VfrBaseFileName) + strlen (VFR_PREPROCESS_FILENAME_EXTENSION) + 1; if (Length > MAX_PATH) { return -1; } mOptions.PreprocessorOutputFileName = (CHAR8 *) malloc (Length); if (mOptions.PreprocessorOutputFileName == NULL) { return -1; } strcpy (mOptions.PreprocessorOutputFileName, mOptions.OutputDirectory); strcat (mOptions.PreprocessorOutputFileName, mOptions.VfrBaseFileName); strcat (mOptions.PreprocessorOutputFileName, VFR_PREPROCESS_FILENAME_EXTENSION); return 0; } INT8 CVfrCompiler::SetRecordListFileName ( VOID ) { INTN Length; if (mOptions.VfrBaseFileName == NULL) { return -1; } Length = strlen (mOptions.OutputDirectory) + strlen (mOptions.VfrBaseFileName) + strlen (VFR_RECORDLIST_FILENAME_EXTENSION) + 1; if (Length > MAX_PATH) { return -1; } mOptions.RecordListFile = (CHAR8 *) malloc (Length); if (mOptions.RecordListFile == NULL) { return -1; } strcpy (mOptions.RecordListFile, mOptions.OutputDirectory); strcat (mOptions.RecordListFile, mOptions.VfrBaseFileName); strcat (mOptions.RecordListFile, VFR_RECORDLIST_FILENAME_EXTENSION); return 0; } CVfrCompiler::CVfrCompiler ( IN INT32 Argc, IN CHAR8 **Argv ) { mPreProcessCmd = (CHAR8 *) PREPROCESSOR_COMMAND; mPreProcessOpt = (CHAR8 *) PREPROCESSOR_OPTIONS; SET_RUN_STATUS (STATUS_STARTED); OptionInitialization(Argc, Argv); if ((IS_RUN_STATUS(STATUS_FAILED)) || (IS_RUN_STATUS(STATUS_DEAD))) { return; } SET_RUN_STATUS(STATUS_INITIALIZED); } CVfrCompiler::~CVfrCompiler ( VOID ) { if (mOptions.VfrFileName != NULL) { free (mOptions.VfrFileName); mOptions.VfrFileName = NULL; } if (mOptions.VfrBaseFileName != NULL) { free (mOptions.VfrBaseFileName); mOptions.VfrBaseFileName = NULL; } if (mOptions.OutputDirectory != NULL) { free (mOptions.OutputDirectory); mOptions.OutputDirectory = NULL; } if (mOptions.PkgOutputFileName != NULL) { free (mOptions.PkgOutputFileName); mOptions.PkgOutputFileName = NULL; } if (mOptions.COutputFileName != NULL) { free (mOptions.COutputFileName); mOptions.COutputFileName = NULL; } if (mOptions.PreprocessorOutputFileName != NULL) { free (mOptions.PreprocessorOutputFileName); mOptions.PreprocessorOutputFileName = NULL; } if (mOptions.RecordListFile != NULL) { free (mOptions.RecordListFile); mOptions.RecordListFile = NULL; } if (mOptions.IncludePaths != NULL) { delete mOptions.IncludePaths; mOptions.IncludePaths = NULL; } if (mOptions.CPreprocessorOptions != NULL) { delete mOptions.CPreprocessorOptions; mOptions.CPreprocessorOptions = NULL; } SET_RUN_STATUS(STATUS_DEAD); } VOID CVfrCompiler::Usage ( VOID ) { UINT32 Index; CONST CHAR8 *Help[] = { " ", "VfrCompile version " VFR_COMPILER_VERSION "Build " __BUILD_VERSION, "Copyright (c) 2004-2016 Intel Corporation. All rights reserved.", " ", "Usage: VfrCompile [options] VfrFile", " ", "Options:", " -h, --help prints this help", " --version prints version info", " -l create an output IFR listing file", " -o DIR, --output-directory DIR", " deposit all output files to directory OutputDir", " default is current directory", " -b, --create-ifr-package", " create an IFR HII pack file", " -n, --no-pre-processing", " do not preprocessing input file", " -c, --compatible-framework", " compatible framework vfr file", " -s, --string-db", " input uni string package file", " -g, --guid", " override class guid input", " format is xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", " -w --warning-as-error", " treat warning as an error", " -a --autodefaut generate default value for question opcode if some default is missing", " -d --checkdefault check the default information in a question opcode", NULL }; for (Index = 0; Help[Index] != NULL; Index++) { fprintf (stdout, "%s\n", Help[Index]); } } VOID CVfrCompiler::Version ( VOID ) { UINT32 Index; CONST CHAR8 *Help[] = { "VfrCompile version " VFR_COMPILER_VERSION "Build " __BUILD_VERSION, NULL }; for (Index = 0; Help[Index] != NULL; Index++) { fprintf (stdout, "%s\n", Help[Index]); } } VOID CVfrCompiler::PreProcess ( VOID ) { FILE *pVfrFile = NULL; UINT32 CmdLen = 0; CHAR8 *PreProcessCmd = NULL; if (!IS_RUN_STATUS(STATUS_INITIALIZED)) { goto Fail; } if (mOptions.SkipCPreprocessor == TRUE) { goto Out; } if ((pVfrFile = fopen (LongFilePath (mOptions.VfrFileName), "r")) == NULL) { DebugError (NULL, 0, 0001, "Error opening the input VFR file", mOptions.VfrFileName); goto Fail; } fclose (pVfrFile); CmdLen = strlen (mPreProcessCmd) + strlen (mPreProcessOpt) + strlen (mOptions.VfrFileName) + strlen (mOptions.PreprocessorOutputFileName); if (mOptions.CPreprocessorOptions != NULL) { CmdLen += strlen (mOptions.CPreprocessorOptions); } if (mOptions.IncludePaths != NULL) { CmdLen += strlen (mOptions.IncludePaths); } PreProcessCmd = new CHAR8[CmdLen + 10]; if (PreProcessCmd == NULL) { DebugError (NULL, 0, 4001, "Resource: memory can't be allocated", NULL); goto Fail; } strcpy (PreProcessCmd, mPreProcessCmd), strcat (PreProcessCmd, " "); strcat (PreProcessCmd, mPreProcessOpt), strcat (PreProcessCmd, " "); if (mOptions.IncludePaths != NULL) { strcat (PreProcessCmd, mOptions.IncludePaths), strcat (PreProcessCmd, " "); } if (mOptions.CPreprocessorOptions != NULL) { strcat (PreProcessCmd, mOptions.CPreprocessorOptions), strcat (PreProcessCmd, " "); } strcat (PreProcessCmd, mOptions.VfrFileName), strcat (PreProcessCmd, " > "); strcat (PreProcessCmd, mOptions.PreprocessorOutputFileName); if (system (PreProcessCmd) != 0) { DebugError (NULL, 0, 0003, "Error parsing file", "failed to spawn C preprocessor on VFR file %s\n", PreProcessCmd); goto Fail; } delete[] PreProcessCmd; Out: SET_RUN_STATUS (STATUS_PREPROCESSED); return; Fail: if (!IS_RUN_STATUS(STATUS_DEAD)) { SET_RUN_STATUS (STATUS_FAILED); } delete[] PreProcessCmd; } extern UINT8 VfrParserStart (IN FILE *, IN INPUT_INFO_TO_SYNTAX *); VOID CVfrCompiler::Compile ( VOID ) { FILE *pInFile = NULL; CHAR8 *InFileName = NULL; INPUT_INFO_TO_SYNTAX InputInfo; if (!IS_RUN_STATUS(STATUS_PREPROCESSED)) { goto Fail; } InFileName = (mOptions.SkipCPreprocessor == TRUE) ? mOptions.VfrFileName : mOptions.PreprocessorOutputFileName; gCVfrErrorHandle.SetInputFile (InFileName); gCVfrErrorHandle.SetWarningAsError(mOptions.WarningAsError); if ((pInFile = fopen (LongFilePath (InFileName), "r")) == NULL) { DebugError (NULL, 0, 0001, "Error opening the input file", InFileName); goto Fail; } InputInfo.CompatibleMode = mOptions.CompatibleMode; if (mOptions.HasOverrideClassGuid) { InputInfo.OverrideClassGuid = &mOptions.OverrideClassGuid; } else { InputInfo.OverrideClassGuid = NULL; } if (VfrParserStart (pInFile, &InputInfo) != 0) { goto Fail; } fclose (pInFile); if (gCFormPkg.HavePendingUnassigned () == TRUE) { gCFormPkg.PendingAssignPrintAll (); goto Fail; } SET_RUN_STATUS (STATUS_COMPILEED); return; Fail: if (!IS_RUN_STATUS(STATUS_DEAD)) { DebugError (NULL, 0, 0003, "Error parsing", "compile error in file %s", InFileName); SET_RUN_STATUS (STATUS_FAILED); } if (pInFile != NULL) { fclose (pInFile); } } VOID CVfrCompiler::AdjustBin ( VOID ) { EFI_VFR_RETURN_CODE Status; if (!IS_RUN_STATUS(STATUS_COMPILEED)) { return; } if (gNeedAdjustOpcode) { // // When parsing the Vfr, has created some opcodes, now need to update the record info. // gCIfrRecordInfoDB.IfrUpdateRecordInfoForDynamicOpcode (FALSE); } // // Check whether need to check default info for question or auto add default for question. // if (mOptions.AutoDefault || mOptions.CheckDefault) { gCIfrRecordInfoDB.IfrCheckAddDefaultRecord (mOptions.AutoDefault, mOptions.CheckDefault); } // // Check Binary Code consistent between Form and IfrRecord // // // Get Package Data and IfrRecord Data // gCFormPkg.BuildPkg (gCBuffer); gCIfrRecordInfoDB.IfrRecordOutput (gRBuffer); // // Compare Form and Record data // if (gCBuffer.Buffer != NULL && gRBuffer.Buffer != NULL) { UINT32 Index; if (gCBuffer.Size != gRBuffer.Size) { DebugError (NULL, 0, 0001, "Error parsing vfr file", " %s. FormBinary Size 0x%X is not same to RecordBuffer Size 0x%X", mOptions.VfrFileName, gCBuffer.Size, gRBuffer.Size); } for (Index = 0; Index < gCBuffer.Size; Index ++) { if (gCBuffer.Buffer[Index] != gRBuffer.Buffer[Index]) { break; } } if (Index != gCBuffer.Size) { DebugError (NULL, 0, 0001, "Error parsing vfr file", " %s. the 0x%X byte is different between Form and Record", mOptions.VfrFileName, Index); } DebugMsg (NULL, 0, 9, (CHAR8 *) "IFR Buffer", (CHAR8 *) "Form Buffer same to Record Buffer and Size is 0x%X", Index); } else if (gCBuffer.Buffer == NULL && gRBuffer.Buffer == NULL) { //ok } else { DebugError (NULL, 0, 0001, "Error parsing vfr file", " %s.Buffer not allocated.", mOptions.VfrFileName); } // // For UEFI mode, not do OpCode Adjust // if (mOptions.CompatibleMode) { // // Adjust Opcode to be compatible with framework vfr // Status = gCIfrRecordInfoDB.IfrRecordAdjust (); if (Status != VFR_RETURN_SUCCESS) { // // Record List Adjust Failed // SET_RUN_STATUS (STATUS_FAILED); return; } // // Re get the IfrRecord Buffer. // gCIfrRecordInfoDB.IfrRecordOutput (gRBuffer); } return; } VOID CVfrCompiler::GenBinary ( VOID ) { FILE *pFile = NULL; if (!IS_RUN_STATUS(STATUS_COMPILEED)) { goto Fail; } if (mOptions.CreateIfrPkgFile == TRUE) { if ((pFile = fopen (LongFilePath (mOptions.PkgOutputFileName), "wb")) == NULL) { DebugError (NULL, 0, 0001, "Error opening file", mOptions.PkgOutputFileName); goto Fail; } if (gCFormPkg.BuildPkg (pFile, &gRBuffer) != VFR_RETURN_SUCCESS) { fclose (pFile); goto Fail; } fclose (pFile); } SET_RUN_STATUS (STATUS_GENBINARY); return; Fail: if (!IS_RUN_STATUS(STATUS_DEAD)) { SET_RUN_STATUS (STATUS_FAILED); } } static const char *gSourceFileHeader[] = { "//", "// DO NOT EDIT -- auto-generated file", "//", "// This file is generated by the vfrcompiler utility", "//", NULL }; VOID CVfrCompiler::GenCFile ( VOID ) { FILE *pFile; UINT32 Index; if (!IS_RUN_STATUS(STATUS_GENBINARY)) { goto Fail; } if (!mOptions.CreateIfrPkgFile || mOptions.CompatibleMode) { if ((pFile = fopen (LongFilePath (mOptions.COutputFileName), "w")) == NULL) { DebugError (NULL, 0, 0001, "Error opening output C file", mOptions.COutputFileName); goto Fail; } for (Index = 0; gSourceFileHeader[Index] != NULL; Index++) { fprintf (pFile, "%s\n", gSourceFileHeader[Index]); } if (mOptions.CompatibleMode) { gCVfrBufferConfig.OutputCFile (pFile, mOptions.VfrBaseFileName); } if (gCFormPkg.GenCFile (mOptions.VfrBaseFileName, pFile, &gRBuffer) != VFR_RETURN_SUCCESS) { fclose (pFile); goto Fail; } fclose (pFile); } SET_RUN_STATUS (STATUS_FINISHED); return; Fail: if (!IS_RUN_STATUS(STATUS_DEAD)) { SET_RUN_STATUS (STATUS_FAILED); } } VOID CVfrCompiler::GenRecordListFile ( VOID ) { CHAR8 *InFileName = NULL; FILE *pInFile = NULL; FILE *pOutFile = NULL; CHAR8 LineBuf[MAX_VFR_LINE_LEN]; UINT32 LineNo; InFileName = (mOptions.SkipCPreprocessor == TRUE) ? mOptions.VfrFileName : mOptions.PreprocessorOutputFileName; if (mOptions.CreateRecordListFile == TRUE) { if ((InFileName[0] == '\0') || (mOptions.RecordListFile[0] == '\0')) { return; } if ((pInFile = fopen (LongFilePath (InFileName), "r")) == NULL) { DebugError (NULL, 0, 0001, "Error opening the input VFR preprocessor output file", InFileName); return; } if ((pOutFile = fopen (LongFilePath (mOptions.RecordListFile), "w")) == NULL) { DebugError (NULL, 0, 0001, "Error opening the record list file", mOptions.RecordListFile); goto Err1; } fprintf (pOutFile, "//\n// VFR compiler version " VFR_COMPILER_VERSION __BUILD_VERSION "\n//\n"); LineNo = 0; while (!feof (pInFile)) { if (fgets (LineBuf, MAX_VFR_LINE_LEN, pInFile) != NULL) { fprintf (pOutFile, "%s", LineBuf); LineNo++; gCIfrRecordInfoDB.IfrRecordOutput (pOutFile, LineNo); } } fprintf (pOutFile, "\n//\n// All Opcode Record List \n//\n"); gCIfrRecordInfoDB.IfrRecordOutput (pOutFile, 0); gCVfrVarDataTypeDB.Dump(pOutFile); fclose (pOutFile); fclose (pInFile); } return; Err1: fclose (pInFile); } int main ( IN int Argc, IN char **Argv ) { COMPILER_RUN_STATUS Status; SetPrintLevel(WARNING_LOG_LEVEL); CVfrCompiler Compiler(Argc, Argv); Compiler.PreProcess(); Compiler.Compile(); Compiler.AdjustBin(); Compiler.GenBinary(); Compiler.GenCFile(); Compiler.GenRecordListFile (); Status = Compiler.RunStatus (); if ((Status == STATUS_DEAD) || (Status == STATUS_FAILED)) { return 2; } if (gCBuffer.Buffer != NULL) { delete gCBuffer.Buffer; } if (gRBuffer.Buffer != NULL) { delete gRBuffer.Buffer; } return GetUtilityStatus (); }
/************************************************************************* * * Copyright (c) 2015-2019, Klaralvdalens Datakonsult AB (KDAB) * All rights reserved. * * See the LICENSE.txt file shipped along with this file for the license. * *************************************************************************/ #include <QGuiApplication> #include <QQuickView> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource(QUrl("qrc:/sol-nested-elements.qml")); view.show(); return app.exec(); }
/* All modification made by Cambricon Corporation: © 2018 Cambricon Corporation All rights reserved. All other contributions: Copyright (c) 2014--2018, the respective contributors All rights reserved. For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EXAMPLES_COMMON_INCLUDE_OFF_DATA_PROVIDER_HPP_ #define EXAMPLES_COMMON_INCLUDE_OFF_DATA_PROVIDER_HPP_ #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <queue> #include <string> #include <vector> #include "runner.hpp" #include "data_provider.hpp" using std::string; using std::queue; using std::vector; // #define PRE_READ template <typename Dtype, template <typename> class Qtype> class OffDataProvider: public DataProvider<Dtype, Qtype>{ public: explicit OffDataProvider(const string& meanfile, const string& meanvalue, const queue<string>& images): DataProvider<Dtype, Qtype>(meanfile, meanvalue, images) {} virtual ~OffDataProvider() { delete [] reinterpret_cast<float*>(cpuData_[0]); delete cpuData_; } virtual void runParallel(); virtual void runSerial(); protected: void allocateMemory(int queueLength); private: Dtype* cpuData_; }; #endif // EXAMPLES_COMMON_INCLUDE_OFF_DATA_PROVIDER_HPP_
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_connect_socket_82_goodG2B.cpp Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc.label.xml Template File: sources-sink-82_goodG2B.tmpl.cpp */ /* * @description * CWE: 680 Integer Overflow to Buffer Overflow * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Small number greater than zero that will not cause an integer overflow in the sink * Sinks: * BadSink : Attempt to allocate array using length value from source * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_connect_socket_82.h" namespace CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_connect_socket_82 { void CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_connect_socket_82_goodG2B::action(int data) { { size_t i; int *intPointer; /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value * so that the for loop doing the initialization causes a buffer overflow */ intPointer = (int*)malloc(data * sizeof(int)); if (intPointer == NULL) {exit(-1);} for (i = 0; i < (size_t)data; i++) { intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ } printIntLine(intPointer[0]); free(intPointer); } } } #endif /* OMITGOOD */
/** @file SVD.cpp @author t-sakai @date 2017/06/02 create */ #include "SVD.h" #include <stdio.h> #include <limits> #include "Householder.h" #include "QR.h" namespace lmath { DiagonalVector::DiagonalVector() :rows_(0) ,cols_(0) ,x_(NULL) {} DiagonalVector::DiagonalVector(s32 rows, s32 cols, element_type* x) :rows_(rows) ,cols_(cols) ,x_(x) {} DiagonalVector::~DiagonalVector() {} element_type DiagonalVector::operator[](s32 index) const { LASSERT(0<=index && index<rows_); return x_[cols_*index + index]; } element_type& DiagonalVector::operator[](s32 index) { LASSERT(0<=index && index<rows_); return x_[cols_*index + index]; } void bidiagonalization(MatrixView& U, MatrixView& B, MatrixView& V, MatrixView& A) { LASSERT(B.rows() == A.rows()); LASSERT(B.cols() == A.cols()); LASSERT(U.rows() == U.cols()); LASSERT(V.rows() == V.cols()); LASSERT(U.rows() == A.rows()); LASSERT(V.cols() == A.cols()); s32 size = (A.cols()<A.rows())? A.rows() : A.cols(); B = A; element_type* hbuffer = LNEW element_type[B.rows()*B.rows()]; element_type* hpbuffer = LNEW element_type[B.cols()*B.cols()]; element_type* tbuffer = LNEW element_type[size*size]; element_type* tv0buffer = LNEW element_type[B.rows()]; element_type* tv1buffer = LNEW element_type[B.cols()]; U.identity(); V.identity(); MatrixView H(B.rows(), B.rows(), hbuffer); MatrixView Hprime(B.cols(), B.cols(), hpbuffer); MatrixView T0(B.rows(), B.cols(), tbuffer); MatrixView T1(B.rows(), B.rows(), tbuffer); MatrixView T2(B.cols(), B.cols(), tbuffer); VectorView tv0(B.rows(), tv0buffer); VectorView tv1(B.cols(), tv1buffer); for(s32 k=0; k<B.cols(); ++k){ //eliminate non-zeros below the diagonal tv0.copy(B.getCol(k)); householder_matrix(H, tv0, k); B = mul(T0, H, B); U = mul(T1, U, H); //eliminate no-zeros to the right to the superdiagonal by working with transpose if(k<B.cols()-2){ tv1.copy(B.getRow(k)); householder_matrix(Hprime, tv1, k+1); transposeSquare(Hprime); B = mul(T0, B, Hprime); V = mul(T2, Hprime, V); } } LDELETE_ARRAY(tv1buffer); LDELETE_ARRAY(tv0buffer); LDELETE_ARRAY(tbuffer); LDELETE_ARRAY(hpbuffer); LDELETE_ARRAY(hbuffer); } void rotGivens(element_type& c, element_type& s, element_type& r, element_type f, element_type g) { element_type af = lmath::absolute(f); if(af<LMATH_EPSILON){ c = 0.0; s = 1.0; r = g; }else if(lmath::absolute(g)<af){ element_type t = g/f; element_type t1 = lmath::sqrt(1.0+t*t); c = 1.0/t1; s = t*c; r = f*t1; }else{ element_type t = f/g; element_type t1 = lmath::sqrt(1.0+t*t); s = 1.0/t1; c = t*s; r = g*t1; } } void rotGivens(element_type& c, element_type& s, element_type f, element_type g) { element_type af = lmath::absolute(f); if(af<LMATH_EPSILON){ c = 0.0; s = 1.0; }else if(lmath::absolute(g)<af){ element_type t = g/f; element_type t1 = lmath::sqrt(1.0+t*t); c = 1.0/t1; s = t*c; }else{ element_type t = f/g; element_type t1 = lmath::sqrt(1.0+t*t); s = 1.0/t1; c = t*s; } } void msweep(MatrixView& B) { LASSERT(B.rows() == B.cols()); element_type* qbuffer = LNEW element_type[B.rows()*B.cols()]; element_type* tbuffer = LNEW element_type[B.rows()*B.cols()]; MatrixView Q(B.rows(), B.cols(), qbuffer); MatrixView T(B.rows(), B.cols(), tbuffer); Q.identity(); s32 r = B.rows(); for(s32 i=0; i<r-1; ++i){ element_type c,s,r; rotGivens(c,s,r, B(i,i), B(i,i+1)); //construct matrix Q and multiply on the right by Q' //this annihilates both B(i-1,i+1) and B(i,i+1) //but makes B(i+1,i) non-zero Q(i,i) = c; Q(i,i+1) = s; Q(i+1,i) = -s; Q(i+1, i+1) = c; transposeSquare(Q); B=mul(T,B,Q); Q(i ,i) = 1.0; Q(i, i+1) = 0.0; Q(i+1,i) = 0.0; Q(i+1, i+1) = 1.0; rotGivens(c,s,r, B(i,i), B(i+1,i)); //construct matrix Q and multiply on the left by Q //this annihilates B(i+1,i), but makes B(i,i+1) and //B(i,i+2) non-zero Q(i,i) = c; Q(i,i+1) = s; Q(i+1,i) = -s; Q(i+1, i+1) = c; B=mul(T,Q,B); Q(i ,i) = 1.0; Q(i, i+1) = 0.0; Q(i+1,i) = 0.0; Q(i+1, i+1) = 1.0; } LDELETE_ARRAY(tbuffer); LDELETE_ARRAY(qbuffer); } void msweep2(MatrixView& U, MatrixView& B, MatrixView& V) { LASSERT(B.rows() == B.cols()); element_type* qbuffer = LNEW element_type[B.rows()*B.cols()]; element_type* tbuffer = LNEW element_type[B.rows()*B.cols()]; MatrixView Q(B.rows(), B.cols(), qbuffer); MatrixView T(B.rows(), B.cols(), tbuffer); Q.identity(); s32 r = B.rows(); for(s32 i=0; i<r-1; ++i){ element_type c,s,r; rotGivens(c,s,r, B(i,i), B(i,i+1)); //construct matrix Q and multiply on the right by Q' //this annihilates both B(i-1,i+1) and B(i,i+1) //but makes B(i+1,i) non-zero Q(i,i) = c; Q(i,i+1) = -s; Q(i+1,i) = s; Q(i+1, i+1) = c; B=mul(T,B,Q); Q(i,i+1) = s; Q(i+1,i) = -s; V=mul(T,Q,V); Q(i ,i) = 1.0; Q(i, i+1) = 0.0; Q(i+1,i) = 0.0; Q(i+1, i+1) = 1.0; rotGivens(c,s,r, B(i,i), B(i+1,i)); //construct matrix Q and multiply on the left by Q //this annihilates B(i+1,i), but makes B(i,i+1) and //B(i,i+2) non-zero Q(i,i) = c; Q(i,i+1) = s; Q(i+1,i) = -s; Q(i+1, i+1) = c; B=mul(T,Q,B); Q(i,i+1) = -s; Q(i+1,i) = s; U=mul(T,U,Q); Q(i ,i) = 1.0; Q(i, i+1) = 0.0; Q(i+1,i) = 0.0; Q(i+1, i+1) = 1.0; } LDELETE_ARRAY(tbuffer); LDELETE_ARRAY(qbuffer); } void msweep2(s32 lower, s32 upper, MatrixView& U, MatrixView& B, MatrixView& V) { s32 size = (B.rows()<B.cols())? B.cols() : B.rows(); element_type* qbuffer = LNEW element_type[B.rows()*B.rows() + B.cols()*B.cols()]; element_type* tbuffer = LNEW element_type[size*size]; MatrixView Q0(B.rows(), B.rows(), qbuffer); MatrixView Q1(B.cols(), B.cols(), qbuffer+B.rows()*B.rows()); MatrixView T0(B.rows(), B.cols(), tbuffer); MatrixView T1(B.rows(), B.rows(), tbuffer); MatrixView T2(B.cols(), B.cols(), tbuffer); Q0.identity(); Q1.identity(); for(s32 i=lower; i<upper; ++i){ element_type c,s,r; rotGivens(c,s,r, B(i,i), B(i,i+1)); //construct matrix Q and multiply on the right by Q' //this annihilates both B(i-1,i+1) and B(i,i+1) //but makes B(i+1,i) non-zero Q1(i,i) = c; Q1(i,i+1) = -s; Q1(i+1,i) = s; Q1(i+1, i+1) = c; B=mul(T0,B,Q1); Q1(i,i+1) = s; Q1(i+1,i) = -s; V=mul(T2,Q1,V); Q1(i ,i) = 1.0; Q1(i, i+1) = 0.0; Q1(i+1,i) = 0.0; Q1(i+1, i+1) = 1.0; rotGivens(c,s,r, B(i,i), B(i+1,i)); //construct matrix Q and multiply on the left by Q //this annihilates B(i+1,i), but makes B(i,i+1) and //B(i,i+2) non-zero Q0(i,i) = c; Q0(i,i+1) = s; Q0(i+1,i) = -s; Q0(i+1, i+1) = c; B=mul(T0,Q0,B); Q0(i,i+1) = -s; Q0(i+1,i) = s; U=mul(T1,U,Q0); Q0(i ,i) = 1.0; Q0(i, i+1) = 0.0; Q0(i+1,i) = 0.0; Q0(i+1, i+1) = 1.0; } LDELETE_ARRAY(tbuffer); LDELETE_ARRAY(qbuffer); } void vsweep(VectorView& d, VectorView& e) { LASSERT(d.size() == (e.size()+1)); element_type c=1.0, cold=1.0; element_type s, sold, r; for(s32 i=0; i<e.size(); ++i){ rotGivens(c,s,r,c*d[i],e[i]); if(0!=i){ e[i-1] = r*sold; } rotGivens(cold,sold,d[i], cold*r, d[i+1]*s); } element_type h = c*d[e.size()]; e[e.size()-1] = h*sold; d[d.size()-1] = h*cold; } void vsweep(s32 lower, s32 upper, VectorView& d, VectorView& e) { LASSERT(d.size() == (e.size()+1)); LASSERT(upper<=e.size()); element_type c=1.0, cold=1.0; element_type s, sold, r; for(s32 i=lower; i<upper; ++i){ rotGivens(c,s,r,c*d[i],e[i]); if(lower!=i){ e[i-1] = r*sold; } rotGivens(cold,sold,d[i], cold*r, d[i+1]*s); } element_type h = c*d[upper]; e[upper-1] = h*sold; d[upper] = h*cold; } s32 svd(VectorView& d, VectorView& e, element_type epsilon, s32 maxIterationFactor) { LASSERT(d.size() == (e.size()+1)); element_type TOL = 100.0*epsilon; s32 maxIteration = maxIterationFactor*d.size()*d.size(); element_type* lambdabuffer = LNEW element_type[d.size()]; element_type* mubuffer = LNEW element_type[d.size()]; VectorView lambda(d.size(), lambdabuffer); VectorView mu(d.size(), mubuffer); //The following convergence criterion is discussed by //Demmel and Kahan. First, estimate the smallest singular value. lambda[d.size()-1] = absolute(d[d.size()-1]); for(s32 i=d.size()-2; 0<=i; --i){ lambda[i] = absolute(d[i]) * lambda[i+1]/(lambda[i+1] + absolute(e[i])); } mu[0] = absolute(d[0]); for(s32 i=1;i<d.size(); ++i){ mu[i] = absolute(d[i]) * mu[i-1]/(mu[i-1]+absolute(e[i-1])); } element_type sigmaLower = minimum(lambda.minimum(), mu.minimum()); element_type threshold = maximum(TOL*sigmaLower, maxIteration*std::numeric_limits<element_type>::min()); LDELETE_ARRAY(mubuffer); LDELETE_ARRAY(lambdabuffer); s32 iterations; s32 iUpper = d.size()-2; s32 iLower = 0; for(iterations=0; iterations<maxIteration; ++iterations){ //reduce problem size when some zeros are on the superdiagonal //how many zeros are near the bottom right? for(s32 i=iUpper; 0<=i; --i){ iUpper=i; if(threshold<absolute(e[i])){ break; } } //how many zeros are near the top left? { s32 j=iUpper; for(s32 i=iLower; i<iUpper; ++i){ if(threshold<absolute(e[i])){ j=i; break; } } iLower = j; } if((iUpper == iLower && absolute(e[iUpper])<=threshold) || (iUpper<iLower)){ //all done, sort singular values in ascending order return iterations; } //do a sweep vsweep(iLower, iUpper+1, d, e); } return -1; } s32 svd(MatrixView& U, MatrixView& A, MatrixView& V, element_type epsilon, s32 maxIterationFactor) { //Bidiagonalize element_type* bbuffer = LNEW element_type[A.rows()*A.cols()]; MatrixView B(A.rows(), A.cols(), bbuffer); bidiagonalization(U,B,V,A); s32 diag = (A.rows()<A.cols())? A.rows() : A.cols(); DiagonalVector d(diag, A.cols(), &B(0,0)); DiagonalVector e(diag-1, A.cols(), &B(0,1)); element_type TOL = 100.0*epsilon; s32 maxIteration = maxIterationFactor*d.size()*d.size(); element_type* lambdabuffer = LNEW element_type[d.size()]; element_type* mubuffer = LNEW element_type[d.size()]; VectorView lambda(diag, lambdabuffer); VectorView mu(diag, mubuffer); //The following convergence criterion is discussed by //Demmel and Kahan. First, estimate the smallest singular value. lambda[d.size()-1] = absolute(d[d.size()-1]); for(s32 i=d.size()-2; 0<=i; --i){ lambda[i] = absolute(d[i]) * lambda[i+1]/(lambda[i+1] + absolute(e[i])); } mu[0] = absolute(d[0]); for(s32 i=1;i<d.size(); ++i){ mu[i] = absolute(d[i]) * mu[i-1]/(mu[i-1]+absolute(e[i-1])); } element_type sigmaLower = minimum(lambda.minimum(), mu.minimum()); element_type threshold = maximum(TOL*sigmaLower, maxIteration*std::numeric_limits<element_type>::min()); LDELETE_ARRAY(mubuffer); LDELETE_ARRAY(lambdabuffer); s32 iterations; s32 iUpper = d.size()-2; s32 iLower = 0; for(iterations=0; iterations<maxIteration; ++iterations){ //reduce problem size when some zeros are on the superdiagonal //how many zeros are near the bottom right? for(s32 i=iUpper; 0<=i; --i){ iUpper=i; if(threshold<absolute(e[i])){ break; } } //how many zeros are near the top left? { s32 j=iUpper; for(s32 i=iLower; i<iUpper; ++i){ if(threshold<absolute(e[i])){ j=i; break; } } iLower = j; } if((iUpper == iLower && absolute(e[iUpper])<=threshold) || (iUpper<iLower)){ #if 0 //all done, sort singular values in ascending order for(s32 i=0; i<d.size(); ++i){ s32 k=i; for(s32 j=i+1; j<d.size(); ++j){ if(lmath::absolute(d[j])<lmath::absolute(d[k])){ k=j; } } if(k==i){ continue; } lmath::swap(d[k],d[i]); U.swapCols(i,k); V.swapRows(i,k); } #endif A = B; LDELETE_ARRAY(bbuffer); return iterations; } //do a sweep //vsweep(iLower, iUpper+1, d, e); msweep2(iLower, iUpper+1, U, B, V); } LDELETE_ARRAY(bbuffer); return -1; } void pseudoInverse(MatrixView& Aplus, MatrixView& U, MatrixView& A, MatrixView& V) { LASSERT(Aplus.rows() == A.cols()); LASSERT(Aplus.cols() == A.rows()); element_type* tbuffer = LNEW element_type[A.rows()*A.cols()]; MatrixView T(Aplus.rows(), Aplus.cols(), tbuffer); Aplus.zero(); s32 diag = (A.rows()<A.cols())? A.rows() : A.cols(); for(s32 i=0; i<diag; ++i){ element_type a = A(i,i); if(LMATH_EPSILON<lmath::absolute(a)){ Aplus(i,i) = 1.0/a; } } transposeSquare(V); transposeSquare(U); Aplus = mul(T,V,Aplus); Aplus = mul(T,Aplus,U); LDELETE_ARRAY(tbuffer); } #if 0 s32 svd(MatrixView& u, VectorView& sigma, MatrixView& vt, MatrixView& m, f32 epsilon, s32 maxIteration) { Matrix tmp_mt(m.rows(), m.cols()); MatrixView mt(tmp_mt); m.transpose(mt); Vector tmp_sigma1(sigma.size()); VectorView sigma1(tmp_sigma1); Vector tmp_e(sigma.size()); VectorView e(tmp_e); Matrix tmp_ut(u.rows(), u.cols()); MatrixView ut(tmp_ut); mul(ut, m, mt); s32 ret=0; if(0 != eigen(ut.cols(), ut, sigma, e, epsilon, maxIteration)){ ret |= 0x01U; } ut.transpose(u); mul(vt, mt, m); if(0 != eigen(vt.cols(), vt, sigma1, e, epsilon, maxIteration)){ ret |= 0x02U; } return ret; } //----------------------------------------- //--- //--- SVD //--- //----------------------------------------- SVD::SVD() :cols_(0) ,rows_(0) ,buffer_(NULL) { } SVD::SVD(s32 cols, s32 rows) :cols_(0) ,rows_(0) ,buffer_(NULL) { reset(cols, rows); } SVD::SVD(SVD&& rhs) :cols_(rhs.cols_) ,rows_(rhs.rows_) ,buffer_(rhs.buffer_) { rhs.cols_ = 0; rhs.rows_ = 0; rhs.buffer_ = NULL; } SVD::~SVD() { cols_ = rows_ = 0; LDELETE_ARRAY(buffer_); } void SVD::reset(s32 cols, s32 rows) { LASSERT(0<=cols); LASSERT(0<=rows); if(cols_ == cols && rows_ == rows){ return; } s32 size0 = cols*rows; s32 size1 = rows*rows; s32 size2 = cols*cols; s32 n = (rows<cols)? cols : rows; if(size0 != (cols_*rows_)){ LDELETE_ARRAY(buffer_); s32 total = size0*3 + size1*2 + size2 + n*2 + cols + rows; buffer_ = LNEW element_type[total]; } cols_ = cols; rows_ = rows; s32 offset=0; a_ = MatrixView(cols_, rows_, buffer_+offset); offset += size0; at_ = MatrixView(rows_, cols_, buffer_+offset); offset += size0; ap_ = MatrixView(rows_, rows_, buffer_+offset); offset += size1; ut_ = MatrixView(rows_, rows_, buffer_+offset); offset += size1; v_ = MatrixView(cols_, cols_, buffer_+offset); offset += size2; sp_ = MatrixView(rows_, cols_, buffer_+offset); offset += size0; sigma_ = VectorView(n, buffer_+offset); offset += n; e_ = VectorView(n, buffer_+offset); offset += n; x_ = VectorView(cols_, buffer_+offset); offset += cols_; b_ = VectorView(rows_, buffer_+offset); offset += rows_; } s32 SVD::solve(element_type epsilon, s32 maxIteration, element_type truncate) { template<typename MatrixType, int QRPreconditioner> void JacobiSVD<MatrixType, QRPreconditioner>::allocate(Index rows, Index cols, unsigned int computationOptions) { eigen_assert(rows >= 0 && cols >= 0); if (m_isAllocated && rows == m_rows && cols == m_cols && computationOptions == m_computationOptions) { return; } m_rows = rows; m_cols = cols; m_isInitialized = false; m_isAllocated = true; m_computationOptions = computationOptions; m_computeFullU = (computationOptions & ComputeFullU) != 0; m_computeThinU = (computationOptions & ComputeThinU) != 0; m_computeFullV = (computationOptions & ComputeFullV) != 0; m_computeThinV = (computationOptions & ComputeThinV) != 0; eigen_assert(!(m_computeFullU && m_computeThinU) && "JacobiSVD: you can't ask for both full and thin U"); eigen_assert(!(m_computeFullV && m_computeThinV) && "JacobiSVD: you can't ask for both full and thin V"); eigen_assert(EIGEN_IMPLIES(m_computeThinU || m_computeThinV, MatrixType::ColsAtCompileTime==Dynamic) && "JacobiSVD: thin U and V are only available when your matrix has a dynamic number of columns."); if (QRPreconditioner == FullPivHouseholderQRPreconditioner) { eigen_assert(!(m_computeThinU || m_computeThinV) && "JacobiSVD: can't compute thin U or thin V with the FullPivHouseholderQR preconditioner. " "Use the ColPivHouseholderQR preconditioner instead."); } m_diagSize = (std::min)(m_rows, m_cols); m_singularValues.resize(m_diagSize); if(RowsAtCompileTime==Dynamic) m_matrixU.resize(m_rows, m_computeFullU ? m_rows : m_computeThinU ? m_diagSize : 0); if(ColsAtCompileTime==Dynamic) m_matrixV.resize(m_cols, m_computeFullV ? m_cols : m_computeThinV ? m_diagSize : 0); m_workMatrix.resize(m_diagSize, m_diagSize); if(m_cols>m_rows) m_qr_precond_morecols.allocate(*this); if(m_rows>m_cols) m_qr_precond_morerows.allocate(*this); if(m_rows!=m_cols) m_scaledMatrix.resize(rows,cols); } template<typename MatrixType, int QRPreconditioner> JacobiSVD<MatrixType, QRPreconditioner>& JacobiSVD<MatrixType, QRPreconditioner>::compute(const MatrixType& matrix, unsigned int computationOptions) { using std::abs; allocate(matrix.rows(), matrix.cols(), computationOptions); // currently we stop when we reach precision 2*epsilon as the last bit of precision can require an unreasonable number of iterations, // only worsening the precision of U and V as we accumulate more rotations const RealScalar precision = RealScalar(2) * NumTraits<Scalar>::epsilon(); // limit for denormal numbers to be considered zero in order to avoid infinite loops (see bug 286) const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)(); // Scaling factor to reduce over/under-flows RealScalar scale = matrix.cwiseAbs().maxCoeff(); if(scale==RealScalar(0)) scale = RealScalar(1); /*** step 1. The R-SVD step: we use a QR decomposition to reduce to the case of a square matrix */ if(m_rows!=m_cols) { m_scaledMatrix = matrix / scale; m_qr_precond_morecols.run(*this, m_scaledMatrix); m_qr_precond_morerows.run(*this, m_scaledMatrix); } else { m_workMatrix = matrix.block(0,0,m_diagSize,m_diagSize) / scale; if(m_computeFullU) m_matrixU.setIdentity(m_rows,m_rows); if(m_computeThinU) m_matrixU.setIdentity(m_rows,m_diagSize); if(m_computeFullV) m_matrixV.setIdentity(m_cols,m_cols); if(m_computeThinV) m_matrixV.setIdentity(m_cols, m_diagSize); } /*** step 2. The main Jacobi SVD iteration. ***/ RealScalar maxDiagEntry = m_workMatrix.cwiseAbs().diagonal().maxCoeff(); bool finished = false; while(!finished) { finished = true; // do a sweep: for all index pairs (p,q), perform SVD of the corresponding 2x2 sub-matrix for(Index p = 1; p < m_diagSize; ++p) { for(Index q = 0; q < p; ++q) { // if this 2x2 sub-matrix is not diagonal already... // notice that this comparison will evaluate to false if any NaN is involved, ensuring that NaN's don't // keep us iterating forever. Similarly, small denormal numbers are considered zero. RealScalar threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry); if(abs(m_workMatrix.coeff(p,q))>threshold || abs(m_workMatrix.coeff(q,p)) > threshold) { finished = false; // perform SVD decomposition of 2x2 sub-matrix corresponding to indices p,q to make it diagonal // the complex to real operation returns true if the updated 2x2 block is not already diagonal if(internal::svd_precondition_2x2_block_to_be_real<MatrixType, QRPreconditioner>::run(m_workMatrix, *this, p, q, maxDiagEntry)) { JacobiRotation<RealScalar> j_left, j_right; internal::real_2x2_jacobi_svd(m_workMatrix, p, q, &j_left, &j_right); // accumulate resulting Jacobi rotations m_workMatrix.applyOnTheLeft(p,q,j_left); if(computeU()) m_matrixU.applyOnTheRight(p,q,j_left.transpose()); m_workMatrix.applyOnTheRight(p,q,j_right); if(computeV()) m_matrixV.applyOnTheRight(p,q,j_right); // keep track of the largest diagonal coefficient maxDiagEntry = numext::maxi<RealScalar>(maxDiagEntry,numext::maxi<RealScalar>(abs(m_workMatrix.coeff(p,p)), abs(m_workMatrix.coeff(q,q)))); } } } } } /*** step 3. The work matrix is now diagonal, so ensure it's positive so its diagonal entries are the singular values ***/ for(Index i = 0; i < m_diagSize; ++i) { // For a complex matrix, some diagonal coefficients might note have been // treated by svd_precondition_2x2_block_to_be_real, and the imaginary part // of some diagonal entry might not be null. if(NumTraits<Scalar>::IsComplex && abs(numext::imag(m_workMatrix.coeff(i,i)))>considerAsZero) { RealScalar a = abs(m_workMatrix.coeff(i,i)); m_singularValues.coeffRef(i) = abs(a); if(computeU()) m_matrixU.col(i) *= m_workMatrix.coeff(i,i)/a; } else { // m_workMatrix.coeff(i,i) is already real, no difficulty: RealScalar a = numext::real(m_workMatrix.coeff(i,i)); m_singularValues.coeffRef(i) = abs(a); if(computeU() && (a<RealScalar(0))) m_matrixU.col(i) = -m_matrixU.col(i); } } m_singularValues *= scale; /*** step 4. Sort singular values in descending order and compute the number of nonzero singular values ***/ m_nonzeroSingularValues = m_diagSize; for(Index i = 0; i < m_diagSize; i++) { Index pos; RealScalar maxRemainingSingularValue = m_singularValues.tail(m_diagSize-i).maxCoeff(&pos); if(maxRemainingSingularValue == RealScalar(0)) { m_nonzeroSingularValues = i; break; } if(pos) { pos += i; std::swap(m_singularValues.coeffRef(i), m_singularValues.coeffRef(pos)); if(computeU()) m_matrixU.col(pos).swap(m_matrixU.col(i)); if(computeV()) m_matrixV.col(pos).swap(m_matrixV.col(i)); } } m_isInitialized = true; return *this; } a_.transpose(at_); s32 ret=0; mul(ut_, a_, at_); if(0 != eigen(ut_.cols(), ut_, sigma_, e_, epsilon, maxIteration)){ ret |= 0x01U; } mul(v_, at_, a_); if(0 != eigen(v_.cols(), v_, sigma_, e_, epsilon, maxIteration)){ ret |= 0x02U; } v_.transpose(); sp_.setIdentity(); for(s32 i=0; i<cols_; ++i){ if(truncate<sigma_[i]){ sp_(i,i) = 1.0f/lmath::sqrt(sigma_[i]); }else{ sp_(i,i) = 0.0; } } mul(at_, sp_, ut_); mul(ap_, v_, at_); for(s32 i=0; i<cols_; ++i){ x_[i] = 0.0; for(s32 j=0; j<rows_; ++j){ x_[i] += ap_(j,i) * b_[j]; } } return ret; } SVD& SVD::operator=(SVD&& rhs) { cols_ = rhs.cols_; rows_ = rhs.rows_; buffer_ = rhs.buffer_; rhs.cols_ = 0; rhs.rows_ = 0; rhs.buffer_ = NULL; return *this; } #endif }
#include "TriCollector.h" #include <algorithm> #include "RenderTarget.h" #include "Camera.h" #include <iostream> TriCollector::TriCollector() { } void TriCollector::SubmitMesh(const Mesh& mesh, const Camera* cam) { const std::vector<Vertex>& verticesToSubmit = mesh.GetVertices(); const std::vector<unsigned int>& vertexIndicesToSubmit = mesh.GetVertexIndices(); const std::vector<UVCoord>& uvCoordinatesToSubmit = mesh.GetUVCoordinates(); const std::vector<unsigned int>& uvCoordinatesIndicesToSubmit = mesh.GetUVIndices(); const Matrix<4,4>& modelMatrix = mesh.GetModelMatrix(); size_t currSize = m_tris.size(); m_tris.reserve(currSize + vertexIndicesToSubmit.size() / 3); for(size_t i = 0; i < vertexIndicesToSubmit.size(); i += 3) { Triangle& tri = m_tris.emplace_back(verticesToSubmit[vertexIndicesToSubmit[i]], uvCoordinatesToSubmit[uvCoordinatesIndicesToSubmit[i]], verticesToSubmit[vertexIndicesToSubmit[i + 1]], uvCoordinatesToSubmit[uvCoordinatesIndicesToSubmit[i + 1]], verticesToSubmit[vertexIndicesToSubmit[i + 2]], uvCoordinatesToSubmit[uvCoordinatesIndicesToSubmit[i + 2]]); // Worldspace tri.p1.coords = modelMatrix * tri.p1.coords; tri.p2.coords = modelMatrix * tri.p2.coords; tri.p3.coords = modelMatrix * tri.p3.coords; // Viewspace tri.p1.coords = cam->GetViewMat() * tri.p1.coords; tri.p2.coords = cam->GetViewMat() * tri.p2.coords; tri.p3.coords = cam->GetViewMat() * tri.p3.coords; // ClipSpace tri.p1.coords = cam->GetProjectionMatrix() * tri.p1.coords; tri.p2.coords = cam->GetProjectionMatrix() * tri.p2.coords; tri.p3.coords = cam->GetProjectionMatrix() * tri.p3.coords; } m_entries.emplace_back(mesh.GetDiffuseTexture(), mesh.GetDiffuseTextureWidth(), mesh.GetDiffuseTextureHeight(), m_tris.size() - 1); } void TriCollector::SortTris() { std::sort(m_tris.begin(), m_tris.end(), [](Triangle& tri1, Triangle& tri2){ double depthFirst = tri1.p1.coords[2] + tri1.p2.coords[2] + tri1.p3.coords[2]; double depthSec = tri2.p1.coords[2] + tri2.p2.coords[2] + tri2.p3.coords[2]; return depthFirst > depthSec; }); } void TriCollector::Draw(RenderTarget& target) { Vertex triOutput[3]; unsigned int entryCount = 0; for(unsigned int i = 0; i < m_tris.size(); ++i) { if(i > m_entries[entryCount].endVertex) { entryCount++; } // Projection triOutput[0].coords = m_tris[i].p1.coords; triOutput[1].coords = m_tris[i].p2.coords; triOutput[2].coords = m_tris[i].p3.coords; // move to the a "rendertarget" to the right and top. triOutput[0].coords[0] = triOutput[0].coords[0] + 1; triOutput[0].coords[1] = triOutput[0].coords[1] + 1; triOutput[1].coords[0] = triOutput[1].coords[0] + 1; triOutput[1].coords[1] = triOutput[1].coords[1] + 1; triOutput[2].coords[0] = triOutput[2].coords[0] + 1; triOutput[2].coords[1] = triOutput[2].coords[1] + 1; // Scale triangle to match the size of the rendertarget. triOutput[0].coords[0] = triOutput[0].coords[0] * 0.5 * target.GetWidth(); triOutput[0].coords[1] = triOutput[0].coords[1] * 0.5 * target.GetHeight(); triOutput[1].coords[0] = triOutput[1].coords[0] * 0.5 * target.GetWidth(); triOutput[1].coords[1] = triOutput[1].coords[1] * 0.5 * target.GetHeight(); triOutput[2].coords[0] = triOutput[2].coords[0] * 0.5 * target.GetWidth(); triOutput[2].coords[1] = triOutput[2].coords[1] * 0.5 * target.GetHeight(); target.FillTexturedTri ( (int)triOutput[0].coords.nums[0], (int)triOutput[0].coords.nums[1], m_tris[i].uv1.u, m_tris[i].uv1.v, (int)triOutput[1].coords.nums[0], (int)triOutput[1].coords.nums[1], m_tris[i].uv2.u, m_tris[i].uv2.v, (int)triOutput[2].coords.nums[0], (int)triOutput[2].coords.nums[1], m_tris[i].uv3.u, m_tris[i].uv3.v, m_entries[entryCount].image, m_entries[entryCount].texWidth, m_entries[entryCount].texHeight ); target.DrawTri ( (int)triOutput[0].coords.nums[0], (int)triOutput[0].coords.nums[1], (int)triOutput[1].coords.nums[0], (int)triOutput[1].coords.nums[1], (int)triOutput[2].coords.nums[0], (int)triOutput[2].coords.nums[1], (255 << 16) ); } } void TriCollector::Clear() { m_tris.clear(); m_entries.clear(); }
// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "db.h" #include "init.h" #include "main.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "rpcserver.h" #include "utilmoneystr.h" #include <boost/tokenizer.hpp> #include <fstream> using namespace json_spirit; void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, AvailableCoinsType coin_type = ALL_COINS) { // Check amount if (nValue <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount"); if (nValue > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); string strError; if (pwalletMain->IsLocked()) { strError = "Error: Wallet locked, unable to create transaction!"; LogPrintf("SendMoney() : %s", strError); throw JSONRPCError(RPC_WALLET_ERROR, strError); } // Parse PAWS address CScript scriptPubKey = GetScriptForDestination(address); // Create and send the transaction CReserveKey reservekey(pwalletMain); CAmount nFeeRequired; if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError, NULL, coin_type)) { if (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)); LogPrintf("SendMoney() : %s\n", strError); throw JSONRPCError(RPC_WALLET_ERROR, strError); } if (!pwalletMain->CommitTransaction(wtxNew, reservekey)) 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."); } Value obfuscation(const Array& params, bool fHelp) { throw runtime_error("Obfuscation is not supported any more. User Zerocoin\n"); if (fHelp || params.size() == 0) throw runtime_error( "obfuscation <pawsaddress> <amount>\n" "pawsaddress, reset, or auto (AutoDenominate)" "<amount> is a real and will be rounded to the next 0.1" + HelpRequiringPassphrase()); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (params[0].get_str() == "auto") { if (fMasterNode) return "ObfuScation is not supported from masternodes"; return "DoAutomaticDenominating " + (obfuScationPool.DoAutomaticDenominating() ? "successful" : ("failed: " + obfuScationPool.GetStatus())); } if (params[0].get_str() == "reset") { obfuScationPool.Reset(); return "successfully reset obfuscation"; } if (params.size() != 2) throw runtime_error( "obfuscation <pawsaddress> <amount>\n" "pawsaddress, denominate, or auto (AutoDenominate)" "<amount> is a real and will be rounded to the next 0.1" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PAWS address"); // Amount CAmount nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; // string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx, ONLY_DENOMINATED); SendMoney(address.Get(), nAmount, wtx, ONLY_DENOMINATED); // if (strError != "") // throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value getpoolinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpoolinfo\n" "\nReturns anonymous pool-related information\n" "\nResult:\n" "{\n" " \"current\": \"addr\", (string) PAWS address of current masternode\n" " \"state\": xxxx, (string) unknown\n" " \"entries\": xxxx, (numeric) Number of entries\n" " \"accepted\": xxxx, (numeric) Number of entries accepted\n" "}\n" "\nExamples:\n" + HelpExampleCli("getpoolinfo", "") + HelpExampleRpc("getpoolinfo", "")); Object obj; obj.push_back(Pair("current_masternode", mnodeman.GetCurrentMasterNode()->addr.ToString())); obj.push_back(Pair("state", obfuScationPool.GetState())); obj.push_back(Pair("entries", obfuScationPool.GetEntriesCount())); obj.push_back(Pair("entries_accepted", obfuScationPool.GetCountEntriesAccepted())); return obj; } // This command is retained for backwards compatibility, but is depreciated. // Future removal of this command is planned to keep things clean. Value masternode(const Array& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "start" && strCommand != "start-alias" && strCommand != "start-many" && strCommand != "start-all" && strCommand != "start-missing" && strCommand != "start-disabled" && strCommand != "list" && strCommand != "list-conf" && strCommand != "count" && strCommand != "enforce" && strCommand != "debug" && strCommand != "current" && strCommand != "winners" && strCommand != "genkey" && strCommand != "connect" && strCommand != "outputs" && strCommand != "status" && strCommand != "calcscore")) throw runtime_error( "masternode \"command\"...\n" "\nSet of commands to execute masternode related actions\n" "This command is depreciated, please see individual command documentation for future reference\n\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "\nAvailable commands:\n" " count - Print count information of all known masternodes\n" " current - Print info on current masternode winner\n" " debug - Print masternode status\n" " genkey - Generate new masternodeprivkey\n" " outputs - Print masternode compatible outputs\n" " start - Start masternode configured in paws.conf\n" " start-alias - Start single masternode by assigned alias configured in masternode.conf\n" " start-<mode> - Start masternodes configured in masternode.conf (<mode>: 'all', 'missing', 'disabled')\n" " status - Print masternode status information\n" " list - Print list of all known masternodes (see masternodelist for more info)\n" " list-conf - Print masternode.conf in JSON format\n" " winners - Print list of masternode winners\n"); if (strCommand == "list") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return listmasternodes(newParams, fHelp); } if (strCommand == "connect") { Array newParams(params.size() -1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return masternodeconnect(newParams, fHelp); } if (strCommand == "count") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return getmasternodecount(newParams, fHelp); } if (strCommand == "current") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return masternodecurrent(newParams, fHelp); } if (strCommand == "debug") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return masternodedebug(newParams, fHelp); } if (strCommand == "start" || strCommand == "start-alias" || strCommand == "start-many" || strCommand == "start-all" || strCommand == "start-missing" || strCommand == "start-disabled") { return startmasternode(params, fHelp); } if (strCommand == "genkey") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return createmasternodekey(newParams, fHelp); } if (strCommand == "list-conf") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return listmasternodeconf(newParams, fHelp); } if (strCommand == "outputs") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return getmasternodeoutputs(newParams, fHelp); } if (strCommand == "status") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return getmasternodestatus(newParams, fHelp); } if (strCommand == "winners") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return getmasternodewinners(newParams, fHelp); } if (strCommand == "calcscore") { Array newParams(params.size() - 1); std::copy(params.begin() + 1, params.end(), newParams.begin()); return getmasternodescores(newParams, fHelp); } return Value::null; } Value listmasternodes(const Array& params, bool fHelp) { std::string strFilter = ""; if (params.size() == 1) strFilter = params[0].get_str(); if (fHelp || (params.size() > 1)) throw runtime_error( "listmasternodes ( \"filter\" )\n" "\nGet a ranked list of masternodes\n" "\nArguments:\n" "1. \"filter\" (string, optional) Filter search text. Partial match by txhash, status, or addr.\n" "\nResult:\n" "[\n" " {\n" " \"rank\": n, (numeric) Masternode Rank (or 0 if not enabled)\n" " \"txhash\": \"hash\", (string) Collateral transaction hash\n" " \"outidx\": n, (numeric) Collateral transaction output index\n" " \"status\": s, (string) Status (ENABLED/EXPIRED/REMOVE/etc)\n" " \"addr\": \"addr\", (string) Masternode PAWS address\n" " \"version\": v, (numeric) Masternode protocol version\n" " \"lastseen\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last seen\n" " \"activetime\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) masternode has been active\n" " \"lastpaid\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) masternode was last paid\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("masternodelist", "") + HelpExampleRpc("masternodelist", "")); Array ret; int nHeight; { LOCK(cs_main); CBlockIndex* pindex = chainActive.Tip(); if(!pindex) return 0; nHeight = pindex->nHeight; } std::vector<pair<int, CMasternode> > vMasternodeRanks = mnodeman.GetMasternodeRanks(nHeight); BOOST_FOREACH (PAIRTYPE(int, CMasternode) & s, vMasternodeRanks) { Object obj; std::string strVin = s.second.vin.prevout.ToStringShort(); std::string strTxHash = s.second.vin.prevout.hash.ToString(); uint32_t oIdx = s.second.vin.prevout.n; CMasternode* mn = mnodeman.Find(s.second.vin); if (mn != NULL) { if (strFilter != "" && strTxHash.find(strFilter) == string::npos && mn->Status().find(strFilter) == string::npos && CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString().find(strFilter) == string::npos) continue; std::string strStatus = mn->Status(); std::string strHost; int port; SplitHostPort(mn->addr.ToString(), port, strHost); CNetAddr node = CNetAddr(strHost, false); std::string strNetwork = GetNetworkName(node.GetNetwork()); obj.push_back(Pair("rank", (strStatus == "ENABLED" ? s.first : 0))); obj.push_back(Pair("network", strNetwork)); obj.push_back(Pair("txhash", strTxHash)); obj.push_back(Pair("outidx", (uint64_t)oIdx)); obj.push_back(Pair("status", strStatus)); obj.push_back(Pair("addr", CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString())); obj.push_back(Pair("version", mn->protocolVersion)); obj.push_back(Pair("lastseen", (int64_t)mn->lastPing.sigTime)); obj.push_back(Pair("activetime", (int64_t)(mn->lastPing.sigTime - mn->sigTime))); obj.push_back(Pair("lastpaid", (int64_t)mn->GetLastPaid())); ret.push_back(obj); } } return ret; } Value masternodeconnect(const Array& params, bool fHelp) { if (fHelp || (params.size() != 1)) throw runtime_error( "masternodeconnect \"address\"\n" "\nAttempts to connect to specified masternode address\n" "\nArguments:\n" "1. \"address\" (string, required) IP or net address to connect to\n" "\nExamples:\n" + HelpExampleCli("masternodeconnect", "\"192.168.0.6:34120\"") + HelpExampleRpc("masternodeconnect", "\"192.168.0.6:5510\"")); std::string strAddress = params[0].get_str(); CService addr = CService(strAddress); CNode* pnode = ConnectNode((CAddress)addr, NULL, false); if (pnode) { pnode->Release(); return Value::null; } else { throw runtime_error("error connecting\n"); } } Value getmasternodecount (const Array& params, bool fHelp) { if (fHelp || (params.size() > 0)) throw runtime_error( "getmasternodecount\n" "\nGet masternode count values\n" "\nResult:\n" "{\n" " \"total\": n, (numeric) Total masternodes\n" " \"stable\": n, (numeric) Stable count\n" " \"obfcompat\": n, (numeric) Obfuscation Compatible\n" " \"enabled\": n, (numeric) Enabled masternodes\n" " \"inqueue\": n (numeric) Masternodes in queue\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmasternodecount", "") + HelpExampleRpc("getmasternodecount", "")); Object obj; int nCount = 0; int ipv4 = 0, ipv6 = 0, onion = 0; if (chainActive.Tip()) mnodeman.GetNextMasternodeInQueueForPayment(chainActive.Tip()->nHeight, true, nCount); mnodeman.CountNetworks(ActiveProtocol(), ipv4, ipv6, onion); obj.push_back(Pair("total", mnodeman.size())); obj.push_back(Pair("stable", mnodeman.stable_size())); obj.push_back(Pair("obfcompat", mnodeman.CountEnabled(ActiveProtocol()))); obj.push_back(Pair("enabled", mnodeman.CountEnabled())); obj.push_back(Pair("inqueue", nCount)); obj.push_back(Pair("ipv4", ipv4)); obj.push_back(Pair("ipv6", ipv6)); obj.push_back(Pair("onion", onion)); return obj; } Value masternodecurrent (const Array& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "masternodecurrent\n" "\nGet current masternode winner\n" "\nResult:\n" "{\n" " \"protocol\": xxxx, (numeric) Protocol version\n" " \"txhash\": \"xxxx\", (string) Collateral transaction hash\n" " \"pubkey\": \"xxxx\", (string) MN Public key\n" " \"lastseen\": xxx, (numeric) Time since epoch of last seen\n" " \"activeseconds\": xxx, (numeric) Seconds MN has been active\n" "}\n" "\nExamples:\n" + HelpExampleCli("masternodecurrent", "") + HelpExampleRpc("masternodecurrent", "")); CMasternode* winner = mnodeman.GetCurrentMasterNode(1); if (winner) { Object obj; obj.push_back(Pair("protocol", (int64_t)winner->protocolVersion)); obj.push_back(Pair("txhash", winner->vin.prevout.hash.ToString())); obj.push_back(Pair("pubkey", CBitcoinAddress(winner->pubKeyCollateralAddress.GetID()).ToString())); obj.push_back(Pair("lastseen", (winner->lastPing == CMasternodePing()) ? winner->sigTime : (int64_t)winner->lastPing.sigTime)); obj.push_back(Pair("activeseconds", (winner->lastPing == CMasternodePing()) ? 0 : (int64_t)(winner->lastPing.sigTime - winner->sigTime))); return obj; } throw runtime_error("unknown"); } Value masternodedebug (const Array& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "masternodedebug\n" "\nPrint masternode status\n" "\nResult:\n" "\"status\" (string) Masternode status message\n" "\nExamples:\n" + HelpExampleCli("masternodedebug", "") + HelpExampleRpc("masternodedebug", "")); if (activeMasternode.status != ACTIVE_MASTERNODE_INITIAL || !masternodeSync.IsSynced()) return activeMasternode.GetStatus(); CTxIn vin = CTxIn(); CPubKey pubkey = CScript(); CKey key; if (!activeMasternode.GetMasterNodeVin(vin, pubkey, key)) throw runtime_error("Missing masternode input, please look at the documentation for instructions on masternode creation\n"); else return activeMasternode.GetStatus(); } Value startmasternode (const Array& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) { strCommand = params[0].get_str(); // Backwards compatibility with legacy 'masternode' super-command forwarder if (strCommand == "start") strCommand = "local"; if (strCommand == "start-alias") strCommand = "alias"; if (strCommand == "start-all") strCommand = "all"; if (strCommand == "start-many") strCommand = "many"; if (strCommand == "start-missing") strCommand = "missing"; if (strCommand == "start-disabled") strCommand = "disabled"; } if (fHelp || params.size() < 2 || params.size() > 3 || (params.size() == 2 && (strCommand != "local" && strCommand != "all" && strCommand != "many" && strCommand != "missing" && strCommand != "disabled")) || (params.size() == 3 && strCommand != "alias")) throw runtime_error( "startmasternode \"local|all|many|missing|disabled|alias\" lockwallet ( \"alias\" )\n" "\nAttempts to start one or more masternode(s)\n" "\nArguments:\n" "1. set (string, required) Specify which set of masternode(s) to start.\n" "2. lockwallet (boolean, required) Lock wallet after completion.\n" "3. alias (string) Masternode alias. Required if using 'alias' as the set.\n" "\nResult: (for 'local' set):\n" "\"status\" (string) Masternode status message\n" "\nResult: (for other sets):\n" "{\n" " \"overall\": \"xxxx\", (string) Overall status message\n" " \"detail\": [\n" " {\n" " \"node\": \"xxxx\", (string) Node name or alias\n" " \"result\": \"xxxx\", (string) 'success' or 'failed'\n" " \"error\": \"xxxx\" (string) Error message, if failed\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("startmasternode", "\"alias\" \"0\" \"my_mn\"") + HelpExampleRpc("startmasternode", "\"alias\" \"0\" \"my_mn\"")); bool fLock = (params[1].get_str() == "true" ? true : false); if (strCommand == "local") { if (!fMasterNode) throw runtime_error("you must set masternode=1 in the configuration\n"); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (activeMasternode.status != ACTIVE_MASTERNODE_STARTED) { activeMasternode.status = ACTIVE_MASTERNODE_INITIAL; // TODO: consider better way activeMasternode.ManageStatus(); if (fLock) pwalletMain->Lock(); } return activeMasternode.GetStatus(); } if (strCommand == "all" || strCommand == "many" || strCommand == "missing" || strCommand == "disabled") { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if ((strCommand == "missing" || strCommand == "disabled") && (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_LIST || masternodeSync.RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED)) { throw runtime_error("You can't use this command until masternode list is synced\n"); } std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; mnEntries = masternodeConfig.getEntries(); int successful = 0; int failed = 0; Array resultsObj; BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; int nIndex; if(!mne.castOutputIndex(nIndex)) continue; CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex)); CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { if (strCommand == "missing") continue; if (strCommand == "disabled" && pmn->IsEnabled()) continue; } bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage); Object statusObj; statusObj.push_back(Pair("alias", mne.getAlias())); statusObj.push_back(Pair("result", result ? "success" : "failed")); if (result) { successful++; statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("error", errorMessage)); } resultsObj.push_back(statusObj); } if (fLock) pwalletMain->Lock(); Object returnObj; returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", successful, failed, successful + failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "alias") { std::string alias = params[2].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); bool found = false; int successful = 0; int failed = 0; Array resultsObj; Object statusObj; statusObj.push_back(Pair("alias", alias)); BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { if (mne.getAlias() == alias) { found = true; std::string errorMessage; bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage); statusObj.push_back(Pair("result", result ? "successful" : "failed")); if (result) { successful++; statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("error", errorMessage)); } break; } } if (!found) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "could not find alias in config. Verify with list-conf.")); } resultsObj.push_back(statusObj); if (fLock) pwalletMain->Lock(); Object returnObj; returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", successful, failed, successful + failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } return Value::null; } Value createmasternodekey (const Array& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "createmasternodekey\n" "\nCreate a new masternode private key\n" "\nResult:\n" "\"key\" (string) Masternode private key\n" "\nExamples:\n" + HelpExampleCli("createmasternodekey", "") + HelpExampleRpc("createmasternodekey", "")); CKey secret; secret.MakeNewKey(false); return CBitcoinSecret(secret).ToString(); } Value getmasternodeoutputs (const Array& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "getmasternodeoutputs\n" "\nPrint all masternode transaction outputs\n" "\nResult:\n" "[\n" " {\n" " \"txhash\": \"xxxx\", (string) output transaction hash\n" " \"outputidx\": n (numeric) output index number\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getmasternodeoutputs", "") + HelpExampleRpc("getmasternodeoutputs", "")); // Find possible candidates vector<COutput> possibleCoins = activeMasternode.SelectCoinsMasternode(); Array ret; BOOST_FOREACH (COutput& out, possibleCoins) { Object obj; obj.push_back(Pair("txhash", out.tx->GetHash().ToString())); obj.push_back(Pair("outputidx", out.i)); ret.push_back(obj); } return ret; } Value listmasternodeconf (const Array& params, bool fHelp) { std::string strFilter = ""; if (params.size() == 1) strFilter = params[0].get_str(); if (fHelp || (params.size() > 1)) throw runtime_error( "listmasternodeconf ( \"filter\" )\n" "\nPrint masternode.conf in JSON format\n" "\nArguments:\n" "1. \"filter\" (string, optional) Filter search text. Partial match on alias, address, txHash, or status.\n" "\nResult:\n" "[\n" " {\n" " \"alias\": \"xxxx\", (string) masternode alias\n" " \"address\": \"xxxx\", (string) masternode IP address\n" " \"privateKey\": \"xxxx\", (string) masternode private key\n" " \"txHash\": \"xxxx\", (string) transaction hash\n" " \"outputIndex\": n, (numeric) transaction output index\n" " \"status\": \"xxxx\" (string) masternode status\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listmasternodeconf", "") + HelpExampleRpc("listmasternodeconf", "")); std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; mnEntries = masternodeConfig.getEntries(); Array ret; BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { int nIndex; if(!mne.castOutputIndex(nIndex)) continue; CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex)); CMasternode* pmn = mnodeman.Find(vin); std::string strStatus = pmn ? pmn->Status() : "MISSING"; if (strFilter != "" && mne.getAlias().find(strFilter) == string::npos && mne.getIp().find(strFilter) == string::npos && mne.getTxHash().find(strFilter) == string::npos && strStatus.find(strFilter) == string::npos) continue; Object mnObj; mnObj.push_back(Pair("alias", mne.getAlias())); mnObj.push_back(Pair("address", mne.getIp())); mnObj.push_back(Pair("privateKey", mne.getPrivKey())); mnObj.push_back(Pair("txHash", mne.getTxHash())); mnObj.push_back(Pair("outputIndex", mne.getOutputIndex())); mnObj.push_back(Pair("status", strStatus)); ret.push_back(mnObj); } return ret; } Value getmasternodestatus (const Array& params, bool fHelp) { if (fHelp || (params.size() != 0)) throw runtime_error( "getmasternodestatus\n" "\nPrint masternode status\n" "\nResult:\n" "{\n" " \"txhash\": \"xxxx\", (string) Collateral transaction hash\n" " \"outputidx\": n, (numeric) Collateral transaction output index number\n" " \"netaddr\": \"xxxx\", (string) Masternode network address\n" " \"addr\": \"xxxx\", (string) PAWS address for masternode payments\n" " \"status\": \"xxxx\", (string) Masternode status\n" " \"message\": \"xxxx\" (string) Masternode status message\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmasternodestatus", "") + HelpExampleRpc("getmasternodestatus", "")); if (!fMasterNode) throw runtime_error("This is not a masternode"); CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn) { Object mnObj; mnObj.push_back(Pair("txhash", activeMasternode.vin.prevout.hash.ToString())); mnObj.push_back(Pair("outputidx", (uint64_t)activeMasternode.vin.prevout.n)); mnObj.push_back(Pair("netaddr", activeMasternode.service.ToString())); mnObj.push_back(Pair("addr", CBitcoinAddress(pmn->pubKeyCollateralAddress.GetID()).ToString())); mnObj.push_back(Pair("status", activeMasternode.status)); mnObj.push_back(Pair("message", activeMasternode.GetStatus())); return mnObj; } throw runtime_error("Masternode not found in the list of available masternodes. Current status: " + activeMasternode.GetStatus()); } Value getmasternodewinners (const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "getmasternodewinners ( blocks \"filter\" )\n" "\nPrint the masternode winners for the last n blocks\n" "\nArguments:\n" "1. blocks (numeric, optional) Number of previous blocks to show (default: 10)\n" "2. filter (string, optional) Search filter matching MN address\n" "\nResult (single winner):\n" "[\n" " {\n" " \"nHeight\": n, (numeric) block height\n" " \"winner\": {\n" " \"address\": \"xxxx\", (string) PAWS MN Address\n" " \"nVotes\": n, (numeric) Number of votes for winner\n" " }\n" " }\n" " ,...\n" "]\n" "\nResult (multiple winners):\n" "[\n" " {\n" " \"nHeight\": n, (numeric) block height\n" " \"winner\": [\n" " {\n" " \"address\": \"xxxx\", (string) PAWS MN Address\n" " \"nVotes\": n, (numeric) Number of votes for winner\n" " }\n" " ,...\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getmasternodewinners", "") + HelpExampleRpc("getmasternodewinners", "")); int nHeight; { LOCK(cs_main); CBlockIndex* pindex = chainActive.Tip(); if(!pindex) return 0; nHeight = pindex->nHeight; } int nLast = 10; std::string strFilter = ""; if (params.size() >= 1) nLast = atoi(params[0].get_str()); if (params.size() == 2) strFilter = params[1].get_str(); Array ret; for (int i = nHeight - nLast; i < nHeight + 20; i++) { Object obj; obj.push_back(Pair("nHeight", i)); std::string strPayment = GetRequiredPaymentsString(i); if (strFilter != "" && strPayment.find(strFilter) == std::string::npos) continue; if (strPayment.find(',') != std::string::npos) { Array winner; boost::char_separator<char> sep(","); boost::tokenizer< boost::char_separator<char> > tokens(strPayment, sep); BOOST_FOREACH (const string& t, tokens) { Object addr; std::size_t pos = t.find(":"); std::string strAddress = t.substr(0,pos); uint64_t nVotes = atoi(t.substr(pos+1)); addr.push_back(Pair("address", strAddress)); addr.push_back(Pair("nVotes", nVotes)); winner.push_back(addr); } obj.push_back(Pair("winner", winner)); } else if (strPayment.find("Unknown") == std::string::npos) { Object winner; std::size_t pos = strPayment.find(":"); std::string strAddress = strPayment.substr(0,pos); uint64_t nVotes = atoi(strPayment.substr(pos+1)); winner.push_back(Pair("address", strAddress)); winner.push_back(Pair("nVotes", nVotes)); obj.push_back(Pair("winner", winner)); } else { Object winner; winner.push_back(Pair("address", strPayment)); winner.push_back(Pair("nVotes", 0)); obj.push_back(Pair("winner", winner)); } ret.push_back(obj); } return ret; } Value getmasternodescores (const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getmasternodescores ( blocks )\n" "\nPrint list of winning masternode by score\n" "\nArguments:\n" "1. blocks (numeric, optional) Show the last n blocks (default 10)\n" "\nResult:\n" "{\n" " xxxx: \"xxxx\" (numeric : string) Block height : Masternode hash\n" " ,...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmasternodescores", "") + HelpExampleRpc("getmasternodescores", "")); int nLast = 10; if (params.size() == 1) { try { nLast = std::stoi(params[0].get_str()); } catch (const boost::bad_lexical_cast &) { throw runtime_error("Exception on param 2"); } } Object obj; std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector(); for (int nHeight = chainActive.Tip()->nHeight - nLast; nHeight < chainActive.Tip()->nHeight + 20; nHeight++) { uint256 nHigh = 0; CMasternode* pBestMasternode = NULL; BOOST_FOREACH (CMasternode& mn, vMasternodes) { uint256 n = mn.CalculateScore(1, nHeight - 100); if (n > nHigh) { nHigh = n; pBestMasternode = &mn; } } if (pBestMasternode) obj.push_back(Pair(strprintf("%d", nHeight), pBestMasternode->vin.prevout.hash.ToString().c_str())); } return obj; }
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "base.hpp" #include <vector> #include <ngraph/opsets/opset2.hpp> using namespace MKLDNNPlugin; namespace InferenceEngine { namespace Extensions { namespace Cpu { class ReorgYoloImpl: public ExtLayerBase { public: bool isSupportedOperation(const std::shared_ptr<ngraph::Node>& op, std::string& errorMessage) noexcept { try { const auto reorgYolo = std::dynamic_pointer_cast<const ngraph::opset2::ReorgYolo>(op); if (!reorgYolo) { errorMessage = "Only opset2 ReorgYolo operation is supported"; return false; } } catch (...) { return false; } return true; } explicit ReorgYoloImpl(const std::shared_ptr<ngraph::Node>& op) { try { std::string errorMessage; if (!isSupportedOperation(op, errorMessage)) { IE_THROW(NotImplemented) << errorMessage; } errorPrefix = std::string(op->get_type_name()) + " node with name '" + op->get_friendly_name() + "'"; if (op->get_input_size() != 1 || op->get_output_size() != 1) IE_THROW() << errorPrefix << " has incorrect number of input/output edges!"; const auto reorgYolo = std::dynamic_pointer_cast<const ngraph::opset2::ReorgYolo>(op); const auto strides = reorgYolo->get_strides(); if (strides.empty()) IE_THROW() << errorPrefix << " has empty strides"; stride = strides[0]; addConfig(op, {{TensorDescCreatorTypes::ncsp, Precision::FP32}}, {{TensorDescCreatorTypes::ncsp, Precision::FP32}}); } catch (InferenceEngine::Exception &ex) { errorMsg = ex.what(); } } StatusCode execute(std::vector<Blob::Ptr>& inputs, std::vector<Blob::Ptr>& outputs, ResponseDesc *resp) noexcept override { const auto *src_data = inputs[0]->cbuffer().as<const float *>(); auto *dst_data = outputs[0]->buffer().as<float *>(); int IW = (inputs[0]->getTensorDesc().getDims().size() > 3) ? inputs[0]->getTensorDesc().getDims()[3] : 1; int IH = (inputs[0]->getTensorDesc().getDims().size() > 2) ? inputs[0]->getTensorDesc().getDims()[2] : 1; int IC = (inputs[0]->getTensorDesc().getDims().size() > 1) ? inputs[0]->getTensorDesc().getDims()[1] : 1; int B = (inputs[0]->getTensorDesc().getDims().size() > 0) ? inputs[0]->getTensorDesc().getDims()[0] : 1; int ic_off = IC / (stride * stride); int ih_off = IH * stride; int iw_off = IW * stride; for (int b = 0; b < B; b++) { for (int ic = 0; ic < IC; ic++) { for (int ih = 0; ih < IH; ih++) { for (int iw = 0; iw < IW; iw++) { int dstIndex = b * IC * IH * IW + ic * IH * IW + ih * IW + iw; int oc = ic % ic_off; int offset = ic / ic_off; int ow = iw * stride + offset % stride; int oh = ih * stride + offset / stride; int srcIndex = b * ic_off * ih_off * iw_off + oc * ih_off * iw_off + oh * iw_off + ow; dst_data[dstIndex] = src_data[srcIndex]; } } } } return OK; } private: int stride; std::string errorPrefix; }; REG_FACTORY_FOR(ReorgYoloImpl, ReorgYolo); } // namespace Cpu } // namespace Extensions } // namespace InferenceEngine
#pragma once #include <nlohmann/json.hpp> struct SPedComponentVariationData { int ComponentId; int DrawableId; int TextureId; int PaletteId; }; inline void to_json(nlohmann::ordered_json& j, const SPedComponentVariationData& componentVariationData) { j = nlohmann::ordered_json{ { "ComponentId", componentVariationData.ComponentId }, { "DrawableId", componentVariationData.DrawableId }, { "TextureId", componentVariationData.TextureId }, { "PaletteId", componentVariationData.PaletteId }, }; } inline void from_json(const nlohmann::ordered_json& j, SPedComponentVariationData& componentVariationData) { j.at("ComponentId").get_to(componentVariationData.ComponentId); j.at("DrawableId").get_to(componentVariationData.DrawableId); j.at("TextureId").get_to(componentVariationData.TextureId); j.at("PaletteId").get_to(componentVariationData.PaletteId); }
#include "activemasternode.h" #include "addrman.h" #include "masternode.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "protocol.h" #include "spork.h" #include "chainparams.h" // Bootup the Masternode, look for a 10000 WILO input and register on the network // void CActiveMasternode::ManageStatus() { std::string errorMessage; if (!fMasterNode) return; if (fDebug) LogPrintf("CActiveMasternode::ManageStatus() - Begin\n"); //need correct blocks to send ping if (Params().NetworkID() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { status = ACTIVE_MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveMasternode::ManageStatus() - %s\n", GetStatus()); return; } if (status == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) status = ACTIVE_MASTERNODE_INITIAL; if (status == ACTIVE_MASTERNODE_INITIAL) { CMasternode* pmn; pmn = mnodeman.Find(pubKeyMasternode); if (pmn != NULL) { pmn->Check(); if (pmn->IsEnabled() && pmn->protocolVersion == PROTOCOL_VERSION) EnableHotColdMasterNode(pmn->vin, pmn->addr); } } if (status != ACTIVE_MASTERNODE_STARTED) { // Set defaults status = ACTIVE_MASTERNODE_NOT_CAPABLE; notCapableReason = ""; if (pwalletMain->IsLocked()) { notCapableReason = "Wallet is locked."; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason); return; } if (pwalletMain->GetBalance() == 0) { notCapableReason = "Hot node, waiting for remote activation."; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason); return; } if (strMasterNodeAddr.empty()) { if (!GetLocal(service)) { notCapableReason = "Can't detect external address. Please use the masternodeaddr configuration option."; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason); return; } } else { service = CService(strMasterNodeAddr); } if (Params().NetworkID() == CBaseChainParams::MAIN) { if (service.GetPort() != 23998) { notCapableReason = strprintf("Invalid port: %u - only 23998 is supported on mainnet.", service.GetPort()); LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason); return; } } else if (service.GetPort() == 23998) { notCapableReason = strprintf("Invalid port: %u - 23998 is only supported on mainnet.", service.GetPort()); LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason); return; } LogPrintf("CActiveMasternode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString()); CNode* pnode = ConnectNode((CAddress)service, NULL, false); if (!pnode) { notCapableReason = "Could not connect to " + service.ToString(); LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason); return; } pnode->Release(); // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; if (GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) { if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) { status = ACTIVE_MASTERNODE_INPUT_TOO_NEW; notCapableReason = strprintf("%s - %d confirmations", GetStatus(), GetInputAge(vin)); LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason); return; } LOCK(pwalletMain->cs_wallet); pwalletMain->LockCoin(vin.prevout); // send to all nodes CPubKey pubKeyMasternode; CKey keyMasternode; if (!DarKsendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { notCapableReason = "Error upon calling SetKey: " + errorMessage; LogPrintf("Register::ManageStatus() - %s\n", notCapableReason); return; } if (!Register(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage)) { notCapableReason = "Error on Register: " + errorMessage; LogPrintf("Register::ManageStatus() - %s\n", notCapableReason); return; } LogPrintf("CActiveMasternode::ManageStatus() - Is capable master node!\n"); status = ACTIVE_MASTERNODE_STARTED; return; } else { notCapableReason = "Could not find suitable coins!"; LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason); return; } } //send to all peers if (!SendMasternodePing(errorMessage)) { LogPrintf("CActiveMasternode::ManageStatus() - Error on Ping: %s\n", errorMessage); } } std::string CActiveMasternode::GetStatus() { switch (status) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", MASTERNODE_MIN_CONFIRMATIONS); case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + notCapableReason; case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started"; default: return "unknown"; } } bool CActiveMasternode::SendMasternodePing(std::string& errorMessage) { if (status != ACTIVE_MASTERNODE_STARTED) { errorMessage = "Masternode is not in a running status"; return false; } CPubKey pubKeyMasternode; CKey keyMasternode; if (!DarKsendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { errorMessage = strprintf("Error upon calling SetKey: %s\n", errorMessage); return false; } LogPrintf("CActiveMasternode::SendMasternodePing() - Relay Masternode Ping vin = %s\n", vin.ToString()); CMasternodePing mnp(vin); if (!mnp.Sign(keyMasternode, pubKeyMasternode)) { errorMessage = "Couldn't sign Masternode Ping"; return false; } // Update lastPing for our masternode in Masternode list CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { if (pmn->IsPingedWithin(MASTERNODE_PING_SECONDS, mnp.sigTime)) { errorMessage = "Too early to send Masternode Ping"; return false; } pmn->lastPing = mnp; mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp)); //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = mnp; mnp.Relay(); /* * IT'S SAFE TO REMOVE THIS IN FURTHER VERSIONS * AFTER MIGRATION TO V12 IS DONE */ if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return true; // for migration purposes ping our node on old masternodes network too std::string retErrorMessage; std::vector<unsigned char> vchMasterNodeSignature; int64_t masterNodeSignatureTime = GetAdjustedTime(); std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + boost::lexical_cast<std::string>(false); if (!DarKsendSigner.SignMessage(strMessage, retErrorMessage, vchMasterNodeSignature, keyMasternode)) { errorMessage = "dseep sign message failed: " + retErrorMessage; return false; } if (!DarKsendSigner.VerifyMessage(pubKeyMasternode, vchMasterNodeSignature, strMessage, retErrorMessage)) { errorMessage = "dseep verify message failed: " + retErrorMessage; return false; } LogPrint("masternode", "dseep - relaying from active mn, %s \n", vin.ToString().c_str()); LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) pnode->PushMessage("dseep", vin, vchMasterNodeSignature, masterNodeSignatureTime, false); /* * END OF "REMOVE" */ return true; } else { // Seems like we are trying to send a ping while the Masternode is not registered in the network errorMessage = "Darksend Masternode List doesn't include our Masternode, shutting down Masternode pinging service! " + vin.ToString(); status = ACTIVE_MASTERNODE_NOT_CAPABLE; notCapableReason = errorMessage; return false; } } bool CActiveMasternode::Register(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& errorMessage) { CTxIn vin; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; //need correct blocks to send ping if (!masternodeSync.IsBlockchainSynced()) { errorMessage = GetStatus(); LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage); return false; } if (!DarKsendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) { errorMessage = strprintf("Can't find keys for masternode %s - %s", strService, errorMessage); LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage); return false; } if (!GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress, strTxHash, strOutputIndex)) { errorMessage = strprintf("Could not allocate vin %s:%s for masternode %s", strTxHash, strOutputIndex, strService); LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage); return false; } CService service = CService(strService); if (Params().NetworkID() == CBaseChainParams::MAIN) { if (service.GetPort() != 23998) { errorMessage = strprintf("Invalid port %u for masternode %s - only 23998 is supported on mainnet.", service.GetPort(), strService); LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage); return false; } } else if (service.GetPort() == 23998) { errorMessage = strprintf("Invalid port %u for masternode %s - 23998 is only supported on mainnet.", service.GetPort(), strService); LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage); return false; } addrman.Add(CAddress(service), CNetAddr("127.0.0.1"), 2 * 60 * 60); return Register(vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage); } bool CActiveMasternode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& errorMessage) { CMasternodeBroadcast mnb; CMasternodePing mnp(vin); if (!mnp.Sign(keyMasternode, pubKeyMasternode)) { errorMessage = strprintf("Failed to sign ping, vin: %s", vin.ToString()); LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage); return false; } mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp)); LogPrintf("CActiveMasternode::Register() - Adding to Masternode list\n service: %s\n vin: %s\n", service.ToString(), vin.ToString()); mnb = CMasternodeBroadcast(service, vin, pubKeyCollateralAddress, pubKeyMasternode, PROTOCOL_VERSION); mnb.lastPing = mnp; if (!mnb.Sign(keyCollateralAddress)) { errorMessage = strprintf("Failed to sign broadcast, vin: %s", vin.ToString()); LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage); return false; } mnodeman.mapSeenMasternodeBroadcast.insert(make_pair(mnb.GetHash(), mnb)); masternodeSync.AddedMasternodeList(mnb.GetHash()); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { CMasternode mn(mnb); mnodeman.Add(mn); } else { pmn->UpdateFromNewBroadcast(mnb); } //send to all peers LogPrintf("CActiveMasternode::Register() - RelayElectionEntry vin = %s\n", vin.ToString()); mnb.Relay(); /* * IT'S SAFE TO REMOVE THIS IN FURTHER VERSIONS * AFTER MIGRATION TO V12 IS DONE */ if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return true; // for migration purposes inject our node in old masternodes' list too std::string retErrorMessage; std::vector<unsigned char> vchMasterNodeSignature; int64_t masterNodeSignatureTime = GetAdjustedTime(); std::string donationAddress = ""; int donationPercantage = 0; std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION) + donationAddress + boost::lexical_cast<std::string>(donationPercantage); if (!DarKsendSigner.SignMessage(strMessage, retErrorMessage, vchMasterNodeSignature, keyCollateralAddress)) { errorMessage = "dsee sign message failed: " + retErrorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str()); return false; } if (!DarKsendSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, retErrorMessage)) { errorMessage = "dsee verify message failed: " + retErrorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str()); return false; } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) pnode->PushMessage("dsee", vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION, donationAddress, donationPercantage); /* * END OF "REMOVE" */ return true; } bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { return GetMasterNodeVin(vin, pubkey, secretKey, "", ""); } bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) { // Find possible candidates TRY_LOCK(pwalletMain->cs_wallet, fWallet); if (!fWallet) return false; vector<COutput> possibleCoins = SelectCoinsMasternode(); COutput* selectedOutput; // Find the vin if (!strTxHash.empty()) { // Let's find it uint256 txHash(strTxHash); int outputIndex; try { outputIndex = std::stoi(strOutputIndex.c_str()); } catch (const std::exception& e) { LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what()); return false; } bool found = false; BOOST_FOREACH (COutput& out, possibleCoins) { if (out.tx->GetHash() == txHash && out.i == outputIndex) { selectedOutput = &out; found = true; break; } } if (!found) { LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate valid vin\n"); return false; } } else { // No output specified, Select the first one if (possibleCoins.size() > 0) { selectedOutput = &possibleCoins[0]; } else { LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate specified vin from possible list\n"); return false; } } // At this point we have a selected output, retrieve the associated info return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey); } // Extract Masternode vin information from output bool CActiveMasternode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { CScript pubScript; vin = CTxIn(out.tx->GetHash(), out.i); pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey CTxDestination address1; ExtractDestination(pubScript, address1); CBitcoinAddress address2(address1); CKeyID keyID; if (!address2.GetKeyID(keyID)) { LogPrintf("CActiveMasternode::GetMasterNodeVin - Address does not refer to a key\n"); return false; } if (!pwalletMain->GetKey(keyID, secretKey)) { LogPrintf("CActiveMasternode::GetMasterNodeVin - Private key for address is not known\n"); return false; } pubkey = secretKey.GetPubKey(); return true; } // get all possible outputs for running Masternode vector<COutput> CActiveMasternode::SelectCoinsMasternode() { vector<COutput> vCoins; vector<COutput> filteredCoins; vector<COutPoint> confLockedCoins; // Temporary unlock MN coins from masternode.conf if (GetBoolArg("-mnconflock", true)) { uint256 mnTxHash; BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { mnTxHash.SetHex(mne.getTxHash()); int nIndex; if(!mne.castOutputIndex(nIndex)) continue; COutPoint outpoint = COutPoint(mnTxHash, nIndex); confLockedCoins.push_back(outpoint); pwalletMain->UnlockCoin(outpoint); } } // Retrieve all possible outputs pwalletMain->AvailableCoins(vCoins); // Lock MN coins from masternode.conf back if they where temporary unlocked if (!confLockedCoins.empty()) { BOOST_FOREACH (COutPoint outpoint, confLockedCoins) pwalletMain->LockCoin(outpoint); } // Filter BOOST_FOREACH (const COutput& out, vCoins) { if (out.tx->vout[out.i].nValue == Params().MasternodeColleteralLimxDev() * COIN) { //exactly filteredCoins.push_back(out); } } return filteredCoins; } // when starting a Masternode, this can enable to run as a hot wallet with no funds bool CActiveMasternode::EnableHotColdMasterNode(CTxIn& newVin, CService& newService) { if (!fMasterNode) return false; status = ACTIVE_MASTERNODE_STARTED; //The values below are needed for signing mnping messages going forward vin = newVin; service = newService; LogPrintf("CActiveMasternode::EnableHotColdMasterNode() - Enabled! You may shut down the cold daemon.\n"); return true; }
#include <gtest/gtest.h> #include <thrust/complex.h> #include <thrust/device_vector.h> #include "gtensor/thrust_ext.h" using namespace thrust::ext; TEST(thrust_ext, is_device_reference) { using D = thrust::device_reference<double>; using T = int; static_assert(is_device_reference<D>::value, "is_device_reference"); static_assert(!is_device_reference<T>::value, "is_device_reference"); } TEST(thrust_ext, has_device_reference) { using D = thrust::device_reference<double>; using T = int; static_assert(has_device_reference<D, D>::value, "has_device_reference"); static_assert(has_device_reference<D, T>::value, "has_device_reference"); static_assert(has_device_reference<T, D>::value, "has_device_reference"); static_assert(!has_device_reference<T, T>::value, "has_device_reference"); } TEST(thrust_ext, remove_device_reference_t) { using D = thrust::device_reference<double>; using T = int; static_assert(std::is_same<remove_device_reference_t<D>, double>::value, "remove_device_reference_t"); static_assert(std::is_same<remove_device_reference_t<T>, int>::value, "remove_device_reference_t"); } TEST(thrust_ext, add_complex_device_reference) { using T = thrust::complex<double>; thrust::device_vector<T> v(2); v[0] = 1.; v[1] = 2.; EXPECT_EQ(v[0] + v[1], 3.); EXPECT_EQ(v[0] + 3., 4.); EXPECT_EQ(3. + v[1], 5.); thrust::device_vector<double> d(2); d[0] = 1.; d[1] = 2.; EXPECT_EQ(v[0] + v[1], 3.); EXPECT_EQ(v[0] + d[1], 3.); EXPECT_EQ(d[0] + v[1], 3.); } TEST(thrust_ext, subtract_complex_device_reference) { using T = thrust::complex<double>; thrust::device_vector<T> v(2); v[0] = 1.; v[1] = 2.; EXPECT_EQ(v[0] - v[1], -1.); EXPECT_EQ(v[0] - 3., -2.); EXPECT_EQ(3. - v[1], 1.); } TEST(thrust_ext, multiply_complex_device_reference) { using T = thrust::complex<double>; thrust::device_vector<T> v(2); v[0] = 1.; v[1] = 2.; EXPECT_EQ(v[0] * v[1], 2.); EXPECT_EQ(v[0] * 3., 3.); EXPECT_EQ(3. * v[1], 6.); } TEST(thrust_ext, divide_complex_device_reference) { using T = thrust::complex<double>; thrust::device_vector<T> v(2); v[0] = 12.; v[1] = 2.; EXPECT_EQ(v[0] / v[1], 6.); EXPECT_EQ(v[0] / 3., 4.); EXPECT_EQ(3. / v[1], 1.5); }
#pragma once #include <Quasar/Core/Base.hpp> #include <Quasar/Scene/Scene.hpp> #include <Quasar/Scene/Entity.hpp> namespace Quasar { class SceneHierarchyPanel { private: Ref<Scene> m_Context; Entity m_SelectionContext; void drawEntityNode(Entity entity); void drawComponents(Entity entity); public: SceneHierarchyPanel() = default; SceneHierarchyPanel(const Ref<Scene> &scene); void setContext(const Ref<Scene> &scene); void onImGuiRender(); Entity getSelectedEntity() const { return m_SelectionContext; } void setSelectedEntity(Entity entity); }; } // namespace Quasar
// Copyright (c) 2018-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "deterministicmns.h" #include "providertx.h" #include "specialtx.h" #include "base58.h" #include "chainparams.h" #include "clientversion.h" #include "core_io.h" #include "hash.h" #include "messagesigner.h" #include "script/standard.h" #include "streams.h" #include "univalue.h" #include "validation.h" template <typename ProTx> static bool CheckService(const uint256& proTxHash, const ProTx& proTx, CValidationState& state) { if (!proTx.addr.IsValid()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); } if (Params().NetworkIDString() != CBaseChainParams::REGTEST && !proTx.addr.IsRoutable()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (proTx.addr.GetPort() != mainnetDefaultPort) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr-port"); } } else if (proTx.addr.GetPort() == mainnetDefaultPort) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr-port"); } if (!proTx.addr.IsIPv4()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-addr"); } return true; } template <typename ProTx> static bool CheckHashSig(const ProTx& proTx, const CKeyID& keyID, CValidationState& state) { std::string strError; if (!CHashSigner::VerifyHash(::SerializeHash(proTx), keyID, proTx.vchSig, strError)) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-sig", false, strError); } return true; } template <typename ProTx> static bool CheckStringSig(const ProTx& proTx, const CKeyID& keyID, CValidationState& state) { std::string strError; if (!CMessageSigner::VerifyMessage(keyID, proTx.vchSig, proTx.MakeSignString(), strError)) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-sig", false, strError); } return true; } template <typename ProTx> static bool CheckHashSig(const ProTx& proTx, const CBLSPublicKey& pubKey, CValidationState& state) { if (!proTx.sig.VerifyInsecure(pubKey, ::SerializeHash(proTx))) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-sig", false); } return true; } template <typename ProTx> static bool CheckInputsHash(const CTransaction& tx, const ProTx& proTx, CValidationState& state) { uint256 inputsHash = CalcTxInputsHash(tx); if (inputsHash != proTx.inputsHash) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-inputs-hash"); } return true; } bool CheckProRegTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { if (tx.nType != TRANSACTION_PROVIDER_REGISTER) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-type"); } CProRegTx ptx; if (!GetTxPayload(tx, ptx)) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-payload"); } if (ptx.nVersion == 0 || ptx.nVersion > CProRegTx::CURRENT_VERSION) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-version"); } if (ptx.nType != 0) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-type"); } if (ptx.nMode != 0) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-mode"); } if (ptx.keyIDOwner.IsNull() || !ptx.pubKeyOperator.IsValid() || ptx.keyIDVoting.IsNull()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-null"); } if (!ptx.scriptPayout.IsPayToPublicKeyHash() && !ptx.scriptPayout.IsPayToScriptHash()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee"); } CTxDestination payoutDest; if (!ExtractDestination(ptx.scriptPayout, payoutDest)) { // should not happen as we checked script types before return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-dest"); } // don't allow reuse of payout key for other keys (don't allow people to put the payee key onto an online server) if (payoutDest == CTxDestination(ptx.keyIDOwner) || payoutDest == CTxDestination(ptx.keyIDVoting)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-reuse"); } // It's allowed to set addr to 0, which will put the MN into PoSe-banned state and require a ProUpServTx to be issues later // If any of both is set, it must be valid however if (ptx.addr != CService() && !CheckService(tx.GetHash(), ptx, state)) { return false; } if (ptx.nOperatorReward > 10000) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-operator-reward"); } CTxDestination collateralTxDest; CKeyID keyForPayloadSig; COutPoint collateralOutpoint; if (!ptx.collateralOutpoint.hash.IsNull()) { Coin coin; if (!GetUTXOCoin(ptx.collateralOutpoint, coin) || coin.out.nValue != 25000 * COIN) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral"); } if (!ExtractDestination(coin.out.scriptPubKey, collateralTxDest)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-dest"); } // Extract key from collateral. This only works for P2PK and P2PKH collaterals and will fail for P2SH. // Issuer of this ProRegTx must prove ownership with this key by signing the ProRegTx if (!CBitcoinAddress(collateralTxDest).GetKeyID(keyForPayloadSig)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-pkh"); } collateralOutpoint = ptx.collateralOutpoint; } else { if (ptx.collateralOutpoint.n >= tx.vout.size()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-index"); } if (tx.vout[ptx.collateralOutpoint.n].nValue != 25000 * COIN) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral"); } if (!ExtractDestination(tx.vout[ptx.collateralOutpoint.n].scriptPubKey, collateralTxDest)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-dest"); } collateralOutpoint = COutPoint(tx.GetHash(), ptx.collateralOutpoint.n); } // don't allow reuse of collateral key for other keys (don't allow people to put the collateral key onto an online server) // this check applies to internal and external collateral, but internal collaterals are not necessarely a P2PKH if (collateralTxDest == CTxDestination(ptx.keyIDOwner) || collateralTxDest == CTxDestination(ptx.keyIDVoting)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-reuse"); } if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); // only allow reusing of addresses when it's for the same collateral (which replaces the old MN) if (mnList.HasUniqueProperty(ptx.addr) && mnList.GetUniquePropertyMN(ptx.addr)->collateralOutpoint != collateralOutpoint) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-addr"); } // never allow duplicate keys, even if this ProTx would replace an existing MN if (mnList.HasUniqueProperty(ptx.keyIDOwner) || mnList.HasUniqueProperty(ptx.pubKeyOperator)) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-key"); } if (!deterministicMNManager->IsDIP3Enforced(pindexPrev->nHeight)) { if (ptx.keyIDOwner != ptx.keyIDVoting) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-not-same"); } } } if (!CheckInputsHash(tx, ptx, state)) { return false; } if (!keyForPayloadSig.IsNull()) { // collateral is not part of this ProRegTx, so we must verify ownership of the collateral if (!CheckStringSig(ptx, keyForPayloadSig, state)) { return false; } } else { // collateral is part of this ProRegTx, so we know the collateral is owned by the issuer if (!ptx.vchSig.empty()) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-sig"); } } return true; } bool CheckProUpServTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { if (tx.nType != TRANSACTION_PROVIDER_UPDATE_SERVICE) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-type"); } CProUpServTx ptx; if (!GetTxPayload(tx, ptx)) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-payload"); } if (ptx.nVersion == 0 || ptx.nVersion > CProRegTx::CURRENT_VERSION) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-version"); } if (!CheckService(ptx.proTxHash, ptx, state)) { return false; } if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); auto mn = mnList.GetMN(ptx.proTxHash); if (!mn) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-hash"); } // don't allow updating to addresses already used by other MNs if (mnList.HasUniqueProperty(ptx.addr) && mnList.GetUniquePropertyMN(ptx.addr)->proTxHash != ptx.proTxHash) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-addr"); } if (ptx.scriptOperatorPayout != CScript()) { if (mn->nOperatorReward == 0) { // don't allow to set operator reward payee in case no operatorReward was set return state.DoS(10, false, REJECT_INVALID, "bad-protx-operator-payee"); } if (!ptx.scriptOperatorPayout.IsPayToPublicKeyHash() && !ptx.scriptOperatorPayout.IsPayToScriptHash()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-operator-payee"); } } // we can only check the signature if pindexPrev != NULL and the MN is known if (!CheckInputsHash(tx, ptx, state)) { return false; } if (!CheckHashSig(ptx, mn->pdmnState->pubKeyOperator.Get(), state)) { return false; } } return true; } bool CheckProUpRegTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { if (tx.nType != TRANSACTION_PROVIDER_UPDATE_REGISTRAR) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-type"); } CProUpRegTx ptx; if (!GetTxPayload(tx, ptx)) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-payload"); } if (ptx.nVersion == 0 || ptx.nVersion > CProRegTx::CURRENT_VERSION) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-version"); } if (ptx.nMode != 0) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-mode"); } if (!ptx.pubKeyOperator.IsValid() || ptx.keyIDVoting.IsNull()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-null"); } if (!ptx.scriptPayout.IsPayToPublicKeyHash() && !ptx.scriptPayout.IsPayToScriptHash()) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee"); } CTxDestination payoutDest; if (!ExtractDestination(ptx.scriptPayout, payoutDest)) { // should not happen as we checked script types before return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-dest"); } if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); auto dmn = mnList.GetMN(ptx.proTxHash); if (!dmn) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-hash"); } // don't allow reuse of payee key for other keys (don't allow people to put the payee key onto an online server) if (payoutDest == CTxDestination(dmn->pdmnState->keyIDOwner) || payoutDest == CTxDestination(ptx.keyIDVoting)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-payee-reuse"); } Coin coin; if (!GetUTXOCoin(dmn->collateralOutpoint, coin)) { // this should never happen (there would be no dmn otherwise) return state.DoS(100, false, REJECT_INVALID, "bad-protx-collateral"); } // don't allow reuse of collateral key for other keys (don't allow people to put the collateral key onto an online server) CTxDestination collateralTxDest; if (!ExtractDestination(coin.out.scriptPubKey, collateralTxDest)) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-collateral-dest"); } if (collateralTxDest == CTxDestination(dmn->pdmnState->keyIDOwner) || collateralTxDest == CTxDestination(ptx.keyIDVoting)) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-collateral-reuse"); } if (mnList.HasUniqueProperty(ptx.pubKeyOperator)) { auto otherDmn = mnList.GetUniquePropertyMN(ptx.pubKeyOperator); if (ptx.proTxHash != otherDmn->proTxHash) { return state.DoS(10, false, REJECT_DUPLICATE, "bad-protx-dup-key"); } } if (!deterministicMNManager->IsDIP3Enforced(pindexPrev->nHeight)) { if (dmn->pdmnState->keyIDOwner != ptx.keyIDVoting) { return state.DoS(10, false, REJECT_INVALID, "bad-protx-key-not-same"); } } if (!CheckInputsHash(tx, ptx, state)) { return false; } if (!CheckHashSig(ptx, dmn->pdmnState->keyIDOwner, state)) { return false; } } return true; } bool CheckProUpRevTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { if (tx.nType != TRANSACTION_PROVIDER_UPDATE_REVOKE) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-type"); } CProUpRevTx ptx; if (!GetTxPayload(tx, ptx)) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-payload"); } if (ptx.nVersion == 0 || ptx.nVersion > CProRegTx::CURRENT_VERSION) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-version"); } // ptx.nReason < CProUpRevTx::REASON_NOT_SPECIFIED is always `false` since // ptx.nReason is unsigned and CProUpRevTx::REASON_NOT_SPECIFIED == 0 if (ptx.nReason > CProUpRevTx::REASON_LAST) { return state.DoS(100, false, REJECT_INVALID, "bad-protx-reason"); } if (pindexPrev) { auto mnList = deterministicMNManager->GetListForBlock(pindexPrev->GetBlockHash()); auto dmn = mnList.GetMN(ptx.proTxHash); if (!dmn) return state.DoS(100, false, REJECT_INVALID, "bad-protx-hash"); if (!CheckInputsHash(tx, ptx, state)) return false; if (!CheckHashSig(ptx, dmn->pdmnState->pubKeyOperator.Get(), state)) return false; } return true; } std::string CProRegTx::MakeSignString() const { std::string s; // We only include the important stuff in the string form... CTxDestination destPayout; CBitcoinAddress addrPayout; std::string strPayout; if (ExtractDestination(scriptPayout, destPayout) && addrPayout.Set(destPayout)) { strPayout = addrPayout.ToString(); } else { strPayout = HexStr(scriptPayout.begin(), scriptPayout.end()); } s += strPayout + "|"; s += strprintf("%d", nOperatorReward) + "|"; s += CBitcoinAddress(keyIDOwner).ToString() + "|"; s += CBitcoinAddress(keyIDVoting).ToString() + "|"; // ... and also the full hash of the payload as a protection agains malleability and replays s += ::SerializeHash(*this).ToString(); return s; } std::string CProRegTx::ToString() const { CTxDestination dest; std::string payee = "unknown"; if (ExtractDestination(scriptPayout, dest)) { payee = CBitcoinAddress(dest).ToString(); } return strprintf("CProRegTx(nVersion=%d, collateralOutpoint=%s, addr=%s, nOperatorReward=%f, ownerAddress=%s, pubKeyOperator=%s, votingAddress=%s, scriptPayout=%s)", nVersion, collateralOutpoint.ToStringShort(), addr.ToString(), (double)nOperatorReward / 100, CBitcoinAddress(keyIDOwner).ToString(), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), payee); } void CProRegTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", nVersion)); obj.push_back(Pair("collateralHash", collateralOutpoint.hash.ToString())); obj.push_back(Pair("collateralIndex", (int)collateralOutpoint.n)); obj.push_back(Pair("service", addr.ToString(false))); obj.push_back(Pair("ownerAddress", CBitcoinAddress(keyIDOwner).ToString())); obj.push_back(Pair("votingAddress", CBitcoinAddress(keyIDVoting).ToString())); CTxDestination dest; if (ExtractDestination(scriptPayout, dest)) { CBitcoinAddress bitcoinAddress(dest); obj.push_back(Pair("payoutAddress", bitcoinAddress.ToString())); } obj.push_back(Pair("pubKeyOperator", pubKeyOperator.ToString())); obj.push_back(Pair("operatorReward", (double)nOperatorReward / 100)); obj.push_back(Pair("inputsHash", inputsHash.ToString())); } std::string CProUpServTx::ToString() const { CTxDestination dest; std::string payee = "unknown"; if (ExtractDestination(scriptOperatorPayout, dest)) { payee = CBitcoinAddress(dest).ToString(); } return strprintf("CProUpServTx(nVersion=%d, proTxHash=%s, addr=%s, operatorPayoutAddress=%s)", nVersion, proTxHash.ToString(), addr.ToString(), payee); } void CProUpServTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", nVersion)); obj.push_back(Pair("proTxHash", proTxHash.ToString())); obj.push_back(Pair("service", addr.ToString(false))); CTxDestination dest; if (ExtractDestination(scriptOperatorPayout, dest)) { CBitcoinAddress bitcoinAddress(dest); obj.push_back(Pair("operatorPayoutAddress", bitcoinAddress.ToString())); } obj.push_back(Pair("inputsHash", inputsHash.ToString())); } std::string CProUpRegTx::ToString() const { CTxDestination dest; std::string payee = "unknown"; if (ExtractDestination(scriptPayout, dest)) { payee = CBitcoinAddress(dest).ToString(); } return strprintf("CProUpRegTx(nVersion=%d, proTxHash=%s, pubKeyOperator=%s, votingAddress=%s, payoutAddress=%s)", nVersion, proTxHash.ToString(), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), payee); } void CProUpRegTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", nVersion)); obj.push_back(Pair("proTxHash", proTxHash.ToString())); obj.push_back(Pair("votingAddress", CBitcoinAddress(keyIDVoting).ToString())); CTxDestination dest; if (ExtractDestination(scriptPayout, dest)) { CBitcoinAddress bitcoinAddress(dest); obj.push_back(Pair("payoutAddress", bitcoinAddress.ToString())); } obj.push_back(Pair("pubKeyOperator", pubKeyOperator.ToString())); obj.push_back(Pair("inputsHash", inputsHash.ToString())); } std::string CProUpRevTx::ToString() const { return strprintf("CProUpRevTx(nVersion=%d, proTxHash=%s, nReason=%d)", nVersion, proTxHash.ToString(), nReason); } void CProUpRevTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", nVersion)); obj.push_back(Pair("proTxHash", proTxHash.ToString())); obj.push_back(Pair("reason", (int)nReason)); obj.push_back(Pair("inputsHash", inputsHash.ToString())); }
//============ Copyright (c) Valve Corporation, All rights reserved. ========== // // Function which do validation tests on UVs values at the s_source_t level // //============================================================================= #include "tier1/fmtstr.h" #include "tier1/utlmap.h" #include "studiomdl.h" #include "checkuv.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CCheckUVCmd::CCheckUVCmd() { Clear(); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CCheckUVCmd::Clear() { ClearCheck( CHECK_UV_ALL_FLAGS ); m_nOptGutterTexWidth = 512; m_nOptGutterTexHeight = 512; m_nOptGutterMin = 5; } //----------------------------------------------------------------------------- // Dumps an s_soruce_t as an OBJ file //----------------------------------------------------------------------------- static void WriteOBJ( const char *pszFilename, const s_source_t *pSource ) { FILE *pFile = fopen( pszFilename, "w" ); fprintf( pFile, "#\n" ); fprintf( pFile, "# s_source_t: %s\n", pSource->filename ); fprintf( pFile, "# Bone Count: %d\n", pSource->numbones ); for ( int i = 0; i < pSource->numbones; ++i ) { if ( pSource->localBone[i].parent >= 0 ) { fprintf( pFile, "# Bone %3d: %s Parent %3d: %s\n", i, pSource->localBone[i].name, pSource->localBone[i].parent, pSource->localBone[pSource->localBone[i].parent].name ); } else { fprintf( pFile, "# Bone %3d: %s\n", i, pSource->localBone[i].name ); } } fprintf( pFile, "# Mesh Count: %d\n", pSource->nummeshes ); fprintf( pFile, "# Vertex Count: %d\n", pSource->numvertices ); fprintf( pFile, "# Face Count: %d\n", pSource->numfaces ); fprintf( pFile, "#\n" ); fprintf( pFile, "# positions\n" ); fprintf( pFile, "#\n" ); for ( int i = 0; i < pSource->numvertices; ++i ) { const s_vertexinfo_t &v = pSource->vertex[i]; fprintf( pFile, "v %.4f %.4f %.4f\n", v.position.x, v.position.y, v.position.z ); } fprintf( pFile, "#\n" ); fprintf( pFile, "# texture coordinates\n" ); fprintf( pFile, "#\n" ); for ( int i = 0; i < pSource->numvertices; ++i ) { const s_vertexinfo_t &v = pSource->vertex[i]; fprintf( pFile, "vt %.4f %.4f\n", v.texcoord.x, v.texcoord.y ); } fprintf( pFile, "#\n" ); fprintf( pFile, "# normals\n" ); fprintf( pFile, "#\n" ); for ( int i = 0; i < pSource->numvertices; ++i ) { const s_vertexinfo_t &v = pSource->vertex[i]; fprintf( pFile, "vn %.4f %.4f %.4f\n", v.normal.x, v.normal.y, v.normal.z ); } for ( int i = 0; i < pSource->nummeshes; ++i ) { const s_mesh_t &m = pSource->mesh[i]; const s_texture_t &t = g_texture[pSource->meshindex[i]]; fprintf( pFile, "#\n" ); fprintf( pFile, "# mesh %d - %s\n", i, t.name ); fprintf( pFile, "# Face Count: %d\n", m.numfaces ); fprintf( pFile, "#\n" ); fprintf( pFile, "usemtl %s\n", t.name ); for ( int j = 0; j < m.numfaces; ++j ) { const s_face_t &f = pSource->face[m.faceoffset + j]; fprintf( pFile, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", f.a, f.a, f.a, f.b, f.b, f.b, f.c, f.c, f.c ); } } fclose( pFile ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- bool CCheckUVCmd::CheckUVs( const s_source_t *const *pSourceList, int nSourceCount ) const { if ( !DoAnyCheck() || nSourceCount <= 0 ) return true; bool bRet = true; for ( int i = 0; i < nSourceCount; ++i ) { const s_source_t *pSource = pSourceList[i]; bRet &= CheckNormalized( pSource ); bRet &= CheckOverlap( pSource ); bRet &= CheckInverse( pSource ); bRet &= CheckGutter( pSource ); } return bRet; } //----------------------------------------------------------------------------- // Check that all UVs are in the [0, 1] range //----------------------------------------------------------------------------- bool CCheckUVCmd::CheckNormalized( const struct s_source_t *pSource ) const { if ( !DoCheck( CHECK_UV_FLAG_NORMALIZED ) ) return true; CUtlRBTree< int > badVertexIndices( CDefOps< int >::LessFunc ); for ( int i = 0; i < pSource->numvertices; ++i ) { const s_vertexinfo_t &v = pSource->vertex[i]; if ( v.texcoord.x < 0.0f || v.texcoord.x > 1.0f || v.texcoord.y < 0.0f || v.texcoord.y > 1.0f ) { badVertexIndices.InsertIfNotFound( i ); } } if ( badVertexIndices.Count() <= 0 ) return true; Msg( "Error! %s\n", pSource->filename ); Msg( " UVs outside of [0, 1] range\n" ); for ( int i = 0; i < pSource->nummeshes; ++i ) { const s_mesh_t &m = pSource->mesh[i]; const s_texture_t &t = g_texture[pSource->meshindex[i]]; CUtlRBTree< int > badMeshVertexIndices( CDefOps< int >::LessFunc ); for ( int j = 0; j < m.numfaces; ++j ) { const s_face_t &f = pSource->face[m.faceoffset + j]; if ( badVertexIndices.HasElement( f.a ) ) { badMeshVertexIndices.InsertIfNotFound( f.a ); } if ( badVertexIndices.HasElement( f.b ) ) { badMeshVertexIndices.InsertIfNotFound( f.b ); } if ( badVertexIndices.HasElement( f.c ) ) { badMeshVertexIndices.InsertIfNotFound( f.c ); } } for ( auto vIt = badMeshVertexIndices.FirstInorder(); badMeshVertexIndices.IsValidIndex( vIt ); vIt = badMeshVertexIndices.NextInorder( vIt ) ) { PrintVertex( pSource->vertex[badMeshVertexIndices.Element( vIt )], t ); } } return false; } //----------------------------------------------------------------------------- // Check that all polygons in UV do not overlap //----------------------------------------------------------------------------- bool CCheckUVCmd::CheckOverlap( const struct s_source_t *pSource ) const { if ( !DoCheck( CHECK_UV_FLAG_OVERLAP ) ) return true; bool bRet = true; CUtlVector< CUtlVector< int > > faceOverlapMap; faceOverlapMap.SetCount( pSource->numfaces ); for ( int i = 0; i < pSource->numfaces; ++i ) { const s_face_t &fA = pSource->face[i]; const Vector2D &tAA = pSource->vertex[fA.a].texcoord; const Vector2D &tAB = pSource->vertex[fA.b].texcoord; const Vector2D &tAC = pSource->vertex[fA.c].texcoord; for ( int j = i + 1; j < pSource->numfaces; ++j ) { const s_face_t &fB = pSource->face[j]; const Vector2D tB[] = { pSource->vertex[fB.a].texcoord, pSource->vertex[fB.b].texcoord, pSource->vertex[fB.c].texcoord }; for ( int k = 0; k < ARRAYSIZE( tB ); ++k ) { const Vector vCheck = Barycentric( tB[k], tAA, tAB, tAC ); if ( vCheck.x > 0.0f && vCheck.y > 0.0f && vCheck.z > 0.0f ) { if ( bRet ) { Msg( "Error! %s\n", pSource->filename ); Msg( " Overlapping UV faces\n" ); bRet = false; } faceOverlapMap[i].AddToTail( j ); break; } } } } for ( int i = 0; i < faceOverlapMap.Count(); ++i ) { const CUtlVector< int > &overlapList = faceOverlapMap[i]; if ( overlapList.IsEmpty() ) continue;; const int nFaceA = i; const int nMeshA = FindMeshIndex( pSource, nFaceA ); PrintFace( pSource, nMeshA, nFaceA ); Msg( " Overlaps\n" ); for ( int j = 0; j < overlapList.Count(); ++j ) { const int nFaceB = overlapList[j]; const int nMeshB = FindMeshIndex( pSource, nFaceB ); PrintFace( pSource, nMeshB, nFaceB, " " ); } } return bRet; } //----------------------------------------------------------------------------- // Check that all polygons in UV have the correct winding, i.e. the cross // product of edge AB x BC points the right direction //----------------------------------------------------------------------------- bool CCheckUVCmd::CheckInverse( const struct s_source_t *pSource ) const { if ( !DoCheck( CHECK_UV_FLAG_INVERSE ) ) return true; bool bRetVal = true; for ( int i = 0; i < pSource->nummeshes; ++i ) { const s_mesh_t &m = pSource->mesh[i]; for ( int j = 0; j < m.numfaces; ++j ) { const int nFaceIndex = m.faceoffset + j; const s_face_t &f = pSource->face[nFaceIndex]; const Vector2D &tA = pSource->vertex[f.a].texcoord; const Vector2D &tB = pSource->vertex[f.b].texcoord; const Vector2D &tC = pSource->vertex[f.c].texcoord; const Vector vA( tA.x, tA.y, 0.0f ); const Vector vB( tB.x, tB.y, 0.0f ); const Vector vC( tC.x, tC.y, 0.0f ); const Vector vAB = vB - vA; const Vector vBC = vC - vB; const Vector vUVNormal = CrossProduct( vAB, vBC ); const float flDot = DotProduct( vUVNormal, Vector( 0.0f, 0.0f, 1.0f ) ); if ( flDot < 0.0f ) { if ( bRetVal ) { Msg( "Error! %s\n", pSource->filename ); Msg( " Inverse UV faces\n" ); bRetVal = false; } PrintFace( pSource, i, nFaceIndex ); } } } return bRetVal; } //----------------------------------------------------------------------------- // Check that the distance between edges in UV islands is a minimum number of pixels for a given texture size //----------------------------------------------------------------------------- bool CCheckUVCmd::CheckGutter( const struct s_source_t *pSource ) const { if ( !DoCheck( CHECK_UV_FLAG_GUTTER ) ) return true; // TODO: Implement me! return true; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- Vector CCheckUVCmd::Barycentric( const Vector2D &vP, const Vector2D &vA, const Vector2D &vB, const Vector2D &vC ) { const Vector2D v0 = vB - vA; const Vector2D v1 = vC - vA; const Vector2D v2 = vP - vA; const float d00 = DotProduct2D( v0, v0 ); const float d01 = DotProduct2D( v0, v1 ); const float d11 = DotProduct2D( v1, v1 ); const float d20 = DotProduct2D( v2, v0 ); const float d21 = DotProduct2D( v2, v1 ); const float flDenom = d00 * d11 - d01 * d01; const float flV = ( d11 * d20 - d01 * d21 ) / flDenom; const float flW = ( d00 * d21 - d01 * d20 ) / flDenom; const float flU = 1.0f - flV - flW; return Vector( flV, flW, flU ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- Vector CCheckUVCmd::Barycentric( const Vector &vP, const Vector &vA, const Vector &vB, const Vector &vC ) { const Vector v0 = vB - vA; const Vector v1 = vC - vA; const Vector v2 = vP - vA; const float d00 = DotProduct( v0, v0 ); const float d01 = DotProduct( v0, v1 ); const float d11 = DotProduct( v1, v1 ); const float d20 = DotProduct( v2, v0 ); const float d21 = DotProduct( v2, v1 ); const float flDenom = d00 * d11 - d01 * d01; const float flV = ( d11 * d20 - d01 * d21 ) / flDenom; const float flW = ( d00 * d21 - d01 * d20 ) / flDenom; const float flU = 1.0f - flV - flW; return Vector( flV, flW, flU ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int CCheckUVCmd::FindMeshIndex( const struct s_source_t *pSource, int nFaceIndex ) { for ( int i = 1; i < pSource->nummeshes; ++i ) { if ( nFaceIndex <= pSource->mesh[i].faceoffset ) return i; } return 0; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CCheckUVCmd::PrintVertex( const s_vertexinfo_t &v, const char *pszPrefix /* = " " */ ) { Msg( "%sP: %8.4f %8.4f %8.4f T: %8.4f %8.4f\n", pszPrefix, v.position.x, v.position.y, v.position.z, v.texcoord.x, v.texcoord.y ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CCheckUVCmd::PrintVertex( const s_vertexinfo_t &v, const s_texture_t &t, const char *pszPrefix /* = " " */ ) { Msg( "%sP: %8.4f %8.4f %8.4f T: %8.4f %8.4f M: %s\n", pszPrefix, v.position.x, v.position.y, v.position.z, v.texcoord.x, v.texcoord.y, t.name ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CCheckUVCmd::PrintFace( const s_source_t *pSource, const int nMesh, const int nFace, const char *pszPrefix /* = " " */ ) { const s_texture_t &t = g_texture[pSource->meshindex[nMesh]]; const s_face_t &f = pSource->face[nFace]; Msg( "%sF: %4d %s\n", pszPrefix, nFace, t.name ); PrintVertex( pSource->vertex[f.a], pszPrefix ); PrintVertex( pSource->vertex[f.b], pszPrefix ); PrintVertex( pSource->vertex[f.c], pszPrefix ); }
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/compiler/frontend/kernel_to_il.h" #include "platform/assert.h" #include "platform/globals.h" #include "vm/class_id.h" #include "vm/compiler/aot/precompiler.h" #include "vm/compiler/backend/il.h" #include "vm/compiler/backend/il_printer.h" #include "vm/compiler/backend/locations.h" #include "vm/compiler/backend/range_analysis.h" #include "vm/compiler/ffi/abi.h" #include "vm/compiler/ffi/marshaller.h" #include "vm/compiler/ffi/native_calling_convention.h" #include "vm/compiler/ffi/native_type.h" #include "vm/compiler/ffi/recognized_method.h" #include "vm/compiler/frontend/kernel_binary_flowgraph.h" #include "vm/compiler/frontend/kernel_translation_helper.h" #include "vm/compiler/frontend/prologue_builder.h" #include "vm/compiler/jit/compiler.h" #include "vm/compiler/runtime_api.h" #include "vm/kernel_isolate.h" #include "vm/kernel_loader.h" #include "vm/log.h" #include "vm/longjump.h" #include "vm/native_entry.h" #include "vm/object_store.h" #include "vm/report.h" #include "vm/resolver.h" #include "vm/scopes.h" #include "vm/stack_frame.h" #include "vm/symbols.h" namespace dart { namespace kernel { #define Z (zone_) #define H (translation_helper_) #define T (type_translator_) #define I Isolate::Current() #define IG IsolateGroup::Current() FlowGraphBuilder::FlowGraphBuilder( ParsedFunction* parsed_function, ZoneGrowableArray<const ICData*>* ic_data_array, ZoneGrowableArray<intptr_t>* context_level_array, InlineExitCollector* exit_collector, bool optimizing, intptr_t osr_id, intptr_t first_block_id, bool inlining_unchecked_entry) : BaseFlowGraphBuilder(parsed_function, first_block_id - 1, osr_id, context_level_array, exit_collector, inlining_unchecked_entry), translation_helper_(Thread::Current()), thread_(translation_helper_.thread()), zone_(translation_helper_.zone()), parsed_function_(parsed_function), optimizing_(optimizing), ic_data_array_(*ic_data_array), next_function_id_(0), loop_depth_(0), try_depth_(0), catch_depth_(0), for_in_depth_(0), block_expression_depth_(0), graph_entry_(NULL), scopes_(NULL), breakable_block_(NULL), switch_block_(NULL), try_catch_block_(NULL), try_finally_block_(NULL), catch_block_(NULL), prepend_type_arguments_(Function::ZoneHandle(zone_)), throw_new_null_assertion_(Function::ZoneHandle(zone_)) { const Script& script = Script::Handle(Z, parsed_function->function().script()); H.InitFromScript(script); } FlowGraphBuilder::~FlowGraphBuilder() {} Fragment FlowGraphBuilder::EnterScope( intptr_t kernel_offset, const LocalScope** context_scope /* = nullptr */) { Fragment instructions; const LocalScope* scope = scopes_->scopes.Lookup(kernel_offset); if (scope->num_context_variables() > 0) { instructions += PushContext(scope); instructions += Drop(); } if (context_scope != nullptr) { *context_scope = scope; } return instructions; } Fragment FlowGraphBuilder::ExitScope(intptr_t kernel_offset) { Fragment instructions; const intptr_t context_size = scopes_->scopes.Lookup(kernel_offset)->num_context_variables(); if (context_size > 0) { instructions += PopContext(); } return instructions; } Fragment FlowGraphBuilder::AdjustContextTo(int depth) { ASSERT(depth <= context_depth_ && depth >= 0); Fragment instructions; if (depth < context_depth_) { instructions += LoadContextAt(depth); instructions += StoreLocal(TokenPosition::kNoSource, parsed_function_->current_context_var()); instructions += Drop(); context_depth_ = depth; } return instructions; } Fragment FlowGraphBuilder::PushContext(const LocalScope* scope) { ASSERT(scope->num_context_variables() > 0); Fragment instructions = AllocateContext(scope->context_slots()); LocalVariable* context = MakeTemporary(); instructions += LoadLocal(context); instructions += LoadLocal(parsed_function_->current_context_var()); instructions += StoreNativeField( Slot::Context_parent(), StoreInstanceFieldInstr::Kind::kInitializing); instructions += StoreLocal(TokenPosition::kNoSource, parsed_function_->current_context_var()); ++context_depth_; return instructions; } Fragment FlowGraphBuilder::PopContext() { return AdjustContextTo(context_depth_ - 1); } Fragment FlowGraphBuilder::LoadInstantiatorTypeArguments() { // TODO(27590): We could use `active_class_->IsGeneric()`. Fragment instructions; if (scopes_ != nullptr && scopes_->type_arguments_variable != nullptr) { #ifdef DEBUG Function& function = Function::Handle(Z, parsed_function_->function().ptr()); while (function.IsClosureFunction()) { function = function.parent_function(); } ASSERT(function.IsFactory()); #endif instructions += LoadLocal(scopes_->type_arguments_variable); } else if (parsed_function_->has_receiver_var() && active_class_.ClassNumTypeArguments() > 0) { ASSERT(!parsed_function_->function().IsFactory()); instructions += LoadLocal(parsed_function_->receiver_var()); instructions += LoadNativeField( Slot::GetTypeArgumentsSlotFor(thread_, *active_class_.klass)); } else { instructions += NullConstant(); } return instructions; } // This function is responsible for pushing a type arguments vector which // contains all type arguments of enclosing functions prepended to the type // arguments of the current function. Fragment FlowGraphBuilder::LoadFunctionTypeArguments() { Fragment instructions; const Function& function = parsed_function_->function(); if (function.IsGeneric() || function.HasGenericParent()) { ASSERT(parsed_function_->function_type_arguments() != NULL); instructions += LoadLocal(parsed_function_->function_type_arguments()); } else { instructions += NullConstant(); } return instructions; } Fragment FlowGraphBuilder::TranslateInstantiatedTypeArguments( const TypeArguments& type_arguments) { Fragment instructions; if (type_arguments.IsNull() || type_arguments.IsInstantiated()) { // There are no type references to type parameters so we can just take it. instructions += Constant(type_arguments); } else { // The [type_arguments] vector contains a type reference to a type // parameter we need to resolve it. if (type_arguments.CanShareInstantiatorTypeArguments( *active_class_.klass)) { // If the instantiator type arguments are just passed on, we don't need to // resolve the type parameters. // // This is for example the case here: // class Foo<T> { // newList() => new List<T>(); // } // We just use the type argument vector from the [Foo] object and pass it // directly to the `new List<T>()` factory constructor. instructions += LoadInstantiatorTypeArguments(); } else if (type_arguments.CanShareFunctionTypeArguments( parsed_function_->function())) { instructions += LoadFunctionTypeArguments(); } else { // Otherwise we need to resolve [TypeParameterType]s in the type // expression based on the current instantiator type argument vector. if (!type_arguments.IsInstantiated(kCurrentClass)) { instructions += LoadInstantiatorTypeArguments(); } else { instructions += NullConstant(); } if (!type_arguments.IsInstantiated(kFunctions)) { instructions += LoadFunctionTypeArguments(); } else { instructions += NullConstant(); } instructions += InstantiateTypeArguments(type_arguments); } } return instructions; } Fragment FlowGraphBuilder::CatchBlockEntry(const Array& handler_types, intptr_t handler_index, bool needs_stacktrace, bool is_synthesized) { LocalVariable* exception_var = CurrentException(); LocalVariable* stacktrace_var = CurrentStackTrace(); LocalVariable* raw_exception_var = CurrentRawException(); LocalVariable* raw_stacktrace_var = CurrentRawStackTrace(); CatchBlockEntryInstr* entry = new (Z) CatchBlockEntryInstr( is_synthesized, // whether catch block was synthesized by FE compiler AllocateBlockId(), CurrentTryIndex(), graph_entry_, handler_types, handler_index, needs_stacktrace, GetNextDeoptId(), exception_var, stacktrace_var, raw_exception_var, raw_stacktrace_var); graph_entry_->AddCatchEntry(entry); Fragment instructions(entry); // Auxiliary variables introduced by the try catch can be captured if we are // inside a function with yield/resume points. In this case we first need // to restore the context to match the context at entry into the closure. const bool should_restore_closure_context = CurrentException()->is_captured() || CurrentCatchContext()->is_captured(); LocalVariable* context_variable = parsed_function_->current_context_var(); if (should_restore_closure_context) { ASSERT(parsed_function_->function().IsClosureFunction()); LocalVariable* closure_parameter = parsed_function_->ParameterVariable(0); ASSERT(!closure_parameter->is_captured()); instructions += LoadLocal(closure_parameter); instructions += LoadNativeField(Slot::Closure_context()); instructions += StoreLocal(TokenPosition::kNoSource, context_variable); instructions += Drop(); } if (exception_var->is_captured()) { instructions += LoadLocal(context_variable); instructions += LoadLocal(raw_exception_var); instructions += StoreNativeField( Slot::GetContextVariableSlotFor(thread_, *exception_var)); } if (stacktrace_var->is_captured()) { instructions += LoadLocal(context_variable); instructions += LoadLocal(raw_stacktrace_var); instructions += StoreNativeField( Slot::GetContextVariableSlotFor(thread_, *stacktrace_var)); } // :saved_try_context_var can be captured in the context of // of the closure, in this case CatchBlockEntryInstr restores // :current_context_var to point to closure context in the // same way as normal function prologue does. // Update current context depth to reflect that. const intptr_t saved_context_depth = context_depth_; ASSERT(!CurrentCatchContext()->is_captured() || CurrentCatchContext()->owner()->context_level() == 0); context_depth_ = 0; instructions += LoadLocal(CurrentCatchContext()); instructions += StoreLocal(TokenPosition::kNoSource, parsed_function_->current_context_var()); instructions += Drop(); context_depth_ = saved_context_depth; return instructions; } Fragment FlowGraphBuilder::TryCatch(int try_handler_index) { // The body of the try needs to have it's own block in order to get a new try // index. // // => We therefore create a block for the body (fresh try index) and another // join block (with current try index). Fragment body; JoinEntryInstr* entry = new (Z) JoinEntryInstr(AllocateBlockId(), try_handler_index, GetNextDeoptId()); body += LoadLocal(parsed_function_->current_context_var()); body += StoreLocal(TokenPosition::kNoSource, CurrentCatchContext()); body += Drop(); body += Goto(entry); return Fragment(body.entry, entry); } Fragment FlowGraphBuilder::CheckStackOverflowInPrologue( TokenPosition position) { ASSERT(loop_depth_ == 0); return BaseFlowGraphBuilder::CheckStackOverflowInPrologue(position); } Fragment FlowGraphBuilder::CloneContext( const ZoneGrowableArray<const Slot*>& context_slots) { LocalVariable* context_variable = parsed_function_->current_context_var(); Fragment instructions = LoadLocal(context_variable); CloneContextInstr* clone_instruction = new (Z) CloneContextInstr( InstructionSource(), Pop(), context_slots, GetNextDeoptId()); instructions <<= clone_instruction; Push(clone_instruction); instructions += StoreLocal(TokenPosition::kNoSource, context_variable); instructions += Drop(); return instructions; } Fragment FlowGraphBuilder::InstanceCall( TokenPosition position, const String& name, Token::Kind kind, intptr_t type_args_len, intptr_t argument_count, const Array& argument_names, intptr_t checked_argument_count, const Function& interface_target, const Function& tearoff_interface_target, const InferredTypeMetadata* result_type, bool use_unchecked_entry, const CallSiteAttributesMetadata* call_site_attrs, bool receiver_is_not_smi) { const intptr_t total_count = argument_count + (type_args_len > 0 ? 1 : 0); InputsArray* arguments = GetArguments(total_count); InstanceCallInstr* call = new (Z) InstanceCallInstr( InstructionSource(position), name, kind, arguments, type_args_len, argument_names, checked_argument_count, ic_data_array_, GetNextDeoptId(), interface_target, tearoff_interface_target); if ((result_type != NULL) && !result_type->IsTrivial()) { call->SetResultType(Z, result_type->ToCompileType(Z)); } if (use_unchecked_entry) { call->set_entry_kind(Code::EntryKind::kUnchecked); } if (call_site_attrs != nullptr && call_site_attrs->receiver_type != nullptr && call_site_attrs->receiver_type->IsInstantiated()) { call->set_receivers_static_type(call_site_attrs->receiver_type); } else if (!interface_target.IsNull()) { const Class& owner = Class::Handle(Z, interface_target.Owner()); const AbstractType& type = AbstractType::ZoneHandle(Z, owner.DeclarationType()); call->set_receivers_static_type(&type); } call->set_receiver_is_not_smi(receiver_is_not_smi); Push(call); if (result_type != nullptr && result_type->IsConstant()) { Fragment instructions(call); instructions += Drop(); instructions += Constant(result_type->constant_value); return instructions; } return Fragment(call); } Fragment FlowGraphBuilder::FfiCall( const compiler::ffi::CallMarshaller& marshaller) { Fragment body; FfiCallInstr* const call = new (Z) FfiCallInstr(Z, GetNextDeoptId(), marshaller, parsed_function_->function().FfiIsLeaf()); for (intptr_t i = call->InputCount() - 1; i >= 0; --i) { call->SetInputAt(i, Pop()); } Push(call); body <<= call; return body; } Fragment FlowGraphBuilder::ThrowException(TokenPosition position) { Fragment instructions; Value* exception = Pop(); instructions += Fragment(new (Z) ThrowInstr(InstructionSource(position), GetNextDeoptId(), exception)) .closed(); // Use its side effect of leaving a constant on the stack (does not change // the graph). NullConstant(); return instructions; } Fragment FlowGraphBuilder::RethrowException(TokenPosition position, int catch_try_index) { Fragment instructions; Value* stacktrace = Pop(); Value* exception = Pop(); instructions += Fragment(new (Z) ReThrowInstr( InstructionSource(position), catch_try_index, GetNextDeoptId(), exception, stacktrace)) .closed(); // Use its side effect of leaving a constant on the stack (does not change // the graph). NullConstant(); return instructions; } Fragment FlowGraphBuilder::LoadLocal(LocalVariable* variable) { // Captured 'this' is immutable, so within the outer method we don't need to // load it from the context. const ParsedFunction* pf = parsed_function_; if (pf->function().HasThisParameter() && pf->has_receiver_var() && variable == pf->receiver_var()) { ASSERT(variable == pf->ParameterVariable(0)); variable = pf->RawParameterVariable(0); } if (variable->is_captured()) { Fragment instructions; instructions += LoadContextAt(variable->owner()->context_level()); instructions += LoadNativeField(Slot::GetContextVariableSlotFor(thread_, *variable)); return instructions; } else { return BaseFlowGraphBuilder::LoadLocal(variable); } } Fragment FlowGraphBuilder::ThrowLateInitializationError( TokenPosition position, const char* throw_method_name, const String& name) { const Class& klass = Class::ZoneHandle(Z, Library::LookupCoreClass(Symbols::LateError())); ASSERT(!klass.IsNull()); const auto& error = klass.EnsureIsFinalized(thread_); ASSERT(error == Error::null()); const Function& throw_new = Function::ZoneHandle(Z, klass.LookupStaticFunctionAllowPrivate( H.DartSymbolObfuscate(throw_method_name))); ASSERT(!throw_new.IsNull()); Fragment instructions; // Call LateError._throwFoo. instructions += Constant(name); instructions += StaticCall(position, throw_new, /* argument_count = */ 1, ICData::kStatic); instructions += Drop(); return instructions; } Fragment FlowGraphBuilder::StoreLateField(const Field& field, LocalVariable* instance, LocalVariable* setter_value) { Fragment instructions; TargetEntryInstr* is_uninitialized; TargetEntryInstr* is_initialized; const TokenPosition position = field.token_pos(); const bool is_static = field.is_static(); const bool is_final = field.is_final(); if (is_final) { // Check whether the field has been initialized already. if (is_static) { instructions += LoadStaticField(field, /*calls_initializer=*/false); } else { instructions += LoadLocal(instance); instructions += LoadField(field, /*calls_initializer=*/false); } instructions += Constant(Object::sentinel()); instructions += BranchIfStrictEqual(&is_uninitialized, &is_initialized); JoinEntryInstr* join = BuildJoinEntry(); { // If the field isn't initialized, do nothing. Fragment initialize(is_uninitialized); initialize += Goto(join); } { // If the field is already initialized, throw a LateInitializationError. Fragment already_initialized(is_initialized); already_initialized += ThrowLateInitializationError( position, "_throwFieldAlreadyInitialized", String::ZoneHandle(Z, field.name())); already_initialized += Goto(join); } instructions = Fragment(instructions.entry, join); } if (!is_static) { instructions += LoadLocal(instance); } instructions += LoadLocal(setter_value); if (is_static) { instructions += StoreStaticField(position, field); } else { instructions += StoreInstanceFieldGuarded(field); } return instructions; } Fragment FlowGraphBuilder::NativeCall(const String* name, const Function* function) { InlineBailout("kernel::FlowGraphBuilder::NativeCall"); const intptr_t num_args = function->NumParameters() + (function->IsGeneric() ? 1 : 0); InputsArray* arguments = GetArguments(num_args); NativeCallInstr* call = new (Z) NativeCallInstr(name, function, FLAG_link_natives_lazily, InstructionSource(function->end_token_pos()), arguments); Push(call); return Fragment(call); } Fragment FlowGraphBuilder::Return(TokenPosition position, bool omit_result_type_check, intptr_t yield_index) { Fragment instructions; const Function& function = parsed_function_->function(); // Emit a type check of the return type in checked mode for all functions // and in strong mode for native functions. if (!omit_result_type_check && function.is_native()) { const AbstractType& return_type = AbstractType::Handle(Z, function.result_type()); instructions += CheckAssignable(return_type, Symbols::FunctionResult()); } if (NeedsDebugStepCheck(function, position)) { instructions += DebugStepCheck(position); } instructions += BaseFlowGraphBuilder::Return(position, yield_index); return instructions; } Fragment FlowGraphBuilder::StaticCall(TokenPosition position, const Function& target, intptr_t argument_count, ICData::RebindRule rebind_rule) { return StaticCall(position, target, argument_count, Array::null_array(), rebind_rule); } void FlowGraphBuilder::SetResultTypeForStaticCall( StaticCallInstr* call, const Function& target, intptr_t argument_count, const InferredTypeMetadata* result_type) { if (call->InitResultType(Z)) { ASSERT((result_type == NULL) || (result_type->cid == kDynamicCid) || (result_type->cid == call->result_cid())); return; } if ((result_type != NULL) && !result_type->IsTrivial()) { call->SetResultType(Z, result_type->ToCompileType(Z)); } } Fragment FlowGraphBuilder::StaticCall(TokenPosition position, const Function& target, intptr_t argument_count, const Array& argument_names, ICData::RebindRule rebind_rule, const InferredTypeMetadata* result_type, intptr_t type_args_count, bool use_unchecked_entry) { const intptr_t total_count = argument_count + (type_args_count > 0 ? 1 : 0); InputsArray* arguments = GetArguments(total_count); StaticCallInstr* call = new (Z) StaticCallInstr( InstructionSource(position), target, type_args_count, argument_names, arguments, ic_data_array_, GetNextDeoptId(), rebind_rule); SetResultTypeForStaticCall(call, target, argument_count, result_type); if (use_unchecked_entry) { call->set_entry_kind(Code::EntryKind::kUnchecked); } Push(call); if (result_type != nullptr && result_type->IsConstant()) { Fragment instructions(call); instructions += Drop(); instructions += Constant(result_type->constant_value); return instructions; } return Fragment(call); } Fragment FlowGraphBuilder::StringInterpolateSingle(TokenPosition position) { const int kTypeArgsLen = 0; const int kNumberOfArguments = 1; const Array& kNoArgumentNames = Object::null_array(); const Class& cls = Class::Handle(Library::LookupCoreClass(Symbols::StringBase())); ASSERT(!cls.IsNull()); const Function& function = Function::ZoneHandle( Z, Resolver::ResolveStatic( cls, Library::PrivateCoreLibName(Symbols::InterpolateSingle()), kTypeArgsLen, kNumberOfArguments, kNoArgumentNames)); Fragment instructions; instructions += StaticCall(position, function, /* argument_count = */ 1, ICData::kStatic); return instructions; } Fragment FlowGraphBuilder::ThrowTypeError() { const Class& klass = Class::ZoneHandle(Z, Library::LookupCoreClass(Symbols::TypeError())); ASSERT(!klass.IsNull()); GrowableHandlePtrArray<const String> pieces(Z, 3); pieces.Add(Symbols::TypeError()); pieces.Add(Symbols::Dot()); pieces.Add(H.DartSymbolObfuscate("_create")); const Function& constructor = Function::ZoneHandle( Z, klass.LookupConstructorAllowPrivate( String::ZoneHandle(Z, Symbols::FromConcatAll(thread_, pieces)))); ASSERT(!constructor.IsNull()); const String& url = H.DartString( parsed_function_->function().ToLibNamePrefixedQualifiedCString(), Heap::kOld); Fragment instructions; // Create instance of _FallThroughError instructions += AllocateObject(TokenPosition::kNoSource, klass, 0); LocalVariable* instance = MakeTemporary(); // Call _TypeError._create constructor. instructions += LoadLocal(instance); // this instructions += Constant(url); // url instructions += NullConstant(); // line instructions += IntConstant(0); // column instructions += Constant(H.DartSymbolPlain("Malformed type.")); // message instructions += StaticCall(TokenPosition::kNoSource, constructor, /* argument_count = */ 5, ICData::kStatic); instructions += Drop(); // Throw the exception instructions += ThrowException(TokenPosition::kNoSource); return instructions; } Fragment FlowGraphBuilder::ThrowNoSuchMethodError(const Function& target) { const Class& klass = Class::ZoneHandle( Z, Library::LookupCoreClass(Symbols::NoSuchMethodError())); ASSERT(!klass.IsNull()); const auto& error = klass.EnsureIsFinalized(H.thread()); ASSERT(error == Error::null()); const Function& throw_function = Function::ZoneHandle( Z, klass.LookupStaticFunctionAllowPrivate(Symbols::ThrowNew())); ASSERT(!throw_function.IsNull()); Fragment instructions; const Class& owner = Class::Handle(Z, target.Owner()); AbstractType& receiver = AbstractType::ZoneHandle(); InvocationMirror::Kind kind = InvocationMirror::Kind::kMethod; if (target.IsImplicitGetterFunction() || target.IsGetterFunction()) { kind = InvocationMirror::kGetter; } else if (target.IsImplicitSetterFunction() || target.IsSetterFunction()) { kind = InvocationMirror::kSetter; } InvocationMirror::Level level; if (owner.IsTopLevel()) { level = InvocationMirror::Level::kTopLevel; } else { receiver = owner.RareType(); if (target.kind() == UntaggedFunction::kConstructor) { level = InvocationMirror::Level::kConstructor; } else { level = InvocationMirror::Level::kStatic; } } // Call NoSuchMethodError._throwNew static function. instructions += Constant(receiver); // receiver instructions += Constant(String::ZoneHandle(Z, target.name())); // memberName instructions += IntConstant(InvocationMirror::EncodeType(level, kind)); instructions += IntConstant(0); // type arguments length instructions += NullConstant(); // type arguments instructions += NullConstant(); // arguments instructions += NullConstant(); // argumentNames instructions += StaticCall(TokenPosition::kNoSource, throw_function, /* argument_count = */ 7, ICData::kStatic); // Properly close graph with a ThrowInstr, although it is not executed. instructions += ThrowException(TokenPosition::kNoSource); instructions += Drop(); return instructions; } LocalVariable* FlowGraphBuilder::LookupVariable(intptr_t kernel_offset) { LocalVariable* local = scopes_->locals.Lookup(kernel_offset); ASSERT(local != NULL); return local; } FlowGraph* FlowGraphBuilder::BuildGraph() { const Function& function = parsed_function_->function(); #ifdef DEBUG // If we attached the native name to the function after it's creation (namely // after reading the constant table from the kernel blob), we must have done // so before building flow graph for the functions (since FGB depends needs // the native name to be there). const Script& script = Script::Handle(Z, function.script()); const KernelProgramInfo& info = KernelProgramInfo::Handle(script.kernel_program_info()); ASSERT(info.IsNull() || info.potential_natives() == GrowableObjectArray::null()); // Check that all functions that are explicitly marked as recognized with the // vm:recognized annotation are in fact recognized. The check can't be done on // function creation, since the recognized status isn't set until later. if ((function.IsRecognized() != MethodRecognizer::IsMarkedAsRecognized(function)) && !function.IsDynamicInvocationForwarder()) { if (function.IsRecognized()) { FATAL1( "Recognized method %s is not marked with the vm:recognized pragma.", function.ToQualifiedCString()); } else { FATAL1( "Non-recognized method %s is marked with the vm:recognized pragma.", function.ToQualifiedCString()); } } #endif auto& kernel_data = ExternalTypedData::Handle(Z, function.KernelData()); intptr_t kernel_data_program_offset = function.KernelDataProgramOffset(); StreamingFlowGraphBuilder streaming_flow_graph_builder( this, kernel_data, kernel_data_program_offset); return streaming_flow_graph_builder.BuildGraph(); } Fragment FlowGraphBuilder::NativeFunctionBody(const Function& function, LocalVariable* first_parameter) { ASSERT(function.is_native()); ASSERT(!IsRecognizedMethodForFlowGraph(function)); Fragment body; String& name = String::ZoneHandle(Z, function.native_name()); if (function.IsGeneric()) { body += LoadLocal(parsed_function_->RawTypeArgumentsVariable()); } for (intptr_t i = 0; i < function.NumParameters(); ++i) { body += LoadLocal(parsed_function_->RawParameterVariable(i)); } body += NativeCall(&name, &function); // We typecheck results of native calls for type safety. body += Return(TokenPosition::kNoSource, /* omit_result_type_check = */ false); return body; } bool FlowGraphBuilder::IsRecognizedMethodForFlowGraph( const Function& function) { const MethodRecognizer::Kind kind = function.recognized_kind(); switch (kind) { case MethodRecognizer::kTypedData_ByteDataView_factory: case MethodRecognizer::kTypedData_Int8ArrayView_factory: case MethodRecognizer::kTypedData_Uint8ArrayView_factory: case MethodRecognizer::kTypedData_Uint8ClampedArrayView_factory: case MethodRecognizer::kTypedData_Int16ArrayView_factory: case MethodRecognizer::kTypedData_Uint16ArrayView_factory: case MethodRecognizer::kTypedData_Int32ArrayView_factory: case MethodRecognizer::kTypedData_Uint32ArrayView_factory: case MethodRecognizer::kTypedData_Int64ArrayView_factory: case MethodRecognizer::kTypedData_Uint64ArrayView_factory: case MethodRecognizer::kTypedData_Float32ArrayView_factory: case MethodRecognizer::kTypedData_Float64ArrayView_factory: case MethodRecognizer::kTypedData_Float32x4ArrayView_factory: case MethodRecognizer::kTypedData_Int32x4ArrayView_factory: case MethodRecognizer::kTypedData_Float64x2ArrayView_factory: case MethodRecognizer::kTypedData_Int8Array_factory: case MethodRecognizer::kTypedData_Uint8Array_factory: case MethodRecognizer::kTypedData_Uint8ClampedArray_factory: case MethodRecognizer::kTypedData_Int16Array_factory: case MethodRecognizer::kTypedData_Uint16Array_factory: case MethodRecognizer::kTypedData_Int32Array_factory: case MethodRecognizer::kTypedData_Uint32Array_factory: case MethodRecognizer::kTypedData_Int64Array_factory: case MethodRecognizer::kTypedData_Uint64Array_factory: case MethodRecognizer::kTypedData_Float32Array_factory: case MethodRecognizer::kTypedData_Float64Array_factory: case MethodRecognizer::kTypedData_Float32x4Array_factory: case MethodRecognizer::kTypedData_Int32x4Array_factory: case MethodRecognizer::kTypedData_Float64x2Array_factory: case MethodRecognizer::kFfiLoadInt8: case MethodRecognizer::kFfiLoadInt16: case MethodRecognizer::kFfiLoadInt32: case MethodRecognizer::kFfiLoadInt64: case MethodRecognizer::kFfiLoadUint8: case MethodRecognizer::kFfiLoadUint16: case MethodRecognizer::kFfiLoadUint32: case MethodRecognizer::kFfiLoadUint64: case MethodRecognizer::kFfiLoadIntPtr: case MethodRecognizer::kFfiLoadFloat: case MethodRecognizer::kFfiLoadFloatUnaligned: case MethodRecognizer::kFfiLoadDouble: case MethodRecognizer::kFfiLoadDoubleUnaligned: case MethodRecognizer::kFfiLoadPointer: case MethodRecognizer::kFfiStoreInt8: case MethodRecognizer::kFfiStoreInt16: case MethodRecognizer::kFfiStoreInt32: case MethodRecognizer::kFfiStoreInt64: case MethodRecognizer::kFfiStoreUint8: case MethodRecognizer::kFfiStoreUint16: case MethodRecognizer::kFfiStoreUint32: case MethodRecognizer::kFfiStoreUint64: case MethodRecognizer::kFfiStoreIntPtr: case MethodRecognizer::kFfiStoreFloat: case MethodRecognizer::kFfiStoreFloatUnaligned: case MethodRecognizer::kFfiStoreDouble: case MethodRecognizer::kFfiStoreDoubleUnaligned: case MethodRecognizer::kFfiStorePointer: case MethodRecognizer::kFfiFromAddress: case MethodRecognizer::kFfiGetAddress: case MethodRecognizer::kObjectEquals: case MethodRecognizer::kStringBaseLength: case MethodRecognizer::kStringBaseIsEmpty: case MethodRecognizer::kGrowableArrayLength: case MethodRecognizer::kObjectArrayLength: case MethodRecognizer::kImmutableArrayLength: case MethodRecognizer::kTypedListLength: case MethodRecognizer::kTypedListViewLength: case MethodRecognizer::kByteDataViewLength: case MethodRecognizer::kByteDataViewOffsetInBytes: case MethodRecognizer::kTypedDataViewOffsetInBytes: case MethodRecognizer::kByteDataViewTypedData: case MethodRecognizer::kTypedDataViewTypedData: case MethodRecognizer::kClassIDgetID: case MethodRecognizer::kGrowableArrayCapacity: case MethodRecognizer::kListFactory: case MethodRecognizer::kObjectArrayAllocate: case MethodRecognizer::kCopyRangeFromUint8ListToOneByteString: case MethodRecognizer::kLinkedHashMap_getIndex: case MethodRecognizer::kLinkedHashMap_setIndex: case MethodRecognizer::kLinkedHashMap_getData: case MethodRecognizer::kLinkedHashMap_setData: case MethodRecognizer::kLinkedHashMap_getHashMask: case MethodRecognizer::kLinkedHashMap_setHashMask: case MethodRecognizer::kLinkedHashMap_getUsedData: case MethodRecognizer::kLinkedHashMap_setUsedData: case MethodRecognizer::kLinkedHashMap_getDeletedKeys: case MethodRecognizer::kLinkedHashMap_setDeletedKeys: case MethodRecognizer::kWeakProperty_getKey: case MethodRecognizer::kWeakProperty_setKey: case MethodRecognizer::kWeakProperty_getValue: case MethodRecognizer::kWeakProperty_setValue: case MethodRecognizer::kFfiAbi: case MethodRecognizer::kReachabilityFence: case MethodRecognizer::kUtf8DecoderScan: case MethodRecognizer::kHas63BitSmis: return true; default: return false; } } FlowGraph* FlowGraphBuilder::BuildGraphOfRecognizedMethod( const Function& function) { ASSERT(IsRecognizedMethodForFlowGraph(function)); graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); PrologueInfo prologue_info(-1, -1); BlockEntryInstr* instruction_cursor = BuildPrologue(normal_entry, &prologue_info); Fragment body(instruction_cursor); body += CheckStackOverflowInPrologue(function.token_pos()); const MethodRecognizer::Kind kind = function.recognized_kind(); switch (kind) { case MethodRecognizer::kTypedData_ByteDataView_factory: body += BuildTypedDataViewFactoryConstructor(function, kByteDataViewCid); break; case MethodRecognizer::kTypedData_Int8ArrayView_factory: body += BuildTypedDataViewFactoryConstructor(function, kTypedDataInt8ArrayViewCid); break; case MethodRecognizer::kTypedData_Uint8ArrayView_factory: body += BuildTypedDataViewFactoryConstructor(function, kTypedDataUint8ArrayViewCid); break; case MethodRecognizer::kTypedData_Uint8ClampedArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataUint8ClampedArrayViewCid); break; case MethodRecognizer::kTypedData_Int16ArrayView_factory: body += BuildTypedDataViewFactoryConstructor(function, kTypedDataInt16ArrayViewCid); break; case MethodRecognizer::kTypedData_Uint16ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataUint16ArrayViewCid); break; case MethodRecognizer::kTypedData_Int32ArrayView_factory: body += BuildTypedDataViewFactoryConstructor(function, kTypedDataInt32ArrayViewCid); break; case MethodRecognizer::kTypedData_Uint32ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataUint32ArrayViewCid); break; case MethodRecognizer::kTypedData_Int64ArrayView_factory: body += BuildTypedDataViewFactoryConstructor(function, kTypedDataInt64ArrayViewCid); break; case MethodRecognizer::kTypedData_Uint64ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataUint64ArrayViewCid); break; case MethodRecognizer::kTypedData_Float32ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataFloat32ArrayViewCid); break; case MethodRecognizer::kTypedData_Float64ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataFloat64ArrayViewCid); break; case MethodRecognizer::kTypedData_Float32x4ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataFloat32x4ArrayViewCid); break; case MethodRecognizer::kTypedData_Int32x4ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataInt32x4ArrayViewCid); break; case MethodRecognizer::kTypedData_Float64x2ArrayView_factory: body += BuildTypedDataViewFactoryConstructor( function, kTypedDataFloat64x2ArrayViewCid); break; case MethodRecognizer::kTypedData_Int8Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataInt8ArrayCid); break; case MethodRecognizer::kTypedData_Uint8Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataUint8ArrayCid); break; case MethodRecognizer::kTypedData_Uint8ClampedArray_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataUint8ClampedArrayCid); break; case MethodRecognizer::kTypedData_Int16Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataInt16ArrayCid); break; case MethodRecognizer::kTypedData_Uint16Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataUint16ArrayCid); break; case MethodRecognizer::kTypedData_Int32Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataInt32ArrayCid); break; case MethodRecognizer::kTypedData_Uint32Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataUint32ArrayCid); break; case MethodRecognizer::kTypedData_Int64Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataInt64ArrayCid); break; case MethodRecognizer::kTypedData_Uint64Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataUint64ArrayCid); break; case MethodRecognizer::kTypedData_Float32Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataFloat32ArrayCid); break; case MethodRecognizer::kTypedData_Float64Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataFloat64ArrayCid); break; case MethodRecognizer::kTypedData_Float32x4Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataFloat32x4ArrayCid); break; case MethodRecognizer::kTypedData_Int32x4Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataInt32x4ArrayCid); break; case MethodRecognizer::kTypedData_Float64x2Array_factory: body += BuildTypedDataFactoryConstructor(function, kTypedDataFloat64x2ArrayCid); break; case MethodRecognizer::kObjectEquals: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StrictCompare(Token::kEQ_STRICT); break; case MethodRecognizer::kStringBaseLength: case MethodRecognizer::kStringBaseIsEmpty: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::String_length()); if (kind == MethodRecognizer::kStringBaseIsEmpty) { body += IntConstant(0); body += StrictCompare(Token::kEQ_STRICT); } break; case MethodRecognizer::kGrowableArrayLength: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::GrowableObjectArray_length()); break; case MethodRecognizer::kObjectArrayLength: case MethodRecognizer::kImmutableArrayLength: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::Array_length()); break; case MethodRecognizer::kTypedListLength: case MethodRecognizer::kTypedListViewLength: case MethodRecognizer::kByteDataViewLength: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::TypedDataBase_length()); break; case MethodRecognizer::kByteDataViewOffsetInBytes: case MethodRecognizer::kTypedDataViewOffsetInBytes: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::TypedDataView_offset_in_bytes()); break; case MethodRecognizer::kByteDataViewTypedData: case MethodRecognizer::kTypedDataViewTypedData: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::TypedDataView_data()); break; case MethodRecognizer::kClassIDgetID: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadClassId(); break; case MethodRecognizer::kGrowableArrayCapacity: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::GrowableObjectArray_data()); body += LoadNativeField(Slot::Array_length()); break; case MethodRecognizer::kListFactory: { ASSERT(function.IsFactory() && (function.NumParameters() == 2) && function.HasOptionalParameters()); // factory List<E>([int length]) { // return (:arg_desc.positional_count == 2) ? new _List<E>(length) // : new _GrowableList<E>(0); // } const Library& core_lib = Library::Handle(Z, Library::CoreLibrary()); TargetEntryInstr* allocate_non_growable; TargetEntryInstr* allocate_growable; body += LoadArgDescriptor(); body += LoadNativeField(Slot::ArgumentsDescriptor_positional_count()); body += IntConstant(2); body += BranchIfStrictEqual(&allocate_non_growable, &allocate_growable); JoinEntryInstr* join = BuildJoinEntry(); { const Class& cls = Class::Handle( Z, core_lib.LookupClass( Library::PrivateCoreLibName(Symbols::_List()))); ASSERT(!cls.IsNull()); const Function& func = Function::ZoneHandle( Z, cls.LookupFactoryAllowPrivate(Symbols::_ListFactory())); ASSERT(!func.IsNull()); Fragment allocate(allocate_non_growable); allocate += LoadLocal(parsed_function_->RawParameterVariable(0)); allocate += LoadLocal(parsed_function_->RawParameterVariable(1)); allocate += StaticCall(TokenPosition::kNoSource, func, 2, ICData::kStatic); allocate += StoreLocal(TokenPosition::kNoSource, parsed_function_->expression_temp_var()); allocate += Drop(); allocate += Goto(join); } { const Class& cls = Class::Handle( Z, core_lib.LookupClass( Library::PrivateCoreLibName(Symbols::_GrowableList()))); ASSERT(!cls.IsNull()); const Function& func = Function::ZoneHandle( Z, cls.LookupFactoryAllowPrivate(Symbols::_GrowableListFactory())); ASSERT(!func.IsNull()); Fragment allocate(allocate_growable); allocate += LoadLocal(parsed_function_->RawParameterVariable(0)); allocate += IntConstant(0); allocate += StaticCall(TokenPosition::kNoSource, func, 2, ICData::kStatic); allocate += StoreLocal(TokenPosition::kNoSource, parsed_function_->expression_temp_var()); allocate += Drop(); allocate += Goto(join); } body = Fragment(body.entry, join); body += LoadLocal(parsed_function_->expression_temp_var()); break; } case MethodRecognizer::kObjectArrayAllocate: ASSERT(function.IsFactory() && (function.NumParameters() == 2)); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += CreateArray(); break; case MethodRecognizer::kCopyRangeFromUint8ListToOneByteString: ASSERT(function.NumParameters() == 5); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += LoadLocal(parsed_function_->RawParameterVariable(2)); body += LoadLocal(parsed_function_->RawParameterVariable(3)); body += LoadLocal(parsed_function_->RawParameterVariable(4)); body += MemoryCopy(kTypedDataUint8ArrayCid, kOneByteStringCid); body += NullConstant(); break; case MethodRecognizer::kLinkedHashMap_getIndex: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::LinkedHashMap_index()); break; case MethodRecognizer::kLinkedHashMap_setIndex: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StoreNativeField(Slot::LinkedHashMap_index()); body += NullConstant(); break; case MethodRecognizer::kLinkedHashMap_getData: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::LinkedHashMap_data()); break; case MethodRecognizer::kLinkedHashMap_setData: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StoreNativeField(Slot::LinkedHashMap_data()); body += NullConstant(); break; case MethodRecognizer::kLinkedHashMap_getHashMask: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::LinkedHashMap_hash_mask()); break; case MethodRecognizer::kLinkedHashMap_setHashMask: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StoreNativeField(Slot::LinkedHashMap_hash_mask(), StoreInstanceFieldInstr::Kind::kOther, kNoStoreBarrier); body += NullConstant(); break; case MethodRecognizer::kLinkedHashMap_getUsedData: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::LinkedHashMap_used_data()); break; case MethodRecognizer::kLinkedHashMap_setUsedData: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StoreNativeField(Slot::LinkedHashMap_used_data(), StoreInstanceFieldInstr::Kind::kOther, kNoStoreBarrier); body += NullConstant(); break; case MethodRecognizer::kLinkedHashMap_getDeletedKeys: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::LinkedHashMap_deleted_keys()); break; case MethodRecognizer::kLinkedHashMap_setDeletedKeys: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StoreNativeField(Slot::LinkedHashMap_deleted_keys(), StoreInstanceFieldInstr::Kind::kOther, kNoStoreBarrier); body += NullConstant(); break; case MethodRecognizer::kWeakProperty_getKey: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::WeakProperty_key()); break; case MethodRecognizer::kWeakProperty_setKey: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StoreNativeField(Slot::WeakProperty_key()); body += NullConstant(); break; case MethodRecognizer::kWeakProperty_getValue: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField(Slot::WeakProperty_value()); break; case MethodRecognizer::kWeakProperty_setValue: ASSERT(function.NumParameters() == 2); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadLocal(parsed_function_->RawParameterVariable(1)); body += StoreNativeField(Slot::WeakProperty_value()); body += NullConstant(); break; case MethodRecognizer::kUtf8DecoderScan: ASSERT(function.NumParameters() == 5); body += LoadLocal(parsed_function_->RawParameterVariable(0)); // decoder body += LoadLocal(parsed_function_->RawParameterVariable(1)); // bytes body += LoadLocal(parsed_function_->RawParameterVariable(2)); // start body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); body += UnboxTruncate(kUnboxedIntPtr); body += LoadLocal(parsed_function_->RawParameterVariable(3)); // end body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); body += UnboxTruncate(kUnboxedIntPtr); body += LoadLocal(parsed_function_->RawParameterVariable(4)); // table body += Utf8Scan(); body += Box(kUnboxedIntPtr); break; case MethodRecognizer::kReachabilityFence: ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += ReachabilityFence(); body += NullConstant(); break; case MethodRecognizer::kFfiAbi: ASSERT(function.NumParameters() == 0); body += IntConstant(static_cast<int64_t>(compiler::ffi::TargetAbi())); break; case MethodRecognizer::kFfiLoadInt8: case MethodRecognizer::kFfiLoadInt16: case MethodRecognizer::kFfiLoadInt32: case MethodRecognizer::kFfiLoadInt64: case MethodRecognizer::kFfiLoadUint8: case MethodRecognizer::kFfiLoadUint16: case MethodRecognizer::kFfiLoadUint32: case MethodRecognizer::kFfiLoadUint64: case MethodRecognizer::kFfiLoadIntPtr: case MethodRecognizer::kFfiLoadFloat: case MethodRecognizer::kFfiLoadFloatUnaligned: case MethodRecognizer::kFfiLoadDouble: case MethodRecognizer::kFfiLoadDoubleUnaligned: case MethodRecognizer::kFfiLoadPointer: { const classid_t ffi_type_arg_cid = compiler::ffi::RecognizedMethodTypeArgCid(kind); const AlignmentType alignment = compiler::ffi::RecognizedMethodAlignment(kind); const classid_t typed_data_cid = compiler::ffi::ElementTypedDataCid(ffi_type_arg_cid); ASSERT(function.NumParameters() == 2); LocalVariable* arg_pointer = parsed_function_->RawParameterVariable(0); LocalVariable* arg_offset = parsed_function_->RawParameterVariable(1); body += LoadLocal(arg_offset); body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); LocalVariable* arg_offset_not_null = MakeTemporary(); body += LoadLocal(arg_pointer); body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); // No GC from here til LoadIndexed. body += LoadUntagged(compiler::target::PointerBase::data_field_offset()); body += LoadLocal(arg_offset_not_null); body += UnboxTruncate(kUnboxedFfiIntPtr); body += LoadIndexed(typed_data_cid, /*index_scale=*/1, /*index_unboxed=*/true, alignment); if (kind == MethodRecognizer::kFfiLoadFloat || kind == MethodRecognizer::kFfiLoadFloatUnaligned) { body += FloatToDouble(); } // Avoid any unnecessary (and potentially deoptimizing) int // conversions by using the representation returned from LoadIndexed. body += Box(LoadIndexedInstr::RepresentationOfArrayElement(typed_data_cid)); if (kind == MethodRecognizer::kFfiLoadPointer) { const auto class_table = thread_->isolate_group()->class_table(); ASSERT(class_table->HasValidClassAt(kFfiPointerCid)); const auto& pointer_class = Class::ZoneHandle(H.zone(), class_table->At(kFfiPointerCid)); // We find the reified type to use for the pointer allocation. // // Call sites to this recognized method are guaranteed to pass a // Pointer<Pointer<X>> as RawParameterVariable(0). This function // will return a Pointer<X> object - for which we inspect the // reified type on the argument. // // The following is safe to do, as (1) we are guaranteed to have a // Pointer<Pointer<X>> as argument, and (2) the bound on the pointer // type parameter guarantees X is an interface type. ASSERT(function.NumTypeParameters() == 1); LocalVariable* address = MakeTemporary(); body += LoadLocal(parsed_function_->RawParameterVariable(0)); body += LoadNativeField( Slot::GetTypeArgumentsSlotFor(thread_, pointer_class)); body += LoadNativeField(Slot::GetTypeArgumentsIndexSlot( thread_, Pointer::kNativeTypeArgPos)); body += LoadNativeField(Slot::Type_arguments()); body += AllocateObject(TokenPosition::kNoSource, pointer_class, 1); LocalVariable* pointer = MakeTemporary(); body += LoadLocal(pointer); body += LoadLocal(address); body += UnboxTruncate(kUnboxedFfiIntPtr); body += StoreNativeField(Slot::Pointer_data_field()); body += DropTempsPreserveTop(1); // Drop [address] keep [pointer]. } body += DropTempsPreserveTop(1); // Drop [arg_offset]. } break; case MethodRecognizer::kFfiStoreInt8: case MethodRecognizer::kFfiStoreInt16: case MethodRecognizer::kFfiStoreInt32: case MethodRecognizer::kFfiStoreInt64: case MethodRecognizer::kFfiStoreUint8: case MethodRecognizer::kFfiStoreUint16: case MethodRecognizer::kFfiStoreUint32: case MethodRecognizer::kFfiStoreUint64: case MethodRecognizer::kFfiStoreIntPtr: case MethodRecognizer::kFfiStoreFloat: case MethodRecognizer::kFfiStoreFloatUnaligned: case MethodRecognizer::kFfiStoreDouble: case MethodRecognizer::kFfiStoreDoubleUnaligned: case MethodRecognizer::kFfiStorePointer: { const classid_t ffi_type_arg_cid = compiler::ffi::RecognizedMethodTypeArgCid(kind); const AlignmentType alignment = compiler::ffi::RecognizedMethodAlignment(kind); const classid_t typed_data_cid = compiler::ffi::ElementTypedDataCid(ffi_type_arg_cid); LocalVariable* arg_pointer = parsed_function_->RawParameterVariable(0); LocalVariable* arg_offset = parsed_function_->RawParameterVariable(1); LocalVariable* arg_value = parsed_function_->RawParameterVariable(2); if (kind == MethodRecognizer::kFfiStorePointer) { // Do type check before anything untagged is on the stack. const auto class_table = thread_->isolate_group()->class_table(); ASSERT(class_table->HasValidClassAt(kFfiPointerCid)); const auto& pointer_class = Class::ZoneHandle(H.zone(), class_table->At(kFfiPointerCid)); const auto& pointer_type_param = TypeParameter::ZoneHandle(pointer_class.TypeParameterAt(0)); // But we type check it as a method on a generic class at runtime. body += LoadLocal(arg_value); // value. body += Constant(pointer_type_param); // dst_type. // We pass the Pointer type argument as instantiator_type_args. // // Call sites to this recognized method are guaranteed to pass a // Pointer<Pointer<X>> as RawParameterVariable(0). This function // will takes a Pointer<X> object - for which we inspect the // reified type on the argument. // // The following is safe to do, as (1) we are guaranteed to have a // Pointer<Pointer<X>> as argument, and (2) the bound on the pointer // type parameter guarantees X is an interface type. body += LoadLocal(arg_pointer); body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); body += LoadNativeField( Slot::GetTypeArgumentsSlotFor(thread_, pointer_class)); body += NullConstant(); // function_type_args. body += AssertAssignable(TokenPosition::kNoSource, Symbols::Empty()); body += Drop(); } ASSERT(function.NumParameters() == 3); body += LoadLocal(arg_offset); body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); LocalVariable* arg_offset_not_null = MakeTemporary(); body += LoadLocal(arg_value); body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); LocalVariable* arg_value_not_null = MakeTemporary(); body += LoadLocal(arg_pointer); // Pointer. body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); // No GC from here til StoreIndexed. body += LoadUntagged(compiler::target::PointerBase::data_field_offset()); body += LoadLocal(arg_offset_not_null); body += UnboxTruncate(kUnboxedFfiIntPtr); body += LoadLocal(arg_value_not_null); if (kind == MethodRecognizer::kFfiStorePointer) { // This can only be Pointer, so it is always safe to LoadUntagged. body += LoadUntagged(compiler::target::Pointer::data_field_offset()); body += ConvertUntaggedToUnboxed(kUnboxedFfiIntPtr); } else { // Avoid any unnecessary (and potentially deoptimizing) int // conversions by using the representation consumed by StoreIndexed. body += UnboxTruncate( StoreIndexedInstr::RepresentationOfArrayElement(typed_data_cid)); if (kind == MethodRecognizer::kFfiStoreFloat || kind == MethodRecognizer::kFfiStoreFloatUnaligned) { body += DoubleToFloat(); } } body += StoreIndexedTypedData(typed_data_cid, /*index_scale=*/1, /*index_unboxed=*/true, alignment); body += Drop(); // Drop [arg_value]. body += Drop(); // Drop [arg_offset]. body += NullConstant(); } break; case MethodRecognizer::kFfiFromAddress: { const auto class_table = thread_->isolate_group()->class_table(); ASSERT(class_table->HasValidClassAt(kFfiPointerCid)); const auto& pointer_class = Class::ZoneHandle(H.zone(), class_table->At(kFfiPointerCid)); ASSERT(function.NumTypeParameters() == 1); ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawTypeArgumentsVariable()); body += AllocateObject(TokenPosition::kNoSource, pointer_class, 1); body += LoadLocal(MakeTemporary()); // Duplicate Pointer. body += LoadLocal(parsed_function_->RawParameterVariable(0)); // Address. body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); body += UnboxTruncate(kUnboxedFfiIntPtr); body += StoreNativeField(Slot::Pointer_data_field()); } break; case MethodRecognizer::kFfiGetAddress: { ASSERT(function.NumParameters() == 1); body += LoadLocal(parsed_function_->RawParameterVariable(0)); // Pointer. body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, function.name())); // This can only be Pointer, so it is always safe to LoadUntagged. body += LoadUntagged(compiler::target::Pointer::data_field_offset()); body += ConvertUntaggedToUnboxed(kUnboxedFfiIntPtr); body += Box(kUnboxedFfiIntPtr); } break; case MethodRecognizer::kHas63BitSmis: { #if defined(TARGET_ARCH_IS_64_BIT) && !defined(DART_COMPRESSED_POINTERS) body += Constant(Bool::True()); #else body += Constant(Bool::False()); #endif // defined(ARCH_IS_64_BIT) } break; default: { UNREACHABLE(); break; } } body += Return(TokenPosition::kNoSource, /* omit_result_type_check = */ true); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } Fragment FlowGraphBuilder::BuildTypedDataViewFactoryConstructor( const Function& function, classid_t cid) { auto token_pos = function.token_pos(); auto class_table = Thread::Current()->isolate_group()->class_table(); ASSERT(class_table->HasValidClassAt(cid)); const auto& view_class = Class::ZoneHandle(H.zone(), class_table->At(cid)); ASSERT(function.IsFactory() && (function.NumParameters() == 4)); LocalVariable* typed_data = parsed_function_->RawParameterVariable(1); LocalVariable* offset_in_bytes = parsed_function_->RawParameterVariable(2); LocalVariable* length = parsed_function_->RawParameterVariable(3); Fragment body; body += AllocateObject(token_pos, view_class, /*arg_count=*/0); LocalVariable* view_object = MakeTemporary(); body += LoadLocal(view_object); body += LoadLocal(typed_data); body += StoreNativeField(token_pos, Slot::TypedDataView_data(), StoreInstanceFieldInstr::Kind::kInitializing); body += LoadLocal(view_object); body += LoadLocal(offset_in_bytes); body += StoreNativeField(token_pos, Slot::TypedDataView_offset_in_bytes(), StoreInstanceFieldInstr::Kind::kInitializing, kNoStoreBarrier); body += LoadLocal(view_object); body += LoadLocal(length); body += StoreNativeField(token_pos, Slot::TypedDataBase_length(), StoreInstanceFieldInstr::Kind::kInitializing, kNoStoreBarrier); // Update the inner pointer. // // WARNING: Notice that we assume here no GC happens between those 4 // instructions! body += LoadLocal(view_object); body += LoadLocal(typed_data); body += LoadUntagged(compiler::target::TypedDataBase::data_field_offset()); body += ConvertUntaggedToUnboxed(kUnboxedIntPtr); body += LoadLocal(offset_in_bytes); body += UnboxSmiToIntptr(); body += AddIntptrIntegers(); body += StoreNativeField(Slot::TypedDataBase_data_field()); return body; } Fragment FlowGraphBuilder::BuildTypedDataFactoryConstructor( const Function& function, classid_t cid) { const auto token_pos = function.token_pos(); ASSERT( Thread::Current()->isolate_group()->class_table()->HasValidClassAt(cid)); ASSERT(function.IsFactory() && (function.NumParameters() == 2)); LocalVariable* length = parsed_function_->RawParameterVariable(1); Fragment instructions; instructions += LoadLocal(length); // AllocateTypedData instruction checks that length is valid (a non-negative // Smi below maximum allowed length). instructions += AllocateTypedData(token_pos, cid); return instructions; } static const LocalScope* MakeImplicitClosureScope(Zone* Z, const Class& klass) { ASSERT(!klass.IsNull()); // Note that if klass is _Closure, DeclarationType will be _Closure, // and not the signature type. Type& klass_type = Type::ZoneHandle(Z, klass.DeclarationType()); LocalVariable* receiver_variable = new (Z) LocalVariable(TokenPosition::kNoSource, TokenPosition::kNoSource, Symbols::This(), klass_type, /*param_type=*/nullptr); receiver_variable->set_is_captured(); // receiver_variable->set_is_final(); LocalScope* scope = new (Z) LocalScope(NULL, 0, 0); scope->set_context_level(0); scope->AddVariable(receiver_variable); scope->AddContextVariable(receiver_variable); return scope; } Fragment FlowGraphBuilder::BuildImplicitClosureCreation( const Function& target) { Fragment fragment; fragment += Constant(target); fragment += AllocateClosure(); LocalVariable* closure = MakeTemporary(); // The function signature can have uninstantiated class type parameters. if (!target.HasInstantiatedSignature(kCurrentClass)) { fragment += LoadLocal(closure); fragment += LoadInstantiatorTypeArguments(); fragment += StoreNativeField(Slot::Closure_instantiator_type_arguments(), StoreInstanceFieldInstr::Kind::kInitializing); } // The function cannot be local and have parent generic functions. ASSERT(!target.HasGenericParent()); // Allocate a context that closes over `this`. // Note: this must be kept in sync with ScopeBuilder::BuildScopes. const LocalScope* implicit_closure_scope = MakeImplicitClosureScope(Z, Class::Handle(Z, target.Owner())); fragment += AllocateContext(implicit_closure_scope->context_slots()); LocalVariable* context = MakeTemporary(); // Store the context in the closure. fragment += LoadLocal(closure); fragment += LoadLocal(context); fragment += StoreNativeField(Slot::Closure_context(), StoreInstanceFieldInstr::Kind::kInitializing); if (target.IsGeneric()) { // Only generic functions need to have properly initialized // delayed_type_arguments. fragment += LoadLocal(closure); fragment += Constant(Object::empty_type_arguments()); fragment += StoreNativeField(Slot::Closure_delayed_type_arguments(), StoreInstanceFieldInstr::Kind::kInitializing); } // The context is on top of the operand stack. Store `this`. The context // doesn't need a parent pointer because it doesn't close over anything // else. fragment += LoadLocal(parsed_function_->receiver_var()); fragment += StoreNativeField( Slot::GetContextVariableSlotFor( thread_, *implicit_closure_scope->context_variables()[0]), StoreInstanceFieldInstr::Kind::kInitializing); return fragment; } Fragment FlowGraphBuilder::CheckVariableTypeInCheckedMode( const AbstractType& dst_type, const String& name_symbol) { return Fragment(); } bool FlowGraphBuilder::NeedsDebugStepCheck(const Function& function, TokenPosition position) { return position.IsDebugPause() && !function.is_native() && function.is_debuggable(); } bool FlowGraphBuilder::NeedsDebugStepCheck(Value* value, TokenPosition position) { if (!position.IsDebugPause()) { return false; } Definition* definition = value->definition(); if (definition->IsConstant() || definition->IsLoadStaticField()) { return true; } if (auto const alloc = definition->AsAllocateClosure()) { return !alloc->known_function().IsNull(); } return definition->IsLoadLocal(); } Fragment FlowGraphBuilder::EvaluateAssertion() { const Class& klass = Class::ZoneHandle(Z, Library::LookupCoreClass(Symbols::AssertionError())); ASSERT(!klass.IsNull()); const auto& error = klass.EnsureIsFinalized(H.thread()); ASSERT(error == Error::null()); const Function& target = Function::ZoneHandle( Z, klass.LookupStaticFunctionAllowPrivate(Symbols::EvaluateAssertion())); ASSERT(!target.IsNull()); return StaticCall(TokenPosition::kNoSource, target, /* argument_count = */ 1, ICData::kStatic); } Fragment FlowGraphBuilder::CheckBoolean(TokenPosition position) { Fragment instructions; LocalVariable* top_of_stack = MakeTemporary(); instructions += LoadLocal(top_of_stack); instructions += AssertBool(position); instructions += Drop(); return instructions; } Fragment FlowGraphBuilder::CheckAssignable(const AbstractType& dst_type, const String& dst_name, AssertAssignableInstr::Kind kind) { Fragment instructions; if (!dst_type.IsTopTypeForSubtyping()) { LocalVariable* top_of_stack = MakeTemporary(); instructions += LoadLocal(top_of_stack); instructions += AssertAssignableLoadTypeArguments(TokenPosition::kNoSource, dst_type, dst_name, kind); instructions += Drop(); } return instructions; } Fragment FlowGraphBuilder::AssertAssignableLoadTypeArguments( TokenPosition position, const AbstractType& dst_type, const String& dst_name, AssertAssignableInstr::Kind kind) { Fragment instructions; instructions += Constant(AbstractType::ZoneHandle(dst_type.ptr())); if (!dst_type.IsInstantiated(kCurrentClass)) { instructions += LoadInstantiatorTypeArguments(); } else { instructions += NullConstant(); } if (!dst_type.IsInstantiated(kFunctions)) { instructions += LoadFunctionTypeArguments(); } else { instructions += NullConstant(); } instructions += AssertAssignable(position, dst_name, kind); return instructions; } Fragment FlowGraphBuilder::AssertSubtype(TokenPosition position, const AbstractType& sub_type_value, const AbstractType& super_type_value, const String& dst_name_value) { Fragment instructions; instructions += LoadInstantiatorTypeArguments(); instructions += LoadFunctionTypeArguments(); instructions += Constant(AbstractType::ZoneHandle(Z, sub_type_value.ptr())); instructions += Constant(AbstractType::ZoneHandle(Z, super_type_value.ptr())); instructions += Constant(String::ZoneHandle(Z, dst_name_value.ptr())); instructions += AssertSubtype(position); return instructions; } Fragment FlowGraphBuilder::AssertSubtype(TokenPosition position) { Fragment instructions; Value* dst_name = Pop(); Value* super_type = Pop(); Value* sub_type = Pop(); Value* function_type_args = Pop(); Value* instantiator_type_args = Pop(); AssertSubtypeInstr* instr = new (Z) AssertSubtypeInstr( InstructionSource(position), instantiator_type_args, function_type_args, sub_type, super_type, dst_name, GetNextDeoptId()); instructions += Fragment(instr); return instructions; } void FlowGraphBuilder::BuildTypeArgumentTypeChecks(TypeChecksToBuild mode, Fragment* implicit_checks) { const Function& dart_function = parsed_function_->function(); const Function* forwarding_target = nullptr; if (parsed_function_->is_forwarding_stub()) { forwarding_target = parsed_function_->forwarding_stub_super_target(); ASSERT(!forwarding_target->IsNull()); } TypeParameters& type_parameters = TypeParameters::Handle(Z); if (dart_function.IsFactory()) { type_parameters = Class::Handle(Z, dart_function.Owner()).type_parameters(); } else { type_parameters = dart_function.type_parameters(); } const intptr_t num_type_params = type_parameters.Length(); if (num_type_params == 0) return; if (forwarding_target != nullptr) { type_parameters = forwarding_target->type_parameters(); ASSERT(type_parameters.Length() == num_type_params); } if (type_parameters.AllDynamicBounds()) { return; // All bounds are dynamic. } TypeParameter& type_param = TypeParameter::Handle(Z); String& name = String::Handle(Z); AbstractType& bound = AbstractType::Handle(Z); Fragment check_bounds; for (intptr_t i = 0; i < num_type_params; ++i) { bound = type_parameters.BoundAt(i); if (bound.IsTopTypeForSubtyping()) { continue; } switch (mode) { case TypeChecksToBuild::kCheckAllTypeParameterBounds: break; case TypeChecksToBuild::kCheckCovariantTypeParameterBounds: if (!type_parameters.IsGenericCovariantImplAt(i)) { continue; } break; case TypeChecksToBuild::kCheckNonCovariantTypeParameterBounds: if (type_parameters.IsGenericCovariantImplAt(i)) { continue; } break; } name = type_parameters.NameAt(i); if (forwarding_target != nullptr) { type_param = forwarding_target->TypeParameterAt(i); } else if (dart_function.IsFactory()) { type_param = Class::Handle(Z, dart_function.Owner()).TypeParameterAt(i); } else { type_param = dart_function.TypeParameterAt(i); } ASSERT(type_param.IsFinalized()); check_bounds += AssertSubtype(TokenPosition::kNoSource, type_param, bound, name); } // Type arguments passed through partial instantiation are guaranteed to be // bounds-checked at the point of partial instantiation, so we don't need to // check them again at the call-site. if (dart_function.IsClosureFunction() && !check_bounds.is_empty() && FLAG_eliminate_type_checks) { LocalVariable* closure = parsed_function_->ParameterVariable(0); *implicit_checks += TestDelayedTypeArgs(closure, /*present=*/{}, /*absent=*/check_bounds); } else { *implicit_checks += check_bounds; } } void FlowGraphBuilder::BuildArgumentTypeChecks( Fragment* explicit_checks, Fragment* implicit_checks, Fragment* implicit_redefinitions) { const Function& dart_function = parsed_function_->function(); const Function* forwarding_target = nullptr; if (parsed_function_->is_forwarding_stub()) { forwarding_target = parsed_function_->forwarding_stub_super_target(); ASSERT(!forwarding_target->IsNull()); } const intptr_t num_params = dart_function.NumParameters(); for (intptr_t i = dart_function.NumImplicitParameters(); i < num_params; ++i) { LocalVariable* param = parsed_function_->ParameterVariable(i); const String& name = param->name(); if (!param->needs_type_check()) { continue; } if (param->is_captured()) { param = parsed_function_->RawParameterVariable(i); } const AbstractType* target_type = &param->type(); if (forwarding_target != NULL) { // We add 1 to the parameter index to account for the receiver. target_type = &AbstractType::ZoneHandle(Z, forwarding_target->ParameterTypeAt(i)); } if (target_type->IsTopTypeForSubtyping()) continue; const bool is_covariant = param->is_explicit_covariant_parameter(); Fragment* checks = is_covariant ? explicit_checks : implicit_checks; *checks += LoadLocal(param); *checks += AssertAssignableLoadTypeArguments( TokenPosition::kNoSource, *target_type, name, AssertAssignableInstr::kParameterCheck); *checks += StoreLocal(param); *checks += Drop(); if (!is_covariant && implicit_redefinitions != nullptr && optimizing_) { // We generate slightly different code in optimized vs. un-optimized code, // which is ok since we don't allocate any deopt ids. AssertNoDeoptIdsAllocatedScope no_deopt_allocation(thread_); *implicit_redefinitions += LoadLocal(param); *implicit_redefinitions += RedefinitionWithType(*target_type); *implicit_redefinitions += StoreLocal(TokenPosition::kNoSource, param); *implicit_redefinitions += Drop(); } } } BlockEntryInstr* FlowGraphBuilder::BuildPrologue(BlockEntryInstr* normal_entry, PrologueInfo* prologue_info) { const bool compiling_for_osr = IsCompiledForOsr(); kernel::PrologueBuilder prologue_builder( parsed_function_, last_used_block_id_, compiling_for_osr, IsInlining()); BlockEntryInstr* instruction_cursor = prologue_builder.BuildPrologue(normal_entry, prologue_info); last_used_block_id_ = prologue_builder.last_used_block_id(); return instruction_cursor; } ArrayPtr FlowGraphBuilder::GetOptionalParameterNames(const Function& function) { if (!function.HasOptionalNamedParameters()) { return Array::null(); } const intptr_t num_fixed_params = function.num_fixed_parameters(); const intptr_t num_opt_params = function.NumOptionalNamedParameters(); const auto& names = Array::Handle(Z, Array::New(num_opt_params, Heap::kOld)); auto& name = String::Handle(Z); for (intptr_t i = 0; i < num_opt_params; ++i) { name = function.ParameterNameAt(num_fixed_params + i); names.SetAt(i, name); } return names.ptr(); } Fragment FlowGraphBuilder::PushExplicitParameters( const Function& function, const Function& target /* = Function::null_function()*/) { Fragment instructions; for (intptr_t i = function.NumImplicitParameters(), n = function.NumParameters(); i < n; ++i) { Fragment push_param = LoadLocal(parsed_function_->ParameterVariable(i)); if (!target.IsNull() && target.is_unboxed_parameter_at(i)) { Representation to; if (target.is_unboxed_integer_parameter_at(i)) { to = kUnboxedInt64; } else { ASSERT(target.is_unboxed_double_parameter_at(i)); to = kUnboxedDouble; } const auto unbox = UnboxInstr::Create(to, Pop(), DeoptId::kNone, Instruction::kNotSpeculative); Push(unbox); push_param += Fragment(unbox); } instructions += push_param; } return instructions; } FlowGraph* FlowGraphBuilder::BuildGraphOfMethodExtractor( const Function& method) { // A method extractor is the implicit getter for a method. const Function& function = Function::ZoneHandle(Z, method.extracted_method_closure()); graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); Fragment body(normal_entry); body += CheckStackOverflowInPrologue(method.token_pos()); body += BuildImplicitClosureCreation(function); body += Return(TokenPosition::kNoSource); // There is no prologue code for a method extractor. PrologueInfo prologue_info(-1, -1); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } FlowGraph* FlowGraphBuilder::BuildGraphOfNoSuchMethodDispatcher( const Function& function) { // This function is specialized for a receiver class, a method name, and // the arguments descriptor at a call site. const ArgumentsDescriptor descriptor(saved_args_desc_array()); graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); PrologueInfo prologue_info(-1, -1); BlockEntryInstr* instruction_cursor = BuildPrologue(normal_entry, &prologue_info); Fragment body(instruction_cursor); body += CheckStackOverflowInPrologue(function.token_pos()); // The receiver is the first argument to noSuchMethod, and it is the first // argument passed to the dispatcher function. body += LoadLocal(parsed_function_->ParameterVariable(0)); // The second argument to noSuchMethod is an invocation mirror. Push the // arguments for allocating the invocation mirror. First, the name. body += Constant(String::ZoneHandle(Z, function.name())); // Second, the arguments descriptor. body += Constant(saved_args_desc_array()); // Third, an array containing the original arguments. Create it and fill // it in. const intptr_t receiver_index = descriptor.TypeArgsLen() > 0 ? 1 : 0; body += Constant(TypeArguments::ZoneHandle(Z, TypeArguments::null())); body += IntConstant(receiver_index + descriptor.Size()); body += CreateArray(); LocalVariable* array = MakeTemporary(); if (receiver_index > 0) { LocalVariable* type_args = parsed_function_->function_type_arguments(); ASSERT(type_args != NULL); body += LoadLocal(array); body += IntConstant(0); body += LoadLocal(type_args); body += StoreIndexed(kArrayCid); } for (intptr_t i = 0; i < descriptor.PositionalCount(); ++i) { body += LoadLocal(array); body += IntConstant(receiver_index + i); body += LoadLocal(parsed_function_->ParameterVariable(i)); body += StoreIndexed(kArrayCid); } String& name = String::Handle(Z); for (intptr_t i = 0; i < descriptor.NamedCount(); ++i) { const intptr_t parameter_index = descriptor.PositionAt(i); name = descriptor.NameAt(i); name = Symbols::New(H.thread(), name); body += LoadLocal(array); body += IntConstant(receiver_index + parameter_index); body += LoadLocal(parsed_function_->ParameterVariable(parameter_index)); body += StoreIndexed(kArrayCid); } // Fourth, false indicating this is not a super NoSuchMethod. body += Constant(Bool::False()); const Class& mirror_class = Class::Handle(Z, Library::LookupCoreClass(Symbols::InvocationMirror())); ASSERT(!mirror_class.IsNull()); const auto& error = mirror_class.EnsureIsFinalized(H.thread()); ASSERT(error == Error::null()); const Function& allocation_function = Function::ZoneHandle( Z, mirror_class.LookupStaticFunction( Library::PrivateCoreLibName(Symbols::AllocateInvocationMirror()))); ASSERT(!allocation_function.IsNull()); body += StaticCall(TokenPosition::kMinSource, allocation_function, /* argument_count = */ 4, ICData::kStatic); const int kTypeArgsLen = 0; ArgumentsDescriptor two_arguments( Array::Handle(Z, ArgumentsDescriptor::NewBoxed(kTypeArgsLen, 2))); Function& no_such_method = Function::ZoneHandle(Z, Resolver::ResolveDynamicForReceiverClass( Class::Handle(Z, function.Owner()), Symbols::NoSuchMethod(), two_arguments)); if (no_such_method.IsNull()) { // If noSuchMethod is not found on the receiver class, call // Object.noSuchMethod. no_such_method = Resolver::ResolveDynamicForReceiverClass( Class::Handle(Z, IG->object_store()->object_class()), Symbols::NoSuchMethod(), two_arguments); } body += StaticCall(TokenPosition::kMinSource, no_such_method, /* argument_count = */ 2, ICData::kNSMDispatch); body += Return(TokenPosition::kNoSource); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } // Information used by the various dynamic closure call fragment builders. struct FlowGraphBuilder::ClosureCallInfo { ClosureCallInfo(LocalVariable* closure, JoinEntryInstr* throw_no_such_method, const Array& arguments_descriptor_array, ParsedFunction::DynamicClosureCallVars* const vars) : closure(ASSERT_NOTNULL(closure)), throw_no_such_method(ASSERT_NOTNULL(throw_no_such_method)), descriptor(arguments_descriptor_array), vars(ASSERT_NOTNULL(vars)) {} LocalVariable* const closure; JoinEntryInstr* const throw_no_such_method; const ArgumentsDescriptor descriptor; ParsedFunction::DynamicClosureCallVars* const vars; // Set up by BuildClosureCallDefaultTypeHandling() when needed. These values // are read-only, so they don't need real local variables and are created // using MakeTemporary(). LocalVariable* signature = nullptr; LocalVariable* num_fixed_params = nullptr; LocalVariable* num_opt_params = nullptr; LocalVariable* num_max_params = nullptr; LocalVariable* has_named_params = nullptr; LocalVariable* parameter_names = nullptr; LocalVariable* parameter_types = nullptr; LocalVariable* type_parameters = nullptr; LocalVariable* num_type_parameters = nullptr; LocalVariable* type_parameter_flags = nullptr; LocalVariable* instantiator_type_args = nullptr; LocalVariable* parent_function_type_args = nullptr; LocalVariable* num_parent_type_args = nullptr; }; Fragment FlowGraphBuilder::TestClosureFunctionGeneric( const ClosureCallInfo& info, Fragment generic, Fragment not_generic) { JoinEntryInstr* after_branch = BuildJoinEntry(); Fragment check; check += LoadLocal(info.type_parameters); TargetEntryInstr* is_not_generic; TargetEntryInstr* is_generic; check += BranchIfNull(&is_not_generic, &is_generic); generic.Prepend(is_generic); generic += Goto(after_branch); not_generic.Prepend(is_not_generic); not_generic += Goto(after_branch); return Fragment(check.entry, after_branch); } Fragment FlowGraphBuilder::TestClosureFunctionNamedParameterRequired( const ClosureCallInfo& info, Fragment set, Fragment not_set) { // Required named arguments only exist if null_safety is enabled. if (!IG->use_strict_null_safety_checks()) return not_set; Fragment check_required; // First, we convert the index to be in terms of the number of optional // parameters, not total parameters (to calculate the flag index and shift). check_required += LoadLocal(info.vars->current_param_index); check_required += LoadLocal(info.num_fixed_params); check_required += SmiBinaryOp(Token::kSUB, /*is_truncating=*/true); LocalVariable* opt_index = MakeTemporary("opt_index"); // Read-only. // Next, we calculate the index to dereference in the parameter names array. check_required += LoadLocal(opt_index); check_required += IntConstant(compiler::target::kNumParameterFlagsPerElementLog2); check_required += SmiBinaryOp(Token::kSHR); check_required += LoadLocal(info.num_max_params); check_required += SmiBinaryOp(Token::kADD); LocalVariable* flags_index = MakeTemporary("flags_index"); // Read-only. // Two read-only stack values (opt_index, flag_index) that must be dropped // after we rejoin at after_check. JoinEntryInstr* after_check = BuildJoinEntry(); // Now we check to see if the flags index is within the bounds of the // parameters names array. If not, it cannot be required. check_required += LoadLocal(flags_index); check_required += LoadLocal(info.parameter_names); check_required += LoadNativeField(Slot::Array_length()); check_required += SmiRelationalOp(Token::kLT); TargetEntryInstr* valid_index; TargetEntryInstr* invalid_index; check_required += BranchIfTrue(&valid_index, &invalid_index); JoinEntryInstr* join_not_set = BuildJoinEntry(); Fragment(invalid_index) + Goto(join_not_set); // Otherwise, we need to retrieve the value. We're guaranteed the Smis in // the flag slots are non-null, so after loading we can immediate check // the required flag bit for the given named parameter. check_required.current = valid_index; check_required += LoadLocal(info.parameter_names); check_required += LoadLocal(flags_index); check_required += LoadIndexed(kArrayCid); check_required += LoadLocal(opt_index); check_required += IntConstant(compiler::target::kNumParameterFlagsPerElement - 1); check_required += SmiBinaryOp(Token::kBIT_AND); // If the below changes, we'll need to multiply by the number of parameter // flags before shifting. static_assert(compiler::target::kNumParameterFlags == 1, "IL builder assumes only one flag bit per parameter"); check_required += SmiBinaryOp(Token::kSHR); check_required += IntConstant(1 << compiler::target::kRequiredNamedParameterFlag); check_required += SmiBinaryOp(Token::kBIT_AND); check_required += IntConstant(0); TargetEntryInstr* is_not_set; TargetEntryInstr* is_set; check_required += BranchIfEqual(&is_not_set, &is_set); Fragment(is_not_set) + Goto(join_not_set); set.Prepend(is_set); set += Goto(after_check); not_set.Prepend(join_not_set); not_set += Goto(after_check); // After rejoining, drop the introduced temporaries. check_required.current = after_check; check_required += DropTemporary(&flags_index); check_required += DropTemporary(&opt_index); return check_required; } Fragment FlowGraphBuilder::BuildClosureCallDefaultTypeHandling( const ClosureCallInfo& info) { if (info.descriptor.TypeArgsLen() > 0) { ASSERT(parsed_function_->function_type_arguments() != nullptr); // A TAV was provided, so we don't need default type argument handling // and can just take the arguments we were given. Fragment store_provided; store_provided += LoadLocal(parsed_function_->function_type_arguments()); store_provided += StoreLocal(info.vars->function_type_args); store_provided += Drop(); return store_provided; } // Load the defaults, instantiating or replacing them with the other type // arguments as appropriate. Fragment store_default; store_default += LoadLocal(info.closure); store_default += LoadNativeField(Slot::Closure_function()); store_default += LoadNativeField(Slot::Function_data()); LocalVariable* closure_data = MakeTemporary("closure_data"); store_default += LoadLocal(closure_data); const auto& slot = Slot::ClosureData_default_type_arguments_kind(); store_default += LoadNativeField(slot); store_default += Box(slot.representation()); LocalVariable* default_tav_kind = MakeTemporary("default_tav_kind"); // Two locals to drop after join, closure_data and default_tav_kind. JoinEntryInstr* done = BuildJoinEntry(); store_default += LoadLocal(default_tav_kind); TargetEntryInstr* is_instantiated; TargetEntryInstr* is_not_instantiated; store_default += IntConstant(static_cast<intptr_t>( ClosureData::DefaultTypeArgumentsKind::kIsInstantiated)); store_default += BranchIfEqual(&is_instantiated, &is_not_instantiated); store_default.current = is_not_instantiated; // Check next case. store_default += LoadLocal(default_tav_kind); TargetEntryInstr* needs_instantiation; TargetEntryInstr* can_share; store_default += IntConstant(static_cast<intptr_t>( ClosureData::DefaultTypeArgumentsKind::kNeedsInstantiation)); store_default += BranchIfEqual(&needs_instantiation, &can_share); store_default.current = can_share; // Check next case. store_default += LoadLocal(default_tav_kind); TargetEntryInstr* can_share_instantiator; TargetEntryInstr* can_share_function; store_default += IntConstant(static_cast<intptr_t>( ClosureData::DefaultTypeArgumentsKind::kSharesInstantiatorTypeArguments)); store_default += BranchIfEqual(&can_share_instantiator, &can_share_function); Fragment instantiated(is_instantiated); instantiated += LoadLocal(info.type_parameters); instantiated += LoadNativeField(Slot::TypeParameters_defaults()); instantiated += StoreLocal(info.vars->function_type_args); instantiated += Drop(); instantiated += Goto(done); Fragment do_instantiation(needs_instantiation); // Load the instantiator type arguments. do_instantiation += LoadLocal(info.instantiator_type_args); // Load the parent function type arguments. (No local function type arguments // can be used within the defaults). do_instantiation += LoadLocal(info.parent_function_type_args); // Load the default type arguments to instantiate. do_instantiation += LoadLocal(info.type_parameters); do_instantiation += LoadNativeField(Slot::TypeParameters_defaults()); do_instantiation += InstantiateDynamicTypeArguments(); do_instantiation += StoreLocal(info.vars->function_type_args); do_instantiation += Drop(); do_instantiation += Goto(done); Fragment share_instantiator(can_share_instantiator); share_instantiator += LoadLocal(info.instantiator_type_args); share_instantiator += StoreLocal(info.vars->function_type_args); share_instantiator += Drop(); share_instantiator += Goto(done); Fragment share_function(can_share_function); // Since the defaults won't have local type parameters, these must all be // from the parent function type arguments, so we can just use it. share_function += LoadLocal(info.parent_function_type_args); share_function += StoreLocal(info.vars->function_type_args); share_function += Drop(); share_function += Goto(done); store_default.current = done; // Return here after branching. store_default += DropTemporary(&default_tav_kind); store_default += DropTemporary(&closure_data); Fragment store_delayed; store_delayed += LoadLocal(info.closure); store_delayed += LoadNativeField(Slot::Closure_delayed_type_arguments()); store_delayed += StoreLocal(info.vars->function_type_args); store_delayed += Drop(); // Use the delayed type args if present, else the default ones. return TestDelayedTypeArgs(info.closure, store_delayed, store_default); } Fragment FlowGraphBuilder::BuildClosureCallNamedArgumentsCheck( const ClosureCallInfo& info) { // When no named arguments are provided, we just need to check for possible // required named arguments. if (info.descriptor.NamedCount() == 0) { // No work to do if there are no possible required named parameters. if (!IG->use_strict_null_safety_checks()) { return Fragment(); } // If the below changes, we can no longer assume that flag slots existing // means there are required parameters. static_assert(compiler::target::kNumParameterFlags == 1, "IL builder assumes only one flag bit per parameter"); // No named args were provided, so check for any required named params. // Here, we assume that the only parameter flag saved is the required bit // for named parameters. If this changes, we'll need to check each flag // entry appropriately for any set required bits. Fragment has_any; has_any += LoadLocal(info.num_max_params); has_any += LoadLocal(info.parameter_names); has_any += LoadNativeField(Slot::Array_length()); TargetEntryInstr* no_required; TargetEntryInstr* has_required; has_any += BranchIfEqual(&no_required, &has_required); Fragment(has_required) + Goto(info.throw_no_such_method); return Fragment(has_any.entry, no_required); } // Otherwise, we need to loop through the parameter names to check the names // of named arguments for validity (and possibly missing required ones). Fragment check_names; check_names += LoadLocal(info.vars->current_param_index); LocalVariable* old_index = MakeTemporary("old_index"); // Read-only. check_names += LoadLocal(info.vars->current_num_processed); LocalVariable* old_processed = MakeTemporary("old_processed"); // Read-only. // Two local stack values (old_index, old_processed) to drop after rejoining // at done. JoinEntryInstr* loop = BuildJoinEntry(); JoinEntryInstr* done = BuildJoinEntry(); check_names += IntConstant(0); check_names += StoreLocal(info.vars->current_num_processed); check_names += Drop(); check_names += LoadLocal(info.num_fixed_params); check_names += StoreLocal(info.vars->current_param_index); check_names += Drop(); check_names += Goto(loop); Fragment loop_check(loop); loop_check += LoadLocal(info.vars->current_param_index); loop_check += LoadLocal(info.num_max_params); loop_check += SmiRelationalOp(Token::kLT); TargetEntryInstr* no_more; TargetEntryInstr* more; loop_check += BranchIfTrue(&more, &no_more); Fragment(no_more) + Goto(done); Fragment loop_body(more); // First load the name we need to check against. loop_body += LoadLocal(info.parameter_names); loop_body += LoadLocal(info.vars->current_param_index); loop_body += LoadIndexed(kArrayCid); LocalVariable* param_name = MakeTemporary("param_name"); // Read only. // One additional local value on the stack within the loop body (param_name) // that should be dropped after rejoining at loop_incr. JoinEntryInstr* loop_incr = BuildJoinEntry(); // Now iterate over the ArgumentsDescriptor names and check for a match. for (intptr_t i = 0; i < info.descriptor.NamedCount(); i++) { const auto& name = String::ZoneHandle(Z, info.descriptor.NameAt(i)); loop_body += Constant(name); loop_body += LoadLocal(param_name); TargetEntryInstr* match; TargetEntryInstr* mismatch; loop_body += BranchIfEqual(&match, &mismatch); loop_body.current = mismatch; // We have a match, so go to the next name after storing the corresponding // parameter index on the stack and incrementing the number of matched // arguments. (No need to check the required bit for provided parameters.) Fragment matched(match); matched += LoadLocal(info.vars->current_param_index); matched += StoreLocal(info.vars->named_argument_parameter_indices.At(i)); matched += Drop(); matched += LoadLocal(info.vars->current_num_processed); matched += IntConstant(1); matched += SmiBinaryOp(Token::kADD, /*is_truncating=*/true); matched += StoreLocal(info.vars->current_num_processed); matched += Drop(); matched += Goto(loop_incr); } // None of the names in the arguments descriptor matched, so check if this // is a required parameter. loop_body += TestClosureFunctionNamedParameterRequired( info, /*set=*/Goto(info.throw_no_such_method), /*not_set=*/{}); loop_body += Goto(loop_incr); Fragment incr_index(loop_incr); incr_index += DropTemporary(&param_name); incr_index += LoadLocal(info.vars->current_param_index); incr_index += IntConstant(1); incr_index += SmiBinaryOp(Token::kADD, /*is_truncating=*/true); incr_index += StoreLocal(info.vars->current_param_index); incr_index += Drop(); incr_index += Goto(loop); Fragment check_processed(done); check_processed += LoadLocal(info.vars->current_num_processed); check_processed += IntConstant(info.descriptor.NamedCount()); TargetEntryInstr* all_processed; TargetEntryInstr* bad_name; check_processed += BranchIfEqual(&all_processed, &bad_name); // Didn't find a matching parameter name for at least one argument name. Fragment(bad_name) + Goto(info.throw_no_such_method); // Drop the temporaries at the end of the fragment. check_names.current = all_processed; check_names += LoadLocal(old_processed); check_names += StoreLocal(info.vars->current_num_processed); check_names += Drop(); check_names += DropTemporary(&old_processed); check_names += LoadLocal(old_index); check_names += StoreLocal(info.vars->current_param_index); check_names += Drop(); check_names += DropTemporary(&old_index); return check_names; } Fragment FlowGraphBuilder::BuildClosureCallArgumentsValidCheck( const ClosureCallInfo& info) { Fragment check_entry; // We only need to check the length of any explicitly provided type arguments. if (info.descriptor.TypeArgsLen() > 0) { Fragment check_type_args_length; check_type_args_length += LoadLocal(info.type_parameters); TargetEntryInstr* null; TargetEntryInstr* not_null; check_type_args_length += BranchIfNull(&null, &not_null); check_type_args_length.current = not_null; // Continue in non-error case. check_type_args_length += LoadLocal(info.type_parameters); check_type_args_length += LoadNativeField(Slot::TypeParameters_names()); check_type_args_length += LoadNativeField(Slot::Array_length()); check_type_args_length += IntConstant(info.descriptor.TypeArgsLen()); TargetEntryInstr* equal; TargetEntryInstr* not_equal; check_type_args_length += BranchIfEqual(&equal, &not_equal); check_type_args_length.current = equal; // Continue in non-error case. // The function is not generic. Fragment(null) + Goto(info.throw_no_such_method); // An incorrect number of type arguments were passed. Fragment(not_equal) + Goto(info.throw_no_such_method); // Type arguments should not be provided if there are delayed type // arguments, as then the closure itself is not generic. check_entry += TestDelayedTypeArgs( info.closure, /*present=*/Goto(info.throw_no_such_method), /*absent=*/check_type_args_length); } check_entry += LoadLocal(info.has_named_params); TargetEntryInstr* has_named; TargetEntryInstr* has_positional; check_entry += BranchIfTrue(&has_named, &has_positional); JoinEntryInstr* join_after_optional = BuildJoinEntry(); check_entry.current = join_after_optional; if (info.descriptor.NamedCount() > 0) { // No reason to continue checking, as this function doesn't take named args. Fragment(has_positional) + Goto(info.throw_no_such_method); } else { Fragment check_pos(has_positional); check_pos += LoadLocal(info.num_fixed_params); check_pos += IntConstant(info.descriptor.PositionalCount()); check_pos += SmiRelationalOp(Token::kLTE); TargetEntryInstr* enough; TargetEntryInstr* too_few; check_pos += BranchIfTrue(&enough, &too_few); check_pos.current = enough; Fragment(too_few) + Goto(info.throw_no_such_method); check_pos += IntConstant(info.descriptor.PositionalCount()); check_pos += LoadLocal(info.num_max_params); check_pos += SmiRelationalOp(Token::kLTE); TargetEntryInstr* valid; TargetEntryInstr* too_many; check_pos += BranchIfTrue(&valid, &too_many); check_pos.current = valid; Fragment(too_many) + Goto(info.throw_no_such_method); check_pos += Goto(join_after_optional); } Fragment check_named(has_named); TargetEntryInstr* same; TargetEntryInstr* different; check_named += LoadLocal(info.num_fixed_params); check_named += IntConstant(info.descriptor.PositionalCount()); check_named += BranchIfEqual(&same, &different); check_named.current = same; Fragment(different) + Goto(info.throw_no_such_method); if (info.descriptor.NamedCount() > 0) { check_named += IntConstant(info.descriptor.NamedCount()); check_named += LoadLocal(info.num_opt_params); check_named += SmiRelationalOp(Token::kLTE); TargetEntryInstr* valid; TargetEntryInstr* too_many; check_named += BranchIfTrue(&valid, &too_many); check_named.current = valid; Fragment(too_many) + Goto(info.throw_no_such_method); } // Check the names for optional arguments. If applicable, also check that all // required named parameters are provided. check_named += BuildClosureCallNamedArgumentsCheck(info); check_named += Goto(join_after_optional); check_entry.current = join_after_optional; return check_entry; } Fragment FlowGraphBuilder::BuildClosureCallTypeArgumentsTypeCheck( const ClosureCallInfo& info) { JoinEntryInstr* done = BuildJoinEntry(); JoinEntryInstr* loop = BuildJoinEntry(); // We assume that the value stored in :t_type_parameters is not null (i.e., // the function stored in :t_function is generic). Fragment loop_init; // A null bounds vector represents a vector of dynamic and no check is needed. loop_init += LoadLocal(info.type_parameters); loop_init += LoadNativeField(Slot::TypeParameters_bounds()); TargetEntryInstr* null_bounds; TargetEntryInstr* non_null_bounds; loop_init += BranchIfNull(&null_bounds, &non_null_bounds); Fragment(null_bounds) + Goto(done); loop_init.current = non_null_bounds; // Loop over the type parameters array. loop_init += IntConstant(0); loop_init += StoreLocal(info.vars->current_param_index); loop_init += Drop(); loop_init += Goto(loop); Fragment loop_check(loop); loop_check += LoadLocal(info.vars->current_param_index); loop_check += LoadLocal(info.num_type_parameters); loop_check += SmiRelationalOp(Token::kLT); TargetEntryInstr* more; TargetEntryInstr* no_more; loop_check += BranchIfTrue(&more, &no_more); Fragment(no_more) + Goto(done); Fragment loop_test_flag(more); JoinEntryInstr* next = BuildJoinEntry(); JoinEntryInstr* check = BuildJoinEntry(); loop_test_flag += LoadLocal(info.type_parameter_flags); TargetEntryInstr* null_flags; TargetEntryInstr* non_null_flags; loop_test_flag += BranchIfNull(&null_flags, &non_null_flags); Fragment(null_flags) + Goto(check); // Check type if null (non-covariant). loop_test_flag.current = non_null_flags; // Test flags if not null. loop_test_flag += LoadLocal(info.type_parameter_flags); loop_test_flag += LoadLocal(info.vars->current_param_index); loop_test_flag += IntConstant(TypeParameters::kFlagsPerSmiShift); loop_test_flag += SmiBinaryOp(Token::kSHR); loop_test_flag += LoadIndexed(kArrayCid); loop_test_flag += LoadLocal(info.vars->current_param_index); loop_test_flag += IntConstant(TypeParameters::kFlagsPerSmiMask); loop_test_flag += SmiBinaryOp(Token::kBIT_AND); loop_test_flag += SmiBinaryOp(Token::kSHR); loop_test_flag += IntConstant(1); loop_test_flag += SmiBinaryOp(Token::kBIT_AND); loop_test_flag += IntConstant(0); TargetEntryInstr* is_noncovariant; TargetEntryInstr* is_covariant; loop_test_flag += BranchIfEqual(&is_noncovariant, &is_covariant); Fragment(is_covariant) + Goto(next); // Continue if covariant. Fragment(is_noncovariant) + Goto(check); // Check type if non-covariant. Fragment loop_prep_type_param(check); JoinEntryInstr* dynamic_type_param = BuildJoinEntry(); JoinEntryInstr* call = BuildJoinEntry(); // Load type argument already stored in function_type_args if non null. loop_prep_type_param += LoadLocal(info.vars->function_type_args); TargetEntryInstr* null_ftav; TargetEntryInstr* non_null_ftav; loop_prep_type_param += BranchIfNull(&null_ftav, &non_null_ftav); Fragment(null_ftav) + Goto(dynamic_type_param); loop_prep_type_param.current = non_null_ftav; loop_prep_type_param += LoadLocal(info.vars->function_type_args); loop_prep_type_param += LoadLocal(info.vars->current_param_index); loop_prep_type_param += LoadLocal(info.num_parent_type_args); loop_prep_type_param += SmiBinaryOp(Token::kADD, /*is_truncating=*/true); loop_prep_type_param += LoadIndexed( kTypeArgumentsCid, /*index_scale*/ compiler::target::kCompressedWordSize); loop_prep_type_param += StoreLocal(info.vars->current_type_param); loop_prep_type_param += Drop(); loop_prep_type_param += Goto(call); Fragment loop_dynamic_type_param(dynamic_type_param); // If function_type_args is null, the instantiated type param is dynamic. loop_dynamic_type_param += Constant(Type::ZoneHandle(Type::DynamicType())); loop_dynamic_type_param += StoreLocal(info.vars->current_type_param); loop_dynamic_type_param += Drop(); loop_dynamic_type_param += Goto(call); Fragment loop_call_check(call); // Load instantiators. loop_call_check += LoadLocal(info.instantiator_type_args); loop_call_check += LoadLocal(info.vars->function_type_args); // Load instantiated type parameter. loop_call_check += LoadLocal(info.vars->current_type_param); // Load bound from type parameters. loop_call_check += LoadLocal(info.type_parameters); loop_call_check += LoadNativeField(Slot::TypeParameters_bounds()); loop_call_check += LoadLocal(info.vars->current_param_index); loop_call_check += LoadIndexed( kTypeArgumentsCid, /*index_scale*/ compiler::target::kCompressedWordSize); // Load (canonicalized) name of type parameter in signature. loop_call_check += LoadLocal(info.type_parameters); loop_call_check += LoadNativeField(Slot::TypeParameters_names()); loop_call_check += LoadLocal(info.vars->current_param_index); loop_call_check += LoadIndexed(kArrayCid); // Assert that the passed-in type argument is consistent with the bound of // the corresponding type parameter. loop_call_check += AssertSubtype(TokenPosition::kNoSource); loop_call_check += Goto(next); Fragment loop_incr(next); loop_incr += LoadLocal(info.vars->current_param_index); loop_incr += IntConstant(1); loop_incr += SmiBinaryOp(Token::kADD, /*is_truncating=*/true); loop_incr += StoreLocal(info.vars->current_param_index); loop_incr += Drop(); loop_incr += Goto(loop); return Fragment(loop_init.entry, done); } Fragment FlowGraphBuilder::BuildClosureCallArgumentTypeCheck( const ClosureCallInfo& info, LocalVariable* param_index, intptr_t arg_index, const String& arg_name) { Fragment instructions; // Load value. instructions += LoadLocal(parsed_function_->ParameterVariable(arg_index)); // Load destination type. instructions += LoadLocal(info.parameter_types); instructions += LoadLocal(param_index); instructions += LoadIndexed(kArrayCid); // Load instantiator type arguments. instructions += LoadLocal(info.instantiator_type_args); // Load the full set of function type arguments. instructions += LoadLocal(info.vars->function_type_args); // Check that the value has the right type. instructions += AssertAssignable(TokenPosition::kNoSource, arg_name, AssertAssignableInstr::kParameterCheck); // Make sure to store the result to keep data dependencies accurate. instructions += StoreLocal(parsed_function_->ParameterVariable(arg_index)); instructions += Drop(); return instructions; } Fragment FlowGraphBuilder::BuildClosureCallArgumentTypeChecks( const ClosureCallInfo& info) { Fragment instructions; // Only check explicit arguments (i.e., skip the receiver), as the receiver // is always assignable to its type (stored as dynamic). for (intptr_t i = 1; i < info.descriptor.PositionalCount(); i++) { instructions += IntConstant(i); LocalVariable* param_index = MakeTemporary("param_index"); // We don't have a compile-time name, so this symbol signals the runtime // that it should recreate the type check using info from the stack. instructions += BuildClosureCallArgumentTypeCheck( info, param_index, i, Symbols::dynamic_assert_assignable_stc_check()); instructions += DropTemporary(&param_index); } for (intptr_t i = 0; i < info.descriptor.NamedCount(); i++) { const intptr_t arg_index = info.descriptor.PositionAt(i); const auto& arg_name = String::ZoneHandle(Z, info.descriptor.NameAt(i)); auto const param_index = info.vars->named_argument_parameter_indices.At(i); instructions += BuildClosureCallArgumentTypeCheck(info, param_index, arg_index, arg_name); } return instructions; } Fragment FlowGraphBuilder::BuildDynamicClosureCallChecks( LocalVariable* closure) { ClosureCallInfo info(closure, BuildThrowNoSuchMethod(), saved_args_desc_array(), parsed_function_->dynamic_closure_call_vars()); Fragment body; body += LoadLocal(info.closure); body += LoadNativeField(Slot::Closure_function()); body += LoadNativeField(Slot::Function_signature()); info.signature = MakeTemporary("signature"); body += LoadLocal(info.signature); body += BuildExtractUnboxedSlotBitFieldIntoSmi< FunctionType::PackedNumFixedParameters>( Slot::FunctionType_packed_fields()); info.num_fixed_params = MakeTemporary("num_fixed_params"); body += LoadLocal(info.signature); body += BuildExtractUnboxedSlotBitFieldIntoSmi< FunctionType::PackedNumOptionalParameters>( Slot::FunctionType_packed_fields()); info.num_opt_params = MakeTemporary("num_opt_params"); body += LoadLocal(info.num_fixed_params); body += LoadLocal(info.num_opt_params); body += SmiBinaryOp(Token::kADD); info.num_max_params = MakeTemporary("num_max_params"); body += LoadLocal(info.signature); body += BuildExtractUnboxedSlotBitFieldIntoSmi< FunctionType::PackedHasNamedOptionalParameters>( Slot::FunctionType_packed_fields()); body += IntConstant(0); body += StrictCompare(Token::kNE_STRICT); info.has_named_params = MakeTemporary("has_named_params"); body += LoadLocal(info.signature); body += LoadNativeField(Slot::FunctionType_parameter_names()); info.parameter_names = MakeTemporary("parameter_names"); body += LoadLocal(info.signature); body += LoadNativeField(Slot::FunctionType_parameter_types()); info.parameter_types = MakeTemporary("parameter_types"); body += LoadLocal(info.signature); body += LoadNativeField(Slot::FunctionType_type_parameters()); info.type_parameters = MakeTemporary("type_parameters"); body += LoadLocal(info.closure); body += LoadNativeField(Slot::Closure_instantiator_type_arguments()); info.instantiator_type_args = MakeTemporary("instantiator_type_args"); body += LoadLocal(info.closure); body += LoadNativeField(Slot::Closure_function_type_arguments()); info.parent_function_type_args = MakeTemporary("parent_function_type_args"); // At this point, all the read-only temporaries stored in the ClosureCallInfo // should be either loaded or still nullptr, if not needed for this function. // Now we check that the arguments to the closure call have the right shape. body += BuildClosureCallArgumentsValidCheck(info); // If the closure function is not generic, there are no local function type // args. Thus, use whatever was stored for the parent function type arguments, // which has already been checked against any parent type parameter bounds. Fragment not_generic; not_generic += LoadLocal(info.parent_function_type_args); not_generic += StoreLocal(info.vars->function_type_args); not_generic += Drop(); // If the closure function is generic, then we first need to calculate the // full set of function type arguments, then check the local function type // arguments against the closure function's type parameter bounds. Fragment generic; // Calculate the number of parent type arguments and store them in // info.num_parent_type_args. generic += LoadLocal(info.signature); generic += BuildExtractUnboxedSlotBitFieldIntoSmi< UntaggedFunctionType::PackedNumParentTypeArguments>( Slot::FunctionType_packed_fields()); info.num_parent_type_args = MakeTemporary("num_parent_type_args"); // Hoist number of type parameters. generic += LoadLocal(info.type_parameters); generic += LoadNativeField(Slot::TypeParameters_names()); generic += LoadNativeField(Slot::Array_length()); info.num_type_parameters = MakeTemporary("num_type_parameters"); // Hoist type parameter flags. generic += LoadLocal(info.type_parameters); generic += LoadNativeField(Slot::TypeParameters_flags()); info.type_parameter_flags = MakeTemporary("type_parameter_flags"); // Calculate the local function type arguments and store them in // info.vars->function_type_args. generic += BuildClosureCallDefaultTypeHandling(info); // Load the local function type args. generic += LoadLocal(info.vars->function_type_args); // Load the parent function type args. generic += LoadLocal(info.parent_function_type_args); // Load the number of parent type parameters. generic += LoadLocal(info.num_parent_type_args); // Load the number of total type parameters. generic += LoadLocal(info.num_parent_type_args); generic += LoadLocal(info.num_type_parameters); generic += SmiBinaryOp(Token::kADD, /*is_truncating=*/true); // Call the static function for prepending type arguments. generic += StaticCall(TokenPosition::kNoSource, PrependTypeArgumentsFunction(), 4, ICData::kStatic); generic += StoreLocal(info.vars->function_type_args); generic += Drop(); // Now that we have the full set of function type arguments, check them // against the type parameter bounds. However, if the local function type // arguments are delayed type arguments, they have already been checked by // the type system and need not be checked again at the call site. auto const check_bounds = BuildClosureCallTypeArgumentsTypeCheck(info); if (FLAG_eliminate_type_checks) { generic += TestDelayedTypeArgs(info.closure, /*present=*/{}, /*absent=*/check_bounds); } else { generic += check_bounds; } generic += DropTemporary(&info.type_parameter_flags); generic += DropTemporary(&info.num_type_parameters); generic += DropTemporary(&info.num_parent_type_args); // Call the appropriate fragment for setting up the function type arguments // and performing any needed type argument checking. body += TestClosureFunctionGeneric(info, generic, not_generic); // Check that the values provided as arguments are assignable to the types // of the corresponding closure function parameters. body += BuildClosureCallArgumentTypeChecks(info); // Drop all the read-only temporaries at the end of the fragment. body += DropTemporary(&info.parent_function_type_args); body += DropTemporary(&info.instantiator_type_args); body += DropTemporary(&info.type_parameters); body += DropTemporary(&info.parameter_types); body += DropTemporary(&info.parameter_names); body += DropTemporary(&info.has_named_params); body += DropTemporary(&info.num_max_params); body += DropTemporary(&info.num_opt_params); body += DropTemporary(&info.num_fixed_params); body += DropTemporary(&info.signature); return body; } FlowGraph* FlowGraphBuilder::BuildGraphOfInvokeFieldDispatcher( const Function& function) { const ArgumentsDescriptor descriptor(saved_args_desc_array()); // Find the name of the field we should dispatch to. const Class& owner = Class::Handle(Z, function.Owner()); ASSERT(!owner.IsNull()); auto& field_name = String::Handle(Z, function.name()); // If the field name has a dyn: tag, then remove it. We don't add dynamic // invocation forwarders for field getters used for invoking, we just use // the tag in the name of the invoke field dispatcher to detect dynamic calls. const bool is_dynamic_call = Function::IsDynamicInvocationForwarderName(field_name); if (is_dynamic_call) { field_name = Function::DemangleDynamicInvocationForwarderName(field_name); } const String& getter_name = String::ZoneHandle( Z, Symbols::New(thread_, String::Handle(Z, Field::GetterSymbol(field_name)))); // Determine if this is `class Closure { get call => this; }` const Class& closure_class = Class::Handle(Z, IG->object_store()->closure_class()); const bool is_closure_call = (owner.ptr() == closure_class.ptr()) && field_name.Equals(Symbols::Call()); graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); PrologueInfo prologue_info(-1, -1); BlockEntryInstr* instruction_cursor = BuildPrologue(normal_entry, &prologue_info); Fragment body(instruction_cursor); body += CheckStackOverflowInPrologue(function.token_pos()); // Build any dynamic closure call checks before pushing arguments to the // final call on the stack to make debugging easier. LocalVariable* closure = nullptr; if (is_closure_call) { closure = parsed_function_->ParameterVariable(0); if (is_dynamic_call) { // The whole reason for making this invoke field dispatcher is that // this closure call needs checking, so we shouldn't inline a call to an // unchecked entry that can't tail call NSM. InlineBailout( "kernel::FlowGraphBuilder::BuildGraphOfInvokeFieldDispatcher"); body += BuildDynamicClosureCallChecks(closure); } } if (descriptor.TypeArgsLen() > 0) { LocalVariable* type_args = parsed_function_->function_type_arguments(); ASSERT(type_args != nullptr); body += LoadLocal(type_args); } if (is_closure_call) { // The closure itself is the first argument. body += LoadLocal(closure); } else { // Invoke the getter to get the field value. body += LoadLocal(parsed_function_->ParameterVariable(0)); const intptr_t kTypeArgsLen = 0; const intptr_t kNumArgsChecked = 1; body += InstanceCall(TokenPosition::kMinSource, getter_name, Token::kGET, kTypeArgsLen, 1, Array::null_array(), kNumArgsChecked); } // Push all arguments onto the stack. for (intptr_t pos = 1; pos < descriptor.Count(); pos++) { body += LoadLocal(parsed_function_->ParameterVariable(pos)); } // Construct argument names array if necessary. const Array* argument_names = &Object::null_array(); if (descriptor.NamedCount() > 0) { const auto& array_handle = Array::ZoneHandle(Z, Array::New(descriptor.NamedCount(), Heap::kNew)); String& string_handle = String::Handle(Z); for (intptr_t i = 0; i < descriptor.NamedCount(); ++i) { const intptr_t named_arg_index = descriptor.PositionAt(i) - descriptor.PositionalCount(); string_handle = descriptor.NameAt(i); array_handle.SetAt(named_arg_index, string_handle); } argument_names = &array_handle; } if (is_closure_call) { body += LoadLocal(closure); if (!FLAG_precompiled_mode || !FLAG_use_bare_instructions) { // Lookup the function in the closure. body += LoadNativeField(Slot::Closure_function()); } body += ClosureCall(TokenPosition::kNoSource, descriptor.TypeArgsLen(), descriptor.Count(), *argument_names); } else { const intptr_t kNumArgsChecked = 1; body += InstanceCall(TokenPosition::kMinSource, is_dynamic_call ? Symbols::DynamicCall() : Symbols::Call(), Token::kILLEGAL, descriptor.TypeArgsLen(), descriptor.Count(), *argument_names, kNumArgsChecked); } body += Return(TokenPosition::kNoSource); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } FlowGraph* FlowGraphBuilder::BuildGraphOfNoSuchMethodForwarder( const Function& function, bool is_implicit_closure_function, bool throw_no_such_method_error) { graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); PrologueInfo prologue_info(-1, -1); BlockEntryInstr* instruction_cursor = BuildPrologue(normal_entry, &prologue_info); Fragment body(instruction_cursor); body += CheckStackOverflowInPrologue(function.token_pos()); // If we are inside the tearoff wrapper function (implicit closure), we need // to extract the receiver from the context. We just replace it directly on // the stack to simplify the rest of the code. if (is_implicit_closure_function && !function.is_static()) { if (parsed_function_->has_arg_desc_var()) { body += LoadArgDescriptor(); body += LoadNativeField(Slot::ArgumentsDescriptor_size()); } else { ASSERT(function.NumOptionalParameters() == 0); body += IntConstant(function.NumParameters()); } body += LoadLocal(parsed_function_->current_context_var()); body += LoadNativeField(Slot::GetContextVariableSlotFor( thread_, *parsed_function_->receiver_var())); body += StoreFpRelativeSlot( kWordSize * compiler::target::frame_layout.param_end_from_fp); } if (function.NeedsTypeArgumentTypeChecks()) { BuildTypeArgumentTypeChecks(TypeChecksToBuild::kCheckAllTypeParameterBounds, &body); } if (function.NeedsArgumentTypeChecks()) { BuildArgumentTypeChecks(&body, &body, nullptr); } body += MakeTemp(); LocalVariable* result = MakeTemporary(); // Do "++argument_count" if any type arguments were passed. LocalVariable* argument_count_var = parsed_function_->expression_temp_var(); body += IntConstant(0); body += StoreLocal(TokenPosition::kNoSource, argument_count_var); body += Drop(); if (function.IsGeneric()) { Fragment then; Fragment otherwise; otherwise += IntConstant(1); otherwise += StoreLocal(TokenPosition::kNoSource, argument_count_var); otherwise += Drop(); body += TestAnyTypeArgs(then, otherwise); } if (function.HasOptionalParameters()) { body += LoadArgDescriptor(); body += LoadNativeField(Slot::ArgumentsDescriptor_size()); } else { body += IntConstant(function.NumParameters()); } body += LoadLocal(argument_count_var); body += SmiBinaryOp(Token::kADD, /* truncate= */ true); LocalVariable* argument_count = MakeTemporary(); // We are generating code like the following: // // var arguments = new Array<dynamic>(argument_count); // // int i = 0; // if (any type arguments are passed) { // arguments[0] = function_type_arguments; // ++i; // } // // for (; i < argument_count; ++i) { // arguments[i] = LoadFpRelativeSlot( // kWordSize * (frame_layout.param_end_from_fp + argument_count - i)); // } body += Constant(TypeArguments::ZoneHandle(Z, TypeArguments::null())); body += LoadLocal(argument_count); body += CreateArray(); LocalVariable* arguments = MakeTemporary(); { // int i = 0 LocalVariable* index = parsed_function_->expression_temp_var(); body += IntConstant(0); body += StoreLocal(TokenPosition::kNoSource, index); body += Drop(); // if (any type arguments are passed) { // arguments[0] = function_type_arguments; // i = 1; // } if (function.IsGeneric()) { Fragment store; store += LoadLocal(arguments); store += IntConstant(0); store += LoadFunctionTypeArguments(); store += StoreIndexed(kArrayCid); store += IntConstant(1); store += StoreLocal(TokenPosition::kNoSource, index); store += Drop(); body += TestAnyTypeArgs(store, Fragment()); } TargetEntryInstr* body_entry; TargetEntryInstr* loop_exit; Fragment condition; // i < argument_count condition += LoadLocal(index); condition += LoadLocal(argument_count); condition += SmiRelationalOp(Token::kLT); condition += BranchIfTrue(&body_entry, &loop_exit, /*negate=*/false); Fragment loop_body(body_entry); // arguments[i] = LoadFpRelativeSlot( // kWordSize * (frame_layout.param_end_from_fp + argument_count - i)); loop_body += LoadLocal(arguments); loop_body += LoadLocal(index); loop_body += LoadLocal(argument_count); loop_body += LoadLocal(index); loop_body += SmiBinaryOp(Token::kSUB, /*truncate=*/true); loop_body += LoadFpRelativeSlot(compiler::target::kWordSize * compiler::target::frame_layout.param_end_from_fp, CompileType::Dynamic()); loop_body += StoreIndexed(kArrayCid); // ++i loop_body += LoadLocal(index); loop_body += IntConstant(1); loop_body += SmiBinaryOp(Token::kADD, /*truncate=*/true); loop_body += StoreLocal(TokenPosition::kNoSource, index); loop_body += Drop(); JoinEntryInstr* join = BuildJoinEntry(); loop_body += Goto(join); Fragment loop(join); loop += condition; Instruction* entry = new (Z) GotoInstr(join, CompilerState::Current().GetNextDeoptId()); body += Fragment(entry, loop_exit); } // Load receiver. if (is_implicit_closure_function) { if (throw_no_such_method_error) { const Function& parent = Function::ZoneHandle(Z, function.parent_function()); const Class& owner = Class::ZoneHandle(Z, parent.Owner()); AbstractType& type = AbstractType::ZoneHandle(Z); type = Type::New(owner, TypeArguments::Handle(Z)); type = ClassFinalizer::FinalizeType(type); body += Constant(type); } else { body += LoadLocal(parsed_function_->current_context_var()); body += LoadNativeField(Slot::GetContextVariableSlotFor( thread_, *parsed_function_->receiver_var())); } } else { body += LoadLocal(parsed_function_->ParameterVariable(0)); } body += Constant(String::ZoneHandle(Z, function.name())); if (!parsed_function_->has_arg_desc_var()) { // If there is no variable for the arguments descriptor (this function's // signature doesn't require it), then we need to create one. Array& args_desc = Array::ZoneHandle( Z, ArgumentsDescriptor::NewBoxed(0, function.NumParameters())); body += Constant(args_desc); } else { body += LoadArgDescriptor(); } body += LoadLocal(arguments); if (throw_no_such_method_error) { const Function& parent = Function::ZoneHandle(Z, function.parent_function()); const Class& owner = Class::ZoneHandle(Z, parent.Owner()); InvocationMirror::Level im_level = owner.IsTopLevel() ? InvocationMirror::kTopLevel : InvocationMirror::kStatic; InvocationMirror::Kind im_kind; if (function.IsImplicitGetterFunction() || function.IsGetterFunction()) { im_kind = InvocationMirror::kGetter; } else if (function.IsImplicitSetterFunction() || function.IsSetterFunction()) { im_kind = InvocationMirror::kSetter; } else { im_kind = InvocationMirror::kMethod; } body += IntConstant(InvocationMirror::EncodeType(im_level, im_kind)); } else { body += NullConstant(); } // Push the number of delayed type arguments. if (function.IsClosureFunction()) { LocalVariable* closure = parsed_function_->ParameterVariable(0); Fragment then; then += IntConstant(function.NumTypeParameters()); then += StoreLocal(TokenPosition::kNoSource, argument_count_var); then += Drop(); Fragment otherwise; otherwise += IntConstant(0); otherwise += StoreLocal(TokenPosition::kNoSource, argument_count_var); otherwise += Drop(); body += TestDelayedTypeArgs(closure, then, otherwise); body += LoadLocal(argument_count_var); } else { body += IntConstant(0); } const Class& mirror_class = Class::Handle(Z, Library::LookupCoreClass(Symbols::InvocationMirror())); ASSERT(!mirror_class.IsNull()); const auto& error = mirror_class.EnsureIsFinalized(H.thread()); ASSERT(error == Error::null()); const Function& allocation_function = Function::ZoneHandle( Z, mirror_class.LookupStaticFunction(Library::PrivateCoreLibName( Symbols::AllocateInvocationMirrorForClosure()))); ASSERT(!allocation_function.IsNull()); body += StaticCall(TokenPosition::kMinSource, allocation_function, /* argument_count = */ 5, ICData::kStatic); if (throw_no_such_method_error) { const Class& klass = Class::ZoneHandle( Z, Library::LookupCoreClass(Symbols::NoSuchMethodError())); ASSERT(!klass.IsNull()); const auto& error = klass.EnsureIsFinalized(H.thread()); ASSERT(error == Error::null()); const Function& throw_function = Function::ZoneHandle( Z, klass.LookupStaticFunctionAllowPrivate(Symbols::ThrowNewInvocation())); ASSERT(!throw_function.IsNull()); body += StaticCall(TokenPosition::kNoSource, throw_function, 2, ICData::kStatic); } else { body += InstanceCall( TokenPosition::kNoSource, Symbols::NoSuchMethod(), Token::kILLEGAL, /*type_args_len=*/0, /*argument_count=*/2, Array::null_array(), /*checked_argument_count=*/1); } body += StoreLocal(TokenPosition::kNoSource, result); body += Drop(); body += Drop(); // arguments body += Drop(); // argument count AbstractType& return_type = AbstractType::Handle(function.result_type()); if (!return_type.IsTopTypeForSubtyping()) { body += AssertAssignableLoadTypeArguments(TokenPosition::kNoSource, return_type, Symbols::Empty()); } body += Return(TokenPosition::kNoSource); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } Fragment FlowGraphBuilder::BuildDefaultTypeHandling(const Function& function) { if (function.IsGeneric()) { auto& default_types = TypeArguments::ZoneHandle(Z, function.InstantiateToBounds(thread_)); if (!default_types.IsNull()) { Fragment then; Fragment otherwise; otherwise += TranslateInstantiatedTypeArguments(default_types); otherwise += StoreLocal(TokenPosition::kNoSource, parsed_function_->function_type_arguments()); otherwise += Drop(); return TestAnyTypeArgs(then, otherwise); } } return Fragment(); } FunctionEntryInstr* FlowGraphBuilder::BuildSharedUncheckedEntryPoint( Fragment shared_prologue_linked_in, Fragment skippable_checks, Fragment redefinitions_if_skipped, Fragment body) { ASSERT(shared_prologue_linked_in.entry == graph_entry_->normal_entry()); ASSERT(parsed_function_->has_entry_points_temp_var()); Instruction* prologue_start = shared_prologue_linked_in.entry->next(); auto* join_entry = BuildJoinEntry(); Fragment normal_entry(shared_prologue_linked_in.entry); normal_entry += IntConstant(static_cast<intptr_t>(UncheckedEntryPointStyle::kNone)); normal_entry += StoreLocal(TokenPosition::kNoSource, parsed_function_->entry_points_temp_var()); normal_entry += Drop(); normal_entry += Goto(join_entry); auto* extra_target_entry = BuildFunctionEntry(graph_entry_); Fragment extra_entry(extra_target_entry); extra_entry += IntConstant( static_cast<intptr_t>(UncheckedEntryPointStyle::kSharedWithVariable)); extra_entry += StoreLocal(TokenPosition::kNoSource, parsed_function_->entry_points_temp_var()); extra_entry += Drop(); extra_entry += Goto(join_entry); if (prologue_start != nullptr) { join_entry->LinkTo(prologue_start); } else { // Prologue is empty. shared_prologue_linked_in.current = join_entry; } TargetEntryInstr* do_checks; TargetEntryInstr* skip_checks; shared_prologue_linked_in += LoadLocal(parsed_function_->entry_points_temp_var()); shared_prologue_linked_in += BuildEntryPointsIntrospection(); shared_prologue_linked_in += LoadLocal(parsed_function_->entry_points_temp_var()); shared_prologue_linked_in += IntConstant( static_cast<intptr_t>(UncheckedEntryPointStyle::kSharedWithVariable)); shared_prologue_linked_in += BranchIfEqual(&skip_checks, &do_checks, /*negate=*/false); JoinEntryInstr* rest_entry = BuildJoinEntry(); Fragment(do_checks) + skippable_checks + Goto(rest_entry); Fragment(skip_checks) + redefinitions_if_skipped + Goto(rest_entry); Fragment(rest_entry) + body; return extra_target_entry; } FunctionEntryInstr* FlowGraphBuilder::BuildSeparateUncheckedEntryPoint( BlockEntryInstr* normal_entry, Fragment normal_prologue, Fragment extra_prologue, Fragment shared_prologue, Fragment body) { auto* join_entry = BuildJoinEntry(); auto* extra_entry = BuildFunctionEntry(graph_entry_); Fragment normal(normal_entry); normal += IntConstant(static_cast<intptr_t>(UncheckedEntryPointStyle::kNone)); normal += BuildEntryPointsIntrospection(); normal += normal_prologue; normal += Goto(join_entry); Fragment extra(extra_entry); extra += IntConstant(static_cast<intptr_t>(UncheckedEntryPointStyle::kSeparate)); extra += BuildEntryPointsIntrospection(); extra += extra_prologue; extra += Goto(join_entry); Fragment(join_entry) + shared_prologue + body; return extra_entry; } FlowGraph* FlowGraphBuilder::BuildGraphOfImplicitClosureFunction( const Function& function) { const Function& parent = Function::ZoneHandle(Z, function.parent_function()); Function& target = Function::ZoneHandle(Z, function.ImplicitClosureTarget(Z)); if (target.IsNull() || (parent.num_fixed_parameters() != target.num_fixed_parameters())) { return BuildGraphOfNoSuchMethodForwarder(function, true, parent.is_static()); } graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); PrologueInfo prologue_info(-1, -1); BlockEntryInstr* instruction_cursor = BuildPrologue(normal_entry, &prologue_info); Fragment closure(instruction_cursor); closure += CheckStackOverflowInPrologue(function.token_pos()); closure += BuildDefaultTypeHandling(function); // For implicit closure functions, any non-covariant checks are either // performed by the type system or a dynamic invocation layer (dynamic closure // call dispatcher, mirror, etc.). Static targets never have covariant // arguments, and for non-static targets, they already perform the covariant // checks internally. Thus, no checks are needed and we just need to invoke // the target with the right receiver (unless static). // // TODO(dartbug.com/44195): Consider replacing the argument pushes + static // call with stack manipulation and a tail call instead. intptr_t type_args_len = 0; if (function.IsGeneric()) { type_args_len = function.NumTypeParameters(); ASSERT(parsed_function_->function_type_arguments() != NULL); closure += LoadLocal(parsed_function_->function_type_arguments()); } // Push receiver. if (!target.is_static()) { // The context has a fixed shape: a single variable which is the // closed-over receiver. closure += LoadLocal(parsed_function_->ParameterVariable(0)); closure += LoadNativeField(Slot::Closure_context()); closure += LoadNativeField(Slot::GetContextVariableSlotFor( thread_, *parsed_function_->receiver_var())); } closure += PushExplicitParameters(function); // Forward parameters to the target. intptr_t argument_count = function.NumParameters() - function.NumImplicitParameters() + (target.is_static() ? 0 : 1); ASSERT(argument_count == target.NumParameters()); Array& argument_names = Array::ZoneHandle(Z, GetOptionalParameterNames(function)); closure += StaticCall(TokenPosition::kNoSource, target, argument_count, argument_names, ICData::kNoRebind, /* result_type = */ NULL, type_args_len); // Return the result. closure += Return(function.end_token_pos()); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } FlowGraph* FlowGraphBuilder::BuildGraphOfFieldAccessor( const Function& function) { ASSERT(function.IsImplicitGetterOrSetter() || function.IsDynamicInvocationForwarder()); // Instead of building a dynamic invocation forwarder that checks argument // type and then invokes original setter we simply generate the type check // and inlined field store. Scope builder takes care of setting correct // type check mode in this case. const auto& target = Function::Handle( Z, function.IsDynamicInvocationForwarder() ? function.ForwardingTarget() : function.ptr()); ASSERT(target.IsImplicitGetterOrSetter()); const bool is_method = !function.IsStaticFunction(); const bool is_setter = target.IsImplicitSetterFunction(); const bool is_getter = target.IsImplicitGetterFunction() || target.IsImplicitStaticGetterFunction(); ASSERT(is_setter || is_getter); const auto& field = Field::ZoneHandle(Z, target.accessor_field()); graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); Fragment body(normal_entry); if (is_setter) { auto const setter_value = parsed_function_->ParameterVariable(is_method ? 1 : 0); if (is_method) { body += LoadLocal(parsed_function_->ParameterVariable(0)); } body += LoadLocal(setter_value); // The dyn:* forwarder has to check the parameters that the // actual target will not check. // Though here we manually inline the target, so the dyn:* forwarder has to // check all parameters. const bool needs_type_check = function.IsDynamicInvocationForwarder() || setter_value->needs_type_check(); if (needs_type_check) { body += CheckAssignable(setter_value->type(), setter_value->name(), AssertAssignableInstr::kParameterCheck); } body += BuildNullAssertions(); if (field.is_late()) { if (is_method) { body += Drop(); } body += Drop(); body += StoreLateField( field, is_method ? parsed_function_->ParameterVariable(0) : nullptr, setter_value); } else { if (is_method) { body += StoreInstanceFieldGuarded( field, StoreInstanceFieldInstr::Kind::kOther); } else { body += StoreStaticField(TokenPosition::kNoSource, field); } } body += NullConstant(); } else if (is_getter && is_method) { ASSERT(!field.needs_load_guard() NOT_IN_PRODUCT(|| IG->HasAttemptedReload())); body += LoadLocal(parsed_function_->ParameterVariable(0)); body += LoadField( field, /*calls_initializer=*/field.NeedsInitializationCheckOnLoad()); if (field.needs_load_guard()) { #if defined(PRODUCT) UNREACHABLE(); #else body += CheckAssignable(AbstractType::Handle(Z, field.type()), Symbols::FunctionResult()); #endif } } else if (field.is_const()) { const auto& value = Object::Handle(Z, field.StaticConstFieldValue()); if (value.IsError()) { Report::LongJump(Error::Cast(value)); } body += Constant(Instance::ZoneHandle(Z, Instance::RawCast(value.ptr()))); } else { // Static fields // - with trivial initializer // - without initializer if they are not late // are initialized eagerly and do not have implicit getters. // Static fields with non-trivial initializer need getter to perform // lazy initialization. Late fields without initializer need getter // to make sure they are already initialized. ASSERT(field.has_nontrivial_initializer() || (field.is_late() && !field.has_initializer())); body += LoadStaticField(field, /*calls_initializer=*/true); if (field.needs_load_guard()) { #if defined(PRODUCT) UNREACHABLE(); #else ASSERT(IsolateGroup::Current()->HasAttemptedReload()); body += CheckAssignable(AbstractType::Handle(Z, field.type()), Symbols::FunctionResult()); #endif } } body += Return(TokenPosition::kNoSource); PrologueInfo prologue_info(-1, -1); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } FlowGraph* FlowGraphBuilder::BuildGraphOfDynamicInvocationForwarder( const Function& function) { auto& name = String::Handle(Z, function.name()); name = Function::DemangleDynamicInvocationForwarderName(name); const auto& target = Function::ZoneHandle(Z, function.ForwardingTarget()); ASSERT(!target.IsNull()); if (target.IsImplicitSetterFunction() || target.IsImplicitGetterFunction()) { return BuildGraphOfFieldAccessor(function); } if (target.IsMethodExtractor()) { return BuildGraphOfMethodExtractor(target); } graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, osr_id_); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); PrologueInfo prologue_info(-1, -1); auto instruction_cursor = BuildPrologue(normal_entry, &prologue_info); Fragment body; if (!function.is_native()) { body += CheckStackOverflowInPrologue(function.token_pos()); } ASSERT(parsed_function_->scope()->num_context_variables() == 0); // Should never build a dynamic invocation forwarder for equality // operator. ASSERT(function.name() != Symbols::EqualOperator().ptr()); // Even if the caller did not pass argument vector we would still // call the target with instantiate-to-bounds type arguments. body += BuildDefaultTypeHandling(function); // Build argument type checks that complement those that are emitted in the // target. BuildTypeArgumentTypeChecks( TypeChecksToBuild::kCheckNonCovariantTypeParameterBounds, &body); BuildArgumentTypeChecks(&body, &body, nullptr); // Push all arguments and invoke the original method. intptr_t type_args_len = 0; if (function.IsGeneric()) { type_args_len = function.NumTypeParameters(); ASSERT(parsed_function_->function_type_arguments() != nullptr); body += LoadLocal(parsed_function_->function_type_arguments()); } // Push receiver. ASSERT(function.NumImplicitParameters() == 1); body += LoadLocal(parsed_function_->receiver_var()); body += PushExplicitParameters(function, target); const intptr_t argument_count = function.NumParameters(); const auto& argument_names = Array::ZoneHandle(Z, GetOptionalParameterNames(function)); body += StaticCall(TokenPosition::kNoSource, target, argument_count, argument_names, ICData::kNoRebind, nullptr, type_args_len); if (target.has_unboxed_integer_return()) { body += Box(kUnboxedInt64); } else if (target.has_unboxed_double_return()) { body += Box(kUnboxedDouble); } // Later optimization passes assume that result of a x.[]=(...) call is not // used. We must guarantee this invariant because violation will lead to an // illegal IL once we replace x.[]=(...) with a sequence that does not // actually produce any value. See http://dartbug.com/29135 for more details. if (name.ptr() == Symbols::AssignIndexToken().ptr()) { body += Drop(); body += NullConstant(); } body += Return(TokenPosition::kNoSource); instruction_cursor->LinkTo(body.entry); // When compiling for OSR, use a depth first search to find the OSR // entry and make graph entry jump to it instead of normal entry. // Catch entries are always considered reachable, even if they // become unreachable after OSR. if (IsCompiledForOsr()) { graph_entry_->RelinkToOsrEntry(Z, last_used_block_id_ + 1); } return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } void FlowGraphBuilder::SetConstantRangeOfCurrentDefinition( const Fragment& fragment, int64_t min, int64_t max) { ASSERT(fragment.current->IsDefinition()); Range range(RangeBoundary::FromConstant(min), RangeBoundary::FromConstant(max)); fragment.current->AsDefinition()->set_range(range); } static classid_t TypedDataCidUnboxed(Representation unboxed_representation) { switch (unboxed_representation) { case kUnboxedFloat: // Note kTypedDataFloat32ArrayCid loads kUnboxedDouble. UNREACHABLE(); return kTypedDataFloat32ArrayCid; case kUnboxedInt32: return kTypedDataInt32ArrayCid; case kUnboxedUint32: return kTypedDataUint32ArrayCid; case kUnboxedInt64: return kTypedDataInt64ArrayCid; case kUnboxedDouble: return kTypedDataFloat64ArrayCid; default: UNREACHABLE(); } UNREACHABLE(); } Fragment FlowGraphBuilder::StoreIndexedTypedDataUnboxed( Representation unboxed_representation, intptr_t index_scale, bool index_unboxed) { ASSERT(unboxed_representation == kUnboxedInt32 || unboxed_representation == kUnboxedUint32 || unboxed_representation == kUnboxedInt64 || unboxed_representation == kUnboxedFloat || unboxed_representation == kUnboxedDouble); Fragment fragment; if (unboxed_representation == kUnboxedFloat) { fragment += BitCast(kUnboxedFloat, kUnboxedInt32); unboxed_representation = kUnboxedInt32; } fragment += StoreIndexedTypedData(TypedDataCidUnboxed(unboxed_representation), index_scale, index_unboxed); return fragment; } Fragment FlowGraphBuilder::LoadIndexedTypedDataUnboxed( Representation unboxed_representation, intptr_t index_scale, bool index_unboxed) { ASSERT(unboxed_representation == kUnboxedInt32 || unboxed_representation == kUnboxedUint32 || unboxed_representation == kUnboxedInt64 || unboxed_representation == kUnboxedFloat || unboxed_representation == kUnboxedDouble); Representation representation_for_load = unboxed_representation; if (unboxed_representation == kUnboxedFloat) { representation_for_load = kUnboxedInt32; } Fragment fragment; fragment += LoadIndexed(TypedDataCidUnboxed(representation_for_load), index_scale, index_unboxed); if (unboxed_representation == kUnboxedFloat) { fragment += BitCast(kUnboxedInt32, kUnboxedFloat); } return fragment; } Fragment FlowGraphBuilder::EnterHandleScope() { auto* instr = new (Z) EnterHandleScopeInstr(EnterHandleScopeInstr::Kind::kEnterHandleScope); Push(instr); return Fragment(instr); } Fragment FlowGraphBuilder::GetTopHandleScope() { auto* instr = new (Z) EnterHandleScopeInstr(EnterHandleScopeInstr::Kind::kGetTopHandleScope); Push(instr); return Fragment(instr); } Fragment FlowGraphBuilder::ExitHandleScope() { auto* instr = new (Z) ExitHandleScopeInstr(); return Fragment(instr); } Fragment FlowGraphBuilder::AllocateHandle(LocalVariable* api_local_scope) { Fragment code; if (api_local_scope != nullptr) { // Use the reference the scope we created in the trampoline. code += LoadLocal(api_local_scope); } else { // Or get a reference to the top handle scope. code += GetTopHandleScope(); } Value* api_local_scope_value = Pop(); auto* instr = new (Z) AllocateHandleInstr(api_local_scope_value); Push(instr); code <<= instr; return code; } Fragment FlowGraphBuilder::RawStoreField(int32_t offset) { Fragment code; Value* value = Pop(); Value* base = Pop(); auto* instr = new (Z) RawStoreFieldInstr(base, value, offset); code <<= instr; return code; } Fragment FlowGraphBuilder::WrapHandle(LocalVariable* api_local_scope) { Fragment code; LocalVariable* object = MakeTemporary(); code += AllocateHandle(api_local_scope); code += LoadLocal(MakeTemporary()); // Duplicate handle pointer. code += ConvertUnboxedToUntagged(kUnboxedIntPtr); code += LoadLocal(object); code += RawStoreField(compiler::target::LocalHandle::ptr_offset()); code += DropTempsPreserveTop(1); // Drop object below handle. return code; } Fragment FlowGraphBuilder::UnwrapHandle() { Fragment code; code += ConvertUnboxedToUntagged(kUnboxedIntPtr); code += IntConstant(compiler::target::LocalHandle::ptr_offset()); code += UnboxTruncate(kUnboxedIntPtr); code += LoadIndexed(kArrayCid, /*index_scale=*/1, /*index_unboxed=*/true); return code; } Fragment FlowGraphBuilder::UnhandledException() { const auto class_table = thread_->isolate_group()->class_table(); ASSERT(class_table->HasValidClassAt(kUnhandledExceptionCid)); const auto& klass = Class::ZoneHandle(H.zone(), class_table->At(kUnhandledExceptionCid)); ASSERT(!klass.IsNull()); Fragment body; body += AllocateObject(TokenPosition::kNoSource, klass, 0); LocalVariable* error_instance = MakeTemporary(); body += LoadLocal(error_instance); body += LoadLocal(CurrentException()); body += StoreNativeField(Slot::UnhandledException_exception(), StoreInstanceFieldInstr::Kind::kInitializing, kNoStoreBarrier); body += LoadLocal(error_instance); body += LoadLocal(CurrentStackTrace()); body += StoreNativeField(Slot::UnhandledException_stacktrace(), StoreInstanceFieldInstr::Kind::kInitializing, kNoStoreBarrier); return body; } Fragment FlowGraphBuilder::UnboxTruncate(Representation to) { auto* unbox = UnboxInstr::Create(to, Pop(), DeoptId::kNone, Instruction::kNotSpeculative); Push(unbox); return Fragment(unbox); } Fragment FlowGraphBuilder::NativeReturn( const compiler::ffi::CallbackMarshaller& marshaller) { auto* instr = new (Z) NativeReturnInstr(InstructionSource(), Pop(), marshaller, DeoptId::kNone); return Fragment(instr).closed(); } Fragment FlowGraphBuilder::FfiPointerFromAddress(const Type& result_type) { LocalVariable* address = MakeTemporary(); LocalVariable* result = parsed_function_->expression_temp_var(); Class& result_class = Class::ZoneHandle(Z, result_type.type_class()); // This class might only be instantiated as a return type of ffi calls. result_class.EnsureIsFinalized(thread_); TypeArguments& args = TypeArguments::ZoneHandle(Z, result_type.arguments()); // A kernel transform for FFI in the front-end ensures that type parameters // do not appear in the type arguments to a any Pointer classes in an FFI // signature. ASSERT(args.IsNull() || args.IsInstantiated()); args = args.Canonicalize(thread_, nullptr); Fragment code; code += Constant(args); code += AllocateObject(TokenPosition::kNoSource, result_class, 1); LocalVariable* pointer = MakeTemporary(); code += LoadLocal(pointer); code += LoadLocal(address); code += UnboxTruncate(kUnboxedFfiIntPtr); code += StoreNativeField(Slot::Pointer_data_field()); code += StoreLocal(TokenPosition::kNoSource, result); code += Drop(); // StoreLocal^ code += Drop(); // address code += LoadLocal(result); return code; } Fragment FlowGraphBuilder::BitCast(Representation from, Representation to) { BitCastInstr* instr = new (Z) BitCastInstr(from, to, Pop()); Push(instr); return Fragment(instr); } Fragment FlowGraphBuilder::WrapTypedDataBaseInCompound( const AbstractType& compound_type) { const auto& compound_sub_class = Class::ZoneHandle(Z, compound_type.type_class()); compound_sub_class.EnsureIsFinalized(thread_); const auto& lib_ffi = Library::Handle(Z, Library::FfiLibrary()); const auto& compound_class = Class::Handle(Z, lib_ffi.LookupClassAllowPrivate(Symbols::Compound())); const auto& compound_typed_data_base = Field::ZoneHandle(Z, compound_class.LookupInstanceFieldAllowPrivate( Symbols::_typedDataBase())); ASSERT(!compound_typed_data_base.IsNull()); Fragment body; LocalVariable* typed_data = MakeTemporary("typed_data_base"); body += AllocateObject(TokenPosition::kNoSource, compound_sub_class, 0); body += LoadLocal(MakeTemporary("compound")); // Duplicate Struct or Union. body += LoadLocal(typed_data); body += StoreInstanceField(compound_typed_data_base, StoreInstanceFieldInstr::Kind::kInitializing); body += DropTempsPreserveTop(1); // Drop TypedData. return body; } Fragment FlowGraphBuilder::LoadTypedDataBaseFromCompound() { const auto& lib_ffi = Library::Handle(Z, Library::FfiLibrary()); const auto& compound_class = Class::Handle(Z, lib_ffi.LookupClassAllowPrivate(Symbols::Compound())); const auto& compound_typed_data_base = Field::ZoneHandle(Z, compound_class.LookupInstanceFieldAllowPrivate( Symbols::_typedDataBase())); ASSERT(!compound_typed_data_base.IsNull()); Fragment body; body += LoadField(compound_typed_data_base, /*calls_initializer=*/false); return body; } Fragment FlowGraphBuilder::CopyFromCompoundToStack( LocalVariable* variable, const GrowableArray<Representation>& representations) { Fragment body; const intptr_t num_defs = representations.length(); int offset_in_bytes = 0; for (intptr_t i = 0; i < num_defs; i++) { body += LoadLocal(variable); body += LoadTypedDataBaseFromCompound(); body += LoadUntagged(compiler::target::Pointer::data_field_offset()); body += IntConstant(offset_in_bytes); const Representation representation = representations[i]; offset_in_bytes += RepresentationUtils::ValueSize(representation); body += LoadIndexedTypedDataUnboxed(representation, /*index_scale=*/1, /*index_unboxed=*/false); } return body; } Fragment FlowGraphBuilder::PopFromStackToTypedDataBase( ZoneGrowableArray<LocalVariable*>* definitions, const GrowableArray<Representation>& representations) { Fragment body; const intptr_t num_defs = representations.length(); ASSERT(definitions->length() == num_defs); LocalVariable* uint8_list = MakeTemporary("uint8_list"); int offset_in_bytes = 0; for (intptr_t i = 0; i < num_defs; i++) { const Representation representation = representations[i]; body += LoadLocal(uint8_list); body += LoadUntagged(compiler::target::TypedDataBase::data_field_offset()); body += IntConstant(offset_in_bytes); body += LoadLocal(definitions->At(i)); body += StoreIndexedTypedDataUnboxed(representation, /*index_scale=*/1, /*index_unboxed=*/false); offset_in_bytes += RepresentationUtils::ValueSize(representation); } body += DropTempsPreserveTop(num_defs); // Drop chunck defs keep TypedData. return body; } static intptr_t chunk_size(intptr_t bytes_left) { ASSERT(bytes_left >= 1); if (bytes_left >= 8 && compiler::target::kWordSize == 8) { return 8; } if (bytes_left >= 4) { return 4; } if (bytes_left >= 2) { return 2; } return 1; } static classid_t typed_data_cid(intptr_t chunk_size) { switch (chunk_size) { case 8: return kTypedDataInt64ArrayCid; case 4: return kTypedDataInt32ArrayCid; case 2: return kTypedDataInt16ArrayCid; case 1: return kTypedDataInt8ArrayCid; } UNREACHABLE(); } Fragment FlowGraphBuilder::CopyFromTypedDataBaseToUnboxedAddress( intptr_t length_in_bytes) { Fragment body; Value* unboxed_address_value = Pop(); LocalVariable* typed_data_base = MakeTemporary("typed_data_base"); Push(unboxed_address_value->definition()); LocalVariable* unboxed_address = MakeTemporary("unboxed_address"); intptr_t offset_in_bytes = 0; while (offset_in_bytes < length_in_bytes) { const intptr_t bytes_left = length_in_bytes - offset_in_bytes; const intptr_t chunk_sizee = chunk_size(bytes_left); const classid_t typed_data_cidd = typed_data_cid(chunk_sizee); body += LoadLocal(typed_data_base); body += LoadUntagged(compiler::target::TypedDataBase::data_field_offset()); body += IntConstant(offset_in_bytes); body += LoadIndexed(typed_data_cidd, /*index_scale=*/1, /*index_unboxed=*/false); LocalVariable* chunk_value = MakeTemporary("chunk_value"); body += LoadLocal(unboxed_address); body += ConvertUnboxedToUntagged(kUnboxedFfiIntPtr); body += IntConstant(offset_in_bytes); body += LoadLocal(chunk_value); body += StoreIndexedTypedData(typed_data_cidd, /*index_scale=*/1, /*index_unboxed=*/false); body += DropTemporary(&chunk_value); offset_in_bytes += chunk_sizee; } ASSERT(offset_in_bytes == length_in_bytes); body += DropTemporary(&unboxed_address); body += DropTemporary(&typed_data_base); return body; } Fragment FlowGraphBuilder::CopyFromUnboxedAddressToTypedDataBase( intptr_t length_in_bytes) { Fragment body; Value* typed_data_base_value = Pop(); LocalVariable* unboxed_address = MakeTemporary("unboxed_address"); Push(typed_data_base_value->definition()); LocalVariable* typed_data_base = MakeTemporary("typed_data_base"); intptr_t offset_in_bytes = 0; while (offset_in_bytes < length_in_bytes) { const intptr_t bytes_left = length_in_bytes - offset_in_bytes; const intptr_t chunk_sizee = chunk_size(bytes_left); const classid_t typed_data_cidd = typed_data_cid(chunk_sizee); body += LoadLocal(unboxed_address); body += ConvertUnboxedToUntagged(kUnboxedFfiIntPtr); body += IntConstant(offset_in_bytes); body += LoadIndexed(typed_data_cidd, /*index_scale=*/1, /*index_unboxed=*/false); LocalVariable* chunk_value = MakeTemporary("chunk_value"); body += LoadLocal(typed_data_base); body += LoadUntagged(compiler::target::TypedDataBase::data_field_offset()); body += IntConstant(offset_in_bytes); body += LoadLocal(chunk_value); body += StoreIndexedTypedData(typed_data_cidd, /*index_scale=*/1, /*index_unboxed=*/false); body += DropTemporary(&chunk_value); offset_in_bytes += chunk_sizee; } ASSERT(offset_in_bytes == length_in_bytes); body += DropTemporary(&typed_data_base); body += DropTemporary(&unboxed_address); return body; } Fragment FlowGraphBuilder::FfiCallConvertCompoundArgumentToNative( LocalVariable* variable, const compiler::ffi::BaseMarshaller& marshaller, intptr_t arg_index) { Fragment body; const auto& native_loc = marshaller.Location(arg_index); if (native_loc.IsStack() || native_loc.IsMultiple()) { // Break struct in pieces to separate IL definitions to pass those // separate definitions into the FFI call. GrowableArray<Representation> representations; marshaller.RepsInFfiCall(arg_index, &representations); body += CopyFromCompoundToStack(variable, representations); } else { ASSERT(native_loc.IsPointerToMemory()); // Only load the typed data, do copying in the FFI call machine code. body += LoadLocal(variable); // User-defined struct. body += LoadTypedDataBaseFromCompound(); } return body; } Fragment FlowGraphBuilder::FfiCallConvertCompoundReturnToDart( const compiler::ffi::BaseMarshaller& marshaller, intptr_t arg_index) { Fragment body; // The typed data is allocated before the FFI call, and is populated in // machine code. So, here, it only has to be wrapped in the struct class. const auto& compound_type = AbstractType::Handle(Z, marshaller.CType(arg_index)); body += WrapTypedDataBaseInCompound(compound_type); return body; } Fragment FlowGraphBuilder::FfiCallbackConvertCompoundArgumentToDart( const compiler::ffi::BaseMarshaller& marshaller, intptr_t arg_index, ZoneGrowableArray<LocalVariable*>* definitions) { const intptr_t length_in_bytes = marshaller.Location(arg_index).payload_type().SizeInBytes(); Fragment body; if ((marshaller.Location(arg_index).IsMultiple() || marshaller.Location(arg_index).IsStack())) { // Allocate and populate a TypedData from the individual NativeParameters. body += IntConstant(length_in_bytes); body += AllocateTypedData(TokenPosition::kNoSource, kTypedDataUint8ArrayCid); GrowableArray<Representation> representations; marshaller.RepsInFfiCall(arg_index, &representations); body += PopFromStackToTypedDataBase(definitions, representations); } else { ASSERT(marshaller.Location(arg_index).IsPointerToMemory()); // Allocate a TypedData and copy contents pointed to by an address into it. LocalVariable* address_of_compound = MakeTemporary("address_of_compound"); body += IntConstant(length_in_bytes); body += AllocateTypedData(TokenPosition::kNoSource, kTypedDataUint8ArrayCid); LocalVariable* typed_data_base = MakeTemporary("typed_data_base"); body += LoadLocal(address_of_compound); body += LoadLocal(typed_data_base); body += CopyFromUnboxedAddressToTypedDataBase(length_in_bytes); body += DropTempsPreserveTop(1); // address_of_compound. } // Wrap typed data in compound class. const auto& compound_type = AbstractType::Handle(Z, marshaller.CType(arg_index)); body += WrapTypedDataBaseInCompound(compound_type); return body; } Fragment FlowGraphBuilder::FfiCallbackConvertCompoundReturnToNative( const compiler::ffi::CallbackMarshaller& marshaller, intptr_t arg_index) { Fragment body; const auto& native_loc = marshaller.Location(arg_index); if (native_loc.IsMultiple()) { // We pass in typed data to native return instruction, and do the copying // in machine code. body += LoadTypedDataBaseFromCompound(); } else { ASSERT(native_loc.IsPointerToMemory()); // We copy the data into the right location in IL. const intptr_t length_in_bytes = marshaller.Location(arg_index).payload_type().SizeInBytes(); body += LoadTypedDataBaseFromCompound(); LocalVariable* typed_data_base = MakeTemporary("typed_data_base"); auto* pointer_to_return = new (Z) NativeParameterInstr(marshaller, compiler::ffi::kResultIndex); Push(pointer_to_return); // Address where return value should be stored. body <<= pointer_to_return; body += UnboxTruncate(kUnboxedFfiIntPtr); LocalVariable* unboxed_address = MakeTemporary("unboxed_address"); body += LoadLocal(typed_data_base); body += LoadLocal(unboxed_address); body += CopyFromTypedDataBaseToUnboxedAddress(length_in_bytes); body += DropTempsPreserveTop(1); // Keep address, drop typed_data_base. } return body; } Fragment FlowGraphBuilder::FfiConvertPrimitiveToDart( const compiler::ffi::BaseMarshaller& marshaller, intptr_t arg_index) { ASSERT(!marshaller.IsCompound(arg_index)); Fragment body; if (marshaller.IsPointer(arg_index)) { body += Box(kUnboxedFfiIntPtr); body += FfiPointerFromAddress( Type::CheckedHandle(Z, marshaller.CType(arg_index))); } else if (marshaller.IsHandle(arg_index)) { body += UnwrapHandle(); } else if (marshaller.IsVoid(arg_index)) { body += Drop(); body += NullConstant(); } else { if (marshaller.RequiresBitCast(arg_index)) { body += BitCast( marshaller.RepInFfiCall(marshaller.FirstDefinitionIndex(arg_index)), marshaller.RepInDart(arg_index)); } body += Box(marshaller.RepInDart(arg_index)); } return body; } Fragment FlowGraphBuilder::FfiConvertPrimitiveToNative( const compiler::ffi::BaseMarshaller& marshaller, intptr_t arg_index, LocalVariable* api_local_scope) { ASSERT(!marshaller.IsCompound(arg_index)); Fragment body; if (marshaller.IsPointer(arg_index)) { // This can only be Pointer, so it is always safe to LoadUntagged. body += LoadUntagged(compiler::target::Pointer::data_field_offset()); body += ConvertUntaggedToUnboxed(kUnboxedFfiIntPtr); } else if (marshaller.IsHandle(arg_index)) { body += WrapHandle(api_local_scope); } else { body += UnboxTruncate(marshaller.RepInDart(arg_index)); } if (marshaller.RequiresBitCast(arg_index)) { body += BitCast( marshaller.RepInDart(arg_index), marshaller.RepInFfiCall(marshaller.FirstDefinitionIndex(arg_index))); } return body; } FlowGraph* FlowGraphBuilder::BuildGraphOfFfiTrampoline( const Function& function) { if (function.FfiCallbackTarget() != Function::null()) { return BuildGraphOfFfiCallback(function); } else { return BuildGraphOfFfiNative(function); } } FlowGraph* FlowGraphBuilder::BuildGraphOfFfiNative(const Function& function) { const intptr_t kClosureParameterOffset = 0; const intptr_t kFirstArgumentParameterOffset = kClosureParameterOffset + 1; graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto normal_entry = BuildFunctionEntry(graph_entry_); graph_entry_->set_normal_entry(normal_entry); PrologueInfo prologue_info(-1, -1); BlockEntryInstr* instruction_cursor = BuildPrologue(normal_entry, &prologue_info); Fragment function_body(instruction_cursor); function_body += CheckStackOverflowInPrologue(function.token_pos()); const auto& marshaller = *new (Z) compiler::ffi::CallMarshaller(Z, function); const bool signature_contains_handles = marshaller.ContainsHandles(); // FFI trampolines are accessed via closures, so non-covariant argument types // and type arguments are either statically checked by the type system or // dynamically checked via dynamic closure call dispatchers. // Null check arguments before we go into the try catch, so that we don't // catch our own null errors. const intptr_t num_args = marshaller.num_args(); for (intptr_t i = 0; i < num_args; i++) { if (marshaller.IsHandle(i)) { continue; } function_body += LoadLocal( parsed_function_->ParameterVariable(kFirstArgumentParameterOffset + i)); // Check for 'null'. // TODO(36780): Mention the param name instead of function reciever. function_body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, marshaller.function_name())); function_body += StoreLocal( TokenPosition::kNoSource, parsed_function_->ParameterVariable(kFirstArgumentParameterOffset + i)); function_body += Drop(); } Fragment body; intptr_t try_handler_index = -1; LocalVariable* api_local_scope = nullptr; if (signature_contains_handles) { // Wrap in Try catch to transition from Native to Generated on a throw from // the dart_api. try_handler_index = AllocateTryIndex(); body += TryCatch(try_handler_index); ++try_depth_; body += EnterHandleScope(); api_local_scope = MakeTemporary("api_local_scope"); } // Allocate typed data before FfiCall and pass it in to ffi call if needed. LocalVariable* typed_data = nullptr; if (marshaller.PassTypedData()) { body += IntConstant(marshaller.TypedDataSizeInBytes()); body += AllocateTypedData(TokenPosition::kNoSource, kTypedDataUint8ArrayCid); typed_data = MakeTemporary(); } // Unbox and push the arguments. for (intptr_t i = 0; i < marshaller.num_args(); i++) { if (marshaller.IsCompound(i)) { body += FfiCallConvertCompoundArgumentToNative( parsed_function_->ParameterVariable(kFirstArgumentParameterOffset + i), marshaller, i); } else { body += LoadLocal(parsed_function_->ParameterVariable( kFirstArgumentParameterOffset + i)); body += FfiConvertPrimitiveToNative(marshaller, i, api_local_scope); } } // Push the function pointer, which is stored (as Pointer object) in the // first slot of the context. body += LoadLocal(parsed_function_->ParameterVariable(kClosureParameterOffset)); body += LoadNativeField(Slot::Closure_context()); body += LoadNativeField(Slot::GetContextVariableSlotFor( thread_, *MakeImplicitClosureScope( Z, Class::Handle(IG->object_store()->ffi_pointer_class())) ->context_variables()[0])); // This can only be Pointer, so it is always safe to LoadUntagged. body += LoadUntagged(compiler::target::Pointer::data_field_offset()); body += ConvertUntaggedToUnboxed(kUnboxedFfiIntPtr); if (marshaller.PassTypedData()) { body += LoadLocal(typed_data); } body += FfiCall(marshaller); for (intptr_t i = 0; i < marshaller.num_args(); i++) { if (marshaller.IsPointer(i)) { body += LoadLocal(parsed_function_->ParameterVariable( kFirstArgumentParameterOffset + i)); body += ReachabilityFence(); } } const intptr_t num_defs = marshaller.NumReturnDefinitions(); ASSERT(num_defs >= 1); auto defs = new (Z) ZoneGrowableArray<LocalVariable*>(Z, num_defs); LocalVariable* def = MakeTemporary(); defs->Add(def); if (marshaller.PassTypedData()) { // Drop call result, typed data with contents is already on the stack. body += Drop(); } if (marshaller.IsCompound(compiler::ffi::kResultIndex)) { body += FfiCallConvertCompoundReturnToDart(marshaller, compiler::ffi::kResultIndex); } else { body += FfiConvertPrimitiveToDart(marshaller, compiler::ffi::kResultIndex); } if (signature_contains_handles) { body += DropTempsPreserveTop(1); // Drop api_local_scope. body += ExitHandleScope(); } body += Return(TokenPosition::kNoSource); if (signature_contains_handles) { --try_depth_; } function_body += body; if (signature_contains_handles) { ++catch_depth_; Fragment catch_body = CatchBlockEntry(Array::empty_array(), try_handler_index, /*needs_stacktrace=*/true, /*is_synthesized=*/true); // TODO(41984): If we want to pass in the handle scope, move it out // of the try catch. catch_body += ExitHandleScope(); catch_body += LoadLocal(CurrentException()); catch_body += LoadLocal(CurrentStackTrace()); catch_body += RethrowException(TokenPosition::kNoSource, try_handler_index); --catch_depth_; } return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } FlowGraph* FlowGraphBuilder::BuildGraphOfFfiCallback(const Function& function) { const auto& marshaller = *new (Z) compiler::ffi::CallbackMarshaller(Z, function); graph_entry_ = new (Z) GraphEntryInstr(*parsed_function_, Compiler::kNoOSRDeoptId); auto* const native_entry = new (Z) NativeEntryInstr( marshaller, graph_entry_, AllocateBlockId(), CurrentTryIndex(), GetNextDeoptId(), function.FfiCallbackId()); graph_entry_->set_normal_entry(native_entry); Fragment function_body(native_entry); function_body += CheckStackOverflowInPrologue(function.token_pos()); // Wrap the entire method in a big try/catch. This is important to ensure that // the VM does not crash if the callback throws an exception. const intptr_t try_handler_index = AllocateTryIndex(); Fragment body = TryCatch(try_handler_index); ++try_depth_; // Box and push the arguments. for (intptr_t i = 0; i < marshaller.num_args(); i++) { const intptr_t num_defs = marshaller.NumDefinitions(i); auto defs = new (Z) ZoneGrowableArray<LocalVariable*>(Z, num_defs); for (intptr_t j = 0; j < num_defs; j++) { const intptr_t def_index = marshaller.DefinitionIndex(j, i); auto* parameter = new (Z) NativeParameterInstr(marshaller, def_index); Push(parameter); body <<= parameter; LocalVariable* def = MakeTemporary(); defs->Add(def); } if (marshaller.IsCompound(i)) { body += FfiCallbackConvertCompoundArgumentToDart(marshaller, i, defs); } else { body += FfiConvertPrimitiveToDart(marshaller, i); } } // Call the target. // // TODO(36748): Determine the hot-reload semantics of callbacks and update the // rebind-rule accordingly. body += StaticCall(TokenPosition::kNoSource, Function::ZoneHandle(Z, function.FfiCallbackTarget()), marshaller.num_args(), Array::empty_array(), ICData::kNoRebind); if (marshaller.IsVoid(compiler::ffi::kResultIndex)) { body += Drop(); body += IntConstant(0); } else if (!marshaller.IsHandle(compiler::ffi::kResultIndex)) { body += CheckNullOptimized(TokenPosition::kNoSource, String::ZoneHandle(Z, marshaller.function_name())); } if (marshaller.IsCompound(compiler::ffi::kResultIndex)) { body += FfiCallbackConvertCompoundReturnToNative( marshaller, compiler::ffi::kResultIndex); } else { body += FfiConvertPrimitiveToNative(marshaller, compiler::ffi::kResultIndex, /*api_local_scope=*/nullptr); } body += NativeReturn(marshaller); --try_depth_; function_body += body; ++catch_depth_; Fragment catch_body = CatchBlockEntry(Array::empty_array(), try_handler_index, /*needs_stacktrace=*/false, /*is_synthesized=*/true); // Return the "exceptional return" value given in 'fromFunction'. // // For pointer and void return types, the exceptional return is always null -- // return 0 instead. if (marshaller.IsPointer(compiler::ffi::kResultIndex) || marshaller.IsVoid(compiler::ffi::kResultIndex)) { ASSERT(function.FfiCallbackExceptionalReturn() == Object::null()); catch_body += IntConstant(0); catch_body += UnboxTruncate(kUnboxedFfiIntPtr); } else if (marshaller.IsHandle(compiler::ffi::kResultIndex)) { catch_body += UnhandledException(); catch_body += FfiConvertPrimitiveToNative(marshaller, compiler::ffi::kResultIndex, /*api_local_scope=*/nullptr); } else if (marshaller.IsCompound(compiler::ffi::kResultIndex)) { ASSERT(function.FfiCallbackExceptionalReturn() == Object::null()); // Manufacture empty result. const intptr_t size = Utils::RoundUp(marshaller.Location(compiler::ffi::kResultIndex) .payload_type() .SizeInBytes(), compiler::target::kWordSize); catch_body += IntConstant(size); catch_body += AllocateTypedData(TokenPosition::kNoSource, kTypedDataUint8ArrayCid); catch_body += WrapTypedDataBaseInCompound( AbstractType::Handle(Z, marshaller.CType(compiler::ffi::kResultIndex))); catch_body += FfiCallbackConvertCompoundReturnToNative( marshaller, compiler::ffi::kResultIndex); } else { catch_body += Constant( Instance::ZoneHandle(Z, function.FfiCallbackExceptionalReturn())); catch_body += FfiConvertPrimitiveToNative(marshaller, compiler::ffi::kResultIndex, /*api_local_scope=*/nullptr); } catch_body += NativeReturn(marshaller); --catch_depth_; PrologueInfo prologue_info(-1, -1); return new (Z) FlowGraph(*parsed_function_, graph_entry_, last_used_block_id_, prologue_info); } void FlowGraphBuilder::SetCurrentTryCatchBlock(TryCatchBlock* try_catch_block) { try_catch_block_ = try_catch_block; SetCurrentTryIndex(try_catch_block == nullptr ? kInvalidTryIndex : try_catch_block->try_index()); } bool FlowGraphBuilder::NeedsNullAssertion(const AbstractType& type) { if (!type.IsNonNullable()) { return false; } if (type.IsTypeParameter()) { return NeedsNullAssertion( AbstractType::Handle(Z, TypeParameter::Cast(type).bound())); } if (type.IsFutureOrType()) { return NeedsNullAssertion(AbstractType::Handle(Z, type.UnwrapFutureOr())); } return true; } Fragment FlowGraphBuilder::NullAssertion(LocalVariable* variable) { Fragment code; if (!NeedsNullAssertion(variable->type())) { return code; } TargetEntryInstr* then; TargetEntryInstr* otherwise; code += LoadLocal(variable); code += NullConstant(); code += BranchIfEqual(&then, &otherwise); const Script& script = Script::Handle(Z, parsed_function_->function().script()); intptr_t line = -1; intptr_t column = -1; script.GetTokenLocation(variable->token_pos(), &line, &column); // Build equivalent of `throw _AssertionError._throwNewNullAssertion(name)` // expression. We build throw (even through _throwNewNullAssertion already // throws) because call is not a valid last instruction for the block. // Blocks can only terminate with explicit control flow instructions // (Branch, Goto, Return or Throw). Fragment null_code(then); null_code += Constant(variable->name()); null_code += IntConstant(line); null_code += IntConstant(column); null_code += StaticCall(variable->token_pos(), ThrowNewNullAssertionFunction(), 3, ICData::kStatic); null_code += ThrowException(TokenPosition::kNoSource); null_code += Drop(); return Fragment(code.entry, otherwise); } Fragment FlowGraphBuilder::BuildNullAssertions() { Fragment code; if (IG->null_safety() || !IG->asserts() || !FLAG_null_assertions) { return code; } const Function& dart_function = parsed_function_->function(); for (intptr_t i = dart_function.NumImplicitParameters(), n = dart_function.NumParameters(); i < n; ++i) { LocalVariable* variable = parsed_function_->ParameterVariable(i); code += NullAssertion(variable); } return code; } const Function& FlowGraphBuilder::ThrowNewNullAssertionFunction() { if (throw_new_null_assertion_.IsNull()) { const Class& klass = Class::ZoneHandle( Z, Library::LookupCoreClass(Symbols::AssertionError())); ASSERT(!klass.IsNull()); const auto& error = klass.EnsureIsFinalized(H.thread()); ASSERT(error == Error::null()); throw_new_null_assertion_ = klass.LookupStaticFunctionAllowPrivate( Symbols::ThrowNewNullAssertion()); ASSERT(!throw_new_null_assertion_.IsNull()); } return throw_new_null_assertion_; } const Function& FlowGraphBuilder::PrependTypeArgumentsFunction() { if (prepend_type_arguments_.IsNull()) { const auto& dart_internal = Library::Handle(Z, Library::InternalLibrary()); prepend_type_arguments_ = dart_internal.LookupFunctionAllowPrivate( Symbols::PrependTypeArguments()); ASSERT(!prepend_type_arguments_.IsNull()); } return prepend_type_arguments_; } } // namespace kernel } // namespace dart
// App.cpp : Defines the entry point for the application. // #include "App.h" // NOMINMAX to prevent compilation errors with bgfx #define NOMINMAX #include <Windows.h> #undef NOMINMAX #include <Windowsx.h> #include <Shlwapi.h> #include <filesystem> #include <algorithm> #include <Shared/TestUtils.h> #include <Babylon/AppRuntime.h> #include <Babylon/Graphics.h> #include <Babylon/ScriptLoader.h> #include <Babylon/Plugins/NativeEngine.h> #include <Babylon/Plugins/NativeXr.h> #include <Babylon/Polyfills/Console.h> #include <Babylon/Polyfills/Window.h> #include <Babylon/Polyfills/XMLHttpRequest.h> #include <Babylon/Polyfills/Canvas.h> #include <iostream> #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance WCHAR szTitle[MAX_LOADSTRING]; // The title bar text WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name std::unique_ptr<Babylon::Graphics> graphics{}; std::unique_ptr<Babylon::AppRuntime> runtime{}; // 600, 400 mandatory size for CI tests static const int TEST_WIDTH = 600; static const int TEST_HEIGHT = 400; // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); namespace { void Uninitialize() { if (graphics) { graphics->FinishRenderingCurrentFrame(); } runtime.reset(); graphics.reset(); } void Initialize(HWND hWnd) { Babylon::WindowConfiguration graphicsConfig{}; graphicsConfig.WindowPtr = hWnd; graphicsConfig.Width = static_cast<size_t>(TEST_WIDTH); graphicsConfig.Height = static_cast<size_t>(TEST_HEIGHT); graphics = Babylon::Graphics::CreateGraphics(graphicsConfig); graphics->SetDiagnosticOutput([](const char* outputString) { printf("%s", outputString); fflush(stdout); }); graphics->StartRenderingCurrentFrame(); runtime = std::make_unique<Babylon::AppRuntime>(); // Initialize console plugin. runtime->Dispatch([hWnd](Napi::Env env) { graphics->AddToJavaScript(env); Babylon::Polyfills::Console::Initialize(env, [](const char* message, auto) { OutputDebugStringA(message); printf("%s", message); fflush(stdout); }); Babylon::Polyfills::Window::Initialize(env); Babylon::Polyfills::XMLHttpRequest::Initialize(env); Babylon::Polyfills::Canvas::Initialize(env); Babylon::Plugins::NativeEngine::Initialize(env); Babylon::Plugins::NativeXr::Initialize(env); Babylon::TestUtils::CreateInstance(env, hWnd); }); Babylon::ScriptLoader loader{ *runtime }; loader.LoadScript("app:///Scripts/babylon.max.js"); loader.LoadScript("app:///Scripts/babylonjs.loaders.js"); loader.LoadScript("app:///Scripts/babylonjs.materials.js"); loader.LoadScript("app:///Scripts/babylon.gui.js"); loader.LoadScript("app:///Scripts/validation_native.js"); } } int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_VALIDATIONTESTSWIN32, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_VALIDATIONTESTSWIN32)); MSG msg{}; // Main message loop: while (msg.message != WM_QUIT) { if (graphics) { graphics->FinishRenderingCurrentFrame(); graphics->StartRenderingCurrentFrame(); } if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) && msg.message != WM_QUIT) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_VALIDATIONTESTSWIN32)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = 0; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Store instance handle in our global variable HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, TEST_WIDTH, TEST_HEIGHT, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); Initialize(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_SIZE: { if (graphics) { size_t width = static_cast<size_t>(LOWORD(lParam)); size_t height = static_cast<size_t>(HIWORD(lParam)); graphics->UpdateSize(width, height); } break; } case WM_DESTROY: { Uninitialize(); PostQuitMessage(errorCode); break; } default: { return DefWindowProc(hWnd, message, wParam, lParam); } } return 0; }
#include "ArTrieNode.h"
#include <iostream> #include <forward_list> #include <list> using std::cout; using std::endl; using std::forward_list; using std::list; int main() { forward_list<int> fi = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; list<int> li = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto fiter_prev = fi.before_begin(); auto fiter = fi.begin(); auto liter = li.begin(); while(fiter != fi.end()) { if(*fiter % 2) { // for iterator of a forward_list, we have to use insert_after, which // returns an iterator to the last inserted element fi.insert_after(fiter_prev, *fiter); fiter_prev = fiter; ++fiter; } else { // erase_after returns an iterator to the element after the one deleted // so just assigning it to fiter is okay, but we have to use fiter_prev // as argument fiter = fi.erase_after(fiter_prev); } } while(liter != li.end()) { if(*liter % 2) { li.insert(liter, *liter); // we cannot use += for iterator of a list, but using after insert, // the iterator keeps valid, so we can use liter directly ++liter; } else { liter = li.erase(liter); } } for(auto &i : fi) cout << i << " "; cout << endl; for(auto &i : li) cout << i << " "; cout << endl; return 0; }
#ifndef NCBI_WIN_HOOK__HPP #define NCBI_WIN_HOOK__HPP /* $Id: ncbi_win_hook.hpp 403742 2013-06-18 15:26:09Z grichenk $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Sergey Sikorskiy * * File Description: Windows DLL function hooking * */ /** @addtogroup WinHook * * @{ */ #if defined(NCBI_OS_MSWIN) #include <corelib/ncbi_safe_static.hpp> #include <process.h> #include <Tlhelp32.h> #include <vector> BEGIN_NCBI_SCOPE namespace NWinHook { /////////////////////////////////////////////////////////////////////////////// class NCBI_DBAPIDRIVER_EXPORT CWinHookException : public CCoreException { public: enum EErrCode { eDbghelp, eDisabled }; /// Translate from the error code value to its string representation. virtual const char* GetErrCodeString(void) const; // Standard exception boilerplate code. NCBI_EXCEPTION_DEFAULT(CWinHookException, CCoreException); }; /////////////////////////////////////////////////////////////////////////////// /// class CHookedFunctions /// class CHookedFunction; int my_stricmp(const char* left, const char* right); // !!! Not thred-safe class !!! class CHookedFunctions { public: CHookedFunctions(void); ~CHookedFunctions(void); public: /// Return the address of an CHookedFunction object CRef<CHookedFunction> GetHookedFunction( PCSTR pszCalleeModName, PCSTR pszFuncName ) const; /// Return the address of an CHookedFunction object CRef<CHookedFunction> GetHookedFunction( HMODULE hmod, PCSTR pszFuncName ) const; /// Add a new object to the container BOOL AddHook(const CRef<CHookedFunction> pHook); /// Remove exising object pointer from the container BOOL RemoveHook(const CRef<CHookedFunction> pHook); void UnHookAllFuncs(void); bool HaveHookedFunctions(void) const { // return(m_FunctionList.size() > 0); size_t num = 0; ITERATE(TModuleList, it, m_ModuleList) { num += it->second.size(); } return (num > 0); } private: /// Return the name of the function from EAT by its ordinal value BOOL x_GetFunctionNameFromExportSection( HMODULE hmodOriginal, DWORD dwFuncOrdinalNum, PSTR pszFuncName ) const; /// Return the name of the function by its ordinal value void x_GetFunctionNameByOrdinal( PCSTR pszCalleeModName, DWORD dwFuncOrdinalNum, PSTR pszFuncName ) const; void x_GetFunctionNameByOrdinal( HMODULE hmodOriginal, DWORD dwFuncOrdinalNum, PSTR pszFuncName ) const; private: struct SNocaseCmp { bool operator()(const string& x, const string& y) const { return my_stricmp(x.c_str(), y.c_str()) < 0; } }; typedef map<string, CRef<CHookedFunction>, SNocaseCmp> TFunctionList; typedef map<void*, TFunctionList> TModuleList; typedef map<string, TFunctionList, SNocaseCmp> TModuleNameList; // TFunctionList m_FunctionList; TModuleList m_ModuleList; TModuleNameList m_ModuleNameList; // Because of CApiHookMgr::HackModuleOnLoad friend class CApiHookMgr; }; /////////////////////////////////////////////////////////////////////////////// /// class CApiHookMgr /// class CApiHookMgr { private: CApiHookMgr(void); ~CApiHookMgr(void); void operator =(const CApiHookMgr&); public: static CApiHookMgr& GetInstance(void); /// Hook up an API BOOL HookImport(PCSTR pszCalleeModName, PCSTR pszFuncName, PROC pfnHook ); /// Restore hooked up API function BOOL UnHookImport(PCSTR pszCalleeModName, PCSTR pszFuncName ); /// Used when a DLL is newly loaded after hooking a function void WINAPI HackModuleOnLoad(HMODULE hmod, DWORD dwFlags ); /// Return the address of an CHookedFunction object /// Protected version. CRef<CHookedFunction> GetHookedFunction(HMODULE hmod, PCSTR pszFuncName ) const; /// Indicates whether there is hooked function bool HaveHookedFunctions(void) const; private: /// Hook all needed system functions in order to trap loading libraries BOOL x_HookSystemFuncs(void); /// Unhook all functions and restore original ones void x_UnHookAllFuncs(void); /// Used to trap events when DLLs are loaded static HMODULE WINAPI MyLoadLibraryA(PCSTR pszModuleName); /// Used to trap events when DLLs are loaded static HMODULE WINAPI MyLoadLibraryW(PCWSTR pszModuleName); /// Used to trap events when DLLs are loaded static HMODULE WINAPI MyLoadLibraryExA(PCSTR pszModuleName, HANDLE hFile, DWORD dwFlags ); /// Used to trap events when DLLs are loaded static HMODULE WINAPI MyLoadLibraryExW(PCWSTR pszModuleName, HANDLE hFile, DWORD dwFlags ); /// Returns address of replacement function if hooked function is /// requested static FARPROC WINAPI MyGetProcAddress(HMODULE hmod, PCSTR pszProcName ); /// Returns original address of the API function static FARPROC WINAPI xs_GetProcAddressWindows( HMODULE hmod, PCSTR pszProcName ); /// Add a newly intercepted function to the container BOOL x_AddHook(PCSTR pszCalleeModName, PCSTR pszFuncName, PROC pfnOrig, PROC pfnHook ); /// Remove intercepted function from the container BOOL x_RemoveHook(PCSTR pszCalleeModName, PCSTR pszFuncName ); mutable CFastMutex m_Mutex; /// Container keeps track of all hacked functions CHookedFunctions m_pHookedFunctions; /// Determines whether all system functions has been successfuly hacked BOOL m_bSystemFuncsHooked; friend class CSafeStatic_Allocator<CApiHookMgr>; }; class NCBI_DBAPIDRIVER_EXPORT COnExitProcess { public: typedef void (*TFunct) (void); static COnExitProcess& Instance(void); // Return true in case of success. bool Add(TFunct funct); void Remove(TFunct funct); void ClearAll(void); private: COnExitProcess(void); ~COnExitProcess(void); // Hook function prototype static void WINAPI xs_ExitProcess(UINT uExitCode); private: typedef vector<TFunct> TRegistry; CFastMutex m_Mutex; TRegistry m_Registry; bool m_Hooked; friend class CSafeStatic_Allocator<COnExitProcess>; }; } END_NCBI_SCOPE #endif // NCBI_OS_MSWIN /* @} */ #endif // NCBI_WIN_HOOK__HPP
/* * Copyright (c) 2003-2021 Rony Shapiro <ronys@pwsafe.org>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ /** \file GuiInfo.cpp * */ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include "wx/wx.h" #endif #ifdef __WXMSW__ #include <wx/msw/msvcrt.h> #endif #include "GuiInfo.h" #include "GridCtrl.h" #include "TreeCtrl.h" #include "PasswordSafeFrame.h" void GuiInfo::Save(PasswordSafeFrame* frame) { SaveTreeViewInfo(frame->m_tree); SaveGridViewInfo(frame->m_grid); } void GuiInfo::Restore(PasswordSafeFrame* frame) { RestoreTreeViewInfo(frame->m_tree); RestoreGridViewInfo(frame->m_grid); } void CollectExpandedNodes(TreeCtrl* tree, wxTreeItemId root, wxArrayString& expanded) { if ( !tree || tree->GetCount() == 0 ) return; wxTreeItemIdValue cookie; for( wxTreeItemId id = tree->GetFirstChild(root, cookie); id.IsOk(); id = tree->GetNextChild(root, cookie)) { if (tree->ItemHasChildren(id) && tree->IsExpanded(id)) { expanded.Add(tree->GetItemGroup(id)); CollectExpandedNodes(tree, id, expanded); } } } void GuiInfo::SaveTreeViewInfo(TreeCtrl* tree) { //save the first visible item wxTreeItemId treeItem = tree->GetFirstVisibleItem(); if (treeItem.IsOk() && treeItem != tree->GetRootItem()) { CItemData* item = tree->GetItem(treeItem); if (item) { m_treeTop = item->GetUUID(); } else if (tree->ItemIsGroup(treeItem)) { m_treeTop = tree->GetItemGroup(treeItem); } else { m_treeTop.Clear(); // The following can happen after UNDO of XML Import - remove FAIL_MSG to do not stop in case of the problem... // wxFAIL_MSG(wxString(wxT("Tree item \'")) << tree->GetItemText(treeItem) << wxT("\' found with no children and no CItemData")); } } else { m_treeTop.Clear(); } m_expanded.Empty(); //find out all the expanded groups in a depth-first manner CollectExpandedNodes(tree, tree->GetRootItem(), m_expanded); //save the selected item wxTreeItemId selection = tree->GetSelection(); if (selection.IsOk() && selection != tree->GetRootItem()) { if(tree->ItemIsGroup(selection)) { m_treeSelection = tree->GetItemGroup(selection); const wxString selectionStr = m_treeSelection; wxASSERT(!selectionStr.IsEmpty()); } else { CItemData* item = tree->GetItem(selection); if (item) { m_treeSelection = item->GetUUID(); } else { m_treeSelection.Clear(); } } } else { m_treeSelection.Clear(); } } void GuiInfo::SaveGridViewInfo(GridCtrl* grid) { //has the grid been initialized? if (grid->GetNumItems() == 0) return; const int row = grid->YToRow(0); if (row != wxNOT_FOUND) { CItemData* item = grid->GetItem(row); if (item) { m_gridTop = item->GetUUID(); } else { wxFAIL_MSG(wxString(wxT("Top grid row ")) << row << wxT(" has no CItemData attached")); m_gridTop = pws_os::CUUID::NullUUID(); } } else { m_gridTop = pws_os::CUUID::NullUUID(); } const int selection = grid->GetGridCursorRow(); if (selection != wxNOT_FOUND) { CItemData* item = grid->GetItem(selection); if (item) { m_gridSelection = item->GetUUID(); } else { wxFAIL_MSG(wxString(wxT("Selected grid row ")) << selection << wxT(" has no CItemData attached")); m_gridSelection = pws_os::CUUID::NullUUID(); } } else { m_gridSelection = pws_os::CUUID::NullUUID(); } } void GuiInfo::RestoreGridViewInfo(GridCtrl* grid) { const int top = grid->FindItemRow(m_gridTop); if (top != wxNOT_FOUND) grid->MakeCellVisible(top, 0); const int selection = grid->FindItemRow(m_gridSelection); if (selection != wxNOT_FOUND) { #if wxCHECK_VERSION(2, 9, 0) grid->GoToCell(selection, 0); #else grid->MakeCellVisible(selection, 0); grid->SetGridCursor(selection, 0); #endif grid->SelectRow(selection); } } template <class TreeFunc> void RestoreTreeItem(TreeCtrl* tree, const string_or_uuid& val, TreeFunc func) { wxTreeItemId id; switch(val.Type()) { case string_or_uuid::ItemType::NORMAL: id = tree->TreeCtrlBase::Find(static_cast<pws_os::CUUID> (val)); break; case string_or_uuid::ItemType::GROUP: id = tree->Find(static_cast<wxString>(val), tree->GetRootItem()); break; default: break; } if (id.IsOk()) func(tree, id); } struct SelectItem { void operator()(TreeCtrl* tree, const wxTreeItemId& id) { tree->wxTreeCtrl::SelectItem(id, true); } }; struct BringItemToTop { //best I can do right now to bring it to top void operator()(TreeCtrl* tree, const wxTreeItemId& id) { tree->ScrollTo(id); } }; void GuiInfo::RestoreTreeViewInfo(TreeCtrl* tree) { // We do this first to ensure that item selection and scrolling an item to top are not wasted by this for (size_t idx = 0; idx < m_expanded.Count(); ++idx) { wxTreeItemId group = tree->Find(m_expanded[idx], tree->GetRootItem()); if (group.IsOk()) { tree->Expand(group); } else { // It is possible that the group with single item was deleted when item was moved to another group // We need to prevent that from happening. But for now, it will assert too much wxLogDebug( wxString(wxT("Could not find group \"")) << m_expanded[idx] << wxT("\" to expand") ); } } // Then restore the "Top" item RestoreTreeItem(tree, m_treeTop, BringItemToTop()); // Finally select the previously "selected" item RestoreTreeItem(tree, m_treeSelection, SelectItem()); }
#include "Rand.h" std::mt19937 generator = std::mt19937(uint(time(NULL))); //Uniform Random Floating Point Number float GetDistribution(std::uniform_real_distribution<float> distro) { return distro(generator); } //Uniform Random Integer int GetDistribution(std::uniform_int_distribution<int> distro) { return distro(generator); } //Normal Random Floating Point Number float GetDistribution(std::normal_distribution<float> distro) { return distro(generator); }
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "common/base/Base.h" #include "common/charset/Charset.h" #include "common/expression/ConstantExpression.h" #include "parser/MaintainSentences.h" #include "service/GraphFlags.h" #include "planner/plan/Admin.h" #include "planner/plan/Maintain.h" #include "planner/plan/Query.h" #include "service/GraphFlags.h" #include "util/IndexUtil.h" #include "util/SchemaUtil.h" #include "util/ExpressionUtils.h" #include "validator/MaintainValidator.h" namespace nebula { namespace graph { Status SchemaValidator::validateColumns(const std::vector<ColumnSpecification *> &columnSpecs, meta::cpp2::Schema &schema) { auto status = Status::OK(); std::unordered_set<std::string> nameSet; for (auto &spec : columnSpecs) { if (nameSet.find(*spec->name()) != nameSet.end()) { return Status::SemanticError("Duplicate column name `%s'", spec->name()->c_str()); } nameSet.emplace(*spec->name()); meta::cpp2::ColumnDef column; auto type = spec->type(); column.set_name(*spec->name()); column.type.set_type(type); if (meta::cpp2::PropertyType::FIXED_STRING == type) { column.type.set_type_length(spec->typeLen()); } for (const auto &property : spec->properties()->properties()) { if (property->isNullable()) { column.set_nullable(property->nullable()); } else if (property->isDefaultValue()) { if (!evaluableExpr(property->defaultValue())) { return Status::SemanticError("Wrong default value experssion `%s'", property->defaultValue()->toString().c_str()); } auto *defaultValueExpr = property->defaultValue(); // some expression is evaluable but not pure so only fold instead of eval here column.set_default_value( ExpressionUtils::foldConstantExpr(defaultValueExpr)->encode()); } else if (property->isComment()) { column.set_comment(*DCHECK_NOTNULL(property->comment())); } } if (!column.nullable_ref().has_value()) { column.set_nullable(true); } schema.columns_ref().value().emplace_back(std::move(column)); } return Status::OK(); } Status CreateTagValidator::validateImpl() { auto sentence = static_cast<CreateTagSentence *>(sentence_); name_ = *sentence->name(); ifNotExist_ = sentence->isIfNotExist(); // Check the validateContext has the same name schema auto pro = vctx_->getSchema(name_); if (pro != nullptr) { return Status::SemanticError("Has the same name `%s' in the SequentialSentences", name_.c_str()); } NG_RETURN_IF_ERROR(validateColumns(sentence->columnSpecs(), schema_)); NG_RETURN_IF_ERROR(SchemaUtil::validateProps(sentence->getSchemaProps(), schema_)); // Save the schema in validateContext auto schemaPro = SchemaUtil::generateSchemaProvider(0, schema_); vctx_->addSchema(name_, schemaPro); return Status::OK(); } Status CreateTagValidator::toPlan() { auto *plan = qctx_->plan(); auto doNode = CreateTag::make(qctx_, plan->root(), std::move(name_), std::move(schema_), ifNotExist_); root_ = doNode; tail_ = root_; return Status::OK(); } Status CreateEdgeValidator::validateImpl() { auto sentence = static_cast<CreateEdgeSentence *>(sentence_); auto status = Status::OK(); name_ = *sentence->name(); ifNotExist_ = sentence->isIfNotExist(); // Check the validateContext has the same name schema auto pro = vctx_->getSchema(name_); if (pro != nullptr) { return Status::SemanticError("Has the same name `%s' in the SequentialSentences", name_.c_str()); } NG_RETURN_IF_ERROR(validateColumns(sentence->columnSpecs(), schema_)); NG_RETURN_IF_ERROR(SchemaUtil::validateProps(sentence->getSchemaProps(), schema_)); // Save the schema in validateContext auto schemaPro = SchemaUtil::generateSchemaProvider(0, schema_); vctx_->addSchema(name_, schemaPro); return Status::OK(); } Status CreateEdgeValidator::toPlan() { auto *plan = qctx_->plan(); auto doNode = CreateEdge::make(qctx_, plan->root(), std::move(name_), std::move(schema_), ifNotExist_); root_ = doNode; tail_ = root_; return Status::OK(); } Status DescTagValidator::validateImpl() { return Status::OK(); } Status DescTagValidator::toPlan() { auto sentence = static_cast<DescribeTagSentence *>(sentence_); auto name = *sentence->name(); auto doNode = DescTag::make(qctx_, nullptr, std::move(name)); root_ = doNode; tail_ = root_; return Status::OK(); } Status DescEdgeValidator::validateImpl() { return Status::OK(); } Status DescEdgeValidator::toPlan() { auto sentence = static_cast<DescribeEdgeSentence *>(sentence_); auto name = *sentence->name(); auto doNode = DescEdge::make(qctx_, nullptr, std::move(name)); root_ = doNode; tail_ = root_; return Status::OK(); } Status AlterValidator::alterSchema(const std::vector<AlterSchemaOptItem *> &schemaOpts, const std::vector<SchemaPropItem *> &schemaProps) { for (auto &schemaOpt : schemaOpts) { meta::cpp2::AlterSchemaItem schemaItem; auto opType = schemaOpt->toType(); schemaItem.set_op(opType); meta::cpp2::Schema schema; if (opType == meta::cpp2::AlterSchemaOp::DROP) { const auto &colNames = schemaOpt->columnNames(); for (auto &colName : colNames) { meta::cpp2::ColumnDef column; column.name = *colName; schema.columns_ref().value().emplace_back(std::move(column)); } } else { const auto &specs = schemaOpt->columnSpecs(); NG_LOG_AND_RETURN_IF_ERROR(validateColumns(specs, schema)); } schemaItem.set_schema(std::move(schema)); schemaItems_.emplace_back(std::move(schemaItem)); } for (auto &schemaProp : schemaProps) { auto propType = schemaProp->getPropType(); StatusOr<int64_t> retInt; StatusOr<std::string> retStr; int ttlDuration; switch (propType) { case SchemaPropItem::TTL_DURATION: retInt = schemaProp->getTtlDuration(); NG_RETURN_IF_ERROR(retInt); ttlDuration = retInt.value(); schemaProp_.set_ttl_duration(ttlDuration); break; case SchemaPropItem::TTL_COL: // Check the legality of the column in meta retStr = schemaProp->getTtlCol(); NG_RETURN_IF_ERROR(retStr); schemaProp_.set_ttl_col(retStr.value()); break; case SchemaPropItem::COMMENT: // Check the legality of the column in meta retStr = schemaProp->getComment(); NG_RETURN_IF_ERROR(retStr); schemaProp_.set_comment(retStr.value()); break; default: return Status::SemanticError("Property type not support"); } } return Status::OK(); } Status AlterTagValidator::validateImpl() { auto sentence = static_cast<AlterTagSentence *>(sentence_); name_ = *sentence->name(); return alterSchema(sentence->getSchemaOpts(), sentence->getSchemaProps()); } Status AlterTagValidator::toPlan() { auto *doNode = AlterTag::make(qctx_, nullptr, vctx_->whichSpace().id, std::move(name_), std::move(schemaItems_), std::move(schemaProp_)); root_ = doNode; tail_ = root_; return Status::OK(); } Status AlterEdgeValidator::validateImpl() { auto sentence = static_cast<AlterEdgeSentence *>(sentence_); name_ = *sentence->name(); return alterSchema(sentence->getSchemaOpts(), sentence->getSchemaProps()); } Status AlterEdgeValidator::toPlan() { auto *doNode = AlterEdge::make(qctx_, nullptr, vctx_->whichSpace().id, std::move(name_), std::move(schemaItems_), std::move(schemaProp_)); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowTagsValidator::validateImpl() { return Status::OK(); } Status ShowTagsValidator::toPlan() { auto *doNode = ShowTags::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowEdgesValidator::validateImpl() { return Status::OK(); } Status ShowEdgesValidator::toPlan() { auto *doNode = ShowEdges::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowCreateTagValidator::validateImpl() { return Status::OK(); } Status ShowCreateTagValidator::toPlan() { auto sentence = static_cast<ShowCreateTagSentence *>(sentence_); auto *doNode = ShowCreateTag::make(qctx_, nullptr, *sentence->name()); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowCreateEdgeValidator::validateImpl() { return Status::OK(); } Status ShowCreateEdgeValidator::toPlan() { auto sentence = static_cast<ShowCreateEdgeSentence *>(sentence_); auto *doNode = ShowCreateEdge::make(qctx_, nullptr, *sentence->name()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropTagValidator::validateImpl() { return Status::OK(); } Status DropTagValidator::toPlan() { auto sentence = static_cast<DropTagSentence *>(sentence_); auto *doNode = DropTag::make(qctx_, nullptr, *sentence->name(), sentence->isIfExists()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropEdgeValidator::validateImpl() { return Status::OK(); } Status DropEdgeValidator::toPlan() { auto sentence = static_cast<DropEdgeSentence *>(sentence_); auto *doNode = DropEdge::make(qctx_, nullptr, *sentence->name(), sentence->isIfExists()); root_ = doNode; tail_ = root_; return Status::OK(); } Status CreateTagIndexValidator::validateImpl() { auto sentence = static_cast<CreateTagIndexSentence*>(sentence_); name_ = *sentence->tagName(); index_ = *sentence->indexName(); fields_ = sentence->fields(); ifNotExist_ = sentence->isIfNotExist(); // TODO(darion) Save the index return Status::OK(); } Status CreateTagIndexValidator::toPlan() { auto sentence = static_cast<CreateTagIndexSentence*>(sentence_); auto *doNode = CreateTagIndex::make(qctx_, nullptr, *sentence->tagName(), *sentence->indexName(), sentence->fields(), sentence->isIfNotExist(), sentence->comment()); root_ = doNode; tail_ = root_; return Status::OK(); } Status CreateEdgeIndexValidator::validateImpl() { auto sentence = static_cast<CreateEdgeIndexSentence*>(sentence_); name_ = *sentence->edgeName(); index_ = *sentence->indexName(); fields_ = sentence->fields(); ifNotExist_ = sentence->isIfNotExist(); // TODO(darion) Save the index return Status::OK(); } Status CreateEdgeIndexValidator::toPlan() { auto sentence = static_cast<CreateEdgeIndexSentence*>(sentence_); auto *doNode = CreateEdgeIndex::make(qctx_, nullptr, *sentence->edgeName(), *sentence->indexName(), sentence->fields(), sentence->isIfNotExist(), sentence->comment()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropTagIndexValidator::validateImpl() { auto sentence = static_cast<DropTagIndexSentence *>(sentence_); indexName_ = *sentence->indexName(); ifExist_ = sentence->isIfExists(); return Status::OK(); } Status DropTagIndexValidator::toPlan() { auto *doNode = DropTagIndex::make(qctx_, nullptr, indexName_, ifExist_); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropEdgeIndexValidator::validateImpl() { auto sentence = static_cast<DropEdgeIndexSentence *>(sentence_); indexName_ = *sentence->indexName(); ifExist_ = sentence->isIfExists(); return Status::OK(); } Status DropEdgeIndexValidator::toPlan() { auto *doNode = DropEdgeIndex::make(qctx_, nullptr, indexName_, ifExist_); root_ = doNode; tail_ = root_; return Status::OK(); } Status DescribeTagIndexValidator::validateImpl() { auto sentence = static_cast<DescribeTagIndexSentence *>(sentence_); indexName_ = *sentence->indexName(); return Status::OK(); } Status DescribeTagIndexValidator::toPlan() { auto *doNode = DescTagIndex::make(qctx_, nullptr, indexName_); root_ = doNode; tail_ = root_; return Status::OK(); } Status DescribeEdgeIndexValidator::validateImpl() { auto sentence = static_cast<DescribeEdgeIndexSentence *>(sentence_); indexName_ = *sentence->indexName(); return Status::OK(); } Status DescribeEdgeIndexValidator::toPlan() { auto *doNode = DescEdgeIndex::make(qctx_, nullptr, indexName_); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowCreateTagIndexValidator::validateImpl() { auto sentence = static_cast<ShowCreateTagIndexSentence *>(sentence_); indexName_ = *sentence->indexName(); return Status::OK(); } Status ShowCreateTagIndexValidator::toPlan() { auto *doNode = ShowCreateTagIndex::make(qctx_, nullptr, indexName_); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowCreateEdgeIndexValidator::validateImpl() { auto sentence = static_cast<ShowCreateTagIndexSentence *>(sentence_); indexName_ = *sentence->indexName(); return Status::OK(); } Status ShowCreateEdgeIndexValidator::toPlan() { auto *doNode = ShowCreateEdgeIndex::make(qctx_, nullptr, indexName_); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowTagIndexesValidator::validateImpl() { return Status::OK(); } Status ShowTagIndexesValidator::toPlan() { auto *doNode = ShowTagIndexes::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowEdgeIndexesValidator::validateImpl() { return Status::OK(); } Status ShowEdgeIndexesValidator::toPlan() { auto *doNode = ShowEdgeIndexes::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowTagIndexStatusValidator::validateImpl() { return Status::OK(); } Status ShowTagIndexStatusValidator::toPlan() { auto *doNode = ShowTagIndexStatus::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status ShowEdgeIndexStatusValidator::validateImpl() { return Status::OK(); } Status ShowEdgeIndexStatusValidator::toPlan() { auto *doNode = ShowEdgeIndexStatus::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status AddGroupValidator::validateImpl() { return Status::OK(); } Status AddGroupValidator::toPlan() { auto sentence = static_cast<AddGroupSentence*>(sentence_); auto *doNode = AddGroup::make(qctx_, nullptr, *sentence->groupName(), sentence->zoneNames()->zoneNames()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropGroupValidator::validateImpl() { return Status::OK(); } Status DropGroupValidator::toPlan() { auto sentence = static_cast<DropGroupSentence*>(sentence_); auto *doNode = DropGroup::make(qctx_, nullptr, *sentence->groupName()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DescribeGroupValidator::validateImpl() { return Status::OK(); } Status DescribeGroupValidator::toPlan() { auto sentence = static_cast<DescribeGroupSentence*>(sentence_); auto *doNode = DescribeGroup::make(qctx_, nullptr, *sentence->groupName()); root_ = doNode; tail_ = root_; return Status::OK(); } Status ListGroupsValidator::validateImpl() { return Status::OK(); } Status ListGroupsValidator::toPlan() { auto *doNode = ListGroups::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status AddZoneIntoGroupValidator::validateImpl() { return Status::OK(); } Status AddZoneIntoGroupValidator::toPlan() { auto sentence = static_cast<AddZoneIntoGroupSentence*>(sentence_); auto *doNode = AddZoneIntoGroup::make(qctx_, nullptr, *sentence->groupName(), *sentence->zoneName()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropZoneFromGroupValidator::validateImpl() { return Status::OK(); } Status DropZoneFromGroupValidator::toPlan() { auto sentence = static_cast<DropZoneFromGroupSentence*>(sentence_); auto *doNode = DropZoneFromGroup::make(qctx_, nullptr, *sentence->groupName(), *sentence->zoneName()); root_ = doNode; tail_ = root_; return Status::OK(); } Status AddZoneValidator::validateImpl() { return Status::OK(); } Status AddZoneValidator::toPlan() { auto sentence = static_cast<AddZoneSentence*>(sentence_); auto *doNode = AddZone::make(qctx_, nullptr, *sentence->zoneName(), sentence->hosts()->hosts()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropZoneValidator::validateImpl() { return Status::OK(); } Status DropZoneValidator::toPlan() { auto sentence = static_cast<DropZoneSentence*>(sentence_); auto *doNode = DropZone::make(qctx_, nullptr, *sentence->zoneName()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DescribeZoneValidator::validateImpl() { return Status::OK(); } Status DescribeZoneValidator::toPlan() { auto sentence = static_cast<DescribeZoneSentence*>(sentence_); auto *doNode = DescribeZone::make(qctx_, nullptr, *sentence->zoneName()); root_ = doNode; tail_ = root_; return Status::OK(); } Status ListZonesValidator::validateImpl() { return Status::OK(); } Status ListZonesValidator::toPlan() { auto *doNode = ListZones::make(qctx_, nullptr); root_ = doNode; tail_ = root_; return Status::OK(); } Status AddHostIntoZoneValidator::validateImpl() { return Status::OK(); } Status AddHostIntoZoneValidator::toPlan() { auto sentence = static_cast<AddHostIntoZoneSentence*>(sentence_); auto *doNode = AddHostIntoZone::make(qctx_, nullptr, *sentence->zoneName(), *sentence->address()); root_ = doNode; tail_ = root_; return Status::OK(); } Status DropHostFromZoneValidator::validateImpl() { return Status::OK(); } Status DropHostFromZoneValidator::toPlan() { auto sentence = static_cast<DropHostFromZoneSentence*>(sentence_); auto *doNode = DropHostFromZone::make(qctx_, nullptr, *sentence->zoneName(), *sentence->address()); root_ = doNode; tail_ = root_; return Status::OK(); } } // namespace graph } // namespace nebula
#include "Runtime/World/CScriptMemoryRelay.hpp" #include "Runtime/CRelayTracker.hpp" #include "Runtime/CStateManager.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { CScriptMemoryRelay::CScriptMemoryRelay(TUniqueId uid, std::string_view name, const CEntityInfo& info, bool defaultActive, bool skipSendActive, bool ignoreMessages) : CEntity(uid, info, true, name) , x34_24_defaultActive(defaultActive) , x34_25_skipSendActive(skipSendActive) , x34_26_ignoreMessages(ignoreMessages) {} void CScriptMemoryRelay::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptMemoryRelay::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& stateMgr) { if (x34_26_ignoreMessages) { return; } if (msg == EScriptObjectMessage::Deactivate) { stateMgr.GetRelayTracker()->RemoveRelay(xc_editorId); return; } else if (msg == EScriptObjectMessage::Activate) { stateMgr.GetRelayTracker()->AddRelay(xc_editorId); if (!x34_25_skipSendActive) { SendScriptMsgs(EScriptObjectState::Active, stateMgr, EScriptObjectMessage::None); } return; } CEntity::AcceptScriptMsg(msg, objId, stateMgr); } } // namespace urde
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/connect/model/DescribeContactFlowResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Connect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeContactFlowResult::DescribeContactFlowResult() { } DescribeContactFlowResult::DescribeContactFlowResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribeContactFlowResult& DescribeContactFlowResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("ContactFlow")) { m_contactFlow = jsonValue.GetObject("ContactFlow"); } return *this; }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // test that <bitset> includes <cstddef>, <string>, <stdexcept> and <iosfwd> #include <bitset> #ifndef _LIBCPP_CSTDDEF #error <cstddef> has not been included #endif #ifndef _LIBCPP_STRING #error <string> has not been included #endif #ifndef _LIBCPP_STDEXCEPT #error <stdexcept> has not been included #endif #ifndef _LIBCPP_IOSFWD #error <iosfwd> has not been included #endif int main() { }
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cstddef> /// \cond class DataVector; template <size_t Dim> class Index; class Matrix; template <size_t Dim> class Mesh; /// \endcond namespace evolution::dg::subcell::fd { /*! * \ingroup DgSubcellGroup * \brief Computes the projection matrix in `Dim` dimensions going from a DG * mesh to a conservative finite difference subcell mesh. */ template <size_t Dim> const Matrix& projection_matrix(const Mesh<Dim>& dg_mesh, const Index<Dim>& subcell_extents); /*! * \ingroup DgSubcellGroup * \brief Computes the matrix needed for reconstructing the DG solution from * the subcell solution. * * Reconstructing the DG solution from the FD solution is a bit more * involved than projecting the DG solution to the FD subcells. Denoting the * projection operator by \f$\mathcal{P}\f$ and the reconstruction operator by * \f$\mathcal{R}\f$, we desire the property * * \f{align*}{ * \mathcal{R}(\mathcal{P}(u_{\breve{\imath}} * J_{\breve{\imath}}))=u_{\breve{\imath}} J_{\breve{\imath}}, * \f} * * where \f$\breve{\imath}\f$ denotes a grid point on the DG grid, \f$u\f$ is * the solution on the DG grid, and \f$J\f$ is the determinant of the Jacobian * on the DG grid. We also require that the integral of the conserved variables * over the subcells is equal to the integral over the DG element. That is, * * \f{align*}{ * \int_{\Omega}u \,d^3x =\int_{\Omega} \underline{u} \,d^3x \Longrightarrow * \int_{\Omega}u J \,d^3\xi=\int_{\Omega} \underline{u} J \,d^3\xi, * \f} * * where \f$\underline{u}\f$ is the solution on the subcells. Because the number * of subcell points is larger than the number of DG points, we need to solve a * constrained linear least squares problem to reconstruct the DG solution from * the subcells. * * The final reconstruction matrix is given by * * \f{align*}{ * R_{\breve{\jmath}\underline{i}} * &=\left\{(2 \mathcal{P}\otimes\mathcal{P})^{-1}2\mathcal{P} - (2 * \mathcal{P}\otimes\mathcal{P})^{-1}\vec{w}\left[\mathbf{w}(2 * \mathcal{P}\otimes\mathcal{P})^{-1}\vec{w}\right]^{-1}\mathbf{w}(2 * \mathcal{P}\otimes\mathcal{P})^{-1}2\mathcal{P} * + (2 \mathcal{P}\otimes\mathcal{P})^{-1}\vec{w}\left[\mathbf{w}(2 * \mathcal{P}\otimes\mathcal{P})^{-1}\vec{w}\right]^{-1}\vec{\underline{w}} * \right\}_{\breve{\jmath}\underline{i}}, * \f} * * where \f$\vec{w}\f$ is the vector of integration weights on the DG element, * \f$\mathbf{w}=w_{\breve{l}}\delta_{\breve{l}\breve{\jmath}}\f$, and * \f$\vec{\underline{w}}\f$ is the vector of integration weights over the * subcells. The integration weights \f$\vec{\underline{w}}\f$ on the subcells * are those for 6th-order integration on a uniform mesh. */ template <size_t Dim> const Matrix& reconstruction_matrix(const Mesh<Dim>& dg_mesh, const Index<Dim>& subcell_extents); } // namespace evolution::dg::subcellfd
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/message_box_view.h" #include "base/i18n/rtl.h" #include "base/message_loop.h" #include "base/strings/string_split.h" #include "base/utf_string_conversions.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" namespace { const int kDefaultMessageWidth = 320; // Paragraph separators are defined in // http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedBidiClass.txt // // # Bidi_Class=Paragraph_Separator // // 000A ; B # Cc <control-000A> // 000D ; B # Cc <control-000D> // 001C..001E ; B # Cc [3] <control-001C>..<control-001E> // 0085 ; B # Cc <control-0085> // 2029 ; B # Zp PARAGRAPH SEPARATOR bool IsParagraphSeparator(char16 c) { return ( c == 0x000A || c == 0x000D || c == 0x001C || c == 0x001D || c == 0x001E || c == 0x0085 || c == 0x2029); } // Splits |text| into a vector of paragraphs. // Given an example "\nabc\ndef\n\n\nhij\n", the split results should be: // "", "abc", "def", "", "", "hij", and "". void SplitStringIntoParagraphs(const string16& text, std::vector<string16>* paragraphs) { paragraphs->clear(); size_t start = 0; for (size_t i = 0; i < text.length(); ++i) { if (IsParagraphSeparator(text[i])) { paragraphs->push_back(text.substr(start, i - start)); start = i + 1; } } paragraphs->push_back(text.substr(start, text.length() - start)); } } // namespace namespace views { /////////////////////////////////////////////////////////////////////////////// // MessageBoxView, public: MessageBoxView::InitParams::InitParams(const string16& message) : options(NO_OPTIONS), message(message), message_width(kDefaultMessageWidth), inter_row_vertical_spacing(kRelatedControlVerticalSpacing), clipboard_source_tag() {} MessageBoxView::InitParams::~InitParams() { } MessageBoxView::MessageBoxView(const InitParams& params) : prompt_field_(NULL), icon_(NULL), checkbox_(NULL), message_width_(params.message_width) { Init(params); } MessageBoxView::~MessageBoxView() {} string16 MessageBoxView::GetInputText() { return prompt_field_ ? prompt_field_->text() : string16(); } bool MessageBoxView::IsCheckBoxSelected() { return checkbox_ ? checkbox_->checked() : false; } void MessageBoxView::SetIcon(const gfx::ImageSkia& icon) { if (!icon_) icon_ = new ImageView(); icon_->SetImage(icon); icon_->SetBounds(0, 0, icon.width(), icon.height()); ResetLayoutManager(); } void MessageBoxView::SetCheckBoxLabel(const string16& label) { if (!checkbox_) checkbox_ = new Checkbox(label); else checkbox_->SetText(label); ResetLayoutManager(); } void MessageBoxView::SetCheckBoxSelected(bool selected) { if (!checkbox_) return; checkbox_->SetChecked(selected); } void MessageBoxView::GetAccessibleState(ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_ALERT; } /////////////////////////////////////////////////////////////////////////////// // MessageBoxView, View overrides: void MessageBoxView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.child == this && details.is_add) { if (prompt_field_) prompt_field_->SelectAll(true); NotifyAccessibilityEvent(ui::AccessibilityTypes::EVENT_ALERT, true); } } bool MessageBoxView::AcceleratorPressed(const ui::Accelerator& accelerator) { // We only accepts Ctrl-C. DCHECK(accelerator.key_code() == 'C' && accelerator.IsCtrlDown()); // We must not intercept Ctrl-C when we have a text box and it's focused. if (prompt_field_ && prompt_field_->HasFocus()) return false; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); if (!clipboard) return false; ui::ScopedClipboardWriter scw(clipboard, ui::Clipboard::BUFFER_STANDARD, source_tag_); string16 text = message_labels_[0]->text(); for (size_t i = 1; i < message_labels_.size(); ++i) text += message_labels_[i]->text(); scw.WriteText(text); return true; } /////////////////////////////////////////////////////////////////////////////// // MessageBoxView, private: void MessageBoxView::Init(const InitParams& params) { if (params.options & DETECT_DIRECTIONALITY) { std::vector<string16> texts; SplitStringIntoParagraphs(params.message, &texts); // If the text originates from a web page, its alignment is based on its // first character with strong directionality. base::i18n::TextDirection message_direction = base::i18n::GetFirstStrongCharacterDirection(params.message); gfx::HorizontalAlignment alignment = (message_direction == base::i18n::RIGHT_TO_LEFT) ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT; for (size_t i = 0; i < texts.size(); ++i) { Label* message_label = new Label(texts[i]); // Don't set multi-line to true if the text is empty, else the label will // have a height of 0. message_label->SetMultiLine(!texts[i].empty()); message_label->SetAllowCharacterBreak(true); message_label->set_directionality_mode(Label::AUTO_DETECT_DIRECTIONALITY); message_label->SetHorizontalAlignment(alignment); message_labels_.push_back(message_label); } } else { Label* message_label = new Label(params.message); message_label->SetMultiLine(true); message_label->SetAllowCharacterBreak(true); message_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); message_labels_.push_back(message_label); } if (params.options & HAS_PROMPT_FIELD) { prompt_field_ = new Textfield; prompt_field_->SetText(params.default_prompt); } inter_row_vertical_spacing_ = params.inter_row_vertical_spacing; source_tag_ = params.clipboard_source_tag; ResetLayoutManager(); } void MessageBoxView::ResetLayoutManager() { // Initialize the Grid Layout Manager used for this dialog box. GridLayout* layout = GridLayout::CreatePanel(this); SetLayoutManager(layout); gfx::Size icon_size; if (icon_) icon_size = icon_->GetPreferredSize(); // Add the column set for the message displayed at the top of the dialog box. // And an icon, if one has been set. const int message_column_view_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(message_column_view_set_id); if (icon_) { column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0, GridLayout::FIXED, icon_size.width(), icon_size.height()); column_set->AddPaddingColumn(0, kUnrelatedControlHorizontalSpacing); } column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::FIXED, message_width_, 0); // Column set for prompt Textfield, if one has been set. const int textfield_column_view_set_id = 1; if (prompt_field_) { column_set = layout->AddColumnSet(textfield_column_view_set_id); if (icon_) { column_set->AddPaddingColumn( 0, icon_size.width() + kUnrelatedControlHorizontalSpacing); } column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); } // Column set for checkbox, if one has been set. const int checkbox_column_view_set_id = 2; if (checkbox_) { column_set = layout->AddColumnSet(checkbox_column_view_set_id); if (icon_) { column_set->AddPaddingColumn( 0, icon_size.width() + kUnrelatedControlHorizontalSpacing); } column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); } for (size_t i = 0; i < message_labels_.size(); ++i) { layout->StartRow(i, message_column_view_set_id); if (icon_) { if (i == 0) layout->AddView(icon_); else layout->SkipColumns(1); } layout->AddView(message_labels_[i]); } if (prompt_field_) { layout->AddPaddingRow(0, inter_row_vertical_spacing_); layout->StartRow(0, textfield_column_view_set_id); layout->AddView(prompt_field_); } if (checkbox_) { layout->AddPaddingRow(0, inter_row_vertical_spacing_); layout->StartRow(0, checkbox_column_view_set_id); layout->AddView(checkbox_); } layout->AddPaddingRow(0, inter_row_vertical_spacing_); } } // namespace views
// 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) // // (C) Copyright 2019 Vicente J. Botet Escriba #ifndef JASEL_EXPERIMENTAL_FLAT_MAP_HPP #define JASEL_EXPERIMENTAL_FLAT_MAP_HPP #include <experimental/fundamental/v3/flat_map/flat_map.hpp> #endif // header
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "utilstrencodings.h" #include "test/test_cic.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(base64_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(base64_testvectors) { static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"}; static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"}; for (unsigned int i=0; i<sizeof(vstrIn)/sizeof(vstrIn[0]); i++) { std::string strEnc = EncodeBase64(vstrIn[i]); BOOST_CHECK(strEnc == vstrOut[i]); std::string strDec = DecodeBase64(strEnc); BOOST_CHECK(strDec == vstrIn[i]); } } BOOST_AUTO_TEST_SUITE_END()
// // Created by YANG Zehai on 2021/11/24. // #include "AST/IndexVisit.h" using namespace pur; using namespace pur::ast; IndexVisit::IndexVisit(const pars::Location& location, Expr& index): Expr(ASTNodeType::kIndexVisit, location), mIndex(&index) { /* empty */ } Expr& IndexVisit::GetOwner() { return *mOwner; } Expr& IndexVisit::GetIndex() { return *mIndex; } void IndexVisit::Accept(Visitor& visitor) { visitor.VisitIndexVisit(*this); } void IndexVisit::SetOwner(Expr& owner) { mOwner.reset(&owner); }
// // Created by roman on 4/6/18. // #ifndef KEYCHAINAPP_CMD_PARSER_HPP #define KEYCHAINAPP_CMD_PARSER_HPP #include <boost/program_options.hpp> #if (defined(linux) || defined(__linux) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)) && !defined(_CRAYC) #define LINUX #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #define WIN #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) #define APPLE #endif namespace po = boost::program_options; namespace keychain_app { class cmd_parser { public: cmd_parser(); int run(int argc, const char* const argv[]); private: po::options_description m_options; int parse_cmd_line(int argc, const char* const argv[]); }; } #endif //KEYCHAINAPP_CMD_PARSER_HPP
/* * Copyright 2013-2020 Automatak, LLC * * Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak * LLC (www.automatak.com) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Green Energy Corp and Automatak LLC license * 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 "CommandSetBuilder.h" #include "Conversions.h" namespace Automatak { namespace DNP3 { namespace Adapter { CommandSetBuilder::CommandSetBuilder(opendnp3::CommandSet& commands) : commands(&commands) {} void CommandSetBuilder::Add(IEnumerable<IndexedValue<ControlRelayOutputBlock^>^>^ commands) { auto& header = this->commands->StartHeader<opendnp3::ControlRelayOutputBlock>(); for each(auto pair in commands) { header.Add(Conversions::ConvertCommand(pair->Value), pair->Index); } } void CommandSetBuilder::Add(IEnumerable<IndexedValue<AnalogOutputInt16^>^>^ commands) { auto& header = this->commands->StartHeader<opendnp3::AnalogOutputInt16>(); for each(auto pair in commands) { header.Add(Conversions::ConvertCommand(pair->Value), pair->Index); } } void CommandSetBuilder::Add(IEnumerable<IndexedValue<AnalogOutputInt32^>^>^ commands) { auto& header = this->commands->StartHeader<opendnp3::AnalogOutputInt32>(); for each(auto pair in commands) { header.Add(Conversions::ConvertCommand(pair->Value), pair->Index); } } void CommandSetBuilder::Add(IEnumerable<IndexedValue<AnalogOutputFloat32^>^>^ commands) { auto& header = this->commands->StartHeader<opendnp3::AnalogOutputFloat32>(); for each(auto pair in commands) { header.Add(Conversions::ConvertCommand(pair->Value), pair->Index); } } void CommandSetBuilder::Add(IEnumerable<IndexedValue<AnalogOutputDouble64^>^>^ commands) { auto& header = this->commands->StartHeader<opendnp3::AnalogOutputDouble64>(); for each(auto pair in commands) { header.Add(Conversions::ConvertCommand(pair->Value), pair->Index); } } } } }
/* Copyright (c) 2007 Cyrus Daboo. 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 "CDayWeekPrintout.h" #include "CCalendarView.h" #include "CDayWeekTitleTable.h" #include "CDayWeekTable.h" #include "CMonthIndicator.h" #include "CPrintText.h" #include "CCalendarStoreManager.h" #include "CICalendar.h" #include "CICalendarPeriod.h" #include "CICalendarUtils.h" // --------------------------------------------------------------------------- // CDayWeekPrintout [public] /** Default constructor */ CDayWeekPrintout::CDayWeekPrintout(LStream *inStream) : CCalendarViewPrintout(inStream) { } // --------------------------------------------------------------------------- // ~CDayWeekPrintout [public] /** Destructor */ CDayWeekPrintout::~CDayWeekPrintout() { } #pragma mark - void CDayWeekPrintout::FinishCreateSelf() { // Do inherited CCalendarViewPrintout::FinishCreateSelf(); // Get the UI objects mTitle = dynamic_cast<CPrintText*>(FindPaneByID(eTitle_ID)); mThisMonth = dynamic_cast<CMonthIndicator*>(FindPaneByID(eThisMonth_ID)); mView = dynamic_cast<LView*>(FindPaneByID(eView_ID)); mTitles = dynamic_cast<CDayWeekTitleTable*>(FindPaneByID(eTitleTable_ID)); mTable = dynamic_cast<CDayWeekTable*>(FindPaneByID(eTable_ID)); mTable->SetTitles(mTitles); mTitles->SetTable(mTable); } void CDayWeekPrintout::SetDetails(const iCal::CICalendarDateTime& date, CDayWeekView::EDayWeekType type, CDayWeekViewTimeRange::ERanges range, CCalendarView* view) { // Set static text cdstring title; title += date.GetMonthText(false); char buf[256]; std::snprintf(buf, 256, "%ld", date.GetYear()); title += " "; title += buf; title += " ("; title += date.GetTimezone().GetTimezoneID(); title += ")"; mTitle->SetText(title); // Set the indicator iCal::CICalendarDateTime temp(date); mThisMonth->ResetTable(temp, 75, true); // Date must be at start of day iCal::CICalendarDateTime dt(date); dt.SetHHMMSS(0, 0, 0); // Adjust date based on type int32_t num_days = 1; switch(type) { case CDayWeekView::eDay: default: // Nothing to do; break; case CDayWeekView::eWorkWeek: // Adjust date to the Monday at or before mDate if (dt.GetDayOfWeek() != iCal::CICalendarDateTime::eMonday) dt.OffsetDay(iCal::CICalendarDateTime::eMonday - dt.GetDayOfWeek()); num_days = 5; break; case CDayWeekView::eWeek: // Adjust date to the Sunday at or before mDate if (dt.GetDayOfWeek() != iCal::CICalendarDateTime::eSunday) dt.OffsetDay(-dt.GetDayOfWeek()); num_days = 7; break; } mTable->ResetTable(dt, type, range); // Get date range for event lookup iCal::CICalendarDateTime dtstart(dt); dtstart.SetDateOnly(false); iCal::CICalendarDateTime dtend(dt); dtend.SetDateOnly(false); dtend.OffsetDay(num_days); // Get events in the range iCal::CICalendarExpandedComponents vevents; iCal::CICalendarComponentList vfreebusy; iCal::CICalendarPeriod period(dtstart, dtend); // Only do visible calendars if (calstore::CCalendarStoreManager::sCalendarStoreManager != NULL) { const iCal::CICalendarList& cals = calstore::CCalendarStoreManager::sCalendarStoreManager->GetSubscribedCalendars(); for(iCal::CICalendarList::const_iterator iter = cals.begin(); iter != cals.end(); iter++) { (*iter)->GetVEvents(period, vevents); (*iter)->GetVFreeBusy(period, vfreebusy); } } // Add events to table mTable->AddItems(vevents, vfreebusy); }
// Copyright John Maddock 2007. // Copyright Paul A. Bristow 2007, 2009 // 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) #ifndef BOOST_STATS_PARETO_HPP #define BOOST_STATS_PARETO_HPP // http://en.wikipedia.org/wiki/Pareto_distribution // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm // Also: // Weisstein, Eric W. "Pareto Distribution." // From MathWorld--A Wolfram Web Resource. // http://mathworld.wolfram.com/ParetoDistribution.html // Handbook of Statistical Distributions with Applications, K Krishnamoorthy, ISBN 1-58488-635-8, Chapter 23, pp 257 - 267. // Caution KK's a and b are the reverse of Mathworld! #include <boost/math/distributions/fwd.hpp> #include <boost/math/distributions/complement.hpp> #include <boost/math/distributions/detail/common_error_handling.hpp> #include <boost/math/special_functions/powm1.hpp> #include <utility> // for BOOST_CURRENT_VALUE? namespace boost { namespace math { namespace detail { // Parameter checking. template <class RealType, class Policy> inline bool check_pareto_scale( const char* function, RealType scale, RealType* result, const Policy& pol) { if((boost::math::isfinite)(scale)) { // any > 0 finite value is OK. if (scale > 0) { return true; } else { *result = policies::raise_domain_error<RealType>( function, "Scale parameter is %1%, but must be > 0!", scale, pol); return false; } } else { // Not finite. *result = policies::raise_domain_error<RealType>( function, "Scale parameter is %1%, but must be finite!", scale, pol); return false; } } // bool check_pareto_scale template <class RealType, class Policy> inline bool check_pareto_shape( const char* function, RealType shape, RealType* result, const Policy& pol) { if((boost::math::isfinite)(shape)) { // Any finite value > 0 is OK. if (shape > 0) { return true; } else { *result = policies::raise_domain_error<RealType>( function, "Shape parameter is %1%, but must be > 0!", shape, pol); return false; } } else { // Not finite. *result = policies::raise_domain_error<RealType>( function, "Shape parameter is %1%, but must be finite!", shape, pol); return false; } } // bool check_pareto_shape( template <class RealType, class Policy> inline bool check_pareto_x( const char* function, RealType const& x, RealType* result, const Policy& pol) { if((boost::math::isfinite)(x)) { // if (x > 0) { return true; } else { *result = policies::raise_domain_error<RealType>( function, "x parameter is %1%, but must be > 0 !", x, pol); return false; } } else { // Not finite.. *result = policies::raise_domain_error<RealType>( function, "x parameter is %1%, but must be finite!", x, pol); return false; } } // bool check_pareto_x template <class RealType, class Policy> inline bool check_pareto( // distribution parameters. const char* function, RealType scale, RealType shape, RealType* result, const Policy& pol) { return check_pareto_scale(function, scale, result, pol) && check_pareto_shape(function, shape, result, pol); } // bool check_pareto( } // namespace detail template <class RealType = double, class Policy = policies::policy<> > class pareto_distribution { public: typedef RealType value_type; typedef Policy policy_type; pareto_distribution(RealType scale = 1, RealType shape = 1) : m_scale(scale), m_shape(shape) { // Constructor. RealType result = 0; detail::check_pareto("boost::math::pareto_distribution<%1%>::pareto_distribution", scale, shape, &result, Policy()); } RealType scale()const { // AKA Xm and Wolfram b and beta return m_scale; } RealType shape()const { // AKA k and Wolfram a and alpha return m_shape; } private: // Data members: RealType m_scale; // distribution scale (xm) or beta RealType m_shape; // distribution shape (k) or alpha }; typedef pareto_distribution<double> pareto; // Convenience to allow pareto(2., 3.); template <class RealType, class Policy> inline const std::pair<RealType, RealType> range(const pareto_distribution<RealType, Policy>& /*dist*/) { // Range of permissible values for random variable x. using boost::math::tools::max_value; return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // scale zero to + infinity. } // range template <class RealType, class Policy> inline const std::pair<RealType, RealType> support(const pareto_distribution<RealType, Policy>& dist) { // Range of supported values for random variable x. // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero. using boost::math::tools::max_value; return std::pair<RealType, RealType>(dist.scale(), max_value<RealType>() ); // scale to + infinity. } // support template <class RealType, class Policy> inline RealType pdf(const pareto_distribution<RealType, Policy>& dist, const RealType& x) { BOOST_MATH_STD_USING // for ADL of std function pow. static const char* function = "boost::math::pdf(const pareto_distribution<%1%>&, %1%)"; RealType scale = dist.scale(); RealType shape = dist.shape(); RealType result = 0; if(false == (detail::check_pareto_x(function, x, &result, Policy()) && detail::check_pareto(function, scale, shape, &result, Policy()))) return result; if (x < scale) { // regardless of shape, pdf is zero (or should be disallow x < scale and throw an exception?). return 0; } result = shape * pow(scale, shape) / pow(x, shape+1); return result; } // pdf template <class RealType, class Policy> inline RealType cdf(const pareto_distribution<RealType, Policy>& dist, const RealType& x) { BOOST_MATH_STD_USING // for ADL of std function pow. static const char* function = "boost::math::cdf(const pareto_distribution<%1%>&, %1%)"; RealType scale = dist.scale(); RealType shape = dist.shape(); RealType result = 0; if(false == (detail::check_pareto_x(function, x, &result, Policy()) && detail::check_pareto(function, scale, shape, &result, Policy()))) return result; if (x <= scale) { // regardless of shape, cdf is zero. return 0; } // result = RealType(1) - pow((scale / x), shape); result = -boost::math::powm1(scale/x, shape, Policy()); // should be more accurate. return result; } // cdf template <class RealType, class Policy> inline RealType quantile(const pareto_distribution<RealType, Policy>& dist, const RealType& p) { BOOST_MATH_STD_USING // for ADL of std function pow. static const char* function = "boost::math::quantile(const pareto_distribution<%1%>&, %1%)"; RealType result = 0; RealType scale = dist.scale(); RealType shape = dist.shape(); if(false == (detail::check_probability(function, p, &result, Policy()) && detail::check_pareto(function, scale, shape, &result, Policy()))) { return result; } if (p == 0) { return scale; // x must be scale (or less). } if (p == 1) { return tools::max_value<RealType>(); // x = + infinity. } result = scale / (pow((1 - p), 1 / shape)); // K. Krishnamoorthy, ISBN 1-58488-635-8 eq 23.1.3 return result; } // quantile template <class RealType, class Policy> inline RealType cdf(const complemented2_type<pareto_distribution<RealType, Policy>, RealType>& c) { BOOST_MATH_STD_USING // for ADL of std function pow. static const char* function = "boost::math::cdf(const pareto_distribution<%1%>&, %1%)"; RealType result = 0; RealType x = c.param; RealType scale = c.dist.scale(); RealType shape = c.dist.shape(); if(false == (detail::check_pareto_x(function, x, &result, Policy()) && detail::check_pareto(function, scale, shape, &result, Policy()))) return result; if (x <= scale) { // regardless of shape, cdf is zero, and complement is unity. return 1; } result = pow((scale/x), shape); return result; } // cdf complement template <class RealType, class Policy> inline RealType quantile(const complemented2_type<pareto_distribution<RealType, Policy>, RealType>& c) { BOOST_MATH_STD_USING // for ADL of std function pow. static const char* function = "boost::math::quantile(const pareto_distribution<%1%>&, %1%)"; RealType result = 0; RealType q = c.param; RealType scale = c.dist.scale(); RealType shape = c.dist.shape(); if(false == (detail::check_probability(function, q, &result, Policy()) && detail::check_pareto(function, scale, shape, &result, Policy()))) { return result; } if (q == 1) { return scale; // x must be scale (or less). } if (q == 0) { return tools::max_value<RealType>(); // x = + infinity. } result = scale / (pow(q, 1 / shape)); // K. Krishnamoorthy, ISBN 1-58488-635-8 eq 23.1.3 return result; } // quantile complement template <class RealType, class Policy> inline RealType mean(const pareto_distribution<RealType, Policy>& dist) { RealType result = 0; static const char* function = "boost::math::mean(const pareto_distribution<%1%>&, %1%)"; if(false == detail::check_pareto(function, dist.scale(), dist.shape(), &result, Policy())) { return result; } if (dist.shape() > RealType(1)) { return dist.shape() * dist.scale() / (dist.shape() - 1); } else { using boost::math::tools::max_value; return max_value<RealType>(); // +infinity. } } // mean template <class RealType, class Policy> inline RealType mode(const pareto_distribution<RealType, Policy>& dist) { return dist.scale(); } // mode template <class RealType, class Policy> inline RealType median(const pareto_distribution<RealType, Policy>& dist) { RealType result = 0; static const char* function = "boost::math::median(const pareto_distribution<%1%>&, %1%)"; if(false == detail::check_pareto(function, dist.scale(), dist.shape(), &result, Policy())) { return result; } BOOST_MATH_STD_USING return dist.scale() * pow(RealType(2), (1/dist.shape())); } // median template <class RealType, class Policy> inline RealType variance(const pareto_distribution<RealType, Policy>& dist) { RealType result = 0; RealType scale = dist.scale(); RealType shape = dist.shape(); static const char* function = "boost::math::variance(const pareto_distribution<%1%>&, %1%)"; if(false == detail::check_pareto(function, scale, shape, &result, Policy())) { return result; } if (shape > 2) { result = (scale * scale * shape) / ((shape - 1) * (shape - 1) * (shape - 2)); } else { result = policies::raise_domain_error<RealType>( function, "variance is undefined for shape <= 2, but got %1%.", dist.shape(), Policy()); } return result; } // variance template <class RealType, class Policy> inline RealType skewness(const pareto_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING RealType result = 0; RealType shape = dist.shape(); static const char* function = "boost::math::pdf(const pareto_distribution<%1%>&, %1%)"; if(false == detail::check_pareto(function, dist.scale(), shape, &result, Policy())) { return result; } if (shape > 3) { result = sqrt((shape - 2) / shape) * 2 * (shape + 1) / (shape - 3); } else { result = policies::raise_domain_error<RealType>( function, "skewness is undefined for shape <= 3, but got %1%.", dist.shape(), Policy()); } return result; } // skewness template <class RealType, class Policy> inline RealType kurtosis(const pareto_distribution<RealType, Policy>& dist) { RealType result = 0; RealType shape = dist.shape(); static const char* function = "boost::math::pdf(const pareto_distribution<%1%>&, %1%)"; if(false == detail::check_pareto(function, dist.scale(), shape, &result, Policy())) { return result; } if (shape > 4) { result = 3 * ((shape - 2) * (3 * shape * shape + shape + 2)) / (shape * (shape - 3) * (shape - 4)); } else { result = policies::raise_domain_error<RealType>( function, "kurtosis_excess is undefined for shape <= 4, but got %1%.", shape, Policy()); } return result; } // kurtosis template <class RealType, class Policy> inline RealType kurtosis_excess(const pareto_distribution<RealType, Policy>& dist) { RealType result = 0; RealType shape = dist.shape(); static const char* function = "boost::math::pdf(const pareto_distribution<%1%>&, %1%)"; if(false == detail::check_pareto(function, dist.scale(), shape, &result, Policy())) { return result; } if (shape > 4) { result = 6 * ((shape * shape * shape) + (shape * shape) - 6 * shape - 2) / (shape * (shape - 3) * (shape - 4)); } else { result = policies::raise_domain_error<RealType>( function, "kurtosis_excess is undefined for shape <= 4, but got %1%.", dist.shape(), Policy()); } return result; } // kurtosis_excess } // namespace math } // namespace boost // This include must be at the end, *after* the accessors // for this distribution have been defined, in order to // keep compilers that support two-phase lookup happy. #include <boost/math/distributions/detail/derived_accessors.hpp> #endif // BOOST_STATS_PARETO_HPP
#ifndef FTXUI_COMPONENT_HPP #define FTXUI_COMPONENT_HPP #include <functional> // for function #include <memory> // for shared_ptr, make_shared #include <string> // for wstring #include <vector> // for vector #include "ftxui/component/component_base.hpp" #include "ftxui/dom/elements.hpp" // for Element #include "ftxui/screen/string.hpp" // for ConstStringRef, StringRef namespace ftxui { class ComponentBase; struct Event; using Component = std::shared_ptr<ComponentBase>; using Components = std::vector<Component>; template <class T, class... Args> std::shared_ptr<T> Make(Args&&... args) { return std::make_shared<T>(args...); } Component Button(ConstStringRef label, std::function<void()> on_click, bool border = true); Component Checkbox(ConstStringRef label, bool* checked); Component Input(StringRef content, ConstStringRef placeholder); Component Menu(const std::vector<std::wstring>* entries, int* selected_); Component Radiobox(const std::vector<std::wstring>* entries, int* selected_); Component Toggle(const std::vector<std::wstring>* entries, int* selected); template <class T> // T = {int, float, long} Component Slider(StringRef label, T* value, T min, T max, T increment); Component Renderer(Component child, std::function<Element()>); Component Renderer(std::function<Element()>); Component CatchEvent(Component child, std::function<bool(Event)>); namespace Container { Component Vertical(Components children); Component Horizontal(Components children); Component Tab(Components children, int* selector); } // namespace Container Component ResizableSplitLeft(Component main, Component back, int* main_size); Component ResizableSplitRight(Component main, Component back, int* main_size); Component ResizableSplitTop(Component main, Component back, int* main_size); Component ResizableSplitBottom(Component main, Component back, int* main_size); } // namespace ftxui #endif /* end of include guard: FTXUI_COMPONENT_HPP */ // Copyright 2021 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file.
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <CppUnitTest.h> #include <IWebSocketResource.h> #include <Test/WebSocketServer.h> #include <unicode.h> // Windows API #include <TlHelp32.h> #include <Windows.h> // Standard library includes #include <math.h> #include <atomic> #include <future> using namespace Microsoft::React; using namespace Microsoft::VisualStudio::CppUnitTestFramework; using Microsoft::Common::Unicode::Utf8ToUtf16; using std::shared_ptr; using std::string; using std::vector; // None of these tests are runnable TEST_CLASS (WebSocketResourcePerformanceTest) { // See http://msdn.microsoft.com/en-us/library/ms686701(v=VS.85).aspx int32_t GetCurrentThreadCount() { DWORD procId = GetCurrentProcessId(); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0 /*th32ProcessID*/); PROCESSENTRY32 entry = {0}; entry.dwSize = sizeof(entry); BOOL procFound = true; procFound = Process32First(snapshot, &entry); while (procFound && entry.th32ProcessID != procId) procFound = Process32Next(snapshot, &entry); CloseHandle(snapshot); if (procFound) return entry.cntThreads; return -1; } /// /// Spawn a number of WebSocket resources, have it write and read a message /// several times, then measure the amount of allocated threads. Important. This /// test must be run in isolation (no other tests running concurrently). /// TEST_METHOD(ProcessThreadsPerResource) { // About 3 seconds total running time. // 6, if we increase this value to 100. const int resourceTotal = 50; const int maxWriteCount = 10; const int expectedThreadsPerResource = 3; const int startThreadCount = GetCurrentThreadCount(); std::atomic_int32_t threadCount = 0; bool errorFound = false; string errorMessage; auto server = std::make_shared<Test::WebSocketServer>(5556); server->SetMessageFactory([](string &&message) { return message + "_response"; }); // TODO: #4493 - Allow TestWebSocketServer to handle multiple incoming messages. // server->Start(); // WebSocket resources scope. { vector<shared_ptr<IWebSocketResource>> resources; for (int i = 0; i < resourceTotal; i++) { auto ws = IWebSocketResource::Make(); ws->SetOnMessage([this, &threadCount, &errorFound](size_t size, const string &message, bool isBinary) { if (errorFound) return; auto count = this->GetCurrentThreadCount(); if (count > threadCount.load()) threadCount.store(count); }); ws->SetOnSend([this, &threadCount, &errorFound](size_t) { if (errorFound) return; auto count = this->GetCurrentThreadCount(); if (count > threadCount.load()) threadCount.store(count); }); ws->SetOnClose([this, &threadCount, &errorFound](IWebSocketResource::CloseCode, const string & /*reason*/) { if (errorFound) return; auto count = this->GetCurrentThreadCount(); if (count > threadCount.load()) threadCount.store(count); }); ws->SetOnError([this, &errorFound, &errorMessage](IWebSocketResource::Error &&error) { if (errorFound) return; errorFound = true; errorMessage = error.Message; }); ws->Connect("ws://localhost:5555"); // TODO: Switch to port 5556 resources.push_back(std::move(ws)); } // Create and store WS resources. // Send messages. for (auto &ws : resources) { ws->Send("some message"); } // Close resources. for (auto &ws : resources) { ws->Close(); } } // TODO: #4493 - Allow TestWebSocketServer to handle multiple incoming messages. // server->Stop(); int32_t finalThreadCount = threadCount.load(); int64_t threadsPerResource = (finalThreadCount - startThreadCount) / resourceTotal; Assert::IsFalse(errorFound, Utf8ToUtf16(errorMessage).c_str()); Assert::AreNotEqual(finalThreadCount, 0); Assert::IsTrue(threadsPerResource <= expectedThreadsPerResource); } };
/* * Raspberry Pi PIC Programmer using GPIO connector * https://github.com/WallaceIT/picberry * Copyright 2014 Francesco Valla * * * 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/>. */ #include <stdint.h> #include <string.h> #include <iostream> #include <unistd.h> #include "dspic33e.h" /* delays (in microseconds; nanoseconds are rounded to 1us) */ #define DELAY_P1 1 // 200ns #define DELAY_P1A 1 // 80ns #define DELAY_P1B 1 // 80ns #define DELAY_P2 1 // 15ns #define DELAY_P3 1 // 15ns #define DELAY_P4 1 // 40ns #define DELAY_P4A 1 // 40ns #define DELAY_P5 1 // 20ns #define DELAY_P6 1 // 100ns #define DELAY_P7_DSPIC33E 25000 // 25ms #define DELAY_P7_PIC24FJ 50000 // 50ms #define DELAY_P8 12 // 12us #define DELAY_P9A 10 // 10us #define DELAY_P9B 15 // 15us - 23us max! #define DELAY_P10 1 // 400ns #define DELAY_P11_DSPIC33E 116000 // 116ms #define DELAY_P11_PIC24FJ 25000 // 25ms #define DELAY_P12_DSPIC33E 23000 // 23ms #define DELAY_P12_PIC24FJ 25000 // 25ms #define DELAY_P13_DSPIC33E 1600 // 1.6ms #define DELAY_P13_PIC24FJ 20 // 20us #define DELAY_P14 1 // 1us MAX! #define DELAY_P15 1 // 10ns #define DELAY_P16 0 // 0s #define DELAY_P17 0 // 0s - 100ns MAX! #define DELAY_P18 1000 // 1ms #define DELAY_P19 1 // 25ns #define DELAY_P20 25000 // 25ms #define DELAY_P21 1 // 1us - 500us MAX! #define ENTER_PROGRAM_KEY 0x4D434851 #define reset_pc() send_cmd(0x040200) #define send_nop() send_cmd(0x000000) static unsigned int counter=0; static uint16_t nvmcon; /* Send a 24-bit command to the PIC (LSB first) through a SIX instruction */ void dspic33e::send_cmd(uint32_t cmd) { uint8_t i; GPIO_CLR(pic_data); /* send the SIX = 0x0000 instruction */ for (i = 0; i < 4; i++) { GPIO_SET(pic_clk); delay_us(DELAY_P1B); GPIO_CLR(pic_clk); delay_us(DELAY_P1A); } delay_us(DELAY_P4); /* send the 24-bit command */ for (i = 0; i < 24; i++) { if ( (cmd >> i) & 0x00000001 ) GPIO_SET(pic_data); else GPIO_CLR(pic_data); delay_us(DELAY_P1A); GPIO_SET(pic_clk); delay_us(DELAY_P1B); GPIO_CLR(pic_clk); } delay_us(DELAY_P4A); } /* Send five NOPs (should be with a frequency greater than 2MHz...) */ inline void dspic33e::send_prog_nop(void) { uint8_t i; GPIO_CLR(pic_data); /* send 5 NOP commands */ for (i = 0; i < 140; i++) { GPIO_SET(pic_clk); delay_us(DELAY_P1A); GPIO_CLR(pic_clk); delay_us(DELAY_P1B); } } /* Read 16-bit data word from the PIC (LSB first) through a REGOUT inst */ uint16_t dspic33e::read_data(void) { uint8_t i; uint16_t data = 0; GPIO_CLR(pic_data); GPIO_CLR(pic_clk); /* send the REGOUT=0x0001 instruction */ for (i = 0; i < 4; i++) { if ( (0x0001 >> i) & 0x001 ) GPIO_SET(pic_data); else GPIO_CLR(pic_data); delay_us(DELAY_P1A); GPIO_SET(pic_clk); delay_us(DELAY_P1B); GPIO_CLR(pic_clk); } delay_us(DELAY_P4); /* idle for 8 clock cycles, waiting for the data to be ready */ for (i = 0; i < 8; i++) { GPIO_SET(pic_clk); delay_us(DELAY_P1B); GPIO_CLR(pic_clk); delay_us(DELAY_P1A); } delay_us(DELAY_P5); GPIO_IN(pic_data); /* read a 16-bit data word */ for (i = 0; i < 16; i++) { GPIO_SET(pic_clk); delay_us(DELAY_P1B); data |= ( GPIO_LEV(pic_data) & 0x00000001 ) << i; GPIO_CLR(pic_clk); delay_us(DELAY_P1A); } delay_us(DELAY_P4A); GPIO_OUT(pic_data); return data; } /* enter program mode */ void dspic33e::enter_program_mode(void) { int i; GPIO_IN(pic_mclr); GPIO_OUT(pic_mclr); GPIO_CLR(pic_clk); GPIO_CLR(pic_mclr); /* remove VDD from MCLR pin */ delay_us(DELAY_P6); GPIO_SET(pic_mclr); /* apply VDD to MCLR pin */ delay_us(DELAY_P21); GPIO_CLR(pic_mclr); /* remove VDD from MCLR pin */ delay_us(DELAY_P18); /* Shift in the "enter program mode" key sequence (MSB first) */ for (i = 31; i > -1; i--) { if ( (ENTER_PROGRAM_KEY >> i) & 0x01 ) GPIO_SET(pic_data); else GPIO_CLR(pic_data); delay_us(DELAY_P1A); GPIO_SET(pic_clk); delay_us(DELAY_P1B); GPIO_CLR(pic_clk); } GPIO_CLR(pic_data); delay_us(DELAY_P19); GPIO_SET(pic_mclr); if(subfamily == SF_DSPIC33E) delay_us(DELAY_P7_DSPIC33E); else if(subfamily == SF_PIC24FJ) delay_us(DELAY_P7_PIC24FJ); /* idle for 5 clock cycles */ for (i = 0; i < 5; i++) { GPIO_SET(pic_clk); delay_us(DELAY_P1B); GPIO_CLR(pic_clk); delay_us(DELAY_P1A); } } /* exit program mode */ void dspic33e::exit_program_mode(void) { GPIO_CLR(pic_clk); GPIO_CLR(pic_data); delay_us(DELAY_P16); GPIO_CLR(pic_mclr); /* remove VDD from MCLR pin */ delay_us(DELAY_P17); /* wait (at least) P17 */ GPIO_SET(pic_mclr); GPIO_IN(pic_mclr); } /* read the device ID and revision; returns only the id */ bool dspic33e::read_device_id(void) { bool found = 0; send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); send_cmd(0x200FF0); send_cmd(0x8802A0); send_cmd(0x200006); send_cmd(0x20F887); send_nop(); send_cmd(0xBA0BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); device_id = read_data(); send_cmd(0xBA0BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); device_rev = read_data(); reset_pc(); send_nop(); for (unsigned short i=0;i < sizeof(piclist)/sizeof(piclist[0]);i++){ if (piclist[i].device_id == device_id){ strcpy(name, piclist[i].name); mem.code_memory_size = piclist[i].code_memory_size; mem.program_memory_size = 0x0F80018; mem.location = (uint16_t*) calloc(mem.program_memory_size,sizeof(uint16_t)); mem.filled = (bool*) calloc(mem.program_memory_size,sizeof(bool)); found = 1; break; } } return found; } /* Check if the device is blank */ uint8_t dspic33e::blank_check(void) { uint32_t addr; unsigned short i; uint16_t data[8], raw_data[6]; uint8_t ret = 0; if(!flags.debug) cerr << "[ 0%]"; counter=0; /* exit reset vector */ send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); /* Output data to W0:W5; repeat until all desired code memory is read. */ for(addr=0; addr < mem.code_memory_size; addr=addr+8) { if((addr & 0x0000FFFF) == 0){ send_cmd(0x200000 | ((addr & 0x00FF0000) >> 12) ); // MOV #<DestAddress23:16>, W0 send_cmd(0x8802A0); // MOV W0, TBLPAG send_cmd(0x200006 | ((addr & 0x0000FFFF) << 4) ); // MOV #<DestAddress15:0>, W6 } /* Fetch the next four memory locations and put them to W0:W5 */ send_cmd(0xEB0380); // CLR W7 send_nop(); send_cmd(0xBA1B96); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBD6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA1BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA1B96); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBD6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA0BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); /* read six data words (16 bits each) */ for(i=0; i<6; i++){ send_cmd(0x887C40 + i); send_nop(); raw_data[i] = read_data(); send_nop(); } send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); /* store data correctly */ data[0] = raw_data[0]; data[1] = raw_data[1] & 0x00FF; data[3] = (raw_data[1] & 0xFF00) >> 8; data[2] = raw_data[2]; data[4] = raw_data[3]; data[5] = raw_data[4] & 0x00FF; data[7] = (raw_data[4] & 0xFF00) >> 8; data[6] = raw_data[5]; if(counter != addr*100/mem.code_memory_size){ counter = addr*100/mem.code_memory_size; fprintf(stderr, "\b\b\b\b\b[%2d%%]", counter); } for(i=0; i<8; i++){ if(flags.debug) fprintf(stderr, "\n addr = 0x%06X data = 0x%04X", (addr+i), data[i]); if ((i%2 == 0 && data[i] != 0xFFFF) || (i%2 == 1 && data[i] != 0x00FF)) { if(!flags.debug) cerr << "\b\b\b\b\b"; ret = 1; addr = mem.code_memory_size + 10; break; } } } if(addr <= (mem.code_memory_size + 8)){ if(!flags.debug) cerr << "\b\b\b\b\b"; ret = 0; }; send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); return ret; } /* Bulk erase the chip */ void dspic33e::bulk_erase(void) { send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); send_cmd(0x2400EA); send_cmd(0x88394A); send_nop(); send_nop(); send_cmd(0x200551); send_cmd(0x883971); send_cmd(0x200AA1); send_cmd(0x883971); send_cmd(0xA8E729); send_nop(); send_nop(); send_nop(); if(subfamily == SF_DSPIC33E) delay_us(DELAY_P11_DSPIC33E); else if(subfamily == SF_PIC24FJ) delay_us(DELAY_P11_PIC24FJ); /* wait while the erase operation completes */ do{ send_cmd(0x803940); send_nop(); send_cmd(0x887C40); send_nop(); nvmcon = read_data(); send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); } while((nvmcon & 0x8000) == 0x8000); if(flags.client) fprintf(stdout, "@FIN"); } /* Read PIC memory and write the contents to a .hex file */ void dspic33e::read(char *outfile, uint32_t start, uint32_t count) { uint32_t addr, startaddr, stopaddr; uint16_t data[8], raw_data[6]; int i=0; startaddr = start; stopaddr = mem.code_memory_size; if(count != 0 && count < stopaddr){ stopaddr = startaddr + count; fprintf(stderr, "Read only %d memory locations, from %06X to %06X\n", count, startaddr, stopaddr); } if(!flags.debug) cerr << "[ 0%]"; if(flags.client) fprintf(stdout, "@000"); counter=0; /* exit reset vector */ send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); /* Output data to W0:W5; repeat until all desired code memory is read. */ for(addr=startaddr; addr < stopaddr; addr=addr+8) { if((addr & 0x0000FFFF) == 0 || startaddr != 0){ send_cmd(0x200000 | ((addr & 0x00FF0000) >> 12) ); // MOV #<DestAddress23:16>, W0 send_cmd(0x8802A0); // MOV W0, TBLPAG send_cmd(0x200006 | ((addr & 0x0000FFFF) << 4) ); // MOV #<DestAddress15:0>, W6 startaddr = 0; } /* Fetch the next four memory locations and put them to W0:W5 */ send_cmd(0xEB0380); // CLR W7 send_nop(); send_cmd(0xBA1B96); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBD6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA1BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA1B96); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBD6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA0BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); /* read six data words (16 bits each) */ for(i=0; i<6; i++){ send_cmd(0x887C40 + i); send_nop(); raw_data[i] = read_data(); send_nop(); } send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); /* store data correctly */ data[0] = raw_data[0]; data[1] = raw_data[1] & 0x00FF; data[3] = (raw_data[1] & 0xFF00) >> 8; data[2] = raw_data[2]; data[4] = raw_data[3]; data[5] = raw_data[4] & 0x00FF; data[7] = (raw_data[4] & 0xFF00) >> 8; data[6] = raw_data[5]; for(i=0; i<8; i++){ if (flags.debug) fprintf(stderr, "\n addr = 0x%06X data = 0x%04X", (addr+i), data[i]); if (i%2 == 0 && data[i] != 0xFFFF) { mem.location[addr+i] = data[i]; mem.filled[addr+i] = 1; } if (i%2 == 1 && data[i] != 0x00FF) { mem.location[addr+i] = data[i]; mem.filled[addr+i] = 1; } } if(counter != addr*100/stopaddr){ counter = addr*100/stopaddr; if(flags.client) fprintf(stdout,"@%03d", counter); if(!flags.debug) fprintf(stderr,"\b\b\b\b\b[%2d%%]", counter); } /* TODO: checksum */ } send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); send_cmd(0x200F80); send_cmd(0x8802A0); send_cmd(0x200046); send_cmd(0x20F887); send_nop(); addr = 0x00F80004; for(i=0; i<8; i++){ send_cmd(0xBA0BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); data[0] = read_data(); if (data[0] != 0xFFFF) { mem.location[addr+2*i] = data[0]; mem.filled[addr+2*i] = 1; } } send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); if(!flags.debug) cerr << "\b\b\b\b\b"; if(flags.client) fprintf(stdout, "@FIN"); write_inhx(&mem, outfile); } /* Write contents of the .hex file to the PIC */ void dspic33e::write(char *infile) { uint16_t i,j,p; uint16_t k; bool skip; uint32_t data[8],raw_data[6]; uint32_t addr = 0; unsigned int filled_locations=1; const char *regname[] = {"FGS","FOSCSEL","FOSC","FWDT","FPOR", "FICD","FAS","FUID0"}; filled_locations = read_inhx(infile, &mem); if(!filled_locations) return; bulk_erase(); /* Exit reset vector */ send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); /* WRITE CODE MEMORY */ if(!flags.debug) cerr << "[ 0%]"; if(flags.client) fprintf(stdout, "@000"); counter=0; for (addr = 0; addr < mem.code_memory_size; ){ skip = 1; for(k=0; k<256; k+=2) if(mem.filled[addr+k]) skip = 0; if(skip){ addr=addr+256; continue; } /* Set the NVMADRU/NVMADR register-pair to point to the correct row */ send_cmd(0x200002 | ((addr & 0x0000FFFF) << 4) ); send_cmd(0x200003 | ((addr & 0x00FF0000) >> 12) ); send_cmd(0x883963); send_cmd(0x883952); send_cmd(0x200FAC); send_cmd(0x8802AC); send_cmd(0x200007); for(p=0; p<32; p++){ for(j=0;j<8;j++){ if (mem.filled[addr+j]) data[j] = mem.location[addr+j]; else data[j] = 0xFFFF; if(flags.debug) fprintf(stderr,"\n Writing 0x%04X to address 0x%06X ", data[j], addr+j ); } send_cmd(0x200000 | (data[0] << 4)); // MOV #<LSW0>, W0 send_cmd(0x200001 | (0x00FFFF & ((data[3] << 8) | (data[1] & 0x00FF))) <<4);// MOV #<MSB1:MSB0>, W1 send_cmd(0x200002 | (data[2] << 4)); // MOV #<LSW1>, W2 send_cmd(0x200003 | (data[4] << 4)); // MOV #<LSW2>, W3 send_cmd(0x200004 | (0x00FFFF & ((data[7] << 8) | (data[5] & 0x00FF))) <<4);// MOV #<MSB3:MSB2>, W4 send_cmd(0x200005 | (data[6] << 4)); // MOV #<LSW3>, W5 /* set_W6_and_load_latches */ send_cmd(0xEB0300); send_nop(); send_cmd(0xBB0BB6); send_nop(); send_nop(); send_cmd(0xBBDBB6); send_nop(); send_nop(); send_cmd(0xBBEBB6); send_nop(); send_nop(); send_cmd(0xBB1BB6); send_nop(); send_nop(); send_cmd(0xBB0BB6); send_nop(); send_nop(); send_cmd(0xBBDBB6); send_nop(); send_nop(); send_cmd(0xBBEBB6); send_nop(); send_nop(); send_cmd(0xBB1BB6); send_nop(); send_nop(); addr = addr+8; } /* Set the NVMCON to program 128 instruction words */ send_cmd(0x24002A); send_cmd(0x88394A); send_nop(); send_nop(); /* Initiate the write cycle */ send_cmd(0x200551); send_cmd(0x883971); send_cmd(0x200AA1); send_cmd(0x883971); send_cmd(0xA8E729); send_prog_nop(); // FIXME: timing??? if(subfamily == SF_DSPIC33E) delay_us(DELAY_P13_DSPIC33E); else if(subfamily == SF_PIC24FJ) delay_us(DELAY_P13_PIC24FJ); do{ send_nop(); send_cmd(0x803940); send_nop(); send_cmd(0x887C40); send_nop(); nvmcon = read_data(); send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); } while((nvmcon & 0x8000) == 0x8000); if(counter != addr*100/filled_locations){ if(flags.client) fprintf(stdout,"@%03d", (addr*100/(filled_locations+0x100))); if(!flags.debug) fprintf(stderr,"\b\b\b\b\b[%2d%%]", addr*100/(filled_locations+0x100)); counter = addr*100/filled_locations; } }; if(!flags.debug) cerr << "\b\b\b\b\b\b"; if(flags.client) fprintf(stdout, "@100"); delay_us(100000); /* WRITE CONFIGURATION REGISTERS */ if(flags.debug) cerr << endl << "Writing Configuration registers..." << endl; send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); send_cmd(0x200007); send_cmd(0x200FAC); send_cmd(0x8802AC); addr = 0x00F80004; for(i=0; i<8; i++){ if(mem.filled[addr]){ send_cmd(0x200000 | ((0x0000FFFF & mem.location[addr]) << 4)); send_cmd(0xBB0B80); send_nop(); send_nop(); send_cmd(0x200002 | ((addr & 0x0000FFFF) << 4)); send_cmd(0x200F83); send_cmd(0x883963); send_cmd(0x883952); /* Set the NVMCON register to program one Configuration register */ send_cmd(0x24000A); send_cmd(0x88394A); send_nop(); send_nop(); /* Initiate the write cycle */ send_cmd(0x200551); send_cmd(0x883971); send_cmd(0x200AA1); send_cmd(0x883971); send_cmd(0xA8E729); send_nop(); send_nop(); send_nop(); delay_us(DELAY_P20); do{ send_nop(); send_cmd(0x803940); send_nop(); send_cmd(0x887C40); send_nop(); nvmcon = read_data(); send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); } while((nvmcon & 0x8000) == 0x8000); if(flags.debug) fprintf(stderr,"\n - %s set to 0x%01x", regname[i], mem.location[addr]); } else if(flags.debug) fprintf(stderr,"\n - %s left unchanged", regname[i]); addr = addr+2; } if(flags.debug) cerr << endl; delay_us(100000); /* VERIFY CODE MEMORY */ if(!flags.noverify){ if(!flags.debug) cerr << "[ 0%]"; if(flags.client) fprintf(stdout, "@000"); counter = 0; send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); for(addr=0; addr < mem.code_memory_size; addr=addr+8) { skip=1; for(k=0; k<8; k+=2) if(mem.filled[addr+k]) skip = 0; if(skip) continue; send_cmd(0x200000 | ((addr & 0x00FF0000) >> 12) ); // MOV #<DestAddress23:16>, W0 send_cmd(0x8802A0); // MOV W0, TBLPAG send_cmd(0x200006 | ((addr & 0x0000FFFF) << 4) ); // MOV #<DestAddress15:0>, W6 /* Fetch the next four memory locations and put them to W0:W5 */ send_cmd(0xEB0380); // CLR W7 send_nop(); send_cmd(0xBA1B96); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBD6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA1BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA1B96); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBADBD6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); send_cmd(0xBA0BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); /* read six data words (16 bits each) */ for(i=0; i<6; i++){ send_cmd(0x887C40 + i); send_nop(); raw_data[i] = read_data(); send_nop(); } send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); /* store data correctly */ data[0] = raw_data[0]; data[1] = raw_data[1] & 0x00FF; data[3] = (raw_data[1] & 0xFF00) >> 8; data[2] = raw_data[2]; data[4] = raw_data[3]; data[5] = raw_data[4] & 0x00FF; data[7] = (raw_data[4] & 0xFF00) >> 8; data[6] = raw_data[5]; for(i=0; i<8; i++){ if (flags.debug) fprintf(stderr, "\n addr = 0x%06X data = 0x%04X", (addr+i), data[i]); if(mem.filled[addr+i] && data[i] != mem.location[addr+i]){ fprintf(stderr,"\n\n ERROR at address %06X: written %04X but %04X read!\n\n", addr+i, mem.location[addr+i], data[i]); return; } } if(counter != addr*100/filled_locations){ if(flags.client) fprintf(stdout,"@%03d", (addr*100/(filled_locations+0x100))); if(!flags.debug) fprintf(stderr,"\b\b\b\b\b[%2d%%]", addr*100/(filled_locations+0x100)); counter = addr*100/filled_locations; } } if(!flags.debug) cerr << "\b\b\b\b\b"; if(flags.client) fprintf(stdout, "@FIN"); } else{ if(flags.client) fprintf(stdout, "@FIN"); } } /* write to screen the configuration registers, without saving them anywhere */ void dspic33e::dump_configuration_registers(void) { const char *regname[] = {"FGS","FOSCSEL","FOSC","FWDT","FPOR", "FICD","FAS","FUID0"}; cerr << endl << "Configuration registers:" << endl << endl; send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); send_cmd(0x200F80); send_cmd(0x8802A0); send_cmd(0x200046); send_cmd(0x20F887); send_nop(); for(unsigned short i=0; i<8; i++){ send_cmd(0xBA0BB6); send_nop(); send_nop(); send_nop(); send_nop(); send_nop(); fprintf(stderr," - %s: 0x%02x\n", regname[i], read_data()); } cerr << endl; send_nop(); send_nop(); send_nop(); reset_pc(); send_nop(); send_nop(); send_nop(); }