text
stringlengths 5
1.04M
|
|---|
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fidl/fuchsia.driver.framework/cpp/wire.h>
#include <lib/async/cpp/executor.h>
#include <lib/ddk/debug.h>
#include <lib/driver2/devfs_exporter.h>
#include <lib/driver2/driver2.h>
#include <lib/driver2/inspect.h>
#include <lib/fpromise/scope.h>
#include <lib/service/llcpp/outgoing_directory.h>
#include <lib/sys/component/llcpp/outgoing_directory.h>
#include <zircon/errors.h>
#include "src/devices/lib/compat/compat.h"
#include "src/devices/lib/compat/symbols.h"
#include "src/ui/input/drivers/hid-input-report/input-report.h"
namespace fdf2 = fuchsia_driver_framework;
namespace fio = fuchsia_io;
namespace {
class InputReportDriver {
public:
InputReportDriver(async_dispatcher_t* dispatcher, fidl::WireSharedClient<fdf2::Node> node,
driver::Namespace ns, component::OutgoingDirectory outgoing,
driver::Logger logger)
: dispatcher_(dispatcher),
outgoing_(std::move(outgoing)),
node_(std::move(node)),
ns_(std::move(ns)),
logger_(std::move(logger)),
executor_(dispatcher) {}
static constexpr const char* Name() { return "InputReport"; }
static zx::status<std::unique_ptr<InputReportDriver>> Start(
fdf2::wire::DriverStartArgs& start_args, async_dispatcher_t* dispatcher,
fidl::WireSharedClient<fdf2::Node> node, driver::Namespace ns, driver::Logger logger) {
auto outgoing = component::OutgoingDirectory::Create(dispatcher);
auto driver = std::make_unique<InputReportDriver>(dispatcher, std::move(node), std::move(ns),
std::move(outgoing), std::move(logger));
auto parent_symbol = driver::GetSymbol<compat::device_t*>(start_args, compat::kDeviceSymbol);
hid_device_protocol_t proto = {};
if (parent_symbol->proto_ops.id != ZX_PROTOCOL_HID_DEVICE) {
FDF_LOGL(ERROR, driver->logger_, "Didn't find HID_DEVICE protocol");
return zx::error(ZX_ERR_NOT_FOUND);
}
proto.ctx = parent_symbol->context;
proto.ops = reinterpret_cast<hid_device_protocol_ops_t*>(parent_symbol->proto_ops.ops);
ddk::HidDeviceProtocolClient hiddev(&proto);
if (!hiddev.is_valid()) {
FDF_LOGL(ERROR, driver->logger_, "Failed to create hiddev");
return zx::error(ZX_ERR_INTERNAL);
}
driver->input_report_.emplace(std::move(hiddev));
auto result = driver->Run(std::move(start_args.outgoing_dir()));
if (result.is_error()) {
return result.take_error();
}
return zx::ok(std::move(driver));
}
private:
zx::status<> ConnectToDevfsExporter() {
// Connect to DevfsExporter.
auto endpoints = fidl::CreateEndpoints<fuchsia_io::Directory>();
if (endpoints.is_error()) {
return endpoints.take_error();
}
// Serve a connection to outgoing.
auto status = outgoing_.Serve(std::move(endpoints->server));
if (status.is_error()) {
return status.take_error();
}
auto exporter = driver::DevfsExporter::Create(
ns_, dispatcher_, fidl::WireSharedClient(std::move(endpoints->client), dispatcher_));
if (exporter.is_error()) {
return zx::error(exporter.error_value());
}
exporter_ = std::move(*exporter);
return zx::ok();
}
zx::status<> Run(fidl::ServerEnd<fio::Directory> outgoing_dir) {
// Expose the driver's inspect data.
auto exposed_inspector =
driver::ExposedInspector::Create(dispatcher_, input_report_->Inspector(), outgoing_);
if (exposed_inspector.is_error()) {
FDF_SLOG(ERROR, "Failed to expose inspector",
KV("error_string", exposed_inspector.status_string()));
return exposed_inspector.take_error();
}
exposed_inspector_ = std::move(exposed_inspector.value());
input_report_->Start();
// Connect to DevfsExporter.
auto status = ConnectToDevfsExporter();
if (status.is_error()) {
return status.take_error();
}
// Connect to our parent.
auto parent_client = compat::ConnectToParentDevice(dispatcher_, &ns_);
if (parent_client.is_error()) {
FDF_LOG(WARNING, "Connecting to compat service failed with %s",
zx_status_get_string(parent_client.error_value()));
return parent_client.take_error();
}
parent_client_ = std::move(parent_client.value());
auto compat_connect =
fpromise::make_result_promise<void, zx_status_t>(fpromise::ok())
.and_then([this]() {
fpromise::bridge<void, zx_status_t> topo_bridge;
parent_client_->GetTopologicalPath().Then(
[this, completer = std::move(topo_bridge.completer)](
fidl::WireUnownedResult<fuchsia_driver_compat::Device::GetTopologicalPath>&
result) mutable {
if (!result.ok()) {
completer.complete_error(result.status());
return;
}
auto* response = result.Unwrap();
parent_topo_path_ = std::string(response->path.data(), response->path.size());
completer.complete_ok();
});
return topo_bridge.consumer.promise_or(fpromise::error(ZX_ERR_CANCELED));
})
// Create our child device and FIDL server.
.and_then([this]() -> fpromise::promise<void, zx_status_t> {
child_ = compat::Child("InputReport", ZX_PROTOCOL_INPUTREPORT,
parent_topo_path_ + "/InputReport", {});
auto status = outgoing_.AddNamedProtocol(
[this](zx::channel channel) {
fidl::BindServer<fidl::WireServer<fuchsia_input_report::InputDevice>>(
dispatcher_,
fidl::ServerEnd<fuchsia_input_report::InputDevice>(std::move(channel)),
&input_report_.value());
},
"InputReport");
if (status.is_error()) {
return fpromise::make_result_promise<void, zx_status_t>(
fpromise::error(status.error_value()));
}
child_->AddCallback(std::make_shared<fit::deferred_callback>([this]() {
auto status = outgoing_.RemoveNamedProtocol("InputReport");
if (status.is_error()) {
FDF_LOG(WARNING, "Removing protocol failed with: %s", status.status_string());
}
}));
return exporter_.Export(std::string("svc/").append(child_->name()),
child_->topological_path(), ZX_PROTOCOL_INPUTREPORT);
})
// Error handling.
.or_else([this](zx_status_t& result) {
FDF_LOG(WARNING, "Device setup failed with: %s", zx_status_get_string(result));
});
executor_.schedule_task(std::move(compat_connect));
return outgoing_.Serve(std::move(outgoing_dir));
}
async_dispatcher_t* dispatcher_;
std::optional<hid_input_report_dev::InputReport> input_report_;
component::OutgoingDirectory outgoing_;
fidl::WireSharedClient<fdf2::Node> node_;
driver::Namespace ns_;
driver::Logger logger_;
inspect::Inspector inspector_;
zx::vmo inspect_vmo_;
async::Executor executor_;
std::optional<driver::ExposedInspector> exposed_inspector_;
std::optional<compat::Child> child_;
std::string parent_topo_path_;
fidl::WireSharedClient<fuchsia_driver_compat::Device> parent_client_;
driver::DevfsExporter exporter_;
// NOTE: Must be the last member.
fpromise::scope scope_;
};
} // namespace
// TODO(fxbug.dev/94884): Figure out how to get logging working.
zx_driver_rec_t __zircon_driver_rec__ = {};
void driver_logf_internal(const zx_driver_t* drv, fx_log_severity_t severity, const char* tag,
const char* file, int line, const char* msg, ...) {}
bool driver_log_severity_enabled_internal(const zx_driver_t* drv, fx_log_severity_t severity) {
return true;
}
FUCHSIA_DRIVER_RECORD_CPP_V1(InputReportDriver);
|
// 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/ui/ash/launcher/launcher_application_menu_item_model.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_per_app.h"
LauncherApplicationMenuItemModel::LauncherApplicationMenuItemModel(
ChromeLauncherAppMenuItems item_list)
: ALLOW_THIS_IN_INITIALIZER_LIST(ash::LauncherMenuModel(this)),
launcher_items_(item_list.Pass()) {
Build();
}
LauncherApplicationMenuItemModel::~LauncherApplicationMenuItemModel() {
}
bool LauncherApplicationMenuItemModel::IsCommandActive(int command_id) const {
DCHECK(command_id >= 0);
DCHECK(static_cast<size_t>(command_id) < launcher_items_.size());
return launcher_items_[command_id]->IsActive();
}
bool LauncherApplicationMenuItemModel::IsCommandIdChecked(
int command_id) const {
return false;
}
bool LauncherApplicationMenuItemModel::IsCommandIdEnabled(
int command_id) const {
DCHECK(command_id < static_cast<int>(launcher_items_.size()));
return launcher_items_[command_id]->IsEnabled();
}
bool LauncherApplicationMenuItemModel::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
void LauncherApplicationMenuItemModel::ExecuteCommand(int command_id) {
DCHECK(command_id < static_cast<int>(launcher_items_.size()));
launcher_items_[command_id]->Execute();
}
void LauncherApplicationMenuItemModel::Build() {
AddSeparator(ui::SPACING_SEPARATOR);
for (size_t i = 0; i < launcher_items_.size(); i++) {
ChromeLauncherAppMenuItem* item = launcher_items_[i];
// The first item is the context menu, the others are the running apps.
AddItem(i, item->title());
if (!item->icon().IsEmpty())
SetIcon(GetIndexOfCommandId(i), item->icon());
// The first item is most likely the application name which should get
// separated from the rest.
if (i == 0)
AddSeparator(ui::NORMAL_SEPARATOR);
}
RemoveTrailingSeparators();
}
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/objects.h"
#include "src/assembler-inl.h"
#include "src/bootstrapper.h"
#include "src/counters.h"
#include "src/date.h"
#include "src/disasm.h"
#include "src/disassembler.h"
#include "src/elements.h"
#include "src/field-type.h"
#include "src/heap/heap-write-barrier-inl.h"
#include "src/ic/handler-configuration-inl.h"
#include "src/layout-descriptor.h"
#include "src/objects-inl.h"
#include "src/objects/allocation-site-inl.h"
#include "src/objects/arguments-inl.h"
#include "src/objects/bigint.h"
#include "src/objects/cell-inl.h"
#include "src/objects/data-handler-inl.h"
#include "src/objects/debug-objects-inl.h"
#include "src/objects/embedder-data-array-inl.h"
#include "src/objects/embedder-data-slot-inl.h"
#include "src/objects/feedback-cell-inl.h"
#include "src/objects/foreign-inl.h"
#include "src/objects/free-space-inl.h"
#include "src/objects/hash-table-inl.h"
#include "src/objects/js-array-inl.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/js-break-iterator-inl.h"
#include "src/objects/js-collator-inl.h"
#endif // V8_INTL_SUPPORT
#include "src/objects/js-collection-inl.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/js-date-time-format-inl.h"
#endif // V8_INTL_SUPPORT
#include "src/objects/js-generator-inl.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/js-list-format-inl.h"
#include "src/objects/js-locale-inl.h"
#include "src/objects/js-number-format-inl.h"
#include "src/objects/js-plural-rules-inl.h"
#endif // V8_INTL_SUPPORT
#include "src/objects/js-regexp-inl.h"
#include "src/objects/js-regexp-string-iterator-inl.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/js-relative-time-format-inl.h"
#include "src/objects/js-segment-iterator-inl.h"
#include "src/objects/js-segmenter-inl.h"
#endif // V8_INTL_SUPPORT
#include "src/objects/js-weak-refs-inl.h"
#include "src/objects/literal-objects-inl.h"
#include "src/objects/maybe-object.h"
#include "src/objects/microtask-inl.h"
#include "src/objects/module-inl.h"
#include "src/objects/oddball-inl.h"
#include "src/objects/promise-inl.h"
#include "src/objects/stack-frame-info-inl.h"
#include "src/objects/struct-inl.h"
#include "src/ostreams.h"
#include "src/regexp/jsregexp.h"
#include "src/transitions-inl.h"
#include "src/wasm/wasm-objects-inl.h"
namespace v8 {
namespace internal {
// Heap Verification Overview
// --------------------------
// - Each InstanceType has a separate XXXVerify method which checks an object's
// integrity in isolation.
// - --verify-heap will iterate over all gc spaces and call ObjectVerify() on
// every encountered tagged pointer.
// - Verification should be pushed down to the specific instance type if its
// integrity is independent of an outer object.
// - In cases where the InstanceType is too genernic (e.g. FixedArray) the
// XXXVerify of the outer method has to do recursive verification.
// - If the corresponding objects have inheritence the parent's Verify method
// is called as well.
// - For any field containing pointes VerifyPointer(...) should be called.
//
// Caveats
// -------
// - Assume that any of the verify methods is incomplete!
// - Some integrity checks are only partially done due to objects being in
// partially initialized states when a gc happens, for instance when outer
// objects are allocted before inner ones.
//
#ifdef VERIFY_HEAP
void Object::ObjectVerify(Isolate* isolate) {
RuntimeCallTimerScope timer(isolate, RuntimeCallCounterId::kObjectVerify);
if (IsSmi()) {
Smi::cast(*this)->SmiVerify(isolate);
} else {
HeapObject::cast(*this)->HeapObjectVerify(isolate);
}
CHECK(!IsConstructor() || IsCallable());
}
void Object::VerifyPointer(Isolate* isolate, Object p) {
if (p->IsHeapObject()) {
HeapObject::VerifyHeapPointer(isolate, p);
} else {
CHECK(p->IsSmi());
}
}
void MaybeObject::VerifyMaybeObjectPointer(Isolate* isolate, MaybeObject p) {
HeapObject heap_object;
if (p->GetHeapObject(&heap_object)) {
HeapObject::VerifyHeapPointer(isolate, heap_object);
} else {
CHECK(p->IsSmi() || p->IsCleared());
}
}
namespace {
void VerifyForeignPointer(Isolate* isolate, HeapObject host, Object foreign) {
host->VerifyPointer(isolate, foreign);
CHECK(foreign->IsUndefined(isolate) || Foreign::IsNormalized(foreign));
}
} // namespace
void Smi::SmiVerify(Isolate* isolate) {
CHECK(IsSmi());
CHECK(!IsCallable());
CHECK(!IsConstructor());
}
void HeapObject::HeapObjectVerify(Isolate* isolate) {
VerifyHeapPointer(isolate, map());
CHECK(map()->IsMap());
switch (map()->instance_type()) {
#define STRING_TYPE_CASE(TYPE, size, name, CamelName) case TYPE:
STRING_TYPE_LIST(STRING_TYPE_CASE)
#undef STRING_TYPE_CASE
String::cast(*this)->StringVerify(isolate);
break;
case SYMBOL_TYPE:
Symbol::cast(*this)->SymbolVerify(isolate);
break;
case MAP_TYPE:
Map::cast(*this)->MapVerify(isolate);
break;
case HEAP_NUMBER_TYPE:
CHECK(IsHeapNumber());
break;
case MUTABLE_HEAP_NUMBER_TYPE:
CHECK(IsMutableHeapNumber());
break;
case BIGINT_TYPE:
BigInt::cast(*this)->BigIntVerify(isolate);
break;
case CALL_HANDLER_INFO_TYPE:
CallHandlerInfo::cast(*this)->CallHandlerInfoVerify(isolate);
break;
case OBJECT_BOILERPLATE_DESCRIPTION_TYPE:
ObjectBoilerplateDescription::cast(*this)
->ObjectBoilerplateDescriptionVerify(isolate);
break;
case EMBEDDER_DATA_ARRAY_TYPE:
EmbedderDataArray::cast(*this)->EmbedderDataArrayVerify(isolate);
break;
// FixedArray types
case CLOSURE_FEEDBACK_CELL_ARRAY_TYPE:
case HASH_TABLE_TYPE:
case ORDERED_HASH_MAP_TYPE:
case ORDERED_HASH_SET_TYPE:
case ORDERED_NAME_DICTIONARY_TYPE:
case NAME_DICTIONARY_TYPE:
case GLOBAL_DICTIONARY_TYPE:
case NUMBER_DICTIONARY_TYPE:
case SIMPLE_NUMBER_DICTIONARY_TYPE:
case STRING_TABLE_TYPE:
case EPHEMERON_HASH_TABLE_TYPE:
case FIXED_ARRAY_TYPE:
case SCOPE_INFO_TYPE:
case SCRIPT_CONTEXT_TABLE_TYPE:
FixedArray::cast(*this)->FixedArrayVerify(isolate);
break;
case AWAIT_CONTEXT_TYPE:
case BLOCK_CONTEXT_TYPE:
case CATCH_CONTEXT_TYPE:
case DEBUG_EVALUATE_CONTEXT_TYPE:
case EVAL_CONTEXT_TYPE:
case FUNCTION_CONTEXT_TYPE:
case MODULE_CONTEXT_TYPE:
case SCRIPT_CONTEXT_TYPE:
case WITH_CONTEXT_TYPE:
Context::cast(*this)->ContextVerify(isolate);
break;
case NATIVE_CONTEXT_TYPE:
NativeContext::cast(*this)->NativeContextVerify(isolate);
break;
case WEAK_FIXED_ARRAY_TYPE:
WeakFixedArray::cast(*this)->WeakFixedArrayVerify(isolate);
break;
case WEAK_ARRAY_LIST_TYPE:
WeakArrayList::cast(*this)->WeakArrayListVerify(isolate);
break;
case FIXED_DOUBLE_ARRAY_TYPE:
FixedDoubleArray::cast(*this)->FixedDoubleArrayVerify(isolate);
break;
case FEEDBACK_METADATA_TYPE:
FeedbackMetadata::cast(*this)->FeedbackMetadataVerify(isolate);
break;
case BYTE_ARRAY_TYPE:
ByteArray::cast(*this)->ByteArrayVerify(isolate);
break;
case BYTECODE_ARRAY_TYPE:
BytecodeArray::cast(*this)->BytecodeArrayVerify(isolate);
break;
case DESCRIPTOR_ARRAY_TYPE:
DescriptorArray::cast(*this)->DescriptorArrayVerify(isolate);
break;
case TRANSITION_ARRAY_TYPE:
TransitionArray::cast(*this)->TransitionArrayVerify(isolate);
break;
case PROPERTY_ARRAY_TYPE:
PropertyArray::cast(*this)->PropertyArrayVerify(isolate);
break;
case FREE_SPACE_TYPE:
FreeSpace::cast(*this)->FreeSpaceVerify(isolate);
break;
case FEEDBACK_CELL_TYPE:
FeedbackCell::cast(*this)->FeedbackCellVerify(isolate);
break;
case FEEDBACK_VECTOR_TYPE:
FeedbackVector::cast(*this)->FeedbackVectorVerify(isolate);
break;
#define VERIFY_TYPED_ARRAY(Type, type, TYPE, ctype) \
case FIXED_##TYPE##_ARRAY_TYPE: \
Fixed##Type##Array::cast(*this)->FixedTypedArrayVerify(isolate); \
break;
TYPED_ARRAYS(VERIFY_TYPED_ARRAY)
#undef VERIFY_TYPED_ARRAY
case CODE_TYPE:
Code::cast(*this)->CodeVerify(isolate);
break;
case ODDBALL_TYPE:
Oddball::cast(*this)->OddballVerify(isolate);
break;
case JS_OBJECT_TYPE:
case JS_ERROR_TYPE:
case JS_API_OBJECT_TYPE:
case JS_SPECIAL_API_OBJECT_TYPE:
case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
case WASM_EXCEPTION_TYPE:
case WASM_GLOBAL_TYPE:
case WASM_MEMORY_TYPE:
case WASM_TABLE_TYPE:
JSObject::cast(*this)->JSObjectVerify(isolate);
break;
case WASM_MODULE_TYPE:
WasmModuleObject::cast(*this)->WasmModuleObjectVerify(isolate);
break;
case WASM_INSTANCE_TYPE:
WasmInstanceObject::cast(*this)->WasmInstanceObjectVerify(isolate);
break;
case JS_ARGUMENTS_TYPE:
JSArgumentsObject::cast(*this)->JSArgumentsObjectVerify(isolate);
break;
case JS_GENERATOR_OBJECT_TYPE:
JSGeneratorObject::cast(*this)->JSGeneratorObjectVerify(isolate);
break;
case JS_ASYNC_FUNCTION_OBJECT_TYPE:
JSAsyncFunctionObject::cast(*this)->JSAsyncFunctionObjectVerify(isolate);
break;
case JS_ASYNC_GENERATOR_OBJECT_TYPE:
JSAsyncGeneratorObject::cast(*this)->JSAsyncGeneratorObjectVerify(
isolate);
break;
case JS_VALUE_TYPE:
JSValue::cast(*this)->JSValueVerify(isolate);
break;
case JS_DATE_TYPE:
JSDate::cast(*this)->JSDateVerify(isolate);
break;
case JS_BOUND_FUNCTION_TYPE:
JSBoundFunction::cast(*this)->JSBoundFunctionVerify(isolate);
break;
case JS_FUNCTION_TYPE:
JSFunction::cast(*this)->JSFunctionVerify(isolate);
break;
case JS_GLOBAL_PROXY_TYPE:
JSGlobalProxy::cast(*this)->JSGlobalProxyVerify(isolate);
break;
case JS_GLOBAL_OBJECT_TYPE:
JSGlobalObject::cast(*this)->JSGlobalObjectVerify(isolate);
break;
case CELL_TYPE:
Cell::cast(*this)->CellVerify(isolate);
break;
case PROPERTY_CELL_TYPE:
PropertyCell::cast(*this)->PropertyCellVerify(isolate);
break;
case JS_ARRAY_TYPE:
JSArray::cast(*this)->JSArrayVerify(isolate);
break;
case JS_MODULE_NAMESPACE_TYPE:
JSModuleNamespace::cast(*this)->JSModuleNamespaceVerify(isolate);
break;
case JS_SET_TYPE:
JSSet::cast(*this)->JSSetVerify(isolate);
break;
case JS_MAP_TYPE:
JSMap::cast(*this)->JSMapVerify(isolate);
break;
case JS_SET_KEY_VALUE_ITERATOR_TYPE:
case JS_SET_VALUE_ITERATOR_TYPE:
JSSetIterator::cast(*this)->JSSetIteratorVerify(isolate);
break;
case JS_MAP_KEY_ITERATOR_TYPE:
case JS_MAP_KEY_VALUE_ITERATOR_TYPE:
case JS_MAP_VALUE_ITERATOR_TYPE:
JSMapIterator::cast(*this)->JSMapIteratorVerify(isolate);
break;
case JS_ARRAY_ITERATOR_TYPE:
JSArrayIterator::cast(*this)->JSArrayIteratorVerify(isolate);
break;
case JS_STRING_ITERATOR_TYPE:
JSStringIterator::cast(*this)->JSStringIteratorVerify(isolate);
break;
case JS_ASYNC_FROM_SYNC_ITERATOR_TYPE:
JSAsyncFromSyncIterator::cast(*this)->JSAsyncFromSyncIteratorVerify(
isolate);
break;
case WEAK_CELL_TYPE:
WeakCell::cast(*this)->WeakCellVerify(isolate);
break;
case JS_WEAK_REF_TYPE:
JSWeakRef::cast(*this)->JSWeakRefVerify(isolate);
break;
case JS_FINALIZATION_GROUP_TYPE:
JSFinalizationGroup::cast(*this)->JSFinalizationGroupVerify(isolate);
break;
case JS_FINALIZATION_GROUP_CLEANUP_ITERATOR_TYPE:
JSFinalizationGroupCleanupIterator::cast(*this)
->JSFinalizationGroupCleanupIteratorVerify(isolate);
break;
case JS_WEAK_MAP_TYPE:
JSWeakMap::cast(*this)->JSWeakMapVerify(isolate);
break;
case JS_WEAK_SET_TYPE:
JSWeakSet::cast(*this)->JSWeakSetVerify(isolate);
break;
case JS_PROMISE_TYPE:
JSPromise::cast(*this)->JSPromiseVerify(isolate);
break;
case JS_REGEXP_TYPE:
JSRegExp::cast(*this)->JSRegExpVerify(isolate);
break;
case JS_REGEXP_STRING_ITERATOR_TYPE:
JSRegExpStringIterator::cast(*this)->JSRegExpStringIteratorVerify(
isolate);
break;
case FILLER_TYPE:
break;
case JS_PROXY_TYPE:
JSProxy::cast(*this)->JSProxyVerify(isolate);
break;
case FOREIGN_TYPE:
Foreign::cast(*this)->ForeignVerify(isolate);
break;
case PREPARSE_DATA_TYPE:
PreparseData::cast(*this)->PreparseDataVerify(isolate);
break;
case UNCOMPILED_DATA_WITHOUT_PREPARSE_DATA_TYPE:
UncompiledDataWithoutPreparseData::cast(*this)
->UncompiledDataWithoutPreparseDataVerify(isolate);
break;
case UNCOMPILED_DATA_WITH_PREPARSE_DATA_TYPE:
UncompiledDataWithPreparseData::cast(*this)
->UncompiledDataWithPreparseDataVerify(isolate);
break;
case SHARED_FUNCTION_INFO_TYPE:
SharedFunctionInfo::cast(*this)->SharedFunctionInfoVerify(isolate);
break;
case JS_MESSAGE_OBJECT_TYPE:
JSMessageObject::cast(*this)->JSMessageObjectVerify(isolate);
break;
case JS_ARRAY_BUFFER_TYPE:
JSArrayBuffer::cast(*this)->JSArrayBufferVerify(isolate);
break;
case JS_TYPED_ARRAY_TYPE:
JSTypedArray::cast(*this)->JSTypedArrayVerify(isolate);
break;
case JS_DATA_VIEW_TYPE:
JSDataView::cast(*this)->JSDataViewVerify(isolate);
break;
case SMALL_ORDERED_HASH_SET_TYPE:
SmallOrderedHashSet::cast(*this)->SmallOrderedHashSetVerify(isolate);
break;
case SMALL_ORDERED_HASH_MAP_TYPE:
SmallOrderedHashMap::cast(*this)->SmallOrderedHashMapVerify(isolate);
break;
case SMALL_ORDERED_NAME_DICTIONARY_TYPE:
SmallOrderedNameDictionary::cast(*this)->SmallOrderedNameDictionaryVerify(
isolate);
break;
case CODE_DATA_CONTAINER_TYPE:
CodeDataContainer::cast(*this)->CodeDataContainerVerify(isolate);
break;
#ifdef V8_INTL_SUPPORT
case JS_INTL_V8_BREAK_ITERATOR_TYPE:
JSV8BreakIterator::cast(*this)->JSV8BreakIteratorVerify(isolate);
break;
case JS_INTL_COLLATOR_TYPE:
JSCollator::cast(*this)->JSCollatorVerify(isolate);
break;
case JS_INTL_DATE_TIME_FORMAT_TYPE:
JSDateTimeFormat::cast(*this)->JSDateTimeFormatVerify(isolate);
break;
case JS_INTL_LIST_FORMAT_TYPE:
JSListFormat::cast(*this)->JSListFormatVerify(isolate);
break;
case JS_INTL_LOCALE_TYPE:
JSLocale::cast(*this)->JSLocaleVerify(isolate);
break;
case JS_INTL_NUMBER_FORMAT_TYPE:
JSNumberFormat::cast(*this)->JSNumberFormatVerify(isolate);
break;
case JS_INTL_PLURAL_RULES_TYPE:
JSPluralRules::cast(*this)->JSPluralRulesVerify(isolate);
break;
case JS_INTL_RELATIVE_TIME_FORMAT_TYPE:
JSRelativeTimeFormat::cast(*this)->JSRelativeTimeFormatVerify(isolate);
break;
case JS_INTL_SEGMENT_ITERATOR_TYPE:
JSSegmentIterator::cast(*this)->JSSegmentIteratorVerify(isolate);
break;
case JS_INTL_SEGMENTER_TYPE:
JSSegmenter::cast(*this)->JSSegmenterVerify(isolate);
break;
#endif // V8_INTL_SUPPORT
#define MAKE_STRUCT_CASE(TYPE, Name, name) \
case TYPE: \
Name::cast(*this)->Name##Verify(isolate); \
break;
STRUCT_LIST(MAKE_STRUCT_CASE)
#undef MAKE_STRUCT_CASE
case ALLOCATION_SITE_TYPE:
AllocationSite::cast(*this)->AllocationSiteVerify(isolate);
break;
case LOAD_HANDLER_TYPE:
LoadHandler::cast(*this)->LoadHandlerVerify(isolate);
break;
case STORE_HANDLER_TYPE:
StoreHandler::cast(*this)->StoreHandlerVerify(isolate);
break;
}
}
// static
void HeapObject::VerifyHeapPointer(Isolate* isolate, Object p) {
CHECK(p->IsHeapObject());
HeapObject ho = HeapObject::cast(p);
CHECK(isolate->heap()->Contains(ho));
}
void Symbol::SymbolVerify(Isolate* isolate) {
CHECK(IsSymbol());
CHECK(HasHashCode());
CHECK_GT(Hash(), 0);
CHECK(name()->IsUndefined(isolate) || name()->IsString());
CHECK_IMPLIES(IsPrivateName(), IsPrivate());
}
void ByteArray::ByteArrayVerify(Isolate* isolate) { CHECK(IsByteArray()); }
void BytecodeArray::BytecodeArrayVerify(Isolate* isolate) {
// TODO(oth): Walk bytecodes and immediate values to validate sanity.
// - All bytecodes are known and well formed.
// - Jumps must go to new instructions starts.
// - No Illegal bytecodes.
// - No consecutive sequences of prefix Wide / ExtraWide.
CHECK(IsBytecodeArray());
CHECK(constant_pool()->IsFixedArray());
VerifyHeapPointer(isolate, constant_pool());
}
void FreeSpace::FreeSpaceVerify(Isolate* isolate) {
CHECK(IsFreeSpace());
VerifySmiField(kSizeOffset);
}
void FeedbackCell::FeedbackCellVerify(Isolate* isolate) {
CHECK(IsFeedbackCell());
VerifyHeapPointer(isolate, value());
CHECK(value()->IsUndefined(isolate) || value()->IsFeedbackVector() ||
value()->IsFixedArray());
}
void FeedbackVector::FeedbackVectorVerify(Isolate* isolate) {
CHECK(IsFeedbackVector());
CHECK(closure_feedback_cell_array()->IsFixedArray());
MaybeObject code = optimized_code_weak_or_smi();
MaybeObject::VerifyMaybeObjectPointer(isolate, code);
CHECK(code->IsSmi() || code->IsWeakOrCleared());
}
template <class Traits>
void FixedTypedArray<Traits>::FixedTypedArrayVerify(Isolate* isolate) {
CHECK(IsHeapObject() && map()->instance_type() == Traits::kInstanceType);
if (base_pointer()->ptr() == ptr()) {
CHECK_EQ(reinterpret_cast<Address>(external_pointer()),
FixedTypedArrayBase::kDataOffset - kHeapObjectTag);
} else {
CHECK_EQ(Smi::kZero, base_pointer());
CHECK_EQ(0, length());
}
}
bool JSObject::ElementsAreSafeToExamine() const {
// If a GC was caused while constructing this object, the elements
// pointer may point to a one pointer filler map.
return elements() != GetReadOnlyRoots().one_pointer_filler_map();
}
namespace {
void VerifyJSObjectElements(Isolate* isolate, JSObject object) {
// Only TypedArrays can have these specialized elements.
if (object->IsJSTypedArray()) {
// TODO(cbruni): Fix CreateTypedArray to either not instantiate the object
// or propertly initialize it on errors during construction.
/* CHECK(object->HasFixedTypedArrayElements()); */
/* CHECK(object->elements()->IsFixedTypedArrayBase()); */
return;
}
CHECK(!object->HasFixedTypedArrayElements());
CHECK(!object->elements()->IsFixedTypedArrayBase());
if (object->HasDoubleElements()) {
if (object->elements()->length() > 0) {
CHECK(object->elements()->IsFixedDoubleArray());
}
return;
}
FixedArray elements = FixedArray::cast(object->elements());
if (object->HasSmiElements()) {
// We might have a partially initialized backing store, in which case we
// allow the hole + smi values.
for (int i = 0; i < elements->length(); i++) {
Object value = elements->get(i);
CHECK(value->IsSmi() || value->IsTheHole(isolate));
}
} else if (object->HasObjectElements()) {
for (int i = 0; i < elements->length(); i++) {
Object element = elements->get(i);
CHECK_IMPLIES(!element->IsSmi(), !HasWeakHeapObjectTag(element));
}
}
}
} // namespace
void JSObject::JSObjectVerify(Isolate* isolate) {
VerifyPointer(isolate, raw_properties_or_hash());
VerifyHeapPointer(isolate, elements());
CHECK_IMPLIES(HasSloppyArgumentsElements(), IsJSArgumentsObject());
if (HasFastProperties()) {
int actual_unused_property_fields = map()->GetInObjectProperties() +
property_array()->length() -
map()->NextFreePropertyIndex();
if (map()->UnusedPropertyFields() != actual_unused_property_fields) {
// There are two reasons why this can happen:
// - in the middle of StoreTransitionStub when the new extended backing
// store is already set into the object and the allocation of the
// MutableHeapNumber triggers GC while the map isn't updated yet.
// - deletion of the last property can leave additional backing store
// capacity behind.
CHECK_GT(actual_unused_property_fields, map()->UnusedPropertyFields());
int delta = actual_unused_property_fields - map()->UnusedPropertyFields();
CHECK_EQ(0, delta % JSObject::kFieldsAdded);
}
DescriptorArray descriptors = map()->instance_descriptors();
bool is_transitionable_fast_elements_kind =
IsTransitionableFastElementsKind(map()->elements_kind());
for (int i = 0; i < map()->NumberOfOwnDescriptors(); i++) {
PropertyDetails details = descriptors->GetDetails(i);
if (details.location() == kField) {
DCHECK_EQ(kData, details.kind());
Representation r = details.representation();
FieldIndex index = FieldIndex::ForDescriptor(map(), i);
if (IsUnboxedDoubleField(index)) {
DCHECK(r.IsDouble());
continue;
}
if (COMPRESS_POINTERS_BOOL && index.is_inobject()) {
VerifyObjectField(isolate, index.offset());
}
Object value = RawFastPropertyAt(index);
if (r.IsDouble()) DCHECK(value->IsMutableHeapNumber());
if (value->IsUninitialized(isolate)) continue;
if (r.IsSmi()) DCHECK(value->IsSmi());
if (r.IsHeapObject()) DCHECK(value->IsHeapObject());
FieldType field_type = descriptors->GetFieldType(i);
bool type_is_none = field_type->IsNone();
bool type_is_any = field_type->IsAny();
if (r.IsNone()) {
CHECK(type_is_none);
} else if (!type_is_any && !(type_is_none && r.IsHeapObject())) {
CHECK(!field_type->NowStable() || field_type->NowContains(value));
}
CHECK_IMPLIES(is_transitionable_fast_elements_kind,
Map::IsMostGeneralFieldType(r, field_type));
}
}
if (map()->EnumLength() != kInvalidEnumCacheSentinel) {
EnumCache enum_cache = descriptors->enum_cache();
FixedArray keys = enum_cache->keys();
FixedArray indices = enum_cache->indices();
CHECK_LE(map()->EnumLength(), keys->length());
CHECK_IMPLIES(indices != ReadOnlyRoots(isolate).empty_fixed_array(),
keys->length() == indices->length());
}
}
// If a GC was caused while constructing this object, the elements
// pointer may point to a one pointer filler map.
if (ElementsAreSafeToExamine()) {
CHECK_EQ((map()->has_fast_smi_or_object_elements() ||
map()->is_frozen_or_sealed_elements() ||
(elements() == GetReadOnlyRoots().empty_fixed_array()) ||
HasFastStringWrapperElements()),
(elements()->map() == GetReadOnlyRoots().fixed_array_map() ||
elements()->map() == GetReadOnlyRoots().fixed_cow_array_map()));
CHECK_EQ(map()->has_fast_object_elements(), HasObjectElements());
VerifyJSObjectElements(isolate, *this);
}
}
void Map::MapVerify(Isolate* isolate) {
Heap* heap = isolate->heap();
CHECK(!ObjectInYoungGeneration(*this));
CHECK(FIRST_TYPE <= instance_type() && instance_type() <= LAST_TYPE);
CHECK(instance_size() == kVariableSizeSentinel ||
(kTaggedSize <= instance_size() &&
static_cast<size_t>(instance_size()) < heap->Capacity()));
CHECK(GetBackPointer()->IsUndefined(isolate) ||
!Map::cast(GetBackPointer())->is_stable());
HeapObject::VerifyHeapPointer(isolate, prototype());
HeapObject::VerifyHeapPointer(isolate, instance_descriptors());
SLOW_DCHECK(instance_descriptors()->IsSortedNoDuplicates());
DisallowHeapAllocation no_gc;
SLOW_DCHECK(
TransitionsAccessor(isolate, *this, &no_gc).IsSortedNoDuplicates());
SLOW_DCHECK(TransitionsAccessor(isolate, *this, &no_gc)
.IsConsistentWithBackPointers());
SLOW_DCHECK(!FLAG_unbox_double_fields ||
layout_descriptor()->IsConsistentWithMap(*this));
if (!may_have_interesting_symbols()) {
CHECK(!has_named_interceptor());
CHECK(!is_dictionary_map());
CHECK(!is_access_check_needed());
DescriptorArray const descriptors = instance_descriptors();
for (int i = 0; i < NumberOfOwnDescriptors(); ++i) {
CHECK(!descriptors->GetKey(i)->IsInterestingSymbol());
}
}
CHECK_IMPLIES(has_named_interceptor(), may_have_interesting_symbols());
CHECK_IMPLIES(is_dictionary_map(), may_have_interesting_symbols());
CHECK_IMPLIES(is_access_check_needed(), may_have_interesting_symbols());
CHECK_IMPLIES(IsJSObjectMap() && !CanHaveFastTransitionableElementsKind(),
IsDictionaryElementsKind(elements_kind()) ||
IsTerminalElementsKind(elements_kind()));
CHECK_IMPLIES(is_deprecated(), !is_stable());
if (is_prototype_map()) {
DCHECK(prototype_info() == Smi::kZero ||
prototype_info()->IsPrototypeInfo());
}
CHECK(prototype_validity_cell()->IsSmi() ||
prototype_validity_cell()->IsCell());
}
void Map::DictionaryMapVerify(Isolate* isolate) {
MapVerify(isolate);
CHECK(is_dictionary_map());
CHECK_EQ(kInvalidEnumCacheSentinel, EnumLength());
CHECK_EQ(ReadOnlyRoots(isolate).empty_descriptor_array(),
instance_descriptors());
CHECK_EQ(0, UnusedPropertyFields());
CHECK_EQ(Map::GetVisitorId(*this), visitor_id());
}
void AliasedArgumentsEntry::AliasedArgumentsEntryVerify(Isolate* isolate) {
VerifySmiField(kAliasedContextSlotOffset);
}
void EmbedderDataArray::EmbedderDataArrayVerify(Isolate* isolate) {
EmbedderDataSlot start(*this, 0);
EmbedderDataSlot end(*this, length());
for (EmbedderDataSlot slot = start; slot < end; ++slot) {
Object e = slot.load_tagged();
Object::VerifyPointer(isolate, e);
}
VerifySmiField(kLengthOffset);
}
void FixedArray::FixedArrayVerify(Isolate* isolate) {
for (int i = 0; i < length(); i++) {
Object e = get(i);
VerifyPointer(isolate, e);
}
}
void WeakFixedArray::WeakFixedArrayVerify(Isolate* isolate) {
for (int i = 0; i < length(); i++) {
MaybeObject::VerifyMaybeObjectPointer(isolate, Get(i));
}
}
void WeakArrayList::WeakArrayListVerify(Isolate* isolate) {
for (int i = 0; i < length(); i++) {
MaybeObject::VerifyMaybeObjectPointer(isolate, Get(i));
}
}
void PropertyArray::PropertyArrayVerify(Isolate* isolate) {
if (length() == 0) {
CHECK_EQ(*this, ReadOnlyRoots(isolate).empty_property_array());
return;
}
// There are no empty PropertyArrays.
CHECK_LT(0, length());
for (int i = 0; i < length(); i++) {
Object e = get(i);
Object::VerifyPointer(isolate, e);
}
VerifySmiField(kLengthAndHashOffset);
}
void FixedDoubleArray::FixedDoubleArrayVerify(Isolate* isolate) {
for (int i = 0; i < length(); i++) {
if (!is_the_hole(i)) {
uint64_t value = get_representation(i);
uint64_t unexpected =
bit_cast<uint64_t>(std::numeric_limits<double>::quiet_NaN()) &
uint64_t{0x7FF8000000000000};
// Create implementation specific sNaN by inverting relevant bit.
unexpected ^= uint64_t{0x0008000000000000};
CHECK((value & uint64_t{0x7FF8000000000000}) != unexpected ||
(value & uint64_t{0x0007FFFFFFFFFFFF}) == uint64_t{0});
}
}
}
void Context::ContextVerify(Isolate* isolate) {
VerifySmiField(kLengthOffset);
VerifyObjectField(isolate, kScopeInfoOffset);
VerifyObjectField(isolate, kPreviousOffset);
VerifyObjectField(isolate, kExtensionOffset);
VerifyObjectField(isolate, kNativeContextOffset);
for (int i = 0; i < length(); i++) {
VerifyObjectField(isolate, OffsetOfElementAt(i));
}
}
void NativeContext::NativeContextVerify(Isolate* isolate) {
ContextVerify(isolate);
CHECK_EQ(length(), NativeContext::NATIVE_CONTEXT_SLOTS);
CHECK_EQ(kSize, map()->instance_size());
}
void FeedbackMetadata::FeedbackMetadataVerify(Isolate* isolate) {
if (slot_count() == 0 && closure_feedback_cell_count() == 0) {
CHECK_EQ(ReadOnlyRoots(isolate).empty_feedback_metadata(), *this);
} else {
FeedbackMetadataIterator iter(*this);
while (iter.HasNext()) {
iter.Next();
FeedbackSlotKind kind = iter.kind();
CHECK_NE(FeedbackSlotKind::kInvalid, kind);
CHECK_GT(FeedbackSlotKind::kKindsNumber, kind);
}
}
}
void DescriptorArray::DescriptorArrayVerify(Isolate* isolate) {
for (int i = 0; i < number_of_all_descriptors(); i++) {
MaybeObject::VerifyMaybeObjectPointer(isolate, get(ToKeyIndex(i)));
MaybeObject::VerifyMaybeObjectPointer(isolate, get(ToDetailsIndex(i)));
MaybeObject::VerifyMaybeObjectPointer(isolate, get(ToValueIndex(i)));
}
if (number_of_all_descriptors() == 0) {
Heap* heap = isolate->heap();
CHECK_EQ(ReadOnlyRoots(heap).empty_descriptor_array(), *this);
CHECK_EQ(0, number_of_all_descriptors());
CHECK_EQ(0, number_of_descriptors());
CHECK_EQ(ReadOnlyRoots(heap).empty_enum_cache(), enum_cache());
} else {
CHECK_LT(0, number_of_all_descriptors());
CHECK_LE(number_of_descriptors(), number_of_all_descriptors());
// Check that properties with private symbols names are non-enumerable.
for (int descriptor = 0; descriptor < number_of_descriptors();
descriptor++) {
Object key = get(ToKeyIndex(descriptor))->cast<Object>();
// number_of_descriptors() may be out of sync with the actual descriptors
// written during descriptor array construction.
if (key->IsUndefined(isolate)) continue;
PropertyDetails details = GetDetails(descriptor);
if (Name::cast(key)->IsPrivate()) {
CHECK_NE(details.attributes() & DONT_ENUM, 0);
}
MaybeObject value = get(ToValueIndex(descriptor));
HeapObject heap_object;
if (details.location() == kField) {
CHECK(
value == MaybeObject::FromObject(FieldType::None()) ||
value == MaybeObject::FromObject(FieldType::Any()) ||
value->IsCleared() ||
(value->GetHeapObjectIfWeak(&heap_object) && heap_object->IsMap()));
} else {
CHECK(!value->IsWeakOrCleared());
CHECK(!value->cast<Object>()->IsMap());
}
}
}
}
void TransitionArray::TransitionArrayVerify(Isolate* isolate) {
WeakFixedArrayVerify(isolate);
CHECK_LE(LengthFor(number_of_transitions()), length());
}
void JSArgumentsObject::JSArgumentsObjectVerify(Isolate* isolate) {
if (IsSloppyArgumentsElementsKind(GetElementsKind())) {
SloppyArgumentsElements::cast(elements())
->SloppyArgumentsElementsVerify(isolate, *this);
}
if (isolate->IsInAnyContext(map(), Context::SLOPPY_ARGUMENTS_MAP_INDEX) ||
isolate->IsInAnyContext(map(),
Context::SLOW_ALIASED_ARGUMENTS_MAP_INDEX) ||
isolate->IsInAnyContext(map(),
Context::FAST_ALIASED_ARGUMENTS_MAP_INDEX)) {
VerifyObjectField(isolate, JSSloppyArgumentsObject::kLengthOffset);
VerifyObjectField(isolate, JSSloppyArgumentsObject::kCalleeOffset);
} else if (isolate->IsInAnyContext(map(),
Context::STRICT_ARGUMENTS_MAP_INDEX)) {
VerifyObjectField(isolate, JSStrictArgumentsObject::kLengthOffset);
}
JSObjectVerify(isolate);
}
void SloppyArgumentsElements::SloppyArgumentsElementsVerify(Isolate* isolate,
JSObject holder) {
FixedArrayVerify(isolate);
// Abort verification if only partially initialized (can't use arguments()
// getter because it does FixedArray::cast()).
if (get(kArgumentsIndex)->IsUndefined(isolate)) return;
ElementsKind kind = holder->GetElementsKind();
bool is_fast = kind == FAST_SLOPPY_ARGUMENTS_ELEMENTS;
CHECK(IsFixedArray());
CHECK_GE(length(), 2);
CHECK_EQ(map(), ReadOnlyRoots(isolate).sloppy_arguments_elements_map());
Context context_object = context();
FixedArray arg_elements = FixedArray::cast(arguments());
if (arg_elements->length() == 0) {
CHECK(arg_elements == ReadOnlyRoots(isolate).empty_fixed_array());
return;
}
ElementsAccessor* accessor;
if (is_fast) {
accessor = ElementsAccessor::ForKind(HOLEY_ELEMENTS);
} else {
accessor = ElementsAccessor::ForKind(DICTIONARY_ELEMENTS);
}
int nofMappedParameters = 0;
int maxMappedIndex = 0;
for (int i = 0; i < nofMappedParameters; i++) {
// Verify that each context-mapped argument is either the hole or a valid
// Smi within context length range.
Object mapped = get_mapped_entry(i);
if (mapped->IsTheHole(isolate)) {
// Slow sloppy arguments can be holey.
if (!is_fast) continue;
// Fast sloppy arguments elements are never holey. Either the element is
// context-mapped or present in the arguments elements.
CHECK(accessor->HasElement(holder, i, arg_elements));
continue;
}
int mappedIndex = Smi::ToInt(mapped);
nofMappedParameters++;
CHECK_LE(maxMappedIndex, mappedIndex);
maxMappedIndex = mappedIndex;
Object value = context_object->get(mappedIndex);
CHECK(value->IsObject());
// None of the context-mapped entries should exist in the arguments
// elements.
CHECK(!accessor->HasElement(holder, i, arg_elements));
}
CHECK_LE(nofMappedParameters, context_object->length());
CHECK_LE(nofMappedParameters, arg_elements->length());
CHECK_LE(maxMappedIndex, context_object->length());
CHECK_LE(maxMappedIndex, arg_elements->length());
}
void JSGeneratorObject::JSGeneratorObjectVerify(Isolate* isolate) {
// In an expression like "new g()", there can be a point where a generator
// object is allocated but its fields are all undefined, as it hasn't yet been
// initialized by the generator. Hence these weak checks.
VerifyObjectField(isolate, kFunctionOffset);
VerifyObjectField(isolate, kContextOffset);
VerifyObjectField(isolate, kReceiverOffset);
VerifyObjectField(isolate, kParametersAndRegistersOffset);
VerifyObjectField(isolate, kContinuationOffset);
}
void JSAsyncFunctionObject::JSAsyncFunctionObjectVerify(Isolate* isolate) {
// Check inherited fields
JSGeneratorObjectVerify(isolate);
VerifyObjectField(isolate, kPromiseOffset);
promise()->HeapObjectVerify(isolate);
}
void JSAsyncGeneratorObject::JSAsyncGeneratorObjectVerify(Isolate* isolate) {
// Check inherited fields
JSGeneratorObjectVerify(isolate);
VerifyObjectField(isolate, kQueueOffset);
queue()->HeapObjectVerify(isolate);
}
void JSValue::JSValueVerify(Isolate* isolate) {
Object v = value();
if (v->IsHeapObject()) {
VerifyHeapPointer(isolate, v);
}
}
void JSDate::JSDateVerify(Isolate* isolate) {
if (value()->IsHeapObject()) {
VerifyHeapPointer(isolate, value());
}
CHECK(value()->IsUndefined(isolate) || value()->IsSmi() ||
value()->IsHeapNumber());
CHECK(year()->IsUndefined(isolate) || year()->IsSmi() || year()->IsNaN());
CHECK(month()->IsUndefined(isolate) || month()->IsSmi() || month()->IsNaN());
CHECK(day()->IsUndefined(isolate) || day()->IsSmi() || day()->IsNaN());
CHECK(weekday()->IsUndefined(isolate) || weekday()->IsSmi() ||
weekday()->IsNaN());
CHECK(hour()->IsUndefined(isolate) || hour()->IsSmi() || hour()->IsNaN());
CHECK(min()->IsUndefined(isolate) || min()->IsSmi() || min()->IsNaN());
CHECK(sec()->IsUndefined(isolate) || sec()->IsSmi() || sec()->IsNaN());
CHECK(cache_stamp()->IsUndefined(isolate) || cache_stamp()->IsSmi() ||
cache_stamp()->IsNaN());
if (month()->IsSmi()) {
int month = Smi::ToInt(this->month());
CHECK(0 <= month && month <= 11);
}
if (day()->IsSmi()) {
int day = Smi::ToInt(this->day());
CHECK(1 <= day && day <= 31);
}
if (hour()->IsSmi()) {
int hour = Smi::ToInt(this->hour());
CHECK(0 <= hour && hour <= 23);
}
if (min()->IsSmi()) {
int min = Smi::ToInt(this->min());
CHECK(0 <= min && min <= 59);
}
if (sec()->IsSmi()) {
int sec = Smi::ToInt(this->sec());
CHECK(0 <= sec && sec <= 59);
}
if (weekday()->IsSmi()) {
int weekday = Smi::ToInt(this->weekday());
CHECK(0 <= weekday && weekday <= 6);
}
if (cache_stamp()->IsSmi()) {
CHECK(Smi::ToInt(cache_stamp()) <=
Smi::ToInt(isolate->date_cache()->stamp()));
}
}
void JSMessageObject::JSMessageObjectVerify(Isolate* isolate) {
CHECK(IsJSMessageObject());
VerifyObjectField(isolate, kStartPositionOffset);
VerifyObjectField(isolate, kEndPositionOffset);
VerifyObjectField(isolate, kArgumentsOffset);
VerifyObjectField(isolate, kScriptOffset);
VerifyObjectField(isolate, kStackFramesOffset);
VerifySmiField(kMessageTypeOffset);
VerifySmiField(kStartPositionOffset);
VerifySmiField(kEndPositionOffset);
VerifySmiField(kErrorLevelOffset);
}
void String::StringVerify(Isolate* isolate) {
CHECK(IsString());
CHECK(length() >= 0 && length() <= Smi::kMaxValue);
CHECK_IMPLIES(length() == 0, *this == ReadOnlyRoots(isolate).empty_string());
CHECK_EQ(*this == ReadOnlyRoots(isolate).empty_string(),
map() == ReadOnlyRoots(isolate).empty_string_map());
if (IsInternalizedString()) {
CHECK(!ObjectInYoungGeneration(*this));
}
if (IsConsString()) {
ConsString::cast(*this)->ConsStringVerify(isolate);
} else if (IsSlicedString()) {
SlicedString::cast(*this)->SlicedStringVerify(isolate);
} else if (IsThinString()) {
ThinString::cast(*this)->ThinStringVerify(isolate);
}
}
void ConsString::ConsStringVerify(Isolate* isolate) {
CHECK(this->first()->IsString());
CHECK(this->second()->IsString());
CHECK_GT(this->first()->length(), 0);
CHECK_GE(this->length(), ConsString::kMinLength);
CHECK(this->length() == this->first()->length() + this->second()->length());
if (this->IsFlat()) {
// A flat cons can only be created by String::SlowFlatten.
// Afterwards, the first part may be externalized or internalized.
CHECK(this->first()->IsSeqString() || this->first()->IsExternalString() ||
this->first()->IsThinString());
}
}
void ThinString::ThinStringVerify(Isolate* isolate) {
CHECK(this->actual()->IsInternalizedString());
CHECK(this->actual()->IsSeqString() || this->actual()->IsExternalString());
}
void SlicedString::SlicedStringVerify(Isolate* isolate) {
CHECK(!this->parent()->IsConsString());
CHECK(!this->parent()->IsSlicedString());
CHECK_GE(this->length(), SlicedString::kMinLength);
}
void JSBoundFunction::JSBoundFunctionVerify(Isolate* isolate) {
CHECK(IsJSBoundFunction());
JSObjectVerify(isolate);
VerifyObjectField(isolate, kBoundThisOffset);
VerifyObjectField(isolate, kBoundTargetFunctionOffset);
VerifyObjectField(isolate, kBoundArgumentsOffset);
CHECK(IsCallable());
if (!raw_bound_target_function()->IsUndefined(isolate)) {
CHECK(bound_target_function()->IsCallable());
CHECK_EQ(IsConstructor(), bound_target_function()->IsConstructor());
}
}
void JSFunction::JSFunctionVerify(Isolate* isolate) {
CHECK(IsJSFunction());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, raw_feedback_cell());
CHECK(raw_feedback_cell()->IsFeedbackCell());
CHECK(code()->IsCode());
CHECK(map()->is_callable());
Handle<JSFunction> function(*this, isolate);
LookupIterator it(isolate, function, isolate->factory()->prototype_string(),
LookupIterator::OWN_SKIP_INTERCEPTOR);
if (has_prototype_slot()) {
VerifyObjectField(isolate, kPrototypeOrInitialMapOffset);
}
if (has_prototype_property()) {
CHECK(it.IsFound());
CHECK_EQ(LookupIterator::ACCESSOR, it.state());
CHECK(it.GetAccessors()->IsAccessorInfo());
} else {
CHECK(!it.IsFound() || it.state() != LookupIterator::ACCESSOR ||
!it.GetAccessors()->IsAccessorInfo());
}
}
void SharedFunctionInfo::SharedFunctionInfoVerify(Isolate* isolate) {
CHECK(IsSharedFunctionInfo());
VerifyObjectField(isolate, kFunctionDataOffset);
VerifyObjectField(isolate, kOuterScopeInfoOrFeedbackMetadataOffset);
VerifyObjectField(isolate, kScriptOrDebugInfoOffset);
VerifyObjectField(isolate, kNameOrScopeInfoOffset);
Object value = name_or_scope_info();
CHECK(value == kNoSharedNameSentinel || value->IsString() ||
value->IsScopeInfo());
if (value->IsScopeInfo()) {
CHECK_LT(0, ScopeInfo::cast(value)->length());
CHECK_NE(value, ReadOnlyRoots(isolate).empty_scope_info());
}
CHECK(HasWasmExportedFunctionData() || IsApiFunction() ||
HasBytecodeArray() || HasAsmWasmData() || HasBuiltinId() ||
HasUncompiledDataWithPreparseData() ||
HasUncompiledDataWithoutPreparseData());
CHECK(script_or_debug_info()->IsUndefined(isolate) ||
script_or_debug_info()->IsScript() || HasDebugInfo());
if (!is_compiled()) {
CHECK(!HasFeedbackMetadata());
CHECK(outer_scope_info()->IsScopeInfo() ||
outer_scope_info()->IsTheHole(isolate));
} else if (HasBytecodeArray() && HasFeedbackMetadata()) {
CHECK(feedback_metadata()->IsFeedbackMetadata());
}
int expected_map_index = Context::FunctionMapIndex(
language_mode(), kind(), HasSharedName(), needs_home_object());
CHECK_EQ(expected_map_index, function_map_index());
if (scope_info()->length() > 0) {
ScopeInfo info = scope_info();
CHECK(kind() == info->function_kind());
CHECK_EQ(kind() == kModule, info->scope_type() == MODULE_SCOPE);
}
if (IsApiFunction()) {
CHECK(construct_as_builtin());
} else if (!HasBuiltinId()) {
CHECK(!construct_as_builtin());
} else {
int id = builtin_id();
if (id != Builtins::kCompileLazy && id != Builtins::kEmptyFunction) {
CHECK(construct_as_builtin());
} else {
CHECK(!construct_as_builtin());
}
}
// At this point we only support skipping arguments adaptor frames
// for strict mode functions (see https://crbug.com/v8/8895).
CHECK_IMPLIES(is_safe_to_skip_arguments_adaptor(),
language_mode() == LanguageMode::kStrict);
}
void JSGlobalProxy::JSGlobalProxyVerify(Isolate* isolate) {
CHECK(IsJSGlobalProxy());
JSObjectVerify(isolate);
VerifyObjectField(isolate, JSGlobalProxy::kNativeContextOffset);
CHECK(map()->is_access_check_needed());
// Make sure that this object has no properties, elements.
CHECK_EQ(0, FixedArray::cast(elements())->length());
}
void JSGlobalObject::JSGlobalObjectVerify(Isolate* isolate) {
CHECK(IsJSGlobalObject());
// Do not check the dummy global object for the builtins.
if (global_dictionary()->NumberOfElements() == 0 &&
elements()->length() == 0) {
return;
}
JSObjectVerify(isolate);
}
void Oddball::OddballVerify(Isolate* isolate) {
CHECK(IsOddball());
Heap* heap = isolate->heap();
VerifyHeapPointer(isolate, to_string());
Object number = to_number();
if (number->IsHeapObject()) {
CHECK(number == ReadOnlyRoots(heap).nan_value() ||
number == ReadOnlyRoots(heap).hole_nan_value());
} else {
CHECK(number->IsSmi());
int value = Smi::ToInt(number);
// Hidden oddballs have negative smis.
const int kLeastHiddenOddballNumber = -7;
CHECK_LE(value, 1);
CHECK_GE(value, kLeastHiddenOddballNumber);
}
ReadOnlyRoots roots(heap);
if (map() == roots.undefined_map()) {
CHECK(*this == roots.undefined_value());
} else if (map() == roots.the_hole_map()) {
CHECK(*this == roots.the_hole_value());
} else if (map() == roots.null_map()) {
CHECK(*this == roots.null_value());
} else if (map() == roots.boolean_map()) {
CHECK(*this == roots.true_value() || *this == roots.false_value());
} else if (map() == roots.uninitialized_map()) {
CHECK(*this == roots.uninitialized_value());
} else if (map() == roots.arguments_marker_map()) {
CHECK(*this == roots.arguments_marker());
} else if (map() == roots.termination_exception_map()) {
CHECK(*this == roots.termination_exception());
} else if (map() == roots.exception_map()) {
CHECK(*this == roots.exception());
} else if (map() == roots.optimized_out_map()) {
CHECK(*this == roots.optimized_out());
} else if (map() == roots.stale_register_map()) {
CHECK(*this == roots.stale_register());
} else if (map() == roots.self_reference_marker_map()) {
// Multiple instances of this oddball may exist at once.
CHECK_EQ(kind(), Oddball::kSelfReferenceMarker);
} else {
UNREACHABLE();
}
CHECK(to_string()->IsString());
CHECK(type_of()->IsString());
}
void Cell::CellVerify(Isolate* isolate) {
CHECK(IsCell());
VerifyObjectField(isolate, kValueOffset);
}
void PropertyCell::PropertyCellVerify(Isolate* isolate) {
CHECK(IsPropertyCell());
VerifyObjectField(isolate, kValueOffset);
}
void CodeDataContainer::CodeDataContainerVerify(Isolate* isolate) {
CHECK(IsCodeDataContainer());
VerifyObjectField(isolate, kNextCodeLinkOffset);
CHECK(next_code_link()->IsCode() || next_code_link()->IsUndefined(isolate));
}
void Code::CodeVerify(Isolate* isolate) {
CHECK_IMPLIES(
has_safepoint_table(),
IsAligned(safepoint_table_offset(), static_cast<unsigned>(kIntSize)));
CHECK_LE(safepoint_table_offset(), handler_table_offset());
CHECK_LE(handler_table_offset(), constant_pool_offset());
CHECK_LE(constant_pool_offset(), code_comments_offset());
CHECK_LE(code_comments_offset(), InstructionSize());
CHECK(IsAligned(raw_instruction_start(), kCodeAlignment));
relocation_info()->ObjectVerify(isolate);
CHECK(Code::SizeFor(body_size()) <= kMaxRegularHeapObjectSize ||
isolate->heap()->InSpace(*this, CODE_LO_SPACE));
Address last_gc_pc = kNullAddress;
for (RelocIterator it(*this); !it.done(); it.next()) {
it.rinfo()->Verify(isolate);
// Ensure that GC will not iterate twice over the same pointer.
if (RelocInfo::IsGCRelocMode(it.rinfo()->rmode())) {
CHECK(it.rinfo()->pc() != last_gc_pc);
last_gc_pc = it.rinfo()->pc();
}
}
}
void JSArray::JSArrayVerify(Isolate* isolate) {
JSObjectVerify(isolate);
CHECK(length()->IsNumber() || length()->IsUndefined(isolate));
// If a GC was caused while constructing this array, the elements
// pointer may point to a one pointer filler map.
if (!ElementsAreSafeToExamine()) return;
if (elements()->IsUndefined(isolate)) return;
CHECK(elements()->IsFixedArray() || elements()->IsFixedDoubleArray());
if (elements()->length() == 0) {
CHECK_EQ(elements(), ReadOnlyRoots(isolate).empty_fixed_array());
}
if (!length()->IsNumber()) return;
// Verify that the length and the elements backing store are in sync.
if (length()->IsSmi() && (HasFastElements() || HasFrozenOrSealedElements())) {
if (elements()->length() > 0) {
CHECK_IMPLIES(HasDoubleElements(), elements()->IsFixedDoubleArray());
CHECK_IMPLIES(HasSmiOrObjectElements() || HasFrozenOrSealedElements(),
elements()->IsFixedArray());
}
int size = Smi::ToInt(length());
// Holey / Packed backing stores might have slack or might have not been
// properly initialized yet.
CHECK(size <= elements()->length() ||
elements() == ReadOnlyRoots(isolate).empty_fixed_array());
} else {
CHECK(HasDictionaryElements());
uint32_t array_length;
CHECK(length()->ToArrayLength(&array_length));
if (array_length == 0xFFFFFFFF) {
CHECK(length()->ToArrayLength(&array_length));
}
if (array_length != 0) {
NumberDictionary dict = NumberDictionary::cast(elements());
// The dictionary can never have more elements than the array length + 1.
// If the backing store grows the verification might be triggered with
// the old length in place.
uint32_t nof_elements = static_cast<uint32_t>(dict->NumberOfElements());
if (nof_elements != 0) nof_elements--;
CHECK_LE(nof_elements, array_length);
}
}
}
void JSSet::JSSetVerify(Isolate* isolate) {
CHECK(IsJSSet());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, table());
CHECK(table()->IsOrderedHashSet() || table()->IsUndefined(isolate));
// TODO(arv): Verify OrderedHashTable too.
}
void JSMap::JSMapVerify(Isolate* isolate) {
CHECK(IsJSMap());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, table());
CHECK(table()->IsOrderedHashMap() || table()->IsUndefined(isolate));
// TODO(arv): Verify OrderedHashTable too.
}
void JSSetIterator::JSSetIteratorVerify(Isolate* isolate) {
CHECK(IsJSSetIterator());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, table());
CHECK(table()->IsOrderedHashSet());
CHECK(index()->IsSmi());
}
void JSMapIterator::JSMapIteratorVerify(Isolate* isolate) {
CHECK(IsJSMapIterator());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, table());
CHECK(table()->IsOrderedHashMap());
CHECK(index()->IsSmi());
}
void WeakCell::WeakCellVerify(Isolate* isolate) {
CHECK(IsWeakCell());
CHECK(target()->IsJSReceiver() || target()->IsUndefined(isolate));
CHECK(prev()->IsWeakCell() || prev()->IsUndefined(isolate));
if (prev()->IsWeakCell()) {
CHECK_EQ(WeakCell::cast(prev())->next(), *this);
}
CHECK(next()->IsWeakCell() || next()->IsUndefined(isolate));
if (next()->IsWeakCell()) {
CHECK_EQ(WeakCell::cast(next())->prev(), *this);
}
CHECK_IMPLIES(key()->IsUndefined(isolate),
key_list_prev()->IsUndefined(isolate));
CHECK_IMPLIES(key()->IsUndefined(isolate),
key_list_next()->IsUndefined(isolate));
CHECK(key_list_prev()->IsWeakCell() || key_list_prev()->IsUndefined(isolate));
if (key_list_prev()->IsWeakCell()) {
CHECK_EQ(WeakCell::cast(key_list_prev())->key_list_next(), *this);
}
CHECK(key_list_next()->IsWeakCell() || key_list_next()->IsUndefined(isolate));
if (key_list_next()->IsWeakCell()) {
CHECK_EQ(WeakCell::cast(key_list_next())->key_list_prev(), *this);
}
CHECK(finalization_group()->IsUndefined(isolate) ||
finalization_group()->IsJSFinalizationGroup());
}
void JSWeakRef::JSWeakRefVerify(Isolate* isolate) {
CHECK(IsJSWeakRef());
JSObjectVerify(isolate);
CHECK(target()->IsUndefined(isolate) || target()->IsJSReceiver());
}
void JSFinalizationGroup::JSFinalizationGroupVerify(Isolate* isolate) {
CHECK(IsJSFinalizationGroup());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, cleanup());
CHECK(active_cells()->IsUndefined(isolate) || active_cells()->IsWeakCell());
if (active_cells()->IsWeakCell()) {
CHECK(WeakCell::cast(active_cells())->prev()->IsUndefined(isolate));
}
CHECK(cleared_cells()->IsUndefined(isolate) || cleared_cells()->IsWeakCell());
if (cleared_cells()->IsWeakCell()) {
CHECK(WeakCell::cast(cleared_cells())->prev()->IsUndefined(isolate));
}
}
void JSFinalizationGroupCleanupIterator::
JSFinalizationGroupCleanupIteratorVerify(Isolate* isolate) {
CHECK(IsJSFinalizationGroupCleanupIterator());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, finalization_group());
}
void FinalizationGroupCleanupJobTask::FinalizationGroupCleanupJobTaskVerify(
Isolate* isolate) {
CHECK(IsFinalizationGroupCleanupJobTask());
CHECK(finalization_group()->IsJSFinalizationGroup());
}
void JSWeakMap::JSWeakMapVerify(Isolate* isolate) {
CHECK(IsJSWeakMap());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, table());
CHECK(table()->IsEphemeronHashTable() || table()->IsUndefined(isolate));
}
void JSArrayIterator::JSArrayIteratorVerify(Isolate* isolate) {
CHECK(IsJSArrayIterator());
JSObjectVerify(isolate);
CHECK(iterated_object()->IsJSReceiver());
CHECK_GE(next_index()->Number(), 0);
CHECK_LE(next_index()->Number(), kMaxSafeInteger);
if (iterated_object()->IsJSTypedArray()) {
// JSTypedArray::length is limited to Smi range.
CHECK(next_index()->IsSmi());
CHECK_LE(next_index()->Number(), Smi::kMaxValue);
} else if (iterated_object()->IsJSArray()) {
// JSArray::length is limited to Uint32 range.
CHECK_LE(next_index()->Number(), kMaxUInt32);
}
}
void JSStringIterator::JSStringIteratorVerify(Isolate* isolate) {
CHECK(IsJSStringIterator());
JSObjectVerify(isolate);
CHECK(string()->IsString());
CHECK_GE(index(), 0);
CHECK_LE(index(), String::kMaxLength);
}
void JSAsyncFromSyncIterator::JSAsyncFromSyncIteratorVerify(Isolate* isolate) {
CHECK(IsJSAsyncFromSyncIterator());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, sync_iterator());
}
void JSWeakSet::JSWeakSetVerify(Isolate* isolate) {
CHECK(IsJSWeakSet());
JSObjectVerify(isolate);
VerifyHeapPointer(isolate, table());
CHECK(table()->IsEphemeronHashTable() || table()->IsUndefined(isolate));
}
void Microtask::MicrotaskVerify(Isolate* isolate) { CHECK(IsMicrotask()); }
void CallableTask::CallableTaskVerify(Isolate* isolate) {
CHECK(IsCallableTask());
MicrotaskVerify(isolate);
VerifyHeapPointer(isolate, callable());
CHECK(callable()->IsCallable());
VerifyHeapPointer(isolate, context());
CHECK(context()->IsContext());
}
void CallbackTask::CallbackTaskVerify(Isolate* isolate) {
CHECK(IsCallbackTask());
MicrotaskVerify(isolate);
VerifyHeapPointer(isolate, callback());
VerifyHeapPointer(isolate, data());
}
void PromiseReactionJobTask::PromiseReactionJobTaskVerify(Isolate* isolate) {
CHECK(IsPromiseReactionJobTask());
MicrotaskVerify(isolate);
VerifyPointer(isolate, argument());
VerifyHeapPointer(isolate, context());
CHECK(context()->IsContext());
VerifyHeapPointer(isolate, handler());
CHECK(handler()->IsUndefined(isolate) || handler()->IsCallable());
VerifyHeapPointer(isolate, promise_or_capability());
CHECK(promise_or_capability()->IsJSPromise() ||
promise_or_capability()->IsPromiseCapability() ||
promise_or_capability()->IsUndefined(isolate));
}
void PromiseFulfillReactionJobTask::PromiseFulfillReactionJobTaskVerify(
Isolate* isolate) {
CHECK(IsPromiseFulfillReactionJobTask());
PromiseReactionJobTaskVerify(isolate);
}
void PromiseRejectReactionJobTask::PromiseRejectReactionJobTaskVerify(
Isolate* isolate) {
CHECK(IsPromiseRejectReactionJobTask());
PromiseReactionJobTaskVerify(isolate);
}
void PromiseResolveThenableJobTask::PromiseResolveThenableJobTaskVerify(
Isolate* isolate) {
CHECK(IsPromiseResolveThenableJobTask());
MicrotaskVerify(isolate);
VerifyHeapPointer(isolate, context());
CHECK(context()->IsContext());
VerifyHeapPointer(isolate, promise_to_resolve());
CHECK(promise_to_resolve()->IsJSPromise());
VerifyHeapPointer(isolate, then());
CHECK(then()->IsCallable());
CHECK(then()->IsJSReceiver());
VerifyHeapPointer(isolate, thenable());
CHECK(thenable()->IsJSReceiver());
}
void PromiseCapability::PromiseCapabilityVerify(Isolate* isolate) {
CHECK(IsPromiseCapability());
VerifyHeapPointer(isolate, promise());
CHECK(promise()->IsJSReceiver() || promise()->IsUndefined(isolate));
VerifyPointer(isolate, resolve());
VerifyPointer(isolate, reject());
}
void PromiseReaction::PromiseReactionVerify(Isolate* isolate) {
CHECK(IsPromiseReaction());
VerifyPointer(isolate, next());
CHECK(next()->IsSmi() || next()->IsPromiseReaction());
VerifyHeapPointer(isolate, reject_handler());
CHECK(reject_handler()->IsUndefined(isolate) ||
reject_handler()->IsCallable());
VerifyHeapPointer(isolate, fulfill_handler());
CHECK(fulfill_handler()->IsUndefined(isolate) ||
fulfill_handler()->IsCallable());
VerifyHeapPointer(isolate, promise_or_capability());
CHECK(promise_or_capability()->IsJSPromise() ||
promise_or_capability()->IsPromiseCapability() ||
promise_or_capability()->IsUndefined(isolate));
}
void JSPromise::JSPromiseVerify(Isolate* isolate) {
CHECK(IsJSPromise());
JSObjectVerify(isolate);
VerifyPointer(isolate, reactions_or_result());
VerifySmiField(kFlagsOffset);
if (status() == Promise::kPending) {
CHECK(reactions()->IsSmi() || reactions()->IsPromiseReaction());
}
}
template <typename Derived>
void SmallOrderedHashTable<Derived>::SmallOrderedHashTableVerify(
Isolate* isolate) {
CHECK(IsSmallOrderedHashTable());
int capacity = Capacity();
CHECK_GE(capacity, kMinCapacity);
CHECK_LE(capacity, kMaxCapacity);
for (int entry = 0; entry < NumberOfBuckets(); entry++) {
int bucket = GetFirstEntry(entry);
if (bucket == kNotFound) continue;
CHECK_GE(bucket, 0);
CHECK_LE(bucket, capacity);
}
for (int entry = 0; entry < NumberOfElements(); entry++) {
int chain = GetNextEntry(entry);
if (chain == kNotFound) continue;
CHECK_GE(chain, 0);
CHECK_LE(chain, capacity);
}
for (int entry = 0; entry < NumberOfElements(); entry++) {
for (int offset = 0; offset < Derived::kEntrySize; offset++) {
Object val = GetDataEntry(entry, offset);
VerifyPointer(isolate, val);
}
}
for (int entry = NumberOfElements() + NumberOfDeletedElements();
entry < Capacity(); entry++) {
for (int offset = 0; offset < Derived::kEntrySize; offset++) {
Object val = GetDataEntry(entry, offset);
CHECK(val->IsTheHole(isolate));
}
}
}
void SmallOrderedHashMap::SmallOrderedHashMapVerify(Isolate* isolate) {
SmallOrderedHashTable<SmallOrderedHashMap>::SmallOrderedHashTableVerify(
isolate);
for (int entry = NumberOfElements(); entry < NumberOfDeletedElements();
entry++) {
for (int offset = 0; offset < kEntrySize; offset++) {
Object val = GetDataEntry(entry, offset);
CHECK(val->IsTheHole(isolate));
}
}
}
void SmallOrderedHashSet::SmallOrderedHashSetVerify(Isolate* isolate) {
SmallOrderedHashTable<SmallOrderedHashSet>::SmallOrderedHashTableVerify(
isolate);
for (int entry = NumberOfElements(); entry < NumberOfDeletedElements();
entry++) {
for (int offset = 0; offset < kEntrySize; offset++) {
Object val = GetDataEntry(entry, offset);
CHECK(val->IsTheHole(isolate));
}
}
}
void SmallOrderedNameDictionary::SmallOrderedNameDictionaryVerify(
Isolate* isolate) {
SmallOrderedHashTable<
SmallOrderedNameDictionary>::SmallOrderedHashTableVerify(isolate);
for (int entry = NumberOfElements(); entry < NumberOfDeletedElements();
entry++) {
for (int offset = 0; offset < kEntrySize; offset++) {
Object val = GetDataEntry(entry, offset);
CHECK(val->IsTheHole(isolate) ||
(PropertyDetails::Empty().AsSmi() == Smi::cast(val)));
}
}
}
void JSRegExp::JSRegExpVerify(Isolate* isolate) {
JSObjectVerify(isolate);
CHECK(data()->IsUndefined(isolate) || data()->IsFixedArray());
CHECK(source()->IsUndefined(isolate) || source()->IsString());
CHECK(flags()->IsUndefined() || flags()->IsSmi());
switch (TypeTag()) {
case JSRegExp::ATOM: {
FixedArray arr = FixedArray::cast(data());
CHECK(arr->get(JSRegExp::kAtomPatternIndex)->IsString());
break;
}
case JSRegExp::IRREGEXP: {
bool is_native = RegExpImpl::UsesNativeRegExp();
FixedArray arr = FixedArray::cast(data());
Object one_byte_data = arr->get(JSRegExp::kIrregexpLatin1CodeIndex);
// Smi : Not compiled yet (-1).
// Code/ByteArray: Compiled code.
CHECK(
(one_byte_data->IsSmi() &&
Smi::ToInt(one_byte_data) == JSRegExp::kUninitializedValue) ||
(is_native ? one_byte_data->IsCode() : one_byte_data->IsByteArray()));
Object uc16_data = arr->get(JSRegExp::kIrregexpUC16CodeIndex);
CHECK((uc16_data->IsSmi() &&
Smi::ToInt(uc16_data) == JSRegExp::kUninitializedValue) ||
(is_native ? uc16_data->IsCode() : uc16_data->IsByteArray()));
CHECK(arr->get(JSRegExp::kIrregexpCaptureCountIndex)->IsSmi());
CHECK(arr->get(JSRegExp::kIrregexpMaxRegisterCountIndex)->IsSmi());
break;
}
default:
CHECK_EQ(JSRegExp::NOT_COMPILED, TypeTag());
CHECK(data()->IsUndefined(isolate));
break;
}
}
void JSRegExpStringIterator::JSRegExpStringIteratorVerify(Isolate* isolate) {
CHECK(IsJSRegExpStringIterator());
JSObjectVerify(isolate);
CHECK(iterating_string()->IsString());
CHECK(iterating_regexp()->IsObject());
VerifySmiField(kFlagsOffset);
}
void JSProxy::JSProxyVerify(Isolate* isolate) {
CHECK(IsJSProxy());
CHECK(map()->GetConstructor()->IsJSFunction());
VerifyPointer(isolate, target());
VerifyPointer(isolate, handler());
if (!IsRevoked()) {
CHECK_EQ(target()->IsCallable(), map()->is_callable());
CHECK_EQ(target()->IsConstructor(), map()->is_constructor());
}
CHECK(map()->prototype()->IsNull(isolate));
// There should be no properties on a Proxy.
CHECK_EQ(0, map()->NumberOfOwnDescriptors());
}
void JSArrayBuffer::JSArrayBufferVerify(Isolate* isolate) {
CHECK(IsJSArrayBuffer());
if (FIELD_SIZE(kOptionalPaddingOffset) != 0) {
CHECK_EQ(4, FIELD_SIZE(kOptionalPaddingOffset));
CHECK_EQ(0,
*reinterpret_cast<uint32_t*>(address() + kOptionalPaddingOffset));
}
JSObjectVerify(isolate);
}
void JSArrayBufferView::JSArrayBufferViewVerify(Isolate* isolate) {
CHECK(IsJSArrayBufferView());
JSObjectVerify(isolate);
VerifyPointer(isolate, buffer());
CHECK(buffer()->IsJSArrayBuffer() || buffer()->IsUndefined(isolate) ||
buffer() == Smi::kZero);
CHECK_LE(byte_length(), JSArrayBuffer::kMaxByteLength);
CHECK_LE(byte_offset(), JSArrayBuffer::kMaxByteLength);
}
void JSTypedArray::JSTypedArrayVerify(Isolate* isolate) {
CHECK(IsJSTypedArray());
JSArrayBufferViewVerify(isolate);
VerifyPointer(isolate, raw_length());
CHECK(raw_length()->IsSmi() || raw_length()->IsUndefined(isolate));
VerifyPointer(isolate, elements());
}
void JSDataView::JSDataViewVerify(Isolate* isolate) {
CHECK(IsJSDataView());
JSArrayBufferViewVerify(isolate);
}
void Foreign::ForeignVerify(Isolate* isolate) { CHECK(IsForeign()); }
void AsyncGeneratorRequest::AsyncGeneratorRequestVerify(Isolate* isolate) {
CHECK(IsAsyncGeneratorRequest());
VerifySmiField(kResumeModeOffset);
CHECK_GE(resume_mode(), JSGeneratorObject::kNext);
CHECK_LE(resume_mode(), JSGeneratorObject::kThrow);
CHECK(promise()->IsJSPromise());
VerifyPointer(isolate, value());
VerifyPointer(isolate, next());
next()->ObjectVerify(isolate);
}
void BigInt::BigIntVerify(Isolate* isolate) {
CHECK(IsBigInt());
CHECK_GE(length(), 0);
CHECK_IMPLIES(is_zero(), !sign()); // There is no -0n.
}
void JSModuleNamespace::JSModuleNamespaceVerify(Isolate* isolate) {
CHECK(IsJSModuleNamespace());
VerifyPointer(isolate, module());
}
void ModuleInfoEntry::ModuleInfoEntryVerify(Isolate* isolate) {
CHECK(IsModuleInfoEntry());
CHECK(export_name()->IsUndefined(isolate) || export_name()->IsString());
CHECK(local_name()->IsUndefined(isolate) || local_name()->IsString());
CHECK(import_name()->IsUndefined(isolate) || import_name()->IsString());
VerifySmiField(kModuleRequestOffset);
VerifySmiField(kCellIndexOffset);
VerifySmiField(kBegPosOffset);
VerifySmiField(kEndPosOffset);
CHECK_IMPLIES(import_name()->IsString(), module_request() >= 0);
CHECK_IMPLIES(export_name()->IsString() && import_name()->IsString(),
local_name()->IsUndefined(isolate));
}
void Module::ModuleVerify(Isolate* isolate) {
CHECK(IsModule());
VerifyPointer(isolate, code());
VerifyPointer(isolate, exports());
VerifyPointer(isolate, module_namespace());
VerifyPointer(isolate, requested_modules());
VerifyPointer(isolate, script());
VerifyPointer(isolate, import_meta());
VerifyPointer(isolate, exception());
VerifySmiField(kHashOffset);
VerifySmiField(kStatusOffset);
CHECK((status() >= kEvaluating && code()->IsModuleInfo()) ||
(status() == kInstantiated && code()->IsJSGeneratorObject()) ||
(status() == kInstantiating && code()->IsJSFunction()) ||
(code()->IsSharedFunctionInfo()));
CHECK_EQ(status() == kErrored, !exception()->IsTheHole(isolate));
CHECK(module_namespace()->IsUndefined(isolate) ||
module_namespace()->IsJSModuleNamespace());
if (module_namespace()->IsJSModuleNamespace()) {
CHECK_LE(kInstantiating, status());
CHECK_EQ(JSModuleNamespace::cast(module_namespace())->module(), *this);
}
CHECK_EQ(requested_modules()->length(), info()->module_requests()->length());
CHECK(import_meta()->IsTheHole(isolate) || import_meta()->IsJSObject());
CHECK_NE(hash(), 0);
}
void PrototypeInfo::PrototypeInfoVerify(Isolate* isolate) {
CHECK(IsPrototypeInfo());
Object module_ns = module_namespace();
CHECK(module_ns->IsJSModuleNamespace() || module_ns->IsUndefined(isolate));
if (prototype_users()->IsWeakArrayList()) {
PrototypeUsers::Verify(WeakArrayList::cast(prototype_users()));
} else {
CHECK(prototype_users()->IsSmi());
}
}
void PrototypeUsers::Verify(WeakArrayList array) {
if (array->length() == 0) {
// Allow empty & uninitialized lists.
return;
}
// Verify empty slot chain.
int empty_slot = Smi::ToInt(empty_slot_index(array));
int empty_slots_count = 0;
while (empty_slot != kNoEmptySlotsMarker) {
CHECK_GT(empty_slot, 0);
CHECK_LT(empty_slot, array->length());
empty_slot = array->Get(empty_slot).ToSmi().value();
++empty_slots_count;
}
// Verify that all elements are either weak pointers or SMIs marking empty
// slots.
int weak_maps_count = 0;
for (int i = kFirstIndex; i < array->length(); ++i) {
HeapObject heap_object;
MaybeObject object = array->Get(i);
if ((object->GetHeapObjectIfWeak(&heap_object) && heap_object->IsMap()) ||
object->IsCleared()) {
++weak_maps_count;
} else {
CHECK(object->IsSmi());
}
}
CHECK_EQ(weak_maps_count + empty_slots_count + 1, array->length());
}
void Tuple2::Tuple2Verify(Isolate* isolate) {
CHECK(IsTuple2());
Heap* heap = isolate->heap();
if (*this == ReadOnlyRoots(heap).empty_enum_cache()) {
CHECK_EQ(ReadOnlyRoots(heap).empty_fixed_array(),
EnumCache::cast(*this)->keys());
CHECK_EQ(ReadOnlyRoots(heap).empty_fixed_array(),
EnumCache::cast(*this)->indices());
} else {
VerifyObjectField(isolate, kValue1Offset);
VerifyObjectField(isolate, kValue2Offset);
}
}
void Tuple3::Tuple3Verify(Isolate* isolate) {
CHECK(IsTuple3());
VerifyObjectField(isolate, kValue1Offset);
VerifyObjectField(isolate, kValue2Offset);
VerifyObjectField(isolate, kValue3Offset);
}
void ClassPositions::ClassPositionsVerify(Isolate* isolate) {
CHECK(IsClassPositions());
VerifySmiField(kStartOffset);
VerifySmiField(kEndOffset);
}
void ObjectBoilerplateDescription::ObjectBoilerplateDescriptionVerify(
Isolate* isolate) {
CHECK(IsObjectBoilerplateDescription());
CHECK_GE(this->length(),
ObjectBoilerplateDescription::kDescriptionStartIndex);
this->FixedArrayVerify(isolate);
}
void ArrayBoilerplateDescription::ArrayBoilerplateDescriptionVerify(
Isolate* isolate) {
CHECK(IsArrayBoilerplateDescription());
CHECK(constant_elements()->IsFixedArrayBase());
VerifyObjectField(isolate, kConstantElementsOffset);
}
void AsmWasmData::AsmWasmDataVerify(Isolate* isolate) {
CHECK(IsAsmWasmData());
VerifyObjectField(isolate, kManagedNativeModuleOffset);
VerifyObjectField(isolate, kExportWrappersOffset);
VerifyObjectField(isolate, kAsmJsOffsetTableOffset);
CHECK(uses_bitset()->IsHeapNumber());
VerifyObjectField(isolate, kUsesBitsetOffset);
}
void WasmDebugInfo::WasmDebugInfoVerify(Isolate* isolate) {
CHECK(IsWasmDebugInfo());
VerifyObjectField(isolate, kInstanceOffset);
CHECK(wasm_instance()->IsWasmInstanceObject());
VerifyObjectField(isolate, kInterpreterHandleOffset);
CHECK(interpreter_handle()->IsUndefined(isolate) ||
interpreter_handle()->IsForeign());
VerifyObjectField(isolate, kInterpretedFunctionsOffset);
VerifyObjectField(isolate, kLocalsNamesOffset);
VerifyObjectField(isolate, kCWasmEntriesOffset);
VerifyObjectField(isolate, kCWasmEntryMapOffset);
}
void WasmExceptionTag::WasmExceptionTagVerify(Isolate* isolate) {
CHECK(IsWasmExceptionTag());
VerifySmiField(kIndexOffset);
}
void WasmInstanceObject::WasmInstanceObjectVerify(Isolate* isolate) {
JSObjectVerify(isolate);
CHECK(IsWasmInstanceObject());
// Just generically check all tagged fields. Don't check the untagged fields,
// as some of them might still contain the "undefined" value if the
// WasmInstanceObject is not fully set up yet.
for (int offset = kHeaderSize; offset < kEndOfTaggedFieldsOffset;
offset += kTaggedSize) {
VerifyObjectField(isolate, offset);
}
}
void WasmExportedFunctionData::WasmExportedFunctionDataVerify(
Isolate* isolate) {
CHECK(IsWasmExportedFunctionData());
VerifyObjectField(isolate, kWrapperCodeOffset);
CHECK(wrapper_code()->kind() == Code::JS_TO_WASM_FUNCTION ||
wrapper_code()->kind() == Code::C_WASM_ENTRY);
VerifyObjectField(isolate, kInstanceOffset);
VerifySmiField(kJumpTableOffsetOffset);
VerifySmiField(kFunctionIndexOffset);
}
void WasmModuleObject::WasmModuleObjectVerify(Isolate* isolate) {
CHECK(IsWasmModuleObject());
VerifyObjectField(isolate, kNativeModuleOffset);
CHECK(managed_native_module()->IsForeign());
VerifyObjectField(isolate, kExportWrappersOffset);
CHECK(export_wrappers()->IsFixedArray());
VerifyObjectField(isolate, kScriptOffset);
VerifyObjectField(isolate, kAsmJsOffsetTableOffset);
VerifyObjectField(isolate, kBreakPointInfosOffset);
}
void DataHandler::DataHandlerVerify(Isolate* isolate) {
CHECK(IsDataHandler());
CHECK_IMPLIES(!smi_handler()->IsSmi(),
smi_handler()->IsCode() && IsStoreHandler());
CHECK(validity_cell()->IsSmi() || validity_cell()->IsCell());
int data_count = data_field_count();
if (data_count >= 1) {
VerifyMaybeObjectField(isolate, kData1Offset);
}
if (data_count >= 2) {
VerifyMaybeObjectField(isolate, kData2Offset);
}
if (data_count >= 3) {
VerifyMaybeObjectField(isolate, kData3Offset);
}
}
void LoadHandler::LoadHandlerVerify(Isolate* isolate) {
DataHandler::DataHandlerVerify(isolate);
// TODO(ishell): check handler integrity
}
void StoreHandler::StoreHandlerVerify(Isolate* isolate) {
DataHandler::DataHandlerVerify(isolate);
// TODO(ishell): check handler integrity
}
void AccessorInfo::AccessorInfoVerify(Isolate* isolate) {
CHECK(IsAccessorInfo());
VerifyPointer(isolate, name());
VerifyPointer(isolate, expected_receiver_type());
VerifyForeignPointer(isolate, *this, getter());
VerifyForeignPointer(isolate, *this, setter());
VerifyForeignPointer(isolate, *this, js_getter());
VerifyPointer(isolate, data());
}
void AccessorPair::AccessorPairVerify(Isolate* isolate) {
CHECK(IsAccessorPair());
VerifyPointer(isolate, getter());
VerifyPointer(isolate, setter());
}
void AccessCheckInfo::AccessCheckInfoVerify(Isolate* isolate) {
CHECK(IsAccessCheckInfo());
VerifyPointer(isolate, callback());
VerifyPointer(isolate, named_interceptor());
VerifyPointer(isolate, indexed_interceptor());
VerifyPointer(isolate, data());
}
void CallHandlerInfo::CallHandlerInfoVerify(Isolate* isolate) {
CHECK(IsCallHandlerInfo());
CHECK(map() == ReadOnlyRoots(isolate).side_effect_call_handler_info_map() ||
map() ==
ReadOnlyRoots(isolate).side_effect_free_call_handler_info_map() ||
map() == ReadOnlyRoots(isolate)
.next_call_side_effect_free_call_handler_info_map());
VerifyPointer(isolate, callback());
VerifyPointer(isolate, js_callback());
VerifyPointer(isolate, data());
}
void InterceptorInfo::InterceptorInfoVerify(Isolate* isolate) {
CHECK(IsInterceptorInfo());
VerifyForeignPointer(isolate, *this, getter());
VerifyForeignPointer(isolate, *this, setter());
VerifyForeignPointer(isolate, *this, query());
VerifyForeignPointer(isolate, *this, deleter());
VerifyForeignPointer(isolate, *this, enumerator());
VerifyPointer(isolate, data());
VerifySmiField(kFlagsOffset);
}
void TemplateInfo::TemplateInfoVerify(Isolate* isolate) {
VerifyPointer(isolate, tag());
VerifyPointer(isolate, property_list());
VerifyPointer(isolate, property_accessors());
}
void FunctionTemplateInfo::FunctionTemplateInfoVerify(Isolate* isolate) {
CHECK(IsFunctionTemplateInfo());
TemplateInfoVerify(isolate);
VerifyPointer(isolate, serial_number());
VerifyPointer(isolate, call_code());
VerifyPointer(isolate, signature());
VerifyPointer(isolate, cached_property_name());
VerifyPointer(isolate, rare_data());
}
void FunctionTemplateRareData::FunctionTemplateRareDataVerify(
Isolate* isolate) {
CHECK(IsFunctionTemplateRareData());
VerifyPointer(isolate, prototype_template());
VerifyPointer(isolate, parent_template());
VerifyPointer(isolate, named_property_handler());
VerifyPointer(isolate, indexed_property_handler());
VerifyPointer(isolate, instance_template());
VerifyPointer(isolate, access_check_info());
}
void ObjectTemplateInfo::ObjectTemplateInfoVerify(Isolate* isolate) {
CHECK(IsObjectTemplateInfo());
TemplateInfoVerify(isolate);
VerifyPointer(isolate, constructor());
VerifyPointer(isolate, data());
}
void AllocationSite::AllocationSiteVerify(Isolate* isolate) {
CHECK(IsAllocationSite());
}
void AllocationMemento::AllocationMementoVerify(Isolate* isolate) {
CHECK(IsAllocationMemento());
VerifyHeapPointer(isolate, allocation_site());
CHECK(!IsValid() || GetAllocationSite()->IsAllocationSite());
}
void Script::ScriptVerify(Isolate* isolate) {
CHECK(IsScript());
VerifyPointer(isolate, source());
VerifyPointer(isolate, name());
VerifyPointer(isolate, line_ends());
for (int i = 0; i < shared_function_infos()->length(); ++i) {
MaybeObject maybe_object = shared_function_infos()->Get(i);
HeapObject heap_object;
CHECK(maybe_object->IsWeak() || maybe_object->IsCleared() ||
(maybe_object->GetHeapObjectIfStrong(&heap_object) &&
heap_object->IsUndefined(isolate)));
}
VerifySmiField(kIdOffset);
VerifySmiField(kLineOffsetOffset);
VerifySmiField(kColumnOffsetOffset);
VerifySmiField(kScriptTypeOffset);
VerifySmiField(kEvalFromPositionOffset);
VerifySmiField(kFlagsOffset);
}
void NormalizedMapCache::NormalizedMapCacheVerify(Isolate* isolate) {
WeakFixedArray::cast(*this)->WeakFixedArrayVerify(isolate);
if (FLAG_enable_slow_asserts) {
for (int i = 0; i < length(); i++) {
MaybeObject e = WeakFixedArray::Get(i);
HeapObject heap_object;
if (e->GetHeapObjectIfWeak(&heap_object)) {
Map::cast(heap_object)->DictionaryMapVerify(isolate);
} else {
CHECK(e->IsCleared() || (e->GetHeapObjectIfStrong(&heap_object) &&
heap_object->IsUndefined(isolate)));
}
}
}
}
void DebugInfo::DebugInfoVerify(Isolate* isolate) {
CHECK(IsDebugInfo());
VerifyPointer(isolate, shared());
VerifyPointer(isolate, script());
VerifyPointer(isolate, original_bytecode_array());
VerifyPointer(isolate, break_points());
}
void StackTraceFrame::StackTraceFrameVerify(Isolate* isolate) {
CHECK(IsStackTraceFrame());
VerifySmiField(kFrameIndexOffset);
VerifySmiField(kIdOffset);
VerifyPointer(isolate, frame_array());
VerifyPointer(isolate, frame_info());
}
void StackFrameInfo::StackFrameInfoVerify(Isolate* isolate) {
CHECK(IsStackFrameInfo());
VerifyPointer(isolate, script_name());
VerifyPointer(isolate, script_name_or_source_url());
VerifyPointer(isolate, function_name());
}
void PreparseData::PreparseDataVerify(Isolate* isolate) {
CHECK(IsPreparseData());
CHECK_LE(0, data_length());
CHECK_LE(0, children_length());
for (int i = 0; i < children_length(); ++i) {
Object child = get_child_raw(i);
CHECK(child->IsNull() || child->IsPreparseData());
VerifyPointer(isolate, child);
}
}
void UncompiledDataWithPreparseData::UncompiledDataWithPreparseDataVerify(
Isolate* isolate) {
CHECK(IsUncompiledDataWithPreparseData());
VerifyPointer(isolate, inferred_name());
VerifyPointer(isolate, preparse_data());
}
void UncompiledDataWithoutPreparseData::UncompiledDataWithoutPreparseDataVerify(
Isolate* isolate) {
CHECK(IsUncompiledDataWithoutPreparseData());
VerifyPointer(isolate, inferred_name());
}
void InterpreterData::InterpreterDataVerify(Isolate* isolate) {
CHECK(IsInterpreterData());
CHECK(bytecode_array()->IsBytecodeArray());
CHECK(interpreter_trampoline()->IsCode());
}
#ifdef V8_INTL_SUPPORT
void JSV8BreakIterator::JSV8BreakIteratorVerify(Isolate* isolate) {
JSObjectVerify(isolate);
VerifyObjectField(isolate, kLocaleOffset);
VerifyObjectField(isolate, kTypeOffset);
VerifyObjectField(isolate, kBreakIteratorOffset);
VerifyObjectField(isolate, kUnicodeStringOffset);
VerifyObjectField(isolate, kBoundAdoptTextOffset);
VerifyObjectField(isolate, kBoundFirstOffset);
VerifyObjectField(isolate, kBoundNextOffset);
VerifyObjectField(isolate, kBoundCurrentOffset);
VerifyObjectField(isolate, kBoundBreakTypeOffset);
}
void JSCollator::JSCollatorVerify(Isolate* isolate) {
CHECK(IsJSCollator());
JSObjectVerify(isolate);
VerifyObjectField(isolate, kICUCollatorOffset);
VerifyObjectField(isolate, kBoundCompareOffset);
}
void JSDateTimeFormat::JSDateTimeFormatVerify(Isolate* isolate) {
JSObjectVerify(isolate);
VerifyObjectField(isolate, kICULocaleOffset);
VerifyObjectField(isolate, kICUSimpleDateFormatOffset);
VerifyObjectField(isolate, kICUDateIntervalFormatOffset);
VerifyObjectField(isolate, kBoundFormatOffset);
VerifyObjectField(isolate, kFlagsOffset);
}
void JSListFormat::JSListFormatVerify(Isolate* isolate) {
JSObjectVerify(isolate);
VerifyObjectField(isolate, kLocaleOffset);
VerifyObjectField(isolate, kICUFormatterOffset);
VerifyObjectField(isolate, kFlagsOffset);
}
void JSLocale::JSLocaleVerify(Isolate* isolate) {
JSObjectVerify(isolate);
VerifyObjectField(isolate, kICULocaleOffset);
}
void JSNumberFormat::JSNumberFormatVerify(Isolate* isolate) {
CHECK(IsJSNumberFormat());
JSObjectVerify(isolate);
VerifyObjectField(isolate, kLocaleOffset);
VerifyObjectField(isolate, kICUNumberFormatOffset);
VerifyObjectField(isolate, kBoundFormatOffset);
VerifyObjectField(isolate, kFlagsOffset);
}
void JSPluralRules::JSPluralRulesVerify(Isolate* isolate) {
CHECK(IsJSPluralRules());
JSObjectVerify(isolate);
VerifyObjectField(isolate, kLocaleOffset);
VerifyObjectField(isolate, kFlagsOffset);
VerifyObjectField(isolate, kICUPluralRulesOffset);
VerifyObjectField(isolate, kICUDecimalFormatOffset);
}
void JSRelativeTimeFormat::JSRelativeTimeFormatVerify(Isolate* isolate) {
JSObjectVerify(isolate);
VerifyObjectField(isolate, kLocaleOffset);
VerifyObjectField(isolate, kICUFormatterOffset);
VerifyObjectField(isolate, kFlagsOffset);
}
void JSSegmentIterator::JSSegmentIteratorVerify(Isolate* isolate) {
JSObjectVerify(isolate);
VerifyObjectField(isolate, kICUBreakIteratorOffset);
VerifyObjectField(isolate, kUnicodeStringOffset);
VerifyObjectField(isolate, kFlagsOffset);
}
void JSSegmenter::JSSegmenterVerify(Isolate* isolate) {
JSObjectVerify(isolate);
VerifyObjectField(isolate, kLocaleOffset);
VerifyObjectField(isolate, kICUBreakIteratorOffset);
VerifyObjectField(isolate, kFlagsOffset);
}
#endif // V8_INTL_SUPPORT
#endif // VERIFY_HEAP
#ifdef DEBUG
void JSObject::IncrementSpillStatistics(Isolate* isolate,
SpillInformation* info) {
info->number_of_objects_++;
// Named properties
if (HasFastProperties()) {
info->number_of_objects_with_fast_properties_++;
info->number_of_fast_used_fields_ += map()->NextFreePropertyIndex();
info->number_of_fast_unused_fields_ += map()->UnusedPropertyFields();
} else if (IsJSGlobalObject()) {
GlobalDictionary dict = JSGlobalObject::cast(*this)->global_dictionary();
info->number_of_slow_used_properties_ += dict->NumberOfElements();
info->number_of_slow_unused_properties_ +=
dict->Capacity() - dict->NumberOfElements();
} else {
NameDictionary dict = property_dictionary();
info->number_of_slow_used_properties_ += dict->NumberOfElements();
info->number_of_slow_unused_properties_ +=
dict->Capacity() - dict->NumberOfElements();
}
// Indexed properties
switch (GetElementsKind()) {
case HOLEY_SMI_ELEMENTS:
case PACKED_SMI_ELEMENTS:
case HOLEY_DOUBLE_ELEMENTS:
case PACKED_DOUBLE_ELEMENTS:
case HOLEY_ELEMENTS:
case PACKED_ELEMENTS:
case PACKED_FROZEN_ELEMENTS:
case PACKED_SEALED_ELEMENTS:
case FAST_STRING_WRAPPER_ELEMENTS: {
info->number_of_objects_with_fast_elements_++;
int holes = 0;
FixedArray e = FixedArray::cast(elements());
int len = e->length();
for (int i = 0; i < len; i++) {
if (e->get(i)->IsTheHole(isolate)) holes++;
}
info->number_of_fast_used_elements_ += len - holes;
info->number_of_fast_unused_elements_ += holes;
break;
}
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) case TYPE##_ELEMENTS:
TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
{
info->number_of_objects_with_fast_elements_++;
FixedArrayBase e = FixedArrayBase::cast(elements());
info->number_of_fast_used_elements_ += e->length();
break;
}
case DICTIONARY_ELEMENTS:
case SLOW_STRING_WRAPPER_ELEMENTS: {
NumberDictionary dict = element_dictionary();
info->number_of_slow_used_elements_ += dict->NumberOfElements();
info->number_of_slow_unused_elements_ +=
dict->Capacity() - dict->NumberOfElements();
break;
}
case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
case NO_ELEMENTS:
break;
}
}
void JSObject::SpillInformation::Clear() {
number_of_objects_ = 0;
number_of_objects_with_fast_properties_ = 0;
number_of_objects_with_fast_elements_ = 0;
number_of_fast_used_fields_ = 0;
number_of_fast_unused_fields_ = 0;
number_of_slow_used_properties_ = 0;
number_of_slow_unused_properties_ = 0;
number_of_fast_used_elements_ = 0;
number_of_fast_unused_elements_ = 0;
number_of_slow_used_elements_ = 0;
number_of_slow_unused_elements_ = 0;
}
void JSObject::SpillInformation::Print() {
PrintF("\n JSObject Spill Statistics (#%d):\n", number_of_objects_);
PrintF(" - fast properties (#%d): %d (used) %d (unused)\n",
number_of_objects_with_fast_properties_,
number_of_fast_used_fields_, number_of_fast_unused_fields_);
PrintF(" - slow properties (#%d): %d (used) %d (unused)\n",
number_of_objects_ - number_of_objects_with_fast_properties_,
number_of_slow_used_properties_, number_of_slow_unused_properties_);
PrintF(" - fast elements (#%d): %d (used) %d (unused)\n",
number_of_objects_with_fast_elements_,
number_of_fast_used_elements_, number_of_fast_unused_elements_);
PrintF(" - slow elements (#%d): %d (used) %d (unused)\n",
number_of_objects_ - number_of_objects_with_fast_elements_,
number_of_slow_used_elements_, number_of_slow_unused_elements_);
PrintF("\n");
}
bool DescriptorArray::IsSortedNoDuplicates(int valid_entries) {
if (valid_entries == -1) valid_entries = number_of_descriptors();
Name current_key;
uint32_t current = 0;
for (int i = 0; i < number_of_descriptors(); i++) {
Name key = GetSortedKey(i);
if (key == current_key) {
Print();
return false;
}
current_key = key;
uint32_t hash = GetSortedKey(i)->Hash();
if (hash < current) {
Print();
return false;
}
current = hash;
}
return true;
}
bool TransitionArray::IsSortedNoDuplicates(int valid_entries) {
DCHECK_EQ(valid_entries, -1);
Name prev_key;
PropertyKind prev_kind = kData;
PropertyAttributes prev_attributes = NONE;
uint32_t prev_hash = 0;
for (int i = 0; i < number_of_transitions(); i++) {
Name key = GetSortedKey(i);
uint32_t hash = key->Hash();
PropertyKind kind = kData;
PropertyAttributes attributes = NONE;
if (!TransitionsAccessor::IsSpecialTransition(key->GetReadOnlyRoots(),
key)) {
Map target = GetTarget(i);
PropertyDetails details =
TransitionsAccessor::GetTargetDetails(key, target);
kind = details.kind();
attributes = details.attributes();
} else {
// Duplicate entries are not allowed for non-property transitions.
DCHECK_NE(prev_key, key);
}
int cmp = CompareKeys(prev_key, prev_hash, prev_kind, prev_attributes, key,
hash, kind, attributes);
if (cmp >= 0) {
Print();
return false;
}
prev_key = key;
prev_hash = hash;
prev_attributes = attributes;
prev_kind = kind;
}
return true;
}
bool TransitionsAccessor::IsSortedNoDuplicates() {
// Simple and non-existent transitions are always sorted.
if (encoding() != kFullTransitionArray) return true;
return transitions()->IsSortedNoDuplicates();
}
static bool CheckOneBackPointer(Map current_map, Object target) {
return !target->IsMap() || Map::cast(target)->GetBackPointer() == current_map;
}
bool TransitionsAccessor::IsConsistentWithBackPointers() {
int num_transitions = NumberOfTransitions();
for (int i = 0; i < num_transitions; i++) {
Map target = GetTarget(i);
if (!CheckOneBackPointer(map_, target)) return false;
}
return true;
}
#endif // DEBUG
} // namespace internal
} // namespace v8
|
//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "ClangdLSPServer.h"
#include "ClangdServer.h"
#include "CodeComplete.h"
#include "Diagnostics.h"
#include "DraftStore.h"
#include "DumpAST.h"
#include "GlobalCompilationDatabase.h"
#include "LSPBinder.h"
#include "Protocol.h"
#include "SemanticHighlighting.h"
#include "SourceCode.h"
#include "TUScheduler.h"
#include "URI.h"
#include "refactor/Tweak.h"
#include "support/Context.h"
#include "support/MemoryTree.h"
#include "support/Trace.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/Version.h"
#include "clang/Tooling/Core/Replacement.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SHA1.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/raw_ostream.h"
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace clang {
namespace clangd {
namespace {
// Tracks end-to-end latency of high level lsp calls. Measurements are in
// seconds.
constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution,
"method_name");
// LSP defines file versions as numbers that increase.
// ClangdServer treats them as opaque and therefore uses strings instead.
std::string encodeVersion(llvm::Optional<int64_t> LSPVersion) {
return LSPVersion ? llvm::to_string(*LSPVersion) : "";
}
llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
int64_t Result;
if (llvm::to_integer(Encoded, Result, 10))
return Result;
if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
elog("unexpected non-numeric version {0}", Encoded);
return llvm::None;
}
const llvm::StringLiteral APPLY_FIX_COMMAND = "clangd.applyFix";
const llvm::StringLiteral APPLY_TWEAK_COMMAND = "clangd.applyTweak";
/// Transforms a tweak into a code action that would apply it if executed.
/// EXPECTS: T.prepare() was called and returned true.
CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
Range Selection) {
CodeAction CA;
CA.title = T.Title;
CA.kind = T.Kind.str();
// This tweak may have an expensive second stage, we only run it if the user
// actually chooses it in the UI. We reply with a command that would run the
// corresponding tweak.
// FIXME: for some tweaks, computing the edits is cheap and we could send them
// directly.
CA.command.emplace();
CA.command->title = T.Title;
CA.command->command = std::string(APPLY_TWEAK_COMMAND);
TweakArgs Args;
Args.file = File;
Args.tweakID = T.ID;
Args.selection = Selection;
CA.command->argument = std::move(Args);
return CA;
}
void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
SymbolKindBitset Kinds) {
for (auto &S : Syms) {
S.kind = adjustKindToCapability(S.kind, Kinds);
adjustSymbolKinds(S.children, Kinds);
}
}
SymbolKindBitset defaultSymbolKinds() {
SymbolKindBitset Defaults;
for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
++I)
Defaults.set(I);
return Defaults;
}
CompletionItemKindBitset defaultCompletionItemKinds() {
CompletionItemKindBitset Defaults;
for (size_t I = CompletionItemKindMin;
I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
Defaults.set(I);
return Defaults;
}
// Makes sure edits in \p FE are applicable to latest file contents reported by
// editor. If not generates an error message containing information about files
// that needs to be saved.
llvm::Error validateEdits(const ClangdServer &Server, const FileEdits &FE) {
size_t InvalidFileCount = 0;
llvm::StringRef LastInvalidFile;
for (const auto &It : FE) {
if (auto Draft = Server.getDraft(It.first())) {
// If the file is open in user's editor, make sure the version we
// saw and current version are compatible as this is the text that
// will be replaced by editors.
if (!It.second.canApplyTo(*Draft)) {
++InvalidFileCount;
LastInvalidFile = It.first();
}
}
}
if (!InvalidFileCount)
return llvm::Error::success();
if (InvalidFileCount == 1)
return error("File must be saved first: {0}", LastInvalidFile);
return error("Files must be saved first: {0} (and {1} others)",
LastInvalidFile, InvalidFileCount - 1);
}
} // namespace
// MessageHandler dispatches incoming LSP messages.
// It handles cross-cutting concerns:
// - serializes/deserializes protocol objects to JSON
// - logging of inbound messages
// - cancellation handling
// - basic call tracing
// MessageHandler ensures that initialize() is called before any other handler.
class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
public:
MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
trace::Span Tracer(Method, LSPLatency);
SPAN_ATTACH(Tracer, "Params", Params);
WithContext HandlerContext(handlerContext());
log("<-- {0}", Method);
if (Method == "exit")
return false;
auto Handler = Server.Handlers.NotificationHandlers.find(Method);
if (Handler != Server.Handlers.NotificationHandlers.end()) {
Handler->second(std::move(Params));
Server.maybeExportMemoryProfile();
Server.maybeCleanupMemory();
} else if (!Server.Server) {
elog("Notification {0} before initialization", Method);
} else if (Method == "$/cancelRequest") {
onCancel(std::move(Params));
} else {
log("unhandled notification {0}", Method);
}
return true;
}
bool onCall(llvm::StringRef Method, llvm::json::Value Params,
llvm::json::Value ID) override {
WithContext HandlerContext(handlerContext());
// Calls can be canceled by the client. Add cancellation context.
WithContext WithCancel(cancelableRequestContext(ID));
trace::Span Tracer(Method, LSPLatency);
SPAN_ATTACH(Tracer, "Params", Params);
ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
log("<-- {0}({1})", Method, ID);
auto Handler = Server.Handlers.MethodHandlers.find(Method);
if (Handler != Server.Handlers.MethodHandlers.end()) {
Handler->second(std::move(Params), std::move(Reply));
} else if (!Server.Server) {
elog("Call {0} before initialization.", Method);
Reply(llvm::make_error<LSPError>("server not initialized",
ErrorCode::ServerNotInitialized));
} else {
Reply(llvm::make_error<LSPError>("method not found",
ErrorCode::MethodNotFound));
}
return true;
}
bool onReply(llvm::json::Value ID,
llvm::Expected<llvm::json::Value> Result) override {
WithContext HandlerContext(handlerContext());
Callback<llvm::json::Value> ReplyHandler = nullptr;
if (auto IntID = ID.getAsInteger()) {
std::lock_guard<std::mutex> Mutex(CallMutex);
// Find a corresponding callback for the request ID;
for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
if (ReplyCallbacks[Index].first == *IntID) {
ReplyHandler = std::move(ReplyCallbacks[Index].second);
ReplyCallbacks.erase(ReplyCallbacks.begin() +
Index); // remove the entry
break;
}
}
}
if (!ReplyHandler) {
// No callback being found, use a default log callback.
ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
elog("received a reply with ID {0}, but there was no such call", ID);
if (!Result)
llvm::consumeError(Result.takeError());
};
}
// Log and run the reply handler.
if (Result) {
log("<-- reply({0})", ID);
ReplyHandler(std::move(Result));
} else {
auto Err = Result.takeError();
log("<-- reply({0}) error: {1}", ID, Err);
ReplyHandler(std::move(Err));
}
return true;
}
// Bind a reply callback to a request. The callback will be invoked when
// clangd receives the reply from the LSP client.
// Return a call id of the request.
llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
int ID;
{
std::lock_guard<std::mutex> Mutex(CallMutex);
ID = NextCallID++;
ReplyCallbacks.emplace_back(ID, std::move(Reply));
// If the queue overflows, we assume that the client didn't reply the
// oldest request, and run the corresponding callback which replies an
// error to the client.
if (ReplyCallbacks.size() > MaxReplayCallbacks) {
elog("more than {0} outstanding LSP calls, forgetting about {1}",
MaxReplayCallbacks, ReplyCallbacks.front().first);
OldestCB = std::move(ReplyCallbacks.front());
ReplyCallbacks.pop_front();
}
}
if (OldestCB)
OldestCB->second(
error("failed to receive a client reply for request ({0})",
OldestCB->first));
return ID;
}
private:
// Function object to reply to an LSP call.
// Each instance must be called exactly once, otherwise:
// - the bug is logged, and (in debug mode) an assert will fire
// - if there was no reply, an error reply is sent
// - if there were multiple replies, only the first is sent
class ReplyOnce {
std::atomic<bool> Replied = {false};
std::chrono::steady_clock::time_point Start;
llvm::json::Value ID;
std::string Method;
ClangdLSPServer *Server; // Null when moved-from.
llvm::json::Object *TraceArgs;
public:
ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
: Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
Server(Server), TraceArgs(TraceArgs) {
assert(Server);
}
ReplyOnce(ReplyOnce &&Other)
: Replied(Other.Replied.load()), Start(Other.Start),
ID(std::move(Other.ID)), Method(std::move(Other.Method)),
Server(Other.Server), TraceArgs(Other.TraceArgs) {
Other.Server = nullptr;
}
ReplyOnce &operator=(ReplyOnce &&) = delete;
ReplyOnce(const ReplyOnce &) = delete;
ReplyOnce &operator=(const ReplyOnce &) = delete;
~ReplyOnce() {
// There's one legitimate reason to never reply to a request: clangd's
// request handler send a call to the client (e.g. applyEdit) and the
// client never replied. In this case, the ReplyOnce is owned by
// ClangdLSPServer's reply callback table and is destroyed along with the
// server. We don't attempt to send a reply in this case, there's little
// to be gained from doing so.
if (Server && !Server->IsBeingDestroyed && !Replied) {
elog("No reply to message {0}({1})", Method, ID);
assert(false && "must reply to all calls!");
(*this)(llvm::make_error<LSPError>("server failed to reply",
ErrorCode::InternalError));
}
}
void operator()(llvm::Expected<llvm::json::Value> Reply) {
assert(Server && "moved-from!");
if (Replied.exchange(true)) {
elog("Replied twice to message {0}({1})", Method, ID);
assert(false && "must reply to each call only once!");
return;
}
auto Duration = std::chrono::steady_clock::now() - Start;
if (Reply) {
log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
if (TraceArgs)
(*TraceArgs)["Reply"] = *Reply;
std::lock_guard<std::mutex> Lock(Server->TranspWriter);
Server->Transp.reply(std::move(ID), std::move(Reply));
} else {
llvm::Error Err = Reply.takeError();
log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
if (TraceArgs)
(*TraceArgs)["Error"] = llvm::to_string(Err);
std::lock_guard<std::mutex> Lock(Server->TranspWriter);
Server->Transp.reply(std::move(ID), std::move(Err));
}
}
};
// Method calls may be cancelled by ID, so keep track of their state.
// This needs a mutex: handlers may finish on a different thread, and that's
// when we clean up entries in the map.
mutable std::mutex RequestCancelersMutex;
llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
void onCancel(const llvm::json::Value &Params) {
const llvm::json::Value *ID = nullptr;
if (auto *O = Params.getAsObject())
ID = O->get("id");
if (!ID) {
elog("Bad cancellation request: {0}", Params);
return;
}
auto StrID = llvm::to_string(*ID);
std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
auto It = RequestCancelers.find(StrID);
if (It != RequestCancelers.end())
It->second.first(); // Invoke the canceler.
}
Context handlerContext() const {
return Context::current().derive(
kCurrentOffsetEncoding,
Server.Opts.Encoding.getValueOr(OffsetEncoding::UTF16));
}
// We run cancelable requests in a context that does two things:
// - allows cancellation using RequestCancelers[ID]
// - cleans up the entry in RequestCancelers when it's no longer needed
// If a client reuses an ID, the last wins and the first cannot be canceled.
Context cancelableRequestContext(const llvm::json::Value &ID) {
auto Task = cancelableTask(
/*Reason=*/static_cast<int>(ErrorCode::RequestCancelled));
auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
{
std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
RequestCancelers[StrID] = {std::move(Task.second), Cookie};
}
// When the request ends, we can clean up the entry we just added.
// The cookie lets us check that it hasn't been overwritten due to ID
// reuse.
return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
auto It = RequestCancelers.find(StrID);
if (It != RequestCancelers.end() && It->second.second == Cookie)
RequestCancelers.erase(It);
}));
}
// The maximum number of callbacks held in clangd.
//
// We bound the maximum size to the pending map to prevent memory leakage
// for cases where LSP clients don't reply for the request.
// This has to go after RequestCancellers and RequestCancellersMutex since it
// can contain a callback that has a cancelable context.
static constexpr int MaxReplayCallbacks = 100;
mutable std::mutex CallMutex;
int NextCallID = 0; /* GUARDED_BY(CallMutex) */
std::deque<std::pair</*RequestID*/ int,
/*ReplyHandler*/ Callback<llvm::json::Value>>>
ReplyCallbacks; /* GUARDED_BY(CallMutex) */
ClangdLSPServer &Server;
};
constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
// call(), notify(), and reply() wrap the Transport, adding logging and locking.
void ClangdLSPServer::callMethod(StringRef Method, llvm::json::Value Params,
Callback<llvm::json::Value> CB) {
auto ID = MsgHandler->bindReply(std::move(CB));
log("--> {0}({1})", Method, ID);
std::lock_guard<std::mutex> Lock(TranspWriter);
Transp.call(Method, std::move(Params), ID);
}
void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
log("--> {0}", Method);
maybeCleanupMemory();
std::lock_guard<std::mutex> Lock(TranspWriter);
Transp.notify(Method, std::move(Params));
}
static std::vector<llvm::StringRef> semanticTokenTypes() {
std::vector<llvm::StringRef> Types;
for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
++I)
Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
return Types;
}
static std::vector<llvm::StringRef> semanticTokenModifiers() {
std::vector<llvm::StringRef> Modifiers;
for (unsigned I = 0;
I <= static_cast<unsigned>(HighlightingModifier::LastModifier); ++I)
Modifiers.push_back(
toSemanticTokenModifier(static_cast<HighlightingModifier>(I)));
return Modifiers;
}
void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Callback<llvm::json::Value> Reply) {
// Determine character encoding first as it affects constructed ClangdServer.
if (Params.capabilities.offsetEncoding && !Opts.Encoding) {
Opts.Encoding = OffsetEncoding::UTF16; // fallback
for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
if (Supported != OffsetEncoding::UnsupportedEncoding) {
Opts.Encoding = Supported;
break;
}
}
if (Params.capabilities.TheiaSemanticHighlighting &&
!Params.capabilities.SemanticTokens) {
elog("Client requested legacy semanticHighlights notification, which is "
"no longer supported. Migrate to standard semanticTokens request");
}
if (Params.rootUri && *Params.rootUri)
Opts.WorkspaceRoot = std::string(Params.rootUri->file());
else if (Params.rootPath && !Params.rootPath->empty())
Opts.WorkspaceRoot = *Params.rootPath;
if (Server)
return Reply(llvm::make_error<LSPError>("server already initialized",
ErrorCode::InvalidRequest));
if (Opts.UseDirBasedCDB) {
DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
CDBOpts.CompileCommandsDir = Dir;
CDBOpts.ContextProvider = Opts.ContextProvider;
BaseCDB =
std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts);
BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
std::move(BaseCDB));
}
auto Mangler = CommandMangler::detect();
if (Opts.ResourceDir)
Mangler.ResourceDir = *Opts.ResourceDir;
CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
tooling::ArgumentsAdjuster(std::move(Mangler)));
{
// Switch caller's context with LSPServer's background context. Since we
// rather want to propagate information from LSPServer's context into the
// Server, CDB, etc.
WithContext MainContext(BackgroundContext.clone());
llvm::Optional<WithContextValue> WithOffsetEncoding;
if (Opts.Encoding)
WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
Server.emplace(*CDB, TFS, Opts,
static_cast<ClangdServer::Callbacks *>(this));
}
applyConfiguration(Params.initializationOptions.ConfigSettings);
Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets;
Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes;
if (!Opts.CodeComplete.BundleOverloads.hasValue())
Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp;
Opts.CodeComplete.DocumentationFormat =
Params.capabilities.CompletionDocumentationFormat;
DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
DiagOpts.EmitRelatedLocations =
Params.capabilities.DiagnosticRelatedInformation;
if (Params.capabilities.WorkspaceSymbolKinds)
SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
if (Params.capabilities.CompletionItemKinds)
SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
SupportsCodeAction = Params.capabilities.CodeActionStructure;
SupportsHierarchicalDocumentSymbol =
Params.capabilities.HierarchicalDocumentSymbol;
SupportFileStatus = Params.initializationOptions.FileStatus;
HoverContentFormat = Params.capabilities.HoverContentFormat;
SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
if (Params.capabilities.WorkDoneProgress)
BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Opts.ImplicitCancellation = !Params.capabilities.CancelsStaleRequests;
llvm::json::Object ServerCaps{
{"textDocumentSync",
llvm::json::Object{
{"openClose", true},
{"change", (int)TextDocumentSyncKind::Incremental},
{"save", true},
}},
{"documentFormattingProvider", true},
{"documentRangeFormattingProvider", true},
{"documentOnTypeFormattingProvider",
llvm::json::Object{
{"firstTriggerCharacter", "\n"},
{"moreTriggerCharacter", {}},
}},
{"completionProvider",
llvm::json::Object{
{"allCommitCharacters",
{" ", "\t", "(", ")", "[", "]", "{", "}", "<",
">", ":", ";", ",", "+", "-", "/", "*", "%",
"^", "&", "#", "?", ".", "=", "\"", "'", "|"}},
{"resolveProvider", false},
// We do extra checks, e.g. that > is part of ->.
{"triggerCharacters", {".", "<", ">", ":", "\"", "/"}},
}},
{"semanticTokensProvider",
llvm::json::Object{
{"full", llvm::json::Object{{"delta", true}}},
{"range", false},
{"legend",
llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
{"tokenModifiers", semanticTokenModifiers()}}},
}},
{"signatureHelpProvider",
llvm::json::Object{
{"triggerCharacters", {"(", ","}},
}},
{"declarationProvider", true},
{"definitionProvider", true},
{"implementationProvider", true},
{"documentHighlightProvider", true},
{"documentLinkProvider",
llvm::json::Object{
{"resolveProvider", false},
}},
{"hoverProvider", true},
{"selectionRangeProvider", true},
{"documentSymbolProvider", true},
{"workspaceSymbolProvider", true},
{"referencesProvider", true},
{"astProvider", true}, // clangd extension
{"typeHierarchyProvider", true},
{"memoryUsageProvider", true}, // clangd extension
{"compilationDatabase", // clangd extension
llvm::json::Object{{"automaticReload", true}}},
{"callHierarchyProvider", true},
};
{
LSPBinder Binder(Handlers, *this);
bindMethods(Binder, Params.capabilities);
if (Opts.FeatureModules)
for (auto &Mod : *Opts.FeatureModules)
Mod.initializeLSP(Binder, Params.rawCapabilities, ServerCaps);
}
// Per LSP, renameProvider can be either boolean or RenameOptions.
// RenameOptions will be specified if the client states it supports prepare.
ServerCaps["renameProvider"] =
Params.capabilities.RenamePrepareSupport
? llvm::json::Object{{"prepareProvider", true}}
: llvm::json::Value(true);
// Per LSP, codeActionProvider can be either boolean or CodeActionOptions.
// CodeActionOptions is only valid if the client supports action literal
// via textDocument.codeAction.codeActionLiteralSupport.
llvm::json::Value CodeActionProvider = true;
ServerCaps["codeActionProvider"] =
Params.capabilities.CodeActionStructure
? llvm::json::Object{{"codeActionKinds",
{CodeAction::QUICKFIX_KIND,
CodeAction::REFACTOR_KIND,
CodeAction::INFO_KIND}}}
: llvm::json::Value(true);
if (Opts.FoldingRanges)
ServerCaps["foldingRangeProvider"] = true;
if (Opts.InlayHints)
ServerCaps["clangdInlayHintsProvider"] = true;
std::vector<llvm::StringRef> Commands;
for (llvm::StringRef Command : Handlers.CommandHandlers.keys())
Commands.push_back(Command);
llvm::sort(Commands);
ServerCaps["executeCommandProvider"] =
llvm::json::Object{{"commands", Commands}};
llvm::json::Object Result{
{{"serverInfo",
llvm::json::Object{{"name", "clangd"},
{"version", getClangToolFullVersion("clangd")}}},
{"capabilities", std::move(ServerCaps)}}};
if (Opts.Encoding)
Result["offsetEncoding"] = *Opts.Encoding;
Reply(std::move(Result));
}
void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
void ClangdLSPServer::onShutdown(const NoParams &,
Callback<std::nullptr_t> Reply) {
// Do essentially nothing, just say we're ready to exit.
ShutdownRequestReceived = true;
Reply(nullptr);
}
// sync is a clangd extension: it blocks until all background work completes.
// It blocks the calling thread, so no messages are processed until it returns!
void ClangdLSPServer::onSync(const NoParams &, Callback<std::nullptr_t> Reply) {
if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
Reply(nullptr);
else
Reply(error("Not idle after a minute"));
}
void ClangdLSPServer::onDocumentDidOpen(
const DidOpenTextDocumentParams &Params) {
PathRef File = Params.textDocument.uri.file();
const std::string &Contents = Params.textDocument.text;
Server->addDocument(File, Contents,
encodeVersion(Params.textDocument.version),
WantDiagnostics::Yes);
}
void ClangdLSPServer::onDocumentDidChange(
const DidChangeTextDocumentParams &Params) {
auto WantDiags = WantDiagnostics::Auto;
if (Params.wantDiagnostics.hasValue())
WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
: WantDiagnostics::No;
PathRef File = Params.textDocument.uri.file();
auto Code = Server->getDraft(File);
if (!Code) {
log("Trying to incrementally change non-added document: {0}", File);
return;
}
std::string NewCode(*Code);
for (const auto &Change : Params.contentChanges) {
if (auto Err = applyChange(NewCode, Change)) {
// If this fails, we are most likely going to be not in sync anymore with
// the client. It is better to remove the draft and let further
// operations fail rather than giving wrong results.
Server->removeDocument(File);
elog("Failed to update {0}: {1}", File, std::move(Err));
return;
}
}
Server->addDocument(File, NewCode, encodeVersion(Params.textDocument.version),
WantDiags, Params.forceRebuild);
}
void ClangdLSPServer::onDocumentDidSave(
const DidSaveTextDocumentParams &Params) {
Server->reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
}
void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
// We could also reparse all open files here. However:
// - this could be frequent, and revalidating all the preambles isn't free
// - this is useful e.g. when switching git branches, but we're likely to see
// fresh headers but still have the old-branch main-file content
Server->onFileEvent(Params);
// FIXME: observe config files, immediately expire time-based caches, reparse:
// - compile_commands.json and compile_flags.txt
// - .clang_format and .clang-tidy
// - .clangd and clangd/config.yaml
}
void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Callback<llvm::json::Value> Reply) {
auto It = Handlers.CommandHandlers.find(Params.command);
if (It == Handlers.CommandHandlers.end()) {
return Reply(llvm::make_error<LSPError>(
llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
ErrorCode::InvalidParams));
}
It->second(Params.argument, std::move(Reply));
}
void ClangdLSPServer::onCommandApplyEdit(const WorkspaceEdit &WE,
Callback<llvm::json::Value> Reply) {
// The flow for "apply-fix" :
// 1. We publish a diagnostic, including fixits
// 2. The user clicks on the diagnostic, the editor asks us for code actions
// 3. We send code actions, with the fixit embedded as context
// 4. The user selects the fixit, the editor asks us to apply it
// 5. We unwrap the changes and send them back to the editor
// 6. The editor applies the changes (applyEdit), and sends us a reply
// 7. We unwrap the reply and send a reply to the editor.
applyEdit(WE, "Fix applied.", std::move(Reply));
}
void ClangdLSPServer::onCommandApplyTweak(const TweakArgs &Args,
Callback<llvm::json::Value> Reply) {
auto Action = [this, Reply = std::move(Reply)](
llvm::Expected<Tweak::Effect> R) mutable {
if (!R)
return Reply(R.takeError());
assert(R->ShowMessage || (!R->ApplyEdits.empty() && "tweak has no effect"));
if (R->ShowMessage) {
ShowMessageParams Msg;
Msg.message = *R->ShowMessage;
Msg.type = MessageType::Info;
ShowMessage(Msg);
}
// When no edit is specified, make sure we Reply().
if (R->ApplyEdits.empty())
return Reply("Tweak applied.");
if (auto Err = validateEdits(*Server, R->ApplyEdits))
return Reply(std::move(Err));
WorkspaceEdit WE;
for (const auto &It : R->ApplyEdits) {
WE.changes[URI::createFile(It.first()).toString()] =
It.second.asTextEdits();
}
// ApplyEdit will take care of calling Reply().
return applyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
};
Server->applyTweak(Args.file.file(), Args.selection, Args.tweakID,
std::move(Action));
}
void ClangdLSPServer::applyEdit(WorkspaceEdit WE, llvm::json::Value Success,
Callback<llvm::json::Value> Reply) {
ApplyWorkspaceEditParams Edit;
Edit.edit = std::move(WE);
ApplyWorkspaceEdit(
Edit, [Reply = std::move(Reply), SuccessMessage = std::move(Success)](
llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
if (!Response)
return Reply(Response.takeError());
if (!Response->applied) {
std::string Reason = Response->failureReason
? *Response->failureReason
: "unknown reason";
return Reply(error("edits were not applied: {0}", Reason));
}
return Reply(SuccessMessage);
});
}
void ClangdLSPServer::onWorkspaceSymbol(
const WorkspaceSymbolParams &Params,
Callback<std::vector<SymbolInformation>> Reply) {
Server->workspaceSymbols(
Params.query, Params.limit.getValueOr(Opts.CodeComplete.Limit),
[Reply = std::move(Reply),
this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
if (!Items)
return Reply(Items.takeError());
for (auto &Sym : *Items)
Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Reply(std::move(*Items));
});
}
void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
Callback<llvm::Optional<Range>> Reply) {
Server->prepareRename(
Params.textDocument.uri.file(), Params.position, /*NewName*/ llvm::None,
Opts.Rename,
[Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable {
if (!Result)
return Reply(Result.takeError());
return Reply(std::move(Result->Target));
});
}
void ClangdLSPServer::onRename(const RenameParams &Params,
Callback<WorkspaceEdit> Reply) {
Path File = std::string(Params.textDocument.uri.file());
if (!Server->getDraft(File))
return Reply(llvm::make_error<LSPError>(
"onRename called for non-added file", ErrorCode::InvalidParams));
Server->rename(File, Params.position, Params.newName, Opts.Rename,
[File, Params, Reply = std::move(Reply),
this](llvm::Expected<RenameResult> R) mutable {
if (!R)
return Reply(R.takeError());
if (auto Err = validateEdits(*Server, R->GlobalChanges))
return Reply(std::move(Err));
WorkspaceEdit Result;
for (const auto &Rep : R->GlobalChanges) {
Result.changes[URI::createFile(Rep.first()).toString()] =
Rep.second.asTextEdits();
}
Reply(Result);
});
}
void ClangdLSPServer::onDocumentDidClose(
const DidCloseTextDocumentParams &Params) {
PathRef File = Params.textDocument.uri.file();
Server->removeDocument(File);
{
std::lock_guard<std::mutex> Lock(FixItsMutex);
FixItsMap.erase(File);
}
{
std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
LastSemanticTokens.erase(File);
}
// clangd will not send updates for this file anymore, so we empty out the
// list of diagnostics shown on the client (e.g. in the "Problems" pane of
// VSCode). Note that this cannot race with actual diagnostics responses
// because removeDocument() guarantees no diagnostic callbacks will be
// executed after it returns.
PublishDiagnosticsParams Notification;
Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
PublishDiagnostics(Notification);
}
void ClangdLSPServer::onDocumentOnTypeFormatting(
const DocumentOnTypeFormattingParams &Params,
Callback<std::vector<TextEdit>> Reply) {
auto File = Params.textDocument.uri.file();
Server->formatOnType(File, Params.position, Params.ch, std::move(Reply));
}
void ClangdLSPServer::onDocumentRangeFormatting(
const DocumentRangeFormattingParams &Params,
Callback<std::vector<TextEdit>> Reply) {
auto File = Params.textDocument.uri.file();
auto Code = Server->getDraft(File);
Server->formatFile(File, Params.range,
[Code = std::move(Code), Reply = std::move(Reply)](
llvm::Expected<tooling::Replacements> Result) mutable {
if (Result)
Reply(replacementsToEdits(*Code, Result.get()));
else
Reply(Result.takeError());
});
}
void ClangdLSPServer::onDocumentFormatting(
const DocumentFormattingParams &Params,
Callback<std::vector<TextEdit>> Reply) {
auto File = Params.textDocument.uri.file();
auto Code = Server->getDraft(File);
Server->formatFile(File,
/*Rng=*/llvm::None,
[Code = std::move(Code), Reply = std::move(Reply)](
llvm::Expected<tooling::Replacements> Result) mutable {
if (Result)
Reply(replacementsToEdits(*Code, Result.get()));
else
Reply(Result.takeError());
});
}
/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
/// Used by the clients that do not support the hierarchical view.
static std::vector<SymbolInformation>
flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
const URIForFile &FileURI) {
std::vector<SymbolInformation> Results;
std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
[&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
SymbolInformation SI;
SI.containerName = std::string(ParentName ? "" : *ParentName);
SI.name = S.name;
SI.kind = S.kind;
SI.location.range = S.range;
SI.location.uri = FileURI;
Results.push_back(std::move(SI));
std::string FullName =
!ParentName ? S.name : (ParentName->str() + "::" + S.name);
for (auto &C : S.children)
Process(C, /*ParentName=*/FullName);
};
for (auto &S : Symbols)
Process(S, /*ParentName=*/"");
return Results;
}
void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Callback<llvm::json::Value> Reply) {
URIForFile FileURI = Params.textDocument.uri;
Server->documentSymbols(
Params.textDocument.uri.file(),
[this, FileURI, Reply = std::move(Reply)](
llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
if (!Items)
return Reply(Items.takeError());
adjustSymbolKinds(*Items, SupportedSymbolKinds);
if (SupportsHierarchicalDocumentSymbol)
return Reply(std::move(*Items));
else
return Reply(flattenSymbolHierarchy(*Items, FileURI));
});
}
void ClangdLSPServer::onFoldingRange(
const FoldingRangeParams &Params,
Callback<std::vector<FoldingRange>> Reply) {
Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
}
static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Command Cmd;
if (Action.command && Action.edit)
return None; // Not representable. (We never emit these anyway).
if (Action.command) {
Cmd = *Action.command;
} else if (Action.edit) {
Cmd.command = std::string(APPLY_FIX_COMMAND);
Cmd.argument = *Action.edit;
} else {
return None;
}
Cmd.title = Action.title;
if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
Cmd.title = "Apply fix: " + Cmd.title;
return Cmd;
}
void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Callback<llvm::json::Value> Reply) {
URIForFile File = Params.textDocument.uri;
// Checks whether a particular CodeActionKind is included in the response.
auto KindAllowed = [Only(Params.context.only)](llvm::StringRef Kind) {
if (Only.empty())
return true;
return llvm::any_of(Only, [&](llvm::StringRef Base) {
return Kind.consume_front(Base) && (Kind.empty() || Kind.startswith("."));
});
};
// We provide a code action for Fixes on the specified diagnostics.
std::vector<CodeAction> FixIts;
if (KindAllowed(CodeAction::QUICKFIX_KIND)) {
for (const Diagnostic &D : Params.context.diagnostics) {
for (auto &F : getFixes(File.file(), D)) {
FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
FixIts.back().diagnostics = {D};
}
}
}
// Now enumerate the semantic code actions.
auto ConsumeActions =
[Reply = std::move(Reply), File, Selection = Params.range,
FixIts = std::move(FixIts), this](
llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
if (!Tweaks)
return Reply(Tweaks.takeError());
std::vector<CodeAction> Actions = std::move(FixIts);
Actions.reserve(Actions.size() + Tweaks->size());
for (const auto &T : *Tweaks)
Actions.push_back(toCodeAction(T, File, Selection));
// If there's exactly one quick-fix, call it "preferred".
// We never consider refactorings etc as preferred.
CodeAction *OnlyFix = nullptr;
for (auto &Action : Actions) {
if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) {
if (OnlyFix) {
OnlyFix->isPreferred = false;
break;
}
Action.isPreferred = true;
OnlyFix = &Action;
}
}
if (SupportsCodeAction)
return Reply(llvm::json::Array(Actions));
std::vector<Command> Commands;
for (const auto &Action : Actions) {
if (auto Command = asCommand(Action))
Commands.push_back(std::move(*Command));
}
return Reply(llvm::json::Array(Commands));
};
Server->enumerateTweaks(
File.file(), Params.range,
[this, KindAllowed(std::move(KindAllowed))](const Tweak &T) {
return Opts.TweakFilter(T) && KindAllowed(T.kind());
},
std::move(ConsumeActions));
}
void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Callback<CompletionList> Reply) {
if (!shouldRunCompletion(Params)) {
// Clients sometimes auto-trigger completions in undesired places (e.g.
// 'a >^ '), we return empty results in those cases.
vlog("ignored auto-triggered completion, preceding char did not match");
return Reply(CompletionList());
}
auto Opts = this->Opts.CodeComplete;
if (Params.limit && *Params.limit >= 0)
Opts.Limit = *Params.limit;
Server->codeComplete(Params.textDocument.uri.file(), Params.position, Opts,
[Reply = std::move(Reply), Opts,
this](llvm::Expected<CodeCompleteResult> List) mutable {
if (!List)
return Reply(List.takeError());
CompletionList LSPList;
LSPList.isIncomplete = List->HasMore;
for (const auto &R : List->Completions) {
CompletionItem C = R.render(Opts);
C.kind = adjustKindToCapability(
C.kind, SupportedCompletionItemKinds);
LSPList.items.push_back(std::move(C));
}
return Reply(std::move(LSPList));
});
}
void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
Callback<SignatureHelp> Reply) {
Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
[Reply = std::move(Reply), this](
llvm::Expected<SignatureHelp> Signature) mutable {
if (!Signature)
return Reply(Signature.takeError());
if (SupportsOffsetsInSignatureHelp)
return Reply(std::move(*Signature));
// Strip out the offsets from signature help for
// clients that only support string labels.
for (auto &SigInfo : Signature->signatures) {
for (auto &Param : SigInfo.parameters)
Param.labelOffsets.reset();
}
return Reply(std::move(*Signature));
});
}
// Go to definition has a toggle function: if def and decl are distinct, then
// the first press gives you the def, the second gives you the matching def.
// getToggle() returns the counterpart location that under the cursor.
//
// We return the toggled location alone (ignoring other symbols) to encourage
// editors to "bounce" quickly between locations, without showing a menu.
static Location *getToggle(const TextDocumentPositionParams &Point,
LocatedSymbol &Sym) {
// Toggle only makes sense with two distinct locations.
if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
return nullptr;
if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
Sym.Definition->range.contains(Point.position))
return &Sym.PreferredDeclaration;
if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
Sym.PreferredDeclaration.range.contains(Point.position))
return &*Sym.Definition;
return nullptr;
}
void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
Callback<std::vector<Location>> Reply) {
Server->locateSymbolAt(
Params.textDocument.uri.file(), Params.position,
[Params, Reply = std::move(Reply)](
llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
if (!Symbols)
return Reply(Symbols.takeError());
std::vector<Location> Defs;
for (auto &S : *Symbols) {
if (Location *Toggle = getToggle(Params, S))
return Reply(std::vector<Location>{std::move(*Toggle)});
Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
}
Reply(std::move(Defs));
});
}
void ClangdLSPServer::onGoToDeclaration(
const TextDocumentPositionParams &Params,
Callback<std::vector<Location>> Reply) {
Server->locateSymbolAt(
Params.textDocument.uri.file(), Params.position,
[Params, Reply = std::move(Reply)](
llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
if (!Symbols)
return Reply(Symbols.takeError());
std::vector<Location> Decls;
for (auto &S : *Symbols) {
if (Location *Toggle = getToggle(Params, S))
return Reply(std::vector<Location>{std::move(*Toggle)});
Decls.push_back(std::move(S.PreferredDeclaration));
}
Reply(std::move(Decls));
});
}
void ClangdLSPServer::onSwitchSourceHeader(
const TextDocumentIdentifier &Params,
Callback<llvm::Optional<URIForFile>> Reply) {
Server->switchSourceHeader(
Params.uri.file(),
[Reply = std::move(Reply),
Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
if (!Path)
return Reply(Path.takeError());
if (*Path)
return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
return Reply(llvm::None);
});
}
void ClangdLSPServer::onDocumentHighlight(
const TextDocumentPositionParams &Params,
Callback<std::vector<DocumentHighlight>> Reply) {
Server->findDocumentHighlights(Params.textDocument.uri.file(),
Params.position, std::move(Reply));
}
void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Callback<llvm::Optional<Hover>> Reply) {
Server->findHover(Params.textDocument.uri.file(), Params.position,
[Reply = std::move(Reply), this](
llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
if (!H)
return Reply(H.takeError());
if (!*H)
return Reply(llvm::None);
Hover R;
R.contents.kind = HoverContentFormat;
R.range = (*H)->SymRange;
switch (HoverContentFormat) {
case MarkupKind::PlainText:
R.contents.value = (*H)->present().asPlainText();
return Reply(std::move(R));
case MarkupKind::Markdown:
R.contents.value = (*H)->present().asMarkdown();
return Reply(std::move(R));
};
llvm_unreachable("unhandled MarkupKind");
});
}
void ClangdLSPServer::onTypeHierarchy(
const TypeHierarchyParams &Params,
Callback<Optional<TypeHierarchyItem>> Reply) {
Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
Params.resolve, Params.direction, std::move(Reply));
}
void ClangdLSPServer::onResolveTypeHierarchy(
const ResolveTypeHierarchyItemParams &Params,
Callback<Optional<TypeHierarchyItem>> Reply) {
Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
std::move(Reply));
}
void ClangdLSPServer::onPrepareCallHierarchy(
const CallHierarchyPrepareParams &Params,
Callback<std::vector<CallHierarchyItem>> Reply) {
Server->prepareCallHierarchy(Params.textDocument.uri.file(), Params.position,
std::move(Reply));
}
void ClangdLSPServer::onCallHierarchyIncomingCalls(
const CallHierarchyIncomingCallsParams &Params,
Callback<std::vector<CallHierarchyIncomingCall>> Reply) {
Server->incomingCalls(Params.item, std::move(Reply));
}
void ClangdLSPServer::onCallHierarchyOutgoingCalls(
const CallHierarchyOutgoingCallsParams &Params,
Callback<std::vector<CallHierarchyOutgoingCall>> Reply) {
// FIXME: To be implemented.
Reply(std::vector<CallHierarchyOutgoingCall>{});
}
void ClangdLSPServer::onInlayHints(const InlayHintsParams &Params,
Callback<std::vector<InlayHint>> Reply) {
Server->inlayHints(Params.textDocument.uri.file(), std::move(Reply));
}
void ClangdLSPServer::applyConfiguration(
const ConfigurationSettings &Settings) {
// Per-file update to the compilation database.
llvm::StringSet<> ModifiedFiles;
for (auto &Entry : Settings.compilationDatabaseChanges) {
PathRef File = Entry.first;
auto Old = CDB->getCompileCommand(File);
auto New =
tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
std::move(Entry.second.compilationCommand),
/*Output=*/"");
if (Old != New) {
CDB->setCompileCommand(File, std::move(New));
ModifiedFiles.insert(File);
}
}
Server->reparseOpenFilesIfNeeded(
[&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
}
void ClangdLSPServer::maybeExportMemoryProfile() {
if (!trace::enabled() || !ShouldProfile())
return;
static constexpr trace::Metric MemoryUsage(
"memory_usage", trace::Metric::Value, "component_name");
trace::Span Tracer("ProfileBrief");
MemoryTree MT;
profile(MT);
record(MT, "clangd_lsp_server", MemoryUsage);
}
void ClangdLSPServer::maybeCleanupMemory() {
if (!Opts.MemoryCleanup || !ShouldCleanupMemory())
return;
Opts.MemoryCleanup();
}
// FIXME: This function needs to be properly tested.
void ClangdLSPServer::onChangeConfiguration(
const DidChangeConfigurationParams &Params) {
applyConfiguration(Params.settings);
}
void ClangdLSPServer::onReference(const ReferenceParams &Params,
Callback<std::vector<Location>> Reply) {
Server->findReferences(
Params.textDocument.uri.file(), Params.position, Opts.ReferencesLimit,
[Reply = std::move(Reply),
IncludeDecl(Params.context.includeDeclaration)](
llvm::Expected<ReferencesResult> Refs) mutable {
if (!Refs)
return Reply(Refs.takeError());
// Filter out declarations if the client asked.
std::vector<Location> Result;
Result.reserve(Refs->References.size());
for (auto &Ref : Refs->References) {
bool IsDecl = Ref.Attributes & ReferencesResult::Declaration;
if (IncludeDecl || !IsDecl)
Result.push_back(std::move(Ref.Loc));
}
return Reply(std::move(Result));
});
}
void ClangdLSPServer::onGoToImplementation(
const TextDocumentPositionParams &Params,
Callback<std::vector<Location>> Reply) {
Server->findImplementations(
Params.textDocument.uri.file(), Params.position,
[Reply = std::move(Reply)](
llvm::Expected<std::vector<LocatedSymbol>> Overrides) mutable {
if (!Overrides)
return Reply(Overrides.takeError());
std::vector<Location> Impls;
for (const LocatedSymbol &Sym : *Overrides)
Impls.push_back(Sym.PreferredDeclaration);
return Reply(std::move(Impls));
});
}
void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
Callback<std::vector<SymbolDetails>> Reply) {
Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
std::move(Reply));
}
void ClangdLSPServer::onSelectionRange(
const SelectionRangeParams &Params,
Callback<std::vector<SelectionRange>> Reply) {
Server->semanticRanges(
Params.textDocument.uri.file(), Params.positions,
[Reply = std::move(Reply)](
llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
if (!Ranges)
return Reply(Ranges.takeError());
return Reply(std::move(*Ranges));
});
}
void ClangdLSPServer::onDocumentLink(
const DocumentLinkParams &Params,
Callback<std::vector<DocumentLink>> Reply) {
// TODO(forster): This currently resolves all targets eagerly. This is slow,
// because it blocks on the preamble/AST being built. We could respond to the
// request faster by using string matching or the lexer to find the includes
// and resolving the targets lazily.
Server->documentLinks(
Params.textDocument.uri.file(),
[Reply = std::move(Reply)](
llvm::Expected<std::vector<DocumentLink>> Links) mutable {
if (!Links) {
return Reply(Links.takeError());
}
return Reply(std::move(Links));
});
}
// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
static void increment(std::string &S) {
for (char &C : llvm::reverse(S)) {
if (C != '9') {
++C;
return;
}
C = '0';
}
S.insert(S.begin(), '1');
}
void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
Callback<SemanticTokens> CB) {
Server->semanticHighlights(
Params.textDocument.uri.file(),
[this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
if (!HT)
return CB(HT.takeError());
SemanticTokens Result;
Result.tokens = toSemanticTokens(*HT);
{
std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
auto &Last = LastSemanticTokens[File];
Last.tokens = Result.tokens;
increment(Last.resultId);
Result.resultId = Last.resultId;
}
CB(std::move(Result));
});
}
void ClangdLSPServer::onSemanticTokensDelta(
const SemanticTokensDeltaParams &Params,
Callback<SemanticTokensOrDelta> CB) {
Server->semanticHighlights(
Params.textDocument.uri.file(),
[this, PrevResultID(Params.previousResultId),
File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
if (!HT)
return CB(HT.takeError());
std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
SemanticTokensOrDelta Result;
{
std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
auto &Last = LastSemanticTokens[File];
if (PrevResultID == Last.resultId) {
Result.edits = diffTokens(Last.tokens, Toks);
} else {
vlog("semanticTokens/full/delta: wanted edits vs {0} but last "
"result had ID {1}. Returning full token list.",
PrevResultID, Last.resultId);
Result.tokens = Toks;
}
Last.tokens = std::move(Toks);
increment(Last.resultId);
Result.resultId = Last.resultId;
}
CB(std::move(Result));
});
}
void ClangdLSPServer::onMemoryUsage(const NoParams &,
Callback<MemoryTree> Reply) {
llvm::BumpPtrAllocator DetailAlloc;
MemoryTree MT(&DetailAlloc);
profile(MT);
Reply(std::move(MT));
}
void ClangdLSPServer::onAST(const ASTParams &Params,
Callback<llvm::Optional<ASTNode>> CB) {
Server->getAST(Params.textDocument.uri.file(), Params.range, std::move(CB));
}
ClangdLSPServer::ClangdLSPServer(Transport &Transp, const ThreadsafeFS &TFS,
const ClangdLSPServer::Options &Opts)
: ShouldProfile(/*Period=*/std::chrono::minutes(5),
/*Delay=*/std::chrono::minutes(1)),
ShouldCleanupMemory(/*Period=*/std::chrono::minutes(1),
/*Delay=*/std::chrono::minutes(1)),
BackgroundContext(Context::current().clone()), Transp(Transp),
MsgHandler(new MessageHandler(*this)), TFS(TFS),
SupportedSymbolKinds(defaultSymbolKinds()),
SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
if (Opts.ConfigProvider) {
assert(!Opts.ContextProvider &&
"Only one of ConfigProvider and ContextProvider allowed!");
this->Opts.ContextProvider = ClangdServer::createConfiguredContextProvider(
Opts.ConfigProvider, this);
}
LSPBinder Bind(this->Handlers, *this);
Bind.method("initialize", this, &ClangdLSPServer::onInitialize);
}
void ClangdLSPServer::bindMethods(LSPBinder &Bind,
const ClientCapabilities &Caps) {
// clang-format off
Bind.notification("initialized", this, &ClangdLSPServer::onInitialized);
Bind.method("shutdown", this, &ClangdLSPServer::onShutdown);
Bind.method("sync", this, &ClangdLSPServer::onSync);
Bind.method("textDocument/rangeFormatting", this, &ClangdLSPServer::onDocumentRangeFormatting);
Bind.method("textDocument/onTypeFormatting", this, &ClangdLSPServer::onDocumentOnTypeFormatting);
Bind.method("textDocument/formatting", this, &ClangdLSPServer::onDocumentFormatting);
Bind.method("textDocument/codeAction", this, &ClangdLSPServer::onCodeAction);
Bind.method("textDocument/completion", this, &ClangdLSPServer::onCompletion);
Bind.method("textDocument/signatureHelp", this, &ClangdLSPServer::onSignatureHelp);
Bind.method("textDocument/definition", this, &ClangdLSPServer::onGoToDefinition);
Bind.method("textDocument/declaration", this, &ClangdLSPServer::onGoToDeclaration);
Bind.method("textDocument/implementation", this, &ClangdLSPServer::onGoToImplementation);
Bind.method("textDocument/references", this, &ClangdLSPServer::onReference);
Bind.method("textDocument/switchSourceHeader", this, &ClangdLSPServer::onSwitchSourceHeader);
Bind.method("textDocument/prepareRename", this, &ClangdLSPServer::onPrepareRename);
Bind.method("textDocument/rename", this, &ClangdLSPServer::onRename);
Bind.method("textDocument/hover", this, &ClangdLSPServer::onHover);
Bind.method("textDocument/documentSymbol", this, &ClangdLSPServer::onDocumentSymbol);
Bind.method("workspace/executeCommand", this, &ClangdLSPServer::onCommand);
Bind.method("textDocument/documentHighlight", this, &ClangdLSPServer::onDocumentHighlight);
Bind.method("workspace/symbol", this, &ClangdLSPServer::onWorkspaceSymbol);
Bind.method("textDocument/ast", this, &ClangdLSPServer::onAST);
Bind.notification("textDocument/didOpen", this, &ClangdLSPServer::onDocumentDidOpen);
Bind.notification("textDocument/didClose", this, &ClangdLSPServer::onDocumentDidClose);
Bind.notification("textDocument/didChange", this, &ClangdLSPServer::onDocumentDidChange);
Bind.notification("textDocument/didSave", this, &ClangdLSPServer::onDocumentDidSave);
Bind.notification("workspace/didChangeWatchedFiles", this, &ClangdLSPServer::onFileEvent);
Bind.notification("workspace/didChangeConfiguration", this, &ClangdLSPServer::onChangeConfiguration);
Bind.method("textDocument/symbolInfo", this, &ClangdLSPServer::onSymbolInfo);
Bind.method("textDocument/typeHierarchy", this, &ClangdLSPServer::onTypeHierarchy);
Bind.method("typeHierarchy/resolve", this, &ClangdLSPServer::onResolveTypeHierarchy);
Bind.method("textDocument/prepareCallHierarchy", this, &ClangdLSPServer::onPrepareCallHierarchy);
Bind.method("callHierarchy/incomingCalls", this, &ClangdLSPServer::onCallHierarchyIncomingCalls);
Bind.method("callHierarchy/outgoingCalls", this, &ClangdLSPServer::onCallHierarchyOutgoingCalls);
Bind.method("textDocument/selectionRange", this, &ClangdLSPServer::onSelectionRange);
Bind.method("textDocument/documentLink", this, &ClangdLSPServer::onDocumentLink);
Bind.method("textDocument/semanticTokens/full", this, &ClangdLSPServer::onSemanticTokens);
Bind.method("textDocument/semanticTokens/full/delta", this, &ClangdLSPServer::onSemanticTokensDelta);
Bind.method("clangd/inlayHints", this, &ClangdLSPServer::onInlayHints);
Bind.method("$/memoryUsage", this, &ClangdLSPServer::onMemoryUsage);
if (Opts.FoldingRanges)
Bind.method("textDocument/foldingRange", this, &ClangdLSPServer::onFoldingRange);
Bind.command(APPLY_FIX_COMMAND, this, &ClangdLSPServer::onCommandApplyEdit);
Bind.command(APPLY_TWEAK_COMMAND, this, &ClangdLSPServer::onCommandApplyTweak);
ApplyWorkspaceEdit = Bind.outgoingMethod("workspace/applyEdit");
PublishDiagnostics = Bind.outgoingNotification("textDocument/publishDiagnostics");
ShowMessage = Bind.outgoingNotification("window/showMessage");
NotifyFileStatus = Bind.outgoingNotification("textDocument/clangd.fileStatus");
CreateWorkDoneProgress = Bind.outgoingMethod("window/workDoneProgress/create");
BeginWorkDoneProgress = Bind.outgoingNotification("$/progress");
ReportWorkDoneProgress = Bind.outgoingNotification("$/progress");
EndWorkDoneProgress = Bind.outgoingNotification("$/progress");
if(Caps.SemanticTokenRefreshSupport)
SemanticTokensRefresh = Bind.outgoingMethod("workspace/semanticTokens/refresh");
// clang-format on
}
ClangdLSPServer::~ClangdLSPServer() {
IsBeingDestroyed = true;
// Explicitly destroy ClangdServer first, blocking on threads it owns.
// This ensures they don't access any other members.
Server.reset();
}
bool ClangdLSPServer::run() {
// Run the Language Server loop.
bool CleanExit = true;
if (auto Err = Transp.loop(*MsgHandler)) {
elog("Transport error: {0}", std::move(Err));
CleanExit = false;
}
return CleanExit && ShutdownRequestReceived;
}
void ClangdLSPServer::profile(MemoryTree &MT) const {
if (Server)
Server->profile(MT.child("clangd_server"));
}
std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
const clangd::Diagnostic &D) {
std::lock_guard<std::mutex> Lock(FixItsMutex);
auto DiagToFixItsIter = FixItsMap.find(File);
if (DiagToFixItsIter == FixItsMap.end())
return {};
const auto &DiagToFixItsMap = DiagToFixItsIter->second;
auto FixItsIter = DiagToFixItsMap.find(D);
if (FixItsIter == DiagToFixItsMap.end())
return {};
return FixItsIter->second;
}
// A completion request is sent when the user types '>' or ':', but we only
// want to trigger on '->' and '::'. We check the preceeding text to make
// sure it matches what we expected.
// Running the lexer here would be more robust (e.g. we can detect comments
// and avoid triggering completion there), but we choose to err on the side
// of simplicity here.
bool ClangdLSPServer::shouldRunCompletion(
const CompletionParams &Params) const {
if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter)
return true;
auto Code = Server->getDraft(Params.textDocument.uri.file());
if (!Code)
return true; // completion code will log the error for untracked doc.
auto Offset = positionToOffset(*Code, Params.position,
/*AllowColumnsBeyondLineLength=*/false);
if (!Offset) {
vlog("could not convert position '{0}' to offset for file '{1}'",
Params.position, Params.textDocument.uri.file());
return true;
}
return allowImplicitCompletion(*Code, *Offset);
}
void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
std::vector<Diag> Diagnostics) {
PublishDiagnosticsParams Notification;
Notification.version = decodeVersion(Version);
Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
DiagnosticToReplacementMap LocalFixIts; // Temporary storage
for (auto &Diag : Diagnostics) {
toLSPDiags(Diag, Notification.uri, DiagOpts,
[&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
auto &FixItsForDiagnostic = LocalFixIts[Diag];
llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Notification.diagnostics.push_back(std::move(Diag));
});
}
// Cache FixIts
{
std::lock_guard<std::mutex> Lock(FixItsMutex);
FixItsMap[File] = LocalFixIts;
}
// Send a notification to the LSP client.
PublishDiagnostics(Notification);
}
void ClangdLSPServer::onBackgroundIndexProgress(
const BackgroundQueue::Stats &Stats) {
static const char ProgressToken[] = "backgroundIndexProgress";
// The background index did some work, maybe we need to cleanup
maybeCleanupMemory();
std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
WorkDoneProgressBegin Begin;
Begin.percentage = true;
Begin.title = "indexing";
BeginWorkDoneProgress({ProgressToken, std::move(Begin)});
BackgroundIndexProgressState = BackgroundIndexProgress::Live;
}
if (Stats.Completed < Stats.Enqueued) {
assert(Stats.Enqueued > Stats.LastIdle);
WorkDoneProgressReport Report;
Report.percentage = 100 * (Stats.Completed - Stats.LastIdle) /
(Stats.Enqueued - Stats.LastIdle);
Report.message =
llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
Stats.Enqueued - Stats.LastIdle);
ReportWorkDoneProgress({ProgressToken, std::move(Report)});
} else {
assert(Stats.Completed == Stats.Enqueued);
EndWorkDoneProgress({ProgressToken, WorkDoneProgressEnd()});
BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
}
};
switch (BackgroundIndexProgressState) {
case BackgroundIndexProgress::Unsupported:
return;
case BackgroundIndexProgress::Creating:
// Cache this update for when the progress bar is available.
PendingBackgroundIndexProgress = Stats;
return;
case BackgroundIndexProgress::Empty: {
if (BackgroundIndexSkipCreate) {
NotifyProgress(Stats);
break;
}
// Cache this update for when the progress bar is available.
PendingBackgroundIndexProgress = Stats;
BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
WorkDoneProgressCreateParams CreateRequest;
CreateRequest.token = ProgressToken;
CreateWorkDoneProgress(
CreateRequest,
[this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
if (E) {
NotifyProgress(this->PendingBackgroundIndexProgress);
} else {
elog("Failed to create background index progress bar: {0}",
E.takeError());
// give up forever rather than thrashing about
BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
}
});
break;
}
case BackgroundIndexProgress::Live:
NotifyProgress(Stats);
break;
}
}
void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
if (!SupportFileStatus)
return;
// FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
// two statuses are running faster in practice, which leads the UI constantly
// changing, and doesn't provide much value. We may want to emit status at a
// reasonable time interval (e.g. 0.5s).
if (Status.PreambleActivity == PreambleAction::Idle &&
(Status.ASTActivity.K == ASTAction::Building ||
Status.ASTActivity.K == ASTAction::RunningAction))
return;
NotifyFileStatus(Status.render(File));
}
void ClangdLSPServer::onSemanticsMaybeChanged(PathRef File) {
if (SemanticTokensRefresh) {
SemanticTokensRefresh(NoParams{}, [](llvm::Expected<std::nullptr_t> E) {
if (E)
return;
elog("Failed to refresh semantic tokens: {0}", E.takeError());
});
}
}
} // namespace clangd
} // namespace clang
|
#include "RecoLocalCalo/HcalRecAlgos/interface/HcalSeverityLevelComputer.h"
#include "CondFormats/HcalObjects/interface/HcalChannelStatus.h"
#include "DataFormats/METReco/interface/HcalCaloFlagLabels.h"
#include "DataFormats/METReco/interface/HcalPhase1FlagLabels.h"
#include "DataFormats/HcalDetId/interface/HcalGenericDetId.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
bool HcalSeverityLevelComputer::getChStBit(HcalSeverityDefinition& mydef, const std::string& mybit) {
if (mybit == "HcalCellOff")
setBit(HcalChannelStatus::HcalCellOff, mydef.chStatusMask);
else if (mybit == "HcalCellMask")
setBit(HcalChannelStatus::HcalCellMask, mydef.chStatusMask);
else if (mybit == "HcalCellDead")
setBit(HcalChannelStatus::HcalCellDead, mydef.chStatusMask);
else if (mybit == "HcalCellHot")
setBit(HcalChannelStatus::HcalCellHot, mydef.chStatusMask);
else if (mybit == "HcalCellStabErr")
setBit(HcalChannelStatus::HcalCellStabErr, mydef.chStatusMask);
else if (mybit == "HcalCellTimErr")
setBit(HcalChannelStatus::HcalCellTimErr, mydef.chStatusMask);
else if (mybit == "HcalCellTrigMask")
setBit(HcalChannelStatus::HcalCellTrigMask, mydef.chStatusMask);
else if (mybit == "HcalCellCaloTowerMask")
setBit(HcalChannelStatus::HcalCellCaloTowerMask, mydef.chStatusMask);
else if (mybit == "HcalCellCaloTowerProb")
setBit(HcalChannelStatus::HcalCellCaloTowerProb, mydef.chStatusMask);
else if (mybit == "HcalCellExcludeFromHBHENoiseSummary")
setBit(HcalChannelStatus::HcalCellExcludeFromHBHENoiseSummary, mydef.chStatusMask);
else if (mybit == "HcalCellExcludeFromHBHENoiseSummaryR45")
setBit(HcalChannelStatus::HcalCellExcludeFromHBHENoiseSummaryR45, mydef.chStatusMask);
else if (mybit == "HcalBadLaserSignal")
setBit(HcalChannelStatus::HcalBadLaserSignal, mydef.chStatusMask);
else { // error: unrecognized channel status name
edm::LogWarning("HcalSeverityLevelComputer")
<< "HcalSeverityLevelComputer: Error: ChannelStatusFlag >>" << mybit << "<< unknown. Ignoring.";
return false;
}
return true;
}
bool HcalSeverityLevelComputer::getRecHitFlag(HcalSeverityDefinition& mydef, const std::string& mybit, int phase) {
if (phase == 1) // Phase 1 Rechit flags
{
// HB, HE ++++++++++++++++++++
if (mybit == "HBHEHpdHitMultiplicity")
setBit(HcalPhase1FlagLabels::HBHEHpdHitMultiplicity, mydef.HBHEFlagMask);
else if (mybit == "HBHEIsolatedNoise")
setBit(HcalPhase1FlagLabels::HBHEIsolatedNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHEFlatNoise")
setBit(HcalPhase1FlagLabels::HBHEFlatNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHESpikeNoise")
setBit(HcalPhase1FlagLabels::HBHESpikeNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHETS4TS5Noise")
setBit(HcalPhase1FlagLabels::HBHETS4TS5Noise, mydef.HBHEFlagMask);
else if (mybit == "HBHENegativeNoise")
setBit(HcalPhase1FlagLabels::HBHENegativeNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHEPulseFitBit")
setBit(HcalPhase1FlagLabels::HBHEPulseFitBit, mydef.HBHEFlagMask);
else if (mybit == "HBHEOOTPU")
setBit(HcalPhase1FlagLabels::HBHEOOTPU, mydef.HBHEFlagMask);
// HF ++++++++++++++++++++
else if (mybit == "HFLongShort")
setBit(HcalPhase1FlagLabels::HFLongShort, mydef.HFFlagMask);
else if (mybit == "HFS8S1Ratio")
setBit(HcalPhase1FlagLabels::HFS8S1Ratio, mydef.HFFlagMask);
else if (mybit == "HFPET")
setBit(HcalPhase1FlagLabels::HFPET, mydef.HFFlagMask);
else if (mybit == "HFSignalAsymmetry")
setBit(HcalPhase1FlagLabels::HFSignalAsymmetry, mydef.HFFlagMask);
else if (mybit == "HFAnomalousHit")
setBit(HcalPhase1FlagLabels::HFAnomalousHit, mydef.HFFlagMask);
// Common subdetector bits ++++++++++++++++++++++
else if (mybit == "TimingFromTDC")
setAllRHMasks(HcalPhase1FlagLabels::TimingFromTDC, mydef);
else if (mybit == "UserDefinedBit0")
setAllRHMasks(HcalPhase1FlagLabels::UserDefinedBit0, mydef);
// unknown -------------------
else {
// error: unrecognized flag name
edm::LogWarning("HcalSeverityLevelComputer")
<< "HcalSeverityLevelComputer: Error: RecHitFlag >>" << mybit << "<< unknown. Ignoring.";
return false;
}
} else // Phase 0 Rechit flags
{
// HB, HE ++++++++++++++++++++
if (mybit == "HBHEHpdHitMultiplicity")
setBit(HcalCaloFlagLabels::HBHEHpdHitMultiplicity, mydef.HBHEFlagMask);
else if (mybit == "HBHEPulseShape")
setBit(HcalCaloFlagLabels::HBHEPulseShape, mydef.HBHEFlagMask);
else if (mybit == "HSCP_R1R2")
setBit(HcalCaloFlagLabels::HSCP_R1R2, mydef.HBHEFlagMask);
else if (mybit == "HSCP_FracLeader")
setBit(HcalCaloFlagLabels::HSCP_FracLeader, mydef.HBHEFlagMask);
else if (mybit == "HSCP_OuterEnergy")
setBit(HcalCaloFlagLabels::HSCP_OuterEnergy, mydef.HBHEFlagMask);
else if (mybit == "HSCP_ExpFit")
setBit(HcalCaloFlagLabels::HSCP_ExpFit, mydef.HBHEFlagMask);
else if (mybit == "HBHEFlatNoise")
setBit(HcalCaloFlagLabels::HBHEFlatNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHESpikeNoise")
setBit(HcalCaloFlagLabels::HBHESpikeNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHETriangleNoise")
setBit(HcalCaloFlagLabels::HBHETriangleNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHETS4TS5Noise")
setBit(HcalCaloFlagLabels::HBHETS4TS5Noise, mydef.HBHEFlagMask);
else if (mybit == "HBHENegativeNoise")
setBit(HcalCaloFlagLabels::HBHENegativeNoise, mydef.HBHEFlagMask);
else if (mybit == "HBHEPulseFitBit")
setBit(HcalCaloFlagLabels::HBHEPulseFitBit, mydef.HBHEFlagMask);
else if (mybit == "HBHEOOTPU")
setBit(HcalCaloFlagLabels::HBHEOOTPU, mydef.HBHEFlagMask);
// These are multi-bit counters; we may have to revisit how to set them in the SLComputer in the future
else if (mybit == "HBHETimingTrustBits")
setBit(HcalCaloFlagLabels::HBHETimingTrustBits, mydef.HBHEFlagMask);
else if (mybit == "HBHETimingShapedCutsBits")
setBit(HcalCaloFlagLabels::HBHETimingShapedCutsBits, mydef.HBHEFlagMask);
else if (mybit == "HBHEIsolatedNoise")
setBit(HcalCaloFlagLabels::HBHEIsolatedNoise, mydef.HBHEFlagMask);
// HO ++++++++++++++++++++
else if (mybit == "HOBit")
setBit(HcalCaloFlagLabels::HOBit, mydef.HOFlagMask);
// HF ++++++++++++++++++++
else if (mybit == "HFLongShort")
setBit(HcalCaloFlagLabels::HFLongShort, mydef.HFFlagMask);
else if (mybit == "HFDigiTime")
setBit(HcalCaloFlagLabels::HFDigiTime, mydef.HFFlagMask);
else if (mybit == "HFInTimeWindow")
setBit(HcalCaloFlagLabels::HFInTimeWindow, mydef.HFFlagMask);
else if (mybit == "HFS8S1Ratio")
setBit(HcalCaloFlagLabels::HFS8S1Ratio, mydef.HFFlagMask);
else if (mybit == "HFPET")
setBit(HcalCaloFlagLabels::HFPET, mydef.HFFlagMask);
else if (mybit == "HFTimingTrustBits")
setBit(HcalCaloFlagLabels::HFTimingTrustBits, mydef.HFFlagMask); // multi-bit counter
// ZDC ++++++++++++++++++++
else if (mybit == "ZDCBit")
setBit(HcalCaloFlagLabels::ZDCBit, mydef.ZDCFlagMask);
// Calib ++++++++++++++++++++
else if (mybit == "CalibrationBit")
setBit(HcalCaloFlagLabels::CalibrationBit, mydef.CalibFlagMask);
// Common subdetector bits ++++++++++++++++++++++
else if (mybit == "TimingSubtractedBit")
setAllRHMasks(HcalCaloFlagLabels::TimingSubtractedBit, mydef);
else if (mybit == "TimingAddedBit")
setAllRHMasks(HcalCaloFlagLabels::TimingAddedBit, mydef);
else if (mybit == "TimingErrorBit")
setAllRHMasks(HcalCaloFlagLabels::TimingErrorBit, mydef);
else if (mybit == "ADCSaturationBit")
setAllRHMasks(HcalCaloFlagLabels::ADCSaturationBit, mydef);
else if (mybit == "AddedSimHcalNoise")
setAllRHMasks(HcalCaloFlagLabels::AddedSimHcalNoise, mydef);
else if (mybit == "UserDefinedBit0")
setAllRHMasks(HcalCaloFlagLabels::UserDefinedBit0, mydef);
// additional defined diagnostic bits; not currently used for rejection
else if (mybit == "PresampleADC")
setAllRHMasks(HcalCaloFlagLabels::PresampleADC, mydef);
else if (mybit == "Fraction2TS")
setAllRHMasks(HcalCaloFlagLabels::Fraction2TS,
mydef); // should deprecate this at some point; it's been replaced by PresampleADC
// unknown -------------------
else {
// error: unrecognized flag name
edm::LogWarning("HcalSeverityLevelComputer")
<< "HcalSeverityLevelComputer: Error: RecHitFlag >>" << mybit << "<< unknown. Ignoring.";
return false;
}
}
return true;
}
HcalSeverityLevelComputer::HcalSeverityLevelComputer(const edm::ParameterSet& iConfig) {
// initialize: get the levels and masks from the cfg:
typedef std::vector<edm::ParameterSet> myParameters;
myParameters myLevels = iConfig.getParameter<myParameters>((std::string) "SeverityLevels");
unsigned int phase_ = iConfig.getParameter<unsigned int>("phase");
// now run through the parameter set vector:
for (myParameters::iterator itLevels = myLevels.begin(); itLevels != myLevels.end(); ++itLevels) {
// create the basic object
HcalSeverityDefinition mydef;
// get the level:
mydef.sevLevel = itLevels->getParameter<int>("Level");
// get the RecHitFlags:
std::vector<std::string> myRecHitFlags = itLevels->getParameter<std::vector<std::string> >("RecHitFlags");
// get channel statuses:
std::vector<std::string> myChStatuses = itLevels->getParameter<std::vector<std::string> >("ChannelStatus");
// now translate the RecHitFlags and the ChannelStatuses into a mask each:
// create counters for invalid flags to be able to catch cases where a definition consists only of invalid bit names:
unsigned int bvalid = 0;
unsigned int bnonempty = 0;
// channel status:
for (unsigned k = 0; k < myChStatuses.size(); k++) {
if (myChStatuses[k].empty())
break; // empty string
bnonempty++;
bvalid += getChStBit(mydef, myChStatuses[k]);
}
// RecHitFlag:
// HBHEStatusFlag, HOStatusFlag, HFStatusFlag, ZDCStatusFlag, CalibrationFlag
for (unsigned k = 0; k < myRecHitFlags.size(); k++) {
if (myRecHitFlags[k].empty())
break; // empty string
bnonempty++;
bvalid += getRecHitFlag(mydef, myRecHitFlags[k], phase_);
}
// std::cout << "Made Severity Level:" << std::endl;
// std::cout << mydef << std::endl;
// case where definition is made entirely out of invalid flags but not empty strings
if ((!bvalid) && (bnonempty)) {
edm::LogWarning("HcalSeverityLevelComputer") << "Warning: level " << mydef.sevLevel
<< " consists of invalid definitions only: "
// << myRecHitFlags << "; " << myChStatuses
<< " Ignoring definition.";
continue;
}
// finally, append the masks to the mask vectors, sorting them according to level
std::vector<HcalSeverityDefinition>::iterator it = SevDef.begin();
do {
if (it == SevDef.end()) {
SevDef.push_back(mydef);
break;
}
if (it->sevLevel == mydef.sevLevel) {
edm::LogWarning("HcalSeverityLevelComputer") << "HcalSeverityLevelComputer: Warning: level " << mydef.sevLevel
<< " already defined. Ignoring new definition.";
break;
}
if (it->sevLevel < mydef.sevLevel)
if (((it + 1) == SevDef.end()) || ((it + 1)->sevLevel > mydef.sevLevel)) {
SevDef.insert(it + 1, mydef);
break;
}
it++;
} while (it != SevDef.end());
} //for (myParameters::iterator itLevels=myLevels.begin(); itLevels != myLevels.end(); ++itLevels)
edm::LogInfo("HcalSeverityLevelComputer") << "HcalSeverityLevelComputer - Summary of Severity Levels:" << std::endl;
for (std::vector<HcalSeverityDefinition>::iterator it = SevDef.begin(); it != SevDef.end(); it++) {
// debug: write the levels definitions on screen:
edm::LogInfo("HcalSeverityLevelComputer") << (*it) << std::endl;
}
//
// Now make the definition for recoveredRecHit
//
std::vector<std::string> myRecovered = iConfig.getParameter<std::vector<std::string> >("RecoveredRecHitBits");
RecoveredRecHit_ = new HcalSeverityDefinition();
for (unsigned k = 0; k < myRecovered.size(); k++) {
if (myRecovered[k].empty())
break;
getRecHitFlag((*RecoveredRecHit_), myRecovered[k], phase_);
}
//
// Now make the definition for dropChannel
//
std::vector<std::string> myDrop = iConfig.getParameter<std::vector<std::string> >("DropChannelStatusBits");
DropChannel_ = new HcalSeverityDefinition();
for (unsigned k = 0; k < myDrop.size(); k++) {
if (myDrop[k].empty())
break;
getChStBit((*DropChannel_), myDrop[k]);
}
edm::LogInfo("HcalSeverityLevelComputer") << "HcalSeverityLevelComputer - Summary for Recovered RecHit bits: \n"
<< (*RecoveredRecHit_) << std::endl
<< "HcalSeverityLevelComputer - Summary for Drop the Channel bits: \n"
<< (*DropChannel_) << std::endl;
} // HcalSeverityLevelComputer::HcalSeverityLevelComputer
HcalSeverityLevelComputer::~HcalSeverityLevelComputer() {
delete DropChannel_;
delete RecoveredRecHit_;
}
int HcalSeverityLevelComputer::getSeverityLevel(const DetId& myid,
const uint32_t& myflag,
const uint32_t& mystatus) const {
uint32_t myRecHitMask;
HcalGenericDetId myId(myid);
HcalGenericDetId::HcalGenericSubdetector mysubdet = myId.genericSubdet();
// for (unsigned i=(SevDef.size()-1); i >= 0; i--) // Wrong
// Since i is unsigned, i >= 0 is always true,
// and the loop termination condition is never reached.
// We offset the loop index by one to fix this.
for (size_t j = (SevDef.size()); j > 0; j--) {
size_t i = j - 1;
switch (mysubdet) {
case HcalGenericDetId::HcalGenBarrel:
case HcalGenericDetId::HcalGenEndcap:
myRecHitMask = SevDef[i].HBHEFlagMask;
break;
case HcalGenericDetId::HcalGenOuter:
myRecHitMask = SevDef[i].HOFlagMask;
break;
case HcalGenericDetId::HcalGenForward:
myRecHitMask = SevDef[i].HFFlagMask;
break;
case HcalGenericDetId::HcalGenZDC:
myRecHitMask = SevDef[i].ZDCFlagMask;
break;
case HcalGenericDetId::HcalGenCalibration:
myRecHitMask = SevDef[i].CalibFlagMask;
break;
default:
myRecHitMask = 0;
}
// for debugging:
// std::cout << std::hex << " SLD: RHMask 0x" << myRecHitMask
// << " chstmask 0x" << SevDef[i].chStatusMask
// << " RHmask & myflag 0x" << (myRecHitMask&myflag)
// << " chstmask & mystatus 0x" << (SevDef[i].chStatusMask&mystatus)
// << std::dec << " level = " << SevDef[i].sevLevel << std::endl;
// true if:
// rechitmask empty and chstatusmask empty
// rechitmask empty and chstatusmask&mychstat true
// chstatusmask empty and rechitmask&myflag true
// rechitmask&myflag true OR chstatusmask&mychstat true
// if ( ( ( (!myRecHitMask) || (myRecHitMask & myflag) ) &&
if ((((!SevDef[i].HBHEFlagMask && !SevDef[i].HOFlagMask && !SevDef[i].HFFlagMask && !SevDef[i].ZDCFlagMask &&
!SevDef[i].CalibFlagMask) ||
(myRecHitMask & myflag)) &&
((!SevDef[i].chStatusMask) || (SevDef[i].chStatusMask & mystatus))) ||
((myRecHitMask & myflag) || (SevDef[i].chStatusMask & mystatus)))
return SevDef[i].sevLevel;
}
return -100; // default value, if no definition applies
}
bool HcalSeverityLevelComputer::recoveredRecHit(const DetId& myid, const uint32_t& myflag) const {
uint32_t myRecHitMask;
HcalGenericDetId myId(myid);
HcalGenericDetId::HcalGenericSubdetector mysubdet = myId.genericSubdet();
switch (mysubdet) {
case HcalGenericDetId::HcalGenBarrel:
case HcalGenericDetId::HcalGenEndcap:
myRecHitMask = RecoveredRecHit_->HBHEFlagMask;
break;
case HcalGenericDetId::HcalGenOuter:
myRecHitMask = RecoveredRecHit_->HOFlagMask;
break;
case HcalGenericDetId::HcalGenForward:
myRecHitMask = RecoveredRecHit_->HFFlagMask;
break;
case HcalGenericDetId::HcalGenZDC:
myRecHitMask = RecoveredRecHit_->ZDCFlagMask;
break;
case HcalGenericDetId::HcalGenCalibration:
myRecHitMask = RecoveredRecHit_->CalibFlagMask;
break;
default:
myRecHitMask = 0;
}
if (myRecHitMask & myflag)
return true;
return false;
}
bool HcalSeverityLevelComputer::dropChannel(const uint32_t& mystatus) const {
if (DropChannel_->chStatusMask & mystatus)
return true;
return false;
}
void HcalSeverityLevelComputer::setBit(const unsigned bitnumber, uint32_t& where) {
uint32_t statadd = 0x1 << (bitnumber);
where = where | statadd;
}
void HcalSeverityLevelComputer::setAllRHMasks(const unsigned bitnumber, HcalSeverityDefinition& mydef) {
setBit(bitnumber, mydef.HBHEFlagMask);
setBit(bitnumber, mydef.HOFlagMask);
setBit(bitnumber, mydef.HFFlagMask);
setBit(bitnumber, mydef.ZDCFlagMask);
setBit(bitnumber, mydef.CalibFlagMask);
}
std::ostream& operator<<(std::ostream& s, const HcalSeverityLevelComputer::HcalSeverityDefinition& def) {
s << "Hcal Severity Level Definition, Level = " << def.sevLevel << std::endl;
s << std::hex << std::showbase;
s << " channel status mask = " << def.chStatusMask << std::endl;
s << " HBHEFlagMask = " << def.HBHEFlagMask << std::endl;
s << " HOFlagMask = " << def.HOFlagMask << std::endl;
s << " HFFlagMask = " << def.HFFlagMask << std::endl;
s << " ZDCFlagMask = " << def.ZDCFlagMask << std::endl;
s << " CalibFlagMask = " << def.CalibFlagMask << std::dec << std::noshowbase << std::endl;
return s;
}
|
/* $Id: panama.c 216 2010-06-08 09:46:57Z tp $ */
/*
* PANAMA implementation.
*
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
*
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
#include <stddef.h>
#include <string.h>
#include "sph_panama.h"
#define LVAR17(b) sph_u32 \
b ## 0, b ## 1, b ## 2, b ## 3, b ## 4, b ## 5, \
b ## 6, b ## 7, b ## 8, b ## 9, b ## 10, b ## 11, \
b ## 12, b ## 13, b ## 14, b ## 15, b ## 16;
#define LVARS \
LVAR17(a) \
LVAR17(g) \
LVAR17(p) \
LVAR17(t)
#define M17(macro) do { \
macro( 0, 1, 2, 4); \
macro( 1, 2, 3, 5); \
macro( 2, 3, 4, 6); \
macro( 3, 4, 5, 7); \
macro( 4, 5, 6, 8); \
macro( 5, 6, 7, 9); \
macro( 6, 7, 8, 10); \
macro( 7, 8, 9, 11); \
macro( 8, 9, 10, 12); \
macro( 9, 10, 11, 13); \
macro(10, 11, 12, 14); \
macro(11, 12, 13, 15); \
macro(12, 13, 14, 16); \
macro(13, 14, 15, 0); \
macro(14, 15, 16, 1); \
macro(15, 16, 0, 2); \
macro(16, 0, 1, 3); \
} while (0)
#define BUPDATE1(n0, n2) do { \
sc->buffer[ptr24][n0] ^= sc->buffer[ptr31][n2]; \
sc->buffer[ptr31][n2] ^= INW1(n2); \
} while (0)
#define BUPDATE do { \
BUPDATE1(0, 2); \
BUPDATE1(1, 3); \
BUPDATE1(2, 4); \
BUPDATE1(3, 5); \
BUPDATE1(4, 6); \
BUPDATE1(5, 7); \
BUPDATE1(6, 0); \
BUPDATE1(7, 1); \
} while (0)
#define RSTATE(n0, n1, n2, n4) (a ## n0 = sc->state[n0])
#define WSTATE(n0, n1, n2, n4) (sc->state[n0] = a ## n0)
#define GAMMA(n0, n1, n2, n4) \
(g ## n0 = a ## n0 ^ (a ## n1 | SPH_T32(~a ## n2)))
#define PI_ALL do { \
p0 = g0; \
p1 = SPH_ROTL32( g7, 1); \
p2 = SPH_ROTL32(g14, 3); \
p3 = SPH_ROTL32( g4, 6); \
p4 = SPH_ROTL32(g11, 10); \
p5 = SPH_ROTL32( g1, 15); \
p6 = SPH_ROTL32( g8, 21); \
p7 = SPH_ROTL32(g15, 28); \
p8 = SPH_ROTL32( g5, 4); \
p9 = SPH_ROTL32(g12, 13); \
p10 = SPH_ROTL32( g2, 23); \
p11 = SPH_ROTL32( g9, 2); \
p12 = SPH_ROTL32(g16, 14); \
p13 = SPH_ROTL32( g6, 27); \
p14 = SPH_ROTL32(g13, 9); \
p15 = SPH_ROTL32( g3, 24); \
p16 = SPH_ROTL32(g10, 8); \
} while (0)
#define THETA(n0, n1, n2, n4) \
(t ## n0 = p ## n0 ^ p ## n1 ^ p ## n4)
#define SIGMA_ALL do { \
a0 = t0 ^ 1; \
a1 = t1 ^ INW2(0); \
a2 = t2 ^ INW2(1); \
a3 = t3 ^ INW2(2); \
a4 = t4 ^ INW2(3); \
a5 = t5 ^ INW2(4); \
a6 = t6 ^ INW2(5); \
a7 = t7 ^ INW2(6); \
a8 = t8 ^ INW2(7); \
a9 = t9 ^ sc->buffer[ptr16][0]; \
a10 = t10 ^ sc->buffer[ptr16][1]; \
a11 = t11 ^ sc->buffer[ptr16][2]; \
a12 = t12 ^ sc->buffer[ptr16][3]; \
a13 = t13 ^ sc->buffer[ptr16][4]; \
a14 = t14 ^ sc->buffer[ptr16][5]; \
a15 = t15 ^ sc->buffer[ptr16][6]; \
a16 = t16 ^ sc->buffer[ptr16][7]; \
} while (0)
#define PANAMA_STEP do { \
unsigned ptr16, ptr24, ptr31; \
\
ptr24 = (ptr0 - 8) & 31; \
ptr31 = (ptr0 - 1) & 31; \
BUPDATE; \
M17(GAMMA); \
PI_ALL; \
M17(THETA); \
ptr16 = ptr0 ^ 16; \
SIGMA_ALL; \
ptr0 = ptr31; \
} while (0)
/*
* These macros are used to compute
*/
#define INC0 1
#define INC1 2
#define INC2 3
#define INC3 4
#define INC4 5
#define INC5 6
#define INC6 7
#define INC7 8
/*
* Push data by blocks of 32 bytes. "pbuf" must be 32-bit aligned. Each
* iteration processes 32 data bytes; "num" contains the number of
* iterations.
*/
static void
panama_push(sph_panama_context *sc, const unsigned char *pbuf, size_t num)
{
LVARS
unsigned ptr0;
#if SPH_LITTLE_FAST
#define INW1(i) sph_dec32le_aligned(pbuf + 4 * (i))
#else
sph_u32 X_var[8];
#define INW1(i) X_var[i]
#endif
#define INW2(i) INW1(i)
M17(RSTATE);
ptr0 = sc->buffer_ptr;
while (num -- > 0) {
#if !SPH_LITTLE_FAST
int i;
for (i = 0; i < 8; i ++)
X_var[i] = sph_dec32le_aligned(pbuf + 4 * (i));
#endif
PANAMA_STEP;
pbuf = (const unsigned char *)pbuf + 32;
}
M17(WSTATE);
sc->buffer_ptr = ptr0;
#undef INW1
#undef INW2
}
/*
* Perform the "pull" operation repeatedly ("num" times). The hash output
* will be extracted from the state afterwards.
*/
static void
panama_pull(sph_panama_context *sc, unsigned num)
{
LVARS
unsigned ptr0;
#define INW1(i) INW_H1(INC ## i)
#define INW_H1(i) INW_H2(i)
#define INW_H2(i) a ## i
#define INW2(i) sc->buffer[ptr4][i]
M17(RSTATE);
ptr0 = sc->buffer_ptr;
while (num -- > 0) {
unsigned ptr4;
ptr4 = (ptr0 + 4) & 31;
PANAMA_STEP;
}
M17(WSTATE);
#undef INW1
#undef INW_H1
#undef INW_H2
#undef INW2
}
/* see sph_panama.h */
void
sph_panama_init(void *cc)
{
sph_panama_context *sc;
sc = (sph_panama_context *) cc;
/*
* This is not completely conformant, but "it will work
* everywhere". Initial state consists of zeroes everywhere.
* Conceptually, the sph_u32 type may have padding bits which
* must not be set to 0; but such an architecture remains to
* be seen.
*/
sc->data_ptr = 0;
memset(sc->buffer, 0, sizeof sc->buffer);
sc->buffer_ptr = 0;
memset(sc->state, 0, sizeof sc->state);
}
#ifdef SPH_UPTR
static void
panama_short(void *cc, const void *data, size_t len)
#else
void
sph_panama(void *cc, const void *data, size_t len)
#endif
{
sph_panama_context *sc;
unsigned current;
sc = (sph_panama_context *) cc;
current = sc->data_ptr;
while (len > 0) {
unsigned clen;
clen = (sizeof sc->data) - current;
if (clen > len)
clen = len;
memcpy(sc->data + current, data, clen);
data = (const unsigned char *)data + clen;
len -= clen;
current += clen;
if (current == sizeof sc->data) {
current = 0;
panama_push(sc, sc->data, 1);
}
}
sc->data_ptr = current;
}
#ifdef SPH_UPTR
/* see sph_panama.h */
void
sph_panama(void *cc, const void *data, size_t len)
{
sph_panama_context *sc;
unsigned current;
size_t rlen;
if (len < (2 * sizeof sc->data)) {
panama_short(cc, data, len);
return;
}
sc = (sph_panama_context *)cc;
current = sc->data_ptr;
if (current > 0) {
unsigned t;
t = (sizeof sc->data) - current;
panama_short(sc, data, t);
data = (const unsigned char *)data + t;
len -= t;
}
#if !SPH_UNALIGNED
if (((SPH_UPTR)data & 3) != 0) {
panama_short(sc, data, len);
return;
}
#endif
panama_push(sc, (const unsigned char *) data, len >> 5);
rlen = len & 31;
if (rlen > 0)
memcpy(sc->data,
(const unsigned char *)data + len - rlen, rlen);
sc->data_ptr = rlen;
}
#endif
/* see sph_panama.h */
void
sph_panama_close(void *cc, void *dst)
{
sph_panama_context *sc;
unsigned current;
int i;
sc = (sph_panama_context *) cc;
current = sc->data_ptr;
sc->data[current ++] = 0x01;
memset(sc->data + current, 0, (sizeof sc->data) - current);
panama_push(sc, sc->data, 1);
panama_pull(sc, 32);
for (i = 0; i < 8; i ++)
sph_enc32le((unsigned char *)dst + 4 * i, sc->state[i + 9]);
sph_panama_init(sc);
}
|
//
// Created by AUGUS on 2021/8/28.
//
#include "augus_list.hh"
using namespace augus_list;
ListSortSptr ListSort::instance() {
static ListSortSptr _sptr = nullptr;
if (_sptr == nullptr) {
_sptr = std::make_shared<ListSort>();
}
return _sptr;
}
|
#pragma once
#include <string> // std::String
#include <unordered_map> // std::unordered_map
#include <utility> // std::pair
#include <vector> // std::vector
#include <seqan/basic.h>
#include <seqan/hts_io.h> // seqan::HtsFileIn, seqan::BamAlignmentRecord
#include <seqan/sequence.h>
#include <graphtyper/utilities/hash_seqan.hpp> // For std::unordered_map<seqan::String<char>, seqan::BamAlignmentRecord>
namespace gyper
{
using TReadPair = std::pair<seqan::BamAlignmentRecord, seqan::BamAlignmentRecord>;
using TReads = std::vector<TReadPair>;
using TReadsFirst = std::unordered_map<seqan::String<char>, seqan::BamAlignmentRecord>;
class SamReader
{
public:
SamReader(std::string const & hts_path, std::vector<std::string> const & _regions);
TReads read_N_reads(std::size_t const N);
void insert_reads(TReads & reads, seqan::BamAlignmentRecord && record);
std::size_t r = 0; /* Current region index */
private:
seqan::HtsFileIn hts_file;
std::vector<std::string> regions;
TReadsFirst reads_first;
TReads unpaired_reads;
};
} // namespace gyper
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
// Disable warning for long symbol names in this file only
#include "itkImage.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionConstIterator.h"
#include "itkTestingMacros.h"
#include <algorithm>
#include <numeric>
int itkRecursiveGaussianImageFiltersTest(int, char* [] )
{
{ // 3D test
// Define the dimension of the images
const unsigned int myDimension = 3;
// Declare the types of the images
typedef itk::Image<float, myDimension> myImageType;
// Declare the type of the index to access images
typedef itk::Index<myDimension> myIndexType;
// Declare the type of the size
typedef itk::Size<myDimension> mySizeType;
// Declare the type of the Region
typedef itk::ImageRegion<myDimension> myRegionType;
// Create the image
myImageType::Pointer inputImage = myImageType::New();
// Define their size, and start index
mySizeType size;
size[0] = 100;
size[1] = 100;
size[2] = 100;
myIndexType start;
start.Fill(0);
myRegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize Image A
inputImage->SetLargestPossibleRegion( region );
inputImage->SetBufferedRegion( region );
inputImage->SetRequestedRegion( region );
inputImage->Allocate();
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIteratorWithIndex<myImageType> myIteratorType;
// Create one iterator for the Input Image A (this is a light object)
myIteratorType it( inputImage, inputImage->GetRequestedRegion() );
// Initialize the content of Image A
std::cout << "Input Image initialization " << std::endl;
while( !it.IsAtEnd() )
{
it.Set( 0.0 );
++it;
}
size[0] = 60;
size[1] = 60;
size[2] = 60;
start[0] = 20;
start[1] = 20;
start[2] = 20;
// Create one iterator for an internal region
region.SetSize( size );
region.SetIndex( start );
myIteratorType itb( inputImage, region );
// Initialize the content the internal region
while( !itb.IsAtEnd() )
{
itb.Set( 100.0 );
++itb;
}
// Declare the type for the Gaussian filter
typedef itk::RecursiveGaussianImageFilter<
myImageType,
myImageType
> myGaussianFilterType;
// Create a Filter
myGaussianFilterType::Pointer filter = myGaussianFilterType::New();
// Connect the input images
filter->SetInput( inputImage );
filter->SetDirection( 2 ); // apply along Z
filter->SetOrder( myGaussianFilterType::ZeroOrder );
// Execute the filter
std::cout << "Executing Smoothing filter...";
filter->Update();
std::cout << " Done !" << std::endl;
// Create a Filter
myGaussianFilterType::Pointer filter1 = myGaussianFilterType::New();
// Connect the input images
filter1->SetInput( inputImage );
filter1->SetDirection( 2 ); // apply along Z
filter1->SetOrder( myGaussianFilterType::FirstOrder );
// Execute the filter1
std::cout << "Executing First Derivative filter...";
filter1->Update();
std::cout << " Done !" << std::endl;
// Create a Filter
myGaussianFilterType::Pointer filter2 = myGaussianFilterType::New();
// Connect the input images
filter2->SetInput( inputImage );
filter2->SetDirection( 2 ); // apply along Z
filter2->SetOrder( myGaussianFilterType::SecondOrder );
// Execute the filter2
std::cout << "Executing Second Derivative filter...";
filter2->Update();
std::cout << " Done !" << std::endl;
}
{ // Test normalizations factors using a 1D image
std::cout << "Test normalizations factors using a 1-D image" << std::endl;
typedef float PixelType;
typedef itk::Image< PixelType, 1 > ImageType;
typedef ImageType::SizeType SizeType;
typedef ImageType::IndexType IndexType;
typedef ImageType::RegionType RegionType;
typedef ImageType::SpacingType SpacingType;
typedef itk::NumericTraits< PixelType >::RealType PixelRealType;
SizeType size;
size[0] = 21;
IndexType start;
start[0] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
SpacingType spacing;
spacing[0] = 1.0;
ImageType::Pointer inputImage = ImageType::New();
inputImage->SetRegions( region );
inputImage->Allocate();
inputImage->SetSpacing( spacing );
inputImage->FillBuffer( itk::NumericTraits< PixelType >::ZeroValue() );
IndexType index;
index[0] = ( size[0] - 1 ) / 2; // the middle pixel
inputImage->SetPixel( index, static_cast< PixelType >( 1000.0 ) );
typedef itk::RecursiveGaussianImageFilter<
ImageType, ImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( inputImage );
std::cout << "Testing normalization across scales... ";
{ // begin of test for normalization across scales
filter->SetNormalizeAcrossScale( true );
const double sigmaA = 2.0;
filter->SetSigma( sigmaA );
filter->Update();
const PixelType valueA = filter->GetOutput()->GetPixel( index );
filter->SetNormalizeAcrossScale( false );
const double sigmaB = 2.0;
filter->SetSigma( sigmaB );
filter->Update();
const PixelType valueB = filter->GetOutput()->GetPixel( index );
// note: for scale space normalization, no scaling should occur
// The additional scale-space testing is performed in a separate
// test.
if( std::fabs( valueB - valueA ) > 1e-4 )
{
std::cout << "FAILED !" << std::endl;
std::cerr << "Error, Normalization across scales is failing" << std::endl;
std::cerr << "Central pixel at sigma = " << sigmaA << " = " << valueA << std::endl;
std::cerr << "Central pixel at sigma = " << sigmaB << " = " << valueB << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "PASSED !" << std::endl;
}
} // end of test for normalization across scales
std::cout << "Testing normalization... ";
{ // begin of test for normalization
filter->SetNormalizeAcrossScale( true );
// size of image is 21, so a sigma of 2 gives up 5 std-devs and
// an expected error of >1e-5 due to truncation
const double sigmaA = 2.0;
filter->SetSigma( sigmaA );
filter->Update();
// the input is an impulse with a value of 1000
// the resulting convolution should aproximatly sum to the same
typedef itk::ImageRegionConstIterator< ImageType > IteratorType;
IteratorType it( filter->GetOutput(), filter->GetOutput()->GetBufferedRegion() );
std::vector<double> values;
while ( !it.IsAtEnd() )
{
values.push_back( it.Get() );
++it;
}
// sort from smallest to largest for best numerical precision
std::sort( values.begin(), values.end() );
double total = std::accumulate( values.begin(), values.end(), 0.0 );
// 1000.0 is the value of the impulse
// compute absolute normalized error
double error = std::fabs( total - 1000.0 )/1000.0;
if ( error > 1e-3)
{
std::cout << "FAILED !" << std::endl;
std::cerr << "Error, Normalization is failing" << std::endl;
std::cerr << "Value of impulse is 1000.0" << std::endl;
std::cerr << "Total value after convolution is " << total << std::endl;
std::cout << "error: " << error << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "PASSED !" << std::endl;
}
} // end of test for normalization
std::cout << "Testing derivatives normalization " << std::endl;
{ // begin of test for normalization among derivatives
filter->SetNormalizeAcrossScale( false );
// Since one side of the Gaussian is monotonic we can
// use the middle-value theorem: The value of the derivative at
// index[0] - 2 must be bounded by the estimation of the derivative
// at index[0] -1 and index[0] -3. In the following we compute an
// estimation of derivatives by partial differences at this two
// positions and use them as bounds for the value of the first order
// derivative returned by the filter.
const double sigmaC = 3.0;
filter->SetSigma( sigmaC );
filter->SetZeroOrder();
filter->Update();
index[0] = ( size[0] - 1 ) / 2; // the middle pixel
const PixelRealType valueA = filter->GetOutput()->GetPixel( index );
index[0] -= 2;
const PixelRealType valueB = filter->GetOutput()->GetPixel( index );
index[0] -= 2;
const PixelRealType valueC = filter->GetOutput()->GetPixel( index );
const PixelRealType derivativeLowerBound = ( valueA - valueB ) / 2.0;
const PixelRealType derivativeUpperBound = ( valueB - valueC ) / 2.0;
// Now let's get the first derivative value computed by the filter
filter->SetFirstOrder();
filter->Update();
index[0] = ( size[0] - 1 ) / 2; // the middle pixel
index[0] -= 2;
const PixelRealType derivativeValue = filter->GetOutput()->GetPixel( index );
std::cout << " first derivative normalization... ";
if( ( derivativeLowerBound > derivativeValue ) ||
( derivativeUpperBound < derivativeValue ) )
{
std::cout << "FAILED !" << std::endl;
std::cerr << "The value of the first derivative at index " << index[0] << std::endl;
std::cerr << "is = " << derivativeValue << std::endl;
std::cerr << "which is outside the bounds = [ " << derivativeLowerBound;
std::cerr << " : " << derivativeUpperBound << " ] " << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "PASSED !" << std::endl;
}
// Now do the similar testing between First Derivative and Second
// derivative.
filter->SetFirstOrder();
filter->Update();
index[0] = ( size[0] - 1 ) / 2; // the middle pixel
const PixelRealType value1A = filter->GetOutput()->GetPixel( index );
index[0] -= 2;
const PixelRealType value1B = filter->GetOutput()->GetPixel( index );
index[0] -= 2;
const PixelRealType value1C = filter->GetOutput()->GetPixel( index );
// NOTE that the second derivative in this region is monotonic but decreasing.
const PixelRealType secondDerivativeLowerBound = ( value1A - value1B ) / 2.0;
const PixelRealType secondDerivativeUpperBound = ( value1B - value1C ) / 2.0;
// Now let's get the second derivative value computed by the filter
filter->SetSecondOrder();
filter->Update();
index[0] = (( size[0] - 1 ) / 2) - 2; // where to sample the second derivative
const PixelRealType secondDerivativeValue = filter->GetOutput()->GetPixel( index );
std::cout << " second derivative normalization... ";
if( ( secondDerivativeLowerBound > secondDerivativeValue ) ||
( secondDerivativeUpperBound < secondDerivativeValue ) )
{
std::cout << "FAILED !" << std::endl;
std::cerr << "The value of the second derivative at index " << index[0] << std::endl;
std::cerr << "is = " << secondDerivativeValue << std::endl;
std::cerr << "which is outside the bounds = [ " << secondDerivativeLowerBound;
std::cerr << " : " << secondDerivativeUpperBound << " ] " << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "PASSED !" << std::endl;
}
} // end of test for normalization among derivatives
// Print out all the values for the zero, first and second order
filter->SetNormalizeAcrossScale( false );
filter->SetSigma( 2.0 );
ImageType::ConstPointer outputImage = filter->GetOutput();
typedef itk::ImageRegionConstIterator< ImageType > IteratorType;
IteratorType it( outputImage, outputImage->GetBufferedRegion() );
std::cout << std::endl << std::endl;
std::cout << "Smoothed image " << std::endl;
filter->SetZeroOrder();
filter->Update();
it.GoToBegin();
while( ! it.IsAtEnd() )
{
std::cout << it.Get() << std::endl;
++it;
}
// Now compute the first derivative
std::cout << std::endl << std::endl;
std::cout << "First Derivative " << std::endl;
filter->SetFirstOrder();
filter->Update();
it.GoToBegin();
while( ! it.IsAtEnd() )
{
std::cout << it.Get() << std::endl;
++it;
}
// Now compute the first derivative
std::cout << std::endl << std::endl;
std::cout << "Second Derivative " << std::endl;
filter->SetSecondOrder();
filter->Update();
it.GoToBegin();
while( ! it.IsAtEnd() )
{
std::cout << it.Get() << std::endl;
++it;
}
filter->SetSigma( 0.0 );
TRY_EXPECT_EXCEPTION( filter->Update() )
}
{
std::cout << "Test InPlace filtering using a 1-D image" << std::endl;
typedef float PixelType;
typedef itk::Image< PixelType, 1 > ImageType;
typedef ImageType::SizeType SizeType;
typedef ImageType::IndexType IndexType;
typedef ImageType::RegionType RegionType;
typedef ImageType::SpacingType SpacingType;
SizeType size;
size[0] = 21;
IndexType start;
start[0] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
SpacingType spacing;
spacing[0] = 1.0;
ImageType::Pointer inputImage = ImageType::New();
inputImage->SetRegions( region );
inputImage->Allocate();
inputImage->SetSpacing( spacing );
inputImage->FillBuffer( itk::NumericTraits< PixelType >::ZeroValue() );
IndexType index;
index[0] = ( size[0] - 1 ) / 2; // the middle pixel
inputImage->SetPixel( index, static_cast< PixelType >( 1.0 ) );
typedef itk::RecursiveGaussianImageFilter< ImageType, ImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( inputImage );
filter->SetSigma( 1 );
// coverage for set/get methods
filter->SetOrder( FilterType::ZeroOrder );
if ( FilterType::ZeroOrder != filter->GetOrder() )
{
std::cerr << "SetOrder/GetOrder failure!" << std::endl;
return EXIT_FAILURE;
}
// Check behavior of InPlace
filter->InPlaceOn();
filter->Update();
ImageType::ConstPointer outputImage = filter->GetOutput();
typedef itk::ImageRegionConstIterator< ImageType > IteratorType;
IteratorType it( outputImage, outputImage->GetBufferedRegion() );
it.GoToBegin();
while( ! it.IsAtEnd() )
{
std::cout << it.Get() << std::endl;
++it;
}
std::cout << "input buffer region: " << inputImage->GetBufferedRegion() << std::endl;
std::cout << "output buffer region: " << outputImage->GetBufferedRegion() << std::endl;
if ( inputImage->GetBufferedRegion().GetNumberOfPixels() != 0 )
{
std::cerr << "Failure for filter to run in-place!" << std::endl;
return EXIT_FAILURE;
}
filter->SetSigma( 0.0 );
TRY_EXPECT_EXCEPTION( filter->Update() )
}
// All objects should be automatically destroyed at this point
return EXIT_SUCCESS;
}
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2008-2017 Free Software Foundation, Inc.
Contributed by Red Hat, originally written by Keith Seitz.
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/>.
Please email any bugs, comments, and/or additions to this file to:
bug-gdb@gnu.org */
#include <stdlib.h>
#include <iostream>
// Forward decls
class base;
class derived;
// A simple template with specializations
template <typename T>
class tclass
{
public:
void do_something () { } // tclass<T>::do_something
};
template <>
void tclass<char>::do_something () { } // tclass<char>::do_something
template <>
void tclass<int>::do_something () { } // tclass<int>::do_something
template<>
void tclass<long>::do_something () { } // tclass<long>::do_something
template<>
void tclass<short>::do_something () { } // tclass<short>::do_something
// A simple template with multiple template parameters
template <class A, class B, class C, class D, class E>
void flubber (void) { // flubber
A a;
B b;
C c;
D d;
E e;
++a;
++b;
++c;
++d;
++e;
}
// Some contrived policies
template <class T>
struct operation_1
{
static void function (void) { } // operation_1<T>::function
};
template <class T>
struct operation_2
{
static void function (void) { } // operation_2<T>::function
};
template <class T>
struct operation_3
{
static void function (void) { } // operation_3<T>::function
};
template <class T>
struct operation_4
{
static void function (void) { } // operation_4<T>::function
};
// A policy-based class w/ and w/o default policy
template <class T, class Policy>
class policy : public Policy
{
public:
policy (T obj) : obj_ (obj) { } // policy<T, Policy>::policy
private:
T obj_;
};
template <class T, class Policy = operation_1<T> >
class policyd : public Policy
{
public:
policyd (T obj) : obj_ (obj) { } // policyd<T, Policy>::policyd
~policyd (void) { } // policyd<T, Policy>::~policyd
private:
T obj_;
};
typedef policy<int, operation_1<void*> > policy1;
typedef policy<int, operation_2<void*> > policy2;
typedef policy<int, operation_3<void*> > policy3;
typedef policy<int, operation_4<void*> > policy4;
typedef policyd<int> policyd1;
typedef policyd<long> policyd2;
typedef policyd<char> policyd3;
typedef policyd<base> policyd4;
typedef policyd<tclass<int> > policyd5;
class fluff { };
static fluff *g_fluff = new fluff ();
class base
{
protected:
int foo_;
public:
base (void) : foo_ (42) { } // base::base(void)
base (int foo) : foo_ (foo) { } // base::base(int)
~base (void) { } // base::~base
// Some overloaded methods
int overload (void) const { return 0; } // base::overload(void) const
int overload (int i) const { return 1; } // base::overload(int) const
int overload (short s) const { return 2; } // base::overload(short) const
int overload (long l) const { return 3; } // base::overload(long) const
int overload (char* a) const { return 4; } // base::overload(char*) const
int overload (base& b) const { return 5; } // base::overload(base&) const
// Operators
int operator+ (base const& o) const { // base::operator+
return foo_ + o.foo_; }
base operator++ (void) { // base::operator++
++foo_; return *this; }
base operator+=(base const& o) { // base::operator+=
foo_ += o.foo_; return *this; }
int operator- (base const& o) const { // base::operator-
return foo_ - o.foo_; }
base operator-- (void) { // base::operator--
--foo_; return *this; }
base operator-= (base const& o) { // base::operator-=
foo_ -= o.foo_; return *this; }
int operator* (base const& o) const { // base::operator*
return foo_ * o.foo_; }
base operator*= (base const& o) { // base::operator*=
foo_ *= o.foo_; return *this; }
int operator/ (base const& o) const { // base::operator/
return foo_ / o.foo_; }
base operator/= (base const& o) { // base::operator/=
foo_ /= o.foo_; return *this; }
int operator% (base const& o) const { // base::operator%
return foo_ % o.foo_; }
base operator%= (base const& o) { // base::operator%=
foo_ %= o.foo_; return *this; }
bool operator< (base const& o) const { // base::operator<
return foo_ < o.foo_; }
bool operator<= (base const& o) const { // base::operator<=
return foo_ <= o.foo_; }
bool operator> (base const& o) const { // base::operator>
return foo_ > o.foo_; }
bool operator>= (base const& o) const { // base::operator>=
return foo_ >= o.foo_; }
bool operator!= (base const& o) const { // base::operator!=
return foo_ != o.foo_; }
bool operator== (base const& o) const { // base::operator==
return foo_ == o.foo_; }
bool operator! (void) const { // base::operator!
return !foo_; }
bool operator&& (base const& o) const { // base::operator&&
return foo_ && o.foo_; }
bool operator|| (base const& o) const { // base::operator||
return foo_ || o.foo_; }
int operator<< (int value) const { // base::operator<<
return foo_ << value; }
base operator<<= (int value) { // base::operator<<=
foo_ <<= value; return *this; }
int operator>> (int value) const { // base::operator>>
return foo_ >> value; }
base operator>>= (int value) { // base::operator>>=
foo_ >>= value; return *this; }
int operator~ (void) const { // base::operator~
return ~foo_; }
int operator& (base const& o) const { // base::operator&
return foo_ & o.foo_; }
base operator&= (base const& o) { // base::operator&=
foo_ &= o.foo_; return *this; }
int operator| (base const& o) const { // base::operator|
return foo_ | o.foo_; }
base operator|= (base const& o) { // base::operator|=
foo_ |= o.foo_; return *this; }
int operator^ (base const& o) const { // base::operator^
return foo_ ^ o.foo_; }
base operator^= (base const& o) { // base::operator^=
foo_ ^= o.foo_; return *this; }
base operator= (base const& o) { // base::operator=
foo_ = o.foo_; return *this; }
void operator() (void) const { // base::operator()
return; }
int operator[] (int idx) const { // base::operator[]
return idx; }
void* operator new (size_t size) throw () { // base::operator new
return malloc (size); }
void operator delete (void* ptr) { // base::operator delete
free (ptr); }
void* operator new[] (size_t size) throw () { // base::operator new[]
return malloc (size); }
void operator delete[] (void* ptr) { // base::operator delete[]
free (ptr); }
base const* operator-> (void) const { // base::opeartor->
return this; }
int operator->* (base const& b) const { // base::operator->*
return foo_ * b.foo_; }
operator char* () const { return const_cast<char*> ("hello"); } // base::operator char*
operator int () const { return 21; } // base::operator int
operator fluff* () const { return new fluff (); } // base::operator fluff*
operator fluff** () const { return &g_fluff; } // base::operator fluff**
};
class base1 : public virtual base
{
public:
base1 (void) : foo_ (21) { } // base1::base1(void)
base1 (int a) : foo_(a) { } // base1::base1(int)
void a_function (void) const { } // base1::a_function
protected:
int foo_;
};
class base2 : public virtual base
{
public:
base2 () : foo_ (3) { } // base2::base2
protected:
void a_function (void) const { } // base2::a_function
int foo_;
};
class derived : public base1, public base2
{
public:
derived(void) : foo_ (4) { } // derived::derived
void a_function (void) const { // derived::a_function
this->base1::a_function ();
this->base2::a_function ();
}
protected:
int foo_;
};
class CV { public:
static const int i;
typedef int t;
void m(t);
void m(t) const;
void m(t) volatile;
void m(t) const volatile;
};
const int CV::i = 42;
#ifdef __GNUC__
# define ATTRIBUTE_USED __attribute__((used))
#else
# define ATTRIBUTE_USED
#endif
ATTRIBUTE_USED void CV::m(CV::t) {}
ATTRIBUTE_USED void CV::m(CV::t) const {}
ATTRIBUTE_USED void CV::m(CV::t) volatile {}
ATTRIBUTE_USED void CV::m(CV::t) const volatile {}
int CV_f (int x)
{
return x + 1;
}
int
test_function (int argc, char* argv[]) // test_function
{ // test_function
derived d;
void (derived::*pfunc) (void) const = &derived::a_function;
(d.*pfunc) ();
base a (1), b (3), c (8);
(void) a.overload ();
(void) a.overload (static_cast<int> (0));
(void) a.overload (static_cast<short> (0));
(void) a.overload (static_cast<long> (0));
(void) a.overload (static_cast<char*> (0));
(void) a.overload (a);
int r;
r = b + c;
++a;
a += b;
r = b - c;
--a;
a -= b;
r = b * c;
a *= b;
r = b / c;
a /= b;
r = b % c;
a %= b;
bool x = (b < c);
x = (b <= c);
x = (b > c);
x = (b >= c);
x = (b != c);
x = (b == c);
x = (!b);
x = (b && c);
x = (b || c);
r = b << 2;
a <<= 1;
r = b >> 2;
a >>= 1;
r = ~b;
r = b & c;
a &= c;
r = b | c;
a |= c;
r = b ^ c;
a ^= c;
a = c;
a ();
int i = a[3];
derived* f = new derived ();
derived* g = new derived[3];
delete f;
delete[] g;
a->overload ();
r = a->*b;
tclass<char> char_tclass;
tclass<int> int_tclass;
tclass<short> short_tclass;
tclass<long> long_tclass;
tclass<base> base_tclass;
char_tclass.do_something ();
int_tclass.do_something ();
short_tclass.do_something ();
long_tclass.do_something ();
base_tclass.do_something ();
flubber<int, int, int, int, int> ();
flubber<int, int, int, int, short> ();
flubber<int, int, int, int, long> ();
flubber<int, int, int, int, char> ();
flubber<int, int, int, short, int> ();
flubber<int, int, int, short, short> ();
flubber<int, int, int, short, long> ();
flubber<int, int, int, short, char> ();
flubber<int, int, int, long, int> ();
flubber<int, int, int, long, short> ();
flubber<int, int, int, long, long> ();
flubber<int, int, int, long, char> ();
flubber<int, int, int, char, int> ();
flubber<int, int, int, char, short> ();
flubber<int, int, int, char, long> ();
flubber<int, int, int, char, char> ();
flubber<int, int, short, int, int> ();
flubber<int, int, short, int, short> ();
flubber<int, int, short, int, long> ();
flubber<int, int, short, int, char> ();
flubber<int, int, short, short, int> ();
flubber<short, int, short, int, short> ();
flubber<long, short, long, short, long> ();
policy1 p1 (1);
p1.function ();
policy2 p2 (2);
p2.function ();
policy3 p3 (3);
p3.function ();
policy4 p4 (4);
p4.function ();
policyd1 pd1 (5);
pd1.function ();
policyd2 pd2 (6);
pd2.function ();
policyd3 pd3 (7);
pd3.function ();
policyd4 pd4 (d);
pd4.function ();
policyd5 pd5 (int_tclass);
pd5.function ();
base1 b1 (3);
r = a;
char* str = a;
fluff* flp = a;
fluff** flpp = a;
CV_f(CV::i);
return 0;
}
int
main (int argc, char* argv[])
{
int i;
/* Call the test function repeatedly, enough times for all our tests
without running forever if something goes wrong. */
for (i = 0; i < 1000; i++)
test_function (argc, argv);
return 0;
}
|
// Copyright Dmitry Anisimov danston@ymail.com (c) 2017.
// README:
/*
Implementation of the modified Catmull-Clark quad-based subdivision in R2
for computing barycentric coordinates.
This class depends on:
1. Face.hpp
2. VertexR2.hpp
3. MeshR2.hpp
*/
#ifndef GBC_QUADSUBDIVISIONR2_HPP
#define GBC_QUADSUBDIVISIONR2_HPP
// STL includes.
#include <iostream>
#include <cassert>
#include <limits>
#include <cmath>
// Local includes.
#include "Face.hpp"
#include "VertexR2.hpp"
#include "MeshR2.hpp"
namespace gbc {
// Quad-based subdivision in R2.
// More details about this concrete implementation can be found in the paper:
// D. Anisimov, C. Deng, and K. Hormann. Subdividing barycentric coordinates.
// Computer Aided Geometric Design, 43:172-185, 2016.
// Please also note that this implementation does not contain all the
// features described in the paper!
class QuadSubdivisionR2 : public MeshR2 {
public:
// Constructor.
QuadSubdivisionR2() { }
// Load quad mesh.
inline void loadMesh(const std::string &path) {
load(path);
}
// Initialize mesh with a polygon and quadrangulate it.
void setFromPolygon(const std::vector<VertexR2> &poly) {
clear();
setQuadrangulation(poly);
setMeshFlags(_f);
initializeHalfedges(_f);
buildHEConnectivity();
setInitialBarycentricCoordinates();
}
// Subdivision.
// Vertex adjustment near the polygon's corners.
// This version of the function preprocess() is not optimized
// and may have slow performance in some cases!
void preprocess(const bool) {
assert(isQuadMesh());
// Save mesh vertices and faces before the corner modification
// in order to sample linearly barycentric coordinates later.
std::vector<VertexR2> tmpv = _v;
std::vector<Face> tmpf = _f;
// Modify 1-ring neighbourhood around each concave corner.
modifyCorners(tmpv, tmpf);
}
// Do one subdivision step with the modified Catmull-Clark subdivision scheme.
void subdivideMesh(const bool) {
assert(isQuadMesh());
///////////////////////////////////
// Do ODD step - add new points. //
///////////////////////////////////
// Initiate some data.
const size_t numV = numVertices();
const size_t numE = numEdges();
const size_t numHE = numHalfedges();
const size_t numF = numHE / 4;
_v.resize(numV + numE + numF);
std::vector<int> neighs(6);
size_t idxV = numV;
// Loop over all halfedges.
for (size_t k = 0; k < numHE; ++k) {
// Consider only the "big brother" of each halfedge-pair.
const int k_ = _he[k].neigh;
if ((int) k > k_) {
// Local configuration:
/*
w2---w1---w5
|| || ||
|| || ||
|| ^|| ||
|| [] ||
|| *|| ||
|| || ||
|| || ||
w3---w0---w4
*/
// The current halfedge and its direction are indicated by "*" and "^".
// Create an odd vertex at the position "[]".
// NOTE: the right quad, w4, and w5 do not exist if "*" is at the boundary.
neighs[0] = _he[_he[k].prev].dest;
neighs[1] = _he[k].dest;
neighs[2] = _he[_he[k].next].dest;
neighs[3] = _he[_he[_he[k].next].next].dest;
// Mask for interior edge vertices.
if (k_ >= 0) {
neighs[4] = _he[_he[k_].next].dest;
neighs[5] = _he[_he[_he[k_].prev].prev].dest;
createIntEdgeVertex(neighs, _v[idxV]);
}
// Mask for boundary edge vertices.
else createBndEdgeVertex(neighs, _v[idxV]);
idxV++;
} // if a halfedge is the "big brother"
} // for all halfedges
// Add new face vertices.
int base = 0, c = 0, idxE = 0;
for (size_t k = 0; k < numHE; ++k) {
if (k % 4 == 0) {
base = 0;
if (_he[0].next == 1) idxE = _he[k].prev;
else idxE = _he[c].prev;
}
neighs[base++] = _he[idxE].dest;
idxE = _he[idxE].next;
if (base == 4) {
createFaceVertex(neighs, _v[idxV++]);
c++;
}
}
// Update halfedge connectivity.
updateHEConnectivity(numV);
/////////////////////////////////////
// Do EVEN step - move old points. //
/////////////////////////////////////
for (size_t i = 0; i < numV; ++i) {
// Mask for even interior vertices.
if (_v[i].type == INTERIOR) {
size_t nSize = 0;
int first, curr, prev, next;
// Find neighbours of the vertex.
curr = first = _v[i].out;
assert(_v[i].val > 0);
neighs.resize(2 * (size_t) _v[i].val);
do {
neighs[nSize++] = _he[curr].dest;
next = _he[curr].next;
neighs[nSize++] = _he[next].dest;
prev = _he[curr].prev;
curr = _he[prev].neigh;
} while((curr >= 0) && (curr != first));
// Add one more neighbour for boundary vertices.
if(curr < 0) {
curr = _he[prev].prev;
neighs[nSize] = _he[curr].dest;
}
moveEvenIntVertex(neighs, _v[i]);
}
// Mask for even boundary vertices.
else {
getRing(i, neighs);
moveEvenBndVertex(neighs, _v[i]);
}
}
}
private:
// Quadrangulate the polygon.
void setQuadrangulation(const std::vector<VertexR2>&) {
// Not yet implemented.
}
// Update halfedge connectivity in the mesh after each subdivision step.
void updateHEConnectivity(const size_t numV) {
const size_t numHE = numHalfedges();
_he.resize(4 * numHE);
// Update connectivity for all new edges created on top of the old edges.
size_t idxV = numV, count = 0;
for (size_t k = 0; k < numHE; ++k) {
const int k_ = _he[k].neigh;
// Consider only the "big brother" of each halfedge-pair.
if ((int) k > k_) {
if (k_ >= 0) { // interior edge
int oldV = _he[k].dest;
const int oldE = _he[k].neigh;
_he[k].dest = (int) idxV;
_he[count + numHE].dest = oldV;
oldV = _he[oldE].dest;
_he[oldE].dest = (int) idxV;
_he[count + numHE + 1].dest = oldV;
_he[count + numHE + 1].neigh = _he[oldE].neigh;
_he[count + numHE].neigh = _he[k].neigh;
_he[k].neigh = count + numHE + 1;
_he[oldE].neigh = count + numHE;
int next = _he[k].next;
_he[count + numHE].next = next;
_he[next].prev = count + numHE;
next = _he[oldE].next;
_he[count + numHE + 1].next = next;
_he[next].prev = count + numHE + 1;
_v[idxV].out = count + numHE;
count++;
} else { // boundary edge
const int oldV = _he[k].dest;
_he[k].dest = (int) idxV;
_he[k].neigh = -1;
_he[count + numHE].dest = oldV;
_he[count + numHE].neigh = -1;
const int next = _he[k].next;
_he[count + numHE].next = next;
_he[next].prev = count + numHE;
_v[idxV].out = count + numHE;
}
idxV++; count++;
} // if a halfedge is the "big brother"
} // for all halfedges
// Update connectivity for all new edges created on top of the old faces.
const int next = _he[0].next;
int base = 0, c = 0, idxE = 0;
for (size_t k = 0; k < numHE; ++k) {
if (k % 4 == 0) base = 0; base++;
if (base == 4) {
if (next == 1) idxE = k - 3;
else idxE = c;
{
int offset_1 = 0, offset_2 = 7;
const int init = int(count + numHE);
_v[idxV].out = init + 1;
for (size_t i = 0; i < 4; ++i) {
const int ind = init + offset_1;
const int neigh = init + offset_1 + 1;
_he[ind].neigh = neigh;
_he[neigh].neigh = ind;
_he[ind].dest = (int) idxV;
_he[neigh].dest = _he[idxE].dest;
_he[ind].prev = idxE;
_he[ind].next = init + offset_2 % 8;
_he[init + offset_2 % 8].prev = ind;
const int tmp = _he[idxE].next;
_he[idxE].next = ind;
_he[neigh].next = _he[tmp].prev;
_he[_he[tmp].prev].prev = neigh;
idxE = tmp;
offset_1 += 2;
offset_2 += 2;
}
}
count += 8;
idxV++;
c++;
}
}
}
// Create a face vertex.
void createFaceVertex(const std::vector<int> &neighs, VertexR2 &newV) const {
assert(neighs.size() == 6);
newV = _v[neighs[0]];
for (size_t i = 1; i < 4; ++i)
newV += _v[neighs[i]];
newV *= 0.25;
// Update its flags.
newV.val = 4;
newV.out = -1;
newV.alpha = -1.0;
newV.type = INTERIOR;
}
// Create an interior edge vertex.
void createIntEdgeVertex(const std::vector<int> &neighs, VertexR2 &newV) const {
assert(neighs.size() == 6);
double c[6] = { 0.375, 0.375, 0.0625, 0.0625, 0.0625, 0.0625 };
// Zorin modification.
if (_v[neighs[0]].type == CONVEX || _v[neighs[0]].type == CONCAVE) {
const int k = _v[neighs[0]].val - 1;
const double alpha = _v[neighs[0]].alpha;
const double theta = (2.0 * M_PI - alpha) / k;
double gamma = 0.375 - 0.25 * cos(theta);
// If both vertices of an edge are convex or concave corners,
// we return to the original weights 3/8.
if (_v[neighs[1]].type == CONVEX || _v[neighs[1]].type == CONCAVE) gamma = 0.375;
// Both weights must behave as 1/2.
c[0] = 0.75 - gamma;
c[1] = gamma;
}
// Zorin modification.
if(_v[neighs[1]].type == CONVEX || _v[neighs[1]].type == CONCAVE) {
const int k = _v[neighs[1]].val - 1;
const double alpha = _v[neighs[1]].alpha;
const double theta = (2.0 * M_PI - alpha) / k;
double gamma = 0.375 - 0.25 * cos(theta);
// If both vertices of an edge are convex or concave corners,
// we return to the original weights 3/8.
if (_v[neighs[0]].type == CONVEX || _v[neighs[0]].type == CONCAVE) gamma = 0.375;
// Both weights must behave as 1/2.
c[1] = 0.75 - gamma;
c[0] = gamma;
}
newV = _v[neighs[0]];
newV *= c[0];
newV += c[1] * _v[neighs[1]];
for (size_t i = 2; i < 6; ++i) newV += c[i] * _v[neighs[i]];
// Update its flags.
newV.val = 4;
newV.out = -1;
newV.alpha = -1.0;
newV.type = INTERIOR;
}
// Create a boundary edge vertex.
void createBndEdgeVertex(const std::vector<int> &neighs, VertexR2 &newV) const {
assert(neighs.size() == 6);
newV = _v[neighs[0]];
newV += _v[neighs[1]];
newV *= 0.5;
// Update its flags.
newV.val = 3;
newV.out = -1;
newV.alpha = -1.0;
newV.type = FLAT;
}
// Move an interior even vertex.
void moveEvenIntVertex(const std::vector<int> &neighs, VertexR2 ¢re) const {
const size_t n = neighs.size();
assert(n > 0);
assert(centre.alpha == -1.0);
assert(centre.type == INTERIOR);
// Update weights.
const int k = centre.val;
const int ks = k * k;
const double alpha = - 1.0 / ks;
const double beta = 4.0 / ks;
const double gamma = 1.0 - k * alpha - k * beta;
centre *= gamma;
for (size_t i = 0; i < n; ++i) {
if (i % 2 == 0) {
centre += beta * _v[neighs[i]];
}
else {
centre += alpha * _v[neighs[i]];
}
}
}
// Move a boundary even vertex.
void moveEvenBndVertex(const std::vector<int> &neighs, VertexR2 ¢re) const {
assert(centre.type != INTERIOR);
if (centre.type == FLAT) { // FLAT vertex
assert(centre.alpha == -1.0);
assert(neighs.size() > 1);
const int n = centre.val;
assert(n > 1);
assert((int) neighs.size() == n);
centre *= 2.0;
centre += _v[neighs[0]];
centre += _v[neighs[n - 1]];
centre *= 0.25;
}
// CONVEX AND CONCAVE vertices are interpolated!
}
// Modify corners of the mesh.
void modifyCorners(std::vector<VertexR2> &tmpv, std::vector<Face> &tmpf) {
const size_t numV = numVertices();
std::vector<int> neighs;
assert(numV != 0);
// Go through all the mesh vertices.
for (size_t i = 0; i < numV; ++i) {
if (_v[i].type == CONCAVE) { // Concave vertex
// Find 1-ring neighbourhood of the corner vertex.
getFullRing(i, neighs);
const size_t nSize = neighs.size();
for (size_t j = 1; j < nSize - 1; ++j)
if (_v[neighs[j]].type != INTERIOR)
std::cerr << "\nERROR: Adjusted vertex is on the boundary!\n" << std::endl;
// Find the internal angle for the corner and split it into equal parts.
const double intAngle = 2.0 * M_PI - _v[i].alpha;
const double angle = intAngle / (nSize - 1);
// Find the closest neighbour to the corner.
double minLen = std::numeric_limits<double>::max();
for (size_t j = 0; j < nSize; ++j) {
const double len = (_v[i] - _v[neighs[j]]).length();
minLen = std::min(minLen, len);
}
// Rotate the first neighbour of the corner vertex by the angle 'angle'
// to get equally-distant and distributed mesh vertices around this corner.
double tmpAngle = 0.0;
VertexR2 &firstV = _v[neighs[0]];
VertexR2 tmpV;
for (size_t j = 0; j < nSize; ++j) {
if (j % 2 == 0) {
tmpAngle = j * angle;
tmpV = firstV.translated(-_v[i]);
tmpV = tmpV.rotated(tmpAngle);
const double len = tmpV.length();
const double scaleFactor = minLen / len;
tmpV = tmpV.scaled(scaleFactor, scaleFactor);
tmpV = tmpV.translated(_v[i]);
_v[neighs[j]].x() = tmpV.x();
_v[neighs[j]].y() = tmpV.y();
}
}
for (size_t j = 0; j < nSize; ++j) {
if (j % 2 != 0) {
_v[neighs[j]].x() = _v[neighs[j - 1]].x() + _v[neighs[j + 1]].x() - _v[i].x();
_v[neighs[j]].y() = _v[neighs[j - 1]].y() + _v[neighs[j + 1]].y() - _v[i].y();
}
}
// Scale mesh vertices around the corner to avoid interior fold-overs.
// scaleVertices(i, neighs); // to be added later
// Fix barycentric coordinates for all the neighbours of the corner vertex.
fixCoordinates(neighs, tmpv, tmpf);
}
}
}
// Get full ring around a vertex.
void getFullRing(const size_t vInd, std::vector<int> &neighs) const {
int first, prev, curr, next;
// Find neighbours of the vertex.
curr = first = _v[vInd].out;
assert(_v[vInd].val > 0);
int nSize = _v[vInd].val * 2;
if (_v[vInd].type != INTERIOR) nSize--;
assert(nSize >= 0);
neighs.resize(nSize);
size_t count = 0;
do {
neighs[count++] = _he[curr].dest;
next = _he[curr].next;
neighs[count++] = _he[next].dest;
prev = _he[curr].prev;
curr = _he[prev].neigh;
} while((curr >= 0) && (curr != first));
// Add one more neighbour for boundary vertices.
if (curr < 0) {
curr = _he[prev].prev;
neighs[count] = _he[curr].dest;
}
}
// Fix barycentric coordinates around the corner.
void fixCoordinates(const std::vector<int> &neighs, const std::vector<VertexR2> &tmpv, const std::vector<Face> &tmpf) {
const size_t nSize = neighs.size();
const size_t numF = tmpf.size();
const size_t numC = _v[0].b().size();
std::vector<VertexR2> quad(4);
// Go through all the neighbours.
for (size_t i = 0; i < nSize; ++i) {
// Go through all the faces of the mesh.
size_t count = 0;
for (size_t j = 0; j < numF; ++j) {
// Compute mean value coordinates.
std::vector<double> lambda;
quad[0] = tmpv[tmpf[j].v[0]];
quad[1] = tmpv[tmpf[j].v[1]];
quad[2] = tmpv[tmpf[j].v[2]];
quad[3] = tmpv[tmpf[j].v[3]];
MeanValueR2 mvc(quad);
mvc.compute(_v[neighs[i]], lambda);
// If we found a face to which current neighbour belongs,
// linearly sample barycentric cordinates from the vertices of this face.
if (lambda[0] >= 0.0 && lambda[1] >= 0.0 && lambda[2] >= 0.0 && lambda[3] >= 0.0) {
for (size_t k = 0; k < numC; ++k) {
_v[neighs[i]].b()[k] = std::fabs(lambda[0]) * tmpv[tmpf[j].v[0]].b()[k] +
std::fabs(lambda[1]) * tmpv[tmpf[j].v[1]].b()[k] +
std::fabs(lambda[2]) * tmpv[tmpf[j].v[2]].b()[k] +
std::fabs(lambda[3]) * tmpv[tmpf[j].v[3]].b()[k];
} break;
} else ++count;
}
// If we did not find at least one face to which current neighbour belongs, return an error.
if (count == numF && numC != 0)
std::cerr << "ERROR: No appropriate face was found! fixCoordinates() function failed!\n" << std::endl;
}
}
};
} // namespace gbc
#endif // GBC_QUADSUBDIVISIONR2_HPP
|
#include <cstddef>
#include <stdexcept>
#include "join.hpp"
#include "set_operations.hpp"
#define SHRINK_MISSED_VLEN 256
namespace frovedis {
std::vector<size_t> shrink_missed(std::vector<size_t>& to_shrink,
std::vector<size_t>& missed) {
size_t missedsize = missed.size();
if(missedsize == 0) return to_shrink;
size_t to_shrinksize = to_shrink.size();
if(to_shrinksize > missedsize * SHRINK_MISSED_VLEN) {
size_t retsize = to_shrinksize - missedsize;
std::vector<size_t> ret(retsize);
size_t* to_shrinkp = &to_shrink[0];
size_t* missedp = &missed[0];
size_t* retp = &ret[0];
size_t ret_idx = 0;
size_t src_idx = 0;
size_t start = 0;
size_t end;
for(size_t i = 0; i < missedsize; i++) {
end = missedp[i];
size_t len = end - start;
for(size_t j = 0; j < len; j++) {
retp[ret_idx + j] = to_shrinkp[src_idx + j];
}
ret_idx += end - start;
src_idx += end - start + 1;
start = end + 1;
}
end = to_shrinksize;
size_t len = end - start;
for(size_t j = 0; j < len; j++) {
retp[ret_idx + j] = to_shrinkp[src_idx + j];
}
return ret;
} else {
std::vector<size_t> tmp(to_shrinksize);
size_t* tmpp = &tmp[0];
for(size_t i = 0; i < to_shrinksize; i++) {
tmpp[i] = i;
}
auto to_shrink_idx = set_difference(tmp, missed);
size_t* to_shrink_idxp = &to_shrink_idx[0];
size_t to_shrink_idx_size = to_shrink_idx.size();
std::vector<size_t> ret(to_shrink_idx_size);
size_t* retp = &ret[0];
size_t* to_shrinkp = &to_shrink[0];
for(size_t i = 0; i < to_shrink_idx_size; i++) {
retp[i] = to_shrinkp[to_shrink_idxp[i]];
}
return ret;
}
}
}
|
#include "atanhnode.h"
ATanHNode::ATanHNode()
{
this->setTitle("ATanh");
this->setHeight(120);
this->setWidth(140);
this->setPanelColor(QColor(195,20,50));
this->setPanelGradColor(QColor(36,11,54));
this->functionName="math.atanh";
Port p1;
p1.Parent=this;
p1.Position=QPoint(20,75);
p1.PortColor=panelColor();
this->inputPort.push_back(p1);
Port p3;
p3.Parent=this;
p3.Position=QPoint(125,75);
p3.PortColor=panelColor();
p3.Type=PortType::OutPut;
this->outputPort.push_back(p3);
Label l1;
l1.Text="Value";
l1.Pos=QPoint(40,85);
this->labelList.push_back(l1);
}
|
// Copyright (c) 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "quiche/quic/core/qpack/qpack_encoder.h"
#include <algorithm>
#include <utility>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_index_conversions.h"
#include "quiche/quic/core/qpack/qpack_instruction_encoder.h"
#include "quiche/quic/core/qpack/qpack_required_insert_count.h"
#include "quiche/quic/core/qpack/value_splitting_header_list.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
namespace {
// Fraction to calculate draining index. The oldest |kDrainingFraction| entries
// will not be referenced in header blocks. A new entry (duplicate or literal
// with name reference) will be added to the dynamic table instead. This allows
// the number of references to the draining entry to go to zero faster, so that
// it can be evicted. See
// https://quicwg.org/base-drafts/draft-ietf-quic-qpack.html#avoiding-blocked-insertions.
// TODO(bnc): Fine tune.
const float kDrainingFraction = 0.25;
} // anonymous namespace
QpackEncoder::QpackEncoder(
DecoderStreamErrorDelegate* decoder_stream_error_delegate)
: decoder_stream_error_delegate_(decoder_stream_error_delegate),
decoder_stream_receiver_(this),
maximum_blocked_streams_(0),
header_list_count_(0) {
QUICHE_DCHECK(decoder_stream_error_delegate_);
}
QpackEncoder::~QpackEncoder() {}
// static
QpackEncoder::Representation QpackEncoder::EncodeIndexedHeaderField(
bool is_static, uint64_t index,
QpackBlockingManager::IndexSet* referred_indices) {
// Add |index| to |*referred_indices| only if entry is in the dynamic table.
if (!is_static) {
referred_indices->insert(index);
}
return Representation::IndexedHeaderField(is_static, index);
}
// static
QpackEncoder::Representation
QpackEncoder::EncodeLiteralHeaderFieldWithNameReference(
bool is_static, uint64_t index, absl::string_view value,
QpackBlockingManager::IndexSet* referred_indices) {
// Add |index| to |*referred_indices| only if entry is in the dynamic table.
if (!is_static) {
referred_indices->insert(index);
}
return Representation::LiteralHeaderFieldNameReference(is_static, index,
value);
}
// static
QpackEncoder::Representation QpackEncoder::EncodeLiteralHeaderField(
absl::string_view name, absl::string_view value) {
return Representation::LiteralHeaderField(name, value);
}
QpackEncoder::Representations QpackEncoder::FirstPassEncode(
QuicStreamId stream_id, const spdy::Http2HeaderBlock& header_list,
QpackBlockingManager::IndexSet* referred_indices,
QuicByteCount* encoder_stream_sent_byte_count) {
// If previous instructions are buffered in |encoder_stream_sender_|,
// do not count them towards the current header block.
const QuicByteCount initial_encoder_stream_buffered_byte_count =
encoder_stream_sender_.BufferedByteCount();
const bool can_write_to_encoder_stream = encoder_stream_sender_.CanWrite();
Representations representations;
representations.reserve(header_list.size());
// The index of the oldest entry that must not be evicted.
uint64_t smallest_blocking_index =
blocking_manager_.smallest_blocking_index();
// Entries with index larger than or equal to |known_received_count| are
// blocking.
const uint64_t known_received_count =
blocking_manager_.known_received_count();
// Only entries with index greater than or equal to |draining_index| are
// allowed to be referenced.
const uint64_t draining_index =
header_table_.draining_index(kDrainingFraction);
// Blocking references are allowed if the number of blocked streams is less
// than the limit.
const bool blocking_allowed = blocking_manager_.blocking_allowed_on_stream(
stream_id, maximum_blocked_streams_);
// Track events for histograms.
bool dynamic_table_insertion_blocked = false;
bool blocked_stream_limit_exhausted = false;
for (const auto& header : ValueSplittingHeaderList(&header_list)) {
// These strings are owned by |header_list|.
absl::string_view name = header.first;
absl::string_view value = header.second;
bool is_static;
uint64_t index;
auto match_type =
header_table_.FindHeaderField(name, value, &is_static, &index);
switch (match_type) {
case QpackEncoderHeaderTable::MatchType::kNameAndValue:
if (is_static) {
// Refer to entry directly.
representations.push_back(
EncodeIndexedHeaderField(is_static, index, referred_indices));
break;
}
if (index >= draining_index) {
// If allowed, refer to entry directly.
if (!blocking_allowed && index >= known_received_count) {
blocked_stream_limit_exhausted = true;
} else {
representations.push_back(
EncodeIndexedHeaderField(is_static, index, referred_indices));
smallest_blocking_index = std::min(smallest_blocking_index, index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
} else {
// Entry is draining, needs to be duplicated.
if (!blocking_allowed) {
blocked_stream_limit_exhausted = true;
} else if (QpackEntry::Size(name, value) >
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
std::min(smallest_blocking_index, index))) {
dynamic_table_insertion_blocked = true;
} else {
if (can_write_to_encoder_stream) {
// If allowed, duplicate entry and refer to it.
encoder_stream_sender_.SendDuplicate(
QpackAbsoluteIndexToEncoderStreamRelativeIndex(
index, header_table_.inserted_entry_count()));
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
is_static, new_index, referred_indices));
smallest_blocking_index =
std::min(smallest_blocking_index, index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
}
}
// Encode entry as string literals.
// TODO(b/112770235): Use already acknowledged entry with lower index if
// exists.
// TODO(b/112770235): Use static entry name with literal value if
// dynamic entry exists but cannot be used.
representations.push_back(EncodeLiteralHeaderField(name, value));
break;
case QpackEncoderHeaderTable::MatchType::kName:
if (is_static) {
if (blocking_allowed &&
QpackEntry::Size(name, value) <=
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
smallest_blocking_index)) {
// If allowed, insert entry into dynamic table and refer to it.
if (can_write_to_encoder_stream) {
encoder_stream_sender_.SendInsertWithNameReference(is_static,
index, value);
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
/* is_static = */ false, new_index, referred_indices));
smallest_blocking_index =
std::min<uint64_t>(smallest_blocking_index, new_index);
break;
}
}
// Emit literal field with name reference.
representations.push_back(EncodeLiteralHeaderFieldWithNameReference(
is_static, index, value, referred_indices));
break;
}
if (!blocking_allowed) {
blocked_stream_limit_exhausted = true;
} else if (QpackEntry::Size(name, value) >
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
std::min(smallest_blocking_index, index))) {
dynamic_table_insertion_blocked = true;
} else {
// If allowed, insert entry with name reference and refer to it.
if (can_write_to_encoder_stream) {
encoder_stream_sender_.SendInsertWithNameReference(
is_static,
QpackAbsoluteIndexToEncoderStreamRelativeIndex(
index, header_table_.inserted_entry_count()),
value);
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
is_static, new_index, referred_indices));
smallest_blocking_index = std::min(smallest_blocking_index, index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
}
if ((blocking_allowed || index < known_received_count) &&
index >= draining_index) {
// If allowed, refer to entry name directly, with literal value.
representations.push_back(EncodeLiteralHeaderFieldWithNameReference(
is_static, index, value, referred_indices));
smallest_blocking_index = std::min(smallest_blocking_index, index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
// Encode entry as string literals.
// TODO(b/112770235): Use already acknowledged entry with lower index if
// exists.
// TODO(b/112770235): Use static entry name with literal value if
// dynamic entry exists but cannot be used.
representations.push_back(EncodeLiteralHeaderField(name, value));
break;
case QpackEncoderHeaderTable::MatchType::kNoMatch:
// If allowed, insert entry and refer to it.
if (!blocking_allowed) {
blocked_stream_limit_exhausted = true;
} else if (QpackEntry::Size(name, value) >
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
smallest_blocking_index)) {
dynamic_table_insertion_blocked = true;
} else {
if (can_write_to_encoder_stream) {
encoder_stream_sender_.SendInsertWithoutNameReference(name, value);
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
/* is_static = */ false, new_index, referred_indices));
smallest_blocking_index =
std::min<uint64_t>(smallest_blocking_index, new_index);
break;
}
}
// Encode entry as string literals.
// TODO(b/112770235): Consider also adding to dynamic table to improve
// compression ratio for subsequent header blocks with peers that do not
// allow any blocked streams.
representations.push_back(EncodeLiteralHeaderField(name, value));
break;
}
}
const QuicByteCount encoder_stream_buffered_byte_count =
encoder_stream_sender_.BufferedByteCount();
QUICHE_DCHECK_GE(encoder_stream_buffered_byte_count,
initial_encoder_stream_buffered_byte_count);
if (encoder_stream_sent_byte_count) {
*encoder_stream_sent_byte_count =
encoder_stream_buffered_byte_count -
initial_encoder_stream_buffered_byte_count;
}
if (can_write_to_encoder_stream) {
encoder_stream_sender_.Flush();
} else {
QUICHE_DCHECK_EQ(encoder_stream_buffered_byte_count,
initial_encoder_stream_buffered_byte_count);
}
++header_list_count_;
if (dynamic_table_insertion_blocked) {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenInsertionBlocked",
header_list_count_, /* min = */ 1, /* max = */ 1000,
/* bucket_count = */ 50,
"The ordinality of a header list within a connection during the "
"encoding of which at least one dynamic table insertion was "
"blocked.");
} else {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenInsertionNotBlocked",
header_list_count_, /* min = */ 1, /* max = */ 1000,
/* bucket_count = */ 50,
"The ordinality of a header list within a connection during the "
"encoding of which no dynamic table insertion was blocked.");
}
if (blocked_stream_limit_exhausted) {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenBlockedStreamLimited",
header_list_count_, /* min = */ 1, /* max = */ 1000,
/* bucket_count = */ 50,
"The ordinality of a header list within a connection during the "
"encoding of which unacknowledged dynamic table entries could not be "
"referenced due to the limit on the number of blocked streams.");
} else {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenNotBlockedStreamLimited",
header_list_count_, /* min = */ 1, /* max = */ 1000,
/* bucket_count = */ 50,
"The ordinality of a header list within a connection during the "
"encoding of which the limit on the number of blocked streams did "
"not "
"prevent referencing unacknowledged dynamic table entries.");
}
return representations;
}
std::string QpackEncoder::SecondPassEncode(
QpackEncoder::Representations representations,
uint64_t required_insert_count) const {
QpackInstructionEncoder instruction_encoder;
std::string encoded_headers;
// Header block prefix.
instruction_encoder.Encode(
Representation::Prefix(QpackEncodeRequiredInsertCount(
required_insert_count, header_table_.max_entries())),
&encoded_headers);
const uint64_t base = required_insert_count;
for (auto& representation : representations) {
// Dynamic table references must be transformed from absolute to relative
// indices.
if ((representation.instruction() == QpackIndexedHeaderFieldInstruction() ||
representation.instruction() ==
QpackLiteralHeaderFieldNameReferenceInstruction()) &&
!representation.s_bit()) {
representation.set_varint(QpackAbsoluteIndexToRequestStreamRelativeIndex(
representation.varint(), base));
}
instruction_encoder.Encode(representation, &encoded_headers);
}
return encoded_headers;
}
std::string QpackEncoder::EncodeHeaderList(
QuicStreamId stream_id, const spdy::Http2HeaderBlock& header_list,
QuicByteCount* encoder_stream_sent_byte_count) {
// Keep track of all dynamic table indices that this header block refers to so
// that it can be passed to QpackBlockingManager.
QpackBlockingManager::IndexSet referred_indices;
// First pass: encode into |representations|.
Representations representations =
FirstPassEncode(stream_id, header_list, &referred_indices,
encoder_stream_sent_byte_count);
const uint64_t required_insert_count =
referred_indices.empty()
? 0
: QpackBlockingManager::RequiredInsertCount(referred_indices);
if (!referred_indices.empty()) {
blocking_manager_.OnHeaderBlockSent(stream_id, std::move(referred_indices));
}
// Second pass.
return SecondPassEncode(std::move(representations), required_insert_count);
}
bool QpackEncoder::SetMaximumDynamicTableCapacity(
uint64_t maximum_dynamic_table_capacity) {
return header_table_.SetMaximumDynamicTableCapacity(
maximum_dynamic_table_capacity);
}
void QpackEncoder::SetDynamicTableCapacity(uint64_t dynamic_table_capacity) {
encoder_stream_sender_.SendSetDynamicTableCapacity(dynamic_table_capacity);
// Do not flush encoder stream. This write can safely be delayed until more
// instructions are written.
bool success = header_table_.SetDynamicTableCapacity(dynamic_table_capacity);
QUICHE_DCHECK(success);
}
bool QpackEncoder::SetMaximumBlockedStreams(uint64_t maximum_blocked_streams) {
if (maximum_blocked_streams < maximum_blocked_streams_) {
return false;
}
maximum_blocked_streams_ = maximum_blocked_streams;
return true;
}
void QpackEncoder::OnInsertCountIncrement(uint64_t increment) {
if (increment == 0) {
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT,
"Invalid increment value 0.");
return;
}
if (!blocking_manager_.OnInsertCountIncrement(increment)) {
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW,
"Insert Count Increment instruction causes overflow.");
}
if (blocking_manager_.known_received_count() >
header_table_.inserted_entry_count()) {
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT,
absl::StrCat("Increment value ", increment,
" raises known received count to ",
blocking_manager_.known_received_count(),
" exceeding inserted entry count ",
header_table_.inserted_entry_count()));
}
}
void QpackEncoder::OnHeaderAcknowledgement(QuicStreamId stream_id) {
if (!blocking_manager_.OnHeaderAcknowledgement(stream_id)) {
OnErrorDetected(
QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT,
absl::StrCat("Header Acknowledgement received for stream ", stream_id,
" with no outstanding header blocks."));
}
}
void QpackEncoder::OnStreamCancellation(QuicStreamId stream_id) {
blocking_manager_.OnStreamCancellation(stream_id);
}
void QpackEncoder::OnErrorDetected(QuicErrorCode error_code,
absl::string_view error_message) {
decoder_stream_error_delegate_->OnDecoderStreamError(error_code,
error_message);
}
} // namespace quic
|
#include "../../../chain/include/eosio/chain/wasm_eosio_constraints.hpp"
#include "Inline/BasicTypes.h"
#include "Inline/Serialization.h"
#include "Inline/UTF8.h"
#include "WASM.h"
#include "IR/Module.h"
#include "IR/Operators.h"
#include "IR/Types.h"
#include "IR/Validate.h"
using namespace Serialization;
static void throwIfNotValidUTF8(const std::string& string)
{
const U8* endChar = (const U8*)string.data() + string.size();
if(UTF8::validateString((const U8*)string.data(),endChar) != endChar)
{
throw FatalSerializationException("invalid UTF-8 encoding");
}
}
// These serialization functions need to be declared in the IR namespace for the array serializer in the Serialization namespace to find them.
namespace IR
{
template<typename Stream>
void serialize(Stream& stream,ValueType& type)
{
I8 encodedValueType = -(I8)type;
serializeVarInt7(stream,encodedValueType);
if(Stream::isInput) { type = (ValueType)-encodedValueType; }
}
FORCEINLINE static void serialize(InputStream& stream,ResultType& resultType)
{
Uptr arity;
serializeVarUInt1(stream,arity);
if(arity == 0) { resultType = ResultType::none; }
else
{
I8 encodedValueType = 0;
serializeVarInt7(stream,encodedValueType);
resultType = (ResultType)-encodedValueType;
}
}
static void serialize(OutputStream& stream,ResultType& returnType)
{
Uptr arity = returnType == ResultType::none ? 0 : 1;
serializeVarUInt1(stream,arity);
if(arity)
{
I8 encodedValueType = -(I8)returnType;
serializeVarInt7(stream,encodedValueType);
}
}
template<typename Stream>
void serialize(Stream& stream,SizeConstraints& sizeConstraints,bool hasMax)
{
serializeVarUInt32(stream,sizeConstraints.min);
if(hasMax) { serializeVarUInt32(stream,sizeConstraints.max); }
else if(Stream::isInput) { sizeConstraints.max = UINT64_MAX; }
}
template<typename Stream>
void serialize(Stream& stream,TableElementType& elementType)
{
serializeNativeValue(stream,elementType);
}
template<typename Stream>
void serialize(Stream& stream,TableType& tableType)
{
serialize(stream,tableType.elementType);
Uptr flags = 0;
if(!Stream::isInput && tableType.size.max != UINT64_MAX) { flags |= 0x01; }
#if ENABLE_THREADING_PROTOTYPE
if(!Stream::isInput && tableType.isShared) { flags |= 0x10; }
serializeVarUInt32(stream,flags);
if(Stream::isInput) { tableType.isShared = (flags & 0x10) != 0; }
#else
serializeVarUInt32(stream,flags);
#endif
serialize(stream,tableType.size,flags & 0x01);
}
template<typename Stream>
void serialize(Stream& stream,MemoryType& memoryType)
{
Uptr flags = 0;
if(!Stream::isInput && memoryType.size.max != UINT64_MAX) { flags |= 0x01; }
#if ENABLE_THREADING_PROTOTYPE
if(!Stream::isInput && memoryType.isShared) { flags |= 0x10; }
serializeVarUInt32(stream,flags);
if(Stream::isInput) { memoryType.isShared = (flags & 0x10) != 0; }
#else
serializeVarUInt32(stream,flags);
#endif
serialize(stream,memoryType.size,flags & 0x01);
}
template<typename Stream>
void serialize(Stream& stream,GlobalType& globalType)
{
serialize(stream,globalType.valueType);
U8 isMutable = globalType.isMutable ? 1 : 0;
serializeVarUInt1(stream,isMutable);
if(Stream::isInput) { globalType.isMutable = isMutable != 0; }
}
template<typename Stream>
void serialize(Stream& stream,ObjectKind& kind)
{
serializeNativeValue(stream,*(U8*)&kind);
}
template<typename Stream>
void serialize(Stream& stream,Export& e)
{
serialize(stream,e.name);
throwIfNotValidUTF8(e.name);
serialize(stream,e.kind);
serializeVarUInt32(stream,e.index);
}
template<typename Stream>
void serialize(Stream& stream,InitializerExpression& initializer)
{
serializeNativeValue(stream,*(U8*)&initializer.type);
switch(initializer.type)
{
case InitializerExpression::Type::i32_const: serializeVarInt32(stream,initializer.i32); break;
case InitializerExpression::Type::i64_const: serializeVarInt64(stream,initializer.i64); break;
case InitializerExpression::Type::f32_const: serialize(stream,initializer.f32); break;
case InitializerExpression::Type::f64_const: serialize(stream,initializer.f64); break;
case InitializerExpression::Type::get_global: serializeVarUInt32(stream,initializer.globalIndex); break;
default: throw FatalSerializationException("invalid initializer expression opcode");
}
serializeConstant(stream,"expected end opcode",(U8)Opcode::end);
}
template<typename Stream>
void serialize(Stream& stream,TableDef& tableDef)
{
serialize(stream,tableDef.type);
}
template<typename Stream>
void serialize(Stream& stream,MemoryDef& memoryDef)
{
serialize(stream,memoryDef.type);
}
template<typename Stream>
void serialize(Stream& stream,GlobalDef& globalDef)
{
serialize(stream,globalDef.type);
serialize(stream,globalDef.initializer);
}
template<typename Stream>
void serialize(Stream& stream,DataSegment& dataSegment)
{
serializeVarUInt32(stream,dataSegment.memoryIndex);
serialize(stream,dataSegment.baseOffset);
serialize(stream,dataSegment.data);
}
template<typename Stream>
void serialize(Stream& stream,TableSegment& tableSegment)
{
serializeVarUInt32(stream,tableSegment.tableIndex);
serialize(stream,tableSegment.baseOffset);
serializeArray(stream,tableSegment.indices,[](Stream& stream,Uptr& functionIndex){serializeVarUInt32(stream,functionIndex);});
}
}
namespace WASM
{
using namespace IR;
using namespace Serialization;
enum
{
magicNumber=0x6d736100, // "\0asm"
currentVersion=1
};
enum class SectionType : U8
{
unknown = 0,
user = 0,
type = 1,
import = 2,
functionDeclarations = 3,
table = 4,
memory = 5,
global = 6,
export_ = 7,
start = 8,
elem = 9,
functionDefinitions = 10,
data = 11
};
FORCEINLINE void serialize(InputStream& stream,Opcode& opcode)
{
opcode = (Opcode)0;
Serialization::serializeNativeValue(stream,*(U8*)&opcode);
if(opcode > Opcode::maxSingleByteOpcode)
{
opcode = (Opcode)(U16(opcode) << 8);
Serialization::serializeNativeValue(stream,*(U8*)&opcode);
}
}
FORCEINLINE void serialize(OutputStream& stream,Opcode opcode)
{
if(opcode <= Opcode::maxSingleByteOpcode) { Serialization::serializeNativeValue(stream,*(U8*)&opcode); }
else
{
serializeNativeValue(stream,*(((U8*)&opcode) + 1));
serializeNativeValue(stream,*(((U8*)&opcode) + 0));
}
}
template<typename Stream>
void serialize(Stream& stream,NoImm&,const FunctionDef&) {}
template<typename Stream>
void serialize(Stream& stream,ControlStructureImm& imm,const FunctionDef&)
{
I8 encodedResultType = imm.resultType == ResultType::none ? -64 : -(I8)imm.resultType;
serializeVarInt7(stream,encodedResultType);
if(Stream::isInput) { imm.resultType = encodedResultType == -64 ? ResultType::none : (ResultType)-encodedResultType; }
}
template<typename Stream>
void serialize(Stream& stream,BranchImm& imm,const FunctionDef&)
{
serializeVarUInt32(stream,imm.targetDepth);
}
void serialize(InputStream& stream,BranchTableImm& imm,FunctionDef& functionDef)
{
std::vector<U32> branchTable;
serializeArray(stream,branchTable,[](InputStream& stream,U32& targetDepth){serializeVarUInt32(stream,targetDepth);});
imm.branchTableIndex = functionDef.branchTables.size();
functionDef.branchTables.push_back(std::move(branchTable));
serializeVarUInt32(stream,imm.defaultTargetDepth);
}
void serialize(OutputStream& stream,BranchTableImm& imm,FunctionDef& functionDef)
{
WAVM_ASSERT_THROW(imm.branchTableIndex < functionDef.branchTables.size());
std::vector<U32>& branchTable = functionDef.branchTables[imm.branchTableIndex];
serializeArray(stream,branchTable,[](OutputStream& stream,U32& targetDepth){serializeVarUInt32(stream,targetDepth);});
serializeVarUInt32(stream,imm.defaultTargetDepth);
}
template<typename Stream>
void serialize(Stream& stream,LiteralImm<I32>& imm,const FunctionDef&)
{ serializeVarInt32(stream,imm.value); }
template<typename Stream>
void serialize(Stream& stream,LiteralImm<I64>& imm,const FunctionDef&)
{ serializeVarInt64(stream,imm.value); }
template<typename Stream,bool isGlobal>
void serialize(Stream& stream,GetOrSetVariableImm<isGlobal>& imm,const FunctionDef&)
{ serializeVarUInt32(stream,imm.variableIndex); }
template<typename Stream>
void serialize(Stream& stream,CallImm& imm,const FunctionDef&)
{
serializeVarUInt32(stream,imm.functionIndex);
}
template<typename Stream>
void serialize(Stream& stream,CallIndirectImm& imm,const FunctionDef&)
{
serializeVarUInt32(stream,imm.type.index);
serializeConstant(stream,"call_indirect immediate reserved field must be 0",U8(0));
}
template<typename Stream,Uptr naturalAlignmentLog2>
void serialize(Stream& stream,LoadOrStoreImm<naturalAlignmentLog2>& imm,const FunctionDef&)
{
serializeVarUInt7(stream,imm.alignmentLog2);
serializeVarUInt32(stream,imm.offset);
}
template<typename Stream>
void serialize(Stream& stream,MemoryImm& imm,const FunctionDef&)
{
serializeConstant(stream,"grow_memory/current_memory immediate reserved field must be 0",U8(0));
}
#if ENABLE_SIMD_PROTOTYPE
template<typename Stream>
void serialize(Stream& stream,V128& v128)
{
serializeNativeValue(stream,v128);
}
template<Uptr numLanes>
void serialize(InputStream& stream,BoolVector<numLanes>& boolVector)
{
U64 mask = 0;
serializeBytes(stream,(U8*)&mask,(numLanes + 7) / 8);
for(Uptr index = 0;index < numLanes;++index)
{
boolVector.b[index] = (mask & (U64(1) << index)) != 0;
}
}
template<Uptr numLanes>
void serialize(OutputStream& stream,BoolVector<numLanes>& boolVector)
{
U64 mask = 0;
for(Uptr index = 0;index < numLanes;++index)
{
if(boolVector.b[index]) { mask |= U64(1) << index; }
}
serializeBytes(stream,(U8*)&mask,(numLanes + 7) / 8);
}
template<typename Stream,Uptr numLanes>
void serialize(Stream& stream,LaneIndexImm<numLanes>& imm,const FunctionDef&)
{
serializeVarUInt7(stream,imm.laneIndex);
}
template<typename Stream,Uptr numLanes>
void serialize(Stream& stream,ShuffleImm<numLanes>& imm,const FunctionDef&)
{
for(Uptr laneIndex = 0;laneIndex < numLanes;++laneIndex)
{
serializeVarUInt7(stream,imm.laneIndices[laneIndex]);
}
}
#endif
#if ENABLE_THREADING_PROTOTYPE
template<typename Stream>
void serialize(Stream& stream,LaunchThreadImm& imm,const FunctionDef&) {}
template<typename Stream,Uptr naturalAlignmentLog2>
void serialize(Stream& stream,AtomicLoadOrStoreImm<naturalAlignmentLog2>& imm,const FunctionDef&)
{
serializeVarUInt7(stream,imm.alignmentLog2);
serializeVarUInt32(stream,imm.offset);
}
#endif
template<typename Stream,typename Value>
void serialize(Stream& stream,LiteralImm<Value>& imm,const FunctionDef&)
{ serialize(stream,imm.value); }
template<typename SerializeSection>
void serializeSection(OutputStream& stream,SectionType type,SerializeSection serializeSectionBody)
{
serializeNativeValue(stream,type);
ArrayOutputStream sectionStream;
serializeSectionBody(sectionStream);
std::vector<U8> sectionBytes = sectionStream.getBytes();
Uptr sectionNumBytes = sectionBytes.size();
serializeVarUInt32(stream,sectionNumBytes);
serializeBytes(stream,sectionBytes.data(),sectionBytes.size());
}
template<typename SerializeSection>
void serializeSection(InputStream& stream,SectionType expectedType,SerializeSection serializeSectionBody)
{
WAVM_ASSERT_THROW((SectionType)*stream.peek(sizeof(SectionType)) == expectedType);
stream.advance(sizeof(SectionType));
Uptr numSectionBytes = 0;
serializeVarUInt32(stream,numSectionBytes);
MemoryInputStream sectionStream(stream.advance(numSectionBytes),numSectionBytes);
serializeSectionBody(sectionStream);
if(sectionStream.capacity()) { throw FatalSerializationException("section contained more data than expected"); }
}
void serialize(OutputStream& stream,UserSection& userSection)
{
serializeConstant(stream,"expected user section (section ID 0)",(U8)SectionType::user);
ArrayOutputStream sectionStream;
serialize(sectionStream,userSection.name);
userSection.data.resize( sectionStream.capacity() ? sectionStream.capacity() : 1 );
serializeBytes(sectionStream,userSection.data.data(),userSection.data.size());
std::vector<U8> sectionBytes = sectionStream.getBytes();
serialize(stream,sectionBytes);
if( !sectionStream.capacity() ) throw FatalSerializationException( "empty section" );
}
void serialize(InputStream& stream,UserSection& userSection)
{
serializeConstant(stream,"expected user section (section ID 0)",(U8)SectionType::user);
Uptr numSectionBytes = 0;
serializeVarUInt32(stream,numSectionBytes);
MemoryInputStream sectionStream(stream.advance(numSectionBytes),numSectionBytes);
serialize(sectionStream,userSection.name);
throwIfNotValidUTF8(userSection.name);
userSection.data.resize(sectionStream.capacity());
serializeBytes(sectionStream,userSection.data.data(),userSection.data.size());
WAVM_ASSERT_THROW(!sectionStream.capacity());
}
struct LocalSet
{
Uptr num;
ValueType type;
};
template<typename Stream>
void serialize(Stream& stream,LocalSet& localSet)
{
serializeVarUInt32(stream,localSet.num);
serialize(stream,localSet.type);
}
struct OperatorSerializerStream
{
typedef void Result;
OperatorSerializerStream(Serialization::OutputStream& inByteStream,FunctionDef& inFunctionDef)
: byteStream(inByteStream), functionDef(inFunctionDef) {}
#define VISIT_OPCODE(_,name,nameString,Imm,...) \
void name(Imm imm) const \
{ \
Opcode opcode = Opcode::name; \
serialize(byteStream,opcode); \
serialize(byteStream,imm,functionDef); \
}
ENUM_OPERATORS(VISIT_OPCODE)
#undef VISIT_OPCODE
void unknown(Opcode opcode)
{
throw FatalSerializationException("unknown opcode");
}
private:
Serialization::OutputStream& byteStream;
FunctionDef& functionDef;
};
void serializeFunctionBody(OutputStream& sectionStream,Module& module,FunctionDef& functionDef)
{
ArrayOutputStream bodyStream;
// Convert the function's local types into LocalSets: runs of locals of the same type.
LocalSet* localSets = (LocalSet*)alloca(sizeof(LocalSet)*functionDef.nonParameterLocalTypes.size());
Uptr numLocalSets = 0;
if(functionDef.nonParameterLocalTypes.size())
{
localSets[0].type = ValueType::any;
localSets[0].num = 0;
for(auto localType : functionDef.nonParameterLocalTypes)
{
if(localSets[numLocalSets].type != localType)
{
if(localSets[numLocalSets].type != ValueType::any) { ++numLocalSets; }
localSets[numLocalSets].type = localType;
localSets[numLocalSets].num = 0;
}
++localSets[numLocalSets].num;
}
if(localSets[numLocalSets].type != ValueType::any) { ++numLocalSets; }
}
// Serialize the local sets.
serializeVarUInt32(bodyStream,numLocalSets);
for(Uptr setIndex = 0;setIndex < numLocalSets;++setIndex) { serialize(bodyStream,localSets[setIndex]); }
// Serialize the function code.
OperatorDecoderStream irDecoderStream(functionDef.code);
OperatorSerializerStream wasmOpEncoderStream(bodyStream,functionDef);
while(irDecoderStream) { irDecoderStream.decodeOp(wasmOpEncoderStream); };
std::vector<U8> bodyBytes = bodyStream.getBytes();
serialize(sectionStream,bodyBytes);
}
void serializeFunctionBody(InputStream& sectionStream,Module& module,FunctionDef& functionDef)
{
Uptr numBodyBytes = 0;
serializeVarUInt32(sectionStream,numBodyBytes);
MemoryInputStream bodyStream(sectionStream.advance(numBodyBytes),numBodyBytes);
// Deserialize local sets and unpack them into a linear array of local types.
Uptr numLocalSets = 0;
serializeVarUInt32(bodyStream,numLocalSets);
constexpr size_t max_size = eosio::chain::wasm_constraints::maximum_code_size;
if (numBodyBytes >= max_size)
throw FatalSerializationException(std::string("Function body too large"));
if (numLocalSets >= 1024)
throw FatalSerializationException(std::string("too many local sets"));
size_t locals_accum = 0;
for(Uptr setIndex = 0;setIndex < numLocalSets;++setIndex)
{
LocalSet localSet;
serialize(bodyStream,localSet);
locals_accum += localSet.num*4;
if( locals_accum > eosio::chain::wasm_constraints::maximum_func_local_bytes )
throw FatalSerializationException( "too many locals" );
for(Uptr index = 0;index < localSet.num;++index) { functionDef.nonParameterLocalTypes.push_back(localSet.type); }
}
// Deserialize the function code, validate it, and re-encode it in the IR format.
ArrayOutputStream irCodeByteStream;
OperatorEncoderStream irEncoderStream(irCodeByteStream);
CodeValidationStream codeValidationStream(module,functionDef);
while(bodyStream.capacity())
{
Opcode opcode;
serialize(bodyStream,opcode);
switch(opcode)
{
#define VISIT_OPCODE(_,name,nameString,Imm,...) \
case Opcode::name: \
{ \
Imm imm; \
serialize(bodyStream,imm,functionDef); \
codeValidationStream.name(imm); \
irEncoderStream.name(imm); \
break; \
}
ENUM_OPERATORS(VISIT_OPCODE)
#undef VISIT_OPCODE
default: throw FatalSerializationException("unknown opcode");
};
};
codeValidationStream.finish();
functionDef.code = std::move(irCodeByteStream.getBytes());
}
template<typename Stream>
void serializeTypeSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::type,[&module](Stream& sectionStream)
{
serializeArray(sectionStream,module.types,[](Stream& stream,const FunctionType*& functionType)
{
serializeConstant(stream,"function type tag",U8(0x60));
if(Stream::isInput)
{
std::vector<ValueType> parameterTypes;
ResultType returnType;
serialize(stream,parameterTypes);
serialize(stream,returnType);
functionType = FunctionType::get(returnType,parameterTypes);
}
else
{
serialize(stream,const_cast<std::vector<ValueType>&>(functionType->parameters));
serialize(stream,const_cast<ResultType&>(functionType->ret));
}
});
});
}
template<typename Stream>
void serializeImportSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::import,[&module](Stream& sectionStream)
{
Uptr size = module.functions.imports.size()
+ module.tables.imports.size()
+ module.memories.imports.size()
+ module.globals.imports.size();
serializeVarUInt32(sectionStream,size);
constexpr size_t max_size = eosio::chain::wasm_constraints::maximum_section_elements;
if(Stream::isInput)
{
for(Uptr index = 0;index < size;++index)
{
std::string moduleName;
std::string exportName;
ObjectKind kind = ObjectKind::invalid;
serialize(sectionStream,moduleName);
serialize(sectionStream,exportName);
throwIfNotValidUTF8(moduleName);
throwIfNotValidUTF8(exportName);
serialize(sectionStream,kind);
switch(kind)
{
case ObjectKind::function:
{
U32 functionTypeIndex = 0;
serializeVarUInt32(sectionStream,functionTypeIndex);
if(functionTypeIndex >= module.types.size())
{
throw FatalSerializationException("invalid import function type index");
}
module.functions.imports.push_back({{functionTypeIndex},std::move(moduleName),std::move(exportName)});
if (module.functions.imports.size() >= max_size)
throw FatalSerializationException(std::string("Too many function imports"));
break;
}
case ObjectKind::table:
{
TableType tableType;
serialize(sectionStream,tableType);
module.tables.imports.push_back({tableType,std::move(moduleName),std::move(exportName)});
if (module.functions.imports.size() >= max_size)
throw FatalSerializationException(std::string("Too many table imports"));
break;
}
case ObjectKind::memory:
{
MemoryType memoryType;
serialize(sectionStream,memoryType);
module.memories.imports.push_back({memoryType,std::move(moduleName),std::move(exportName)});
if (module.functions.imports.size() >= max_size)
throw FatalSerializationException(std::string("Too many memory imports"));
break;
}
case ObjectKind::global:
{
GlobalType globalType;
serialize(sectionStream,globalType);
module.globals.imports.push_back({globalType,std::move(moduleName),std::move(exportName)});
if (module.functions.imports.size() >= max_size)
throw FatalSerializationException(std::string("Too many global imports"));
break;
}
default: throw FatalSerializationException("invalid ObjectKind");
}
}
}
else
{
for(auto& functionImport : module.functions.imports)
{
serialize(sectionStream,functionImport.moduleName);
serialize(sectionStream,functionImport.exportName);
ObjectKind kind = ObjectKind::function;
serialize(sectionStream,kind);
serializeVarUInt32(sectionStream,functionImport.type.index);
}
for(auto& tableImport : module.tables.imports)
{
serialize(sectionStream,tableImport.moduleName);
serialize(sectionStream,tableImport.exportName);
ObjectKind kind = ObjectKind::table;
serialize(sectionStream,kind);
serialize(sectionStream,tableImport.type);
}
for(auto& memoryImport : module.memories.imports)
{
serialize(sectionStream,memoryImport.moduleName);
serialize(sectionStream,memoryImport.exportName);
ObjectKind kind = ObjectKind::memory;
serialize(sectionStream,kind);
serialize(sectionStream,memoryImport.type);
}
for(auto& globalImport : module.globals.imports)
{
serialize(sectionStream,globalImport.moduleName);
serialize(sectionStream,globalImport.exportName);
ObjectKind kind = ObjectKind::global;
serialize(sectionStream,kind);
serialize(sectionStream,globalImport.type);
}
}
});
}
template<typename Stream>
void serializeFunctionSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::functionDeclarations,[&module](Stream& sectionStream)
{
Uptr numFunctions = module.functions.defs.size();
serializeVarUInt32(sectionStream,numFunctions);
if(Stream::isInput)
{
// Grow the vector one element at a time:
// try to get a serialization exception before making a huge allocation for malformed input.
module.functions.defs.clear();
constexpr size_t max_size = eosio::chain::wasm_constraints::maximum_section_elements;
if ( numFunctions >= max_size )
throw FatalSerializationException(std::string("Too many function defs"));
for(Uptr functionIndex = 0;functionIndex < numFunctions;++functionIndex)
{
U32 functionTypeIndex = 0;
serializeVarUInt32(sectionStream,functionTypeIndex);
if(functionTypeIndex >= module.types.size()) { throw FatalSerializationException("invalid function type index"); }
module.functions.defs.push_back({{functionTypeIndex},{},{}});
}
module.functions.defs.shrink_to_fit();
}
else
{
for(FunctionDef& function : module.functions.defs)
{
serializeVarUInt32(sectionStream,function.type.index);
}
}
});
}
template<typename Stream>
void serializeTableSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::table,[&module](Stream& sectionStream)
{
serialize(sectionStream,module.tables.defs);
});
}
template<typename Stream>
void serializeMemorySection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::memory,[&module](Stream& sectionStream)
{
serialize(sectionStream,module.memories.defs);
});
}
template<typename Stream>
void serializeGlobalSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::global,[&module](Stream& sectionStream)
{
serialize(sectionStream,module.globals.defs);
});
}
template<typename Stream>
void serializeExportSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::export_,[&module](Stream& sectionStream)
{
serialize(sectionStream,module.exports);
});
}
template<typename Stream>
void serializeStartSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::start,[&module](Stream& sectionStream)
{
serializeVarUInt32(sectionStream,module.startFunctionIndex);
});
}
template<typename Stream>
void serializeElementSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::elem,[&module](Stream& sectionStream)
{
serialize(sectionStream,module.tableSegments);
});
}
template<typename Stream>
void serializeCodeSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::functionDefinitions,[&module](Stream& sectionStream)
{
Uptr numFunctionBodies = module.functions.defs.size();
serializeVarUInt32(sectionStream,numFunctionBodies);
if(Stream::isInput && numFunctionBodies != module.functions.defs.size())
{ throw FatalSerializationException("function and code sections have mismatched function counts"); }
for(FunctionDef& functionDef : module.functions.defs) { serializeFunctionBody(sectionStream,module,functionDef); }
});
}
template<typename Stream>
void serializeDataSection(Stream& moduleStream,Module& module)
{
serializeSection(moduleStream,SectionType::data,[&module](Stream& sectionStream)
{
serialize(sectionStream,module.dataSegments);
});
}
void serializeModule(OutputStream& moduleStream,Module& module)
{
serializeConstant(moduleStream,"magic number",U32(magicNumber));
serializeConstant(moduleStream,"version",U32(currentVersion));
if(module.types.size() > 0) { serializeTypeSection(moduleStream,module); }
if(module.functions.imports.size() > 0
|| module.tables.imports.size() > 0
|| module.memories.imports.size() > 0
|| module.globals.imports.size() > 0) { serializeImportSection(moduleStream,module); }
if(module.functions.defs.size() > 0) { serializeFunctionSection(moduleStream,module); }
if(module.tables.defs.size() > 0) { serializeTableSection(moduleStream,module); }
if(module.memories.defs.size() > 0) { serializeMemorySection(moduleStream,module); }
if(module.globals.defs.size() > 0) { serializeGlobalSection(moduleStream,module); }
if(module.exports.size() > 0) { serializeExportSection(moduleStream,module); }
if(module.startFunctionIndex != UINTPTR_MAX) { serializeStartSection(moduleStream,module); }
if(module.tableSegments.size() > 0) { serializeElementSection(moduleStream,module); }
if(module.functions.defs.size() > 0) { serializeCodeSection(moduleStream,module); }
if(module.dataSegments.size() > 0) { serializeDataSection(moduleStream,module); }
for(auto& userSection : module.userSections) { serialize(moduleStream,userSection); }
}
void serializeModule(InputStream& moduleStream,Module& module)
{
serializeConstant(moduleStream,"magic number",U32(magicNumber));
serializeConstant(moduleStream,"version",U32(currentVersion));
SectionType lastKnownSectionType = SectionType::unknown;
while(moduleStream.capacity())
{
const SectionType sectionType = *(SectionType*)moduleStream.peek(sizeof(SectionType));
if(sectionType != SectionType::user)
{
if(sectionType > lastKnownSectionType) { lastKnownSectionType = sectionType; }
else { throw FatalSerializationException("incorrect order for known section"); }
}
switch(sectionType)
{
case SectionType::type: serializeTypeSection(moduleStream,module); break;
case SectionType::import: serializeImportSection(moduleStream,module); break;
case SectionType::functionDeclarations: serializeFunctionSection(moduleStream,module); break;
case SectionType::table: serializeTableSection(moduleStream,module); break;
case SectionType::memory: serializeMemorySection(moduleStream,module); break;
case SectionType::global: serializeGlobalSection(moduleStream,module); break;
case SectionType::export_: serializeExportSection(moduleStream,module); break;
case SectionType::start: serializeStartSection(moduleStream,module); break;
case SectionType::elem: serializeElementSection(moduleStream,module); break;
case SectionType::functionDefinitions: serializeCodeSection(moduleStream,module); break;
case SectionType::data: serializeDataSection(moduleStream,module); break;
case SectionType::user:
{
UserSection& userSection = *module.userSections.insert(module.userSections.end(),UserSection());
serialize(moduleStream,userSection);
break;
}
default: throw FatalSerializationException("unknown section ID");
};
};
}
void serialize(Serialization::InputStream& stream,Module& module)
{
serializeModule(stream,module);
IR::validateDefinitions(module);
}
void serialize(Serialization::OutputStream& stream,const Module& module)
{
serializeModule(stream,const_cast<Module&>(module));
}
}
|
//===-- lds_gaussian_fit_em.cpp - GLDS Fit (EM) ---------------------------===//
//
// Copyright 2021 Michael Bolus
// Copyright 2021 Georgia Institute of Technology
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements a type by which Gaussian-output LDS models are fit by
/// the expectation-maximization (EM) algorithm (`lds::gaussian::emFit_t`).
///
/// References:
/// [1] Shumway RH, Stoffer DS. (1982) An Approach to Time Series Smoothing and
/// Forecasting Using the EM Algorithm.Journal of Time Series Analysis 3(2).
///
/// [2] Ghahramani Z, Hinton GE. (1996) Parameter Estimation for Linear
/// Dynamical Systems. Technical Report CRG-TR-96-2.
///
/// \brief GLDS E-M fit type
//===----------------------------------------------------------------------===//
#include <ldsCtrlEst_h/lds_gaussian_fit_em.h>
namespace lds {
namespace gaussian {
void FitEM::RecurseKe(Matrix& Ke, Cube& P_pre, Cube& P_post, size_t t) {
// predict covar
P_pre.slice(t) = fit_.A() * P_post.slice(t - 1) * fit_.A().t() + fit_.Q();
ForceSymPD(P_pre.slice(t));
// update Ke
Ke = P_pre.slice(t) * fit_.C().t() *
inv_sympd(fit_.C() * P_pre.slice(t) * fit_.C().t() + fit_.R());
// update covar
// Reference: Ghahramani et Hinton (1996)
P_post.slice(t) = P_pre.slice(t) - Ke * fit_.C() * P_pre.slice(t);
ForceSymPD(P_post.slice(t));
}
void FitEM::MaximizeOutput() {
// solve for C+d:
Matrix sum_zx(n_y_, n_x_ + 1, fill::zeros);
Vector x1(n_x_ + 1, fill::zeros);
x1[n_x_] = 1.0; // augment with one to solve for bias
Matrix sum_e_x1_x1(n_x_ + 1, n_x_ + 1, fill::zeros);
for (size_t trial = 0; trial < z_.size(); trial++) {
for (size_t t = 1; t < n_t_[trial]; t++) {
x1.subvec(0, n_x_ - 1) = x_[trial].col(t);
sum_zx += z_.at(trial).col(t) * x1.t();
sum_e_x1_x1 += x1 * x1.t();
sum_e_x1_x1.submat(0, 0, n_x_ - 1, n_x_ - 1) += P_[trial].slice(t);
}
}
Matrix cd = sum_zx * inv_sympd(sum_e_x1_x1);
fit_.set_C(cd.submat(0, 0, n_y_ - 1, n_x_ - 1));
fit_.set_d(vectorise(cd.submat(0, n_x_, n_y_ - 1, n_x_)));
std::cout << "C_new[0]: " << fit_.C()[0] << "\n";
std::cout << "d_new[0]: " << fit_.d()[0] << "\n";
}
void FitEM::MaximizeMeasurement() {
// Solve for measurement noise covar
size_t n_t_tot = 0;
// Ghahgramani, Hinton 1996:
Matrix sum_zz(n_y_, n_y_, fill::zeros);
Matrix sum_yz(n_y_, n_y_, fill::zeros);
for (size_t trial = 0; trial < z_.size(); trial++) {
for (size_t t = 1; t < n_t_[trial]; t++) {
sum_zz += z_.at(trial).col(t) * z_.at(trial).col(t).t();
// Use Cnew:
sum_yz +=
(fit_.C() * x_[trial].col(t) + fit_.d()) * z_.at(trial).col(t).t();
n_t_tot += 1;
}
}
fit_.set_R((sum_zz - sum_yz) / n_t_tot);
std::cout << "R_new[0]: " << fit_.R()[0] << "\n";
}
} // namespace gaussian
} // namespace lds
|
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/server/GOSSIP_onReceived.h"
#include "logdevice/server/ServerWorker.h"
#include "logdevice/server/ServerProcessor.h"
#include "logdevice/server/FailureDetector.h"
namespace facebook { namespace logdevice {
void GOSSIP_onSent(const GOSSIP_Message& msg,
Status st,
const Address& to,
const SteadyTimestamp /*enqueue-time*/) {
ServerWorker* w = ServerWorker::onThisThread();
auto failure_detector = w->processor_->failure_detector_.get();
// only call the onGossipMessageSent callback if it was a gossip sent by the
// failure detector thread
if (failure_detector && w->worker_type_ == WorkerType::FAILURE_DETECTOR) {
failure_detector->onGossipMessageSent(st, to, msg.msg_id_);
}
}
}} // namespace facebook::logdevice
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/policy/core/browser/autofill_policy_handler.h"
#include "base/prefs/pref_value_map.h"
#include "base/values.h"
#include "components/autofill/core/common/autofill_pref_names.h"
#include "components/policy/core/common/policy_map.h"
#include "policy/policy_constants.h"
namespace policy {
AutofillPolicyHandler::AutofillPolicyHandler()
: TypeCheckingPolicyHandler(key::kAutoFillEnabled,
base::Value::TYPE_BOOLEAN) {}
AutofillPolicyHandler::~AutofillPolicyHandler() {
}
void AutofillPolicyHandler::ApplyPolicySettings(const PolicyMap& policies,
PrefValueMap* prefs) {
const base::Value* value = policies.GetValue(policy_name());
bool auto_fill_enabled;
if (value && value->GetAsBoolean(&auto_fill_enabled) && !auto_fill_enabled)
prefs->SetBoolean(autofill::prefs::kAutofillEnabled, false);
}
} // namespace policy
|
// MIT Licensed (see LICENSE.md).
#pragma once
namespace Zero
{
// Editor Resource management functions. These functions work with the
// content system and the resource system to manage resources for the editor.
// Add a new resource all resource adding goes through this function
Resource* AddNewResource(ResourceManager* resourceManager, ResourceAdd& resourceAdd);
// Add a resource to the current project from a file
Resource* AddResourceFromFile(StringParam filePath, StringParam resourceType);
// Add a resources to the current project from files
void AddResourcesFromFiles(const Array<String>& files, StringParam resourceType);
// Duplicate a resource
Resource* DuplicateResource(Resource* resource, StringParam newName = String());
// Rename a resource
bool RenameResource(Resource* resource, StringParam newName);
// Reload a resource and content item
void ReloadResource(Resource* resource);
void ReloadContentItem(ContentItem* contentItem);
// Edit the resource in an external program
void EditResourceExternal(Resource* resource);
// Remove the resource project the project
void RemoveResource(Resource* resource);
// Load a resource from a content item
Resource* LoadResourceFromNewContentItem(ResourceManager* resourceManager,
ContentItem* newContentItem,
Resource* resource);
// Get what the file name should be for this resource
String GetResourceFileName(ResourceManager* resourceManager, StringParam resourceName, ContentItem* current = NULL);
// Where to place deleted files
String GetEditorTrash();
Resource* NewResourceOnWrite(ResourceManager* resourceManager,
BoundType* type,
StringParam property,
Space* space,
Resource* resource,
Archetype* archetype,
bool modified);
} // namespace Zero
|
#include<iostream>
using namespace std;
long long fast_pow(long long x, long long y, long long p) {
long long res = 1;
while(y > 0) {
if( y % 2 != 0) {
res = (res * x) % p;
}
x = (x * x) % p;
y /= 2;
}
return res;
}
long long qwerty1(long long x, long long p) {
return fast_pow(x, p-2, p);
}
long long qwerty2(long long n, long long k, long long p) {
long long no = 1;
for (int i = 0; i < k; i ++) {
no = (no * (n-i)) % p;
// cout<<no<<"\n";
}
// cout<<"\n";
long long don = 1;
for (int i=1; i <= k; i++) {
don = (don * i ) % p;
}
// cout<<no<<"\n";
return ( no * qwerty1(don,p)) % p;
}
int main(void){
int t;cin>>t;
while(t--){
int n,k;cin>>n>>k;
if(k > n)cout<<0<<"\n";
else {
long long final_ans = 0;
for(int i = 0; i < k; i++){
// cout<<qwerty2(k - 1, i, 1000000007)<<"\n";
// cout<<qwerty2(k + 1 + i - k, k, 1000000007)<<"\n";
final_ans = (final_ans + (2 * qwerty2(k - 1, i,1000000007) * qwerty2(n + 1 + i - k, k, 1000000007))) % 1000000007;
// cout<<final_ans<<"\n";
}
cout<<final_ans <<"\n";
}
}
}
|
#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include <vector>
#include <ncurses.h>
#include <time.h>
#include <sstream>
#include <iomanip>
#include "util.h"
#include "SysInfo.h"
#include "ProcessContainer.h"
using namespace std;
char* getCString(std::string str){
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
return cstr;
}
void writeSysInfoToConsole(SysInfo sys, WINDOW* sys_win){
sys.setAttributes();
mvwprintw(sys_win,2,2,getCString(( "OS: " + sys.getOSName())));
mvwprintw(sys_win,3,2,getCString(( "Kernel version: " + sys.getKernelVersion())));
mvwprintw(sys_win,4,2,getCString( "CPU: "));
wattron(sys_win,COLOR_PAIR(1));
wprintw(sys_win,getCString(Util::getProgressBar(sys.getCpuPercent())));
wattroff(sys_win,COLOR_PAIR(1));
mvwprintw(sys_win,5,2,getCString(( "Other cores:")));
wattron(sys_win,COLOR_PAIR(1));
std::vector<std::string> val = sys.getCoresStats();
for(int i=0;i<val.size();i++){
mvwprintw(sys_win,(6+i),2,getCString(val[i]));
}
wattroff(sys_win,COLOR_PAIR(1));
mvwprintw(sys_win,10,2,getCString(( "Memory: ")));
wattron(sys_win,COLOR_PAIR(1));
wprintw(sys_win,getCString(Util::getProgressBar(sys.getMemPercent())));
wattroff(sys_win,COLOR_PAIR(1));
mvwprintw(sys_win,11,2,getCString(( "Total Processes:" + sys.getTotalProc())));
mvwprintw(sys_win,12,2,getCString(( "Running Processes:" + sys.getRunningProc())));
mvwprintw(sys_win,13,2,getCString(( "Up Time: " + Util::convertToTime(sys.getUpTime()))));
wrefresh(sys_win);
}
void getProcessListToConsole(std::vector<string> processes,WINDOW* win){
wattron(win,COLOR_PAIR(2));
mvwprintw(win,1,2,"PID:");
mvwprintw(win,1,9,"User:");
mvwprintw(win,1,16,"CPU[%%]:");
mvwprintw(win,1,26,"RAM[MB]:");
mvwprintw(win,1,35,"Uptime:");
mvwprintw(win,1,44,"CMD:");
wattroff(win, COLOR_PAIR(2));
for(int i=0; i< processes.size();i++){
mvwprintw(win,2+i,2,getCString(processes[i]));
}
}
void printMain(SysInfo sys,ProcessContainer procs){
initscr(); /* Start curses mode */
noecho(); // not printing input values
cbreak(); // Terminating on classic ctrl + c
start_color(); // Enabling color change of text
int yMax,xMax;
getmaxyx(stdscr,yMax,xMax); // getting size of window measured in lines and columns(column one char length)
WINDOW *sys_win = newwin(17,xMax-1,0,0);
WINDOW *proc_win = newwin(15,xMax-1,18,0);
init_pair(1,COLOR_BLUE,COLOR_BLACK);
init_pair(2,COLOR_GREEN,COLOR_BLACK);
int counter = 0;
while(1){
box(sys_win,0,0);
box (proc_win,0,0);
procs.refreshList();
std::vector<std::vector<std::string>> processes = procs.getList();
writeSysInfoToConsole(sys,sys_win);
getProcessListToConsole(processes[counter],proc_win);
wrefresh(sys_win);
wrefresh(proc_win);
refresh();
sleep(1);
if(counter == (processes.size() -1)){
counter = 0;
}
else {
counter ++;
}
}
endwin();
}
int main( int argc, char *argv[] )
{
//Object which contains list of current processes, Container for Process Class
ProcessContainer procs;
// Object which containts relevant methods and attributes regarding system details
SysInfo sys;
// std::string s = writeToConsole(sys);
printMain(sys,procs);
return 0;
}
|
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "SpatialReceiver.h"
#include "EngineMinimal.h"
#include "GameFramework/PlayerController.h"
#include "TimerManager.h"
#include "EngineClasses/SpatialActorChannel.h"
#include "EngineClasses/SpatialNetConnection.h"
#include "EngineClasses/SpatialPackageMapClient.h"
#include "Interop/Connection/SpatialWorkerConnection.h"
#include "Interop/GlobalStateManager.h"
#include "Interop/SpatialPlayerSpawner.h"
#include "Interop/SpatialSender.h"
#include "Schema/DynamicComponent.h"
#include "Schema/Rotation.h"
#include "Schema/UnrealMetadata.h"
#include "SpatialConstants.h"
#include "Utils/ComponentReader.h"
#include "Utils/EntityRegistry.h"
#include "Utils/RepLayoutUtils.h"
DEFINE_LOG_CATEGORY(LogSpatialReceiver);
using namespace improbable;
template <typename T>
T* GetComponentData(USpatialReceiver& Receiver, Worker_EntityId EntityId)
{
for (PendingAddComponentWrapper& PendingAddComponent : Receiver.PendingAddComponents)
{
if (PendingAddComponent.EntityId == EntityId && PendingAddComponent.ComponentId == T::ComponentId)
{
return static_cast<T*>(PendingAddComponent.Data.Get());
}
}
return nullptr;
}
void USpatialReceiver::Init(USpatialNetDriver* InNetDriver, FTimerManager* InTimerManager)
{
NetDriver = InNetDriver;
View = InNetDriver->View;
Sender = InNetDriver->Sender;
PackageMap = InNetDriver->PackageMap;
World = InNetDriver->GetWorld();
TypebindingManager = InNetDriver->TypebindingManager;
GlobalStateManager = InNetDriver->GlobalStateManager;
TimerManager = InTimerManager;
}
void USpatialReceiver::OnCriticalSection(bool InCriticalSection)
{
if (InCriticalSection)
{
EnterCriticalSection();
}
else
{
LeaveCriticalSection();
}
}
void USpatialReceiver::EnterCriticalSection()
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Entering critical section."));
check(!bInCriticalSection);
bInCriticalSection = true;
}
void USpatialReceiver::LeaveCriticalSection()
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Leaving critical section."));
check(bInCriticalSection);
for (Worker_EntityId& PendingAddEntity : PendingAddEntities)
{
ReceiveActor(PendingAddEntity);
}
for (Worker_AuthorityChangeOp& PendingAuthorityChange : PendingAuthorityChanges)
{
HandleActorAuthority(PendingAuthorityChange);
}
for (Worker_EntityId& PendingRemoveEntity : PendingRemoveEntities)
{
RemoveActor(PendingRemoveEntity);
}
// Mark that we've left the critical section.
bInCriticalSection = false;
PendingAddEntities.Empty();
PendingAddComponents.Empty();
PendingAuthorityChanges.Empty();
PendingRemoveEntities.Empty();
}
void USpatialReceiver::OnAddEntity(Worker_AddEntityOp& Op)
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("AddEntity: %lld"), Op.entity_id);
check(bInCriticalSection);
PendingAddEntities.Emplace(Op.entity_id);
}
void USpatialReceiver::OnAddComponent(Worker_AddComponentOp& Op)
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("AddComponent component ID: %u entity ID: %lld"),
Op.data.component_id, Op.entity_id);
if (!bInCriticalSection)
{
UE_LOG(LogSpatialReceiver, Warning, TEXT("Received a dynamically added component, these are currently unsupported - component ID: %u entity ID: %lld"),
Op.data.component_id, Op.entity_id);
return;
}
TSharedPtr<improbable::Component> Data;
switch (Op.data.component_id)
{
case SpatialConstants::ENTITY_ACL_COMPONENT_ID:
Data = MakeShared<improbable::EntityAcl>(Op.data);
break;
case SpatialConstants::METADATA_COMPONENT_ID:
Data = MakeShared<improbable::Metadata>(Op.data);
break;
case SpatialConstants::POSITION_COMPONENT_ID:
Data = MakeShared<improbable::Position>(Op.data);
break;
case SpatialConstants::PERSISTENCE_COMPONENT_ID:
Data = MakeShared<improbable::Persistence>(Op.data);
break;
case SpatialConstants::ROTATION_COMPONENT_ID:
Data = MakeShared<improbable::Rotation>(Op.data);
break;
case SpatialConstants::UNREAL_METADATA_COMPONENT_ID:
Data = MakeShared<improbable::UnrealMetadata>(Op.data);
break;
case SpatialConstants::GLOBAL_STATE_MANAGER_COMPONENT_ID:
GlobalStateManager->ApplyData(Op.data);
GlobalStateManager->LinkExistingSingletonActors();
return;
default:
Data = MakeShared<improbable::DynamicComponent>(Op.data);
break;
}
PendingAddComponents.Emplace(Op.entity_id, Op.data.component_id, Data);
}
void USpatialReceiver::OnRemoveEntity(Worker_RemoveEntityOp& Op)
{
UE_LOG(LogSpatialReceiver, Log, TEXT("RemoveEntity: %lld"), Op.entity_id);
RemoveActor(Op.entity_id);
}
void USpatialReceiver::OnAuthorityChange(Worker_AuthorityChangeOp& Op)
{
if (bInCriticalSection)
{
PendingAuthorityChanges.Add(Op);
return;
}
HandleActorAuthority(Op);
}
// TODO UNR-640 - This function needs a pass once we introduce soft handover (AUTHORITY_LOSS_IMMINENT)
void USpatialReceiver::HandleActorAuthority(Worker_AuthorityChangeOp& Op)
{
if (NetDriver->IsServer())
{
if (Op.component_id == SpatialConstants::GLOBAL_STATE_MANAGER_COMPONENT_ID
&& Op.authority == WORKER_AUTHORITY_AUTHORITATIVE)
{
GlobalStateManager->ExecuteInitialSingletonActorReplication();
return;
}
// If we became authoritative over the position component. set our role to be ROLE_Authority
// and set our RemoteRole to be ROLE_AutonomousProxy iff the actor has an owning connection.
if (Op.component_id == SpatialConstants::POSITION_COMPONENT_ID)
{
if (AActor* Actor = NetDriver->GetEntityRegistry()->GetActorFromEntityId(Op.entity_id))
{
if (Op.authority == WORKER_AUTHORITY_AUTHORITATIVE)
{
Actor->Role = ROLE_Authority;
if (Actor->GetNetConnection() != nullptr)
{
Actor->RemoteRole = ROLE_AutonomousProxy;
}
else if (Actor->IsA<APawn>())
{
Actor->RemoteRole = ROLE_AutonomousProxy;
}
else
{
Actor->RemoteRole = ROLE_SimulatedProxy;
}
}
else if (Op.authority == WORKER_AUTHORITY_NOT_AUTHORITATIVE)
{
Actor->Role = ROLE_SimulatedProxy;
Actor->RemoteRole = ROLE_Authority;
}
}
}
}
else
{
// Check to see if we became authoritative over the ClientRPC component over this entity
// If we did, our local role should be ROLE_AutonomousProxy. Otherwise ROLE_SimulatedProxy
if (AActor* Actor = NetDriver->GetEntityRegistry()->GetActorFromEntityId(Op.entity_id))
{
FClassInfo* Info = TypebindingManager->FindClassInfoByClass(Actor->GetClass());
check(Info);
if (Op.component_id == Info->RPCComponents[RPC_Client])
{
Actor->Role = Op.authority == WORKER_AUTHORITY_AUTHORITATIVE ? ROLE_AutonomousProxy : ROLE_SimulatedProxy;
}
}
}
}
void USpatialReceiver::ReceiveActor(Worker_EntityId EntityId)
{
checkf(World, TEXT("We should have a world whilst processing ops."));
check(NetDriver);
UEntityRegistry* EntityRegistry = NetDriver->GetEntityRegistry();
check(EntityRegistry);
improbable::Position* Position = GetComponentData<improbable::Position>(*this, EntityId);
improbable::Metadata* Metadata = GetComponentData<improbable::Metadata>(*this, EntityId);
improbable::Rotation* Rotation = GetComponentData<improbable::Rotation>(*this, EntityId);
check(Position && Metadata);
if (AActor* EntityActor = EntityRegistry->GetActorFromEntityId(EntityId))
{
UE_LOG(LogSpatialReceiver, Log, TEXT("Entity for actor %s has been checked out on the worker which spawned it."), *EntityActor->GetName());
// Assume SimulatedProxy until we've been delegated Authority
bool bAuthority = View->GetAuthority(EntityId, improbable::Position::ComponentId) == WORKER_AUTHORITY_AUTHORITATIVE;
EntityActor->Role = bAuthority ? ROLE_Authority : ROLE_SimulatedProxy;
EntityActor->RemoteRole = bAuthority ? ROLE_SimulatedProxy : ROLE_Authority;
if (bAuthority)
{
if (EntityActor->GetNetConnection() != nullptr || EntityActor->IsA<APawn>())
{
EntityActor->RemoteRole = ROLE_AutonomousProxy;
}
}
UE_LOG(LogSpatialReceiver, Log, TEXT("Received create entity response op for %lld"), EntityId);
}
else
{
UClass* ActorClass = GetNativeEntityClass(Metadata);
if (ActorClass == nullptr)
{
return;
}
// Initial Singleton Actor replication is handled with GlobalStateManager::LinkExistingSingletonActors
if (NetDriver->IsServer() && ActorClass->HasAnySpatialClassFlags(SPATIALCLASS_Singleton))
{
return;
}
UNetConnection* Connection = nullptr;
improbable::UnrealMetadata* UnrealMetadataComponent = GetComponentData<improbable::UnrealMetadata>(*this, EntityId);
check(UnrealMetadataComponent);
bool bDoingDeferredSpawn = false;
// If we're checking out a player controller, spawn it via "USpatialNetDriver::AcceptNewPlayer"
if (NetDriver->IsServer() && ActorClass->IsChildOf(APlayerController::StaticClass()))
{
checkf(!UnrealMetadataComponent->OwnerWorkerAttribute.IsEmpty(), TEXT("A player controller entity must have an owner worker attribute."));
FString URLString = FURL().ToString();
URLString += TEXT("?workerAttribute=") + UnrealMetadataComponent->OwnerWorkerAttribute;
Connection = NetDriver->AcceptNewPlayer(FURL(nullptr, *URLString, TRAVEL_Absolute), true);
check(Connection);
EntityActor = Connection->PlayerController;
}
else
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Spawning a %s whilst checking out an entity."), *ActorClass->GetFullName());
EntityActor = CreateActor(Position, Rotation, ActorClass, true);
// Don't have authority over Actor until SpatialOS delegates authority
EntityActor->Role = ROLE_SimulatedProxy;
EntityActor->RemoteRole = ROLE_Authority;
bDoingDeferredSpawn = true;
// Get the net connection for this actor.
if (NetDriver->IsServer())
{
// Currently, we just create an actor channel on the "catch-all" connection, then create a new actor channel once we check out the player controller
// and create a new connection. This is fine due to lazy actor channel creation in USpatialNetDriver::ServerReplicateActors. However, the "right" thing to do
// would be to make sure to create anything which depends on the PlayerController _after_ the PlayerController's connection is set up so we can use the right
// one here. We should revisit this after implementing working sets - UNR:411
Connection = NetDriver->GetSpatialOSNetConnection();
}
else
{
Connection = NetDriver->GetSpatialOSNetConnection();
}
}
// Add to entity registry.
EntityRegistry->AddToRegistry(EntityId, EntityActor);
// Set up actor channel.
USpatialPackageMapClient* SpatialPackageMap = Cast<USpatialPackageMapClient>(Connection->PackageMap);
USpatialActorChannel* Channel = Cast<USpatialActorChannel>(Connection->CreateChannel(CHTYPE_Actor, NetDriver->IsServer()));
check(Channel);
if (bDoingDeferredSpawn)
{
FVector InitialLocation = improbable::Coordinates::ToFVector(Position->Coords);
FVector SpawnLocation = FRepMovement::RebaseOntoLocalOrigin(InitialLocation, World->OriginLocation);
EntityActor->FinishSpawning(FTransform(Rotation->ToFRotator(), SpawnLocation));
}
SpatialPackageMap->ResolveEntityActor(EntityActor, EntityId, UnrealMetadataComponent->SubobjectNameToOffset);
Channel->SetChannelActor(EntityActor);
// Apply initial replicated properties.
// This was moved to after FinishingSpawning because components existing only in blueprints aren't added until spawning is complete
// Potentially we could split out the initial actor state and the initial component state
for (PendingAddComponentWrapper& PendingAddComponent : PendingAddComponents)
{
if (PendingAddComponent.EntityId == EntityId && PendingAddComponent.Data.IsValid() && PendingAddComponent.Data->bIsDynamic)
{
ApplyComponentData(EntityId, *static_cast<improbable::DynamicComponent*>(PendingAddComponent.Data.Get())->Data, Channel);
}
}
if (!NetDriver->IsServer())
{
// Update interest on the entity's components after receiving initial component data (so Role and RemoteRole are properly set).
Sender->SendComponentInterest(EntityActor, EntityId);
// This is a bit of a hack unfortunately, among the core classes only PlayerController implements this function and it requires
// a player index. For now we don't support split screen, so the number is always 0.
if (EntityActor->IsA(APlayerController::StaticClass()))
{
uint8 PlayerIndex = 0;
// FInBunch takes size in bits not bytes
FInBunch Bunch(NetDriver->ServerConnection, &PlayerIndex, sizeof(PlayerIndex) * 8);
EntityActor->OnActorChannelOpen(Bunch, NetDriver->ServerConnection);
}
else
{
FInBunch Bunch(NetDriver->ServerConnection);
EntityActor->OnActorChannelOpen(Bunch, NetDriver->ServerConnection);
}
}
// Taken from PostNetInit
if (!EntityActor->HasActorBegunPlay())
{
EntityActor->DispatchBeginPlay();
}
EntityActor->UpdateOverlaps();
}
}
void USpatialReceiver::RemoveActor(Worker_EntityId EntityId)
{
AActor* Actor = NetDriver->GetEntityRegistry()->GetActorFromEntityId(EntityId);
UE_LOG(LogSpatialReceiver, Log, TEXT("Remove Actor: %s %lld"), Actor ? *Actor->GetName() : TEXT("nullptr"), EntityId);
// Actor already deleted (this worker was most likely authoritative over it and deleted it earlier).
if (!Actor || Actor->IsPendingKill())
{
CleanupDeletedEntity(EntityId);
return;
}
if (APlayerController* PC = Cast<APlayerController>(Actor))
{
// Force APlayerController::DestroyNetworkActorHandled to return false
PC->Player = nullptr;
}
// Workaround for camera loss on handover: prevent UnPossess() (non-authoritative destruction of pawn, while being authoritative over the controller)
// TODO: Check how AI controllers are affected by this (UNR-430)
// TODO: This should be solved properly by working sets (UNR-411)
if (APawn* Pawn = Cast<APawn>(Actor))
{
AController* Controller = Pawn->Controller;
if (Controller && Controller->HasAuthority())
{
Pawn->Controller = nullptr;
}
}
if (Actor->GetClass()->HasAnySpatialClassFlags(SPATIALCLASS_Singleton))
{
return;
}
// Destruction of actors can cause the destruction of associated actors (eg. Character > Controller). Actor destroy
// calls will eventually find their way into USpatialActorChannel::DeleteEntityIfAuthoritative() which checks if the entity
// is currently owned by this worker before issuing an entity delete request. If the associated entity is still authoritative
// on this server, we need to make sure this worker doesn't issue an entity delete request, as this entity is really
// transitioning to the same server as the actor we're currently operating on, and is just a few frames behind.
// We make the assumption that if we're destroying actors here (due to a remove entity op), then this is only due to two
// situations;
// 1. Actor's entity has been transitioned to another server
// 2. The Actor was deleted on another server
// In neither situation do we want to delete associated entities, so prevent them from being issued.
// TODO: fix this with working sets (UNR-411)
NetDriver->StartIgnoringAuthoritativeDestruction();
if (!World->DestroyActor(Actor, true))
{
UE_LOG(LogSpatialReceiver, Error, TEXT("World->DestroyActor failed on RemoveActor %s %lld"), *Actor->GetName(), EntityId);
}
NetDriver->StopIgnoringAuthoritativeDestruction();
CleanupDeletedEntity(EntityId);
}
void USpatialReceiver::CleanupDeletedEntity(Worker_EntityId EntityId)
{
NetDriver->GetEntityRegistry()->RemoveFromRegistry(EntityId);
NetDriver->RemoveActorChannel(EntityId);
Cast<USpatialPackageMapClient>(NetDriver->GetSpatialOSNetConnection()->PackageMap)->RemoveEntityActor(EntityId);
}
UClass* USpatialReceiver::GetNativeEntityClass(improbable::Metadata* Metadata)
{
UClass* Class = FindObject<UClass>(ANY_PACKAGE, *Metadata->EntityType);
return Class->IsChildOf<AActor>() ? Class : nullptr;
}
// This function is only called for client and server workers who did not spawn the Actor
AActor* USpatialReceiver::CreateActor(improbable::Position* Position, improbable::Rotation* Rotation, UClass* ActorClass, bool bDeferred)
{
FVector InitialLocation = improbable::Coordinates::ToFVector(Position->Coords);
FRotator InitialRotation = Rotation->ToFRotator();
AActor* NewActor = nullptr;
if (ActorClass)
{
//bRemoteOwned needs to be public in source code. This might be a controversial change.
FActorSpawnParameters SpawnInfo;
SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
SpawnInfo.bRemoteOwned = !NetDriver->IsServer();
SpawnInfo.bNoFail = true;
// We defer the construction in the GDK pipeline to allow initialization of replicated properties first.
SpawnInfo.bDeferConstruction = bDeferred;
FVector SpawnLocation = FRepMovement::RebaseOntoLocalOrigin(InitialLocation, World->OriginLocation);
NewActor = World->SpawnActorAbsolute(ActorClass, FTransform(InitialRotation, SpawnLocation), SpawnInfo);
check(NewActor);
}
return NewActor;
}
void USpatialReceiver::ApplyComponentData(Worker_EntityId EntityId, Worker_ComponentData& Data, USpatialActorChannel* Channel)
{
UClass* Class = TypebindingManager->FindClassByComponentId(Data.component_id);
checkf(Class, TEXT("Component %d isn't hand-written and not present in ComponentToClassMap."), Data.component_id);
UObject* TargetObject = GetTargetObjectFromChannelAndClass(Channel, Class);
if (!TargetObject)
{
return;
}
FChannelObjectPair ChannelObjectPair(Channel, TargetObject);
FClassInfo* Info = TypebindingManager->FindClassInfoByClass(Class);
check(Info);
bool bAutonomousProxy = NetDriver->GetNetMode() == NM_Client && View->GetAuthority(EntityId, Info->RPCComponents[RPC_Client] == WORKER_AUTHORITY_AUTHORITATIVE);
if (Data.component_id == Info->SingleClientComponent || Data.component_id == Info->MultiClientComponent)
{
FObjectReferencesMap& ObjectReferencesMap = UnresolvedRefsMap.FindOrAdd(ChannelObjectPair);
TSet<FUnrealObjectRef> UnresolvedRefs;
ComponentReader Reader(NetDriver, ObjectReferencesMap, UnresolvedRefs);
Reader.ApplyComponentData(Data, TargetObject, Channel, /* bIsHandover */ false);
QueueIncomingRepUpdates(ChannelObjectPair, ObjectReferencesMap, UnresolvedRefs);
}
else if (Data.component_id == Info->HandoverComponent)
{
FObjectReferencesMap& ObjectReferencesMap = UnresolvedRefsMap.FindOrAdd(ChannelObjectPair);
TSet<FUnrealObjectRef> UnresolvedRefs;
ComponentReader Reader(NetDriver, ObjectReferencesMap, UnresolvedRefs);
Reader.ApplyComponentData(Data, TargetObject, Channel, /* bIsHandover */ true);
QueueIncomingRepUpdates(ChannelObjectPair, ObjectReferencesMap, UnresolvedRefs);
}
else
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Entity: %d Component: %d - Skipping because RPC components don't have actual data."), EntityId, Data.component_id);
}
}
void USpatialReceiver::OnComponentUpdate(Worker_ComponentUpdateOp& Op)
{
if (View->GetAuthority(Op.entity_id, Op.update.component_id) == WORKER_AUTHORITY_AUTHORITATIVE)
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Entity: %d Component: %d - Skipping update because this was short circuited"), Op.entity_id, Op.update.component_id);
return;
}
switch (Op.update.component_id)
{
case SpatialConstants::ENTITY_ACL_COMPONENT_ID:
case SpatialConstants::METADATA_COMPONENT_ID:
case SpatialConstants::POSITION_COMPONENT_ID:
case SpatialConstants::PERSISTENCE_COMPONENT_ID:
case SpatialConstants::PLAYER_SPAWNER_COMPONENT_ID:
case SpatialConstants::UNREAL_METADATA_COMPONENT_ID:
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Entity: %d Component: %d - Skipping because this is hand-written Spatial component"), Op.entity_id, Op.update.component_id);
return;
case SpatialConstants::GLOBAL_STATE_MANAGER_COMPONENT_ID:
NetDriver->GlobalStateManager->ApplyUpdate(Op.update);
NetDriver->GlobalStateManager->LinkExistingSingletonActors();
return;
}
UClass* Class = TypebindingManager->FindClassByComponentId(Op.update.component_id);
if (Class == nullptr)
{
return;
}
FClassInfo* Info = TypebindingManager->FindClassInfoByClass(Class);
check(Info);
USpatialActorChannel* ActorChannel = NetDriver->GetActorChannelByEntityId(Op.entity_id);
if (ActorChannel == nullptr)
{
UE_LOG(LogSpatialReceiver, Warning, TEXT("Entity: %d Component: %d - No actor channel for update"), Op.entity_id, Op.update.component_id);
return;
}
if (Op.update.component_id == Info->SingleClientComponent || Op.update.component_id == Info->MultiClientComponent)
{
if (UObject* TargetObject = GetTargetObjectFromChannelAndClass(ActorChannel, Class))
{
ApplyComponentUpdate(Op.update, TargetObject, ActorChannel, /* bIsHandover */ false);
}
}
else if (Op.update.component_id == Info->HandoverComponent)
{
if (!NetDriver->IsServer())
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Entity: %d Component: %d - Skipping Handover component because we're a client."), Op.entity_id, Op.update.component_id);
return;
}
if (UObject* TargetObject = GetTargetObjectFromChannelAndClass(ActorChannel, Class))
{
ApplyComponentUpdate(Op.update, TargetObject, ActorChannel, /* bIsHandover */ true);
}
}
else if (Op.update.component_id == Info->RPCComponents[RPC_NetMulticast])
{
if (UObject* TargetObject = GetTargetObjectFromChannelAndClass(ActorChannel, Class))
{
if (TArray<UFunction*>* RPCArray = Info->RPCs.Find(RPC_NetMulticast))
{
ReceiveMulticastUpdate(Op.update, TargetObject, *RPCArray);
}
}
}
else
{
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Entity: %d Component: %d - Skipping because it's an empty component update from an RPC component. (most likely as a result of gaining authority)"), Op.entity_id, Op.update.component_id);
}
}
void USpatialReceiver::OnCommandRequest(Worker_CommandRequestOp& Op)
{
Schema_FieldId CommandIndex = Schema_GetCommandRequestCommandIndex(Op.request.schema_type);
UE_LOG(LogSpatialReceiver, Verbose, TEXT("Received command request (entity: %lld, component: %d, command: %d)"), Op.entity_id, Op.request.component_id, CommandIndex);
if (Op.request.component_id == SpatialConstants::PLAYER_SPAWNER_COMPONENT_ID && CommandIndex == 1)
{
Schema_Object* Payload = Schema_GetCommandRequestObject(Op.request.schema_type);
// Op.caller_attribute_set has two attributes.
// 1. The attribute of the worker type
// 2. The attribute of the specific worker that sent the request
// We want to give authority to the specific worker, so we grab the second element from the attribute set.
NetDriver->PlayerSpawner->ReceivePlayerSpawnRequest(GetStringFromSchema(Payload, 1), Op.caller_attribute_set.attributes[1], Op.request_id);
return;
}
Worker_CommandResponse Response = {};
Response.component_id = Op.request.component_id;
Response.schema_type = Schema_CreateCommandResponse(Op.request.component_id, CommandIndex);
USpatialActorChannel* ActorChannel = NetDriver->GetActorChannelByEntityId(Op.entity_id);
if (ActorChannel == nullptr)
{
UE_LOG(LogSpatialReceiver, Warning, TEXT("No actor channel for Entity %d"), Op.entity_id);
Sender->SendCommandResponse(Op.request_id, Response);
return;
}
if (UClass* Class = TypebindingManager->FindClassByComponentId(Op.request.component_id))
{
FClassInfo* Info = TypebindingManager->FindClassInfoByClass(Class);
check(Info);
if (UObject* TargetObject = GetTargetObjectFromChannelAndClass(ActorChannel, Class))
{
ERPCType RPCType = RPC_Count;
for (int i = RPC_Client; i <= RPC_CrossServer; i++)
{
if (Info->RPCComponents[i] == Op.request.component_id)
{
RPCType = (ERPCType)i;
break;
}
}
check(RPCType <= RPC_CrossServer);
const TArray<UFunction*>* RPCArray = Info->RPCs.Find(RPCType);
check(RPCArray);
check((int)CommandIndex - 1 < RPCArray->Num());
UFunction* Function = (*RPCArray)[CommandIndex - 1];
ReceiveRPCCommandRequest(Op.request, TargetObject, Function);
}
}
Sender->SendCommandResponse(Op.request_id, Response);
}
void USpatialReceiver::OnCommandResponse(Worker_CommandResponseOp& Op)
{
if (Op.entity_id == SpatialConstants::SPAWNER_ENTITY_ID && Op.response.component_id == SpatialConstants::PLAYER_SPAWNER_COMPONENT_ID)
{
NetDriver->PlayerSpawner->ReceivePlayerSpawnResponse(Op);
}
ReceiveCommandResponse(Op);
}
void USpatialReceiver::ReceiveCommandResponse(Worker_CommandResponseOp& Op)
{
TSharedRef<FPendingRPCParams>* ReliableRPCPtr = PendingReliableRPCs.Find(Op.request_id);
if (ReliableRPCPtr == nullptr)
{
// We received a response for an unreliable RPC, ignore.
return;
}
TSharedRef<FPendingRPCParams> ReliableRPC = *ReliableRPCPtr;
PendingReliableRPCs.Remove(Op.request_id);
if (Op.status_code != WORKER_STATUS_CODE_SUCCESS)
{
if (ReliableRPC->Attempts < SpatialConstants::MAX_NUMBER_COMMAND_ATTEMPTS)
{
float WaitTime = SpatialConstants::GetCommandRetryWaitTimeSeconds(ReliableRPC->Attempts);
UE_LOG(LogSpatialReceiver, Log, TEXT("%s: retrying in %f seconds. Error code: %d Message: %s"),
*ReliableRPC->Function->GetName(), WaitTime, (int)Op.status_code, UTF8_TO_TCHAR(Op.message));
if (!ReliableRPC->TargetObject.IsValid())
{
UE_LOG(LogSpatialReceiver, Warning, TEXT("%s: target object was destroyed before we could deliver the RPC."),
*ReliableRPC->Function->GetName());
return;
}
// Queue retry
FTimerHandle RetryTimer;
TimerManager->SetTimer(RetryTimer, [this, ReliableRPC]()
{
Sender->SendRPC(ReliableRPC);
}, WaitTime, false);
}
else
{
UE_LOG(LogSpatialReceiver, Error, TEXT("%s: failed too many times, giving up (%u attempts). Error code: %d Message: %s"),
*ReliableRPC->Function->GetName(), SpatialConstants::MAX_NUMBER_COMMAND_ATTEMPTS, (int)Op.status_code, UTF8_TO_TCHAR(Op.message));
}
}
}
void USpatialReceiver::ApplyComponentUpdate(const Worker_ComponentUpdate& ComponentUpdate, UObject* TargetObject, USpatialActorChannel* Channel, bool bIsHandover)
{
FChannelObjectPair ChannelObjectPair(Channel, TargetObject);
FObjectReferencesMap& ObjectReferencesMap = UnresolvedRefsMap.FindOrAdd(ChannelObjectPair);
TSet<FUnrealObjectRef> UnresolvedRefs;
ComponentReader Reader(NetDriver, ObjectReferencesMap, UnresolvedRefs);
Reader.ApplyComponentUpdate(ComponentUpdate, TargetObject, Channel, bIsHandover);
QueueIncomingRepUpdates(ChannelObjectPair, ObjectReferencesMap, UnresolvedRefs);
}
void USpatialReceiver::ReceiveMulticastUpdate(const Worker_ComponentUpdate& ComponentUpdate, UObject* TargetObject, const TArray<UFunction*>& RPCArray)
{
Schema_Object* EventsObject = Schema_GetComponentUpdateEvents(ComponentUpdate.schema_type);
for (Schema_FieldId EventIndex = 1; (int)EventIndex <= RPCArray.Num(); EventIndex++)
{
UFunction* Function = RPCArray[EventIndex - 1];
for (uint32 i = 0; i < Schema_GetObjectCount(EventsObject, EventIndex); i++)
{
Schema_Object* EventData = Schema_IndexObject(EventsObject, EventIndex, i);
TArray<uint8> PayloadData = GetPayloadFromSchema(EventData, 1);
// A bit hacky, we should probably include the number of bits with the data instead.
int64 CountBits = PayloadData.Num() * 8;
ApplyRPC(TargetObject, Function, PayloadData, CountBits);
}
}
}
void USpatialReceiver::ApplyRPC(UObject* TargetObject, UFunction* Function, TArray<uint8>& PayloadData, int64 CountBits)
{
uint8* Parms = (uint8*)FMemory_Alloca(Function->ParmsSize);
FMemory::Memzero(Parms, Function->ParmsSize);
TSet<FUnrealObjectRef> UnresolvedRefs;
FSpatialNetBitReader PayloadReader(PackageMap, PayloadData.GetData(), CountBits, UnresolvedRefs);
TSharedPtr<FRepLayout> RepLayout = NetDriver->GetFunctionRepLayout(Function);
RepLayout_ReceivePropertiesForRPC(*RepLayout, PayloadReader, Parms);
if (UnresolvedRefs.Num() == 0)
{
TargetObject->ProcessEvent(Function, Parms);
}
else
{
QueueIncomingRPC(UnresolvedRefs, TargetObject, Function, PayloadData, CountBits);
}
// Destroy the parameters.
// warning: highly dependent on UObject::ProcessEvent freeing of parms!
for (TFieldIterator<UProperty> It(Function); It && It->HasAnyPropertyFlags(CPF_Parm); ++It)
{
It->DestroyValue_InContainer(Parms);
}
}
UObject* USpatialReceiver::GetTargetObjectFromChannelAndClass(USpatialActorChannel* Channel, UClass* Class)
{
UObject* TargetObject = nullptr;
if (Class->IsChildOf<AActor>())
{
check(Channel->Actor->IsA(Class));
TargetObject = Channel->Actor;
}
else
{
FClassInfo* ActorInfo = TypebindingManager->FindClassInfoByClass(Channel->Actor->GetClass());
check(ActorInfo);
if (!ActorInfo->SubobjectClasses.Contains(Class))
{
UE_LOG(LogSpatialReceiver, Warning, TEXT("No target object for Class %s on Actor %s probably caused by dynamic component"),
*Class->GetName(), *Channel->Actor->GetName());
return nullptr;
}
TArray<UObject*> DefaultSubobjects;
Channel->Actor->GetDefaultSubobjects(DefaultSubobjects);
UObject** FoundSubobject = DefaultSubobjects.FindByPredicate([Class](const UObject* Obj)
{
return Obj->GetClass() == Class;
});
check(FoundSubobject);
TargetObject = *FoundSubobject;
}
return TargetObject;
}
void USpatialReceiver::OnReserveEntityIdResponse(Worker_ReserveEntityIdResponseOp& Op)
{
UE_LOG(LogSpatialReceiver, Log, TEXT("Received reserve entity Id: request id: %d, entity id: %lld"), Op.request_id, Op.entity_id);
if (USpatialActorChannel* Channel = PopPendingActorRequest(Op.request_id))
{
Channel->OnReserveEntityIdResponse(Op);
}
}
void USpatialReceiver::OnCreateEntityIdResponse(Worker_CreateEntityResponseOp& Op)
{
if (USpatialActorChannel* Channel = PopPendingActorRequest(Op.request_id))
{
Channel->OnCreateEntityResponse(Op);
}
}
void USpatialReceiver::AddPendingActorRequest(Worker_RequestId RequestId, USpatialActorChannel* Channel)
{
PendingActorRequests.Add(RequestId, Channel);
}
void USpatialReceiver::AddPendingReliableRPC(Worker_RequestId RequestId, TSharedRef<FPendingRPCParams> Params)
{
PendingReliableRPCs.Add(RequestId, Params);
}
USpatialActorChannel* USpatialReceiver::PopPendingActorRequest(Worker_RequestId RequestId)
{
USpatialActorChannel** ChannelPtr = PendingActorRequests.Find(RequestId);
if (ChannelPtr == nullptr)
{
return nullptr;
}
USpatialActorChannel* Channel = *ChannelPtr;
PendingActorRequests.Remove(RequestId);
return Channel;
}
void USpatialReceiver::ProcessQueuedResolvedObjects()
{
for (TPair<UObject*, FUnrealObjectRef>& It : ResolvedObjectQueue)
{
ResolvePendingOperations_Internal(It.Key, It.Value);
}
ResolvedObjectQueue.Empty();
}
void USpatialReceiver::ResolvePendingOperations(UObject* Object, const FUnrealObjectRef& ObjectRef)
{
if (bInCriticalSection)
{
ResolvedObjectQueue.Add(TPair<UObject*, FUnrealObjectRef>{ Object, ObjectRef });
}
else
{
ResolvePendingOperations_Internal(Object, ObjectRef);
}
}
void USpatialReceiver::QueueIncomingRepUpdates(FChannelObjectPair ChannelObjectPair, const FObjectReferencesMap& ObjectReferencesMap, const TSet<FUnrealObjectRef>& UnresolvedRefs)
{
for (const FUnrealObjectRef& UnresolvedRef : UnresolvedRefs)
{
UE_LOG(LogSpatialReceiver, Log, TEXT("Added pending incoming property for object ref: %s, target object: %s"), *UnresolvedRef.ToString(), *ChannelObjectPair.Value->GetName());
IncomingRefsMap.FindOrAdd(UnresolvedRef).Add(ChannelObjectPair);
}
if (ObjectReferencesMap.Num() == 0)
{
UnresolvedRefsMap.Remove(ChannelObjectPair);
}
}
void USpatialReceiver::QueueIncomingRPC(const TSet<FUnrealObjectRef>& UnresolvedRefs, UObject* TargetObject, UFunction* Function, const TArray<uint8>& PayloadData, int64 CountBits)
{
TSharedPtr<FPendingIncomingRPC> IncomingRPC = MakeShared<FPendingIncomingRPC>(UnresolvedRefs, TargetObject, Function, PayloadData, CountBits);
for (const FUnrealObjectRef& UnresolvedRef : UnresolvedRefs)
{
FIncomingRPCArray& IncomingRPCArray = IncomingRPCMap.FindOrAdd(UnresolvedRef);
IncomingRPCArray.Add(IncomingRPC);
}
}
void USpatialReceiver::ResolvePendingOperations_Internal(UObject* Object, const FUnrealObjectRef& ObjectRef)
{
UE_LOG(LogSpatialReceiver, Log, TEXT("Resolving pending object refs and RPCs which depend on object: %s %s."), *Object->GetName(), *ObjectRef.ToString());
Sender->ResolveOutgoingOperations(Object, /* bIsHandover */ false);
Sender->ResolveOutgoingOperations(Object, /* bIsHandover */ true);
ResolveIncomingOperations(Object, ObjectRef);
Sender->ResolveOutgoingRPCs(Object);
ResolveIncomingRPCs(Object, ObjectRef);
}
void USpatialReceiver::ResolveIncomingOperations(UObject* Object, const FUnrealObjectRef& ObjectRef)
{
// TODO: queue up resolved objects since they were resolved during process ops
// and then resolve all of them at the end of process ops - UNR:582
TSet<FChannelObjectPair>* TargetObjectSet = IncomingRefsMap.Find(ObjectRef);
if (!TargetObjectSet)
{
return;
}
UE_LOG(LogSpatialReceiver, Log, TEXT("Resolving incoming operations depending on object ref %s, resolved object: %s"), *ObjectRef.ToString(), *Object->GetName());
for (FChannelObjectPair& ChannelObjectPair : *TargetObjectSet)
{
FObjectReferencesMap* UnresolvedRefs = UnresolvedRefsMap.Find(ChannelObjectPair);
if (!UnresolvedRefs)
{
continue;
}
if (!ChannelObjectPair.Key.IsValid() || !ChannelObjectPair.Value.IsValid())
{
UnresolvedRefsMap.Remove(ChannelObjectPair);
continue;
}
USpatialActorChannel* DependentChannel = ChannelObjectPair.Key.Get();
UObject* ReplicatingObject = ChannelObjectPair.Value.Get();
bool bStillHasUnresolved = false;
bool bSomeObjectsWereMapped = false;
TArray<UProperty*> RepNotifies;
FRepLayout& RepLayout = DependentChannel->GetObjectRepLayout(ReplicatingObject);
FRepStateStaticBuffer& ShadowData = DependentChannel->GetObjectStaticBuffer(ReplicatingObject);
ResolveObjectReferences(RepLayout, ReplicatingObject, *UnresolvedRefs, ShadowData.GetData(), (uint8*)ReplicatingObject, ShadowData.Num(), RepNotifies, bSomeObjectsWereMapped, bStillHasUnresolved);
if (bSomeObjectsWereMapped)
{
UE_LOG(LogSpatialReceiver, Log, TEXT("Resolved for target object %s"), *ReplicatingObject->GetName());
DependentChannel->PostReceiveSpatialUpdate(ReplicatingObject, RepNotifies);
}
if (!bStillHasUnresolved)
{
UnresolvedRefsMap.Remove(ChannelObjectPair);
}
}
IncomingRefsMap.Remove(ObjectRef);
}
void USpatialReceiver::ResolveIncomingRPCs(UObject* Object, const FUnrealObjectRef& ObjectRef)
{
FIncomingRPCArray* IncomingRPCArray = IncomingRPCMap.Find(ObjectRef);
if (!IncomingRPCArray)
{
return;
}
UE_LOG(LogSpatialReceiver, Log, TEXT("Resolving incoming RPCs depending on object ref %s, resolved object: %s"), *ObjectRef.ToString(), *Object->GetName());
for (const TSharedPtr<FPendingIncomingRPC>& IncomingRPC : *IncomingRPCArray)
{
if (!IncomingRPC->TargetObject.IsValid())
{
// The target object has been destroyed before this RPC was resolved
continue;
}
IncomingRPC->UnresolvedRefs.Remove(ObjectRef);
if (IncomingRPC->UnresolvedRefs.Num() == 0)
{
ApplyRPC(IncomingRPC->TargetObject.Get(), IncomingRPC->Function, IncomingRPC->PayloadData, IncomingRPC->CountBits);
}
}
IncomingRPCMap.Remove(ObjectRef);
}
void USpatialReceiver::ResolveObjectReferences(FRepLayout& RepLayout, UObject* ReplicatedObject, FObjectReferencesMap& ObjectReferencesMap, uint8* RESTRICT StoredData, uint8* RESTRICT Data, int32 MaxAbsOffset, TArray<UProperty*>& RepNotifies, bool& bOutSomeObjectsWereMapped, bool& bOutStillHasUnresolved)
{
for (auto It = ObjectReferencesMap.CreateIterator(); It; ++It)
{
int32 AbsOffset = It.Key();
if (AbsOffset >= MaxAbsOffset)
{
UE_LOG(LogSpatialReceiver, Log, TEXT("ResolveObjectReferences: Removed unresolved reference: AbsOffset >= MaxAbsOffset: %d"), AbsOffset);
It.RemoveCurrent();
continue;
}
FObjectReferences& ObjectReferences = It.Value();
UProperty* Property = ObjectReferences.Property;
// ParentIndex is -1 for handover properties
FRepParentCmd* Parent = ObjectReferences.ParentIndex >= 0 ? &RepLayout.Parents[ObjectReferences.ParentIndex] : nullptr;
if (ObjectReferences.Array)
{
check(Property->IsA<UArrayProperty>());
Property->CopySingleValue(StoredData + AbsOffset, Data + AbsOffset);
FScriptArray* StoredArray = (FScriptArray*)(StoredData + AbsOffset);
FScriptArray* Array = (FScriptArray*)(Data + AbsOffset);
int32 NewMaxOffset = Array->Num() * Property->ElementSize;
bool bArrayHasUnresolved = false;
ResolveObjectReferences(RepLayout, ReplicatedObject, *ObjectReferences.Array, (uint8*)StoredArray->GetData(), (uint8*)Array->GetData(), NewMaxOffset, RepNotifies, bOutSomeObjectsWereMapped, bArrayHasUnresolved);
if (!bArrayHasUnresolved)
{
It.RemoveCurrent();
}
else
{
bOutStillHasUnresolved = true;
}
continue;
}
bool bResolvedSomeRefs = false;
UObject* SinglePropObject = nullptr;
for (auto UnresolvedIt = ObjectReferences.UnresolvedRefs.CreateIterator(); UnresolvedIt; ++UnresolvedIt)
{
FUnrealObjectRef& ObjectRef = *UnresolvedIt;
FNetworkGUID NetGUID = PackageMap->GetNetGUIDFromUnrealObjectRef(ObjectRef);
if (NetGUID.IsValid())
{
UObject* Object = PackageMap->GetObjectFromNetGUID(NetGUID, true);
check(Object);
UE_LOG(LogSpatialReceiver, Log, TEXT("ResolveObjectReferences: Resolved object ref: Offset: %d, Object ref: %s, PropName: %s, ObjName: %s"), AbsOffset, *ObjectRef.ToString(), *Property->GetNameCPP(), *Object->GetName());
UnresolvedIt.RemoveCurrent();
bResolvedSomeRefs = true;
if (ObjectReferences.bSingleProp)
{
SinglePropObject = Object;
}
}
}
if (bResolvedSomeRefs)
{
if (!bOutSomeObjectsWereMapped)
{
ReplicatedObject->PreNetReceive();
bOutSomeObjectsWereMapped = true;
}
if (Parent && Parent->Property->HasAnyPropertyFlags(CPF_RepNotify))
{
Property->CopySingleValue(StoredData + AbsOffset, Data + AbsOffset);
}
if (ObjectReferences.bSingleProp)
{
UObjectPropertyBase* ObjectProperty = Cast<UObjectPropertyBase>(Property);
check(ObjectProperty);
ObjectProperty->SetObjectPropertyValue(Data + AbsOffset, SinglePropObject);
}
else
{
TSet<FUnrealObjectRef> NewUnresolvedRefs;
FSpatialNetBitReader BitReader(PackageMap, ObjectReferences.Buffer.GetData(), ObjectReferences.NumBufferBits, NewUnresolvedRefs);
check(Property->IsA<UStructProperty>());
ReadStructProperty(BitReader, Cast<UStructProperty>(Property), NetDriver, Data + AbsOffset, bOutStillHasUnresolved);
}
if (Parent && Parent->Property->HasAnyPropertyFlags(CPF_RepNotify))
{
if (Parent->RepNotifyCondition == REPNOTIFY_Always || !Property->Identical(StoredData + AbsOffset, Data + AbsOffset))
{
RepNotifies.AddUnique(Parent->Property);
}
}
}
if (ObjectReferences.UnresolvedRefs.Num() > 0)
{
bOutStillHasUnresolved = true;
}
else
{
It.RemoveCurrent();
}
}
}
void USpatialReceiver::ReceiveRPCCommandRequest(const Worker_CommandRequest& CommandRequest, UObject* TargetObject, UFunction* Function)
{
Schema_Object* RequestObject = Schema_GetCommandRequestObject(CommandRequest.schema_type);
TArray<uint8> PayloadData = GetPayloadFromSchema(RequestObject, 1);
// A bit hacky, we should probably include the number of bits with the data instead.
int64 CountBits = PayloadData.Num() * 8;
ApplyRPC(TargetObject, Function, PayloadData, CountBits);
}
|
#include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
///
/// Header file
#include <Dy/Builtin/FrameBuffer/Deferred/FDyBtFbSSAOBlur.h>
#include <Dy/Builtin/Attachment/Deferred/FDyBtAtSSAOFinalOutput.h>
namespace dy::builtin
{
void FDyBtFbSSAOBlur::ConstructBuffer(_MOUT_ PDyGlFrameBufferInstanceMetaInfo& property) noexcept
{
property.mSpecifierName = sName;
property.mFrameBufferSize = DIVec2{1280, 720};
property.mIsUsingDepthBuffer = false;
property.mColorAttachmentList.emplace_back((FDyBtAtSSAOOutputFinal::sName), EDyGlAttachmentType::Color0);
}
} /// ::dy::builtin namespace
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
template <>
rdcstr DoStringise(const SDBasic &el)
{
BEGIN_ENUM_STRINGISE(SDBasic);
{
STRINGISE_ENUM_CLASS(Chunk);
STRINGISE_ENUM_CLASS(Struct);
STRINGISE_ENUM_CLASS(Array);
STRINGISE_ENUM_CLASS(Null);
STRINGISE_ENUM_CLASS(Buffer);
STRINGISE_ENUM_CLASS(String);
STRINGISE_ENUM_CLASS(Enum);
STRINGISE_ENUM_CLASS(UnsignedInteger);
STRINGISE_ENUM_CLASS(SignedInteger);
STRINGISE_ENUM_CLASS(Float);
STRINGISE_ENUM_CLASS(Boolean);
STRINGISE_ENUM_CLASS(Character);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ReplayStatus &el)
{
BEGIN_ENUM_STRINGISE(ReplayStatus)
{
STRINGISE_ENUM_CLASS_NAMED(Succeeded, "Success");
STRINGISE_ENUM_CLASS_NAMED(UnknownError, "Unknown error");
STRINGISE_ENUM_CLASS_NAMED(InternalError, "Internal error");
STRINGISE_ENUM_CLASS_NAMED(FileNotFound, "File not found");
STRINGISE_ENUM_CLASS_NAMED(InjectionFailed, "RenderDoc injection failed");
STRINGISE_ENUM_CLASS_NAMED(IncompatibleProcess, "Process is incompatible");
STRINGISE_ENUM_CLASS_NAMED(NetworkIOFailed, "Network I/O operation failed");
STRINGISE_ENUM_CLASS_NAMED(NetworkRemoteBusy, "Remote side of network connection is busy");
STRINGISE_ENUM_CLASS_NAMED(NetworkVersionMismatch, "Version mismatch between network clients");
STRINGISE_ENUM_CLASS_NAMED(FileIOFailed, "File I/O failed");
STRINGISE_ENUM_CLASS_NAMED(FileIncompatibleVersion, "File of incompatible version");
STRINGISE_ENUM_CLASS_NAMED(FileCorrupted, "File corrupted");
STRINGISE_ENUM_CLASS_NAMED(ImageUnsupported,
"The image file is recognised but the format is unsupported");
STRINGISE_ENUM_CLASS_NAMED(APIUnsupported, "API is unsupported");
STRINGISE_ENUM_CLASS_NAMED(APIInitFailed, "API initialisation failed");
STRINGISE_ENUM_CLASS_NAMED(APIIncompatibleVersion,
"Captured API data has an incompatible version");
STRINGISE_ENUM_CLASS_NAMED(
APIHardwareUnsupported,
"Current hardware unsupported or incompatible with captured hardware");
STRINGISE_ENUM_CLASS_NAMED(APIDataCorrupted,
"Replaying the capture encountered invalid/corrupted data");
STRINGISE_ENUM_CLASS_NAMED(APIReplayFailed, "Replaying the capture failed at the API level");
STRINGISE_ENUM_CLASS_NAMED(JDWPFailure, "JDWP debugger connection could not be established");
STRINGISE_ENUM_CLASS_NAMED(
AndroidGrantPermissionsFailed,
"Failed to grant runtime permissions when installing Android remote server");
STRINGISE_ENUM_CLASS_NAMED(
AndroidABINotFound,
"Couldn't determine supported ABIs when installing Android remote server");
STRINGISE_ENUM_CLASS_NAMED(
AndroidAPKFolderNotFound,
"Couldn't find the folder which contains the Android remote server APK");
STRINGISE_ENUM_CLASS_NAMED(AndroidAPKInstallFailed,
"Failed to install Android remote server for unknown reasons");
STRINGISE_ENUM_CLASS_NAMED(AndroidAPKVerifyFailed,
"Failed to verify installed Android remote server");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const WindowingSystem &el)
{
BEGIN_ENUM_STRINGISE(WindowingSystem)
{
STRINGISE_ENUM_CLASS(Unknown);
STRINGISE_ENUM_CLASS(Headless);
STRINGISE_ENUM_CLASS(Win32);
STRINGISE_ENUM_CLASS(Xlib);
STRINGISE_ENUM_CLASS(XCB);
STRINGISE_ENUM_CLASS(Android);
STRINGISE_ENUM_CLASS(MacOS);
STRINGISE_ENUM_CLASS(GGP);
STRINGISE_ENUM_CLASS(Wayland);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ResourceFormatType &el)
{
BEGIN_ENUM_STRINGISE(ResourceFormatType)
{
STRINGISE_ENUM_CLASS(Regular);
STRINGISE_ENUM_CLASS(Undefined);
STRINGISE_ENUM_CLASS(BC1);
STRINGISE_ENUM_CLASS(BC2);
STRINGISE_ENUM_CLASS(BC3);
STRINGISE_ENUM_CLASS(BC4);
STRINGISE_ENUM_CLASS(BC5);
STRINGISE_ENUM_CLASS(BC6);
STRINGISE_ENUM_CLASS(BC7);
STRINGISE_ENUM_CLASS(ETC2);
STRINGISE_ENUM_CLASS(EAC);
STRINGISE_ENUM_CLASS(ASTC);
STRINGISE_ENUM_CLASS(R10G10B10A2);
STRINGISE_ENUM_CLASS(R11G11B10);
STRINGISE_ENUM_CLASS(R5G6B5);
STRINGISE_ENUM_CLASS(R5G5B5A1);
STRINGISE_ENUM_CLASS(R9G9B9E5);
STRINGISE_ENUM_CLASS(R4G4B4A4);
STRINGISE_ENUM_CLASS(R4G4);
STRINGISE_ENUM_CLASS(D16S8);
STRINGISE_ENUM_CLASS(D24S8);
STRINGISE_ENUM_CLASS(D32S8);
STRINGISE_ENUM_CLASS(S8);
STRINGISE_ENUM_CLASS(YUV8);
STRINGISE_ENUM_CLASS(YUV10);
STRINGISE_ENUM_CLASS(YUV12);
STRINGISE_ENUM_CLASS(YUV16);
STRINGISE_ENUM_CLASS(PVRTC);
STRINGISE_ENUM_CLASS(A8);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const CompType &el)
{
BEGIN_ENUM_STRINGISE(CompType)
{
STRINGISE_ENUM_CLASS(Typeless);
STRINGISE_ENUM_CLASS(Float);
STRINGISE_ENUM_CLASS(UNorm);
STRINGISE_ENUM_CLASS(SNorm);
STRINGISE_ENUM_CLASS(UInt);
STRINGISE_ENUM_CLASS(SInt);
STRINGISE_ENUM_CLASS(UScaled);
STRINGISE_ENUM_CLASS(SScaled);
STRINGISE_ENUM_CLASS_NAMED(Depth, "Depth/Stencil");
STRINGISE_ENUM_CLASS(Double);
STRINGISE_ENUM_CLASS_NAMED(UNormSRGB, "sRGB");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const FileType &el)
{
BEGIN_ENUM_STRINGISE(FileType)
{
STRINGISE_ENUM_CLASS(DDS);
STRINGISE_ENUM_CLASS(PNG);
STRINGISE_ENUM_CLASS(JPG);
STRINGISE_ENUM_CLASS(BMP);
STRINGISE_ENUM_CLASS(TGA);
STRINGISE_ENUM_CLASS(HDR);
STRINGISE_ENUM_CLASS(EXR);
STRINGISE_ENUM_CLASS(Raw);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const AlphaMapping &el)
{
BEGIN_ENUM_STRINGISE(AlphaMapping)
{
STRINGISE_ENUM_CLASS_NAMED(Discard, "Discard");
STRINGISE_ENUM_CLASS_NAMED(BlendToColor, "Blend to Color");
STRINGISE_ENUM_CLASS_NAMED(BlendToCheckerboard, "Blend to Checkerboard");
STRINGISE_ENUM_CLASS_NAMED(Preserve, "Preserve");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const EnvMod &el)
{
BEGIN_ENUM_STRINGISE(EnvMod)
{
STRINGISE_ENUM_CLASS(Set);
STRINGISE_ENUM_CLASS(Append);
STRINGISE_ENUM_CLASS(Prepend);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const EnvSep &el)
{
BEGIN_ENUM_STRINGISE(EnvSep)
{
STRINGISE_ENUM_CLASS_NAMED(Platform, "Platform style");
STRINGISE_ENUM_CLASS_NAMED(SemiColon, "Semi-colon (;)");
STRINGISE_ENUM_CLASS_NAMED(Colon, "Colon (:)");
STRINGISE_ENUM_CLASS_NAMED(NoSep, "No Separator");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const LogType &el)
{
BEGIN_ENUM_STRINGISE(LogType)
{
STRINGISE_ENUM_CLASS(Debug);
STRINGISE_ENUM_CLASS_NAMED(Comment, "Log");
STRINGISE_ENUM_CLASS(Warning);
STRINGISE_ENUM_CLASS(Error);
STRINGISE_ENUM_CLASS(Fatal);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const Topology &el)
{
BEGIN_ENUM_STRINGISE(Topology)
{
STRINGISE_ENUM_CLASS_NAMED(Unknown, "Unknown");
STRINGISE_ENUM_CLASS_NAMED(PointList, "Point List");
STRINGISE_ENUM_CLASS_NAMED(LineList, "Line List");
STRINGISE_ENUM_CLASS_NAMED(LineStrip, "Line Strip");
STRINGISE_ENUM_CLASS_NAMED(LineLoop, "Line Loop");
STRINGISE_ENUM_CLASS_NAMED(TriangleList, "Triangle List");
STRINGISE_ENUM_CLASS_NAMED(TriangleStrip, "Triangle Strip");
STRINGISE_ENUM_CLASS_NAMED(TriangleFan, "Triangle Fan");
STRINGISE_ENUM_CLASS_NAMED(LineList_Adj, "Line List with Adjacency");
STRINGISE_ENUM_CLASS_NAMED(LineStrip_Adj, "Line Strip with Adjacency");
STRINGISE_ENUM_CLASS_NAMED(TriangleList_Adj, "Triangle List with Adjacency");
STRINGISE_ENUM_CLASS_NAMED(TriangleStrip_Adj, "Triangle Strip with Adjacency");
STRINGISE_ENUM_CLASS_NAMED(PatchList_1CPs, "Patch List 1 CP");
STRINGISE_ENUM_CLASS_NAMED(PatchList_2CPs, "Patch List 2 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_3CPs, "Patch List 3 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_4CPs, "Patch List 4 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_5CPs, "Patch List 5 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_6CPs, "Patch List 6 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_7CPs, "Patch List 7 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_8CPs, "Patch List 8 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_9CPs, "Patch List 9 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_10CPs, "Patch List 10 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_11CPs, "Patch List 11 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_12CPs, "Patch List 12 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_13CPs, "Patch List 13 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_14CPs, "Patch List 14 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_15CPs, "Patch List 15 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_16CPs, "Patch List 16 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_17CPs, "Patch List 17 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_18CPs, "Patch List 18 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_19CPs, "Patch List 19 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_20CPs, "Patch List 20 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_21CPs, "Patch List 21 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_22CPs, "Patch List 22 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_23CPs, "Patch List 23 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_24CPs, "Patch List 24 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_25CPs, "Patch List 25 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_26CPs, "Patch List 26 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_27CPs, "Patch List 27 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_28CPs, "Patch List 28 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_29CPs, "Patch List 29 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_30CPs, "Patch List 30 CPs");
STRINGISE_ENUM_CLASS_NAMED(PatchList_31CPs, "Patch List 31 CPs");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const FillMode &el)
{
BEGIN_ENUM_STRINGISE(FillMode)
{
STRINGISE_ENUM_CLASS(Solid);
STRINGISE_ENUM_CLASS(Wireframe);
STRINGISE_ENUM_CLASS(Point);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const CullMode &el)
{
BEGIN_ENUM_STRINGISE(CullMode)
{
STRINGISE_ENUM_CLASS_NAMED(NoCull, "None");
STRINGISE_ENUM_CLASS_NAMED(Front, "Front");
STRINGISE_ENUM_CLASS_NAMED(Back, "Back");
STRINGISE_ENUM_CLASS_NAMED(FrontAndBack, "Front & Back");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ConservativeRaster &el)
{
BEGIN_ENUM_STRINGISE(ConservativeRaster)
{
STRINGISE_ENUM_CLASS(Disabled);
STRINGISE_ENUM_CLASS(Underestimate);
STRINGISE_ENUM_CLASS(Overestimate);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const LineRaster &el)
{
BEGIN_ENUM_STRINGISE(LineRaster)
{
STRINGISE_ENUM_CLASS(Default);
STRINGISE_ENUM_CLASS(Rectangular);
STRINGISE_ENUM_CLASS(Bresenham);
STRINGISE_ENUM_CLASS(RectangularSmooth);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const FilterMode &el)
{
BEGIN_ENUM_STRINGISE(FilterMode)
{
STRINGISE_ENUM_CLASS_NAMED(NoFilter, "None");
STRINGISE_ENUM_CLASS_NAMED(Point, "Point");
STRINGISE_ENUM_CLASS_NAMED(Linear, "Linear");
STRINGISE_ENUM_CLASS_NAMED(Cubic, "Cubic");
STRINGISE_ENUM_CLASS_NAMED(Anisotropic, "Anisotropic");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const FilterFunction &el)
{
BEGIN_ENUM_STRINGISE(FilterFunction)
{
STRINGISE_ENUM_CLASS(Normal);
STRINGISE_ENUM_CLASS(Comparison);
STRINGISE_ENUM_CLASS(Minimum);
STRINGISE_ENUM_CLASS(Maximum);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const CompareFunction &el)
{
BEGIN_ENUM_STRINGISE(CompareFunction)
{
STRINGISE_ENUM_CLASS_NAMED(Never, "Never");
STRINGISE_ENUM_CLASS_NAMED(AlwaysTrue, "Always");
STRINGISE_ENUM_CLASS_NAMED(Less, "Less");
STRINGISE_ENUM_CLASS_NAMED(LessEqual, "Less Equal");
STRINGISE_ENUM_CLASS_NAMED(Greater, "Greater");
STRINGISE_ENUM_CLASS_NAMED(GreaterEqual, "Greater Equal");
STRINGISE_ENUM_CLASS_NAMED(Equal, "Equal");
STRINGISE_ENUM_CLASS_NAMED(NotEqual, "NotEqual");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const BlendMultiplier &el)
{
BEGIN_ENUM_STRINGISE(BlendMultiplier)
{
STRINGISE_ENUM_CLASS_NAMED(Zero, "Zero");
STRINGISE_ENUM_CLASS_NAMED(One, "One");
STRINGISE_ENUM_CLASS_NAMED(SrcCol, "Src Col");
STRINGISE_ENUM_CLASS_NAMED(InvSrcCol, "1 - Src Col");
STRINGISE_ENUM_CLASS_NAMED(DstCol, "Dst Col");
STRINGISE_ENUM_CLASS_NAMED(InvDstCol, "1 - Dst Col");
STRINGISE_ENUM_CLASS_NAMED(SrcAlpha, "Src Alpha");
STRINGISE_ENUM_CLASS_NAMED(InvSrcAlpha, "1 - Src Alpha");
STRINGISE_ENUM_CLASS_NAMED(DstAlpha, "Dst Alpha");
STRINGISE_ENUM_CLASS_NAMED(InvDstAlpha, "1 - Dst Alpha");
STRINGISE_ENUM_CLASS_NAMED(SrcAlphaSat, "Src Alpha Sat");
STRINGISE_ENUM_CLASS_NAMED(FactorRGB, "Constant RGB");
STRINGISE_ENUM_CLASS_NAMED(InvFactorRGB, "1 - Constant RGB");
STRINGISE_ENUM_CLASS_NAMED(FactorAlpha, "Constant A");
STRINGISE_ENUM_CLASS_NAMED(InvFactorAlpha, "1 - Constant A");
STRINGISE_ENUM_CLASS_NAMED(Src1Col, "Src1 Col");
STRINGISE_ENUM_CLASS_NAMED(InvSrc1Col, "1 - Src1 Col");
STRINGISE_ENUM_CLASS_NAMED(Src1Alpha, "Src1 Alpha");
STRINGISE_ENUM_CLASS_NAMED(InvSrc1Alpha, "1 - Src1 Alpha");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const BlendOperation &el)
{
BEGIN_ENUM_STRINGISE(BlendOperation)
{
STRINGISE_ENUM_CLASS_NAMED(Add, "Add");
STRINGISE_ENUM_CLASS_NAMED(Subtract, "Subtract");
STRINGISE_ENUM_CLASS_NAMED(ReversedSubtract, "Rev. Subtract");
STRINGISE_ENUM_CLASS_NAMED(Minimum, "Minimum");
STRINGISE_ENUM_CLASS_NAMED(Maximum, "Maximum");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const StencilOperation &el)
{
BEGIN_ENUM_STRINGISE(StencilOperation)
{
STRINGISE_ENUM_CLASS_NAMED(Keep, "Keep");
STRINGISE_ENUM_CLASS_NAMED(Zero, "Zero");
STRINGISE_ENUM_CLASS_NAMED(Replace, "Replace");
STRINGISE_ENUM_CLASS_NAMED(IncSat, "Inc Sat");
STRINGISE_ENUM_CLASS_NAMED(DecSat, "Dec Sat");
STRINGISE_ENUM_CLASS_NAMED(IncWrap, "Inc Wrap");
STRINGISE_ENUM_CLASS_NAMED(DecWrap, "Dec Wrap");
STRINGISE_ENUM_CLASS_NAMED(Invert, "Invert");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const LogicOperation &el)
{
BEGIN_ENUM_STRINGISE(LogicOperation)
{
STRINGISE_ENUM_CLASS_NAMED(NoOp, "No-Op");
STRINGISE_ENUM_CLASS_NAMED(Clear, "Clear");
STRINGISE_ENUM_CLASS_NAMED(Set, "Set");
STRINGISE_ENUM_CLASS_NAMED(Copy, "Copy");
STRINGISE_ENUM_CLASS_NAMED(CopyInverted, "Copy Inverted");
STRINGISE_ENUM_CLASS_NAMED(Invert, "Invert");
STRINGISE_ENUM_CLASS_NAMED(And, "And");
STRINGISE_ENUM_CLASS_NAMED(Nand, "Nand");
STRINGISE_ENUM_CLASS_NAMED(Or, "Or");
STRINGISE_ENUM_CLASS_NAMED(Xor, "Xor");
STRINGISE_ENUM_CLASS_NAMED(Nor, "Nor");
STRINGISE_ENUM_CLASS_NAMED(Equivalent, "Equivalent");
STRINGISE_ENUM_CLASS_NAMED(AndReverse, "And Reverse");
STRINGISE_ENUM_CLASS_NAMED(AndInverted, "And Inverted");
STRINGISE_ENUM_CLASS_NAMED(OrReverse, "Or Reverse");
STRINGISE_ENUM_CLASS_NAMED(OrInverted, "Or Inverted");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const QualityHint &el)
{
BEGIN_ENUM_STRINGISE(QualityHint)
{
STRINGISE_ENUM_CLASS_NAMED(DontCare, "Don't Care");
STRINGISE_ENUM_CLASS_NAMED(Nicest, "Nicest");
STRINGISE_ENUM_CLASS_NAMED(Fastest, "Fastest");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const TextureFilter &el)
{
rdcstr filter = "";
rdcstr filtPrefix = "";
rdcstr filtVal = "";
rdcstr filters[] = {ToStr(el.minify), ToStr(el.magnify), ToStr(el.mip)};
rdcstr filterPrefixes[] = {"Min", "Mag", "Mip"};
for(int a = 0; a < 3; a++)
{
if(a == 0 || filters[a] == filters[a - 1])
{
if(filtPrefix != "")
filtPrefix += "&";
filtPrefix += filterPrefixes[a];
}
else
{
filter += filtPrefix + ": " + filtVal + ", ";
filtPrefix = filterPrefixes[a];
}
filtVal = filters[a];
}
filter += filtPrefix + ": " + filtVal;
return filter;
}
template <>
rdcstr DoStringise(const AddressMode &el)
{
BEGIN_ENUM_STRINGISE(AddressMode);
{
STRINGISE_ENUM_CLASS(Wrap);
STRINGISE_ENUM_CLASS(Mirror);
STRINGISE_ENUM_CLASS(MirrorOnce);
STRINGISE_ENUM_CLASS(ClampEdge);
STRINGISE_ENUM_CLASS(ClampBorder);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const YcbcrConversion &el)
{
BEGIN_ENUM_STRINGISE(YcbcrConversion);
{
STRINGISE_ENUM_CLASS(Raw);
STRINGISE_ENUM_CLASS_NAMED(RangeOnly, "Range Only");
STRINGISE_ENUM_CLASS_NAMED(BT709, "BT.709");
STRINGISE_ENUM_CLASS_NAMED(BT601, "BT.601");
STRINGISE_ENUM_CLASS_NAMED(BT2020, "BT.2020");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const YcbcrRange &el)
{
BEGIN_ENUM_STRINGISE(YcbcrRange);
{
STRINGISE_ENUM_CLASS_NAMED(ITUFull, "Full");
STRINGISE_ENUM_CLASS_NAMED(ITUNarrow, "Narrow");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ChromaSampleLocation &el)
{
BEGIN_ENUM_STRINGISE(ChromaSampleLocation);
{
STRINGISE_ENUM_CLASS_NAMED(CositedEven, "Even");
STRINGISE_ENUM_CLASS_NAMED(Midpoint, "Mid");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ResourceType &el)
{
BEGIN_ENUM_STRINGISE(ResourceType)
{
STRINGISE_ENUM_CLASS(Unknown);
STRINGISE_ENUM_CLASS(Device);
STRINGISE_ENUM_CLASS(Queue);
STRINGISE_ENUM_CLASS(CommandBuffer);
STRINGISE_ENUM_CLASS(Texture);
STRINGISE_ENUM_CLASS(Buffer);
STRINGISE_ENUM_CLASS(View);
STRINGISE_ENUM_CLASS(Sampler);
STRINGISE_ENUM_CLASS(SwapchainImage);
STRINGISE_ENUM_CLASS(Memory);
STRINGISE_ENUM_CLASS(Shader);
STRINGISE_ENUM_CLASS(ShaderBinding);
STRINGISE_ENUM_CLASS(PipelineState);
STRINGISE_ENUM_CLASS(StateObject);
STRINGISE_ENUM_CLASS(RenderPass);
STRINGISE_ENUM_CLASS(Query);
STRINGISE_ENUM_CLASS(Sync);
STRINGISE_ENUM_CLASS(Pool);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const TextureType &el)
{
BEGIN_ENUM_STRINGISE(TextureType)
{
STRINGISE_ENUM_CLASS_NAMED(Unknown, "Unknown");
STRINGISE_ENUM_CLASS_NAMED(Buffer, "Buffer");
STRINGISE_ENUM_CLASS_NAMED(Texture1D, "Texture 1D");
STRINGISE_ENUM_CLASS_NAMED(Texture1DArray, "Texture 1D Array");
STRINGISE_ENUM_CLASS_NAMED(Texture2D, "Texture 2D");
STRINGISE_ENUM_CLASS_NAMED(TextureRect, "Texture Rect");
STRINGISE_ENUM_CLASS_NAMED(Texture2DArray, "Texture 2D Array");
STRINGISE_ENUM_CLASS_NAMED(Texture2DMS, "Texture 2D MS");
STRINGISE_ENUM_CLASS_NAMED(Texture2DMSArray, "Texture 2D MS Array");
STRINGISE_ENUM_CLASS_NAMED(Texture3D, "Texture 3D");
STRINGISE_ENUM_CLASS_NAMED(TextureCube, "Texture Cube");
STRINGISE_ENUM_CLASS_NAMED(TextureCubeArray, "Texture Cube Array");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ShaderBuiltin &el)
{
BEGIN_ENUM_STRINGISE(ShaderBuiltin)
{
STRINGISE_ENUM_CLASS_NAMED(Undefined, "Undefined");
STRINGISE_ENUM_CLASS_NAMED(Position, "Position");
STRINGISE_ENUM_CLASS_NAMED(PointSize, "Point Size");
STRINGISE_ENUM_CLASS_NAMED(ClipDistance, "Clip Distance");
STRINGISE_ENUM_CLASS_NAMED(CullDistance, "Cull Distance");
STRINGISE_ENUM_CLASS_NAMED(RTIndex, "RT Index");
STRINGISE_ENUM_CLASS_NAMED(ViewportIndex, "Viewport Index");
STRINGISE_ENUM_CLASS_NAMED(VertexIndex, "Vertex Index");
STRINGISE_ENUM_CLASS_NAMED(PrimitiveIndex, "Primitive Index");
STRINGISE_ENUM_CLASS_NAMED(InstanceIndex, "Instance Index");
STRINGISE_ENUM_CLASS_NAMED(DispatchSize, "Dispatch Size");
STRINGISE_ENUM_CLASS_NAMED(DispatchThreadIndex, "Dispatch Thread Index");
STRINGISE_ENUM_CLASS_NAMED(GroupIndex, "Group Index");
STRINGISE_ENUM_CLASS_NAMED(GroupSize, "Group Size");
STRINGISE_ENUM_CLASS_NAMED(GroupFlatIndex, "Group Flat Index");
STRINGISE_ENUM_CLASS_NAMED(GroupThreadIndex, "Group Thread Index");
STRINGISE_ENUM_CLASS_NAMED(GSInstanceIndex, "GS Instance Index");
STRINGISE_ENUM_CLASS_NAMED(OutputControlPointIndex, "Output Control Point Index");
STRINGISE_ENUM_CLASS_NAMED(DomainLocation, "Domain Location");
STRINGISE_ENUM_CLASS_NAMED(IsFrontFace, "Is FrontFace");
STRINGISE_ENUM_CLASS_NAMED(MSAACoverage, "MSAA Coverage");
STRINGISE_ENUM_CLASS_NAMED(MSAASamplePosition, "MSAA Sample Position");
STRINGISE_ENUM_CLASS_NAMED(MSAASampleIndex, "MSAA Sample Index");
STRINGISE_ENUM_CLASS_NAMED(PatchNumVertices, "Patch NumVertices");
STRINGISE_ENUM_CLASS_NAMED(OuterTessFactor, "Outer TessFactor");
STRINGISE_ENUM_CLASS_NAMED(InsideTessFactor, "Inside TessFactor");
STRINGISE_ENUM_CLASS_NAMED(ColorOutput, "Color Output");
STRINGISE_ENUM_CLASS_NAMED(DepthOutput, "Depth Output");
STRINGISE_ENUM_CLASS_NAMED(DepthOutputGreaterEqual, "Depth Output (GEqual)");
STRINGISE_ENUM_CLASS_NAMED(DepthOutputLessEqual, "Depth Output (LEqual)");
STRINGISE_ENUM_CLASS_NAMED(BaseVertex, "Base Vertex");
STRINGISE_ENUM_CLASS_NAMED(BaseInstance, "Base Instance");
STRINGISE_ENUM_CLASS_NAMED(DrawIndex, "Draw Index");
STRINGISE_ENUM_CLASS_NAMED(StencilReference, "Stencil Ref Value");
STRINGISE_ENUM_CLASS_NAMED(PointCoord, "Point Co-ord");
STRINGISE_ENUM_CLASS_NAMED(IsHelper, "Is Helper");
STRINGISE_ENUM_CLASS_NAMED(SubgroupSize, "Subgroup Size");
STRINGISE_ENUM_CLASS_NAMED(NumSubgroups, "Num Subgroups");
STRINGISE_ENUM_CLASS_NAMED(SubgroupIndexInWorkgroup, "Subgroup Index in Workgroup");
STRINGISE_ENUM_CLASS_NAMED(IndexInSubgroup, "Index in Subgroup");
STRINGISE_ENUM_CLASS_NAMED(SubgroupEqualMask, "Subgroup Equal Mask");
STRINGISE_ENUM_CLASS_NAMED(SubgroupGreaterEqualMask, "Subgroup Greater-Equal Mask");
STRINGISE_ENUM_CLASS_NAMED(SubgroupGreaterMask, "Subgroup Greater Mask");
STRINGISE_ENUM_CLASS_NAMED(SubgroupLessEqualMask, "Subgroup Less-Equal Mask");
STRINGISE_ENUM_CLASS_NAMED(SubgroupLessMask, "Subgroup Less Mask");
STRINGISE_ENUM_CLASS_NAMED(DeviceIndex, "Device Index");
STRINGISE_ENUM_CLASS_NAMED(IsFullyCovered, "Is Fully Covered");
STRINGISE_ENUM_CLASS_NAMED(FragAreaSize, "Fragment Area Size");
STRINGISE_ENUM_CLASS_NAMED(FragInvocationCount, "Fragment Invocation Count");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const BindType &el)
{
BEGIN_ENUM_STRINGISE(BindType)
{
STRINGISE_ENUM_CLASS_NAMED(ConstantBuffer, "Constants");
STRINGISE_ENUM_CLASS_NAMED(Sampler, "Sampler");
STRINGISE_ENUM_CLASS_NAMED(ImageSampler, "Image&Sampler");
STRINGISE_ENUM_CLASS_NAMED(ReadOnlyImage, "Image");
STRINGISE_ENUM_CLASS_NAMED(ReadWriteImage, "RW Image");
STRINGISE_ENUM_CLASS_NAMED(ReadOnlyTBuffer, "TexBuffer");
STRINGISE_ENUM_CLASS_NAMED(ReadWriteTBuffer, "RW TexBuffer");
STRINGISE_ENUM_CLASS_NAMED(ReadOnlyBuffer, "Buffer");
STRINGISE_ENUM_CLASS_NAMED(ReadWriteBuffer, "RW Buffer");
STRINGISE_ENUM_CLASS_NAMED(ReadOnlyResource, "Resource");
STRINGISE_ENUM_CLASS_NAMED(ReadWriteResource, "RW Resource");
STRINGISE_ENUM_CLASS_NAMED(InputAttachment, "Input");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const MessageSource &el)
{
BEGIN_ENUM_STRINGISE(MessageSource)
{
STRINGISE_ENUM_CLASS_NAMED(API, "API");
STRINGISE_ENUM_CLASS_NAMED(RedundantAPIUse, "Redundant API Use");
STRINGISE_ENUM_CLASS_NAMED(IncorrectAPIUse, "Incorrect API Use");
STRINGISE_ENUM_CLASS_NAMED(GeneralPerformance, "General Performance");
STRINGISE_ENUM_CLASS_NAMED(GCNPerformance, "GCN Performance");
STRINGISE_ENUM_CLASS_NAMED(RuntimeWarning, "Runtime Warning");
STRINGISE_ENUM_CLASS_NAMED(UnsupportedConfiguration, "Unsupported Configuration");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const MessageSeverity &el)
{
BEGIN_ENUM_STRINGISE(MessageSeverity)
{
STRINGISE_ENUM_CLASS(High);
STRINGISE_ENUM_CLASS(Medium);
STRINGISE_ENUM_CLASS(Low);
STRINGISE_ENUM_CLASS(Info);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const MessageCategory &el)
{
BEGIN_ENUM_STRINGISE(MessageCategory)
{
STRINGISE_ENUM_CLASS_NAMED(Application_Defined, "Application Defined");
STRINGISE_ENUM_CLASS_NAMED(Miscellaneous, "Miscellaneous");
STRINGISE_ENUM_CLASS_NAMED(Initialization, "Initialization");
STRINGISE_ENUM_CLASS_NAMED(Cleanup, "Cleanup");
STRINGISE_ENUM_CLASS_NAMED(Compilation, "Compilation");
STRINGISE_ENUM_CLASS_NAMED(State_Creation, "State Creation");
STRINGISE_ENUM_CLASS_NAMED(State_Setting, "State Setting");
STRINGISE_ENUM_CLASS_NAMED(State_Getting, "State Getting");
STRINGISE_ENUM_CLASS_NAMED(Resource_Manipulation, "Resource Manipulation");
STRINGISE_ENUM_CLASS_NAMED(Execution, "Execution");
STRINGISE_ENUM_CLASS_NAMED(Shaders, "Shaders");
STRINGISE_ENUM_CLASS_NAMED(Deprecated, "Deprecated");
STRINGISE_ENUM_CLASS_NAMED(Undefined, "Undefined");
STRINGISE_ENUM_CLASS_NAMED(Portability, "Portability");
STRINGISE_ENUM_CLASS_NAMED(Performance, "Performance");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const TextureSwizzle &el)
{
BEGIN_ENUM_STRINGISE(TextureSwizzle)
{
STRINGISE_ENUM_CLASS_NAMED(Red, "R");
STRINGISE_ENUM_CLASS_NAMED(Green, "G");
STRINGISE_ENUM_CLASS_NAMED(Blue, "B");
STRINGISE_ENUM_CLASS_NAMED(Alpha, "A");
STRINGISE_ENUM_CLASS_NAMED(Zero, "0");
STRINGISE_ENUM_CLASS_NAMED(One, "1");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ResourceUsage &el)
{
BEGIN_ENUM_STRINGISE(ResourceUsage)
{
STRINGISE_ENUM_CLASS_NAMED(Unused, "Unused");
STRINGISE_ENUM_CLASS_NAMED(VertexBuffer, "Vertex Buffer");
STRINGISE_ENUM_CLASS_NAMED(IndexBuffer, "Index Buffer");
STRINGISE_ENUM_CLASS_NAMED(VS_Constants, "VS - Constants");
STRINGISE_ENUM_CLASS_NAMED(HS_Constants, "HS - Constants");
STRINGISE_ENUM_CLASS_NAMED(DS_Constants, "DS - Constants");
STRINGISE_ENUM_CLASS_NAMED(GS_Constants, "GS - Constants");
STRINGISE_ENUM_CLASS_NAMED(PS_Constants, "PS - Constants");
STRINGISE_ENUM_CLASS_NAMED(CS_Constants, "CS - Constants");
STRINGISE_ENUM_CLASS_NAMED(All_Constants, "All Stages - Constants");
STRINGISE_ENUM_CLASS_NAMED(StreamOut, "Stream-Out");
STRINGISE_ENUM_CLASS_NAMED(VS_Resource, "VS - Read-only Resource");
STRINGISE_ENUM_CLASS_NAMED(HS_Resource, "HS - Read-only Resource");
STRINGISE_ENUM_CLASS_NAMED(DS_Resource, "DS - Read-only Resource");
STRINGISE_ENUM_CLASS_NAMED(GS_Resource, "GS - Read-only Resource");
STRINGISE_ENUM_CLASS_NAMED(PS_Resource, "PS - Read-only Resource");
STRINGISE_ENUM_CLASS_NAMED(CS_Resource, "CS - Read-only Resource");
STRINGISE_ENUM_CLASS_NAMED(All_Resource, "All Stages - Read-only Resource");
STRINGISE_ENUM_CLASS_NAMED(VS_RWResource, "VS - Read-write Resource");
STRINGISE_ENUM_CLASS_NAMED(HS_RWResource, "HS - Read-write Resource");
STRINGISE_ENUM_CLASS_NAMED(DS_RWResource, "DS - Read-write Resource");
STRINGISE_ENUM_CLASS_NAMED(GS_RWResource, "GS - Read-write Resource");
STRINGISE_ENUM_CLASS_NAMED(PS_RWResource, "PS - Read-write Resource");
STRINGISE_ENUM_CLASS_NAMED(CS_RWResource, "CS - Read-write Resource");
STRINGISE_ENUM_CLASS_NAMED(All_RWResource, "All Stages - Read-write Resource");
STRINGISE_ENUM_CLASS_NAMED(InputTarget, "Input target");
STRINGISE_ENUM_CLASS_NAMED(ColorTarget, "Color target");
STRINGISE_ENUM_CLASS_NAMED(DepthStencilTarget, "Depth/stencil target");
STRINGISE_ENUM_CLASS_NAMED(Indirect, "Indirect parameters");
STRINGISE_ENUM_CLASS_NAMED(Clear, "Clear");
STRINGISE_ENUM_CLASS_NAMED(GenMips, "Mip Generation");
STRINGISE_ENUM_CLASS_NAMED(Resolve, "Resolve - Source&Dest");
STRINGISE_ENUM_CLASS_NAMED(ResolveSrc, "Resolve - Source");
STRINGISE_ENUM_CLASS_NAMED(ResolveDst, "Resolve - Destination");
STRINGISE_ENUM_CLASS_NAMED(Copy, "Copy - Source&Dest");
STRINGISE_ENUM_CLASS_NAMED(CopySrc, "Copy - Source");
STRINGISE_ENUM_CLASS_NAMED(CopyDst, "Copy - Destination");
STRINGISE_ENUM_CLASS_NAMED(Barrier, "Barrier");
STRINGISE_ENUM_CLASS_NAMED(CPUWrite, "CPU Write");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const VarType &el)
{
BEGIN_ENUM_STRINGISE(VarType)
{
STRINGISE_ENUM_CLASS_NAMED(Float, "float");
STRINGISE_ENUM_CLASS_NAMED(Double, "double");
STRINGISE_ENUM_CLASS_NAMED(Half, "half");
STRINGISE_ENUM_CLASS_NAMED(SInt, "int");
STRINGISE_ENUM_CLASS_NAMED(UInt, "uint");
STRINGISE_ENUM_CLASS_NAMED(SShort, "short");
STRINGISE_ENUM_CLASS_NAMED(UShort, "ushort");
STRINGISE_ENUM_CLASS_NAMED(SLong, "long");
STRINGISE_ENUM_CLASS_NAMED(ULong, "ulong");
STRINGISE_ENUM_CLASS_NAMED(SByte, "byte");
STRINGISE_ENUM_CLASS_NAMED(UByte, "ubyte");
STRINGISE_ENUM_CLASS_NAMED(Unknown, "unknown");
STRINGISE_ENUM_CLASS_NAMED(GPUPointer, "pointer");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const DebugVariableType &el)
{
BEGIN_ENUM_STRINGISE(DebugVariableType)
{
STRINGISE_ENUM_CLASS(Undefined);
STRINGISE_ENUM_CLASS(Input);
STRINGISE_ENUM_CLASS(Constant);
STRINGISE_ENUM_CLASS(Variable);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const GPUCounter &el)
{
if(IsAMDCounter(el))
return "AMD Counter " + ToStr((uint32_t)el);
if(IsNvidiaCounter(el))
return "Nvidia Counter " + ToStr((uint32_t)el);
if(IsIntelCounter(el))
return "Intel Counter " + ToStr((uint32_t)el);
BEGIN_ENUM_STRINGISE(GPUCounter)
{
STRINGISE_ENUM_CLASS(EventGPUDuration);
STRINGISE_ENUM_CLASS(InputVerticesRead);
STRINGISE_ENUM_CLASS(IAPrimitives);
STRINGISE_ENUM_CLASS(GSPrimitives);
STRINGISE_ENUM_CLASS(RasterizerInvocations);
STRINGISE_ENUM_CLASS(RasterizedPrimitives);
STRINGISE_ENUM_CLASS(SamplesPassed);
STRINGISE_ENUM_CLASS(VSInvocations);
STRINGISE_ENUM_CLASS(HSInvocations);
STRINGISE_ENUM_CLASS(DSInvocations);
STRINGISE_ENUM_CLASS(GSInvocations);
STRINGISE_ENUM_CLASS(PSInvocations);
STRINGISE_ENUM_CLASS(CSInvocations);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const CounterUnit &el)
{
BEGIN_ENUM_STRINGISE(CounterUnit)
{
STRINGISE_ENUM_CLASS(Absolute);
STRINGISE_ENUM_CLASS(Seconds);
STRINGISE_ENUM_CLASS(Percentage);
STRINGISE_ENUM_CLASS(Ratio);
STRINGISE_ENUM_CLASS(Bytes);
STRINGISE_ENUM_CLASS(Cycles);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ShaderStage &el)
{
BEGIN_ENUM_STRINGISE(ShaderStage)
{
STRINGISE_ENUM_CLASS(Vertex);
STRINGISE_ENUM_CLASS(Hull);
STRINGISE_ENUM_CLASS(Domain);
STRINGISE_ENUM_CLASS(Geometry);
STRINGISE_ENUM_CLASS(Pixel);
STRINGISE_ENUM_CLASS(Compute);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const MeshDataStage &el)
{
BEGIN_ENUM_STRINGISE(MeshDataStage)
{
STRINGISE_ENUM_CLASS(Unknown);
STRINGISE_ENUM_CLASS(VSIn);
STRINGISE_ENUM_CLASS(VSOut);
STRINGISE_ENUM_CLASS(GSOut);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const DebugOverlay &el)
{
BEGIN_ENUM_STRINGISE(DebugOverlay)
{
STRINGISE_ENUM_CLASS(NoOverlay);
STRINGISE_ENUM_CLASS(Drawcall);
STRINGISE_ENUM_CLASS(Wireframe);
STRINGISE_ENUM_CLASS(Depth);
STRINGISE_ENUM_CLASS(Stencil);
STRINGISE_ENUM_CLASS(BackfaceCull);
STRINGISE_ENUM_CLASS(ViewportScissor);
STRINGISE_ENUM_CLASS(NaN);
STRINGISE_ENUM_CLASS(Clipping);
STRINGISE_ENUM_CLASS(ClearBeforePass);
STRINGISE_ENUM_CLASS(ClearBeforeDraw);
STRINGISE_ENUM_CLASS(QuadOverdrawPass);
STRINGISE_ENUM_CLASS(QuadOverdrawDraw);
STRINGISE_ENUM_CLASS(TriangleSizePass);
STRINGISE_ENUM_CLASS(TriangleSizeDraw);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const GPUVendor &el)
{
BEGIN_ENUM_STRINGISE(GPUVendor)
{
STRINGISE_ENUM_CLASS(Unknown);
STRINGISE_ENUM_CLASS(ARM);
STRINGISE_ENUM_CLASS(AMD);
STRINGISE_ENUM_CLASS(Broadcom);
STRINGISE_ENUM_CLASS(Imagination);
STRINGISE_ENUM_CLASS(Intel);
STRINGISE_ENUM_CLASS(nVidia);
STRINGISE_ENUM_CLASS(Qualcomm);
STRINGISE_ENUM_CLASS(Verisilicon);
STRINGISE_ENUM_CLASS(Software);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const GraphicsAPI &el)
{
BEGIN_ENUM_STRINGISE(GraphicsAPI)
{
STRINGISE_ENUM_CLASS(D3D11);
STRINGISE_ENUM_CLASS(D3D12);
STRINGISE_ENUM_CLASS(OpenGL);
STRINGISE_ENUM_CLASS(Vulkan);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ShaderEncoding &el)
{
BEGIN_ENUM_STRINGISE(ShaderEncoding)
{
STRINGISE_ENUM_CLASS(Unknown);
STRINGISE_ENUM_CLASS(DXBC);
STRINGISE_ENUM_CLASS(GLSL);
STRINGISE_ENUM_CLASS_NAMED(SPIRV, "SPIR-V");
STRINGISE_ENUM_CLASS_NAMED(SPIRVAsm, "SPIR-V Asm");
STRINGISE_ENUM_CLASS(HLSL);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const SectionType &el)
{
BEGIN_ENUM_STRINGISE(SectionType);
{
STRINGISE_ENUM_CLASS_NAMED(FrameCapture, "renderdoc/internal/framecapture");
STRINGISE_ENUM_CLASS_NAMED(ResolveDatabase, "renderdoc/internal/resolvedb");
STRINGISE_ENUM_CLASS_NAMED(Bookmarks, "renderdoc/ui/bookmarks");
STRINGISE_ENUM_CLASS_NAMED(Notes, "renderdoc/ui/notes");
STRINGISE_ENUM_CLASS_NAMED(ResourceRenames, "renderdoc/ui/resrenames");
STRINGISE_ENUM_CLASS_NAMED(AMDRGPProfile, "amd/rgp/profile");
STRINGISE_ENUM_CLASS_NAMED(ExtendedThumbnail, "renderdoc/internal/exthumb");
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const ReplayOptimisationLevel &el)
{
BEGIN_ENUM_STRINGISE(ReplayOptimisationLevel);
{
STRINGISE_ENUM_CLASS_NAMED(NoOptimisation, "No Optimisation");
STRINGISE_ENUM_CLASS(Conservative);
STRINGISE_ENUM_CLASS(Balanced);
STRINGISE_ENUM_CLASS(Fastest);
}
END_ENUM_STRINGISE();
}
template <>
rdcstr DoStringise(const D3DBufferViewFlags &el)
{
BEGIN_BITFIELD_STRINGISE(D3DBufferViewFlags);
{
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(NoFlags, "");
STRINGISE_BITFIELD_CLASS_BIT(Raw);
STRINGISE_BITFIELD_CLASS_BIT(Append);
STRINGISE_BITFIELD_CLASS_BIT(Counter);
}
END_BITFIELD_STRINGISE();
}
template <>
rdcstr DoStringise(const PathProperty &el)
{
BEGIN_BITFIELD_STRINGISE(PathProperty);
{
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(ErrorUnknown, "Unknown Error");
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(ErrorAccessDenied, "Access Denied");
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(ErrorInvalidPath, "Invalid Path");
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(NoFlags, "No Flags");
STRINGISE_BITFIELD_CLASS_BIT(Directory);
STRINGISE_BITFIELD_CLASS_BIT(Hidden);
STRINGISE_BITFIELD_CLASS_BIT(Executable);
}
END_BITFIELD_STRINGISE();
}
template <>
rdcstr DoStringise(const SectionFlags &el)
{
BEGIN_BITFIELD_STRINGISE(SectionFlags);
{
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(NoFlags, "No Flags");
STRINGISE_BITFIELD_CLASS_BIT_NAMED(ASCIIStored, "Stored as ASCII");
STRINGISE_BITFIELD_CLASS_BIT_NAMED(LZ4Compressed, "Compressed with LZ4");
STRINGISE_BITFIELD_CLASS_BIT_NAMED(ZstdCompressed, "Compressed with Zstd");
}
END_BITFIELD_STRINGISE();
}
template <>
rdcstr DoStringise(const ShaderEvents &el)
{
BEGIN_BITFIELD_STRINGISE(ShaderEvents);
{
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(NoEvent, "None");
STRINGISE_BITFIELD_CLASS_BIT(SampleLoadGather);
STRINGISE_BITFIELD_CLASS_BIT(GeneratedNanOrInf);
}
END_BITFIELD_STRINGISE();
}
template <>
rdcstr DoStringise(const TextureCategory &el)
{
BEGIN_BITFIELD_STRINGISE(TextureCategory);
{
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(NoFlags, "None");
STRINGISE_BITFIELD_CLASS_BIT(ShaderRead);
STRINGISE_BITFIELD_CLASS_BIT(ColorTarget);
STRINGISE_BITFIELD_CLASS_BIT(DepthTarget);
STRINGISE_BITFIELD_CLASS_BIT(ShaderReadWrite);
STRINGISE_BITFIELD_CLASS_BIT(SwapBuffer);
}
END_BITFIELD_STRINGISE();
}
template <>
rdcstr DoStringise(const BufferCategory &el)
{
BEGIN_BITFIELD_STRINGISE(BufferCategory);
{
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(NoFlags, "None");
STRINGISE_BITFIELD_CLASS_BIT(Vertex);
STRINGISE_BITFIELD_CLASS_BIT(Index);
STRINGISE_BITFIELD_CLASS_BIT(Constants);
STRINGISE_BITFIELD_CLASS_BIT(ReadWrite);
STRINGISE_BITFIELD_CLASS_BIT(Indirect);
}
END_BITFIELD_STRINGISE();
}
template <>
rdcstr DoStringise(const DrawFlags &el)
{
BEGIN_BITFIELD_STRINGISE(DrawFlags);
{
STRINGISE_BITFIELD_CLASS_VALUE_NAMED(NoFlags, "None");
STRINGISE_BITFIELD_CLASS_BIT(Clear);
STRINGISE_BITFIELD_CLASS_BIT(Drawcall);
STRINGISE_BITFIELD_CLASS_BIT(Dispatch);
STRINGISE_BITFIELD_CLASS_BIT(CmdList);
STRINGISE_BITFIELD_CLASS_BIT(SetMarker);
STRINGISE_BITFIELD_CLASS_BIT(PushMarker);
STRINGISE_BITFIELD_CLASS_BIT(PopMarker);
STRINGISE_BITFIELD_CLASS_BIT(Present);
STRINGISE_BITFIELD_CLASS_BIT(MultiDraw);
STRINGISE_BITFIELD_CLASS_BIT(Copy);
STRINGISE_BITFIELD_CLASS_BIT(Resolve);
STRINGISE_BITFIELD_CLASS_BIT(GenMips);
STRINGISE_BITFIELD_CLASS_BIT(PassBoundary);
STRINGISE_BITFIELD_CLASS_BIT(Indexed);
STRINGISE_BITFIELD_CLASS_BIT(Instanced);
STRINGISE_BITFIELD_CLASS_BIT(Auto);
STRINGISE_BITFIELD_CLASS_BIT(Indirect);
STRINGISE_BITFIELD_CLASS_BIT(ClearColor);
STRINGISE_BITFIELD_CLASS_BIT(ClearDepthStencil);
STRINGISE_BITFIELD_CLASS_BIT(BeginPass);
STRINGISE_BITFIELD_CLASS_BIT(EndPass);
STRINGISE_BITFIELD_CLASS_BIT(APICalls);
}
END_BITFIELD_STRINGISE();
}
template <>
rdcstr DoStringise(const ShaderStageMask &el)
{
BEGIN_BITFIELD_STRINGISE(ShaderStageMask);
{
STRINGISE_BITFIELD_CLASS_VALUE(Unknown);
STRINGISE_BITFIELD_CLASS_VALUE(All);
STRINGISE_BITFIELD_CLASS_BIT(Vertex);
STRINGISE_BITFIELD_CLASS_BIT(Hull);
STRINGISE_BITFIELD_CLASS_BIT(Domain);
STRINGISE_BITFIELD_CLASS_BIT(Geometry);
STRINGISE_BITFIELD_CLASS_BIT(Pixel);
STRINGISE_BITFIELD_CLASS_BIT(Compute);
}
END_BITFIELD_STRINGISE();
}
|
//===- YAMLRemarkSerializer.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 provides the implementation of the YAML remark serializer using
// LLVM's YAMLTraits.
//
//===----------------------------------------------------------------------===//
#include "llvm/Remarks/YAMLRemarkSerializer.h"
#include "llvm/Remarks/Remark.h"
#include "llvm/Support/FileSystem.h"
using namespace llvm;
using namespace llvm::remarks;
// Use the same keys whether we use a string table or not (respectively, T is an
// unsigned or a StringRef).
template <typename T>
static void mapRemarkHeader(yaml::IO &io, T PassName, T RemarkName,
Optional<RemarkLocation> RL, T FunctionName,
Optional<uint64_t> Hotness,
ArrayRef<Argument> Args) {
io.mapRequired("Pass", PassName);
io.mapRequired("Name", RemarkName);
io.mapOptional("DebugLoc", RL);
io.mapRequired("Function", FunctionName);
io.mapOptional("Hotness", Hotness);
io.mapOptional("Args", Args);
}
namespace llvm {
namespace yaml {
template <> struct MappingTraits<remarks::Remark *> {
static void mapping(IO &io, remarks::Remark *&Remark) {
assert(io.outputting() && "input not yet implemented");
if (io.mapTag("!Passed", (Remark->RemarkType == Type::Passed)))
;
else if (io.mapTag("!Missed", (Remark->RemarkType == Type::Missed)))
;
else if (io.mapTag("!Analysis", (Remark->RemarkType == Type::Analysis)))
;
else if (io.mapTag("!AnalysisFPCommute",
(Remark->RemarkType == Type::AnalysisFPCommute)))
;
else if (io.mapTag("!AnalysisAliasing",
(Remark->RemarkType == Type::AnalysisAliasing)))
;
else if (io.mapTag("!Failure", (Remark->RemarkType == Type::Failure)))
;
else
llvm_unreachable("Unknown remark type");
if (auto *Serializer = dyn_cast<YAMLStrTabRemarkSerializer>(
reinterpret_cast<RemarkSerializer *>(io.getContext()))) {
assert(Serializer->StrTab.hasValue() &&
"YAMLStrTabSerializer with no StrTab.");
StringTable &StrTab = *Serializer->StrTab;
unsigned PassID = StrTab.add(Remark->PassName).first;
unsigned NameID = StrTab.add(Remark->RemarkName).first;
unsigned FunctionID = StrTab.add(Remark->FunctionName).first;
mapRemarkHeader(io, PassID, NameID, Remark->Loc, FunctionID,
Remark->Hotness, Remark->Args);
} else {
mapRemarkHeader(io, Remark->PassName, Remark->RemarkName, Remark->Loc,
Remark->FunctionName, Remark->Hotness, Remark->Args);
}
}
};
template <> struct MappingTraits<RemarkLocation> {
static void mapping(IO &io, RemarkLocation &RL) {
assert(io.outputting() && "input not yet implemented");
StringRef File = RL.SourceFilePath;
unsigned Line = RL.SourceLine;
unsigned Col = RL.SourceColumn;
if (auto *Serializer = dyn_cast<YAMLStrTabRemarkSerializer>(
reinterpret_cast<RemarkSerializer *>(io.getContext()))) {
assert(Serializer->StrTab.hasValue() &&
"YAMLStrTabSerializer with no StrTab.");
StringTable &StrTab = *Serializer->StrTab;
unsigned FileID = StrTab.add(File).first;
io.mapRequired("File", FileID);
} else {
io.mapRequired("File", File);
}
io.mapRequired("Line", Line);
io.mapRequired("Column", Col);
}
static const bool flow = true;
};
/// Helper struct for multiline string block literals. Use this type to preserve
/// newlines in strings.
struct StringBlockVal {
StringRef Value;
StringBlockVal(StringRef R) : Value(R) {}
};
template <> struct BlockScalarTraits<StringBlockVal> {
static void output(const StringBlockVal &S, void *Ctx, raw_ostream &OS) {
return ScalarTraits<StringRef>::output(S.Value, Ctx, OS);
}
static StringRef input(StringRef Scalar, void *Ctx, StringBlockVal &S) {
return ScalarTraits<StringRef>::input(Scalar, Ctx, S.Value);
}
};
/// ArrayRef is not really compatible with the YAMLTraits. Everything should be
/// immutable in an ArrayRef, while the SequenceTraits expect a mutable version
/// for inputting, but we're only using the outputting capabilities here.
/// This is a hack, but still nicer than having to manually call the YAMLIO
/// internal methods.
/// Keep this in this file so that it doesn't get misused from YAMLTraits.h.
template <typename T> struct SequenceTraits<ArrayRef<T>> {
static size_t size(IO &io, ArrayRef<T> &seq) { return seq.size(); }
static Argument &element(IO &io, ArrayRef<T> &seq, size_t index) {
assert(io.outputting() && "input not yet implemented");
// The assert above should make this "safer" to satisfy the YAMLTraits.
return const_cast<T &>(seq[index]);
}
};
/// Implement this as a mapping for now to get proper quotation for the value.
template <> struct MappingTraits<Argument> {
static void mapping(IO &io, Argument &A) {
assert(io.outputting() && "input not yet implemented");
if (auto *Serializer = dyn_cast<YAMLStrTabRemarkSerializer>(
reinterpret_cast<RemarkSerializer *>(io.getContext()))) {
assert(Serializer->StrTab.hasValue() &&
"YAMLStrTabSerializer with no StrTab.");
StringTable &StrTab = *Serializer->StrTab;
auto ValueID = StrTab.add(A.Val).first;
io.mapRequired(A.Key.data(), ValueID);
} else if (StringRef(A.Val).count('\n') > 1) {
StringBlockVal S(A.Val);
io.mapRequired(A.Key.data(), S);
} else {
io.mapRequired(A.Key.data(), A.Val);
}
io.mapOptional("DebugLoc", A.Loc);
}
};
} // end namespace yaml
} // end namespace llvm
LLVM_YAML_IS_SEQUENCE_VECTOR(Argument)
YAMLRemarkSerializer::YAMLRemarkSerializer(raw_ostream &OS, SerializerMode Mode,
Optional<StringTable> StrTabIn)
: YAMLRemarkSerializer(Format::YAML, OS, Mode, std::move(StrTabIn)) {}
YAMLRemarkSerializer::YAMLRemarkSerializer(Format SerializerFormat,
raw_ostream &OS, SerializerMode Mode,
Optional<StringTable> StrTabIn)
: RemarkSerializer(SerializerFormat, OS, Mode),
YAMLOutput(OS, reinterpret_cast<void *>(this)) {
StrTab = std::move(StrTabIn);
}
void YAMLRemarkSerializer::emit(const Remark &Remark) {
// Again, YAMLTraits expect a non-const object for inputting, but we're not
// using that here.
auto R = const_cast<remarks::Remark *>(&Remark);
YAMLOutput << R;
}
std::unique_ptr<MetaSerializer>
YAMLRemarkSerializer::metaSerializer(raw_ostream &OS,
Optional<StringRef> ExternalFilename) {
return std::make_unique<YAMLMetaSerializer>(OS, ExternalFilename);
}
void YAMLStrTabRemarkSerializer::emit(const Remark &Remark) {
// In standalone mode, for the serializer with a string table, emit the
// metadata first and set DidEmitMeta to avoid emitting it again.
if (Mode == SerializerMode::Standalone && !DidEmitMeta) {
std::unique_ptr<MetaSerializer> MetaSerializer =
metaSerializer(OS, /*ExternalFilename=*/None);
MetaSerializer->emit();
DidEmitMeta = true;
}
// Then do the usual remark emission.
YAMLRemarkSerializer::emit(Remark);
}
std::unique_ptr<MetaSerializer> YAMLStrTabRemarkSerializer::metaSerializer(
raw_ostream &OS, Optional<StringRef> ExternalFilename) {
assert(StrTab);
return std::make_unique<YAMLStrTabMetaSerializer>(OS, ExternalFilename,
*StrTab);
}
static void emitMagic(raw_ostream &OS) {
// Emit the magic number.
OS << remarks::Magic;
// Explicitly emit a '\0'.
OS.write('\0');
}
static void emitVersion(raw_ostream &OS) {
// Emit the version number: little-endian uint64_t.
std::array<char, 8> Version;
support::endian::write64le(Version.data(), remarks::CurrentRemarkVersion);
OS.write(Version.data(), Version.size());
}
static void emitStrTab(raw_ostream &OS, Optional<const StringTable *> StrTab) {
// Emit the string table in the section.
uint64_t StrTabSize = StrTab ? (*StrTab)->SerializedSize : 0;
// Emit the total size of the string table (the size itself excluded):
// little-endian uint64_t.
// Note: even if no string table is used, emit 0.
std::array<char, 8> StrTabSizeBuf;
support::endian::write64le(StrTabSizeBuf.data(), StrTabSize);
OS.write(StrTabSizeBuf.data(), StrTabSizeBuf.size());
if (StrTab)
(*StrTab)->serialize(OS);
}
static void emitExternalFile(raw_ostream &OS, StringRef Filename) {
// Emit the null-terminated absolute path to the remark file.
SmallString<128> FilenameBuf = Filename;
sys::fs::make_absolute(FilenameBuf);
assert(!FilenameBuf.empty() && "The filename can't be empty.");
OS.write(FilenameBuf.data(), FilenameBuf.size());
OS.write('\0');
}
void YAMLMetaSerializer::emit() {
emitMagic(OS);
emitVersion(OS);
emitStrTab(OS, None);
if (ExternalFilename)
emitExternalFile(OS, *ExternalFilename);
}
void YAMLStrTabMetaSerializer::emit() {
emitMagic(OS);
emitVersion(OS);
emitStrTab(OS, &StrTab);
if (ExternalFilename)
emitExternalFile(OS, *ExternalFilename);
}
|
//
// Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "misc/debug.h"
#include "misc/object_tracker.h"
#include "misc/shader_module_cache.h"
#include "wrappers/shader_module.h"
/** Please see header for documentation */
Anvil::ShaderModuleCache::ShaderModuleCache()
:MTSafetySupportProvider(true)
{
update_subscriptions(true);
}
/** Please see header for documentation */
Anvil::ShaderModuleCache::~ShaderModuleCache()
{
update_subscriptions(false);
}
/** TODO */
void Anvil::ShaderModuleCache::cache(Anvil::ShaderModule* in_shader_module_ptr)
{
const auto shader_module_cs_entrypoint_name = in_shader_module_ptr->get_cs_entrypoint_name();
const auto shader_module_device_ptr = in_shader_module_ptr->get_parent_device ();
const auto shader_module_fs_entrypoint_name = in_shader_module_ptr->get_fs_entrypoint_name();
const auto shader_module_gs_entrypoint_name = in_shader_module_ptr->get_gs_entrypoint_name();
const auto shader_module_spirv_blob = in_shader_module_ptr->get_spirv_blob();
const auto shader_module_tc_entrypoint_name = in_shader_module_ptr->get_tc_entrypoint_name();
const auto shader_module_te_entrypoint_name = in_shader_module_ptr->get_te_entrypoint_name();
const auto shader_module_vs_entrypoint_name = in_shader_module_ptr->get_vs_entrypoint_name();
const size_t hash(get_hash(reinterpret_cast<const char*>(&shader_module_spirv_blob.at(0) ),
static_cast<uint32_t>(shader_module_spirv_blob.size() * sizeof(shader_module_spirv_blob.at(0) )),
shader_module_cs_entrypoint_name,
shader_module_fs_entrypoint_name,
shader_module_gs_entrypoint_name,
shader_module_tc_entrypoint_name,
shader_module_te_entrypoint_name,
shader_module_vs_entrypoint_name) );
anvil_assert(in_shader_module_ptr != nullptr);
{
std::unique_lock<std::recursive_mutex> mutex_lock(*get_mutex() );
auto items_map_iterator = m_item_ptrs.find(hash);
bool should_store_new_item = false;
if (items_map_iterator == m_item_ptrs.end() )
{
/* No collision case */
should_store_new_item = true;
}
else
{
/* The item we are being asked to cache might be already there. Make sure this is not the case
* before stashing the new structure.
*/
bool item_found = false;
auto& item_list = items_map_iterator->second;
for (const auto& current_item_ptr : item_list)
{
if (current_item_ptr->matches(shader_module_device_ptr,
reinterpret_cast<const char*>(&shader_module_spirv_blob.at(0) ),
static_cast<uint32_t>(shader_module_spirv_blob.size() * sizeof(shader_module_spirv_blob.at(0) )),
shader_module_cs_entrypoint_name,
shader_module_fs_entrypoint_name,
shader_module_gs_entrypoint_name,
shader_module_tc_entrypoint_name,
shader_module_te_entrypoint_name,
shader_module_vs_entrypoint_name) )
{
/* This assertion check should never explode */
anvil_assert(current_item_ptr->shader_module_owned_ptr.get() == in_shader_module_ptr);
item_found = true;
break;
}
}
should_store_new_item = !item_found;
}
if (should_store_new_item)
{
std::unique_ptr<HashMapItem> new_item_ptr(
new HashMapItem(shader_module_device_ptr,
shader_module_spirv_blob,
shader_module_cs_entrypoint_name,
shader_module_fs_entrypoint_name,
shader_module_gs_entrypoint_name,
shader_module_tc_entrypoint_name,
shader_module_te_entrypoint_name,
shader_module_vs_entrypoint_name,
in_shader_module_ptr)
);
m_item_ptrs[hash].push_front(
std::move(new_item_ptr)
);
}
}
}
Anvil::ShaderModuleCacheUniquePtr Anvil::ShaderModuleCache::create()
{
ShaderModuleCacheUniquePtr result_ptr(nullptr,
std::default_delete<ShaderModuleCache>() );
result_ptr.reset(
new Anvil::ShaderModuleCache()
);
return result_ptr;
}
/** Please see header for documentation */
Anvil::ShaderModuleUniquePtr Anvil::ShaderModuleCache::get_cached_shader_module(const Anvil::BaseDevice* in_device_ptr,
const char* in_spirv_blob,
uint32_t in_n_spirv_blob_bytes,
const std::string& in_cs_entrypoint_name,
const std::string& in_fs_entrypoint_name,
const std::string& in_gs_entrypoint_name,
const std::string& in_tc_entrypoint_name,
const std::string& in_te_entrypoint_name,
const std::string& in_vs_entrypoint_name)
{
Anvil::ShaderModuleUniquePtr result_ptr;
{
std::unique_lock<std::recursive_mutex> mutex_lock(*get_mutex() );
const auto hash (get_hash(in_spirv_blob,
in_n_spirv_blob_bytes,
in_cs_entrypoint_name,
in_fs_entrypoint_name,
in_gs_entrypoint_name,
in_tc_entrypoint_name,
in_te_entrypoint_name,
in_vs_entrypoint_name) );
auto items_map_iterator(m_item_ptrs.find(hash) );
if (items_map_iterator != m_item_ptrs.end() )
{
const auto& items = items_map_iterator->second;
for (const auto& current_item_ptr : items)
{
if (current_item_ptr->matches(in_device_ptr,
in_spirv_blob,
in_n_spirv_blob_bytes,
in_cs_entrypoint_name,
in_fs_entrypoint_name,
in_gs_entrypoint_name,
in_tc_entrypoint_name,
in_te_entrypoint_name,
in_vs_entrypoint_name) )
{
anvil_assert(current_item_ptr->shader_module_owned_ptr != nullptr);
anvil_assert(current_item_ptr->shader_module_owned_ptr->get_module() != VK_NULL_HANDLE);
result_ptr = Anvil::ShaderModuleUniquePtr(current_item_ptr->shader_module_owned_ptr.get(),
[](ShaderModule*)
{
/* Stub */
});
break;
}
}
}
}
return result_ptr;
}
/** TODO */
size_t Anvil::ShaderModuleCache::get_hash(const char* in_spirv_blob,
uint32_t in_n_spirv_blob_bytes,
const std::string& in_cs_entrypoint_name,
const std::string& in_fs_entrypoint_name,
const std::string& in_gs_entrypoint_name,
const std::string& in_tc_entrypoint_name,
const std::string& in_te_entrypoint_name,
const std::string& in_vs_entrypoint_name) const
{
std::hash<std::string> hash_string;
std::hash<uint32_t> hash_uint32;
const uint32_t n_spirv_blob_ops = in_n_spirv_blob_bytes / sizeof(uint32_t);
size_t result_hash = 0;
const uint32_t* spirv_blob_uint32_ptr = reinterpret_cast<const uint32_t*>(in_spirv_blob);
anvil_assert((in_n_spirv_blob_bytes % sizeof(uint32_t)) == 0);
for (uint32_t n_spirv_blob_op = 0;
n_spirv_blob_op < n_spirv_blob_ops;
++n_spirv_blob_op)
{
result_hash ^= hash_uint32(spirv_blob_uint32_ptr[n_spirv_blob_op]);
}
result_hash ^= hash_string(in_cs_entrypoint_name);
result_hash ^= hash_string(in_fs_entrypoint_name);
result_hash ^= hash_string(in_gs_entrypoint_name);
result_hash ^= hash_string(in_tc_entrypoint_name);
result_hash ^= hash_string(in_te_entrypoint_name);
result_hash ^= hash_string(in_vs_entrypoint_name);
return result_hash;
}
/** TODO */
void Anvil::ShaderModuleCache::on_shader_module_object_about_to_be_released(CallbackArgument* in_callback_arg_ptr)
{
/* Technically we should never reach this place, as shader module cache does not implement
* any sort of GC mechanism.
*
* Please investigate if this assertion check fires.
*/
ANVIL_REDUNDANT_ARGUMENT(in_callback_arg_ptr);
anvil_assert_fail();
}
/** TODO */
void Anvil::ShaderModuleCache::on_shader_module_object_registered(CallbackArgument* in_callback_arg_ptr)
{
const auto callback_arg_ptr = dynamic_cast<Anvil::OnObjectRegisteredCallbackArgument*>(in_callback_arg_ptr);
anvil_assert(callback_arg_ptr != nullptr);
auto shader_module_ptr = static_cast<Anvil::ShaderModule*>(callback_arg_ptr->object_raw_ptr);
cache(shader_module_ptr);
}
void Anvil::ShaderModuleCache::update_subscriptions(bool in_should_init)
{
auto object_tracker_ptr = Anvil::ObjectTracker::get();
auto on_object_about_to_be_released_func = std::bind(&ShaderModuleCache::on_shader_module_object_about_to_be_released,
this,
std::placeholders::_1);
auto on_object_registered_func = std::bind(&ShaderModuleCache::on_shader_module_object_registered,
this,
std::placeholders::_1);
if (in_should_init)
{
object_tracker_ptr->register_for_callbacks(OBJECT_TRACKER_CALLBACK_ID_ON_SHADER_MODULE_OBJECT_ABOUT_TO_BE_UNREGISTERED,
on_object_about_to_be_released_func,
this);
object_tracker_ptr->register_for_callbacks(OBJECT_TRACKER_CALLBACK_ID_ON_SHADER_MODULE_OBJECT_REGISTERED,
on_object_registered_func,
this);
}
else
{
object_tracker_ptr->unregister_from_callbacks(OBJECT_TRACKER_CALLBACK_ID_ON_SHADER_MODULE_OBJECT_ABOUT_TO_BE_UNREGISTERED,
on_object_about_to_be_released_func,
this);
object_tracker_ptr->unregister_from_callbacks(OBJECT_TRACKER_CALLBACK_ID_ON_SHADER_MODULE_OBJECT_REGISTERED,
on_object_registered_func,
this);
}
}
|
// RemoteNotifyInject.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include <Windows.h>
#include <assert.h>
#include <stdio.h>
#include <string>
#pragma data_seg("SHARED")
HWND hTargetWnd = nullptr;
bool hasMsg = false;
HHOOK hHook = nullptr;
#pragma data_seg()
#pragma comment(linker, "/section:SHARED,RWS")
bool isMaster = false;
HMODULE hMyModule;
LRESULT CALLBACK MsgFilter(int code, WPARAM wparam, LPARAM lparam)
{
auto pmsg = (PMSG)lparam;
if (pmsg->hwnd == hTargetWnd && pmsg->message == WM_TIMER)
{
if(pmsg->wParam == 1)
hasMsg = true;
}
return CallNextHookEx(hHook, code, wparam, lparam);
}
__declspec(dllexport) HHOOK Inject(HWND hWnd)
{
DWORD dummy;
hTargetWnd = hWnd;
auto ret = SetWindowsHookExA(WH_GETMESSAGE, MsgFilter, hMyModule, GetWindowThreadProcessId(hWnd, &dummy));
assert(ret);
hHook = ret;
isMaster = true;
return ret;
}
__declspec(dllexport) bool HasMessage()
{
auto ret = hasMsg;
hasMsg = false;
return ret;
}
__declspec(dllexport) void UnInject()
{
printf("Exiting\n");
if(hHook)
UnhookWindowsHookEx(hHook);
hHook = nullptr;
}
extern HMODULE hMyModule;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
hMyModule = hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
if (isMaster)
UnInject();
break;
}
return TRUE;
}
|
/*
* Copyright (c) 2013-2015, Roland Bock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 "MockDb.h"
#include "Sample.h"
#include "is_regular.h"
#include <iostream>
#include <sqlpp11/functions.h>
#include <sqlpp11/insert.h>
int Insert(int, char*[])
{
MockDb db = {};
MockDb::_serializer_context_t printer = {};
const auto t = test::TabBar{};
const auto tabDateTime = test::TabDateTime{};
// test::TabFoo f;
{
using T = decltype(insert_into(t));
static_assert(sqlpp::is_regular<T>::value, "type requirement");
}
{
using T = decltype(insert_into(t).set(t.beta = "kirschauflauf"));
static_assert(sqlpp::is_regular<T>::value, "type requirement");
}
{
using T = decltype(dynamic_insert_into(db, t).dynamic_set());
static_assert(sqlpp::is_regular<T>::value, "type requirement");
}
db(insert_into(t).default_values());
db(insert_into(t).set(t.gamma = true, t.beta = "kirschauflauf"));
db(insert_into(t).set(t.gamma = sqlpp::default_value, t.beta = sqlpp::value_or_null("pie"),
t.delta = sqlpp::value_or_null<sqlpp::integer>(sqlpp::null)));
serialize(insert_into(t).default_values(), printer).str();
serialize(insert_into(t), printer).str();
serialize(insert_into(t).set(t.gamma = true, t.beta = "kirschauflauf"), printer).str();
serialize(insert_into(t).columns(t.gamma, t.beta), printer).str();
auto multi_insert = insert_into(t).columns(t.gamma, t.beta, t.delta);
multi_insert.values.add(t.gamma = true, t.beta = "cheesecake", t.delta = 1);
multi_insert.values.add(t.gamma = sqlpp::default_value, t.beta = sqlpp::default_value,
t.delta = sqlpp::default_value);
multi_insert.values.add(t.gamma = sqlpp::value_or_null(true), t.beta = sqlpp::value_or_null("pie"),
t.delta = sqlpp::value_or_null<sqlpp::integer>(sqlpp::null));
printer.reset();
std::cerr << serialize(multi_insert, printer).str() << std::endl;
// Beware, you need exact types for inserted values in multi_insert
insert_into(tabDateTime)
.set(tabDateTime.colTimePoint = std::chrono::system_clock::now());
auto multi_time_insert = insert_into(tabDateTime).columns(tabDateTime.colTimePoint);
multi_time_insert.values.add(tabDateTime.colTimePoint = std::chrono::time_point_cast<std::chrono::microseconds>(
std::chrono::system_clock::now()));
auto i = dynamic_insert_into(db, t).dynamic_set();
i.insert_list.add(t.beta = "kirschauflauf");
printer.reset();
std::cerr << serialize(i, printer).str() << std::endl;
db(multi_insert);
auto values = [&t]() { return std::make_tuple(t.gamma = true, t.beta = sqlpp::null); };
db(insert_into(t).set(t.gamma = true, t.delta = sqlpp::verbatim<sqlpp::integer>("17+4")));
db(insert_into(t).set(t.gamma = true, t.delta = sqlpp::null));
db(insert_into(t).set(t.gamma = true, t.delta = sqlpp::default_value));
db(insert_into(t).set(t.gamma = true, t.delta = 0));
db(insert_into(t).set(values()));
auto prepared_insert = db.prepare(insert_into(t).set(t.gamma = parameter(t.gamma), t.delta = parameter(t.delta)));
prepared_insert.params.gamma = true;
prepared_insert.params.delta = sqlpp::null;
prepared_insert.params.delta = 17;
prepared_insert.params.delta = sqlpp::value_or_null<sqlpp::integer>(sqlpp::null);
prepared_insert.params.delta = sqlpp::value_or_null(17);
db(prepared_insert);
return 0;
}
|
/*
* Copyright 2010-2017 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/comprehendmedical/model/ListEntitiesDetectionV2JobsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::ComprehendMedical::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
ListEntitiesDetectionV2JobsRequest::ListEntitiesDetectionV2JobsRequest() :
m_filterHasBeenSet(false),
m_nextTokenHasBeenSet(false),
m_maxResults(0),
m_maxResultsHasBeenSet(false)
{
}
Aws::String ListEntitiesDetectionV2JobsRequest::SerializePayload() const
{
JsonValue payload;
if(m_filterHasBeenSet)
{
payload.WithObject("Filter", m_filter.Jsonize());
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
if(m_maxResultsHasBeenSet)
{
payload.WithInteger("MaxResults", m_maxResults);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection ListEntitiesDetectionV2JobsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ComprehendMedical_20181030.ListEntitiesDetectionV2Jobs"));
return headers;
}
|
// Copyright 2017 Google 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 "application_sandbox/sample_application_framework/sample_application.h"
#include "support/entry/entry.h"
#include "vulkan_helpers/buffer_frame_data.h"
#include "vulkan_helpers/helper_functions.h"
#include "vulkan_helpers/vulkan_application.h"
#include "vulkan_helpers/vulkan_model.h"
#include <chrono>
#include "mathfu/matrix.h"
#include "mathfu/vector.h"
using Mat44 = mathfu::Matrix<float, 4, 4>;
using Vector4 = mathfu::Vector<float, 4>;
namespace cube_model {
#include "cube.obj.h"
}
const auto& cube_data = cube_model::model;
uint32_t cube_vertex_shader[] =
#include "cube.vert.spv"
;
uint32_t cube_fragment_shader[] =
#include "cube.frag.spv"
;
namespace floor_model {
#include "floor.obj.h"
}
const auto& floor_data = floor_model::model;
uint32_t floor_vertex_shader[] =
#include "floor.vert.spv"
;
uint32_t floor_fragment_shader[] =
#include "floor.frag.spv"
;
uint32_t mirror_vertex_shader[] =
#include "mirror.vert.spv"
;
const VkFormat kDepthStencilFormat = VK_FORMAT_D32_SFLOAT_S8_UINT;
struct MixedSamplesFrameData {
containers::unique_ptr<vulkan::VkCommandBuffer> command_buffer_;
containers::unique_ptr<vulkan::VkFramebuffer> framebuffer_;
containers::unique_ptr<vulkan::DescriptorSet> cube_descriptor_set_;
// The sample application assumes the depth format to VK_FORMAT_D16_UNORM.
// As we need to use stencil aspect, we declare another depth_stencil image
// and its view here.
vulkan::ImagePointer depth_stencil_image_;
containers::unique_ptr<vulkan::VkImageView> depth_stencil_image_view_;
vulkan::ImagePointer depth_stencil_resolve_image_;
containers::unique_ptr<vulkan::VkImageView> depth_stencil_resolve_image_view_;
};
// This creates an application with 16MB of image memory, and defaults
// for host, and device buffer sizes.
class MixedSamplesSample
: public sample_application::Sample<MixedSamplesFrameData> {
public:
MixedSamplesSample(const entry::EntryData* data)
: data_(data),
Sample<MixedSamplesFrameData>(
data->allocator(), data, 1, 512, 1, 1,
sample_application::SampleOptions().EnableMultisampling(), {0}, {},
{VK_KHR_MULTIVIEW_EXTENSION_NAME,
VK_KHR_MAINTENANCE2_EXTENSION_NAME,
VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME,
VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME}),
cube_(data->allocator(), data->logger(), cube_data),
floor_(data->allocator(), data->logger(), floor_data) {}
virtual void InitializeApplicationData(
vulkan::VkCommandBuffer* initialization_buffer,
size_t num_swapchain_images) override {
cube_.InitializeData(app(), initialization_buffer);
floor_.InitializeData(app(), initialization_buffer);
// Initialization for cube and floor rendering. Cube and floor shares the
// same transformation matrix, so they shares the same descriptor sets for
// vertex shader and pipeline layout. However, the fragment shaders are
// different, so two different pipelines are required.
descriptor_set_layouts_[0] = {
0, // binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_VERTEX_BIT, // stageFlags
nullptr // pImmutableSamplers
};
descriptor_set_layouts_[1] = {
1, // binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_VERTEX_BIT, // stageFlags
nullptr // pImmutableSamplers
};
pipeline_layout_ = containers::make_unique<vulkan::PipelineLayout>(
data_->allocator(),
app()->CreatePipelineLayout(
{{descriptor_set_layouts_[0], descriptor_set_layouts_[1]}}));
VkAttachmentReference2KHR color_attachment = {
VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR, // sType
nullptr, // pNext
0, // attachment
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // layout
VK_IMAGE_ASPECT_COLOR_BIT // aspectMask
};
VkAttachmentReference2KHR depth_attachment = {
VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR, // sType
nullptr, // pNext
1, // attachment
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, // layout
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT // aspectMask
};
VkAttachmentReference2KHR resolve_attachment = {
VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR, // sType
nullptr, // pNext
2, // attachment
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, // layout
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT // aspectMask
};
VkAttachmentDescription2KHR color_attachment_description{
VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR, // sType
nullptr, // pNext
0, // flags
render_format(), // format
num_color_samples(), // samples
VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp
VK_ATTACHMENT_STORE_OP_STORE, // storeOp
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // stencilLoadOp
VK_ATTACHMENT_STORE_OP_DONT_CARE, // stencilStoreOp
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // initialLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // finalLayout
};
VkAttachmentDescription2KHR depth_stencil_attachment_description{
VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR, // sType
nullptr, // pNext
0, // flags
kDepthStencilFormat, // format
num_depth_stencil_samples(), // samples
VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp
VK_ATTACHMENT_STORE_OP_STORE, // storeOp
VK_ATTACHMENT_LOAD_OP_CLEAR, // stencilLoadOp
VK_ATTACHMENT_STORE_OP_STORE, // stencilStoreOp
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // finalLayout
};
VkAttachmentDescription2KHR depth_stencil_resolve_attachment_description{
VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR, // sType
nullptr, // pNext
0, // flags
kDepthStencilFormat, // format
VK_SAMPLE_COUNT_1_BIT, // samples
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // loadOp
VK_ATTACHMENT_STORE_OP_STORE, // storeOp
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // stencilLoadOp
VK_ATTACHMENT_STORE_OP_STORE, // stencilStoreOp
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // finalLayout
};
VkSubpassDescriptionDepthStencilResolveKHR
subpass_description_depth_stencil_resolve{
VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR, // sType
nullptr, // pNext
VK_RESOLVE_MODE_MAX_BIT_KHR, // depthResolveMode
VK_RESOLVE_MODE_MAX_BIT_KHR, // stencilResolveMode
&resolve_attachment // pDepthStencilResolveAttachment
};
render_pass_ = containers::make_unique<vulkan::VkRenderPass>(
data_->allocator(),
app()->CreateRenderPass2(
{color_attachment_description, depth_stencil_attachment_description,
depth_stencil_resolve_attachment_description}, // AttachmentDescriptions
{{
VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, // sType
&subpass_description_depth_stencil_resolve, // pNext
0, // flags
VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint
0, // viewMask
0, // inputAttachmentCount
nullptr, // pInputAttachments
1, // colorAttachmentCount
&color_attachment, // colorAttachment
nullptr, // pResolveAttachments
&depth_attachment, // pDepthStencilAttachment
0, // preserveAttachmentCount
nullptr // pPreserveAttachments
}}, // SubpassDescriptions
{} // SubpassDependencies
));
// Initialize cube shaders
cube_pipeline_ = containers::make_unique<vulkan::VulkanGraphicsPipeline>(
data_->allocator(), app()->CreateGraphicsPipeline(
pipeline_layout_.get(), render_pass_.get(), 0));
cube_pipeline_->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main",
cube_vertex_shader);
cube_pipeline_->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main",
cube_fragment_shader);
cube_pipeline_->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
cube_pipeline_->SetInputStreams(&cube_);
cube_pipeline_->SetViewport(viewport());
cube_pipeline_->SetScissor(scissor());
cube_pipeline_->SetSamples(num_samples());
cube_pipeline_->AddAttachment();
cube_pipeline_->Commit();
// Initialize floor shaders
floor_pipeline_ = containers::make_unique<vulkan::VulkanGraphicsPipeline>(
data_->allocator(), app()->CreateGraphicsPipeline(
pipeline_layout_.get(), render_pass_.get(), 0));
floor_pipeline_->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main",
floor_vertex_shader);
floor_pipeline_->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main",
floor_fragment_shader);
floor_pipeline_->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
floor_pipeline_->SetInputStreams(&floor_);
floor_pipeline_->SetViewport(viewport());
floor_pipeline_->SetScissor(scissor());
floor_pipeline_->SetSamples(num_samples());
floor_pipeline_->AddAttachment();
// Need to enable the stencil buffer to be written. The reference and
// write mask will be set later dynamically, the actual value write to
// stencil buffer will be 'reference & write mask'.
floor_pipeline_->AddDynamicState(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
floor_pipeline_->AddDynamicState(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
floor_pipeline_->DepthStencilState().stencilTestEnable = VK_TRUE;
floor_pipeline_->DepthStencilState().front.compareOp = VK_COMPARE_OP_ALWAYS;
floor_pipeline_->DepthStencilState().front.passOp = VK_STENCIL_OP_REPLACE;
floor_pipeline_->Commit();
// Initialize mirror pipeline
mirror_pipeline_ = containers::make_unique<vulkan::VulkanGraphicsPipeline>(
data_->allocator(), app()->CreateGraphicsPipeline(
pipeline_layout_.get(), render_pass_.get(), 0));
mirror_pipeline_->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main",
mirror_vertex_shader);
mirror_pipeline_->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main",
cube_fragment_shader);
mirror_pipeline_->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
mirror_pipeline_->SetFrontFace(VK_FRONT_FACE_CLOCKWISE);
mirror_pipeline_->SetInputStreams(&cube_);
mirror_pipeline_->SetViewport(viewport());
mirror_pipeline_->SetScissor(scissor());
mirror_pipeline_->SetSamples(num_samples());
// Enable color blend
mirror_pipeline_->AddDynamicState(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
mirror_pipeline_->AddAttachment(VkPipelineColorBlendAttachmentState{
VK_TRUE, // blendEnable
VK_BLEND_FACTOR_CONSTANT_COLOR, // srcColorBlendFactor
VK_BLEND_FACTOR_ONE, // dstColorBlendFactor
VK_BLEND_OP_ADD, // colorBlendOp
VK_BLEND_FACTOR_ONE, // srcAlphaBlendFactor
VK_BLEND_FACTOR_ONE, // dstAlphaBlendFactor
VK_BLEND_OP_MAX, // alphaBlendOp
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT
// colorWriteMask
});
// Need to test the stencil buffer. The reference and compare mask are to
// be set later dynamically. The real value used to compare to the stencil
// buffer is 'reference & compare mask'.
mirror_pipeline_->AddDynamicState(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
mirror_pipeline_->AddDynamicState(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
mirror_pipeline_->DepthStencilState().stencilTestEnable = VK_TRUE;
mirror_pipeline_->DepthStencilState().front.compareOp = VK_COMPARE_OP_EQUAL;
// Disable depth test, so the reflection can be shown on the floor.
mirror_pipeline_->DepthStencilState().depthTestEnable = VK_FALSE;
mirror_pipeline_->Commit();
// Transformation data for viewing and cube/floor rotation.
camera_data_ = containers::make_unique<vulkan::BufferFrameData<CameraData>>(
data_->allocator(), app(), num_swapchain_images,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
model_data_ = containers::make_unique<vulkan::BufferFrameData<ModelData>>(
data_->allocator(), app(), num_swapchain_images,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
float aspect =
(float)app()->swapchain().width() / (float)app()->swapchain().height();
camera_data_->data().projection_matrix =
Mat44::FromScaleVector(mathfu::Vector<float, 3>{1.0f, -1.0f, 1.0f}) *
Mat44::Perspective(1.5708f, aspect, 0.1f, 100.0f);
model_data_->data().transform =
Mat44::FromTranslationVector(
mathfu::Vector<float, 3>{0.0f, 0.0f, -3.0f}) *
Mat44::FromRotationMatrix(Mat44::RotationX(3.14f * 0.2f));
model_data_->data().transform =
model_data_->data().transform *
Mat44::FromRotationMatrix(Mat44::RotationY(3.14f * 0.3f));
}
virtual void InitializeFrameData(
MixedSamplesFrameData* frame_data,
vulkan::VkCommandBuffer* initialization_buffer,
size_t frame_index) override {
// Initalize the depth stencil image and the image view.
VkImageCreateInfo depth_stencil_image_create_info = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
VK_IMAGE_TYPE_2D, // imageType
kDepthStencilFormat, // format
{
app()->swapchain().width(),
app()->swapchain().height(),
app()->swapchain().depth(),
}, // extent
1, // mipLevels
1, // arrayLayers
num_depth_stencil_samples(), // samples
VK_IMAGE_TILING_OPTIMAL, // tiling
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, // usage
VK_SHARING_MODE_EXCLUSIVE, // sharingMode
0, // queueFamilyIndexCount
nullptr, // pQueueFamilyIndices
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
};
frame_data->depth_stencil_image_ =
app()->CreateAndBindImage(&depth_stencil_image_create_info);
frame_data->depth_stencil_image_view_ = app()->CreateImageView(
frame_data->depth_stencil_image_.get(), VK_IMAGE_VIEW_TYPE_2D,
{VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, 0, 1, 0, 1});
VkImageCreateInfo depth_stencil_resolve_image_create_info = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
VK_IMAGE_TYPE_2D, // imageType
kDepthStencilFormat, // format
{
app()->swapchain().width(),
app()->swapchain().height(),
app()->swapchain().depth(),
}, // extent
1, // mipLevels
1, // arrayLayers
VK_SAMPLE_COUNT_1_BIT, // samples
VK_IMAGE_TILING_OPTIMAL, // tiling
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, // usage
VK_SHARING_MODE_EXCLUSIVE, // sharingMode
0, // queueFamilyIndexCount
nullptr, // pQueueFamilyIndices
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
};
frame_data->depth_stencil_resolve_image_ =
app()->CreateAndBindImage(&depth_stencil_resolve_image_create_info);
frame_data->depth_stencil_resolve_image_view_ = app()->CreateImageView(
frame_data->depth_stencil_resolve_image_.get(), VK_IMAGE_VIEW_TYPE_2D,
{VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, 0, 1, 0, 1});
// Initialize the descriptor sets
frame_data->cube_descriptor_set_ =
containers::make_unique<vulkan::DescriptorSet>(
data_->allocator(),
app()->AllocateDescriptorSet(
{descriptor_set_layouts_[0], descriptor_set_layouts_[1]}));
VkDescriptorBufferInfo buffer_infos[2] = {
{
camera_data_->get_buffer(), // buffer
camera_data_->get_offset_for_frame(frame_index), // offset
camera_data_->size(), // range
},
{
model_data_->get_buffer(), // buffer
model_data_->get_offset_for_frame(frame_index), // offset
model_data_->size(), // range
}};
VkWriteDescriptorSet write{
VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, // sType
nullptr, // pNext
*frame_data->cube_descriptor_set_, // dstSet
0, // dstbinding
0, // dstArrayElement
2, // descriptorCount
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
nullptr, // pImageInfo
buffer_infos, // pBufferInfo
nullptr, // pTexelBufferView
};
app()->device()->vkUpdateDescriptorSets(app()->device(), 1, &write, 0,
nullptr);
::VkImageView raw_views[3] = {
color_view(frame_data), *frame_data->depth_stencil_image_view_,
*frame_data->depth_stencil_resolve_image_view_};
// Create a framebuffer with depth and image attachments
VkFramebufferCreateInfo framebuffer_create_info{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
*render_pass_, // renderPass
3, // attachmentCount
raw_views, // attachments
app()->swapchain().width(), // width
app()->swapchain().height(), // height
1 // layers
};
::VkFramebuffer raw_framebuffer;
app()->device()->vkCreateFramebuffer(
app()->device(), &framebuffer_create_info, nullptr, &raw_framebuffer);
frame_data->framebuffer_ = containers::make_unique<vulkan::VkFramebuffer>(
data_->allocator(),
vulkan::VkFramebuffer(raw_framebuffer, nullptr, &app()->device()));
// Populate the render command buffer
frame_data->command_buffer_ =
containers::make_unique<vulkan::VkCommandBuffer>(
data_->allocator(), app()->GetCommandBuffer());
(*frame_data->command_buffer_)
->vkBeginCommandBuffer((*frame_data->command_buffer_),
&sample_application::kBeginCommandBuffer);
vulkan::VkCommandBuffer& cmdBuffer = (*frame_data->command_buffer_);
VkClearValue clears[3];
clears[0].color = {1.0f, 1.0f, 1.0f, 1.0f};
clears[1].depthStencil = {1.0f, 0};
clears[2].depthStencil = {1.0f, 0};
VkRenderPassBeginInfo pass_begin = {
VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, // sType
nullptr, // pNext
*render_pass_, // renderPass
*frame_data->framebuffer_, // framebuffer
{{0, 0},
{app()->swapchain().width(),
app()->swapchain().height()}}, // renderArea
3, // clearValueCount
clears // clears
};
cmdBuffer->vkCmdBeginRenderPass(cmdBuffer, &pass_begin,
VK_SUBPASS_CONTENTS_INLINE);
cmdBuffer->vkCmdBindDescriptorSets(
cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
::VkPipelineLayout(*pipeline_layout_), 0, 1,
&frame_data->cube_descriptor_set_->raw_set(), 0, nullptr);
// Draw the cube
cmdBuffer->vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
*cube_pipeline_);
cube_.Draw(&cmdBuffer);
// Draw the floor
cmdBuffer->vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
*floor_pipeline_);
cmdBuffer->vkCmdSetStencilReference(cmdBuffer, VK_STENCIL_FACE_FRONT_BIT,
0xAB);
cmdBuffer->vkCmdSetStencilWriteMask(cmdBuffer, VK_STENCIL_FACE_FRONT_BIT,
0x0F);
floor_.Draw(&cmdBuffer);
// Draw the reflection
cmdBuffer->vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
*mirror_pipeline_);
float blend_constants[4] = {0.5f, 0.5f, 0.5f, 0.5f};
cmdBuffer->vkCmdSetBlendConstants(cmdBuffer, blend_constants);
cmdBuffer->vkCmdSetStencilReference(cmdBuffer, VK_STENCIL_FACE_FRONT_BIT,
0xFF);
cmdBuffer->vkCmdSetStencilCompareMask(cmdBuffer, VK_STENCIL_FACE_FRONT_BIT,
0x0B);
cube_.Draw(&cmdBuffer);
cmdBuffer->vkCmdEndRenderPass(cmdBuffer);
(*frame_data->command_buffer_)
->vkEndCommandBuffer(*frame_data->command_buffer_);
}
virtual void Update(float time_since_last_render) override {
model_data_->data().transform = model_data_->data().transform *
Mat44::FromRotationMatrix(Mat44::RotationY(
3.14f * time_since_last_render *
0.5f));
}
virtual void Render(vulkan::VkQueue* queue, size_t frame_index,
MixedSamplesFrameData* frame_data) override {
// Update our uniform buffers.
camera_data_->UpdateBuffer(queue, frame_index);
model_data_->UpdateBuffer(queue, frame_index);
VkSubmitInfo init_submit_info{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType
nullptr, // pNext
0, // waitSemaphoreCount
nullptr, // pWaitSemaphores
nullptr, // pWaitDstStageMask,
1, // commandBufferCount
&(frame_data->command_buffer_->get_command_buffer()),
0, // signalSemaphoreCount
nullptr // pSignalSemaphores
};
app()->render_queue()->vkQueueSubmit(app()->render_queue(), 1,
&init_submit_info,
static_cast<VkFence>(VK_NULL_HANDLE));
}
private:
struct CameraData {
Mat44 projection_matrix;
};
struct ModelData {
Mat44 transform;
};
const entry::EntryData* data_;
containers::unique_ptr<vulkan::PipelineLayout> pipeline_layout_;
containers::unique_ptr<vulkan::VulkanGraphicsPipeline> cube_pipeline_;
containers::unique_ptr<vulkan::VulkanGraphicsPipeline> floor_pipeline_;
containers::unique_ptr<vulkan::VulkanGraphicsPipeline> mirror_pipeline_;
containers::unique_ptr<vulkan::VkRenderPass> render_pass_;
VkDescriptorSetLayoutBinding descriptor_set_layouts_[2];
vulkan::VulkanModel cube_;
vulkan::VulkanModel floor_;
containers::unique_ptr<vulkan::BufferFrameData<CameraData>> camera_data_;
containers::unique_ptr<vulkan::BufferFrameData<ModelData>> model_data_;
};
int main_entry(const entry::EntryData* data) {
data->logger()->LogInfo("Application Startup");
MixedSamplesSample sample(data);
sample.Initialize();
while (!sample.should_exit() && !data->WindowClosing()) {
sample.ProcessFrame();
}
sample.WaitIdle();
data->logger()->LogInfo("Application Shutdown");
return 0;
}
|
#include <iostream>
#include <algorithm>
#include <cassert>
#include "Fetcher.hpp"
#include "GPUTypes.hpp"
#include "GPU.hpp"
namespace nsfgbe {
Fetcher::Fetcher(GPU &gpu, PixelFIFO &pixelFIFO) :
gpu(gpu), pixelFIFO(pixelFIFO) {}
void Fetcher::fetch(Word tileId, Byte verticalLine) {
this->tileId = tileId;
this->verticalLine = verticalLine;
this->currentMode = FetcherMode::READ_TILE;
}
void Fetcher::tick() {
switch (currentMode) {
// Background
case FetcherMode::READ_TILE:
readTile();
break;
case FetcherMode::READ_DATA_0:
readData0();
break;
case FetcherMode::READ_DATA_1:
readData1();
buildBgPixels();
// falls through
case FetcherMode::ADD_TO_FIFO:
addToFifo();
break;
// Sprites
case FetcherMode::READ_SPRITE_PATTERN:
readSpritePattern();
break;
case FetcherMode::READ_SPRITE_DATA_0:
readSpriteData0();
break;
case FetcherMode::READ_SPRITE_DATA_1:
readSpriteData1();
buildSpritePixels();
break;
case FetcherMode::ADD_SPRITE_TO_FIFO:
addSpriteToFifo();
break;
}
}
// ####################################
// Background
// ####################################
void Fetcher::readTile() {
tile = gpu.vram[gpu.registers.lcdc.getBgTileMapAddress() + tileId];
currentMode = FetcherMode::READ_DATA_0;
}
void Fetcher::readData0() {
Address tileAddress = gpu.registers.lcdc.getBgTileAddress(tile);
tileData0 = gpu.vram[tileAddress + 2 * verticalLine];
currentMode = FetcherMode::READ_DATA_1;
}
void Fetcher::readData1() {
Address tileAddress = gpu.registers.lcdc.getBgTileAddress(tile);
tileData1 = gpu.vram[tileAddress + 2 * verticalLine + 1];
currentMode = FetcherMode::ADD_TO_FIFO;
}
void Fetcher::buildBgPixels() {
for (int i = 0; i < 8; ++i) {
pixels[i].source = PixelSource::BG;
pixels[i].value = static_cast<Byte>(
((tileData0 >> (7 - i)) & 1) |
(((tileData1 >> (7 - i)) & 1) << 1));
}
}
void Fetcher::addToFifo() {
if (pixelFIFO.canAddEightPixels()) {
pixelFIFO.addEightPixels(pixels);
++tileId;
if (tileId % 32 == 0) {
// Wrap tiles horizontally
tileId -= 32;
}
currentMode = FetcherMode::READ_TILE;
}
}
// ####################################
// Sprites
// ####################################
void Fetcher::fetchSprite(Byte spriteId, Byte verticalLine, Byte pixelsToDrop) {
assert(!isFetchingSprite());
this->spriteId = spriteId;
if (getCurrentOAMEntry().getFlag(OAMEntry::Flags::Y_FLIP)) {
verticalLine =
gpu.registers.lcdc.getSpriteHeight() - verticalLine - 1_b;
}
this->spriteVerticalLine = verticalLine;
this->spritePixelsToDrop = pixelsToDrop;
this->lastMode = currentMode;
this->currentMode = FetcherMode::READ_SPRITE_PATTERN;
}
OAMEntry &Fetcher::getCurrentOAMEntry() const {
return gpu.oamRam[spriteId];
}
void Fetcher::readSpritePattern() {
sprite = getCurrentOAMEntry().pattern;
spriteSource =
getCurrentOAMEntry().getFlag(OAMEntry::Flags::PALETTE) ?
PixelSource::OB1 :
PixelSource::OB0;
currentMode = FetcherMode::READ_SPRITE_DATA_0;
}
void Fetcher::readSpriteData0() {
spriteData0 = gpu.vram[0x0000 + 16 * sprite + 2 * spriteVerticalLine];
currentMode = FetcherMode::READ_SPRITE_DATA_1;
}
void Fetcher::readSpriteData1() {
spriteData1 = gpu.vram[0x0000 + 16 * sprite + 2 * spriteVerticalLine + 1];
currentMode = FetcherMode::ADD_SPRITE_TO_FIFO;
}
void Fetcher::buildSpritePixels() {
for (int i = 0; i < 8; ++i) {
spritePixels[i].source = spriteSource;
spritePixels[i].value = static_cast<Byte>(
((spriteData0 >> (7 - i)) & 1) |
(((spriteData1 >> (7 - i)) & 1) << 1));
}
}
void Fetcher::addSpriteToFifo() {
reverseSpritePixels();
dropSpritePixels();
pixelFIFO.addSpritePixels(spritePixels);
currentMode = lastMode;
}
void Fetcher::reverseSpritePixels() {
if (getCurrentOAMEntry().getFlag(OAMEntry::Flags::X_FLIP)) {
std::reverse(spritePixels.begin(), spritePixels.end());
}
}
void Fetcher::dropSpritePixels() {
std::copy(spritePixels.begin() + spritePixelsToDrop,
spritePixels.end(),
spritePixels.begin());
for (Byte i = 8_b - spritePixelsToDrop; i < 8; ++i) {
spritePixels[i].value = 0;
}
}
bool Fetcher::isFetchingSprite() const {
return currentMode == FetcherMode::READ_SPRITE_PATTERN ||
currentMode == FetcherMode::READ_SPRITE_DATA_0 ||
currentMode == FetcherMode::READ_SPRITE_DATA_1 ||
currentMode == FetcherMode::ADD_SPRITE_TO_FIFO;
}
}
|
#include "RecoVertex/VertexTools/interface/PerigeeLinearizedTrackState.h"
#include "RecoVertex/VertexTools/interface/PerigeeRefittedTrackState.h"
#include "TrackingTools/TrajectoryState/interface/PerigeeConversions.h"
#include "RecoVertex/VertexPrimitives/interface/VertexException.h"
#include "MagneticField/Engine/interface/MagneticField.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
void PerigeeLinearizedTrackState::computeJacobians() const
{
GlobalPoint paramPt(theLinPoint);
thePredState = builder(theTSOS, paramPt);
if unlikely(!thePredState.isValid()) return;
double field = theTrack.field()->inInverseGeV(thePredState.theState().position()).z();
if ((std::abs(theCharge)<1e-5)||(fabs(field)<1.e-10)){
//neutral track
computeNeutralJacobians();
} else {
//charged track
computeChargedJacobians();
}
jacobiansAvailable = true;
}
bool PerigeeLinearizedTrackState::operator ==(LinearizedTrackState<5> & other)const
{
const PerigeeLinearizedTrackState* otherP =
dynamic_cast<const PerigeeLinearizedTrackState*>(&other);
if (otherP == 0) {
throw VertexException("PerigeeLinearizedTrackState: don't know how to compare myself to non-perigee track state");
}
return (otherP->track() == theTrack);
}
bool PerigeeLinearizedTrackState::operator ==(ReferenceCountingPointer<LinearizedTrackState<5> >& other)const
{
const PerigeeLinearizedTrackState* otherP =
dynamic_cast<const PerigeeLinearizedTrackState*>(other.get());
if (otherP == 0) {
throw VertexException("PerigeeLinearizedTrackState: don't know how to compare myself to non-perigee track state");
}
return (otherP->track() == theTrack);
}
PerigeeLinearizedTrackState::RefCountedLinearizedTrackState
PerigeeLinearizedTrackState::stateWithNewLinearizationPoint
(const GlobalPoint & newLP) const
{
return RefCountedLinearizedTrackState(
new PerigeeLinearizedTrackState(newLP, track(), theTSOS));
}
PerigeeLinearizedTrackState::RefCountedRefittedTrackState
PerigeeLinearizedTrackState::createRefittedTrackState(
const GlobalPoint & vertexPosition,
const AlgebraicVector3 & vectorParameters,
const AlgebraicSymMatrix66 & covarianceMatrix) const
{
TrajectoryStateClosestToPoint refittedTSCP =
PerigeeConversions::trajectoryStateClosestToPoint(
vectorParameters, vertexPosition, charge(), covarianceMatrix, theTrack.field());
return RefCountedRefittedTrackState(new PerigeeRefittedTrackState(refittedTSCP, vectorParameters));
}
std::vector< PerigeeLinearizedTrackState::RefCountedLinearizedTrackState >
PerigeeLinearizedTrackState::components() const
{
std::vector<RefCountedLinearizedTrackState> result; result.reserve(1);
result.push_back(RefCountedLinearizedTrackState(
const_cast<PerigeeLinearizedTrackState*>(this)));
return result;
}
AlgebraicVector5 PerigeeLinearizedTrackState::refittedParamFromEquation(
const RefCountedRefittedTrackState & theRefittedState) const
{
auto p = theRefittedState->position();
AlgebraicVector3 vertexPosition(p.x(),p.y(),p.z());
AlgebraicVector3 momentum = theRefittedState->momentumVector();
if ((momentum(2)*predictedStateMomentumParameters()(2) < 0)&&(fabs(momentum(2))>M_PI/2) ) {
if (predictedStateMomentumParameters()(2) < 0.) momentum(2)-= 2*M_PI;
if (predictedStateMomentumParameters()(2) > 0.) momentum(2)+= 2*M_PI;
}
AlgebraicVectorN param = constantTerm() +
positionJacobian() * vertexPosition +
momentumJacobian() * momentum;
if (param(2) > M_PI) param(2)-= 2*M_PI;
if (param(2) < -M_PI) param(2)+= 2*M_PI;
return param;
}
void PerigeeLinearizedTrackState::checkParameters(AlgebraicVector5 & parameters) const
{
if (parameters(2) > M_PI) parameters(2)-= 2*M_PI;
if (parameters(2) < -M_PI) parameters(2)+= 2*M_PI;
}
void PerigeeLinearizedTrackState::computeChargedJacobians() const
{
GlobalPoint paramPt(theLinPoint);
//tarjectory parameters
double field = theTrack.field()->inInverseGeV(thePredState.theState().position()).z();
double signTC = -theCharge;
double thetaAtEP = thePredState.perigeeParameters().theta();
double phiAtEP = thePredState.perigeeParameters().phi();
double ptAtEP = thePredState.pt();
double transverseCurvatureAtEP = field / ptAtEP*signTC;
double x_v = thePredState.theState().position().x();
double y_v = thePredState.theState().position().y();
double z_v = thePredState.theState().position().z();
double X = x_v - paramPt.x() - sin(phiAtEP) / transverseCurvatureAtEP;
double Y = y_v - paramPt.y() + cos(phiAtEP) / transverseCurvatureAtEP;
double SS = X*X + Y*Y;
double S = sqrt(SS);
// The track parameters at the expansion point
theExpandedParams[0] = transverseCurvatureAtEP;
theExpandedParams[1] = thetaAtEP;
theExpandedParams[3] = 1/transverseCurvatureAtEP - signTC * S;
double phiFEP;
if (std::abs(X)>std::abs(Y)) {
double signX = (X>0.0? +1.0:-1.0);
phiFEP = -signTC * signX*acos(signTC*Y/S);
} else {
phiFEP = asin(-signTC*X/S);
if ((signTC*Y)<0.0)
phiFEP = M_PI - phiFEP;
}
if (phiFEP>M_PI) phiFEP-= 2*M_PI;
theExpandedParams[2] = phiFEP;
theExpandedParams[4] = z_v - paramPt.z() -
(phiAtEP - theExpandedParams[2]) / tan(thetaAtEP)/transverseCurvatureAtEP;
// The Jacobian: (all at the expansion point)
// [i,j]
// i = 0: rho , 1: theta, 2: phi_p, 3: epsilon, 4: z_p
// j = 0: x_v, 1: y_v, 2: z_v
thePositionJacobian(2,0) = - Y / (SS);
thePositionJacobian(2,1) = X / (SS);
thePositionJacobian(3,0) = - signTC * X / S;
thePositionJacobian(3,1) = - signTC * Y / S;
thePositionJacobian(4,0) = thePositionJacobian(2,0)/tan(thetaAtEP)/transverseCurvatureAtEP;
thePositionJacobian(4,1) = thePositionJacobian(2,1)/tan(thetaAtEP)/transverseCurvatureAtEP;
thePositionJacobian(4,2) = 1;
// [i,j]
// i = 0: rho , 1: theta, 2: phi_p, 3: epsilon, 4: z_p
// j = 0: rho, 1: theta, 2: phi_v
theMomentumJacobian(0,0) = 1;
theMomentumJacobian(1,1) = 1;
theMomentumJacobian(2,0) = -
(X*cos(phiAtEP) + Y*sin(phiAtEP))/
(SS*transverseCurvatureAtEP*transverseCurvatureAtEP);
theMomentumJacobian(2,2) = (Y*cos(phiAtEP) - X*sin(phiAtEP)) /
(SS*transverseCurvatureAtEP);
theMomentumJacobian(3,0) =
(signTC * (Y*cos(phiAtEP) - X*sin(phiAtEP)) / S - 1)/
(transverseCurvatureAtEP*transverseCurvatureAtEP);
theMomentumJacobian(3,2) = signTC *(X*cos(phiAtEP) + Y*sin(phiAtEP))/
(S*transverseCurvatureAtEP);
theMomentumJacobian(4,0) = (phiAtEP - theExpandedParams[2]) /
tan(thetaAtEP)/(transverseCurvatureAtEP*transverseCurvatureAtEP)+
theMomentumJacobian(2,0) / tan(thetaAtEP)/transverseCurvatureAtEP;
theMomentumJacobian(4,1) = (phiAtEP - theExpandedParams[2]) *
(1 + 1/(tan(thetaAtEP)*tan(thetaAtEP)))/transverseCurvatureAtEP;
theMomentumJacobian(4,2) = (theMomentumJacobian(2,2) - 1) /
tan(thetaAtEP)/transverseCurvatureAtEP;
// And finally the residuals:
auto p = thePredState.theState().position();
AlgebraicVector3 expansionPoint(p.x(),p.y(),p.z());
AlgebraicVector3 momentumAtExpansionPoint( transverseCurvatureAtEP,thetaAtEP,phiAtEP);
theConstantTerm = AlgebraicVector5( theExpandedParams -
thePositionJacobian * expansionPoint -
theMomentumJacobian * momentumAtExpansionPoint );
}
void PerigeeLinearizedTrackState::computeNeutralJacobians() const
{
GlobalPoint paramPt(theLinPoint);
//tarjectory parameters
double thetaAtEP = thePredState.theState().momentum().theta();
double phiAtEP = thePredState.theState().momentum().phi();
double ptAtEP = thePredState.theState().momentum().perp();
double x_v = thePredState.theState().position().x();
double y_v = thePredState.theState().position().y();
double z_v = thePredState.theState().position().z();
double X = x_v - paramPt.x();
double Y = y_v - paramPt.y();
// The track parameters at the expansion point
theExpandedParams(0) = 1 / ptAtEP;
theExpandedParams(1) = thetaAtEP;
theExpandedParams(2) = phiAtEP;
theExpandedParams(3) = X*sin(phiAtEP) - Y*cos(phiAtEP);
theExpandedParams(4) = z_v - paramPt.z() -
(X*cos(phiAtEP) + Y*sin(phiAtEP)) / tan(thetaAtEP);
// The Jacobian: (all at the expansion point)
// [i,j]
// i = 0: rho = 1/pt , 1: theta, 2: phi_p, 3: epsilon, 4: z_p
// j = 0: x_v, 1: y_v, 2: z_v
thePositionJacobian(3,0) = sin(phiAtEP);
thePositionJacobian(3,1) = - cos(phiAtEP);
thePositionJacobian(4,0) = - cos(phiAtEP)/tan(thetaAtEP);
thePositionJacobian(4,1) = - sin(phiAtEP)/tan(thetaAtEP);
thePositionJacobian(4,2) = 1;
// [i,j]
// i = 0: rho = 1/pt , 1: theta, 2: phi_p, 3: epsilon, 4: z_p
// j = 0: rho = 1/pt , 1: theta, 2: phi_v
theMomentumJacobian(0,0) = 1;
theMomentumJacobian(1,1) = 1;
theMomentumJacobian(2,2) = 1;
theMomentumJacobian(3,2) = X*cos(phiAtEP) + Y*sin(phiAtEP);
theMomentumJacobian(4,1) = theMomentumJacobian(3,2)*
(1 + 1/(tan(thetaAtEP)*tan(thetaAtEP)));
theMomentumJacobian(4,2) = (X*sin(phiAtEP) - Y*cos(phiAtEP))/tan(thetaAtEP);
// And finally the residuals:
auto p = thePredState.theState().position();
AlgebraicVector3 expansionPoint(p.x(),p.y(),p.z());
AlgebraicVector3 momentumAtExpansionPoint(1./ptAtEP,thetaAtEP,phiAtEP);
theConstantTerm = AlgebraicVector5( theExpandedParams -
thePositionJacobian * expansionPoint -
theMomentumJacobian * momentumAtExpansionPoint );
}
|
#include "parser.h"
#include "vw.h"
#include "parse_regressor.h"
#include "parse_dispatch_loop.h"
using namespace std;
void dispatch_example(vw& all, example& ec)
{
all.learn(ec);
as_singleline(all.l)->finish_example(all, ec);
}
namespace prediction_type
{
#define CASE(type) \
case type: \
return #type;
const char* to_string(prediction_type_t prediction_type)
{
switch (prediction_type)
{
CASE(scalar)
CASE(scalars)
CASE(action_scores)
CASE(action_probs)
CASE(multiclass)
CASE(multilabels)
CASE(prob)
CASE(multiclassprobs)
default:
return "<unsupported>";
}
}
} // namespace prediction_type
namespace LEARNER
{
void dispatch_end_pass(vw& all, example& ec)
{
all.current_pass++;
all.l->end_pass();
VW::finish_example(all, ec);
}
void save(vw& all, example* ec)
{
// save state command
string final_regressor_name = all.final_regressor_name;
if ((ec->tag).size() >= 6 && (ec->tag)[4] == '_')
final_regressor_name = string(ec->tag.begin() + 5, (ec->tag).size() - 5);
if (!all.quiet)
all.trace_message << "saving regressor to " << final_regressor_name << endl;
save_predictor(all, final_regressor_name, 0);
VW::finish_example(all, *ec);
}
bool inline is_save_cmd(example* ec)
{
return (ec->tag.size() >= 4) && (0 == strncmp((const char*)ec->tag.begin(), "save", 4));
}
void process_example(vw& all, example* ec)
{
if (ec->indices.size() > 1) // 1+ nonconstant feature. (most common case first)
dispatch_example(all, *ec);
else if (ec->end_pass)
dispatch_end_pass(all, *ec);
else if (is_save_cmd(ec))
save(all, ec);
else
dispatch_example(all, *ec);
}
void process_multi_ex(vw& all, multi_ex& ec_seq)
{
all.learn(ec_seq);
as_multiline(all.l)->finish_example(all, ec_seq);
}
/* example headers have the word "shared" */
bool ec_is_example_header(example& ec)
{
v_array<CB::cb_class> costs = ec.l.cb.costs;
if (costs.size() != 1)
return false;
if (costs[0].probability == -1.f)
return true;
return false;
}
/* is this just a newline */
inline bool example_is_newline_not_header(example& ec) { return (example_is_newline(ec) && !ec_is_example_header(ec)); }
/* Adds an example to multiline collection
* Returns: true if complete and false if incomplete example */
bool complete_multi_ex(example* ec, multi_ex& ec_seq, vw& all)
{
const bool is_test_ec = all.p->lp.test_label(&ec->l);
const bool need_to_break = VW::is_ring_example(all, ec) && (ec_seq.size() >= all.p->ring_size - 2);
if ((example_is_newline_not_header(*ec) && is_test_ec) || need_to_break)
{
VW::finish_example(all, *ec);
if (ec_seq.size() == 0)
{
cout << "Something is wrong---an example with no choice. Do you have all 0 features? Or multiple empty lines?"
<< endl;
return false;
}
return true; // example complete
}
ec_seq.push_back(ec);
return false;
}
template <void (*f)(vw&, multi_ex&)>
void dispatch_multi_ex(vw& all, multi_ex& ec_seq)
{
f(all, ec_seq); // call learn or predict
VW::finish_example(all, ec_seq); // clean up
}
template <void (*f)(vw&, multi_ex&)>
void dispatch_multi_ex(vw& all, example* ec, multi_ex& ec_seq)
{
if (complete_multi_ex(ec, ec_seq, all))
{
dispatch_multi_ex<f>(all, ec_seq);
}
}
template <void (*f)(vw&, multi_ex&)>
void on_new_partial_ex(example* ec, multi_ex& ec_seq, vw& all)
{
if (ec != nullptr)
{
if (ec->indices.size() > 1) // 1+ nonconstant feature. (most common case first)
dispatch_multi_ex<f>(all, ec, ec_seq);
else if (ec->end_pass)
dispatch_end_pass(all, *ec);
else if (is_save_cmd(ec))
save(all, ec);
else
dispatch_multi_ex<f>(all, ec, ec_seq);
}
else
{
if (ec_seq.size() > 0)
dispatch_multi_ex<f>(all, ec_seq);
}
}
template <void (*f)(vw&, multi_ex&)>
void multi_ex_generic_driver(vw& all)
{
multi_ex ec_seq;
example* ec = nullptr;
while (all.early_terminate == false)
{
ec = VW::get_example(all.p);
on_new_partial_ex<f>(ec, ec_seq, all);
if (ec == nullptr)
break;
}
if (all.early_terminate) // drain any extra examples from parser.
while ((ec = VW::get_example(all.p)) != nullptr) VW::finish_example(all, *ec);
all.l->end_examples();
}
template <class T, void (*f)(T, example*)>
void generic_driver(vw& all, T context)
{
example* ec = nullptr;
while (all.early_terminate == false)
if ((ec = VW::get_example(all.p)) != nullptr)
f(context, ec);
else
break;
if (all.early_terminate) // drain any extra examples from parser.
while ((ec = VW::get_example(all.p)) != nullptr) VW::finish_example(all, *ec);
all.l->end_examples();
}
void process_multiple(vector<vw*> alls, example* ec)
{
// start with last as the first instance will free the example as it is the owner
for (auto it = alls.rbegin(); it != alls.rend(); ++it) process_example(**it, ec);
}
void generic_driver(vector<vw*> alls)
{
generic_driver<vector<vw*>, process_multiple>(**alls.begin(), alls);
// skip first as it already called end_examples()
auto it = alls.begin();
for (it++; it != alls.end(); it++) (*it)->l->end_examples();
}
void generic_driver(vw& all)
{
if (all.l->is_multiline)
multi_ex_generic_driver<process_multi_ex>(all);
else
generic_driver<vw&, process_example>(all, all);
}
void dispatch(vw& all, v_array<example*> examples)
{
all.p->end_parsed_examples += examples.size(); // divergence: lock & signal
for (size_t i = 0; i < examples.size(); ++i) process_example(all, examples[i]);
}
void generic_driver_onethread(vw& all)
{
if (all.l->is_multiline)
{
multi_ex ctxt;
auto multi_ex_fptr = [&ctxt](vw& all, v_array<example*> examples) {
all.p->end_parsed_examples += examples.size(); // divergence: lock & signal
for (size_t i = 0; i < examples.size(); ++i) on_new_partial_ex<process_multi_ex>(examples[i], ctxt, all);
};
parse_dispatch(all, multi_ex_fptr);
// flush accumulated examples if there is no newline
// at the end of the file
on_new_partial_ex<process_multi_ex>(nullptr, ctxt, all);
}
else
parse_dispatch(all, dispatch);
all.l->end_examples();
}
float recur_sensitivity(void*, base_learner& base, example& ec) { return base.sensitivity(ec); }
} // namespace LEARNER
|
//
// OctreeQueryNode.cpp
// assignment-client/src/octree
//
// Created by Stephen Birarda on 3/21/13.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "OctreeQueryNode.h"
#include <cstring>
#include <cstdio>
#include <udt/PacketHeaders.h>
#include <SharedUtil.h>
#include <UUID.h>
#include "OctreeSendThread.h"
OctreeQueryNode::OctreeQueryNode() :
_viewSent(false),
_octreePacket(),
_octreePacketWaiting(false),
_lastOctreePayload(new char[udt::MAX_PACKET_SIZE]),
_lastOctreePacketLength(0),
_duplicatePacketCount(0),
_firstSuppressedPacket(usecTimestampNow()),
_maxSearchLevel(1),
_maxLevelReachedInLastSearch(1),
_lastTimeBagEmpty(0),
_viewFrustumChanging(false),
_viewFrustumJustStoppedChanging(true),
_currentPacketIsColor(true),
_currentPacketIsCompressed(false),
_octreeSendThread(NULL),
_lastClientBoundaryLevelAdjust(0),
_lastClientOctreeSizeScale(DEFAULT_OCTREE_SIZE_SCALE),
_lodChanged(false),
_lodInitialized(false),
_sequenceNumber(0),
_lastRootTimestamp(0),
_myPacketType(PacketType::Unknown),
_isShuttingDown(false),
_sentPacketHistory()
{
}
OctreeQueryNode::~OctreeQueryNode() {
_isShuttingDown = true;
if (_octreeSendThread) {
forceNodeShutdown();
}
delete[] _lastOctreePayload;
}
void OctreeQueryNode::nodeKilled() {
_isShuttingDown = true;
elementBag.unhookNotifications(); // if our node is shutting down, then we no longer need octree element notifications
if (_octreeSendThread) {
// just tell our thread we want to shutdown, this is asynchronous, and fast, we don't need or want it to block
// while the thread actually shuts down
_octreeSendThread->setIsShuttingDown();
}
}
void OctreeQueryNode::forceNodeShutdown() {
_isShuttingDown = true;
elementBag.unhookNotifications(); // if our node is shutting down, then we no longer need octree element notifications
if (_octreeSendThread) {
// we really need to force our thread to shutdown, this is synchronous, we will block while the thread actually
// shuts down because we really need it to shutdown, and it's ok if we wait for it to complete
OctreeSendThread* sendThread = _octreeSendThread;
_octreeSendThread = NULL;
sendThread->setIsShuttingDown();
sendThread->terminate();
delete sendThread;
}
}
void OctreeQueryNode::sendThreadFinished() {
// We've been notified by our thread that it is shutting down. So we can clean up our reference to it, and
// delete the actual thread object. Cleaning up our thread will correctly unroll all refereces to shared
// pointers to our node as well as the octree server assignment
if (_octreeSendThread) {
OctreeSendThread* sendThread = _octreeSendThread;
_octreeSendThread = NULL;
delete sendThread;
}
}
void OctreeQueryNode::initializeOctreeSendThread(OctreeServer* myServer, const SharedNodePointer& node) {
_octreeSendThread = new OctreeSendThread(myServer, node);
// we want to be notified when the thread finishes
connect(_octreeSendThread, &GenericThread::finished, this, &OctreeQueryNode::sendThreadFinished);
_octreeSendThread->initialize(true);
}
bool OctreeQueryNode::packetIsDuplicate() const {
// if shutting down, return immediately
if (_isShuttingDown) {
return false;
}
// since our packets now include header information, like sequence number, and createTime, we can't just do a memcmp
// of the entire packet, we need to compare only the packet content...
if (_lastOctreePacketLength == _octreePacket->getPayloadSize()) {
if (memcmp(_lastOctreePayload + OCTREE_PACKET_EXTRA_HEADERS_SIZE,
_octreePacket->getPayload() + OCTREE_PACKET_EXTRA_HEADERS_SIZE,
_octreePacket->getPayloadSize() - OCTREE_PACKET_EXTRA_HEADERS_SIZE) == 0) {
return true;
}
}
return false;
}
bool OctreeQueryNode::shouldSuppressDuplicatePacket() {
// if shutting down, return immediately
if (_isShuttingDown) {
return true;
}
bool shouldSuppress = false; // assume we won't suppress
// only consider duplicate packets
if (packetIsDuplicate()) {
_duplicatePacketCount++;
// If this is the first suppressed packet, remember our time...
if (_duplicatePacketCount == 1) {
_firstSuppressedPacket = usecTimestampNow();
}
// How long has it been since we've sent one, if we're still under our max time, then keep considering
// this packet for suppression
quint64 now = usecTimestampNow();
long sinceFirstSuppressedPacket = now - _firstSuppressedPacket;
const long MAX_TIME_BETWEEN_DUPLICATE_PACKETS = 1000 * 1000; // 1 second.
if (sinceFirstSuppressedPacket < MAX_TIME_BETWEEN_DUPLICATE_PACKETS) {
// Finally, if we know we've sent at least one duplicate out, then suppress the rest...
if (_duplicatePacketCount >= 1) {
shouldSuppress = true;
}
} else {
// Reset our count, we've reached our maximum time.
_duplicatePacketCount = 0;
}
} else {
// Reset our count, it wasn't a duplicate
_duplicatePacketCount = 0;
}
return shouldSuppress;
}
void OctreeQueryNode::init() {
_myPacketType = getMyPacketType();
_octreePacket = NLPacket::create(getMyPacketType());
resetOctreePacket(); // don't bump sequence
}
void OctreeQueryNode::resetOctreePacket() {
// if shutting down, return immediately
if (_isShuttingDown) {
return;
}
// Whenever we call this, we will keep a copy of the last packet, so we can determine if the last packet has
// changed since we last reset it. Since we know that no two packets can ever be identical without being the same
// scene information, (e.g. the root node packet of a static scene), we can use this as a strategy for reducing
// packet send rate.
_lastOctreePacketLength = _octreePacket->getPayloadSize();
memcpy(_lastOctreePayload, _octreePacket->getPayload(), _lastOctreePacketLength);
// If we're moving, and the client asked for low res, then we force monochrome, otherwise, use
// the clients requested color state.
_currentPacketIsColor = getWantColor();
_currentPacketIsCompressed = getWantCompression();
OCTREE_PACKET_FLAGS flags = 0;
if (_currentPacketIsColor) {
setAtBit(flags, PACKET_IS_COLOR_BIT);
}
if (_currentPacketIsCompressed) {
setAtBit(flags, PACKET_IS_COMPRESSED_BIT);
}
_octreePacket->reset();
// pack in flags
_octreePacket->writePrimitive(flags);
// pack in sequence number
_octreePacket->writePrimitive(_sequenceNumber);
// pack in timestamp
OCTREE_PACKET_SENT_TIME now = usecTimestampNow();
_octreePacket->writePrimitive(now);
_octreePacketWaiting = false;
}
void OctreeQueryNode::writeToPacket(const unsigned char* buffer, unsigned int bytes) {
// if shutting down, return immediately
if (_isShuttingDown) {
return;
}
// compressed packets include lead bytes which contain compressed size, this allows packing of
// multiple compressed portions together
if (_currentPacketIsCompressed) {
OCTREE_PACKET_INTERNAL_SECTION_SIZE sectionSize = bytes;
_octreePacket->writePrimitive(sectionSize);
}
if (bytes <= _octreePacket->bytesAvailableForWrite()) {
_octreePacket->write(reinterpret_cast<const char*>(buffer), bytes);
_octreePacketWaiting = true;
}
}
bool OctreeQueryNode::updateCurrentViewFrustum() {
// if shutting down, return immediately
if (_isShuttingDown) {
return false;
}
bool currentViewFrustumChanged = false;
ViewFrustum newestViewFrustum;
// get position and orientation details from the camera
newestViewFrustum.setPosition(getCameraPosition());
newestViewFrustum.setOrientation(getCameraOrientation());
// Also make sure it's got the correct lens details from the camera
float originalFOV = getCameraFov();
float wideFOV = originalFOV + VIEW_FRUSTUM_FOV_OVERSEND;
if (0.0f != getCameraAspectRatio() &&
0.0f != getCameraNearClip() &&
0.0f != getCameraFarClip() &&
getCameraNearClip() != getCameraFarClip()) {
newestViewFrustum.setProjection(glm::perspective(
glm::radians(wideFOV), // hack
getCameraAspectRatio(),
getCameraNearClip(),
getCameraFarClip()));
}
// if there has been a change, then recalculate
if (!newestViewFrustum.isVerySimilar(_currentViewFrustum)) {
_currentViewFrustum = newestViewFrustum;
_currentViewFrustum.calculate();
currentViewFrustumChanged = true;
}
// Also check for LOD changes from the client
if (_lodInitialized) {
if (_lastClientBoundaryLevelAdjust != getBoundaryLevelAdjust()) {
_lastClientBoundaryLevelAdjust = getBoundaryLevelAdjust();
_lodChanged = true;
}
if (_lastClientOctreeSizeScale != getOctreeSizeScale()) {
_lastClientOctreeSizeScale = getOctreeSizeScale();
_lodChanged = true;
}
} else {
_lodInitialized = true;
_lastClientOctreeSizeScale = getOctreeSizeScale();
_lastClientBoundaryLevelAdjust = getBoundaryLevelAdjust();
_lodChanged = false;
}
// When we first detect that the view stopped changing, we record this.
// but we don't change it back to false until we've completely sent this
// scene.
if (_viewFrustumChanging && !currentViewFrustumChanged) {
_viewFrustumJustStoppedChanging = true;
}
_viewFrustumChanging = currentViewFrustumChanged;
return currentViewFrustumChanged;
}
void OctreeQueryNode::setViewSent(bool viewSent) {
_viewSent = viewSent;
if (viewSent) {
_viewFrustumJustStoppedChanging = false;
_lodChanged = false;
}
}
void OctreeQueryNode::updateLastKnownViewFrustum() {
// if shutting down, return immediately
if (_isShuttingDown) {
return;
}
bool frustumChanges = !_lastKnownViewFrustum.isVerySimilar(_currentViewFrustum);
if (frustumChanges) {
// save our currentViewFrustum into our lastKnownViewFrustum
_lastKnownViewFrustum = _currentViewFrustum;
}
// save that we know the view has been sent.
setLastTimeBagEmpty();
}
bool OctreeQueryNode::moveShouldDump() const {
// if shutting down, return immediately
if (_isShuttingDown) {
return false;
}
glm::vec3 oldPosition = _lastKnownViewFrustum.getPosition();
glm::vec3 newPosition = _currentViewFrustum.getPosition();
// theoretically we could make this slightly larger but relative to avatar scale.
const float MAXIMUM_MOVE_WITHOUT_DUMP = 0.0f;
if (glm::distance(newPosition, oldPosition) > MAXIMUM_MOVE_WITHOUT_DUMP) {
return true;
}
return false;
}
void OctreeQueryNode::dumpOutOfView() {
// if shutting down, return immediately
if (_isShuttingDown) {
return;
}
int stillInView = 0;
int outOfView = 0;
OctreeElementBag tempBag;
while (!elementBag.isEmpty()) {
OctreeElementPointer elementToCheck = elementBag.extract();
if (elementToCheck->isInView(_currentViewFrustum)) {
tempBag.insert(elementToCheck);
stillInView++;
} else {
outOfView++;
}
}
if (stillInView > 0) {
while (!tempBag.isEmpty()) {
OctreeElementPointer elementToKeepInBag = tempBag.extract();
if (elementToKeepInBag->isInView(_currentViewFrustum)) {
elementBag.insert(elementToKeepInBag);
}
}
}
}
void OctreeQueryNode::packetSent(const NLPacket& packet) {
_sentPacketHistory.packetSent(_sequenceNumber, packet);
_sequenceNumber++;
}
bool OctreeQueryNode::hasNextNackedPacket() const {
return !_nackedSequenceNumbers.isEmpty();
}
const NLPacket* OctreeQueryNode::getNextNackedPacket() {
if (!_nackedSequenceNumbers.isEmpty()) {
// could return null if packet is not in the history
return _sentPacketHistory.getPacket(_nackedSequenceNumbers.dequeue());
}
return nullptr;
}
void OctreeQueryNode::parseNackPacket(NLPacket& packet) {
// read sequence numbers
while (packet.bytesLeftToRead()) {
OCTREE_PACKET_SEQUENCE sequenceNumber;
packet.readPrimitive(&sequenceNumber);
_nackedSequenceNumbers.enqueue(sequenceNumber);
}
}
|
#include "src/query.h"
#include "src/query_parser/tokenizer.h"
#include "src/stopwords.h"
#include "src/extension.h"
#include "src/ext/default.h"
#include "gtest/gtest.h"
#include <stdio.h>
#define QUERY_PARSE_CTX(ctx, qt, opts) NewQueryParseCtx(&ctx, qt, strlen(qt), &opts);
struct SearchOptionsCXX : RSSearchOptions {
SearchOptionsCXX() {
memset(this, 0, sizeof(*this));
flags = RS_DEFAULT_QUERY_FLAGS;
fieldmask = RS_FIELDMASK_ALL;
language = DEFAULT_LANGUAGE;
stopwords = DefaultStopWordList();
}
};
class QASTCXX : public QueryAST {
SearchOptionsCXX m_opts;
QueryError m_status = {QueryErrorCode(0)};
RedisSearchCtx *sctx = NULL;
public:
QASTCXX() {
memset(static_cast<QueryAST *>(this), 0, sizeof(QueryAST));
}
QASTCXX(RedisSearchCtx &sctx) : QASTCXX() {
setContext(&sctx);
}
void setContext(RedisSearchCtx *sctx) {
this->sctx = sctx;
}
bool parse(const char *s) {
QueryError_ClearError(&m_status);
QAST_Destroy(this);
int rc = QAST_Parse(this, sctx, &m_opts, s, strlen(s), &m_status);
return rc == REDISMODULE_OK && !QueryError_HasError(&m_status) && root != NULL;
}
void print() const {
QAST_Print(this, sctx->spec);
}
const char *getError() const {
return QueryError_GetError(&m_status);
}
~QASTCXX() {
QueryError_ClearError(&m_status);
QAST_Destroy(this);
}
};
bool isValidQuery(const char *qt, RedisSearchCtx &ctx) {
QASTCXX ast;
ast.setContext(&ctx);
return ast.parse(qt);
// if (err) {
// Query_Free(q);
// fprintf(stderr, "Error parsing query '%s': %s\n", qt, err);
// free(err);
// return 1;
// }
// Query_Free(q);
// return 0;
}
#define assertValidQuery(qt, ctx) ASSERT_TRUE(isValidQuery(qt, ctx))
#define assertInvalidQuery(qt, ctx) ASSERT_FALSE(isValidQuery(qt, ctx))
class QueryTest : public ::testing::Test {};
TEST_F(QueryTest, testParser) {
RedisSearchCtx ctx;
static const char *args[] = {"SCHEMA", "title", "text", "weight", "0.1",
"body", "text", "weight", "2.0", "bar",
"numeric", "loc", "geo", "tags", "tag"};
QueryError err = {QueryErrorCode(0)};
ctx.spec = IndexSpec_Parse("idx", args, sizeof(args) / sizeof(const char *), &err);
ASSERT_FALSE(QueryError_HasError(&err)) << QueryError_GetError(&err);
// test some valid queries
assertValidQuery("hello", ctx);
assertValidQuery("hello wor*", ctx);
assertValidQuery("hello world", ctx);
assertValidQuery("hello (world)", ctx);
assertValidQuery("\"hello world\"", ctx);
assertValidQuery("\"hello\"", ctx);
assertValidQuery("\"hello world\" \"foo bar\"", ctx);
assertValidQuery("\"hello world\"|\"foo bar\"", ctx);
assertValidQuery("\"hello world\" (\"foo bar\")", ctx);
assertValidQuery("hello \"foo bar\" world", ctx);
assertValidQuery("hello|hallo|yellow world", ctx);
assertValidQuery("(hello|world|foo) bar baz 123", ctx);
assertValidQuery("(hello|world|foo) (bar baz)", ctx);
// assertValidQuery("(hello world|foo \"bar baz\") \"bar baz\" bbbb");
assertValidQuery("@title:(barack obama) @body:us|president", ctx);
assertValidQuery("@ti_tle:barack obama @body:us", ctx);
assertValidQuery("@title:barack @body:obama", ctx);
assertValidQuery("@tit_le|bo_dy:barack @body|title|url|something_else:obama", ctx);
assertValidQuery("hello world&good+bye foo.bar", ctx);
assertValidQuery("@BusinessName:\"Wells Fargo Bank, National Association\"", ctx);
// escaping and unicode in field names
assertValidQuery("@Business\\:\\-\\ Name:Wells Fargo", ctx);
assertValidQuery("@שלום:Wells Fargo", ctx);
assertValidQuery("foo -bar -(bar baz)", ctx);
assertValidQuery("(hello world)|(goodbye moon)", ctx);
assertInvalidQuery("@title:", ctx);
assertInvalidQuery("@body:@title:", ctx);
assertInvalidQuery("@body|title:@title:", ctx);
assertInvalidQuery("@body|title", ctx);
assertValidQuery("hello ~world ~war", ctx);
assertValidQuery("hello ~(world war)", ctx);
assertValidQuery("-foo", ctx);
assertValidQuery("@title:-foo", ctx);
assertValidQuery("-@title:foo", ctx);
// some geo queries
assertValidQuery("@loc:[15.1 -15 30 km]", ctx);
assertValidQuery("@loc:[15 -15.1 30 m]", ctx);
assertValidQuery("@loc:[15.03 -15.45 30 mi]", ctx);
assertValidQuery("@loc:[15.65 -15.65 30 ft]", ctx);
assertValidQuery("hello world @loc:[15.65 -15.65 30 ft]", ctx);
assertValidQuery("hello world -@loc:[15.65 -15.65 30 ft]", ctx);
assertValidQuery("hello world ~@loc:[15.65 -15.65 30 ft]", ctx);
assertValidQuery("@title:hello world ~@loc:[15.65 -15.65 30 ft]", ctx);
assertValidQuery("@loc:[15.65 -15.65 30 ft] @loc:[15.65 -15.65 30 ft]", ctx);
assertValidQuery("@loc:[15.65 -15.65 30 ft]|@loc:[15.65 -15.65 30 ft]", ctx);
assertValidQuery("hello (world @loc:[15.65 -15.65 30 ft])", ctx);
assertInvalidQuery("@loc:[190.65 -100.65 30 ft])", ctx);
assertInvalidQuery("@loc:[50 50 -1 ft])", ctx);
assertInvalidQuery("@loc:[50 50 1 quoops])", ctx);
assertInvalidQuery("@loc:[50 50 1 ftps])", ctx);
assertInvalidQuery("@loc:[50 50 1 1])", ctx);
assertInvalidQuery("@loc:[50 50 1])", ctx);
// numeric
assertValidQuery("@number:[100 200]", ctx);
assertValidQuery("@number:[100 -200]", ctx);
assertValidQuery("@number:[(100 (200]", ctx);
assertValidQuery("@number:[100 inf]", ctx);
assertValidQuery("@number:[100 -inf]", ctx);
assertValidQuery("@number:[-inf +inf]", ctx);
assertValidQuery("@number:[-inf +inf]|@number:[100 200]", ctx);
assertInvalidQuery("@number:[100 foo]", ctx);
// Tag queries
assertValidQuery("@tags:{foo}", ctx);
assertValidQuery("@tags:{foo|bar baz|boo}", ctx);
assertValidQuery("@tags:{foo|bar\\ baz|boo}", ctx);
assertValidQuery("@tags:{foo*}", ctx);
assertValidQuery("@tags:{foo\\-*}", ctx);
assertValidQuery("@tags:{bar | foo*}", ctx);
assertValidQuery("@tags:{bar* | foo}", ctx);
assertValidQuery("@tags:{bar* | foo*}", ctx);
assertInvalidQuery("@tags:{foo|bar\\ baz|}", ctx);
assertInvalidQuery("@tags:{foo|bar\\ baz|", ctx);
assertInvalidQuery("{foo|bar\\ baz}", ctx);
assertInvalidQuery("(foo", ctx);
assertInvalidQuery("\"foo", ctx);
assertValidQuery("", ctx);
assertInvalidQuery("()", ctx);
// test stopwords
assertValidQuery("a for is", ctx);
assertValidQuery("a|for|is", ctx);
assertValidQuery("a little bit of party", ctx);
assertValidQuery("no-as", ctx);
assertValidQuery("~no~as", ctx);
assertValidQuery("(no -as) =>{$weight: 0.5}", ctx);
assertValidQuery("@foo:-as", ctx);
// test utf-8 query
assertValidQuery("שלום עולם", ctx);
// Test attribute
assertValidQuery("(foo bar) => {$weight: 0.5; $slop: 2}", ctx);
assertValidQuery("foo => {$weight: 0.5} bar => {$weight: 0.1}", ctx);
assertValidQuery("@title:(foo bar) => {$weight: 0.5; $slop: 2}", ctx);
assertValidQuery(
"@title:(foo bar) => {$weight: 0.5; $slop: 2} @body:(foo bar) => {$weight: 0.5; $slop: 2}",
ctx);
assertValidQuery("(foo => {$weight: 0.5;}) | ((bar) => {$weight: 0.5})", ctx);
assertValidQuery("(foo => {$weight: 0.5;}) ((bar) => {}) => {}", ctx);
assertValidQuery("@tag:{foo | bar} => {$weight: 0.5;} ", ctx);
assertValidQuery("@num:[0 100] => {$weight: 0.5;} ", ctx);
assertInvalidQuery("@tag:{foo | bar} => {$weight: -0.5;} ", ctx);
assertInvalidQuery("@tag:{foo | bar} => {$great: 0.5;} ", ctx);
assertInvalidQuery("@tag:{foo | bar} => {$great:;} ", ctx);
assertInvalidQuery("@tag:{foo | bar} => {$:1;} ", ctx);
assertInvalidQuery(" => {$weight: 0.5;} ", ctx);
const char *qt = "(hello|world) and \"another world\" (foo is bar) -(baz boo*)";
QASTCXX ast;
ast.setContext(&ctx);
ASSERT_TRUE(ast.parse(qt));
QueryNode *n = ast.root;
//QAST_Print(&ast, ctx.spec);
ASSERT_TRUE(n != NULL);
ASSERT_EQ(n->type, QN_PHRASE);
ASSERT_EQ(n->pn.exact, 0);
ASSERT_EQ(QueryNode_NumChildren(n), 4);
ASSERT_EQ(n->opts.fieldMask, RS_FIELDMASK_ALL);
ASSERT_TRUE(n->children[0]->type == QN_UNION);
ASSERT_STREQ("hello", n->children[0]->children[0]->tn.str);
ASSERT_STREQ("world", n->children[0]->children[1]->tn.str);
QueryNode *_n = n->children[1];
ASSERT_TRUE(_n->type == QN_PHRASE);
ASSERT_TRUE(_n->pn.exact == 1);
ASSERT_EQ(QueryNode_NumChildren(_n), 2);
ASSERT_STREQ("another", _n->children[0]->tn.str);
ASSERT_STREQ("world", _n->children[1]->tn.str);
_n = n->children[2];
ASSERT_TRUE(_n->type == QN_PHRASE);
ASSERT_TRUE(_n->pn.exact == 0);
ASSERT_EQ(QueryNode_NumChildren(_n), 2);
ASSERT_STREQ("foo", _n->children[0]->tn.str);
ASSERT_STREQ("bar", _n->children[1]->tn.str);
_n = n->children[3];
ASSERT_TRUE(_n->type == QN_NOT);
_n = QueryNode_GetChild(_n, 0);
ASSERT_TRUE(_n->pn.exact == 0);
ASSERT_EQ(2, QueryNode_NumChildren(_n));
ASSERT_STREQ("baz", _n->children[0]->tn.str);
ASSERT_EQ(_n->children[1]->type, QN_PREFIX);
ASSERT_STREQ("boo", _n->children[1]->pfx.str);
QAST_Destroy(&ast);
IndexSpec_Free(ctx.spec);
}
TEST_F(QueryTest, testPureNegative) {
const char *qs[] = {"-@title:hello", "-hello", "@title:-hello", "-(foo)", "-foo", "(-foo)", NULL};
static const char *args[] = {"SCHEMA", "title", "text", "weight", "0.1", "body",
"text", "weight", "2.0", "bar", "numeric"};
QueryError err = {QueryErrorCode(0)};
IndexSpec *spec = IndexSpec_Parse("idx", args, sizeof(args) / sizeof(const char *), &err);
RedisSearchCtx ctx = SEARCH_CTX_STATIC(NULL, spec);
for (size_t i = 0; qs[i] != NULL; i++) {
QASTCXX ast;
ast.setContext(&ctx);
ASSERT_TRUE(ast.parse(qs[i])) << ast.getError();
QueryNode *n = ast.root;
ASSERT_TRUE(n != NULL);
ASSERT_EQ(n->type, QN_NOT);
ASSERT_TRUE(QueryNode_GetChild(n, 0) != NULL);
}
IndexSpec_Free(ctx.spec);
}
TEST_F(QueryTest, testGeoQuery) {
static const char *args[] = {"SCHEMA", "title", "text", "loc", "geo"};
QueryError err = {QueryErrorCode(0)};
IndexSpec *spec = IndexSpec_Parse("idx", args, sizeof(args) / sizeof(const char *), &err);
RedisSearchCtx ctx = SEARCH_CTX_STATIC(NULL, spec);
const char *qt = "@title:hello world @loc:[31.52 32.1342 10.01 km]";
QASTCXX ast;
ast.setContext(&ctx);
ASSERT_TRUE(ast.parse(qt)) << ast.getError();
QueryNode *n = ast.root;
ASSERT_EQ(n->type, QN_PHRASE);
ASSERT_TRUE((n->opts.fieldMask == RS_FIELDMASK_ALL));
ASSERT_EQ(QueryNode_NumChildren(n), 2);
QueryNode *gn = n->children[1];
ASSERT_EQ(gn->type, QN_GEO);
ASSERT_STREQ(gn->gn.gf->property, "loc");
ASSERT_EQ(gn->gn.gf->unitType, GEO_DISTANCE_KM);
ASSERT_EQ(gn->gn.gf->lon, 31.52);
ASSERT_EQ(gn->gn.gf->lat, 32.1342);
ASSERT_EQ(gn->gn.gf->radius, 10.01);
IndexSpec_Free(ctx.spec);
}
TEST_F(QueryTest, testFieldSpec) {
static const char *args[] = {"SCHEMA", "title", "text", "weight", "0.1", "body",
"text", "weight", "2.0", "bar", "numeric"};
QueryError err = {QUERY_OK};
IndexSpec *spec = IndexSpec_Parse("idx", args, sizeof(args) / sizeof(const char *), &err);
RedisSearchCtx ctx = SEARCH_CTX_STATIC(NULL, spec);
const char *qt = "@title:hello world";
QASTCXX ast(ctx);
ASSERT_TRUE(ast.parse(qt)) << ast.getError();
//ast.print();
QueryNode *n = ast.root;
ASSERT_EQ(n->type, QN_PHRASE);
ASSERT_EQ(n->opts.fieldMask, 0x01);
qt = "(@title:hello) (@body:world)";
ASSERT_TRUE(ast.parse(qt)) << ast.getError();
n = ast.root;
ASSERT_TRUE(n != NULL);
//printf("%s ====> ", qt);
//ast.print();
ASSERT_EQ(n->type, QN_PHRASE);
ASSERT_EQ(n->opts.fieldMask, RS_FIELDMASK_ALL);
ASSERT_EQ(n->children[0]->opts.fieldMask, 0x01);
ASSERT_EQ(n->children[1]->opts.fieldMask, 0x02);
// test field modifiers
qt = "@title:(hello world) @body:(world apart) @adas_dfsd:fofofof";
ASSERT_TRUE(ast.parse(qt)) << ast.getError();
n = ast.root;
//printf("%s ====> ", qt);
//ast.print();
ASSERT_EQ(n->type, QN_PHRASE);
ASSERT_EQ(n->opts.fieldMask, RS_FIELDMASK_ALL);
ASSERT_EQ(QueryNode_NumChildren(n), 3);
ASSERT_EQ(n->children[0]->opts.fieldMask, 0x01);
ASSERT_EQ(n->children[1]->opts.fieldMask, 0x02);
ASSERT_EQ(n->children[2]->opts.fieldMask, 0x00);
// ASSERT_EQ(n->children[2]->fieldMask, 0x00)
// test numeric ranges
qt = "@num:[0.4 (500]";
ASSERT_TRUE(ast.parse(qt)) << ast.getError();
n = ast.root;
ASSERT_EQ(n->type, QN_NUMERIC);
ASSERT_EQ(n->nn.nf->min, 0.4);
ASSERT_EQ(n->nn.nf->max, 500.0);
ASSERT_EQ(n->nn.nf->inclusiveMin, 1);
ASSERT_EQ(n->nn.nf->inclusiveMax, 0);
IndexSpec_Free(ctx.spec);
}
TEST_F(QueryTest, testAttributes) {
static const char *args[] = {"SCHEMA", "title", "text", "body", "text"};
QueryError err = {QUERY_OK};
IndexSpec *spec = IndexSpec_Parse("idx", args, sizeof(args) / sizeof(const char *), &err);
RedisSearchCtx ctx = SEARCH_CTX_STATIC(NULL, spec);
const char *qt =
"(@title:(foo bar) => {$weight: 0.5} @body:lol => {$weight: 0.2}) => "
"{$weight:0.3; $slop:2; $inorder:true}";
QASTCXX ast(ctx);
ASSERT_TRUE(ast.parse(qt)) << ast.getError();
QueryNode *n = ast.root;
ASSERT_EQ(0.3, n->opts.weight);
ASSERT_EQ(2, n->opts.maxSlop);
ASSERT_EQ(1, n->opts.inOrder);
ASSERT_EQ(n->type, QN_PHRASE);
ASSERT_EQ(QueryNode_NumChildren(n), 2);
ASSERT_EQ(0.5, n->children[0]->opts.weight);
ASSERT_EQ(0.2, n->children[1]->opts.weight);
IndexSpec_Free(ctx.spec);
}
TEST_F(QueryTest, testTags) {
static const char *args[] = {"SCHEMA", "title", "text", "tags", "tag", "separator", ";"};
QueryError err = {QUERY_OK};
IndexSpec *spec = IndexSpec_Parse("idx", args, sizeof(args) / sizeof(const char *), &err);
RedisSearchCtx ctx = SEARCH_CTX_STATIC(NULL, spec);
const char *qt = "@tags:{hello world |foo| שלום| lorem\\ ipsum }";
QASTCXX ast(ctx);
ASSERT_TRUE(ast.parse(qt)) << ast.getError();
//ast.print();
QueryNode *n = ast.root;
ASSERT_EQ(n->type, QN_TAG);
ASSERT_EQ(4, QueryNode_NumChildren(n));
ASSERT_EQ(QN_PHRASE, n->children[0]->type);
ASSERT_STREQ("hello", n->children[0]->children[0]->tn.str);
ASSERT_STREQ("world", n->children[0]->children[1]->tn.str);
ASSERT_EQ(QN_TOKEN, n->children[1]->type);
ASSERT_STREQ("foo", n->children[1]->tn.str);
ASSERT_EQ(QN_TOKEN, n->children[2]->type);
ASSERT_STREQ("שלום", n->children[2]->tn.str);
ASSERT_EQ(QN_TOKEN, n->children[3]->type);
ASSERT_STREQ("lorem\\ ipsum", n->children[3]->tn.str);
IndexSpec_Free(ctx.spec);
}
|
#include <iostream>
#include <cstdlib>
#include <algorithm>
bool almost_equal(float x, float gold, float rel_tol=1e-09, float abs_tol=0.0) {
return std::abs(x-gold) <= std::max(rel_tol * std::max(std::abs(x), std::abs(gold)), abs_tol);
}
void test_target__teams__distribute() {
const int N0 { 32768 };
const float expected_value { N0 };
float counter_N0{};
#pragma omp target map(tofrom: counter_N0)
#pragma omp teams reduction(+: counter_N0)
#pragma omp distribute
for (int i0 = 0 ; i0 < N0 ; i0++ )
{
counter_N0 = counter_N0 + 1. ;
}
if (!almost_equal(counter_N0, expected_value, 0.01)) {
std::cerr << "Expected: " << expected_value << " Got: " << counter_N0 << std::endl;
std::exit(112);
}
}
int main()
{
test_target__teams__distribute();
}
|
/*
* (C) Copyright 1996- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include <pthread.h>
#include <signal.h>
#include "eckit/config/Resource.h"
#include "eckit/container/MappedArray.h"
#include "eckit/container/SharedMemArray.h"
#include "eckit/filesystem/LocalPathName.h"
#include "eckit/filesystem/PathName.h"
#include "eckit/os/BackTrace.h"
#include "eckit/runtime/Main.h"
#include "eckit/runtime/Monitor.h"
#include "eckit/runtime/TaskInfo.h"
#include "eckit/system/SystemInfo.h"
#include "eckit/thread/AutoLock.h"
namespace eckit {
//----------------------------------------------------------------------------------------------------------------------
Monitor::TaskArray::~TaskArray() {}
class MemoryMappedTaskArray : public Monitor::TaskArray {
virtual void sync() { map_.sync(); }
virtual void lock() { map_.lock(); }
virtual void unlock() { map_.unlock(); }
virtual iterator begin() { return map_.begin(); }
virtual iterator end() { return map_.end(); }
virtual const_iterator begin() const { return map_.begin(); }
virtual const_iterator end() const { return map_.end(); }
virtual unsigned long size() { return map_.size(); }
virtual TaskInfo& operator[](unsigned long n) { return map_[n]; }
MappedArray<TaskInfo> map_;
public:
MemoryMappedTaskArray(const PathName& path, unsigned long size) :
TaskArray(), map_(path, size) {}
};
class SharedMemoryTaskArray : public Monitor::TaskArray {
virtual void sync() { map_.sync(); }
virtual void lock() { map_.lock(); }
virtual void unlock() { map_.unlock(); }
virtual iterator begin() { return map_.begin(); }
virtual iterator end() { return map_.end(); }
virtual const_iterator begin() const { return map_.begin(); }
virtual const_iterator end() const { return map_.end(); }
virtual unsigned long size() { return map_.size(); }
virtual TaskInfo& operator[](unsigned long n) { return map_[n]; }
SharedMemArray<TaskInfo> map_;
public:
SharedMemoryTaskArray(const PathName& path, const std::string& name, unsigned long size) :
TaskArray(), map_(path, name, size) {}
};
//----------------------------------------------------------------------------------------------------------------------
static bool active_ = false;
static Monitor::TaskArray* mapArray = nullptr;
static pthread_once_t once = PTHREAD_ONCE_INIT;
static void taskarray_init(void) {
LocalPathName monitorPath(Resource<std::string>("monitorPath", "~/etc/monitor"));
size_t size = Resource<size_t>("monitorSize", 1000);
std::string monitorArrayType = Resource<std::string>("monitorArrayType", "MemoryMapped");
// Log::info() << "monitorPath: " << monitorPath << std::endl;
if (monitorArrayType == "MemoryMapped") {
mapArray = new MemoryMappedTaskArray(monitorPath, size);
return;
}
if (monitorArrayType == "SharedMemory") {
std::string shmpath = eckit::system::SystemInfo::instance().userName() + "-etc-monitor";
mapArray = new SharedMemoryTaskArray(monitorPath, shmpath, size);
return;
}
std::ostringstream oss;
oss << "Invalid monitorArrayType : " << monitorArrayType << ", valid types are 'MemoryMapped' and 'SharedMemory'"
<< std::endl;
throw eckit::BadParameter(oss.str(), Here());
}
Monitor::TaskArray& Monitor::tasks() {
ASSERT(active_);
pthread_once(&once, taskarray_init);
return *mapArray;
}
//----------------------------------------------------------------------------------------------------------------------
template class ThreadSingleton<Monitor>;
Monitor& Monitor::instance() {
static ThreadSingleton<Monitor> monitor;
Monitor& m = monitor.instance();
if (!m.ready_)
m.init();
return m;
}
//----------------------------------------------------------------------------------------------------------------------
Monitor::Monitor() :
slot_(0), ready_(false), check_(false) {}
void Monitor::init() {
if (ready_)
return;
if (!active_) {
ready_ = true;
return;
} // this is for processes that don't use Monitor
if (check_)
return; // safely ignore double initialization
check_ = true;
TaskArray& a = tasks();
AutoLock<TaskArray> lock(a);
int slot = hash() % a.size();
bool found = false;
for (bool check = false; !check && !found; check = true) {
for (size_t i = 0; i < a.size() && !found; ++i) {
slot_ = (slot + i) % a.size();
if (!a[slot_].busy(check)) {
new (&a[slot_]) TaskInfo();
found = true;
}
}
}
if (!found) {
std::cout << "No free monitor slots" << std::endl;
std::cerr << "No free monitor slots" << std::endl;
}
// No free monitor slots
PANIC(!found);
check_ = false;
ready_ = true;
}
Monitor::~Monitor() {
if (ready_ && active_) {
TaskArray& a = tasks();
AutoLock<TaskArray> lock(a);
a[slot_].TaskInfo::~TaskInfo();
}
}
bool Monitor::active() {
return active_;
}
void Monitor::active(bool a) {
active_ = a;
}
void Monitor::reset() {
Monitor::shutdown();
slot_ = 0;
ready_ = false;
check_ = false;
Monitor::startup();
}
void Monitor::startup() {
if (!ready_)
init();
}
void Monitor::shutdown() {
if (!active_)
return;
TaskArray& a = tasks();
AutoLock<TaskArray> lock(a);
pid_t pid = ::getpid();
for (size_t i = 0; i < a.size(); ++i)
if (a[i].pid() == pid)
a[i].TaskInfo::~TaskInfo();
// should unmap
}
unsigned long Monitor::hash() {
return (((unsigned long)::pthread_self() << 16) | (unsigned long)::getpid());
}
TaskInfo& Monitor::task() {
return task(slot_);
}
TaskInfo& Monitor::task(unsigned long slot) {
if (!active_ || !ready_) {
static TaskInfo info;
return info;
}
TaskArray& a = tasks();
return a[slot];
}
long Monitor::self() {
if (!active_) {
return Main::instance().taskID();
}
if (!ready_)
return -1;
return slot_;
}
void Monitor::out(char* from, char* to) {
if (!ready_)
return;
task().out(from, to);
}
void Monitor::name(const std::string& s) {
if (!ready_)
return;
task().name(s);
}
void Monitor::kind(const std::string& s) {
if (!ready_)
return;
task().kind(s);
}
void Monitor::progress(const std::string& name, unsigned long long min, unsigned long long max) {
if (!ready_)
return;
task().progressName(name);
task().start(min, max);
}
void Monitor::progress(unsigned long long value) {
if (!ready_)
return;
task().progress(value);
}
void Monitor::progress() {
if (!ready_)
return;
task().done();
}
char Monitor::state(char c) {
char x = task().state();
task().state(c);
return x;
}
void Monitor::status(const std::string& msg) {
if (!ready_)
return;
task().status(msg);
}
std::string Monitor::status() {
if (!ready_)
return std::string();
return task().status();
}
void Monitor::message(const std::string& msg) {
if (!ready_)
return;
task().message(msg);
}
std::string Monitor::message() {
if (!ready_)
return std::string();
return task().message();
}
void Monitor::stoppable(bool b) {
task().stoppable(b);
}
bool Monitor::stopped() {
return task().stopped();
}
bool Monitor::stopTriggered() {
return task().stopTriggered();
}
void Monitor::setStopped() {
task().setStopped();
}
void Monitor::abort() {
task().abort();
}
void Monitor::checkAbort() {
task().checkAbort();
}
void Monitor::parent(long p) {
task().parent(p);
}
std::string Monitor::statusTree() {
std::ostringstream os;
os << status();
int n = self();
TaskArray& p = tasks();
for (size_t j = 0; j < p.size(); ++j)
if ((p[j].parent() == n) && p[j].show() && p[j].busy(true)) {
os << "|" << p[j].status();
}
return os.str();
}
void Monitor::start(const std::string& app) {
if (!active_)
return;
TaskArray& p = tasks();
for (size_t j = 0; j < p.size(); ++j)
if (p[j].busy(true) && app == p[j].application() && p[j].depth() == 0) {
Log::warning() << app << " is already running with a pid of " << p[j].pid() << std::endl;
Log::warning() << "Please stop it first" << std::endl;
return;
}
PathName cmd = Resource<PathName>("startCmd", "~/admin/starter");
std::string s = std::string(cmd) + " " + app;
Log::info() << "Executing shell command: " << s << std::endl;
SYSCALL(::system(s.c_str()));
}
void Monitor::port(int p) {
task().port(p);
}
int Monitor::port() {
return task().port();
}
void Monitor::host(const std::string& h) {
task().host(h);
}
std::string Monitor::host() {
return task().host();
}
void Monitor::taskID(const TaskID& id) {
task().taskID(id);
}
TaskID Monitor::taskID() {
return task().taskID();
}
void Monitor::show(bool on) {
task().show(on);
}
int Monitor::kill(const std::string& name, int sig) {
if (!active_)
return 0;
Monitor::TaskArray& info = tasks();
pid_t me = ::getpid();
int n = 0;
// Name. Look for Unix process ID
for (size_t i = 0; i < info.size(); ++i)
if (info[i].busy(true) && info[i].application() == name) {
pid_t pid = info[i].pid();
if (pid == me)
Log::info() << pid << ": Suicide avoided ;-)" << std::endl;
else {
if (::kill(pid, sig))
Log::info() << Log::syserr << std::endl;
else {
Log::info() << pid << ": Killed" << std::endl;
n++;
}
}
}
return n;
}
//----------------------------------------------------------------------------------------------------------------------
} // namespace eckit
|
#include "Window.h"
#include "Input.h"
#include "Stopwatch.h"
#include "Triangle.h"
#include <iostream>
void version() {
#ifdef _DEBUG
std::string configuration = "Debug";
#else
std::string configuration = "Release";
#endif
SB_MESSAGE("Audio - Build: " << configuration << ", " << __DATE__ << ", " << __TIME__);
}
void demo0() {
sb::Window window;
sb::Triangle triangle;
while (window.isOpen()) {
sb::Input::update();
window.update();
window.clear(sb::Color(1, 1, 1, 1));
window.draw(triangle);
window.display();
}
}
int main() {
version();
demo0();
return 0;
}
|
//==----------- stl.hpp - basic STL implementation -------------------------==//
//
// 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
//
//===----------------------------------------------------------------------===//
#pragma once
// 4.5 C++ Standard library classes required for the interface
#include <CL/sycl/bit_cast.hpp>
#include <CL/sycl/detail/defines.hpp>
#include <CL/sycl/sycl_span.hpp>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
__SYCL_INLINE_NAMESPACE(cl) {
namespace sycl {
#if defined(_WIN32) && !defined(_DLL) && !defined(__SYCL_DEVICE_ONLY__)
// SYCL library is designed such a way that STL objects cross DLL boundary,
// which is guaranteed to work properly only when the application uses the same
// C++ runtime that SYCL library uses.
// The appplications using sycl.dll must be linked with dynamic/release C++ MSVC
// runtime, i.e. be compiled with /MD switch. Similarly, the applications using
// sycld.dll must be linked with dynamic/debug C++ runtime and be compiled with
// /MDd switch.
// Compiler automatically adds /MD or /MDd when -fsycl switch is used.
// The options /MD and /MDd that make the code to use dynamic runtime also
// define the _DLL macro.
#if defined(_MSC_VER)
#pragma message( \
"SYCL library is designed to work safely with dynamic C++ runtime." \
"Please use /MD switch with sycl.dll, /MDd switch with sycld.dll, " \
"or -fsycl switch to set C++ runtime automatically.")
#else
#warning "SYCL library is designed to work safely with dynamic C++ runtime."\
"Please use /MD switch with sycl.dll, /MDd switch with sycld.dll, "\
"or -fsycl switch to set C++ runtime automatically."
#endif
#endif // defined(_WIN32) && !defined(_DLL) && !defined(__SYCL_DEVICE_ONLY__)
// TODO deprecation attribute can not be applied to template alias. Find a way
// to show deprecation warning with those aliases anyway.
template <class T, class Alloc = std::allocator<T>>
using vector_class = std::vector<T, Alloc>;
using string_class
__SYCL2020_DEPRECATED("use STL classes directly") = std::string;
template <class Sig> using function_class = std::function<Sig>;
using mutex_class
__SYCL2020_DEPRECATED("use STL classes directly") = std::mutex;
template <class T, class Deleter = std::default_delete<T>>
using unique_ptr_class = std::unique_ptr<T, Deleter>;
template <class T> using shared_ptr_class = std::shared_ptr<T>;
template <class T> using weak_ptr_class = std::weak_ptr<T>;
template <class T> using hash_class = std::hash<T>;
using exception_ptr_class
__SYCL2020_DEPRECATED("use STL classes directly") = std::exception_ptr;
template <typename T, typename... ArgsT>
std::unique_ptr<T> make_unique_ptr(ArgsT &&... Args) {
return std::unique_ptr<T>(new T(std::forward<ArgsT>(Args)...));
}
} // namespace sycl
} // __SYCL_INLINE_NAMESPACE(cl)
|
#include "DcTestDeserialize.h"
#include "DataConfig/Deserialize/DcDeserializer.h"
#include "DataConfig/Deserialize/DcDeserializeTypes.h"
#include "DataConfig/Json/DcJsonReader.h"
#include "DataConfig/Property/DcPropertyWriter.h"
#include "DataConfig/Diagnostic/DcDiagnosticDeserialize.h"
#include "DataConfig/Diagnostic/DcDiagnosticReadWrite.h"
#include "DataConfig/Automation/DcAutomation.h"
#include "DataConfig/Automation/DcAutomationUtils.h"
DC_TEST("DataConfig.Core.Deserialize.Primitive1")
{
FString Str = TEXT(R"(
{
"BoolField" : true,
"NameField" : "AName",
"StringField" : "AStr",
"TextField" : "AText",
"EnumField" : "Tard",
"FloatField" : 17.5,
"DoubleField" : 19.375,
"Int8Field" : -43,
"Int16Field" : -2243,
"Int32Field" : -23415,
"Int64Field" : -1524523,
"UInt8Field" : 213,
"UInt16Field" : 2243,
"UInt32Field" : 23415,
"UInt64Field" : 1524523,
}
)");
FDcJsonReader Reader(Str);
FDcTestStruct1 Dest;
FDcPropertyDatum DestDatum(FDcTestStruct1::StaticStruct(), &Dest);
FDcTestStruct1 Expect;
Expect.BoolField = true;
Expect.NameField = TEXT("AName");
Expect.StringField = TEXT("AStr");
Expect.TextField = FText::FromString(TEXT("AText"));
Expect.EnumField = EDcTestEnum1::Tard;
Expect.FloatField = 17.5f;
Expect.DoubleField = 19.375;
Expect.Int8Field = -43;
Expect.Int16Field = -2243;
Expect.Int32Field = -23415;
Expect.Int64Field = -1524523;
Expect.UInt8Field = 213;
Expect.UInt16Field = 2243,
Expect.UInt32Field = 23415;
Expect.UInt64Field = 1524523;
FDcPropertyDatum ExpectDatum(FDcTestStruct1::StaticStruct(), &Expect);
UTEST_OK("Deserialize into FDcTestStruct1", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum));
UTEST_OK("Deserialize into FDcTestStruct1", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
return true;
}
DC_TEST("DataConfig.Core.Deserialize.EnumFlags")
{
FString Str = TEXT(R"(
{
"EnumFlagField1" : [],
"EnumFlagField2" : ["One", "Three", "Five"],
}
)");
FDcJsonReader Reader(Str);
FDcTestStructEnumFlag1 Dest;
FDcPropertyDatum DestDatum(FDcTestStructEnumFlag1::StaticStruct(), &Dest);
FDcTestStructEnumFlag1 Expect;
Expect.EnumFlagField1 = EDcTestEnumFlag::None;
Expect.EnumFlagField2 = EDcTestEnumFlag::One | EDcTestEnumFlag::Three | EDcTestEnumFlag::Five;
FDcPropertyDatum ExpectDatum(FDcTestStructEnumFlag1::StaticStruct(), &Expect);
#if !WITH_METADATA
UEnum* EnumClass = FindObject<UEnum>(ANY_PACKAGE, TEXT("EDcTestEnumFlag"), true);
check(EnumClass);
DcAutomationUtils::AmendMetaData(EnumClass, TEXT("Bitflags"), TEXT(""));
DcAutomationUtils::AmendMetaData(EnumClass, TEXT("Bitflags"), TEXT(""));
#endif
UTEST_OK("Deserialize into FDcTestStructEnumFlag1", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum));
UTEST_OK("Deserialize into FDcTestStructEnumFlag1", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
return true;
}
DC_TEST("DataConfig.Core.Deserialize.InlineSubObject")
{
FString Str = TEXT(R"(
{
"ShapeField1" : {
"$type" : "DcShapeBox",
"ShapeName" : "Box1",
"Height" : 17.5,
"Width" : 1.9375
},
"ShapeField2" : {
"$type" : "DcShapeSquare",
"ShapeName" : "Square1",
"Radius" : 1.75,
},
"ShapeField3" : null
}
)");
FDcJsonReader Reader(Str);
FDcTestStructShapeContainer1 Dest; // note that Dest fields are all uninitialized atm
FDcPropertyDatum DestDatum(FDcTestStructShapeContainer1::StaticStruct(), &Dest);
FDcTestStructShapeContainer1 Expect;
UDcShapeBox* Shape1 = NewObject<UDcShapeBox>();
Shape1->ShapeName = TEXT("Box1");
Shape1->Height = 17.5;
Shape1->Width = 1.9375;
Expect.ShapeField1 = Shape1;
UDcShapeSquare* Shape2 = NewObject<UDcShapeSquare>();
Shape2->ShapeName = TEXT("Square1");
Shape2->Radius = 1.75;
Expect.ShapeField2 = Shape2;
Expect.ShapeField3 = nullptr;
FDcPropertyDatum ExpectDatum(FDcTestStructShapeContainer1::StaticStruct(), &Expect);
UTEST_OK("Deserialize into FDcTestStructShapeContainer1", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum,
[](FDcDeserializer&, FDcDeserializeContext& Ctx){
Ctx.Objects.Push(GetTransientPackage());
}));
UTEST_OK("Deserialize into FDcTestStructShapeContainer1", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
return true;
}
DC_TEST("DataConfig.Core.Deserialize.ObjectRef")
{
FString Str = TEXT(R"(
{
"ObjField1" : "Object'/Script/DataConfigTests'",
"ObjField2" : null
}
)");
FDcJsonReader Reader(Str);
FDcTestStructObjectRef1 Dest; // note that Dest fields are all uninitialized atm
FDcPropertyDatum DestDatum(FDcTestStructObjectRef1::StaticStruct(), &Dest);
FDcTestStructObjectRef1 Expect;
Expect.ObjField1 = FindObject<UPackage>(ANY_PACKAGE, TEXT("/Script/DataConfigTests"), true);
Expect.ObjField2 = nullptr;
FDcPropertyDatum ExpectDatum(FDcTestStructObjectRef1::StaticStruct(), &Expect);
UTEST_OK("Deserialize into FDcTestStructObjectRef1", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum));
UTEST_OK("Deserialize into FDcTestStructObjectRef1", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
return true;
}
DC_TEST("DataConfig.Core.Deserialize.Containers")
{
FString Str = TEXT(R"(
{
"StringArray" : [
"Foo", "Bar", "Baz"
],
"StringSet" : [
"Doo", "Dar", "Daz"
],
"StringMap" : {
"One": "1",
"Two": "2",
"Three": "3",
},
"StructSet" : [
{
"Name" : "One",
"Index" : 1,
},
{
"Name" : "Two",
"Index" : 2,
},
{
"Name" : "Three",
"Index" : 3,
}
],
}
)");
FDcJsonReader Reader(Str);
FDcTestStruct3 Dest;
FDcPropertyDatum DestDatum(FDcTestStruct3::StaticStruct(), &Dest);
FDcTestStruct3 Expect;
Expect.StringArray.Add(TEXT("Foo"));
Expect.StringArray.Add(TEXT("Bar"));
Expect.StringArray.Add(TEXT("Baz"));
Expect.StringSet.Add(TEXT("Doo"));
Expect.StringSet.Add(TEXT("Dar"));
Expect.StringSet.Add(TEXT("Daz"));
Expect.StringMap.Add(TEXT("One"), TEXT("1"));
Expect.StringMap.Add(TEXT("Two"), TEXT("2"));
Expect.StringMap.Add(TEXT("Three"), TEXT("3"));
Expect.StructSet.Add({TEXT("One"), 1});
Expect.StructSet.Add({TEXT("Two"), 2});
Expect.StructSet.Add({TEXT("Three"), 3});
FDcPropertyDatum ExpectDatum(FDcTestStruct3::StaticStruct(), &Expect);
UTEST_OK("Deserialize into FDcTestStruct3", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum));
UTEST_OK("Deserialize into FDcTestStruct3", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
return true;
}
DC_TEST("DataConfig.Core.Deserialize.SubClass")
{
FString Str = TEXT(R"(
{
"StructSubClassField1" : null,
"StructSubClassField2" : "ScriptStruct",
"StructSubClassField3" : "DynamicClass",
}
)");
FDcJsonReader Reader(Str);
FDcTestStructSubClass1 Dest;
FDcPropertyDatum DestDatum(FDcTestStructSubClass1::StaticStruct(), &Dest);
FDcTestStructSubClass1 Expect;
Expect.StructSubClassField1 = nullptr;
Expect.StructSubClassField2 = UScriptStruct::StaticClass();
Expect.StructSubClassField3 = UDynamicClass::StaticClass();
FDcPropertyDatum ExpectDatum(FDcTestStructSubClass1::StaticStruct(), &Expect);
UTEST_OK("Deserialize into FDcTestStructSubClass1", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum));
UTEST_OK("Deserialize into FDcTestStructSubClass1", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
FString BadStr = TEXT(R"(
{
"StructSubClassField1" : "Object",
}
)");
UTEST_OK("Deserialize into FDcTestStructSubClass1 Fail", Reader.SetNewString(*BadStr));
UTEST_DIAG("Deserialize into FDcTestStructSubClass1 Fail", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum),
DcDDeserialize, ClassLhsIsNotChildOfRhs);
return true;
}
DC_TEST("DataConfig.Core.Deserialize.ObjRefs")
{
FString Str = TEXT(R"(
{
"ObjectField1" : "'/Script/DataConfigTests'",
"ObjectField2" : null,
"SoftField1" : "'/Script/DataConfigTests'",
"SoftField2" : null,
"WeakField1" : "'/Script/DataConfigTests'",
"WeakField2" : null,
"LazyField1" : "'/Script/DataConfigTests'",
"LazyField2" : null,
}
)");
FDcJsonReader Reader(Str);
FDcTestStructRefs1 Dest;
FDcPropertyDatum DestDatum(FDcTestStructRefs1::StaticStruct(), &Dest);
FDcTestStructRefs1 Expect;
UObject* TestsObject = StaticFindObject(UObject::StaticClass(), nullptr, TEXT("/Script/DataConfigTests"));
Expect.ObjectField1 = TestsObject;
Expect.ObjectField2 = nullptr;
Expect.SoftField1 = TestsObject;
Expect.SoftField2 = nullptr;
Expect.WeakField1 = TestsObject;
Expect.WeakField2 = nullptr;
Expect.LazyField1 = TestsObject;
Expect.LazyField2 = nullptr;
FDcPropertyDatum ExpectDatum(FDcTestStructRefs1::StaticStruct(), &Expect);
UTEST_OK("Deserialize into FDcTestStructRefs1", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum));
UTEST_OK("Deserialize into FDcTestStructRefs1", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
return true;
}
DC_TEST("DataConfig.Core.Deserialize.ClassRefs")
{
FString Str = TEXT(R"(
{
"RawClassField1" : "DynamicClass",
"RawClassField2" : null,
"SubClassField1" : "DynamicClass",
"SubClassField2" : null,
"SoftClassField1" : "DynamicClass",
"SoftClassField2" : null,
}
)");
FDcJsonReader Reader(Str);
FDcTestStructRefs2 Dest;
FDcPropertyDatum DestDatum(FDcTestStructRefs2::StaticStruct(), &Dest);
FDcTestStructRefs2 Expect;
UClass* DynamicMetaClass = FindObject<UClass>(ANY_PACKAGE, TEXT("DynamicClass"));
Expect.RawClassField1 = DynamicMetaClass;
Expect.RawClassField2 = nullptr;
Expect.SubClassField1 = DynamicMetaClass;
Expect.SubClassField2 = nullptr;
Expect.SoftClassField1 = DynamicMetaClass;
Expect.SoftClassField2 = nullptr;
FDcPropertyDatum ExpectDatum(FDcTestStructRefs2::StaticStruct(), &Expect);
UTEST_OK("Deserialize into FDcTestStructRefs2", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum));
UTEST_OK("Deserialize into FDcTestStructRefs2", DcAutomationUtils::TestReadDatumEqual(DestDatum, ExpectDatum));
return true;
}
DC_TEST("DataConfig.Core.Deserialize.Fails1")
{
{
FString Str = TEXT(R"(
{
"WhatField" : "Doesnt Exist",
}
)");
FDcJsonReader Reader(Str);
FDcTestStruct1 Dest;
FDcPropertyDatum DestDatum(FDcTestStruct1::StaticStruct(), &Dest);
UTEST_DIAG("Deserialize Fails", DcAutomationUtils::DeserializeJsonInto(&Reader, DestDatum), DcDReadWrite, CantFindPropertyByName);
}
return true;
}
|
#include "../../CompanyManager.h"
#include "../../Graphics/ImageIds.h"
#include "../../Input.h"
#include "../../Localisation/FormatArguments.hpp"
#include "../../Objects/AirportObject.h"
#include "../../Objects/CargoObject.h"
#include "../../Objects/DockObject.h"
#include "../../Objects/ObjectManager.h"
#include "../../Objects/RoadObject.h"
#include "../../Objects/RoadStationObject.h"
#include "../../Objects/TrackObject.h"
#include "../../Objects/TrainStationObject.h"
#include "../../StationManager.h"
#include "../../Ui/Dropdown.h"
#include "Construction.h"
using namespace OpenLoco::Interop;
using namespace OpenLoco::Map;
using namespace OpenLoco::Map::TileManager;
namespace OpenLoco::Ui::Windows::Construction::Station
{
widget_t widgets[] = {
commonWidgets(138, 190, StringIds::stringid_2),
makeWidget({ 3, 45 }, { 132, 12 }, widget_type::wt_18, 1, 0xFFFFFFFF, StringIds::tooltip_select_station_type),
makeWidget({ 123, 46 }, { 11, 10 }, widget_type::wt_11, 1, StringIds::dropdown, StringIds::tooltip_select_station_type),
makeWidget({ 35, 60 }, { 68, 68 }, widget_type::wt_3, 1),
makeWidget({ 112, 104 }, { 24, 24 }, widget_type::wt_9, 1, ImageIds::rotate_object, StringIds::rotate_90),
widgetEnd(),
};
window_event_list events;
// 0x0049E228
static void onMouseUp(window* self, widget_index widgetIndex)
{
switch (widgetIndex)
{
case Common::widx::close_button:
WindowManager::close(self);
break;
case Common::widx::tab_construction:
case Common::widx::tab_overhead:
case Common::widx::tab_signal:
case Common::widx::tab_station:
Common::switchTab(self, widgetIndex);
break;
case widx::rotate:
_constructionRotation++;
_constructionRotation = _constructionRotation & 3;
_stationCost = 0x80000000;
self->invalidate();
break;
}
}
template<typename obj_type>
void AddStationsToDropdown(const uint8_t stationCount)
{
for (auto stationIndex = 0; stationIndex < stationCount; stationIndex++)
{
auto station = _stationList[stationIndex];
if (station == _lastSelectedStationType)
Dropdown::setHighlightedItem(stationIndex);
auto obj = ObjectManager::get<obj_type>(station);
Dropdown::add(stationIndex, obj->name);
}
}
// 0x0049E249
static void onMouseDown(window* self, widget_index widgetIndex)
{
switch (widgetIndex)
{
case widx::station_dropdown:
{
uint8_t stationCount = 0;
while (_stationList[stationCount] != 0xFF)
stationCount++;
auto widget = self->widgets[widx::station];
auto xPos = widget.left + self->x;
auto yPos = widget.top + self->y;
auto width = widget.width() + 2;
auto height = widget.height();
Dropdown::show(xPos, yPos, width, height, self->colours[1], stationCount, (1 << 7));
if (_byte_1136063 & (1 << 7))
{
AddStationsToDropdown<airport_object>(stationCount);
}
else if (_byte_1136063 & (1 << 6))
{
AddStationsToDropdown<dock_object>(stationCount);
}
else if (_trackType & (1 << 7))
{
AddStationsToDropdown<road_station_object>(stationCount);
}
else
{
AddStationsToDropdown<train_station_object>(stationCount);
}
break;
}
case widx::image:
{
Input::toolCancel();
Input::toolSet(self, widgetIndex, 44);
break;
}
}
}
// 0x0049E256
static void onDropdown(window* self, widget_index widgetIndex, int16_t itemIndex)
{
if (widgetIndex == widx::station_dropdown)
{
if (itemIndex == -1)
return;
auto selectedStation = _stationList[itemIndex];
_lastSelectedStationType = selectedStation;
if (_byte_1136063 & (1 << 7))
{
_lastAirport = selectedStation;
}
else if (_byte_1136063 & (1 << 6))
{
_lastShipPort = selectedStation;
}
else if (_trackType & (1 << 7))
{
auto trackType = _trackType & ~(1 << 7);
_scenarioRoadStations[trackType] = selectedStation;
}
else
{
_scenarioTrainStations[_trackType] = selectedStation;
}
self->invalidate();
}
}
// 0x0049E437
static void onUpdate(window* self)
{
Common::onUpdate(self, (1 << 3));
}
// 0x0049E421
static void onToolUpdate(window& self, const widget_index widgetIndex, const int16_t x, const int16_t y)
{
registers regs;
regs.esi = (int32_t)&self;
regs.dx = widgetIndex;
regs.ax = x;
regs.bx = y;
call(0x0049E421, regs);
}
// 0x0049E42C
static void onToolDown(window& self, const widget_index widgetIndex, const int16_t x, const int16_t y)
{
registers regs;
regs.esi = (int32_t)&self;
regs.dx = widgetIndex;
regs.ax = x;
regs.bx = y;
call(0x0049E42C, regs);
}
// 0x0049DD39
static void prepareDraw(window* self)
{
Common::prepareDraw(self);
self->widgets[widx::rotate].type = widget_type::none;
auto args = FormatArguments();
if (_byte_1136063 & (1 << 7))
{
self->widgets[widx::rotate].type = widget_type::wt_9;
auto airportObj = ObjectManager::get<airport_object>(_lastSelectedStationType);
self->widgets[widx::station].text = airportObj->name;
args.push(StringIds::title_airport);
}
else if (_byte_1136063 & (1 << 6))
{
auto dockObj = ObjectManager::get<dock_object>(_lastSelectedStationType);
self->widgets[widx::station].text = dockObj->name;
args.push(StringIds::title_ship_port);
}
else if (_trackType & (1 << 7))
{
auto trackType = _trackType & ~(1 << 7);
auto roadObj = ObjectManager::get<road_object>(trackType);
args.push(roadObj->name);
auto roadStationObject = ObjectManager::get<road_station_object>(_lastSelectedStationType);
self->widgets[widx::station].text = roadStationObject->name;
}
else
{
auto trackObj = ObjectManager::get<track_object>(_trackType);
args.push(trackObj->name);
auto trainStationObject = ObjectManager::get<train_station_object>(_lastSelectedStationType);
self->widgets[widx::station].text = trainStationObject->name;
}
Common::repositionTabs(self);
}
// 0x0049DE40
static void draw(window* self, Gfx::drawpixelinfo_t* dpi)
{
self->draw(dpi);
Common::drawTabs(self, dpi);
auto company = CompanyManager::get(_playerCompany);
auto companyColour = company->mainColours.primary;
int16_t xPos = self->widgets[widx::image].left + self->x;
int16_t yPos = self->widgets[widx::image].top + self->y;
if (_byte_1136063 & (1 << 7))
{
auto airportObj = ObjectManager::get<airport_object>(_lastSelectedStationType);
auto imageId = Gfx::recolour(airportObj->image, companyColour);
Gfx::drawImage(dpi, xPos, yPos, imageId);
}
else if (_byte_1136063 & (1 << 6))
{
auto dockObj = ObjectManager::get<dock_object>(_lastSelectedStationType);
auto imageId = Gfx::recolour(dockObj->image, companyColour);
Gfx::drawImage(dpi, xPos, yPos, imageId);
}
else if (_trackType & (1 << 7))
{
auto roadStationObj = ObjectManager::get<road_station_object>(_lastSelectedStationType);
auto imageId = Gfx::recolour(roadStationObj->image, companyColour);
Gfx::drawImage(dpi, xPos, yPos, imageId);
auto colour = _byte_5045FA[companyColour];
if (!(roadStationObj->flags & RoadStationFlags::recolourable))
{
colour = 46;
}
imageId = Gfx::recolour(imageId, colour) + 1;
Gfx::drawImage(dpi, xPos, yPos, imageId);
}
else
{
auto trainStationObj = ObjectManager::get<train_station_object>(_lastSelectedStationType);
auto imageId = Gfx::recolour(trainStationObj->image, companyColour);
Gfx::drawImage(dpi, xPos, yPos, imageId);
auto colour = _byte_5045FA[companyColour];
if (!(trainStationObj->flags & TrainStationFlags::recolourable))
{
colour = 46;
}
imageId = Gfx::recolour(imageId, colour) + 1;
Gfx::drawImage(dpi, xPos, yPos, imageId);
}
if (_stationCost != 0x80000000 && _stationCost != 0)
{
xPos = self->x + 69;
yPos = self->widgets[widx::image].bottom + self->y + 4;
auto args = FormatArguments();
args.push<uint32_t>(_stationCost);
Gfx::drawStringCentred(*dpi, xPos, yPos, Colour::black, StringIds::build_cost, &args);
}
xPos = self->x + 3;
yPos = self->widgets[widx::image].bottom + self->y + 16;
auto width = self->width - 4;
Gfx::drawRectInset(dpi, xPos, yPos, width, 1, self->colours[1], (1 << 5));
if (!(_byte_522096 & (1 << 3)))
return;
auto args = FormatArguments();
if (_constructingStationId == 0xFFFFFFFF)
{
args.push(StringIds::new_station);
}
else
{
auto station = StationManager::get(_constructingStationId);
args.push(station->name);
args.push(station->town);
}
xPos = self->x + 69;
yPos = self->widgets[widx::image].bottom + self->y + 18;
width = self->width - 4;
Gfx::drawStringCentredClipped(*dpi, xPos, yPos, width, Colour::black, StringIds::new_station_buffer, &args);
xPos = self->x + 2;
yPos = self->widgets[widx::image].bottom + self->y + 29;
Gfx::point_t origin = { xPos, yPos };
Gfx::drawString_494B3F(*dpi, &origin, Colour::black, StringIds::catchment_area_accepts);
if (_constructingStationAcceptedCargoTypes == 0)
{
Gfx::drawString_494B3F(*dpi, origin.x, origin.y, Colour::black, StringIds::catchment_area_nothing);
}
else
{
yPos--;
for (uint8_t i = 0; i < ObjectManager::getMaxObjects(object_type::cargo); i++)
{
if (_constructingStationAcceptedCargoTypes & (1 << i))
{
auto xPosMax = self->x + self->width - 12;
if (origin.x <= xPosMax)
{
auto cargoObj = ObjectManager::get<cargo_object>(i);
Gfx::drawImage(dpi, origin.x, origin.y, cargoObj->unit_inline_sprite);
origin.x += 10;
}
}
}
}
xPos = self->x + 2;
yPos = self->widgets[widx::image].bottom + self->y + 49;
origin = { xPos, yPos };
Gfx::drawString_494B3F(*dpi, &origin, Colour::black, StringIds::catchment_area_produces);
if (_constructingStationProducedCargoTypes == 0)
{
Gfx::drawString_494B3F(*dpi, origin.x, origin.y, Colour::black, StringIds::catchment_area_nothing);
}
else
{
yPos--;
for (uint8_t i = 0; i < ObjectManager::getMaxObjects(object_type::cargo); i++)
{
if (_constructingStationProducedCargoTypes & (1 << i))
{
auto xPosMax = self->x + self->width - 12;
if (origin.x <= xPosMax)
{
auto cargoObj = ObjectManager::get<cargo_object>(i);
Gfx::drawImage(dpi, origin.x, origin.y, cargoObj->unit_inline_sprite);
origin.x += 10;
}
}
}
}
}
void tabReset(window* self)
{
self->callOnMouseDown(Station::widx::image);
}
void initEvents()
{
events.on_close = Common::onClose;
events.on_mouse_up = onMouseUp;
events.on_mouse_down = onMouseDown;
events.on_dropdown = onDropdown;
events.on_update = onUpdate;
events.on_tool_update = onToolUpdate;
events.on_tool_down = onToolDown;
events.prepare_draw = prepareDraw;
events.draw = draw;
}
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017 The BitcoinSubsidium Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "streams.h"
#include "version.h"
#include "assets/assets.h"
#include "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "standard.h"
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expansion
case OP_NOP1 : return "OP_NOP1";
case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
/** XBTX START */
case OP_XBTX_ASSET : return "OP_XBTX_ASSET";
/** XBTX END */
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
// Note:
// The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum
// as kind of implementation hack, they are *NOT* real opcodes. If found in real
// Script, just let the default: case deal with them.
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += MAX_PUBKEYS_PER_MULTISIG;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
std::vector<unsigned char> vData;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, vData))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(vData.begin(), vData.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsPayToPublicKeyHash() const
{
// Extra-fast test for pay-to-pubkey-hash CScripts:
return (this->size() == 25 &&
(*this)[0] == OP_DUP &&
(*this)[1] == OP_HASH160 &&
(*this)[2] == 0x14 &&
(*this)[23] == OP_EQUALVERIFY &&
(*this)[24] == OP_CHECKSIG);
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
(*this)[0] == OP_HASH160 &&
(*this)[1] == 0x14 &&
(*this)[22] == OP_EQUAL);
}
/** XBTX START */
bool CScript::IsAssetScript() const
{
int nType = 0;
bool isOwner = false;
int start = 0;
return IsAssetScript(nType, isOwner, start);
}
bool CScript::IsAssetScript(int& nType, bool& isOwner) const
{
int start = 0;
return IsAssetScript(nType, isOwner, start);
}
bool CScript::IsAssetScript(int& nType, bool& fIsOwner, int& nStartingIndex) const
{
if (this->size() > 30) {
if ((*this)[25] == OP_XBTX_ASSET) { // OP_XBTX_ASSET is always in the 25 index of the script if it exists
int index = -1;
if ((*this)[27] == XBTX_R) { // Check to see if XBTX starts at 27 ( this->size() < 105)
if ((*this)[28] == XBTX_V)
if ((*this)[29] == XBTX_N)
index = 30;
} else {
if ((*this)[28] == XBTX_R) // Check to see if XBTX starts at 28 ( this->size() >= 105)
if ((*this)[29] == XBTX_V)
if ((*this)[30] == XBTX_N)
index = 31;
}
if (index > 0) {
nStartingIndex = index + 1; // Set the index where the asset data begins. Use to serialize the asset data into asset objects
if ((*this)[index] == XBTX_T) { // Transfer first anticipating more transfers than other assets operations
nType = TX_TRANSFER_ASSET;
return true;
} else if ((*this)[index] == XBTX_Q && this->size() > 39) {
nType = TX_NEW_ASSET;
fIsOwner = false;
return true;
} else if ((*this)[index] == XBTX_O) {
nType = TX_NEW_ASSET;
fIsOwner = true;
return true;
} else if ((*this)[index] == XBTX_R) {
nType = TX_REISSUE_ASSET;
return true;
}
}
}
}
return false;
}
bool CScript::IsNewAsset() const
{
int nType = 0;
bool fIsOwner = false;
if (IsAssetScript(nType, fIsOwner))
return !fIsOwner && nType == TX_NEW_ASSET;
return false;
}
bool CScript::IsOwnerAsset() const
{
int nType = 0;
bool fIsOwner = false;
if (IsAssetScript(nType, fIsOwner))
return fIsOwner && nType == TX_NEW_ASSET;
return false;
}
bool CScript::IsReissueAsset() const
{
int nType = 0;
bool fIsOwner = false;
if (IsAssetScript(nType, fIsOwner))
return nType == TX_REISSUE_ASSET;
return false;
}
bool CScript::IsTransferAsset() const
{
int nType = 0;
bool fIsOwner = false;
if (IsAssetScript(nType, fIsOwner))
return nType == TX_TRANSFER_ASSET;
return false;
}
/** XBTX END */
bool CScript::IsPayToWitnessScriptHash() const
{
// Extra-fast test for pay-to-witness-script-hash CScripts:
return (this->size() == 34 &&
(*this)[0] == OP_0 &&
(*this)[1] == 0x20);
}
// A witness program is any valid CScript that consists of a 1-byte push opcode
// followed by a data push between 2 and 40 bytes.
bool CScript::IsWitnessProgram(int& version, std::vector<unsigned char>& program) const
{
if (this->size() < 4 || this->size() > 42) {
return false;
}
if ((*this)[0] != OP_0 && ((*this)[0] < OP_1 || (*this)[0] > OP_16)) {
return false;
}
if ((size_t)((*this)[1] + 2) == this->size()) {
version = DecodeOP_N((opcodetype)(*this)[0]);
program = std::vector<unsigned char>(this->begin() + 2, this->end());
return true;
}
return false;
}
bool CScript::IsPayToPublicKey() const
{
// Test for pay-to-pubkey CScript with both
// compressed or uncompressed pubkey
if (this->size() == 35) {
return ((*this)[1] == 0x02 || (*this)[1] == 0x03) &&
(*this)[34] == OP_CHECKSIG;
}
if (this->size() == 67) {
return (*this)[1] == 0x04 &&
(*this)[66] == OP_CHECKSIG;
}
return false;
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
std::string CScriptWitness::ToString() const
{
std::string ret = "CScriptWitness(";
for (unsigned int i = 0; i < stack.size(); i++) {
if (i) {
ret += ", ";
}
ret += HexStr(stack[i]);
}
return ret + ")";
}
bool CScript::HasValidOps() const
{
CScript::const_iterator it = begin();
while (it < end()) {
opcodetype opcode;
std::vector<unsigned char> item;
if (!GetOp(it, opcode, item) || opcode > MAX_OPCODE || item.size() > MAX_SCRIPT_ELEMENT_SIZE) {
return false;
}
}
return true;
}
bool CScript::IsUnspendable() const
{
CAmount nAmount;
return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE) || (GetAssetAmountFromScript(*this, nAmount) && nAmount == 0);
}
//!--------------------------------------------------------------------------------------------------------------------------!//
//! These are needed because script.h and script.cpp do not have access to asset.h and asset.cpp functions. This is
//! because the make file compiles them at different times. The script files are compiled with other
//! consensus files, and asset files are compiled with core files.
//! Used to check if an asset script contains zero assets. Is so, it should be unspendable
bool GetAssetAmountFromScript(const CScript& script, CAmount& nAmount)
{
// Placeholder strings that will get set if you successfully get the transfer or asset from the script
std::string address = "";
std::string assetName = "";
int nType = 0;
bool fIsOwner = false;
if (!script.IsAssetScript(nType, fIsOwner)) {
return false;
}
txnouttype type = txnouttype(nType);
// Get the New Asset or Transfer Asset from the scriptPubKey
if (type == TX_NEW_ASSET && !fIsOwner) {
if (AmountFromNewAssetScript(script, nAmount)) {
return true;
}
} else if (type == TX_TRANSFER_ASSET) {
if (AmountFromTransferScript(script, nAmount)) {
return true;
}
} else if (type == TX_NEW_ASSET && fIsOwner) {
nAmount = OWNER_ASSET_AMOUNT;
return true;
} else if (type == TX_REISSUE_ASSET) {
if (AmountFromReissueScript(script, nAmount)) {
return true;
}
}
return false;
}
bool ScriptNewAsset(const CScript& scriptPubKey, int& nStartingIndex)
{
int nType = 0;
bool fIsOwner =false;
if (scriptPubKey.IsAssetScript(nType, fIsOwner, nStartingIndex)) {
return nType == TX_NEW_ASSET && !fIsOwner;
}
return false;
}
bool ScriptTransferAsset(const CScript& scriptPubKey, int& nStartingIndex)
{
int nType = 0;
bool fIsOwner =false;
if (scriptPubKey.IsAssetScript(nType, fIsOwner, nStartingIndex)) {
return nType == TX_TRANSFER_ASSET;
}
return false;
}
bool ScriptReissueAsset(const CScript& scriptPubKey, int& nStartingIndex)
{
int nType = 0;
bool fIsOwner =false;
if (scriptPubKey.IsAssetScript(nType, fIsOwner, nStartingIndex)) {
return nType == TX_REISSUE_ASSET;
}
return false;
}
bool AmountFromNewAssetScript(const CScript& scriptPubKey, CAmount& nAmount)
{
int nStartingIndex = 0;
if (!ScriptNewAsset(scriptPubKey, nStartingIndex))
return false;
std::vector<unsigned char> vchNewAsset;
vchNewAsset.insert(vchNewAsset.end(), scriptPubKey.begin() + nStartingIndex, scriptPubKey.end());
CDataStream ssAsset(vchNewAsset, SER_NETWORK, PROTOCOL_VERSION);
CNewAsset assetNew;
try {
ssAsset >> assetNew;
} catch(std::exception& e) {
std::cout << "Failed to get the asset from the stream: " << e.what() << std::endl;
return false;
}
nAmount = assetNew.nAmount;
return true;
}
bool AmountFromTransferScript(const CScript& scriptPubKey, CAmount& nAmount)
{
int nStartingIndex = 0;
if (!ScriptTransferAsset(scriptPubKey, nStartingIndex))
return false;
std::vector<unsigned char> vchAsset;
vchAsset.insert(vchAsset.end(), scriptPubKey.begin() + nStartingIndex, scriptPubKey.end());
CDataStream ssAsset(vchAsset, SER_NETWORK, PROTOCOL_VERSION);
CAssetTransfer asset;
try {
ssAsset >> asset;
} catch(std::exception& e) {
std::cout << "Failed to get the asset from the stream: " << e.what() << std::endl;
return false;
}
nAmount = asset.nAmount;
return true;
}
bool AmountFromReissueScript(const CScript& scriptPubKey, CAmount& nAmount)
{
int nStartingIndex = 0;
if (!ScriptReissueAsset(scriptPubKey, nStartingIndex))
return false;
std::vector<unsigned char> vchNewAsset;
vchNewAsset.insert(vchNewAsset.end(), scriptPubKey.begin() + nStartingIndex, scriptPubKey.end());
CDataStream ssAsset(vchNewAsset, SER_NETWORK, PROTOCOL_VERSION);
CReissueAsset asset;
try {
ssAsset >> asset;
} catch(std::exception& e) {
std::cout << "Failed to get the asset from the stream: " << e.what() << std::endl;
return false;
}
nAmount = asset.nAmount;
return true;
}
//!--------------------------------------------------------------------------------------------------------------------------!//
|
#include<bits/stdc++.h>
using namespace std;
typedef long double ld;
typedef long long int ll;
vector<vector<ll> > adjlist;
ll max(ll x,ll y){return (x>y)?x:y;}
#define min(x,y) (x>y)?y:x
#define sfor(a,n,i) for(ll i=a;i<n;i++)
#define rfor(n,a,i) for(ll i=n;i>=a;i--)
#define mod 1000000007
#define pb push_back
#define in insert
#define mp make_pair
#define inf mod
#define bg begin()
#define ed end()
#define sz size()
#define vi vector<ll>
#define vc vector<char>
#define vinv vector<vector<ll,ll> >
#define imap map<ll,ll>
#define cmap map<char,ll>
#define smap map<string,ll>
#define iset set<ll>
#define bit(x,i) (x&(1<<i))
int main()
{
ll t;cin>>t;
while(t--){
ld n,d;
cin>>n>>d;
ll start=0;
ll end=n,mid=n;
ll x=0;
sfor(0,n+1,i){
if(i+ceil(d/(i+1))<=n){
cout<<"YES "<<endl;
x=01;
break;
}
}
if(!x){
cout<<"NO"<<endl;
}
}
return 0;
}
|
#include <muduo/base/Logging.h>
#include <muduo/base/CurrentThread.h>
#include <muduo/base/StringPiece.h>
#include <muduo/base/Timestamp.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
namespace muduo
{
/*
class LoggerImpl
{
public:
typedef Logger::LogLevel LogLevel;
LoggerImpl(LogLevel level, int old_errno, const char* file, int line);
void finish();
Timestamp time_;
LogStream stream_;
LogLevel level_;
int line_;
const char* fullname_;
const char* basename_;
};
*/
__thread char t_errnobuf[512];
__thread char t_time[32];
__thread time_t t_lastSecond;
const char* strerror_tl(int savedErrno)
{
return strerror_r(savedErrno, t_errnobuf, sizeof t_errnobuf);
}
Logger::LogLevel initLogLevel()
{
if (::getenv("MUDUO_LOG_TRACE"))
return Logger::TRACE;
else if (::getenv("MUDUO_LOG_DEBUG"))
return Logger::DEBUG;
else
return Logger::INFO;
}
Logger::LogLevel g_logLevel = initLogLevel();
const char* LogLevelName[Logger::NUM_LOG_LEVELS] =
{
"TRACE ",
"DEBUG ",
"INFO ",
"WARN ",
"ERROR ",
"FATAL ",
};
// helper class for known string length at compile time
class T
{
public:
T(const char* str, unsigned len)
:str_(str),
len_(len)
{
assert(strlen(str) == len_);
}
const char* str_;
const unsigned len_;
};
inline LogStream& operator<<(LogStream& s, T v)
{
s.append(v.str_, v.len_);
return s;
}
inline LogStream& operator<<(LogStream& s, const Logger::SourceFile& v)
{
s.append(v.data_, v.size_);
return s;
}
void defaultOutput(const char* msg, int len)
{
size_t n = fwrite(msg, 1, len, stdout);
//FIXME check n
(void)n;
}
void defaultFlush()
{
fflush(stdout);
}
Logger::OutputFunc g_output = defaultOutput;
Logger::FlushFunc g_flush = defaultFlush;
}
using namespace muduo;
Logger::Impl::Impl(LogLevel level, int savedErrno, const SourceFile& file, int line)
: time_(Timestamp::now()),
stream_(),
level_(level),
line_(line),
basename_(file)
{
formatTime();
CurrentThread::tid();
stream_ << T(CurrentThread::tidString(), 6);
stream_ << T(LogLevelName[level], 6);
if (savedErrno != 0)
{
stream_ << strerror_tl(savedErrno) << " (errno=" << savedErrno << ") ";
}
}
void Logger::Impl::formatTime()
{
int64_t microSecondsSinceEpoch = time_.microSecondsSinceEpoch();
time_t seconds = static_cast<time_t>(microSecondsSinceEpoch / 1000000);
int microseconds = static_cast<int>(microSecondsSinceEpoch % 1000000);
if (seconds != t_lastSecond)
{
t_lastSecond = seconds;
struct tm tm_time;
::gmtime_r(&seconds, &tm_time); // FIXME TimeZone::fromUtcTime
int len = snprintf(t_time, sizeof(t_time), "%4d%02d%02d %02d:%02d:%02d",
tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec);
assert(len == 17); (void)len;
}
Fmt us(".%06dZ ", microseconds);
assert(us.length() == 9);
stream_ << T(t_time, 17) << T(us.data(), 9);
}
void Logger::Impl::finish()
{
stream_ << " - " << basename_ << ':' << line_ << '\n';
}
Logger::Logger(SourceFile file, int line)
: impl_(INFO, 0, file, line)
{
}
Logger::Logger(SourceFile file, int line, LogLevel level, const char* func)
: impl_(level, 0, file, line)
{
impl_.stream_ << func << ' ';
}
Logger::Logger(SourceFile file, int line, LogLevel level)
: impl_(level, 0, file, line)
{
}
Logger::Logger(SourceFile file, int line, bool toAbort)
: impl_(toAbort?FATAL:ERROR, errno, file, line)
{
}
Logger::~Logger()
{
impl_.finish();
const LogStream::Buffer& buf(stream().buffer());
g_output(buf.data(), buf.length());
if (impl_.level_ == FATAL)
{
g_flush();
abort();
}
}
void Logger::setLogLevel(Logger::LogLevel level)
{
g_logLevel = level;
}
void Logger::setOutput(OutputFunc out)
{
g_output = out;
}
void Logger::setFlush(FlushFunc flush)
{
g_flush = flush;
}
|
/**********************************************************************************
* Project: Eskapade
* Class : TMsgLogger *
* *
* Description: *
* Implementation (see header for description) *
* *
* Adapted from TMVA:MsgLogger.
* Original authors: *
* *
* Attila Krasznahorkay <Attila.Krasznahorkay@cern.ch> - CERN, Switzerland *
* Andreas Hoecker <Andreas.Hocker@cern.ch> - CERN, Switzerland *
* Joerg Stelzer <stelzer@cern.ch> - DESY, Germany *
* Eckhard v. Toerne <evt@uni-bonn.de> - U of Bonn, Germany *
* *
* Copyright (c) 2005-2014: *
* CERN, Switzerland *
* U. of Victoria, Canada *
* MPI-K Heidelberg, Germany *
* U. of Bonn, Germany *
* *
* http://root.cern.ch/root/htmldoc/src/TMVA__MsgLogger.h.html *
* *
* (http://tmva.sourceforge.net/LICENSE) *
**********************************************************************************/
// esroofit includes.
#include <esroofit/TMsgLogger.h>
// STL includes.
#include <iomanip>
ClassImp(TMsgLogger)
using namespace std;
// uncomment this line to inhibit colored output
#define USE_COLORED_CONSOLE
// this is the hard-coded maximum length of the source names
static const string::size_type MAXIMUM_SOURCE_NAME_LENGTH = 20;
#ifndef __APPLE__
// this is the hardcoded prefix
static const char *PREFIX = ""; //"--- ";
// this is the hardcoded suffix
static const char *SUFFIX = ": ";
#else
#define PREFIX "" //"--- "
#define SUFFIX ": "
#endif
TMsgLevel TMsgLogger::m_minLevel = kINFO;
bool TMsgLogger::m_levelLock = false;
//_____________________________________________________________________________
TMsgLogger::TMsgLogger(const TObject *source, TMsgLevel /*minLevel*/)
: m_objSource(source),
m_strSource(""),
m_prefix(PREFIX),
m_suffix(SUFFIX),
m_activeLevel(kINFO),
m_maxSourceSize(MAXIMUM_SOURCE_NAME_LENGTH)
{
// constructor
InitMaps();
}
//_____________________________________________________________________________
TMsgLogger::TMsgLogger(const string &source, TMsgLevel /*minLevel*/)
: m_objSource(0),
m_strSource(source),
m_prefix(PREFIX),
m_suffix(SUFFIX),
m_activeLevel(kINFO),
m_maxSourceSize(MAXIMUM_SOURCE_NAME_LENGTH)
{
// constructor
InitMaps();
}
//_____________________________________________________________________________
TMsgLogger::TMsgLogger(TMsgLevel /*minLevel*/)
: m_objSource(0),
m_strSource("Unknown"),
m_prefix(PREFIX),
m_suffix(SUFFIX),
m_activeLevel(kINFO),
m_maxSourceSize(MAXIMUM_SOURCE_NAME_LENGTH)
{
// constructor
InitMaps();
}
//_____________________________________________________________________________
TMsgLogger::TMsgLogger(const TMsgLogger &parent)
: basic_ios<TMsgLogger::char_type, TMsgLogger::traits_type>(),
//: basic_ios<TMsgLogger::char_type, TMsgLogger::traits_type>(new TMsgLogger::__stringbuf_type()),
ostringstream(),
TObject(),
m_prefix(PREFIX),
m_suffix(SUFFIX),
m_maxSourceSize(MAXIMUM_SOURCE_NAME_LENGTH)
{
InitMaps();
*this = parent;
}
//_____________________________________________________________________________
TMsgLogger::~TMsgLogger()
{
}
//_____________________________________________________________________________
TMsgLogger &TMsgLogger::operator=(const TMsgLogger &parent)
{
m_objSource = parent.m_objSource;
m_strSource = parent.m_strSource;
m_activeLevel = parent.m_activeLevel;
return *this;
}
//_____________________________________________________________________________
string TMsgLogger::GetFormattedSource() const
{
// make sure the source name is no longer than m_maxSourceSize:
string source_name;
if (m_objSource)
{ source_name = m_objSource->GetName(); }
else
{ source_name = m_strSource; }
if (source_name.size() > m_maxSourceSize)
{
source_name = source_name.substr(0, m_maxSourceSize - 3);
source_name += "...";
}
return source_name;
}
//_____________________________________________________________________________
string TMsgLogger::GetPrintedSource() const
{
// the full logger prefix
string source_name = GetFormattedSource();
return m_prefix + source_name + m_suffix;
}
//_____________________________________________________________________________
void TMsgLogger::Send()
{
// activates the logger writer
// make sure the source name is no longer than m_maxSourceSize:
string source_name = GetFormattedSource();
string message = this->str();
string::size_type previous_pos = 0, current_pos = 0;
// slice the message into lines:
for (;;)
{
current_pos = message.find('\n', previous_pos);
string line = message.substr(previous_pos, current_pos - previous_pos);
ostringstream message_to_send;
// must call the modifiers like this, otherwise g++ get's confused with the operators...
message_to_send.setf(ios::adjustfield, ios::left);
message_to_send.width(source_name.size());
message_to_send << source_name << m_suffix << line;
this->WriteMsg(m_activeLevel, message_to_send.str());
if (current_pos == message.npos)
{
break;
}
previous_pos = current_pos + 1;
}
// reset the stream buffer:
this->str("");
return;
}
//_____________________________________________________________________________
void TMsgLogger::WriteMsg(TMsgLevel mlevel, const std::string &line) const
{
if (mlevel < GetMinLevel())
{
return;
}
map<TMsgLevel, std::string>::const_iterator slevel;
if ((slevel = m_levelMap.find(mlevel)) == m_levelMap.end())
{
return;
}
//we do print names for kINFO - gbesjes 17/10/12
#ifdef USE_COLORED_CONSOLE
cout << m_colorMap.find(mlevel)->second << m_prefix << "<" << slevel->second << "> "
<< line; // << "\033[0m" << endl;
if (mlevel == kINFO)
{
cout << endl;
}
else
{
cout << "\033[0m" << endl;
}
#else
cout << m_prefix << "<" << slevel->second << "> " << line << endl;
#endif // USE_COLORED_CONSOLE
// take decision to stop if fatal error
if (mlevel == kFATAL)
{
cout << "***> abort program execution" << endl;
exit(1);
}
}
//_____________________________________________________________________________
TMsgLogger &TMsgLogger::endmsg(TMsgLogger &logger)
{
// end line
logger.Send();
return logger;
}
//_____________________________________________________________________________
TMsgLevel TMsgLogger::MapLevel(const TString &instr) const
{
TString ins = instr; // need to copy
ins.ToUpper();
// find the corresponding key
std::map<TMsgLevel, std::string>::const_iterator it = m_levelMap.begin();
for (; it != m_levelMap.end(); it++)
{
if (ins == it->second)
{
return it->first;
}
}
// not found --> fatal error
TString line(Form("fatal error in <TMsgLogger::MapLevel> unknown output level: %s ==> abort", ins.Data()));
cout << m_colorMap.find(kFATAL)->second << m_prefix << line << "\033[0m" << endl;
abort();
return kFATAL;
}
//_____________________________________________________________________________
void TMsgLogger::InitMaps()
{
m_levelMap[kVERBOSE] = "VERBOSE";
m_levelMap[kDEBUG] = "DEBUG";
m_levelMap[kINFO] = "INFO";
m_levelMap[kWARNING] = "WARNING";
m_levelMap[kERROR] = "ERROR";
m_levelMap[kFATAL] = "FATAL";
m_levelMap[kALWAYS] = "ALWAYS";
m_colorMap[kVERBOSE] = "\033[1;34m";
m_colorMap[kDEBUG] = "\033[34m";
m_colorMap[kINFO] = "";
m_colorMap[kWARNING] = "\033[1;31m";
m_colorMap[kERROR] = "\033[1;31m";
m_colorMap[kFATAL] = "\033[37;41;1m";
m_colorMap[kALWAYS] = "\033[30m";
}
|
/*
Copyright (C) 2010 Klarälvdalens Datakonsult AB,
a KDAB Group company, info@kdab.net,
author Stephen Kelly <stephen@kdab.com>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "kmodelindexproxymapper.h"
#include <QtCore/QAbstractItemModel>
#include <QtCore/QPointer>
#include <QAbstractProxyModel>
#include <QItemSelectionModel>
#include "kdebug.h"
class KModelIndexProxyMapperPrivate
{
KModelIndexProxyMapperPrivate(const QAbstractItemModel *leftModel, const QAbstractItemModel *rightModel, KModelIndexProxyMapper *qq)
: q_ptr(qq), m_leftModel(leftModel), m_rightModel(rightModel)
{
createProxyChain();
}
void createProxyChain();
bool assertValid();
bool assertSelectionValid(const QItemSelection &selection) const {
foreach(const QItemSelectionRange &range, selection) {
if (!range.isValid()) {
//kDebug() << selection << m_leftModel << m_rightModel << m_proxyChainDown << m_proxyChainUp;
}
Q_ASSERT(range.isValid());
}
return true;
}
Q_DECLARE_PUBLIC(KModelIndexProxyMapper)
KModelIndexProxyMapper * const q_ptr;
QList<QPointer<const QAbstractProxyModel> > m_proxyChainUp;
QList<QPointer<const QAbstractProxyModel> > m_proxyChainDown;
QPointer<const QAbstractItemModel> m_leftModel;
QPointer<const QAbstractItemModel> m_rightModel;
};
/*
The idea here is that <tt>this</tt> selection model and proxySelectionModel might be in different parts of the
proxy chain. We need to build up to two chains of proxy models to create mappings between them.
Example 1:
Root model
|
/ \
Proxy 1 Proxy 3
| |
Proxy 2 Proxy 4
Need Proxy 1 and Proxy 2 in one chain, and Proxy 3 and 4 in the other.
Example 2:
Root model
|
Proxy 1
|
Proxy 2
/ \
Proxy 3 Proxy 6
| |
Proxy 4 Proxy 7
|
Proxy 5
We first build the chain from 1 to 5, then start building the chain from 7 to 1. We stop when we find that proxy 2 is
already in the first chain.
Stephen Kelly, 30 March 2010.
*/
void KModelIndexProxyMapperPrivate::createProxyChain()
{
QPointer<const QAbstractItemModel> targetModel = m_rightModel;
if (!targetModel)
return;
if (m_leftModel == targetModel)
return;
QList<QPointer<const QAbstractProxyModel> > proxyChainDown;
QPointer<const QAbstractProxyModel> selectionTargetProxyModel = qobject_cast<const QAbstractProxyModel*>(targetModel.data());
while( selectionTargetProxyModel )
{
proxyChainDown.prepend( selectionTargetProxyModel );
selectionTargetProxyModel = qobject_cast<const QAbstractProxyModel*>(selectionTargetProxyModel.data()->sourceModel());
if (selectionTargetProxyModel.data() == m_leftModel.data())
{
m_proxyChainDown = proxyChainDown;
return;
}
}
QPointer<const QAbstractItemModel> sourceModel = m_leftModel;
QPointer<const QAbstractProxyModel> sourceProxyModel = qobject_cast<const QAbstractProxyModel*>(sourceModel.data());
while(sourceProxyModel)
{
m_proxyChainUp.append(sourceProxyModel);
sourceProxyModel = qobject_cast<const QAbstractProxyModel*>(sourceProxyModel.data()->sourceModel());
const int targetIndex = proxyChainDown.indexOf(sourceProxyModel);
if (targetIndex != -1)
{
m_proxyChainDown = proxyChainDown.mid(targetIndex + 1, proxyChainDown.size());
return;
}
}
m_proxyChainDown = proxyChainDown;
Q_ASSERT(assertValid());
}
bool KModelIndexProxyMapperPrivate::assertValid()
{
if ( m_proxyChainDown.isEmpty())
{
Q_ASSERT( !m_proxyChainUp.isEmpty() );
Q_ASSERT( m_proxyChainUp.last().data()->sourceModel() == m_rightModel.data() );
}
else if ( m_proxyChainUp.isEmpty())
{
Q_ASSERT( !m_proxyChainDown.isEmpty() );
Q_ASSERT( m_proxyChainDown.first().data()->sourceModel() == m_leftModel.data() );
} else {
Q_ASSERT( m_proxyChainDown.first().data()->sourceModel() == m_proxyChainUp.last().data()->sourceModel() );
}
return true;
}
KModelIndexProxyMapper::KModelIndexProxyMapper(const QAbstractItemModel* leftModel, const QAbstractItemModel* rightModel, QObject* parent)
: QObject(parent), d_ptr( new KModelIndexProxyMapperPrivate(leftModel, rightModel, this) )
{
}
KModelIndexProxyMapper::~KModelIndexProxyMapper()
{
delete d_ptr;
}
QModelIndex KModelIndexProxyMapper::mapLeftToRight(const QModelIndex& index) const
{
const QItemSelection selection = mapSelectionLeftToRight(QItemSelection(index, index));
if (selection.isEmpty())
return QModelIndex();
return selection.indexes().first();
}
QModelIndex KModelIndexProxyMapper::mapRightToLeft(const QModelIndex& index) const
{
const QItemSelection selection = mapSelectionRightToLeft(QItemSelection(index, index));
if (selection.isEmpty())
return QModelIndex();
return selection.indexes().first();
}
// QAbstractProxyModel::mapSelectionFromSource creates invalid ranges to we filter
// those out manually in a loop. Hopefully fixed in Qt 4.7.2, so we ifdef it out.
// http://qt.gitorious.org/qt/qt/merge_requests/2474
// http://qt.gitorious.org/qt/qt/merge_requests/831
#if QT_VERSION < 0x040702
#define RANGE_FIX_HACK
#endif
#ifdef RANGE_FIX_HACK
static QItemSelection removeInvalidRanges(const QItemSelection &selection)
{
QItemSelection result;
Q_FOREACH(const QItemSelectionRange &range, selection)
{
if (!range.isValid())
continue;
result << range;
}
return result;
}
#endif
QItemSelection KModelIndexProxyMapper::mapSelectionLeftToRight(const QItemSelection& selection) const
{
Q_D(const KModelIndexProxyMapper);
if (selection.isEmpty())
return QItemSelection();
//if (selection.first().model() != d->m_leftModel.data())
// kDebug() << "FAIL" << selection.first().model() << d->m_leftModel.data() << d->m_rightModel.data();
Q_ASSERT(selection.first().model() == d->m_leftModel.data());
QItemSelection seekSelection = selection;
Q_ASSERT(d->assertSelectionValid(seekSelection));
QListIterator<QPointer<const QAbstractProxyModel> > iUp(d->m_proxyChainUp);
while (iUp.hasNext())
{
const QPointer<const QAbstractProxyModel> proxy = iUp.next();
if (!proxy.data())
return QItemSelection();
seekSelection = proxy.data()->mapSelectionToSource(seekSelection);
#ifdef RANGE_FIX_HACK
seekSelection = removeInvalidRanges(seekSelection);
#endif
Q_ASSERT(d->assertSelectionValid(seekSelection));
}
QListIterator<QPointer<const QAbstractProxyModel> > iDown(d->m_proxyChainDown);
while (iDown.hasNext())
{
const QPointer<const QAbstractProxyModel> proxy = iDown.next();
if (!proxy.data())
return QItemSelection();
seekSelection = proxy.data()->mapSelectionFromSource(seekSelection);
#ifdef RANGE_FIX_HACK
seekSelection = removeInvalidRanges(seekSelection);
#endif
Q_ASSERT(d->assertSelectionValid(seekSelection));
}
Q_ASSERT( ( !seekSelection.isEmpty() && seekSelection.first().model() == d->m_rightModel.data() ) || true );
return seekSelection;
}
QItemSelection KModelIndexProxyMapper::mapSelectionRightToLeft(const QItemSelection& selection) const
{
Q_D(const KModelIndexProxyMapper);
if (selection.isEmpty())
return QItemSelection();
//if (selection.first().model() != d->m_rightModel.data())
// kDebug() << "FAIL" << selection.first().model() << d->m_leftModel.data() << d->m_rightModel.data();
Q_ASSERT(selection.first().model() == d->m_rightModel.data());
QItemSelection seekSelection = selection;
Q_ASSERT(d->assertSelectionValid(seekSelection));
QListIterator<QPointer<const QAbstractProxyModel> > iDown(d->m_proxyChainDown);
iDown.toBack();
while (iDown.hasPrevious())
{
const QPointer<const QAbstractProxyModel> proxy = iDown.previous();
if (!proxy.data())
return QItemSelection();
seekSelection = proxy.data()->mapSelectionToSource(seekSelection);
#ifdef RANGE_FIX_HACK
seekSelection = removeInvalidRanges(seekSelection);
#endif
Q_ASSERT(d->assertSelectionValid(seekSelection));
}
QListIterator<QPointer<const QAbstractProxyModel> > iUp(d->m_proxyChainUp);
iUp.toBack();
while (iUp.hasPrevious())
{
const QPointer<const QAbstractProxyModel> proxy = iUp.previous();
if (!proxy.data())
return QItemSelection();
seekSelection = proxy.data()->mapSelectionFromSource(seekSelection);
#ifdef RANGE_FIX_HACK
seekSelection = removeInvalidRanges(seekSelection);
#endif
Q_ASSERT(d->assertSelectionValid(seekSelection));
}
Q_ASSERT( ( !seekSelection.isEmpty() && seekSelection.first().model() == d->m_leftModel.data() ) || true );
return seekSelection;
}
#include <3rd/kde/moc_kmodelindexproxymapper.cpp>
|
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkCanvas.h"
#include "include/core/SkImage.h"
#include "include/core/SkString.h"
#include "include/effects/SkImageFilters.h"
#include "src/core/SkImageFilter_Base.h"
#include "src/core/SkReadBuffer.h"
#include "src/core/SkSamplingPriv.h"
#include "src/core/SkSpecialImage.h"
#include "src/core/SkSpecialSurface.h"
#include "src/core/SkWriteBuffer.h"
namespace {
class SkImageImageFilter final : public SkImageFilter_Base {
public:
SkImageImageFilter(sk_sp<SkImage> image, const SkRect& srcRect, const SkRect& dstRect,
const SkSamplingOptions& sampling)
: INHERITED(nullptr, 0, nullptr)
, fImage(std::move(image))
, fSrcRect(srcRect)
, fDstRect(dstRect)
, fSampling(sampling) {}
SkRect computeFastBounds(const SkRect& src) const override;
protected:
void flatten(SkWriteBuffer&) const override;
sk_sp<SkSpecialImage> onFilterImage(const Context&, SkIPoint* offset) const override;
SkIRect onFilterNodeBounds(const SkIRect&, const SkMatrix& ctm,
MapDirection, const SkIRect* inputRect) const override;
MatrixCapability onGetCTMCapability() const override { return MatrixCapability::kComplex; }
private:
friend void ::SkRegisterImageImageFilterFlattenable();
SK_FLATTENABLE_HOOKS(SkImageImageFilter)
sk_sp<SkImage> fImage;
SkRect fSrcRect, fDstRect;
SkSamplingOptions fSampling;
using INHERITED = SkImageFilter_Base;
};
} // end namespace
sk_sp<SkImageFilter> SkImageFilters::Image(sk_sp<SkImage> image,
const SkRect& srcRect,
const SkRect& dstRect,
const SkSamplingOptions& sampling) {
if (!image || srcRect.width() <= 0.0f || srcRect.height() <= 0.0f) {
return nullptr;
}
return sk_sp<SkImageFilter>(new SkImageImageFilter(
std::move(image), srcRect, dstRect, sampling));
}
void SkRegisterImageImageFilterFlattenable() {
SK_REGISTER_FLATTENABLE(SkImageImageFilter);
// TODO (michaelludwig) - Remove after grace period for SKPs to stop using old name
SkFlattenable::Register("SkImageSourceImpl", SkImageImageFilter::CreateProc);
}
sk_sp<SkFlattenable> SkImageImageFilter::CreateProc(SkReadBuffer& buffer) {
SkSamplingOptions sampling;
if (buffer.isVersionLT(SkPicturePriv::kImageFilterImageSampling_Version)) {
sampling = SkSamplingPriv::FromFQ(buffer.checkFilterQuality(), kLinear_SkMediumAs);
} else {
sampling = buffer.readSampling();
}
SkRect src, dst;
buffer.readRect(&src);
buffer.readRect(&dst);
sk_sp<SkImage> image(buffer.readImage());
if (!image) {
return nullptr;
}
return SkImageFilters::Image(std::move(image), src, dst, sampling);
}
void SkImageImageFilter::flatten(SkWriteBuffer& buffer) const {
SkSamplingPriv::Write(buffer, fSampling);
buffer.writeRect(fSrcRect);
buffer.writeRect(fDstRect);
buffer.writeImage(fImage.get());
}
///////////////////////////////////////////////////////////////////////////////////////////////////
sk_sp<SkSpecialImage> SkImageImageFilter::onFilterImage(const Context& ctx,
SkIPoint* offset) const {
const SkRect dstBounds = ctx.ctm().mapRect(fDstRect);
const SkIRect dstIBounds = dstBounds.roundOut();
// Quick check to see if we can return the image directly, which can be done if the transform
// ends up being an integer translate and sampling would have no effect on the output.
// TODO: This currently means cubic sampling can be skipped, even though it would change results
// for integer translation draws.
// TODO: This is prone to false negatives due to the floating point math; we could probably
// get away with dimensions and translates being epsilon close to integers.
const bool passthroughTransform = ctx.ctm().isScaleTranslate() &&
ctx.ctm().getScaleX() > 0.f &&
ctx.ctm().getScaleY() > 0.f;
const bool passthroughSrcOffsets = SkScalarIsInt(fSrcRect.fLeft) &&
SkScalarIsInt(fSrcRect.fTop);
const bool passthroughDstOffsets = SkScalarIsInt(dstBounds.fLeft) &&
SkScalarIsInt(dstBounds.fTop);
const bool passthroughDims =
SkScalarIsInt(fSrcRect.width()) && fSrcRect.width() == dstBounds.width() &&
SkScalarIsInt(fSrcRect.height()) && fSrcRect.height() == dstBounds.height();
if (passthroughTransform && passthroughSrcOffsets && passthroughDstOffsets && passthroughDims) {
// Can pass through fImage directly, applying the dst's location to 'offset'. If fSrcRect
// extends outside of the image, we adjust dst to match since those areas would have been
// transparent black anyways.
SkIRect srcIBounds = fSrcRect.roundOut();
SkIPoint srcOffset = srcIBounds.topLeft();
if (!srcIBounds.intersect(SkIRect::MakeWH(fImage->width(), fImage->height()))) {
return nullptr;
}
*offset = dstIBounds.topLeft() + srcIBounds.topLeft() - srcOffset;
return SkSpecialImage::MakeFromImage(ctx.getContext(), srcIBounds, fImage,
ctx.surfaceProps());
}
sk_sp<SkSpecialSurface> surf(ctx.makeSurface(dstIBounds.size()));
if (!surf) {
return nullptr;
}
SkCanvas* canvas = surf->getCanvas();
// Subtract off the integer component of the translation (will be applied in offset, below).
canvas->translate(-dstIBounds.fLeft, -dstIBounds.fTop);
canvas->concat(ctx.ctm());
// TODO(skbug.com/5075): Canvases from GPU special surfaces come with unitialized content
canvas->clear(SK_ColorTRANSPARENT);
canvas->drawImageRect(fImage.get(), fSrcRect, fDstRect, fSampling, nullptr,
SkCanvas::kStrict_SrcRectConstraint);
*offset = dstIBounds.topLeft();
return surf->makeImageSnapshot();
}
SkRect SkImageImageFilter::computeFastBounds(const SkRect& src) const {
return fDstRect;
}
SkIRect SkImageImageFilter::onFilterNodeBounds(const SkIRect& src, const SkMatrix& ctm,
MapDirection direction,
const SkIRect* inputRect) const {
if (kReverse_MapDirection == direction) {
return INHERITED::onFilterNodeBounds(src, ctm, direction, inputRect);
}
SkRect dstRect = fDstRect;
ctm.mapRect(&dstRect);
return dstRect.roundOut();
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkHoughTransform2DCirclesImageFilter_hxx
#define itkHoughTransform2DCirclesImageFilter_hxx
#include "itkHoughTransform2DCirclesImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkGaussianDerivativeImageFunction.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMath.h"
namespace itk
{
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::
HoughTransform2DCirclesImageFilter()
{
this->SetNumberOfRequiredInputs(1);
}
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
void
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::SetRadius(double radius)
{
this->SetMinimumRadius(radius);
this->SetMaximumRadius(radius);
}
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
void
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::EnlargeOutputRequestedRegion(
DataObject * output)
{
Superclass::EnlargeOutputRequestedRegion(output);
output->SetRequestedRegionToLargestPossibleRegion();
}
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
void
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::GenerateInputRequestedRegion()
{
Superclass::GenerateInputRequestedRegion();
if (this->GetInput())
{
InputImagePointer image = const_cast<InputImageType *>(this->GetInput());
image->SetRequestedRegionToLargestPossibleRegion();
}
}
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
void
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::VerifyPreconditions()
ITKv5_CONST
{
Superclass::VerifyPreconditions();
if (!(m_GradientNormThreshold >= 0.0))
{
itkExceptionMacro("Failed precondition: GradientNormThreshold >= 0.");
}
}
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
void
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::GenerateData()
{
// Get the input and output pointers
const InputImageConstPointer inputImage = this->GetInput(0);
const OutputImagePointer outputImage = this->GetOutput(0);
// Allocate the output
this->AllocateOutputs();
outputImage->FillBuffer(0);
using DoGFunctionType = GaussianDerivativeImageFunction<InputImageType>;
const auto DoGFunction = DoGFunctionType::New();
DoGFunction->SetSigma(m_SigmaGradient);
DoGFunction->SetUseImageSpacing(m_UseImageSpacing);
// Set input image _after_ setting the other GaussianDerivative properties,
// to avoid multiple kernel recomputation within GaussianDerivativeImageFunction.
DoGFunction->SetInputImage(inputImage);
m_RadiusImage = RadiusImageType::New();
m_RadiusImage->SetRegions(outputImage->GetLargestPossibleRegion());
m_RadiusImage->SetOrigin(inputImage->GetOrigin());
m_RadiusImage->SetSpacing(inputImage->GetSpacing());
m_RadiusImage->SetDirection(inputImage->GetDirection());
m_RadiusImage->Allocate(true); // initialize buffer to zero
ImageRegionConstIteratorWithIndex<InputImageType> image_it(inputImage, inputImage->GetRequestedRegion());
image_it.GoToBegin();
const ImageRegion<2> & region = outputImage->GetRequestedRegion();
while (!image_it.IsAtEnd())
{
if (image_it.Get() > m_Threshold)
{
const Index<2> inputIndex = image_it.GetIndex();
const typename DoGFunctionType::VectorType grad = DoGFunction->DoGFunctionType::EvaluateAtIndex(inputIndex);
double Vx = grad[0];
double Vy = grad[1];
const double norm = std::sqrt(Vx * Vx + Vy * Vy);
// if the gradient is not flat (using GradientNormThreshold to estimate flatness)
if (norm > m_GradientNormThreshold)
{
Vx /= norm;
Vy /= norm;
for (double angle = -m_SweepAngle; angle <= m_SweepAngle; angle += 0.05)
{
double i = m_MinimumRadius;
double distance;
do
{
const Index<2> outputIndex = {
{ Math::Round<IndexValueType>(inputIndex[0] - i * (Vx * std::cos(angle) + Vy * std::sin(angle))),
Math::Round<IndexValueType>(inputIndex[1] - i * (Vx * std::sin(angle) + Vy * std::cos(angle))) }
};
if (region.IsInside(outputIndex))
{
distance =
std::sqrt(static_cast<double>((outputIndex[0] - inputIndex[0]) * (outputIndex[0] - inputIndex[0]) +
(outputIndex[1] - inputIndex[1]) * (outputIndex[1] - inputIndex[1])));
++outputImage->GetPixel(outputIndex);
m_RadiusImage->GetPixel(outputIndex) += distance;
}
else
{
break;
}
++i;
} while (distance < m_MaximumRadius);
}
}
}
++image_it;
}
// Compute the average radius
ImageRegionConstIterator<OutputImageType> output_it(outputImage, outputImage->GetLargestPossibleRegion());
ImageRegionIterator<RadiusImageType> radius_it(m_RadiusImage, m_RadiusImage->GetLargestPossibleRegion());
output_it.GoToBegin();
radius_it.GoToBegin();
while (!output_it.IsAtEnd())
{
if (output_it.Get() > 1)
{
radius_it.Value() /= output_it.Get();
}
++output_it;
++radius_it;
}
}
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
typename HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::CirclesListType &
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::GetCircles()
{
// Make sure that all the required inputs exist and have a non-null value
this->VerifyPreconditions();
if (this->GetMTime() == m_OldModifiedTime)
{
// If the filter has not been updated
return m_CirclesList;
}
if (m_RadiusImage.IsNull())
{
itkExceptionMacro(<< "Update() must be called before GetCircles().");
}
m_CirclesList.clear();
if (m_NumberOfCircles > 0)
{
// Blur the accumulator in order to find the maximum
using InternalImageType = Image<float, 2>;
// The variable "outputImage" is only used as input to gaussianFilter.
// It should not be modified, because GetOutput(0) should not be changed.
const auto outputImage = OutputImageType::New();
outputImage->Graft(this->GetOutput(0));
const auto gaussianFilter = DiscreteGaussianImageFilter<OutputImageType, InternalImageType>::New();
gaussianFilter->SetInput(outputImage); // The output is the accumulator image
gaussianFilter->SetVariance(m_Variance);
gaussianFilter->SetUseImageSpacing(m_UseImageSpacing);
gaussianFilter->Update();
const InternalImageType::Pointer postProcessImage = gaussianFilter->GetOutput();
const auto minMaxCalculator = MinimumMaximumImageCalculator<InternalImageType>::New();
ImageRegionIterator<InternalImageType> it_input(postProcessImage, postProcessImage->GetLargestPossibleRegion());
CirclesListSizeType circles = 0;
// Find maxima
// Break out of "forever loop" as soon as the requested number of circles is found.
for (;;)
{
minMaxCalculator->SetImage(postProcessImage);
minMaxCalculator->ComputeMaximum();
if (minMaxCalculator->GetMaximum() <= 0)
{
// When all pixel values in 'postProcessImage' are zero or less, no more circles
// should be found. Note that a zero in 'postProcessImage' might correspond to a
// zero in the accumulator image, or it might be that the pixel is within a
// removed disc around a previously found circle center.
break;
}
const InternalImageType::IndexType indexOfMaximum = minMaxCalculator->GetIndexOfMaximum();
// Create a Circle Spatial Object
const auto Circle = CircleType::New();
Circle->SetId(static_cast<int>(circles));
Circle->SetRadiusInObjectSpace(m_RadiusImage->GetPixel(indexOfMaximum));
CircleType::PointType center;
center[0] = indexOfMaximum[0];
center[1] = indexOfMaximum[1];
Circle->SetCenterInObjectSpace(center);
Circle->Update();
m_CirclesList.push_back(Circle);
circles++;
if (circles >= m_NumberOfCircles)
{
break;
}
// Remove a black disc from the Hough space domain
for (double angle = 0; angle <= 2 * itk::Math::pi; angle += itk::Math::pi / 1000)
{
for (double length = 0; length < m_DiscRadiusRatio * Circle->GetRadiusInObjectSpace()[0]; length += 1)
{
const Index<2> index = { { Math::Round<IndexValueType>(indexOfMaximum[0] + length * std::cos(angle)),
Math::Round<IndexValueType>(indexOfMaximum[1] + length * std::sin(angle)) } };
if (postProcessImage->GetLargestPossibleRegion().IsInside(index))
{
postProcessImage->SetPixel(index, 0);
}
}
}
}
}
m_OldModifiedTime = this->GetMTime();
return m_CirclesList;
}
template <typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType>
void
HoughTransform2DCirclesImageFilter<TInputPixelType, TOutputPixelType, TRadiusPixelType>::PrintSelf(std::ostream & os,
Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Threshold: " << m_Threshold << std::endl;
os << indent << "Gradient Norm Threshold: " << m_GradientNormThreshold << std::endl;
os << indent << "Minimum Radius: " << m_MinimumRadius << std::endl;
os << indent << "Maximum Radius: " << m_MaximumRadius << std::endl;
os << indent << "Derivative Scale : " << m_SigmaGradient << std::endl;
os << indent << "Number Of Circles: " << m_NumberOfCircles << std::endl;
os << indent << "Disc Radius Ratio: " << m_DiscRadiusRatio << std::endl;
os << indent << "Accumulator blur variance: " << m_Variance << std::endl;
os << indent << "Sweep angle : " << m_SweepAngle << std::endl;
os << indent << "UseImageSpacing: " << m_UseImageSpacing << std::endl;
itkPrintSelfObjectMacro(RadiusImage);
os << indent << "CirclesList: " << std::endl;
unsigned int i = 0;
auto it = m_CirclesList.begin();
while (it != m_CirclesList.end())
{
os << indent << "[" << i << "]: " << *it << std::endl;
++it;
++i;
}
os << indent << "OldModifiedTime: " << NumericTraits<ModifiedTimeType>::PrintType(m_OldModifiedTime) << std::endl;
}
} // namespace itk
#endif
|
/*!
\file NormalColorCommand.cpp
\author Tody
NormalColorCommand definition.
date 2015/12/17
*/
#include "NormalColorCommand.h"
#include "NormalColor.h"
void NormalColorCommand::doImp ()
{
Mesh* mesh = _scene->mesh();
Eigen::MatrixXd N;
mesh->vertexNormals ( N );
Eigen::MatrixXd C;
NormalColor::normalToColor ( N, C );
/* Eigen::MatrixXd::Ones ( N.rows(), 3 );
for ( int i = 0; i < N.rows(); i++ )
{
Eigen::Vector3d n = N.row ( i ).normalized();
for ( int j = 0; j < 3; j++ )
{
C ( i, j ) = 0.5 * N ( i, j ) + 0.5;
}
}*/
mesh->setVertexColors ( C );
_scene->setMeshDisplayMode ( Mesh::DisplayMode::VERTEX_COLOR );
}
|
/*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "try_catch.h"
namespace maplebe {
BBT *TryCatchBlocksLower::CreateNewBB(StmtNode *first, StmtNode *last) {
BBT *newBB = memPool.New<BBT>(first, last, &memPool);
bbList.emplace_back(newBB);
return newBB;
}
BBT *TryCatchBlocksLower::FindTargetBBlock(LabelIdx idx, const std::vector<BBT*> &bbs) {
for (auto &target : bbs) {
if (target->GetLabelIdx() == idx) {
return target;
}
}
return nullptr;
}
/* returns the first statement that is moved in into the try block. If none is moved in, nullptr is returned */
StmtNode *TryCatchBlocksLower::MoveCondGotoIntoTry(BBT &jtBB, BBT &condbrBB, const MapleVector<BBT*> &labeledBBsInTry) {
StmtNode *firstStmtMovedIn = nullptr;
const MapleVector<BBT*> &bbs = labeledBBsInTry;
StmtNode *jtStmt = jtBB.GetKeyStmt();
#if DEBUG
StmtNode *js = jtBB.GetFirstStmt();
while (js->GetOpCode() != OP_try) {
js = js->GetNext();
}
CHECK_FATAL(js == jtStmt, "make sure js equal jtStmt");
#endif
StmtNode *ts = jtBB.GetFirstStmt()->GetPrev();
while ((ts != nullptr) && (ts->GetOpCode() == OP_comment)) {
ts = ts->GetPrev();
}
if (ts != nullptr && ts->IsCondBr()) {
CHECK_FATAL(ts->GetNext() == jtBB.GetFirstStmt(), "make sure ts's next equal jtBB's firstStmt");
StmtNode *firstStmtNode = jtBB.GetFirstStmt();
/* [ jtbb_b..jtstmt ]; either jtbb_b is a comment or jtbb_b == jtstmt */
LabelIdx id = static_cast<CondGotoNode*>(ts)->GetOffset();
for (auto &lbb : bbs) {
if (lbb->GetLabelIdx() == id) {
/*
* this cond goto jumps into the try block; let the try block enclose it
* first find the preceding comment statements if any
*/
StmtNode *brS = ts;
while ((ts->GetPrev() != nullptr) && (ts->GetPrev()->GetOpCode() == OP_comment)) {
ts = ts->GetPrev();
}
StmtNode *secondStmtNode = ts; /* beginning statement of branch block */
/* [ brbb_b..br_s ]; either brbb_b is a comment or brbb_b == br_s */
firstStmtNode->SetPrev(secondStmtNode->GetPrev());
if (secondStmtNode->GetPrev()) {
secondStmtNode->GetPrev()->SetNext(firstStmtNode);
}
jtStmt->GetNext()->SetPrev(brS);
brS->SetNext(jtStmt->GetNext());
secondStmtNode->SetPrev(jtStmt);
jtStmt->SetNext(secondStmtNode);
condbrBB.SetLastStmt(*firstStmtNode->GetPrev());
CHECK_FATAL(condbrBB.GetFallthruBranch() == &jtBB, "make sure condbrBB's fallthruBranch equal &jtBB");
condbrBB.SetFallthruBranch(&jtBB);
condbrBB.SetCondJumpBranch(nullptr);
firstStmtMovedIn = secondStmtNode;
break;
}
}
}
return firstStmtMovedIn;
}
void TryCatchBlocksLower::RecoverBasicBlock() {
std::vector<BBT*> condbrBBs;
std::vector<BBT*> switchBBs;
std::vector<BBT*> labeledBBs;
using BBTPair = std::pair<BBT*, BBT*>;
std::vector<BBTPair> tryBBs;
std::vector<BBT*> catchBBs;
CHECK_FATAL(body.GetFirst() != nullptr, "body should not be NULL");
bodyFirst = body.GetFirst();
StmtNode *next = bodyFirst;
/*
* comment block [ begin, end ], We treat comment statements as if they are parts
* of the immediately following non-comment statement
*/
StmtNode *commentB = nullptr;
StmtNode *commentE = nullptr;
BBT *curBB = nullptr;
BBT *lastBB = nullptr;
BBT *openTry = nullptr;
/* recover basic blocks */
for (StmtNode *stmt = next; stmt != nullptr; stmt = next) {
next = stmt->GetNext();
if (stmt->GetOpCode() == OP_comment) {
if (commentB == nullptr) {
commentB = stmt;
commentE = stmt;
} else {
CHECK_FATAL(commentE != nullptr, "nullptr is not expected");
CHECK_FATAL(commentE->GetNext() == stmt, "make sure commentE's next is stmt");
commentE = stmt;
}
continue;
}
CHECK_FATAL(stmt->GetOpCode() != OP_comment, "make sure stmt's opcde not equal OP_comment");
CHECK_FATAL(commentB == nullptr || (commentE != nullptr && commentE->GetNext() == stmt),
"make sure commentB is nullptr or commentE's next is stmt");
if (curBB != nullptr) {
if (stmt->GetOpCode() != OP_label && stmt->GetOpCode() != OP_try && stmt->GetOpCode() != OP_endtry) {
curBB->Extend(commentB, stmt);
} else {
/* java catch blockes always start with a label (i.e., OP_catch) */
CHECK_FATAL(curBB->GetCondJumpBranch() == nullptr, "expect curBB's condJumpBranch is nullptr");
CHECK_FATAL(curBB->GetFallthruBranch() == nullptr, "expect curBB's fallthruBranch is nullptr");
/* a 'label' statement starts a new basic block */
BBT *newBB = CreateNewBB(commentB, stmt);
/*
* if the immediately preceding statement (discounting comments) was throw, goto or return,
* curBB is to be reset to nullptr, so the control won't come here.
*/
curBB->SetFallthruBranch(newBB);
curBB = newBB;
}
} else {
/* start a new basic block with 'comment_b -- stmt' */
curBB = CreateNewBB(commentB, stmt);
if (lastBB != nullptr) {
Opcode lastBBLastStmtOp = lastBB->GetLastStmt()->GetOpCode();
if (lastBB->GetLastStmt()->IsCondBr() || lastBBLastStmtOp == OP_endtry) {
lastBB->SetFallthruBranch(curBB);
}
/* else don't connect curBB to last_bb */
}
}
commentB = nullptr;
commentE = nullptr;
switch (stmt->GetOpCode()) {
case OP_throw:
case OP_return:
case OP_goto:
/* start a new bb at the next stmt */
lastBB = curBB;
curBB = nullptr;
break;
case OP_label: {
LabelNode *labelStmt = static_cast<LabelNode*>(stmt);
labeledBBs.emplace_back(curBB);
curBB->SetLabelIdx((LabelIdx)labelStmt->GetLabelIdx());
} break;
case OP_brtrue:
case OP_brfalse:
condbrBBs.emplace_back(curBB);
lastBB = curBB;
curBB = nullptr;
break;
case OP_switch:
switchBBs.emplace_back(curBB);
lastBB = curBB;
curBB = nullptr;
break;
/*
* We deal try and endtry slightly differently.
* 1. try begins a basic block which includes the try statement and the subsequent statements up to one that
* results in non-sequential control transfer such as unconditional/conditional branches.
* 2. endtry will create its own basic block which contains the endtry statement and nothing else.
*/
case OP_try:
case OP_endtry: {
/* because a label statement is inserted at the function entry */
CHECK_FATAL(curBB != nullptr, "expect curBB is not nullptr");
CHECK_FATAL(curBB->GetCondJumpBranch() == nullptr, "expect curBB's condJumpBranch is nullptr");
CHECK_FATAL(curBB->GetFallthruBranch() == nullptr, "expect curBB's fallthruBranch is nullptr");
CHECK_FATAL(curBB->GetLastStmt()->GetOpCode() == stmt->GetOpCode(),
"the opcode of curBB's lastStmt should equal stmt's opcocde");
if (stmt->GetOpCode() == OP_try) {
CHECK_FATAL(openTry == nullptr, "trys are not expected to be nested");
curBB->SetType(BBT::kBBTry, *stmt);
openTry = curBB;
prevBBOfTry[openTry] = lastBB;
} else {
tryBBs.emplace_back(BBTPair(openTry, curBB));
openTry = nullptr;
curBB->SetType(BBT::kBBEndTry, *stmt);
lastBB = curBB;
curBB = nullptr;
}
break;
}
case OP_catch: {
#if DEBUG
StmtNode *ss = stmt->GetPrev();
while ((ss != nullptr) && (ss->GetOpCode() == OP_comment)) {
ss = ss->GetPrev();
}
CHECK_FATAL(ss != nullptr, "expect ss is not nullptr");
CHECK_FATAL(ss->GetOpCode() == OP_label, "expect op equal OP_label");
for (auto &tb : catchBBs) {
CHECK_FATAL(tb != curBB, "tb should not equal curBB");
}
#endif
catchBBs.emplace_back(curBB);
curBB->SetType(BBT::kBBCatch, *stmt);
break;
}
case OP_block:
CHECK_FATAL(0, "should not run here");
default:
break;
}
}
for (auto &cbBB : condbrBBs) {
CHECK_FATAL(cbBB->GetLastStmt()->IsCondBr(), "cbBB's lastStmt is not condBr");
CondGotoNode *s = static_cast<CondGotoNode*>(cbBB->GetLastStmt());
cbBB->SetCondJumpBranch(FindTargetBBlock((LabelIdx)s->GetOffset(), labeledBBs));
}
for (auto &swBB : switchBBs) {
CHECK_FATAL(swBB->GetLastStmt()->GetOpCode() == OP_switch, "the opcode of sw's lastStmt should equal OP_switch");
SwitchNode *ss = static_cast<SwitchNode*>(swBB->GetLastStmt());
swBB->AddSuccs(FindTargetBBlock(ss->GetDefaultLabel(), labeledBBs));
for (auto &cp : ss->GetSwitchTable()) {
swBB->AddSuccs(FindTargetBBlock(cp.second, labeledBBs));
}
}
for (auto &bb : bbList) {
firstStmtToBBMap[bb->GetFirstStmt()] = bb;
}
CHECK_FATAL(openTry == nullptr, "trys are not expected to be nested");
}
/* if catchBB is in try-endtry block and catch is own to current try-endtry, process it and return true */
bool TryCatchBlocksLower::CheckAndProcessCatchNodeInCurrTryBlock(BBT &origLowerBB, LabelIdx ebbLabel,
uint32 index) {
MapleVector<BBT*> &enclosedBBs = tryEndTryBlock.GetEnclosedBBs();
MapleVector<BBT*> &bbsToRelocate = tryEndTryBlock.GetBBsToRelocate();
BBT *endTryBB = tryEndTryBlock.GetEndTryBB();
StmtNode *tryStmt = tryEndTryBlock.GetTryStmtNode();
bool found = false;
for (size_t tempIndex = 0; tempIndex < static_cast<TryNode*>(tryStmt)->GetOffsetsCount(); ++tempIndex) {
auto id = static_cast<TryNode*>(tryStmt)->GetOffset(tempIndex);
/*
* if this labeled bb is a catch block,
* remove it from the list of blocks enclosed in this try-block'
*/
if (ebbLabel == id) {
found = true;
enclosedBBs[index] = nullptr;
std::vector<BBT*> currBBThread;
BBT *lowerBB = &origLowerBB;
/* append it to the list of blocks placed after the end try block */
currBBThread.emplace_back(lowerBB);
while (lowerBB->GetFallthruBranch() != nullptr) {
lowerBB = lowerBB->GetFallthruBranch();
CHECK_FATAL(!lowerBB->IsTry(), "ebb must not be tryBB");
if (lowerBB->IsEndTry()) {
CHECK_FATAL(lowerBB == endTryBB, "lowerBB should equal endTryBB");
break;
}
for (uint32 j = 0; j < enclosedBBs.size(); ++j) {
if (enclosedBBs[j] == lowerBB) {
enclosedBBs[j] = nullptr;
break;
}
}
currBBThread.emplace_back(lowerBB);
}
if (!lowerBB->IsEndTry()) {
for (auto &e : currBBThread) {
bbsToRelocate.emplace_back(e);
}
} else {
/*
* We have the following case.
* bb_head -> bb_1 -> .. bb_n -> endtry_bb -> succ
* For this particular case, we swap endtry bb and curr_bb_thread because the bblock that
* contains the endtry statement does not contain any other statements!!
*/
CHECK_FATAL(endTryBB->GetFirstStmt()->GetOpCode() == OP_comment ||
endTryBB->GetFirstStmt()->GetOpCode() == OP_endtry,
"the opcode of endTryBB's firstStmt should be OP_comment or OP_endtry");
CHECK_FATAL(endTryBB->GetLastStmt()->GetOpCode() == OP_endtry,
"the opcode of endTryBB's lastStmt should be OP_endtry");
/* we move endtry_bb before thread_head */
BBT *threadHead = currBBThread.front();
CHECK_FATAL(threadHead->GetFirstStmt()->GetPrev() != nullptr,
"the prev node of threadHead's firstStmt should be not nullptr");
CHECK_FATAL(threadHead->GetFirstStmt()->GetOpCode() == OP_comment ||
threadHead->GetFirstStmt()->GetOpCode() == OP_label,
"the opcode of threadHead's firstStmt should be OP_comment or OP_label");
CHECK_FATAL(threadHead->GetFirstStmt()->GetPrev()->GetNext() == threadHead->GetFirstStmt(),
"the next of the prev of threadHead's firstStmt should equal threadHead's firstStmt");
threadHead->GetFirstStmt()->GetPrev()->SetNext(endTryBB->GetFirstStmt());
endTryBB->GetFirstStmt()->SetPrev(threadHead->GetFirstStmt()->GetPrev());
BBT *threadTail = currBBThread.back();
threadTail->GetLastStmt()->SetNext(endTryBB->GetLastStmt()->GetNext());
if (endTryBB->GetLastStmt()->GetNext() != nullptr) {
endTryBB->GetLastStmt()->GetNext()->SetPrev(threadTail->GetLastStmt());
}
endTryBB->GetLastStmt()->SetNext(threadHead->GetFirstStmt());
CHECK_FATAL(endTryBB->GetCondJumpBranch() == nullptr, "endTryBB's condJumpBranch must be nullptr");
if (threadTail->GetFallthruBranch() != nullptr) {
threadTail->SetFallthruBranch(firstStmtToBBMap[threadTail->GetLastStmt()->GetNext()]);
}
endTryBB->SetFallthruBranch(nullptr);
if (bodyEndWithEndTry) {
body.SetLast(threadTail->GetLastStmt());
}
}
break;
}
}
return found;
}
/* collect catchbb->fallthru(0-n) into currBBThread, when encounter a new catch, return it, else return nullptr */
BBT *TryCatchBlocksLower::CollectCatchAndFallthruUntilNextCatchBB(BBT *&lowerBB, uint32 &nextEnclosedIdx,
std::vector<BBT*> &currBBThread) {
MapleVector<BBT*> &enclosedBBs = tryEndTryBlock.GetEnclosedBBs();
BBT *endTryBB = tryEndTryBlock.GetEndTryBB();
BBT *nextBBThreadHead = nullptr;
while (lowerBB->GetFallthruBranch() != nullptr) {
lowerBB = lowerBB->GetFallthruBranch();
++nextEnclosedIdx;
if (lowerBB->IsEndTry()) {
CHECK_FATAL(lowerBB == endTryBB, "lowerBB should equal endTryBB");
break;
}
for (uint32 j = 0; j < enclosedBBs.size(); ++j) {
if (enclosedBBs[j] == lowerBB) {
enclosedBBs[j] = nullptr;
break;
}
}
if (lowerBB->IsCatch()) {
nextBBThreadHead = lowerBB;
break;
}
currBBThread.emplace_back(lowerBB);
}
if (nextBBThreadHead == nullptr && lowerBB->GetFallthruBranch() == nullptr && lowerBB != endTryBB &&
nextEnclosedIdx < enclosedBBs.size() && enclosedBBs[nextEnclosedIdx]) {
/*
* Using a loop to find the next_bb_thread_head when it's a catch_BB or a normal_BB which
* is after a catch_BB. Other condition, push_back into the curr_bb_thread.
*/
do {
lowerBB = enclosedBBs[nextEnclosedIdx];
enclosedBBs[nextEnclosedIdx++] = nullptr;
BBT *head = currBBThread.front();
if (head->IsCatch() || lowerBB->IsCatch()) {
nextBBThreadHead = lowerBB;
break;
}
currBBThread.emplace_back(lowerBB);
} while (nextEnclosedIdx < enclosedBBs.size());
}
return nextBBThreadHead;
}
void TryCatchBlocksLower::ProcessThreadTail(BBT &threadTail, const BBT *&nextBBThreadHead, bool hasMoveEndTry) {
BBT *endTryBB = tryEndTryBlock.GetEndTryBB();
StmtNode *newEndTry = endTryBB->GetKeyStmt()->CloneTree(mirModule.GetCurFuncCodeMPAllocator());
newEndTry->SetPrev(threadTail.GetLastStmt());
newEndTry->SetNext(threadTail.GetLastStmt()->GetNext());
if (bodyEndWithEndTry && hasMoveEndTry) {
if (threadTail.GetLastStmt()->GetNext()) {
threadTail.GetLastStmt()->GetNext()->SetPrev(newEndTry);
}
} else {
CHECK_FATAL(threadTail.GetLastStmt()->GetNext() != nullptr,
"the next of threadTail's lastStmt should not be nullptr");
threadTail.GetLastStmt()->GetNext()->SetPrev(newEndTry);
}
threadTail.GetLastStmt()->SetNext(newEndTry);
threadTail.SetLastStmt(*newEndTry);
if (hasMoveEndTry && nextBBThreadHead == nullptr) {
body.SetLast(threadTail.GetLastStmt());
}
}
/* Wrap this catch block with try-endtry block */
void TryCatchBlocksLower::WrapCatchWithTryEndTryBlock(std::vector<BBT*> &currBBThread, BBT *&nextBBThreadHead,
uint32 &nextEnclosedIdx, bool hasMoveEndTry) {
BBT *endTryBB = tryEndTryBlock.GetEndTryBB();
StmtNode *tryStmt = tryEndTryBlock.GetTryStmtNode();
MapleVector<BBT*> &enclosedBBs = tryEndTryBlock.GetEnclosedBBs();
for (auto &e : currBBThread) {
CHECK_FATAL(!e->IsTry(), "expect e is not try");
}
BBT *threadHead = currBBThread.front();
if (threadHead->IsCatch()) {
StmtNode *jcStmt = threadHead->GetKeyStmt();
CHECK_FATAL(jcStmt->GetNext() != nullptr, "jcStmt's next should not be nullptr");
TryNode *jtCopy = static_cast<TryNode*>(tryStmt)->CloneTree(mirModule.GetCurFuncCodeMPAllocator());
jtCopy->SetNext(jcStmt->GetNext());
jtCopy->SetPrev(jcStmt);
jcStmt->GetNext()->SetPrev(jtCopy);
jcStmt->SetNext(jtCopy);
BBT *threadTail = currBBThread.back();
/* for this endtry stmt, we don't need to create a basic block */
ProcessThreadTail(*threadTail, (const BBT *&)nextBBThreadHead, hasMoveEndTry);
} else {
/* For cases try->catch->normal_bb->normal_bb->endtry, Combine normal bb first. */
while (nextEnclosedIdx < enclosedBBs.size()) {
if (nextBBThreadHead != nullptr) {
if (nextBBThreadHead->IsCatch()) {
break;
}
}
BBT *ebbSecond = enclosedBBs[nextEnclosedIdx];
enclosedBBs[nextEnclosedIdx++] = nullptr;
CHECK_FATAL(ebbSecond != endTryBB, "ebbSecond should not equal endTryBB");
if (ebbSecond->IsCatch()) {
nextBBThreadHead = ebbSecond;
break;
}
currBBThread.emplace_back(ebbSecond);
}
/* normal bb. */
StmtNode *stmt = threadHead->GetFirstStmt();
TryNode *jtCopy = static_cast<TryNode*>(tryStmt)->CloneTree(mirModule.GetCurFuncCodeMPAllocator());
jtCopy->SetNext(stmt);
jtCopy->SetPrev(stmt->GetPrev());
stmt->GetPrev()->SetNext(jtCopy);
stmt->SetPrev(jtCopy);
threadHead->SetFirstStmt(*jtCopy);
BBT *threadTail = currBBThread.back();
/* for this endtry stmt, we don't need to create a basic block */
ProcessThreadTail(*threadTail, (const BBT *&)nextBBThreadHead, hasMoveEndTry);
}
}
/*
* We have the following case.
* bb_head -> bb_1 -> .. bb_n -> endtry_bb -> succ
* For this particular case, we swap EndTry bb and curr_bb_thread, because the bblock that contains the endtry
* statement does not contain any other statements!!
*/
void TryCatchBlocksLower::SwapEndTryBBAndCurrBBThread(const std::vector<BBT*> &currBBThread, bool &hasMoveEndTry,
const BBT *nextBBThreadHead) {
BBT *endTryBB = tryEndTryBlock.GetEndTryBB();
CHECK_FATAL(endTryBB->GetFirstStmt()->GetOpCode() == OP_comment ||
endTryBB->GetFirstStmt()->GetOpCode() == OP_endtry,
"the opcode of endTryBB's firstStmt should be OP_comment or OP_endtry");
CHECK_FATAL(endTryBB->GetLastStmt()->GetOpCode() == OP_endtry,
"the opcode of endTryBB's lastStmt should be OP_endtry");
/* we move endtry_bb before bb_head */
BBT *threadHead = currBBThread.front();
CHECK_FATAL(threadHead->GetFirstStmt()->GetPrev() != nullptr,
"the prev of threadHead's firstStmt should not nullptr");
CHECK_FATAL(threadHead->GetFirstStmt()->GetOpCode() == OP_comment ||
threadHead->GetFirstStmt()->GetOpCode() == OP_label,
"the opcode of threadHead's firstStmt should be OP_comment or OP_label");
CHECK_FATAL(threadHead->GetFirstStmt()->GetPrev()->GetNext() == threadHead->GetFirstStmt(),
"the next of the prev of threadHead's firstStmt should equal threadHead's firstStmt");
endTryBB->GetFirstStmt()->GetPrev()->SetNext(endTryBB->GetLastStmt()->GetNext());
if (endTryBB->GetLastStmt()->GetNext() != nullptr) {
endTryBB->GetLastStmt()->GetNext()->SetPrev(endTryBB->GetFirstStmt()->GetPrev());
}
threadHead->GetFirstStmt()->GetPrev()->SetNext(endTryBB->GetFirstStmt());
endTryBB->GetFirstStmt()->SetPrev(threadHead->GetFirstStmt()->GetPrev());
endTryBB->GetLastStmt()->SetNext(threadHead->GetFirstStmt());
threadHead->GetFirstStmt()->SetPrev(endTryBB->GetLastStmt());
CHECK_FATAL(endTryBB->GetCondJumpBranch() == nullptr, "endTryBB's condJumpBranch must be nullptr");
endTryBB->SetFallthruBranch(nullptr);
if (bodyEndWithEndTry) {
hasMoveEndTry = true;
if (nextBBThreadHead == nullptr) {
body.SetLast(currBBThread.back()->GetLastStmt());
}
}
}
void TryCatchBlocksLower::ProcessEnclosedBBBetweenTryEndTry() {
MapleVector<BBT*> &enclosedBBs = tryEndTryBlock.GetEnclosedBBs();
MapleVector<BBT*> &labeledBBsInTry = tryEndTryBlock.GetLabeledBBsInTry();
for (uint32 i = 0; i < enclosedBBs.size(); ++i) {
BBT *lowerBB = enclosedBBs[i];
uint32 nextEnclosedIdx = i + 1;
if (lowerBB == nullptr) {
continue; /* we may have removed the element */
}
if (!lowerBB->IsLabeled()) {
continue;
}
labeledBBsInTry.emplace_back(lowerBB);
/*
* It seems the way a finally is associated with its try is to put the catch block inside
* the java-try-end-try block. So, keep the 'catch(void*)' in it.
*/
LabelIdx ebbLabel = lowerBB->GetLabelIdx();
bool found = CheckAndProcessCatchNodeInCurrTryBlock(*lowerBB, ebbLabel, i);
/* fill cur_bb_thread until meet the next catch */
if (!found && lowerBB->IsCatch()) {
enclosedBBs[i] = nullptr;
std::vector<BBT*> currBBThread;
BBT *nextBBThreadHead = nullptr;
bool isFirstTime = true;
bool hasMoveEndTry = false;
do {
if (nextBBThreadHead != nullptr) {
isFirstTime = false;
}
nextBBThreadHead = nullptr;
currBBThread.clear();
currBBThread.emplace_back(lowerBB);
nextBBThreadHead = CollectCatchAndFallthruUntilNextCatchBB(lowerBB, nextEnclosedIdx, currBBThread);
WrapCatchWithTryEndTryBlock(currBBThread, nextBBThreadHead, nextEnclosedIdx, hasMoveEndTry);
if (isFirstTime) {
SwapEndTryBBAndCurrBBThread(currBBThread, hasMoveEndTry, nextBBThreadHead);
}
} while (nextBBThreadHead != nullptr);
}
}
}
void TryCatchBlocksLower::ConnectRemainBB() {
MapleVector<BBT*> &enclosedBBs = tryEndTryBlock.GetEnclosedBBs();
BBT *startTryBB = tryEndTryBlock.GetStartTryBB();
BBT *endTryBB = tryEndTryBlock.GetEndTryBB();
size_t nEnclosedBBs = enclosedBBs.size();
size_t k = 0;
while ((k < nEnclosedBBs) && (enclosedBBs[k] == nullptr)) {
++k;
}
if (k < nEnclosedBBs) {
BBT *prevBB = enclosedBBs[k];
startTryBB->GetLastStmt()->SetNext(prevBB->GetFirstStmt());
prevBB->GetFirstStmt()->SetPrev(startTryBB->GetLastStmt());
for (++k; k < nEnclosedBBs; ++k) {
BBT *lowerBB = enclosedBBs[k];
if (lowerBB == nullptr) {
continue;
}
prevBB->GetLastStmt()->SetNext(lowerBB->GetFirstStmt());
lowerBB->GetFirstStmt()->SetPrev(prevBB->GetLastStmt());
prevBB = lowerBB;
}
prevBB->GetLastStmt()->SetNext(endTryBB->GetFirstStmt());
endTryBB->GetFirstStmt()->SetPrev(prevBB->GetLastStmt());
} else {
startTryBB->GetLastStmt()->SetNext(endTryBB->GetFirstStmt());
endTryBB->GetFirstStmt()->SetPrev(startTryBB->GetLastStmt());
}
}
BBT *TryCatchBlocksLower::FindInsertAfterBB() {
BBT *insertAfter = tryEndTryBlock.GetEndTryBB();
CHECK_FATAL(tryEndTryBlock.GetEndTryBB()->GetLastStmt()->GetOpCode() == OP_endtry, "LowerBB type check");
BBT *iaOpenTry = nullptr;
while (insertAfter->GetFallthruBranch() != nullptr || iaOpenTry != nullptr) {
if (insertAfter->GetFallthruBranch() != nullptr) {
insertAfter = insertAfter->GetFallthruBranch();
} else {
CHECK_FATAL(iaOpenTry != nullptr, "iaOpenTry should not be nullptr");
insertAfter = firstStmtToBBMap[insertAfter->GetLastStmt()->GetNext()];
CHECK_FATAL(!insertAfter->IsTry(), "insertAfter should not be try");
}
if (insertAfter->IsTry()) {
iaOpenTry = insertAfter;
} else if (insertAfter->IsEndTry()) {
iaOpenTry = nullptr;
}
}
return insertAfter;
}
void TryCatchBlocksLower::PlaceRelocatedBB(BBT &insertAfter) {
StmtNode *iaLast = insertAfter.GetLastStmt();
CHECK_FATAL(iaLast != nullptr, "iaLast should not nullptr");
StmtNode *iaNext = iaLast->GetNext();
if (iaNext == nullptr) {
CHECK_FATAL(body.GetLast() == iaLast, "body's last should equal iaLast");
}
BBT *prevBB = &insertAfter;
MapleVector<BBT*> &bbsToRelocate = tryEndTryBlock.GetBBsToRelocate();
for (auto &rbb : bbsToRelocate) {
prevBB->GetLastStmt()->SetNext(rbb->GetFirstStmt());
rbb->GetFirstStmt()->SetPrev(prevBB->GetLastStmt());
prevBB = rbb;
}
prevBB->GetLastStmt()->SetNext(iaNext);
if (iaNext != nullptr) {
iaNext->SetPrev(prevBB->GetLastStmt());
} else {
/* !ia_next means we started with insert_after that was the last bblock Refer to the above CHECK_FATAL. */
body.SetLast(prevBB->GetLastStmt());
body.GetLast()->SetNext(nullptr);
}
}
void TryCatchBlocksLower::PalceCatchSeenSofar(BBT &insertAfter) {
TryNode *tryNode = static_cast<TryNode*>(tryEndTryBlock.GetTryStmtNode());
ASSERT(tryNode != nullptr, "tryNode should not be nullptr");
MapleVector<BBT*> &bbsToRelocate = tryEndTryBlock.GetBBsToRelocate();
for (size_t offsetIndex = 0; offsetIndex < tryNode->GetOffsetsCount(); ++offsetIndex) {
auto id = tryNode->GetOffset(offsetIndex);
bool myCatchBlock = false;
for (auto &jcb : bbsToRelocate) {
if (!jcb->IsLabeled()) {
continue;
}
myCatchBlock = (id == jcb->GetLabelIdx());
if (myCatchBlock) {
break;
}
}
/*
* If the catch block is the one enclosed in this try-endtry block,
* we just relocated it above, so we don't need to consider it again
*/
if (myCatchBlock) {
continue;
}
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
for (auto &jcb : catchesSeenSoFar) {
CHECK_FATAL(jcb->IsLabeled(), "jcb should be labeled");
if (id == jcb->GetLabelIdx()) {
/*
* Remove jcb and all of the blocks that are reachable by following fallthruBranch.
* If we hit a try block, cut there, append an unconditional jump to it to the preceding bblock,
* and relocate them. We may need to insert a label in the try block
*/
BBT *lastBB = jcb;
while (lastBB->GetFallthruBranch() != nullptr && !lastBB->GetFallthruBranch()->IsTry()) {
lastBB = lastBB->GetFallthruBranch();
}
#if DEBUG
BBT::ValidateStmtList(bodyFirst);
#endif
if (lastBB->GetFallthruBranch() != nullptr) {
BBT *jtBB = lastBB->GetFallthruBranch();
CHECK_FATAL(jtBB->IsTry(), "jtBB should be try");
if (!jtBB->IsLabeled()) {
LabelIdx jtLabIdx = mirModule.GetMIRBuilder()->CreateLabIdx(*mirModule.CurFunction());
jtBB->SetLabelIdx(jtLabIdx);
StmtNode *labelStmt = mirModule.GetMIRBuilder()->CreateStmtLabel(jtLabIdx);
bool adjustBBFirstStmt = (jtBB->GetKeyStmt() == jtBB->GetFirstStmt());
labelStmt->SetNext(jtBB->GetKeyStmt());
labelStmt->SetPrev(jtBB->GetKeyStmt()->GetPrev());
CHECK_FATAL(jtBB->GetKeyStmt()->GetPrev() != nullptr, "the prev of jtBB's ketStmt shpould not be nullptr");
jtBB->GetKeyStmt()->GetPrev()->SetNext(labelStmt);
CHECK_FATAL(jtBB->GetKeyStmt()->GetNext() != nullptr, "the next of jtBB's ketStmt shpould not be nullptr");
jtBB->GetKeyStmt()->SetPrev(labelStmt);
if (adjustBBFirstStmt) {
firstStmtToBBMap.erase(jtBB->GetFirstStmt());
jtBB->SetFirstStmt(*labelStmt);
firstStmtToBBMap[jtBB->GetFirstStmt()] = jtBB;
}
}
CHECK_FATAL(jtBB->IsLabeled(), "jtBB should be labeled");
CHECK_FATAL(lastBB->GetLastStmt()->GetOpCode() != OP_goto,
"the opcode of lastBB's lastStmt should not be OP_goto");
StmtNode *gotoStmt = mirModule.GetMIRBuilder()->CreateStmtGoto(OP_goto, jtBB->GetLabelIdx());
StmtNode *lastBBLastStmt = lastBB->GetLastStmt();
gotoStmt->SetNext(lastBBLastStmt->GetNext());
gotoStmt->SetPrev(lastBBLastStmt);
if (lastBBLastStmt->GetNext()) {
lastBBLastStmt->GetNext()->SetPrev(gotoStmt);
}
lastBBLastStmt->SetNext(gotoStmt);
lastBB->SetLastStmt(*gotoStmt);
lastBB->SetFallthruBranch(nullptr);
#if DEBUG
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
BBT::ValidateStmtList(bodyFirst);
#endif
}
/* we want to remove [jcb .. last_bb], inclusively. */
if (jcb->GetFirstStmt() == body.GetFirst()) {
body.SetFirst(lastBB->GetLastStmt()->GetNext());
body.GetFirst()->SetPrev(nullptr);
lastBB->GetLastStmt()->GetNext()->SetPrev(nullptr);
bodyFirst = body.GetFirst();
} else {
CHECK_FATAL(jcb->GetFirstStmt()->GetPrev() != nullptr, "the prev of jcb's firstStmt should not be nullptr");
CHECK_FATAL(jcb->GetFirstStmt()->GetPrev()->GetNext() == jcb->GetFirstStmt(),
"the next of the prev of jcb's firstStmt should equal jcb's firstStmt");
if (lastBB->GetLastStmt()->GetNext() != nullptr) {
jcb->GetFirstStmt()->GetPrev()->SetNext(lastBB->GetLastStmt()->GetNext());
lastBB->GetLastStmt()->GetNext()->SetPrev(jcb->GetFirstStmt()->GetPrev());
} else {
CHECK_FATAL(lastBB->GetLastStmt() == body.GetLast(), "lastBB's lastStmt should equal body's last");
body.SetLast(jcb->GetFirstStmt()->GetPrev());
body.GetLast()->SetNext(nullptr);
jcb->GetFirstStmt()->GetPrev()->SetNext(nullptr);
}
}
jcb->GetFirstStmt()->SetPrev(nullptr);
lastBB->GetLastStmt()->SetNext(nullptr);
#if DEBUG
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
BBT::ValidateStmtList(body.GetFirst(), jcb->GetFirstStmt());
#endif
/* append it (i.e., [jcb->firstStmt .. last_bb->lastStmt]) after insert_after */
CHECK_FATAL(insertAfter.GetFallthruBranch() == nullptr, "insertAfter's fallthruBranch should be nullptr");
if (insertAfter.GetLastStmt() == body.GetLast()) {
CHECK_FATAL(insertAfter.GetLastStmt()->GetNext() == nullptr,
"the next of insertAfter's lastStmt should not be nullptr");
}
jcb->GetFirstStmt()->SetPrev(insertAfter.GetLastStmt());
lastBB->GetLastStmt()->SetNext(insertAfter.GetLastStmt()->GetNext());
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
if (insertAfter.GetLastStmt()->GetNext() != nullptr) {
insertAfter.GetLastStmt()->GetNext()->SetPrev(lastBB->GetLastStmt());
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
} else {
/*
* note that we have a single BlockNode that contains all the instructions of a method.
* What that means is each instruction's next is not nullptr except for the very last instruction.
* insert_after->lastStmt->next == nullptr, means insert_after->lastStmt is indeed the last instruction,
* and we are moving instructions of 'last_bb' after it. Thus, we need to fix the BlockNode's last field.
*/
body.SetLast(lastBB->GetLastStmt());
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
}
insertAfter.GetLastStmt()->SetNext(jcb->GetFirstStmt());
if (jcb->GetFirstStmt()->GetPrev() != nullptr) {
CHECK_FATAL(jcb->GetFirstStmt()->GetPrev()->GetNext() == jcb->GetFirstStmt(),
"the next of the prev of jcb's firstStmt should equal jcb's firstStmt");
}
if (lastBB->GetLastStmt()->GetNext() != nullptr) {
CHECK_FATAL(lastBB->GetLastStmt()->GetNext()->GetPrev() == lastBB->GetLastStmt(),
"thr prev of the next of lastBB's lastStmt should equal lastBB's lastStmt");
}
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
}
}
}
}
void TryCatchBlocksLower::TraverseBBList() {
tryEndTryBlock.Init();
for (auto &bb : bbList) {
if (bb->IsCatch() && tryEndTryBlock.GetStartTryBB() == nullptr) {
/* Add to the list of catch blocks seen so far. */
catchesSeenSoFar.emplace_back(bb);
}
bodyEndWithEndTry = false;
if (tryEndTryBlock.GetStartTryBB() == nullptr) {
if (bb->IsTry()) {
StmtNode *firstNonCommentStmt = bb->GetFirstStmt();
while (firstNonCommentStmt != nullptr && firstNonCommentStmt->GetOpCode() == OP_comment) {
firstNonCommentStmt = firstNonCommentStmt->GetNext();
}
CHECK_FATAL(bb->GetLastStmt()->GetOpCode() != OP_try || bb->GetLastStmt() == firstNonCommentStmt ||
!generateEHCode, "make sure the opcode of bb's lastStmt is not OP_try"
"or the opcode of bb's lastStmt is OP_try but bb's lastStmt equals firstNonCommentStmt"
"or not generate EHCode");
/* prepare for processing a java try block */
tryEndTryBlock.Reset(*bb);
}
continue;
}
/* We should have not a try block enclosed in another java try block!! */
CHECK_FATAL(!bb->IsTry(), "bb should not be try");
if (!bb->IsEndTry()) {
tryEndTryBlock.PushToEnclosedBBs(*bb);
} else {
tryEndTryBlock.SetEndTryBB(bb);
if (tryEndTryBlock.GetEndTryBB()->GetLastStmt() == body.GetLast()) {
bodyEndWithEndTry = true;
}
#if DEBUG
for (size_t i = 0; i < tryEndTryBlock.GetEnclosedBBsSize(); ++i) {
CHECK_FATAL(tryEndTryBlock.GetEnclosedBBsElem(i), "there should not be nullptr in enclosedBBs");
}
#endif
ProcessEnclosedBBBetweenTryEndTry();
/* Now, connect the remaining ones again n_enclosed_bbs includes 'nullptr's (i.e., deleted entries) */
ConnectRemainBB();
BBT *insertAfter = FindInsertAfterBB();
PlaceRelocatedBB(*insertAfter);
#if DEBUG
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
BBT::ValidateStmtList(bodyFirst);
#endif
if (prevBBOfTry[tryEndTryBlock.GetStartTryBB()]) {
StmtNode *firstStmtMovedIn = MoveCondGotoIntoTry(*tryEndTryBlock.GetStartTryBB(),
*prevBBOfTry[tryEndTryBlock.GetStartTryBB()],
tryEndTryBlock.GetLabeledBBsInTry());
if (firstStmtMovedIn == bodyFirst) {
bodyFirst = tryEndTryBlock.GetStartTryBB()->GetFirstStmt();
prevBBOfTry[tryEndTryBlock.GetStartTryBB()] = nullptr;
}
}
/*
* Now, examine each offset attached to this try and move any catch block
* that is not in 'bbs_to_relocate' but in 'catches_seen_so_far'
*/
PalceCatchSeenSofar(*insertAfter);
/* close the try that is open */
tryEndTryBlock.SetStartTryBB(nullptr);
}
#if DEBUG
CHECK_FATAL(body.GetLast()->GetNext() == nullptr, "the next of body's last should be nullptr");
BBT::ValidateStmtList(bodyFirst);
#endif
}
body.SetFirst(bodyFirst);
}
void TryCatchBlocksLower::CheckTryCatchPattern() const {
StmtNode *openJt = nullptr;
for (StmtNode *stmt = body.GetFirst(); stmt; stmt = stmt->GetNext()) {
switch (stmt->GetOpCode()) {
case OP_try:
openJt = stmt;
break;
case OP_endtry:
openJt = nullptr;
break;
case OP_catch:
if (openJt != nullptr) {
CatchNode *jcn = static_cast<CatchNode*>(stmt);
for (uint32 i = 0; i < jcn->Size(); ++i) {
MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(jcn->GetExceptionTyIdxVecElement(i));
MIRPtrType *ptr = static_cast<MIRPtrType*>(type);
type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(ptr->GetPointedTyIdx());
CHECK_FATAL(type->GetPrimType() == PTY_void, "type's primType should be PTY_void");
}
}
break;
default:
break;
}
}
}
} /* namespace maplebe */
|
#ifndef INCG_PHI_CORE_AS_CONST_HPP
#define INCG_PHI_CORE_AS_CONST_HPP
#include "phi/phi_config.hpp"
#if PHI_HAS_EXTENSION_PRAGMA_ONCE()
# pragma once
#endif
#include "phi/compiler_support/nodiscard.hpp"
#include "phi/type_traits/add_const.hpp"
DETAIL_PHI_BEGIN_NAMESPACE()
template <typename TypeT>
PHI_NODISCARD constexpr add_const_t<TypeT>& as_const(TypeT& t) noexcept
{
return t;
}
template <typename TypeT>
void as_const(const TypeT&&) = delete;
DETAIL_PHI_END_NAMESPACE()
#endif // INCG_PHI_CORE_AS_CONST_HPP
|
// Copyright 2010 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. 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 <iostream>
// back-end
#include <boost/msm/back/state_machine.hpp>
//front-end
#include <boost/msm/front/state_machine_def.hpp>
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>
namespace msm = boost::msm;
namespace mpl = boost::mpl;
namespace
{
// events
struct play {};
struct end_pause {};
struct stop {};
struct pause {};
struct open_close {};
struct NextSong {};
struct PreviousSong {};
struct cd_detected
{
cd_detected(std::string name)
: name(name)
{}
std::string name;
};
// front-end: define the FSM structure
struct player_ : public msm::front::state_machine_def<player_>
{
unsigned int start_playback_counter;
unsigned int can_close_drawer_counter;
player_():
start_playback_counter(0),
can_close_drawer_counter(0)
{}
// The list of FSM states
struct Empty : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Open : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
// sm_ptr still supported but deprecated as functors are a much better way to do the same thing
struct Stopped : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Playing_ : public msm::front::state_machine_def<Playing_>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
unsigned int start_next_song_counter;
unsigned int start_prev_song_guard_counter;
Playing_():
start_next_song_counter(0),
start_prev_song_guard_counter(0)
{}
// The list of FSM states
struct Song1 : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Song2 : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Song3 : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
// the initial state. Must be defined
typedef Song1 initial_state;
// transition actions
void start_next_song(NextSong const&) {++start_next_song_counter; }
void start_prev_song(PreviousSong const&) { }
// guard conditions
bool start_prev_song_guard(PreviousSong const&) {++start_prev_song_guard_counter;return true; }
typedef Playing_ pl; // makes transition table cleaner
// Transition table for Playing
struct transition_table : mpl::vector4<
// Start Event Next Action Guard
// +---------+-------------+---------+---------------------+----------------------+
_row < Song1 , NextSong , Song2 >,
row < Song2 , PreviousSong, Song1 , &pl::start_prev_song,&pl::start_prev_song_guard>,
a_row < Song2 , NextSong , Song3 , &pl::start_next_song >,
g_row < Song3 , PreviousSong, Song2 ,&pl::start_prev_song_guard>
// +---------+-------------+---------+---------------------+----------------------+
> {};
// Replaces the default no-transition response.
template <class FSM,class Event>
void no_transition(Event const&, FSM&,int)
{
BOOST_FAIL("no_transition called!");
}
};
// back-end
typedef msm::back::state_machine<Playing_> Playing;
// state not defining any entry or exit
struct Paused : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
// the initial state of the player SM. Must be defined
typedef Empty initial_state;
// transition actions
void start_playback(play const&) {++start_playback_counter; }
void open_drawer(open_close const&) { }
void store_cd_info(cd_detected const&) { }
void stop_playback(stop const&) { }
void pause_playback(pause const&) { }
void resume_playback(end_pause const&) { }
void stop_and_open(open_close const&) { }
void stopped_again(stop const&){}
//guards
bool can_close_drawer(open_close const&)
{
++can_close_drawer_counter;
return true;
}
typedef player_ p; // makes transition table cleaner
// Transition table for player
struct transition_table : mpl::vector<
// Start Event Next Action Guard
// +---------+-------------+---------+---------------------+----------------------+
a_row < Stopped , play , Playing , &p::start_playback >,
a_row < Stopped , open_close , Open , &p::open_drawer >,
_row < Stopped , stop , Stopped >,
// +---------+-------------+---------+---------------------+----------------------+
g_row < Open , open_close , Empty , &p::can_close_drawer >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Empty , open_close , Open , &p::open_drawer >,
a_row < Empty , cd_detected , Stopped , &p::store_cd_info >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Playing , stop , Stopped , &p::stop_playback >,
a_row < Playing , pause , Paused , &p::pause_playback >,
a_row < Playing , open_close , Open , &p::stop_and_open >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Paused , end_pause , Playing , &p::resume_playback >,
a_row < Paused , stop , Stopped , &p::stop_playback >,
a_row < Paused , open_close , Open , &p::stop_and_open >
// +---------+-------------+---------+---------------------+----------------------+
> {};
// Replaces the default no-transition response.
template <class FSM,class Event>
void no_transition(Event const& e, FSM&,int state)
{
BOOST_FAIL("no_transition called!");
}
// init counters
template <class Event,class FSM>
void on_entry(Event const&,FSM& fsm)
{
fsm.template get_state<player_::Stopped&>().entry_counter=0;
fsm.template get_state<player_::Stopped&>().exit_counter=0;
fsm.template get_state<player_::Open&>().entry_counter=0;
fsm.template get_state<player_::Open&>().exit_counter=0;
fsm.template get_state<player_::Empty&>().entry_counter=0;
fsm.template get_state<player_::Empty&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song1&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song1&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song2&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song2&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song3&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song3&>().exit_counter=0;
fsm.template get_state<player_::Paused&>().entry_counter=0;
fsm.template get_state<player_::Paused&>().exit_counter=0;
}
};
// Pick a back-end
typedef msm::back::state_machine<player_> player;
// static char const* const state_names[] = { "Stopped", "Open", "Empty", "Playing", "Paused" };
BOOST_AUTO_TEST_CASE( my_test )
{
player p;
p.start();
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().entry_counter == 1,"Empty entry not called correctly");
p.process_event(open_close());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 1,"Open should be active"); //Open
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().exit_counter == 1,"Empty exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Open&>().entry_counter == 1,"Open entry not called correctly");
p.process_event(open_close());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 2,"Empty should be active"); //Empty
BOOST_CHECK_MESSAGE(p.get_state<player_::Open&>().exit_counter == 1,"Open exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().entry_counter == 2,"Empty entry not called correctly");
BOOST_CHECK_MESSAGE(p.can_close_drawer_counter == 1,"guard not called correctly");
p.process_event(cd_detected("louie, louie"));
BOOST_CHECK_MESSAGE(p.current_state()[0] == 0,"Stopped should be active"); //Stopped
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().exit_counter == 2,"Empty exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().entry_counter == 1,"Stopped entry not called correctly");
p.process_event(play());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().exit_counter == 1,"Stopped exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().entry_counter == 1,"Playing entry not called correctly");
BOOST_CHECK_MESSAGE(p.start_playback_counter == 1,"action not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 0,"Song1 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song1&>().entry_counter == 1,
"Song1 entry not called correctly");
p.process_event(NextSong());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 1,"Song2 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song2&>().entry_counter == 1,
"Song2 entry not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song1&>().exit_counter == 1,
"Song1 exit not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().start_next_song_counter == 0,
"submachine action not called correctly");
p.process_event(NextSong());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 2,"Song3 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song3&>().entry_counter == 1,
"Song3 entry not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song2&>().exit_counter == 1,
"Song2 exit not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().start_next_song_counter == 1,
"submachine action not called correctly");
p.process_event(PreviousSong());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 1,"Song2 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song2&>().entry_counter == 2,
"Song2 entry not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song3&>().exit_counter == 1,
"Song3 exit not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().start_prev_song_guard_counter == 1,
"submachine guard not called correctly");
p.process_event(pause());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 4,"Paused should be active"); //Paused
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().exit_counter == 1,"Playing exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().entry_counter == 1,"Paused entry not called correctly");
// go back to Playing
p.process_event(end_pause());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().exit_counter == 1,"Paused exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().entry_counter == 2,"Playing entry not called correctly");
p.process_event(pause());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 4,"Paused should be active"); //Paused
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().exit_counter == 2,"Playing exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().entry_counter == 2,"Paused entry not called correctly");
p.process_event(stop());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 0,"Stopped should be active"); //Stopped
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().exit_counter == 2,"Paused exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().entry_counter == 2,"Stopped entry not called correctly");
p.process_event(stop());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 0,"Stopped should be active"); //Stopped
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().exit_counter == 2,"Stopped exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().entry_counter == 3,"Stopped entry not called correctly");
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "Color.h"
namespace facebook {
namespace react {
SharedColor colorFromComponents(ColorComponents components) {
const CGFloat componentsArray[] = {
components.red, components.green, components.blue, components.alpha};
auto color = CGColorCreate(CGColorSpaceCreateDeviceRGB(), componentsArray);
return SharedColor(color, CFRelease);
}
ColorComponents colorComponentsFromColor(SharedColor color) {
if (!color) {
// Empty color object can be considered as `clear` (black, fully
// transparent) color.
return ColorComponents{0, 0, 0, 0};
}
auto numberOfComponents __unused = CGColorGetNumberOfComponents(color.get());
assert(numberOfComponents == 4);
const CGFloat *components = CGColorGetComponents(color.get());
return ColorComponents{(float)components[0],
(float)components[1],
(float)components[2],
(float)components[3]};
}
SharedColor clearColor() {
static SharedColor color = colorFromComponents(ColorComponents{0, 0, 0, 0});
return color;
}
SharedColor blackColor() {
static SharedColor color = colorFromComponents(ColorComponents{0, 0, 0, 1});
return color;
}
SharedColor whiteColor() {
static SharedColor color = colorFromComponents(ColorComponents{1, 1, 1, 1});
return color;
}
} // namespace react
} // namespace facebook
|
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Fernando Iglesias, Shashwat Lal Das, Thoralf Klein,
* Soeren Sonnenburg
*/
#include <shogun/loss/SmoothHingeLoss.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
float64_t CSmoothHingeLoss::loss(float64_t z)
{
if (z < 0)
return 0.5 - z;
if (z < 1)
return 0.5 * (1-z) * (1-z);
return 0;
}
float64_t CSmoothHingeLoss::first_derivative(float64_t z)
{
if (z < 0)
return -1;
if (z < 1)
return z-1;
return 0;
}
float64_t CSmoothHingeLoss::second_derivative(float64_t z)
{
if (z < 0)
return 0;
if (z < 1)
return 1;
return 0;
}
float64_t CSmoothHingeLoss::get_update(float64_t prediction, float64_t label, float64_t eta_t, float64_t norm)
{
not_implemented(SOURCE_LOCATION);
return -1;
}
float64_t CSmoothHingeLoss::get_square_grad(float64_t prediction, float64_t label)
{
not_implemented(SOURCE_LOCATION);
return -1;
}
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/base/tf/regTest.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/arch/defines.h"
#include <stdarg.h>
#include <string>
#include <vector>
#include <sstream>
#include <stdio.h>
using namespace std;
PXR_NAMESPACE_USING_DIRECTIVE
static bool
TestNumbers()
{
/* compare as floats */
TF_AXIOM(float(TfStringToDouble("")) == 0.0f);
TF_AXIOM(float(TfStringToDouble("blah")) == 0.0f);
TF_AXIOM(float(TfStringToDouble("-")) == -0.0f);
TF_AXIOM(float(TfStringToDouble("1.2")) == 1.2f);
TF_AXIOM(float(TfStringToDouble("1")) == 1.0f);
TF_AXIOM(float(TfStringToDouble("-5000001")) == -5000001.0f);
TF_AXIOM(float(TfStringToDouble("0.123")) == 0.123f);
TF_AXIOM(float(TfStringToDouble("-.123")) == -0.123f);
TF_AXIOM(float(TfStringToDouble(string("-1e3"))) == -1e3f);
TF_AXIOM(float(TfStringToDouble(string("1e6"))) == 1e6f);
TF_AXIOM(float(TfStringToDouble(string("-1E-1"))) == -1E-1f);
TF_AXIOM(TfIntToString(1) == "1");
TF_AXIOM(TfIntToString(1024) == "1024");
TF_AXIOM(TfIntToString(0) == "0");
TF_AXIOM(TfIntToString(-22) == "-22");
// Test round-tripping of floating point numbers.
// This is obviously not an exhaustive test of the 2^64 space of
// double-precision floats -- these are simply representative values
// that failed to round-trip correctly under a prior implementation.
TF_AXIOM(TfStringToDouble(TfStringify(0.1)) == 0.1);
TF_AXIOM(TfStringToDouble(TfStringify(0.336316384899143))
== 0.336316384899143);
TF_AXIOM(float(TfStringToDouble(TfStringify(0.1f))) == 0.1f);
TF_AXIOM(float(TfStringToDouble(TfStringify(0.84066f))) == 0.84066f);
// Test similar operations on stream based stringify operations
std::stringstream sstr;
sstr << TfStreamDouble(0.1);
TF_AXIOM(TfStringToDouble(sstr.str()) == 0.1);
sstr.str(std::string());
sstr << TfStreamDouble(0.336316384899143);
TF_AXIOM(TfStringToDouble(sstr.str()) == 0.336316384899143);
sstr.str(std::string());
sstr << TfStreamFloat(0.1f);
TF_AXIOM(float(TfStringToDouble(sstr.str())) == 0.1f);
sstr.str(std::string());
sstr << TfStreamFloat(0.84066f);
TF_AXIOM(float(TfStringToDouble(sstr.str())) == 0.84066f);
constexpr int bufferSize = 25;
char buffer[bufferSize];
TF_AXIOM(
TfDoubleToString(-1.1111111111111113e-308, buffer, bufferSize, true));
TF_AXIOM(strcmp(buffer, "-1.1111111111111113e-308") == 0);
TF_AXIOM(
!TfDoubleToString(-1.1111111111111113e-308, buffer, 24, true));
return true;
}
static bool
DictLessThan(const string &a, const string &b)
{
return TfDictionaryLessThan()(a, b);
}
static bool
TestPreds()
{
TF_AXIOM(TfStringStartsWith(" ", " "));
TF_AXIOM(TfStringStartsWith("abc", "ab"));
TF_AXIOM(TfStringStartsWith("xyz", "xyz"));
TF_AXIOM(TfStringStartsWith("a little bit longer string", "a little"));
TF_AXIOM(TfStringStartsWith("anything", ""));
TF_AXIOM(!TfStringStartsWith("", " "));
TF_AXIOM(!TfStringStartsWith("abc", "bc"));
TF_AXIOM(TfStringEndsWith(" ", " "));
TF_AXIOM(TfStringEndsWith("abc", "bc"));
TF_AXIOM(TfStringEndsWith("xyz", "xyz"));
TF_AXIOM(TfStringEndsWith("a little bit longer string", " string"));
TF_AXIOM(TfStringEndsWith("anything", ""));
TF_AXIOM(!TfStringEndsWith("", " "));
TF_AXIOM(!TfStringEndsWith("abc", "ab"));
TF_AXIOM(DictLessThan("ring", "robot"));
TF_AXIOM(!DictLessThan("robot", "ring"));
TF_AXIOM(!DictLessThan("Alex", "aardvark"));
TF_AXIOM(DictLessThan("aardvark", "Alex"));
TF_AXIOM(DictLessThan("Alex", "AMD"));
TF_AXIOM(!DictLessThan("AMD", "Alex"));
TF_AXIOM(DictLessThan("1", "15"));
TF_AXIOM(!DictLessThan("15", "1"));
TF_AXIOM(DictLessThan("1998", "1999"));
TF_AXIOM(!DictLessThan("1999", "1998"));
TF_AXIOM(DictLessThan("Worker8", "Worker11"));
TF_AXIOM(!DictLessThan("Worker11", "Worker8"));
TF_AXIOM(DictLessThan("agent007", "agent222"));
TF_AXIOM(!DictLessThan("agent222", "agent007"));
TF_AXIOM(DictLessThan("agent007", "agent0007"));
TF_AXIOM(DictLessThan("agent7", "agent07"));
TF_AXIOM(!DictLessThan("agent07", "agent07"));
TF_AXIOM(DictLessThan("0", "00"));
TF_AXIOM(DictLessThan("1", "01"));
TF_AXIOM(!DictLessThan("2", "01"));
TF_AXIOM(DictLessThan("foo001bar001abc", "foo001bar002abc"));
TF_AXIOM(DictLessThan("foo001bar01abc", "foo001bar001abc"));
TF_AXIOM(!DictLessThan("foo001bar002abc", "foo001bar001abc"));
TF_AXIOM(DictLessThan("foo00001bar0002abc", "foo001bar002xyz"));
TF_AXIOM(!DictLessThan("foo00001bar0002xyz", "foo001bar002abc"));
TF_AXIOM(DictLessThan("foo1bar02", "foo01bar2"));
TF_AXIOM(DictLessThan("agent007", "agent8"));
TF_AXIOM(DictLessThan("agent007", "agent222"));
TF_AXIOM(DictLessThan("agent007", "agent222"));
TF_AXIOM(!DictLessThan("GOTO8", "goto7"));
TF_AXIOM(DictLessThan("goto7", "GOTO8"));
TF_AXIOM(DictLessThan("!", "$"));
TF_AXIOM(!DictLessThan("$", "!"));
TF_AXIOM(DictLessThan("foo", "foo") == 0);
TF_AXIOM(DictLessThan("aa", "aaa"));
TF_AXIOM(!DictLessThan("aaa", "aa"));
TF_AXIOM(TfIsValidIdentifier("f"));
TF_AXIOM(TfIsValidIdentifier("foo"));
TF_AXIOM(TfIsValidIdentifier("foo1"));
TF_AXIOM(TfIsValidIdentifier("_foo"));
TF_AXIOM(TfIsValidIdentifier("_foo1"));
TF_AXIOM(TfIsValidIdentifier("__foo__"));
TF_AXIOM(TfIsValidIdentifier("__foo1__"));
TF_AXIOM(TfIsValidIdentifier("__foo1__2"));
TF_AXIOM(TfIsValidIdentifier("_"));
TF_AXIOM(TfIsValidIdentifier("_2"));
TF_AXIOM(!TfIsValidIdentifier(""));
TF_AXIOM(!TfIsValidIdentifier("1"));
TF_AXIOM(!TfIsValidIdentifier("2foo"));
TF_AXIOM(!TfIsValidIdentifier("1_foo"));
TF_AXIOM(!TfIsValidIdentifier("13_foo2"));
TF_AXIOM(!TfIsValidIdentifier(" "));
TF_AXIOM(!TfIsValidIdentifier(" foo"));
TF_AXIOM(!TfIsValidIdentifier(" _foo\n "));
TF_AXIOM(!TfIsValidIdentifier(" _foo32 \t "));
TF_AXIOM(!TfIsValidIdentifier("$"));
TF_AXIOM(!TfIsValidIdentifier("\a"));
TF_AXIOM(!TfIsValidIdentifier("foo$"));
TF_AXIOM(!TfIsValidIdentifier("_foo$"));
TF_AXIOM(!TfIsValidIdentifier(" _foo$"));
TF_AXIOM(!TfIsValidIdentifier("foo bar"));
TF_AXIOM(!TfIsValidIdentifier("\"foo\""));
return true;
}
string
DoPrintf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
string ret = TfVStringPrintf(fmt, ap);
va_end(ap);
return ret;
}
string
DoPrintfStr(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
string ret = TfVStringPrintf(string(fmt), ap);
va_end(ap);
return ret;
}
static bool
TestStrings()
{
TF_AXIOM(TfStringToLower(" ") == " ");
TF_AXIOM(TfStringToLower("lower") == "lower");
TF_AXIOM(TfStringToLower("LOWER") == "lower");
TF_AXIOM(TfStringToLower("LOWer") == "lower");
TF_AXIOM(TfStringToLower("LOWer@123") == "lower@123");
TF_AXIOM(TfStringToUpper("upper") == "UPPER");
TF_AXIOM(TfStringToUpper("UPPER") == "UPPER");
TF_AXIOM(TfStringToUpper("UPPer") == "UPPER");
TF_AXIOM(TfStringToUpper("UPPer@123") == "UPPER@123");
TF_AXIOM(TfStringCapitalize("Already") == "Already");
TF_AXIOM(TfStringCapitalize("notyet") == "Notyet");
TF_AXIOM(TfStringCapitalize("@@@@") == "@@@@");
TF_AXIOM(TfStringCapitalize("") == "");
TF_AXIOM(TfStringGetSuffix("file.ext") == "ext");
TF_AXIOM(TfStringGetSuffix("here are some words", ' ') == "words");
TF_AXIOM(TfStringGetSuffix("0words", '0') == "words");
TF_AXIOM(TfStringGetSuffix("A@B@C", '@') == "C");
TF_AXIOM(TfStringGetSuffix("nothing", ' ') == "");
TF_AXIOM(TfStringGetSuffix("nothing", '\0') == "");
TF_AXIOM(TfStringGetBeforeSuffix("file.ext") == "file");
TF_AXIOM(TfStringGetBeforeSuffix("here are some words", ' ') == "here are some");
TF_AXIOM(TfStringGetBeforeSuffix("0words", '0') == "");
TF_AXIOM(TfStringGetBeforeSuffix("A@B@C", '@') == "A@B");
TF_AXIOM(TfStringGetBeforeSuffix("nothing", ' ') == "nothing");
TF_AXIOM(TfStringGetBeforeSuffix("nothing", '\0') == "nothing");
TF_AXIOM(TfGetBaseName("") == "");
TF_AXIOM(TfGetBaseName("/foo/bar") == "bar");
TF_AXIOM(TfGetBaseName("/foo/bar/") == "bar");
TF_AXIOM(TfGetBaseName("../some-dir/bar") == "bar");
TF_AXIOM(TfGetBaseName("bar") == "bar");
#if defined(ARCH_OS_WINDOWS)
// Same on Windows but with backslashes.
TF_AXIOM(TfGetBaseName("\\foo\\bar") == "bar");
TF_AXIOM(TfGetBaseName("\\foo\\bar\\") == "bar");
TF_AXIOM(TfGetBaseName("..\\some-dir\\bar") == "bar");
TF_AXIOM(TfGetBaseName("C:\\hello") == "hello");
TF_AXIOM(TfGetBaseName("C:\\") == "");
TF_AXIOM(TfGetBaseName("C:") == "");
TF_AXIOM(TfGetBaseName("C:hello.txt") == "hello.txt");
#endif
TF_AXIOM(TfGetPathName("") == "");
TF_AXIOM(TfGetPathName("/") == "/");
TF_AXIOM(TfGetPathName("/foo/bar") == "/foo/");
TF_AXIOM(TfGetPathName("../some-dir/bar") == "../some-dir/");
TF_AXIOM(TfGetPathName("bar") == "");
#if defined(ARCH_OS_WINDOWS)
// Same on Windows but with backslashes.
TF_AXIOM(TfGetPathName("\\") == "\\");
TF_AXIOM(TfGetPathName("\\foo\\bar") == "\\foo\\");
TF_AXIOM(TfGetPathName("..\\some-dir\\bar") == "..\\some-dir\\");
#endif
TF_AXIOM(TfStringTrimRight("", " ") == "");
TF_AXIOM(TfStringTrimRight("to be trimmed") == "to be trimmed");
TF_AXIOM(TfStringTrimRight("to be trimmed", "x") == "to be trimmed");
TF_AXIOM(TfStringTrimRight(" to be trimmed ") == " to be trimmed");
TF_AXIOM(TfStringTrimRight(" to be trimmed ", " ") == " to be trimmed");
TF_AXIOM(TfStringTrimRight(" to be trimmed ", "x ") == " to be trimmed");
TF_AXIOM(TfStringTrimLeft("", " ") == "");
TF_AXIOM(TfStringTrimLeft("to be trimmed") == "to be trimmed");
TF_AXIOM(TfStringTrimLeft("to be trimmed", "x") == "to be trimmed");
TF_AXIOM(TfStringTrimLeft(" to be trimmed ") == "to be trimmed ");
TF_AXIOM(TfStringTrimLeft(" to be trimmed ", " ") == "to be trimmed ");
TF_AXIOM(TfStringTrimLeft(" to be trimmed ", "x ") == "to be trimmed ");
TF_AXIOM(TfStringTrim("", " ") == "");
TF_AXIOM(TfStringTrim("to be trimmed") == "to be trimmed");
TF_AXIOM(TfStringTrim("to be trimmed", "x") == "to be trimmed");
TF_AXIOM(TfStringTrim(" to be trimmed ") == "to be trimmed");
TF_AXIOM(TfStringTrim(" to be trimmed ", " ") == "to be trimmed");
TF_AXIOM(TfStringTrim(" to be trimmed ", "x ") == "to be trimmed");
TF_AXIOM(TfStringTrim("_to be trimmed ", "_ ") == "to be trimmed");
TF_AXIOM(TfStringReplace("an old string", "n old", " new") == "a new string");
TF_AXIOM(TfStringReplace("remove", "remove", "") == "");
TF_AXIOM(TfStringReplace("12121", "21", "31") == "13131");
TF_AXIOM(TfStringReplace("aaaa", "aa", "b") == "bb");
TF_AXIOM(TfStringReplace("no more spaces", " ", "_") == "no_more_spaces");
TF_AXIOM(TfStringReplace("Capital", "cap", "zap") == "Capital");
TF_AXIOM(TfStringReplace("string", "", "number") == "string");
TF_AXIOM(TfStringReplace("string", "str", "str") == "string");
TF_AXIOM(TfStringGetCommonPrefix("", "") == "");
TF_AXIOM(TfStringGetCommonPrefix("a", "") == "");
TF_AXIOM(TfStringGetCommonPrefix("", "b") == "");
TF_AXIOM(TfStringGetCommonPrefix("a", "b") == "");
TF_AXIOM(TfStringGetCommonPrefix("a", "a") == "a");
TF_AXIOM(TfStringGetCommonPrefix("abracadabra", "abracababra") == "abraca");
TF_AXIOM(TfStringGetCommonPrefix("aabcd", "aaabcd") == "aa");
TF_AXIOM(TfStringGetCommonPrefix("aabcdefg", "aabcd") == "aabcd");
std::string const s = "foo";
TF_AXIOM(TfStringify(s) == "foo");
TF_AXIOM(TfStringify(true) == "true");
TF_AXIOM(TfStringify(false) == "false");
TF_AXIOM(TfUnstringify<bool>("true") == true);
TF_AXIOM(TfUnstringify<bool>("false") == false);
TF_AXIOM(TfStringify(1) == "1");
TF_AXIOM(TfUnstringify<int>("1") == 1);
TF_AXIOM(TfStringify(1.1) == "1.1");
TF_AXIOM(TfUnstringify<float>("1.1") == 1.1f);
TF_AXIOM(TfStringify('a') == "a");
TF_AXIOM(TfUnstringify<char>("a") == 'a');
TF_AXIOM(TfStringify("string") == "string");
TF_AXIOM(TfUnstringify<string>("string") == "string");
bool unstringRet = true;
TfUnstringify<int>("this ain't no int", &unstringRet);
TF_AXIOM(unstringRet == false);
TF_AXIOM(TfStringPrintf("%s", "hello") == "hello");
TF_AXIOM(TfStringPrintf("%d%d", 1, 2) == "12");
TF_AXIOM(DoPrintf("%s", "hello") == "hello");
TF_AXIOM(DoPrintf("%d%d", 1, 2) == "12");
TF_AXIOM(DoPrintfStr("%s", "hello") == "hello");
TF_AXIOM(DoPrintfStr("%d%d", 1, 2) == "12");
TF_AXIOM(TfEscapeString("\\\\") == "\\");
TF_AXIOM(TfEscapeString("new\\nline") == "new\nline");
TF_AXIOM(TfEscapeString("two\\nnew\\nlines") == "two\nnew\nlines");
TF_AXIOM(TfEscapeString("a\\ttab") == "a\ttab");
TF_AXIOM(TfEscapeString("\\a\\b") == "\a\b");
TF_AXIOM(TfEscapeString("\\f\\n") == "\f\n");
TF_AXIOM(TfEscapeString("\\r\\v") == "\r\v");
TF_AXIOM(TfEscapeString("\\c \\d") == "c d");
TF_AXIOM(TfEscapeString("\\xB") == "\xB");
TF_AXIOM(TfEscapeString("\\xab") == "\xab");
TF_AXIOM(TfEscapeString("\\x01f") == "\x1" "f");
TF_AXIOM(TfEscapeString("\\x008d") == string() + '\0' + "8d");
TF_AXIOM(TfEscapeString("x\\x0x") == string() + 'x' + '\0' + 'x');
TF_AXIOM(TfEscapeString("\\5") == "\5");
TF_AXIOM(TfEscapeString("\\70") == "\70");
TF_AXIOM(TfEscapeString("\\11z") == "\11z");
TF_AXIOM(TfEscapeString("\\007") == "\007");
TF_AXIOM(TfEscapeString("\\008") == string() + '\0' + '8');
TF_AXIOM(TfEscapeString("\\010") == "\010");
TF_AXIOM(TfEscapeString("\\0077") == "\07" "7");
TF_AXIOM(TfEscapeString("\\00107") == "\01" "07");
TF_AXIOM(TfEscapeString("\\005107") == "\05" "107");
TF_AXIOM(TfStringCatPaths("foo", "bar") == "foo/bar");
TF_AXIOM(TfStringCatPaths("foo/crud", "../bar") == "foo/bar");
TF_AXIOM(TfStringCatPaths("foo", "../bar") == "bar");
TF_AXIOM(TfStringCatPaths("/foo", "../bar") == "/bar");
TF_AXIOM(TfStringCatPaths("foo/crud/crap", "../bar") == "foo/crud/bar");
#if defined(ARCH_OS_WINDOWS)
// Same on Windows but with backslashes.
TF_AXIOM(TfStringCatPaths("foo", "bar") == "foo/bar");
TF_AXIOM(TfStringCatPaths("foo\\crud", "../bar") == "foo/bar");
TF_AXIOM(TfStringCatPaths("foo", "..\\bar") == "bar");
TF_AXIOM(TfStringCatPaths("\\foo", "..\\bar") == "/bar");
TF_AXIOM(TfStringCatPaths("foo\\crud\\crap", "..\\bar") == "foo/crud/bar");
#endif
return true;
}
static bool
TestTokens()
{
vector<string> tokens;
vector<string> empty;
set<string> tokenSet;
TF_AXIOM(TfStringJoin(empty, " ") == "");
tokenSet = TfStringTokenizeToSet(" to be tokens ", " ");
TF_AXIOM(tokenSet.size() == 3);
tokenSet = TfStringTokenizeToSet(" to be tokens", " ");
TF_AXIOM(tokenSet.size() == 3);
tokens = TfStringTokenize(" to be tokens ", " ");
TF_AXIOM(tokens.size() == 3);
TF_AXIOM(TfStringJoin(tokens, " ") == "to be tokens");
tokens = TfStringTokenize("A1B2C3", "123");
TF_AXIOM(tokens.size() == 3);
TF_AXIOM(TfStringJoin(tokens, "") == "ABC");
tokens = TfStringTokenize("no tokens", "");
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, "") == "no tokens");
tokens = TfStringTokenize("no tokens", "xyz");
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "no tokens");
tokens = TfQuotedStringTokenize("\"no tokens\"", " ");
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "no tokens");
tokens = TfQuotedStringTokenize(" foo\"no tokens\"", " ");
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "foono tokens");
// test error conditions
string errorString;
tokens = TfQuotedStringTokenize("\"no tokens\"", "\"", &errorString);
TF_AXIOM(errorString != "");
errorString = "";
tokens = TfQuotedStringTokenize("\"no tokens", " ", &errorString);
TF_AXIOM(errorString != "");
TF_AXIOM(tokens.empty());
tokens = TfQuotedStringTokenize("A1B2C3", "123");
TF_AXIOM(tokens.size() == 3);
TF_AXIOM(TfStringJoin(tokens, "") == "ABC");
tokens = TfQuotedStringTokenize("\"a \\\"b\\\" c\" d");
TF_AXIOM(tokens.size() == 2);
TF_AXIOM(TfStringJoin(tokens, " ") == "a \"b\" c d");
tokens = TfQuotedStringTokenize(" \"there are\" \"two tokens\" ");
TF_AXIOM(tokens.size() == 2);
TF_AXIOM(TfStringJoin(tokens, " ") == "there are two tokens");
tokens = TfQuotedStringTokenize("\"there is\"\" one token\"", " ");
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "there is one token");
tokens = TfQuotedStringTokenize("\\\"this_gets_split\\\"", "_");
TF_AXIOM(tokens.size() == 3);
TF_AXIOM(TfStringJoin(tokens, " ") == "\"this gets split\"");
tokens = TfQuotedStringTokenize("\"\\\"this_doesn't\\\"\"", "_");
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "\"this_doesn't\"");
tokens = TfQuotedStringTokenize("\"\'nothing\' `to` \\\"split\\\"\"", " ");
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "\'nothing\' `to` \"split\"");
tokens = TfQuotedStringTokenize("\'esc\\\"\' \\\"aped", " ");
TF_AXIOM(tokens.size() == 2);
TF_AXIOM(TfStringJoin(tokens, " ") == "esc\" \"aped");
// test error conditions
// same delimiter
errorString = "";
tokens = TfMatchedStringTokenize("{", '{', '{', '\0', &errorString);
TF_AXIOM(tokens.empty());
TF_AXIOM(errorString != "");
// delimiter order
errorString = "";
tokens = TfMatchedStringTokenize("}garble{", '{', '}', '\0', &errorString);
TF_AXIOM(tokens.empty());
TF_AXIOM(errorString != "");
// unmatched open
errorString = "";
tokens = TfMatchedStringTokenize("{garble} {", '{', '}', '\0', &errorString);
TF_AXIOM(tokens.empty());
TF_AXIOM(errorString != "");
// unmatched close
errorString = "";
tokens = TfMatchedStringTokenize("{garble} }", '{', '}', '\0', &errorString);
TF_AXIOM(tokens.empty());
TF_AXIOM(errorString != "");
tokens = TfMatchedStringTokenize("{", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("}", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("}{}", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("{}{", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("{}}", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("{{}", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("{whoops", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("none!", '{', '}');
TF_AXIOM(tokens.empty());
tokens = TfMatchedStringTokenize("{test {test} test}", '{', '}');
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "test {test} test");
tokens = TfMatchedStringTokenize("{foo} {bar}", '{', '}');
TF_AXIOM(tokens.size() == 2);
TF_AXIOM(TfStringJoin(tokens, " ") == "foo bar");
tokens = TfMatchedStringTokenize("out{in}out", '{', '}');
TF_AXIOM(tokens.size() == 1);
TF_AXIOM(TfStringJoin(tokens, " ") == "in");
tokens = TfMatchedStringTokenize("{} {} {stuff_{foo}_{bar}}", '{', '}');
TF_AXIOM(tokens.size() == 3);
TF_AXIOM(TfStringJoin(tokens, " ") == " stuff_{foo}_{bar}");
tokens = TfMatchedStringTokenize("{and} {more{nested{braces}}}", '{', '}');
TF_AXIOM(tokens.size() == 2);
TF_AXIOM(TfStringJoin(tokens, " ") == "and more{nested{braces}}");
return true;
}
static bool
TestGetXmlEscapedString()
{
TF_AXIOM(TfGetXmlEscapedString("Amiga") == "Amiga");
TF_AXIOM(TfGetXmlEscapedString("Amiga & Atari") == "Amiga & Atari");
TF_AXIOM(TfGetXmlEscapedString("Amiga < Atari") == "Amiga < Atari");
TF_AXIOM(TfGetXmlEscapedString("Amiga > Atari") == "Amiga > Atari");
TF_AXIOM(TfGetXmlEscapedString("\"Atari\"") == ""Atari"");
TF_AXIOM(TfGetXmlEscapedString("'Atari'") == "'Atari'");
return true;
}
static bool
Test_TfStringUtils()
{
return TestNumbers() && TestPreds() && TestStrings() && TestTokens() &&
TestGetXmlEscapedString();
}
TF_ADD_REGTEST(TfStringUtils);
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute(L"CLibraryShim")];
[assembly:AssemblyDescriptionAttribute(L"")];
[assembly:AssemblyConfigurationAttribute(L"")];
[assembly:AssemblyCompanyAttribute(L"")];
[assembly:AssemblyProductAttribute(L"CLibraryShim")];
[assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2015")];
[assembly:AssemblyTrademarkAttribute(L"")];
[assembly:AssemblyCultureAttribute(L"")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/media/content_video_capture_device_core.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback_forward.h"
#include "base/callback_helpers.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/metrics/histogram.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "content/public/browser/browser_thread.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/video_frame.h"
#include "media/base/video_util.h"
#include "media/video/capture/video_capture_types.h"
#include "ui/gfx/rect.h"
namespace content {
namespace {
void DeleteCaptureMachineOnUIThread(
scoped_ptr<VideoCaptureMachine> capture_machine) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
capture_machine.reset();
}
} // namespace
ThreadSafeCaptureOracle::ThreadSafeCaptureOracle(
scoped_ptr<media::VideoCaptureDevice::Client> client,
scoped_ptr<VideoCaptureOracle> oracle,
const media::VideoCaptureParams& params)
: client_(client.Pass()),
oracle_(oracle.Pass()),
params_(params),
capture_size_updated_(false) {
// Frame dimensions must each be an even integer since the client wants (or
// will convert to) YUV420.
capture_size_ = gfx::Size(
MakeEven(params.requested_format.frame_size.width()),
MakeEven(params.requested_format.frame_size.height()));
frame_rate_ = params.requested_format.frame_rate;
}
ThreadSafeCaptureOracle::~ThreadSafeCaptureOracle() {}
bool ThreadSafeCaptureOracle::ObserveEventAndDecideCapture(
VideoCaptureOracle::Event event,
base::TimeTicks event_time,
scoped_refptr<media::VideoFrame>* storage,
CaptureFrameCallback* callback) {
base::AutoLock guard(lock_);
if (!client_)
return false; // Capture is stopped.
scoped_refptr<media::VideoCaptureDevice::Client::Buffer> output_buffer =
client_->ReserveOutputBuffer(media::VideoFrame::I420, capture_size_);
const bool should_capture =
oracle_->ObserveEventAndDecideCapture(event, event_time);
const bool content_is_dirty =
(event == VideoCaptureOracle::kCompositorUpdate ||
event == VideoCaptureOracle::kSoftwarePaint);
const char* event_name =
(event == VideoCaptureOracle::kTimerPoll ? "poll" :
(event == VideoCaptureOracle::kCompositorUpdate ? "gpu" :
"paint"));
// Consider the various reasons not to initiate a capture.
if (should_capture && !output_buffer) {
TRACE_EVENT_INSTANT1("mirroring",
"EncodeLimited",
TRACE_EVENT_SCOPE_THREAD,
"trigger",
event_name);
return false;
} else if (!should_capture && output_buffer) {
if (content_is_dirty) {
// This is a normal and acceptable way to drop a frame. We've hit our
// capture rate limit: for example, the content is animating at 60fps but
// we're capturing at 30fps.
TRACE_EVENT_INSTANT1("mirroring", "FpsRateLimited",
TRACE_EVENT_SCOPE_THREAD,
"trigger", event_name);
}
return false;
} else if (!should_capture && !output_buffer) {
// We decided not to capture, but we wouldn't have been able to if we wanted
// to because no output buffer was available.
TRACE_EVENT_INSTANT1("mirroring", "NearlyEncodeLimited",
TRACE_EVENT_SCOPE_THREAD,
"trigger", event_name);
return false;
}
int frame_number = oracle_->RecordCapture();
TRACE_EVENT_ASYNC_BEGIN2("mirroring", "Capture", output_buffer.get(),
"frame_number", frame_number,
"trigger", event_name);
*callback = base::Bind(&ThreadSafeCaptureOracle::DidCaptureFrame,
this,
output_buffer,
frame_number);
*storage = media::VideoFrame::WrapExternalPackedMemory(
media::VideoFrame::I420,
capture_size_,
gfx::Rect(capture_size_),
capture_size_,
static_cast<uint8*>(output_buffer->data()),
output_buffer->size(),
base::SharedMemory::NULLHandle(),
base::TimeDelta(),
base::Closure());
return true;
}
gfx::Size ThreadSafeCaptureOracle::GetCaptureSize() const {
base::AutoLock guard(lock_);
return capture_size_;
}
void ThreadSafeCaptureOracle::UpdateCaptureSize(const gfx::Size& source_size) {
base::AutoLock guard(lock_);
// If this is the first call to UpdateCaptureSize(), or the receiver supports
// variable resolution, then determine the capture size by treating the
// requested width and height as maxima.
if (!capture_size_updated_ || params_.allow_resolution_change) {
// The capture resolution should not exceed the source frame size.
// In other words it should downscale the image but not upscale it.
if (source_size.width() > params_.requested_format.frame_size.width() ||
source_size.height() > params_.requested_format.frame_size.height()) {
gfx::Rect capture_rect = media::ComputeLetterboxRegion(
gfx::Rect(params_.requested_format.frame_size), source_size);
capture_size_ = gfx::Size(MakeEven(capture_rect.width()),
MakeEven(capture_rect.height()));
} else {
capture_size_ = gfx::Size(MakeEven(source_size.width()),
MakeEven(source_size.height()));
}
capture_size_updated_ = true;
}
}
void ThreadSafeCaptureOracle::Stop() {
base::AutoLock guard(lock_);
client_.reset();
}
void ThreadSafeCaptureOracle::ReportError(const std::string& reason) {
base::AutoLock guard(lock_);
if (client_)
client_->OnError(reason);
}
void ThreadSafeCaptureOracle::DidCaptureFrame(
scoped_refptr<media::VideoCaptureDevice::Client::Buffer> buffer,
int frame_number,
base::TimeTicks timestamp,
bool success) {
base::AutoLock guard(lock_);
TRACE_EVENT_ASYNC_END2("mirroring", "Capture", buffer.get(),
"success", success,
"timestamp", timestamp.ToInternalValue());
if (!client_)
return; // Capture is stopped.
if (success) {
if (oracle_->CompleteCapture(frame_number, timestamp)) {
client_->OnIncomingCapturedBuffer(buffer,
media::VideoFrame::I420,
capture_size_,
timestamp,
frame_rate_);
}
}
}
void ContentVideoCaptureDeviceCore::AllocateAndStart(
const media::VideoCaptureParams& params,
scoped_ptr<media::VideoCaptureDevice::Client> client) {
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ != kIdle) {
DVLOG(1) << "Allocate() invoked when not in state Idle.";
return;
}
if (params.requested_format.frame_rate <= 0) {
std::string error_msg = base::StringPrintf(
"invalid frame_rate: %d", params.requested_format.frame_rate);
DVLOG(1) << error_msg;
client->OnError(error_msg);
return;
}
if (params.requested_format.frame_size.width() < kMinFrameWidth ||
params.requested_format.frame_size.height() < kMinFrameHeight) {
std::string error_msg =
"invalid frame size: " + params.requested_format.frame_size.ToString();
DVLOG(1) << error_msg;
client->OnError(error_msg);
return;
}
base::TimeDelta capture_period = base::TimeDelta::FromMicroseconds(
1000000.0 / params.requested_format.frame_rate + 0.5);
scoped_ptr<VideoCaptureOracle> oracle(
new VideoCaptureOracle(capture_period,
kAcceleratedSubscriberIsSupported));
oracle_proxy_ =
new ThreadSafeCaptureOracle(client.Pass(), oracle.Pass(), params);
// Starts the capture machine asynchronously.
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::UI, FROM_HERE,
base::Bind(&VideoCaptureMachine::Start,
base::Unretained(capture_machine_.get()),
oracle_proxy_),
base::Bind(&ContentVideoCaptureDeviceCore::CaptureStarted,
AsWeakPtr()));
TransitionStateTo(kCapturing);
}
void ContentVideoCaptureDeviceCore::StopAndDeAllocate() {
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ != kCapturing)
return;
oracle_proxy_->Stop();
oracle_proxy_ = NULL;
TransitionStateTo(kIdle);
// Stops the capture machine asynchronously.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, base::Bind(
&VideoCaptureMachine::Stop,
base::Unretained(capture_machine_.get()),
base::Bind(&base::DoNothing)));
}
void ContentVideoCaptureDeviceCore::CaptureStarted(bool success) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!success) {
std::string reason("Failed to start capture machine.");
DVLOG(1) << reason;
Error(reason);
}
}
ContentVideoCaptureDeviceCore::ContentVideoCaptureDeviceCore(
scoped_ptr<VideoCaptureMachine> capture_machine)
: state_(kIdle),
capture_machine_(capture_machine.Pass()) {}
ContentVideoCaptureDeviceCore::~ContentVideoCaptureDeviceCore() {
// If capture_machine is not NULL, then we need to return to the UI thread to
// safely stop the capture machine.
if (capture_machine_) {
VideoCaptureMachine* capture_machine_ptr = capture_machine_.get();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&VideoCaptureMachine::Stop,
base::Unretained(capture_machine_ptr),
base::Bind(&DeleteCaptureMachineOnUIThread,
base::Passed(&capture_machine_))));
}
DVLOG(1) << "ContentVideoCaptureDeviceCore@" << this << " destroying.";
}
void ContentVideoCaptureDeviceCore::TransitionStateTo(State next_state) {
DCHECK(thread_checker_.CalledOnValidThread());
#ifndef NDEBUG
static const char* kStateNames[] = {
"Idle", "Allocated", "Capturing", "Error"
};
DVLOG(1) << "State change: " << kStateNames[state_]
<< " --> " << kStateNames[next_state];
#endif
state_ = next_state;
}
void ContentVideoCaptureDeviceCore::Error(const std::string& reason) {
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ == kIdle)
return;
if (oracle_proxy_)
oracle_proxy_->ReportError(reason);
StopAndDeAllocate();
TransitionStateTo(kError);
}
} // namespace content
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__int_rand_to_short_84a.cpp
Label Definition File: CWE197_Numeric_Truncation_Error__int.label.xml
Template File: sources-sink-84a.tmpl.cpp
*/
/*
* @description
* CWE: 197 Numeric Truncation Error
* BadSource: rand Set data to result of rand(), which may be zero
* GoodSource: Less than CHAR_MAX
* Sinks: to_short
* BadSink : Convert data to a short
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#include "std_testcase.h"
#include "CWE197_Numeric_Truncation_Error__int_rand_to_short_84.h"
namespace CWE197_Numeric_Truncation_Error__int_rand_to_short_84
{
#ifndef OMITBAD
void bad()
{
int data;
/* Initialize data */
data = -1;
CWE197_Numeric_Truncation_Error__int_rand_to_short_84_bad * badObject = new CWE197_Numeric_Truncation_Error__int_rand_to_short_84_bad(data);
delete badObject;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int data;
/* Initialize data */
data = -1;
CWE197_Numeric_Truncation_Error__int_rand_to_short_84_goodG2B * goodG2BObject = new CWE197_Numeric_Truncation_Error__int_rand_to_short_84_goodG2B(data);
delete goodG2BObject;
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE197_Numeric_Truncation_Error__int_rand_to_short_84; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/******************************************************************************
CoolSparkFunBME280.h
Modified by Mehdi Zemzem
Originally SparkFunBME280.h
BME280 Arduino and Teensy Driver
Marshall Taylor @ SparkFun Electronics
May 20, 2015
https://github.com/sparkfun/BME280_Breakout
Resources:
Uses Wire.h for i2c operation
Uses SPI.h for SPI operation
Development environment specifics:
Arduino IDE 1.6.4
Teensy loader 1.23
This code is released under the [MIT License](http://opensource.org/licenses/MIT).
Please review the LICENSE.md file included with this example. If you have any questions
or concerns with licensing, please contact techsupport@sparkfun.com.
Distributed as-is; no warranty is given.
******************************************************************************/
//See SparkFunBME280.h for additional topology notes.
#include "CoolSparkFunBME280.h"
#include "stdint.h"
#include <math.h>
#include "Wire.h"
#include "SPI.h"
//****************************************************************************//
//
// Settings and configuration
//
//****************************************************************************//
//Constructor -- Specifies default configuration
BME280::BME280( void )
{
//Construct with these default settings if nothing is specified
//Select interface mode
settings.commInterface = I2C_MODE; //Can be I2C_MODE, SPI_MODE
//Select address for I2C. Does nothing for SPI
settings.I2CAddress = 0x77; //Ignored for SPI_MODE
//Select CS pin for SPI. Does nothing for I2C
settings.chipSelectPin = 10;
settings.runMode = 0;
settings.tempOverSample = 0;
settings.pressOverSample = 0;
settings.humidOverSample = 0;
}
//****************************************************************************//
//
// Configuration section
//
// This uses the stored SensorSettings to start the IMU
// Use statements such as "mySensor.settings.commInterface = SPI_MODE;" to
// configure before calling .begin();
//
//****************************************************************************//
uint8_t BME280::begin()
{
//Check the settings structure values to determine how to setup the device
uint8_t dataToWrite = 0; //Temporary variable
switch (settings.commInterface)
{
case I2C_MODE:
Wire.begin(2,14);
break;
case SPI_MODE:
// start the SPI library:
SPI.begin();
#ifdef ARDUINO_ARCH_ESP32
SPI.setFrequency(1000000);
// Data is read and written MSb first.
SPI.setBitOrder(SPI_MSBFIRST);
// Like the standard arduino/teensy comment below, mode0 seems wrong according to standards
// but conforms to the timing diagrams when used for the ESP32
SPI.setDataMode(SPI_MODE0);
#else
// Maximum SPI frequency is 10MHz, could divide by 2 here:
SPI.setClockDivider(SPI_CLOCK_DIV32);
// Data is read and written MSb first.
SPI.setBitOrder(MSBFIRST);
// Data is captured on rising edge of clock (CPHA = 0)
// Base value of the clock is HIGH (CPOL = 1)
// This was SPI_MODE3 for RedBoard, but I had to change to
// MODE0 for Teensy 3.1 operation
SPI.setDataMode(SPI_MODE3);
#endif
// initalize the data ready and chip select pins:
pinMode(settings.chipSelectPin, OUTPUT);
digitalWrite(settings.chipSelectPin, HIGH);
break;
default:
break;
}
//Reading all compensation data, range 0x88:A1, 0xE1:E7
calibration.dig_T1 = ((uint16_t)((readRegister(BME280_DIG_T1_MSB_REG) << 8) + readRegister(BME280_DIG_T1_LSB_REG)));
calibration.dig_T2 = ((int16_t)((readRegister(BME280_DIG_T2_MSB_REG) << 8) + readRegister(BME280_DIG_T2_LSB_REG)));
calibration.dig_T3 = ((int16_t)((readRegister(BME280_DIG_T3_MSB_REG) << 8) + readRegister(BME280_DIG_T3_LSB_REG)));
calibration.dig_P1 = ((uint16_t)((readRegister(BME280_DIG_P1_MSB_REG) << 8) + readRegister(BME280_DIG_P1_LSB_REG)));
calibration.dig_P2 = ((int16_t)((readRegister(BME280_DIG_P2_MSB_REG) << 8) + readRegister(BME280_DIG_P2_LSB_REG)));
calibration.dig_P3 = ((int16_t)((readRegister(BME280_DIG_P3_MSB_REG) << 8) + readRegister(BME280_DIG_P3_LSB_REG)));
calibration.dig_P4 = ((int16_t)((readRegister(BME280_DIG_P4_MSB_REG) << 8) + readRegister(BME280_DIG_P4_LSB_REG)));
calibration.dig_P5 = ((int16_t)((readRegister(BME280_DIG_P5_MSB_REG) << 8) + readRegister(BME280_DIG_P5_LSB_REG)));
calibration.dig_P6 = ((int16_t)((readRegister(BME280_DIG_P6_MSB_REG) << 8) + readRegister(BME280_DIG_P6_LSB_REG)));
calibration.dig_P7 = ((int16_t)((readRegister(BME280_DIG_P7_MSB_REG) << 8) + readRegister(BME280_DIG_P7_LSB_REG)));
calibration.dig_P8 = ((int16_t)((readRegister(BME280_DIG_P8_MSB_REG) << 8) + readRegister(BME280_DIG_P8_LSB_REG)));
calibration.dig_P9 = ((int16_t)((readRegister(BME280_DIG_P9_MSB_REG) << 8) + readRegister(BME280_DIG_P9_LSB_REG)));
calibration.dig_H1 = ((uint8_t)(readRegister(BME280_DIG_H1_REG)));
calibration.dig_H2 = ((int16_t)((readRegister(BME280_DIG_H2_MSB_REG) << 8) + readRegister(BME280_DIG_H2_LSB_REG)));
calibration.dig_H3 = ((uint8_t)(readRegister(BME280_DIG_H3_REG)));
calibration.dig_H4 = ((int16_t)((readRegister(BME280_DIG_H4_MSB_REG) << 4) + (readRegister(BME280_DIG_H4_LSB_REG) & 0x0F)));
calibration.dig_H5 = ((int16_t)((readRegister(BME280_DIG_H5_MSB_REG) << 4) + ((readRegister(BME280_DIG_H4_LSB_REG) >> 4) & 0x0F)));
calibration.dig_H6 = ((uint8_t)readRegister(BME280_DIG_H6_REG));
//Set the oversampling control words.
//config will only be writeable in sleep mode, so first insure that.
writeRegister(BME280_CTRL_MEAS_REG, 0x00);
//Set the config word
dataToWrite = (settings.tStandby << 0x5) & 0xE0;
dataToWrite |= (settings.filter << 0x02) & 0x1C;
writeRegister(BME280_CONFIG_REG, dataToWrite);
//Set ctrl_hum first, then ctrl_meas to activate ctrl_hum
dataToWrite = settings.humidOverSample & 0x07; //all other bits can be ignored
writeRegister(BME280_CTRL_HUMIDITY_REG, dataToWrite);
//set ctrl_meas
//First, set temp oversampling
dataToWrite = (settings.tempOverSample << 0x5) & 0xE0;
//Next, pressure oversampling
dataToWrite |= (settings.pressOverSample << 0x02) & 0x1C;
//Last, set mode
dataToWrite |= (settings.runMode) & 0x03;
//Load the byte
writeRegister(BME280_CTRL_MEAS_REG, dataToWrite);
return readRegister(0xD0);
}
//Strictly resets. Run .begin() afterwards
void BME280::reset( void )
{
writeRegister(BME280_RST_REG, 0xB6);
}
//****************************************************************************//
//
// Pressure Section
//
//****************************************************************************//
float BME280::readFloatPressure( void )
{
// Returns pressure in Pa as unsigned 32 bit integer in Q24.8 format (24 integer bits and 8 fractional bits).
// Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa
uint8_t buffer[3];
readRegisterRegion(buffer, BME280_PRESSURE_MSB_REG, 3);
int32_t adc_P = ((uint32_t)buffer[0] << 12) | ((uint32_t)buffer[1] << 4) | ((buffer[2] >> 4) & 0x0F);
int64_t var1, var2, p_acc;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)calibration.dig_P6;
var2 = var2 + ((var1 * (int64_t)calibration.dig_P5)<<17);
var2 = var2 + (((int64_t)calibration.dig_P4)<<35);
var1 = ((var1 * var1 * (int64_t)calibration.dig_P3)>>8) + ((var1 * (int64_t)calibration.dig_P2)<<12);
var1 = (((((int64_t)1)<<47)+var1))*((int64_t)calibration.dig_P1)>>33;
if (var1 == 0)
{
return 0; // avoid exception caused by division by zero
}
p_acc = 1048576 - adc_P;
p_acc = (((p_acc<<31) - var2)*3125)/var1;
var1 = (((int64_t)calibration.dig_P9) * (p_acc>>13) * (p_acc>>13)) >> 25;
var2 = (((int64_t)calibration.dig_P8) * p_acc) >> 19;
p_acc = ((p_acc + var1 + var2) >> 8) + (((int64_t)calibration.dig_P7)<<4);
return (float)p_acc / 256.0;
}
float BME280::readFloatAltitudeMeters( void )
{
float heightOutput = 0;
heightOutput = ((float)-45846.2)*(pow(((float)readFloatPressure()/(float)101325), 0.190263) - (float)1);
return heightOutput;
}
float BME280::readFloatAltitudeFeet( void )
{
float heightOutput = 0;
heightOutput = readFloatAltitudeMeters() * 3.28084;
return heightOutput;
}
//****************************************************************************//
//
// Humidity Section
//
//****************************************************************************//
float BME280::readFloatHumidity( void )
{
// Returns humidity in %RH as unsigned 32 bit integer in Q22. 10 format (22 integer and 10 fractional bits).
// Output value of “47445” represents 47445/1024 = 46. 333 %RH
uint8_t buffer[2];
readRegisterRegion(buffer, BME280_HUMIDITY_MSB_REG, 2);
int32_t adc_H = ((uint32_t)buffer[0] << 8) | ((uint32_t)buffer[1]);
int32_t var1;
var1 = (t_fine - ((int32_t)76800));
var1 = (((((adc_H << 14) - (((int32_t)calibration.dig_H4) << 20) - (((int32_t)calibration.dig_H5) * var1)) +
((int32_t)16384)) >> 15) * (((((((var1 * ((int32_t)calibration.dig_H6)) >> 10) * (((var1 * ((int32_t)calibration.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) + ((int32_t)2097152)) *
((int32_t)calibration.dig_H2) + 8192) >> 14));
var1 = (var1 - (((((var1 >> 15) * (var1 >> 15)) >> 7) * ((int32_t)calibration.dig_H1)) >> 4));
var1 = (var1 < 0 ? 0 : var1);
var1 = (var1 > 419430400 ? 419430400 : var1);
return (float)(var1>>12) / 1024.0;
}
//****************************************************************************//
//
// Temperature Section
//
//****************************************************************************//
float BME280::readTempC( void )
{
// Returns temperature in DegC, resolution is 0.01 DegC. Output value of “5123” equals 51.23 DegC.
// t_fine carries fine temperature as global value
//get the reading (adc_T);
uint8_t buffer[3];
readRegisterRegion(buffer, BME280_TEMPERATURE_MSB_REG, 3);
int32_t adc_T = ((uint32_t)buffer[0] << 12) | ((uint32_t)buffer[1] << 4) | ((buffer[2] >> 4) & 0x0F);
//By datasheet, calibrate
int64_t var1, var2;
var1 = ((((adc_T>>3) - ((int32_t)calibration.dig_T1<<1))) * ((int32_t)calibration.dig_T2)) >> 11;
var2 = (((((adc_T>>4) - ((int32_t)calibration.dig_T1)) * ((adc_T>>4) - ((int32_t)calibration.dig_T1))) >> 12) *
((int32_t)calibration.dig_T3)) >> 14;
t_fine = var1 + var2;
float output = (t_fine * 5 + 128) >> 8;
output = output / 100;
return output;
}
float BME280::readTempF( void )
{
float output = readTempC();
output = (output * 9) / 5 + 32;
return output;
}
//****************************************************************************//
//
// Utility
//
//****************************************************************************//
void BME280::readRegisterRegion(uint8_t *outputPointer , uint8_t offset, uint8_t length)
{
//define pointer that will point to the external space
uint8_t i = 0;
char c = 0;
switch (settings.commInterface)
{
case I2C_MODE:
Wire.beginTransmission(settings.I2CAddress);
Wire.write(offset);
Wire.endTransmission();
// request bytes from slave device
Wire.requestFrom(settings.I2CAddress, length);
while ( (Wire.available()) && (i < length)) // slave may send less than requested
{
c = Wire.read(); // receive a byte as character
*outputPointer = c;
outputPointer++;
i++;
}
break;
case SPI_MODE:
// take the chip select low to select the device:
digitalWrite(settings.chipSelectPin, LOW);
// send the device the register you want to read:
SPI.transfer(offset | 0x80); //Ored with "read request" bit
while ( i < length ) // slave may send less than requested
{
c = SPI.transfer(0x00); // receive a byte as character
*outputPointer = c;
outputPointer++;
i++;
}
// take the chip select high to de-select:
digitalWrite(settings.chipSelectPin, HIGH);
break;
default:
break;
}
}
uint8_t BME280::readRegister(uint8_t offset)
{
//Return value
uint8_t result;
uint8_t numBytes = 1;
switch (settings.commInterface) {
case I2C_MODE:
Wire.beginTransmission(settings.I2CAddress);
Wire.write(offset);
Wire.endTransmission();
Wire.requestFrom(settings.I2CAddress, numBytes);
while ( Wire.available() ) // slave may send less than requested
{
result = Wire.read(); // receive a byte as a proper uint8_t
}
break;
case SPI_MODE:
// take the chip select low to select the device:
digitalWrite(settings.chipSelectPin, LOW);
// send the device the register you want to read:
SPI.transfer(offset | 0x80); //Ored with "read request" bit
// send a value of 0 to read the first byte returned:
result = SPI.transfer(0x00);
// take the chip select high to de-select:
digitalWrite(settings.chipSelectPin, HIGH);
break;
default:
break;
}
return result;
}
int16_t BME280::readRegisterInt16( uint8_t offset )
{
uint8_t myBuffer[2];
readRegisterRegion(myBuffer, offset, 2); //Does memory transfer
int16_t output = (int16_t)myBuffer[0] | int16_t(myBuffer[1] << 8);
return output;
}
void BME280::writeRegister(uint8_t offset, uint8_t dataToWrite)
{
switch (settings.commInterface)
{
case I2C_MODE:
//Write the byte
Wire.beginTransmission(settings.I2CAddress);
Wire.write(offset);
Wire.write(dataToWrite);
Wire.endTransmission();
break;
case SPI_MODE:
// take the chip select low to select the device:
digitalWrite(settings.chipSelectPin, LOW);
// send the device the register you want to read:
SPI.transfer(offset & 0x7F);
// send a value of 0 to read the first byte returned:
SPI.transfer(dataToWrite);
// decrement the number of bytes left to read:
// take the chip select high to de-select:
digitalWrite(settings.chipSelectPin, HIGH);
break;
default:
break;
}
}
|
////////////////////////////////////////////////////////////////////////////
// Module : ai_stalker_misc.cpp
// Created : 27.02.2003
// Modified : 27.02.2003
// Author : Dmitriy Iassenev
// Description : Miscellaneous functions for monster "Stalker"
////////////////////////////////////////////////////////////////////////////
#include "pch_script.h"
#include "ai_stalker.h"
#include "ai_stalker_space.h"
#include "../../bolt.h"
#include "../../inventory.h"
#include "../../character_info.h"
#include "../../relation_registry.h"
#include "../../memory_manager.h"
#include "../../item_manager.h"
#include "../../stalker_movement_manager.h"
#include "../../explosive.h"
#include "../../agent_manager.h"
#include "../../agent_member_manager.h"
#include "../../agent_explosive_manager.h"
#include "../../agent_location_manager.h"
#include "../../danger_object_location.h"
#include "../../member_order.h"
#include "../../level.h"
#include "../../sound_player.h"
#include "../../enemy_manager.h"
#include "../../danger_manager.h"
#include "../../visual_memory_manager.h"
#include "../../agent_enemy_manager.h"
const u32 TOLLS_INTERVAL = 2000;
const u32 GRENADE_INTERVAL = 0*1000;
const float FRIENDLY_GRENADE_ALARM_DIST = 5.f;
const u32 DANGER_INFINITE_INTERVAL = 60000000;
const float DANGER_EXPLOSIVE_DISTANCE = 10.f;
bool CAI_Stalker::useful (const CItemManager *manager, const CGameObject *object) const
{
const CExplosive *explosive = smart_cast<const CExplosive*>(object);
if (explosive && smart_cast<const CInventoryItem*>(object))
agent_manager().location().add (xr_new<CDangerObjectLocation>(object,Device.dwTimeGlobal,DANGER_INFINITE_INTERVAL,DANGER_EXPLOSIVE_DISTANCE));
if (explosive && (explosive->CurrentParentID() != 0xffff)) {
agent_manager().explosive().register_explosive(explosive,object);
CEntityAlive *entity_alive = smart_cast<CEntityAlive*>(Level().Objects.net_Find(explosive->CurrentParentID()));
if (entity_alive)
memory().danger().add(CDangerObject(entity_alive,object->Position(),Device.dwTimeGlobal,CDangerObject::eDangerTypeGrenade,CDangerObject::eDangerPerceiveTypeVisual,object));
}
if (!memory().item().useful(object))
return (false);
const CInventoryItem *inventory_item = smart_cast<const CInventoryItem*>(object);
if (!inventory_item || !inventory_item->useful_for_NPC())
return (false);
if (!const_cast<CAI_Stalker*>(this)->can_take(inventory_item))
return (false);
const CBolt *bolt = smart_cast<const CBolt*>(object);
if (bolt)
return (false);
CInventory *inventory_non_const = const_cast<CInventory*>(&inventory());
CInventoryItem *inventory_item_non_const = const_cast<CInventoryItem*>(inventory_item);
if (!inventory_non_const->CanTakeItem(inventory_item_non_const))
return (false);
return (true);
}
float CAI_Stalker::evaluate (const CItemManager *manager, const CGameObject *object) const
{
float distance = Position().distance_to_sqr(object->Position());
distance = !fis_zero(distance) ? distance : EPS_L;
return (distance);
}
bool CAI_Stalker::useful (const CEnemyManager *manager, const CEntityAlive *object) const
{
if (!agent_manager().enemy().useful_enemy(object,this))
return (false);
return (memory().enemy().useful(object));
}
ALife::ERelationType CAI_Stalker::tfGetRelationType (const CEntityAlive *tpEntityAlive) const
{
const CInventoryOwner* pOtherIO = smart_cast<const CInventoryOwner*>(tpEntityAlive);
ALife::ERelationType relation = ALife::eRelationTypeDummy;
if(pOtherIO && !(const_cast<CEntityAlive*>(tpEntityAlive)->cast_base_monster()))
relation = RELATION_REGISTRY().GetRelationType(static_cast<const CInventoryOwner*>(this), pOtherIO);
if(ALife::eRelationTypeDummy != relation)
return relation;
else
return inherited::tfGetRelationType(tpEntityAlive);
}
void CAI_Stalker::react_on_grenades ()
{
CMemberOrder::CGrenadeReaction &reaction = agent_manager().member().member(this).grenade_reaction();
if (!reaction.m_processing)
return;
if (Device.dwTimeGlobal < reaction.m_time + GRENADE_INTERVAL)
return;
// u32 interval = AFTER_GRENADE_DESTROYED_INTERVAL;
const CMissile *missile = smart_cast<const CMissile*>(reaction.m_grenade);
// if (missile && (missile->destroy_time() > Device.dwTimeGlobal))
// interval = missile->destroy_time() - Device.dwTimeGlobal + AFTER_GRENADE_DESTROYED_INTERVAL;
// m_object->agent_manager().add_danger_location(reaction.m_game_object->Position(),Device.dwTimeGlobal,interval,GRENADE_RADIUS);
if (missile && agent_manager().member().group_behaviour()) {
// Msg ("%6d : Stalker %s : grenade reaction",Device.dwTimeGlobal,*m_object->cName());
CEntityAlive *initiator = smart_cast<CEntityAlive*>(Level().Objects.net_Find(reaction.m_grenade->CurrentParentID()));
if (is_relation_enemy(initiator))
sound().play (StalkerSpace::eStalkerSoundGrenadeAlarm);
else
if (missile->Position().distance_to(Position()) < FRIENDLY_GRENADE_ALARM_DIST)
sound().play (StalkerSpace::eStalkerSoundFriendlyGrenadeAlarm);
}
reaction.clear ();
}
void CAI_Stalker::react_on_member_death ()
{
CMemberOrder::CMemberDeathReaction &reaction = agent_manager().member().member(this).member_death_reaction();
if (!reaction.m_processing)
return;
if (Device.dwTimeGlobal < reaction.m_time + TOLLS_INTERVAL)
return;
if (agent_manager().member().group_behaviour())
sound().play (StalkerSpace::eStalkerSoundTolls);
reaction.clear ();
}
void CAI_Stalker::process_enemies ()
{
if (memory().enemy().selected())
return;
typedef MemorySpace::squad_mask_type squad_mask_type;
typedef CVisualMemoryManager::VISIBLES VISIBLES;
bool found = false;
squad_mask_type mask = memory().visual().mask();
VISIBLES::const_iterator I = memory().visual().objects().begin();
VISIBLES::const_iterator E = memory().visual().objects().end();
for ( ; I != E; ++I) {
if (!(*I).visible(mask))
continue;
const CAI_Stalker *member = smart_cast<const CAI_Stalker*>((*I).m_object);
if (!member)
continue;
if (is_relation_enemy(member))
continue;
if (!member->g_Alive())
continue;
if (!member->memory().enemy().selected()) {
if (!memory().danger().selected() && member->memory().danger().selected())
memory().danger().add(*member->memory().danger().selected());
continue;
}
memory().make_object_visible_somewhen (member->memory().enemy().selected());
found = true;
break;
}
}
|
#include "umlReflectionExec/OpaqueActionObject.hpp"
//General Includes
#include "abstractDataTypes/SubsetUnion.hpp"
#include "uml/OpaqueAction.hpp"
#include "umlReflection/UMLPackage.hpp"
#include "fUML/Semantics/Loci/Locus.hpp"
#include "uml/Class.hpp"
//Includes From Composite Structures
/*Not done for metamodel object classes*/
//Execution Engine Includes
#include "abstractDataTypes/Any.hpp"
#include "PSCS/Semantics/StructuredClassifiers/StructuredClassifiersFactory.hpp"
#include "PSCS/Semantics/StructuredClassifiers/CS_Reference.hpp"
#include "fUML/Semantics/SimpleClassifiers/SimpleClassifiersFactory.hpp"
#include "fUML/Semantics/Values/Value.hpp"
#include "fUML/Semantics/SimpleClassifiers/FeatureValue.hpp"
#include "PSCS/Semantics/StructuredClassifiers/CS_Link.hpp"
#include "PSCS/Semantics/StructuredClassifiers/CS_InteractionPoint.hpp"
#include "fUML/Semantics/CommonBehavior/Execution.hpp"
#include "fUML/Semantics/CommonBehavior/CommonBehaviorFactory.hpp"
#include "fUML/Semantics/Loci/ExecutionFactory.hpp"
#include "fUML/Semantics/Loci/ChoiceStrategy.hpp"
//UML Includes
#include "uml/umlPackage.hpp"
#include "uml/Association.hpp"
#include "uml/Connector.hpp"
#include "uml/ConnectorEnd.hpp"
#include "uml/Operation.hpp"
#include "uml/Property.hpp"
#include "uml/Port.hpp"
//Property Includes
#include "uml/Classifier.hpp"
#include "umlReflectionExec/ClassifierObject.hpp"
#include "uml/InputPin.hpp"
#include "umlReflectionExec/InputPinObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/BooleanValue.hpp"
#include "uml/Constraint.hpp"
#include "umlReflectionExec/ConstraintObject.hpp"
#include "uml/Constraint.hpp"
#include "umlReflectionExec/ConstraintObject.hpp"
#include "uml/OutputPin.hpp"
#include "umlReflectionExec/OutputPinObject.hpp"
#include "uml/Activity.hpp"
#include "umlReflectionExec/ActivityObject.hpp"
#include "uml/ActivityGroup.hpp"
#include "umlReflectionExec/ActivityGroupObject.hpp"
#include "uml/InterruptibleActivityRegion.hpp"
#include "umlReflectionExec/InterruptibleActivityRegionObject.hpp"
#include "uml/ActivityPartition.hpp"
#include "umlReflectionExec/ActivityPartitionObject.hpp"
#include "uml/StructuredActivityNode.hpp"
#include "umlReflectionExec/StructuredActivityNodeObject.hpp"
#include "uml/ActivityEdge.hpp"
#include "umlReflectionExec/ActivityEdgeObject.hpp"
#include "uml/ActivityEdge.hpp"
#include "umlReflectionExec/ActivityEdgeObject.hpp"
#include "uml/ActivityNode.hpp"
#include "umlReflectionExec/ActivityNodeObject.hpp"
#include "uml/Comment.hpp"
#include "umlReflectionExec/CommentObject.hpp"
#include "uml/Element.hpp"
#include "umlReflectionExec/ElementObject.hpp"
#include "uml/Element.hpp"
#include "umlReflectionExec/ElementObject.hpp"
#include "uml/ExceptionHandler.hpp"
#include "umlReflectionExec/ExceptionHandlerObject.hpp"
#include "uml/Dependency.hpp"
#include "umlReflectionExec/DependencyObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/StringValue.hpp"
#include "uml/StringExpression.hpp"
#include "umlReflectionExec/StringExpressionObject.hpp"
#include "uml/Namespace.hpp"
#include "umlReflectionExec/NamespaceObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/StringValue.hpp"
#include "fUML/Semantics/SimpleClassifiers/EnumerationValue.hpp"
#include "uml/VisibilityKind.hpp"
#include "fUML/Semantics/SimpleClassifiers/StringValue.hpp"
#include "uml/InputPin.hpp"
#include "umlReflectionExec/InputPinObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/StringValue.hpp"
#include "uml/OutputPin.hpp"
#include "umlReflectionExec/OutputPinObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/BooleanValue.hpp"
#include "uml/RedefinableElement.hpp"
#include "umlReflectionExec/RedefinableElementObject.hpp"
#include "uml/Classifier.hpp"
#include "umlReflectionExec/ClassifierObject.hpp"
//Property Packages Includes
#include "primitivetypesReflection/PrimitiveTypesPackage.hpp"
using namespace UML;
OpaqueActionObject::OpaqueActionObject(std::shared_ptr<uml::OpaqueAction> _element):
m_OpaqueActionValue(_element)
{
this->getTypes()->insert(this->getTypes()->begin(), UML::UMLPackage::eInstance()->get_UML_OpaqueAction());
}
OpaqueActionObject::OpaqueActionObject(OpaqueActionObject &obj):
CS_ObjectImpl(obj)
{
}
OpaqueActionObject::OpaqueActionObject()
{
this->getTypes()->insert(this->getTypes()->begin(), UML::UMLPackage::eInstance()->get_UML_OpaqueAction());
}
OpaqueActionObject::~OpaqueActionObject()
{
}
std::shared_ptr<ecore::EObject> OpaqueActionObject::copy()
{
std::shared_ptr<OpaqueActionObject> element(new OpaqueActionObject(*this));
element->setThisOpaqueActionObjectPtr(element);
return element;
}
void OpaqueActionObject::destroy()
{
m_OpaqueActionValue.reset();
fUML::Semantics::StructuredClassifiers::ObjectImpl::destroy();
}
std::shared_ptr<uml::Element> OpaqueActionObject::getUmlValue() const
{
return getOpaqueActionValue();
}
std::shared_ptr<uml::OpaqueAction> OpaqueActionObject::getOpaqueActionValue() const
{
return m_OpaqueActionValue;
}
void OpaqueActionObject::setUmlValue(std::shared_ptr<uml::Element> _element)
{
setOpaqueActionValue(std::dynamic_pointer_cast<uml::OpaqueAction>(_element));
}
void OpaqueActionObject::setOpaqueActionValue(std::shared_ptr<uml::OpaqueAction> _OpaqueActionElement)
{
m_OpaqueActionValue = _OpaqueActionElement;
//set super type values
UML::ActionObject::setActionValue(_OpaqueActionElement);
}
void OpaqueActionObject::setThisOpaqueActionObjectPtr(std::weak_ptr<OpaqueActionObject> thisObjectPtr)
{
setThisCS_ObjectPtr(thisObjectPtr);
}
bool OpaqueActionObject::equals(std::shared_ptr<fUML::Semantics::Values::Value> otherValue)
{
bool isEqual = false;
std::shared_ptr<OpaqueActionObject> otherOpaqueActionObject = std::dynamic_pointer_cast<OpaqueActionObject>(otherValue);
if(otherOpaqueActionObject != nullptr)
{
if(this->getOpaqueActionValue() == otherOpaqueActionObject->getOpaqueActionValue())
{
isEqual = true;
}
}
return isEqual;
}
std::string OpaqueActionObject::toString()
{
std::string buffer = "Instance of 'OpaqueActionObject', " + std::to_string(getTypes()->size()) + " types (";
for(unsigned int i = 0; i < getTypes()->size(); ++i)
{
buffer += "type{" + std::to_string(i) + "}: '" + getTypes()->at(i)->getName() + "', ";
}
buffer +=")";
return buffer;
}
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Object>> OpaqueActionObject::getDirectContainers()
{
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Object>> directContainers(new Bag<PSCS::Semantics::StructuredClassifiers::CS_Object>());
/*Not done for metamodel object classes*/
return directContainers;
}
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Link>> OpaqueActionObject::getLinks(std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_InteractionPoint> interactionPoint)
{
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Link>> allLinks(new Bag<PSCS::Semantics::StructuredClassifiers::CS_Link>());
/*Not done for metamodel object classes*/
return allLinks;
}
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> OpaqueActionObject::retrieveEndValueAsInteractionPoint(std::shared_ptr<fUML::Semantics::Values::Value> endValue, std::shared_ptr<uml::ConnectorEnd> end)
{
/*Not done for metamodel object classes*/
return nullptr;
}
void OpaqueActionObject::removeValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<fUML::Semantics::Values::Value> value)
{
if (feature->getMetaElementID() != uml::umlPackage::PROPERTY_CLASS && feature->getMetaElementID() != uml::umlPackage::PORT_CLASS && feature->getMetaElementID() != uml::umlPackage::EXTENSIONEND_CLASS)
{
std::cerr << __PRETTY_FUNCTION__ << ": feature is null or not kind of uml::Property" << std::endl;
throw "feature is null or not kind of uml::Property";
}
if (m_OpaqueActionValue == nullptr)
{
std::cerr << __PRETTY_FUNCTION__ << ": no value stored inside OpaqueActionObject (property: " << feature->getName() << ")" << std::endl;
throw "NullPointerException";
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_isLocallyReentrant())
{
m_OpaqueActionValue->setIsLocallyReentrant(false /*defined default value*/);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_localPostcondition())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getLocalPostcondition()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::ConstraintObject> inputValue = std::dynamic_pointer_cast<UML::ConstraintObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getLocalPostcondition()->erase(inputValue->getConstraintValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_localPrecondition())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getLocalPrecondition()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::ConstraintObject> inputValue = std::dynamic_pointer_cast<UML::ConstraintObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getLocalPrecondition()->erase(inputValue->getConstraintValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_activity())
{
m_OpaqueActionValue->getActivity().reset();
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inInterruptibleRegion())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getInInterruptibleRegion()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::InterruptibleActivityRegionObject> inputValue = std::dynamic_pointer_cast<UML::InterruptibleActivityRegionObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getInInterruptibleRegion()->erase(inputValue->getInterruptibleActivityRegionValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inPartition())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getInPartition()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::ActivityPartitionObject> inputValue = std::dynamic_pointer_cast<UML::ActivityPartitionObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getInPartition()->erase(inputValue->getActivityPartitionValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inStructuredNode())
{
m_OpaqueActionValue->getInStructuredNode().reset();
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_incoming())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getIncoming()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::ActivityEdgeObject> inputValue = std::dynamic_pointer_cast<UML::ActivityEdgeObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getIncoming()->erase(inputValue->getActivityEdgeValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_outgoing())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getOutgoing()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::ActivityEdgeObject> inputValue = std::dynamic_pointer_cast<UML::ActivityEdgeObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getOutgoing()->erase(inputValue->getActivityEdgeValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_redefinedNode())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getRedefinedNode()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::ActivityNodeObject> inputValue = std::dynamic_pointer_cast<UML::ActivityNodeObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getRedefinedNode()->erase(inputValue->getActivityNodeValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getOwnedComment()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::CommentObject> inputValue = std::dynamic_pointer_cast<UML::CommentObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getOwnedComment()->erase(inputValue->getCommentValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ExecutableNode_handler())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getHandler()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::ExceptionHandlerObject> inputValue = std::dynamic_pointer_cast<UML::ExceptionHandlerObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getHandler()->erase(inputValue->getExceptionHandlerValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_name())
{
// no default value defined, clear not realized
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression())
{
m_OpaqueActionValue->getNameExpression().reset();
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_visibility())
{
// no default value defined, clear not realized
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_body())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getBody()->clear();
}
else
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> inputValue = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::StringValue>(value);
if (inputValue != nullptr)
{
std::string specificValue = inputValue->getValue();
std::shared_ptr<Bag<std::string>> valueList = m_OpaqueActionValue->getBody();
Bag<std::string>::iterator iter = valueList->begin();
Bag<std::string>::iterator end = valueList->end();
while (iter != end)
{
if (specificValue == *(*iter))
{
valueList->erase(iter);
break;
}
iter++;
}
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_inputValue())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getInputValue()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::InputPinObject> inputValue = std::dynamic_pointer_cast<UML::InputPinObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getInputValue()->erase(inputValue->getInputPinValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_language())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getLanguage()->clear();
}
else
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> inputValue = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::StringValue>(value);
if (inputValue != nullptr)
{
std::string specificValue = inputValue->getValue();
std::shared_ptr<Bag<std::string>> valueList = m_OpaqueActionValue->getLanguage();
Bag<std::string>::iterator iter = valueList->begin();
Bag<std::string>::iterator end = valueList->end();
while (iter != end)
{
if (specificValue == *(*iter))
{
valueList->erase(iter);
break;
}
iter++;
}
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_outputValue())
{
if (value == nullptr) // clear mode
{
m_OpaqueActionValue->getOutputValue()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::OutputPinObject> inputValue = std::dynamic_pointer_cast<UML::OutputPinObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_OpaqueActionValue->getOutputValue()->erase(inputValue->getOutputPinValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_RedefinableElement_isLeaf())
{
m_OpaqueActionValue->setIsLeaf(false /*defined default value*/);
}
}
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> OpaqueActionObject::getValues(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> featureValues)
{
if (feature->getMetaElementID() != uml::umlPackage::PROPERTY_CLASS && feature->getMetaElementID() != uml::umlPackage::PORT_CLASS && feature->getMetaElementID() != uml::umlPackage::EXTENSIONEND_CLASS)
{
std::cerr << __PRETTY_FUNCTION__ << ": feature is null or not kind of uml::Property" << std::endl;
throw "feature is null or not kind of uml::Property";
}
if (m_OpaqueActionValue == nullptr)
{
std::cerr << __PRETTY_FUNCTION__ << ": no value stored inside OpaqueActionObject (property: " << feature->getName() << ")" << std::endl;
throw "NullPointerException";
}
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values(new Bag<fUML::Semantics::Values::Value>());
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_context())
{
std::shared_ptr<UML::ClassifierObject> value(new UML::ClassifierObject());
value->setThisClassifierObjectPtr(value);
value->setLocus(this->getLocus());
value->setClassifierValue(m_OpaqueActionValue->getContext());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_input())
{
std::shared_ptr<Bag<uml::InputPin>> inputList = m_OpaqueActionValue->getInput();
Bag<uml::InputPin>::iterator iter = inputList->begin();
Bag<uml::InputPin>::iterator end = inputList->end();
while (iter != end)
{
std::shared_ptr<UML::InputPinObject> value(new UML::InputPinObject());
value->setThisInputPinObjectPtr(value);
value->setLocus(this->getLocus());
value->setInputPinValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_isLocallyReentrant())
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::BooleanValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createBooleanValue();
value->setValue(m_OpaqueActionValue->getIsLocallyReentrant());
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_localPostcondition())
{
std::shared_ptr<Bag<uml::Constraint>> localPostconditionList = m_OpaqueActionValue->getLocalPostcondition();
Bag<uml::Constraint>::iterator iter = localPostconditionList->begin();
Bag<uml::Constraint>::iterator end = localPostconditionList->end();
while (iter != end)
{
std::shared_ptr<UML::ConstraintObject> value(new UML::ConstraintObject());
value->setThisConstraintObjectPtr(value);
value->setLocus(this->getLocus());
value->setConstraintValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_localPrecondition())
{
std::shared_ptr<Bag<uml::Constraint>> localPreconditionList = m_OpaqueActionValue->getLocalPrecondition();
Bag<uml::Constraint>::iterator iter = localPreconditionList->begin();
Bag<uml::Constraint>::iterator end = localPreconditionList->end();
while (iter != end)
{
std::shared_ptr<UML::ConstraintObject> value(new UML::ConstraintObject());
value->setThisConstraintObjectPtr(value);
value->setLocus(this->getLocus());
value->setConstraintValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_output())
{
std::shared_ptr<Bag<uml::OutputPin>> outputList = m_OpaqueActionValue->getOutput();
Bag<uml::OutputPin>::iterator iter = outputList->begin();
Bag<uml::OutputPin>::iterator end = outputList->end();
while (iter != end)
{
std::shared_ptr<UML::OutputPinObject> value(new UML::OutputPinObject());
value->setThisOutputPinObjectPtr(value);
value->setLocus(this->getLocus());
value->setOutputPinValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_activity())
{
std::shared_ptr<UML::ActivityObject> value(new UML::ActivityObject());
value->setThisActivityObjectPtr(value);
value->setLocus(this->getLocus());
value->setActivityValue(m_OpaqueActionValue->getActivity().lock());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inGroup())
{
std::shared_ptr<Bag<uml::ActivityGroup>> inGroupList = m_OpaqueActionValue->getInGroup();
Bag<uml::ActivityGroup>::iterator iter = inGroupList->begin();
Bag<uml::ActivityGroup>::iterator end = inGroupList->end();
while (iter != end)
{
std::shared_ptr<UML::ActivityGroupObject> value(new UML::ActivityGroupObject());
value->setThisActivityGroupObjectPtr(value);
value->setLocus(this->getLocus());
value->setActivityGroupValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inInterruptibleRegion())
{
std::shared_ptr<Bag<uml::InterruptibleActivityRegion>> inInterruptibleRegionList = m_OpaqueActionValue->getInInterruptibleRegion();
Bag<uml::InterruptibleActivityRegion>::iterator iter = inInterruptibleRegionList->begin();
Bag<uml::InterruptibleActivityRegion>::iterator end = inInterruptibleRegionList->end();
while (iter != end)
{
std::shared_ptr<UML::InterruptibleActivityRegionObject> value(new UML::InterruptibleActivityRegionObject());
value->setThisInterruptibleActivityRegionObjectPtr(value);
value->setLocus(this->getLocus());
value->setInterruptibleActivityRegionValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inPartition())
{
std::shared_ptr<Bag<uml::ActivityPartition>> inPartitionList = m_OpaqueActionValue->getInPartition();
Bag<uml::ActivityPartition>::iterator iter = inPartitionList->begin();
Bag<uml::ActivityPartition>::iterator end = inPartitionList->end();
while (iter != end)
{
std::shared_ptr<UML::ActivityPartitionObject> value(new UML::ActivityPartitionObject());
value->setThisActivityPartitionObjectPtr(value);
value->setLocus(this->getLocus());
value->setActivityPartitionValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inStructuredNode())
{
std::shared_ptr<UML::StructuredActivityNodeObject> value(new UML::StructuredActivityNodeObject());
value->setThisStructuredActivityNodeObjectPtr(value);
value->setLocus(this->getLocus());
value->setStructuredActivityNodeValue(m_OpaqueActionValue->getInStructuredNode().lock());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_incoming())
{
std::shared_ptr<Bag<uml::ActivityEdge>> incomingList = m_OpaqueActionValue->getIncoming();
Bag<uml::ActivityEdge>::iterator iter = incomingList->begin();
Bag<uml::ActivityEdge>::iterator end = incomingList->end();
while (iter != end)
{
std::shared_ptr<UML::ActivityEdgeObject> value(new UML::ActivityEdgeObject());
value->setThisActivityEdgeObjectPtr(value);
value->setLocus(this->getLocus());
value->setActivityEdgeValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_outgoing())
{
std::shared_ptr<Bag<uml::ActivityEdge>> outgoingList = m_OpaqueActionValue->getOutgoing();
Bag<uml::ActivityEdge>::iterator iter = outgoingList->begin();
Bag<uml::ActivityEdge>::iterator end = outgoingList->end();
while (iter != end)
{
std::shared_ptr<UML::ActivityEdgeObject> value(new UML::ActivityEdgeObject());
value->setThisActivityEdgeObjectPtr(value);
value->setLocus(this->getLocus());
value->setActivityEdgeValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_redefinedNode())
{
std::shared_ptr<Bag<uml::ActivityNode>> redefinedNodeList = m_OpaqueActionValue->getRedefinedNode();
Bag<uml::ActivityNode>::iterator iter = redefinedNodeList->begin();
Bag<uml::ActivityNode>::iterator end = redefinedNodeList->end();
while (iter != end)
{
std::shared_ptr<UML::ActivityNodeObject> value(new UML::ActivityNodeObject());
value->setThisActivityNodeObjectPtr(value);
value->setLocus(this->getLocus());
value->setActivityNodeValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment())
{
std::shared_ptr<Bag<uml::Comment>> ownedCommentList = m_OpaqueActionValue->getOwnedComment();
Bag<uml::Comment>::iterator iter = ownedCommentList->begin();
Bag<uml::Comment>::iterator end = ownedCommentList->end();
while (iter != end)
{
std::shared_ptr<UML::CommentObject> value(new UML::CommentObject());
value->setThisCommentObjectPtr(value);
value->setLocus(this->getLocus());
value->setCommentValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedElement())
{
std::shared_ptr<Bag<uml::Element>> ownedElementList = m_OpaqueActionValue->getOwnedElement();
Bag<uml::Element>::iterator iter = ownedElementList->begin();
Bag<uml::Element>::iterator end = ownedElementList->end();
while (iter != end)
{
std::shared_ptr<UML::ElementObject> value(new UML::ElementObject());
value->setThisElementObjectPtr(value);
value->setLocus(this->getLocus());
value->setElementValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_owner())
{
std::shared_ptr<UML::ElementObject> value(new UML::ElementObject());
value->setThisElementObjectPtr(value);
value->setLocus(this->getLocus());
value->setElementValue(m_OpaqueActionValue->getOwner().lock());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ExecutableNode_handler())
{
std::shared_ptr<Bag<uml::ExceptionHandler>> handlerList = m_OpaqueActionValue->getHandler();
Bag<uml::ExceptionHandler>::iterator iter = handlerList->begin();
Bag<uml::ExceptionHandler>::iterator end = handlerList->end();
while (iter != end)
{
std::shared_ptr<UML::ExceptionHandlerObject> value(new UML::ExceptionHandlerObject());
value->setThisExceptionHandlerObjectPtr(value);
value->setLocus(this->getLocus());
value->setExceptionHandlerValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_clientDependency())
{
std::shared_ptr<Bag<uml::Dependency>> clientDependencyList = m_OpaqueActionValue->getClientDependency();
Bag<uml::Dependency>::iterator iter = clientDependencyList->begin();
Bag<uml::Dependency>::iterator end = clientDependencyList->end();
while (iter != end)
{
std::shared_ptr<UML::DependencyObject> value(new UML::DependencyObject());
value->setThisDependencyObjectPtr(value);
value->setLocus(this->getLocus());
value->setDependencyValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_name())
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createStringValue();
value->setValue(m_OpaqueActionValue->getName());
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression())
{
std::shared_ptr<UML::StringExpressionObject> value(new UML::StringExpressionObject());
value->setThisStringExpressionObjectPtr(value);
value->setLocus(this->getLocus());
value->setStringExpressionValue(m_OpaqueActionValue->getNameExpression());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_namespace())
{
std::shared_ptr<UML::NamespaceObject> value(new UML::NamespaceObject());
value->setThisNamespaceObjectPtr(value);
value->setLocus(this->getLocus());
value->setNamespaceValue(m_OpaqueActionValue->getNamespace().lock());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_qualifiedName())
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createStringValue();
value->setValue(m_OpaqueActionValue->getQualifiedName());
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_visibility())
{
uml::VisibilityKind visibility = m_OpaqueActionValue->getVisibility();
std::shared_ptr<fUML::Semantics::SimpleClassifiers::EnumerationValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createEnumerationValue();
if (visibility == uml::VisibilityKind::PUBLIC)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_public());
}
if (visibility == uml::VisibilityKind::PRIVATE)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_private());
}
if (visibility == uml::VisibilityKind::PROTECTED)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_protected());
}
if (visibility == uml::VisibilityKind::PACKAGE)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_package());
}
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_body())
{
std::shared_ptr<Bag<std::string>> valueList = m_OpaqueActionValue->getBody();
Bag<std::string>::iterator iter = valueList->begin();
Bag<std::string>::iterator end = valueList->end();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createStringValue();
value->setValue(*(*iter));
values->push_back(value);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_inputValue())
{
std::shared_ptr<Bag<uml::InputPin>> inputValueList = m_OpaqueActionValue->getInputValue();
Bag<uml::InputPin>::iterator iter = inputValueList->begin();
Bag<uml::InputPin>::iterator end = inputValueList->end();
while (iter != end)
{
std::shared_ptr<UML::InputPinObject> value(new UML::InputPinObject());
value->setThisInputPinObjectPtr(value);
value->setLocus(this->getLocus());
value->setInputPinValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_language())
{
std::shared_ptr<Bag<std::string>> valueList = m_OpaqueActionValue->getLanguage();
Bag<std::string>::iterator iter = valueList->begin();
Bag<std::string>::iterator end = valueList->end();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createStringValue();
value->setValue(*(*iter));
values->push_back(value);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_outputValue())
{
std::shared_ptr<Bag<uml::OutputPin>> outputValueList = m_OpaqueActionValue->getOutputValue();
Bag<uml::OutputPin>::iterator iter = outputValueList->begin();
Bag<uml::OutputPin>::iterator end = outputValueList->end();
while (iter != end)
{
std::shared_ptr<UML::OutputPinObject> value(new UML::OutputPinObject());
value->setThisOutputPinObjectPtr(value);
value->setLocus(this->getLocus());
value->setOutputPinValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_RedefinableElement_isLeaf())
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::BooleanValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createBooleanValue();
value->setValue(m_OpaqueActionValue->getIsLeaf());
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_RedefinableElement_redefinedElement())
{
std::shared_ptr<Bag<uml::RedefinableElement>> redefinedElementList = m_OpaqueActionValue->getRedefinedElement();
Bag<uml::RedefinableElement>::iterator iter = redefinedElementList->begin();
Bag<uml::RedefinableElement>::iterator end = redefinedElementList->end();
while (iter != end)
{
std::shared_ptr<UML::RedefinableElementObject> value(new UML::RedefinableElementObject());
value->setThisRedefinableElementObjectPtr(value);
value->setLocus(this->getLocus());
value->setRedefinableElementValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_RedefinableElement_redefinitionContext())
{
std::shared_ptr<Bag<uml::Classifier>> redefinitionContextList = m_OpaqueActionValue->getRedefinitionContext();
Bag<uml::Classifier>::iterator iter = redefinitionContextList->begin();
Bag<uml::Classifier>::iterator end = redefinitionContextList->end();
while (iter != end)
{
std::shared_ptr<UML::ClassifierObject> value(new UML::ClassifierObject());
value->setThisClassifierObjectPtr(value);
value->setLocus(this->getLocus());
value->setClassifierValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
return values;
}
std::shared_ptr<fUML::Semantics::SimpleClassifiers::FeatureValue> OpaqueActionObject::retrieveFeatureValue(std::shared_ptr<uml::StructuralFeature> feature)
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::FeatureValue> featureValue(fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createFeatureValue());
featureValue->setFeature(feature);
std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> featureValues(new Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>());
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values = this->getValues(feature, featureValues);
unsigned int valuesSize = values->size();
for(unsigned int i = 0; i < valuesSize; i++)
{
featureValue->getValues()->add(values->at(i));
}
return featureValue;
}
void OpaqueActionObject::setFeatureValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values, int position)
{
if (feature->getMetaElementID() != uml::umlPackage::PROPERTY_CLASS && feature->getMetaElementID() != uml::umlPackage::PORT_CLASS && feature->getMetaElementID() != uml::umlPackage::EXTENSIONEND_CLASS)
{
std::cerr << __PRETTY_FUNCTION__ << ": feature is null or not kind of uml::Property" << std::endl;
throw "feature is null or not kind of uml::Property";
}
if (m_OpaqueActionValue == nullptr)
{
std::cerr << __PRETTY_FUNCTION__ << ": no value stored inside OpaqueActionObject (property: " << feature->getName() << ")" << std::endl;
throw "NullPointerException";
}
if (values->size() == 0)
{
std::cout << __PRETTY_FUNCTION__ << ": no input value given" << std::endl;
return;
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_isLocallyReentrant())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::BooleanValue> valueObject = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::BooleanValue>(inputValue);
if (valueObject != nullptr)
{
m_OpaqueActionValue->setIsLocallyReentrant(valueObject->isValue());
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_localPostcondition())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getLocalPostcondition()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::ConstraintObject> value = std::dynamic_pointer_cast<UML::ConstraintObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getLocalPostcondition()->push_back(value->getConstraintValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Action_localPrecondition())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getLocalPrecondition()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::ConstraintObject> value = std::dynamic_pointer_cast<UML::ConstraintObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getLocalPrecondition()->push_back(value->getConstraintValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inInterruptibleRegion())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getInInterruptibleRegion()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::InterruptibleActivityRegionObject> value = std::dynamic_pointer_cast<UML::InterruptibleActivityRegionObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getInInterruptibleRegion()->push_back(value->getInterruptibleActivityRegionValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inPartition())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getInPartition()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::ActivityPartitionObject> value = std::dynamic_pointer_cast<UML::ActivityPartitionObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getInPartition()->push_back(value->getActivityPartitionValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_incoming())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getIncoming()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::ActivityEdgeObject> value = std::dynamic_pointer_cast<UML::ActivityEdgeObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getIncoming()->push_back(value->getActivityEdgeValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_outgoing())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getOutgoing()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::ActivityEdgeObject> value = std::dynamic_pointer_cast<UML::ActivityEdgeObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getOutgoing()->push_back(value->getActivityEdgeValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ActivityNode_redefinedNode())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getRedefinedNode()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::ActivityNodeObject> value = std::dynamic_pointer_cast<UML::ActivityNodeObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getRedefinedNode()->push_back(value->getActivityNodeValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getOwnedComment()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::CommentObject> value = std::dynamic_pointer_cast<UML::CommentObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getOwnedComment()->push_back(value->getCommentValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ExecutableNode_handler())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getHandler()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::ExceptionHandlerObject> value = std::dynamic_pointer_cast<UML::ExceptionHandlerObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getHandler()->push_back(value->getExceptionHandlerValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_name())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> valueObject = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::StringValue>(inputValue);
if (valueObject != nullptr)
{
m_OpaqueActionValue->setName(valueObject->getValue());
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::StringExpressionObject> value = std::dynamic_pointer_cast<UML::StringExpressionObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->setNameExpression(value->getStringExpressionValue());
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_visibility())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::EnumerationValue> enumValue = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::EnumerationValue>(inputValue);
std::shared_ptr<uml::EnumerationLiteral> literal = enumValue->getLiteral();
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_public())
{
m_OpaqueActionValue->setVisibility(uml::VisibilityKind::PUBLIC);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_private())
{
m_OpaqueActionValue->setVisibility(uml::VisibilityKind::PRIVATE);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_protected())
{
m_OpaqueActionValue->setVisibility(uml::VisibilityKind::PROTECTED);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_package())
{
m_OpaqueActionValue->setVisibility(uml::VisibilityKind::PACKAGE);
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_body())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getBody()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> valueObject = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::StringValue>(inputValue);
if (valueObject != nullptr)
{
std::shared_ptr<std::string> value(new std::string(valueObject->getValue()));
m_OpaqueActionValue->getBody()->push_back(value);
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_inputValue())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getInputValue()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::InputPinObject> value = std::dynamic_pointer_cast<UML::InputPinObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getInputValue()->push_back(value->getInputPinValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_language())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getLanguage()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> valueObject = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::StringValue>(inputValue);
if (valueObject != nullptr)
{
std::shared_ptr<std::string> value(new std::string(valueObject->getValue()));
m_OpaqueActionValue->getLanguage()->push_back(value);
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_outputValue())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_OpaqueActionValue->getOutputValue()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::OutputPinObject> value = std::dynamic_pointer_cast<UML::OutputPinObject>(reference->getReferent());
if (value != nullptr)
{
m_OpaqueActionValue->getOutputValue()->push_back(value->getOutputPinValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_RedefinableElement_isLeaf())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::BooleanValue> valueObject = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::BooleanValue>(inputValue);
if (valueObject != nullptr)
{
m_OpaqueActionValue->setIsLeaf(valueObject->isValue());
}
}
}
void OpaqueActionObject::assignFeatureValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values, int position)
{
this->setFeatureValue(feature, values, position);
}
std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> OpaqueActionObject::retrieveFeatureValues()
{
std::shared_ptr<uml::Classifier> type = this->getTypes()->at(0);
std::shared_ptr<Bag<uml::Property>> allAttributes = type->getAllAttributes();
std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> featureValues(new Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>());
unsigned int allAttributesSize = allAttributes->size();
for(unsigned int i = 0; i < allAttributesSize; i++)
{
std::shared_ptr<uml::Property> property = allAttributes->at(i);
if (property == UML::UMLPackage::eInstance()->get_UML_Action_context() && m_OpaqueActionValue->getContext() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Action_input() && m_OpaqueActionValue->getInput() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Action_localPostcondition() && m_OpaqueActionValue->getLocalPostcondition() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Action_localPrecondition() && m_OpaqueActionValue->getLocalPrecondition() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Action_output() && m_OpaqueActionValue->getOutput() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_activity() && m_OpaqueActionValue->getActivity().lock() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inGroup() && m_OpaqueActionValue->getInGroup() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inInterruptibleRegion() && m_OpaqueActionValue->getInInterruptibleRegion() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inPartition() && m_OpaqueActionValue->getInPartition() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_inStructuredNode() && m_OpaqueActionValue->getInStructuredNode().lock() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_incoming() && m_OpaqueActionValue->getIncoming() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_outgoing() && m_OpaqueActionValue->getOutgoing() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ActivityNode_redefinedNode() && m_OpaqueActionValue->getRedefinedNode() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment() && m_OpaqueActionValue->getOwnedComment() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Element_ownedElement() && m_OpaqueActionValue->getOwnedElement() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Element_owner() && m_OpaqueActionValue->getOwner().lock() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ExecutableNode_handler() && m_OpaqueActionValue->getHandler() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_NamedElement_clientDependency() && m_OpaqueActionValue->getClientDependency() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression() && m_OpaqueActionValue->getNameExpression() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_NamedElement_namespace() && m_OpaqueActionValue->getNamespace().lock() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_inputValue() && m_OpaqueActionValue->getInputValue() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_OpaqueAction_outputValue() && m_OpaqueActionValue->getOutputValue() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_RedefinableElement_redefinedElement() && m_OpaqueActionValue->getRedefinedElement() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_RedefinableElement_redefinitionContext() && m_OpaqueActionValue->getRedefinitionContext() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
}
return featureValues;
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "UnrealCodeAnalyzerTestsPCH.h"
#include "UseElifMacro.h"
static int Function_UseElifMacro()
{
#if TEST_IF_MACRO
return 0;
#elif ELIF_MACRO
return 1;
#else
return 2;
#endif
}
|
// Copyright (c) 2014-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 "coins.h"
#include "random.h"
#include "script/standard.h"
#include "uint256.h"
#include "undo.h"
#include "utilstrencodings.h"
#include "test/test_globalmovementclub.h"
#include "validation.h"
#include "consensus/validation.h"
#include <vector>
#include <map>
#include <boost/test/unit_test.hpp>
int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out);
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight);
namespace
{
//! equality test
bool operator==(const Coin &a, const Coin &b) {
// Empty Coin objects are always equal.
if (a.IsSpent() && b.IsSpent()) return true;
return a.fCoinBase == b.fCoinBase &&
a.nHeight == b.nHeight &&
a.out == b.out;
}
class CCoinsViewTest : public CCoinsView
{
uint256 hashBestBlock_;
std::map<COutPoint, Coin> map_;
public:
bool GetCoin(const COutPoint& outpoint, Coin& coin) const override
{
std::map<COutPoint, Coin>::const_iterator it = map_.find(outpoint);
if (it == map_.end()) {
return false;
}
coin = it->second;
if (coin.IsSpent() && insecure_rand() % 2 == 0) {
// Randomly return false in case of an empty entry.
return false;
}
return true;
}
uint256 GetBestBlock() const override { return hashBestBlock_; }
bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) override
{
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
// Same optimization used in CCoinsViewDB is to only write dirty entries.
map_[it->first] = it->second.coin;
if (it->second.coin.IsSpent() && insecure_rand() % 3 == 0) {
// Randomly delete empty entries on write.
map_.erase(it->first);
}
}
mapCoins.erase(it++);
}
if (!hashBlock.IsNull())
hashBestBlock_ = hashBlock;
return true;
}
};
class CCoinsViewCacheTest : public CCoinsViewCache
{
public:
CCoinsViewCacheTest(CCoinsView* base) : CCoinsViewCache(base) {}
void SelfTest() const
{
// Manually recompute the dynamic usage of the whole data, and compare it.
size_t ret = memusage::DynamicUsage(cacheCoins);
size_t count = 0;
for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) {
ret += it->second.coin.DynamicMemoryUsage();
++count;
}
BOOST_CHECK_EQUAL(GetCacheSize(), count);
BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);
}
CCoinsMap& map() { return cacheCoins; }
size_t& usage() { return cachedCoinsUsage; }
};
}
BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)
static const unsigned int NUM_SIMULATION_ITERATIONS = 40000;
// This is a large randomized insert/remove simulation test on a variable-size
// stack of caches on top of CCoinsViewTest.
//
// It will randomly create/update/delete Coin entries to a tip of caches, with
// txids picked from a limited list of random 256-bit hashes. Occasionally, a
// new tip is added to the stack of caches, or the tip is flushed and removed.
//
// During the process, booleans are kept to make sure that the randomized
// operation hits all branches.
BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
{
// Various coverage trackers.
bool removed_all_caches = false;
bool reached_4_caches = false;
bool added_an_entry = false;
bool added_an_unspendable_entry = false;
bool removed_an_entry = false;
bool updated_an_entry = false;
bool found_an_entry = false;
bool missed_an_entry = false;
bool uncached_an_entry = false;
// A simple map to track what we expect the cache stack to represent.
std::map<COutPoint, Coin> result;
// The cache stack.
CCoinsViewTest base; // A CCoinsViewTest at the bottom.
std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.
// Use a limited set of random transaction ids, so we do test overwriting entries.
std::vector<uint256> txids;
txids.resize(NUM_SIMULATION_ITERATIONS / 8);
for (unsigned int i = 0; i < txids.size(); i++) {
txids[i] = GetRandHash();
}
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
// Do a random modification.
{
uint256 txid = txids[insecure_rand() % txids.size()]; // txid we're going to modify in this iteration.
Coin& coin = result[COutPoint(txid, 0)];
// Determine whether to test HaveCoin before or after Access* (or both). As these functions
// can influence each other's behaviour by pulling things into the cache, all combinations
// are tested.
bool test_havecoin_before = (insecure_rand() & 0x3) == 0; // TODO change to InsecureRandBits(2) when backporting Bitcoin #10321
bool test_havecoin_after = (insecure_rand() & 0x3) == 0; // TODO change to InsecureRandBits(2) when backporting Bitcoin #10321
bool result_havecoin = test_havecoin_before ? stack.back()->HaveCoin(COutPoint(txid, 0)) : false;
const Coin& entry = (insecure_rand() % 500 == 0) ? AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
BOOST_CHECK(coin == entry);
BOOST_CHECK(!test_havecoin_before || result_havecoin == !entry.IsSpent());
if (test_havecoin_after) {
bool ret = stack.back()->HaveCoin(COutPoint(txid, 0));
BOOST_CHECK(ret == !entry.IsSpent());
}
if (insecure_rand() % 5 == 0 || coin.IsSpent()) {
Coin newcoin;
newcoin.out.nValue = insecure_rand();
newcoin.nHeight = 1;
if (insecure_rand() % 16 == 0 && coin.IsSpent()) {
newcoin.out.scriptPubKey.assign(1 + (insecure_rand() & 0x3F), OP_RETURN);
BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable());
added_an_unspendable_entry = true;
} else {
newcoin.out.scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting
(coin.IsSpent() ? added_an_entry : updated_an_entry) = true;
coin = newcoin;
}
stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), !coin.IsSpent() || insecure_rand() & 1);
} else {
removed_an_entry = true;
coin.Clear();
stack.back()->SpendCoin(COutPoint(txid, 0));
}
}
// One every 10 iterations, remove a random entry from the cache
if (insecure_rand() % 10) {
COutPoint out(txids[insecure_rand() % txids.size()], 0);
int cacheid = insecure_rand() % stack.size();
stack[cacheid]->Uncache(out);
uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out);
}
// Once every 1000 iterations and at the end, verify the full cache.
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
BOOST_TEST_MESSAGE("coins_cache_simulation_test - verifying full cache");
for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first);
BOOST_CHECK(have == !coin.IsSpent());
BOOST_CHECK(coin == it->second);
if (coin.IsSpent()) {
missed_an_entry = true;
} else {
BOOST_CHECK(stack.back()->HaveCoinInCache(it->first));
found_an_entry = true;
}
}
BOOST_FOREACH(const CCoinsViewCacheTest *test, stack) {
test->SelfTest();
}
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && insecure_rand() % 2 == 0) {
unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
stack[flushIndex]->Flush();
}
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, change the cache stack.
if (stack.size() > 0 && insecure_rand() % 2 == 0) {
//Remove the top cache
stack.back()->Flush();
delete stack.back();
stack.pop_back();
}
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
//Add a new cache
CCoinsView* tip = &base;
if (stack.size() > 0) {
tip = stack.back();
} else {
removed_all_caches = true;
}
stack.push_back(new CCoinsViewCacheTest(tip));
if (stack.size() == 4) {
reached_4_caches = true;
}
}
}
}
// Clean up the stack.
while (stack.size() > 0) {
delete stack.back();
stack.pop_back();
}
// Verify coverage.
BOOST_CHECK(removed_all_caches);
BOOST_CHECK(reached_4_caches);
BOOST_CHECK(added_an_entry);
BOOST_CHECK(added_an_unspendable_entry);
BOOST_CHECK(removed_an_entry);
BOOST_CHECK(updated_an_entry);
BOOST_CHECK(found_an_entry);
BOOST_CHECK(missed_an_entry);
BOOST_CHECK(uncached_an_entry);
}
// Store of all necessary tx and undo data for next test
typedef std::map<COutPoint, std::tuple<CTransaction,CTxUndo,Coin>> UtxoData;
UtxoData utxoData;
UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
assert(utxoSet.size());
auto utxoSetIt = utxoSet.lower_bound(COutPoint(GetRandHash(), 0));
if (utxoSetIt == utxoSet.end()) {
utxoSetIt = utxoSet.begin();
}
auto utxoDataIt = utxoData.find(*utxoSetIt);
assert(utxoDataIt != utxoData.end());
return utxoDataIt;
}
// This test is similar to the previous test
// except the emphasis is on testing the functionality of UpdateCoins
// random txs are created and UpdateCoins is used to update the cache stack
// In particular it is tested that spending a duplicate coinbase tx
// has the expected effect (the other duplicate is overwitten at all cache levels)
BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
{
bool spent_a_duplicate_coinbase = false;
// A simple map to track what we expect the cache stack to represent.
std::map<COutPoint, Coin> result;
// The cache stack.
CCoinsViewTest base; // A CCoinsViewTest at the bottom.
std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.
// Track the txids we've used in various sets
std::set<COutPoint> coinbase_coins;
std::set<COutPoint> disconnected_coins;
std::set<COutPoint> duplicate_coins;
std::set<COutPoint> utxoset;
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
uint32_t randiter = insecure_rand();
// 19/20 txs add a new transaction
if (randiter % 20 < 19) {
CMutableTransaction tx;
tx.vin.resize(1);
tx.vout.resize(1);
tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
tx.vout[0].scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting
unsigned int height = insecure_rand();
Coin old_coin;
// 2/20 times create a new coinbase
if (randiter % 20 < 2 || coinbase_coins.size() < 10) {
// 1/10 of those times create a duplicate coinbase
if (insecure_rand() % 10 == 0 && coinbase_coins.size()) {
auto utxod = FindRandomFrom(coinbase_coins);
// Reuse the exact same coinbase
tx = std::get<0>(utxod->second);
// shouldn't be available for reconnection if its been duplicated
disconnected_coins.erase(utxod->first);
duplicate_coins.insert(utxod->first);
}
else {
coinbase_coins.insert(COutPoint(tx.GetHash(), 0));
}
assert(CTransaction(tx).IsCoinBase());
}
// 17/20 times reconnect previous or add a regular tx
else {
COutPoint prevout;
// 1/20 times reconnect a previously disconnected tx
if (randiter % 20 == 2 && disconnected_coins.size()) {
auto utxod = FindRandomFrom(disconnected_coins);
tx = std::get<0>(utxod->second);
prevout = tx.vin[0].prevout;
if (!CTransaction(tx).IsCoinBase() && !utxoset.count(prevout)) {
disconnected_coins.erase(utxod->first);
continue;
}
// If this tx is already IN the UTXO, then it must be a coinbase, and it must be a duplicate
if (utxoset.count(utxod->first)) {
assert(CTransaction(tx).IsCoinBase());
assert(duplicate_coins.count(utxod->first));
}
disconnected_coins.erase(utxod->first);
}
// 16/20 times create a regular tx
else {
auto utxod = FindRandomFrom(utxoset);
prevout = utxod->first;
// Construct the tx to spend the coins of prevouthash
tx.vin[0].prevout = prevout;
assert(!CTransaction(tx).IsCoinBase());
}
// In this simple test coins only have two states, spent or unspent, save the unspent state to restore
old_coin = result[prevout];
// Update the expected result of prevouthash to know these coins are spent
result[prevout].Clear();
utxoset.erase(prevout);
// The test is designed to ensure spending a duplicate coinbase will work properly
// if that ever happens and not resurrect the previously overwritten coinbase
if (duplicate_coins.count(prevout)) {
spent_a_duplicate_coinbase = true;
}
}
// Update the expected result to know about the new output coins
assert(tx.vout.size() == 1);
const COutPoint outpoint(tx.GetHash(), 0);
result[outpoint] = Coin(tx.vout[0], height, CTransaction(tx).IsCoinBase());
// Call UpdateCoins on the top cache
CTxUndo undo;
CValidationState dummy;
UpdateCoins(tx, dummy, *(stack.back()), undo, height);
// Update the utxo set for future spends
utxoset.insert(outpoint);
// Track this tx and undo info to use later
utxoData.emplace(outpoint, std::make_tuple(tx,undo,old_coin));
} else if (utxoset.size()) {
//1/20 times undo a previous transaction
auto utxod = FindRandomFrom(utxoset);
CTransaction &tx = std::get<0>(utxod->second);
CTxUndo &undo = std::get<1>(utxod->second);
Coin &orig_coin = std::get<2>(utxod->second);
// Update the expected result
// Remove new outputs
result[utxod->first].Clear();
// If not coinbase restore prevout
if (!tx.IsCoinBase()) {
result[tx.vin[0].prevout] = orig_coin;
}
// Disconnect the tx from the current UTXO
// See code in DisconnectBlock
// remove outputs
stack.back()->SpendCoin(utxod->first);
// restore inputs
if (!tx.IsCoinBase()) {
const COutPoint &out = tx.vin[0].prevout;
Coin coin = undo.vprevout[0];
ApplyTxInUndo(std::move(coin), *(stack.back()), out);
}
// Store as a candidate for reconnection
disconnected_coins.insert(utxod->first);
// Update the utxoset
utxoset.erase(utxod->first);
if (!tx.IsCoinBase())
utxoset.insert(tx.vin[0].prevout);
}
// Once every 1000 iterations and at the end, verify the full cache.
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
BOOST_TEST_MESSAGE("updatecoins_simulation_test - verifying full cache");
for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first);
BOOST_CHECK(have == !coin.IsSpent());
BOOST_CHECK(coin == it->second);
}
}
// One every 10 iterations, remove a random entry from the cache
if (utxoset.size() > 1 && insecure_rand() % 30) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
}
if (disconnected_coins.size() > 1 && insecure_rand() % 30) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
}
if (duplicate_coins.size() > 1 && insecure_rand() % 30) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && insecure_rand() % 2 == 0) {
unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
stack[flushIndex]->Flush();
}
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, change the cache stack.
if (stack.size() > 0 && insecure_rand() % 2 == 0) {
stack.back()->Flush();
delete stack.back();
stack.pop_back();
}
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
CCoinsView* tip = &base;
if (stack.size() > 0) {
tip = stack.back();
}
stack.push_back(new CCoinsViewCacheTest(tip));
}
}
}
// Clean up the stack.
while (stack.size() > 0) {
delete stack.back();
stack.pop_back();
}
// Verify coverage.
BOOST_CHECK(spent_a_duplicate_coinbase);
}
BOOST_AUTO_TEST_CASE(ccoins_serialization)
{
// Good example
CDataStream ss1(ParseHex("97f23c835800816115944e077fe7c803cfa57f29b36bf87c1d35"), SER_DISK, CLIENT_VERSION);
Coin cc1;
ss1 >> cc1;
BOOST_CHECK_EQUAL(cc1.fCoinBase, false);
BOOST_CHECK_EQUAL(cc1.nHeight, 203998);
BOOST_CHECK_EQUAL(cc1.out.nValue, 60000000000ULL);
BOOST_CHECK_EQUAL(HexStr(cc1.out.scriptPubKey), HexStr(GetScriptForDestination(CKeyID(uint160(ParseHex("816115944e077fe7c803cfa57f29b36bf87c1d35"))))));
// Good example
CDataStream ss2(ParseHex("8ddf77bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4"), SER_DISK, CLIENT_VERSION);
Coin cc2;
ss2 >> cc2;
BOOST_CHECK_EQUAL(cc2.fCoinBase, true);
BOOST_CHECK_EQUAL(cc2.nHeight, 120891);
BOOST_CHECK_EQUAL(cc2.out.nValue, 110397);
BOOST_CHECK_EQUAL(HexStr(cc2.out.scriptPubKey), HexStr(GetScriptForDestination(CKeyID(uint160(ParseHex("8c988f1a4a4de2161e0f50aac7f17e7f9555caa4"))))));
// Smallest possible example
CDataStream ss3(ParseHex("000006"), SER_DISK, CLIENT_VERSION);
Coin cc3;
ss3 >> cc3;
BOOST_CHECK_EQUAL(cc3.fCoinBase, false);
BOOST_CHECK_EQUAL(cc3.nHeight, 0);
BOOST_CHECK_EQUAL(cc3.out.nValue, 0);
BOOST_CHECK_EQUAL(cc3.out.scriptPubKey.size(), 0);
// scriptPubKey that ends beyond the end of the stream
CDataStream ss4(ParseHex("000007"), SER_DISK, CLIENT_VERSION);
try {
Coin cc4;
ss4 >> cc4;
BOOST_CHECK_MESSAGE(false, "We should have thrown");
} catch (const std::ios_base::failure& e) {
}
// Very large scriptPubKey (3*10^9 bytes) past the end of the stream
CDataStream tmp(SER_DISK, CLIENT_VERSION);
uint64_t x = 3000000000ULL;
tmp << VARINT(x);
BOOST_CHECK_EQUAL(HexStr(tmp.begin(), tmp.end()), "8a95c0bb00");
CDataStream ss5(ParseHex("00008a95c0bb00"), SER_DISK, CLIENT_VERSION);
try {
Coin cc5;
ss5 >> cc5;
BOOST_CHECK_MESSAGE(false, "We should have thrown");
} catch (const std::ios_base::failure& e) {
}
}
const static COutPoint OUTPOINT;
const static CAmount PRUNED = -1;
const static CAmount ABSENT = -2;
const static CAmount FAIL = -3;
const static CAmount VALUE1 = 100;
const static CAmount VALUE2 = 200;
const static CAmount VALUE3 = 300;
const static char DIRTY = CCoinsCacheEntry::DIRTY;
const static char FRESH = CCoinsCacheEntry::FRESH;
const static char NO_ENTRY = -1;
const static auto FLAGS = {char(0), FRESH, DIRTY, char(DIRTY | FRESH)};
const static auto CLEAN_FLAGS = {char(0), FRESH};
const static auto DIRTY_FLAGS = {DIRTY, char(DIRTY | FRESH)};
const static auto ABSENT_FLAGS = {NO_ENTRY};
void SetCoinsValue(CAmount value, Coin& coin)
{
assert(value != ABSENT);
coin.Clear();
assert(coin.IsSpent());
if (value != PRUNED) {
coin.out.nValue = value;
coin.nHeight = 1;
assert(!coin.IsSpent());
}
}
size_t InsertCoinsMapEntry(CCoinsMap& map, CAmount value, char flags)
{
if (value == ABSENT) {
assert(flags == NO_ENTRY);
return 0;
}
assert(flags != NO_ENTRY);
CCoinsCacheEntry entry;
entry.flags = flags;
SetCoinsValue(value, entry.coin);
auto inserted = map.emplace(OUTPOINT, std::move(entry));
assert(inserted.second);
return inserted.first->second.coin.DynamicMemoryUsage();
}
void GetCoinsMapEntry(const CCoinsMap& map, CAmount& value, char& flags)
{
auto it = map.find(OUTPOINT);
if (it == map.end()) {
value = ABSENT;
flags = NO_ENTRY;
} else {
if (it->second.coin.IsSpent()) {
value = PRUNED;
} else {
value = it->second.coin.out.nValue;
}
flags = it->second.flags;
assert(flags != NO_ENTRY);
}
}
void WriteCoinsViewEntry(CCoinsView& view, CAmount value, char flags)
{
CCoinsMap map;
InsertCoinsMapEntry(map, value, flags);
view.BatchWrite(map, {});
}
class SingleEntryCacheTest
{
public:
SingleEntryCacheTest(CAmount base_value, CAmount cache_value, char cache_flags)
{
WriteCoinsViewEntry(base, base_value, base_value == ABSENT ? NO_ENTRY : DIRTY);
cache.usage() += InsertCoinsMapEntry(cache.map(), cache_value, cache_flags);
}
CCoinsView root;
CCoinsViewCacheTest base{&root};
CCoinsViewCacheTest cache{&base};
};
void CheckAccessCoin(CAmount base_value, CAmount cache_value, CAmount expected_value, char cache_flags, char expected_flags)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
test.cache.AccessCoin(OUTPOINT);
test.cache.SelfTest();
CAmount result_value;
char result_flags;
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
BOOST_AUTO_TEST_CASE(ccoins_access)
{
/* Check AccessCoin behavior, requesting a coin from a cache view layered on
* top of a base view, and checking the resulting entry in the cache after
* the access.
*
* Base Cache Result Cache Result
* Value Value Value Flags Flags
*/
CheckAccessCoin(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(ABSENT, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(PRUNED, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(PRUNED, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(VALUE1, ABSENT, VALUE1, NO_ENTRY , 0 );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(VALUE1, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
}
void CheckSpendCoins(CAmount base_value, CAmount cache_value, CAmount expected_value, char cache_flags, char expected_flags)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
test.cache.SpendCoin(OUTPOINT);
test.cache.SelfTest();
CAmount result_value;
char result_flags;
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
};
BOOST_AUTO_TEST_CASE(ccoins_spend)
{
/* Check SpendCoin behavior, requesting a coin from a cache view layered on
* top of a base view, spending, and then checking
* the resulting entry in the cache after the modification.
*
* Base Cache Result Cache Result
* Value Value Value Flags Flags
*/
CheckSpendCoins(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckSpendCoins(ABSENT, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(ABSENT, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(ABSENT, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(ABSENT, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(ABSENT, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(ABSENT, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(ABSENT, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(ABSENT, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(PRUNED, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckSpendCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(PRUNED, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(PRUNED, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(PRUNED, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(PRUNED, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(PRUNED, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(VALUE1, ABSENT, PRUNED, NO_ENTRY , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(VALUE1, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(VALUE1, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(VALUE1, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(VALUE1, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
}
void CheckAddCoinBase(CAmount base_value, CAmount cache_value, CAmount modify_value, CAmount expected_value, char cache_flags, char expected_flags, bool coinbase)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
CAmount result_value;
char result_flags;
try {
CTxOut output;
output.nValue = modify_value;
test.cache.AddCoin(OUTPOINT, Coin(std::move(output), 1, coinbase), coinbase);
test.cache.SelfTest();
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
} catch (std::logic_error& e) {
result_value = FAIL;
result_flags = NO_ENTRY;
}
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
// Simple wrapper for CheckAddCoinBase function above that loops through
// different possible base_values, making sure each one gives the same results.
// This wrapper lets the coins_add test below be shorter and less repetitive,
// while still verifying that the CoinsViewCache::AddCoin implementation
// ignores base values.
template <typename... Args>
void CheckAddCoin(Args&&... args)
{
for (CAmount base_value : {ABSENT, PRUNED, VALUE1})
CheckAddCoinBase(base_value, std::forward<Args>(args)...);
}
BOOST_AUTO_TEST_CASE(ccoins_add)
{
/* Check AddCoin behavior, requesting a new coin from a cache view,
* writing a modification to the coin, and then checking the resulting
* entry in the cache after the modification. Verify behavior with the
* with the AddCoin potential_overwrite argument set to false, and to true.
*
* Cache Write Result Cache Result potential_overwrite
* Value Value Value Flags Flags
*/
CheckAddCoin(ABSENT, VALUE3, VALUE3, NO_ENTRY , DIRTY|FRESH, false);
CheckAddCoin(ABSENT, VALUE3, VALUE3, NO_ENTRY , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, 0 , DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, 0 , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
CheckAddCoin(VALUE2, VALUE3, FAIL , 0 , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, 0 , DIRTY , true );
CheckAddCoin(VALUE2, VALUE3, FAIL , FRESH , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
CheckAddCoin(VALUE2, VALUE3, FAIL , DIRTY , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, DIRTY , DIRTY , true );
CheckAddCoin(VALUE2, VALUE3, FAIL , DIRTY|FRESH, NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
}
void CheckWriteCoins(CAmount parent_value, CAmount child_value, CAmount expected_value, char parent_flags, char child_flags, char expected_flags)
{
SingleEntryCacheTest test(ABSENT, parent_value, parent_flags);
CAmount result_value;
char result_flags;
try {
WriteCoinsViewEntry(test.cache, child_value, child_flags);
test.cache.SelfTest();
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
} catch (std::logic_error& e) {
result_value = FAIL;
result_flags = NO_ENTRY;
}
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
BOOST_AUTO_TEST_CASE(ccoins_write)
{
/* Check BatchWrite behavior, flushing one entry from a child cache to a
* parent cache, and checking the resulting entry in the parent cache
* after the write.
*
* Parent Child Result Parent Child Result
* Value Value Value Flags Flags Flags
*/
CheckWriteCoins(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY , NO_ENTRY );
CheckWriteCoins(ABSENT, PRUNED, PRUNED, NO_ENTRY , DIRTY , DIRTY );
CheckWriteCoins(ABSENT, PRUNED, ABSENT, NO_ENTRY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(ABSENT, VALUE2, VALUE2, NO_ENTRY , DIRTY , DIRTY );
CheckWriteCoins(ABSENT, VALUE2, VALUE2, NO_ENTRY , DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(PRUNED, ABSENT, PRUNED, 0 , NO_ENTRY , 0 );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, FRESH , NO_ENTRY , FRESH );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, DIRTY , NO_ENTRY , DIRTY );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, DIRTY|FRESH, NO_ENTRY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, FRESH , DIRTY , NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, DIRTY , NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, 0 , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, 0 , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, FRESH , DIRTY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, FRESH , DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(VALUE1, ABSENT, VALUE1, 0 , NO_ENTRY , 0 );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, FRESH , NO_ENTRY , FRESH );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, DIRTY , NO_ENTRY , DIRTY );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, DIRTY|FRESH, NO_ENTRY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, PRUNED, PRUNED, 0 , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , 0 , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, ABSENT, FRESH , DIRTY , NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , DIRTY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, ABSENT, DIRTY|FRESH, DIRTY , NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, 0 , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, VALUE2, FAIL , 0 , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, FRESH , DIRTY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, VALUE2, FAIL , FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, VALUE2, FAIL , DIRTY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, DIRTY|FRESH, DIRTY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, VALUE2, FAIL , DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
// The checks above omit cases where the child flags are not DIRTY, since
// they would be too repetitive (the parent cache is never updated in these
// cases). The loop below covers these cases and makes sure the parent cache
// is always left unchanged.
for (CAmount parent_value : {ABSENT, PRUNED, VALUE1})
for (CAmount child_value : {ABSENT, PRUNED, VALUE2})
for (char parent_flags : parent_value == ABSENT ? ABSENT_FLAGS : FLAGS)
for (char child_flags : child_value == ABSENT ? ABSENT_FLAGS : CLEAN_FLAGS)
CheckWriteCoins(parent_value, child_value, parent_value, parent_flags, child_flags, parent_flags);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <iostream>
#include <cassert>
#include <csignal>
#include "ASock.hpp"
#include "../../msg_defines.h"
///////////////////////////////////////////////////////////////////////////////
class EchoServer : public asock::ASock
{
public:
EchoServer(){this_instance_ = this; }
static void sigint_handler(int signo);
private:
size_t OnCalculateDataLen(asock::Context* context_ptr);
bool OnRecvedCompleteData(asock::Context* context_ptr,
char* data_ptr, size_t len ) ;
void OnClientConnected(asock::Context* context_ptr) ;
void OnClientDisconnected(asock::Context* context_ptr) ;
static EchoServer* this_instance_ ;
};
EchoServer* EchoServer::this_instance_ = nullptr;
///////////////////////////////////////////////////////////////////////////////
size_t EchoServer::OnCalculateDataLen(asock::Context* context_ptr)
{
//---------------------------------------------------
//user specific :
//calculate your complete packet length here using buffer data.
//---------------------------------------------------
if(context_ptr->recv_buffer.GetCumulatedLen() < (int)CHAT_HEADER_SIZE ) {
return asock::MORE_TO_COME ; //more to come
}
ST_MY_HEADER header ;
context_ptr->recv_buffer.PeekData(CHAT_HEADER_SIZE, (char*)&header);
size_t supposed_total_len = std::atoi(header.msg_len) + CHAT_HEADER_SIZE;
assert(supposed_total_len<=context_ptr->recv_buffer.GetCapacity());
return supposed_total_len ;
}
///////////////////////////////////////////////////////////////////////////////
bool EchoServer::OnRecvedCompleteData(asock::Context* context_ptr,
char* data_ptr, size_t len )
{
//user specific : - your whole data has arrived.
char packet[asock::DEFAULT_PACKET_SIZE];
memcpy(&packet, data_ptr+CHAT_HEADER_SIZE, len-CHAT_HEADER_SIZE);
packet[len-CHAT_HEADER_SIZE] = '\0';
std::cout << "recved [" << packet << "]\n";
// this is echo server
if(! SendData(context_ptr, data_ptr, len) ) {
std::cerr <<"["<< __func__ <<"-"<<__LINE__ <<"] error! "<< GetLastErrMsg() <<"\n";
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
void EchoServer::OnClientConnected(asock::Context* context_ptr)
{
std::cout << "client connected : socket fd ["<< context_ptr->socket <<"]\n";
}
///////////////////////////////////////////////////////////////////////////////
void EchoServer::OnClientDisconnected(asock::Context* context_ptr)
{
std::cout << "client disconnected : socket fd ["<< context_ptr->socket <<"]\n";
}
///////////////////////////////////////////////////////////////////////////////
void EchoServer::sigint_handler(int signo)
{
sigset_t sigset, oldset;
sigfillset(&sigset);
if (sigprocmask(SIG_BLOCK, &sigset, &oldset) < 0) {
std::cerr <<"["<< __func__ <<"-"<<__LINE__ <<"] error! "<< strerror(errno) <<"\n";
}
std::cout << "Stop Server! \n";
this_instance_->StopServer();
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
if(argc !=2) {
std::cout << "usage : " << argv[0] << " ipc_socket_full_path \n\n";
return 1;
}
std::signal(SIGINT,EchoServer::sigint_handler);
//max client is 100000,
//max message length is approximately 1024 bytes...
EchoServer echoserver;
if(!echoserver.InitIpcServer(argv[1])) {
std::cerr <<"["<< __func__ <<"-"<<__LINE__ <<"] error! "<< echoserver.GetLastErrMsg() <<"\n";
exit(1);
}std::cout << "server started" << "\n";
while( echoserver.IsServerRunning() ) {
sleep(1);
}
std::cout << "server exit...\n";
return 0;
}
|
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include <gtest/gtest.h>
#include <seqan3/argument_parser/argument_parser.hpp>
TEST(design_error, app_name_validation)
{
const char * argv[] = {"./argument_parser_test"};
EXPECT_NO_THROW((seqan3::argument_parser{"test_parser", 1, argv}));
EXPECT_NO_THROW((seqan3::argument_parser{"test-parser1234_foo", 1, argv}));
EXPECT_THROW((seqan3::argument_parser{"test parser", 1, argv}), seqan3::design_error);
EXPECT_THROW((seqan3::argument_parser{"test;", 1, argv}), seqan3::design_error);
EXPECT_THROW((seqan3::argument_parser{";", 1, argv}), seqan3::design_error);
EXPECT_THROW((seqan3::argument_parser{"test;bad script:D", 1, argv}), seqan3::design_error);
}
TEST(parse_test, design_error)
{
int option_value;
// short option
const char * argv[] = {"./argument_parser_test"};
seqan3::argument_parser parser{"test_parser", 1, argv};
parser.add_option(option_value, 'i', "int", "this is a int option.");
EXPECT_THROW(parser.add_option(option_value, 'i', "aint", "oh oh same id."),
seqan3::design_error);
// long option
seqan3::argument_parser parser2{"test_parser", 1, argv};
parser2.add_option(option_value, 'i', "int", "this is an int option.");
EXPECT_THROW(parser2.add_option(option_value, 'a', "int", "oh oh another id."),
seqan3::design_error);
// empty identifier
seqan3::argument_parser parser3{"test_parser", 1, argv};
EXPECT_THROW(parser3.add_option(option_value, '\0', "", "oh oh all is empty."),
seqan3::design_error);
bool flag_value;
// short flag
seqan3::argument_parser parser4{"test_parser", 1, argv};
parser4.add_flag(flag_value, 'i', "int1", "this is an int option.");
EXPECT_THROW(parser4.add_flag(flag_value, 'i', "int2", "oh oh another id."),
seqan3::design_error);
// long flag
seqan3::argument_parser parser5{"test_parser", 1, argv};
parser5.add_flag(flag_value, 'i', "int", "this is an int option.");
EXPECT_THROW(parser5.add_flag(flag_value, 'a', "int", "oh oh another id."),
seqan3::design_error);
// empty identifier
seqan3::argument_parser parser6{"test_parser", 1, argv};
EXPECT_THROW(parser6.add_flag(flag_value, '\0', "", "oh oh another id."),
seqan3::design_error);
// positional option not at the end
const char * argv2[] = {"./argument_parser_test", "arg1", "arg2", "arg3"};
std::vector<int> vec;
seqan3::argument_parser parser7{"test_parser", 4, argv2};
parser7.add_positional_option(vec, "oh oh list not at the end.");
EXPECT_THROW(parser7.add_positional_option(option_value, "desc."), seqan3::design_error);
// using h, help, advanced-help, and export-help
seqan3::argument_parser parser8{"test_parser", 1, argv};
EXPECT_THROW(parser8.add_option(option_value, 'h', "", "-h is bad."),
seqan3::design_error);
EXPECT_THROW(parser8.add_option(option_value, '\0', "help", "help is bad."),
seqan3::design_error);
EXPECT_THROW(parser8.add_option(option_value, '\0', "advanced-help",
"advanced-help is bad"), seqan3::design_error);
EXPECT_THROW(parser8.add_option(option_value, '\0', "export-help",
"export-help is bad"), seqan3::design_error);
// using one-letter long identifiers.
seqan3::argument_parser parser9{"test_parser", 1, argv};
EXPECT_THROW(parser9.add_option(option_value, 'y', "z", "long identifier is one letter"),
seqan3::design_error);
EXPECT_THROW(parser9.add_flag(flag_value, 'y', "z", "long identifier is one letter"),
seqan3::design_error);
// using non-printable characters
seqan3::argument_parser parser10{"test_parser", 1, argv};
EXPECT_THROW(parser10.add_option(option_value, '\t', "no\n", "tab and newline don't work!"),
seqan3::design_error);
EXPECT_THROW(parser10.add_flag(flag_value, 'i', "no\n", "tab and newline don't work!"),
seqan3::design_error);
EXPECT_THROW(parser10.add_flag(flag_value, 'a', "-no", "can't start long_id with a hyphen"),
seqan3::design_error);
}
TEST(parse_test, parse_called_twice)
{
std::string option_value;
const char * argv[] = {"./argument_parser_test", "--version-check", "0", "-s", "option_string"};
seqan3::argument_parser parser{"test_parser", 5, argv};
parser.add_option(option_value, 's', "string-option", "this is a string option.");
testing::internal::CaptureStderr();
EXPECT_NO_THROW(parser.parse());
EXPECT_TRUE((testing::internal::GetCapturedStderr()).empty());
EXPECT_EQ(option_value, "option_string");
EXPECT_THROW(parser.parse(), seqan3::design_error);
}
TEST(parse_test, subcommand_argument_parser_error)
{
bool flag_value{};
// subcommand parsing was not enabled on construction but get_sub_parser() is called
{
const char * argv[]{"./top_level", "-f"};
seqan3::argument_parser top_level_parser{"top_level", 2, argv, false};
top_level_parser.add_flag(flag_value, 'f', "foo", "foo bar");
EXPECT_NO_THROW(top_level_parser.parse());
EXPECT_EQ(true, flag_value);
EXPECT_THROW(top_level_parser.get_sub_parser(), seqan3::design_error);
}
// subcommand key word must only contain alpha numeric characters
{
const char * argv[]{"./top_level", "-f"};
EXPECT_THROW((seqan3::argument_parser{"top_level", 2, argv, false, {"with space"}}), seqan3::design_error);
EXPECT_THROW((seqan3::argument_parser{"top_level", 2, argv, false, {"-dash"}}), seqan3::design_error);
}
// no positional/options are allowed
{
const char * argv[]{"./top_level", "foo"};
seqan3::argument_parser top_level_parser{"top_level", 2, argv, false, {"foo"}};
EXPECT_THROW((top_level_parser.add_option(flag_value, 'f', "foo", "foo bar")), seqan3::design_error);
EXPECT_THROW((top_level_parser.add_positional_option(flag_value, "foo bar")), seqan3::design_error);
}
}
|
// rocks_btree_impl_test.cpp
/**
* Copyright (C) 2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include <boost/filesystem/operations.hpp>
#include <rocksdb/db.h>
#include <rocksdb/slice.h>
#include <rocksdb/options.h>
#include "mongo/db/operation_context_noop.h"
#include "mongo/db/storage/rocks/rocks_btree_impl.h"
#include "mongo/db/storage/rocks/rocks_record_store.h"
#include "mongo/db/storage/rocks/rocks_recovery_unit.h"
#include "mongo/unittest/unittest.h"
using namespace mongo;
namespace mongo {
class MyOperationContext : public OperationContextNoop {
public:
MyOperationContext( rocksdb::DB* db )
: OperationContextNoop( new RocksRecoveryUnit( db, false ) ) {
}
};
rocksdb::DB* getDB() {
string path = "/tmp/mongo-rocks-test";
boost::filesystem::remove_all( path );
rocksdb::Options options;
// Optimize RocksDB. This is the easiest way to get RocksDB to perform well
options.IncreaseParallelism();
options.OptimizeLevelStyleCompaction();
// create the DB if it's not already present
options.create_if_missing = true;
// open DB
rocksdb::DB* db;
rocksdb::Status s = rocksdb::DB::Open(options, path, &db);
ASSERT(s.ok());
return db;
}
TEST( RocksRecordStoreTest, BrainDead ) {
scoped_ptr<rocksdb::DB> db( getDB() );
{
RocksBtreeImpl btree( db.get(), db->DefaultColumnFamily() );
BSONObj key = BSON( "" << 1 );
DiskLoc loc( 5, 16 );
{
MyOperationContext opCtx( db.get() );
{
WriteUnitOfWork uow( opCtx.recoveryUnit() );
ASSERT( !btree.unindex( &opCtx, key, loc ) );
}
}
{
MyOperationContext opCtx( db.get() );
{
WriteUnitOfWork uow( opCtx.recoveryUnit() );
Status res = btree.insert( &opCtx, key, loc, true );
ASSERT_OK( res );
}
}
{
MyOperationContext opCtx( db.get() );
{
WriteUnitOfWork uow( opCtx.recoveryUnit() );
ASSERT( btree.unindex( &opCtx, key, loc ) );
}
}
{
MyOperationContext opCtx( db.get() );
{
WriteUnitOfWork uow( opCtx.recoveryUnit() );
btree.unindex( &opCtx, key, loc );
}
}
}
}
TEST( RocksRecordStoreTest, Locate1 ) {
scoped_ptr<rocksdb::DB> db( getDB() );
{
RocksBtreeImpl btree( db.get(), db->DefaultColumnFamily() );
BSONObj key = BSON( "" << 1 );
DiskLoc loc( 5, 16 );
{
scoped_ptr<BtreeInterface::Cursor> cursor( btree.newCursor( 1 ) );
ASSERT( !cursor->locate( key, loc ) );
}
{
MyOperationContext opCtx( db.get() );
{
WriteUnitOfWork uow( opCtx.recoveryUnit() );
Status res = btree.insert( &opCtx, key, loc, true );
ASSERT_OK( res );
}
}
{
scoped_ptr<BtreeInterface::Cursor> cursor( btree.newCursor( 1 ) );
ASSERT( cursor->locate( key, loc ) );
ASSERT_EQUALS( key, cursor->getKey() );
ASSERT_EQUALS( loc, cursor->getDiskLoc() );
}
}
}
TEST( RocksRecordStoreTest, Locate2 ) {
scoped_ptr<rocksdb::DB> db( getDB() );
{
RocksBtreeImpl btree( db.get(), db->DefaultColumnFamily() );
{
MyOperationContext opCtx( db.get() );
{
WriteUnitOfWork uow( opCtx.recoveryUnit() );
ASSERT_OK( btree.insert( &opCtx, BSON( "" << 1 ), DiskLoc(1,1), true ) );
ASSERT_OK( btree.insert( &opCtx, BSON( "" << 2 ), DiskLoc(1,2), true ) );
ASSERT_OK( btree.insert( &opCtx, BSON( "" << 3 ), DiskLoc(1,3), true ) );
}
}
{
scoped_ptr<BtreeInterface::Cursor> cursor( btree.newCursor( 1 ) );
ASSERT( cursor->locate( BSON( "a" << 2 ), DiskLoc(0,0) ) );
ASSERT( !cursor->isEOF() );
ASSERT_EQUALS( BSON( "" << 2 ), cursor->getKey() );
ASSERT_EQUALS( DiskLoc(1,2), cursor->getDiskLoc() );
}
}
}
}
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
AudioIODeviceType::AudioIODeviceType (const String& name)
: typeName (name)
{
}
AudioIODeviceType::~AudioIODeviceType()
{
}
//==============================================================================
void AudioIODeviceType::addListener (Listener* l) { listeners.add (l); }
void AudioIODeviceType::removeListener (Listener* l) { listeners.remove (l); }
void AudioIODeviceType::callDeviceChangeListeners()
{
listeners.call (&AudioIODeviceType::Listener::audioDeviceListChanged);
}
//==============================================================================
#if ! JUCE_MAC
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio() { return nullptr; }
#endif
#if ! JUCE_IOS
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio() { return nullptr; }
#endif
#if ! (JUCE_WINDOWS && JUCE_WASAPI)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI() { return nullptr; }
#endif
#if ! (JUCE_WINDOWS && JUCE_DIRECTSOUND)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound() { return nullptr; }
#endif
#if ! (JUCE_WINDOWS && JUCE_ASIO)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO() { return nullptr; }
#endif
#if ! (JUCE_LINUX && JUCE_ALSA)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA() { return nullptr; }
#endif
#if ! (JUCE_LINUX && JUCE_JACK)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK() { return nullptr; }
#endif
#if ! JUCE_ANDROID
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android() { return nullptr; }
#endif
#if ! (JUCE_ANDROID && JUCE_USE_ANDROID_OPENSLES)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES() { return nullptr; }
#endif
|
#include "darksendconfig.h"
#include "ui_darksendconfig.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "init.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
#include <QSettings>
DarksendConfig::DarksendConfig(QWidget *parent) :
QDialog(parent),
ui(new Ui::DarksendConfig),
model(0)
{
ui->setupUi(this);
connect(ui->buttonBasic, SIGNAL(clicked()), this, SLOT(clickBasic()));
connect(ui->buttonHigh, SIGNAL(clicked()), this, SLOT(clickHigh()));
connect(ui->buttonMax, SIGNAL(clicked()), this, SLOT(clickMax()));
}
DarksendConfig::~DarksendConfig()
{
delete ui;
}
void DarksendConfig::setModel(WalletModel *model)
{
this->model = model;
}
void DarksendConfig::clickBasic()
{
configure(true, 1000, 2);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("Darksend Configuration"),
tr(
"Darksend was successfully set to basic (%1 and 2 rounds). You can change this at any time by opening Antcoin's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::clickHigh()
{
configure(true, 1000, 8);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("Darksend Configuration"),
tr(
"Darksend was successfully set to high (%1 and 8 rounds). You can change this at any time by opening Antcoin's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::clickMax()
{
configure(true, 1000, 16);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("Darksend Configuration"),
tr(
"Darksend was successfully set to maximum (%1 and 16 rounds). You can change this at any time by opening Antcoin's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::configure(bool enabled, int coins, int rounds) {
QSettings settings;
settings.setValue("nDarksendRounds", rounds);
settings.setValue("nAnonymizeDarkcoinAmount", coins);
nDarksendRounds = rounds;
nAnonymizeDarkcoinAmount = coins;
}
|
#include <iostream>
#include "talvos/Device.h"
#include "talvos/Instruction.h"
#include "talvos/Invocation.h"
#include "talvos/Plugin.h"
using namespace talvos;
class CallbackTest : public Plugin
{
public:
CallbackTest() { std::cout << "plugin created" << std::endl; }
~CallbackTest() { std::cout << "plugin destroyed" << std::endl; }
bool isThreadSafe() const override { return false; }
void commandBegin(const Command *Cmd) override
{
std::cout << "command begin" << std::endl;
}
void commandComplete(const Command *Cmd) override
{
std::cout << "command complete" << std::endl;
}
void hostMemoryLoad(const Memory *Mem, uint64_t Address,
uint64_t NumBytes) override
{
std::cout << "host memory load" << std::endl;
}
void hostMemoryStore(const Memory *Mem, uint64_t Address, uint64_t NumBytes,
const uint8_t *Data) override
{
std::cout << "host memory store" << std::endl;
}
void instructionExecuted(const Invocation *Invoc,
const Instruction *Inst) override
{
std::cout << Invoc->getGlobalId() << ": ";
Inst->print(std::cout);
std::cout << std::endl;
}
void invocationBegin(const Invocation *Invoc) override
{
std::cout << "invocation begin" << std::endl;
}
void invocationComplete(const Invocation *Invoc) override
{
std::cout << "invocation complete" << std::endl;
}
void memoryLoad(const Memory *Mem, uint64_t Address, uint64_t NumBytes,
const Invocation *Invoc) override
{
std::cout << "memory load" << std::endl;
}
void memoryStore(const Memory *Mem, uint64_t Address, uint64_t NumBytes,
const uint8_t *Data, const Invocation *Invoc) override
{
std::cout << "memory store" << std::endl;
}
void workgroupBegin(const Workgroup *Group) override
{
std::cout << "workgroup begin" << std::endl;
}
void workgroupBarrier(const Workgroup *Group) override
{
std::cout << "workgroup barrier" << std::endl;
}
void workgroupComplete(const Workgroup *Group) override
{
std::cout << "workgroup complete" << std::endl;
}
};
extern "C"
{
Plugin *talvosCreatePlugin(const Device *Dev) { return new CallbackTest; }
void talvosDestroyPlugin(Plugin *P) { delete P; }
}
|
//
//
//
#include "UrlTile.h"
ol::source::UrlTile::UrlTile()
{
}
ol::source::UrlTile::~UrlTile()
{
}
|
#include <cmath>
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/examples/pendulum/pendulum_geometry.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace pendulum {
namespace {
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
template <typename T>
class PendulumEnergyShapingController : public systems::LeafSystem<T> {
public:
explicit PendulumEnergyShapingController(const PendulumParams<T>& params) {
this->DeclareVectorInputPort(PendulumState<T>());
this->DeclareVectorOutputPort(PendulumInput<T>(),
&PendulumEnergyShapingController::CalcTau);
this->DeclareNumericParameter(params);
}
private:
void CalcTau(const systems::Context<T>& context,
PendulumInput<T>* output) const {
const auto* state =
this->template EvalVectorInput<PendulumState>(context, 0);
const PendulumParams<T>& params =
this->template GetNumericParameter<PendulumParams>(context, 0);
// Pendulum energy shaping from Section 3.5.2 of
// http://underactuated.csail.mit.edu/underactuated.html?chapter=3
using std::pow;
// Desired energy is slightly more than the energy at the top (want to pass
// through the upright with non-zero velocity).
const T desired_energy =
1.1 * params.mass() * params.gravity() * params.length();
// Current total energy (see PendulumPlant::CalcTotalEnergy).
const T current_energy =
0.5 * params.mass() * pow(params.length() * state->thetadot(), 2) -
params.mass() * params.gravity() * params.length() *
cos(state->theta());
const double kEnergyFeedbackGain = .1;
output->set_tau(params.damping() * state->thetadot() +
kEnergyFeedbackGain * state->thetadot() *
(desired_energy - current_energy));
}
};
int DoMain() {
PendulumParams<double> params;
systems::DiagramBuilder<double> builder;
auto pendulum = builder.AddSystem<PendulumPlant>();
pendulum->set_name("pendulum");
// Use default pendulum parameters in the controller (real controllers never
// get the true parameters).
auto controller = builder.AddSystem<PendulumEnergyShapingController>(
params);
controller->set_name("controller");
builder.Connect(pendulum->get_state_output_port(),
controller->get_input_port(0));
builder.Connect(controller->get_output_port(0), pendulum->get_input_port());
auto scene_graph = builder.AddSystem<geometry::SceneGraph>();
PendulumGeometry::AddToBuilder(
&builder, pendulum->get_state_output_port(), scene_graph);
geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph);
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
systems::Context<double>& pendulum_context =
diagram->GetMutableSubsystemContext(*pendulum,
&simulator.get_mutable_context());
auto& state = pendulum->get_mutable_state(&pendulum_context);
// Desired energy is the total energy when the pendulum is at the upright.
state.set_theta(M_PI);
state.set_thetadot(0.0);
const double desired_energy = pendulum->CalcTotalEnergy(pendulum_context);
// Set initial conditions (near the bottom).
state.set_theta(0.1);
state.set_thetadot(0.2);
const double initial_energy = pendulum->CalcTotalEnergy(pendulum_context);
// Run the simulation.
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.Initialize();
simulator.AdvanceTo(10);
// Compute the final (total) energy.
const double final_energy = pendulum->CalcTotalEnergy(pendulum_context);
// Adds a numerical test that we have successfully regulated the energy
// towards the desired energy level.
DRAKE_DEMAND(std::abs(final_energy - desired_energy) <
(0.5 * std::abs(initial_energy - desired_energy)));
return 0;
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::pendulum::DoMain();
}
|
/*
* include/action.hh
*
* Copyright 2018 Brandon Gomes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MU__ACTION_HH
#define MU__ACTION_HH
#pragma once
#include <G4VUserActionInitialization.hh>
#include <G4UserEventAction.hh>
#include <G4UserRunAction.hh>
#include <G4VUserPrimaryGeneratorAction.hh>
#include <G4Event.hh>
#include <G4Run.hh>
#include "physics/Generator.hh"
#include "ui.hh"
namespace MATHUSLA { namespace MU {
//__Geant4 Action Initializer___________________________________________________________________
class ActionInitialization : public G4VUserActionInitialization {
public:
ActionInitialization(const std::string& generator="",
const std::string& data_dir="");
void BuildForMaster() const;
void Build() const;
};
//----------------------------------------------------------------------------------------------
//__Event Action Manager________________________________________________________________________
class EventAction : public G4UserEventAction {
public:
EventAction(const size_t print_modulo);
void BeginOfEventAction(const G4Event* event);
static const G4Event* GetEvent();
static size_t EventID();
};
//----------------------------------------------------------------------------------------------
//__Run Action Manager__________________________________________________________________________
class RunAction : public G4UserRunAction {
public:
RunAction(const std::string& data_dir="");
void BeginOfRunAction(const G4Run* run);
void EndOfRunAction(const G4Run*);
static const G4Run* GetRun();
static size_t RunID();
static size_t EventCount();
};
//----------------------------------------------------------------------------------------------
//__Generator Action Manager____________________________________________________________________
class GeneratorAction : public G4VUserPrimaryGeneratorAction, public G4UImessenger {
public:
GeneratorAction(const std::string& generator="");
void GeneratePrimaries(G4Event* event);
void SetNewValue(G4UIcommand* command, G4String value);
static const Physics::Generator* GetGenerator();
static Physics::ParticleVector GetLastEvent();
static void SetGenerator(const std::string& generator);
private:
Command::NoArg* _list;
Command::NoArg* _current;
Command::StringArg* _select;
};
//----------------------------------------------------------------------------------------------
} } /* namespace MATHUSLA::MU */
#endif /* MU__ACTION_HH */
|
#include <bits/stdc++.h>
using namespace std;
int main() {
string s; cin >> s;
int k; cin >> k;
int ca = 0, sf = 0, lt = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '?') ca++;
else if(s[i] == '*') sf++;
else lt++;
}
// cout << ca << " " << sf << " " << lt << endl;
if(lt == k) {
for(int i = 0; i < s.length(); i++) {
if(s[i] != '?' && s[i] != '*') cout << s[i];
}
cout << endl;
return 0;
}
if(lt < k) {
if(sf == 0) cout << "Impossible\n";
else {
int fl = 0;
cout << s[0];
for(int i = 1; i < s.length(); i++) {
if(fl == 0 && s[i] == '*' && s[i - 1] != '?' && s[i - 1] != '*') {
for(int j = 0; j < k - lt; j++) {
cout << s[i - 1];
}
fl = 1;
}
if(s[i] != '*' && s[i] != '?') cout << s[i];
}
cout << endl;
return 0;
}
}
if(lt > k) {
if(ca + sf < lt - k) cout << "Impossible\n";
else {
int req = lt - k, cnt = 0;
for(int i = 0; i < s.length() - 1; i++) {
if(s[i] != '*' && s[i] != '?') {
if(s[i + 1] == '?' || s[i + 1] == '*') {
if(cnt >= req) {
cout << s[i];
} else {
cnt++;
}
} else {
cout << s[i];
}
}
}
if(s[s.length() - 1] != '*' && s[s.length() - 1] != '?')
cout << s[s.length() - 1] << endl;
}
}
return 0;
}
|
#include <stdio.h>
#include <Kokkos_Core.hpp>
#include <MemberTypes.h>
#include <SellCSigma.h>
#include <Distribute.h>
#include <psAssert.h>
using particle_structs::SellCSigma;
using particle_structs::MemberTypes;
using particle_structs::distribute_elements;
using particle_structs::distribute_particles;
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
Kokkos::initialize(argc,argv);
typedef MemberTypes<int> Type1;
typedef MemberTypes<int,double[2]> Type2;
typedef MemberTypes<int[3],double[2],char> Type3;
printf("Type1: %lu\n",Type1::memsize);
PS_ALWAYS_ASSERT(Type1::memsize == sizeof(int));
printf("Type2: %lu\n",Type2::memsize);
PS_ALWAYS_ASSERT(Type2::memsize == sizeof(int) + 2*sizeof(double));
printf("Type3: %lu\n",Type3::memsize);
PS_ALWAYS_ASSERT(Type3::memsize == 3*sizeof(int) + 2*sizeof(double) + sizeof(char));
printf("Type3 start of doubles: %lu\n",Type3::sizeToIndex<1>());
PS_ALWAYS_ASSERT(Type3::sizeToIndex<1>() == 3*sizeof(int));
int ne = 5;
int np = 10;
int* ptcls_per_elem = new int[ne];
std::vector<int>* ids = new std::vector<int>[ne];
distribute_particles(ne,np, 0, ptcls_per_elem, ids);
typedef Kokkos::DefaultExecutionSpace exe_space;
Kokkos::TeamPolicy<exe_space> po(128, 4);
typedef SellCSigma<Type2,exe_space> SCS;
{
SCS::kkLidView ptcls_per_elem_v("ptcls_per_elem_v", ne);
SCS::kkGidView element_gids_v("", 0);
particle_structs::hostToDevice(ptcls_per_elem_v, ptcls_per_elem);
delete [] ptcls_per_elem;
delete [] ids;
SCS* scs = new SCS(po, 1, 10000, ne, np, ptcls_per_elem_v, element_gids_v);
scs->printFormat();
auto scs_first = scs->get<0>(); //int
auto scs_second = scs->get<1>(); //double[2]
auto setValues = SCS_LAMBDA(int element_id, int particle_id, bool mask) {
if (mask) {
scs_first(particle_id) = element_id;
scs_second(particle_id, 0) = 1.0;
scs_second(particle_id,0) = 2.0;
}
else {
scs_first(particle_id) = -1;
scs_second(particle_id, 0) = 0;
scs_second(particle_id,0) = 0;
}
};
scs->parallel_for(setValues);
delete scs;
}
Kokkos::finalize();
MPI_Finalize();
printf("All tests passed\n");
return 0;
}
|
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#include <distribution.h>
#include <gaussian.h>
using namespace std;
#define DPRINTC(C) printf(#C " = %c\n", (C))
#define DPRINTS(S) printf(#S " = %s\n", (S))
#define DPRINTD(D) printf(#D " = %d\n", (D))
#define DPRINTLLD(LLD) printf(#LLD " = %lld\n", (LLD))
#define DPRINTLF(LF) printf(#LF " = %.5lf\n", (LF))
// helper function; Phi(x; mean, stddev)
double Gaussian::gaussian_pdf(double x, double mean, double stdev)
{
// simply compute exp(-(x - mu)^2/2*sigma^2)/sqrt(2*pi*sigma^2)
double E = x - mean;
E *= -E;
E /= 2 * stdev * stdev;
double ret = exp(E);
return ret / (stdev * sqrt(2 * M_PI));
}
// create a new untrained Gaussian distribution with a known number of sub-outputs
Gaussian::Gaussian(int sub_count) : obs(sub_count)
{
mu = new double[sub_count];
sigma = new double[sub_count];
}
// copy a known Gaussian distribution from its parameters
Gaussian::Gaussian(int sub_count, double *mu, double *sigma) : obs(sub_count)
{
this -> mu = new double[obs];
this -> sigma = new double[obs];
for (int i=0;i<obs;i++)
{
this -> mu[i] = mu[i];
this -> sigma[i] = sigma[i];
}
}
Gaussian::~Gaussian()
{
delete[] mu;
delete[] sigma;
}
// Create a (deep) copy of the distribution
Distribution* Gaussian::clone()
{
return new Gaussian(obs, mu, sigma);
}
// Train the distribution's parameters on a training set
void Gaussian::train(vector<vector<pair<int, double> > > &train_set)
{
int *cnt = new int[obs];
for (int i=0;i<obs;i++)
{
mu[i] = 0.0;
sigma[i] = 0.0;
cnt[i] = 0;
}
// compute sample means and std. deviations for each sub-output individually
for (uint i=0;i<train_set.size();i++)
{
for (uint j=0;j<train_set[i].size();j++)
{
mu[train_set[i][j].first] += train_set[i][j].second;
cnt[train_set[i][j].first]++;
}
}
for (int i=0;i<obs;i++) mu[i] /= cnt[i];
for (uint i=0;i<train_set.size();i++)
{
for (uint j=0;j<train_set[i].size();j++)
{
sigma[train_set[i][j].first] += (train_set[i][j].second - mu[train_set[i][j].first]) * (train_set[i][j].second - mu[train_set[i][j].first]);
}
}
for (int i=0;i<obs;i++) sigma[i] = sqrt(sigma[i] / (cnt[i] - 1));
delete[] cnt;
}
// Get the probability of producing output x, assuming the sub-output is obs_id
double Gaussian::get_probability(int obs_id, double x)
{
// simply return the already defined probability density function
return gaussian_pdf(x, mu[obs_id], sigma[obs_id]);
}
// read the distribution from an input stream
istream& Gaussian::read(istream &in)
{
in >> this -> obs;
this -> mu = new double[obs];
this -> sigma = new double[obs];
for (int i=0;i<obs;i++)
{
in >> mu[i] >> sigma[i];
}
return in;
}
// write the distribution to an output stream
ostream& Gaussian::write(ostream &out)
{
out << obs << endl;
for (int i=0;i<obs;i++)
{
out << mu[i] << " " << sigma[i] << endl;
}
return out;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
#ifndef WIN32
#include <execinfo.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64 nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64 nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64 GetRand(uint64 nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
uint64 nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
static FILE* fileout = NULL;
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
loop
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
loop
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64 n_abs = (n > 0 ? n : -n);
int64 quotient = n_abs/COIN;
int64 remainder = n_abs%COIN;
string str = strprintf("%"PRI64d".%06"PRI64d, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64& nRet)
{
string strWhole;
int64 nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64 nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64 nWhole = atoi64(strWhole);
int64 nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
static const long hextable[] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-19
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 30-39
-1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, -1, -1, // 50-59
-1, -1, -1, -1, -1, 10, 11, 12, 13, 14,
15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 70-79
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 10, 11, 12, // 90-99
13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 110-109
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 130-139
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 150-159
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 170-179
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 190-199
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 210-219
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 230-239
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1
};
long hex2long(const char* hexString)
{
long ret = 0;
while (*hexString && ret >= 0)
{
ret = (ret << 4) | hextable[*hexString++];
}
return ret;
}
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
loop
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64 GetArg(const std::string& strArg, int64 nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
loop
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "LxcCoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void LogStackTrace() {
printf("\n\n******* exception encountered *******\n");
if (fileout)
{
#ifndef WIN32
void* pszBuffer[32];
size_t size;
size = backtrace(pszBuffer, 32);
backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
#endif
}
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\LxcCoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\LxcCoin
// Mac: ~/Library/Application Support/LxcCoin
// Unix: ~/.LxcCoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "Lxc Coin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "LxcCoin";
#else
// Unix
return pathRet / ".lxcgbp";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet2";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "LxcCoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "LxcCoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
int GetFilesize(FILE* file)
{
int nSavePos = ftell(file);
int nFilesize = -1;
if (fseek(file, 0, SEEK_END) == 0)
nFilesize = ftell(file);
fseek(file, nSavePos, SEEK_SET);
return nFilesize;
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && GetFilesize(file) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64 nMockTime = 0; // For unit testing
int64 GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64 nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64 nTimeOffset = 0;
int64 GetAdjustedTime()
{
return GetTime() + nTimeOffset;
}
void AddTimeData(const CNetAddr& ip, int64 nTime)
{
int64 nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64 nMedian = vTimeOffsets.median();
std::vector<int64> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64 nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong LxcCoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("LxcCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64 n, vSorted)
printf("%+"PRI64d" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
|
/********************************************************************************
* Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,
* Faculty of Engineering, University of Southern Denmark
*
* 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 "Sphere.hpp"
#include "PlainTriMesh.hpp"
#include <rw/core/Ptr.hpp>
#include <rw/math/Vector3D.hpp>
using namespace rw::core;
using namespace rw::geometry;
using namespace rw::math;
namespace {
// this is a helper function for createsphere
// if you just want to make a sphere, just call createsphere
void spherehelper (const std::vector< Triangle<> >& triangles,
std::vector< Triangle<> >& newtriangles, double radius)
{
newtriangles.clear ();
std::vector< Triangle<> >::const_iterator i = triangles.begin ();
while (i != triangles.end ()) {
const Triangle<>& t = *i++;
Vector3D<> a = t[0], b = t[1], c = t[2];
Vector3D<> v1 (a[0] + b[0], a[1] + b[1], a[2] + b[2]);
Vector3D<> v2 (a[0] + c[0], a[1] + c[1], a[2] + c[2]);
Vector3D<> v3 (b[0] + c[0], b[1] + c[1], b[2] + c[2]);
v1 = normalize (v1) * radius;
v2 = normalize (v2) * radius;
v3 = normalize (v3) * radius;
newtriangles.push_back (Triangle<> (a, v1, v2));
newtriangles.push_back (Triangle<> (c, v2, v3));
newtriangles.push_back (Triangle<> (b, v3, v1));
newtriangles.push_back (Triangle<> (v1, v3, v2));
}
}
} // namespace
// levels specifies how many levels of detail we will have
// levels should be 0 or greater
// there will be 4^(levels+1) faces in there sphere
// std::vector<Triangle> createsphere(int levels)
TriMesh::Ptr Sphere::createMesh (int resolution) const
{
std::vector< Triangle<> > triangles, triangles_dst, *trimesh_dst, *trimesh_src;
/* Let's find the helper granulation value of the sphere generator.
* Old version of this code used value 6 for granulation, which was
* supposed to match the detail achieved by other primitives
* with resolution of 20.
* It should be that the default value for resolution results in the same
* level of detail as in the previous version. Should resolution parameter
* increase the number of faces linearly?
*
* for level=20 faces=16384
* -> faces = resolution/20 * 16384
* if faces = 4^(granulation+1)
* -> granulation = log_4(faces)-1
*/
double faces = resolution / 20.0 * 16384;
double granulation = log (faces) / log (4) - 1;
// build a tetrahedron
Vector3D<> v0 (0.0, 0.0, 1.0);
Vector3D<> v1 (2.0 * sqrt (2.0) / 3.0, 0.0, -1.0 / 3.0);
Vector3D<> v2 (-sqrt (2.0) / 3.0, sqrt (6.0) / 3.0, -1.0 / 3.0);
Vector3D<> v3 (-sqrt (2.0) / 3.0, -sqrt (6.0) / 3.0, -1.0 / 3.0);
triangles.push_back (Triangle<> (v0 * _radius, v1 * _radius, v2 * _radius));
triangles.push_back (Triangle<> (v0 * _radius, v2 * _radius, v3 * _radius));
triangles.push_back (Triangle<> (v0 * _radius, v3 * _radius, v1 * _radius));
triangles.push_back (Triangle<> (v1 * _radius, v3 * _radius, v2 * _radius));
trimesh_dst = &triangles_dst;
trimesh_src = &triangles;
for (int ctr = 0; ctr < granulation; ctr++) {
spherehelper (*trimesh_src, *trimesh_dst, _radius);
std::swap (trimesh_src, trimesh_dst);
trimesh_dst->clear ();
}
PlainTriMeshD* mesh = new PlainTriMeshD (*trimesh_src);
return ownedPtr (mesh);
}
void Sphere::setParameters (const rw::math::Q& q)
{
if (q.size () != 1) {
RW_THROW ("Size of parameter list must equal 1!");
}
_radius = q (0);
}
|
#include "_reg_ReadWriteImage.h"
#include "_reg_ReadWriteMatrix.h"
#include "_reg_localTrans.h"
#include "_reg_tools.h"
#include "AffineDeformationFieldKernel.h"
#define EPS 0.0001
int main(int argc, char **argv)
{
if (argc != 6) {
fprintf(stderr, "Usage: %s <refImage> <inputGrid> <expectedField> <useComp> <platformCode>\n", argv[0]);
return EXIT_FAILURE;
}
char *inputRefImageName = argv[1];
char *inputCPPFileName = argv[2];
char *inputDefImageName = argv[3];
bool useComposition = atoi(argv[4]);
// int platformCode = atoi(argv[5]);
// Read the input reference image
nifti_image *referenceImage = reg_io_ReadImageFile(inputRefImageName);
if (referenceImage == NULL) {
reg_print_msg_error("The input reference image could not be read");
return EXIT_FAILURE;
}
nifti_image *cppImage = reg_io_ReadImageFile(inputCPPFileName);
if (cppImage == NULL) {
reg_print_msg_error("The control point grid image could not be read");
return EXIT_FAILURE;
}
// Read the input deformation field image image
nifti_image *expectedDefField = reg_io_ReadImageFile(inputDefImageName);
if (expectedDefField == NULL){
reg_print_msg_error("The input deformation field image could not be read");
return EXIT_FAILURE;
}
// Check the dimension of the input images
if (referenceImage->nx != expectedDefField->nx ||
referenceImage->ny != expectedDefField->ny ||
referenceImage->nz != expectedDefField->nz ||
(referenceImage->nz > 1 ? 3 : 2) != expectedDefField->nu){
reg_print_msg_error("The input reference and deformation field images do not have corresponding sizes");
return EXIT_FAILURE;
}
// Create a deformation field
nifti_image *test_field = nifti_copy_nim_info(expectedDefField);
test_field->data = (void *)malloc(test_field->nvox*test_field->nbyper);
if(useComposition)
{
// Set the deformation to identity
reg_tools_multiplyValueToImage(test_field, test_field, 0.f);
test_field->intent_p1=DISP_FIELD;
reg_getDeformationFromDisplacement(test_field);
// Compute the deformation field throught composition
reg_spline_getDeformationField(cppImage,
test_field,
NULL,
true,
true);
}
else{
// Compute the deformation field from scratch
reg_spline_getDeformationField(cppImage,
test_field,
NULL,
false,
true);
}
// Compute the difference between the computed and expected deformation fields
nifti_image *diff_field = nifti_copy_nim_info(expectedDefField);
diff_field->data = (void *) malloc(diff_field->nvox*diff_field->nbyper);
reg_tools_substractImageToImage(expectedDefField, test_field, diff_field);
reg_tools_abs_image(diff_field);
double max_difference = reg_tools_getMaxValue(diff_field, -1);
// Delete all allocated images
nifti_image_free(referenceImage);
nifti_image_free(expectedDefField);
nifti_image_free(cppImage);
nifti_image_free(test_field);
nifti_image_free(diff_field);
// Check if the obtained difference is below a specific threshold
if (max_difference > EPS){
fprintf(stderr, "reg_test_bspline_deformation_field from blank error too large: %g (>%g)\n",
max_difference, EPS);
// return on a failed test
return EXIT_FAILURE;
}
#ifndef NDEBUG
fprintf(stdout, "reg_test_bspline_deformation_field ok 1: %g (<%g)\n",
max_difference, EPS);
#endif
// return on a successful test
return EXIT_SUCCESS;
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzNetworking/Framework/INetworking.h>
#include <AzNetworking/UdpTransport/UdpNetworkInterface.h>
#include <AzNetworking/UdpTransport/UdpConnection.h>
#include <AzNetworking/UdpTransport/DtlsSocket.h>
#include <AzNetworking/UdpTransport/UdpSocket.h>
#include <AzNetworking/Serialization/NetworkInputSerializer.h>
#include <AzNetworking/Serialization/NetworkOutputSerializer.h>
#include <AzNetworking/Framework/ICompressor.h>
#include <AzNetworking/Utilities/NetworkCommon.h>
#include <AzCore/Console/IConsole.h>
#include <AzCore/Console/ILogger.h>
#include <AzCore/Math/MathUtils.h>
namespace AzNetworking
{
#if AZ_TRAIT_USE_OPENSSL
AZ_CVAR(bool, net_UdpUseEncryption, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Enable encryption on Udp based connections");
AZ_CVAR(uint32_t, net_SslInflationOverhead, 32, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "A SSL fudge overhead value to take out of fragmented packet payloads");
#else
static const bool net_UdpUseEncryption = false;
static const uint32_t net_SslInflationOverhead = 0;
#endif
AZ_CVAR(bool, net_UdpTimeoutConnections, true, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Boolean value on whether we should timeout Udp connections");
AZ_CVAR(AZ::TimeMs, net_UdpPacketTimeSliceMs, AZ::TimeMs{ 8 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The number of milliseconds to allow for packet processing");
AZ_CVAR(uint32_t, net_UdpUnackedHeartbeats, 5, nullptr, AZ::ConsoleFunctorFlags::Null, "The number of heartbeats to attempt to send to keep a connection alive before giving up");
AZ_CVAR(AZ::TimeMs, net_UdpDefaultTimeoutMs, AZ::TimeMs{ 10 * 1000 }, nullptr, AZ::ConsoleFunctorFlags::Null, "Time in milliseconds before we timeout an idle Udp connection");
AZ_CVAR(AZ::TimeMs, net_MinPacketTimeoutMs, AZ::TimeMs{ 200 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Minimum time to wait before timing out an unacked packet");
AZ_CVAR(int32_t, net_MaxTimeoutsPerFrame, 1000, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of packet timeouts to allow to process in a single frame");
AZ_CVAR(float, net_RttFudgeScalar, 2.0f, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Scalar value to multiply computed Rtt by to determine an optimal packet timeout threshold");
AZ_CVAR(uint32_t, net_FragmentedHeaderOverhead, 32, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "A fudge overhead value to take out of fragmented packet payloads");
AZ_CVAR(bool, net_FragmentsAlwaysReliable, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether fragmented packets should be reliable by default or use their source packet's reliability type");
AZ_CVAR(AZ::CVarFixedString, net_UdpCompressor, "MultiplayerCompressor", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "UDP compressor to use."); // WARN: similar to encryption this needs to be set once and only once before creating the network interface
static uint64_t ConstructTimeoutId(ConnectionId connectionId, PacketId packetId, ReliabilityType reliability)
{
const uint64_t intConnectionId = aznumeric_cast<uint64_t>(connectionId);
const uint64_t intPacketId = aznumeric_cast<uint64_t>(packetId);
const uint64_t intReliability = (reliability == ReliabilityType::Reliable) ? 1 : 0;
const uint64_t baseTimeoutId = ((intConnectionId << 32) | intPacketId) & 0x7FFFFFFFFFFFFFFF;
return (intReliability << 63) | baseTimeoutId;
}
static void DecodeTimeoutId(uint64_t timeoutId, ConnectionId& outConnectionId, PacketId& outPacketId, ReliabilityType& outReliability)
{
outConnectionId = ConnectionId(aznumeric_cast<uint32_t>(timeoutId >> 32) & 0x7FFFFFFF);
outPacketId = PacketId(aznumeric_cast<uint32_t>(timeoutId >> 0) & 0xFFFFFFFF);
outReliability = ((timeoutId & 0x8000000000000000) > 0) ? ReliabilityType::Reliable : ReliabilityType::Unreliable;
}
UdpNetworkInterface::UdpNetworkInterface(const AZ::Name& name, IConnectionListener& connectionListener, TrustZone trustZone, UdpReaderThread& readerThread)
: m_name(name)
, m_trustZone(trustZone)
, m_connectionListener(connectionListener)
, m_socket(net_UdpUseEncryption ? new DtlsSocket() : new UdpSocket())
, m_readerThread(readerThread)
, m_timeoutMs(net_UdpDefaultTimeoutMs)
{
const AZ::CVarFixedString compressor = static_cast<AZ::CVarFixedString>(net_UdpCompressor);
m_compressor = AZ::Interface<INetworking>::Get()->CreateCompressor(compressor);
}
UdpNetworkInterface::~UdpNetworkInterface()
{
m_readerThread.UnregisterSocket(m_socket.get());
}
AZ::Name UdpNetworkInterface::GetName() const
{
return m_name;
}
ProtocolType UdpNetworkInterface::GetType() const
{
return ProtocolType::Udp;
}
TrustZone UdpNetworkInterface::GetTrustZone() const
{
return m_trustZone;
}
uint16_t UdpNetworkInterface::GetPort() const
{
return m_port;
}
IConnectionSet& UdpNetworkInterface::GetConnectionSet()
{
return m_connectionSet;
}
IConnectionListener& UdpNetworkInterface::GetConnectionListener()
{
return m_connectionListener;
}
bool UdpNetworkInterface::Listen(uint16_t port)
{
if (m_socket->IsOpen())
{
AZ_Assert(false, "Listen cannot be invoked on an already opened network interface");
return false;
}
m_port = port;
m_allowIncomingConnections = true;
if (m_socket->Open(m_port, UdpSocket::CanAcceptConnections::True, m_trustZone))
{
m_readerThread.RegisterSocket(m_socket.get());
return true;
}
else
{
return false;
}
}
ConnectionId UdpNetworkInterface::Connect(const IpAddress& remoteAddress, uint16_t localPort)
{
if (m_connectionSet.GetConnection(remoteAddress) != nullptr)
{
AZLOG_WARN("Attempting to connect to an endpoint (%s) that already has a connection", remoteAddress.GetString().c_str());
return InvalidConnectionId;
}
m_port = localPort;
if (!m_socket->IsOpen())
{
if (m_socket->Open(m_port, UdpSocket::CanAcceptConnections::False, m_trustZone))
{
m_readerThread.RegisterSocket(m_socket.get());
}
else
{
return InvalidConnectionId;
}
}
const ConnectionId connectionId = m_connectionSet.GetNextConnectionId();
const AZ::TimeMs timeoutTimeMs = m_timeoutMs / static_cast<AZ::TimeMs>(static_cast<int32_t>(net_UdpUnackedHeartbeats));
const TimeoutId timeoutId = m_connectionTimeoutQueue.RegisterItem(aznumeric_cast<uint64_t>(connectionId), timeoutTimeMs);
AZStd::unique_ptr<UdpConnection> connection = AZStd::make_unique<UdpConnection>(connectionId, remoteAddress, *this, ConnectionRole::Connector);
UdpPacketEncodingBuffer dtlsData;
m_socket->ConnectDtlsEndpoint(connection->GetDtlsEndpoint(), remoteAddress, dtlsData);
// We're initiating this connection, so go to a connecting state until we receive some kind of response so that we know it's alive and valid
connection->m_state = ConnectionState::Connecting;
connection->SetConnectionMtu(MaxUdpTransmissionUnit);
connection->SetTimeoutId(timeoutId);
// Signal the connection attempt
CorePackets::InitiateConnectionPacket connectPacket = CorePackets::InitiateConnectionPacket();
connectPacket.SetHandshakeBuffer(dtlsData);
connection->SendReliablePacket(connectPacket);
m_connectionListener.OnConnect(connection.get());
m_connectionSet.AddConnection(AZStd::move(connection));
return connectionId;
}
void UdpNetworkInterface::Update()
{
if (!m_socket->IsOpen())
{
return;
}
const AZ::TimeMs startTimeMs = AZ::GetElapsedTimeMs();
const UdpReaderThread::ReceivedPackets* packets = m_readerThread.GetReceivedPackets(m_socket.get());
if (packets == nullptr)
{
// Socket is not yet registered with the reader thread and is likely still pending, try again later
return;
}
for (uint32_t i = 0; i < packets->size(); ++i)
{
const UdpReaderThread::ReceivedPacket& packet = (*packets)[i];
const AZ::TimeMs currentTimeMs = AZ::GetElapsedTimeMs();
// Don't exceed our timeslice, even if unprocessed data remains
if ((currentTimeMs - startTimeMs) > net_UdpPacketTimeSliceMs)
{
AZLOG_WARN("Processing time exceeded, discarding %d/%d received packets", aznumeric_cast<int32_t>(packets->size() - i), aznumeric_cast<int32_t>(packets->size()));
GetMetrics().m_discardedPackets += packets->size() - i;
break;
}
UdpConnection* connection = m_connectionSet.GetConnection(packet.m_address);
if (connection == nullptr)
{
AcceptConnection(packet);
continue;
}
const DisconnectReason disconnectReason = GetDisconnectReasonForSocketResult(packet.m_receivedBytes);
if (disconnectReason != DisconnectReason::MAX)
{
connection->Disconnect(disconnectReason, TerminationEndpoint::Local);
continue;
}
const ConnectionState connectionState = connection->GetConnectionState();
if (connectionState == ConnectionState::Disconnecting || connectionState == ConnectionState::Disconnected)
{
// Skip packets from disconnected connections
continue;
}
int32_t decodedPacketSize = 0;
m_decryptBuffer.Resize(m_decryptBuffer.GetCapacity());
const uint8_t* decodedPacketData = connection->GetDtlsEndpoint().DecodePacket(*connection, packet.m_buffer, packet.m_receivedBytes, m_decryptBuffer.GetBuffer(), decodedPacketSize);
m_decryptBuffer.Resize(decodedPacketSize);
if (decodedPacketSize == 0)
{
// OpenSSL may have consumed packets during handshake negotiation
continue;
}
else if (decodedPacketSize < 0)
{
// Late unencrypted handshake packets or just random garbage can show up, discard and continue
continue;
}
connection->GetMetrics().LogPacketRecv(packet.m_receivedBytes + UdpPacketHeaderSize, currentTimeMs);
// Decode the packet flag bitset first since it's always uncompressed
UdpPacketHeader header;
{
NetworkOutputSerializer flagSerializer(decodedPacketData, decodedPacketSize);
if (!header.SerializePacketFlags(flagSerializer))
{
continue;
}
// Adjust decoded tracking to represent the payload now that we've grabbed the flags
decodedPacketData = flagSerializer.GetUnreadData();
decodedPacketSize = flagSerializer.GetUnreadSize();
GetMetrics().m_recvBytesUncompressed += flagSerializer.GetReadSize();
}
if (m_compressor && header.IsPacketFlagSet(PacketFlag::Compressed))
{
// Only the payload is compressed
if (!DecompressPacket(decodedPacketData, decodedPacketSize, m_decompressBuffer))
{
AZLOG_WARN("Failed to decompress packet!");
continue;
}
decodedPacketData = m_decompressBuffer.GetBuffer();
decodedPacketSize = static_cast<int32_t>(m_decompressBuffer.GetSize());
}
GetMetrics().m_recvBytesUncompressed += decodedPacketSize;
TimeoutQueue::TimeoutItem* timeoutItem = m_connectionTimeoutQueue.RetrieveItem(connection->GetTimeoutId());
if (timeoutItem == nullptr)
{
connection->Disconnect(DisconnectReason::Unknown, TerminationEndpoint::Local);
continue;
}
else
{
// Deserialize the packet header
NetworkOutputSerializer packetSerializer(decodedPacketData, decodedPacketSize);
ISerializer& serializer = packetSerializer; // To get the default typeinfo parameters in ISerializer
if (!serializer.Serialize(header, "Header"))
{
continue;
}
// Note that the serializer passed in here is unused for UDP
if (!connection->ProcessReceived(header, packetSerializer, packet.m_receivedBytes + UdpPacketHeaderSize, currentTimeMs))
{
continue;
}
timeoutItem->UpdateTimeoutTime(startTimeMs);
connection->m_timeoutCounter = 0;
PacketDispatchResult handledPacket = PacketDispatchResult::Failure;
if (header.GetPacketType() < aznumeric_cast<PacketType>(CorePackets::PacketType::MAX))
{
handledPacket = connection->HandleCorePacket(m_connectionListener, header, packetSerializer);
}
else
{
handledPacket = m_connectionListener.OnPacketReceived(connection, header, packetSerializer);
}
if (handledPacket == PacketDispatchResult::Success)
{
connection->UpdateHeartbeat(currentTimeMs);
if (connection->GetConnectionState() == ConnectionState::Connecting && !connection->GetDtlsEndpoint().IsConnecting())
{
// Connection is realized once a packet is received and socket handshake is verified complete
connection->m_state = ConnectionState::Connected;
}
}
else if (m_socket->IsEncrypted() && connection->GetDtlsEndpoint().IsConnecting() &&
!IsHandshakePacket(connection->GetDtlsEndpoint(), header.GetPacketType()))
{
// It's possible for one side to finish its half of the encryption handshake and start sending encrypted data
// This will appear as a SerializationError due to the incomplete encryption handshake
// If it's not an expected unencrypted type then skip it for now
continue;
}
else if (handledPacket == PacketDispatchResult::Skipped)
{
// If the result is marked as skipped then do so (i.e. if a handshake is not yet complete)
continue;
}
else if (connection->GetConnectionState() != ConnectionState::Disconnecting)
{
connection->Disconnect(DisconnectReason::StreamError, TerminationEndpoint::Local);
}
}
}
const AZ::TimeMs receiveTimeMs = AZ::GetElapsedTimeMs() - startTimeMs;
// Time out any stale client connections
m_connectionTimeoutQueue.UpdateTimeouts([this](TimeoutQueue::TimeoutItem& item) { return HandleConnectionTimeout(item); });
// Time out any packets that haven't been acked within our timeout window
m_packetTimeoutQueue.UpdateTimeouts([this](TimeoutQueue::TimeoutItem& item) { return HandlePacketTimeout(item); }, static_cast<int32_t>(net_MaxTimeoutsPerFrame));
// Delete any connections we've disconnected
for (RemovedConnection& removedConnection : m_removedConnections)
{
m_connectionListener.OnDisconnect(removedConnection.m_connection, removedConnection.m_reason, removedConnection.m_endpoint);
m_connectionSet.DeleteConnection(removedConnection.m_connection->GetConnectionId()); // Will delete the connection
}
m_removedConnections.clear();
// Update metrics
GetMetrics().m_sendPackets = m_socket->GetSentPackets();
GetMetrics().m_sendBytes = m_socket->GetSentBytes();
GetMetrics().m_sendPacketsEncrypted = m_socket->GetSentPacketsEncrypted();
GetMetrics().m_sendBytesEncryptionInflation = m_socket->GetSentBytesEncryptionInflation();
GetMetrics().m_recvTimeMs += receiveTimeMs;
GetMetrics().m_recvPackets = m_socket->GetRecvPackets();
GetMetrics().m_recvBytes = m_socket->GetRecvBytes();
GetMetrics().m_connectionCount = m_connectionSet.GetConnectionCount();
GetMetrics().m_updateTimeMs += AZ::GetElapsedTimeMs() - startTimeMs;
}
bool UdpNetworkInterface::SendReliablePacket(ConnectionId connectionId, const IPacket& packet)
{
IConnection* connection = m_connectionSet.GetConnection(connectionId);
if (connection == nullptr)
{
return false;
}
return connection->SendReliablePacket(packet);
}
PacketId UdpNetworkInterface::SendUnreliablePacket(ConnectionId connectionId, const IPacket& packet)
{
IConnection* connection = m_connectionSet.GetConnection(connectionId);
if (connection == nullptr)
{
return InvalidPacketId;
}
return connection->SendUnreliablePacket(packet);
}
bool UdpNetworkInterface::WasPacketAcked(ConnectionId connectionId, PacketId packetId)
{
IConnection* connection = m_connectionSet.GetConnection(connectionId);
if (connection == nullptr)
{
return false;
}
return connection->WasPacketAcked(packetId);
}
bool UdpNetworkInterface::StopListening()
{
if (!m_socket->IsOpen())
{
return false;
}
m_port = 0;
m_readerThread.UnregisterSocket(m_socket.get());
m_allowIncomingConnections = false;
m_socket->Close();
return true;
}
bool UdpNetworkInterface::Disconnect(ConnectionId connectionId, DisconnectReason reason)
{
IConnection* connection = m_connectionSet.GetConnection(connectionId);
if (connection == nullptr)
{
return false;
}
return connection->Disconnect(reason, TerminationEndpoint::Local);
}
void UdpNetworkInterface::SetTimeoutMs(AZ::TimeMs timeoutMs)
{
m_timeoutMs = timeoutMs;
}
AZ::TimeMs UdpNetworkInterface::GetTimeoutMs() const
{
return m_timeoutMs;
}
bool UdpNetworkInterface::IsEncrypted() const
{
return m_socket->IsEncrypted();
}
bool UdpNetworkInterface::IsOpen() const
{
return m_socket->IsOpen();
}
void UdpNetworkInterface::RegisterWithTimeoutQueue(ConnectionId connectionId, PacketId packetId, ReliabilityType reliability, const ConnectionMetrics& metrics)
{
const float avgRtt = metrics.m_connectionRtt.GetRoundTripTimeSeconds(); // Time is in seconds, timeout times are in milliseconds
const AZ::TimeMs expectedTimeoutMs = aznumeric_cast<AZ::TimeMs>(aznumeric_cast<int64_t>(avgRtt * 1000.0f * net_RttFudgeScalar));
const AZ::TimeMs packetTimeoutMs = AZStd::max<AZ::TimeMs>(expectedTimeoutMs, net_MinPacketTimeoutMs); // Consider packets lost after twice the current connection Rtt
AZLOG(NET_Debug, "Registering packetId %u with timeout %u", aznumeric_cast<uint32_t>(packetId), aznumeric_cast<uint32_t>(packetTimeoutMs));
m_packetTimeoutQueue.RegisterItem(ConstructTimeoutId(connectionId, packetId, reliability), packetTimeoutMs);
}
bool UdpNetworkInterface::DecompressPacket(const uint8_t* packetBuffer, size_t packetSize, UdpPacketEncodingBuffer& packetBufferOut) const
{
if (!m_compressor) // should probably have some compression handshake than relying on existence of compressor
{
AZLOG_ERROR("Decompress called without a compressor.");
return false;
}
AZStd::size_t uncompSize = 0;
AZStd::size_t bytesConsumed = 0;
packetBufferOut.Resize(packetBufferOut.GetCapacity());
const CompressorError compErr = m_compressor->Decompress(packetBuffer, packetSize, packetBufferOut.GetBuffer(), packetBufferOut.GetCapacity(), bytesConsumed, uncompSize);
packetBufferOut.Resize(aznumeric_cast<uint32_t>(uncompSize)); // Decompress will fail if larger than buffer size, so this cast is safe
if (compErr != CompressorError::Ok)
{
AZLOG_ERROR("Decompress failed with error %d this will lead to data read errors!", aznumeric_cast<int32_t>(compErr));
return false;
}
if (packetSize != bytesConsumed)
{
AZLOG_ERROR("Decompress must consume entire buffer [%zu != %zu]!", bytesConsumed, packetSize);
return false;
}
return true;
}
PacketId UdpNetworkInterface::SendPacket(UdpConnection& connection, const IPacket& packet, SequenceId reliableSequence)
{
AZLOG(NET_DebugPacketSend, "Sending packet type %u to remote address %s", aznumeric_cast<uint32_t>(packet.GetPacketType()), connection.GetRemoteAddress().GetString().c_str());
// The ordering inside this function is incredibly important and fragile
const IpAddress& address = connection.GetRemoteAddress();
// We don't want to compress the initial InitiateConnectionPacket, ConnectionHandshakePackets or FragmentedPackets of those two
const bool shouldCompress = packet.GetPacketType() != aznumeric_cast<PacketType>(CorePackets::PacketType::InitiateConnectionPacket);
if (address.GetAddress(ByteOrder::Host) == 0)
{
return InvalidPacketId;
}
const ReliabilityType reliabilityType = (reliableSequence == InvalidSequenceId) ? ReliabilityType::Unreliable : ReliabilityType::Reliable;
// Check if we need to fragment this packet first
// We don't ack aggregate packets that get fragmented, so we want to get this chunk out of the way before
// we start throwing PacketId's and SequenceId's into our other tracking data structures below
UdpPacketHeader header(connection.GetPacketTracker(), packet.GetPacketType(), reliableSequence);
const PacketId localPacketId = header.GetPacketId();
// If it's a reliable packet, make sure our reliable queue knows about it now because we might need to drop it if our connection is
// not set up
if (reliabilityType == ReliabilityType::Reliable)
{
if (!connection.PrepareReliablePacketForSend(localPacketId, reliableSequence, packet))
{
connection.Disconnect(DisconnectReason::ReliableQueueFull, TerminationEndpoint::Local);
}
}
// If we're still connecting, only transmit packets related to establishing connection and queue the rest for later
// This implicitly enforces that the only FragmentedPackets sent here are of ConnectionHandshakePacket
// Other large packets are simply queued before they are fragmented
if (connection.GetDtlsEndpoint().IsConnecting() && !IsHandshakePacket(connection.GetDtlsEndpoint(), packet.GetPacketType()))
{
// IMPORTANT that we register with the timeout queue here, otherwise we don't have the timer to pop for reliable packets
RegisterWithTimeoutQueue(connection.GetConnectionId(), localPacketId, reliabilityType, connection.GetMetrics());
AZLOG(
NET_DebugDtls, "Connection is still in handshake negotiation, blocking packet send for packet type %d",
(int)packet.GetPacketType());
return localPacketId;
}
UdpPacketEncodingBuffer buffer;
{
buffer.Resize(buffer.GetCapacity());
NetworkInputSerializer networkSerializer(buffer.GetBuffer(), static_cast<uint32_t>(buffer.GetCapacity()));
ISerializer& serializer = networkSerializer; // To get the default typeinfo parameters in ISerializer
if (!header.SerializePacketFlags(serializer))
{
AZLOG_ERROR("PacketId %u failed flag serialization and will not be sent", aznumeric_cast<uint32_t>(localPacketId));
return InvalidPacketId;
}
if (!serializer.Serialize(header, "Header"))
{
AZLOG_ERROR("PacketId %u failed header serialization and will not be sent", aznumeric_cast<uint32_t>(localPacketId));
return InvalidPacketId;
}
if (!serializer.Serialize(const_cast<IPacket&>(packet), "Payload"))
{
AZLOG_ERROR("PacketId %u failed payload serialization and will not be sent", aznumeric_cast<uint32_t>(localPacketId));
return InvalidPacketId;
}
buffer.Resize(serializer.GetSize());
}
uint32_t packetSize = static_cast<uint32_t>(buffer.GetSize());
uint8_t* packetData = buffer.GetBuffer();
// If the packet doesn't fit within our MTU (minus potential SSL encryption overhead), break it up
if (packetSize > connection.GetConnectionMtu() - net_SslInflationOverhead)
{
// Each fragmented packet we send adds an extra fragmented packet header, need to deduct that from our chunk size, otherwise we infinitely loop
// SSL encryption can also inflate our payload so we pre-emptively deduct an estimated tax
const uint32_t chunkSize = connection.GetConnectionMtu() - net_FragmentedHeaderOverhead - net_SslInflationOverhead;
const uint32_t numChunks = AZ::DivideAndRoundUp(packetSize, chunkSize); // We want to round up on the remainder
const uint8_t* chunkStart = packetData;
const SequenceId fragmentedSequence = connection.m_fragmentQueue.GetNextFragmentedSequenceId();
uint32_t bytesRemaining = packetSize;
ChunkBuffer chunkBuffer;
for (uint32_t chunkIndex = 0; chunkIndex < numChunks; ++chunkIndex)
{
const uint32_t nextChunkSize = AZStd::min(bytesRemaining, chunkSize);
chunkBuffer.CopyValues(chunkStart, nextChunkSize);
CorePackets::FragmentedPacket fragmentedPacket(ToSequenceId(localPacketId), fragmentedSequence, aznumeric_cast<uint8_t>(chunkIndex), aznumeric_cast<uint8_t>(numChunks), chunkBuffer);
const SequenceId chunkReliableId = (net_FragmentsAlwaysReliable || reliabilityType == ReliabilityType::Reliable)
? connection.m_reliableQueue.GetNextSequenceId()
: InvalidSequenceId;
SendPacket(connection, fragmentedPacket, chunkReliableId);
bytesRemaining -= nextChunkSize;
chunkStart += nextChunkSize;
}
AZ_Assert(bytesRemaining == 0, "Non-zero bytes remaining (%u) after chunking a packet into fragments", bytesRemaining);
return localPacketId;
}
UdpPacketEncodingBuffer writeBuffer;
if (m_compressor && shouldCompress)
{
NetworkInputSerializer flagSerializer(writeBuffer.GetBuffer(), static_cast<uint32_t>(writeBuffer.GetCapacity()));
ISerializer& serializer = flagSerializer; // To get the default typeinfo parameters in ISerializer
header.SetPacketFlag(PacketFlag::Compressed, true);
if (!header.SerializePacketFlags(serializer))
{
AZLOG_ERROR("PacketId %u failed flag serialization for compression and will not be sent", aznumeric_cast<uint32_t>(localPacketId));
return InvalidPacketId;
}
uint32_t flagSize = flagSerializer.GetSize();
AZ_Assert(flagSize == 1, "Flag bitfield should serialize to one byte");
// Compress the packet, make sure to offset by the size of the flag which is now serialized
const uint32_t payloadSize = static_cast<uint32_t>(buffer.GetSize() - flagSize);
uint8_t* payload = buffer.GetBuffer() + flagSize;
const AZStd::size_t maxSizeNeeded = m_compressor->GetMaxCompressedBufferSize(payloadSize);
AZStd::size_t compressionMemBytesUsed = 0;
CompressorError compErr = m_compressor->Compress(payload, payloadSize, writeBuffer.GetBuffer() + flagSize, maxSizeNeeded, compressionMemBytesUsed);
if (compErr != CompressorError::Ok)
{
AZLOG_ERROR("Failed to compress packet with error %d", aznumeric_cast<int32_t>(compErr));
return InvalidPacketId;
}
// Only use compression if there's actual gain
if (compressionMemBytesUsed < payloadSize)
{
writeBuffer.Resize(aznumeric_cast<int32_t>(flagSize + compressionMemBytesUsed));
packetSize = static_cast<uint32_t>(writeBuffer.GetSize());
packetData = writeBuffer.GetBuffer();
// Track byte delta caused by compression
GetMetrics().m_sendBytesCompressedDelta += (packetSize - compressionMemBytesUsed);
}
}
AZLOG(NET_Debug, "Sending local sequence id %d, remote sequence id %d, %s, reliable id: %d, ack vector %x",
aznumeric_cast<int32_t>(header.GetLocalSequenceId()),
aznumeric_cast<int32_t>(header.GetRemoteSequenceId()),
header.GetIsReliable() ? "reliable" : "unreliable",
aznumeric_cast<int32_t>(header.GetReliableSequenceId()),
aznumeric_cast<uint32_t>(header.GetSequenceWindow())
);
AZLOG(NET_DebugDtls, "Connection is sending packet type %d", aznumeric_cast<int32_t>(packet.GetPacketType()));
// If we're not connected then we're still handshaking and require packets to be unencrypted
const bool shouldEncrypt = !IsHandshakePacket(connection.GetDtlsEndpoint(), packet.GetPacketType());
if (m_socket->Send(address, packetData, packetSize, shouldEncrypt, connection.GetDtlsEndpoint(), connection.GetConnectionQuality()))
{
RegisterWithTimeoutQueue(connection.GetConnectionId(), localPacketId, reliabilityType, connection.GetMetrics());
connection.ProcessSent(localPacketId, packet, packetSize + UdpPacketHeaderSize, reliabilityType);
GetMetrics().m_sendBytesUncompressed += buffer.GetSize() + UdpPacketHeaderSize + (shouldEncrypt ? DtlsPacketHeaderSize : 0);
return localPacketId;
}
else
{
AZLOG_ERROR("PacketId %u failed to send on the socket", aznumeric_cast<uint32_t>(localPacketId));
}
return InvalidPacketId;
}
void UdpNetworkInterface::AcceptConnection(const UdpReaderThread::ReceivedPacket& connectPacket)
{
if (!m_allowIncomingConnections)
{
// This network interface is not set to allow incoming connections
return;
}
CorePackets::InitiateConnectionPacket packet;
{
NetworkOutputSerializer networkSerializer(connectPacket.m_buffer, connectPacket.m_receivedBytes);
// First, serialize out the header
UdpPacketHeader header;
if (!header.SerializePacketFlags(networkSerializer))
{
return;
}
if (!static_cast<ISerializer&>(networkSerializer).Serialize(header, "Header"))
{
return;
}
// Validate that this is really an InitiateConnection packet
if (header.GetPacketType() != aznumeric_cast<PacketType>(CorePackets::PacketType::InitiateConnectionPacket))
{
return;
}
// Next serialize the InitiateConnectionPacket itself
{
NetworkOutputSerializer tempPacketSerializer(networkSerializer.GetUnreadData(), networkSerializer.GetUnreadSize());
if (!static_cast<ISerializer&>(tempPacketSerializer).Serialize(packet, "Packet"))
{
return;
}
}
// Retrieve the connection type, and run application layer connection filtering (state checks, CIDR address filtering, etc..)
const ConnectResult connectResult = m_connectionListener.ValidateConnect(connectPacket.m_address, header, networkSerializer);
switch (connectResult)
{
case ConnectResult::Rejected:
return; // Failed validation, simply discard the connect message
case ConnectResult::Accepted:
break; // This is not actually an expected return from this code path, assume it's a client connection
}
}
// We've passed all our security checks, so now we're free to allocate memory and track the new connection
// How long should we sit in the timeout queue before heartbeating or disconnecting
const ConnectionId connectionId = m_connectionSet.GetNextConnectionId();
const TimeoutId timeoutId = m_connectionTimeoutQueue.RegisterItem(aznumeric_cast<uint64_t>(connectionId), m_timeoutMs);
AZLOG(Debug_UdpConnect, "Accepted new Udp Connection");
AZStd::unique_ptr<UdpConnection> connection = AZStd::make_unique<UdpConnection>(connectionId, connectPacket.m_address, *this, ConnectionRole::Acceptor);
DtlsEndpoint::ConnectResult result = m_socket->AcceptDtlsEndpoint(connection->GetDtlsEndpoint(), connectPacket.m_address);
// Transition state based on our how our socket resolved
connection->m_state = result == DtlsEndpoint::ConnectResult::Complete ? ConnectionState::Connected : ConnectionState::Connecting;
connection->SetTimeoutId(timeoutId);
m_connectionListener.OnConnect(connection.get());
m_connectionSet.AddConnection(AZStd::move(connection));
}
void UdpNetworkInterface::RequestDisconnect(UdpConnection* connection, DisconnectReason reason, TerminationEndpoint endpoint)
{
if (connection == nullptr)
{
return;
}
connection->m_state = ConnectionState::Disconnecting;
m_removedConnections.emplace_back(RemovedConnection{ connection, reason, endpoint });
}
bool UdpNetworkInterface::IsHandshakePacket(const DtlsEndpoint& endpoint, PacketType packetType) const
{
// Packets involved in handshake are InitiateConnection, ConnectionHandshake and FragmentedPackets of ConnectionHandshake
return packetType == aznumeric_cast<PacketType>(CorePackets::PacketType::InitiateConnectionPacket) ||
packetType == aznumeric_cast<PacketType>(CorePackets::PacketType::ConnectionHandshakePacket) ||
(packetType == aznumeric_cast<PacketType>(CorePackets::PacketType::FragmentedPacket) && endpoint.IsConnecting());
}
TimeoutResult UdpNetworkInterface::HandleConnectionTimeout(TimeoutQueue::TimeoutItem& item)
{
const ConnectionId connectionId = ConnectionId(aznumeric_cast<uint32_t>(item.m_userData));
UdpConnection* udpConnection = static_cast<UdpConnection*>(m_connectionSet.GetConnection(connectionId));
if (udpConnection == nullptr)
{
// We've already deleted this connection
return TimeoutResult::Delete;
}
if ((udpConnection->GetConnectionState() == ConnectionState::Connecting)
&& udpConnection->GetDtlsEndpoint().IsConnecting())
{
// DTLS prefers we resend data lost over the wire with fresh SSL IDs so account for that here
UdpPacketEncodingBuffer dtlsData;
udpConnection->ProcessHandshakeData(dtlsData);
return TimeoutResult::Refresh;
}
if ((udpConnection->GetConnectionRole() == ConnectionRole::Connector)
&& (udpConnection->m_timeoutCounter < net_UdpUnackedHeartbeats))
{
// Set the request response flag to true since we want a response to keep the connection alive
udpConnection->SendUnreliablePacket(CorePackets::HeartbeatPacket(true));
++udpConnection->m_timeoutCounter;
}
else if (net_UdpTimeoutConnections && (GetTimeoutMs() > AZ::Time::ZeroTimeMs))
{
udpConnection->Disconnect(DisconnectReason::Timeout, TerminationEndpoint::Local);
return TimeoutResult::Delete;
}
return TimeoutResult::Refresh;
}
TimeoutResult UdpNetworkInterface::HandlePacketTimeout(TimeoutQueue::TimeoutItem& item)
{
ConnectionId connectionId;
PacketId packetId;
ReliabilityType reliability;
DecodeTimeoutId(item.m_userData, connectionId, packetId, reliability);
UdpConnection* connection = static_cast<UdpConnection*>(m_connectionSet.GetConnection(connectionId));
if (connection == nullptr)
{
AZLOG(NET_Debug, "Failed to look up connection for timed out packetId %u", aznumeric_cast<uint32_t>(packetId));
return TimeoutResult::Delete;
}
const PacketTimeoutResult result = connection->ProcessTimeout(packetId, reliability);
AZLOG(NET_Debug, "Timeout triggered for packetId %u with result %s", aznumeric_cast<uint32_t>(packetId), GetEnumString(result));
switch (result)
{
case PacketTimeoutResult::Acked:
// Packet was already acked, just discard this timeout entry
return TimeoutResult::Delete;
case PacketTimeoutResult::Pending:
// Packet timed out before we received any info about it's sequence from the remote endpoint
// The connection latency may have increased, and our Rtt metrics may still be adjusting..
// Just throw it back into the timeout queue
return TimeoutResult::Refresh;
case PacketTimeoutResult::Lost:
// Packet timed out and was not acked, so we consider it lost
m_connectionListener.OnPacketLost(connection, packetId);
break;
}
return TimeoutResult::Delete;
}
}
|
/*
Copyright 2019 Xilinx 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 "target.pb.h"
namespace vitis {
namespace ai {
const Target create_target_v2(const std::uint64_t fingerprint) {
Target target;
target.set_name("DPUCZDX8G_CUSTOMIZED");
target.set_type("DPUCZDX8G");
target.set_isa_version((fingerprint & 0x00ff000000000000) >> 48);
target.set_feature_code(fingerprint & 0x0000ffffffffffff);
constexpr std::array<uint64_t, 11> PP_MAP{4, 4, 8, 4, 8, 8, 8, 8, 4, 2, 2};
constexpr std::array<uint64_t, 11> ICP_MAP{8, 10, 8, 12, 10, 12,
14, 16, 4, 6, 8};
constexpr std::array<uint64_t, 11> OCP_MAP{8, 10, 8, 12, 10, 12,
14, 16, 4, 6, 8};
auto ARCH = fingerprint & 0xf;
auto PP = PP_MAP[ARCH];
auto ICP = ICP_MAP[ARCH];
auto OCP = OCP_MAP[ARCH];
auto PL_PP = (fingerprint & 0xf00) >> 8;
auto DW_PP = (fingerprint & 0xf000) >> 12;
auto EL_PP = (fingerprint & 0xf0000) >> 16;
auto IMG_BG = (fingerprint & 0x3000000) >> 24;
auto LD_AUGM = (fingerprint & 0x4000000) >> 26;
// auto LD_MEAN = (fingerprint & 0x8000000) >> 27;
auto CV_LKRL = (fingerprint & 0x10000000) >> 28;
auto CV_RL6 = (fingerprint & 0x20000000) >> 29;
auto PL_AVG = (fingerprint & 0x40000000) >> 30;
auto DW_RL6 = (fingerprint & 0x80000000) >> 31;
auto EL_MULT = (fingerprint & 0x1000000000) >> 36;
auto PL_DSM = (fingerprint & 0x2000000000) >> 37;
auto base_id = 0U;
for (auto idx = 0U; idx < IMG_BG; idx++) {
auto img_bank_group = target.add_bank_group();
img_bank_group->set_name("VB" + std::to_string(idx));
img_bank_group->set_type("Virtual");
img_bank_group->set_base_id(base_id);
img_bank_group->set_bank_num(PP);
img_bank_group->set_bank_width(ICP);
img_bank_group->set_bank_depth(2048);
base_id += PP;
}
auto convw_bank_group = target.add_bank_group();
convw_bank_group->set_name("CONVW");
convw_bank_group->set_type("Param");
convw_bank_group->set_base_id(base_id);
convw_bank_group->set_bank_num(OCP);
convw_bank_group->set_bank_width(ICP);
convw_bank_group->set_bank_depth(2048);
base_id += OCP;
if (DW_PP) {
auto dwconvw_bank_group = target.add_bank_group();
dwconvw_bank_group->set_name("DWCONVW");
dwconvw_bank_group->set_type("Param");
dwconvw_bank_group->set_base_id(base_id);
dwconvw_bank_group->set_bank_num(1);
dwconvw_bank_group->set_bank_width(ICP);
dwconvw_bank_group->set_bank_depth(2048);
base_id += 1;
}
auto bias_bank_group = target.add_bank_group();
bias_bank_group->set_name("BIAS");
bias_bank_group->set_type("Param");
bias_bank_group->set_base_id(base_id);
bias_bank_group->set_bank_num(1);
bias_bank_group->set_bank_width(ICP);
bias_bank_group->set_bank_depth(2048);
base_id += 1;
auto load_engine = target.mutable_load_engine();
load_engine->set_channel_parallel(ICP);
for (auto idx = 0U; idx < IMG_BG; idx++) {
load_engine->add_output_bank("VB" + std::to_string(idx));
}
auto save_engine = target.mutable_save_engine();
save_engine->set_channel_parallel(ICP);
for (auto idx = 0U; idx < IMG_BG; idx++) {
save_engine->add_input_bank("VB" + std::to_string(idx));
}
auto conv_engine = target.mutable_conv_engine();
conv_engine->set_input_channel_parallel(ICP);
conv_engine->set_output_channel_parallel(OCP);
conv_engine->set_pixel_parallel(PP);
for (auto idx = 0U; idx < IMG_BG; idx++) {
conv_engine->add_input_bank("VB" + std::to_string(idx));
conv_engine->add_output_bank("VB" + std::to_string(idx));
}
conv_engine->set_weight_bank("CONVW");
conv_engine->set_bias_bank("BIAS");
if (LD_AUGM) {
conv_engine->mutable_channel_augmentation()->set_channel_num(ICP * 2);
}
auto conv_nonlinear = conv_engine->mutable_nonlinear();
conv_nonlinear->add_nonlinear_type(Target::Nonlinear::relu);
if (CV_LKRL) {
conv_nonlinear->add_nonlinear_type(Target::Nonlinear::leaky_relu);
}
if (CV_RL6) {
conv_nonlinear->add_nonlinear_type(Target::Nonlinear::relu_six);
}
auto conv_limit = conv_engine->mutable_conv_limit();
conv_limit->set_kernel_size("1-16");
conv_limit->set_stride("1-8");
auto eltwise_engine = target.mutable_eltwise_engine();
eltwise_engine->set_channel_parallel(ICP);
eltwise_engine->set_pixel_parallel(EL_PP);
for (auto idx = 0U; idx < IMG_BG; idx++) {
eltwise_engine->add_input_bank("VB" + std::to_string(idx));
eltwise_engine->add_output_bank("VB" + std::to_string(idx));
}
auto eltwise_nonlinear = eltwise_engine->mutable_nonlinear();
eltwise_nonlinear->add_nonlinear_type(Target::Nonlinear::relu);
eltwise_engine->add_elew_type(Target::Eltwise::add);
if (EL_MULT) {
eltwise_engine->add_elew_type(Target::Eltwise::mult);
}
auto pool_engine = target.mutable_pool_engine();
pool_engine->set_channel_parallel(ICP);
pool_engine->set_pixel_parallel(PL_PP);
for (auto idx = 0U; idx < IMG_BG; idx++) {
pool_engine->add_input_bank("VB" + std::to_string(idx));
pool_engine->add_output_bank("VB" + std::to_string(idx));
}
auto pool_nonlinear = pool_engine->mutable_nonlinear();
pool_nonlinear->add_nonlinear_type(Target::Nonlinear::relu);
pool_engine->add_pool_type(Target::Pool::max);
auto max_limit = pool_engine->mutable_max_limit();
max_limit->set_kernel_size("1-8");
max_limit->set_stride("1-8");
if (PL_AVG) {
pool_engine->add_pool_type(Target::Pool::avg);
auto avg_limit = pool_engine->mutable_avg_limit();
avg_limit->set_kernel_size("2-8");
avg_limit->set_stride("1-8");
}
if (PL_DSM) {
pool_engine->add_pool_type(Target::Pool::max_reduce);
}
if (DW_PP) {
auto dwconv_engine = target.mutable_dwconv_engine();
dwconv_engine->set_channel_parallel(ICP);
dwconv_engine->set_pixel_parallel(DW_PP);
for (auto idx = 0U; idx < IMG_BG; idx++) {
dwconv_engine->add_input_bank("VB" + std::to_string(idx));
dwconv_engine->add_output_bank("VB" + std::to_string(idx));
}
dwconv_engine->set_weight_bank("DWCONVW");
dwconv_engine->set_bias_bank("BIAS");
auto dwconv_nonlinear = dwconv_engine->mutable_nonlinear();
dwconv_nonlinear->add_nonlinear_type(Target::Nonlinear::relu);
if (DW_RL6) {
dwconv_nonlinear->add_nonlinear_type(Target::Nonlinear::relu_six);
}
auto dwconv_limit = dwconv_engine->mutable_dwconv_limit();
dwconv_limit->set_kernel_size("1-16");
dwconv_limit->set_stride("1-8");
}
return target;
}
} // namespace ai
} // namespace vitis
|
#include "stdafx.h"
#include "LightObject.h"
LightObject::LightObject(ID3D11Device* pDevice, std::string& filename)
:Model(pDevice, filename)
{
}
LightObject::~LightObject()
{
}
|
#include<iostream>
#include<math.h>
using namespace std;
int main(void){
float coeficientes[3],delta,x1,x2;
int i;
for(i=0;i<3;i++){
cout<<"Digite os coeficientes: ";
cin>>coeficientes[i];
}
cout<<"\n";
delta = (pow(coeficientes[1],2)) - (4*coeficientes[0]*coeficientes[2]);
if(coeficientes[0] != 0 && delta >= 0){
x1 = (-coeficientes[1] + (sqrt(delta)) ) / (2*coeficientes[0]);
x2 = (-coeficientes[1] - (sqrt(delta)) ) / (2*coeficientes[0]);
cout<<"X1: "<<x1;
cout<<"\n";
cout<<"X2: "<<x2;
}else{
cout<<"Impossivel calcular";
}
}
|
//===-- MipsSubtarget.cpp - Mips Subtarget Information --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Mips specific subclass of TargetSubtargetInfo.
//
//===----------------------------------------------------------------------===//
#include "MipsSubtarget.h"
#include "Mips.h"
#include "MipsMachineFunction.h"
#include "MipsRegisterInfo.h"
#include "MipsTargetMachine.h"
#include "MipsCallLowering.h"
#include "MipsLegalizerInfo.h"
#include "MipsRegisterBankInfo.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "mips-subtarget"
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "MipsGenSubtargetInfo.inc"
// FIXME: Maybe this should be on by default when Mips16 is specified
//
static cl::opt<bool>
Mixed16_32("mips-mixed-16-32", cl::init(false),
cl::desc("Allow for a mixture of Mips16 "
"and Mips32 code in a single output file"),
cl::Hidden);
static cl::opt<bool> Mips_Os16("mips-os16", cl::init(false),
cl::desc("Compile all functions that don't use "
"floating point as Mips 16"),
cl::Hidden);
static cl::opt<bool> Mips16HardFloat("mips16-hard-float", cl::NotHidden,
cl::desc("Enable mips16 hard float."),
cl::init(false));
static cl::opt<bool>
Mips16ConstantIslands("mips16-constant-islands", cl::NotHidden,
cl::desc("Enable mips16 constant islands."),
cl::init(true));
static cl::opt<bool>
GPOpt("mgpopt", cl::Hidden,
cl::desc("Enable gp-relative addressing of mips small data items"));
bool MipsSubtarget::DspWarningPrinted = false;
bool MipsSubtarget::MSAWarningPrinted = false;
void MipsSubtarget::anchor() {}
MipsSubtarget::MipsSubtarget(const Triple &TT, StringRef CPU, StringRef FS,
bool little, const MipsTargetMachine &TM,
unsigned StackAlignOverride)
: MipsGenSubtargetInfo(TT, CPU, FS), MipsArchVersion(MipsDefault),
IsLittle(little), IsSoftFloat(false), IsSingleFloat(false), IsFPXX(false),
NoABICalls(false), IsFP64bit(false), UseOddSPReg(true),
IsNaN2008bit(false), IsGP64bit(false), HasVFPU(false), HasCnMips(false),
HasMips3_32(false), HasMips3_32r2(false), HasMips4_32(false),
HasMips4_32r2(false), HasMips5_32r2(false), InMips16Mode(false),
InMips16HardFloat(Mips16HardFloat), InMicroMipsMode(false), HasDSP(false),
HasDSPR2(false), HasDSPR3(false), AllowMixed16_32(Mixed16_32 | Mips_Os16),
Os16(Mips_Os16), HasMSA(false), UseTCCInDIV(false), HasSym32(false),
HasEVA(false), DisableMadd4(false), HasMT(false), HasCRC(false),
HasVirt(false), HasGINV(false), UseIndirectJumpsHazard(false),
StackAlignOverride(StackAlignOverride),
TM(TM), TargetTriple(TT), TSInfo(),
InstrInfo(
MipsInstrInfo::create(initializeSubtargetDependencies(CPU, FS, TM))),
FrameLowering(MipsFrameLowering::create(*this)),
TLInfo(MipsTargetLowering::create(TM, *this)) {
if (MipsArchVersion == MipsDefault)
MipsArchVersion = Mips32;
// Don't even attempt to generate code for MIPS-I and MIPS-V. They have not
// been tested and currently exist for the integrated assembler only.
if (MipsArchVersion == Mips1)
report_fatal_error("Code generation for MIPS-I is not implemented", false);
if (MipsArchVersion == Mips5)
report_fatal_error("Code generation for MIPS-V is not implemented", false);
// Check if Architecture and ABI are compatible.
assert(((!isGP64bit() && isABI_O32()) ||
(isGP64bit() && (isABI_N32() || isABI_N64()))) &&
"Invalid Arch & ABI pair.");
if (hasMSA() && !isFP64bit())
report_fatal_error("MSA requires a 64-bit FPU register file (FR=1 mode). "
"See -mattr=+fp64.",
false);
if (!isABI_O32() && !useOddSPReg())
report_fatal_error("-mattr=+nooddspreg requires the O32 ABI.", false);
if (IsFPXX && (isABI_N32() || isABI_N64()))
report_fatal_error("FPXX is not permitted for the N32/N64 ABI's.", false);
if (hasMips64r6() && InMicroMipsMode)
report_fatal_error("microMIPS64R6 is not supported", false);
if (UseIndirectJumpsHazard) {
if (InMicroMipsMode)
report_fatal_error(
"cannot combine indirect jumps with hazard barriers and microMIPS");
if (!hasMips32r2())
report_fatal_error(
"indirect jumps with hazard barriers requires MIPS32R2 or later");
}
if (hasMips32r6()) {
StringRef ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
assert(isFP64bit());
assert(isNaN2008());
if (hasDSP())
report_fatal_error(ISA + " is not compatible with the DSP ASE", false);
}
if (NoABICalls && TM.isPositionIndependent())
report_fatal_error("position-independent code requires '-mabicalls'");
if (isABI_N64() && !TM.isPositionIndependent() && !hasSym32())
NoABICalls = true;
// Set UseSmallSection.
UseSmallSection = GPOpt;
if (!NoABICalls && GPOpt) {
errs() << "warning: cannot use small-data accesses for '-mabicalls'"
<< "\n";
UseSmallSection = false;
}
if (hasDSPR2() && !DspWarningPrinted) {
if (hasMips64() && !hasMips64r2()) {
errs() << "warning: the 'dspr2' ASE requires MIPS64 revision 2 or "
<< "greater\n";
DspWarningPrinted = true;
} else if (hasMips32() && !hasMips32r2()) {
errs() << "warning: the 'dspr2' ASE requires MIPS32 revision 2 or "
<< "greater\n";
DspWarningPrinted = true;
}
} else if (hasDSP() && !DspWarningPrinted) {
if (hasMips64() && !hasMips64r2()) {
errs() << "warning: the 'dsp' ASE requires MIPS64 revision 2 or "
<< "greater\n";
DspWarningPrinted = true;
} else if (hasMips32() && !hasMips32r2()) {
errs() << "warning: the 'dsp' ASE requires MIPS32 revision 2 or "
<< "greater\n";
DspWarningPrinted = true;
}
}
if (hasMSA() && !MSAWarningPrinted) {
if (hasMips64() && !hasMips64r5()) {
errs() << "warning: the 'msa' ASE requires MIPS64 revision 5 or "
<< "greater\n";
MSAWarningPrinted = true;
} else if (hasMips32() && !hasMips32r5()) {
errs() << "warning: the 'msa' ASE requires MIPS32 revision 5 or "
<< "greater\n";
MSAWarningPrinted = true;
}
}
CallLoweringInfo.reset(new MipsCallLowering(*getTargetLowering()));
Legalizer.reset(new MipsLegalizerInfo(*this));
auto *RBI = new MipsRegisterBankInfo(*getRegisterInfo());
RegBankInfo.reset(RBI);
InstSelector.reset(createMipsInstructionSelector(
*static_cast<const MipsTargetMachine *>(&TM), *this, *RBI));
}
bool MipsSubtarget::isPositionIndependent() const {
return TM.isPositionIndependent();
}
/// This overrides the PostRAScheduler bit in the SchedModel for any CPU.
bool MipsSubtarget::enablePostRAScheduler() const { return true; }
void MipsSubtarget::getCriticalPathRCs(RegClassVector &CriticalPathRCs) const {
CriticalPathRCs.clear();
CriticalPathRCs.push_back(isGP64bit() ? &Mips::GPR64RegClass
: &Mips::GPR32RegClass);
}
CodeGenOpt::Level MipsSubtarget::getOptLevelToEnablePostRAScheduler() const {
return CodeGenOpt::Aggressive;
}
MipsSubtarget &
MipsSubtarget::initializeSubtargetDependencies(StringRef CPU, StringRef FS,
const TargetMachine &TM) {
std::string CPUName = MIPS_MC::selectMipsCPU(TM.getTargetTriple(), CPU);
// Parse features string.
ParseSubtargetFeatures(CPUName, FS);
// Initialize scheduling itinerary for the specified CPU.
InstrItins = getInstrItineraryForCPU(CPUName);
if (InMips16Mode && !IsSoftFloat)
InMips16HardFloat = true;
if (StackAlignOverride)
stackAlignment = StackAlignOverride;
else if (isABI_N32() || isABI_N64())
stackAlignment = 16;
else {
assert(isABI_O32() && "Unknown ABI for stack alignment!");
stackAlignment = 8;
}
return *this;
}
bool MipsSubtarget::useConstantIslands() {
LLVM_DEBUG(dbgs() << "use constant islands " << Mips16ConstantIslands
<< "\n");
return Mips16ConstantIslands;
}
Reloc::Model MipsSubtarget::getRelocationModel() const {
return TM.getRelocationModel();
}
bool MipsSubtarget::isABI_N64() const { return getABI().IsN64(); }
bool MipsSubtarget::isABI_N32() const { return getABI().IsN32(); }
bool MipsSubtarget::isABI_O32() const { return getABI().IsO32(); }
const MipsABIInfo &MipsSubtarget::getABI() const { return TM.getABI(); }
const CallLowering *MipsSubtarget::getCallLowering() const {
return CallLoweringInfo.get();
}
const LegalizerInfo *MipsSubtarget::getLegalizerInfo() const {
return Legalizer.get();
}
const RegisterBankInfo *MipsSubtarget::getRegBankInfo() const {
return RegBankInfo.get();
}
const InstructionSelector *MipsSubtarget::getInstructionSelector() const {
return InstSelector.get();
}
|
// Copyright (c) 2020, The MKEcoin Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string.h>
#include "misc_log_ex.h"
#include "int-util.h"
#include "crypto/crypto.h"
#include "common/util.h"
#include "merge_mining.h"
using namespace epee;
#undef MKEcoin_DEFAULT_LOG_CATEGORY
#define MKEcoin_DEFAULT_LOG_CATEGORY "cn.mm"
using namespace crypto;
namespace cryptonote
{
//---------------------------------------------------------------
uint32_t get_aux_slot(const crypto::hash &id, uint32_t nonce, uint32_t n_aux_chains)
{
CHECK_AND_ASSERT_THROW_MES(n_aux_chains > 0, "n_aux_chains is 0");
uint8_t buf[HASH_SIZE + sizeof(uint32_t) + 1];
memcpy(buf, &id, HASH_SIZE);
uint32_t v = SWAP32LE(nonce);
memcpy(buf + HASH_SIZE, &v, sizeof(uint32_t));
buf[HASH_SIZE + sizeof(uint32_t)] = config::HASH_KEY_MM_SLOT;
crypto::hash res;
tools::sha256sum(buf, sizeof(buf), res);
v = *((const uint32_t*)&res);
return SWAP32LE(v) % n_aux_chains;
}
//---------------------------------------------------------------
uint32_t get_path_from_aux_slot(uint32_t slot, uint32_t n_aux_chains)
{
CHECK_AND_ASSERT_THROW_MES(n_aux_chains > 0, "n_aux_chains is 0");
CHECK_AND_ASSERT_THROW_MES(slot < n_aux_chains, "slot >= n_aux_chains");
uint32_t path = 0;
CHECK_AND_ASSERT_THROW_MES(tree_path(n_aux_chains, slot, &path), "Failed to get path from aux slot");
return path;
}
//---------------------------------------------------------------
uint32_t encode_mm_depth(uint32_t n_aux_chains, uint32_t nonce)
{
CHECK_AND_ASSERT_THROW_MES(n_aux_chains > 0, "n_aux_chains is 0");
// how many bits to we need to representing n_aux_chains - 1
uint32_t n_bits = 1;
while ((1u << n_bits) < n_aux_chains && n_bits < 16)
++n_bits;
CHECK_AND_ASSERT_THROW_MES(n_bits <= 16, "Way too many bits required");
const uint32_t depth = (n_bits - 1) | ((n_aux_chains - 1) << 3) | (nonce << (3 + n_bits));
return depth;
}
//---------------------------------------------------------------
bool decode_mm_depth(uint32_t depth, uint32_t &n_aux_chains, uint32_t &nonce)
{
const uint32_t n_bits = 1 + (depth & 7);
n_aux_chains = 1 + (depth >> 3 & ((1 << n_bits) - 1));
nonce = depth >> (3 + n_bits);
return true;
}
//---------------------------------------------------------------
}
|
#include "Boundary.h"
#include <iostream>
#include <fstream>
using namespace std;
extern float* Ez;
extern float *E_nbd_up, *E_nbd_down, *E_nbd_right, *E_nbd_left;
extern float *E_bd_up, *E_bd_down, *E_bd_right, *E_bd_left;
extern int Nx;
extern float dt, dz, coe_MUR;
const float C = 3e8f;
void Bd_proc_up();
void Bd_proc_down();
void Bd_proc_left_right();
void Bd_proc_point();
void Boundary_Init()
{
int i;
E_bd_left = (float *)malloc((Nx-1)*sizeof(float));
memset(E_bd_left, 0, (Nx - 1)*sizeof(float));
E_bd_right = (float *)malloc((Nx-1)*sizeof(float));
memset(E_bd_right, 0, (Nx - 1)*sizeof(float));
E_bd_up = (float *)malloc((Nx-1)*sizeof(float));
memset(E_bd_up, 0, (Nx - 1)*sizeof(float));
E_bd_down = (float *)malloc((Nx-1)*sizeof(float));
memset(E_bd_down, 0, (Nx - 1)*sizeof(float));
E_nbd_left = (float *)malloc((Nx-1)*sizeof(float));
memset(E_nbd_left, 0, (Nx - 1)*sizeof(float));
E_nbd_right = (float *)malloc((Nx-1)*sizeof(float));
memset(E_nbd_right, 0, (Nx - 1)*sizeof(float));
E_nbd_up = (float *)malloc((Nx-1)*sizeof(float));
memset(E_nbd_up, 0, (Nx-1)*sizeof(float));
/*for (i = 0; i < Nx - 1; i++){
cout << "E_nbd_up[" << i << "]= " << E_nbd_up[i] << endl;
}*/
E_nbd_down = (float *)malloc((Nx-1)*sizeof(float));
memset(E_nbd_down, 0, (Nx - 1)*sizeof(float));
coe_MUR = (C*dt - dz) / (C*dt + dz);
}
void Boundary_cmp_PEC()
{
int i, j;
for (i = 0; i < Nx + 1;i++){
if (i == 0 || i == Nx){
for (j = 0; j < Nx + 1; j++){
Ez[i*(Nx+1) + j] = 0.f;
}
}
else{
Ez[i*(Nx+1) + 0] = 0.f;
Ez[i*(Nx+1) + Nx] = 0.f;
}
}
}
void Boundary_MUR1()
{
Bd_proc_up();
Bd_proc_down();
Bd_proc_left_right();
Bd_proc_point();
}
void Bd_proc_up()
{
int j;
for (j = 1; j < Nx; j++){
//E(0,j)=Enb(j-1)+c*(E(1,j)-Eb(j-1))
Ez[j] = E_nbd_up[j - 1] + coe_MUR*(Ez[Nx + 1 + j] - E_bd_up[j - 1]);
//cout << "Ez["<<j <<"]= " << Ez[j] << endl;
E_nbd_up[j - 1] = Ez[Nx + 1 + j];
E_bd_up[j - 1] = Ez[j];
}
}
void Bd_proc_down()
{
int j;
for (j = 1; j < Nx; j++){
//E(Nx,j)=Enb(j-1)+c*(E(Nx-1,j)-Eb(j-1))
Ez[Nx*(Nx + 1) + j] = E_nbd_down[j - 1] + coe_MUR*(Ez[(Nx - 1)*(Nx + 1) + j] - E_bd_down[j - 1]);
E_nbd_down[j - 1] = Ez[(Nx - 1)*(Nx + 1) + j];
E_bd_down[j - 1] = Ez[Nx*(Nx + 1) + j];
}
}
void Bd_proc_left_right()
{
int i;
for (i = 1; i < Nx; i++){
//left E(i,0)=Enb(i-1)+c*(E(i,1)-Eb(i-1))
Ez[i*(Nx + 1)] = E_nbd_left[i - 1] + coe_MUR*(Ez[i*(Nx + 1) + 1] - E_bd_left[i - 1]);
E_nbd_left[i - 1] = Ez[i*(Nx + 1) + 1];
E_bd_left[i - 1] = Ez[i*(Nx + 1)];
//right E(i,Nx)=Enb(i-1)+c*(E(i,Nx-1)-Eb(i-1))
Ez[i*(Nx + 1) + Nx] = E_nbd_right[i - 1] + coe_MUR*(Ez[i*(Nx + 1) + Nx - 1] - E_bd_right[i - 1]);
E_nbd_right[i - 1] = Ez[i*(Nx + 1) + Nx - 1];
E_bd_right[i - 1] = Ez[i*(Nx + 1) + Nx];
}
}
void Bd_proc_point()
{
int i, j;
Ez[0] = (Ez[1] + Ez[Nx + 1]) / 2;
Ez[Nx] = (Ez[Nx - 1] + Ez[Nx + 1 + Nx]) / 2;
Ez[Nx*(Nx + 1)] = (Ez[(Nx - 1)*(Nx + 1)] + Ez[Nx*(Nx + 1) + 1]) / 2;
Ez[Nx*(Nx + 1) + Nx] = (Ez[(Nx - 1)*(Nx + 1) + Nx] + Ez[Nx*(Nx + 1) + Nx - 1]) / 2;
}
|
///////////////////////////////////////////////////////////////////////
// File: pain_points.cpp
// Description: Functions that utilize the knowledge about the properties
// of the paths explored by the segmentation search in order
// to "pain points" - the locations in the ratings matrix
// which should be classified next.
// Author: Rika Antonova
// Created: Mon Jun 20 11:26:43 PST 2012
//
// (C) Copyright 2012, Google 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 "lm_pain_points.h"
#include "associate.h"
#include "dict.h"
#include "genericheap.h"
#include "lm_state.h"
#include "matrix.h"
#include "pageres.h"
#include <algorithm>
namespace tesseract {
const float LMPainPoints::kDefaultPainPointPriorityAdjustment = 2.0f;
const float LMPainPoints::kLooseMaxCharWhRatio = 2.5f;
LMPainPointsType LMPainPoints::Deque(MATRIX_COORD *pp, float *priority) {
for (int h = 0; h < LM_PPTYPE_NUM; ++h) {
if (pain_points_heaps_[h].empty()) continue;
*priority = pain_points_heaps_[h].PeekTop().key();
*pp = pain_points_heaps_[h].PeekTop().data();
pain_points_heaps_[h].Pop(nullptr);
return static_cast<LMPainPointsType>(h);
}
return LM_PPTYPE_NUM;
}
void LMPainPoints::GenerateInitial(WERD_RES *word_res) {
MATRIX *ratings = word_res->ratings;
AssociateStats associate_stats;
for (int col = 0; col < ratings->dimension(); ++col) {
int row_end = std::min(ratings->dimension(), col + ratings->bandwidth() + 1);
for (int row = col + 1; row < row_end; ++row) {
MATRIX_COORD coord(col, row);
if (coord.Valid(*ratings) &&
ratings->get(col, row) != NOT_CLASSIFIED) continue;
// Add an initial pain point if needed.
if (ratings->Classified(col, row - 1, dict_->WildcardID()) ||
(col + 1 < ratings->dimension() &&
ratings->Classified(col + 1, row, dict_->WildcardID()))) {
GeneratePainPoint(col, row, LM_PPTYPE_SHAPE, 0.0,
true, max_char_wh_ratio_, word_res);
}
}
}
}
void LMPainPoints::GenerateFromPath(float rating_cert_scale,
ViterbiStateEntry *vse,
WERD_RES *word_res) {
ViterbiStateEntry *curr_vse = vse;
BLOB_CHOICE *curr_b = vse->curr_b;
// The following pain point generation and priority calculation approaches
// prioritize exploring paths with low average rating of the known part of
// the path, while not relying on the ratings of the pieces to be combined.
//
// A pain point to combine the neighbors is generated for each pair of
// neighboring blobs on the path (the path is represented by vse argument
// given to GenerateFromPath()). The priority of each pain point is set to
// the average rating (per outline length) of the path, not including the
// ratings of the blobs to be combined.
// The ratings of the blobs to be combined are not used to calculate the
// priority, since it is not possible to determine from their magnitude
// whether it will be beneficial to combine the blobs. The reason is that
// chopped junk blobs (/ | - ') can have very good (low) ratings, however
// combining them will be beneficial. Blobs with high ratings might be
// over-joined pieces of characters, but also could be blobs from an unseen
// font or chopped pieces of complex characters.
while (curr_vse->parent_vse != nullptr) {
ViterbiStateEntry* parent_vse = curr_vse->parent_vse;
const MATRIX_COORD& curr_cell = curr_b->matrix_cell();
const MATRIX_COORD& parent_cell = parent_vse->curr_b->matrix_cell();
MATRIX_COORD pain_coord(parent_cell.col, curr_cell.row);
if (!pain_coord.Valid(*word_res->ratings) ||
!word_res->ratings->Classified(parent_cell.col, curr_cell.row,
dict_->WildcardID())) {
// rat_subtr contains ratings sum of the two adjacent blobs to be merged.
// rat_subtr will be subtracted from the ratings sum of the path, since
// the blobs will be joined into a new blob, whose rating is yet unknown.
float rat_subtr = curr_b->rating() + parent_vse->curr_b->rating();
// ol_subtr contains the outline length of the blobs that will be joined.
float ol_subtr =
AssociateUtils::ComputeOutlineLength(rating_cert_scale, *curr_b) +
AssociateUtils::ComputeOutlineLength(rating_cert_scale,
*(parent_vse->curr_b));
// ol_dif is the outline of the path without the two blobs to be joined.
float ol_dif = vse->outline_length - ol_subtr;
// priority is set to the average rating of the path per unit of outline,
// not counting the ratings of the pieces to be joined.
float priority = ol_dif > 0 ? (vse->ratings_sum-rat_subtr)/ol_dif : 0.0;
GeneratePainPoint(pain_coord.col, pain_coord.row, LM_PPTYPE_PATH,
priority, true, max_char_wh_ratio_, word_res);
} else if (debug_level_ > 3) {
tprintf("NO pain point (Classified) for col=%d row=%d type=%s\n",
pain_coord.col, pain_coord.row,
LMPainPointsTypeName[LM_PPTYPE_PATH]);
BLOB_CHOICE_IT b_it(word_res->ratings->get(pain_coord.col,
pain_coord.row));
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
BLOB_CHOICE* choice = b_it.data();
choice->print_full();
}
}
curr_vse = parent_vse;
curr_b = curr_vse->curr_b;
}
}
void LMPainPoints::GenerateFromAmbigs(const DANGERR &fixpt,
ViterbiStateEntry *vse,
WERD_RES *word_res) {
// Begins and ends in DANGERR vector now record the blob indices as used
// by the ratings matrix.
for (int d = 0; d < fixpt.size(); ++d) {
const DANGERR_INFO &danger = fixpt[d];
// Only use dangerous ambiguities.
if (danger.dangerous) {
GeneratePainPoint(danger.begin, danger.end - 1,
LM_PPTYPE_AMBIG, vse->cost, true,
kLooseMaxCharWhRatio, word_res);
}
}
}
bool LMPainPoints::GeneratePainPoint(
int col, int row, LMPainPointsType pp_type, float special_priority,
bool ok_to_extend, float max_char_wh_ratio,
WERD_RES *word_res) {
MATRIX_COORD coord(col, row);
if (coord.Valid(*word_res->ratings) &&
word_res->ratings->Classified(col, row, dict_->WildcardID())) {
return false;
}
if (debug_level_ > 3) {
tprintf("Generating pain point for col=%d row=%d type=%s\n",
col, row, LMPainPointsTypeName[pp_type]);
}
// Compute associate stats.
AssociateStats associate_stats;
AssociateUtils::ComputeStats(col, row, nullptr, 0, fixed_pitch_,
max_char_wh_ratio, word_res, debug_level_,
&associate_stats);
// For fixed-pitch fonts/languages: if the current combined blob overlaps
// the next blob on the right and it is ok to extend the blob, try extending
// the blob until there is no overlap with the next blob on the right or
// until the width-to-height ratio becomes too large.
if (ok_to_extend) {
while (associate_stats.bad_fixed_pitch_right_gap &&
row + 1 < word_res->ratings->dimension() &&
!associate_stats.bad_fixed_pitch_wh_ratio) {
AssociateUtils::ComputeStats(col, ++row, nullptr, 0, fixed_pitch_,
max_char_wh_ratio, word_res, debug_level_,
&associate_stats);
}
}
if (associate_stats.bad_shape) {
if (debug_level_ > 3) {
tprintf("Discarded pain point with a bad shape\n");
}
return false;
}
// Insert the new pain point into pain_points_heap_.
if (pain_points_heaps_[pp_type].size() < max_heap_size_) {
// Compute pain point priority.
float priority;
if (pp_type == LM_PPTYPE_PATH) {
priority = special_priority;
} else {
priority = associate_stats.gap_sum;
}
MatrixCoordPair pain_point(priority, MATRIX_COORD(col, row));
pain_points_heaps_[pp_type].Push(&pain_point);
if (debug_level_) {
tprintf("Added pain point with priority %g\n", priority);
}
return true;
} else {
if (debug_level_) tprintf("Pain points heap is full\n");
return false;
}
}
/**
* Adjusts the pain point coordinates to cope with expansion of the ratings
* matrix due to a split of the blob with the given index.
*/
void LMPainPoints::RemapForSplit(int index) {
for (auto & pain_points_heap : pain_points_heaps_) {
GenericVector<MatrixCoordPair>* heap = pain_points_heap.heap();
for (int j = 0; j < heap->size(); ++j)
(*heap)[j].data().MapForSplit(index);
}
}
} // namespace tesseract
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "cuda_common.h"
#include "cuda_execution_provider.h"
#include "cuda_fence.h"
#include "cuda_allocator.h"
#include "core/framework/kernel_registry.h"
#include "core/framework/compute_capability.h"
#include "core/framework/memcpy.h"
#include "core/graph/graph_utils.h"
#include "core/providers/cuda/gpu_data_transfer.h"
#ifndef DISABLE_CONTRIB_OPS
#include "contrib_ops/cuda/cuda_contrib_kernels.h"
#endif
#ifdef ENABLE_TRAINING
#include "orttraining/training_ops/cuda/cuda_training_kernels.h"
#endif
using namespace onnxruntime::common;
namespace {
struct KernelRegistryAndStatus {
std::shared_ptr<onnxruntime::KernelRegistry> kernel_registry = std::make_shared<onnxruntime::KernelRegistry>();
Status st;
};
} // namespace
namespace onnxruntime {
namespace cuda {
ONNX_OPERATOR_KERNEL_EX(
MemcpyFromHost,
kOnnxDomain,
1,
kCudaExecutionProvider,
KernelDefBuilder()
.InputMemoryType<OrtMemTypeCPUInput>(0)
.ExecQueueId(kCudaStreamCopyIn)
.TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()),
Memcpy);
ONNX_OPERATOR_KERNEL_EX(
MemcpyToHost,
kOnnxDomain,
1,
kCudaExecutionProvider,
KernelDefBuilder()
.OutputMemoryType<OrtMemTypeCPUOutput>(0)
.ExecQueueId(kCudaStreamCopyOut)
.TypeConstraint("T", DataTypeImpl::AllFixedSizeTensorTypes()),
Memcpy);
} // namespace cuda
thread_local std::unique_ptr<CUDAExecutionProvider::PerThreadContextMap> CUDAExecutionProvider::per_thread_context_map_;
CUDAExecutionProvider::PerThreadContext::PerThreadContext(OrtDevice::DeviceId device_id, size_t cuda_mem_limit, ArenaExtendStrategy arena_extend_strategy) {
CUDA_CALL_THROW(cudaSetDevice(device_id));
CUBLAS_CALL_THROW(cublasCreate(&cublas_handle_));
CUDNN_CALL_THROW(cudnnCreate(&cudnn_handle_));
CURAND_CALL_THROW(curandCreateGenerator(&curand_generator_, CURAND_RNG_PSEUDO_DEFAULT));
DeviceAllocatorRegistrationInfo default_memory_info(
{OrtMemTypeDefault,
[](OrtDevice::DeviceId id) { return onnxruntime::make_unique<CUDAAllocator>(id, CUDA); }, cuda_mem_limit, arena_extend_strategy});
allocator_ = CreateAllocator(default_memory_info, device_id);
}
CUDAExecutionProvider::PerThreadContext::~PerThreadContext() {
// dtor shouldn't throw. if something went wrong earlier (e.g. out of CUDA memory) the handles
// here may be bad, and the destroy calls can throw.
// https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-dtor-noexcept
try {
CUBLAS_CALL(cublasDestroy(cublas_handle_));
} catch (const std::exception& ex) {
LOGS_DEFAULT(ERROR) << "cublasDestroy threw:" << ex.what();
}
try {
CUDNN_CALL(cudnnDestroy(cudnn_handle_));
} catch (const std::exception& ex) {
LOGS_DEFAULT(ERROR) << "cudnnDestroy threw:" << ex.what();
}
CURAND_CALL_THROW(curandDestroyGenerator(curand_generator_));
}
CUDAExecutionProvider::CUDAExecutionProvider(const CUDAExecutionProviderInfo& info)
: IExecutionProvider{onnxruntime::kCudaExecutionProvider},
device_id_(info.device_id),
cuda_mem_limit_(info.cuda_mem_limit),
arena_extend_strategy_(info.arena_extend_strategy) {
CUDA_CALL_THROW(cudaSetDevice(device_id_));
// must wait GPU idle, otherwise cudaGetDeviceProperties might fail
CUDA_CALL_THROW(cudaDeviceSynchronize());
CUDA_CALL_THROW(cudaGetDeviceProperties(&device_prop_, device_id_));
size_t free = 0;
size_t total = 0;
CUDA_CALL_THROW(cudaMemGetInfo(&free, &total));
DeviceAllocatorRegistrationInfo default_memory_info(
{OrtMemTypeDefault,
[](OrtDevice::DeviceId device_id) {
return onnxruntime::make_unique<CUDAAllocator>(device_id, CUDA);
},
cuda_mem_limit_});
InsertAllocator(CreateAllocator(default_memory_info, device_id_));
DeviceAllocatorRegistrationInfo pinned_memory_info(
{OrtMemTypeCPUOutput,
[](OrtDevice::DeviceId device_id) {
return onnxruntime::make_unique<CUDAPinnedAllocator>(device_id, CUDA_PINNED);
},
std::numeric_limits<size_t>::max()});
InsertAllocator(CreateAllocator(pinned_memory_info, CPU_ALLOCATOR_DEVICE_ID));
// TODO: this is actually used for the cuda kernels which explicitly ask for inputs from CPU.
// This will be refactored/removed when allocator and execution provider are decoupled.
DeviceAllocatorRegistrationInfo cpu_memory_info({OrtMemTypeCPUInput,
[](int device_id) { return onnxruntime::make_unique<CPUAllocator>(
onnxruntime::make_unique<OrtMemoryInfo>(
"CUDA_CPU",
OrtAllocatorType::OrtDeviceAllocator,
OrtDevice(),
device_id,
OrtMemTypeCPUInput)); },
std::numeric_limits<size_t>::max()});
InsertAllocator(CreateAllocator(cpu_memory_info, CPU_ALLOCATOR_DEVICE_ID));
}
CUDAExecutionProvider::~CUDAExecutionProvider() {
auto cpu_alloc = GetAllocator(CPU_ALLOCATOR_DEVICE_ID, OrtMemTypeCPU);
std::lock_guard<OrtMutex> lock(deferred_release_cpu_ptr_mutex_);
auto it = deferred_release_cpu_ptr_.begin();
while (it != deferred_release_cpu_ptr_.end()) {
auto& e = it->first;
auto& v = it->second;
if (v.recorded)
CUDA_CALL_THROW(cudaEventSynchronize(e));
for (auto p : v.cpu_ptrs) {
cpu_alloc->Free(p);
}
CUDA_CALL_THROW(cudaEventDestroy(e));
it = deferred_release_cpu_ptr_.erase(it);
}
}
CUDAExecutionProvider::PerThreadContext& CUDAExecutionProvider::GetPerThreadContext() const {
if (per_thread_context_map_ == nullptr) {
per_thread_context_map_ = onnxruntime::make_unique<PerThreadContextMap>();
}
auto* p = per_thread_context_map_.get();
if (p->count(this) == 0) {
std::lock_guard<OrtMutex> lock(context_pool_mutex_);
std::shared_ptr<PerThreadContext> ptc;
if (retired_context_pool_.empty()) {
ptc = std::make_shared<PerThreadContext>(device_id_, cuda_mem_limit_, arena_extend_strategy_);
} else {
ptc = retired_context_pool_.back();
retired_context_pool_.pop_back();
}
p->insert(std::make_pair(this, ptc));
}
return *(p->at(this));
}
void CUDAExecutionProvider::ReleasePerThreadStuffs() const {
ORT_ENFORCE(per_thread_context_map_ != nullptr);
auto iter_ctx = per_thread_context_map_->find(this);
ORT_ENFORCE(iter_ctx != per_thread_context_map_->end());
std::lock_guard<OrtMutex> lock(context_pool_mutex_);
retired_context_pool_.push_back(iter_ctx->second);
per_thread_context_map_->erase(iter_ctx);
// Release TLS if empty to avoid memory leak report
if (per_thread_context_map_->empty()) {
per_thread_context_map_.reset(nullptr);
}
}
AllocatorPtr CUDAExecutionProvider::GetAllocator(int id, OrtMemType mem_type) const {
// Pinned memory allocator is shared between threads, but CUDA memory allocator is per-thread or it may cause result changes
// A hypothesis is that arena allocator is not aligned with CUDA output cache, and data from different kernel writes may
// cause cacheline to contain dirty data.
if (mem_type == OrtMemTypeDefault) {
return GetPerThreadContext().GetAllocator();
} else {
return IExecutionProvider::GetAllocator(id, mem_type);
}
}
Status CUDAExecutionProvider::Sync() const {
CUDA_RETURN_IF_ERROR(cudaDeviceSynchronize());
return Status::OK();
}
void CUDAExecutionProvider::AddDeferredReleaseCPUPtr(void* p) {
// when not running in InferenceSession (e.g. Test)
// it's OK to not remember the deferred release ptr
// as the actual memory will be cleaned in arena allocator dtor
auto current_deferred_release_event = GetPerThreadContext().GetCurrentDeferredReleaseEvent();
if (current_deferred_release_event) {
std::lock_guard<OrtMutex> lock(deferred_release_cpu_ptr_mutex_);
auto iter = deferred_release_cpu_ptr_.find(current_deferred_release_event);
ORT_ENFORCE(iter != deferred_release_cpu_ptr_.end());
iter->second.cpu_ptrs.push_back(p);
}
}
Status CUDAExecutionProvider::OnRunStart() {
// always set CUDA device when session::Run() in case it runs in a worker thread
CUDA_RETURN_IF_ERROR(cudaSetDevice(GetDeviceId()));
auto cpu_alloc = GetAllocator(0, OrtMemTypeCPU);
// check if cudaEvents has passed for deferred release
// note that we need to take a mutex in case of multi-threaded Run()
std::lock_guard<OrtMutex> lock(deferred_release_cpu_ptr_mutex_);
auto it = deferred_release_cpu_ptr_.begin();
while (it != deferred_release_cpu_ptr_.end()) {
auto& e = it->first;
auto& v = it->second;
// note that cudaEventQuery returns cudaSucess before first cudaEventRecord
if (v.recorded && cudaSuccess == cudaEventQuery(e)) {
for (auto p : v.cpu_ptrs) {
cpu_alloc->Free(p);
}
cudaEvent_t expired_event = it->first;
it = deferred_release_cpu_ptr_.erase(it);
CUDA_RETURN_IF_ERROR(cudaEventDestroy(expired_event));
} else {
++it;
}
}
auto& current_deferred_release_event = GetPerThreadContext().GetCurrentDeferredReleaseEvent();
CUDA_RETURN_IF_ERROR(cudaEventCreate(¤t_deferred_release_event, cudaEventDisableTiming));
deferred_release_cpu_ptr_.emplace(current_deferred_release_event, DeferredReleaseCPUPtrs());
return Status::OK();
}
Status CUDAExecutionProvider::OnRunEnd() {
// record deferred release event on default stream, and release per_thread_context
auto current_deferred_release_event = GetPerThreadContext().GetCurrentDeferredReleaseEvent();
CUDA_RETURN_IF_ERROR(cudaEventRecord(current_deferred_release_event, nullptr));
ReleasePerThreadStuffs();
std::lock_guard<OrtMutex> lock(deferred_release_cpu_ptr_mutex_);
deferred_release_cpu_ptr_[current_deferred_release_event].recorded = true;
return Status::OK();
}
namespace cuda {
// opset 1 to 9
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MemcpyFromHost);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MemcpyToHost);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 4, 10, Concat);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Unsqueeze);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, Flatten);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Squeeze);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, Identity);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, Dropout);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Gather);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, Gemm);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, Gemm);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, Gemm);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, float, Gemm);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, double, Gemm);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, MLFloat16, Gemm);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, float, MatMul);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, double, MatMul);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, MLFloat16, MatMul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, MatMul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, MatMul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, MatMul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, int8_t, MatMulInteger);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Tile);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Tile);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Tile);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Elu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Elu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Elu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, HardSigmoid);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, HardSigmoid);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, HardSigmoid);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, LeakyRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, LeakyRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, LeakyRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Relu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Relu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Relu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Selu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Selu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Selu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Sigmoid);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Sigmoid);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Sigmoid);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, Softsign);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, Softsign);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, Softsign);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Tanh);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Tanh);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Tanh);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, Softplus);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, Softplus);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, Softplus);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, Softmax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, Softmax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, Softmax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 11, float, Pow);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 11, double, Pow);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 11, MLFloat16, Pow);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, PRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, PRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, PRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, bool, And);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, bool, Or);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, bool, Xor);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, int32_t, Sum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, int64_t, Sum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, uint32_t, Sum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, uint64_t, Sum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, float, Sum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, double, Sum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, MLFloat16, Sum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, int32_t, Sum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, int64_t, Sum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, uint32_t, Sum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, uint64_t, Sum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, float, Sum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, double, Sum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, MLFloat16, Sum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, float, Max);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, double, Max);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, MLFloat16, Max);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, float, Max);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, double, Max);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, MLFloat16, Max);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, Max);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int64_t, Max);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint32_t, Max);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint64_t, Max);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, Max);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, Max);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, Max);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, float, Min);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, double, Min);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, MLFloat16, Min);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, float, Min);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, double, Min);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, MLFloat16, Min);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, Min);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int64_t, Min);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint32_t, Min);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint64_t, Min);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, Min);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, Min);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, Min);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, Greater);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, Greater);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, Greater);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 10, bool, Equal);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 10, int32_t, Equal);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 10, int64_t, Equal);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, Expand);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Greater);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Greater);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Greater);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Greater);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Greater);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Greater);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Greater);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Add);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Add);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Add);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Add);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Add);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Add);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Add);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Sub);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Sub);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Sub);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Sub);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Sub);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Sub);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Sub);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Mul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Mul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Mul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Mul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Mul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Mul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Mul);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Div);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Div);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Div);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Div);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Div);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Div);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Div);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int8_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int16_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int32_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int64_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint8_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint16_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint32_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint64_t, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Abs);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int8_t, Neg);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int16_t, Neg);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int32_t, Neg);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int64_t, Neg);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Neg);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Neg);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Neg);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Floor);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Floor);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Floor);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Ceil);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Ceil);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Ceil);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 10, float, Clip);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Reciprocal);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Reciprocal);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Reciprocal);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Sqrt);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Sqrt);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Sqrt);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Log);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Log);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Log);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Exp);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Exp);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Exp);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Erf);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Erf);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Erf);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, bool, Not);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, BatchNormalization);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, BatchNormalization);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, BatchNormalization);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, BatchNormalization);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, BatchNormalization);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, BatchNormalization);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, LRN);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, LRN);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, LRN);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, Conv);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, Conv);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, Conv);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ConvTranspose);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ConvTranspose);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ConvTranspose);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, float, AveragePool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, double, AveragePool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, MLFloat16, AveragePool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, GlobalAveragePool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, GlobalAveragePool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, GlobalAveragePool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 9, float, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 9, double, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 9, MLFloat16, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 7, float, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 7, double, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 7, MLFloat16, MaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, GlobalMaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, GlobalMaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, GlobalMaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ArgMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ArgMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ArgMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ArgMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ArgMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ArgMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceL1);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceL1);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceL1);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceL1);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceL2);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceL2);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceL2);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceL2);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceMean);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceMean);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceMean);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceMean);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceProd);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceProd);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceProd);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceProd);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceSum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceSum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceSum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceSum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceLogSum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceLogSum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceLogSum);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceSumSquare);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceSumSquare);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceSumSquare);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceLogSumExp);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceLogSumExp);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceLogSumExp);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, float, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, double, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, MLFloat16, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int8_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int16_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int32_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int64_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint8_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint16_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint32_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint64_t, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, bool, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int8_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int16_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint16_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Cast);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, bool, Cast);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, float, Pad);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, double, Pad);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, MLFloat16, Pad);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 5, Reshape);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 4, Reshape_1);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, Shape);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Tile);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Tile);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Tile);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, Transpose);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, InstanceNormalization);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, InstanceNormalization);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, InstanceNormalization);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, RNN);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, RNN);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, RNN);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, GRU);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, GRU);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, GRU);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, LSTM);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, LSTM);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, LSTM);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, int32_t, Slice);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, int64_t, Slice);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, float, Slice);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Compress);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Flatten);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, float, Upsample);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, double, Upsample);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, MLFloat16, Upsample);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, int32_t, Upsample);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, uint8_t, Upsample);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, Split);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, ConstantOfShape);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int8_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int16_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint16_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Shrink);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Shrink);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, Less);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, Less);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, Less);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Less);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Less);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Less);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Less);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Less);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Less);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Less);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, EyeLike);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Scatter);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Where);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Where);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Where);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Where);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, Where);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, bool, NonZero);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, NonZero);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, NonZero);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, NonZero);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, NonZero);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, TopK);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, If);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 8, Scan);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Scan);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Loop);
// opset 10
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, AveragePool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, double, AveragePool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, MLFloat16, AveragePool);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, Dropout);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, double, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, MLFloat16, MaxPool);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, NonMaxSuppression);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, Resize);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, double, Resize);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, MLFloat16, Resize);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, int32_t, Resize);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, uint8_t, Resize);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, ReverseSequence);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, float, RoiAlign);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, double, RoiAlign);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, int32_t, Slice);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, int64_t, Slice);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, Slice);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, float, ThresholdedRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, double, ThresholdedRelu);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, MLFloat16, ThresholdedRelu);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, TopK);
// opset 11
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ArgMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ArgMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ArgMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ArgMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ArgMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ArgMin);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Compress);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Concat);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Flatten);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Gather);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, GatherElements);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Gemm);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Gemm);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Gemm);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, If);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Loop);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, NonMaxSuppression);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Range);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceL1);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceL1);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceL1);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceL1);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceL2);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceL2);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceL2);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceL2);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceLogSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceLogSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceLogSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceLogSumExp);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceLogSumExp);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceLogSumExp);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, float, ReduceMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, double, ReduceMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, MLFloat16, ReduceMax);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, int32_t, ReduceMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceMean);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceMean);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceMean);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceMean);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, float, ReduceMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, double, ReduceMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, MLFloat16, ReduceMin);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, int32_t, ReduceMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceProd);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceProd);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceProd);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceProd);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceSumSquare);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceSumSquare);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceSumSquare);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Scan);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, ScatterElements);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, Slice);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t, Slice);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Slice);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Softmax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Softmax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Softmax);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Split);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Squeeze);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, TopK);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Unsqueeze);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Conv);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Conv);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Conv);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ConvTranspose);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ConvTranspose);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ConvTranspose);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, AveragePool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, AveragePool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, AveragePool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, float, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, double, MaxPool);
class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, MLFloat16, MaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Resize);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Resize);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Resize);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, Resize);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, uint8_t, Resize);
class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, Clip);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Pad);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Pad);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Pad);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, bool, Equal);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, Equal);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t, Equal);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Round);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Round);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Round);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, int8_t, QuantizeLinear);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, uint8_t, QuantizeLinear);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, int8_t, DequantizeLinear);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, uint8_t, DequantizeLinear);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, CumSum);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t_int64_t_int64_t, OneHot);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t_float_int64_t, OneHot);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t_float_int32_t, OneHot);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t_MLFloat16_int64_t, OneHot);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t_MLFloat16_int32_t, OneHot);
// OpSet 12
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, Clip);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, MaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, MaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, MaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int8_t, MaxPool);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint8_t, MaxPool);
class ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, Pow);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, ReduceMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, ReduceMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, ReduceMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, ReduceMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int8_t, ReduceMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint8_t, ReduceMax);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, ReduceMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, ReduceMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, ReduceMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, ReduceMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int8_t, ReduceMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint8_t, ReduceMin);
class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int64_t, GatherND);
static Status RegisterCudaKernels(KernelRegistry& kernel_registry) {
static const BuildKernelCreateInfoFn function_table[] = {
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MemcpyFromHost)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MemcpyToHost)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 4, 10, Concat)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Unsqueeze)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, Flatten)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Squeeze)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, Identity)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, Dropout)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Gather)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, float, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, double, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, MLFloat16, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, float, MatMul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, double, MatMul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 8, MLFloat16, MatMul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, MatMul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, MatMul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, MatMul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, int8_t, MatMulInteger)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 10, float, Clip)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Tile)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Tile)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Tile)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Elu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Elu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Elu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, HardSigmoid)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, HardSigmoid)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, HardSigmoid)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, LeakyRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, LeakyRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, LeakyRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Relu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Relu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Relu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Selu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Selu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Selu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Sigmoid)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Sigmoid)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Sigmoid)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, Softsign)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, Softsign)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, Softsign)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Tanh)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Tanh)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Tanh)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, Softplus)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, Softplus)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, Softplus)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, Softmax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, Softmax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, Softmax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 11, float, Pow)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 11, double, Pow)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 11, MLFloat16, Pow)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, PRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, PRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, PRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, bool, And)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, bool, Or)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, bool, Xor)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, int32_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, int64_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, uint32_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, uint64_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, float, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, double, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, MLFloat16, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, int32_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, int64_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, uint32_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, uint64_t, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, float, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, double, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, MLFloat16, Sum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, float, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, double, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, MLFloat16, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, float, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, double, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, MLFloat16, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int64_t, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint32_t, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint64_t, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, Max)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, float, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, double, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 7, MLFloat16, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, float, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, double, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 11, MLFloat16, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int64_t, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint32_t, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint64_t, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, Min)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 10, bool, Equal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 10, int32_t, Equal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 10, int64_t, Equal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, Expand)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Greater)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Add)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Add)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Add)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Add)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Add)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Add)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Add)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Sub)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Sub)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Sub)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Sub)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Sub)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Sub)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Sub)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Mul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Mul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Mul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Mul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Mul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Mul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Mul)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int32_t, Div)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, int64_t, Div)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint32_t, Div)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, uint64_t, Div)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, Div)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, Div)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, Div)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int8_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int16_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int32_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int64_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint8_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint16_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint32_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, uint64_t, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Abs)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int8_t, Neg)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int16_t, Neg)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int32_t, Neg)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, int64_t, Neg)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Neg)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Neg)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Neg)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Floor)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Floor)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Floor)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Ceil)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Ceil)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Ceil)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Reciprocal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Reciprocal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Reciprocal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Sqrt)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Sqrt)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Sqrt)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Log)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Log)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Log)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Exp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Exp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Exp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Erf)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Erf)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Erf)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, bool, Not)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, BatchNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, BatchNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, BatchNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, BatchNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, BatchNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, BatchNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, LRN)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, LRN)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, LRN)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, Conv)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, Conv)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, Conv)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ConvTranspose)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ConvTranspose)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ConvTranspose)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, float, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, double, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, MLFloat16, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, GlobalAveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, GlobalAveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, GlobalAveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 9, float, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 9, double, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 9, MLFloat16, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 7, float, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 7, double, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 7, MLFloat16, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, float, GlobalMaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, double, GlobalMaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, MLFloat16, GlobalMaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ArgMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ArgMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ArgMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ArgMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ArgMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ArgMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, int32_t, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceLogSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceLogSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceLogSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceSumSquare)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceSumSquare)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceSumSquare)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, float, ReduceLogSumExp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, double, ReduceLogSumExp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, MLFloat16, ReduceLogSumExp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, float, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, double, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, MLFloat16, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int8_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int16_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int32_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, int64_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint8_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint16_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint32_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, uint64_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, 8, bool, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int8_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int16_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint16_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, bool, Cast)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, float, Pad)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, double, Pad)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, MLFloat16, Pad)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 5, Reshape)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 4, Reshape_1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, Shape)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, Tile)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, Tile)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, Tile)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, Transpose)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, float, InstanceNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, double, InstanceNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 6, MLFloat16, InstanceNormalization)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, RNN)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, RNN)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, RNN)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, GRU)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, GRU)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, GRU)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, float, LSTM)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, double, LSTM)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, MLFloat16, LSTM)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, int32_t, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, int64_t, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, float, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Compress)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Flatten)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, float, Upsample)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, double, Upsample)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, MLFloat16, Upsample)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, int32_t, Upsample)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 9, uint8_t, Upsample)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 2, 10, Split)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, ConstantOfShape)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int8_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int16_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint16_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Shrink)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, float, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, double, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 7, 8, MLFloat16, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint32_t, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint64_t, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, double, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Less)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, EyeLike)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Scatter)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, MLFloat16, Where)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, Where)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, Where)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, Where)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, Where)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, bool, NonZero)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, uint8_t, NonZero)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int32_t, NonZero)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, int64_t, NonZero)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, float, NonZero)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 9, TopK)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 8, 8, Scan)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 9, 10, Scan)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, Loop)>,
// opset 10
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, double, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, MLFloat16, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, Dropout)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, double, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, MLFloat16, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, NonMaxSuppression)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, double, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, MLFloat16, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, int32_t, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, uint8_t, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, ReverseSequence)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, float, RoiAlign)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, double, RoiAlign)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, int32_t, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, int64_t, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, float, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, float, ThresholdedRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, double, ThresholdedRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, MLFloat16, ThresholdedRelu)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, 10, TopK)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 1, 10, If)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, int8_t, QuantizeLinear)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, uint8_t, QuantizeLinear)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, int8_t, DequantizeLinear)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 10, uint8_t, DequantizeLinear)>,
// opset 11
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ArgMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ArgMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ArgMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ArgMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ArgMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ArgMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Compress)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Concat)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Flatten)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Gather)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, GatherElements)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Gemm)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, If)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Loop)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, NonMaxSuppression)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Range)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceL1)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceL2)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceLogSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceLogSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceLogSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceLogSumExp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceLogSumExp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceLogSumExp)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, float, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, double, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, MLFloat16, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, int32_t, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceMean)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, float, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, double, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, MLFloat16, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, int32_t, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceProd)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, ReduceSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ReduceSumSquare)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ReduceSumSquare)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ReduceSumSquare)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Scan)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, ScatterElements)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Slice)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Softmax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Softmax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Softmax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Split)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Squeeze)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, TopK)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, Unsqueeze)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Conv)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Conv)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Conv)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, ConvTranspose)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, ConvTranspose)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, ConvTranspose)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, AveragePool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, float, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, double, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, MLFloat16, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, uint8_t, Resize)>,
BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, 11, Clip)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Pad)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Pad)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Pad)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, bool, Equal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t, Equal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t, Equal)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, float, Round)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, double, Round)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, MLFloat16, Round)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, CumSum)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t_int64_t_int64_t, OneHot)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t_float_int64_t, OneHot)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t_float_int32_t, OneHot)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int64_t_MLFloat16_int64_t, OneHot)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 11, int32_t_MLFloat16_int32_t, OneHot)>,
// OpSet 12
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, Clip)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int8_t, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint8_t, MaxPool)>,
BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, Pow)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int8_t, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint8_t, ReduceMax)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, float, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, double, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, MLFloat16, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int32_t, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int8_t, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, uint8_t, ReduceMin)>,
BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(kCudaExecutionProvider, kOnnxDomain, 12, int64_t, GatherND)>,
};
for (auto& function_table_entry : function_table) {
ORT_RETURN_IF_ERROR(kernel_registry.Register(function_table_entry()));
}
#ifndef DISABLE_CONTRIB_OPS
ORT_RETURN_IF_ERROR(::onnxruntime::contrib::cuda::RegisterCudaContribKernels(kernel_registry));
#endif
#ifdef ENABLE_TRAINING
ORT_RETURN_IF_ERROR(::onnxruntime::cuda::RegisterCudaTrainingKernels(kernel_registry));
#endif
return Status::OK();
}
KernelRegistryAndStatus GetCudaKernelRegistry() {
KernelRegistryAndStatus ret;
ret.st = RegisterCudaKernels(*ret.kernel_registry);
return ret;
}
} // namespace cuda
std::shared_ptr<KernelRegistry> CUDAExecutionProvider::GetKernelRegistry() const {
static KernelRegistryAndStatus k = onnxruntime::cuda::GetCudaKernelRegistry();
// throw if the registry failed to initialize
ORT_THROW_IF_ERROR(k.st);
return k.kernel_registry;
}
static bool RNNNeedFallbackToCPU(const onnxruntime::Node& node,
const std::vector<std::string> activations_supported,
const std::string& op_type) {
const auto& node_attributes = node.GetAttributes();
// Check attributes
for (auto& attr : node_attributes) {
auto attr_name = attr.first;
auto attr_value = attr.second;
if ("activation_alpha" == attr_name || "activation_beta" == attr_name || "clip" == attr_name) {
return true;
}
if ("activations" == attr_name &&
::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_STRINGS == attr_value.type()) {
for (int i = 0; i < attr_value.strings_size(); ++i) {
std::string activation_lowercase(attr_value.strings(i));
std::transform(activation_lowercase.begin(), activation_lowercase.end(), activation_lowercase.begin(),
[](const unsigned char i) { return static_cast<char>(::tolower(i)); });
if (activations_supported[i] != activation_lowercase) {
return true;
}
}
}
if ("LSTM" == op_type &&
"input_forget" == attr_name &&
::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_INT == attr_value.type()) {
if (0 != attr_value.i()) {
return true;
}
}
if ("GRU" == op_type &&
"linear_before_reset" == attr_name &&
::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_INT == attr_value.type()) {
// cudnn GRU only support linear_before_reset = 1
if (1 != attr_value.i()) {
return true;
}
}
}
if ("LSTM" == op_type) {
// cudnn LSTM not support peephole
auto input_defs = node.InputDefs();
if (8 == input_defs.size()) {
auto peephole = input_defs.at(7);
if (peephole->Exists()) {
return true;
}
}
}
return false;
}
static bool ConvNeedFallbackToCPU(const onnxruntime::Node& node) {
const auto& node_attributes = node.GetAttributes();
// Check attributes
for (auto& attr : node_attributes) {
auto attr_name = attr.first;
auto attr_value = attr.second;
//cudnn only supports symmetric padding
if ("pads" == attr_name && ::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_INTS == attr_value.type()) {
auto& pads = attr_value.ints();
int pads_size = pads.size();
ORT_ENFORCE(pads_size % 2 == 0);
int rank = pads_size / 2;
for (int i = 0; i < rank; i++) {
if (pads.Get(i) != pads.Get(i + rank)) {
return true;
}
}
}
}
return false;
}
static bool CastNeedFallbackToCPU(const onnxruntime::Node& node) {
const auto& node_attributes = node.GetAttributes();
// Check attributes
for (auto& attr : node_attributes) {
auto attr_name = attr.first;
auto attr_value = attr.second;
// string is not supported
if ("to" == attr_name && ::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_INT == attr_value.type()) {
auto to_type = attr_value.i();
if (to_type == ::ONNX_NAMESPACE::TensorProto_DataType_STRING)
return true;
}
}
return false;
}
std::unique_ptr<onnxruntime::IDataTransfer> CUDAExecutionProvider::GetDataTransfer() const {
return onnxruntime::make_unique<onnxruntime::GPUDataTransfer>();
}
std::vector<std::unique_ptr<ComputeCapability>>
CUDAExecutionProvider::GetCapability(const onnxruntime::GraphViewer& graph,
const std::vector<const KernelRegistry*>& kernel_registries) const {
std::vector<std::unique_ptr<ComputeCapability>> result;
std::unordered_set<const NodeArg*> defs_outside_cuda;
for (auto& node_index : graph.GetNodesInTopologicalOrder()) {
const auto* p_node = graph.GetNode(node_index);
if (p_node == nullptr)
continue;
const auto& node = *p_node;
const KernelCreateInfo* cuda_kernel_def = nullptr;
if (!node.GetExecutionProviderType().empty()) {
defs_outside_cuda.insert(node.OutputDefs().cbegin(), node.OutputDefs().cend());
continue;
}
for (auto registry : kernel_registries) {
auto st = registry->TryFindKernel(node, Type(), &cuda_kernel_def);
// at least one registry has a CUDA kernel for this node
if (st.IsOK())
break;
}
// none of the provided registries has a CUDA kernel for this node
if (cuda_kernel_def == nullptr) {
// node is not in cuda exeuction provider if no kernel def found,
// or if other execution provider already assigned to it
defs_outside_cuda.insert(node.OutputDefs().cbegin(), node.OutputDefs().cend());
continue;
}
bool not_supported = false;
bool force_outside = false;
bool force_inside = false; // for some compute heavy ops, we'll force it to run inside CUDA
if ("LSTM" == node.OpType()) {
// the supported activations covers the bidirectional mode
std::vector<std::string> activations_supported{"sigmoid", "tanh", "tanh", "sigmoid", "tanh", "tanh"};
not_supported = RNNNeedFallbackToCPU(node, activations_supported, node.OpType());
force_inside = !not_supported;
} else if ("RNN" == node.OpType()) {
std::vector<std::string> activations_supported{"tanh", "tanh"};
not_supported = RNNNeedFallbackToCPU(node, activations_supported, node.OpType());
force_inside = !not_supported;
} else if ("GRU" == node.OpType()) {
std::vector<std::string> activations_supported{"sigmoid", "tanh", "sigmoid", "tanh"};
not_supported = RNNNeedFallbackToCPU(node, activations_supported, node.OpType());
force_inside = !not_supported;
} else if ("Conv" == node.OpType()) {
not_supported = ConvNeedFallbackToCPU(node);
force_inside = !not_supported;
} else if ("Cast" == node.OpType()) {
not_supported = CastNeedFallbackToCPU(node);
// cast is not compute heavy, and may be placed outside
}
//Below rule only works for inference, for training, we can't do constant folding.
//We need find a better solution.
//Temporary disable the check here, the cost is all the cast will be on GPU now.
#ifndef ENABLE_TRAINING
if (!not_supported && !force_inside) {
// Note that nodes with only inputs from initializer would not be place on CUDA
// Ideally, those nodes should be eliminated in constant folding
bool should_force_outside = true;
bool all_inputs_are_initializers = true;
ORT_THROW_IF_ERROR(node.ForEachWithIndex(node.InputDefs(),
[&](const NodeArg& def, size_t index) {
// The input is not a initializer and the input is from CPU
// or the input declared as CPU memory and is from CPU
// in that case we should still keep the node on CUDA
bool initializer_input = graph.IsConstantInitializer(def.Name(), /*check_outer_scope*/ true);
bool input_is_on_cpu = defs_outside_cuda.count(&def) > 0;
if ((!initializer_input && !input_is_on_cpu) ||
(input_is_on_cpu && cuda_kernel_def->kernel_def->IsInputOnCpu(index))) {
should_force_outside = false;
}
if (!initializer_input) {
all_inputs_are_initializers = false;
}
return Status::OK();
}));
// If all the inputs are initializers, we shouldn't force it to CPU
if (should_force_outside && !all_inputs_are_initializers) {
force_outside = true;
}
}
#endif
if (!force_inside && (not_supported || force_outside)) {
defs_outside_cuda.insert(node.OutputDefs().cbegin(), node.OutputDefs().cend());
if (not_supported) {
LOGS_DEFAULT(WARNING) << "CUDA kernel not supported. Fallback to CPU execution provider for Op type: " << node.OpType() << " node name: " << node.Name();
} else if (force_outside) {
LOGS_DEFAULT(INFO) << "Force fallback to CPU execution provider for Op type: " << node.OpType() << " node name: " << node.Name();
}
} else {
// for nodes placed on CUDA, check if its output is on CPU
ORT_THROW_IF_ERROR(node.ForEachWithIndex(
node.OutputDefs(),
[&](const NodeArg& def, size_t out_index) {
if (cuda_kernel_def->kernel_def->OutputMemoryType(out_index) != OrtMemTypeDefault)
defs_outside_cuda.insert(&def);
return Status::OK();
}));
std::unique_ptr<IndexedSubGraph> sub_graph = onnxruntime::make_unique<IndexedSubGraph>();
sub_graph->nodes.push_back(node.Index());
result.push_back(onnxruntime::make_unique<ComputeCapability>(std::move(sub_graph)));
}
}
return result;
}
} // namespace onnxruntime
|
// Copyright (c), Firelight Technologies Pty, Ltd. 2012-2019.
#include "FMODAssetTable.h"
#include "FMODEvent.h"
#include "FMODSnapshot.h"
#include "FMODSnapshotReverb.h"
#include "FMODBank.h"
#include "FMODBus.h"
#include "FMODVCA.h"
#include "FMODUtils.h"
#include "FMODSettings.h"
#include "FMODFileCallbacks.h"
#include "FMODStudioPrivatePCH.h"
#include "fmod_studio.hpp"
#include "Misc/Paths.h"
#include "UObject/Package.h"
#if WITH_EDITOR
#include "AssetRegistryModule.h"
#endif
FFMODAssetTable::FFMODAssetTable()
: StudioSystem(nullptr)
{
}
FFMODAssetTable::~FFMODAssetTable()
{
Destroy();
}
void FFMODAssetTable::Create()
{
Destroy();
// Create a sandbox system purely for loading and considering banks
verifyfmod(FMOD::Studio::System::create(&StudioSystem));
FMOD::System *lowLevelSystem = nullptr;
verifyfmod(StudioSystem->getCoreSystem(&lowLevelSystem));
verifyfmod(lowLevelSystem->setOutput(FMOD_OUTPUTTYPE_NOSOUND));
AttachFMODFileSystem(lowLevelSystem, 2048);
verifyfmod(
StudioSystem->initialize(1, FMOD_STUDIO_INIT_ALLOW_MISSING_PLUGINS | FMOD_STUDIO_INIT_SYNCHRONOUS_UPDATE, FMOD_INIT_MIX_FROM_UPDATE, 0));
}
void FFMODAssetTable::Destroy()
{
if (StudioSystem != nullptr)
{
verifyfmod(StudioSystem->release());
}
StudioSystem = nullptr;
}
UFMODAsset *FFMODAssetTable::FindByName(const FString &Name) const
{
const TWeakObjectPtr<UFMODAsset> *FoundAsset = FullNameLookup.Find(Name);
if (FoundAsset)
{
return FoundAsset->Get();
}
return nullptr;
}
void FFMODAssetTable::Refresh()
{
if (StudioSystem == nullptr)
{
return;
}
BuildBankPathLookup();
if (!MasterStringsBankPath.IsEmpty())
{
const UFMODSettings &Settings = *GetDefault<UFMODSettings>();
FString StringPath = Settings.GetFullBankPath() / MasterStringsBankPath;
UE_LOG(LogFMOD, Log, TEXT("Loading strings bank: %s"), *StringPath);
FMOD::Studio::Bank *StudioStringBank;
FMOD_RESULT StringResult = StudioSystem->loadBankFile(TCHAR_TO_UTF8(*StringPath), FMOD_STUDIO_LOAD_BANK_NORMAL, &StudioStringBank);
if (StringResult == FMOD_OK)
{
TArray<char> RawBuffer;
RawBuffer.SetNum(256); // Initial capacity
int Count = 0;
verifyfmod(StudioStringBank->getStringCount(&Count));
for (int StringIdx = 0; StringIdx < Count; ++StringIdx)
{
FMOD_RESULT Result;
FMOD::Studio::ID Guid = { 0 };
while (true)
{
int ActualSize = 0;
Result = StudioStringBank->getStringInfo(StringIdx, &Guid, RawBuffer.GetData(), RawBuffer.Num(), &ActualSize);
if (Result == FMOD_ERR_TRUNCATED)
{
RawBuffer.SetNum(ActualSize);
}
else
{
break;
}
}
verifyfmod(Result);
FString AssetName(UTF8_TO_TCHAR(RawBuffer.GetData()));
FGuid AssetGuid = FMODUtils::ConvertGuid(Guid);
if (!AssetName.IsEmpty())
{
AddAsset(AssetGuid, AssetName);
}
}
verifyfmod(StudioStringBank->unload());
verifyfmod(StudioSystem->update());
}
else
{
UE_LOG(LogFMOD, Warning, TEXT("Failed to load strings bank: %s"), *StringPath);
}
}
}
void FFMODAssetTable::AddAsset(const FGuid &AssetGuid, const FString &AssetFullName)
{
FString AssetPath = AssetFullName;
FString AssetType = "";
FString AssetFileName = "asset";
int DelimIndex;
if (AssetPath.FindChar(':', DelimIndex))
{
AssetType = AssetPath.Left(DelimIndex);
AssetPath = AssetPath.Right(AssetPath.Len() - DelimIndex - 1);
}
FString FormattedAssetType = "";
UClass *AssetClass = UFMODAsset::StaticClass();
if (AssetType.Equals(TEXT("event")))
{
FormattedAssetType = TEXT("Events");
AssetClass = UFMODEvent::StaticClass();
}
else if (AssetType.Equals(TEXT("snapshot")))
{
FormattedAssetType = TEXT("Snapshots");
AssetClass = UFMODSnapshot::StaticClass();
}
else if (AssetType.Equals(TEXT("bank")))
{
FormattedAssetType = TEXT("Banks");
AssetClass = UFMODBank::StaticClass();
}
else if (AssetType.Equals(TEXT("bus")))
{
FormattedAssetType = TEXT("Buses");
AssetClass = UFMODBus::StaticClass();
}
else if (AssetType.Equals(TEXT("vca")))
{
FormattedAssetType = TEXT("VCAs");
AssetClass = UFMODVCA::StaticClass();
}
else if (AssetType.Equals(TEXT("parameter")))
{
return;
}
else
{
UE_LOG(LogFMOD, Warning, TEXT("Unknown asset type: %s"), *AssetType);
}
if (AssetPath.FindLastChar('/', DelimIndex))
{
AssetFileName = AssetPath.Right(AssetPath.Len() - DelimIndex - 1);
AssetPath = AssetPath.Left(AssetPath.Len() - AssetFileName.Len() - 1);
}
else
{
// No path part, all name
AssetFileName = AssetPath;
AssetPath = TEXT("");
}
if (AssetFileName.IsEmpty() || AssetFileName.Contains(TEXT(".strings")))
{
UE_LOG(LogFMOD, Log, TEXT("Skipping asset: %s"), *AssetFullName);
return;
}
AssetPath = AssetPath.Replace(TEXT(" "), TEXT("_"));
FString AssetShortName = AssetFileName.Replace(TEXT(" "), TEXT("_"));
AssetShortName = AssetShortName.Replace(TEXT("."), TEXT("_"));
const UFMODSettings &Settings = *GetDefault<UFMODSettings>();
FString FolderPath = Settings.ContentBrowserPrefix;
FolderPath += FormattedAssetType;
FolderPath += AssetPath;
FString AssetPackagePath = FolderPath + TEXT("/") + AssetShortName;
FName AssetPackagePathName(*AssetPackagePath);
TWeakObjectPtr<UFMODAsset> &ExistingNameAsset = NameMap.FindOrAdd(AssetPackagePathName);
TWeakObjectPtr<UFMODAsset> &ExistingGuidAsset = GuidMap.FindOrAdd(AssetGuid);
TWeakObjectPtr<UFMODAsset> &ExistingFullNameLookupAsset = FullNameLookup.FindOrAdd(AssetFullName);
UFMODAsset *AssetNameObject = ExistingNameAsset.Get();
if (AssetNameObject == nullptr)
{
UE_LOG(LogFMOD, Log, TEXT("Constructing asset: %s"), *AssetPackagePath);
UPackage *NewPackage = CreatePackage(nullptr, *AssetPackagePath);
if (IsValid(NewPackage))
{
if (!GEventDrivenLoaderEnabled)
{
NewPackage->SetPackageFlags(PKG_CompiledIn);
}
AssetNameObject = NewObject<UFMODAsset>(NewPackage, AssetClass, FName(*AssetShortName), RF_Standalone | RF_Public /* | RF_Transient */);
AssetNameObject->AssetGuid = AssetGuid;
AssetNameObject->bShowAsAsset = true;
AssetNameObject->FileName = AssetFileName;
#if WITH_EDITOR
FAssetRegistryModule &AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry"));
AssetRegistryModule.Get().AddPath(*FolderPath);
FAssetRegistryModule::AssetCreated(AssetNameObject);
#endif
}
else
{
UE_LOG(LogFMOD, Warning, TEXT("Failed to construct package for asset %s"), *AssetPackagePath);
}
if (AssetClass == UFMODSnapshot::StaticClass())
{
FString ReverbFolderPath = Settings.ContentBrowserPrefix;
ReverbFolderPath += TEXT("Reverbs");
ReverbFolderPath += AssetPath;
FString ReverbAssetPackagePath = ReverbFolderPath + TEXT("/") + AssetShortName;
UPackage *ReverbPackage = CreatePackage(nullptr, *ReverbAssetPackagePath);
if (ReverbPackage)
{
if (!GEventDrivenLoaderEnabled)
{
ReverbPackage->SetPackageFlags(PKG_CompiledIn);
}
UFMODSnapshotReverb *AssetReverb = NewObject<UFMODSnapshotReverb>(
ReverbPackage, UFMODSnapshotReverb::StaticClass(), FName(*AssetShortName), RF_Standalone | RF_Public /* | RF_Transient */);
AssetReverb->AssetGuid = AssetGuid;
AssetReverb->bShowAsAsset = true;
#if WITH_EDITOR
FAssetRegistryModule &AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry"));
AssetRegistryModule.Get().AddPath(*ReverbFolderPath);
FAssetRegistryModule::AssetCreated(AssetReverb);
#endif
}
}
}
UFMODAsset *AssetGuidObject = ExistingGuidAsset.Get();
if (IsValid(AssetGuidObject) && AssetGuidObject != AssetNameObject)
{
FString OldPath = AssetGuidObject->GetPathName();
UE_LOG(LogFMOD, Log, TEXT("Hiding old asset '%s'"), *OldPath);
// We had an asset with the same guid but it must have been renamed
// We just hide the old asset from the asset table
AssetGuidObject->bShowAsAsset = false;
#if WITH_EDITOR
FAssetRegistryModule::AssetRenamed(AssetNameObject, OldPath);
#endif
}
ExistingNameAsset = AssetNameObject;
ExistingGuidAsset = AssetNameObject;
ExistingFullNameLookupAsset = AssetNameObject;
}
FString FFMODAssetTable::GetBankPath(const UFMODBank &Bank) const
{
FString BankPath = "";
const FString* File = BankPathLookup.Find(Bank.AssetGuid);
if (File)
{
BankPath = *File;
}
else
{
UE_LOG(LogFMOD, Warning, TEXT("Could not find disk file for bank %s"), *Bank.FileName);
}
return BankPath;
}
FString FFMODAssetTable::GetMasterBankPath() const
{
return MasterBankPath;
}
FString FFMODAssetTable::GetMasterStringsBankPath() const
{
return MasterStringsBankPath;
}
FString FFMODAssetTable::GetMasterAssetsBankPath() const
{
return MasterAssetsBankPath;
}
void FFMODAssetTable::BuildBankPathLookup()
{
const UFMODSettings &Settings = *GetDefault<UFMODSettings>();
TArray<FString> BankPaths;
Settings.GetAllBankPaths(BankPaths, true);
BankPathLookup.Empty(BankPaths.Num());
MasterBankPath.Empty();
MasterStringsBankPath.Empty();
MasterAssetsBankPath.Empty();
if (BankPaths.Num() == 0)
{
return;
}
for (FString BankPath : BankPaths)
{
FMOD::Studio::Bank *Bank;
FMOD_RESULT result = StudioSystem->loadBankFile(TCHAR_TO_UTF8(*BankPath), FMOD_STUDIO_LOAD_BANK_NORMAL, &Bank);
FMOD_GUID GUID;
if (result == FMOD_OK)
{
result = Bank->getID(&GUID);
Bank->unload();
}
if (result == FMOD_OK)
{
FString CurFilename = FPaths::GetCleanFilename(BankPath);
BankPath = BankPath.RightChop(Settings.GetFullBankPath().Len() + 1);
BankPathLookup.Add(FMODUtils::ConvertGuid(GUID), BankPath);
if (MasterBankPath.IsEmpty() && CurFilename == Settings.GetMasterBankFilename())
{
MasterBankPath = BankPath;
}
else if (MasterStringsBankPath.IsEmpty() && CurFilename == Settings.GetMasterStringsBankFilename())
{
MasterStringsBankPath = BankPath;
}
else if (MasterAssetsBankPath.IsEmpty() && CurFilename == Settings.GetMasterAssetsBankFilename())
{
MasterAssetsBankPath = BankPath;
}
}
if (result != FMOD_OK)
{
UE_LOG(LogFMOD, Error, TEXT("Failed to register disk file for bank: %s"), *BankPath);
}
}
StudioSystem->flushCommands();
}
|
#include "GameNetClient.h"
//#include "MessageHeader.h"
#include "KMessage.h"
//#include "LoginController.h"
//#include "SceneController.h"
//#include "PlayerController.h"
//#include "PlayerData.h"
//#include "GameUIController.h"
//#include "TaskController.h"
//#include "DialogController.h"
//#include "ActivityManager.h"
//#include "PetManager.h"
//#include "GameSocket.h"
//#include "GameGobal.h"
//#include "GameUILayer.h"
//#include "SceneLayer.h"
//#include "InstanceManager.h"
//#include "FriendManager.h"
USING_NS_CC;
#define RECV_LEN 4096
GameNetClient::GameNetClient()
{
heartBeatTime = 0;
}
//void GameNetClient::handlMessage(Message& msg)
//{
// uint16 messageID = msg.getOpcode();
// switch(messageID)
// {
// case msg_player_role_list_s2c:
// {
// //LoginController::getInstance().recRoleListS2C(msg);
// break;
// }
// default:
// break;
// }
//}
void GameNetClient::tick(float dt)
{
NetClient::tick(dt);
//return;//for test.
if (sock && isConnect)
{
handleHeartBeat(dt);
}
}
void GameNetClient::noticeSocketDisconnect(int len, int sockErr)
{
CCLOG("socket disconnet!!!!!!!!!, len: %d, error: %d", len, sockErr);
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
switch (sockErr)
{
case ETIMEDOUT:
CCLOG("Connection timed out");
break;
case ECONNREFUSED:
CCLOG("Connection refused");
break;
case EHOSTDOWN:
CCLOG("Host is down");
break;
case EHOSTUNREACH:
CCLOG("No route to host");
break;
}
#endif
MessageBox("socket disconnet!", "");
}
void GameNetClient::reConnectBtnCallback(void* result, void* bindData)
{
}
void GameNetClient::handleHeartBeat(float dt)
{
heartBeatTime += dt;
if (heartBeatTime > HEARTBEAT_INTERVAL)
{
//KMessage::
/* Message msg;
msg.setOpcode(msg_heartbeat_c2s);
int beatTime = TimeUtil::getInstance().currentTimestamp1();
msg << beatTime;
sendMessage(msg);*/
KMessage::sendActiveAck();
heartBeatTime = 0;
}
}
|
/*
Copyright 2013-present Barefoot Networks, 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 "midend.h"
#include "frontends/common/constantFolding.h"
#include "frontends/common/resolveReferences/resolveReferences.h"
#include "frontends/p4/evaluator/evaluator.h"
#include "frontends/p4/fromv1.0/v1model.h"
#include "frontends/p4/moveDeclarations.h"
#include "frontends/p4/simplify.h"
#include "frontends/p4/simplifyParsers.h"
#include "frontends/p4/strengthReduction.h"
#include "frontends/p4/typeChecking/typeChecker.h"
#include "frontends/p4/typeMap.h"
#include "frontends/p4/uniqueNames.h"
#include "frontends/p4/unusedDeclarations.h"
#include "midend/actionSynthesis.h"
#include "midend/complexComparison.h"
#include "midend/convertEnums.h"
#include "midend/copyStructures.h"
#include "midend/eliminateTuples.h"
#include "midend/eliminateNewtype.h"
#include "midend/eliminateSerEnums.h"
#include "midend/local_copyprop.h"
#include "midend/nestedStructs.h"
#include "midend/removeLeftSlices.h"
#include "midend/removeParameters.h"
#include "midend/removeUnusedParameters.h"
#include "midend/simplifyKey.h"
#include "midend/simplifySelectCases.h"
#include "midend/simplifySelectList.h"
#include "midend/removeSelectBooleans.h"
#include "midend/validateProperties.h"
#include "midend/compileTimeOps.h"
#include "midend/orderArguments.h"
#include "midend/predication.h"
#include "midend/expandLookahead.h"
#include "midend/expandEmit.h"
#include "midend/tableHit.h"
#include "midend/midEndLast.h"
namespace BMV2 {
SimpleSwitchMidEnd::SimpleSwitchMidEnd(CompilerOptions& options) : MidEnd(options) {
auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap);
auto convertEnums = new P4::ConvertEnums(&refMap, &typeMap, new EnumOn32Bits("v1model.p4"));
addPasses({
new P4::EliminateNewtype(&refMap, &typeMap),
new P4::EliminateSerEnums(&refMap, &typeMap),
new P4::RemoveActionParameters(&refMap, &typeMap),
convertEnums,
new VisitFunctor([this, convertEnums]() { enumMap = convertEnums->getEnumMapping(); }),
new P4::OrderArguments(&refMap, &typeMap),
new P4::TypeChecking(&refMap, &typeMap),
new P4::SimplifyKey(&refMap, &typeMap,
new P4::OrPolicy(
new P4::IsValid(&refMap, &typeMap),
new P4::IsMask())),
new P4::ConstantFolding(&refMap, &typeMap),
new P4::StrengthReduction(),
new P4::SimplifySelectCases(&refMap, &typeMap, true), // require constant keysets
new P4::ExpandLookahead(&refMap, &typeMap),
new P4::ExpandEmit(&refMap, &typeMap),
new P4::SimplifyParsers(&refMap),
new P4::StrengthReduction(),
new P4::EliminateTuples(&refMap, &typeMap),
new P4::SimplifyComparisons(&refMap, &typeMap),
new P4::CopyStructures(&refMap, &typeMap),
new P4::NestedStructs(&refMap, &typeMap),
new P4::SimplifySelectList(&refMap, &typeMap),
new P4::RemoveSelectBooleans(&refMap, &typeMap),
new P4::Predication(&refMap),
new P4::MoveDeclarations(), // more may have been introduced
new P4::ConstantFolding(&refMap, &typeMap),
new P4::LocalCopyPropagation(&refMap, &typeMap),
new P4::ConstantFolding(&refMap, &typeMap),
new P4::MoveDeclarations(),
new P4::ValidateTableProperties({ "implementation",
"size",
"counters",
"meters",
"support_timeout" }),
new P4::SimplifyControlFlow(&refMap, &typeMap),
new P4::CompileTimeOperations(),
new P4::TableHit(&refMap, &typeMap),
new P4::RemoveLeftSlices(&refMap, &typeMap),
// p4c-bm removed unused action parameters. To produce a compatible
// control plane API, we remove them as well for P4-14 programs.
isv1 ? new P4::RemoveUnusedActionParameters(&refMap) : nullptr,
new P4::TypeChecking(&refMap, &typeMap),
new P4::MidEndLast(),
evaluator,
new VisitFunctor([this, evaluator]() { toplevel = evaluator->getToplevelBlock(); }),
});
}
} // namespace BMV2
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "myriad_layers_slice_test.hpp"
INSTANTIATE_TEST_CASE_P(accuracy, myriadLayersTestsSlice_smoke,
::testing::Values<SliceTestParams>(
MAKE_STRUCT(SliceParams, {4, 8, 16, 32, 64}, {{4, 8, 16, 10, 64}, {4, 8, 16, 22, 64}}, 3),
MAKE_STRUCT(SliceParams, {4, 8, 16, 32}, {{4, 8, 2, 32}, {4, 8, 14, 32}}, 2))
);
|
/*
* Copyright 2013 Kyle Treubig
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MOVERULECOMMAND_HPP
#define MOVERULECOMMAND_HPP
// Qt include(s)
#include <QList>
#include <QUndoCommand>
// UnderBudget include(s)
#include "budget/AssignmentRule.hpp"
// Forward delcaration(s)
class AssignmentRules;
namespace ub {
/**
* An undoable command to move an existing rule within the rules list.
*
* @ingroup rule_commands
*/
class MoveRuleCommand : public QUndoCommand
{
public:
/**
* Constructs a new move rule command. It is critical to note that the
* rules list pointer being given is not owned by this object, and it
* may be deleted externally at any time. Since the `QUndoStack` that
* will take ownership of this command is tied to the `Session` that
* also holds a `QSharedPointer` to the encompassing budget, it should
* be impossible for the rules list to be deleted while this command
* is still relevant.
*
* @param[in] rules rules list
* @param[in] from original index from which to move the rule
* @param[in] to destination index to which to move the rule
* @param[in] parent parent undoable command for grouping
*/
MoveRuleCommand(AssignmentRules* rules, int from, int to,
QUndoCommand* parent);
// Overriding methods
int id() const;
bool mergeWith(const QUndoCommand* command);
void redo();
void undo();
private:
/** Move rule command ID */
static const int ID;
/** Rules list */
AssignmentRules* rules;
/** Original index of the rule to be moved */
const int oldIndex;
/** New index of the rule to be moved */
const int newIndex;
};
}
#endif //MOVERULECOMMAND_HPP
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2017-2018 The LitecoinZ developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "base58.h"
#include "checkpoints.h"
#include "consensus/validation.h"
#include "main.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "sync.h"
#include "util.h"
#include <stdint.h>
#include <univalue.h>
#include <regex>
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
double GetDifficultyINTERNAL(const CBlockIndex* blockindex, bool networkDifficulty)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (chainActive.Tip() == NULL)
return 1.0;
else
blockindex = chainActive.Tip();
}
uint32_t bits;
if (networkDifficulty) {
bits = GetNextWorkRequired(blockindex, nullptr, Params().GetConsensus());
} else {
bits = blockindex->nBits;
}
uint32_t powLimit =
UintToArith256(Params().GetConsensus().powLimit).GetCompact();
int nShift = (bits >> 24) & 0xff;
int nShiftAmount = (powLimit >> 24) & 0xff;
double dDiff =
(double)(powLimit & 0x00ffffff) /
(double)(bits & 0x00ffffff);
while (nShift < nShiftAmount)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > nShiftAmount)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
double GetDifficulty(const CBlockIndex* blockindex)
{
return GetDifficultyINTERNAL(blockindex, false);
}
double GetNetworkDifficulty(const CBlockIndex* blockindex)
{
return GetDifficultyINTERNAL(blockindex, true);
}
static UniValue ValuePoolDesc(
const std::string &name,
const boost::optional<CAmount> chainValue,
const boost::optional<CAmount> valueDelta)
{
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("id", name));
rv.push_back(Pair("monitored", (bool)chainValue));
if (chainValue) {
rv.push_back(Pair("chainValue", ValueFromAmount(*chainValue)));
rv.push_back(Pair("chainValueZat", *chainValue));
}
if (valueDelta) {
rv.push_back(Pair("valueDelta", ValueFromAmount(*valueDelta)));
rv.push_back(Pair("valueDeltaZat", *valueDelta));
}
return rv;
}
UniValue blockheaderToJSON(const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", blockindex->nVersion));
result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
result.push_back(Pair("time", (int64_t)blockindex->nTime));
result.push_back(Pair("nonce", blockindex->nNonce.GetHex()));
result.push_back(Pair("solution", HexStr(blockindex->nSolution)));
result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue blockToDeltasJSON(const CBlock& block, const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", block.GetHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex)) {
confirmations = chainActive.Height() - blockindex->nHeight + 1;
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block is an orphan");
}
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
UniValue deltas(UniValue::VARR);
for (unsigned int i = 0; i < block.vtx.size(); i++) {
const CTransaction &tx = block.vtx[i];
const uint256 txhash = tx.GetHash();
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txhash.GetHex()));
entry.push_back(Pair("index", (int)i));
UniValue inputs(UniValue::VARR);
if (!tx.IsCoinBase()) {
for (size_t j = 0; j < tx.vin.size(); j++) {
const CTxIn input = tx.vin[j];
UniValue delta(UniValue::VOBJ);
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(input.prevout.hash, input.prevout.n);
if (GetSpentIndex(spentKey, spentInfo)) {
if (spentInfo.addressType == 1) {
delta.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
delta.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
} else {
continue;
}
delta.push_back(Pair("satoshis", -1 * spentInfo.satoshis));
delta.push_back(Pair("index", (int)j));
delta.push_back(Pair("prevtxid", input.prevout.hash.GetHex()));
delta.push_back(Pair("prevout", (int)input.prevout.n));
inputs.push_back(delta);
} else {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Spent information not available");
}
}
}
entry.push_back(Pair("inputs", inputs));
UniValue outputs(UniValue::VARR);
for (unsigned int k = 0; k < tx.vout.size(); k++) {
const CTxOut &out = tx.vout[k];
UniValue delta(UniValue::VOBJ);
if (out.scriptPubKey.IsPayToScriptHash()) {
vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
delta.push_back(Pair("address", CBitcoinAddress(CScriptID(uint160(hashBytes))).ToString()));
} else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
delta.push_back(Pair("address", CBitcoinAddress(CKeyID(uint160(hashBytes))).ToString()));
} else {
continue;
}
delta.push_back(Pair("satoshis", out.nValue));
delta.push_back(Pair("index", (int)k));
outputs.push_back(delta);
}
entry.push_back(Pair("outputs", outputs));
deltas.push_back(entry);
}
result.push_back(Pair("deltas", deltas));
result.push_back(Pair("time", block.GetBlockTime()));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", block.nNonce.GetHex()));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", block.GetHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
UniValue txs(UniValue::VARR);
BOOST_FOREACH(const CTransaction&tx, block.vtx)
{
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
TxToJSON(tx, uint256(), objTx);
txs.push_back(objTx);
}
else
txs.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", block.GetBlockTime()));
result.push_back(Pair("nonce", block.nNonce.GetHex()));
result.push_back(Pair("solution", HexStr(block.nSolution)));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
result.push_back(Pair("anchor", blockindex->hashAnchorEnd.GetHex()));
UniValue valuePools(UniValue::VARR);
valuePools.push_back(ValuePoolDesc("sprout", blockindex->nChainSproutValue, blockindex->nSproutValue));
result.push_back(Pair("valuePools", valuePools));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue getblockcount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"\nReturns the number of blocks in the best valid block chain.\n"
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n"
+ HelpExampleCli("getblockcount", "")
+ HelpExampleRpc("getblockcount", "")
);
LOCK(cs_main);
return chainActive.Height();
}
UniValue getbestblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"\nReturns the hash of the best (tip) block in the longest block chain.\n"
"\nResult\n"
"\"hex\" (string) the block hash hex encoded\n"
"\nExamples\n"
+ HelpExampleCli("getbestblockhash", "")
+ HelpExampleRpc("getbestblockhash", "")
);
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
UniValue getdifficulty(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nResult:\n"
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nExamples:\n"
+ HelpExampleCli("getdifficulty", "")
+ HelpExampleRpc("getdifficulty", "")
);
LOCK(cs_main);
return GetNetworkDifficulty();
}
UniValue mempoolToJSON(bool fVerbose = false)
{
if (fVerbose)
{
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(const PAIRTYPE(uint256, CTxMemPoolEntry)& entry, mempool.mapTx)
{
const uint256& hash = entry.first;
const CTxMemPoolEntry& e = entry.second;
UniValue info(UniValue::VOBJ);
info.push_back(Pair("size", (int)e.GetTxSize()));
info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
info.push_back(Pair("time", e.GetTime()));
info.push_back(Pair("height", (int)e.GetHeight()));
info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
const CTransaction& tx = e.GetTx();
set<string> setDepends;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
BOOST_FOREACH(const string& dep, setDepends)
{
depends.push_back(dep);
}
info.push_back(Pair("depends", depends));
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
else
{
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
}
UniValue getrawmempool(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawmempool ( verbose )\n"
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
" \"size\" : n, (numeric) transaction size in bytes\n"
" \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
" \"currentpriority\" : n, (numeric) transaction priority now\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ]\n"
" }, ...\n"
"}\n"
"\nExamples\n"
+ HelpExampleCli("getrawmempool", "true")
+ HelpExampleRpc("getrawmempool", "true")
);
LOCK(cs_main);
bool fVerbose = false;
if (params.size() > 0)
fVerbose = params[0].get_bool();
return mempoolToJSON(fVerbose);
}
UniValue getblockdeltas(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error("");
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
if(!ReadBlockFromDisk(block, pblockindex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
return blockToDeltasJSON(block, pblockindex);
}
UniValue getblockhashes(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2)
throw runtime_error(
"getblockhashes timestamp\n"
"\nReturns array of hashes of blocks within the timestamp range provided.\n"
"\nArguments:\n"
"1. high (numeric, required) The newer block timestamp\n"
"2. low (numeric, required) The older block timestamp\n"
"3. options (string, required) A json object\n"
" {\n"
" \"noOrphans\":true (boolean) will only include blocks on the main chain\n"
" \"logicalTimes\":true (boolean) will include logical timestamps with hashes\n"
" }\n"
"\nResult:\n"
"[\n"
" \"hash\" (string) The block hash\n"
"]\n"
"[\n"
" {\n"
" \"blockhash\": (string) The block hash\n"
" \"logicalts\": (numeric) The logical timestamp\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhashes", "1231614698 1231024505")
+ HelpExampleRpc("getblockhashes", "1231614698, 1231024505")
+ HelpExampleCli("getblockhashes", "1231614698 1231024505 '{\"noOrphans\":false, \"logicalTimes\":true}'")
);
unsigned int high = params[0].get_int();
unsigned int low = params[1].get_int();
bool fActiveOnly = false;
bool fLogicalTS = false;
if (params.size() > 2) {
if (params[2].isObject()) {
UniValue noOrphans = find_value(params[2].get_obj(), "noOrphans");
UniValue returnLogical = find_value(params[2].get_obj(), "logicalTimes");
if (noOrphans.isBool())
fActiveOnly = noOrphans.get_bool();
if (returnLogical.isBool())
fLogicalTS = returnLogical.get_bool();
}
}
std::vector<std::pair<uint256, unsigned int> > blockHashes;
if (fActiveOnly)
LOCK(cs_main);
if (!GetTimestampIndex(high, low, fActiveOnly, blockHashes)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
}
UniValue result(UniValue::VARR);
for (std::vector<std::pair<uint256, unsigned int> >::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) {
if (fLogicalTS) {
UniValue item(UniValue::VOBJ);
item.push_back(Pair("blockhash", it->first.GetHex()));
item.push_back(Pair("logicalts", (int)it->second));
result.push_back(item);
} else {
result.push_back(it->first.GetHex());
}
}
return result;
}
UniValue getblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash index\n"
"\nReturns hash of block in best-block-chain at index provided.\n"
"\nArguments:\n"
"1. index (numeric, required) The block index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
);
LOCK(cs_main);
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
UniValue getblockheader(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblockheader \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
"If verbose is true, returns an Object with information about blockheader <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(pblockindex);
}
UniValue getblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock \"hash|height\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash|height'.\n"
"If verbose is true, returns an Object with information about block <hash|height>.\n"
"\nArguments:\n"
"1. \"hash|height\" (string, required) The block hash or height\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided hash)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"height\" : n, (numeric) The block height or index (same as provided height)\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleCli("getblock", "12800")
+ HelpExampleRpc("getblock", "12800")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
// If height is supplied, find the hash
if (strHash.size() < (2 * sizeof(uint256))) {
// std::stoi allows characters, whereas we want to be strict
regex r("[[:digit:]]+");
if (!regex_match(strHash, r)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block height parameter");
}
int nHeight = -1;
try {
nHeight = std::stoi(strHash);
}
catch (const std::exception &e) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block height parameter");
}
if (nHeight < 0 || nHeight > chainActive.Height()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
}
strHash = chainActive[nHeight]->GetBlockHash().GetHex();
}
uint256 hash(uint256S(strHash));
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
if(!ReadBlockFromDisk(block, pblockindex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
UniValue gettxoutsetinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gettxoutsetinfo\n"
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n"
"\nResult:\n"
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) the best block hash hex\n"
" \"transactions\": n, (numeric) The number of transactions\n"
" \"txouts\": n, (numeric) The number of output transactions\n"
" \"bytes_serialized\": n, (numeric) The serialized size\n"
" \"hash_serialized\": \"hash\", (string) The serialized hash\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutsetinfo", "")
+ HelpExampleRpc("gettxoutsetinfo", "")
);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
FlushStateToDisk();
if (pcoinsTip->GetStats(stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize));
ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
}
return ret;
}
UniValue gettxout(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"gettxout \"txid\" n ( includemempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. n (numeric, required) vout value\n"
"3. includemempool (boolean, optional) Whether to include the mempool\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of LitecoinZ addresses\n"
" \"litecoinzaddress\" (string) LitecoinZ address\n"
" ,...\n"
" ]\n"
" },\n"
" \"version\" : n, (numeric) The version\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nView the details\n"
+ HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("gettxout", "\"txid\", 1")
);
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
int n = params[1].get_int();
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
CCoins coins;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip, mempool);
if (!view.GetCoins(hash, coins))
return NullUniValue;
mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
} else {
if (!pcoinsTip->GetCoins(hash, coins))
return NullUniValue;
}
if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
return NullUniValue;
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex *pindex = it->second;
ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
ret.push_back(Pair("confirmations", 0));
else
ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("version", coins.nVersion));
ret.push_back(Pair("coinbase", coins.fCoinBase));
return ret;
}
UniValue verifychain(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"verifychain ( checklevel numblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n"
"2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n"
+ HelpExampleCli("verifychain", "")
+ HelpExampleRpc("verifychain", "")
);
LOCK(cs_main);
int nCheckLevel = GetArg("-checklevel", 3);
int nCheckDepth = GetArg("-checkblocks", 288);
if (params.size() > 0)
nCheckLevel = params[0].get_int();
if (params.size() > 1)
nCheckDepth = params[1].get_int();
return CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth);
}
/** Implementation of IsSuperMajority with better feedback */
static UniValue SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired, const Consensus::Params& consensusParams)
{
int nFound = 0;
CBlockIndex* pstart = pindex;
for (int i = 0; i < consensusParams.nMajorityWindow && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("status", nFound >= nRequired));
rv.push_back(Pair("found", nFound));
rv.push_back(Pair("required", nRequired));
rv.push_back(Pair("window", consensusParams.nMajorityWindow));
return rv;
}
static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("id", name));
rv.push_back(Pair("version", version));
rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams)));
rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityRejectBlockOutdated, consensusParams)));
return rv;
}
UniValue getblockchaininfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockchaininfo\n"
"Returns an object containing various state info regarding block chain processing.\n"
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"commitments\": xxxxxx, (numeric) the current number of note commitments in the commitment tree\n"
" \"softforks\": [ (array) status of softforks in progress\n"
" {\n"
" \"id\": \"xxxx\", (string) name of softfork\n"
" \"version\": xx, (numeric) block version\n"
" \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n"
" \"status\": xx, (boolean) true if threshold reached\n"
" \"found\": xx, (numeric) number of blocks with the new version found\n"
" \"required\": xx, (numeric) number of blocks required to trigger\n"
" \"window\": xx, (numeric) maximum size of examined window of recent blocks\n"
" },\n"
" \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n"
" }, ...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblockchaininfo", "")
+ HelpExampleRpc("getblockchaininfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("chain", Params().NetworkIDString()));
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
obj.push_back(Pair("difficulty", (double)GetNetworkDifficulty()));
obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip())));
obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
obj.push_back(Pair("pruned", fPruneMode));
ZCIncrementalMerkleTree tree;
pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), tree);
obj.push_back(Pair("commitments", static_cast<uint64_t>(tree.size())));
CBlockIndex* tip = chainActive.Tip();
UniValue valuePools(UniValue::VARR);
valuePools.push_back(ValuePoolDesc("sprout", tip->nChainSproutValue, boost::none));
obj.push_back(Pair("valuePools", valuePools));
const Consensus::Params& consensusParams = Params().GetConsensus();
UniValue softforks(UniValue::VARR);
softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
obj.push_back(Pair("softforks", softforks));
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
block = block->pprev;
obj.push_back(Pair("pruneheight", block->nHeight));
}
return obj;
}
/** Comparison function for sorting the getchaintips heads. */
struct CompareBlocksByHeight
{
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/* Make sure that unequal blocks with the same height do not compare
equal. Use the pointers themselves to make a distinction. */
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
UniValue getchaintips(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getchaintips\n"
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n"
+ HelpExampleCli("getchaintips", "")
+ HelpExampleRpc("getchaintips", "")
);
LOCK(cs_main);
/* Build up a list of chain tips. We start with the list of all
known blocks, and successively remove blocks that appear as pprev
of another block. */
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
setTips.insert(item.second);
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
const CBlockIndex* pprev = item.second->pprev;
if (pprev)
setTips.erase(pprev);
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
/* Construct the output array. */
UniValue res(UniValue::VARR);
BOOST_FOREACH(const CBlockIndex* block, setTips)
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("height", block->nHeight));
obj.push_back(Pair("hash", block->phashBlock->GetHex()));
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
obj.push_back(Pair("branchlen", branchLen));
string status;
if (chainActive.Contains(block)) {
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (block->nChainTx == 0) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.push_back(Pair("status", status));
res.push_back(obj);
}
return res;
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("size", (int64_t) mempool.size()));
ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
return ret;
}
UniValue getmempoolinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmempoolinfo\n"
"\nReturns details on the active state of the TX memory pool.\n"
"\nResult:\n"
"{\n"
" \"size\": xxxxx (numeric) Current tx count\n"
" \"bytes\": xxxxx (numeric) Sum of all tx sizes\n"
" \"usage\": xxxxx (numeric) Total memory usage for the mempool\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolinfo", "")
+ HelpExampleRpc("getmempoolinfo", "")
);
return mempoolInfoToJSON();
}
UniValue invalidateblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"invalidateblock \"hash\"\n"
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to mark as invalid\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("invalidateblock", "\"blockhash\"")
+ HelpExampleRpc("invalidateblock", "\"blockhash\"")
);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
InvalidateBlock(state, pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue reconsiderblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"reconsiderblock \"hash\"\n"
"\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to reconsider\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("reconsiderblock", "\"blockhash\"")
+ HelpExampleRpc("reconsiderblock", "\"blockhash\"")
);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
ReconsiderBlock(state, pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
|
// 07/12/2021
// Purpose: Implements the quadratic equation formula.
// (-b±√(b²-4ac))/(2a)
#include <iostream>
#include <cmath> // std::pow, std::sqrt
#include <utility> // std::pair
auto Quadf(const double& a, const double& b, const double& c) {
using std::sqrt;
using std::pow;
double positiveX = ((-b) + sqrt((pow(2, b) - 4 * a * c))) / (2 * a);
double negativeX = ((-b) - sqrt((pow(2, b) - 4 * a * c))) / (2 * a);
return std::pair<double, double> {positiveX, negativeX};
}
int main() {
auto ans = Quadf( 1, 4, -21);
std::cout << ans.first << ' ' << ans.second << '\n';
}
|
// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
template <int> int f(int); // expected-note {{candidate function}}
#if __cplusplus <= 199711L
// expected-note@-2 {{candidate function}}
#endif
template <signed char> int f(int); // expected-note {{candidate function}}
#if __cplusplus <= 199711L
// expected-note@-2 {{candidate function}}
#endif
int i1 = f<1>(0); // expected-error{{call to 'f' is ambiguous}}
int i2 = f<1000>(0);
#if __cplusplus <= 199711L
// expected-error@-2{{call to 'f' is ambiguous}}
#endif
namespace PR6707 {
template<typename T, T Value>
struct X { };
template<typename T, T Value>
void f(X<T, Value>);
void g(X<int, 10> x) {
f(x);
}
static const unsigned char ten = 10;
template<typename T, T Value, typename U>
void f2(X<T, Value>, X<U, Value>);
// expected-note@-1 {{candidate template ignored: deduced values of conflicting types for parameter 'Value' (10 of type 'int' vs. 10 of type 'char')}}
// expected-note@-2 {{candidate template ignored: deduced values of conflicting types for parameter 'Value' (10 of type 'char' vs. 10 of type 'int')}}
void g2() {
f2(X<int, 10>(), X<char, ten>()); // expected-error {{no matching}}
f2(X<char, 10>(), X<int, ten>()); // expected-error {{no matching}}
}
}
|
/***************************************************************************
* Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_EXPRESSION_HPP
#define XTENSOR_EXPRESSION_HPP
#include <cstddef>
#include <type_traits>
#include <vector>
#include <xtl/xclosure.hpp>
#include <xtl/xmeta_utils.hpp>
#include <xtl/xtype_traits.hpp>
#include "xlayout.hpp"
#include "xshape.hpp"
#include "xtensor_forward.hpp"
#include "xutils.hpp"
namespace xt
{
template <class D>
class xexpression;
template <class E>
auto make_xshared(xexpression<E>&&);
/***************************
* xexpression declaration *
***************************/
/**
* @class xexpression
* @brief Base class for xexpressions
*
* The xexpression class is the base class for all classes representing an expression
* that can be evaluated to a multidimensional container with tensor semantic.
* Functions that can apply to any xexpression regardless of its specific type should take a
* xexpression argument.
*
* \tparam E The derived type.
*
*/
template <class D>
class xexpression
{
public:
using derived_type = D;
derived_type& derived_cast() & noexcept;
const derived_type& derived_cast() const & noexcept;
derived_type derived_cast() && noexcept;
protected:
xexpression();
~xexpression() = default;
xexpression(const xexpression&) = default;
xexpression& operator=(const xexpression&) = default;
xexpression(xexpression&&) = default;
xexpression& operator=(xexpression&&) = default;
private:
std::shared_ptr<D> p_shared;
friend auto make_xshared<D>(xexpression<D>&&);
};
/******************************
* xexpression implementation *
******************************/
template <class D>
inline xexpression<D>::xexpression()
: p_shared(nullptr)
{
}
/**
* @name Downcast functions
*/
//@{
/**
* Returns a reference to the actual derived type of the xexpression.
*/
template <class D>
inline auto xexpression<D>::derived_cast() & noexcept -> derived_type&
{
return *static_cast<derived_type*>(this);
}
/**
* Returns a constant reference to the actual derived type of the xexpression.
*/
template <class D>
inline auto xexpression<D>::derived_cast() const & noexcept -> const derived_type&
{
return *static_cast<const derived_type*>(this);
}
/**
* Returns a constant reference to the actual derived type of the xexpression.
*/
template <class D>
inline auto xexpression<D>::derived_cast() && noexcept -> derived_type
{
return *static_cast<derived_type*>(this);
}
//@}
/* is_crtp_base_of<B, E>
* Resembles std::is_base_of, but adresses the problem of whether _some_ instantiation
* of a CRTP templated class B is a base of class E. A CRTP templated class is correctly
* templated with the most derived type in the CRTP hierarchy. Using this assumption,
* this implementation deals with either CRTP final classes (checks for inheritance
* with E as the CRTP parameter of B) or CRTP base classes (which are singly templated
* by the most derived class, and that's pulled out to use as a templete parameter for B).
*/
namespace detail
{
template <template <class> class B, class E>
struct is_crtp_base_of_impl : std::is_base_of<B<E>, E> {};
template <template <class> class B, class E, template <class> class F>
struct is_crtp_base_of_impl<B, F<E>> :
xtl::disjunction< std::is_base_of<B<E>, F<E>>, std::is_base_of<B<F<E>>, F<E>>> {};
}
template <template <class> class B, class E>
using is_crtp_base_of = detail::is_crtp_base_of_impl<B, std::decay_t<E>>;
template <class E>
using is_xexpression = is_crtp_base_of<xexpression, E>;
template <class E, class R = void>
using enable_xexpression = typename std::enable_if<is_xexpression<E>::value, R>::type;
template <class E, class R = void>
using disable_xexpression = typename std::enable_if<!is_xexpression<E>::value, R>::type;
template <class... E>
using has_xexpression = xtl::disjunction<is_xexpression<E>...>;
/***********************
* evaluation_strategy *
***********************/
namespace detail
{
struct option_base {};
}
namespace evaluation_strategy
{
struct immediate_type : xt::detail::option_base {};
constexpr auto immediate = std::tuple<immediate_type>{};
struct lazy_type : xt::detail::option_base {};
constexpr auto lazy = std::tuple<lazy_type>{};
/*
struct cached {};
*/
}
template <class T>
struct is_evaluation_strategy : std::is_base_of<detail::option_base, std::decay_t<T>>
{
};
/************
* xclosure *
************/
template <class T>
class xscalar;
template <class E>
class xshared_expression;
template <class E, class EN = void>
struct xclosure
{
using type = xtl::closure_type_t<E>;
};
template <class E>
struct xclosure<xshared_expression<E>, std::enable_if_t<true>>
{
using type = xshared_expression<E>; // force copy
};
template <class E>
struct xclosure<E, disable_xexpression<std::decay_t<E>>>
{
using type = xscalar<xtl::closure_type_t<E>>;
};
template <class E>
using xclosure_t = typename xclosure<E>::type;
template <class E, class EN = void>
struct const_xclosure
{
using type = xtl::const_closure_type_t<E>;
};
template <class E>
struct const_xclosure<E, disable_xexpression<std::decay_t<E>>>
{
using type = xscalar<xtl::const_closure_type_t<E>>;
};
template <class E>
struct const_xclosure<xshared_expression<E>&, std::enable_if_t<true>>
{
using type = xshared_expression<E>; // force copy
};
template <class E>
using const_xclosure_t = typename const_xclosure<E>::type;
/*************************
* expression tag system *
*************************/
struct xtensor_expression_tag
{
};
struct xoptional_expression_tag
{
};
namespace extension
{
template <class E, class = void_t<int>>
struct get_expression_tag_impl
{
using type = xtensor_expression_tag;
};
template <class E>
struct get_expression_tag_impl<E, void_t<typename std::decay_t<E>::expression_tag>>
{
using type = typename std::decay_t<E>::expression_tag;
};
template <class E>
struct get_expression_tag : get_expression_tag_impl<E>
{
};
template <class E>
using get_expression_tag_t = typename get_expression_tag<E>::type;
template <class... T>
struct expression_tag_and;
template <>
struct expression_tag_and<>
{
using type = xtensor_expression_tag;
};
template <class T>
struct expression_tag_and<T>
{
using type = T;
};
template <class T>
struct expression_tag_and<T, T>
{
using type = T;
};
template <class T>
struct expression_tag_and<xtensor_expression_tag, T>
{
using type = T;
};
template <class T>
struct expression_tag_and<T, xtensor_expression_tag>
: expression_tag_and<xtensor_expression_tag, T>
{
};
template <>
struct expression_tag_and<xtensor_expression_tag, xtensor_expression_tag>
{
using type = xtensor_expression_tag;
};
template <class T1, class... T>
struct expression_tag_and<T1, T...>
: expression_tag_and<T1, typename expression_tag_and<T...>::type>
{
};
template <class... T>
using expression_tag_and_t = typename expression_tag_and<T...>::type;
struct xtensor_empty_base
{
using expression_tag = xtensor_expression_tag;
};
}
template <class... T>
struct xexpression_tag
{
using type = extension::expression_tag_and_t<extension::get_expression_tag_t<std::decay_t<const_xclosure_t<T>>>...>;
};
template <class... T>
using xexpression_tag_t = typename xexpression_tag<T...>::type;
template <class E>
struct is_xtensor_expression : std::is_same<xexpression_tag_t<E>, xtensor_expression_tag>
{
};
template <class E>
struct is_xoptional_expression : std::is_same<xexpression_tag_t<E>, xoptional_expression_tag>
{
};
/********************************
* xoptional_comparable concept *
********************************/
template <class... E>
struct xoptional_comparable : xtl::conjunction<xtl::disjunction<is_xtensor_expression<E>,
is_xoptional_expression<E>
>...
>
{
};
#define XTENSOR_FORWARD_CONST_METHOD(name) \
auto name() const \
-> decltype(std::declval<xtl::constify_t<E>>().name()) \
{ \
return m_ptr->name(); \
}
#define XTENSOR_FORWARD_METHOD(name) \
auto name() -> decltype(std::declval<E>().name()) \
{ \
return m_ptr->name(); \
}
#define XTENSOR_FORWARD_CONST_ITERATOR_METHOD(name) \
template <layout_type L = XTENSOR_DEFAULT_TRAVERSAL> \
auto name() const noexcept \
-> decltype(std::declval<xtl::constify_t<E>>().template name<L>()) \
{ \
return m_ptr->template name<L>(); \
} \
template <layout_type L = XTENSOR_DEFAULT_TRAVERSAL, class S> \
auto name(const S& shape) const noexcept \
-> decltype(std::declval<xtl::constify_t<E>>().template name<L>(shape)) \
{ \
return m_ptr->template name<L>(); \
}
#define XTENSOR_FORWARD_ITERATOR_METHOD(name) \
template <layout_type L = XTENSOR_DEFAULT_TRAVERSAL, class S> \
auto name(const S& shape) noexcept \
-> decltype(std::declval<E>().template name<L>(shape)) \
{ \
return m_ptr->template name<L>(); \
} \
template <layout_type L = XTENSOR_DEFAULT_TRAVERSAL> \
auto name() noexcept -> decltype(std::declval<E>().template name<L>()) \
{ \
return m_ptr->template name<L>(); \
} \
namespace detail
{
template <class E>
struct expr_strides_type
{
using type = typename E::strides_type;
};
template <class E>
struct expr_inner_strides_type
{
using type = typename E::inner_strides_type;
};
template <class E>
struct expr_backstrides_type
{
using type = typename E::backstrides_type;
};
template <class E>
struct expr_inner_backstrides_type
{
using type = typename E::inner_backstrides_type;
};
template <class E>
struct expr_storage_type
{
using type = typename E::storage_type;
};
}
/**
* @class xshared_expression
* @brief Shared xexpressions
*
* Due to C++ lifetime constraints it's sometimes necessary to create shared
* expressions (akin to a shared pointer).
*
* For example, when a temporary expression needs to be used twice in another
* expression, shared expressions can come to the rescue:
*
* \code{.cpp}
* template <class E>
* auto cos_plus_sin(xexpression<E>&& expr)
* {
* // THIS IS WRONG: forwarding rvalue twice not permitted!
* // return xt::sin(std::forward<E>(expr)) + xt::cos(std::forward<E>(expr));
* // THIS IS WRONG TOO: because second `expr` is taken as reference (which will be invalid)
* // return xt::sin(std::forward<E>(expr)) + xt::cos(expr)
* auto shared_expr = xt::make_xshared(std::forward<E>(expr));
* auto result = xt::sin(shared_expr) + xt::cos(shared_expr);
* std::cout << shared_expr.use_count() << std::endl; // Will print 3 because used twice in expression
* return result; // all valid because expr lifetime managed by xshared_expression / shared_ptr.
* }
* \endcode
*/
template <class E>
class xshared_expression
: public xexpression<xshared_expression<E>>
{
public:
using base_class = xexpression<xshared_expression<E>>;
using value_type = typename E::value_type;
using reference = typename E::reference;
using const_reference = typename E::const_reference;
using pointer = typename E::pointer;
using const_pointer = typename E::const_pointer;
using size_type = typename E::size_type;
using difference_type = typename E::difference_type;
using inner_shape_type = typename E::inner_shape_type;
using shape_type = typename E::shape_type;
using strides_type = xtl::mpl::eval_if_t<has_strides<E>,
detail::expr_strides_type<E>,
get_strides_type<shape_type>>;
using backstrides_type = xtl::mpl::eval_if_t<has_strides<E>,
detail::expr_backstrides_type<E>,
get_strides_type<shape_type>>;
using inner_strides_type = xtl::mpl::eval_if_t<has_strides<E>,
detail::expr_inner_strides_type<E>,
get_strides_type<shape_type>>;
using inner_backstrides_type = xtl::mpl::eval_if_t<has_strides<E>,
detail::expr_inner_backstrides_type<E>,
get_strides_type<shape_type>>;
using storage_type = xtl::mpl::eval_if_t<has_data_interface<E>,
detail::expr_storage_type<E>,
make_invalid_type<>>;
using stepper = typename E::stepper;
using const_stepper = typename E::const_stepper;
using storage_iterator = typename E::storage_iterator;
using const_storage_iterator = typename E::const_storage_iterator;
static constexpr layout_type static_layout = E::static_layout;
static constexpr bool contiguous_layout = static_layout != layout_type::dynamic;
explicit xshared_expression(const std::shared_ptr<E>& ptr);
long use_count() const noexcept;
template <class... Args>
auto operator()(Args... args)
-> decltype(std::declval<E>()(args...))
{
return m_ptr->operator()(args...);
}
XTENSOR_FORWARD_CONST_METHOD(shape)
XTENSOR_FORWARD_CONST_METHOD(dimension)
XTENSOR_FORWARD_CONST_METHOD(size)
XTENSOR_FORWARD_CONST_METHOD(layout)
XTENSOR_FORWARD_ITERATOR_METHOD(begin)
XTENSOR_FORWARD_ITERATOR_METHOD(end)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(begin)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(end)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(cbegin)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(cend)
XTENSOR_FORWARD_ITERATOR_METHOD(rbegin)
XTENSOR_FORWARD_ITERATOR_METHOD(rend)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(rbegin)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(rend)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(crbegin)
XTENSOR_FORWARD_CONST_ITERATOR_METHOD(crend)
XTENSOR_FORWARD_METHOD(storage_begin)
XTENSOR_FORWARD_METHOD(storage_end)
XTENSOR_FORWARD_CONST_METHOD(storage_begin)
XTENSOR_FORWARD_CONST_METHOD(storage_end)
XTENSOR_FORWARD_CONST_METHOD(storage_cbegin)
XTENSOR_FORWARD_CONST_METHOD(storage_cend)
XTENSOR_FORWARD_METHOD(storage_rbegin)
XTENSOR_FORWARD_METHOD(storage_rend)
XTENSOR_FORWARD_CONST_METHOD(storage_rbegin)
XTENSOR_FORWARD_CONST_METHOD(storage_rend)
XTENSOR_FORWARD_CONST_METHOD(storage_crbegin)
XTENSOR_FORWARD_CONST_METHOD(storage_crend)
template <class T = E>
std::enable_if_t<has_strides<T>::value, const inner_strides_type&>
strides() const
{
return m_ptr->strides();
}
template <class T = E>
std::enable_if_t<has_strides<T>::value, const inner_strides_type&>
backstrides() const
{
return m_ptr->backstrides();
}
template <class T = E>
std::enable_if_t<has_data_interface<T>::value, pointer>
data() noexcept
{
return m_ptr->data();
}
template <class T = E>
std::enable_if_t<has_data_interface<T>::value, pointer>
data() const noexcept
{
return m_ptr->data();
}
template <class T = E>
std::enable_if_t<has_data_interface<T>::value, size_type>
data_offset() const noexcept
{
return m_ptr->data_offset();
}
template <class T = E>
std::enable_if_t<has_data_interface<T>::value, typename T::storage_type&>
storage() noexcept
{
return m_ptr->storage();
}
template <class T = E>
std::enable_if_t<has_data_interface<T>::value, const typename T::storage_type&>
storage() const noexcept
{
return m_ptr->storage();
}
template <class It>
auto element(It first, It last) {
return m_ptr->element(first, last);
}
template <class It>
auto element(It first, It last) const {
return m_ptr->element(first, last);
}
template <class S>
bool broadcast_shape(S& shape, bool reuse_cache = false) const
{
return m_ptr->broadcast_shape(shape, reuse_cache);
}
template <class S>
bool has_linear_assign(const S& strides) const noexcept
{
return m_ptr->has_linear_assign(strides);
}
template <class S>
auto stepper_begin(const S& shape) noexcept
-> decltype(std::declval<E>().stepper_begin(shape))
{
return m_ptr->stepper_begin(shape);
}
template <class S>
auto stepper_end(const S& shape, layout_type l) noexcept
-> decltype(std::declval<E>().stepper_end(shape, l))
{
return m_ptr->stepper_end(shape, l);
}
template <class S>
auto stepper_begin(const S& shape) const noexcept
-> decltype(std::declval<const E>().stepper_begin(shape))
{
return static_cast<const E*>(m_ptr.get())->stepper_begin(shape);
}
template <class S>
auto stepper_end(const S& shape, layout_type l) const noexcept
-> decltype(std::declval<const E>().stepper_end(shape, l))
{
return static_cast<const E*>(m_ptr.get())->stepper_end(shape, l);
}
private:
std::shared_ptr<E> m_ptr;
};
/**
* Constructor for xshared expression (note: usually the free function
* `make_xshared` is recommended).
*
* @param ptr shared ptr that contains the expression
* @sa make_xshared
*/
template <class E>
inline xshared_expression<E>::xshared_expression(const std::shared_ptr<E>& ptr)
: m_ptr(ptr)
{
}
/**
* Return the number of times this expression is referenced.
* Internally calls the use_count() function of the std::shared_ptr.
*/
template <class E>
inline long xshared_expression<E>::use_count() const noexcept
{
return m_ptr.use_count();
}
/**
* Helper function to create shared expression from any xexpression
*
* @param expr rvalue expression that will be shared
* @return xshared expression
*/
template <class E>
inline auto make_xshared(xexpression<E>&& expr)
{
if(expr.p_shared == nullptr)
{
expr.p_shared = std::make_shared<E>(std::move(expr).derived_cast());
}
return xshared_expression<E>(expr.p_shared);
}
/**
* Helper function to create shared expression from any xexpression
*
* @param expr rvalue expression that will be shared
* @return xshared expression
* @sa make_xshared
*/
template <class E>
inline auto share(xexpression<E>& expr)
{
return make_xshared(std::move(expr));
}
/**
* Helper function to create shared expression from any xexpression
*
* @param expr rvalue expression that will be shared
* @return xshared expression
* @sa make_xshared
*/
template <class E>
inline auto share(xexpression<E>&& expr)
{
return make_xshared(std::move(expr));
}
#undef XTENSOR_FORWARD_METHOD
}
#endif
|
/*
* Copyright (c), 2017, Adrien Devresse
*
* 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 <iostream>
#include <string>
#include <vector>
#include <h5gt/H5DataSet.hpp>
#include <h5gt/H5DataSpace.hpp>
#include <h5gt/H5File.hpp>
const std::string FILE_NAME("create_dataset_example.h5");
const std::string DATASET_NAME("dset");
// Create a dataset name "dset" of double 4x6
//
int main(void) {
using namespace h5gt;
try {
// Create a new file using the default property lists.
File file(FILE_NAME, File::ReadWrite | File::Create | File::Truncate);
// Define the size of our dataset: 2x6
std::vector<size_t> dims{2, 6};
// Create the dataset
DataSet dataset =
file.createDataSet<double>(DATASET_NAME, DataSpace(dims));
double data[2][6] = {{1.1, 2.2, 3.3, 4.4, 5.5, 6.6},
{11.11, 12.12, 13.13, 14.14, 15.15, 16.16}};
// write it
dataset.write(data);
} catch (Exception& err) {
// catch and print any HDF5 error
std::cerr << err.what() << std::endl;
}
return 0; // successfully terminated
}
|
// codeforces/558div2/A/main.cpp
// author: @___Johniel
// github: https://github.com/johniel/
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; }
template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
while (cin >> n >> m) {
if (m == 0 || m == 1) {
cout << 1 << endl;
continue;
}
if ((n - n/2) <= m) {
cout << (n / 2) - (m - (n / 2)) << endl;
} else {
cout << n/2 << endl;
}
}
return 0;
}
|
#ifndef MESHSYSTEM_HPP
#define MESHSYSTEM_HPP
#include "enginesystem.hpp"
#include "memory.hpp"
#include "mesh.hpp"
#include "vulkansystem.hpp"
#include <set>
#include <vector>
#include <limits>
#include <mutex>
class MeshSystem : public EngineSystem
{
public:
void configure( Engine *engine ) override;
void unconfigure( Engine *engine ) override;
Mesh *CreateMesh();
// Adds mesh to destroy list
void DestroyMesh( Mesh *mesh );
// Destroys meshes in destroy list and re-sets mesh indices
void DestroyDeadMeshes();
private:
std::vector< unique_ptr< Mesh > > meshes;
std::set< size_t > destroyList;
std::mutex meshMutex;
VulkanSystem *vulkanSystem = nullptr;
};
#endif // MESHSYSTEM_HPP
|
/** @file
*****************************************************************************
Declaration of interfaces for initializing MNT6.
*****************************************************************************
* @author This file is part of libff, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef MNT6753_INIT_HPP_
#define MNT6753_INIT_HPP_
#include <libff/algebra/curves/mnt753/mnt46753_common.hpp>
#include <libff/algebra/curves/public_params.hpp>
#include <libff/algebra/fields/fp.hpp>
#include <libff/algebra/fields/fp3.hpp>
#include <libff/algebra/fields/fp6_2over3.hpp>
namespace libff {
#define mnt6753_modulus_r mnt46753_modulus_B
#define mnt6753_modulus_q mnt46753_modulus_A
const mp_size_t mnt6753_r_bitcount = mnt46753_B_bitcount;
const mp_size_t mnt6753_q_bitcount = mnt46753_A_bitcount;
const mp_size_t mnt6753_r_limbs = mnt46753_B_limbs;
const mp_size_t mnt6753_q_limbs = mnt46753_A_limbs;
extern bigint<mnt6753_r_limbs> mnt6753_modulus_r;
extern bigint<mnt6753_q_limbs> mnt6753_modulus_q;
typedef Fp_model<mnt6753_r_limbs, mnt6753_modulus_r> mnt6753_Fr;
typedef Fp_model<mnt6753_q_limbs, mnt6753_modulus_q> mnt6753_Fq;
typedef Fp3_model<mnt6753_q_limbs, mnt6753_modulus_q> mnt6753_Fq3;
typedef Fp6_2over3_model<mnt6753_q_limbs, mnt6753_modulus_q> mnt6753_Fq6;
typedef mnt6753_Fq6 mnt6753_GT;
// parameters for twisted short Weierstrass curve E'/Fq3 : y^2 = x^3 + (a * twist^2) * x + (b * twist^3)
extern mnt6753_Fq3 mnt6753_twist;
extern mnt6753_Fq3 mnt6753_twist_coeff_a;
extern mnt6753_Fq3 mnt6753_twist_coeff_b;
extern mnt6753_Fq mnt6753_twist_mul_by_a_c0;
extern mnt6753_Fq mnt6753_twist_mul_by_a_c1;
extern mnt6753_Fq mnt6753_twist_mul_by_a_c2;
extern mnt6753_Fq mnt6753_twist_mul_by_b_c0;
extern mnt6753_Fq mnt6753_twist_mul_by_b_c1;
extern mnt6753_Fq mnt6753_twist_mul_by_b_c2;
extern mnt6753_Fq mnt6753_twist_mul_by_q_X;
extern mnt6753_Fq mnt6753_twist_mul_by_q_Y;
// parameters for pairing
extern bigint<mnt6753_q_limbs> mnt6753_ate_loop_count;
extern bool mnt6753_ate_is_loop_count_neg;
extern bigint<6*mnt6753_q_limbs> mnt6753_final_exponent;
extern bigint<mnt6753_q_limbs> mnt6753_final_exponent_last_chunk_abs_of_w0;
extern bool mnt6753_final_exponent_last_chunk_is_w0_neg;
extern bigint<mnt6753_q_limbs> mnt6753_final_exponent_last_chunk_w1;
void init_mnt6753_params();
class mnt6753_G1;
class mnt6753_G2;
} // libff
#endif // MNT6753_INIT_HPP_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.