text
string
size
int64
token_count
int64
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::tuple; using std::tr1::make_tuple; using std::tr1::get; #define TYPICAL_MAT_SIZES_SORT TYPICAL_MAT_SIZES #define TYPICAL_MAT_TYPES_SORT CV_8UC1, CV_16UC1, CV_32FC1 #define SORT_TYPES SORT_EVERY_ROW | SORT_ASCENDING, SORT_EVERY_ROW | SORT_DESCENDING #define TYPICAL_MATS_SORT testing::Combine( testing::Values(TYPICAL_MAT_SIZES_SORT), testing::Values(TYPICAL_MAT_TYPES_SORT), testing::Values(SORT_TYPES) ) typedef tuple<Size, MatType, int> sortParams; typedef TestBaseWithParam<sortParams> sortFixture; PERF_TEST_P(sortFixture, sort, TYPICAL_MATS_SORT) { const sortParams params = GetParam(); const Size sz = get<0>(params); const int type = get<1>(params), flags = get<2>(params); cv::Mat a(sz, type), b(sz, type); declare.in(a, WARMUP_RNG).out(b); TEST_CYCLE() cv::sort(a, b, flags); SANITY_CHECK(b); } typedef sortFixture sortIdxFixture; #undef SORT_TYPES #define SORT_TYPES SORT_EVERY_COLUMN | SORT_ASCENDING, SORT_EVERY_COLUMN | SORT_DESCENDING PERF_TEST_P(sortIdxFixture, sorIdx, TYPICAL_MATS_SORT) { const sortParams params = GetParam(); const Size sz = get<0>(params); const int type = get<1>(params), flags = get<2>(params); cv::Mat a(sz, type), b(sz, type); declare.in(a, WARMUP_RNG).out(b); TEST_CYCLE() cv::sortIdx(a, b, flags); SANITY_CHECK_NOTHING(); }
1,518
665
#include "LocalHookBase.h" namespace blackbone { std::unordered_map<void*, DetourBase*> DetourBase::_breakpoints; void* DetourBase::_vecHandler = nullptr; DetourBase::DetourBase() { } DetourBase::~DetourBase() { VirtualFree( _buf, 0, MEM_RELEASE ); } /// <summary> /// Allocate detour buffer as close to target as possible /// </summary> /// <param name="nearest">Target address</param> /// <returns>true on success</returns> bool DetourBase::AllocateBuffer( uint8_t* nearest ) { if (_buf != nullptr) return true; MEMORY_BASIC_INFORMATION mbi = { 0 }; for (SIZE_T addr = (SIZE_T)nearest; addr > (SIZE_T)nearest - 0x80000000; addr = (SIZE_T)mbi.BaseAddress - 1) { if (!VirtualQuery( (LPCVOID)addr, &mbi, sizeof( mbi ) )) break; if (mbi.State == MEM_FREE) { _buf = (uint8_t*)VirtualAlloc( (uint8_t*)mbi.BaseAddress + mbi.RegionSize - 0x1000, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE ); if (_buf) break; } } // If allocating a memory page failed, allocate first suitable if (_buf == nullptr) _buf = (uint8_t*)VirtualAlloc( nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE ); _origCode = _buf + 0x100; _newCode = _buf + 0x200; return _buf != nullptr; } /// <summary> /// Temporarily disable hook /// </summary> /// <returns>true on success</returns> bool DetourBase::DisableHook() { if (_type == HookType::InternalInline || _type == HookType::Int3) WriteProcessMemory( GetCurrentProcess(), _original, _origCode, _origSize, NULL ); else if (_type == HookType::HWBP) ToggleHBP( _hwbpIdx[GetCurrentThreadId()], false ); return true; } /// <summary> /// Enable disabled hook /// </summary> /// <returns>true on success</returns> bool DetourBase::EnableHook() { if (_type == HookType::InternalInline || _type == HookType::Int3) WriteProcessMemory( GetCurrentProcess(), _original, _newCode, _origSize, NULL ); else if (_type == HookType::HWBP) ToggleHBP( _hwbpIdx[GetCurrentThreadId()], true ); return true; } /// <summary> /// Toggle hardware breakpoint for current thread /// </summary> /// <param name="index">Breakpoint index ( 0-4 )</param> /// <param name="enable">true to enable, false to disable</param> /// <returns>true on success</returns> bool DetourBase::ToggleHBP( int index, bool enable ) { CONTEXT context = { 0 }; context.ContextFlags = CONTEXT_DEBUG_REGISTERS; if (GetThreadContext( GetCurrentThread(), &context ) != TRUE) return FALSE; if (enable) BitTestAndSetT( (LONG_PTR*)&context.Dr7, 2 * index ); else BitTestAndResetT( (LONG_PTR*)&context.Dr7, 2 * index ); return (SetThreadContext( GetCurrentThread(), &context ) != FALSE); } /// <summary> /// Copy original function bytes /// </summary> /// <param name="Ptr">Origianl function address</param> void DetourBase::CopyOldCode( uint8_t* ptr ) { // Store original bytes uint8_t* src = ptr; uint8_t* old = (uint8_t*)_origCode; uint32_t all_len = 0; ldasm_data ld = { 0 }; do { uint32_t len = ldasm( src, &ld, is_x64 ); // Determine code end if (ld.flags & F_INVALID || (len == 1 && (src[ld.opcd_offset] == 0xCC || src[ld.opcd_offset] == 0xC3)) || (len == 3 && src[ld.opcd_offset] == 0xC2) || len + all_len > 128) { break; } // move instruction memcpy( old, src, len ); // if instruction has relative offset, calculate new offset if (ld.flags & F_RELATIVE) { int32_t diff = 0; const uintptr_t ofst = (ld.disp_offset != 0 ? ld.disp_offset : ld.imm_offset); const uintptr_t sz = ld.disp_size != 0 ? ld.disp_size : ld.imm_size; memcpy( &diff, src + ofst, sz ); #ifdef USE64 // exit if jump is greater then 2GB if (_abs64( src + len + diff - old ) > INT_MAX) { break; } else { diff += static_cast<int32_t>(src - old); memcpy( old + ofst, &diff, sz ); } #else diff += src - old; memcpy( old + ofst, &diff, sz ); #endif } src += len; old += len; all_len += len; } while (all_len < _origSize); // Failed to copy old code, use backup plan if (all_len < _origSize) { _type = HookType::InternalInline; memcpy( _origCode, ptr, _origSize ); } else { SET_JUMP( old, src ); _callOriginal = _origCode; } } /// <summary> /// Exception handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::VectoredHandler( PEXCEPTION_POINTERS excpt ) { switch (excpt->ExceptionRecord->ExceptionCode) { case static_cast<DWORD>(EXCEPTION_BREAKPOINT): return Int3Handler( excpt ); case static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION): return AVHandler( excpt ); case static_cast<DWORD>(EXCEPTION_SINGLE_STEP): return StepHandler( excpt ); default: return EXCEPTION_CONTINUE_SEARCH; } } /// <summary> /// Int3 exception handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::Int3Handler( PEXCEPTION_POINTERS excpt ) { if (_breakpoints.count( excpt->ExceptionRecord->ExceptionAddress )) { DetourBase* pInst = _breakpoints[excpt->ExceptionRecord->ExceptionAddress]; ((_NT_TIB*)NtCurrentTeb())->ArbitraryUserPointer = (void*)pInst; excpt->ContextRecord->NIP = (uintptr_t)pInst->_internalHandler; return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } /// <summary> /// Access violation handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::AVHandler( PEXCEPTION_POINTERS /*excpt*/ ) { return EXCEPTION_CONTINUE_SEARCH; } /// <summary> /// Single step exception handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::StepHandler( PEXCEPTION_POINTERS excpt ) { DWORD index = 0; int found = _BitScanForward( &index, static_cast<DWORD>(excpt->ContextRecord->Dr6) ); if (found != 0 && index < 4 && _breakpoints.count( excpt->ExceptionRecord->ExceptionAddress )) { DetourBase* pInst = _breakpoints[excpt->ExceptionRecord->ExceptionAddress]; // Disable breakpoint at current index BitTestAndResetT( (LONG_PTR*)&excpt->ContextRecord->Dr7, 2 * index ); ((_NT_TIB*)NtCurrentTeb())->ArbitraryUserPointer = (void*)pInst; excpt->ContextRecord->NIP = (uintptr_t)pInst->_internalHandler; return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } }
7,246
2,493
#include<iostream> #include<fstream> #include<map> #include<vector> #include<cstdlib> #include<algorithm> #include<set> #define CH printf("check!!\n"); using namespace std; int main(int argc,char *argv[]) { ifstream infile1(argv[1]); ofstream outfile(argv[2],ios_base::out | ios_base::binary); string str1,str2; unsigned int node1,node2; map<unsigned int , unsigned int> mp2; unsigned int node_count; node_count = 0; unsigned int index_size = 0; cout << "create_node_number_map" << endl; while(getline(infile1,str1,'\t')){ getline(infile1,str2); node1 = atoi(str1.c_str()); node2 = atoi(str2.c_str()); if(node1 != node2){ if(mp2.find(node1) == mp2.end()){ mp2[node1] = node_count; node_count++; } index_size++; if(mp2.find(node2) == mp2.end()){ mp2[node2] = node_count; node_count++; } } } ifstream infile2(argv[1]); unsigned int *edge_list = new unsigned int[index_size*2]; unsigned int edge_count = 0; cout << "create_edge_list" << endl; while(getline(infile2,str1,'\t')){ getline(infile2,str2); node1 = atoi(str1.c_str()); node2 = atoi(str2.c_str()); if(node1 != node2){ edge_list[edge_count] = mp2[node1]; edge_count++; edge_list[edge_count] = mp2[node2]; edge_count++; } } mp2.clear(); unsigned int c = 0; unsigned int *node = new unsigned int[node_count + 1]; node[0] = 0; ofstream log("logfile.txt",ios_base::out | ios_base::binary); cout << "create_node_array" << endl; while(c < node_count){ map<unsigned int,set<unsigned int>> mp; unsigned int c0 = c; unsigned int c2 = c+100000; if(c2 >= node_count){ c2 = node_count; } for(unsigned int i = 0;i < index_size*2;i+=2){ if(c <= edge_list[i] && edge_list[i] < c2){ mp[edge_list[i]].insert(edge_list[i+1]); } if(c <= edge_list[i+1] && edge_list[i+1] < c2){ mp[edge_list[i+1]].insert(edge_list[i]); } } while(c<c2){ unsigned int index = mp[c].size(); node[c+1] = node[c] + index; c++; } unsigned int edgesize = node[c] - node[c0]; cout << edgesize << endl; unsigned int *edge_log = new unsigned int[edgesize]; unsigned int n = 0; // cout << "aaa" << endl; while(c0 < c2){ for(auto itr = mp[c0].begin();itr != mp[c0].end();++itr){ edge_log[n] = *itr; n++; } c0++; } log.write((const char*)&edge_log[0],sizeof(unsigned int)*edgesize); delete[] edge_log; mp.clear(); } cout << "write_file" << endl; unsigned int node_total = node_count + 1; unsigned int edge_total = node[node_count]; outfile.write((const char*)&node_count,sizeof(int)); outfile.write((const char*)&edge_total,sizeof(int)); outfile.write((const char*)&node[0],sizeof(int)*(node_total)); delete[] node; ifstream infile3("logfile.txt",ios_base::in | ios_base::binary); unsigned int *edge = new unsigned int[edge_total]; infile3.read((char*)&edge[0],sizeof(int)*(edge_total)); outfile.write((const char*)(edge),sizeof(int)*(edge_total)); log.close(); remove("logfile.txt"); }
3,195
1,280
#include <test/unit/math/test_ad.hpp> TEST(mathMixMatFun, log1m) { auto f = [](const auto& x1) { return stan::math::log1m(x1); }; stan::test::expect_common_unary_vectorized(f); stan::test::expect_unary_vectorized(f, -21.5, -21, -1, 0.9, 3); }
250
116
#include "LumenPCH.h" #include <regex> #include <stb_image.h> #define TINYEXR_IMPLEMENTATION #include <zlib.h> #include <tinyexr.h> #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define TINYOBJLOADER_IMPLEMENTATION #include "RayTracer.h" RayTracer* RayTracer::instance = nullptr; static void fb_resize_callback(GLFWwindow* window, int width, int height) { auto app = reinterpret_cast<RayTracer*>(glfwGetWindowUserPointer(window)); app->resized = true; } RayTracer::RayTracer(int width, int height, bool debug, int argc, char* argv[]) : LumenInstance(width, height, debug) { this->instance = this; parse_args(argc, argv); } void RayTracer::init(Window* window) { srand((uint32_t)time(NULL)); this->window = window; vkb.ctx.window_ptr = window->get_window_ptr(); glfwSetFramebufferSizeCallback(vkb.ctx.window_ptr, fb_resize_callback); // Init with ray tracing extensions vkb.add_device_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); vkb.add_device_extension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME); vkb.add_device_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); vkb.add_device_extension(VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME); vkb.add_device_extension(VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME); vkb.add_device_extension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); vkb.create_instance(); if (vkb.enable_validation_layers) { vkb.setup_debug_messenger(); } vkb.create_surface(); vkb.pick_physical_device(); vkb.create_logical_device(); vkb.create_swapchain(); create_default_render_pass(vkb.ctx); vkb.create_framebuffers(vkb.ctx.default_render_pass); vkb.create_command_pool(); vkb.create_command_buffers(); vkb.create_sync_primitives(); initialized = true; scene.load_scene(scene_name); switch (scene.config.integrator_type) { case IntegratorType::Path : integrator = std::make_unique<Path>(this, &scene); break; case IntegratorType::BDPT: integrator = std::make_unique<BDPT>(this, &scene); break; case IntegratorType::SPPM: integrator = std::make_unique<SPPM>(this, &scene); break; case IntegratorType::VCM: integrator = std::make_unique<VCM>(this, &scene); break; case IntegratorType::PSSMLT: integrator = std::make_unique<PSSMLT>(this, &scene); break; case IntegratorType::SMLT: integrator = std::make_unique<SMLT>(this, &scene); break; case IntegratorType::VCMMLT: integrator = std::make_unique<VCMMLT>(this, &scene); break; case IntegratorType::ReSTIR: integrator = std::make_unique<ReSTIR>(this, &scene); break; case IntegratorType::ReSTIRGI: integrator = std::make_unique<ReSTIRGI>(this, &scene); break; case IntegratorType::DDGI: integrator = std::make_unique<DDGI>(this, &scene); break; default: break; } integrator->init(); init_resources(); create_post_descriptor(); update_post_desc_set(); create_post_pipeline(); create_compute_pipelines(); init_imgui(); VkPhysicalDeviceMemoryProperties2 props = {}; props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2; VkPhysicalDeviceMemoryBudgetPropertiesEXT budget_props = {}; budget_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT; props.pNext = &budget_props; vkGetPhysicalDeviceMemoryProperties2(vk_ctx.physical_device, &props); printf("Memory usage %f MB\n", budget_props.heapUsage[0] * 1e-6); } void RayTracer::update() { if (instance->window->is_key_down(KeyInput::KEY_F10)) { write_exr = true; } float frame_time = draw_frame(); cpu_avg_time = (1. - 1./ (cnt)) * cpu_avg_time + frame_time / (float)cnt; cpu_avg_time = 0.95 * cpu_avg_time + 0.05 * frame_time; integrator->update(); } void RayTracer::render(uint32_t i) { // Render image integrator->render(); auto cmdbuf = vkb.ctx.command_buffers[i]; VkCommandBufferBeginInfo begin_info = vk::command_buffer_begin_info( VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); vk::check(vkBeginCommandBuffer(cmdbuf, &begin_info)); if (write_exr) { // Copy to host visible storage buffer { VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageExtent.width = instance->width; region.imageExtent.height = instance->height; region.imageExtent.depth = 1; transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); vkCmdCopyImageToBuffer(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, output_img_buffer_cpu.handle, 1, &region); transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL); } } if (calc_rmse && has_gt) { // Calculate RMSE { VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageExtent.width = instance->width; region.imageExtent.height = instance->height; region.imageExtent.depth = 1; transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); vkCmdCopyImageToBuffer(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, output_img_buffer.handle, 1, &region); auto barrier = buffer_barrier(output_img_buffer.handle, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); vkCmdPipelineBarrier(cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, 0, 1, &barrier, 0, 0); // Calculate and reduce { vkCmdBindDescriptorSets( cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, calc_rmse_pipeline->pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdBindDescriptorSets( cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, reduce_rmse_pipeline->pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdBindDescriptorSets( cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, output_rmse_pipeline->pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdPushConstants(cmdbuf, calc_rmse_pipeline->pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PostPC), &post_pc); vkCmdPushConstants(cmdbuf, reduce_rmse_pipeline->pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PostPC), &post_pc); vkCmdPushConstants(cmdbuf, output_rmse_pipeline->pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PostPC), &post_pc); reduce(cmdbuf, residual_buffer, counter_buffer, *calc_rmse_pipeline, *reduce_rmse_pipeline, instance->width * instance->height); vkCmdBindPipeline(cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, output_rmse_pipeline->handle); auto num_wgs = 1; vkCmdDispatch(cmdbuf, num_wgs, 1, 1); transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL); } } } // Apply Post FX and present VkClearValue clear_color = { 0.25f, 0.25f, 0.25f, 1.0f }; VkClearValue clear_depth = { 1.0f, 0 }; VkViewport viewport = vk::viewport((float)width, (float)height, 0.0f, 1.0f); VkClearValue clear_values[] = { clear_color, clear_depth }; VkRenderPassBeginInfo post_rpi{ VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; post_rpi.clearValueCount = 2; post_rpi.pClearValues = clear_values; post_rpi.renderPass = vkb.ctx.default_render_pass; post_rpi.framebuffer = vkb.ctx.swapchain_framebuffers[i]; post_rpi.renderArea = { {0, 0}, vkb.ctx.swapchain_extent }; pc_post_settings.enable_tonemapping = settings.enable_tonemapping; vkCmdBeginRenderPass(cmdbuf, &post_rpi, VK_SUBPASS_CONTENTS_INLINE); vkCmdSetViewport(cmdbuf, 0, 1, &viewport); VkRect2D scissor = vk::rect2D(width, height, 0, 0); vkCmdSetScissor(cmdbuf, 0, 1, &scissor); vkCmdBindPipeline(cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, post_pipeline->handle); vkCmdBindDescriptorSets(cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, post_pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdPushConstants(cmdbuf, post_pipeline_layout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushConstantPost), &pc_post_settings); vkCmdDraw(cmdbuf, 3, 1, 0, 0); ImGui::Render(); ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cmdbuf); vkCmdEndRenderPass(cmdbuf); VkClearColorValue val = { 0,0,0,1 }; VkImageSubresourceRange range; range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; range.baseMipLevel = 0; range.levelCount = 1; range.baseArrayLayer = 0; range.layerCount = 1; vk::check(vkEndCommandBuffer(cmdbuf), "Failed to record command buffer"); } float RayTracer::draw_frame() { if (cnt == 0) { start = clock(); } auto t_begin = glfwGetTime() * 1000; bool updated = false; ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGui::Text("Frame time %f ms ( %f FPS )", cpu_avg_time, 1000 / cpu_avg_time); if (ImGui::Button("Reload shaders")) { integrator->reload(); updated |= true; } bool gui_updated = integrator->gui(); updated |= ImGui::Checkbox("Enable ACES tonemapping", &settings.enable_tonemapping); if (updated || gui_updated) { ImGui::Render(); auto t_end = glfwGetTime() * 1000; auto t_diff = t_end - t_begin; integrator->updated = true; return (float)t_diff; } ImGui::Checkbox("Show camera statistics", &show_cam_stats); if (show_cam_stats) { ImGui::PushItemWidth(170); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[0]), 0.05f); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[1]), 0.05f); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[2]), 0.05f); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[3]), 0.05f); } uint32_t image_idx = vkb.prepare_frame(); if (image_idx == UINT32_MAX) { auto t_end = glfwGetTime() * 1000; auto t_diff = t_end - t_begin; return (float)t_diff; } render(image_idx); vkb.submit_frame(image_idx, resized); auto now = clock(); auto diff = ((float)now - start); if (write_exr) { write_exr = false; save_exr((float*)output_img_buffer_cpu.data, instance->width, instance->height, "out.exr"); } bool time_limit = (abs(diff / CLOCKS_PER_SEC - 5)) < 0.1; //calc_rmse = cnt % 30 == 0 || time_limit; //calc_rmse = time_limit; //bool t2 = (abs(diff / CLOCKS_PER_SEC - 10.0)) < 0.1; //if (t2) { // printf("Go!\n"); // t2 = false; //} //printf("Time %f\n", diff / CLOCKS_PER_SEC); //calc_rmse = true; //write_exr = time_limit; if (calc_rmse && has_gt) { float rmse = *(float*)rmse_val_buffer.data; printf("%RMSE: %f - %f\n", rmse * 1e6, diff); } auto t_end = glfwGetTime() * 1000; auto t_diff = t_end - t_begin; cnt++; return (float)t_diff; } void RayTracer::create_post_descriptor() { constexpr int OUTPUT_COLOR_BINDING = 0; constexpr int POST_DESC_BINDING = 1; std::vector<VkDescriptorPoolSize> pool_sizes = { vk::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1), vk::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1), }; auto descriptor_pool_ci = vk::descriptor_pool_CI(pool_sizes.size(), pool_sizes.data(), 1); vk::check(vkCreateDescriptorPool(vkb.ctx.device, &descriptor_pool_ci, nullptr, &post_desc_pool), "Failed to create descriptor pool"); std::vector<VkDescriptorSetLayoutBinding> set_layout_bindings = { vk::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, OUTPUT_COLOR_BINDING), vk::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT, POST_DESC_BINDING), }; auto set_layout_ci = vk::descriptor_set_layout_CI( set_layout_bindings.data(), set_layout_bindings.size()); vk::check(vkCreateDescriptorSetLayout(vkb.ctx.device, &set_layout_ci, nullptr, &post_desc_layout), "Failed to create descriptor set layout"); auto set_allocate_info = vk::descriptor_set_allocate_info(post_desc_pool, &post_desc_layout, 1); vk::check(vkAllocateDescriptorSets(vkb.ctx.device, &set_allocate_info, &post_desc_set), "Failed to allocate descriptor sets"); } void RayTracer::update_post_desc_set() { std::array<VkWriteDescriptorSet, 2> sets = { vk::write_descriptor_set( post_desc_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &integrator->output_tex.descriptor_image_info), vk::write_descriptor_set( post_desc_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, &post_desc_buffer.descriptor) }; vkUpdateDescriptorSets(vkb.ctx.device, sets.size(), sets.data(), 0, nullptr); } void RayTracer::create_post_pipeline() { GraphicsPipelineSettings post_settings; VkPipelineLayoutCreateInfo create_info{ VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO }; create_info.setLayoutCount = 1; create_info.pSetLayouts = &post_desc_layout; create_info.pushConstantRangeCount = 1; VkPushConstantRange pc_range = { VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushConstantPost) }; create_info.pPushConstantRanges = &pc_range; vkCreatePipelineLayout(vkb.ctx.device, &create_info, nullptr, &post_pipeline_layout); post_settings.pipeline_layout = post_pipeline_layout; post_settings.render_pass = vkb.ctx.default_render_pass; post_settings.shaders = { {"src/shaders/post.vert"}, {"src/shaders/post.frag"} }; for (auto& shader : post_settings.shaders) { if (shader.compile()) { LUMEN_ERROR("Shader compilation failed"); } } post_settings.cull_mode = VK_CULL_MODE_NONE; post_settings.enable_tracking = false; post_settings.dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; post_pipeline = std::make_unique<Pipeline>(vkb.ctx.device); post_pipeline->create_gfx_pipeline(post_settings); } void RayTracer::create_compute_pipelines() { calc_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device); reduce_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device); output_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device); std::vector<Shader> shaders = { {"src/shaders/rmse/calc_rmse.comp"}, {"src/shaders/rmse/reduce_rmse.comp"}, {"src/shaders/rmse/output_rmse.comp"} }; for (auto& shader : shaders) { shader.compile(); } ComputePipelineSettings settings; settings.desc_set_layouts = &post_desc_layout; settings.desc_set_layout_cnt = 1; settings.push_const_size = sizeof(PostPC); settings.shader = shaders[0]; calc_rmse_pipeline->create_compute_pipeline(settings); settings.shader = shaders[1]; reduce_rmse_pipeline->create_compute_pipeline(settings); settings.shader = shaders[2]; output_rmse_pipeline->create_compute_pipeline(settings); } void RayTracer::init_imgui() { VkDescriptorPoolSize pool_sizes[] = { {VK_DESCRIPTOR_TYPE_SAMPLER, 1000}, {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000}, {VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000} }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; pool_info.maxSets = 1000; pool_info.poolSizeCount = (uint32_t)std::size(pool_sizes); pool_info.pPoolSizes = pool_sizes; vk::check(vkCreateDescriptorPool(vkb.ctx.device, &pool_info, nullptr, &imgui_pool)); IMGUI_CHECKVERSION(); ImGui::CreateContext(); // Setup Platform/Renderer backends ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForVulkan(window->get_window_ptr(), true); ImGui_ImplVulkan_InitInfo init_info = {}; init_info.Instance = vkb.ctx.instance; init_info.PhysicalDevice = vkb.ctx.physical_device; init_info.Device = vkb.ctx.device; init_info.Queue = vkb.ctx.queues[(int)QueueType::GFX]; init_info.DescriptorPool = imgui_pool; init_info.MinImageCount = 2; init_info.ImageCount = 2; init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; ImGui_ImplVulkan_Init(&init_info, vkb.ctx.default_render_pass); CommandBuffer cmd(&vkb.ctx, true); ImGui_ImplVulkan_CreateFontsTexture(cmd.handle); cmd.submit(vkb.ctx.queues[(int)QueueType::GFX]); ImGui_ImplVulkan_DestroyFontUploadObjects(); } void RayTracer::init_resources() { PostDesc desc; output_img_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, instance->width * instance->height * 4 * 4 ); output_img_buffer_cpu.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_SHARING_MODE_EXCLUSIVE, instance->width * instance->height * 4 * 4 ); residual_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, instance->width * instance->height * 4 ); counter_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, sizeof(int) ); rmse_val_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_SHARING_MODE_EXCLUSIVE, sizeof(float) ); if (load_exr) { // Load the ground truth image const char* img_name = "out.exr"; float* data; int width; int height; const char* err = nullptr; int ret = LoadEXR(&data, &width, &height, img_name, &err); if (ret != TINYEXR_SUCCESS) { if (err) { fprintf(stderr, "ERR : %s\n", err); FreeEXRErrorMessage(err); // release memory of error message. } } else { std::vector<vec4> pixels; int img_res = width * height; pixels.resize(img_res); for (int i = 0; i < img_res; i++) { pixels[i].x = data[4 * i + 0]; pixels[i].y = data[4 * i + 1]; pixels[i].z = data[4 * i + 2]; pixels[i].w = 1.; } auto gt_size = pixels.size() * 4 * 4; gt_img_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, gt_size, pixels.data(), true ); desc.gt_img_addr = gt_img_buffer.get_device_address(); has_gt = true; } if (has_gt) { free(data); } } desc.out_img_addr = output_img_buffer.get_device_address(); desc.residual_addr = residual_buffer.get_device_address(); desc.counter_addr = counter_buffer.get_device_address(); desc.rmse_val_addr = rmse_val_buffer.get_device_address(); post_desc_buffer.create(&instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, sizeof(PostDesc), &desc, true); post_pc.size = instance->width * instance->height; } void RayTracer::parse_args(int argc, char* argv[]){ scene_name = "scenes/caustics.json"; std::regex fn("(.*).(.json|.xml)"); for (int i = 0; i < argc; i++) { if (std::regex_match(argv[i], fn)) { scene_name = argv[i]; } } } void RayTracer::save_exr(const float* rgb, int width, int height, const char* outfilename) { EXRHeader header; InitEXRHeader(&header); EXRImage image; InitEXRImage(&image); image.num_channels = 3; std::vector<float> images[3]; images[0].resize(width * height); images[1].resize(width * height); images[2].resize(width * height); // Split RGBRGBRGB... into R, G and B layer for (int i = 0; i < width * height; i++) { images[0][i] = rgb[4 * i + 0]; images[1][i] = rgb[4 * i + 1]; images[2][i] = rgb[4 * i + 2]; } float* image_ptr[3]; image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R image.images = (unsigned char**)image_ptr; image.width = width; image.height = height; header.num_channels = 3; header.channels = (EXRChannelInfo*)malloc(sizeof(EXRChannelInfo) * header.num_channels); // Must be (A)BGR order, since most of EXR viewers expect this channel order. strncpy_s(header.channels[0].name, "B", 255); header.channels[0].name[strlen("B")] = '\0'; strncpy_s(header.channels[1].name, "G", 255); header.channels[1].name[strlen("G")] = '\0'; strncpy_s(header.channels[2].name, "R", 255); header.channels[2].name[strlen("R")] = '\0'; header.pixel_types = (int*)malloc(sizeof(int) * header.num_channels); header.requested_pixel_types = (int*)malloc(sizeof(int) * header.num_channels); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // pixel type of output image to be stored in .EXR } const char* err = NULL; // or nullptr in C++11 or later. int ret = SaveEXRImageToFile(&image, &header, outfilename, &err); if (ret != TINYEXR_SUCCESS) { fprintf(stderr, "Save EXR err: %s\n", err); FreeEXRErrorMessage(err); // free's buffer for an error message } printf("Saved exr file. [ %s ] \n", outfilename); free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); } void RayTracer::cleanup() { const auto device = vkb.ctx.device; vkDeviceWaitIdle(device); if (initialized) { vkDestroyDescriptorSetLayout(device, post_desc_layout, nullptr); vkDestroyDescriptorPool(device, post_desc_pool, nullptr); vkDestroyDescriptorPool(device, imgui_pool, nullptr); vkDestroyPipelineLayout(device, post_pipeline_layout, nullptr); ImGui_ImplVulkan_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); gt_img_buffer.destroy(); output_img_buffer.destroy(); integrator->destroy(); post_pipeline->cleanup(); vkb.cleanup(); } }
22,717
10,115
#include "Diagnostics.H" #include "Diagnostics/ComputeDiagFunctors/ComputeDiagFunctor.H" #include "ComputeDiagFunctors/BackTransformParticleFunctor.H" #include "Diagnostics/FlushFormats/FlushFormat.H" #include "Diagnostics/ParticleDiag/ParticleDiag.H" #include "FlushFormats/FlushFormatAscent.H" #include "FlushFormats/FlushFormatCheckpoint.H" #ifdef WARPX_USE_OPENPMD # include "FlushFormats/FlushFormatOpenPMD.H" #endif #include "FlushFormats/FlushFormatPlotfile.H" #include "FlushFormats/FlushFormatSensei.H" #include "Particles/MultiParticleContainer.H" #include "Parallelization/WarpXCommUtil.H" #include "Utils/TextMsg.H" #include "Utils/WarpXAlgorithmSelection.H" #include "Utils/WarpXProfilerWrapper.H" #include "Utils/WarpXUtil.H" #include "WarpX.H" #include <AMReX.H> #include <AMReX_BLassert.H> #include <AMReX_Config.H> #include <AMReX_Geometry.H> #include <AMReX_MultiFab.H> #include <AMReX_ParallelDescriptor.H> #include <AMReX_ParmParse.H> #include <AMReX_Print.H> #include <AMReX_Vector.H> #include <algorithm> #include <string> using namespace amrex::literals; Diagnostics::Diagnostics (int i, std::string name) : m_diag_name(name), m_diag_index(i) { } Diagnostics::~Diagnostics () { } bool Diagnostics::BaseReadParameters () { auto & warpx = WarpX::GetInstance(); amrex::ParmParse pp_diag_name(m_diag_name); m_file_prefix = "diags/" + m_diag_name; pp_diag_name.query("file_prefix", m_file_prefix); queryWithParser(pp_diag_name, "file_min_digits", m_file_min_digits); pp_diag_name.query("format", m_format); pp_diag_name.query("dump_last_timestep", m_dump_last_timestep); amrex::ParmParse pp_geometry("geometry"); std::string dims; pp_geometry.get("dims", dims); // Query list of grid fields to write to output bool varnames_specified = pp_diag_name.queryarr("fields_to_plot", m_varnames_fields); if (!varnames_specified){ if( dims == "RZ" and m_format == "openpmd" ) { m_varnames_fields = {"Er", "Et", "Ez", "Br", "Bt", "Bz", "jr", "jt", "jz"}; } else { m_varnames_fields = {"Ex", "Ey", "Ez", "Bx", "By", "Bz", "jx", "jy", "jz"}; } } // Sanity check if user requests to plot phi if (WarpXUtilStr::is_in(m_varnames_fields, "phi")){ WARPX_ALWAYS_ASSERT_WITH_MESSAGE( warpx.do_electrostatic==ElectrostaticSolverAlgo::LabFrame, "plot phi only works if do_electrostatic = labframe"); } // Sanity check if user requests to plot F if (WarpXUtilStr::is_in(m_varnames_fields, "F")){ WARPX_ALWAYS_ASSERT_WITH_MESSAGE( warpx.do_dive_cleaning, "plot F only works if warpx.do_dive_cleaning = 1"); } // G can be written to file only if WarpX::do_divb_cleaning = 1 if (WarpXUtilStr::is_in(m_varnames_fields, "G")) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( warpx.do_divb_cleaning, "G can be written to file only if warpx.do_divb_cleaning = 1"); } // If user requests to plot proc_number for a serial run, // delete proc_number from fields_to_plot if (amrex::ParallelDescriptor::NProcs() == 1){ m_varnames_fields.erase( std::remove(m_varnames_fields.begin(), m_varnames_fields.end(), "proc_number"), m_varnames_fields.end()); } // Get names of particle quantities to average at each grid point const bool pfield_varnames_specified = pp_diag_name.queryarr("particle_fields_to_plot", m_pfield_varnames); if (!pfield_varnames_specified){ m_pfield_varnames = {}; } #ifdef WARPX_DIM_RZ if (m_pfield_varnames.size() != 0) { amrex::Abort("Input error: cannot use particle_fields_to_plot not implemented for RZ"); } #endif // Get parser strings for particle fields and generate map of parsers std::string parser_str; std::string filter_parser_str = ""; bool do_parser_filter; amrex::ParmParse pp_diag_pfield(m_diag_name + ".particle_fields"); for (const auto& var : m_pfield_varnames) { Store_parserString(pp_diag_pfield, (var + "(x,y,z,ux,uy,uz)").c_str(), parser_str); if (parser_str != "") { m_pfield_strings.insert({var, parser_str}); } else { amrex::Abort("Input error: cannot find parser string for " + var + "." + m_diag_name + ".particle_fields." + var + " in file"); } // Look for and record filter functions. If one is not found, the empty string will be // stored as the filter string, and will be ignored. do_parser_filter = pp_diag_pfield.query((var + ".filter(x,y,z,ux,uy,uz)").c_str(), filter_parser_str); m_pfield_dofilter.insert({var, do_parser_filter}); m_pfield_filter_strings.insert({var, filter_parser_str}); } // Names of all species in the simulation m_all_species_names = warpx.GetPartContainer().GetSpeciesNames(); // Get names of species to average at each grid point const bool pfield_species_specified = pp_diag_name.queryarr("particle_fields_species", m_pfield_species); if (!pfield_species_specified){ m_pfield_species = m_all_species_names; } // Check that species names specified in m_pfield_species are valid bool p_species_name_is_wrong; // Loop over all species specified above for (const auto& species : m_pfield_species) { // Boolean used to check if species name was misspelled p_species_name_is_wrong = true; // Loop over all species for (int i = 0, n = int(m_all_species_names.size()); i < n; i++) { if (species == m_all_species_names[i]) { // Store species index: will be used in ParticleReductionFunctor to calculate // averages for this species m_pfield_species_index.push_back(i); p_species_name_is_wrong = false; } } // If species name was misspelled, abort with error message if (p_species_name_is_wrong) { amrex::Abort("Input error: string " + species + " in " + m_diag_name + ".particle_fields_species does not match any species"); } } m_varnames = m_varnames_fields; // Generate names of averaged particle fields and append to m_varnames for (int ivar=0; ivar<m_pfield_varnames.size(); ivar++) { for (int ispec=0; ispec < int(m_pfield_species.size()); ispec++) { m_varnames.push_back(m_pfield_varnames[ivar] + '_' + m_pfield_species[ispec]); } } // Read user-defined physical extents for the output and store in m_lo and m_hi. m_lo.resize(AMREX_SPACEDIM); m_hi.resize(AMREX_SPACEDIM); bool lo_specified = queryArrWithParser(pp_diag_name, "diag_lo", m_lo, 0, AMREX_SPACEDIM); if (!lo_specified) { for (int idim=0; idim < AMREX_SPACEDIM; ++idim) { m_lo[idim] = warpx.Geom(0).ProbLo(idim); } } bool hi_specified = queryArrWithParser(pp_diag_name, "diag_hi", m_hi, 0, AMREX_SPACEDIM); if (!hi_specified) { for (int idim =0; idim < AMREX_SPACEDIM; ++idim) { m_hi[idim] = warpx.Geom(0).ProbHi(idim); } } // For a moving window simulation, the user-defined m_lo and m_hi must be converted. if (warpx.do_moving_window) { #if defined(WARPX_DIM_3D) amrex::Vector<int> dim_map {0, 1, 2}; #elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) amrex::Vector<int> dim_map {0, 2}; #else amrex::Vector<int> dim_map {2}; #endif if (warpx.boost_direction[ dim_map[warpx.moving_window_dir] ] == 1) { // Convert user-defined lo and hi for diagnostics to account for boosted-frame // simulations with moving window amrex::Real convert_factor = 1._rt/(warpx.gamma_boost * (1._rt - warpx.beta_boost) ); // Assuming that the window travels with speed c m_lo[warpx.moving_window_dir] *= convert_factor; m_hi[warpx.moving_window_dir] *= convert_factor; } } // Initialize cr_ratio with default value of 1 for each dimension. amrex::Vector<int> cr_ratio(AMREX_SPACEDIM, 1); // Read user-defined coarsening ratio for the output MultiFab. bool cr_specified = queryArrWithParser(pp_diag_name, "coarsening_ratio", cr_ratio, 0, AMREX_SPACEDIM); if (cr_specified) { for (int idim =0; idim < AMREX_SPACEDIM; ++idim) { m_crse_ratio[idim] = cr_ratio[idim]; } } // Names of species to write to output bool species_specified = pp_diag_name.queryarr("species", m_output_species_names); // Auxiliary variables std::string species; bool species_name_is_wrong; // Loop over all fields stored in m_varnames for (const auto& var : m_varnames) { // Check if m_varnames contains a string of the form rho_<species_name> if (var.rfind("rho_", 0) == 0) { // Extract species name from the string rho_<species_name> species = var.substr(var.find("rho_") + 4); // Boolean used to check if species name was misspelled species_name_is_wrong = true; // Loop over all species for (int i = 0, n = int(m_all_species_names.size()); i < n; i++) { // Check if species name extracted from the string rho_<species_name> // matches any of the species in the simulation if (species == m_all_species_names[i]) { // Store species index: will be used in RhoFunctor to dump // rho for this species m_rho_per_species_index.push_back(i); species_name_is_wrong = false; } } // If species name was misspelled, abort with error message if (species_name_is_wrong) { amrex::Abort("Input error: string " + var + " in " + m_diag_name + ".fields_to_plot does not match any species"); } } } bool checkpoint_compatibility = false; if (m_format == "checkpoint"){ if ( varnames_specified == false && pfield_varnames_specified == false && pfield_species_specified == false && lo_specified == false && hi_specified == false && cr_specified == false && species_specified == false ) checkpoint_compatibility = true; } return checkpoint_compatibility; } void Diagnostics::InitData () { // initialize member variables and arrays in base class::Diagnostics InitBaseData(); // initialize member variables and arrays specific to each derived class // (FullDiagnostics, BTDiagnostics, etc.) DerivedInitData(); amrex::ParmParse pp_geometry("geometry"); std::string dims; pp_geometry.get("dims", dims); for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) { // loop over all levels // This includes full diagnostics and BTD as well as cell-center functors for BTD. // Note that the cell-centered data for BTD is computed for all levels and hence // the corresponding functor is also initialized for all the levels for (int lev = 0; lev < nmax_lev; ++lev) { // allocate and initialize m_all_field_functors depending on diag type if (dims == "RZ" and m_format == "openpmd") { InitializeFieldFunctorsRZopenPMD(lev); } else { InitializeFieldFunctors(lev); } } // loop over the levels selected for output // This includes all the levels for full diagnostics // and only the coarse level (mother grid) for BTD for (int lev = 0; lev < nlev_output; ++lev) { // Initialize buffer data required for particle and/or fields InitializeBufferData(i_buffer, lev); } } amrex::ParmParse pp_diag_name(m_diag_name); // default for writing species output is 1 int write_species = 1; pp_diag_name.query("write_species", write_species); if (write_species == 1) { // When particle buffers, m_particle_boundary_buffer are included, // they will be initialized here InitializeParticleBuffer(); InitializeParticleFunctors(); } if (write_species == 0) { if (m_format == "checkpoint"){ amrex::Abort("For checkpoint format, write_species flag must be 1."); } // if user-defined value for write_species == 0, then clear species vector for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer ) { m_output_species.at(i_buffer).clear(); } m_output_species_names.clear(); } else { amrex::Vector <amrex::Real> dummy_val(AMREX_SPACEDIM); if ( queryArrWithParser(pp_diag_name, "diag_lo", dummy_val, 0, AMREX_SPACEDIM) || queryArrWithParser(pp_diag_name, "diag_hi", dummy_val, 0, AMREX_SPACEDIM) ) { // set geometry filter for particle-diags to true when the diagnostic domain-extent // is specified by the user. // Note that the filter is set for every ith snapshot, and the number of snapshots // for full diagnostics is 1, while for BTD it is user-defined. for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer ) { for (auto& v : m_output_species.at(i_buffer)) { v.m_do_geom_filter = true; } // Disabling particle-io for reduced domain diagnostics by reducing // the particle-diag vector to zero. // This is a temporary fix until particle_buffer is supported in diagnostics. m_output_species.at(i_buffer).clear(); } std::string warnMsg = "For full diagnostics on a reduced domain, particle I/O is not "; warnMsg += "supported, yet! Therefore, particle I/O is disabled for this diagnostics: "; warnMsg += m_diag_name; WarpX::GetInstance().RecordWarning("Diagnostics", warnMsg); } } } void Diagnostics::InitBaseData () { auto & warpx = WarpX::GetInstance(); // Number of levels in the simulation at the current timestep nlev = warpx.finestLevel() + 1; // default number of levels to be output = nlev nlev_output = nlev; // Maximum number of levels that will be allocated in the simulation nmax_lev = warpx.maxLevel() + 1; m_all_field_functors.resize( nmax_lev ); // For restart, move the m_lo and m_hi of the diag consistent with the // current moving_window location if (warpx.do_moving_window) { int moving_dir = warpx.moving_window_dir; int shift_num_base = static_cast<int>((warpx.getmoving_window_x() - m_lo[moving_dir]) / warpx.Geom(0).CellSize(moving_dir) ); m_lo[moving_dir] += shift_num_base * warpx.Geom(0).CellSize(moving_dir); m_hi[moving_dir] += shift_num_base * warpx.Geom(0).CellSize(moving_dir); } // Construct Flush class. if (m_format == "plotfile"){ m_flush_format = std::make_unique<FlushFormatPlotfile>() ; } else if (m_format == "checkpoint"){ // creating checkpoint format m_flush_format = std::make_unique<FlushFormatCheckpoint>() ; } else if (m_format == "ascent"){ m_flush_format = std::make_unique<FlushFormatAscent>(); } else if (m_format == "sensei"){ #ifdef AMREX_USE_SENSEI_INSITU m_flush_format = std::make_unique<FlushFormatSensei>( dynamic_cast<amrex::AmrMesh*>(const_cast<WarpX*>(&warpx)), m_diag_name); #else amrex::Abort("To use SENSEI in situ, compile with USE_SENSEI=TRUE"); #endif } else if (m_format == "openpmd"){ #ifdef WARPX_USE_OPENPMD m_flush_format = std::make_unique<FlushFormatOpenPMD>(m_diag_name); #else amrex::Abort("To use openpmd output format, need to compile with USE_OPENPMD=TRUE"); #endif } else { amrex::Abort("unknown output format"); } // allocate vector of buffers then allocate vector of levels for each buffer m_mf_output.resize( m_num_buffers ); for (int i = 0; i < m_num_buffers; ++i) { m_mf_output[i].resize( nmax_lev ); } // allocate vector of geometry objects corresponding to each output multifab. m_geom_output.resize( m_num_buffers ); for (int i = 0; i < m_num_buffers; ++i) { m_geom_output[i].resize( nmax_lev ); } // allocate vector of particle buffers m_output_species.resize(m_num_buffers); } void Diagnostics::ComputeAndPack () { PrepareBufferData(); // prepare the field-data necessary to compute output data PrepareFieldDataForOutput(); // Prepare the particle data necessary to compute output data // Field-data is called first for BTD, since the z-slice location is used to prepare particle data // to determine if the transform is to be done this step. PrepareParticleDataForOutput(); auto & warpx = WarpX::GetInstance(); // compute the necessary fields and store result in m_mf_output. for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) { for(int lev=0; lev<nlev_output; lev++){ int icomp_dst = 0; const auto n = static_cast<int>(m_all_field_functors[lev].size()); for (int icomp=0; icomp<n; icomp++){ // Call all functors in m_all_field_functors[lev]. Each of them computes // a diagnostics and writes in one or more components of the output // multifab m_mf_output[lev]. m_all_field_functors[lev][icomp]->operator()(m_mf_output[i_buffer][lev], icomp_dst, i_buffer); // update the index of the next component to fill icomp_dst += m_all_field_functors[lev][icomp]->nComp(); } // Check that the proper number of components of mf_avg were updated. AMREX_ALWAYS_ASSERT( icomp_dst == m_varnames.size() ); // needed for contour plots of rho, i.e. ascent/sensei if (m_format == "sensei" || m_format == "ascent") { WarpXCommUtil::FillBoundary(m_mf_output[i_buffer][lev], warpx.Geom(lev).periodicity()); } } // Call Particle functor for (int isp = 0; isp < m_all_particle_functors.size(); ++isp) { m_all_particle_functors[isp]->operator()(*m_particles_buffer[i_buffer][isp], m_totalParticles_in_buffer[i_buffer][isp], i_buffer); } } UpdateBufferData(); } void Diagnostics::FilterComputePackFlush (int step, bool force_flush) { WARPX_PROFILE("Diagnostics::FilterComputePackFlush()"); MovingWindowAndGalileanDomainShift (step); if ( DoComputeAndPack (step, force_flush) ) { ComputeAndPack(); } for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) { if ( !DoDump (step, i_buffer, force_flush) ) continue; Flush(i_buffer); } }
19,044
6,324
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /************************************************************************************************** *** This file was autogenerated from GrCircleBlurFragmentProcessor.fp; do not modify. **************************************************************************************************/ #include "GrCircleBlurFragmentProcessor.h" #include "include/gpu/GrContext.h" #include "include/private/GrRecordingContext.h" #include "src/gpu/GrBitmapTextureMaker.h" #include "src/gpu/GrProxyProvider.h" #include "src/gpu/GrRecordingContextPriv.h" // Computes an unnormalized half kernel (right side). Returns the summation of all the half // kernel values. static float make_unnormalized_half_kernel(float* halfKernel, int halfKernelSize, float sigma) { const float invSigma = 1.f / sigma; const float b = -0.5f * invSigma * invSigma; float tot = 0.0f; // Compute half kernel values at half pixel steps out from the center. float t = 0.5f; for (int i = 0; i < halfKernelSize; ++i) { float value = expf(t * t * b); tot += value; halfKernel[i] = value; t += 1.f; } return tot; } // Create a Gaussian half-kernel (right side) and a summed area table given a sigma and number // of discrete steps. The half kernel is normalized to sum to 0.5. static void make_half_kernel_and_summed_table(float* halfKernel, float* summedHalfKernel, int halfKernelSize, float sigma) { // The half kernel should sum to 0.5 not 1.0. const float tot = 2.f * make_unnormalized_half_kernel(halfKernel, halfKernelSize, sigma); float sum = 0.f; for (int i = 0; i < halfKernelSize; ++i) { halfKernel[i] /= tot; sum += halfKernel[i]; summedHalfKernel[i] = sum; } } // Applies the 1D half kernel vertically at points along the x axis to a circle centered at the // origin with radius circleR. void apply_kernel_in_y(float* results, int numSteps, float firstX, float circleR, int halfKernelSize, const float* summedHalfKernelTable) { float x = firstX; for (int i = 0; i < numSteps; ++i, x += 1.f) { if (x < -circleR || x > circleR) { results[i] = 0; continue; } float y = sqrtf(circleR * circleR - x * x); // In the column at x we exit the circle at +y and -y // The summed table entry j is actually reflects an offset of j + 0.5. y -= 0.5f; int yInt = SkScalarFloorToInt(y); SkASSERT(yInt >= -1); if (y < 0) { results[i] = (y + 0.5f) * summedHalfKernelTable[0]; } else if (yInt >= halfKernelSize - 1) { results[i] = 0.5f; } else { float yFrac = y - yInt; results[i] = (1.f - yFrac) * summedHalfKernelTable[yInt] + yFrac * summedHalfKernelTable[yInt + 1]; } } } // Apply a Gaussian at point (evalX, 0) to a circle centered at the origin with radius circleR. // This relies on having a half kernel computed for the Gaussian and a table of applications of // the half kernel in y to columns at (evalX - halfKernel, evalX - halfKernel + 1, ..., evalX + // halfKernel) passed in as yKernelEvaluations. static uint8_t eval_at(float evalX, float circleR, const float* halfKernel, int halfKernelSize, const float* yKernelEvaluations) { float acc = 0; float x = evalX - halfKernelSize; for (int i = 0; i < halfKernelSize; ++i, x += 1.f) { if (x < -circleR || x > circleR) { continue; } float verticalEval = yKernelEvaluations[i]; acc += verticalEval * halfKernel[halfKernelSize - i - 1]; } for (int i = 0; i < halfKernelSize; ++i, x += 1.f) { if (x < -circleR || x > circleR) { continue; } float verticalEval = yKernelEvaluations[i + halfKernelSize]; acc += verticalEval * halfKernel[i]; } // Since we applied a half kernel in y we multiply acc by 2 (the circle is symmetric about // the x axis). return SkUnitScalarClampToByte(2.f * acc); } // This function creates a profile of a blurred circle. It does this by computing a kernel for // half the Gaussian and a matching summed area table. The summed area table is used to compute // an array of vertical applications of the half kernel to the circle along the x axis. The // table of y evaluations has 2 * k + n entries where k is the size of the half kernel and n is // the size of the profile being computed. Then for each of the n profile entries we walk out k // steps in each horizontal direction multiplying the corresponding y evaluation by the half // kernel entry and sum these values to compute the profile entry. static void create_circle_profile(uint8_t* weights, float sigma, float circleR, int profileTextureWidth) { const int numSteps = profileTextureWidth; // The full kernel is 6 sigmas wide. int halfKernelSize = SkScalarCeilToInt(6.0f * sigma); // round up to next multiple of 2 and then divide by 2 halfKernelSize = ((halfKernelSize + 1) & ~1) >> 1; // Number of x steps at which to apply kernel in y to cover all the profile samples in x. int numYSteps = numSteps + 2 * halfKernelSize; SkAutoTArray<float> bulkAlloc(halfKernelSize + halfKernelSize + numYSteps); float* halfKernel = bulkAlloc.get(); float* summedKernel = bulkAlloc.get() + halfKernelSize; float* yEvals = bulkAlloc.get() + 2 * halfKernelSize; make_half_kernel_and_summed_table(halfKernel, summedKernel, halfKernelSize, sigma); float firstX = -halfKernelSize + 0.5f; apply_kernel_in_y(yEvals, numYSteps, firstX, circleR, halfKernelSize, summedKernel); for (int i = 0; i < numSteps - 1; ++i) { float evalX = i + 0.5f; weights[i] = eval_at(evalX, circleR, halfKernel, halfKernelSize, yEvals + i); } // Ensure the tail of the Gaussian goes to zero. weights[numSteps - 1] = 0; } static void create_half_plane_profile(uint8_t* profile, int profileWidth) { SkASSERT(!(profileWidth & 0x1)); // The full kernel is 6 sigmas wide. float sigma = profileWidth / 6.f; int halfKernelSize = profileWidth / 2; SkAutoTArray<float> halfKernel(halfKernelSize); // The half kernel should sum to 0.5. const float tot = 2.f * make_unnormalized_half_kernel(halfKernel.get(), halfKernelSize, sigma); float sum = 0.f; // Populate the profile from the right edge to the middle. for (int i = 0; i < halfKernelSize; ++i) { halfKernel[halfKernelSize - i - 1] /= tot; sum += halfKernel[halfKernelSize - i - 1]; profile[profileWidth - i - 1] = SkUnitScalarClampToByte(sum); } // Populate the profile from the middle to the left edge (by flipping the half kernel and // continuing the summation). for (int i = 0; i < halfKernelSize; ++i) { sum += halfKernel[i]; profile[halfKernelSize - i - 1] = SkUnitScalarClampToByte(sum); } // Ensure tail goes to 0. profile[profileWidth - 1] = 0; } static GrSurfaceProxyView create_profile_texture(GrRecordingContext* context, const SkRect& circle, float sigma, float* solidRadius, float* textureRadius) { float circleR = circle.width() / 2.0f; if (circleR < SK_ScalarNearlyZero) { return {}; } // Profile textures are cached by the ratio of sigma to circle radius and by the size of the // profile texture (binned by powers of 2). SkScalar sigmaToCircleRRatio = sigma / circleR; // When sigma is really small this becomes a equivalent to convolving a Gaussian with a // half-plane. Similarly, in the extreme high ratio cases circle becomes a point WRT to the // Guassian and the profile texture is a just a Gaussian evaluation. However, we haven't yet // implemented this latter optimization. sigmaToCircleRRatio = std::min(sigmaToCircleRRatio, 8.f); SkFixed sigmaToCircleRRatioFixed; static const SkScalar kHalfPlaneThreshold = 0.1f; bool useHalfPlaneApprox = false; if (sigmaToCircleRRatio <= kHalfPlaneThreshold) { useHalfPlaneApprox = true; sigmaToCircleRRatioFixed = 0; *solidRadius = circleR - 3 * sigma; *textureRadius = 6 * sigma; } else { // Convert to fixed point for the key. sigmaToCircleRRatioFixed = SkScalarToFixed(sigmaToCircleRRatio); // We shave off some bits to reduce the number of unique entries. We could probably // shave off more than we do. sigmaToCircleRRatioFixed &= ~0xff; sigmaToCircleRRatio = SkFixedToScalar(sigmaToCircleRRatioFixed); sigma = circleR * sigmaToCircleRRatio; *solidRadius = 0; *textureRadius = circleR + 3 * sigma; } static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain(); GrUniqueKey key; GrUniqueKey::Builder builder(&key, kDomain, 1, "1-D Circular Blur"); builder[0] = sigmaToCircleRRatioFixed; builder.finish(); GrProxyProvider* proxyProvider = context->priv().proxyProvider(); if (sk_sp<GrTextureProxy> blurProfile = proxyProvider->findOrCreateProxyByUniqueKey(key, GrColorType::kAlpha_8)) { GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(blurProfile->backendFormat(), GrColorType::kAlpha_8); return {std::move(blurProfile), kTopLeft_GrSurfaceOrigin, swizzle}; } static constexpr int kProfileTextureWidth = 512; SkBitmap bm; if (!bm.tryAllocPixels(SkImageInfo::MakeA8(kProfileTextureWidth, 1))) { return {}; } if (useHalfPlaneApprox) { create_half_plane_profile(bm.getAddr8(0, 0), kProfileTextureWidth); } else { // Rescale params to the size of the texture we're creating. SkScalar scale = kProfileTextureWidth / *textureRadius; create_circle_profile(bm.getAddr8(0, 0), sigma * scale, circleR * scale, kProfileTextureWidth); } bm.setImmutable(); GrBitmapTextureMaker maker(context, bm); auto blurView = maker.view(GrMipMapped::kNo); if (!blurView) { return {}; } proxyProvider->assignUniqueKeyToProxy(key, blurView.asTextureProxy()); return blurView; } std::unique_ptr<GrFragmentProcessor> GrCircleBlurFragmentProcessor::Make( GrRecordingContext* context, const SkRect& circle, float sigma) { float solidRadius; float textureRadius; GrSurfaceProxyView profile = create_profile_texture(context, circle, sigma, &solidRadius, &textureRadius); if (!profile) { return nullptr; } return std::unique_ptr<GrFragmentProcessor>(new GrCircleBlurFragmentProcessor( circle, textureRadius, solidRadius, std::move(profile))); } #include "include/gpu/GrTexture.h" #include "src/gpu/glsl/GrGLSLFragmentProcessor.h" #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h" #include "src/gpu/glsl/GrGLSLProgramBuilder.h" #include "src/sksl/SkSLCPP.h" #include "src/sksl/SkSLUtil.h" class GrGLSLCircleBlurFragmentProcessor : public GrGLSLFragmentProcessor { public: GrGLSLCircleBlurFragmentProcessor() {} void emitCode(EmitArgs& args) override { GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; const GrCircleBlurFragmentProcessor& _outer = args.fFp.cast<GrCircleBlurFragmentProcessor>(); (void)_outer; auto circleRect = _outer.circleRect; (void)circleRect; auto textureRadius = _outer.textureRadius; (void)textureRadius; auto solidRadius = _outer.solidRadius; (void)solidRadius; circleDataVar = args.fUniformHandler->addUniform(kFragment_GrShaderFlag, kHalf4_GrSLType, "circleData"); fragBuilder->codeAppendf( "half2 vec = half2(half((sk_FragCoord.x - float(%s.x)) * float(%s.w)), " "half((sk_FragCoord.y - float(%s.y)) * float(%s.w)));\nhalf dist = length(vec) + " "(0.5 - %s.z) * %s.w;\n%s = %s * sample(%s, float2(half2(dist, 0.5))).%s.w;\n", args.fUniformHandler->getUniformCStr(circleDataVar), args.fUniformHandler->getUniformCStr(circleDataVar), args.fUniformHandler->getUniformCStr(circleDataVar), args.fUniformHandler->getUniformCStr(circleDataVar), args.fUniformHandler->getUniformCStr(circleDataVar), args.fUniformHandler->getUniformCStr(circleDataVar), args.fOutputColor, args.fInputColor, fragBuilder->getProgramBuilder()->samplerVariable(args.fTexSamplers[0]), fragBuilder->getProgramBuilder() ->samplerSwizzle(args.fTexSamplers[0]) .asString() .c_str()); } private: void onSetData(const GrGLSLProgramDataManager& data, const GrFragmentProcessor& _proc) override { const GrCircleBlurFragmentProcessor& _outer = _proc.cast<GrCircleBlurFragmentProcessor>(); auto circleRect = _outer.circleRect; (void)circleRect; auto textureRadius = _outer.textureRadius; (void)textureRadius; auto solidRadius = _outer.solidRadius; (void)solidRadius; const GrSurfaceProxyView& blurProfileSamplerView = _outer.textureSampler(0).view(); GrTexture& blurProfileSampler = *blurProfileSamplerView.proxy()->peekTexture(); (void)blurProfileSampler; UniformHandle& circleData = circleDataVar; (void)circleData; data.set4f(circleData, circleRect.centerX(), circleRect.centerY(), solidRadius, 1.f / textureRadius); } UniformHandle circleDataVar; }; GrGLSLFragmentProcessor* GrCircleBlurFragmentProcessor::onCreateGLSLInstance() const { return new GrGLSLCircleBlurFragmentProcessor(); } void GrCircleBlurFragmentProcessor::onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const {} bool GrCircleBlurFragmentProcessor::onIsEqual(const GrFragmentProcessor& other) const { const GrCircleBlurFragmentProcessor& that = other.cast<GrCircleBlurFragmentProcessor>(); (void)that; if (circleRect != that.circleRect) return false; if (textureRadius != that.textureRadius) return false; if (solidRadius != that.solidRadius) return false; if (blurProfileSampler != that.blurProfileSampler) return false; return true; } GrCircleBlurFragmentProcessor::GrCircleBlurFragmentProcessor( const GrCircleBlurFragmentProcessor& src) : INHERITED(kGrCircleBlurFragmentProcessor_ClassID, src.optimizationFlags()) , circleRect(src.circleRect) , textureRadius(src.textureRadius) , solidRadius(src.solidRadius) , blurProfileSampler(src.blurProfileSampler) { this->setTextureSamplerCnt(1); } std::unique_ptr<GrFragmentProcessor> GrCircleBlurFragmentProcessor::clone() const { return std::unique_ptr<GrFragmentProcessor>(new GrCircleBlurFragmentProcessor(*this)); } const GrFragmentProcessor::TextureSampler& GrCircleBlurFragmentProcessor::onTextureSampler( int index) const { return IthTextureSampler(index, blurProfileSampler); } GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrCircleBlurFragmentProcessor); #if GR_TEST_UTILS std::unique_ptr<GrFragmentProcessor> GrCircleBlurFragmentProcessor::TestCreate( GrProcessorTestData* testData) { SkScalar wh = testData->fRandom->nextRangeScalar(100.f, 1000.f); SkScalar sigma = testData->fRandom->nextRangeF(1.f, 10.f); SkRect circle = SkRect::MakeWH(wh, wh); return GrCircleBlurFragmentProcessor::Make(testData->context(), circle, sigma); } #endif
16,133
5,059
#include <cassert> #include "UserAgent.hxx" #include "UserAgentServerAuthManager.hxx" #include <resip/dum/DialogUsageManager.hxx> #include <resip/dum/ServerAuthManager.hxx> #include <resip/dum/UserAuthInfo.hxx> #include <resip/dum/UserProfile.hxx> #include <rutil/MD5Stream.hxx> #include <rutil/WinLeakCheck.hxx> #define RESIPROCATE_SUBSYSTEM Subsystem::RECON using namespace recon; using namespace resip; UserAgentServerAuthManager::UserAgentServerAuthManager(UserAgent& userAgent) : ServerAuthManager(userAgent.getDialogUsageManager(), userAgent.getDialogUsageManager().dumIncomingTarget()), mUserAgent(userAgent) { } UserAgentServerAuthManager::~UserAgentServerAuthManager() { } bool UserAgentServerAuthManager::useAuthInt() const { return true; } bool UserAgentServerAuthManager::proxyAuthenticationMode() const { return false; // Challenge with 401 } const Data& UserAgentServerAuthManager::getChallengeRealm(const SipMessage& msg) { return mUserAgent.getIncomingConversationProfile(msg)->getDefaultFrom().uri().host(); } bool UserAgentServerAuthManager::isMyRealm(const Data& realm) { return true; // .slg. this means we will try to find credentials for any authorization headers // could improve this by looking through all active conversation profiles to see if realm exists } bool UserAgentServerAuthManager::authorizedForThisIdentity(const resip::Data &user, const resip::Data &realm, resip::Uri &fromUri) { return true; // We don't care who the request came from } ServerAuthManager::AsyncBool UserAgentServerAuthManager::requiresChallenge(const SipMessage& msg) { assert(msg.isRequest()); ConversationProfile* profile = mUserAgent.getIncomingConversationProfile(msg).get(); // We want to challenge OOD Refer requests and Invite Requests with Auto-Answer indications switch(msg.method()) { case REFER: if(profile->challengeOODReferRequests() && !msg.header(h_To).exists(p_tag)) { // Don't challenge OOD Refer requests have a valid TargetDialog header if(!msg.exists(h_TargetDialog) || mUserAgent.getDialogUsageManager().findInviteSession(msg.header(h_TargetDialog)).first == InviteSessionHandle::NotValid()) { return True; } } break; case INVITE: if(profile->challengeAutoAnswerRequests() && profile->shouldAutoAnswer(msg)) { return True; } break; default: break; } // Default to not challenge return False; } void UserAgentServerAuthManager::requestCredential(const Data& user, const Data& realm, const SipMessage& msg, const Auth& auth, const Data& transactionId ) { const UserProfile::DigestCredential& digestCredential = mUserAgent.getIncomingConversationProfile(msg)->getDigestCredential(realm); MD5Stream a1; a1 << digestCredential.user << Symbols::COLON << digestCredential.realm << Symbols::COLON << digestCredential.password; a1.flush(); UserAuthInfo* userAuthInfo = new UserAuthInfo(user,realm,a1.getHex(),transactionId); mUserAgent.getDialogUsageManager().post( userAuthInfo ); } /* ==================================================================== Copyright (c) 2007-2008, Plantronics, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Plantronics nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==================================================================== */
5,159
1,565
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #define BOOST_TEST_MODULE SparseFormatsTest #include "../lib/popsparse/SparseStorageInternal.hpp" #include <boost/test/unit_test.hpp> // CSR/CSC representation of matrix for element sparsity // 10 20 0 0 0 0 // 0 30 0 40 0 0 // 0 0 50 60 70 0 // 0 0 0 0 0 80 // CSR/CSC representation of matrix for block sparsity with 2x3 blocks // 10 11 12 20 21 22 0 0 0 0 0 0 0 0 0 0 0 0 // 13 14 15 23 24 25 0 0 0 0 0 0 0 0 0 0 0 0 // // 0 0 0 30 31 32 0 0 0 40 41 42 0 0 0 0 0 0 // 0 0 0 33 34 35 0 0 0 43 44 45 0 0 0 0 0 0 // // 0 0 0 0 0 0 50 51 52 60 61 62 70 71 72 0 0 0 // 0 0 0 0 0 0 53 54 55 63 64 65 73 74 75 0 0 0 // // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 81 82 // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 83 84 85 const std::size_t numRows = 4; const std::size_t numColumns = 6; const std::size_t numRowsInBlock = 2; const std::size_t numColumnsInBlock = 3; static const popsparse::CSRMatrix<double> csrRef({10.0, 20, 30, 40, 50, 60, 70, 80.0}, {0, 1, 1, 3, 2, 3, 4, 5}, {0, 2, 4, 7, 8}); const popsparse::CSRMatrix<double> csrRef2x3( {10.0, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 60, 61, 62, 63, 64, 65, 70, 71, 72, 73, 74, 75, 80.0, 81, 82, 83, 84, 85}, {0, 3, 3, 9, 6, 9, 12, 15}, {0, 12, 24, 42, 48}, {2, 3}); // CSR/CSC/COO representation of matrix for block sparsity with 2x6 blocks // 0 1 2 3 4 5 0 0 0 0 0 0 20 21 22 23 24 25 // 6 7 8 9 10 11 0 0 0 0 0 0 26 27 28 29 30 31 // // 0 0 0 0 0 0 40 41 42 43 44 45 0 0 0 0 0 0 // 0 0 0 0 0 0 46 47 48 49 50 51 0 0 0 0 0 0 // // 50 51 52 53 54 55 70 71 72 73 74 75 80 81 82 83 84 85 // 56 57 58 59 60 61 76 77 78 79 80 81 86 87 88 89 90 91 static const popsparse::CSRMatrix<std::size_t> csrRef2x6( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91}, {0, 12, 6, 0, 6, 12}, {0, 24, 36, 72}, {2, 6}); static const popsparse::COOMatrix<std::size_t> cooRef2x6( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91}, {0, 12, 6, 0, 6, 12}, {0, 0, 2, 4, 4, 4}, {2, 6}); static const popsparse::CSRMatrix<std::size_t> csrRef2x6_1x2( {0, 1, 2, 3, 4, 5, 20, 21, 22, 23, 24, 25, 6, 7, 8, 9, 10, 11, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 70, 71, 72, 73, 74, 75, 80, 81, 82, 83, 84, 85, 56, 57, 58, 59, 60, 61, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91}, {0, 2, 4, 12, 14, 16, 0, 2, 4, 12, 14, 16, 6, 8, 10, 6, 8, 10, 0, 2, 4, 6, 8, 10, 12, 14, 16, 0, 2, 4, 6, 8, 10, 12, 14, 16}, {0, 12, 24, 30, 36, 54, 72}, {1, 2}); static const popsparse::COOMatrix<std::size_t> cooRef2x6_1x2( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91}, {0, 2, 4, 0, 2, 4, 12, 14, 16, 12, 14, 16, 6, 8, 10, 6, 8, 10, 0, 2, 4, 0, 2, 4, 6, 8, 10, 6, 8, 10, 12, 14, 16, 12, 14, 16}, {0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 4, 4, 4, 5, 5, 5, 4, 4, 4, 5, 5, 5}, {1, 2}); // CSR/CSC with block size of 4x4 // 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 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 52 53 54 55 56 57 58 59 60 61 62 63 static const popsparse::CSRMatrix<std::size_t> csrRef4x4({0, 1, 2, 3, 16, 17, 18, 19, 32, 33, 34, 35, 48, 49, 50, 51, 4, 5, 6, 7, 20, 21, 22, 23, 36, 37, 38, 39, 52, 53, 54, 55, 8, 9, 10, 11, 24, 25, 26, 27, 40, 41, 42, 43, 56, 57, 58, 59, 12, 13, 14, 15, 28, 29, 30, 31, 44, 45, 46, 47, 60, 61, 62, 63}, {0, 4, 8, 12}, {0, 64}, {4, 4}); static const popsparse::CSRMatrix<std::size_t> csrRef4x4_2x2( {0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23, 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31, 32, 33, 48, 49, 34, 35, 50, 51, 36, 37, 52, 53, 38, 39, 54, 55, 40, 41, 56, 57, 42, 43, 58, 59, 44, 45, 60, 61, 46, 47, 62, 63}, {0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14}, {0, 32, 64}, {2, 2}); static const popsparse::COOMatrix<std::size_t> cooRef4x4({0, 1, 2, 3, 16, 17, 18, 19, 32, 33, 34, 35, 48, 49, 50, 51, 4, 5, 6, 7, 20, 21, 22, 23, 36, 37, 38, 39, 52, 53, 54, 55, 8, 9, 10, 11, 24, 25, 26, 27, 40, 41, 42, 43, 56, 57, 58, 59, 12, 13, 14, 15, 28, 29, 30, 31, 44, 45, 46, 47, 60, 61, 62, 63}, {0, 4, 8, 12}, {0, 0, 0, 0}, {4, 4}); static const popsparse::COOMatrix<std::size_t> cooRef4x4_2x2( {0, 1, 16, 17, 2, 3, 18, 19, 32, 33, 48, 49, 34, 35, 50, 51, 4, 5, 20, 21, 6, 7, 22, 23, 36, 37, 52, 53, 38, 39, 54, 55, 8, 9, 24, 25, 10, 11, 26, 27, 40, 41, 56, 57, 42, 43, 58, 59, 12, 13, 28, 29, 14, 15, 30, 31, 44, 45, 60, 61, 46, 47, 62, 63}, {0, 2, 0, 2, 4, 6, 4, 6, 8, 10, 8, 10, 12, 14, 12, 14}, {0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2}, {2, 2}); static const popsparse::CSRMatrix<std::size_t> csrRefS({10, 20, 30, 40, 50, 60, 70, 80}, {0, 1, 1, 3, 2, 3, 4, 5}, {0, 2, 4, 7, 8}); static const popsparse::CSCMatrix<double> cscRef({10, 20, 30, 50, 40, 60, 70, 80}, {0, 1, 3, 4, 6, 7, 8}, {0, 0, 1, 2, 1, 2, 2, 3}); static const popsparse::CSCMatrix<double> cscRef2x3({10, 13, 11, 14, 12, 15, 20, 23, 21, 24, 22, 25, 30, 33, 31, 34, 32, 35, 50, 53, 51, 54, 52, 55, 40, 43, 41, 44, 42, 45, 60, 63, 61, 64, 62, 65, 70, 73, 71, 74, 72, 75, 80, 83, 81, 84, 82, 85}, {0, 6, 18, 24, 36, 42, 48}, {0, 0, 2, 4, 2, 4, 4, 6}, {2, 3}); static const popsparse::CSRMatrix<double> csrRefUnsorted({10.0, 20, 40, 30, 70, 50, 60, 80.0}, {0, 1, 3, 1, 4, 2, 3, 5}, {0, 2, 4, 7, 8}); static const popsparse::CSRMatrix<double> csrRefUnsorted2x3( {10.0, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 40, 41, 42, 43, 44, 45, 30, 31, 32, 33, 34, 35, 70, 71, 72, 73, 74, 75, 50, 51, 52, 53, 54, 55, 60, 61, 62, 63, 64, 65, 80.0, 81, 82, 83, 84, 85}, {0, 3, 9, 3, 12, 6, 9, 15}, {0, 12, 24, 42, 48}, {2, 3}); static const popsparse::COOMatrix<double> cooUnsorted({80, 70, 60, 50, 40, 30, 20, 10}, {5, 4, 3, 2, 3, 1, 1, 0}, {3, 2, 2, 2, 1, 1, 0, 0}); static const popsparse::COOMatrix<double> cooUnsorted2x3( {80, 81, 82, 83, 84, 85, 70, 71, 72, 73, 74, 75, 60, 61, 62, 63, 64, 65, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45, 30, 31, 32, 33, 34, 35, 20, 21, 22, 23, 24, 25, 10, 11, 12, 13, 14, 15}, {15, 12, 9, 6, 9, 3, 3, 0}, {6, 4, 4, 4, 2, 2, 0, 0}); BOOST_AUTO_TEST_CASE(ValidateCsrToCsc) { auto cscResult = popsparse::csrToCSC(numRows, numColumns, csrRef); BOOST_CHECK_EQUAL_COLLECTIONS(cscRef.nzValues.begin(), cscRef.nzValues.end(), cscResult.nzValues.begin(), cscResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef.rowIndices.begin(), cscRef.rowIndices.end(), cscResult.rowIndices.begin(), cscResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef.columnIndices.begin(), cscRef.columnIndices.end(), cscResult.columnIndices.begin(), cscResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCsrToCscBlock) { auto cscResult = popsparse::csrToCSC( numRows * numRowsInBlock, numColumns * numColumnsInBlock, csrRef2x3); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef2x3.nzValues.begin(), cscRef2x3.nzValues.end(), cscResult.nzValues.begin(), cscResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef2x3.rowIndices.begin(), cscRef2x3.rowIndices.end(), cscResult.rowIndices.begin(), cscResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef2x3.columnIndices.begin(), cscRef2x3.columnIndices.end(), cscResult.columnIndices.begin(), cscResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCscToCsr) { auto csrResult = popsparse::cscToCSR(numRows, numColumns, cscRef); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csrResult.nzValues.begin(), csrResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csrResult.rowIndices.begin(), csrResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csrResult.columnIndices.begin(), csrResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCscToCsrBlock) { auto csrResult = popsparse::cscToCSR( numRows * numRowsInBlock, numColumns * numColumnsInBlock, cscRef2x3); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.nzValues.begin(), csrRef2x3.nzValues.end(), csrResult.nzValues.begin(), csrResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.rowIndices.begin(), csrRef2x3.rowIndices.end(), csrResult.rowIndices.begin(), csrResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.columnIndices.begin(), csrRef2x3.columnIndices.end(), csrResult.columnIndices.begin(), csrResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateTransposeCSR) { auto csrRes1 = popsparse::csrTranspose(numRows, numColumns, csrRef); auto csrRes2 = popsparse::csrTranspose(numColumns, numRows, csrRes1); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csrRes2.nzValues.begin(), csrRes2.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csrRes2.rowIndices.begin(), csrRes2.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csrRes2.columnIndices.begin(), csrRes2.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateTransposeCSRBlock) { auto csrRes1 = popsparse::csrTranspose( numRows * numRowsInBlock, numColumns * numColumnsInBlock, csrRef2x3); auto csrRes2 = popsparse::csrTranspose(numColumns * numColumnsInBlock, numRows * numRowsInBlock, csrRes1); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.nzValues.begin(), csrRef2x3.nzValues.end(), csrRes2.nzValues.begin(), csrRes2.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.rowIndices.begin(), csrRef2x3.rowIndices.end(), csrRes2.rowIndices.begin(), csrRes2.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.columnIndices.begin(), csrRef2x3.columnIndices.end(), csrRes2.columnIndices.begin(), csrRes2.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCSRCanonicalize) { auto csr = csrRefUnsorted; popsparse::canonicalizeCSR(csr); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCSRCanonicalizeBlock) { auto csr = csrRefUnsorted2x3; popsparse::canonicalizeCSR(csr); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x3.nzValues.begin(), csrRef2x3.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x3.rowIndices.begin(), csrRef2x3.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.columnIndices.begin(), csrRef2x3.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(GetRowPositionTest) { const auto tile = popsparse::Tile(poplar::Interval(0, 2), poplar::Interval(0, 4)); const std::size_t blockSizeX = 1, blockSizeY = 1; const auto rowInfo = popsparse::getPositionValuePairsPerRow( csrRefS, blockSizeX, blockSizeY, tile); const std::vector<std::vector<std::pair<double, std::size_t>>> expectedInfo = {{{0, 10}, {1, 20}}, {{1, 30}, {3, 40}}}; BOOST_CHECK_EQUAL(rowInfo.size(), expectedInfo.size()); for (unsigned row = 0; row != expectedInfo.size(); ++row) { BOOST_CHECK_EQUAL(rowInfo[row].positionValues.size(), expectedInfo[row].size()); const auto expt = expectedInfo[row]; const auto real = rowInfo[row].positionValues; for (unsigned column = 0; column != expectedInfo[row].size(); ++column) { BOOST_CHECK_EQUAL(real[column].first, expt[column].first); BOOST_CHECK_EQUAL(real[column].second, expt[column].second); } BOOST_CHECK_EQUAL(rowInfo[row].rowNumber, row); } } BOOST_AUTO_TEST_CASE(ConvertCooToCsr) { auto csr = popsparse::cooToCSR(numRows, numColumns, cooUnsorted); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCsrBlockSize2x6) { auto csr = popsparse::changeCSRBlockSize(csrRef2x6, {1, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x6_1x2.nzValues.begin(), csrRef2x6_1x2.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x6_1x2.rowIndices.begin(), csrRef2x6_1x2.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x6_1x2.columnIndices.begin(), csrRef2x6_1x2.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCsrBlockSize4x4) { auto csr = popsparse::changeCSRBlockSize(csrRef4x4, {2, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef4x4_2x2.nzValues.begin(), csrRef4x4_2x2.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef4x4_2x2.rowIndices.begin(), csrRef4x4_2x2.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef4x4_2x2.columnIndices.begin(), csrRef4x4_2x2.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCscBlockSize4x4) { auto csc4x4 = popsparse::csrToCSC(4, 16, csrRef4x4); auto csc4x4_2x2 = popsparse::csrToCSC(4, 16, csrRef4x4_2x2); auto csc = popsparse::changeCSCBlockSize(csc4x4, {2, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csc4x4_2x2.nzValues.begin(), csc4x4_2x2.nzValues.end(), csc.nzValues.begin(), csc.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csc4x4_2x2.rowIndices.begin(), csc4x4_2x2.rowIndices.end(), csc.rowIndices.begin(), csc.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csc4x4_2x2.columnIndices.begin(), csc4x4_2x2.columnIndices.end(), csc.columnIndices.begin(), csc.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCscBlockSize2x6) { auto csc2x6 = popsparse::csrToCSC(6, 18, csrRef2x6); auto csc2x6_1x2 = popsparse::csrToCSC(6, 18, csrRef2x6_1x2); auto csc = popsparse::changeCSCBlockSize(csc2x6, {1, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csc2x6_1x2.nzValues.begin(), csc2x6_1x2.nzValues.end(), csc.nzValues.begin(), csc.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csc2x6_1x2.rowIndices.begin(), csc2x6_1x2.rowIndices.end(), csc.rowIndices.begin(), csc.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csc2x6_1x2.columnIndices.begin(), csc2x6_1x2.columnIndices.end(), csc.columnIndices.begin(), csc.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize4x4) { auto coo = popsparse::changeCOOBlockSize(cooRef4x4, {2, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef4x4_2x2.nzValues.begin(), cooRef4x4_2x2.nzValues.end(), coo.nzValues.begin(), coo.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef4x4_2x2.rowIndices.begin(), cooRef4x4_2x2.rowIndices.end(), coo.rowIndices.begin(), coo.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4_2x2.columnIndices.begin(), cooRef4x4_2x2.columnIndices.end(), coo.columnIndices.begin(), coo.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize2x6) { auto coo = popsparse::changeCOOBlockSize(cooRef2x6, {1, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef2x6_1x2.nzValues.begin(), cooRef2x6_1x2.nzValues.end(), coo.nzValues.begin(), coo.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef2x6_1x2.rowIndices.begin(), cooRef2x6_1x2.rowIndices.end(), coo.rowIndices.begin(), coo.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6_1x2.columnIndices.begin(), cooRef2x6_1x2.columnIndices.end(), coo.columnIndices.begin(), coo.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize2x6DoubleChange) { auto coo = popsparse::changeCOOBlockSize(cooRef2x6, {1, 2}); auto cooOrig = popsparse::changeCOOBlockSize(coo, {2, 6}); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6.nzValues.begin(), cooRef2x6.nzValues.end(), cooOrig.nzValues.begin(), cooOrig.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6.rowIndices.begin(), cooRef2x6.rowIndices.end(), cooOrig.rowIndices.begin(), cooOrig.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6.columnIndices.begin(), cooRef2x6.columnIndices.end(), cooOrig.columnIndices.begin(), cooOrig.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize4x4DoubleChange) { auto coo = popsparse::changeCOOBlockSize(cooRef4x4, {2, 2}); auto cooOrig = popsparse::changeCOOBlockSize(coo, {4, 4}); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4.nzValues.begin(), cooRef4x4.nzValues.end(), cooOrig.nzValues.begin(), cooOrig.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4.rowIndices.begin(), cooRef4x4.rowIndices.end(), cooOrig.rowIndices.begin(), cooOrig.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4.columnIndices.begin(), cooRef4x4.columnIndices.end(), cooOrig.columnIndices.begin(), cooOrig.columnIndices.end()); }
20,539
10,820
// // onnxOpConverter.cpp // MNNConverter // // Created by MNN on 2019/01/31. // Copyright © 2018, Alibaba Group Holding Limited // #include "onnxOpConverter.hpp" #include "OpCount.hpp" using namespace MNN; static int32_t _limit(int64_t i64) { if (i64 > (int64_t)(1 << 30)) { return 1 << 30; } if (i64 < (int64_t)(-(1 << 30))) { return (-(1 << 30)); } return i64; } class DefaultonnxOpConverter : public onnxOpConverter { public: virtual void run(MNN::OpT* dstOp, const onnx::NodeProto* onnxNode, std::vector<const onnx::TensorProto*> initializers) override { auto extra = new ExtraT; dstOp->main.type = OpParameter_Extra; dstOp->main.value = extra; extra->engine = "ONNX"; extra->type = onnxNode->op_type(); for (auto srcAttr : onnxNode->attribute()) { std::unique_ptr<AttributeT> attr(new AttributeT); attr->key = srcAttr.name(); switch (srcAttr.type()) { case onnx::AttributeProto_AttributeType_INTS: attr->list.reset(new ListValueT); attr->list->i.resize(srcAttr.ints_size()); for (int i = 0; i < srcAttr.ints_size(); ++i) { attr->list->i[i] = _limit(srcAttr.ints(i)); } break; case onnx::AttributeProto_AttributeType_FLOATS: attr->list.reset(new ListValueT); attr->list->f.resize(srcAttr.floats_size()); for (int i = 0; i < srcAttr.floats_size(); ++i) { attr->list->f[i] = srcAttr.floats(i); } break; case onnx::AttributeProto_AttributeType_TENSOR: attr->tensor.reset(convertTensorToBlob(&srcAttr.t())); break; default: break; } attr->i = _limit(srcAttr.i()); attr->s = srcAttr.s(); attr->f = srcAttr.f(); extra->attr.emplace_back(std::move(attr)); } } virtual MNN::OpParameter type() override { return OpParameter_Extra; } virtual MNN::OpType opType() override { return OpType_Extra; } }; onnxOpConverterSuit::onnxOpConverterSuit() { } onnxOpConverterSuit::~onnxOpConverterSuit() { for (auto& iter : mConverterContainer) { delete iter.second; } mConverterContainer.clear(); } onnxOpConverterSuit* onnxOpConverterSuit::global = nullptr; onnxOpConverterSuit* onnxOpConverterSuit::get() { if (global == nullptr) { global = new onnxOpConverterSuit; } return global; } void onnxOpConverterSuit::insert(onnxOpConverter* t, const char* name) { MNN::OpCount::get()->insertOp("ONNX", std::string(name)); mConverterContainer.insert(std::make_pair(name, t)); } onnxOpConverter* onnxOpConverterSuit::search(const std::string& name) { auto iter = mConverterContainer.find(name); if (iter == mConverterContainer.end()) { static DefaultonnxOpConverter defaultConverter; return &defaultConverter; } return iter->second; } MNN::DataType onnxOpConverter::convertDataType(::onnx::TensorProto_DataType type) { static std::map<::onnx::TensorProto_DataType, MNN::DataType> dataTypeMap{ {onnx::TensorProto_DataType_FLOAT, MNN::DataType_DT_FLOAT}, {onnx::TensorProto_DataType_INT8, MNN::DataType_DT_INT8}, {onnx::TensorProto_DataType_INT32, MNN::DataType_DT_INT32}, {onnx::TensorProto_DataType_INT64, MNN::DataType_DT_INT32}, // For compability, use int32 instead of int64 {onnx::TensorProto_DataType_DOUBLE, MNN::DataType_DT_FLOAT}, // For compability, use float instead of double {onnx::TensorProto_DataType_UINT8, MNN::DataType_DT_UINT8}, {onnx::TensorProto_DataType_INT8, MNN::DataType_DT_INT8}, {onnx::TensorProto_DataType_BOOL, MNN::DataType_DT_INT32}, // For compability, use int32 instead of bool {onnx::TensorProto_DataType_INT16, MNN::DataType_DT_INT32}, // For compability, use int32 instead of int16 {onnx::TensorProto_DataType_UINT16, MNN::DataType_DT_INT32}, // For compability, use int32 instead of uint16 }; if (dataTypeMap.find(type) != dataTypeMap.end()) { return dataTypeMap[type]; } return MNN::DataType_DT_INVALID; } MNN::BlobT* onnxOpConverter::convertTensorToBlob(const onnx::TensorProto* constantTp) { auto constantParam = new MNN::BlobT; auto dataType = convertDataType(constantTp->data_type()); // printf("origindataType = %d, dataType = %s\n", constantTp->data_type(), MNN::EnumNameDataType(dataType)); constantParam->dataType = dataType; constantParam->dataFormat = MNN::MNN_DATA_FORMAT_NCHW; size_t dimSize = constantTp->dims().size(); constantParam->dims.resize(dimSize); size_t dataSize = 1; for (int i = 0; i < dimSize; ++i) { constantParam->dims[i] = constantTp->dims(i); dataSize = dataSize * constantTp->dims(i); } std::vector<int64_t> alignContent((constantTp->raw_data().size() + sizeof(int64_t) - 1) / sizeof(int64_t)); ::memcpy(alignContent.data(), constantTp->raw_data().data(), constantTp->raw_data().size()); const void* tensor_content = (const void*)alignContent.data(); switch (constantTp->data_type()) { #define CASE_DATA_TYPE(src, dst) \ case src: \ if (constantTp->dst##_data_size() != 0) { \ tensor_content = constantTp->dst##_data().data(); \ } \ break; CASE_DATA_TYPE(onnx::TensorProto_DataType_DOUBLE, double); CASE_DATA_TYPE(onnx::TensorProto_DataType_INT64, int64); CASE_DATA_TYPE(onnx::TensorProto_DataType_INT32, int32); CASE_DATA_TYPE(onnx::TensorProto_DataType_FLOAT, float); default: break; } if (0 == dataSize) { // Empty blob return constantParam; } if (!tensor_content) { DLOG(FATAL) << "Convert no data, " "Please make sure "; } switch (constantTp->data_type()) { case onnx::TensorProto_DataType_DOUBLE: { constantParam->float32s.resize(dataSize); auto source = (double*)tensor_content; for (int i = 0; i < dataSize; ++i) { constantParam->float32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_INT64: { constantParam->int32s.resize(dataSize); auto source = (int64_t*)tensor_content; for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = _limit(source[i]); } break; } case onnx::TensorProto_DataType_INT32: { auto source = (int32_t*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_UINT16: { auto source = (uint16_t*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_INT16: { auto source = (int16_t*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_BOOL: { auto source = (bool*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_INT8: { auto source = (int8_t*)tensor_content; constantParam->int8s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int8s[i] = source[i]; } break; } case onnx::TensorProto_DataType_UINT8: { auto source = (uint8_t*)tensor_content; constantParam->uint8s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->uint8s[i] = source[i]; } break; } case onnx::TensorProto_DataType_FLOAT: { float* tempFloatData = (float*)tensor_content; constantParam->float32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->float32s[i] = tempFloatData[i]; } break; } default: { DLOG(FATAL) << "Don't support " << constantTp->data_type(); break; } } return constantParam; }
9,224
3,036
/*========================================================================= * * 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 itkImageFileReader_hxx #define itkImageFileReader_hxx #include "itkImageFileReader.h" #include "itkObjectFactory.h" #include "itkImageIOFactory.h" #include "itkConvertPixelBuffer.h" #include "itkPixelTraits.h" #include "itkVectorImage.h" #include "itkMetaDataObject.h" #include "itksys/SystemTools.hxx" #include <memory> // For unique_ptr #include <fstream> namespace itk { template <typename TOutputImage, typename ConvertPixelTraits> ImageFileReader<TOutputImage, ConvertPixelTraits>::ImageFileReader() { m_ImageIO = nullptr; this->SetFileName(""); m_UserSpecifiedImageIO = false; m_UseStreaming = true; } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); itkPrintSelfObjectMacro(ImageIO); os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n"; os << indent << "m_UseStreaming: " << m_UseStreaming << "\n"; } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::SetImageIO(ImageIOBase * imageIO) { itkDebugMacro("setting ImageIO to " << imageIO); if (this->m_ImageIO != imageIO) { this->m_ImageIO = imageIO; this->Modified(); } m_UserSpecifiedImageIO = true; } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::GenerateOutputInformation() { typename TOutputImage::Pointer output = this->GetOutput(); itkDebugMacro(<< "Reading file for GenerateOutputInformation()" << this->GetFileName()); // Check to see if we can read the file given the name or prefix // if (this->GetFileName().empty()) { throw ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); } // Test if the file exists and if it can be opened. // An exception will be thrown otherwise. // We catch the exception because some ImageIO's may not actually // open a file. Still reports file error if no ImageIO is loaded. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch (const itk::ExceptionObject & err) { m_ExceptionMessage = err.GetDescription(); } if (m_UserSpecifiedImageIO == false) // try creating via factory { m_ImageIO = ImageIOFactory::CreateImageIO(this->GetFileName().c_str(), ImageIOFactory::IOFileModeEnum::ReadMode); } if (m_ImageIO.IsNull()) { std::ostringstream msg; msg << " Could not create IO object for reading file " << this->GetFileName().c_str() << std::endl; if (!m_ExceptionMessage.empty()) { msg << m_ExceptionMessage; } else { std::list<LightObject::Pointer> allobjects = ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); if (!allobjects.empty()) { msg << " Tried to create one of the following:" << std::endl; for (auto & allobject : allobjects) { auto * io = dynamic_cast<ImageIOBase *>(allobject.GetPointer()); msg << " " << io->GetNameOfClass() << std::endl; } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; } else { msg << " There are no registered IO factories." << std::endl; msg << " Please visit https://www.itk.org/Wiki/ITK/FAQ#NoFactoryException to diagnose the problem." << std::endl; } } ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } // Got to allocate space for the image. Determine the characteristics of // the image. // m_ImageIO->SetFileName(this->GetFileName().c_str()); m_ImageIO->ReadImageInformation(); SizeType dimSize; double spacing[TOutputImage::ImageDimension]; double origin[TOutputImage::ImageDimension]; typename TOutputImage::DirectionType direction; std::vector<std::vector<double>> directionIO; const unsigned int numberOfDimensionsIO = m_ImageIO->GetNumberOfDimensions(); if (numberOfDimensionsIO > TOutputImage::ImageDimension) { for (unsigned int k = 0; k < numberOfDimensionsIO; ++k) { directionIO.push_back(m_ImageIO->GetDefaultDirection(k)); } } else { for (unsigned int k = 0; k < numberOfDimensionsIO; ++k) { directionIO.push_back(m_ImageIO->GetDirection(k)); } } std::vector<double> axis; for (unsigned int i = 0; i < TOutputImage::ImageDimension; ++i) { if (i < numberOfDimensionsIO) { dimSize[i] = m_ImageIO->GetDimensions(i); spacing[i] = m_ImageIO->GetSpacing(i); origin[i] = m_ImageIO->GetOrigin(i); // Please note: direction cosines are stored as columns of the // direction matrix axis = directionIO[i]; for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j) { if (j < numberOfDimensionsIO) { direction[j][i] = axis[j]; } else { direction[j][i] = 0.0; } } } else { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, origin and direction for the final (degenerate) dimensions. dimSize[i] = 1; spacing[i] = 1.0; origin[i] = 0.0; for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j) { if (i == j) { direction[j][i] = 1.0; } else { direction[j][i] = 0.0; } } } } MetaDataDictionary & thisDic = m_ImageIO->GetMetaDataDictionary(); // Store original directions and spacing EncapsulateMetaData<std::vector<double>>( thisDic, "ITK_original_spacing", std::vector<double>(spacing, spacing + TOutputImage::ImageDimension)); EncapsulateMetaData<typename TOutputImage::DirectionType>(thisDic, "ITK_original_direction", direction); // Spacing is expected to be greater than 0 // If negative, flip image direction along this axis. // and store this information in the metadata for (unsigned int i = 0; i < TOutputImage::ImageDimension; ++i) { if (spacing[i] < 0) { spacing[i] = -spacing[i]; for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j) { direction[j][i] = -direction[j][i]; } } } output->SetSpacing(spacing); // Set the image spacing output->SetOrigin(origin); // Set the image origin output->SetDirection(direction); // Set the image direction cosines // Copy MetaDataDictionary from instantiated reader to output image. output->SetMetaDataDictionary(thisDic); this->SetMetaDataDictionary(thisDic); IndexType start; start.Fill(0); ImageRegionType region; region.SetSize(dimSize); region.SetIndex(start); // If a VectorImage, this requires us to set the // VectorLength before allocate if (strcmp(output->GetNameOfClass(), "VectorImage") == 0) { using AccessorFunctorType = typename TOutputImage::AccessorFunctorType; AccessorFunctorType::SetVectorLength(output, m_ImageIO->GetNumberOfComponents()); } output->SetLargestPossibleRegion(region); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::TestFileExistanceAndReadability() { // Test if the file exists. if (!itksys::SystemTools::FileExists(this->GetFileName().c_str())) { ImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "The file doesn't exist. " << std::endl << "Filename = " << this->GetFileName() << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; } // Test if the file can be open for reading access. std::ifstream readTester; readTester.open(this->GetFileName().c_str()); if (readTester.fail()) { readTester.close(); std::ostringstream msg; msg << "The file couldn't be opened for reading. " << std::endl << "Filename: " << this->GetFileName() << std::endl; ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } readTester.close(); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::EnlargeOutputRequestedRegion(DataObject * output) { itkDebugMacro(<< "Starting EnlargeOutputRequestedRegion() "); typename TOutputImage::Pointer out = dynamic_cast<TOutputImage *>(output); typename TOutputImage::RegionType largestRegion = out->GetLargestPossibleRegion(); ImageRegionType streamableRegion; // The following code converts the ImageRegion (templated over dimension) // into an ImageIORegion (not templated over dimension). ImageRegionType imageRequestedRegion = out->GetRequestedRegion(); ImageIORegion ioRequestedRegion(TOutputImage::ImageDimension); using ImageIOAdaptor = ImageIORegionAdaptor<TOutputImage::ImageDimension>; ImageIOAdaptor::Convert(imageRequestedRegion, ioRequestedRegion, largestRegion.GetIndex()); // Tell the IO if we should use streaming while reading m_ImageIO->SetUseStreamedReading(m_UseStreaming); // Delegate to the ImageIO the computation of how the // requested region must be enlarged. m_ActualIORegion = m_ImageIO->GenerateStreamableReadRegionFromRequestedRegion(ioRequestedRegion); // the m_ActualIORegion may be more dimensions then the output // Image, in which case we still need to read this larger region to // support reading the "first slice" of a larger image // see bug 9212 // convert the IORegion to a ImageRegion (which is dimension templated) // if the ImageIO must read a higher dimension region, this will // truncate the last dimensions ImageIOAdaptor::Convert(m_ActualIORegion, streamableRegion, largestRegion.GetIndex()); // Check whether the imageRequestedRegion is fully contained inside the // streamable region. Since, ImageRegion::IsInside regards zero // sized regions, as not being inside any other region, we must // specially check this condition to enable zero sized regions to // pass the region propagation phase of the pipeline. if (!streamableRegion.IsInside(imageRequestedRegion) && imageRequestedRegion.GetNumberOfPixels() != 0) { // we must use a InvalidRequestedRegionError since // DataObject::PropagateRequestedRegion() has an exception // specification std::ostringstream message; message << "ImageIO returns IO region that does not fully contain the requested region" << "Requested region: " << imageRequestedRegion << "StreamableRegion region: " << streamableRegion; InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription(message.str().c_str()); throw e; } itkDebugMacro(<< "RequestedRegion is set to:" << streamableRegion << " while the m_ActualIORegion is: " << m_ActualIORegion); out->SetRequestedRegion(streamableRegion); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::GenerateData() { this->UpdateProgress(0.0f); typename TOutputImage::Pointer output = this->GetOutput(); itkDebugMacro(<< "ImageFileReader::GenerateData() \n" << "Allocating the buffer with the EnlargedRequestedRegion \n" << output->GetRequestedRegion() << "\n"); // allocated the output image to the size of the enlarge requested region this->AllocateOutputs(); // Test if the file exists and if it can be opened. // An exception will be thrown otherwise, since we can't // successfully read the file. We catch the exception because some // ImageIO's may not actually open a file. Still // reports file error if no ImageIO is loaded. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch (const itk::ExceptionObject & err) { m_ExceptionMessage = err.GetDescription(); } // Tell the ImageIO to read the file m_ImageIO->SetFileName(this->GetFileName().c_str()); itkDebugMacro(<< "Setting imageIO IORegion to: " << m_ActualIORegion); m_ImageIO->SetIORegion(m_ActualIORegion); // the size of the buffer is computed based on the actual number of // pixels to be read and the actual size of the pixels to be read // (as opposed to the sizes of the output) size_t sizeOfActualIORegion = m_ActualIORegion.GetNumberOfPixels() * (m_ImageIO->GetComponentSize() * m_ImageIO->GetNumberOfComponents()); IOComponentEnum ioType = ImageIOBase::MapPixelType<typename ConvertPixelTraits::ComponentType>::CType; if (m_ImageIO->GetComponentType() != ioType || (m_ImageIO->GetNumberOfComponents() != ConvertPixelTraits::GetNumberOfComponents())) { // the pixel types don't match so a type conversion needs to be // performed itkDebugMacro(<< "Buffer conversion required from: " << m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType()) << " to: " << m_ImageIO->GetComponentTypeAsString(ioType) << " ConvertPixelTraits::NumComponents " << ConvertPixelTraits::GetNumberOfComponents() << " m_ImageIO->NumComponents " << m_ImageIO->GetNumberOfComponents()); const std::unique_ptr<char[]> loadBuffer(new char[sizeOfActualIORegion]); m_ImageIO->Read(static_cast<void *>(loadBuffer.get())); // See note below as to why the buffered region is needed and // not actualIOregion this->DoConvertBuffer(static_cast<void *>(loadBuffer.get()), output->GetBufferedRegion().GetNumberOfPixels()); } else if (m_ActualIORegion.GetNumberOfPixels() != output->GetBufferedRegion().GetNumberOfPixels()) { // NOTE: // for the number of pixels read and the number of pixels // requested to not match, the dimensions of the two regions may // be different, therefore we buffer and copy the pixels itkDebugMacro(<< "Buffer required because file dimension is greater then image dimension"); OutputImagePixelType * outputBuffer = output->GetPixelContainer()->GetBufferPointer(); const std::unique_ptr<char[]> loadBuffer(new char[sizeOfActualIORegion]); m_ImageIO->Read(static_cast<void *>(loadBuffer.get())); // we use std::copy_n here as it should be optimized to memcpy for // plain old data, but still is oop std::copy_n(reinterpret_cast<const OutputImagePixelType *>(loadBuffer.get()), output->GetBufferedRegion().GetNumberOfPixels(), outputBuffer); } else { itkDebugMacro(<< "No buffer conversion required."); OutputImagePixelType * outputBuffer = output->GetPixelContainer()->GetBufferPointer(); m_ImageIO->Read(outputBuffer); } this->UpdateProgress(1.0f); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::DoConvertBuffer(void * inputData, size_t numberOfPixels) { // get the pointer to the destination buffer OutputImagePixelType * outputData = this->GetOutput()->GetPixelContainer()->GetBufferPointer(); bool isVectorImage(strcmp(this->GetOutput()->GetNameOfClass(), "VectorImage") == 0); // TODO: // Pass down the PixelType (RGB, VECTOR, etc.) so that any vector to // scalar conversion be type specific. i.e. RGB to scalar would use // a formula to convert to luminance, VECTOR to scalar would use // vector magnitude. // Create a macro as this code is a bit lengthy and repetitive // if the ImageIO pixel type is typeid(type) then use the ConvertPixelBuffer // class to convert the data block to TOutputImage's pixel type // see DefaultConvertPixelTraits and ConvertPixelBuffer // The first else if block applies only to images of type itk::VectorImage // VectorImage needs to copy out the buffer differently.. The buffer is of // type InternalPixelType, but each pixel is really 'k' consecutive pixels. #define ITK_CONVERT_BUFFER_IF_BLOCK(_CType, type) \ else if (m_ImageIO->GetComponentType() == _CType) \ { \ if (isVectorImage) \ { \ ConvertPixelBuffer<type, OutputImagePixelType, ConvertPixelTraits>::ConvertVectorImage( \ static_cast<type *>(inputData), m_ImageIO->GetNumberOfComponents(), outputData, numberOfPixels); \ } \ else \ { \ ConvertPixelBuffer<type, OutputImagePixelType, ConvertPixelTraits>::Convert( \ static_cast<type *>(inputData), m_ImageIO->GetNumberOfComponents(), outputData, numberOfPixels); \ } \ } if (false) { } ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::UCHAR, unsigned char) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::CHAR, char) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::USHORT, unsigned short) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::SHORT, short) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::UINT, unsigned int) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::INT, int) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::ULONG, unsigned long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::LONG, long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::ULONGLONG, unsigned long long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::LONGLONG, long long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::FLOAT, float) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::DOUBLE, double) else { #define TYPENAME(x) m_ImageIO->GetComponentTypeAsString(ImageIOBase::MapPixelType<x>::CType) ImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "Couldn't convert component type: " << std::endl << " " << m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType()) << std::endl << "to one of: " << std::endl << " " << TYPENAME(unsigned char) << std::endl << " " << TYPENAME(char) << std::endl << " " << TYPENAME(unsigned short) << std::endl << " " << TYPENAME(short) << std::endl << " " << TYPENAME(unsigned int) << std::endl << " " << TYPENAME(int) << std::endl << " " << TYPENAME(unsigned long) << std::endl << " " << TYPENAME(long) << std::endl << " " << TYPENAME(unsigned long long) << std::endl << " " << TYPENAME(long long) << std::endl << " " << TYPENAME(float) << std::endl << " " << TYPENAME(double) << std::endl; e.SetDescription(msg.str().c_str()); e.SetLocation(ITK_LOCATION); throw e; return; } #undef ITK_CONVERT_BUFFER_IF_BLOCK } } // namespace itk #endif
20,382
6,110
/** * Copyright 2004-present, Facebook, 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 "Logger.h" #include <algorithm> #include <chrono> #include <cstring> #include <stdexcept> #include <util/common.h> namespace facebook { namespace profilo { using namespace entries; Logger::EntryIDCounter& Logger::getGlobalEntryID() { static EntryIDCounter global_instance{kDefaultInitialID}; return global_instance; } Logger::Logger(logger::TraceBufferProvider provider, EntryIDCounter& counter) : entryID_(counter), logger_(provider) {} int32_t Logger::writeBytes( EntryType type, int32_t arg1, const uint8_t* arg2, size_t len) { if (len > kMaxVariableLengthEntry) { throw std::overflow_error("len is bigger than kMaxVariableLengthEntry"); } if (arg2 == nullptr) { throw std::invalid_argument("arg2 is null"); } return write(BytesEntry{ .id = 0, .type = type, .matchid = arg1, .bytes = { .values = const_cast<uint8_t*>(arg2), .size = static_cast<uint16_t>(len)}}); } } // namespace profilo } // namespace facebook
1,628
512
/* * Copyright (c) 2014 - 2015, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define __STDC_FORMAT_MACROS #include <ctype.h> #include <math.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <inttypes.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <linux/fb.h> #include <utils/constants.h> #include <utils/debug.h> #include "hw_device.h" #define __CLASS__ "HWDevice" namespace sdm { HWDevice::HWDevice(BufferSyncHandler *buffer_sync_handler) : fb_node_index_(-1), fb_path_("/sys/devices/virtual/graphics/fb"), hotplug_enabled_(false), buffer_sync_handler_(buffer_sync_handler), synchronous_commit_(false) { #ifndef SDM_VIRTUAL_DRIVER // Pointer to actual driver interfaces. ioctl_ = ::ioctl; open_ = ::open; close_ = ::close; poll_ = ::poll; pread_ = ::pread; pwrite_ = ::pwrite; fopen_ = ::fopen; fclose_ = ::fclose; getline_ = ::getline; #else // Point to virtual driver interfaces. extern int virtual_ioctl(int fd, int cmd, ...); extern int virtual_open(const char *file_name, int access, ...); extern int virtual_close(int fd); extern int virtual_poll(struct pollfd *fds, nfds_t num, int timeout); extern ssize_t virtual_pread(int fd, void *data, size_t count, off_t offset); extern ssize_t virtual_pwrite(int fd, const void *data, size_t count, off_t offset); extern FILE* virtual_fopen(const char *fname, const char *mode); extern int virtual_fclose(FILE* fileptr); extern ssize_t virtual_getline(char **lineptr, size_t *linelen, FILE *stream); ioctl_ = virtual_ioctl; open_ = virtual_open; close_ = virtual_close; poll_ = virtual_poll; pread_ = virtual_pread; pwrite_ = virtual_pwrite; fopen_ = virtual_fopen; fclose_ = virtual_fclose; getline_ = virtual_getline; #endif } DisplayError HWDevice::Init() { DisplayError error = kErrorNone; // Read the fb node index fb_node_index_ = GetFBNodeIndex(device_type_); if (fb_node_index_ == -1) { DLOGE("%s should be present", device_name_); return kErrorHardware; } // Populate Panel Info (Used for Partial Update) PopulateHWPanelInfo(); // Populate HW Capabilities hw_resource_ = HWResourceInfo(); hw_info_intf_->GetHWResourceInfo(&hw_resource_); return error; } DisplayError HWDevice::Open(HWEventHandler *eventhandler) { DisplayError error = kErrorNone; char device_name[64] = {0}; // Store EventHandlers for two Physical displays, i.e., Primary and HDMI // TODO(user): Need to revisit for HDMI as Primary usecase event_handler_ = eventhandler; snprintf(device_name, sizeof(device_name), "%s%d", "/dev/graphics/fb", fb_node_index_); device_fd_ = open_(device_name, O_RDWR); if (device_fd_ < 0) { DLOGE("open %s failed err = %d errstr = %s", device_name, errno, strerror(errno)); return kErrorResources; } return error; } DisplayError HWDevice::Close() { if (device_fd_ > 0) { close_(device_fd_); } return kErrorNone; } DisplayError HWDevice::GetNumDisplayAttributes(uint32_t *count) { *count = 1; return kErrorNone; } DisplayError HWDevice::GetDisplayAttributes(HWDisplayAttributes *display_attributes, uint32_t index) { return kErrorNone; } DisplayError HWDevice::GetHWPanelInfo(HWPanelInfo *panel_info) { *panel_info = hw_panel_info_; return kErrorNone; } DisplayError HWDevice::SetDisplayAttributes(uint32_t index) { return kErrorNone; } DisplayError HWDevice::GetConfigIndex(uint32_t mode, uint32_t *index) { return kErrorNone; } DisplayError HWDevice::PowerOn() { DTRACE_SCOPED(); if (ioctl_(device_fd_, FBIOBLANK, FB_BLANK_UNBLANK) < 0) { IOCTL_LOGE(FB_BLANK_UNBLANK, device_type_); return kErrorHardware; } // Need to turn on HPD if (!hotplug_enabled_) { hotplug_enabled_ = EnableHotPlugDetection(1); } return kErrorNone; } DisplayError HWDevice::PowerOff() { return kErrorNone; } DisplayError HWDevice::Doze() { return kErrorNone; } DisplayError HWDevice::DozeSuspend() { return kErrorNone; } DisplayError HWDevice::Standby() { return kErrorNone; } DisplayError HWDevice::Validate(HWLayers *hw_layers) { DTRACE_SCOPED(); DisplayError error = kErrorNone; HWLayersInfo &hw_layer_info = hw_layers->info; LayerStack *stack = hw_layer_info.stack; DLOGV_IF(kTagDriverConfig, "************************** %s Validate Input ***********************", device_name_); DLOGV_IF(kTagDriverConfig, "SDE layer count is %d", hw_layer_info.count); mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1; uint32_t &mdp_layer_count = mdp_commit.input_layer_cnt; DLOGI_IF(kTagDriverConfig, "left_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.left_roi.x, mdp_commit.left_roi.y, mdp_commit.left_roi.w, mdp_commit.left_roi.h); DLOGI_IF(kTagDriverConfig, "right_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.right_roi.x, mdp_commit.right_roi.y, mdp_commit.right_roi.w, mdp_commit.right_roi.h); for (uint32_t i = 0; i < hw_layer_info.count; i++) { uint32_t layer_index = hw_layer_info.index[i]; Layer &layer = stack->layers[layer_index]; LayerBuffer *input_buffer = layer.input_buffer; HWPipeInfo *left_pipe = &hw_layers->config[i].left_pipe; HWPipeInfo *right_pipe = &hw_layers->config[i].right_pipe; HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session; bool is_rotator_used = (hw_rotator_session->hw_block_count != 0); mdp_input_layer mdp_layer; for (uint32_t count = 0; count < 2; count++) { HWPipeInfo *pipe_info = (count == 0) ? left_pipe : right_pipe; HWRotateInfo *hw_rotate_info = &hw_rotator_session->hw_rotate_info[count]; if (hw_rotate_info->valid) { input_buffer = &hw_rotator_session->output_buffer; } if (pipe_info->valid) { mdp_input_layer &mdp_layer = mdp_in_layers_[mdp_layer_count]; mdp_layer_buffer &mdp_buffer = mdp_layer.buffer; mdp_buffer.width = input_buffer->width; mdp_buffer.height = input_buffer->height; mdp_buffer.comp_ratio.denom = 1000; mdp_buffer.comp_ratio.numer = UINT32(hw_layers->config[i].compression * 1000); error = SetFormat(input_buffer->format, &mdp_buffer.format); if (error != kErrorNone) { return error; } mdp_layer.alpha = layer.plane_alpha; mdp_layer.z_order = UINT16(pipe_info->z_order); mdp_layer.transp_mask = 0xffffffff; SetBlending(layer.blending, &mdp_layer.blend_op); mdp_layer.pipe_ndx = pipe_info->pipe_id; mdp_layer.horz_deci = pipe_info->horizontal_decimation; mdp_layer.vert_deci = pipe_info->vertical_decimation; SetRect(pipe_info->src_roi, &mdp_layer.src_rect); SetRect(pipe_info->dst_roi, &mdp_layer.dst_rect); SetMDPFlags(layer, is_rotator_used, &mdp_layer.flags); SetColorSpace(layer.color_space, &mdp_layer.color_space); if (pipe_info->scale_data.enable_pixel_ext) { if ((mdp_layer.flags & MDP_LAYER_DEINTERLACE) && (layer.transform.rotation == 90.0f)) { mdp_buffer.width = pipe_info->scale_data.src_width; } SetHWScaleData(pipe_info->scale_data, mdp_layer_count); } // Send scale data to MDP driver mdp_layer.scale = GetScaleDataRef(mdp_layer_count); mdp_layer_count++; DLOGV_IF(kTagDriverConfig, "******************* Layer[%d] %s pipe Input ******************", i, count ? "Right" : "Left"); DLOGV_IF(kTagDriverConfig, "in_w %d, in_h %d, in_f %d", mdp_buffer.width, mdp_buffer.height, mdp_buffer.format); DLOGV_IF(kTagDriverConfig, "plane_alpha %d, zorder %d, blending %d, horz_deci %d, " "vert_deci %d, pipe_id = 0x%x, mdp_flags 0x%x", mdp_layer.alpha, mdp_layer.z_order, mdp_layer.blend_op, mdp_layer.horz_deci, mdp_layer.vert_deci, mdp_layer.pipe_ndx, mdp_layer.flags); DLOGV_IF(kTagDriverConfig, "src_rect [%d, %d, %d, %d]", mdp_layer.src_rect.x, mdp_layer.src_rect.y, mdp_layer.src_rect.w, mdp_layer.src_rect.h); DLOGV_IF(kTagDriverConfig, "dst_rect [%d, %d, %d, %d]", mdp_layer.dst_rect.x, mdp_layer.dst_rect.y, mdp_layer.dst_rect.w, mdp_layer.dst_rect.h); for (int j = 0; j < 4; j++) { DLOGV_IF(kTagDriverConfig, "Scale Data[%d]: Phase=[%x %x %x %x] Pixel_Ext=[%d %d %d %d]", j, mdp_layer.scale->init_phase_x[j], mdp_layer.scale->phase_step_x[j], mdp_layer.scale->init_phase_y[j], mdp_layer.scale->phase_step_y[j], mdp_layer.scale->num_ext_pxls_left[j], mdp_layer.scale->num_ext_pxls_top[j], mdp_layer.scale->num_ext_pxls_right[j], mdp_layer.scale->num_ext_pxls_btm[j]); DLOGV_IF(kTagDriverConfig, "Fetch=[%d %d %d %d] Repeat=[%d %d %d %d] roi_width = %d", mdp_layer.scale->left_ftch[j], mdp_layer.scale->top_ftch[j], mdp_layer.scale->right_ftch[j], mdp_layer.scale->btm_ftch[j], mdp_layer.scale->left_rpt[j], mdp_layer.scale->top_rpt[j], mdp_layer.scale->right_rpt[j], mdp_layer.scale->btm_rpt[j], mdp_layer.scale->roi_w[j]); } DLOGV_IF(kTagDriverConfig, "*************************************************************"); } } } if (device_type_ == kDeviceVirtual) { LayerBuffer *output_buffer = hw_layers->info.stack->output_buffer; // TODO(user): Need to assign the writeback id from the resource manager, since the support // has not been added hard coding it to 2 for now. mdp_out_layer_.writeback_ndx = 2; mdp_out_layer_.buffer.width = output_buffer->width; mdp_out_layer_.buffer.height = output_buffer->height; mdp_out_layer_.buffer.comp_ratio.denom = 1000; mdp_out_layer_.buffer.comp_ratio.numer = UINT32(hw_layers->output_compression * 1000); SetFormat(output_buffer->format, &mdp_out_layer_.buffer.format); DLOGI_IF(kTagDriverConfig, "********************* Output buffer Info ************************"); DLOGI_IF(kTagDriverConfig, "out_w %d, out_h %d, out_f %d, wb_id %d", mdp_out_layer_.buffer.width, mdp_out_layer_.buffer.height, mdp_out_layer_.buffer.format, mdp_out_layer_.writeback_ndx); DLOGI_IF(kTagDriverConfig, "*****************************************************************"); } mdp_commit.flags |= MDP_VALIDATE_LAYER; if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) { IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_); DumpLayerCommit(mdp_disp_commit_); return kErrorHardware; } return kErrorNone; } void HWDevice::DumpLayerCommit(const mdp_layer_commit &layer_commit) { const mdp_layer_commit_v1 &mdp_commit = layer_commit.commit_v1; const mdp_input_layer *mdp_layers = mdp_commit.input_layers; DLOGE("mdp_commit: flags = %x, release fence = %x", mdp_commit.flags, mdp_commit.release_fence); DLOGE("left_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.left_roi.x, mdp_commit.left_roi.y, mdp_commit.left_roi.w, mdp_commit.left_roi.h); DLOGE("right_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.right_roi.x, mdp_commit.right_roi.y, mdp_commit.right_roi.w, mdp_commit.right_roi.h); for (uint32_t i = 0; i < mdp_commit.input_layer_cnt; i++) { DLOGE("mdp_commit: layer_cnt = %d, pipe_ndx = %x, zorder = %d, flags = %x", i, mdp_layers[i].pipe_ndx, mdp_layers[i].z_order, mdp_layers[i].flags); const mdp_rect &src_rect = mdp_layers[i].src_rect; DLOGE("src rect: x = %d, y = %d, w = %d, h = %d", src_rect.x, src_rect.y, src_rect.w, src_rect.h); const mdp_rect &dst_rect = mdp_layers[i].dst_rect; DLOGE("dst rect: x = %d, y = %d, w = %d, h = %d", dst_rect.x, dst_rect.y, dst_rect.w, dst_rect.h); } } DisplayError HWDevice::Commit(HWLayers *hw_layers) { DTRACE_SCOPED(); HWLayersInfo &hw_layer_info = hw_layers->info; LayerStack *stack = hw_layer_info.stack; DLOGV_IF(kTagDriverConfig, "*************************** %s Commit Input ************************", device_name_); DLOGV_IF(kTagDriverConfig, "SDE layer count is %d", hw_layer_info.count); mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1; uint32_t mdp_layer_index = 0; for (uint32_t i = 0; i < hw_layer_info.count; i++) { uint32_t layer_index = hw_layer_info.index[i]; LayerBuffer *input_buffer = stack->layers[layer_index].input_buffer; HWPipeInfo *left_pipe = &hw_layers->config[i].left_pipe; HWPipeInfo *right_pipe = &hw_layers->config[i].right_pipe; HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session; for (uint32_t count = 0; count < 2; count++) { HWPipeInfo *pipe_info = (count == 0) ? left_pipe : right_pipe; HWRotateInfo *hw_rotate_info = &hw_rotator_session->hw_rotate_info[count]; if (hw_rotate_info->valid) { input_buffer = &hw_rotator_session->output_buffer; } if (pipe_info->valid) { mdp_layer_buffer &mdp_buffer = mdp_in_layers_[mdp_layer_index].buffer; mdp_input_layer &mdp_layer = mdp_in_layers_[mdp_layer_index]; if (input_buffer->planes[0].fd >= 0) { mdp_buffer.plane_count = 1; mdp_buffer.planes[0].fd = input_buffer->planes[0].fd; mdp_buffer.planes[0].offset = input_buffer->planes[0].offset; SetStride(device_type_, input_buffer->format, input_buffer->planes[0].stride, &mdp_buffer.planes[0].stride); } else { DLOGW("Invalid buffer fd, setting plane count to 0"); mdp_buffer.plane_count = 0; } mdp_buffer.fence = input_buffer->acquire_fence_fd; mdp_layer_index++; DLOGV_IF(kTagDriverConfig, "****************** Layer[%d] %s pipe Input *******************", i, count ? "Right" : "Left"); DLOGI_IF(kTagDriverConfig, "in_w %d, in_h %d, in_f %d, horz_deci %d, vert_deci %d", mdp_buffer.width, mdp_buffer.height, mdp_buffer.format, mdp_layer.horz_deci, mdp_layer.vert_deci); DLOGI_IF(kTagDriverConfig, "in_buf_fd %d, in_buf_offset %d, in_buf_stride %d, " \ "in_plane_count %d, in_fence %d, layer count %d", mdp_buffer.planes[0].fd, mdp_buffer.planes[0].offset, mdp_buffer.planes[0].stride, mdp_buffer.plane_count, mdp_buffer.fence, mdp_commit.input_layer_cnt); DLOGV_IF(kTagDriverConfig, "*************************************************************"); } } } if (device_type_ == kDeviceVirtual) { LayerBuffer *output_buffer = hw_layers->info.stack->output_buffer; if (output_buffer->planes[0].fd >= 0) { mdp_out_layer_.buffer.planes[0].fd = output_buffer->planes[0].fd; mdp_out_layer_.buffer.planes[0].offset = output_buffer->planes[0].offset; SetStride(device_type_, output_buffer->format, output_buffer->planes[0].stride, &mdp_out_layer_.buffer.planes[0].stride); mdp_out_layer_.buffer.plane_count = 1; } else { DLOGW("Invalid output buffer fd, setting plane count to 0"); mdp_out_layer_.buffer.plane_count = 0; } mdp_out_layer_.buffer.fence = output_buffer->acquire_fence_fd; DLOGI_IF(kTagDriverConfig, "********************** Output buffer Info ***********************"); DLOGI_IF(kTagDriverConfig, "out_fd %d, out_offset %d, out_stride %d, acquire_fence %d", mdp_out_layer_.buffer.planes[0].fd, mdp_out_layer_.buffer.planes[0].offset, mdp_out_layer_.buffer.planes[0].stride, mdp_out_layer_.buffer.fence); DLOGI_IF(kTagDriverConfig, "*****************************************************************"); } mdp_commit.release_fence = -1; mdp_commit.flags &= ~MDP_VALIDATE_LAYER; if (synchronous_commit_) { mdp_commit.flags |= MDP_COMMIT_WAIT_FOR_FINISH; } if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) { IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_); DumpLayerCommit(mdp_disp_commit_); synchronous_commit_ = false; return kErrorHardware; } stack->retire_fence_fd = mdp_commit.retire_fence; // MDP returns only one release fence for the entire layer stack. Duplicate this fence into all // layers being composed by MDP. for (uint32_t i = 0; i < hw_layer_info.count; i++) { uint32_t layer_index = hw_layer_info.index[i]; LayerBuffer *input_buffer = stack->layers[layer_index].input_buffer; HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session; if (hw_rotator_session->hw_block_count) { input_buffer = &hw_rotator_session->output_buffer; } input_buffer->release_fence_fd = dup(mdp_commit.release_fence); } DLOGI_IF(kTagDriverConfig, "*************************** %s Commit Input ************************", device_name_); DLOGI_IF(kTagDriverConfig, "retire_fence_fd %d", stack->retire_fence_fd); DLOGI_IF(kTagDriverConfig, "*******************************************************************"); close_(mdp_commit.release_fence); if (synchronous_commit_) { // A synchronous commit can be requested when changing the display mode so we need to update // panel info. PopulateHWPanelInfo(); synchronous_commit_ = false; } return kErrorNone; } DisplayError HWDevice::Flush() { ResetDisplayParams(); mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1; mdp_commit.input_layer_cnt = 0; mdp_commit.output_layer = NULL; mdp_commit.flags &= ~MDP_VALIDATE_LAYER; if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) { IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_); DumpLayerCommit(mdp_disp_commit_); return kErrorHardware; } return kErrorNone; } DisplayError HWDevice::SetFormat(const LayerBufferFormat &source, uint32_t *target) { switch (source) { case kFormatARGB8888: *target = MDP_ARGB_8888; break; case kFormatRGBA8888: *target = MDP_RGBA_8888; break; case kFormatBGRA8888: *target = MDP_BGRA_8888; break; case kFormatRGBX8888: *target = MDP_RGBX_8888; break; case kFormatBGRX8888: *target = MDP_BGRX_8888; break; case kFormatRGBA5551: *target = MDP_RGBA_5551; break; case kFormatRGBA4444: *target = MDP_RGBA_4444; break; case kFormatRGB888: *target = MDP_RGB_888; break; case kFormatBGR888: *target = MDP_BGR_888; break; case kFormatRGB565: *target = MDP_RGB_565; break; case kFormatYCbCr420Planar: *target = MDP_Y_CB_CR_H2V2; break; case kFormatYCrCb420Planar: *target = MDP_Y_CR_CB_H2V2; break; case kFormatYCbCr420SemiPlanar: *target = MDP_Y_CBCR_H2V2; break; case kFormatYCrCb420SemiPlanar: *target = MDP_Y_CRCB_H2V2; break; case kFormatYCbCr422H1V2SemiPlanar: *target = MDP_Y_CBCR_H1V2; break; case kFormatYCrCb422H1V2SemiPlanar: *target = MDP_Y_CRCB_H1V2; break; case kFormatYCbCr422H2V1SemiPlanar: *target = MDP_Y_CBCR_H2V1; break; case kFormatYCrCb422H2V1SemiPlanar: *target = MDP_Y_CRCB_H2V1; break; case kFormatYCbCr422H2V1Packed: *target = MDP_YCBYCR_H2V1; break; case kFormatYCbCr420SemiPlanarVenus: *target = MDP_Y_CBCR_H2V2_VENUS; break; case kFormatRGBA8888Ubwc: *target = MDP_RGBA_8888_UBWC; break; case kFormatRGBX8888Ubwc: *target = MDP_RGBX_8888_UBWC; break; case kFormatRGB565Ubwc: *target = MDP_RGB_565_UBWC; break; case kFormatYCbCr420SPVenusUbwc: *target = MDP_Y_CBCR_H2V2_UBWC; break; default: DLOGE("Unsupported format type %d", source); return kErrorParameters; } return kErrorNone; } DisplayError HWDevice::SetStride(HWDeviceType device_type, LayerBufferFormat format, uint32_t width, uint32_t *target) { // TODO(user): This SetStride function is a workaround to satisfy the driver expectation for // rotator and virtual devices. Eventually this will be taken care in the driver. if (device_type != kDeviceRotator && device_type != kDeviceVirtual) { *target = width; return kErrorNone; } switch (format) { case kFormatARGB8888: case kFormatRGBA8888: case kFormatBGRA8888: case kFormatRGBX8888: case kFormatBGRX8888: case kFormatRGBA8888Ubwc: case kFormatRGBX8888Ubwc: *target = width * 4; break; case kFormatRGB888: case kFormatBGR888: *target = width * 3; break; case kFormatRGB565: case kFormatRGB565Ubwc: *target = width * 2; break; case kFormatYCbCr420SemiPlanarVenus: case kFormatYCbCr420SPVenusUbwc: case kFormatYCbCr420Planar: case kFormatYCrCb420Planar: case kFormatYCbCr420SemiPlanar: case kFormatYCrCb420SemiPlanar: *target = width; break; case kFormatYCbCr422H2V1Packed: case kFormatYCrCb422H2V1SemiPlanar: case kFormatYCrCb422H1V2SemiPlanar: case kFormatYCbCr422H2V1SemiPlanar: case kFormatYCbCr422H1V2SemiPlanar: case kFormatRGBA5551: case kFormatRGBA4444: *target = width * 2; break; default: DLOGE("Unsupported format type %d", format); return kErrorParameters; } return kErrorNone; } void HWDevice::SetBlending(const LayerBlending &source, mdss_mdp_blend_op *target) { switch (source) { case kBlendingPremultiplied: *target = BLEND_OP_PREMULTIPLIED; break; case kBlendingCoverage: *target = BLEND_OP_COVERAGE; break; default: *target = BLEND_OP_NOT_DEFINED; break; } } void HWDevice::SetRect(const LayerRect &source, mdp_rect *target) { target->x = UINT32(source.left); target->y = UINT32(source.top); target->w = UINT32(source.right) - target->x; target->h = UINT32(source.bottom) - target->y; } void HWDevice::SetMDPFlags(const Layer &layer, const bool &is_rotator_used, uint32_t *mdp_flags) { LayerBuffer *input_buffer = layer.input_buffer; // Flips will be taken care by rotator, if layer uses rotator for downscale/rotation. So ignore // flip flags for MDP. if (!is_rotator_used) { if (layer.transform.flip_vertical) { *mdp_flags |= MDP_LAYER_FLIP_UD; } if (layer.transform.flip_horizontal) { *mdp_flags |= MDP_LAYER_FLIP_LR; } } if (input_buffer->flags.interlace) { *mdp_flags |= MDP_LAYER_DEINTERLACE; } if (input_buffer->flags.secure) { *mdp_flags |= MDP_LAYER_SECURE_SESSION; } if (input_buffer->flags.secure_display) { *mdp_flags |= MDP_SECURE_DISPLAY_OVERLAY_SESSION; } } void HWDevice::SyncMerge(const int &fd1, const int &fd2, int *target) { if (fd1 >= 0 && fd2 >= 0) { buffer_sync_handler_->SyncMerge(fd1, fd2, target); } else if (fd1 >= 0) { *target = fd1; } else if (fd2 >= 0) { *target = fd2; } } int HWDevice::GetFBNodeIndex(HWDeviceType device_type) { int fb_node_index = -1; for (int i = 0; i <= kDeviceVirtual; i++) { HWPanelInfo *panel_info = new HWPanelInfo(); GetHWPanelInfoByNode(i, panel_info); switch (device_type) { case kDevicePrimary: if (panel_info->is_primary_panel) { fb_node_index = i; } break; case kDeviceHDMI: if (panel_info->port == kPortDTv) { fb_node_index = i; } break; case kDeviceVirtual: if (panel_info->port == kPortWriteBack) { fb_node_index = i; } break; default: break; } } return fb_node_index; } void HWDevice::PopulateHWPanelInfo() { hw_panel_info_ = HWPanelInfo(); GetHWPanelInfoByNode(fb_node_index_, &hw_panel_info_); DLOGI("Device type = %d, Display Port = %d, Display Mode = %d, Device Node = %d, Is Primary = %d", device_type_, hw_panel_info_.port, hw_panel_info_.mode, fb_node_index_, hw_panel_info_.is_primary_panel); DLOGI("Partial Update = %d, Dynamic FPS = %d", hw_panel_info_.partial_update, hw_panel_info_.dynamic_fps); DLOGI("Align: left = %d, width = %d, top = %d, height = %d", hw_panel_info_.left_align, hw_panel_info_.width_align, hw_panel_info_.top_align, hw_panel_info_.height_align); DLOGI("ROI: min_width = %d, min_height = %d, need_merge = %d", hw_panel_info_.min_roi_width, hw_panel_info_.min_roi_height, hw_panel_info_.needs_roi_merge); DLOGI("FPS: min = %d, max =%d", hw_panel_info_.min_fps, hw_panel_info_.max_fps); DLOGI("Left Split = %d, Right Split = %d", hw_panel_info_.split_info.left_split, hw_panel_info_.split_info.right_split); DLOGI("Source Split Always = %d", hw_panel_info_.split_info.always_src_split); } void HWDevice::GetHWPanelInfoByNode(int device_node, HWPanelInfo *panel_info) { if (!panel_info) { DLOGE("PanelInfo pointer in invalid."); return; } char stringbuffer[kMaxStringLength]; FILE *fileptr = NULL; snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_panel_info", fb_path_, device_node); fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("Failed to open msm_fb_panel_info node device node %d", device_node); return; } size_t len = kMaxStringLength; ssize_t read; char *line = NULL; while ((read = getline(&line, &len, fileptr)) != -1) { uint32_t token_count = 0; const uint32_t max_count = 10; char *tokens[max_count] = { NULL }; if (!ParseLine(line, tokens, max_count, &token_count)) { if (!strncmp(tokens[0], "pu_en", strlen("pu_en"))) { panel_info->partial_update = atoi(tokens[1]); } else if (!strncmp(tokens[0], "xstart", strlen("xstart"))) { panel_info->left_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "walign", strlen("walign"))) { panel_info->width_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "ystart", strlen("ystart"))) { panel_info->top_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "halign", strlen("halign"))) { panel_info->height_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "min_w", strlen("min_w"))) { panel_info->min_roi_width = atoi(tokens[1]); } else if (!strncmp(tokens[0], "min_h", strlen("min_h"))) { panel_info->min_roi_height = atoi(tokens[1]); } else if (!strncmp(tokens[0], "roi_merge", strlen("roi_merge"))) { panel_info->needs_roi_merge = atoi(tokens[1]); } else if (!strncmp(tokens[0], "dyn_fps_en", strlen("dyn_fps_en"))) { panel_info->dynamic_fps = atoi(tokens[1]); } else if (!strncmp(tokens[0], "min_fps", strlen("min_fps"))) { panel_info->min_fps = atoi(tokens[1]); } else if (!strncmp(tokens[0], "max_fps", strlen("max_fps"))) { panel_info->max_fps = atoi(tokens[1]); } else if (!strncmp(tokens[0], "primary_panel", strlen("primary_panel"))) { panel_info->is_primary_panel = atoi(tokens[1]); } } } fclose(fileptr); free(line); panel_info->port = GetHWDisplayPort(device_node); panel_info->mode = GetHWDisplayMode(device_node); GetSplitInfo(device_node, panel_info); } HWDisplayPort HWDevice::GetHWDisplayPort(int device_node) { char stringbuffer[kMaxStringLength]; DisplayError error = kErrorNone; char *line = NULL; size_t len = kMaxStringLength; ssize_t read; HWDisplayPort port = kPortDefault; snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_type", fb_path_, device_node); FILE *fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return port; } read = getline(&line, &len, fileptr); if (read == -1) { fclose(fileptr); return port; } if ((strncmp(line, "mipi dsi cmd panel", strlen("mipi dsi cmd panel")) == 0)) { port = kPortDSI; } else if ((strncmp(line, "mipi dsi video panel", strlen("mipi dsi video panel")) == 0)) { port = kPortDSI; } else if ((strncmp(line, "lvds panel", strlen("lvds panel")) == 0)) { port = kPortLVDS; } else if ((strncmp(line, "edp panel", strlen("edp panel")) == 0)) { port = kPortEDP; } else if ((strncmp(line, "dtv panel", strlen("dtv panel")) == 0)) { port = kPortDTv; } else if ((strncmp(line, "writeback panel", strlen("writeback panel")) == 0)) { port = kPortWriteBack; } else { port = kPortDefault; } fclose(fileptr); free(line); return port; } HWDisplayMode HWDevice::GetHWDisplayMode(int device_node) { char stringbuffer[kMaxStringLength]; DisplayError error = kErrorNone; char *line = NULL; size_t len = kMaxStringLength; ssize_t read; HWDisplayMode mode = kModeDefault; snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_type", fb_path_, device_node); FILE *fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return mode; } read = getline(&line, &len, fileptr); if (read == -1) { fclose(fileptr); return mode; } if ((strncmp(line, "mipi dsi cmd panel", strlen("mipi dsi cmd panel")) == 0)) { mode = kModeCommand; } else if ((strncmp(line, "mipi dsi video panel", strlen("mipi dsi video panel")) == 0)) { mode = kModeVideo; } else { mode = kModeDefault; } fclose(fileptr); free(line); return mode; } void HWDevice::GetSplitInfo(int device_node, HWPanelInfo *panel_info) { char stringbuffer[kMaxStringLength]; FILE *fileptr = NULL; size_t len = kMaxStringLength; ssize_t read; char *line = NULL; uint32_t token_count = 0; const uint32_t max_count = 10; char *tokens[max_count] = { NULL }; // Split info - for MDSS Version 5 - No need to check version here snprintf(stringbuffer , sizeof(stringbuffer), "%s%d/msm_fb_split", fb_path_, device_node); fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return; } // Format "left right" space as delimiter read = getline(&line, &len, fileptr); if (read != -1) { if (!ParseLine(line, tokens, max_count, &token_count)) { panel_info->split_info.left_split = atoi(tokens[0]); panel_info->split_info.right_split = atoi(tokens[1]); } } fclose(fileptr); // SourceSplit enabled - Get More information snprintf(stringbuffer , sizeof(stringbuffer), "%s%d/msm_fb_src_split_info", fb_path_, device_node); fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return; } read = getline(&line, &len, fileptr); if (read != -1) { if (!strncmp(line, "src_split_always", strlen("src_split_always"))) { panel_info->split_info.always_src_split = true; } } fclose(fileptr); free(line); } int HWDevice::ParseLine(char *input, char *tokens[], const uint32_t max_token, uint32_t *count) { char *tmp_token = NULL; char *temp_ptr; uint32_t index = 0; const char *delim = ", =\n"; if (!input) { return -1; } tmp_token = strtok_r(input, delim, &temp_ptr); while (tmp_token && index < max_token) { tokens[index++] = tmp_token; tmp_token = strtok_r(NULL, delim, &temp_ptr); } *count = index; return 0; } bool HWDevice::EnableHotPlugDetection(int enable) { bool ret_value = true; char hpdpath[kMaxStringLength]; int hdmi_node_index = GetFBNodeIndex(kDeviceHDMI); snprintf(hpdpath , sizeof(hpdpath), "%s%d/hpd", fb_path_, hdmi_node_index); int hpdfd = open_(hpdpath, O_RDWR, 0); if (hpdfd < 0) { DLOGE("Open failed = %s", hpdpath); return kErrorHardware; } char value = enable ? '1' : '0'; ssize_t length = pwrite_(hpdfd, &value, 1, 0); if (length <= 0) { DLOGE("Write failed 'hpd' = %d", enable); ret_value = false; } close_(hpdfd); return ret_value; } void HWDevice::ResetDisplayParams() { memset(&mdp_disp_commit_, 0, sizeof(mdp_disp_commit_)); memset(&mdp_in_layers_, 0, sizeof(mdp_in_layers_)); memset(&mdp_out_layer_, 0, sizeof(mdp_out_layer_)); memset(&scale_data_, 0, sizeof(scale_data_)); for (uint32_t i = 0; i < kMaxSDELayers * 2; i++) { mdp_in_layers_[i].buffer.fence = -1; } mdp_disp_commit_.version = MDP_COMMIT_VERSION_1_0; mdp_disp_commit_.commit_v1.input_layers = mdp_in_layers_; mdp_disp_commit_.commit_v1.output_layer = &mdp_out_layer_; mdp_disp_commit_.commit_v1.release_fence = -1; mdp_disp_commit_.commit_v1.retire_fence = -1; } void HWDevice::SetHWScaleData(const ScaleData &scale, uint32_t index) { mdp_scale_data *mdp_scale = GetScaleDataRef(index); mdp_scale->enable_pxl_ext = scale.enable_pixel_ext; for (int i = 0; i < 4; i++) { const HWPlane &plane = scale.plane[i]; mdp_scale->init_phase_x[i] = plane.init_phase_x; mdp_scale->phase_step_x[i] = plane.phase_step_x; mdp_scale->init_phase_y[i] = plane.init_phase_y; mdp_scale->phase_step_y[i] = plane.phase_step_y; mdp_scale->num_ext_pxls_left[i] = plane.left.extension; mdp_scale->left_ftch[i] = plane.left.overfetch; mdp_scale->left_rpt[i] = plane.left.repeat; mdp_scale->num_ext_pxls_top[i] = plane.top.extension; mdp_scale->top_ftch[i] = plane.top.overfetch; mdp_scale->top_rpt[i] = plane.top.repeat; mdp_scale->num_ext_pxls_right[i] = plane.right.extension; mdp_scale->right_ftch[i] = plane.right.overfetch; mdp_scale->right_rpt[i] = plane.right.repeat; mdp_scale->num_ext_pxls_btm[i] = plane.bottom.extension; mdp_scale->btm_ftch[i] = plane.bottom.overfetch; mdp_scale->btm_rpt[i] = plane.bottom.repeat; mdp_scale->roi_w[i] = plane.roi_width; } } void HWDevice::SetColorSpace(LayerColorSpace source, mdp_color_space *color_space) { switch (source) { case kLimitedRange601: *color_space = MDP_CSC_ITU_R_601; break; case kFullRange601: *color_space = MDP_CSC_ITU_R_601_FR; break; case kLimitedRange709: *color_space = MDP_CSC_ITU_R_709; break; } } } // namespace sdm
35,578
13,990
// // IndexBox.h // InternetMap // // Created by Alexander on 11.12.12. // Copyright (c) 2012 Peer1. All rights reserved. // #ifndef InternetMap_IndexBox_hpp #define InternetMap_IndexBox_hpp #include "Types.hpp" #include <set> static const float IndexBoxMinX = -8; static const float IndexBoxMaxX = 8; static const float IndexBoxMinY = -2.1; static const float IndexBoxMaxY = 2.1; static const float IndexBoxMinZ = -2.1; static const float IndexBoxMaxZ = 2.1; static const float lengthX = -IndexBoxMinX + IndexBoxMaxX; static const float lengthY = -IndexBoxMinY + IndexBoxMaxY; static const float lengthZ = -IndexBoxMinZ + IndexBoxMaxZ; static const int numberOfCellsX = 32; static const int numberOfCellsY = 4; static const int numberOfCellsZ = 4; static const float boxSizeXWithoutOverlap = lengthX/numberOfCellsX; static const float boxSizeYWithoutOverlap = lengthY/numberOfCellsY; static const float boxSizeZWithoutOverlap = lengthZ/numberOfCellsZ; class IndexBox { Point3 _parameters[2]; Point3 _center; Point3 _minCorner; Point3 _maxCorner; public: std::set<int> indices; bool isPointInside(const Point3& point); bool doesLineIntersectOptimized(const Vector3& origin, const Vector3& invertedDirection, int* sign); Point3 minCorner(); Point3 maxCorner(); Point3 center(); void setMinCorner(const Point3& minCorner); void setMaxCorner(const Point3& maxCorner); void setCenter(const Point3& center); }; typedef shared_ptr<IndexBox> IndexBoxPointer; #endif
1,538
520
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016, Intel Corporation // 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. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@intel.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "vaCameraControllers.h" #include "vaCameraBase.h" #include "Core/vaInput.h" #include "IntegratedExternals/vaImguiIntegration.h" using namespace VertexAsylum; void vaCameraControllerBase::CameraAttached( const shared_ptr<vaCameraBase> & camera ) { if( camera == nullptr ) { assert( !m_attachedCamera.expired() ); m_attachedCamera.reset(); } else { assert( m_attachedCamera.expired() ); m_attachedCamera = camera; } } vaCameraControllerFreeFlight::vaCameraControllerFreeFlight( ) // orient the camera so that X is forward, Z is up, Y is right : m_baseOrientation( vaMatrix4x4::RotationZ( VA_PIf * 0.5f ) * vaMatrix4x4::RotationY( VA_PIf * 0.5f ) ) { // m_hasFocus = true; // temporary m_accumMouseDeltaX = 0.0f; m_accumMouseDeltaY = 0.0f; m_accumMove = vaVector3( 0.0f, 0.0f, 0.0f ); m_rotationSpeed = 0.5f; m_movementSpeed = 20.0f; m_inputSmoothingLerpK = 200.0f; m_yaw = 0.0f; m_pitch = 0.0f; // look towards x m_roll = 0.0f; // y is right m_movementSpeedAccelerationModifier = 0.0f; m_moveWhileNotCaptured = true; } vaCameraControllerFreeFlight::~vaCameraControllerFreeFlight( ) { } void vaCameraControllerFreeFlight::CameraAttached( const shared_ptr<vaCameraBase> & camera ) { vaCameraControllerBase::CameraAttached( camera ); if( camera != nullptr ) { // extract yaw/pitch from attached camera vaMatrix4x4 debasedOrientation = m_baseOrientation.Inverse() * vaMatrix4x4::FromQuaternion( camera->GetOrientation() ); debasedOrientation.DecomposeRotationYawPitchRoll( m_yaw, m_pitch, m_roll ); m_roll = 0; } } void vaCameraControllerFreeFlight::CameraTick( float deltaTime, vaCameraBase & camera, bool hasFocus ) { if( ( vaInputMouseBase::GetCurrent( ) == NULL ) || ( vaInputKeyboardBase::GetCurrent( ) == NULL ) ) return; vaVector3 objectPos = camera.GetPosition(); vaQuaternion objectOri = camera.GetOrientation(); vaInputMouseBase & mouse = *vaInputMouseBase::GetCurrent(); vaInputKeyboardBase & keyboard = *vaInputKeyboardBase::GetCurrent( ); { float smoothingLerpK = vaMath::TimeIndependentLerpF( deltaTime, m_inputSmoothingLerpK ); float speedBoost = 1.0f; if( hasFocus ) { speedBoost *= (keyboard.IsKeyDown( KK_SHIFT ))?(12.0f):(1.0f); speedBoost *= keyboard.IsKeyDown( KK_CONTROL )?(0.08f):(1.0f); if( keyboard.IsKeyDown( KK_SHIFT ) && keyboard.IsKeyDown( KK_MENU ) ) speedBoost *= 10.0f; } // /////////////////////////////////////////////////////////////////////////// // Update camera range/speed changes if( hasFocus ) { if( keyboard.IsKeyDown( KK_SUBTRACT ) ) m_movementSpeed *= 0.95f; if( keyboard.IsKeyDown( KK_ADD ) ) m_movementSpeed *= 1.05f; m_movementSpeed = vaMath::Clamp( m_movementSpeed, 1.0f, 5000.0f ); //if( vaIsKeyClicked( kcViewRangeDown ) ) m_viewRange *= 0.99f; //if( vaIsKeyClicked( kcViewRangeUp ) ) m_viewRange *= 1.01f; //m_viewRange = vaMath::Clamp( m_viewRange, 1000.0f, 1000000.0f ); // } /////////////////////////////////////////////////////////////////////////// // Update camera rotation vaVector2 cdelta = vaVector2( 0.0f, 0.0f ); if( hasFocus ) cdelta = (vaVector2)mouse.GetCursorDelta( ) * m_rotationSpeed; // // smoothing { m_accumMouseDeltaX += cdelta.x; m_accumMouseDeltaY += cdelta.y; cdelta.x = smoothingLerpK * m_accumMouseDeltaX; cdelta.y = smoothingLerpK * m_accumMouseDeltaY; m_accumMouseDeltaX = (1 - smoothingLerpK) * m_accumMouseDeltaX; m_accumMouseDeltaY = (1 - smoothingLerpK) * m_accumMouseDeltaY; } // // Rotate if( mouse.IsCaptured( ) ) { if( mouse.IsKeyDown( MK_Middle ) ) m_roll -= cdelta.x * 0.005f; else m_yaw += cdelta.x * 0.005f; m_pitch += cdelta.y * 0.003f; m_yaw = vaMath::AngleWrap( m_yaw ); m_pitch = vaMath::Clamp( m_pitch, -(float)VA_PIf/2 + 1e-1f, +(float)VA_PIf/2 - 1e-1f ); m_roll = vaMath::AngleWrap( m_roll ); } #if 1 { // round yaw/pitch/roll slightly to avoid precision errors causing non-determinism when saving/loading cameras; 5 is precise enough for 10x zoom sniping (fov/10) but stepping could potential be seen with 100x int precisionTrimDecimals = 5; float k = vaMath::Pow( 10, (float)precisionTrimDecimals ); m_yaw = vaMath::Round(m_yaw * k)/k; m_pitch = vaMath::Round(m_pitch * k)/k; m_roll = vaMath::Round(m_roll * k)/k; } #endif // vaMatrix4x4 cameraWorld = vaMatrix4x4::FromYawPitchRoll( m_yaw, m_pitch, m_roll ); // // Move if( mouse.IsCaptured() || m_moveWhileNotCaptured ) { /////////////////////////////////////////////////////////////////////////// // Update camera movement bool hasInput = false; if( hasFocus ) { hasInput = keyboard.IsKeyDown( (vaKeyboardKeys)'W' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'S' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'A' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'D' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'Q' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'E' ); } m_movementSpeedAccelerationModifier = (hasInput)?(vaMath::Min(m_movementSpeedAccelerationModifier + deltaTime * 0.5f, 1.0f)):(0.0f); float moveSpeed = m_movementSpeed * deltaTime * ( 0.3f + 0.7f * m_movementSpeedAccelerationModifier ) * speedBoost; vaVector3 forward( cameraWorld.GetAxisX() ); vaVector3 right( cameraWorld.GetAxisY() ); vaVector3 up( cameraWorld.GetAxisZ() ); vaVector3 accumMove = m_accumMove; if( hasFocus ) { if( keyboard.IsKeyDown( (vaKeyboardKeys)'W' ) || keyboard.IsKeyDown( KK_UP ) ) accumMove += forward * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'S' ) || keyboard.IsKeyDown( KK_DOWN ) ) accumMove -= forward * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'D' ) || keyboard.IsKeyDown( KK_RIGHT ) ) accumMove += right * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'A' ) || keyboard.IsKeyDown( KK_LEFT ) ) accumMove -= right * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'Q' ) ) accumMove -= up * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'E' ) ) accumMove += up * moveSpeed; } objectPos += accumMove * smoothingLerpK; m_accumMove = accumMove * (1-smoothingLerpK); } objectOri = vaQuaternion::FromRotationMatrix( m_baseOrientation * cameraWorld ); } camera.SetPosition( objectPos ); camera.SetOrientation( objectOri ); } vaCameraControllerFlythrough::vaCameraControllerFlythrough( ) { m_currentTime = 0.0f; m_totalTime = 0.0f; //m_userParam0 = 0.0f; //m_userParam1 = 0.0f; m_playSpeed = 1.0f; m_enableLoop = true; m_fixedUp = false; m_fixedUpVec = vaVector3( 0.0f, 0.0f, 1.0f ); } vaCameraControllerFlythrough::~vaCameraControllerFlythrough( ) { } void vaCameraControllerFlythrough::CameraAttached( const shared_ptr<vaCameraBase> & camera ) { vaCameraControllerBase::CameraAttached( camera ); } bool vaCameraControllerFlythrough::FindKeys( float time, int & keyIndexFrom, int & keyIndexTo ) { time = vaMath::Clamp( time, 0.0f, m_totalTime ); if( m_keys.size() == 0 ) return false; keyIndexFrom = 0; keyIndexTo = 0; if( m_keys.size() == 1 ) return true; // linear search - find binary in std:: algorithms when more perf needed :) for( keyIndexTo = 1; keyIndexTo < m_keys.size(); keyIndexTo++ ) { if( m_keys[keyIndexTo].Time >= time ) break; } keyIndexFrom = keyIndexTo-1; return true; } void vaCameraControllerFlythrough::CameraTick( float deltaTime, vaCameraBase & camera, bool hasFocus ) { hasFocus; //unreferenced if( m_keys.size( ) == 0 ) return; SetPlayTime( GetPlayTime() + deltaTime * GetPlaySpeed() ); int indexFrom, indexTo; if( !FindKeys( GetPlayTime(), indexFrom, indexTo ) ) return; Keyframe & keyFrom = m_keys[indexFrom]; Keyframe & keyTo = m_keys[indexTo]; float timeBetweenKeys = keyTo.Time - keyFrom.Time; timeBetweenKeys = vaMath::Max( 0.00001f, timeBetweenKeys ); float lerpK = vaMath::Clamp( (m_currentTime-keyFrom.Time) / timeBetweenKeys, 0.0f, 1.0f ); //lerpK = vaMath::Smoothstep( lerpK ); vaVector3 pos = vaVector3::Lerp( keyFrom.Position, keyTo.Position, lerpK ); vaQuaternion rot = vaQuaternion::Slerp( keyFrom.Orientation, keyTo.Orientation, lerpK ); #if 1 int index0 = vaMath::Max( 0, indexFrom-1 ); int index1 = indexFrom; int index2 = indexTo; int index3 = vaMath::Min( (int)m_keys.size()-1, indexTo+1 ); Keyframe & key0 = m_keys[index0]; Keyframe & key1 = m_keys[index1]; Keyframe & key2 = m_keys[index2]; Keyframe & key3 = m_keys[index3]; pos = vaVector3::CatmullRom( key0.Position, key1.Position, key2.Position, key3.Position, lerpK ); //pos = vaVector3::Hermite( key1.Position, (key2.Position - key0.Position).Normalized(), key2.Position, (key3.Position - key1.Position).Normalized(), lerpK ); //rot = vaQuaternion::Squad( key0.Orientation, key1.Orientation, key2.Orientation, key3.Orientation, lerpK ); //rot = vaQuaternion::Slerp( key0.Orientation, key1.Orientation, lerpK ); rot = vaQuaternion::CatmullRom( key0.Orientation, key1.Orientation, key2.Orientation, key3.Orientation, lerpK ); #endif if( m_fixedUp ) { vaVector3 currentUp = rot.GetAxisY(); vaVector3 rotAxis = vaVector3::Cross( currentUp, m_fixedUpVec ); float rotAngle = vaVector3::AngleBetweenVectors( currentUp, m_fixedUpVec ); rot *= vaQuaternion::RotationAxis( rotAxis, rotAngle ); } // float lf = vaMath::TimeIndependentLerpF( deltaTime, 5.0f / (currentKey.ShowTime+2.0f) ); // // pos = vaMath::Lerp( camera.GetPosition(), pos, lf ); // rot = vaQuaternion::Slerp( camera.GetOrientation(), rot, lf ); camera.SetPosition( pos ); camera.SetOrientation( rot ); } void vaCameraControllerFlythrough::AddKey( const Keyframe & newKey ) { vector< Keyframe >::iterator it = std::lower_bound( m_keys.begin( ), m_keys.end( ), newKey, ( [ this ]( const Keyframe & a, const Keyframe & b ) { return a.Time < b.Time; } ) ); m_keys.insert( it, newKey ); // insert before iterator it m_totalTime = m_keys.back().Time; } void vaCameraControllerFlythrough::UIPropertiesItemDraw( ) { #ifdef VA_IMGUI_INTEGRATION_ENABLED //ImGui::Text( "Time: %", m_currentTime ); ImGui::SliderFloat( "Playback position", &m_currentTime, 0.0f, m_totalTime ); m_currentTime = vaMath::Clamp( m_currentTime, 0.0f, m_totalTime ); ImGui::InputFloat( "Playback speed", &m_playSpeed, 0.2f ); m_playSpeed = vaMath::Clamp( m_playSpeed, -10.0f, 10.0f ); #endif }
13,132
4,527
#include "prestopch.h" #include "Channel.h" #include "Presto/Components/Electronics/Communication/Signals/ISignal.h" namespace Presto { void Channel::Send(ISignal* signal) { m_Signal = signal; } ISignal* Channel::Read() { return m_Signal; } }
286
110
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class PrintPreviewUITest : public UITest { public: PrintPreviewUITest() { dom_automation_enabled_ = true; // TODO(thestig): Remove when print preview is enabled by default. launch_arguments_.AppendSwitch(switches::kEnablePrintPreview); } void AssertIsPrintPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_PRINT_PREVIEW_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; // TODO(thestig) Remove this test in the future if loading // chrome::kChromeUIPrintURL directly does not make sense. TEST_F(PrintPreviewUITest, LoadPrintPreviewByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the print preview tab via URL. NavigateToURL(GURL(chrome::kChromeUIPrintURL)); AssertIsPrintPage(tab); } TEST_F(PrintPreviewUITest, PrintCommandDisabled) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); // Go to the about:blank page. NavigateToURL(GURL(chrome::kAboutBlankURL)); // Make sure there is 1 tab and print is enabled. Create print preview tab. int tab_count; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); bool enabled; ASSERT_TRUE(browser->IsMenuCommandEnabled(IDC_PRINT, &enabled)); ASSERT_TRUE(enabled); ASSERT_TRUE(browser->RunCommand(IDC_PRINT)); // Make sure there are 2 tabs and print is disabled. ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsPrintPage(tab); ASSERT_TRUE(browser->IsMenuCommandEnabled(IDC_PRINT, &enabled)); ASSERT_FALSE(enabled); } } // namespace
2,497
896
#include "default_theme_provider.h" #include "ui_base/resource/resource_bundle.h" #include "view/widget/native_widget_win.h" namespace view { DefaultThemeProvider::DefaultThemeProvider() {} DefaultThemeProvider::~DefaultThemeProvider() {} void DefaultThemeProvider::Init(Profile* profile) {} SkBitmap* DefaultThemeProvider::GetBitmapNamed(int id) const { return ui::ResourceBundle::GetSharedInstance().GetBitmapNamed(id); } SkColor DefaultThemeProvider::GetColor(int id) const { // Return debugging-blue. return 0xff0000ff; } bool DefaultThemeProvider::GetDisplayProperty(int id, int* result) const { return false; } bool DefaultThemeProvider::ShouldUseNativeFrame() const { return NativeWidgetWin::IsAeroGlassEnabled(); } bool DefaultThemeProvider::HasCustomImage(int id) const { return false; } RefCountedMemory* DefaultThemeProvider::GetRawData(int id) const { return NULL; } } //namespace view
1,055
309
#include <cmath> #include "greentea-client/test_env.h" #include "mbed.h" #include "unity.h" #include "utest.h" #include "vznncv_stepper_motor.h" #include "vznncv_stepper_motor_extra.h" using namespace utest::v1; using vznncvsteppermotor::BaseStepperMotor; using vznncvsteppermotor::microseconds_u32; using vznncvsteppermotor::SimpleSequenceWrapper; //-------------------------------- // test setup functions //-------------------------------- static utest::v1::status_t app_test_setup_handler(const size_t number_of_cases) { // common setup code ... return greentea_test_setup_handler(number_of_cases); } static utest::v1::status_t app_case_setup_handler(const Case *const source, const size_t index_of_case) { // test setup code ... return greentea_case_setup_handler(source, index_of_case); } static utest::v1::status_t app_case_teardown_handler(const Case *const source, const size_t passed, const size_t failed, const failure_t failure) { // test tear down code ... return greentea_case_teardown_handler(source, passed, failed, failure); } static void app_test_teardown_handler(const size_t passed, const size_t failed, const failure_t failure) { // common tear down code return greentea_test_teardown_handler(passed, failed, failure); } //-------------------------------- // dummy stepper motor driver to track steps //-------------------------------- class DummyStepperMotor : public BaseStepperMotor { public: DummyStepperMotor() = default; private: MoveDirection _last_direction; int _total_steps_forward; int _total_steps_backward; int _enable_event_count; int _disable_event_count; std::chrono::microseconds _last_step; Timer _t; int _err_step_impl = 0; int _err_set_direction_impl = 0; int _err_set_state_impl = 0; public: MoveDirection dsm_get_last_direction() const { return _last_direction; } int dsm_get_total_steps_forward() const { return _total_steps_forward; } int dsm_get_total_steps_backward() const { return _total_steps_backward; } int dsm_get_total_steps() const { return dsm_get_total_steps_forward() + dsm_get_total_steps_backward(); } float dsm_get_movement_time() const { return _last_step.count() / 1'000'000.0f; } int dsm_get_enable_event_count() const { return _enable_event_count; } int dsm_get_disable_event_count() const { return _disable_event_count; } void dsm_reset_step_timer() { CriticalSectionLock lock; _t.reset(); } void dsm_reset_statistic() { CriticalSectionLock lock; _total_steps_forward = 0; _total_steps_backward = 0; _enable_event_count = 0; _disable_event_count = 0; _last_step = 0ms; _last_direction = DIR_NONE; dsm_reset_step_timer(); } void dsm_err_step_impl(int err) { _err_step_impl = err; } void dsm_err_set_direction_impl(int err) { _err_set_direction_impl = err; } void dsm_err_set_state_impl(int err) { _err_set_state_impl = err; } protected: // BaseStepperMotor interface int init_impl() override { _t.start(); dsm_reset_statistic(); return 0; } int step_impl(const step_description_t &step) override { if (_err_step_impl) { return _err_step_impl; } if (_total_steps_forward == 0 && _total_steps_backward == 0) { _t.reset(); } switch (_last_direction) { case vznncvsteppermotor::BaseStepperMotor::DIR_FORWARD: _total_steps_forward++; break; case vznncvsteppermotor::BaseStepperMotor::DIR_NONE: MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_DRIVER, MBED_ERROR_CODE_INVALID_OPERATION), "Step with no direction"); break; case vznncvsteppermotor::BaseStepperMotor::DIR_BACKWARD: _total_steps_backward++; break; default: MBED_ERROR(MBED_ERROR_UNKNOWN, "Unreachable code"); } _last_step = _t.elapsed_time(); return 0; } int set_direction_impl(MoveDirection dir) override { if (_err_set_direction_impl) { return _err_set_direction_impl; } _last_direction = dir; return 0; } int set_state_impl(State state) override { if (_err_set_state_impl) { return _err_set_state_impl; } if (state == STATE_ENABLED) { _enable_event_count++; } else if (state == STATE_DISABLED) { _disable_event_count++; } else { MBED_ERROR(MBED_ERROR_UNKNOWN, "Unknown state code"); } return 0; } }; static constexpr float PI = 3.141592653589793f; //-------------------------------- // test functions //-------------------------------- static void test_simple_forward_movement_with_constant_speed() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(2000)); dsm.dsm_reset_statistic(); dsm.move(100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.01f, 0.05f, dsm.dsm_get_movement_time()); } static void test_simple_backward_movement_with_constant_speed() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(2000)); dsm.dsm_reset_statistic(); dsm.move(-100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.01f, 0.05f, dsm.dsm_get_movement_time()); } static void test_simple_forward_movement_with_constant_acceleration() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(2000, 2000)); dsm.dsm_reset_statistic(); dsm.move(100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.06f, 0.39f, dsm.dsm_get_movement_time()); } static void test_simple_backward_movement_with_constant_acceleration() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(2000, 2000)); dsm.dsm_reset_statistic(); dsm.move(-100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.06f, 0.39f, dsm.dsm_get_movement_time()); } struct sine_wave_generator_t { sine_wave_generator_t(float a = 0.0f, float phi = 0.0f, float d_phi = 0.1f * PI, int step_count = 0) : a(a) , phi(phi) , d_phi(d_phi) , step_count(step_count) { } float a; float phi; float d_phi; int step_count; SimpleSequenceWrapper::sample_t next() { SimpleSequenceWrapper::sample_t sample; if (step_count <= 0) { sample.value = 0; sample.flags = SimpleSequenceWrapper::FLAG_STOP; } else { sample.value = a * sinf(phi); phi += d_phi; sample.flags = 0; step_count--; } return sample; } }; static void test_simple_movement_with_custom_step() { const microseconds_u32 interval = 10ms; const float f = 2.0f; const int num_periods = 3; sine_wave_generator_t sine_wave_generator; sine_wave_generator.a = 500.0f; sine_wave_generator.d_phi = 2 * PI * f * interval.count() / 1'000'000.0f; sine_wave_generator.step_count = num_periods * 1'000'000.0f / (f * interval.count()); SimpleSequenceWrapper seq_wrapper(callback(&sine_wave_generator, &sine_wave_generator_t::next), interval); DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_custom_step(seq_wrapper.get_custom_step_callback())); dsm.dsm_reset_statistic(); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); const int expected_one_dir_steps = sine_wave_generator.a * 2 * num_periods; const float expected_move_time = num_periods / f; TEST_ASSERT_EQUAL(0, sine_wave_generator.step_count); TEST_ASSERT_INT_WITHIN(100, expected_one_dir_steps, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_INT_WITHIN(100, expected_one_dir_steps, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.2f, expected_move_time, dsm.dsm_get_movement_time()); } static void test_complex_movement() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(2000, 1000)); dsm.dsm_reset_statistic(); dsm.move(100); ThisThread::sleep_for(500ms); dsm.move_to(-500); ThisThread::sleep_for(500ms); dsm.move(-1000); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(4000, 4000)); ThisThread::sleep_for(500ms); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(4000)); dsm.move(2000); dsm.wait_end_of_movement(); TEST_ASSERT_INT_WITHIN(50, 1160, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_INT_WITHIN(50, 660, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.2f, 1.8f, dsm.dsm_get_movement_time()); } void test_base_enable_disable_functionality() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(1000)); // check default state TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_disable_event_count()); // check disabling TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); // check idempotence TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); // check enabling TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_ENABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(2, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); // check idempotence TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_ENABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(2, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); } void test_active_base_enable_disable_functionality() { int steps; int dist_to_go; Timer t; DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(1000)); dsm.dsm_reset_statistic(); // move, but stop at the center dsm.move(200); ThisThread::sleep_for(100ms); dsm.set_state(BaseStepperMotor::STATE_DISABLED); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); dist_to_go = dsm.distance_to_go(); steps = dsm.dsm_get_total_steps_forward(); TEST_ASSERT_INT_WITHIN(25, 100, steps); TEST_ASSERT_INT_WITHIN(25, 100, dist_to_go); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); // wait and check that there is no more movement ThisThread::sleep_for(200ms); TEST_ASSERT_EQUAL(steps, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(dist_to_go, dsm.distance_to_go()); // check that resume method doesn't work TEST_ASSERT_EQUAL(0, dsm.resume_movement()); ThisThread::sleep_for(200ms); TEST_ASSERT_EQUAL(steps, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(dist_to_go, dsm.distance_to_go()); // check that ::wait_stopping resum control immediately t.start(); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); t.stop(); // note: time should be small, but any interrupt may increase it (like OS scheduler), so check it with some reserve TEST_ASSERT_INT_WITHIN(100, 0, t.elapsed_time().count()); // resume movement dsm.dsm_reset_step_timer(); TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_ENABLED)); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); // check results TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); TEST_ASSERT_EQUAL(200, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.02f, 0.1f, dsm.dsm_get_movement_time()); } static void test_configuration_methods() { float max_speed; float max_accelration; BaseStepperMotor::CustomStepCallback custom_step_cb; BaseStepperMotor::CustomStepCallback custom_step_cb_impl = [](const BaseStepperMotor::position_t &pos) -> BaseStepperMotor::step_instruction_t { return { BaseStepperMotor::DIR_NONE, 500us }; }; DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); // check constant speed parameters TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(1200.0f)); max_speed = 0.0f; TEST_ASSERT_EQUAL(0, dsm.get_mode_params_constant_speed(max_speed)); TEST_ASSERT_EQUAL(1200.0f, max_speed); TEST_ASSERT_EQUAL(BaseStepperMotor::MODE_CONSTANT_SPEED, dsm.get_mode()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_acceleration(max_speed, max_accelration)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_custom_step(custom_step_cb)); // check constant acceleration parameters TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(800.0f, 500.0f)); max_speed = 0.0f; max_accelration = 0.0f; TEST_ASSERT_EQUAL(0, dsm.get_mode_params_constant_acceleration(max_speed, max_accelration)); TEST_ASSERT_EQUAL(800.0f, max_speed); TEST_ASSERT_EQUAL(500.0f, max_accelration); TEST_ASSERT_EQUAL(BaseStepperMotor::MODE_CONSTANT_ACCELERATION, dsm.get_mode()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_speed(max_speed)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_custom_step(custom_step_cb)); // check custom step TEST_ASSERT_EQUAL(0, dsm.set_mode_custom_step(custom_step_cb_impl)); custom_step_cb = 0; TEST_ASSERT_EQUAL(0, dsm.get_mode_params_custom_step(custom_step_cb)); TEST_ASSERT_TRUE(custom_step_cb == custom_step_cb_impl); TEST_ASSERT_EQUAL(BaseStepperMotor::MODE_CUSTOM_STEP, dsm.get_mode()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_speed(max_speed)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_acceleration(max_speed, max_accelration)); // check step parameters dsm.set_mode_constant_speed(1000.0f); TEST_ASSERT_EQUAL(0, dsm.get_target_position()); TEST_ASSERT_EQUAL(0, dsm.get_current_position()); TEST_ASSERT_EQUAL(0, dsm.distance_to_go()); dsm.set_target_position(100); dsm.set_current_position(50); TEST_ASSERT_EQUAL(100, dsm.get_target_position()); TEST_ASSERT_EQUAL(50, dsm.get_current_position()); TEST_ASSERT_EQUAL(50, dsm.distance_to_go()); dsm.set_target_position(-20); dsm.set_current_position(80); TEST_ASSERT_EQUAL(-20, dsm.get_target_position()); TEST_ASSERT_EQUAL(80, dsm.get_current_position()); TEST_ASSERT_EQUAL(-100, dsm.distance_to_go()); } void test_impl_errors() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); dsm.set_mode_constant_speed(1000.0f); TEST_ASSERT_EQUAL(0, dsm.get_error()); auto reset_postions = [](BaseStepperMotor &bsm) { bsm.set_current_position(0); bsm.set_target_position(0); }; // check that we movement doesn't cause errors dsm.move(10); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(0, dsm.get_error()); // check that step error prevents movement dsm.dsm_reset_statistic(); reset_postions(dsm); dsm.dsm_err_step_impl(-1); dsm.move(10); TEST_ASSERT_NOT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(10, dsm.distance_to_go()); TEST_ASSERT_EQUAL(0, dsm.get_current_position()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps()); dsm.dsm_err_step_impl(0); dsm.clear_error(); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(0, dsm.distance_to_go()); TEST_ASSERT_EQUAL(10, dsm.get_current_position()); TEST_ASSERT_EQUAL(10, dsm.dsm_get_total_steps()); // check that direction error prevents movement dsm.dsm_reset_statistic(); reset_postions(dsm); dsm.dsm_err_set_direction_impl(-1); dsm.move(5); TEST_ASSERT_NOT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(5, dsm.distance_to_go()); TEST_ASSERT_EQUAL(0, dsm.get_current_position()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps()); dsm.dsm_err_set_direction_impl(0); dsm.clear_error(); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(0, dsm.distance_to_go()); TEST_ASSERT_EQUAL(5, dsm.get_current_position()); TEST_ASSERT_EQUAL(5, dsm.dsm_get_total_steps()); // check set state error dsm.dsm_reset_statistic(); reset_postions(dsm); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); dsm.dsm_err_set_state_impl(-1); TEST_ASSERT_NOT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); dsm.dsm_err_set_state_impl(0); dsm.clear_error(); TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); } // test cases description #define SimpleCase(test_fun) Case(#test_fun, app_case_setup_handler, test_fun, app_case_teardown_handler, greentea_case_failure_continue_handler) static Case cases[] = { // base modes SimpleCase(test_simple_forward_movement_with_constant_acceleration), SimpleCase(test_simple_backward_movement_with_constant_acceleration), SimpleCase(test_simple_forward_movement_with_constant_speed), SimpleCase(test_simple_backward_movement_with_constant_speed), SimpleCase(test_simple_movement_with_custom_step), // combination of modes SimpleCase(test_complex_movement), SimpleCase(test_base_enable_disable_functionality), SimpleCase(test_active_base_enable_disable_functionality), // test configuration methods SimpleCase(test_configuration_methods), SimpleCase(test_impl_errors) }; static Specification specification(app_test_setup_handler, cases, app_test_teardown_handler); // Entry point into the tests int main() { // host handshake // note: should be invoked here or in the test_setup_handler GREENTEA_SETUP(40, "default_auto"); // run tests return !Harness::run(specification); }
20,804
8,500
// -*- C++ -*- //===--------------------------- semaphore --------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_SEMAPHORE #define _LIBCPP_SEMAPHORE /* semaphore synopsis namespace std { template<ptrdiff_t least_max_value = implementation-defined> class counting_semaphore { public: static constexpr ptrdiff_t max() noexcept; constexpr explicit counting_semaphore(ptrdiff_t desired); ~counting_semaphore(); counting_semaphore(const counting_semaphore&) = delete; counting_semaphore& operator=(const counting_semaphore&) = delete; void release(ptrdiff_t update = 1); void acquire(); bool try_acquire() noexcept; template<class Rep, class Period> bool try_acquire_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time); private: ptrdiff_t counter; // exposition only }; using binary_semaphore = counting_semaphore<1>; } */ #ifndef __simt__ #include <__config.hxx> #include <__threading_support.hxx> #include <atomic.hxx> #include <cassert.hxx> #endif #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif #ifdef _LIBCPP_HAS_NO_THREADS # error <semaphore> is not supported on this single threaded system #endif #if _LIBCPP_STD_VER < 11 # error <semaphore> is requires C++11 or later #endif _LIBCPP_BEGIN_NAMESPACE_STD template<int _Sco> class __atomic_semaphore_base { __atomic_base<ptrdiff_t, _Sco> __count; #ifndef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE __libcpp_contention_t __contention; #endif public: _LIBCPP_INLINE_VISIBILITY __atomic_semaphore_base(ptrdiff_t __count) : __count(__count) { } ~__atomic_semaphore_base() = default; __atomic_semaphore_base(__atomic_semaphore_base const&) = delete; __atomic_semaphore_base& operator=(__atomic_semaphore_base const&) = delete; _LIBCPP_INLINE_VISIBILITY void release(ptrdiff_t __update = 1) { if(0 < __count.fetch_add(__update, memory_order_release)) ; #ifdef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE else if(__update > 1) __cxx_atomic_notify_all(&__count.__a_); else __cxx_atomic_notify_one(&__count.__a_); #else else if(__update > 1) __cxx_atomic_notify_all(&__count.__a_, &__contention); else __cxx_atomic_notify_one(&__count.__a_, &__contention); #endif } _LIBCPP_INLINE_VISIBILITY void acquire() { ptrdiff_t __old = __count.load(memory_order_relaxed); while (1) { if(__old == 0) { #ifdef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE __cxx_atomic_wait(&__count.__a_, __old, memory_order_relaxed); #else __cxx_atomic_wait(&__count.__a_, __old, memory_order_relaxed, &__contention); #endif __old = __count.load(memory_order_relaxed); continue; } if(__count.compare_exchange_weak(__old, __old - 1, memory_order_acquire, memory_order_relaxed)) break; } } template <class Rep, class Period> _LIBCPP_INLINE_VISIBILITY bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time) { return __libcpp_thread_poll_with_backoff([=]() { ptrdiff_t __old = __count.load(memory_order_acquire); if (__old == 0) return false; return __count.compare_exchange_weak(__old, __old - 1, memory_order_acquire, memory_order_relaxed); }, __rel_time); } }; #ifndef _LIBCPP_HAS_NO_SEMAPHORES class __sem_semaphore_basic_base { #ifdef __APPLE__ atomic<ptrdiff_t> __balance = {0}; #endif __libcpp_semaphore_t __semaphore; public: _LIBCPP_EXPORTED_FROM_ABI __sem_semaphore_basic_base(ptrdiff_t __count); _LIBCPP_EXPORTED_FROM_ABI ~__sem_semaphore_basic_base(); _LIBCPP_EXPORTED_FROM_ABI void release(ptrdiff_t __update); _LIBCPP_EXPORTED_FROM_ABI void acquire(); _LIBCPP_EXPORTED_FROM_ABI bool try_acquire_for(chrono::nanoseconds __rel_time); }; #ifndef _LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER class __sem_semaphore_back_buffered_base { _LIBCPP_INLINE_VISIBILITY void __backfill(); __sem_semaphore_basic_base __semaphore; atomic<ptrdiff_t> __backbuffer; public: _LIBCPP_EXPORTED_FROM_ABI __sem_semaphore_back_buffered_base(ptrdiff_t __count); _LIBCPP_EXPORTED_FROM_ABI ~__sem_semaphore_back_buffered_base(); _LIBCPP_EXPORTED_FROM_ABI void release(ptrdiff_t __update); _LIBCPP_EXPORTED_FROM_ABI void acquire(); _LIBCPP_EXPORTED_FROM_ABI bool try_acquire_for(chrono::nanoseconds __rel_time); }; #endif //_LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER #ifndef _LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER class __sem_semaphore_front_buffered_base { _LIBCPP_INLINE_VISIBILITY bool __try_acquire_fast(); _LIBCPP_INLINE_VISIBILITY void __try_done(); #ifndef _LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER __sem_semaphore_back_buffered_base __semaphore; #else __sem_semaphore_basic_base __semaphore; #endif atomic<ptrdiff_t> __frontbuffer; public: _LIBCPP_EXPORTED_FROM_ABI __sem_semaphore_front_buffered_base(ptrdiff_t __count); _LIBCPP_EXPORTED_FROM_ABI ~__sem_semaphore_front_buffered_base(); _LIBCPP_EXPORTED_FROM_ABI void release(ptrdiff_t __update); _LIBCPP_EXPORTED_FROM_ABI void acquire(); _LIBCPP_EXPORTED_FROM_ABI bool try_acquire_for(chrono::nanoseconds __rel_time); }; #endif //_LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER #endif //_LIBCPP_HAS_NO_SEMAPHORES #if defined(_LIBCPP_HAS_NO_SEMAPHORES) template<int _Sco, ptrdiff_t> using __semaphore_base = __atomic_semaphore_base<_Sco>; #else # if !defined(_LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER) using __sem_semaphore_base = __sem_semaphore_front_buffered_base; # elif !defined(_LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER) using __sem_semaphore_base = __sem_semaphore_back_buffered_base; # else using __sem_semaphore_base = __sem_semaphore_basic_base; # endif template<int _Sco, ptrdiff_t __least_max_value> using __semaphore_base = typename conditional<(__least_max_value > 1 && __least_max_value <= _LIBCPP_SEMAPHORE_MAX), __sem_semaphore_base, __atomic_semaphore_base<_Sco>>::type; #endif template<ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX> class counting_semaphore { __semaphore_base<0, __least_max_value> __semaphore; public: static constexpr ptrdiff_t max() noexcept { return __least_max_value; } _LIBCPP_INLINE_VISIBILITY counting_semaphore(ptrdiff_t __count = 0) : __semaphore(__count) { } ~counting_semaphore() = default; counting_semaphore(const counting_semaphore&) = delete; counting_semaphore& operator=(const counting_semaphore&) = delete; _LIBCPP_INLINE_VISIBILITY void release(ptrdiff_t __update = 1) { __semaphore.release(__update); } _LIBCPP_INLINE_VISIBILITY void acquire() { __semaphore.acquire(); } template<class Rep, class Period> _LIBCPP_INLINE_VISIBILITY bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time) { return __semaphore.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time)); } _LIBCPP_INLINE_VISIBILITY bool try_acquire() { return try_acquire_for(chrono::nanoseconds::zero()); } template <class Clock, class Duration> _LIBCPP_INLINE_VISIBILITY bool try_acquire_until(chrono::time_point<Clock, Duration> const& __abs_time) { auto const current = Clock::now(); if(current >= __abs_time) return try_acquire(); else return try_acquire_for(__abs_time - current); } }; using binary_semaphore = counting_semaphore<1>; _LIBCPP_END_NAMESPACE_STD #endif //_LIBCPP_SEMAPHORE
8,329
3,142
/*************************************************************************** * ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk * Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle * * This program is PUBLIC DOMAIN. * This means that there is no copyright and anyone is able to take a copy * for free and use it as they wish, with or without modifications, and in * any context, commercially or otherwise. The only limitation is that I * don't guarantee that the software is fit for any purpose or accept any * liability for it's use or misuse - this software is without warranty. *************************************************************************** * File Description: Abstract interpretation for Thumb mode. **************************************************************************/ #if defined(__arm__) || defined(__thumb__) #define MODULE_NAME "UNWARM_THUMB" #include <stdio.h> #include "unwarm.h" /** Sign extend an 11 bit value. * This function simply inspects bit 11 of the input \a value, and if * set, the top 5 bits are set to give a 2's compliment signed value. * \param value The value to sign extend. * \return The signed-11 bit value stored in a 16bit data type. */ static int32_t signExtend11(const uint16_t value) { return (value & 0x400) ? value | 0xFFFFF800 : value; } UnwResult UnwStartThumb(UnwState * const state) { bool found = false; uint16_t t = UNW_MAX_INSTR_COUNT; uint32_t lastJumpAddr = 0; // Last JUMP address, to try to detect infinite loops bool loopDetected = false; // If a loop was detected do { uint16_t instr; /* Attempt to read the instruction */ if (!state->cb->readH(state->regData[15].v & (~0x1), &instr)) return UNWIND_IREAD_H_FAIL; UnwPrintd4("T %x %x %04x:", state->regData[13].v, state->regData[15].v, instr); /* Check that the PC is still on Thumb alignment */ if (!(state->regData[15].v & 0x1)) { UnwPrintd1("\nError: PC misalignment\n"); return UNWIND_INCONSISTENT; } /* Check that the SP and PC have not been invalidated */ if (!M_IsOriginValid(state->regData[13].o) || !M_IsOriginValid(state->regData[15].o)) { UnwPrintd1("\nError: PC or SP invalidated\n"); return UNWIND_INCONSISTENT; } /* * Detect 32bit thumb instructions */ if ((instr & 0xE000) == 0xE000 && (instr & 0x1800) != 0) { uint16_t instr2; /* Check next address */ state->regData[15].v += 2; /* Attempt to read the 2nd part of the instruction */ if (!state->cb->readH(state->regData[15].v & (~0x1), &instr2)) return UNWIND_IREAD_H_FAIL; UnwPrintd3(" %x %04x:", state->regData[15].v, instr2); /* * Load/Store multiple: Only interpret * PUSH and POP */ if ((instr & 0xFE6F) == 0xE82D) { bool L = !!(instr & 0x10); uint16_t rList = instr2; if (L) { uint8_t r; /* Load from memory: POP */ UnwPrintd1("POP {Rlist}\n"); /* Load registers from stack */ for (r = 0; r < 16; r++) { if (rList & (0x1 << r)) { /* Read the word */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (M_IsOriginValid(state->regData[r].o)) { state->regData[r].o = REG_VAL_FROM_STACK; /* If restoring the PC */ if (r == 15) { /* The bottom bit should have been set to indicate that * the caller was from Thumb. This would allow return * by BX for interworking APCS. */ if ((state->regData[15].v & 0x1) == 0) { UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v); /* Pop into the PC will not switch mode */ return UNWIND_INCONSISTENT; } /* Store the return address */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Now have the return address */ UnwPrintd2(" Return PC=%x\n", state->regData[15].v); /* Compensate for the auto-increment, which isn't needed here */ state->regData[15].v -= 2; } } else { if (r == 15) { /* Return address is not valid */ UnwPrintd1("PC popped with invalid address\n"); return UNWIND_FAILURE; } } state->regData[13].v += 4; UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v); } } } else { int8_t r; /* Store to memory: PUSH */ UnwPrintd1("PUSH {Rlist}"); for (r = 15; r >= 0; r--) { if (rList & (0x1 << r)) { UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o)); state->regData[13].v -= 4; if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DWRITE_W_FAIL; } } } } /* * PUSH register */ else if (instr == 0xF84D && (instr2 & 0x0FFF) == 0x0D04) { uint8_t r = instr2 >> 12; /* Store to memory: PUSH */ UnwPrintd2("PUSH {R%d}\n", r); UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o)); state->regData[13].v -= 4; if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DWRITE_W_FAIL; } /* * POP register */ else if (instr == 0xF85D && (instr2 & 0x0FFF) == 0x0B04) { uint8_t r = instr2 >> 12; /* Load from memory: POP */ UnwPrintd2("POP {R%d}\n", r); /* Read the word */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (M_IsOriginValid(state->regData[r].o)) { state->regData[r].o = REG_VAL_FROM_STACK; /* If restoring the PC */ if (r == 15) { /* The bottom bit should have been set to indicate that * the caller was from Thumb. This would allow return * by BX for interworking APCS. */ if ((state->regData[15].v & 0x1) == 0) { UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v); /* Pop into the PC will not switch mode */ return UNWIND_INCONSISTENT; } /* Store the return address */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Now have the return address */ UnwPrintd2(" Return PC=%x\n", state->regData[15].v); /* Compensate for the auto-increment, which isn't needed here */ state->regData[15].v -= 2; } } else { if (r == 15) { /* Return address is not valid */ UnwPrintd1("PC popped with invalid address\n"); return UNWIND_FAILURE; } } state->regData[13].v += 4; UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v); } /* * TBB / TBH */ else if ((instr & 0xFFF0) == 0xE8D0 && (instr2 & 0xFFE0) == 0xF000) { /* We are only interested in * the forms * TBB [PC, ...] * TBH [PC, ..., LSL #1] * as those are used by the C compiler to implement * the switch clauses */ uint8_t rn = instr & 0xF; bool H = !!(instr2 & 0x10); UnwPrintd5("TB%c [r%d,r%d%s]\n", H ? 'H' : 'B', rn, (instr2 & 0xF), H ? ",LSL #1" : ""); // We are only interested if the RN is the PC. Let's choose the 1st destination if (rn == 15) { if (H) { uint16_t rv; if (!state->cb->readH((state->regData[15].v & (~1)) + 2, &rv)) return UNWIND_DREAD_H_FAIL; state->regData[15].v += rv * 2; } else { uint8_t rv; if (!state->cb->readB((state->regData[15].v & (~1)) + 2, &rv)) return UNWIND_DREAD_B_FAIL; state->regData[15].v += rv * 2; } } } /* * Unconditional branch */ else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x9000) { uint32_t v; uint8_t S = (instr & 0x400) >> 10; uint16_t imm10 = (instr & 0x3FF); uint8_t J1 = (instr2 & 0x2000) >> 13; uint8_t J2 = (instr2 & 0x0800) >> 11; uint16_t imm11 = (instr2 & 0x7FF); uint8_t I1 = J1 ^ S ^ 1; uint8_t I2 = J2 ^ S ^ 1; uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1); if (S) imm32 |= 0xFE000000; UnwPrintd2("B %d \n", imm32); /* Update PC */ state->regData[15].v += imm32; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Compute the jump address */ v = state->regData[15].v + 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", v); /* Did we detect an infinite loop ? */ loopDetected = lastJumpAddr == v; /* Remember the last address we jumped to */ lastJumpAddr = v; } /* * Branch with link */ else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0xD000) { uint8_t S = (instr & 0x400) >> 10; uint16_t imm10 = (instr & 0x3FF); uint8_t J1 = (instr2 & 0x2000) >> 13; uint8_t J2 = (instr2 & 0x0800) >> 11; uint16_t imm11 = (instr2 & 0x7FF); uint8_t I1 = J1 ^ S ^ 1; uint8_t I2 = J2 ^ S ^ 1; uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1); if (S) imm32 |= 0xFE000000; UnwPrintd2("BL %d \n", imm32); /* Never taken, as we are unwinding the stack */ if (0) { /* Store return address in LR register */ state->regData[14].v = state->regData[15].v + 2; state->regData[14].o = REG_VAL_FROM_CONST; /* Update PC */ state->regData[15].v += imm32; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Display PC of next instruction */ UnwPrintd2(" Return PC=%x", state->regData[15].v); /* Report the return address, including mode bit */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Determine the new mode */ if (state->regData[15].v & 0x1) { /* Branching to THUMB */ /* Account for the auto-increment which isn't needed */ state->regData[15].v -= 2; } else { /* Branch to ARM */ return UnwStartArm(state); } } } /* * Conditional branches. Usually not taken, unless infinite loop is detected */ else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x8000) { uint8_t S = (instr & 0x400) >> 10; uint16_t imm6 = (instr & 0x3F); uint8_t J1 = (instr2 & 0x2000) >> 13; uint8_t J2 = (instr2 & 0x0800) >> 11; uint16_t imm11 = (instr2 & 0x7FF); uint8_t I1 = J1 ^ S ^ 1; uint8_t I2 = J2 ^ S ^ 1; uint32_t imm32 = (S << 20) | (I1 << 19) | (I2 << 18) |(imm6 << 12) | (imm11 << 1); if (S) imm32 |= 0xFFE00000; UnwPrintd2("Bcond %d\n", imm32); /* Take the jump only if a loop is detected */ if (loopDetected) { /* Update PC */ state->regData[15].v += imm32; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", state->regData[15].v + 2); } } /* * PC-relative load * LDR Rd,[PC, #+/-imm] */ else if ((instr & 0xFF7F) == 0xF85F) { uint8_t rt = (instr2 & 0xF000) >> 12; uint8_t imm12 = (instr2 & 0x0FFF); bool A = !!(instr & 0x80); uint32_t address; /* Compute load address, adding a word to account for prefetch */ address = (state->regData[15].v & (~0x3)) + 4; if (A) address += imm12; else address -= imm12; UnwPrintd4("LDR r%d,[PC #%c0x%08x]", rt, A?'+':'-', address); if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } /* * LDR immediate. * We are only interested when destination is PC. * LDR Rt,[Rn , #n] */ else if ((instr & 0xFFF0) == 0xF8D0) { uint8_t rn = (instr & 0xF); uint8_t rt = (instr2 & 0xF000) >> 12; uint16_t imm12 = (instr2 & 0xFFF); /* If destination is PC and we don't know the source value, then fail */ if (!M_IsOriginValid(state->regData[rn].o)) { state->regData[rt].o = state->regData[rn].o; } else { uint32_t address = state->regData[rn].v + imm12; if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } } /* * LDR immediate * We are only interested when destination is PC. * LDR Rt,[Rn , #-n] * LDR Rt,[Rn], #+/-n] * LDR Rt,[Rn, #+/-n]! */ else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0800) == 0x0800) { uint8_t rn = (instr & 0xF); uint8_t rt = (instr2 & 0xF000) >> 12; uint16_t imm8 = (instr2 & 0xFF); bool P = !!(instr2 & 0x400); bool U = !!(instr2 & 0x200); bool W = !!(instr2 & 0x100); if (!M_IsOriginValid(state->regData[rn].o)) state->regData[rt].o = state->regData[rn].o; else { uint32_t offaddress = state->regData[rn].v + (U ? imm8 + imm8 : 0), address = P ? offaddress : state->regData[rn].v; if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; if (W) state->regData[rn].v = offaddress; } } /* * LDR (register). * We are interested in the form * ldr Rt, [Rn, Rm, lsl #x] * Where Rt is PC, Rn value is known, Rm is not known or unknown */ else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0FC0) == 0x0000) { const uint8_t rn = (instr & 0xF), rt = (instr2 & 0xF000) >> 12, rm = (instr2 & 0xF), imm2 = (instr2 & 0x30) >> 4; if (!M_IsOriginValid(state->regData[rn].o) || !M_IsOriginValid(state->regData[rm].o)) { /* If Rt is PC, and Rn is known, then do an exception and assume Rm equals 0 => This takes the first case in a switch() */ if (rt == 15 && M_IsOriginValid(state->regData[rn].o)) { uint32_t address = state->regData[rn].v; if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } else /* Propagate unknown value */ state->regData[rt].o = state->regData[rn].o; } else { uint32_t address = state->regData[rn].v + (state->regData[rm].v << imm2); if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } } else { UnwPrintd1("???? (32)"); /* Unknown/undecoded. May alter some register, so invalidate file */ UnwInvalidateRegisterFile(state->regData); } /* End of thumb 32bit code */ } /* Format 1: Move shifted register * LSL Rd, Rs, #Offset5 * LSR Rd, Rs, #Offset5 * ASR Rd, Rs, #Offset5 */ else if ((instr & 0xE000) == 0x0000 && (instr & 0x1800) != 0x1800) { bool signExtend; const uint8_t op = (instr & 0x1800) >> 11, offset5 = (instr & 0x07C0) >> 6, rs = (instr & 0x0038) >> 3, rd = (instr & 0x0007); switch (op) { case 0: /* LSL */ UnwPrintd6("LSL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o)); state->regData[rd].v = state->regData[rs].v << offset5; state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; case 1: /* LSR */ UnwPrintd6("LSR r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o)); state->regData[rd].v = state->regData[rs].v >> offset5; state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; case 2: /* ASR */ UnwPrintd6("ASL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o)); signExtend = !!(state->regData[rs].v & 0x8000); state->regData[rd].v = state->regData[rs].v >> offset5; if (signExtend) state->regData[rd].v |= 0xFFFFFFFF << (32 - offset5); state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; } } /* Format 2: add/subtract * ADD Rd, Rs, Rn * ADD Rd, Rs, #Offset3 * SUB Rd, Rs, Rn * SUB Rd, Rs, #Offset3 */ else if ((instr & 0xF800) == 0x1800) { bool I = !!(instr & 0x0400); bool op = !!(instr & 0x0200); uint8_t rn = (instr & 0x01C0) >> 6; uint8_t rs = (instr & 0x0038) >> 3; uint8_t rd = (instr & 0x0007); /* Print decoding */ UnwPrintd6("%s r%d, r%d, %c%d\t;",op ? "SUB" : "ADD",rd, rs,I ? '#' : 'r',rn); UnwPrintd5("r%d %s, r%d %s",rd, M_Origin2Str(state->regData[rd].o),rs, M_Origin2Str(state->regData[rs].o)); if (!I) { UnwPrintd3(", r%d %s", rn, M_Origin2Str(state->regData[rn].o)); /* Perform calculation */ state->regData[rd].v = state->regData[rs].v + (op ? -state->regData[rn].v : state->regData[rn].v); /* Propagate the origin */ if (M_IsOriginValid(state->regData[rs].o) && M_IsOriginValid(state->regData[rn].o)) { state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; } else state->regData[rd].o = REG_VAL_INVALID; } else { /* Perform calculation */ state->regData[rd].v = state->regData[rs].v + (op ? -rn : rn); /* Propagate the origin */ state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; } } /* Format 3: move/compare/add/subtract immediate * MOV Rd, #Offset8 * CMP Rd, #Offset8 * ADD Rd, #Offset8 * SUB Rd, #Offset8 */ else if ((instr & 0xE000) == 0x2000) { uint8_t op = (instr & 0x1800) >> 11; uint8_t rd = (instr & 0x0700) >> 8; uint8_t offset8 = (instr & 0x00FF); switch (op) { case 0: /* MOV */ UnwPrintd3("MOV r%d, #0x%x", rd, offset8); state->regData[rd].v = offset8; state->regData[rd].o = REG_VAL_FROM_CONST; break; case 1: /* CMP */ /* Irrelevant to unwinding */ UnwPrintd1("CMP ???"); break; case 2: /* ADD */ UnwPrintd5("ADD r%d, #0x%x\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o)); state->regData[rd].v += offset8; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; case 3: /* SUB */ UnwPrintd5("SUB r%d, #0x%d\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o)); state->regData[rd].v -= offset8; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; } } /* Format 4: ALU operations * AND Rd, Rs * EOR Rd, Rs * LSL Rd, Rs * LSR Rd, Rs * ASR Rd, Rs * ADC Rd, Rs * SBC Rd, Rs * ROR Rd, Rs * TST Rd, Rs * NEG Rd, Rs * CMP Rd, Rs * CMN Rd, Rs * ORR Rd, Rs * MUL Rd, Rs * BIC Rd, Rs * MVN Rd, Rs */ else if ((instr & 0xFC00) == 0x4000) { uint8_t op = (instr & 0x03C0) >> 6; uint8_t rs = (instr & 0x0038) >> 3; uint8_t rd = (instr & 0x0007); #ifdef UNW_DEBUG static const char * const mnu[16] = { "AND", "EOR", "LSL", "LSR", "ASR", "ADC", "SBC", "ROR", "TST", "NEG", "CMP", "CMN", "ORR", "MUL", "BIC", "MVN" }; #endif /* Print the mnemonic and registers */ switch (op) { case 0: /* AND */ case 1: /* EOR */ case 2: /* LSL */ case 3: /* LSR */ case 4: /* ASR */ case 7: /* ROR */ case 9: /* NEG */ case 12: /* ORR */ case 13: /* MUL */ case 15: /* MVN */ UnwPrintd8("%s r%d ,r%d\t; r%d %s, r%d %s",mnu[op],rd, rs, rd, M_Origin2Str(state->regData[rd].o), rs, M_Origin2Str(state->regData[rs].o)); break; case 5: /* ADC */ case 6: /* SBC */ UnwPrintd4("%s r%d, r%d", mnu[op], rd, rs); break; case 8: /* TST */ case 10: /* CMP */ case 11: /* CMN */ /* Irrelevant to unwinding */ UnwPrintd2("%s ???", mnu[op]); break; case 14: /* BIC */ UnwPrintd5("r%d ,r%d\t; r%d %s", rd, rs, rs, M_Origin2Str(state->regData[rs].o)); break; } /* Perform operation */ switch (op) { case 0: /* AND */ state->regData[rd].v &= state->regData[rs].v; break; case 1: /* EOR */ state->regData[rd].v ^= state->regData[rs].v; break; case 2: /* LSL */ state->regData[rd].v <<= state->regData[rs].v; break; case 3: /* LSR */ state->regData[rd].v >>= state->regData[rs].v; break; case 4: /* ASR */ if (state->regData[rd].v & 0x80000000) { state->regData[rd].v >>= state->regData[rs].v; state->regData[rd].v |= 0xFFFFFFFF << (32 - state->regData[rs].v); } else { state->regData[rd].v >>= state->regData[rs].v; } break; case 5: /* ADC */ case 6: /* SBC */ case 8: /* TST */ case 10: /* CMP */ case 11: /* CMN */ break; case 7: /* ROR */ state->regData[rd].v = (state->regData[rd].v >> state->regData[rs].v) | (state->regData[rd].v << (32 - state->regData[rs].v)); break; case 9: /* NEG */ state->regData[rd].v = -state->regData[rs].v; break; case 12: /* ORR */ state->regData[rd].v |= state->regData[rs].v; break; case 13: /* MUL */ state->regData[rd].v *= state->regData[rs].v; break; case 14: /* BIC */ state->regData[rd].v &= ~state->regData[rs].v; break; case 15: /* MVN */ state->regData[rd].v = ~state->regData[rs].v; break; } /* Propagate data origins */ switch (op) { case 0: /* AND */ case 1: /* EOR */ case 2: /* LSL */ case 3: /* LSR */ case 4: /* ASR */ case 7: /* ROR */ case 12: /* ORR */ case 13: /* MUL */ case 14: /* BIC */ if (M_IsOriginValid(state->regData[rd].o) && M_IsOriginValid(state->regData[rs].o)) { state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; } else state->regData[rd].o = REG_VAL_INVALID; break; case 5: /* ADC */ case 6: /* SBC */ /* C-bit not tracked */ state->regData[rd].o = REG_VAL_INVALID; break; case 8: /* TST */ case 10: /* CMP */ case 11: /* CMN */ /* Nothing propagated */ break; case 9: /* NEG */ case 15: /* MVN */ state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; } } /* Format 5: Hi register operations/branch exchange * ADD Rd, Hs * CMP Hd, Rs * MOV Hd, Hs */ else if ((instr & 0xFC00) == 0x4400) { uint8_t op = (instr & 0x0300) >> 8; bool h1 = (instr & 0x0080) ? true: false; bool h2 = (instr & 0x0040) ? true: false; uint8_t rhs = (instr & 0x0038) >> 3; uint8_t rhd = (instr & 0x0007); /* Adjust the register numbers */ if (h2) rhs += 8; if (h1) rhd += 8; switch (op) { case 0: /* ADD */ UnwPrintd5("ADD r%d, r%d\t; r%d %s", rhd, rhs, rhs, M_Origin2Str(state->regData[rhs].o)); state->regData[rhd].v += state->regData[rhs].v; state->regData[rhd].o = state->regData[rhs].o; state->regData[rhd].o |= REG_VAL_ARITHMETIC; break; case 1: /* CMP */ /* Irrelevant to unwinding */ UnwPrintd1("CMP ???"); break; case 2: /* MOV */ UnwPrintd5("MOV r%d, r%d\t; r%d %s", rhd, rhs, rhd, M_Origin2Str(state->regData[rhs].o)); state->regData[rhd].v = state->regData[rhs].v; state->regData[rhd].o = state->regData[rhd].o; break; case 3: /* BX */ UnwPrintd4("BX r%d\t; r%d %s\n", rhs, rhs, M_Origin2Str(state->regData[rhs].o)); /* Only follow BX if the data was from the stack or BX LR */ if (rhs == 14 || state->regData[rhs].o == REG_VAL_FROM_STACK) { UnwPrintd2(" Return PC=0x%x\n", state->regData[rhs].v & (~0x1)); /* Report the return address, including mode bit */ if (!UnwReportRetAddr(state, state->regData[rhs].v)) return UNWIND_TRUNCATED; /* Update the PC */ state->regData[15].v = state->regData[rhs].v; /* Determine the new mode */ if (state->regData[rhs].v & 0x1) { /* Branching to THUMB */ /* Account for the auto-increment which isn't needed */ state->regData[15].v -= 2; } else /* Branch to ARM */ return UnwStartArm(state); } else { UnwPrintd4("\nError: BX to invalid register: r%d = 0x%x (%s)\n", rhs, state->regData[rhs].o, M_Origin2Str(state->regData[rhs].o)); return UNWIND_FAILURE; } } } /* Format 9: PC-relative load * LDR Rd,[PC, #imm] */ else if ((instr & 0xF800) == 0x4800) { uint8_t rd = (instr & 0x0700) >> 8; uint8_t word8 = (instr & 0x00FF); uint32_t address; /* Compute load address, adding a word to account for prefetch */ address = (state->regData[15].v & (~0x3)) + 4 + (word8 << 2); UnwPrintd3("LDR r%d, 0x%08x", rd, address); if (!UnwMemReadRegister(state, address, &state->regData[rd])) return UNWIND_DREAD_W_FAIL; } /* Format 13: add offset to Stack Pointer * ADD sp,#+imm * ADD sp,#-imm */ else if ((instr & 0xFF00) == 0xB000) { uint8_t value = (instr & 0x7F) * 4; /* Check the negative bit */ if ((instr & 0x80) != 0) { UnwPrintd2("SUB sp,#0x%x", value); state->regData[13].v -= value; } else { UnwPrintd2("ADD sp,#0x%x", value); state->regData[13].v += value; } } /* Format 14: push/pop registers * PUSH {Rlist} * PUSH {Rlist, LR} * POP {Rlist} * POP {Rlist, PC} */ else if ((instr & 0xF600) == 0xB400) { bool L = !!(instr & 0x0800); bool R = !!(instr & 0x0100); uint8_t rList = (instr & 0x00FF); if (L) { uint8_t r; /* Load from memory: POP */ UnwPrintd2("POP {Rlist%s}\n", R ? ", PC" : ""); for (r = 0; r < 8; r++) { if (rList & (0x1 << r)) { /* Read the word */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (M_IsOriginValid(state->regData[r].o)) state->regData[r].o = REG_VAL_FROM_STACK; state->regData[13].v += 4; UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v); } } /* Check if the PC is to be popped */ if (R) { /* Get the return address */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[15])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (!M_IsOriginValid(state->regData[15].o)) { /* Return address is not valid */ UnwPrintd1("PC popped with invalid address\n"); return UNWIND_FAILURE; } else { /* The bottom bit should have been set to indicate that * the caller was from Thumb. This would allow return * by BX for interworking APCS. */ if ((state->regData[15].v & 0x1) == 0) { UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v); /* Pop into the PC will not switch mode */ return UNWIND_INCONSISTENT; } /* Store the return address */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Now have the return address */ UnwPrintd2(" Return PC=%x\n", state->regData[15].v); /* Update the pc */ state->regData[13].v += 4; /* Compensate for the auto-increment, which isn't needed here */ state->regData[15].v -= 2; } } } else { int8_t r; /* Store to memory: PUSH */ UnwPrintd2("PUSH {Rlist%s}", R ? ", LR" : ""); /* Check if the LR is to be pushed */ if (R) { UnwPrintd3("\n lr = 0x%08x\t; %s", state->regData[14].v, M_Origin2Str(state->regData[14].o)); state->regData[13].v -= 4; /* Write the register value to memory */ if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[14])) return UNWIND_DWRITE_W_FAIL; } for (r = 7; r >= 0; r--) { if (rList & (0x1 << r)) { UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o)); state->regData[13].v -= 4; if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DWRITE_W_FAIL; } } } } /* * Conditional branches * Bcond */ else if ((instr & 0xF000) == 0xD000) { int32_t branchValue = (instr & 0xFF); if (branchValue & 0x80) branchValue |= 0xFFFFFF00; /* Branch distance is twice that specified in the instruction. */ branchValue *= 2; UnwPrintd2("Bcond %d \n", branchValue); /* Only take the branch if a loop was detected */ if (loopDetected) { /* Update PC */ state->regData[15].v += branchValue; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", state->regData[15].v + 2); } } /* Format 18: unconditional branch * B label */ else if ((instr & 0xF800) == 0xE000) { uint32_t v; int32_t branchValue = signExtend11(instr & 0x07FF); /* Branch distance is twice that specified in the instruction. */ branchValue *= 2; UnwPrintd2("B %d \n", branchValue); /* Update PC */ state->regData[15].v += branchValue; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Compute the jump address */ v = state->regData[15].v + 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", v); /* Did we detect an infinite loop ? */ loopDetected = lastJumpAddr == v; /* Remember the last address we jumped to */ lastJumpAddr = v; } else { UnwPrintd1("????"); /* Unknown/undecoded. May alter some register, so invalidate file */ UnwInvalidateRegisterFile(state->regData); } UnwPrintd1("\n"); /* Should never hit the reset vector */ if (state->regData[15].v == 0) return UNWIND_RESET; /* Check next address */ state->regData[15].v += 2; /* Garbage collect the memory hash (used only for the stack) */ UnwMemHashGC(state); if (--t == 0) return UNWIND_EXHAUSTED; } while (!found); return UNWIND_SUCCESS; } #endif // __arm__ || __thumb__
34,521
13,141
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file ctc_loss.cc * \brief * \author Sebastian Bodenstein */ #include "./ctc_loss-inl.h" #include "./ctc_include/detail/cpu_ctc.h" namespace mshadow { template <typename DType> ctcStatus_t compute_ctc_cost(const Tensor<cpu, 3, DType> activations, DType *costs, DType *grads, int *labels, int *label_lengths, int *data_lengths, void *workspace, int train) { int minibatch = static_cast<int>(activations.size(1)); int alphabet_size = static_cast<int>(activations.size(2)); int blank_label = 0; mxnet_warpctc::CpuCTC<DType> ctc(alphabet_size, minibatch, workspace, blank_label); if (train) return ctc.cost_and_grad(activations.dptr_, grads, costs, labels, label_lengths, data_lengths); else return ctc.score_forward(activations.dptr_, costs, labels, label_lengths, data_lengths); } } // namespace mshadow namespace mxnet { namespace op { template <> Operator *CreateOp<cpu>(CTCLossParam param, int dtype) { return new CTCLossOp<cpu>(param); } // DO_BIND_DISPATCH comes from operator_common.h Operator *CTCLossProp::CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape, std::vector<int> *in_type) const { std::vector<TShape> out_shape, aux_shape; std::vector<int> out_type, aux_type; CHECK(InferType(in_type, &out_type, &aux_type)); CHECK(InferShape(in_shape, &out_shape, &aux_shape)); DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]); } DMLC_REGISTER_PARAMETER(CTCLossParam); MXNET_REGISTER_OP_PROPERTY(_contrib_CTCLoss, CTCLossProp) .describe(R"code(Connectionist Temporal Classification Loss. The shapes of the inputs and outputs: - **data**: *(sequence_length, batch_size, alphabet_size + 1)* - **label**: *(batch_size, label_sequence_length)* - **out**: *(batch_size)*. ``label`` is a tensor of integers between 1 and *alphabet_size*. If a sequence of labels is shorter than *label_sequence_length*, use the special padding character 0 at the end of the sequence to conform it to the correct length. For example, if *label_sequence_length* = 4, and one has two sequences of labels [2, 1] and [3, 2, 2], the resulting ```label``` tensor should be padded to be:: [[2, 1, 0, 0], [3, 2, 2, 0]] The ``data`` tensor consists of sequences of activation vectors. The layer applies a softmax to each vector, which then becomes a vector of probabilities over the alphabet. Note that the 0th element of this vector is reserved for the special blank character. ``out`` is a list of CTC loss values, one per example in the batch. See *Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks*, A. Graves *et al*. for more information. )code" ADD_FILELINE) .add_argument("data", "NDArray-or-Symbol", "Input data to the ctc_loss op.") .add_argument("label", "NDArray-or-Symbol", "Ground-truth labels for the loss.") .add_argument("data_lengths", "NDArray-or-Symbol", "Lengths of data for each of the samples. Only required " "when use_data_lengths is true.") .add_argument("label_lengths", "NDArray-or-Symbol", "Lengths of labels for each of the samples. Only required " "when use_label_lengths is true.") .add_arguments(CTCLossParam::__FIELDS__()); NNVM_REGISTER_OP(_contrib_CTCLoss).add_alias("_contrib_ctc_loss"); } // namespace op } // namespace mxnet
4,411
1,385
#include <algorithm> #include "predictor.cpp" inline double sq(const double& x) { return x * x; } double cosine(const LDMap &syms1, const LVec &syms2, const Tfidf &tfidf){ double sig = 0, sig1 = 0, sig2 = 0; for (auto s : syms1) sig1 += sq(tfidf.get(s.first)) * sq(s.second); for (auto s : syms2) { const double tw = tfidf.get(s); sig2 += sq(tw); auto got = syms1.find(s); if (got != syms1.end()) sig += sq(tw) * got->second; } return (sq(sig) / (sig1 * sig2)); // for jaccard use: // return (sig / (sig1 + sig2 + sig)); } double euclid(const LDMap &syms1, const LVec &syms2, const Tfidf &tfidf) { double sig = 0; for (auto s : syms2) if (syms1.find(s) == syms1.end()) sig += sq(tfidf.get(s)); for (const auto s : syms1) if (find(syms2.begin(), syms2.end(), s.first) == syms2.end()) sig += sq(tfidf.get(s.first)) * sq(s.second); return (1 / (1 + sig)); } class MePo : public Predictor { public: MePo(LVecVec deps, LVecVec syms, LVecVec sym_ths, long sym_num); void learn(long from, long to); protected: LDPairVec predict(const LVec& csyms, long maxth, long no_adv) const; private: Tfidf tfidf; const static int mepo_incr = 100; }; MePo::MePo(LVecVec deps, LVecVec syms, LVecVec sym_ths, long sym_num) : Predictor(deps, syms, sym_ths, sym_num), tfidf(sym_num) { } void MePo::learn(long from, long to) { for (unsigned i = from; i < to; ++i) tfidf.add(syms[i]); } LDPairVec MePo::predict(const LVec& csyms, long maxth, long no_adv) const { // theorem importance matrix LDPairVec ans = LDPairVec(maxth, make_pair(0, 0)); for (long i = 0; i < maxth; ++i) ans[i].first = i; LDMap nsyms; for (auto s : csyms) nsyms[s] = 1.0; for (long sofar = 0; sofar < no_adv; sofar += mepo_incr) { for (long i = sofar; i < maxth; ++i) ans[i].second = cosine(nsyms, syms[ans[i].first], tfidf); long until = min(sofar + mepo_incr, no_adv); partial_sort(ans.begin() + sofar, ans.begin() + until, ans.begin() + maxth, sortfun); if (until >= maxth) return ans; for (long i = sofar; i < until; i++) for (auto s : syms[ans[i].first]) nsyms[s] = max(nsyms[s], ans[i].second); } return ans; }
2,271
981
/* Текстовый квест 20WaysToDie Учебный проект (c) Брянцев Всеволод (c) Компьютерная академия ШАГ . Воронеж Версия 1.0 (08.04.2019) */ #include "pch.h" #include <iostream> #include <stdlib.h> using namespace std; int endings[21]; int menu_choice; /*-----------------------------------------------------------------------*/ // меню void Menu(); // функции для меню void Endings_Output(); void Game(); /*-----------------------------------------------------------------------*/ // универсальная функция выбора int Choice(); /*-----------------------------------------------------------------------*/ // единственная выигрышная концовка (21 номер само собой) void WinTheGame(); // готова /*-----------------------------------------------------------------------*/ // вот это я придумал конечно, да, вывод текста для каждой смерти отдельно, мб изменю потом void Death1(); // готова void Death2(); // готова void Death3(); // готова void Death4(); // готова void Death5(); // готова void Death6(); // готова void Death7(); // готова void Death8(); // готова void Death9(); // готова void Death10(); // готова void Death11(); // готова void Death12(); // готова void Death13(); // готова void Death14(); // готова void Death15(); // готова void Death16(); // готова void Death17(); // готова void Death18(); // готова void Death19(); // готова void Death20(); // готова /*-----------------------------------------------------------------------*/ // естессна все сцены тоже будут написаны отдельно, какой я непредсказуемый void Scene1(); void subScene1(); // готова void Scene2(); // готова void Scene3(); void subScene3_1(); void subScene3_2(); // готова void Scene4(); // готова void Scene5(); // готова void Scene6(); // готова void Scene7(); void subScene7_1(); void subScene7_2(); void subScene7_3(); // готова void Scene8(); void subScene8(); // готова void Scene9(); void subScene9_1(); void subScene9_2(); void subScene9_3(); void subScene9_4(); // готова void Scene10(); void subScene10(); // готова void Scene11(); void subScene11_1(); void subScene11_2(); void subScene11_3(); // готова void Scene12(); void subScene12_1(); void subScene12_2(); void subScene12_3(); void subScene12_4(); // готова void Scene13(); void subScene13_1(); void subScene13_2(); void subScene13_3();// готова void Scene14(); // готова void Scene15(); void subScene15_1(); void subScene15_2(); // готова void Scene16(); // готова void Scene17(); // готова void Scene18(); // готова void Scene19(); // готова void Scene20(); // готова void Scene21(); // готова void Scene22(); void subScene22_1(); void subScene22_2(); void subScene22_3(); void subScene22_4(); void subScene22_5(); void subScene22_6(); void subScene22_7(); void subScene22_8(); void subScene22_9(); void subScene22_10(); // готова void Scene23(); void subScene23(); // готова void Scene24(); void subScene24(); // готова void Scene25(); // готова void Scene26(); void subScene26(); // готова void Scene27(); // готова void Scene28(); // готова void Scene29(); // готова void Scene30(); void subScene30_1(); void subScene30_2(); // готова void Scene31(); // готова void Scene32(); // готова void Scene33(); // готова /*-----------------------------------------------------------------------*/ int main() { setlocale(LC_ALL, "rus"); cout << "Текстовый квест 20WaysToDie" << endl << "(c) Брянцев Всеволод" << endl << "(c) Компьютерная академия ШАГ . Воронеж" << endl << "Версия 1.0 (08.04.2019)" << endl << endl; system("pause"); system("cls"); Menu(); } /*-----------------------------------------------------------------------*/ // функции для игрового меню void Endings_Output() { cout << "Разблокированные концовки: " << endl << endl; for (int i = 0; i < 21; i++) { switch (i) { case 0: if (endings[i] == 1) { cout << "1. Умер, так и не дождавшись спасительного чуда" << endl; } break; case 1: if (endings[i] == 1) { cout << "2. Употребление электронных устройств в пищу вредит вашему здоровью" << endl; } break; case 2: if (endings[i] == 1) { cout << "3. Поиск ответа на вопрос \"В чем смысл жизни?\" до добра не доводит" << endl; } break; case 3: if (endings[i] == 1) { cout << "4. Бесследно пропал после задержания Росгвардией" << endl; } break; case 4: if (endings[i] == 1) { cout << "5. Отключился мозг (за ненадобностью)" << endl; } break; case 5: if (endings[i] == 1) { cout << "Умер в страшных мучениях, съев незнакомый науке гриб" << endl; } break; case 6: if (endings[i] == 1) { cout << "Поплатился за кражу грибов, превратившись в пепел" << endl; } break; case 7: if (endings[i] == 1) { cout << "Умер в компании русалок. Хотя, это стоило того" << endl; } break; case 8: if (endings[i] == 1) { cout << "Тебя съела пажылая Годзилла, плохо просвещенная в музыкальном искусстве" << endl; } break; case 9: if (endings[i] == 1) { cout << "Замрглбрлглблен насмерть мурлоками" << endl; } break; case 10: if (endings[i] == 1) { cout << "Плохая концовка без причины, просто так. Смирись с этим" << endl; } case 11: if (endings[i] == 1) { cout << "Умер чисто по-приколу, потому что автор так захотел" << endl; } break; case 12: if (endings[i] == 1) { cout << "Обидел мурлоков незнанием их языка" << endl; } break; case 13: if (endings[i] == 1) { cout << "Закосплеил Балрога" << endl; } break; case 14: if (endings[i] == 1) { cout << "Погиб из-за необдуманности своих действий" << endl; } break; case 15: if (endings[i] == 1) { cout << "Случайно раздавлен троллем" << endl; } break; case 16: if (endings[i] == 1) { cout << "Был до смерти затроллен троллем" << endl; } break; case 17: if (endings[i] == 1) { cout << "Пожизненно забанен за читы" << endl; } break; case 18: if (endings[i] == 1) { cout << "Неудачно бустанул компьютер" << endl; } break; case 19: if (endings[i] == 1) { cout << "Умер, потому что не смог отгадать детскую загадку" << endl; } break; case 20: if (endings[i] == 1) { cout << "Выбрался из той комнаты и прошел этот ужасный квест" << endl; } break; default: break; } } cout << endl; Menu(); } void Game() { Scene1(); } // само игровое меню void Menu() { cout << "Меню: " << endl; cout << "1. Играть" << endl; cout << "2. Показать открытые концовки (всего их 21 штука)" << endl; cout << "3. Выход" << endl; cout << "Выбор действия (1, 2 или 3): "; cin >> menu_choice; cout << endl; system("cls"); switch (menu_choice) { case 1: Game(); break; case 2: Endings_Output(); break; case 3: exit(0); break; } } /*-----------------------------------------------------------------------*/ // функция выбора int Choice() { int choice; Retry: cout << "Выбор действия (1, 2 или 3): "; cin >> choice; if (choice < 1 || choice > 3) { cout << "Прочитай внимательнее: " << endl; goto Retry; } cout << endl << endl; return choice; } /*-----------------------------------------------------------------------*/ // СМЭРТИ void Death1() // задействовано { cout << "Ты умер от истощения, так и не дождавшись спасительного чуда" << endl << endl; endings[0] = 1; Menu(); } void Death2() // задействовано { cout << "Ты умер от пищевого отравления телефоном" << endl << "Похоже тебе никто не говорил, что есть телефоны нельзя" << endl << endl; endings[1] = 1; Menu(); } void Death3() // задействовано { cout << "Ты так и не получил ответа на вопрос о смысле жизни, тем самым ты умер от экзистенциального кризиса" << endl << endl; endings[2] = 1; Menu(); } void Death4() // задействовано { cout << "Примерно через 10 минут стены комнаты были пробиты зарядами и тебя повязала Росгвардия." << endl << "Потом ты был конвоирован в неизвестном направлении и больше никто и никогда тебя не видел" << endl << endl; endings[3] = 1; Menu(); } void Death5() // задействовано { cout << "Твой мозг решил, что он больше не вынесет твоей тупости, и отключился" << endl << endl; endings[4] = 1; Menu(); } void Death6() // задействовано { cout << "Твой живот скрутило так, что ты умер в мучениях примерно через восемь секунд" << endl << "Мораль: не верь всяким незнакомым старикам" << endl << endl; endings[5] = 1; Menu(); } void Death7() // задействовано { cout << "Как только ты схватил корзинку и собрался убегать, костры вокруг старика всколыхнулись адским пламенем и превратили тебя в пепел" << endl << endl; endings[6] = 1; Menu(); } void Death8() // задействовано { cout << "Ты с разбегу сиганул в пруд. Русалки обняли тебя и угостили вином с черной икрой" << endl << "В пруду включился режим джакузи и вы чудесно провели пару часов" << endl << "А потом русалки тебя съели" << endl << endl; endings[7] = 1; Menu(); } void Death9() // задействовано { cout << "Похоже что Годзилла не знает такой песни. Иначе она не стала бы тебя есть" << endl << endl; endings[8] = 1; Menu(); } void Death10() // задействовано { cout << "Ты так и не понял, получилось ли у тебя втереться в доверие к мурлокам, потому что тебя замрглбрлглблобили насмерть" << endl << endl; endings[9] = 1; Menu(); } void Death11() // задействовано { cout << "Игра закончена от недостатка в ней сюжета, мотивации, каких-либо действий и вообще чего бы то ни было" << endl << "Будем считать, что ты мертв" << endl << endl; endings[10] = 1; Menu(); } void Death12() // задействовано { cout << "Хотел нелепый конец игры? Ок, ты умер, потому что я так сказал." << endl << "И не спорь, я автор, мне виднее" << endl << endl; endings[11] = 1; Menu(); } void Death13() // задействовано { cout << "Ты хоть сам-то понял что сказал? Нет? А вот мурлоки поняли" << endl << "И походу обиделись, потому что далее ты обнаружил копье у себя в почке" << endl << endl; endings[12] = 1; Menu(); } void Death14() // задействовано { cout << "Ваша битва продолжалась очень долго и была нереально эпичной и зрелищной" << endl << "А потом вы оба плюхнулись на дно ямы" << endl << endl; endings[13] = 1; Menu(); } void Death15() // задействовано { cout << "Прыгая в люк, ты заметил что там была лестница, по которой можно было нормально спуститься" << endl << "Тебе просто напросто не хватило ловкости, чтобы схватиться за нее" << endl << "Короче, че я распинаюсь? Надо было думать головой, прежде чем прыгать во всякие люки" << endl << endl; endings[14] = 1; Menu(); } void Death16() // задействовано { cout << "Тролль заметил тебя только тогда, когда случайно раздавил тебя" << endl << "А ведь у него просто закончилась рабочая смена и он хотел пойти домой" << endl << endl; endings[15] = 1; Menu(); } void Death17() // задействовано { cout << "Ты взорвался от злости, так и не услышав еще одной обидной провокации от тролля" << endl << "Мораль: не тролль, незатроллирован будешь" << endl << endl; endings[16] = 1; Menu(); } void Death18() // задействовано { cout << "По чисто субъективному мнению автора (шучу, оно объективное), юзать читы в многопользовательских играх - значит быть криворуким инвалидом" << endl << "Автор отправляет тебя в пожизненный бан в реальной жизни" << endl << endl; endings[17] = 1; Menu(); } void Death19() // задействовано { cout << "Чет мне кажется, что так делать не нужно было" << endl << "Компьютер реально начал работать быстрее, но взорвался от перегрева. И ты вместе с ним" << endl << endl; endings[18] = 1; Menu(); } void Death20() // задействовано { cout << "Все как и договаривались: ты мертв" << endl << endl; endings[19] = 1; Menu(); } /*-----------------------------------------------------------------------*/ // ВЫИГРЫШНАЯ КОНЦОВКА void WinTheGame() // задействовано { cout << "Тебе удалось выбраться из этой передряги живым и невредимым. Красава!" << endl << endl; endings[20] = 1; Menu(); } /*-----------------------------------------------------------------------*/ // СЦЕНЫ void Scene1() { cout << "Ты очнулся в темном помещении, естественно вокруг ничего не видно." << endl << "В твоей голове возникла здравая мысль выбраться отсюда." << endl << endl; cout << "1. Пошарить по карманам" << endl; cout << "2. Ощупать комнату" << endl; cout << "3. Помолиться Богу о спасении твоей души" << endl; switch (Choice()) { case 1: Scene2(); break; case 2: Scene3(); break; case 3: subScene1(); break; } } void subScene1() { cout << "Перед тобой начала высвечиваться белым светом надпись " << endl << "\"Ваша заявка на спасение души принята, " << endl << "ждите обработки в течение 2 - 10 тысяч рабочих лет\"" << endl << endl; cout << "1. Пошарить по карманам" << endl; cout << "2. Ощупать комнату" << endl; cout << "3. Ждать 2 - 10 тысяч рабочих лет" << endl; switch (Choice()) { case 1: Scene2(); break; case 2: Scene3(); break; case 3: Death1(); break; } } void Scene2() { cout << "Пошарив у себя по карманам, ты достаешь оттуда свой мобильник" << endl << "На нем остался всего 1% зарядки." << endl << "Это значит что можно позвонить только один раз" << endl; cout << "1. Позвонить в полицию" << endl; cout << "2. Поиграть в 20WaysToDie" << endl; cout << "3. Позвонить маме" << endl; switch (Choice()) { case 1: Scene5(); break; case 2: Scene6(); break; case 3: Scene7(); break; } } void Scene3() { cout << "Встав и пройдя вперед, ты уперся в стену." << endl << "А далее: угол, стена, угол, стена, угол, снова стена" << endl << "Походу это реально комната." << endl << " На одной из стен ты нащупал дверь" << endl; cout << "1. Открыть дверь" << endl; cout << "2. Выбить дверь ногой, как это делают во всех боевиках" << endl; cout << "3. Поговорить с дверью" << endl; switch (Choice()) { case 1: Scene4(); break; case 2: Scene4(); break; case 3: subScene3_1(); break; } } void subScene3_1() { cout << "Ты сейчас серьезно?" << endl; cout << "1. Открыть дверь" << endl; cout << "2. Выбить дверь ногой, как это делают во всех боевиках" << endl; cout << "3. Не, ну а почему нет?" << endl; switch (Choice()) { case 1: Scene4(); break; case 2: Scene4(); break; case 3: subScene3_2(); break; } } void subScene3_2() { cout << "Вау, похоже что дверь молчит, может быть она немая?" << endl; cout << "1. Открыть дверь" << endl; cout << "2. Попробовать говорить на языке жестов" << endl; cout << "3. Наорать на дверь" << endl; switch (Choice()) { case 1: Scene4(); break; case 2: Death5(); break; case 3: Death5(); break; } } void Scene4() { cout << "Перед тобой уже хорошо освещенная комната" << endl << "На полу лежат футбольный мяч, блокнот с какими-то записями и одна лыжа" << endl; cout << "1. Попинать мяч" << endl; cout << "2. Почитать записи в блокноте" << endl; cout << "3. Покататься на одной лыже по бетонному полу" << endl; switch (Choice()) { case 1: Scene11(); break; case 2: Scene12(); break; case 3: Scene13(); break; } } void Scene5() { cout << "\"Городское отделение полиции, у телефона Светлана, я вас слушаю\"" << endl; cout << "1. Алло, девушка, я заперт в какой-то темной комнате" << endl << "Прошу, помогите!" << endl; cout << "2. Детка, у тебя самый сексуальный голос, что я слышал" << endl; cout << "3. Хочу заказать пиццу, пеперони пожалуйста" << endl << "Адрес: темная комната, хрен знает где" << endl; switch (Choice()) { case 1: Scene9(); break; case 2: Scene10(); break; case 3: subScene9_3(); break; } } void Scene6() { cout << "Только ты успел получить одну концовку, как телефон разрядился" << endl << "Что будешь делать дальше?" << endl; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void Scene7() { cout << "\"Ой, здравствуй, сынок, спасибо что позвонил" << endl << "Мы так с папой твоим соскучились, ну расскажи что там у тебя?" << endl << "Как жизнь? Как работа? А девушку ты себе нашел?" << endl << "А приедешь когда? Надо на дачу съездить, ремонт доделать то." << endl << "Огород еще бы хорошо прополоть, я то уже старая стала" << endl << "А вот если бы еще внуки были...\"" << endl; cout << "1. Мам, я тут в какой-то комнате темной сижу, мне срочно нужна..." << endl; cout << "2. Промолчать" << endl; cout << "3. Бросить трубку" << endl; switch (Choice()) { case 1: subScene7_1(); break; case 2: subScene7_2(); break; case 3: subScene7_3(); break; } } void subScene7_1() { cout << "\"Что значит сидишь в темной комнате?!?" << endl << "Опять небось веселился со своими друзьями-наркоманами!" << endl << "Такими темпами они тебя скоро накурят спайсами какими-нибудь!" << endl << "И все, а ведь мне еще внуков хочется повидать!" << endl << "В общем вылазь из своей комнаты и быстро к нам! А не то...\"" << endl << "Мама не успела договорить, так как телефон решил неожиданно разрядиться"; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void subScene7_2() { cout << "\"Ну что молчишь то?" << endl << "Или это не наш сына?" << endl << "Так, хватить играться! А ну быстро говори, где мой сын?!!?" << endl << "Или я сейчас же звоню в полицию!!! Они там...\"" << endl << "Только ты хотел сказать маме, чтобы она все таки позвонила в полицию, как телефон разрядился" << endl; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void subScene7_3() { cout << "Как только ты бросил трубку, телефон разрядился." << endl << "Окей, дальше то что делать будешь?" << endl; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void Scene8() { cout << "А ведь было же все просто отлично..." << endl << "Образование, отличная работа, друзья, даже машину себе купил не в кредит" << endl << "Что же могло пойти не так?" << endl; cout << "1. Иногда мне кажется, что внутри меня пустота..." << endl; cout << "2. Жизнь слишком хороша, но я недостоин ее" << endl; cout << "3. У меня все как у людей, но являюсь ли я человеком?" << endl; switch (Choice()) { case 1: subScene8(); break; case 2: subScene8(); break; case 3: subScene8(); break; } } void subScene8() { cout << "Ну вот зачем так про себя говорить?" << endl << "Ты отчличный парень, и впереди тебя ждет отличное будущее" << endl; cout << "1. Будущее?!?! Нет у меня никакого будущего!!!" << endl; cout << "2. И в чем смысл этого будущего?" << endl; cout << "3. Что значит хороший парень? Кто это сказал? Кто это определил?" << endl << "Я не чувствую себя отличным..." << endl; switch (Choice()) { case 1: Death3(); break; case 2: Death3(); break; case 3: Death3(); break; } } void Scene9() { cout << "\"Адрес комнаты сообщите, пожалуйста\"" << endl; cout << "1. Да откуда я знаю?!? Здесь темно, страшно и я не знаю, как сюда попал!" << endl; cout << "2. Пилингуйте мой телефон, таким образом вы узнаете где я!" << endl; cout << "3. Бейкер-стрит, 221b" << endl; switch (Choice()) { case 1: subScene9_1(); break; case 2: subScene9_2(); break; case 3: subScene9_3(); break; } } void subScene9_1() { cout << "Послышались длинные гудки, а потом телефон отключился" << endl; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void subScene9_2() { cout << "\"Мы вам тут не ФЭС, у нас не настолько продвинутые технологии" << endl << "Без адреса не могу вам ничем помочь\"" << endl; cout << "1. Да пошла ты!" << endl; cout << "2. Долой Путина! Навального в президенты! Все на митинг!" << endl; cout << "3. Да откуда я знаю?!? Здесь темно, страшно и я не знаю, как сюда попал!" << endl; switch (Choice()) { case 1: subScene9_4(); break; case 2: Death4(); break; case 3: subScene9_1(); break; } } void subScene9_3() { cout << "\"Очень смешно\", - сказала девушка и повесила трубку" << endl << "А потом телефон разрядился" << endl; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void subScene9_4() { cout << "\"Ну вы и хамло\", - сказала Светлана и бросила трубку" << endl << "Телефон, само собой, разрядился" << endl; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void Scene10() { cout << "\"Мужчина, это полиция, говорите, что случилось, иначе я повешу трубку\"" << endl; cout << "1. Детка, со мной случилась ты..." << endl; cout << "2. Я очнулся в какой-то темной комнате и мне нужна помощь" << endl; cout << "3. Подкат к девушке не удался, повесить трубку" << endl; switch (Choice()) { case 1: subScene9_1(); break; case 2: Scene9(); break; case 3: subScene10(); break; } } void subScene10() { cout << "Ты повесил трубку, а телефон не выдержал твоего позора и разрядился" << endl; cout << "1. Обыскать комнату" << endl; cout << "2. Съесть телефон" << endl; cout << "3. Подумать о том, как ты докатился до такого" << endl; switch (Choice()) { case 1: Scene3(); break; case 2: Death2(); break; case 3: Scene8(); break; } } void Scene11() { cout << "Как будем пинать мяч?" << endl; cout << "1. Как Роналду" << endl; cout << "2. Как Зидан" << endl; cout << "3. Как Аршавин" << endl; switch (Choice()) { case 1: subScene11_1(); break; case 2: subScene11_2(); break; case 3: subScene11_3(); break; } } void subScene11_1() { cout << "Пиная мяч и выполняя крутые финты, ты вскружил себе голову и упал в обморок" << endl << "Очнувшись, ты понял, что лежишь на каком-то люке" << endl; cout << "1. Открыть люк" << endl; cout << "2. Люк, откройся!" << endl; cout << "3. Приложить силу к люку, направленную перпендикулярно поверхности, чтобы открыть его" << endl; switch (Choice()) { case 1: Scene14(); break; case 2: Scene14(); break; case 3: Scene14(); break; } } void subScene11_2() { cout << "Подойдя к мячу, ты резко двинул головой вперед, потерял равновесие и упал в стену" << endl; cout << "1. Проломить стену" << endl; cout << "2. Проломить стену аки боец файтинга" << endl; cout << "3. Почитать записи в блокноте" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: Scene15(); break; case 3: Scene12(); break; } } void subScene11_3() { cout << "В попытке с разбегу ударить по мячу, ты промахиваешься и попадаешь ногой в стену" << endl << "Та оказалась картонной" << endl; cout << "1. Доломать стену, сделав вид, что так и задумано" << endl; cout << "2. Доломать стену с жесточайшим фейспалмом" << endl; cout << "3. Почитать записи в блокноте" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: subScene15_1(); break; case 3: Scene12(); break; } } void Scene12() { cout << "\"Из этой комнаты выхода нет. Ну кроме люка в углу. А еще тут стены картонные" << endl << "Не, ну а так то выхода нет\"" << endl; cout << "1. Проломить стену" << endl; cout << "2. Открыть люк" << endl; cout << "3. Читать дальше" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: Scene14(); break; case 3: subScene12_1(); break; } } void subScene12_1() { cout << "\"Тысячи людей погибли в этой комнате, потому что выхода из нее нет!" << endl << "Кроме люка. И стен\"" << endl; cout << "1. Проломить стену" << endl; cout << "2. Открыть люк" << endl; cout << "3. Читать дальше" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: Scene14(); break; case 3: subScene12_2(); break; } } void subScene12_2() { cout << "\"Тут что, непонятно написано? Люк есть в углу, а стены картонные!" << endl << "Иди уже отсюда, хватит читать\"" << endl; cout << "1. Проломить стену" << endl; cout << "2. Открыть люк" << endl; cout << "3. Читать дальше" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: Scene14(); break; case 3: subScene12_3(); break; } } void subScene12_3() { cout << "\"Ок, дальше не читай, там пусто\"" << endl; cout << "1. Проломить стену" << endl; cout << "2. Открыть люк" << endl; cout << "3. Читать дальше" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: Scene14(); break; case 3: subScene12_4(); break; } } void subScene12_4() { cout << "Ты попытался прочесть следующую страницу, но у тебя ничего не получилось" << endl << "Хмммм, может потому что она пустая?" << endl; cout << "1. Проломить стену" << endl; cout << "2. Открыть люк" << endl; cout << "3. Читать дальше" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: Scene14(); break; case 3: subScene12_4(); break; } } void Scene13() { cout << "Невероятно, но у тебя ничего не получилось" << endl; cout << "1. Попинать мяч" << endl; cout << "2. Почитать записи в блокноте" << endl; cout << "3. Попробовать еще раз" << endl; switch (Choice()) { case 1: Scene11(); break; case 2: Scene12(); break; case 3: subScene13_1(); break; } } void subScene13_1() { cout << "Опять не получилось, как так то?" << endl; cout << "1. Попинать мяч" << endl; cout << "2. Почитать записи в блокноте" << endl; cout << "3. Попробовать еще раз" << endl; switch (Choice()) { case 1: Scene11(); break; case 2: Scene12(); break; case 3: subScene13_2(); break; } } void subScene13_2() { cout << "Снова провал. Хоть немного разумный человек заметил бы тут закономерность" << endl; cout << "1. Попинать мяч" << endl; cout << "2. Почитать записи в блокноте" << endl; cout << "3. Э, слыш, ты кого тут тупым назвал?" << endl; switch (Choice()) { case 1: Scene11(); break; case 2: Scene12(); break; case 3: subScene13_3(); break; } } void subScene13_3() { cout << "Не тупым, а не очень разумным, это разные вещи вообще-то" << endl; cout << "1. Попинать мяч" << endl; cout << "2. Почитать записи в блокноте" << endl; cout << "3. Кинуть со злости лыжу" << endl; switch (Choice()) { case 1: Scene11(); break; case 2: Scene12(); break; case 3: subScene13_3(); break; } } void subScene13_4() { cout << "Кидая лыжу в неизвестно кого, ты попадаешь в стену" << endl << "Лыжа пробила ее насквозь. Хреновая видимо стена" << endl; cout << "1. Проломить стену" << endl; cout << "2. Побежать сквозь стену за дорогой твоему сердцу лыжей" << endl; cout << "3. Почитать записи в блокноте" << endl; switch (Choice()) { case 1: Scene15(); break; case 2: Scene15(); break; case 3: Scene12(); break; } } void Scene14() { cout << "Открыв люк и спустившись по лестнице, ты оказываешься в каком-то подземелье" << endl << "Перед тобой три одинаково жутких темных прохода" << endl; cout << "1. Пойти в левый проход" << endl; cout << "2. Пойти в средний проход" << endl; cout << "3. Пойти в правый проход" << endl; switch (Choice()) { case 1: Scene16(); break; case 2: Scene17(); break; case 3: Scene18(); break; } } void Scene15() { cout << "Проломив стену, ты видишь три прохода" << endl << "Внутри первого видны заженные факелы" << endl << "Во втором с потолка льется какая-то жидкость" << endl << "На полу третьего валяются металлические трубы" << endl << "Через что пойдешь?" << endl; cout << "1. Огонь" << endl; cout << "2. Вода" << endl; cout << "3. Трубы" << endl; switch (Choice()) { case 1: Scene19(); break; case 2: Scene20(); break; case 3: Scene21(); break; } } void subScene15_1() { cout << "Проломив стену и чуть не проломив себе лицо, ты видишь три прохода" << endl << "Внутри первого видны заженные факелы" << endl << "Во втором с потолка льется какая-то жидкость" << endl << "На полу третьего валяются металлические трубы" << endl << "Через что пойдешь?" << endl; cout << "1. Огонь" << endl; cout << "2. Вода" << endl; cout << "3. Трубы" << endl; switch (Choice()) { case 1: Scene19(); break; case 2: Scene20(); break; case 3: Scene21(); break; } } void subScene15_2() { cout << "Ты видишь три прохода" << endl << "Внутри первого видны заженные факелы" << endl << "Во втором с потолка льется какая-то жидкость" << endl << "На полу третьего валяются металлические трубы" << endl << "Через что пойдешь?" << endl; cout << "1. Огонь" << endl; cout << "2. Вода" << endl; cout << "3. Трубы" << endl; switch (Choice()) { case 1: Scene19(); break; case 2: Scene20(); break; case 3: Scene21(); break; } } void Scene16() { cout << "Пока ты шел по левому проходу, прямо за твоей спиной вдруг закрылась бетонная дверь" << endl << "Дальше ты можешь идти только налево, прямо или направо" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: Scene22(); break; case 2: Scene22(); break; case 3: Scene22(); break; } } void Scene17() { cout << "Ты пришел в прекраснейшую пещеру, с прудом посередине, в котором плавают три прелестные русалки" << endl << "Они зовут тебя к себе!" << endl << "Но сзади виднеется проход куда-то еще" << endl; cout << "1. Мама учила тебя не разговаривать с незнакомыми людьми и нелюдьми, пройти дальше" << endl; cout << "2. Присоединиться к русалкам" << endl; cout << "3. Показать им средний палец и вернуться обратно" << endl; switch (Choice()) { case 1: Scene23(); break; case 2: Death8(); break; case 3: Scene14(); break; } } void Scene18() { cout << "Идя по проходу, ты встретил старика, вокруг него горят два костра, а у его ног стоит корзина с грибами" << endl << "\"Грибов не хочешь отведать? Смотри какие сочные! Белые называются\", - сказал старик" << endl; cout << "1. Попробовать грибы" << endl; cout << "2. Украсть корзину с грибами" << endl; cout << "3. Отказаться и пойти дальше" << endl; switch (Choice()) { case 1: Death6(); break; case 2: Death7(); break; case 3: Scene20(); break; } } void Scene19() { cout << "Ты оказываешься в комнате с огромной пажылой Годзиллой" << endl << "Учуяв тебя, она начинает просыпаться" << endl; cout << "1. Тихонько на цыпочках уйти обратно" << endl; cout << "2. Спеть ей колыбельную" << endl; cout << "3. Спеть ей \"Пажылой какаге сонг\"" << endl; switch (Choice()) { case 1: subScene15_2(); break; case 2: Scene25(); break; case 3: Death9(); break; } } void Scene20() { cout << "Ты пришел в полузатопленную водой пещеру, густо заставленную странными хижинами на сваях" << endl << "Вдруг на тебя со всех сторон налетают человекоподобные рыбожабы" << endl << "Черт, да ведь это же мурлоки!" << endl; cout << "1. Попытаться втереться к ним в доверие, сказав \"Мргл-брл-гл-бл\"" << endl; cout << "2. Попытаться втереться к ним в доверие, сказав \"I am murloc!\"" << endl; cout << "3. Убежать обратно" << endl; switch (Choice()) { case 1: Death13(); break; case 2: Death10(); break; case 3: subScene15_2(); break; } } void Scene21() { cout << "Ты приходишь к мосту через глубокую яму, на котором стоит мужик в сером балахоне и орет: \"Ты не пройдешь!\"" << endl; cout << "1. Ну ок, пошли обратно" << endl; cout << "2. Пройти" << endl; cout << "3. Атаковать мужика" << endl; switch (Choice()) { case 1: subScene15_2(); break; case 2: Scene27(); break; case 3: Scene26(); break; } } void Scene22() { cout << "Опять три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_1(); break; case 2: subScene22_1(); break; case 3: subScene22_1(); break; } } void subScene22_1() { cout << "И снова три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_2(); break; case 2: subScene22_2(); break; case 3: subScene22_2(); break; } } void subScene22_2() { cout << "Опять три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_3(); break; case 2: subScene22_3(); break; case 3: subScene22_3(); break; } } void subScene22_3() { cout << "И снова три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_4(); break; case 2: subScene22_4(); break; case 3: subScene22_4(); break; } } void subScene22_4() { cout << "Опять три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_5(); break; case 2: subScene22_5(); break; case 3: subScene22_5(); break; } } void subScene22_5() { cout << "И снова три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_6(); break; case 2: subScene22_6(); break; case 3: subScene22_6(); break; } } void subScene22_6() { cout << "Опять три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_7(); break; case 2: subScene22_7(); break; case 3: subScene22_7(); break; } } void subScene22_7() { cout << "И снова три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_8(); break; case 2: subScene22_8(); break; case 3: subScene22_8(); break; } } void subScene22_8() { cout << "Опять три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_9(); break; case 2: subScene22_9(); break; case 3: subScene22_9(); break; } } void subScene22_9() { cout << "И снова три прохода. Куда идем?" << endl; cout << "1. Налево наш выбор!" << endl; cout << "2. Только вперед!" << endl; cout << "3. Направо, вот куда нам нужно!" << endl; switch (Choice()) { case 1: subScene22_10(); break; case 2: subScene22_10(); break; case 3: subScene22_10(); break; } } void subScene22_10() { cout << "За очередным поворотом в конце туннеля виден свет" << endl << "Похоже все, смэрть" << endl << "Хотя стоп, это же солнце! Ты нашел выход" << endl; cout << "1. Наконец-то! Свобода!" << endl; cout << "2. Найс, че" << endl; cout << "3. Заплакать от счастья" << endl; switch (Choice()) { case 1: WinTheGame(); break; case 2: WinTheGame(); break; case 3: WinTheGame(); break; } } void Scene23() { cout << "Ты идешь вдоль узкой пещеры, а потом оказываешься в полностью белой комнате" << endl << "В ней абсолютно ничего нет, кроме твоего присутствия" << endl; cout << "1. Ничего не делать" << endl; cout << "2. Проявить полную апатию к ситуации" << endl; cout << "3. Сделать что-нибудь" << endl; switch (Choice()) { case 1: Death11(); break; case 2: Death11(); break; case 3: subScene23(); break; } } void subScene23() { cout << "Ты встал на одну ногу, закинул руки за голову" << endl << "В таком положении ты спел Smells Like Teen Spirit на татарском языке" << endl << "Потом, крикнув как чайка, упал на живот и стал кататься по полу" << endl << "Неожиданно, но это сработало - в белой стене открылся проход дальше " << endl; cout << "1. Идти в проход" << endl; cout << "2. В проход идти" << endl; cout << "3. Проход идти в" << endl; switch (Choice()) { case 1: Scene24(); break; case 2: Scene24(); break; case 3: Scene24(); break; } } void Scene24() { cout << "Ты оказался в очередной нелепой комнате и тебе нужно выполнить одно из нелепых действий, чтобы очень нелепо закончить игру" << endl; cout << "1. Первое действие" << endl; cout << "2. Действие 2" << endl; cout << "3. Action №3" << endl; switch (Choice()) { case 1: subScene24(); break; case 2: Death12(); break; case 3: subScene24(); break; } } void subScene24() { cout << "Ха, лох! Ты не угадал с действием! Вот и отправляйся на самое начало квеста!" << endl; cout << "1. Всм" << endl; cout << "2. Эй, это нечестно!" << endl; cout << "3. Автор, ты сука" << endl; switch (Choice()) { case 1: Scene1(); break; case 2: Scene1(); break; case 3: Scene1(); break; } } void Scene25() { cout << "Годзилла немного привстала, а затем вздохнула и снова заснула" << endl << "Рядом с ней ты видишь люк" << endl; cout << "1. Прыгнуть в люк" << endl; cout << "2. Аккуратно спутиться в люк" << endl; cout << "3. Ну нафиг, пойдем обратно" << endl; switch (Choice()) { case 1: Death15(); break; case 2: Scene29(); break; case 3: subScene15_2(); break; } } void Scene26() { cout << "Ты кидаешься на мужика и под вами проваливается мост" << endl << "\"Бегите, глупцы...\" - сказал он, перед тем, как вы оба начали падать" << endl; cout << "1. Удар в живот" << endl; cout << "2. Удар в голову" << endl; cout << "3. Поговорить о ситуации" << endl; switch (Choice()) { case 1: Death14(); break; case 2: Death14(); break; case 3: subScene26(); break; } } void subScene26() { cout << "\"Немного поздновато ты лезешь с разговорами, мы падаем, если что\"" << endl << "И вообще, бейся со мной!" << endl; cout << "1. Заломать руки" << endl; cout << "2. Сделать крапиву" << endl; cout << "3. Ткнуть в глаз" << endl; switch (Choice()) { case 1: Death14(); break; case 2: Death14(); break; case 3: Death14(); break; } } void Scene27() { cout << "Тебе удалось спокойно пройти мост" << endl << "\"Эй, чувак, ну не позорь меня, я же сказал: ты не пройдешь\"" << endl; cout << "1. Не моя проблема" << endl; cout << "2. Проигнорить и пройти дальше" << endl; cout << "3. Пройти дальше с крутым видом" << endl; switch (Choice()) { case 1: Scene28(); break; case 2: Scene28(); break; case 3: Scene28(); break; } } void Scene28() { cout << "Перед тобой три двери, куда пойдешь?" << endl; cout << "1. В первую" << endl; cout << "2. Во вторую" << endl; cout << "3. В третью" << endl; switch (Choice()) { case 1: Scene31(); break; case 2: Scene31(); break; case 3: Scene31(); break; } } void Scene29() { cout << "Ты спустился в люк и немного прошел по коридору, прежде чем встретил огромного тролля с дубиной" << endl << "Тролль стоит лицом к стене, так что он тебя сейчас точно не заметил" << endl; cout << "1. Тупо пройти мимо" << endl; cout << "2. Потроллить тролля" << endl; cout << "3. Проползти мимо тролля, как шпион" << endl; switch (Choice()) { case 1: Scene33(); break; case 2: Scene30(); break; case 3: Death16(); break; } } void Scene30() { cout << "\"Ахахахах, ну ты и дурачок, у вас в семье все такие же тупые?\"" << endl << "\"Особенно, я думаю, мама твоя.\" - на удивление членораздельно прорычал тролль" << endl; cout << "1. Эй, маму не трожь!" << endl; cout << "2. Ты себя-то видел, сверхразум?!?!" << endl; cout << "3. Проигнорить и пойти дальше" << endl; switch (Choice()) { case 1: subScene30_1(); break; case 2: subScene30_1(); break; case 3: Scene33(); break; } } void subScene30_1() { cout << "\"Ахахахаха, лох интернетный, что в реальной жизни ничего не можешь сделать?\"" << endl; cout << "1. Прекрати быстро!" << endl; cout << "2. Ну хватит уже!" << endl; cout << "3. Проигнорить и пойти дальше" << endl; switch (Choice()) { case 1: subScene30_2(); break; case 2: subScene30_2(); break; case 3: Scene33(); break; } } void subScene30_2() { cout << "\"Шо, обидна да? Обидна? даб даб даб я\"" << endl; cout << "1. Заплакать" << endl; cout << "2. Обозвать тролля всеми известными тебе ругательствами" << endl; cout << "3. Проигнорить и пойти дальше" << endl; switch (Choice()) { case 1: Death17(); break; case 2: Death17(); break; case 3: Scene33(); break; } } void Scene31() { cout << "Пройдя через дверь, ты заметил, что все три двери вели в одну комнату" << endl << "Это было сделано, чтобы продемонстрировать тебе иллюзию выбора в этой игре" << endl << "Посередине комнаты стоит компьютер, на нем горит надпись \"Выиграй!\"" << endl << "Сев за комп, ты понял что игра, где надо выиграть - это популярная нынче Си Эс Жо" << endl; cout << "1. Заюзать читы" << endl; cout << "2. Разнести всех тупа на скиллухе" << endl; cout << "3. Долбануть системник кулаком для лучшей работы" << endl; switch (Choice()) { case 1: Death18(); break; case 2: Scene32(); break; case 3: Death19(); break; } } void Scene32() { cout << "Ты тупа унизил всех и затащил игру" << endl << "Вдруг в стене открылась дверь на улицу, а на компе высветилась надпись:" << endl <<"\"Красава, я думаю, что теперь ты можешь быть свободным\"" << endl << "Что нужно сказать, когда прошел игру?" << endl; cout << "1. GGWP" << endl; cout << "2. Спасибо за игру" << endl; cout << "3. Ez" << endl; switch (Choice()) { case 1: void WinTheGame(); break; case 2: void WinTheGame(); break; case 3: void WinTheGame(); break; } } void Scene33() { cout << "Ты проигнорил тролля и прошел мимо" << endl << "Чуть дальше ты увидел камень с надписями, на нем написано:" << endl << "\"Радуйся ведь это последнее испытание. Тебе необходимо отгадать загадку" << endl << "Правила просты: угадаешь - выйдешь наружу, не угадаешь - умрешь" << endl << "Текст загадки: Что нужно делать, когда видишь зелёного человечка?\"" << endl; cout << "1. Бежать" << endl; cout << "2. Просить забрать тебя из России" << endl; cout << "3. Переходить дорогу" << endl; switch (Choice()) { case 1: Death20(); break; case 2: Death20(); break; case 3: WinTheGame(); break; } }
45,266
20,287
#include <UnitTest/UnitTest.hpp> #include <Euclid/Geometry/Axis.hpp> namespace Euclid { namespace Geometry { UnitTest::Suite AxisTestSuite { "Euclid::Geometry::Axis", {"Construction", [](UnitTest::Examiner & examiner) { auto a1 = Axis<RealT>{IDENTITY}; examiner << "Identity axis has zero translation." << std::endl; examiner.check(a1.translation().equivalent(0)); examiner << "Identity axis has zero rotation." << std::endl; examiner.check(a1.rotation().angle().equivalent(0_deg)); auto a2 = Axis<RealT>{{1, 2, 3}, rotate<Z>(R90)}; examiner << "Axis has correct translation." << std::endl; examiner.check(a2.translation().equivalent({1, 2, 3})); examiner << "Axis has correct rotation." << std::endl; examiner.check(a2.rotation().equivalent((Quat)rotate<Z>(R90))); // This transform should move any points from axis-space to origin-space auto p1 = a2.to_origin() * Vec3(1, 2, 3); /// This transform should move any points from origin-space to axis-space auto p2 = a2.from_origin() * Vec3(0); examiner << "Point is transformed to origin." << std::endl; examiner.check(p1.equivalent(0)); examiner << "Point is transformed from origin." << std::endl; examiner.check(p2.equivalent({1, 2, 3})); auto p3 = a2.to_origin() * Vec3(2, 2, 3); examiner << "Point is rotated correctly around Z." << std::endl; examiner.check(p3.equivalent({0, 1, 0})); } }, {"Axis-Axis Mating", [](UnitTest::Examiner & examiner) { auto a1 = Axis<RealT>({10, 10, 10}, IDENTITY); auto a2 = Axis<RealT>({-5, -5, -5}, rotate<Z>(R90)); auto m1 = a1.mate_with(a2); auto p1 = m1 * Vec3(10, 10, 10); examiner << "Point is translated." << std::endl; examiner.check(p1.equivalent({-5, -5, -5})); auto p2 = m1 * Vec3(10, 10, 15); examiner << "Point is translated." << std::endl; examiner.check(p2.equivalent({-5, -5, 0})); auto p3 = m1 * Vec3(10, 15, 10); examiner << "Point is translated and rotated." << std::endl; examiner.check(p3.equivalent({-10, -5, -5})); auto m2 = a1.mate_with(a2, translate(Vec3{1, 1, 1})); auto p4 = m2 * Vec3(10, 10, 10); examiner << "Point is transformed with intermediate translation." << std::endl; examiner.check(p4.equivalent({-6, -4, -4})); } }, }; } }
2,401
1,135
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/devices/testing/mock-ddk/mock-device.h" #include <zircon/syscalls/log.h> MockDevice::MockDevice(device_add_args_t* args, MockDevice* parent) : parent_(parent), ops_(args->ops), ctx_(args->ctx), name_(args->name) { if (args->proto_id && args->proto_ops) { AddProtocol(args->proto_id, args->proto_ops, ctx_); } } // static std::shared_ptr<MockDevice> MockDevice::FakeRootParent() { // Using `new` to access a non-public constructor. return std::shared_ptr<MockDevice>(new MockDevice()); } // Static member function. zx_status_t MockDevice::Create(device_add_args_t* args, MockDevice* parent, MockDevice** out_dev) { // We only check the minimum requirements to make sure the mock does not crash: if (!parent || !args || !args->name) { return ZX_ERR_INVALID_ARGS; } // Using `new` to access a non-public constructor. auto new_device = std::shared_ptr<MockDevice>(new MockDevice(args, parent)); *out_dev = new_device.get(); parent->children_.emplace_back(std::move(new_device)); // PropagateMetadata to last child: for (const auto& [key, value] : parent->metadata_) { parent->children().back()->metadata_[key] = value; } parent->children().back()->PropagateMetadata(); return ZX_OK; } MockDevice* MockDevice::GetLatestChild() { if (child_count()) { return children_.back().get(); } return nullptr; } // Templates that dispatch the protocol operations if they were set. // If they were not set, the second parameter is returned to the caller // (usually ZX_ERR_NOT_SUPPORTED) template <typename RetType, typename... ArgTypes> RetType Dispatch(void* ctx, RetType (*op)(void* ctx, ArgTypes...), RetType fallback, ArgTypes... args) { return op ? (*op)(ctx, args...) : fallback; } template <typename... ArgTypes> void Dispatch(void* ctx, void (*op)(void* ctx, ArgTypes...), ArgTypes... args) { if (op) { (*op)(ctx, args...); } } void MockDevice::InitOp() { Dispatch(ctx_, ops_->init); } zx_status_t MockDevice::OpenOp(zx_device_t** dev_out, uint32_t flags) { return Dispatch(ctx_, ops_->open, ZX_OK, dev_out, flags); } zx_status_t MockDevice::CloseOp(uint32_t flags) { return Dispatch(ctx_, ops_->close, ZX_OK, flags); } void MockDevice::UnbindOp() { Dispatch(ctx_, ops_->unbind); } void MockDevice::ReleaseOp() { Dispatch(ctx_, ops_->release); // Make parent release child now for (auto it = parent_->children_.begin(); it != parent_->children_.end(); ++it) { if (it->get() == this) { parent_->children_.erase(it); return; } } // Print error: we did not find ourselves! } MockDevice::~MockDevice() { while (!children_.empty()) { // This should remove the first child device from children_: children_.front()->ReleaseOp(); } } void MockDevice::SuspendNewOp(uint8_t requested_state, bool enable_wake, uint8_t suspend_reason) { Dispatch(ctx_, ops_->suspend, requested_state, enable_wake, suspend_reason); } zx_status_t MockDevice::SetPerformanceStateOp(uint32_t requested_state, uint32_t* out_state) { return Dispatch(ctx_, ops_->set_performance_state, ZX_ERR_NOT_SUPPORTED, requested_state, out_state); } zx_status_t MockDevice::ConfigureAutoSuspendOp(bool enable, uint8_t requested_state) { return Dispatch(ctx_, ops_->configure_auto_suspend, ZX_ERR_NOT_SUPPORTED, enable, requested_state); } void MockDevice::ResumeNewOp(uint32_t requested_state) { Dispatch(ctx_, ops_->resume, requested_state); } zx_status_t MockDevice::ReadOp(void* buf, size_t count, zx_off_t off, size_t* actual) { return Dispatch(ctx_, ops_->read, ZX_ERR_NOT_SUPPORTED, buf, count, off, actual); } zx_status_t MockDevice::WriteOp(const void* buf, size_t count, zx_off_t off, size_t* actual) { return Dispatch(ctx_, ops_->write, ZX_ERR_NOT_SUPPORTED, buf, count, off, actual); } zx_off_t MockDevice::GetSizeOp() { return Dispatch(ctx_, ops_->get_size, 0lu); } zx_status_t MockDevice::MessageOp(fidl_incoming_msg_t* msg, fidl_txn_t* txn) { return Dispatch(ctx_, ops_->message, ZX_ERR_NOT_SUPPORTED, msg, txn); } void MockDevice::ChildPreReleaseOp(void* child_ctx) { Dispatch(ctx_, ops_->child_pre_release, child_ctx); } void MockDevice::SetMetadata(uint32_t type, const void* data, size_t data_length) { metadata_[type] = std::make_pair(data, data_length); PropagateMetadata(); } zx_status_t MockDevice::GetMetadata(uint32_t type, void* buf, size_t buflen, size_t* actual) { auto itr = metadata_.find(type); if (itr != metadata_.end()) { auto [metadata, size] = itr->second; *actual = size; if (buflen < size) { return ZX_ERR_BUFFER_TOO_SMALL; } memcpy(buf, metadata, size); return ZX_OK; } return ZX_ERR_NOT_FOUND; } zx_status_t MockDevice::GetMetadataSize(uint32_t type, size_t* out_size) { auto itr = metadata_.find(type); if (itr != metadata_.end()) { auto [_, size] = itr->second; *out_size = size; return ZX_OK; } return ZX_ERR_BAD_STATE; } void MockDevice::PropagateMetadata() { for (auto& child : children_) { for (const auto& [key, value] : metadata_) { child->metadata_[key] = value; } child->PropagateMetadata(); } } void MockDevice::AddProtocol(uint32_t id, const void* ops, void* ctx) { protocols_.push_back(mock_ddk::ProtocolEntry{id, {ops, ctx}}); } void MockDevice::AddParentProtocol(uint32_t id, const void* ops, void* ctx) { if (!IsRootParent()) { parent_->AddProtocol(id, ops, ctx); } } void MockDevice::SetFirmware(std::vector<uint8_t> firmware, std::string_view path) { firmware_[path] = std::move(firmware); } void MockDevice::SetFirmware(std::string firmware, std::string_view path) { std::vector<uint8_t> vec(firmware.begin(), firmware.end()); SetFirmware(vec, path); } zx_status_t MockDevice::LoadFirmware(std::string_view path, zx_handle_t* fw, size_t* size) { auto firmware = firmware_.find(path); // If a match is not found to 'path', check if there is a firmware that was loaded with // path == nullptr: if (firmware == firmware_.end()) { firmware = firmware_.find(""); } if (firmware == firmware_.end()) { return ZX_ERR_NOT_FOUND; } zx_status_t status = ZX_OK; zx_handle_t vmo = ZX_HANDLE_INVALID; if ((status = zx_vmo_create(firmware->second.size(), 0, &vmo)) != ZX_OK) { return status; } if ((status = zx_vmo_write(vmo, firmware->second.data(), 0, firmware->second.size())) != ZX_OK) { return status; } *fw = vmo; *size = firmware->second.size(); return ZX_OK; } zx_status_t MockDevice::GetProtocol(uint32_t proto_id, void* protocol) const { auto out = reinterpret_cast<mock_ddk::Protocol*>(protocol); // First we check if the user has added protocols: for (const auto& proto : protocols_) { if (proto_id == proto.id) { out->ops = proto.proto.ops; out->ctx = proto.proto.ctx; return ZX_OK; } } return ZX_ERR_NOT_SUPPORTED; } size_t MockDevice::descendant_count() const { size_t count = child_count(); for (auto& child : children_) { count += child->descendant_count(); } return count; } // helper functions: namespace { zx_status_t ProcessDeviceRemoval(MockDevice* device) { device->UnbindOp(); // deleting children, so use a while loop: while (!device->children().empty()) { auto status = ProcessDeviceRemoval(device->children().back().get()); if (status != ZX_OK) { return status; } } if (device->HasUnbindOp()) { zx_status_t status = device->WaitUntilUnbindReplyCalled(); if (status != ZX_OK) { return status; } } device->ReleaseOp(); return ZX_OK; } } // anonymous namespace zx_status_t mock_ddk::ReleaseFlaggedDevices(MockDevice* device) { if (device->AsyncRemoveCalled()) { return ProcessDeviceRemoval(device); } // Make a vector of the child device pointers, because we might delete the child: std::vector<MockDevice*> children; std::transform(device->children().begin(), device->children().end(), std::back_inserter(children), [](std::shared_ptr<MockDevice> c) -> MockDevice* { return c.get(); }); for (auto child : children) { auto ret = ReleaseFlaggedDevices(child); if (ret != ZX_OK) { return ret; } } return ZX_OK; }
8,428
3,037
#include "Controller.hpp" #include "Transform.hpp" #include "Window.hpp" Controller::Controller(Engine& engine) : _engine(engine), _possessed(engine) { SYSFUNC_ENABLE(SystemInterface, update, 0); SYSFUNC_ENABLE(SystemInterface, cursorPosition, 0); SYSFUNC_ENABLE(SystemInterface, keyInput, 0); SYSFUNC_ENABLE(SystemInterface, cursorEnter, 0); SYSFUNC_ENABLE(SystemInterface, mousePress, 0); SYSFUNC_ENABLE(SystemInterface, windowOpen, 0); SYSFUNC_ENABLE(SystemInterface, scrollWheel, 0); assert(_engine.hasSystem<Window>()); } void Controller::update(double dt) { Transform* transform = nullptr; if (_possessed.valid()) transform = _possessed.get<Transform>(); if (transform && _locked) { transform->globalRotate(glm::quat({ 0.0, 0.0, -_dMousePos.x * dt })); transform->localRotate(glm::quat({ -_dMousePos.y * dt, 0.0, 0.0 })); float moveSpeed = 300.f * dt; if (_boost) moveSpeed = 1000.f * dt; transform->localTranslate(glm::vec3(0.f, 0.f, -_flash * 100.f)); if (_forward) transform->localTranslate(Transform::localForward * (float)moveSpeed); if (_back) transform->localTranslate(Transform::localBack * (float)moveSpeed); if (_left) transform->localTranslate(Transform::localLeft * (float)moveSpeed); if (_right) transform->localTranslate(Transform::localRight * (float)moveSpeed); if (_up) transform->globalTranslate(Transform::globalUp * (float)moveSpeed); if (_down) transform->globalTranslate(Transform::globalDown * (float)moveSpeed); } _flash = 0; _dMousePos = { 0.0, 0.0 }; } void Controller::cursorPosition(glm::dvec2 position){ /* glm::vec2 newMousePos = position; if (_mousePos == glm::vec2(0.0, 0.0)) _mousePos = newMousePos; _dMousePos = newMousePos - _mousePos; _mousePos = newMousePos; */ _dMousePos = position; } void Controller::keyInput(uint32_t key, Action action, uint8_t mods){ if (action == Action::Release && key == Key::Key_Escape) { if (_locked) { _engine.system<Window>().setLockedCursor(false); _locked = false; } else if (!_locked) { _engine.quit(); } return; } if (!_possessed.valid()) return; bool value; if (action == Action::Press) value = true; else if (action == Action::Release) value = false; else return; switch (key) { case Key::Key_W: _forward = value; return; case Key::Key_S: _back = value; return; case Key::Key_A: _left = value; return; case Key::Key_D: _right = value; return; case Key::Key_Space: _up = value; return; case Key::Key_LCtrl: _down = value; return; case Key::Key_LShift: _boost = value; return; } } void Controller::cursorEnter(bool enterered) { _cursorInside = enterered; } void Controller::mousePress(uint32_t button, Action action, uint8_t mods) { if (action == Action::Release && !_locked && _cursorInside) { _engine.system<Window>().setLockedCursor(true); _locked = true; } } void Controller::windowOpen(bool opened){ if (!opened) _engine.quit(); } void Controller::scrollWheel(glm::dvec2 offset){ _flash += (float)offset.y; } void Controller::setPossessed(uint64_t id) { _possessed.set(id); }
3,136
1,254
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/render_text.h" #include <algorithm> #include "base/debug/trace_event.h" #include "base/i18n/break_iterator.h" #include "base/logging.h" #include "base/stl_util.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkTypeface.h" #include "third_party/skia/include/effects/SkBlurMaskFilter.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "third_party/skia/include/effects/SkLayerDrawLooper.h" #include "ui/base/text/utf16_indexing.h" #include "ui/gfx/canvas.h" #include "ui/gfx/insets.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/shadow_value.h" namespace { // All chars are replaced by this char when the password style is set. // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*' // that's available in the font (find_invisible_char() in gtkentry.c). const char16 kPasswordReplacementChar = '*'; // Default color used for the cursor. const SkColor kDefaultCursorColor = SK_ColorBLACK; // Default color used for drawing selection text. const SkColor kDefaultSelectionColor = SK_ColorBLACK; // Default color used for drawing selection background. const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY; #ifndef NDEBUG // Check StyleRanges invariant conditions: sorted and non-overlapping ranges. void CheckStyleRanges(const gfx::StyleRanges& style_ranges, size_t length) { if (length == 0) { DCHECK(style_ranges.empty()) << "Style ranges exist for empty text."; return; } for (gfx::StyleRanges::size_type i = 0; i < style_ranges.size() - 1; i++) { const ui::Range& former = style_ranges[i].range; const ui::Range& latter = style_ranges[i + 1].range; DCHECK(!former.is_empty()) << "Empty range at " << i << ":" << former; DCHECK(former.IsValid()) << "Invalid range at " << i << ":" << former; DCHECK(!former.is_reversed()) << "Reversed range at " << i << ":" << former; DCHECK(former.end() == latter.start()) << "Ranges gap/overlap/unsorted." << "former:" << former << ", latter:" << latter; } const gfx::StyleRange& end_style = *style_ranges.rbegin(); DCHECK(!end_style.range.is_empty()) << "Empty range at end."; DCHECK(end_style.range.IsValid()) << "Invalid range at end."; DCHECK(!end_style.range.is_reversed()) << "Reversed range at end."; DCHECK(end_style.range.end() == length) << "Style and text length mismatch."; } #endif void ApplyStyleRangeImpl(gfx::StyleRanges* style_ranges, const gfx::StyleRange& style_range) { const ui::Range& new_range = style_range.range; // Follow StyleRanges invariant conditions: sorted and non-overlapping ranges. gfx::StyleRanges::iterator i; for (i = style_ranges->begin(); i != style_ranges->end();) { if (i->range.end() < new_range.start()) { i++; } else if (i->range.start() == new_range.end()) { break; } else if (new_range.Contains(i->range)) { i = style_ranges->erase(i); if (i == style_ranges->end()) break; } else if (i->range.start() < new_range.start() && i->range.end() > new_range.end()) { // Split the current style into two styles. gfx::StyleRange split_style = gfx::StyleRange(*i); split_style.range.set_end(new_range.start()); i = style_ranges->insert(i, split_style) + 1; i->range.set_start(new_range.end()); break; } else if (i->range.start() < new_range.start()) { i->range.set_end(new_range.start()); i++; } else if (i->range.end() > new_range.end()) { i->range.set_start(new_range.end()); break; } else { NOTREACHED(); } } // Add the new range in its sorted location. style_ranges->insert(i, style_range); } // Converts |gfx::Font::FontStyle| flags to |SkTypeface::Style| flags. SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) { int skia_style = SkTypeface::kNormal; if (font_style & gfx::Font::BOLD) skia_style |= SkTypeface::kBold; if (font_style & gfx::Font::ITALIC) skia_style |= SkTypeface::kItalic; return static_cast<SkTypeface::Style>(skia_style); } // Given |font| and |display_width|, returns the width of the fade gradient. int CalculateFadeGradientWidth(const gfx::Font& font, int display_width) { // Fade in/out about 2.5 characters of the beginning/end of the string. // The .5 here is helpful if one of the characters is a space. // Use a quarter of the display width if the display width is very short. const int average_character_width = font.GetAverageCharacterWidth(); const double gradient_width = std::min(average_character_width * 2.5, display_width / 4.0); DCHECK_GE(gradient_width, 0.0); return static_cast<int>(floor(gradient_width + 0.5)); } // Appends to |positions| and |colors| values corresponding to the fade over // |fade_rect| from color |c0| to color |c1|. void AddFadeEffect(const gfx::Rect& text_rect, const gfx::Rect& fade_rect, SkColor c0, SkColor c1, std::vector<SkScalar>* positions, std::vector<SkColor>* colors) { const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x()); const SkScalar width = static_cast<SkScalar>(fade_rect.width()); const SkScalar p0 = left / text_rect.width(); const SkScalar p1 = (left + width) / text_rect.width(); // Prepend 0.0 to |positions|, as required by Skia. if (positions->empty() && p0 != 0.0) { positions->push_back(0.0); colors->push_back(c0); } positions->push_back(p0); colors->push_back(c0); positions->push_back(p1); colors->push_back(c1); } // Creates a SkShader to fade the text, with |left_part| specifying the left // fade effect, if any, and |right_part| specifying the right fade effect. SkShader* CreateFadeShader(const gfx::Rect& text_rect, const gfx::Rect& left_part, const gfx::Rect& right_part, SkColor color) { // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color. const SkColor fade_color = SkColorSetA(color, 51); std::vector<SkScalar> positions; std::vector<SkColor> colors; if (!left_part.IsEmpty()) AddFadeEffect(text_rect, left_part, fade_color, color, &positions, &colors); if (!right_part.IsEmpty()) AddFadeEffect(text_rect, right_part, color, fade_color, &positions, &colors); DCHECK(!positions.empty()); // Terminate |positions| with 1.0, as required by Skia. if (positions.back() != 1.0) { positions.push_back(1.0); colors.push_back(colors.back()); } SkPoint points[2]; points[0].iset(text_rect.x(), text_rect.y()); points[1].iset(text_rect.right(), text_rect.y()); return SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0], colors.size(), SkShader::kClamp_TileMode); } } // namespace namespace gfx { namespace internal { SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas) : canvas_skia_(canvas->sk_canvas()), started_drawing_(false) { DCHECK(canvas_skia_); paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint_.setStyle(SkPaint::kFill_Style); paint_.setAntiAlias(true); paint_.setSubpixelText(true); paint_.setLCDRenderText(true); bounds_.setEmpty(); } SkiaTextRenderer::~SkiaTextRenderer() { // Work-around for http://crbug.com/122743, where non-ClearType text is // rendered with incorrect gamma when using the fade shader. Draw the text // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode. // // TODO(asvitkine): Remove this work-around once the Skia bug is fixed. // http://code.google.com/p/skia/issues/detail?id=590 if (deferred_fade_shader_.get()) { paint_.setShader(deferred_fade_shader_.get()); paint_.setXfermodeMode(SkXfermode::kDstIn_Mode); canvas_skia_->drawRect(bounds_, paint_); canvas_skia_->restore(); } } void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) { paint_.setLooper(draw_looper); } void SkiaTextRenderer::SetFontSmoothingSettings(bool enable_smoothing, bool enable_lcd_text) { paint_.setAntiAlias(enable_smoothing); paint_.setSubpixelText(enable_smoothing); paint_.setLCDRenderText(enable_lcd_text); } void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) { paint_.setTypeface(typeface); } void SkiaTextRenderer::SetTextSize(int size) { paint_.setTextSize(size); } void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family, int style) { DCHECK(!family.empty()); SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style); SkTypeface* typeface = SkTypeface::CreateFromName(family.c_str(), skia_style); SkAutoUnref auto_unref(typeface); if (typeface) { // |paint_| adds its own ref. So don't |release()| it from the ref ptr here. SetTypeface(typeface); // Enable fake bold text if bold style is needed but new typeface does not // have it. paint_.setFakeBoldText((skia_style & SkTypeface::kBold) && !typeface->isBold()); } } void SkiaTextRenderer::SetForegroundColor(SkColor foreground) { paint_.setColor(foreground); } void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) { bounds_ = RectToSkRect(bounds); paint_.setShader(shader); } void SkiaTextRenderer::DrawPosText(const SkPoint* pos, const uint16* glyphs, size_t glyph_count) { if (!started_drawing_) { started_drawing_ = true; // Work-around for http://crbug.com/122743, where non-ClearType text is // rendered with incorrect gamma when using the fade shader. Draw the text // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode. // // Skip this when there is a looper which seems not working well with // deferred paint. Currently a looper is only used for text shadows. // // TODO(asvitkine): Remove this work-around once the Skia bug is fixed. // http://code.google.com/p/skia/issues/detail?id=590 if (!paint_.isLCDRenderText() && paint_.getShader() && !paint_.getLooper()) { deferred_fade_shader_ = paint_.getShader(); paint_.setShader(NULL); canvas_skia_->saveLayer(&bounds_, NULL); } } const size_t byte_length = glyph_count * sizeof(glyphs[0]); canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_); } // Draw underline and strike through text decorations. // Based on |SkCanvas::DrawTextDecorations()| and constants from: // third_party/skia/src/core/SkTextFormatParams.h void SkiaTextRenderer::DrawDecorations(int x, int y, int width, const StyleRange& style) { if (!style.underline && !style.strike && !style.diagonal_strike) return; // Fraction of the text size to lower a strike through below the baseline. const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21); // Fraction of the text size to lower an underline below the baseline. const SkScalar kUnderlineOffset = (SK_Scalar1 / 9); // Fraction of the text size to use for a strike through or under-line. const SkScalar kLineThickness = (SK_Scalar1 / 18); // Fraction of the text size to use for a top margin of a diagonal strike. const SkScalar kDiagonalStrikeThroughMarginOffset = (SK_Scalar1 / 4); SkScalar text_size = paint_.getTextSize(); SkScalar height = SkScalarMul(text_size, kLineThickness); SkRect r; r.fLeft = x; r.fRight = x + width; if (style.underline) { SkScalar offset = SkScalarMulAdd(text_size, kUnderlineOffset, y); r.fTop = offset; r.fBottom = offset + height; canvas_skia_->drawRect(r, paint_); } if (style.strike) { SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y); r.fTop = offset; r.fBottom = offset + height; canvas_skia_->drawRect(r, paint_); } if (style.diagonal_strike) { SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeThroughMarginOffset); SkPaint paint(paint_); paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setStrokeWidth(height); canvas_skia_->drawLine( SkIntToScalar(x), SkIntToScalar(y) - text_size + offset, SkIntToScalar(x + width), SkIntToScalar(y), paint); } } } // namespace internal StyleRange::StyleRange() : foreground(SK_ColorBLACK), font_style(gfx::Font::NORMAL), strike(false), diagonal_strike(false), underline(false) { } RenderText::~RenderText() { } void RenderText::SetText(const string16& text) { DCHECK(!composition_range_.IsValid()); size_t old_text_length = text_.length(); text_ = text; // Update the style ranges as needed. if (text_.empty()) { style_ranges_.clear(); } else if (style_ranges_.empty()) { ApplyDefaultStyle(); } else if (text_.length() > old_text_length) { style_ranges_.back().range.set_end(text_.length()); } else if (text_.length() < old_text_length) { StyleRanges::iterator i; for (i = style_ranges_.begin(); i != style_ranges_.end(); i++) { if (i->range.start() >= text_.length()) { // Style ranges are sorted and non-overlapping, so all the subsequent // style ranges should be out of text_.length() as well. style_ranges_.erase(i, style_ranges_.end()); break; } } // Since style ranges are sorted and non-overlapping, if there is a style // range ends beyond text_.length, it must be the last one. style_ranges_.back().range.set_end(text_.length()); } #ifndef NDEBUG CheckStyleRanges(style_ranges_, text_.length()); #endif cached_bounds_and_offset_valid_ = false; // Reset selection model. SetText should always followed by SetSelectionModel // or SetCursorPosition in upper layer. SetSelectionModel(SelectionModel()); ResetLayout(); } void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) { if (horizontal_alignment_ != alignment) { horizontal_alignment_ = alignment; display_offset_ = Point(); cached_bounds_and_offset_valid_ = false; } } void RenderText::SetFontList(const FontList& font_list) { font_list_ = font_list; cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::SetFontSize(int size) { font_list_ = font_list_.DeriveFontListWithSize(size); cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::SetCursorEnabled(bool cursor_enabled) { cursor_enabled_ = cursor_enabled; cached_bounds_and_offset_valid_ = false; } const Font& RenderText::GetFont() const { return font_list_.GetFonts()[0]; } void RenderText::ToggleInsertMode() { insert_mode_ = !insert_mode_; cached_bounds_and_offset_valid_ = false; } void RenderText::SetObscured(bool obscured) { if (obscured != obscured_) { obscured_ = obscured; cached_bounds_and_offset_valid_ = false; ResetLayout(); } } void RenderText::SetDisplayRect(const Rect& r) { if (r.width() != display_rect_.width()) ResetLayout(); display_rect_ = r; cached_bounds_and_offset_valid_ = false; } void RenderText::SetCursorPosition(size_t position) { MoveCursorTo(position, false); } void RenderText::MoveCursor(BreakType break_type, VisualCursorDirection direction, bool select) { SelectionModel position(cursor_position(), selection_model_.caret_affinity()); // Cancelling a selection moves to the edge of the selection. if (break_type != LINE_BREAK && !selection().is_empty() && !select) { SelectionModel selection_start = GetSelectionModelForSelectionStart(); int start_x = GetCursorBounds(selection_start, true).x(); int cursor_x = GetCursorBounds(position, true).x(); // Use the selection start if it is left (when |direction| is CURSOR_LEFT) // or right (when |direction| is CURSOR_RIGHT) of the selection end. if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x) position = selection_start; // For word breaks, use the nearest word boundary in the appropriate // |direction|. if (break_type == WORD_BREAK) position = GetAdjacentSelectionModel(position, break_type, direction); } else { position = GetAdjacentSelectionModel(position, break_type, direction); } if (select) position.set_selection_start(selection().start()); MoveCursorTo(position); } bool RenderText::MoveCursorTo(const SelectionModel& model) { // Enforce valid selection model components. size_t text_length = text().length(); ui::Range range(std::min(model.selection().start(), text_length), std::min(model.caret_pos(), text_length)); // The current model only supports caret positions at valid character indices. if (!IsCursorablePosition(range.start()) || !IsCursorablePosition(range.end())) return false; SelectionModel sel(range, model.caret_affinity()); bool changed = sel != selection_model_; SetSelectionModel(sel); return changed; } bool RenderText::MoveCursorTo(const Point& point, bool select) { SelectionModel position = FindCursorPosition(point); if (select) position.set_selection_start(selection().start()); return MoveCursorTo(position); } bool RenderText::SelectRange(const ui::Range& range) { ui::Range sel(std::min(range.start(), text().length()), std::min(range.end(), text().length())); if (!IsCursorablePosition(sel.start()) || !IsCursorablePosition(sel.end())) return false; LogicalCursorDirection affinity = (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD; SetSelectionModel(SelectionModel(sel, affinity)); return true; } bool RenderText::IsPointInSelection(const Point& point) { if (selection().is_empty()) return false; SelectionModel cursor = FindCursorPosition(point); return RangeContainsCaret( selection(), cursor.caret_pos(), cursor.caret_affinity()); } void RenderText::ClearSelection() { SetSelectionModel(SelectionModel(cursor_position(), selection_model_.caret_affinity())); } void RenderText::SelectAll() { SelectionModel all; if (GetTextDirection() == base::i18n::LEFT_TO_RIGHT) all = SelectionModel(ui::Range(0, text().length()), CURSOR_FORWARD); else all = SelectionModel(ui::Range(text().length(), 0), CURSOR_BACKWARD); SetSelectionModel(all); } void RenderText::SelectWord() { if (obscured_) { SelectAll(); return; } size_t cursor_pos = cursor_position(); //base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); //bool success = iter.Init(); //DCHECK(success); //if (!success) // return; size_t selection_start = cursor_pos; //for (; selection_start != 0; --selection_start) { // if (iter.IsStartOfWord(selection_start) || // iter.IsEndOfWord(selection_start)) // break; //} //if (selection_start == cursor_pos) // ++cursor_pos; //for (; cursor_pos < text().length(); ++cursor_pos) // if (iter.IsEndOfWord(cursor_pos) || iter.IsStartOfWord(cursor_pos)) // break; MoveCursorTo(selection_start, false); MoveCursorTo(cursor_pos, true); } const ui::Range& RenderText::GetCompositionRange() const { return composition_range_; } void RenderText::SetCompositionRange(const ui::Range& composition_range) { CHECK(!composition_range.IsValid() || ui::Range(0, text_.length()).Contains(composition_range)); composition_range_.set_end(composition_range.end()); composition_range_.set_start(composition_range.start()); ResetLayout(); } void RenderText::ApplyStyleRange(const StyleRange& style_range) { const ui::Range& new_range = style_range.range; if (!new_range.IsValid() || new_range.is_empty()) return; CHECK(!new_range.is_reversed()); CHECK(ui::Range(0, text_.length()).Contains(new_range)); ApplyStyleRangeImpl(&style_ranges_, style_range); #ifndef NDEBUG CheckStyleRanges(style_ranges_, text_.length()); #endif // TODO(xji): only invalidate if font or underline changes. cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::ApplyDefaultStyle() { style_ranges_.clear(); StyleRange style = StyleRange(default_style_); style.range.set_end(text_.length()); style_ranges_.push_back(style); cached_bounds_and_offset_valid_ = false; ResetLayout(); } VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() { return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ? CURSOR_RIGHT : CURSOR_LEFT; } void RenderText::Draw(Canvas* canvas) { TRACE_EVENT0("gfx", "RenderText::Draw"); { TRACE_EVENT0("gfx", "RenderText::EnsureLayout"); EnsureLayout(); } gfx::Rect clip_rect(display_rect()); clip_rect.Inset(ShadowValue::GetMargin(text_shadows_)); canvas->Save(); canvas->ClipRect(clip_rect); if (!text().empty()) DrawSelection(canvas); DrawCursor(canvas); if (!text().empty()) { TRACE_EVENT0("gfx", "RenderText::Draw draw text"); DrawVisualText(canvas); } canvas->Restore(); } Rect RenderText::GetCursorBounds(const SelectionModel& caret, bool insert_mode) { EnsureLayout(); size_t caret_pos = caret.caret_pos(); // In overtype mode, ignore the affinity and always indicate that we will // overtype the next character. LogicalCursorDirection caret_affinity = insert_mode ? caret.caret_affinity() : CURSOR_FORWARD; int x = 0, width = 0, height = 0; if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) { // The caret is attached to the boundary. Always return a zero-width caret, // since there is nothing to overtype. Size size = GetStringSize(); if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0)) x = size.width(); height = size.height(); } else { size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ? caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD); ui::Range xspan; GetGlyphBounds(grapheme_start, &xspan, &height); if (insert_mode) { x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start(); } else { // overtype mode x = xspan.GetMin(); width = xspan.length(); } } height = std::min(height, display_rect().height()); int y = (display_rect().height() - height) / 2; return Rect(ToViewPoint(Point(x, y)), Size(width, height)); } const Rect& RenderText::GetUpdatedCursorBounds() { UpdateCachedBoundsAndOffset(); return cursor_bounds_; } size_t RenderText::IndexOfAdjacentGrapheme(size_t index, LogicalCursorDirection direction) { if (index > text().length()) return text().length(); EnsureLayout(); if (direction == CURSOR_FORWARD) { while (index < text().length()) { index++; if (IsCursorablePosition(index)) return index; } return text().length(); } while (index > 0) { index--; if (IsCursorablePosition(index)) return index; } return 0; } SelectionModel RenderText::GetSelectionModelForSelectionStart() { const ui::Range& sel = selection(); if (sel.is_empty()) return selection_model_; return SelectionModel(sel.start(), sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD); } void RenderText::SetTextShadows(const std::vector<ShadowValue>& shadows) { text_shadows_ = shadows; } RenderText::RenderText() : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT), cursor_enabled_(true), cursor_visible_(false), insert_mode_(true), cursor_color_(kDefaultCursorColor), selection_color_(kDefaultSelectionColor), selection_background_focused_color_(kDefaultSelectionBackgroundColor), selection_background_unfocused_color_(kDefaultSelectionBackgroundColor), focused_(false), composition_range_(ui::Range::InvalidRange()), obscured_(false), fade_head_(false), fade_tail_(false), background_is_transparent_(false), cached_bounds_and_offset_valid_(false) { } const Point& RenderText::GetUpdatedDisplayOffset() { UpdateCachedBoundsAndOffset(); return display_offset_; } SelectionModel RenderText::GetAdjacentSelectionModel( const SelectionModel& current, BreakType break_type, VisualCursorDirection direction) { EnsureLayout(); if (break_type == LINE_BREAK || text().empty()) return EdgeSelectionModel(direction); if (break_type == CHARACTER_BREAK) return AdjacentCharSelectionModel(current, direction); DCHECK(break_type == WORD_BREAK); return AdjacentWordSelectionModel(current, direction); } SelectionModel RenderText::EdgeSelectionModel( VisualCursorDirection direction) { if (direction == GetVisualDirectionOfLogicalEnd()) return SelectionModel(text().length(), CURSOR_FORWARD); return SelectionModel(0, CURSOR_BACKWARD); } void RenderText::SetSelectionModel(const SelectionModel& model) { DCHECK_LE(model.selection().GetMax(), text().length()); selection_model_ = model; cached_bounds_and_offset_valid_ = false; } string16 RenderText::GetDisplayText() const { if (!obscured_) return text_; size_t obscured_text_length = static_cast<size_t>(ui::UTF16IndexToOffset(text_, 0, text_.length())); return string16(obscured_text_length, kPasswordReplacementChar); } void RenderText::ApplyCompositionAndSelectionStyles( StyleRanges* style_ranges) { // TODO(msw): This pattern ought to be reconsidered; what about composition // and selection overlaps, retain existing local style features? // Apply a composition style override to a copy of the style ranges. if (composition_range_.IsValid() && !composition_range_.is_empty()) { StyleRange composition_style(default_style_); composition_style.underline = true; composition_style.range = composition_range_; ApplyStyleRangeImpl(style_ranges, composition_style); } // Apply a selection style override to a copy of the style ranges. if (!selection().is_empty()) { StyleRange selection_style(default_style_); selection_style.foreground = selection_color_; selection_style.range = ui::Range(selection().GetMin(), selection().GetMax()); ApplyStyleRangeImpl(style_ranges, selection_style); } // Apply replacement-mode style override to a copy of the style ranges. // // TODO(xji): NEED TO FIX FOR WINDOWS ASAP. Windows call this function (to // apply styles) in ItemizeLogicalText(). In order for the cursor's underline // character to be drawn correctly, we will need to re-layout the text. It's // not practical to do layout on every cursor blink. We need to fix Windows // port to apply styles during drawing phase like Linux port does. // http://crbug.com/110109 if (!insert_mode_ && cursor_visible() && focused()) { StyleRange replacement_mode_style(default_style_); replacement_mode_style.foreground = selection_color_; size_t cursor = cursor_position(); replacement_mode_style.range.set_start(cursor); replacement_mode_style.range.set_end( IndexOfAdjacentGrapheme(cursor, CURSOR_FORWARD)); ApplyStyleRangeImpl(style_ranges, replacement_mode_style); } } Point RenderText::GetTextOrigin() { Point origin = display_rect().origin(); origin = origin.Add(GetUpdatedDisplayOffset()); origin = origin.Add(GetAlignmentOffset()); return origin; } Point RenderText::ToTextPoint(const Point& point) { return point.Subtract(GetTextOrigin()); } Point RenderText::ToViewPoint(const Point& point) { return point.Add(GetTextOrigin()); } int RenderText::GetContentWidth() { return GetStringSize().width() + (cursor_enabled_ ? 1 : 0); } Point RenderText::GetAlignmentOffset() { if (horizontal_alignment() != ALIGN_LEFT) { int x_offset = display_rect().width() - GetContentWidth(); if (horizontal_alignment() == ALIGN_CENTER) x_offset /= 2; return Point(x_offset, 0); } return Point(); } Point RenderText::GetOriginForDrawing() { Point origin(GetTextOrigin()); const int height = GetStringSize().height(); DCHECK_LE(height, display_rect().height()); // Center the text vertically in the display area. origin.Offset(0, (display_rect().height() - height) / 2); return origin; } void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) { if (!fade_head() && !fade_tail()) return; const int text_width = GetStringSize().width(); const int display_width = display_rect().width(); // If the text fits as-is, no need to fade. if (text_width <= display_width) return; int gradient_width = CalculateFadeGradientWidth(GetFont(), display_width); if (gradient_width == 0) return; bool fade_left = fade_head(); bool fade_right = fade_tail(); // Under RTL, |fade_right| == |fade_head|. if (GetTextDirection() == base::i18n::RIGHT_TO_LEFT) std::swap(fade_left, fade_right); gfx::Rect solid_part = display_rect(); gfx::Rect left_part; gfx::Rect right_part; if (fade_left) { left_part = solid_part; left_part.Inset(0, 0, solid_part.width() - gradient_width, 0); solid_part.Inset(gradient_width, 0, 0, 0); } if (fade_right) { right_part = solid_part; right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0); solid_part.Inset(0, 0, gradient_width, 0); } gfx::Rect text_rect = display_rect(); text_rect.Inset(GetAlignmentOffset().x(), 0, 0, 0); const SkColor color = default_style().foreground; SkShader* shader = CreateFadeShader(text_rect, left_part, right_part, color); SkAutoUnref auto_unref(shader); if (shader) { // |renderer| adds its own ref. So don't |release()| it from the ref ptr. renderer->SetShader(shader, display_rect()); } } void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) { if (text_shadows_.empty()) { renderer->SetDrawLooper(NULL); return; } SkLayerDrawLooper* looper = new SkLayerDrawLooper; SkAutoUnref auto_unref(looper); looper->addLayer(); // top layer of the original. SkLayerDrawLooper::LayerInfo layer_info; layer_info.fPaintBits |= SkLayerDrawLooper::kMaskFilter_Bit; layer_info.fPaintBits |= SkLayerDrawLooper::kColorFilter_Bit; layer_info.fColorMode = SkXfermode::kSrc_Mode; for (size_t i = 0; i < text_shadows_.size(); ++i) { const ShadowValue& shadow = text_shadows_[i]; layer_info.fOffset.set(SkIntToScalar(shadow.x()), SkIntToScalar(shadow.y())); // SkBlurMaskFilter's blur radius defines the range to extend the blur from // original mask, which is half of blur amount as defined in ShadowValue. SkMaskFilter* blur_mask = SkBlurMaskFilter::Create( SkDoubleToScalar(shadow.blur() / 2), SkBlurMaskFilter::kNormal_BlurStyle, SkBlurMaskFilter::kHighQuality_BlurFlag); SkColorFilter* color_filter = SkColorFilter::CreateModeFilter( shadow.color(), SkXfermode::kSrcIn_Mode); SkPaint* paint = looper->addLayer(layer_info); SkSafeUnref(paint->setMaskFilter(blur_mask)); SkSafeUnref(paint->setColorFilter(color_filter)); } renderer->SetDrawLooper(looper); } // static bool RenderText::RangeContainsCaret(const ui::Range& range, size_t caret_pos, LogicalCursorDirection caret_affinity) { // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9). size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ? caret_pos - 1 : caret_pos + 1; return range.Contains(ui::Range(caret_pos, adjacent)); } void RenderText::MoveCursorTo(size_t position, bool select) { size_t cursor = std::min(position, text().length()); if (IsCursorablePosition(cursor)) SetSelectionModel(SelectionModel( ui::Range(select ? selection().start() : cursor, cursor), (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD)); } void RenderText::UpdateCachedBoundsAndOffset() { if (cached_bounds_and_offset_valid_) return; // First, set the valid flag true to calculate the current cursor bounds using // the stale |display_offset_|. Applying |delta_offset| at the end of this // function will set |cursor_bounds_| and |display_offset_| to correct values. cached_bounds_and_offset_valid_ = true; cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_); // Update |display_offset_| to ensure the current cursor is visible. const int display_width = display_rect_.width(); const int content_width = GetContentWidth(); int delta_offset = 0; if (content_width <= display_width || !cursor_enabled()) { // Don't pan if the text fits in the display width or when the cursor is // disabled. delta_offset = -display_offset_.x(); } else if (cursor_bounds_.right() >= display_rect_.right()) { // TODO(xji): when the character overflow is a RTL character, currently, if // we pan cursor at the rightmost position, the entered RTL character is not // displayed. Should pan cursor to show the last logical characters. // // Pan to show the cursor when it overflows to the right, delta_offset = display_rect_.right() - cursor_bounds_.right() - 1; } else if (cursor_bounds_.x() < display_rect_.x()) { // TODO(xji): have similar problem as above when overflow character is a // LTR character. // // Pan to show the cursor when it overflows to the left. delta_offset = display_rect_.x() - cursor_bounds_.x(); } else if (display_offset_.x() != 0) { // Reduce the pan offset to show additional overflow text when the display // width increases. const int negate_rtl = horizontal_alignment_ == ALIGN_RIGHT ? -1 : 1; const int offset = negate_rtl * display_offset_.x(); if (display_width > (content_width + offset)) delta_offset = negate_rtl * (display_width - (content_width + offset)); } display_offset_.Offset(delta_offset, 0); cursor_bounds_.Offset(delta_offset, 0); } void RenderText::DrawSelection(Canvas* canvas) { const SkColor color = focused() ? selection_background_focused_color_ : selection_background_unfocused_color_; const std::vector<Rect> sel = GetSubstringBounds(selection()); for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i) canvas->FillRect(*i, color); } void RenderText::DrawCursor(Canvas* canvas) { // Paint cursor. Replace cursor is drawn as rectangle for now. // TODO(msw): Draw a better cursor with a better indication of association. if (cursor_enabled() && cursor_visible() && focused()) { const Rect& bounds = GetUpdatedCursorBounds(); if (bounds.width() != 0) canvas->FillRect(bounds, cursor_color_); else canvas->DrawRect(bounds, cursor_color_); } } } // namespace gfx
35,240
11,571
// $Id: SSL_Asynch_Stream_Test.cpp 90163 2010-05-18 21:42:20Z mitza $ // ============================================================================ // // = LIBRARY // tests/SSL // // = FILENAME // SSL_Asynch_Stream_Test.cpp // // = DESCRIPTION // This program is a functionality test of ACE_SSL_Asynch_Stream. // It demonstrates one proper use case of ACE_SSL_Asynch_Stream in the // Proactor framework and validates its basic functionality. // // Usage: SSL_Asynch_Stream_Test [-r <hostname:port#>] // [-t <num threads>] [-d <delay>] // [-i <client conn attempt#>] [-n <client request# per conn>] // // Default value: // <hostname:port#>: ACE_DEFAULT_SERVER_HOST:ACE_DEFAULT_PORT // <num threads>: ACE_MAX_THREADS // <client conn attempt#>: ACE_MAX_ITERATIONS // <client req# per conn>: 20 // <delay>: 0 usec // // = AUTHOR // Steve Huston <shuston@riverace.com> // // ============================================================================ #include "../test_config.h" #include "ace/Default_Constants.h" #include "ace/OS_NS_signal.h" #include "ace/OS_NS_string.h" #include "ace/Event_Handler.h" #include "ace/Get_Opt.h" #include "ace/Proactor.h" #include "ace/Reactor.h" #include "ace/Thread_Manager.h" #include "ace/INET_Addr.h" #include "ace/SSL/SSL_Asynch_Stream.h" #include "ace/SSL/SSL_SOCK_Connector.h" #include "ace/SSL/SSL_SOCK_Acceptor.h" #include "ace/SSL/SSL_SOCK_Stream.h" ACE_RCSID(tests, SSL_Asynch_Stream_Test, "$Id: SSL_Asynch_Stream_Test.cpp 90163 2010-05-18 21:42:20Z mitza $") #if defined (ACE_HAS_THREADS) && ((defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) || (defined (ACE_HAS_AIO_CALLS))) // This only works on Win32 platforms and on Unix platforms // supporting POSIX aio calls. class Client_Handler : public ACE_Handler { public: Client_Handler () : msgs_sent_ (0), stream_ (ACE_SSL_Asynch_Stream::ST_CLIENT), block_ (1024) {} ~Client_Handler (); //FUZZ: disable check_for_lack_ACE_OS int open (ACE_HANDLE); //FUZZ: enable check_for_lack_ACE_OS private: virtual void handle_write_stream (const ACE_Asynch_Write_Stream::Result &result); private: size_t msgs_sent_; ACE_SSL_Asynch_Stream stream_; ACE_Message_Block block_; }; class Server_Handler : public ACE_Handler { public: Server_Handler () : msgs_rcvd_ (0), stream_ (ACE_SSL_Asynch_Stream::ST_SERVER), block_ (1024) {} ~Server_Handler (); //FUZZ: disable check_for_lack_ACE_OS int open (ACE_HANDLE); //FUZZ: enable check_for_lack_ACE_OS private: virtual void handle_read_stream (const ACE_Asynch_Read_Stream::Result &result); private: size_t msgs_rcvd_; ACE_SSL_Asynch_Stream stream_; ACE_Message_Block block_; }; class Server_Acceptor : public ACE_Event_Handler { public: //FUZZ: disable check_for_lack_ACE_OS int open (const ACE_INET_Addr &listen_addr); //FUZZ: enable check_for_lack_ACE_OS // Get the I/O handle. virtual ACE_HANDLE get_handle (void) const; // Called when a new connection is ready to accept. virtual int handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE); virtual int handle_close (ACE_HANDLE handle, ACE_Reactor_Mask close_mask); private: ACE_SSL_SOCK_Acceptor acceptor_; }; // Accepting end point. This is actually "localhost:10010", but some // platform couldn't resolve the name so we use the IP address // directly here. static const ACE_TCHAR *rendezvous = \ ACE_DEFAULT_SERVER_HOST ACE_TEXT (":") ACE_DEFAULT_SERVER_PORT_STR; // Total number of proactor threads. static size_t num_threads = ACE_MAX_THREADS; #if defined (CHORUS) // Add platforms that can't handle too many // connection simultaneously here. #define ACE_LOAD_FACTOR /2 #else #define ACE_LOAD_FACTOR #endif // Number of client connections to attempt. static size_t cli_conn_no = ACE_MAX_ITERATIONS ACE_LOAD_FACTOR; // Number of requests each client connection sends. static size_t cli_req_no = ACE_MAX_THREADS ACE_LOAD_FACTOR; // Delay before a thread sending the next request (in msec.) static int req_delay = 0; // This is the string sent from client to server. static const char *test_string = "SSL_Asynch_Stream_Test!"; // Function to remove signals from the signal mask. static int disable_signal (int sigmin, int sigmax) { #if !defined (ACE_LACKS_UNIX_SIGNALS) sigset_t signal_set; if (ACE_OS::sigemptyset (&signal_set) == - 1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("Error: (%P|%t):%p\n"), ACE_TEXT ("sigemptyset failed"))); for (int i = sigmin; i <= sigmax; i++) ACE_OS::sigaddset (&signal_set, i); // Put the <signal_set>. # if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) // In multi-threaded application this is not POSIX compliant // but let's leave it just in case. if (ACE_OS::sigprocmask (SIG_BLOCK, &signal_set, 0) != 0) # else if (ACE_OS::thr_sigsetmask (SIG_BLOCK, &signal_set, 0) != 0) # endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Error: (%P|%t): %p\n"), ACE_TEXT ("SIG_BLOCK failed")), -1); #else ACE_UNUSED_ARG (sigmin); ACE_UNUSED_ARG (sigmax); #endif /* ACE_LACKS_UNIX_SIGNALS */ return 0; } static void parse_args (int argc, ACE_TCHAR *argv[]) { //FUZZ: disable check_for_lack_ACE_OS ACE_Get_Opt getopt (argc, argv, ACE_TEXT ("r:t:d:i:n:")); int c; while ((c = getopt ()) != -1) { //FUZZ: enable check_for_lack_ACE_OS switch (c) { case 'r': // hostname:port rendezvous = getopt.opt_arg (); break; case 't': num_threads = ACE_OS::atoi (getopt.opt_arg ()); break; case 'd': req_delay = ACE_OS::atoi (getopt.opt_arg ()); break; case 'i': cli_conn_no = ACE_OS::atoi (getopt.opt_arg ()); break; case 'n': cli_req_no = ACE_OS::atoi (getopt.opt_arg ()); break; default: ACE_ERROR ((LM_ERROR, ACE_TEXT ("Usage: %s [-r <hostname:port#>]") ACE_TEXT ("\t[-t <nr threads>] [-d <delay>]") ACE_TEXT ("\t[-i <client conn attempt#>]") ACE_TEXT ("\t[-n <client request# per conn>]\n"), argv[0])); break; } } } Client_Handler::~Client_Handler () { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client %@ handle %d down\n"), this, this->stream_.handle ())); if (this->stream_.handle () != ACE_INVALID_HANDLE) { if (this->msgs_sent_ != cli_req_no) ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Client handle %d sent %d messages; ") ACE_TEXT ("expected %d\n"), this->stream_.handle (), this->msgs_sent_, cli_req_no)); else ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client handle %d sent %d messages; ") ACE_TEXT ("closing connection\n"), this->stream_.handle (), cli_req_no)); } this->stream_.close (); } int Client_Handler::open (ACE_HANDLE handle) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client %@ handle %d up\n"), this, handle)); if (this->stream_.open (*this, handle) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Client_Handler: %p\n"), ACE_TEXT ("open")), -1); this->block_.copy (test_string); if (this->stream_.write (this->block_, this->block_.length ()) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Client_Handler: %p\n"), ACE_TEXT ("initiate write")), -1); return 0; } void Client_Handler::handle_write_stream (const ACE_Asynch_Write_Stream::Result &result) { if (!result.success ()) { errno = result.error (); ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Client handle %d: %p\n"), this->stream_.handle (), ACE_TEXT ("write"))); delete this; return; } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client %@ handle %d sent %B of %B bytes\n"), this, this->stream_.handle (), result.bytes_transferred (), result.bytes_to_write ())); ACE_Message_Block &b = result.message_block (); bool send_again = true; if (b.length () == 0) { // All block's data sent; rewind the read pointer and send it again // until we've sent the configured number of times. ++this->msgs_sent_; if (this->msgs_sent_ == cli_req_no) send_again = false; // All done else b.rd_ptr (b.base ()); } if (send_again) { if (this->stream_.write (this->block_, this->block_.length ()) == -1) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Client_Handler: %p\n"), ACE_TEXT ("initiate write"))); delete this; } } else { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client handle %d done sending\n"), this->stream_.handle ())); delete this; } return; } Server_Handler::~Server_Handler () { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server %@ handle %d down\n"), this, this->stream_.handle ())); if (this->stream_.handle () != ACE_INVALID_HANDLE) { if (this->msgs_rcvd_ != cli_req_no) ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Server handle %d received %d messages; ") ACE_TEXT ("expected %d\n"), this->stream_.handle (), this->msgs_rcvd_, cli_req_no)); else ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server handle %d received %d messages; ") ACE_TEXT ("closing connection\n"), this->stream_.handle (), cli_req_no)); } this->stream_.close (); } int Server_Handler::open (ACE_HANDLE handle) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server %@ handle %d up\n"), this, handle)); if (this->stream_.open (*this, handle) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Server_Handler: %p\n"), ACE_TEXT ("open")), -1); if (this->stream_.read (this->block_, this->block_.space () - 1) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Server_Handler: %p\n"), ACE_TEXT ("read")), -1); return 0; } void Server_Handler::handle_read_stream (const ACE_Asynch_Read_Stream::Result &result) { if (!result.success ()) { errno = result.error (); ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Server handle %d: %p\n"), this->stream_.handle (), ACE_TEXT ("read"))); delete this; return; } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server %@ handle %d recv %B of %B bytes\n"), this, this->stream_.handle (), result.bytes_transferred (), result.bytes_to_read ())); if (result.bytes_transferred () == 0) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server handle %d closed by peer\n"), this->stream_.handle ())); delete this; return; } // Scan through the received data for the expected string. There may be // multiples and/or partials. Count up how many arrive before the connection // is closed. // Remember that the client side sends the terminating nul; in case the // whole thing didn't arrive, we add a nul to the end of the receive // block so we don't run off the end. When the recv into this buffer was // initiated, we left the last byte empty to facilitate this. ACE_Message_Block &b = result.message_block (); *(b.wr_ptr ()) = '\0'; size_t test_string_len = ACE_OS::strlen (test_string); while (b.length () >= test_string_len) { if (0 != ACE_OS::strncmp (b.rd_ptr (), test_string, test_string_len)) ACE_ERROR_BREAK ((LM_ERROR, ACE_TEXT ("(%t) Read string: %C; expected: %C\n"), b.rd_ptr (), test_string)); b.rd_ptr (test_string_len); // That ran up over the string; can we also consume the nul? if (b.length () > 0) b.rd_ptr (1); ++this->msgs_rcvd_; } b.crunch (); if (this->stream_.read (b, b.space () - 1) == -1) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Server_Handler: %p\n"), ACE_TEXT ("read"))); delete this; } return; } int Server_Acceptor::open (const ACE_INET_Addr &listen_addr) { if (this->acceptor_.open (listen_addr) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("listen")), -1); return 0; } ACE_HANDLE Server_Acceptor::get_handle (void) const { return this->acceptor_.get_handle (); } int Server_Acceptor::handle_input (ACE_HANDLE) { ACE_SSL_SOCK_Stream new_stream; if (this->acceptor_.accept (new_stream) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) %p\n"), ACE_TEXT ("accept")), -1); Server_Handler *new_handler = 0; ACE_NEW_RETURN (new_handler, Server_Handler, -1); if (new_handler->open (new_stream.get_handle ()) != 0) delete new_handler; return 0; } int Server_Acceptor::handle_close (ACE_HANDLE, ACE_Reactor_Mask) { this->acceptor_.close (); return 0; } static ACE_THR_FUNC_RETURN proactor_loop (void *) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Start handling events.\n"))); disable_signal (ACE_SIGRTMIN, ACE_SIGRTMAX); disable_signal (SIGPIPE, SIGPIPE); int result = ACE_Proactor::instance ()->proactor_run_event_loop (); if (result == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) %p\n"), ACE_TEXT ("Error handling events")), 0); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Done handling events.\n"))); return 0; } static ACE_THR_FUNC_RETURN start_clients (void *) { // Client thread function. ACE_INET_Addr addr (rendezvous); ACE_SSL_SOCK_Connector connect; disable_signal (ACE_SIGRTMIN, ACE_SIGRTMAX); disable_signal (SIGPIPE, SIGPIPE); for (size_t i = 0 ; i < cli_conn_no; i++) { ACE_SSL_SOCK_Stream stream; if (connect.connect (stream, addr) < 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) %p\n"), ACE_TEXT ("connect"))); continue; } Client_Handler *new_handler = 0; ACE_NEW_RETURN (new_handler, Client_Handler, (ACE_THR_FUNC_RETURN)-1); if (new_handler->open (stream.get_handle ()) != 0) { delete new_handler; stream.close (); } } return 0; } int run_main (int argc, ACE_TCHAR *argv[]) { ACE_START_TEST (ACE_TEXT ("SSL_Asynch_Stream_Test")); ACE_SSL_Context *context = ACE_SSL_Context::instance (); // Note - the next two strings are naked on purpose... the arguments to // the ACE_SSL_Context methods are const char *, not ACE_TCHAR *. context->certificate ("dummy.pem", SSL_FILETYPE_PEM); context->private_key ("key.pem", SSL_FILETYPE_PEM); parse_args (argc, argv); disable_signal (ACE_SIGRTMIN, ACE_SIGRTMAX); disable_signal (SIGPIPE, SIGPIPE); Server_Acceptor acceptor; ACE_INET_Addr accept_addr (rendezvous); if (acceptor.open (accept_addr) == -1) return 1; if (-1 == ACE_Reactor::instance ()->register_handler (&acceptor, ACE_Event_Handler::ACCEPT_MASK)) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) %p; aborting\n"), ACE_TEXT ("register_handler"))); return 1; } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Listening at %s\n"), rendezvous)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Spawning %d proactor threads\n"), num_threads)); ACE_Thread_Manager::instance ()->spawn_n (num_threads, proactor_loop); ACE_Thread_Manager::instance ()->spawn (start_clients); ACE_Time_Value loop_limit (20); ACE_Reactor::instance ()->run_reactor_event_loop (loop_limit); ACE_Thread_Manager::instance ()->wait (); // Check for num connections up/down. ACE_END_TEST; return 0; } #else int run_main (int, ACE_TCHAR *[]) { ACE_START_TEST (ACE_TEXT ("SSL_Asynch_Stream_Test")); ACE_ERROR ((LM_INFO, ACE_TEXT ("This test requires threads and AIO which are not ") ACE_TEXT ("supported on this platform\n"))); ACE_END_TEST; return 0; } #endif /* ACE_HAS_THREADS && (WIN32 || AIO) */
17,743
6,401
/* Copyright (c) 2019 Adam Biser <adambiser@gmail.com> 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 "stdafx.h" #include "SteamUser.h" CDurationControlCallback DurationControlCallback; /* @page ISteamUser */ //AdvertiseGame - game server stuff //BeginAuthSession - game server stuff /* @desc Checks if the current users looks like they are behind a NAT device. @return 1 if the current user is behind a NAT, otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsBehindNAT */ extern "C" DLL_EXPORT int IsBehindNAT() { CheckInitialized(false); return SteamUser()->BIsBehindNAT(); } /* @desc Checks whether the user's phone number is used to uniquely identify them. @return 1 f the current user's phone uniquely verifies their identity; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsPhoneIdentifying */ extern "C" DLL_EXPORT int IsPhoneIdentifying() { CheckInitialized(false); return SteamUser()->BIsPhoneIdentifying(); } /* @desc Checks whether the current user's phone number is awaiting (re)verification. @return 1 if the it is requiring verification; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsPhoneRequiringVerification */ extern "C" DLL_EXPORT int IsPhoneRequiringVerification() { CheckInitialized(false); return SteamUser()->BIsPhoneRequiringVerification(); } /* @desc Checks whether the current user has verified their phone number. @return 1 if the current user has phone verification enabled; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsTwoFactorEnabled */ extern "C" DLL_EXPORT int IsPhoneVerified() { CheckInitialized(false); return SteamUser()->BIsPhoneVerified(); } /* @desc Checks whether the current user has Steam Guard two factor authentication enabled on their account. @return 1 if the current user has two factor authentication enabled; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#IsPhoneVerified */ extern "C" DLL_EXPORT int IsTwoFactorEnabled() { CheckInitialized(false); return SteamUser()->BIsTwoFactorEnabled(); } /* @desc Checks to see whether the user is logged on to Steam. @return 1 when the user is logged on; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BLoggedOn */ extern "C" DLL_EXPORT int LoggedOn() { CheckInitialized(false); return SteamUser()->BLoggedOn(); } //CancelAuthTicket - game server stuff //DecompressVoice - voice stuff //EndAuthSession - game server stuff //GetAuthSessionTicket - game server stuff //GetAvailableVoice - voice stuff class CGetDurationControlCallResult : public CCallResultItem<DurationControl_t> { public: CGetDurationControlCallResult() { m_CallResultName = "GetDurationControl()"; m_hSteamAPICall = SteamUser()->GetDurationControl(); } virtual ~CGetDurationControlCallResult() { } AppId_t GetAppID() { return m_Response.m_appid; } bool GetApplicable() { return m_Response.m_bApplicable; } int32 GetCSecsLast5h() { return m_Response.m_csecsLast5h; } int GetProgress() { return (int)m_Response.m_progress; } int GetNotification() { return (int)m_Response.m_notification; } protected: void OnResponse(DurationControl_t *pCallResult, bool bFailure) { CCallResultItem::OnResponse(pCallResult, bFailure); } }; /* @desc Retrieves anti indulgence / duration control for current user / game combination. @return A [call result handle](Callbacks-and-Call-Results#call-results) on success; otherwise 0. @callback-type callresult @callback-getters GetDurationControlAppID, GetDurationControlApplicable, GetDurationControlSecondsInLastFiveHours, GetDurationControlProgress, GetDurationControlNotification @url https://partner.steamgames.com/doc/api/ISteamUser#GetDurationControl */ extern "C" DLL_EXPORT int GetDurationControl() { CheckInitialized(0); DurationControlCallback.Register(); return CallResults()->Add(new CGetDurationControlCallResult()); } /* @desc Sent for games with enabled anti indulgence / duration control, for enabled users. Lets the game know whether persistent rewards or XP should be granted at normal rate, half rate, or zero rate. This callback is fired asynchronously in response to timers triggering. It is also fired in response to calls to GetDurationControl(). @callback-type list @callback-getters GetDurationControlResult, GetDurationControlAppID, GetDurationControlApplicable, GetDurationControlSecondsInLastFiveHours, GetDurationControlProgress, GetDurationControlNotification @return 1 when the callback has more responses to process; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int HasDurationControlResponse() { return DurationControlCallback.HasResponse(); } /* @desc Returns the result of the current DurationControl_t callback response. @return An EResult value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/steam_api#EResult */ extern "C" DLL_EXPORT int GetDurationControlResult() { return DurationControlCallback.GetCurrent().m_eResult; } /* @desc Returns the appid generating playtime of the current DurationControl_t callback response. @return An app ID. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int GetDurationControlAppID() { return DurationControlCallback.GetCurrent().m_appid; } /* @desc Returns the appid generating playtime for the given call result. @param hCallResult An GetDurationControl call result handle. @return An app ID. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @plugin-name GetDurationControlAppID */ extern "C" DLL_EXPORT int GetDurationControlCallResultAppID(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetAppID); } /* @desc Returns whether the duration control is applicable to user + game combination for the current DurationControl_t callback response. @return 1 when the duration control is applicable to user + game combination; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int GetDurationControlApplicable() { return DurationControlCallback.GetCurrent().m_bApplicable; } /* @desc Returns whether the duration control is applicable to user + game combination for the given call result. @param hCallResult An GetDurationControl call result handle. @return 1 when the duration control is applicable to user + game combination; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @plugin-name GetDurationControlApplicable */ extern "C" DLL_EXPORT int GetDurationControlCallResultApplicable(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetApplicable); } /* @desc Returns playtime in trailing 5 hour window plus current session, in seconds, for the current DurationControl_t callback response. @return An integer. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int GetDurationControlSecondsInLastFiveHours() { return DurationControlCallback.GetCurrent().m_csecsLast5h; } /* @desc Returns playtime in trailing 5 hour window plus current session, in seconds, for the given call result. @param hCallResult An GetDurationControl call result handle. @return An integer. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @plugin-name GetDurationControlSecondsInLastFiveHours */ extern "C" DLL_EXPORT int GetDurationControlCallResultSecondsInLastFiveHours(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetCSecsLast5h); } /* @desc Returns the recommended progress for the current DurationControl_t callback response. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlProgress */ extern "C" DLL_EXPORT int GetDurationControlProgress() { return DurationControlCallback.GetCurrent().m_progress; } /* @desc Returns the recommended progress for the given call result. @param hCallResult An GetDurationControl call result handle. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlProgress @plugin-name GetDurationControlProgress */ extern "C" DLL_EXPORT int GetDurationControlCallResultProgress(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetProgress); } /* @desc Returns the notification to show, if any (always k_EDurationControlNotification_None for API calls), for the current DurationControl_t callback response. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlNotification */ extern "C" DLL_EXPORT int GetDurationControlNotification() { return DurationControlCallback.GetCurrent().m_notification; } /* @desc Returns the notification to show, if any (always k_EDurationControlNotification_None for API calls), for the given call result. @param hCallResult An GetDurationControl call result handle. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlNotification @plugin-name GetDurationControlNotification */ extern "C" DLL_EXPORT int GetDurationControlCallResultNotification(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetNotification); } //GetEncryptedAppTicket - encrypted app ticket stuff /* @desc Gets the level of the users Steam badge for your game. The user can have two different badges for a series; the regular badge (max level 5) and the foil badge (max level 1). @param series If you only have one set of cards, the series will be 1. @param foil Check if they have received the foil badge. @return The user's badge level. @url https://partner.steamgames.com/doc/api/ISteamUser#GetGameBadgeLevel */ extern "C" DLL_EXPORT int GetGameBadgeLevel(int series, int foil) { CheckInitialized(0); return SteamUser()->GetGameBadgeLevel(series, foil != 0); } //GetHSteamUser - internal use template<> void ResponseWrapper<MarketEligibilityResponse_t>::SetResult() { m_eResult = k_EResultOK; } class CGetMarketEligibilityCallResult : public CCallResultItem<MarketEligibilityResponse_t, ResponseWrapper<MarketEligibilityResponse_t>> { public: CGetMarketEligibilityCallResult() { m_CallResultName = "GetMarketEligibility()"; m_hSteamAPICall = SteamUser()->GetMarketEligibility(); } virtual ~CGetMarketEligibilityCallResult() { } bool IsAllowed() { return m_Response.m_bAllowed; } int GetNotAllowedReason() { return (int)m_Response.m_eNotAllowedReason; } int GetAllowedAtTime() { return (int)m_Response.m_rtAllowedAtTime; } int GetSteamGuardRequiredDays() { return m_Response.m_cdaySteamGuardRequiredDays; } int GetNewDeviceCooldown() { return m_Response.m_cdayNewDeviceCooldown; } protected: void OnResponse(MarketEligibilityResponse_t *pCallResult, bool bFailure) { CCallResultItem::OnResponse(pCallResult, bFailure); } }; /* @desc Checks whether or not an account is allowed to use the market. @return A [call result handle](Callbacks-and-Call-Results#call-results) on success; otherwise 0. @callback-type callresult @callback-getters GetDurationControlAppID, GetDurationControlApplicable, GetDurationControlSecondsInLastFiveHours, GetDurationControlProgress, GetDurationControlNotification @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibility() { // Not in API docs, see https://partner.steamgames.com/doc/webapi/IEconMarketService#GetMarketEligibility CheckInitialized(0); return CallResults()->Add(new CGetMarketEligibilityCallResult()); } /* @desc Returns whether or not the user can use the market. @param hCallResult An GetMarketEligibility call result handle. @return 1 if the user can use the market; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityIsAllowed(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::IsAllowed); } /* @desc Returns the reasons a user may not use the Community Market. @param hCallResult An GetMarketEligibility call result handle. @return A EMarketNotAllowedReasonFlags value. @return-url https://partner.steamgames.com/doc/api/ISteamUser#EMarketNotAllowedReasonFlags @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityNotAllowedReason(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetNotAllowedReason); } /* @desc Returns when the user is allowed to use the market again. @param hCallResult An GetMarketEligibility call result handle. @return A Unix time. @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityAllowedAtTime(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetAllowedAtTime); } /* @desc Returns the number of days any user is required to have had Steam Guard before they can use the market @param hCallResult An GetMarketEligibility call result handle. @return An integer. @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilitySteamGuardRequiredDays(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetSteamGuardRequiredDays); } /* @desc Returns the number of days after initial device authorization a user must wait before using the market on that device @param hCallResult An GetMarketEligibility call result handle. @return An integer @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityNewDeviceCooldown(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetNewDeviceCooldown); } /* @desc Gets the Steam level of the user, as shown on their Steam community profile. @return The level of the current user. @url https://partner.steamgames.com/doc/api/ISteamUser#GetPlayerSteamLevel */ extern "C" DLL_EXPORT int GetPlayerSteamLevel() { CheckInitialized(0); return SteamUser()->GetPlayerSteamLevel(); } /* @desc Gets a handle to the Steam ID of the account currently logged into the Steam client. @return A SteamID handle @url https://partner.steamgames.com/doc/api/ISteamUser#GetSteamID */ extern "C" DLL_EXPORT int GetSteamID() { CheckInitialized(0); return SteamHandles()->GetPluginHandle(SteamUser()->GetSteamID()); } // Not in the API, but grouping this near GetSteamID(). /* @desc Checks to see if a Steam ID handle is valid. @param hSteamID The Steam ID handle to check. @return 1 when the Steam ID handle is valid; otherwise 0. */ extern "C" DLL_EXPORT int IsSteamIDValid(int hSteamID) { CheckInitialized(false); CSteamID steamID = SteamHandles()->GetSteamHandle(hSteamID); return steamID.IsValid(); } // Not in the API, but grouping this near GetSteamID(). /* @desc Gets the the account ID (profile number) for the given Steam ID handle. @param hSteamIDUser A user Steam ID handle. @return The account ID. */ extern "C" DLL_EXPORT int GetAccountID(int hSteamIDUser) { CheckInitialized(0); CSteamID steamID = SteamHandles()->GetSteamHandle(hSteamIDUser); if (steamID != k_steamIDNil) { return steamID.GetAccountID(); } return 0; } // Not in the API, but grouping this near GetSteamID(). /* @desc Gets the the SteamID3 for the given Steam ID handle. @param hSteamIDUser A user Steam ID handle. @return A string containing the SteamID3. @url https://developer.valvesoftware.com/wiki/SteamID#Types_of_Steam_Accounts */ extern "C" DLL_EXPORT char *GetSteamID3(int hSteamIDUser) { CheckInitialized(NULL_STRING); CSteamID steamID = SteamHandles()->GetSteamHandle(hSteamIDUser); if (steamID != k_steamIDNil) { std::string steam3("["); // Source: https://developer.valvesoftware.com/wiki/SteamID#Types_of_Steam_Accounts switch (steamID.GetEAccountType()) { case k_EAccountTypeInvalid: // I case k_EAccountTypeIndividual: // U case k_EAccountTypeMultiseat: // M case k_EAccountTypeGameServer: // G case k_EAccountTypeAnonGameServer: // A case k_EAccountTypePending: // P case k_EAccountTypeContentServer: // C case k_EAccountTypeClan: // g case k_EAccountTypeChat: // T / L / c case k_EAccountTypeAnonUser: // a steam3 += "IUMGAPCgT?a"[steamID.GetEAccountType()]; break; case k_EAccountTypeConsoleUser: // 9 = P2P, but this doesn't look right. Fake anyway, just do the default below. default: steam3 += std::to_string(steamID.GetEAccountType()); break; } steam3 += ":" + std::to_string(steamID.GetEUniverse()) + ":" + std::to_string(steamID.GetAccountID()); switch (steamID.GetEAccountType()) { case k_EAccountTypeAnonGameServer: case k_EAccountTypeAnonUser: steam3 += ":" + std::to_string(steamID.GetUnAccountInstance()); break; default: break; } steam3 += "]"; return utils::CreateString(steam3); } return NULL_STRING; } // Not in the API, but grouping this near GetSteamID(). /* @desc Gets the the SteamID64 (profile number) for the given Steam ID handle. @param hSteamIDUser A user Steam ID handle. @return A string containing the 64-bit SteamID64 in base 10. */ extern "C" DLL_EXPORT char *GetSteamID64(int hSteamIDUser) { CheckInitialized(NULL_STRING); char id64[21]; // Max value is 18,446,744,073,709,551,615 //_i64toa(SteamHandles()->GetSteamHandle(hSteamIDUser), id64, 10); // Windows and Linux snprintf(id64, 21, "%llu", SteamHandles()->GetSteamHandle(hSteamIDUser)); return utils::CreateString(id64); } // Not in the API, but grouping this near GetSteamID(). /* @desc Returns the handle for the given SteamID64 string. @param steamID64 A SteamID64 string. @return A Steam ID handle or 0. */ extern "C" DLL_EXPORT int GetHandleFromSteamID64(const char *steamID64) { CheckInitialized(0); //uint64 id = _atoi64(steamID64); uint64 id = atoll(steamID64); return SteamHandles()->GetPluginHandle(CSteamID(id)); } //GetUserDataFolder - Deprecated //GetVoice - voice stuff //GetVoiceOptimalSampleRate - voice stuff //InitiateGameConnection - old authentication, skip? //RequestEncryptedAppTicket - encrypted app ticket stuff //RequestStoreAuthURL - store stuff //StartVoiceRecording - voice stuff //StopVoiceRecording - voice stuff //TerminateGameConnection - old authentication, skip? //TrackAppUsageEvent - deprecated //UserHasLicenseForApp - game server stuff... validate DLC for auth session //Callbacks
20,030
6,526
/* * MIT License * * Copyright (c) 2018 insa.4if.hexanome_kalate * * 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 "SymbolTable.h" #include "../../Logger.h" #include "../../utils/Common.h" #include "../context/Context.h" #include "../statements/definition/TypeDefinition.h" #include "../../exceptions/UndefinedSymbolError.h" #include "../../exceptions/SymbolAlreadyDefinedError.h" #include "../../exceptions/SymbolAlreadyDeclaredError.h" #include "../../exceptions/DeclarationMismatchException.h" #include "../../exceptions/FunctionCallArgumentsTypeMismatchException.h" #include "../../exceptions/FunctionDefinitionParameterNameMismatchError.h" #include "../../exceptions/FunctionDefinitionParameterTypeMismatchError.h" #include "../../exceptions/FunctionCallArgumentsNumberMismatchException.h" #include "../../exceptions/FunctionDefinitionNumberOfParametersMismatchError.h" #include "../../exceptions/FunctionNameAlreadyDeclaredError.h" namespace caramel::ast { using namespace utils; using namespace exceptions; SymbolTable::SymbolTable(SymbolTable::Ptr const &parentTable) : mParentTable(parentTable) {} VariableSymbol::Ptr SymbolTable::addVariableDeclaration( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, const Declaration::Ptr &declaration ) { logger.trace() << "SymbolTable::addVariableDeclaration(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), declaration ); } else if (isDeclared(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDeclaredError( name, symbol, antlrContext, symbol->getDeclaration(), declaration ); } else { VariableSymbol::Ptr variableSymbol = std::make_shared<VariableSymbol>(name, primaryType); mSymbolMap[name] = variableSymbol; variableSymbol->addDeclaration(declaration); return variableSymbol; } } VariableSymbol::Ptr SymbolTable::addVariableDefinition( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, const Definition::Ptr &definition ) { logger.trace() << "SymbolTable::addVariableDefinition(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), definition ); } else if (isDeclared(name)) { Symbol::Ptr recordedSymbol = getSymbol(antlrContext, name); if (recordedSymbol->getSymbolType() != SymbolType::VariableSymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::VariableSymbol, mSymbolMap[name] ); } if (!recordedSymbol->getType()->equals(primaryType)) { throw DeclarationMismatchException( antlrContext, name, primaryType, mSymbolMap[name] ); } recordedSymbol->addDefinition(definition); return std::dynamic_pointer_cast<VariableSymbol>(recordedSymbol); } else { VariableSymbol::Ptr variableSymbol = std::make_shared<VariableSymbol>(name, primaryType); mSymbolMap[name] = variableSymbol; variableSymbol->addDefinition(definition); return variableSymbol; } } Symbol::Ptr SymbolTable::addVariableUsage( antlr4::ParserRuleContext *antlrContext, std::string const &name, const Statement::Ptr &statement ) { logger.trace() << "SymbolTable::addVariableUsage(" << name << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::VariableSymbol && symbol->getSymbolType() != SymbolType::ArraySymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::VariableSymbol, mSymbolMap[name] ); } symbol->addUsage(statement); return symbol; } else { SymbolTable::Ptr parent = getParentTable(); if (parent) { return parent->addVariableUsage(antlrContext, name, statement); } else { throw UndefinedSymbolError( name, SymbolType::VariableSymbol, antlrContext ); } } } ArraySymbol::Ptr SymbolTable::addArrayDeclaration( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, bool sized, size_t size, const Declaration::Ptr &declaration ) { logger.trace() << "SymbolTable::addArrayDeclaration(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), declaration ); } else if (isDeclared(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDeclaredError( name, symbol, antlrContext, symbol->getDeclaration(), declaration ); } else { ArraySymbol::Ptr arraySymbol; if (sized) { arraySymbol = std::make_shared<ArraySymbol>(name, primaryType, size); } else { arraySymbol = std::make_shared<ArraySymbol>(name, primaryType); } mSymbolMap[name] = arraySymbol; arraySymbol->addDeclaration(declaration); return arraySymbol; } } ArraySymbol::Ptr SymbolTable::addArrayDefinition( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, std::vector<Expression::Ptr> &&content, const Definition::Ptr &definition ) { logger.trace() << "SymbolTable::addArrayDefinition(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), definition ); } else if (isDeclared(name)) { Symbol::Ptr recordedSymbol = getSymbol(antlrContext, name); if (recordedSymbol->getSymbolType() != SymbolType::ArraySymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::ArraySymbol, mSymbolMap[name] ); } if (!recordedSymbol->getType()->equals(primaryType)) { throw DeclarationMismatchException( antlrContext, name, primaryType, mSymbolMap[name] ); } recordedSymbol->addDefinition(definition); return castTo<ArraySymbol::Ptr>(recordedSymbol); } else { ArraySymbol::Ptr arraySymbol = std::make_shared<ArraySymbol>(name, primaryType, std::move(content)); mSymbolMap[name] = arraySymbol; arraySymbol->addDefinition(definition); return arraySymbol; } } ArraySymbol::Ptr SymbolTable::addArrayAccess( antlr4::ParserRuleContext *antlrContext, std::string const &name, const Statement::Ptr &statement ) { logger.trace() << "SymbolTable::addArrayAccess(" << name << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::ArraySymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::ArraySymbol, mSymbolMap[name] ); } auto const &arraySymbol = castTo<ArraySymbol::Ptr>(symbol); arraySymbol->addUsage(statement); return arraySymbol; } else { SymbolTable::Ptr parent = getParentTable(); if (parent) { return parent->addArrayAccess(antlrContext, name, statement); } else { throw UndefinedSymbolError( name, SymbolType::ArraySymbol, antlrContext ); } } } FunctionSymbol::Ptr SymbolTable::addFunctionDeclaration( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &returnType, std::string const &name, std::vector<FunctionParameterSignature> parameters, const Declaration::Ptr &declaration, bool variadic ) { logger.trace() << "SymbolTable::addFunctionDeclaration(" << name << ", " << returnType->getIdentifier() << ")"; if (isDeclared(name)) { // or defined // TODO: Duplicated code in addFunctionDefinition() -> move to a helper function auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::FunctionSymbol) { throw FunctionNameAlreadyDeclaredError( antlrContext, name, symbol ); } FunctionSymbol::Ptr const &functionSymbol = castTo<FunctionSymbol::Ptr>(symbol); auto declaredParameters = functionSymbol->getParameters(); if (declaredParameters.size() == parameters.size()) { for (size_t i = 0; i < declaredParameters.size(); i++) { std::string const declaredParameterName = declaredParameters[i].name; std::string const declaredParameterTypeIdentifier = declaredParameters[i].primaryType->getIdentifier(); std::string const parameterName = parameters[i].name; std::string const parameterTypeIdentifier = parameters[i].primaryType->getIdentifier(); if (declaredParameterName != parameterName) { throw FunctionDefinitionParameterNameMismatchError( name, antlrContext, declaredParameterName, parameterName ); } if (declaredParameterTypeIdentifier != parameterTypeIdentifier) { throw FunctionDefinitionParameterTypeMismatchError( antlrContext, name, declaredParameters[i].primaryType, parameters[i].primaryType ); } } } else { throw FunctionDefinitionNumberOfParametersMismatchError( name, antlrContext, declaredParameters.size(), parameters.size() ); } functionSymbol->addDeclaration(declaration); return functionSymbol; } else { FunctionSymbol::Ptr functionSymbol = std::make_shared<FunctionSymbol>(name, returnType, variadic); mSymbolMap[name] = functionSymbol; functionSymbol->setParameters(std::move(parameters)); functionSymbol->addDeclaration(declaration); return functionSymbol; } } FunctionSymbol::Ptr SymbolTable::addFunctionDefinition( antlr4::ParserRuleContext *antlrContext, Context::Ptr functionContext, PrimaryType::Ptr const &returnType, std::string const &name, std::vector<Symbol::Ptr> parameters, const Definition::Ptr &definition, bool variadic ) { logger.trace() << "SymbolTable::addFunctionDefinition(" << name << ", " << returnType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), definition ); } else if (isDeclared(name)) { auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::FunctionSymbol) { throw FunctionNameAlreadyDeclaredError( antlrContext, name, symbol ); } FunctionSymbol::Ptr const &functionSymbol = castTo<FunctionSymbol::Ptr>(symbol); if (functionSymbol->getContext()) { logger.fatal() << "The function is only declared, but the function context isn't null:\n" << " - existing declaration: " << *functionSymbol->getContext() << '\n' << " - current definition: " << *functionContext; exit(1); } auto declaredParameters = functionSymbol->getParameters(); if (declaredParameters.size() == parameters.size()) { for (size_t i = 0; i < declaredParameters.size(); i++) { std::string const declaredParameterName = declaredParameters[i].name; std::string const declaredParameterTypeIdentifier = declaredParameters[i].primaryType->getIdentifier(); std::string const parameterName = parameters[i]->getName(); std::string const parameterTypeIdentifier = parameters[i]->getType()->getIdentifier(); if (declaredParameterName != parameterName) { throw FunctionDefinitionParameterNameMismatchError( name, antlrContext, declaredParameterName, parameterName ); } if (declaredParameterTypeIdentifier != parameterTypeIdentifier) { throw FunctionDefinitionParameterTypeMismatchError( antlrContext, name, declaredParameters[i].primaryType, parameters[i]->getType() ); } } } else { throw FunctionDefinitionNumberOfParametersMismatchError( name, antlrContext, declaredParameters.size(), parameters.size() ); } functionSymbol->setContext(functionContext); functionSymbol->addDefinition(definition); return functionSymbol; } else { FunctionSymbol::Ptr functionSymbol = std::make_shared<FunctionSymbol>(name, returnType, variadic); mSymbolMap[name] = functionSymbol; functionSymbol->setContext(functionContext); functionSymbol->setParameters(std::move(parameters)); functionSymbol->addDefinition(definition); return functionSymbol; } } Symbol::Ptr SymbolTable::addFunctionParameter( antlr4::ParserRuleContext *antlrContext, std::string const &name, PrimaryType::Ptr const &primaryType, SymbolType parameterType ) { logger.trace() << "SymbolTable::addFunctionParameter(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); // TODO: A proper error throw std::runtime_error("Two different parameters can't have the same name."); } else { // If it's defined, we just shadow it if (parameterType == SymbolType::ArraySymbol) { ArraySymbol::Ptr arraySymbol = std::make_shared<ArraySymbol>(name, primaryType); mSymbolMap[name] = arraySymbol; return castTo<Symbol::Ptr>(arraySymbol); } else if (parameterType == SymbolType::VariableSymbol) { VariableSymbol::Ptr variableSymbol = std::make_shared<VariableSymbol>(name, primaryType); mSymbolMap[name] = variableSymbol; return castTo<Symbol::Ptr>(variableSymbol); } else { throw std::runtime_error("This can't be. And it is. Have a cookie!"); } } } FunctionSymbol::Ptr SymbolTable::addFunctionCall( antlr4::ParserRuleContext *antlrContext, std::string const &name, const FunctionCall::Ptr &functionCall ) { logger.trace() << "SymbolTable::addFunctionCall(" << name << ")"; if (isDeclared(name)) { Symbol::Ptr symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::FunctionSymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::FunctionSymbol, mSymbolMap[name] ); } auto functionSymbol = castTo<FunctionSymbol::Ptr>(symbol); // Check if the arguments match with the function parameters types, if it's not a variadic function if (!functionSymbol->isVariadic()) { std::vector<PrimaryType::Ptr> const &argumentsTypes = functionCall->getArgumentsPrimaryTypes(); auto const &parameters = functionSymbol->getParameters(); if (argumentsTypes.size() != parameters.size()) { throw FunctionCallArgumentsNumberMismatchException( "The function " + name + " takes " + std::to_string(parameters.size()) + " arguments, " + "but " + std::to_string(argumentsTypes.size()) + " were given." ); } for (size_t i = 0; i < argumentsTypes.size(); ++i) { if (!parameters[i].primaryType->greaterThan(argumentsTypes[i])) { std::stringstream errorMessage; errorMessage << "The function " << name << " " << (i+1) << "-th parameter is of type " << parameters[i].primaryType->getIdentifier() << ", but got a " << argumentsTypes[i]->getIdentifier() << "."; throw FunctionCallArgumentsTypeMismatchException(errorMessage.str()); } } } functionSymbol->addUsage(functionCall); return functionSymbol; } else { throw UndefinedSymbolError( name, SymbolType::FunctionSymbol, antlrContext ); } } void SymbolTable::addPrimaryType( PrimaryType::Ptr const &primaryType, std::string const &name ) { logger.trace() << "SymbolTable::addPrimaryType(" << name << ", " << primaryType->getIdentifier() << ")"; // Not declared and not defined if (isNotDeclared(name) && isNotDefined(name)) { mSymbolMap[name] = std::make_shared<TypeSymbol>(name, primaryType); mSymbolMap.at(name)->addDeclaration(nullptr); mSymbolMap.at(name)->addDefinition(nullptr); } else { logger.fatal() << "Can't add " << name << " as a primary type, because a symbol named " << name << " already exists."; exit(1); } } TypeSymbol::Ptr SymbolTable::addType( antlr4::ParserRuleContext *antlrContext, TypeDefinition::Ptr definition ) { auto definitionSymbol = definition->getSymbol().lock(); logger.trace() << "SymbolTable::addType(" << definitionSymbol->getName() << ", " << definitionSymbol->getType()->getIdentifier() << ")"; std::string typeAlias = definitionSymbol->getName(); PrimaryType::Ptr primaryType = definitionSymbol->getType(); // Not declared and not defined if (isNotDeclared(typeAlias)) { TypeSymbol::Ptr typeSymbol = std::make_shared<TypeSymbol>(typeAlias, primaryType); mSymbolMap[typeAlias] = typeSymbol; typeSymbol->addDefinition(definition); return typeSymbol; } else { throw caramel::exceptions::SymbolAlreadyDeclaredError( "Cannot execute typedef", mSymbolMap[typeAlias], antlrContext, mSymbolMap[typeAlias]->getDeclaration(), std::dynamic_pointer_cast<Declaration>(definition)); } } bool SymbolTable::hasSymbol(std::string const &name) { return thisHasSymbol(name) || parentHasSymbol(name); } bool SymbolTable::thisHasSymbol(std::string const &name) { return mSymbolMap.find(name) != mSymbolMap.end(); } bool SymbolTable::parentHasSymbol(std::string const &name) { return getParentTable() && getParentTable()->hasSymbol(name); } Symbol::Ptr SymbolTable::getSymbol(antlr4::ParserRuleContext *antlrContext, std::string const &name) { logger.trace() << "SymbolTable::getSymbol(): " << grey << name; if (thisHasSymbol(name)) { return mSymbolMap.at(name); } else { SymbolTable::Ptr parent = getParentTable(); if (parent) { return parent->getSymbol(antlrContext, name); } else { throw UndefinedSymbolError(name, antlrContext); } } } SymbolTable::Ptr SymbolTable::getParentTable() { return mParentTable; } size_t SymbolTable::getNumberOfSymbols() const { return mSymbolMap.size(); } std::map<std::string, Symbol::Ptr> const &SymbolTable::getSymbols() const { return mSymbolMap; } void SymbolTable::acceptAstDotVisit() { addNode(thisId(), "SymbolTable: " + std::to_string(mSymbolMap.size()) + " symbols", "cylinder", "darkorange"); visitChildrenAstDot(); } void SymbolTable::visitChildrenAstDot() { for (auto const &symbol : mSymbolMap) { addEdge(thisId(), symbol.second->thisId(), symbol.first); symbol.second->acceptAstDotVisit(); } } bool SymbolTable::isDeclared(const std::string &name) { return (thisHasSymbol(name) && mSymbolMap.at(name)->isDeclared()) || (getParentTable() && getParentTable()->isDeclared(name)); } bool SymbolTable::isDefined(const std::string &name) { return (thisHasSymbol(name) && mSymbolMap.at(name)->isDefined()) || (getParentTable() && getParentTable()->isDefined(name)); } } // namespace caramel::ast
23,963
6,058
//***************************************************************************** // Copyright (c) 2003. All rights reserved. // Developed by Jarl Lindrud. // Contact: jlindrud@hotmail.com . //***************************************************************************** #ifndef _UTIL_READWRITEPROTECT_HPP_ #define _UTIL_READWRITEPROTECT_HPP_ #include "ThreadLibrary.hpp" namespace util { // Utility for applying the readers/writer synchronization pattern. // Currently no bias for writers over readers. // To give multiple read access and single write access to a class X: // //class X { // void read() // { // ReadLock lock(rwp); // // ... // } // void write() // { // WriteLock lock(rwp); // // ... // } // ReadWriteProtect rwp; //} class ReadWriteProtect { public: typedef Platform::Threads::recursive_mutex Mutex; typedef Platform::Threads::condition Event; ReadWriteProtect() : readerCount(0) {} Mutex &getReadMutex() { return readMutex; } Mutex &getWriteMutex() { return writeMutex; } int &getReaderCount() { return readerCount; } void waitOnReadUnlock() { Mutex::scoped_lock lock( readUnlockMutex ); readUnlockEvent.wait(lock); } void notifyReadUnlock() { readUnlockEvent.notify_all(); } private: Mutex readMutex; Mutex writeMutex; Mutex readUnlockMutex; Event readUnlockEvent; int readerCount; }; class ReadLock { public: ReadLock( ReadWriteProtect &rwp ) : rwp( rwp ) { ReadWriteProtect::Mutex::scoped_lock lock( rwp.getReadMutex() ); rwp.getReaderCount()++; } ~ReadLock() { { ReadWriteProtect::Mutex::scoped_lock lock( rwp.getReadMutex() ); rwp.getReaderCount()--; } rwp.notifyReadUnlock(); } private: ReadWriteProtect &rwp; }; class WriteLock { public: WriteLock( ReadWriteProtect &rwp ) : rwp( rwp ), read_lock( rwp.getWriteMutex(), false ), write_lock( rwp.getWriteMutex(), false ) { read_lock.lock(); while (rwp.getReaderCount() > 0) { read_lock.unlock(); rwp.waitOnReadUnlock(); read_lock.lock(); } write_lock.lock(); } ~WriteLock() { write_lock.unlock(); read_lock.unlock(); } private: ReadWriteProtect &rwp; ReadWriteProtect::Mutex::scoped_lock read_RCF_UNUSED_VARIABLE(lock); ReadWriteProtect::Mutex::scoped_lock write_RCF_UNUSED_VARIABLE(lock); }; } // namespace util #endif // ! _UTIL_READWRITEPROTECT_HPP_
3,021
962
#include "InetAddress.h" #include "TlsAcceptor.h" #include "TlsConfig.h" #include "TlsStream.h" int main(int argc, char* argv[]) { TlsConfig config; // config.setCaFile("ca.pem"); config.setCertFile("server.pem"); config.setKeyFile("server.pem"); InetAddress listenAddr(4433); TlsAcceptor acceptor(&config, listenAddr); TlsStreamPtr stream = acceptor.accept(); if (stream) { LOG_INFO << "OK"; } }
425
173
#pragma warning(default:4005) extern void** ppPluginData; extern void* pAMXFunctions; typedef void (*logprintf_t)(const char* szFormat, ...); extern logprintf_t logprintf;
172
62
/** * @brief define container Data_Vec * * @file class_data_vec.hpp * @author Michal Vrastil * @date 2018-07-11 */ #pragma once #include "stdafx.h" #include <array> /** * @class: Data_Vec * @brief: class containing data [x, y,...] */ template <typename T, size_t N> class Data_Vec { public: // CONSTRUCTORS Data_Vec() = default; Data_Vec(size_t size) { data.fill(std::vector<T>(size)); } // VARIABLES std::array<std::vector<T>, N> data; // ELEMENT ACCESS std::vector<T>& operator[](size_t i){ return data[i]; } const std::vector<T>& operator[](size_t i) const { return data[i]; } // CAPACITY size_t dim() const noexcept{ return data.size(); } size_t size() const noexcept{ return data[0].size(); } void resize (size_t n){ for (auto &vec : data) vec.resize(n); } void resize (size_t n, T val){ for (auto &vec : data) vec.resize(n, val); } void reserve(size_t n){ for (auto &vec : data) vec.reserve(n); } void erase(size_t index){ for (auto &vec : data) vec.erase(vec.begin() + index); } // MODIFIERS void fill(T val){ for (auto &vec : data) std::fill(vec.begin(), vec.end(), val); } };
1,227
465
/* @@@@@@@@ @@ @@@@@@ @@@@@@@@ @@ /@@///// /@@ @@////@@ @@////// /@@ /@@ /@@ @@@@@ @@ // /@@ /@@ /@@@@@@@ /@@ @@///@@/@@ /@@@@@@@@@/@@ /@@//// /@@/@@@@@@@/@@ ////////@@/@@ /@@ /@@/@@//// //@@ @@ /@@/@@ /@@ @@@//@@@@@@ //@@@@@@ @@@@@@@@ /@@ // /// ////// ////// //////// // Copyright (c) 2016, Los Alamos National Security, LLC All rights reserved. */ /*! @file */ #include <flecsi-config.h> #if !defined(FLECSI_ENABLE_MPI) #error FLECSI_ENABLE_MPI not defined! This file depends on MPI! #endif #include <mpi.h> #include <flecsi/execution/context.h> // Boost command-line options #if defined(FLECSI_ENABLE_BOOST) #include <boost/program_options.hpp> using namespace boost::program_options; #endif #if defined(ENABLE_CALIPER) #include <caliper/cali-mpi.h> #include <caliper/cali.h> #endif //----------------------------------------------------------------------------// //! FleCSI runtime main function. //----------------------------------------------------------------------------// int main(int argc, char ** argv) { #if defined(FLECSI_ENABLE_MPI) // Get the MPI version int version, subversion; MPI_Get_version(&version, &subversion); #if defined(GASNET_CONDUIT_MPI) if(version == 3 && subversion > 0) { int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); // If you fail this assertion, then your version of MPI // does not support calls from multiple threads and you // cannot use the GASNet MPI conduit if(provided < MPI_THREAD_MULTIPLE) printf("ERROR: Your implementation of MPI does not support " "MPI_THREAD_MULTIPLE which is required for use of the " "GASNet MPI conduit with the Legion-MPI Interop!\n"); assert(provided == MPI_THREAD_MULTIPLE); } else { // Initialize the MPI runtime int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); if(provided < MPI_THREAD_MULTIPLE) printf("ERROR: Your implementation of MPI does not support " "MPI_THREAD_MULTIPLE which is required for use of the " "GASNet MPI conduit with the Legion-MPI Interop!\n"); assert(provided == MPI_THREAD_MULTIPLE); } // if #else int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); if(provided < MPI_THREAD_MULTIPLE) printf("ERROR: Your implementation of MPI does not support " "MPI_THREAD_MULTIPLE which is required for use of the " "GASNet MPI conduit with the Legion-MPI Interop!\n"); assert(provided == MPI_THREAD_MULTIPLE); #endif //#if defined(ENABLE_CALIPER) // cali_mpi_init(); //#endif // get the rank int rank{0}; MPI_Comm_rank(MPI_COMM_WORLD, &rank); #endif // FLECSI_ENABLE_MPI //--------------------------------------------------------------------------// // INIT CLOG //--------------------------------------------------------------------------// // Initialize tags to output all tag groups from CLOG std::string tags("all"); #if defined(FLECSI_ENABLE_BOOST) options_description desc("Cinch test options"); // Add command-line options desc.add_options()("help,h", "Print this message and exit.")("tags,t", value(&tags)->implicit_value("0"), "Enable the specified output tags, e.g., --tags=tag1,tag2." " Passing --tags by itself will print the available tags."); variables_map vm; parsed_options parsed = command_line_parser(argc, argv).options(desc).allow_unregistered().run(); store(parsed, vm); notify(vm); if(vm.count("help")) { if(rank == 0) { std::cout << desc << std::endl; } // if MPI_Finalize(); return 1; } // if #endif // FLECSI_ENABLE_BOOST int result{0}; if(tags == "0") { // Output the available tags if(rank == 0) { std::cout << "Available tags (CLOG):" << std::endl; for(auto t : clog_tag_map()) { std::cout << " " << t.first << std::endl; } // for } // if } else { // Initialize the cinchlog runtime clog_init(tags); // Execute the flecsi runtime. result = flecsi::execution::context_t::instance().initialize(argc, argv); } // if #if defined(FLECSI_ENABLE_MPI) // Shutdown the MPI runtime #ifndef GASNET_CONDUIT_MPI MPI_Finalize(); #endif #endif // FLECSI_ENABLE_MPI return result; } // main
4,529
1,593
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2019 Blender Foundation. * All rights reserved. */ /** \file * \ingroup depsgraph */ #include "intern/eval/deg_eval_runtime_backup_movieclip.h" #include "DNA_movieclip_types.h" #include "BLI_utildefines.h" namespace DEG { MovieClipBackup::MovieClipBackup(const Depsgraph * /*depsgraph*/) { reset(); } void MovieClipBackup::reset() { anim = nullptr; cache = nullptr; } void MovieClipBackup::init_from_movieclip(MovieClip *movieclip) { anim = movieclip->anim; cache = movieclip->cache; /* Clear pointers stored in the movie clip, so they are not freed when copied-on-written * datablock is freed for re-allocation. */ movieclip->anim = nullptr; movieclip->cache = nullptr; } void MovieClipBackup::restore_to_movieclip(MovieClip *movieclip) { movieclip->anim = anim; movieclip->cache = cache; reset(); } } // namespace DEG
1,623
536
#include "bmat.hpp" #include "SwapByTwoIndex.hpp" /* bool SwapByTwoIndex::getVal(class sstd::bmat& bMat, uint& p, uint& q){ // Mat 座標 <- bMat 座標 uint p_Div8 = p / 8; uint q_Div8 = q / 8; // bMat8x8 座標 <- bMat 座標 uint p_Mod8 = p - p_Div8 * 8; // p % 8; uint q_Mod8 = q - q_Div8 * 8; // q % 8; UINT64 mask = 0x8000000000000000; mask = mask>>(8*p_Mod8+q_Mod8); return ((bMat.bMat8x8(p_Div8, q_Div8)&mask) != (UINT64)0); } void SwapByTwoIndex::setVal(class sstd::bmat& bMat, uint& p, uint& q, bool val){ // Mat 座標 <- bMat 座標 uint p_Div8 = p / 8; uint q_Div8 = q / 8; // bMat8x8 座標 <- bMat 座標 uint p_Mod8 = p - p_Div8 * 8; // p % 8; uint q_Mod8 = q - q_Div8 * 8; // q % 8; UINT64 mask = 0x8000000000000000; mask = mask>>(8*p_Mod8+q_Mod8); if(val){ // val != 0, true bMat.bMat8x8(p_Div8, q_Div8) |= mask; }else{ // val == 0, false mask=~mask; bMat.bMat8x8(p_Div8, q_Div8) &= mask; } } class SwapByTwoIndex OpSwapByTwoIndex(sstd::bmat* pthis, uint p, uint q){ class SwapByTwoIndex SBTI; SBTI.pBMxs = pthis; SBTI.SwapRowNum = p; SBTI.SwapColNum = q; return SBTI; }; */
1,284
670
/** * \file linkedlist.hpp * \author Dan Obermiller * \brief Implementation of a singly-linked list. */ #ifndef LINKEDLIST_HPP #define LINKEDLIST_HPP 1 #include <cstddef> #include <iterator> #include "list.hpp" #include "../exceptions.hpp" /** * \brief A paramaterized singly-linked list */ template <typename T> class LinkedList : public List<T> { private: /** * \brief Iterator for a linkedlist. */ class Iterator; /** * \brief Constant iterator for a linkedlist. */ class ConstIterator; /** * \brief Node of a linkedlist */ struct ListNode; public: /** * \brief A default constructor for a linked list. */ LinkedList(); /** * \brief A constructor from an array. */ LinkedList(T* arr, std::size_t length); /** * \brief Copy constructor. */ LinkedList(const LinkedList<T>& orig); /** * \brief Move constructor. */ LinkedList(LinkedList<T>&& other); /** * \brief Assignment to a list; */ LinkedList<T>& operator=(LinkedList<T> rhs); /** * \brief The destructor for a linked list. */ ~LinkedList(); /** * \brief Non-member function version of swap. */ template <class P> friend void swap(LinkedList<P>& lhs, LinkedList<P>& rhs); /** * \brief The head (first item) of the list. */ T& getHead(); /** * \brief Constant version of getHead() */ const T& getHead() const; /** * \brief The tail (last item) of the list. */ T& getTail(); /** * \brief Constant version of getTail() */ const T& getTail() const; /** * \brief Returns the size of the list */ std::size_t size() const; /** * \brief Returns whether or not the list is empty. */ bool isEmpty() const; /** * \brief Adds a node to the end of the list. * \post All nodes have the appropriate "next_" and the list has * the appropriate size. */ void append(T value); /** * \brief Removes the first item in the list. */ void remove(); /** * \brief Removes the nth item in the list. */ void remove(std::size_t n); /** * \brief Removes and returns a copy of the value of the first item * in the list. */ T pop(); /** * \brief Removes and returns a copy of the value of the nth item * in the list. */ T pop(std::size_t n); /** * \brief inserts an item at the indicated index. */ void insert(std::size_t index, T value); /** * \brief Determines the index of an element. */ std::size_t index_of(T const& value) const; /** * \brief Determines whether or not the value is present. */ bool contains(T const& value) const; /** * \brief Overloads the addition operator. * \details Adds two lists together and returns the result. */ template <typename P> friend LinkedList<P> operator+(LinkedList<P> lhs, LinkedList<P> rhs); /** * \brief Overloads the multiplication operator. * \details Allows us to make the list repeat n times. */ template <typename P> friend LinkedList<P> operator*(LinkedList<P> lhs, std::size_t n); /** * \brief Overloads the mutable subscript operator. */ T& operator[](std::size_t index); /** * \brief Overloads the immutable subscript operator. */ const T& operator[](std::size_t index) const; /** * \brief Overloads the equivalence operator. */ bool operator==(const LinkedList<T>& rhs) const; /** * \brief Overloads the inequivalence operator. */ bool operator!=(const LinkedList<T>& rhs) const; /** * \brief Returns an array of the values within the list. * \details This is a dynamically allocated array and needs to be * explicitly deleted. */ T* asArray() const; /** * \brief Overloads the << operator. */ template <class P> friend std::ostream& operator<<( std::ostream& str, const LinkedList<P>& list); typedef Iterator iterator; typedef ConstIterator const_iterator; /** * \brief Returns the start of the ListIterator. */ iterator begin(); /** * \brief Returns the end of the ListIterator. */ iterator end(); /** * \brief Returns a costant version of the ListIterator (from the start) */ const_iterator begin() const; /** * \brief Returns a constant version of the ListIterator (at the end). */ const_iterator end() const; /** * \brief Sorts the current list. */ void sort(); /** * \brief Returns a copy of the list in sorted order. * \post The original list is unchanged. */ LinkedList<T> sorted() const; /** * \brief Reverses the order of the list. */ void reverse(); /** * \brief Returns a copy of the list, reversed. * \post The original list is unchanged. */ LinkedList<T> reversed() const; /** * \brief Returns an array of the items in the list. */ T* toArray() const; private: class Iterator : public std::iterator<std::forward_iterator_tag, T> { public: /** * \brief Prefix increment operator overloading. */ Iterator& operator++(); /** * \brief Postfix increment operator overloading. */ Iterator operator++(int) const; /** * \brief Dereferencing operator overloading. */ const T& operator*() const; /** * \brief Member access operator overriding. */ const T* operator->() const; /** * \brief Equality operator overriding. */ bool operator==(const Iterator& rhs) const; /** * \brief Inequality operator overriding. */ bool operator!=(const Iterator& rhs) const; private: friend class LinkedList; /** * \brief The default constructor. */ Iterator() = delete; /** * \brief All iterators should have a current node. */ Iterator(ListNode* node) : current_{node} { } ListNode* current_; }; class ConstIterator : public std::iterator<std::forward_iterator_tag, T> { public: /** * \brief Prefix increment operator overloading. */ ConstIterator& operator++(); /** * \brief Postfix increment operator overloading. */ ConstIterator operator++(int) const; /** * \brief Dereferencing operator overloading. */ const T& operator*() const; /** * \brief Member access operator overriding. */ const T* operator->() const; /** * \brief Equality operator overriding. */ bool operator==(const ConstIterator& rhs) const; /** * \brief Inequality operator overriding. */ bool operator!=(const ConstIterator& rhs) const; private: friend class LinkedList; /** * \brief The default constructor. */ ConstIterator() = delete; /** * \brief All iterators should have a current node. */ ConstIterator(ListNode* node) : current_{node} { } ListNode* current_; }; /** * \brief Node of a linkedlist */ struct ListNode { T value_; ListNode* next_; }; /** * \brief Gets a list node at the given index */ LinkedList<T>::ListNode* getListNode(std::size_t index) const; std::size_t numElements_; ListNode* head_; ListNode* tail_; }; #include "_linkedlist.hpp" #endif
7,117
2,510
/* * TFTP.cpp * * See also: * * https://tools.ietf.org/html/rfc1350 * Created on: May 21, 2017 * Author: kolban */ #include "TFTP.h" #include <esp_log.h> #include <FreeRTOS.h> #include <GeneralUtils.h> #include <string> #include <stdio.h> #include <errno.h> #include <string.h> #include <Socket.h> #include "sdkconfig.h" extern "C" { extern uint16_t lwip_ntohs(uint16_t); extern uint32_t lwip_ntohl(uint32_t); extern uint16_t lwip_htons(uint16_t); extern uint32_t lwip_htonl(uint32_t); } static const char* LOG_TAG = "TFTP"; enum opcode { TFTP_OPCODE_RRQ = 1, // Read request TFTP_OPCODE_WRQ = 2, // Write request TFTP_OPCODE_DATA = 3, // Data TFTP_OPCODE_ACK = 4, // Acknowledgement TFTP_OPCODE_ERROR = 5 // Error }; enum ERRORCODE { ERROR_CODE_NOTDEFINED = 0, ERROR_CODE_FILE_NOT_FOUND = 1, ERROR_CODE_ACCESS_VIOLATION = 2, ERROR_CODE_NO_SPACE = 3, ERROR_CODE_ILLEGAL_OPERATION = 4, ERROR_CODE_UNKNOWN_ID = 5, ERROR_CODE_FILE_EXISTS = 6, ERROR_CODE_UNKNOWN_USER = 7 }; /** * Size of the TFTP data payload. */ const int TFTP_DATA_SIZE = 512; struct data_packet { uint16_t blockNumber; std::string data; }; TFTP::TFTP() { m_baseDir = ""; } TFTP::~TFTP() { } /** * @brief Start a TFTP transaction. * @return N/A. */ TFTP::TFTP_Transaction::TFTP_Transaction() { m_baseDir = ""; m_filename = ""; m_mode = ""; m_opCode = -1; } // TFTP_Transaction /** * @brief Process a client read request. * @return N/A. */ void TFTP::TFTP_Transaction::processRRQ() { /* * 2 bytes 2 bytes n bytes * ---------------------------------- * | Opcode | Block # | Data | * ---------------------------------- * */ FILE* file; bool finished = false; ESP_LOGD(LOG_TAG, "Reading TFTP data from file: %s", m_filename.c_str()); std::string tmpName = m_baseDir + "/" + m_filename; /* struct stat buf; if (stat(tmpName.c_str(), &buf) != 0) { ESP_LOGE(LOG_TAG, "Stat file: %s: %s", tmpName.c_str(), strerror(errno)); return; } int length = buf.st_size; */ int blockNumber = 1; file = fopen(tmpName.c_str(), "r"); if (file == nullptr) { ESP_LOGE(LOG_TAG, "Failed to open file for reading: %s: %s", tmpName.c_str(), strerror(errno)); sendError(ERROR_CODE_FILE_NOT_FOUND, tmpName); return; } struct { uint16_t opCode; uint16_t blockNumber; uint8_t buf[TFTP_DATA_SIZE]; } record; record.opCode = htons(TFTP_OPCODE_DATA); // Set the op code to be DATA. while (!finished) { record.blockNumber = htons(blockNumber); int sizeRead = fread(record.buf, 1, TFTP_DATA_SIZE, file); ESP_LOGD(LOG_TAG, "Sending data to %s, blockNumber=%d, size=%d", Socket::addressToString(&m_partnerAddress).c_str(), blockNumber, sizeRead); m_partnerSocket.sendTo((uint8_t*) &record, sizeRead + 4, &m_partnerAddress); if (sizeRead < TFTP_DATA_SIZE) { finished = true; } else { waitForAck(blockNumber); } blockNumber++; // Increment the block number. } ESP_LOGD(LOG_TAG, "File sent"); } // processRRQ /** * @brief Process a client write request. * @return N/A. */ void TFTP::TFTP_Transaction::processWRQ() { /* * 2 bytes 2 bytes n bytes * --------------------------------- * DATA | 03 | Block # | Data | * --------------------------------- * The opcode for data is 0x03 - TFTP_OPCODE_DATA */ struct recv_data { uint16_t opCode; uint16_t blockNumber; uint8_t data; } *pRecv_data; struct sockaddr recvAddr; uint8_t dataBuffer[TFTP_DATA_SIZE + 2 + 2]; bool finished = false; FILE* file; ESP_LOGD(LOG_TAG, "Writing TFTP data to file: %s", m_filename.c_str()); std::string tmpName = m_baseDir + "/" + m_filename; file = fopen(tmpName.c_str(), "w"); if (file == nullptr) { ESP_LOGE(LOG_TAG, "Failed to open file for writing: %s: %s", tmpName.c_str(), strerror(errno)); return; } while(!finished) { pRecv_data = (struct recv_data*) dataBuffer; int receivedSize = m_partnerSocket.receiveFrom(dataBuffer, sizeof(dataBuffer), &recvAddr); if (receivedSize == -1) { ESP_LOGE(LOG_TAG, "rc == -1 from receive_from"); } struct data_packet dp; dp.blockNumber = ntohs(pRecv_data->blockNumber); dp.data = std::string((char*) &pRecv_data->data, receivedSize - 4); fwrite(dp.data.data(), dp.data.length(), 1, file); sendAck(dp.blockNumber); ESP_LOGD(LOG_TAG, "Block size: %d", dp.data.length()); if (dp.data.length() < TFTP_DATA_SIZE) { finished = true; } } // Finished fclose(file); m_partnerSocket.close(); } // process /** * @brief Send an acknowledgment back to the partner. * A TFTP acknowledgment packet contains an opcode (4) and a block number. * * @param [in] blockNumber The block number to send. * @return N/A. */ void TFTP::TFTP_Transaction::sendAck(uint16_t blockNumber) { struct { uint16_t opCode; uint16_t blockNumber; } ackData; ackData.opCode = htons(TFTP_OPCODE_ACK); ackData.blockNumber = htons(blockNumber); ESP_LOGD(LOG_TAG, "Sending ack to %s, blockNumber=%d", Socket::addressToString(&m_partnerAddress).c_str(), blockNumber); m_partnerSocket.sendTo((uint8_t*) &ackData, sizeof(ackData), &m_partnerAddress); } // sendAck /** * @brief Start being a TFTP server. * * This function does not return. * * @param [in] port The port number on which to listen. The default is 69. * @return N/A. */ void TFTP::start(uint16_t port) { /* * Loop forever. At the start of the loop we block waiting for an incoming client request. * The requests that we are expecting are either a request to read a file from the server * or write a file to the server. Once we have received a request we then call the appropriate * handler to handle that type of request. When the request has been completed, we start again. */ ESP_LOGD(LOG_TAG, "Starting TFTP::start() on port %d", port); Socket serverSocket; serverSocket.listen(port, true); // Create a listening socket that is a datagram. while (true) { // This would be a good place to start a transaction in the background. TFTP_Transaction* pTFTPTransaction = new TFTP_Transaction(); pTFTPTransaction->setBaseDir(m_baseDir); uint16_t receivedOpCode = pTFTPTransaction->waitForRequest(&serverSocket); switch (receivedOpCode) { // Handle the write request (client file upload) case opcode::TFTP_OPCODE_WRQ: { pTFTPTransaction->processWRQ(); break; } // Handle the read request (server file download) case opcode::TFTP_OPCODE_RRQ: { pTFTPTransaction->processRRQ(); break; } default: ESP_LOGE(LOG_TAG, "Unknown opcode: %d", receivedOpCode); break; } delete pTFTPTransaction; } // End while loop } // run /** * @brief Set the base dir for file access. * If we are asked to put a file to the file system, this is the base relative directory. * @param baseDir Base directory for file access. * @return N/A. */ void TFTP::TFTP_Transaction::setBaseDir(std::string baseDir) { m_baseDir = baseDir; } // setBaseDir /** * @brief Set the base dir for file access. * If we are asked to put a file to the file system, this is the base relative directory. * @param baseDir Base directory for file access. * @return N/A. */ void TFTP::setBaseDir(std::string baseDir) { m_baseDir = baseDir; } // setBaseDir /** * @brief Wait for an acknowledgment from the client. * After having sent data to the client, we expect an acknowledment back from the client. * This function causes us to wait for an incoming acknowledgment. */ void TFTP::TFTP_Transaction::waitForAck(uint16_t blockNumber) { struct { uint16_t opCode; uint16_t blockNumber; } ackData; ESP_LOGD(LOG_TAG, "TFTP: Waiting for an acknowledgment request"); int sizeRead = m_partnerSocket.receiveFrom((uint8_t*) &ackData, sizeof(ackData), &m_partnerAddress); ESP_LOGD(LOG_TAG, "TFTP: Received some data."); if (sizeRead != sizeof(ackData)) { ESP_LOGE(LOG_TAG, "waitForAck: Received %d but expected %d", sizeRead, sizeof(ackData)); sendError(ERROR_CODE_NOTDEFINED, "Ack not correct size"); return; } ackData.opCode = ntohs(ackData.opCode); ackData.blockNumber = ntohs(ackData.blockNumber); if (ackData.opCode != opcode::TFTP_OPCODE_ACK) { ESP_LOGE(LOG_TAG, "waitForAck: Received opcode %d but expected %d", ackData.opCode, opcode::TFTP_OPCODE_ACK); return; } if (ackData.blockNumber != blockNumber) { ESP_LOGE(LOG_TAG, "waitForAck: Blocknumber received %d but expected %d", ackData.blockNumber, blockNumber); return; } } // waitForAck /** * @brief Wait for a client request. * A %TFTP server waits for requests to send or receive files. A request can be * either WRQ (write request) which is a request from the client to write a new local * file or it can be a RRQ (read request) which is a request from the client to * read a local file. * @param pServerSocket The server socket on which to listen for client requests. * @return The op code received. */ /* * 2 bytes string 1 byte string 1 byte * ----------------------------------------------- * RRQ/ | 01/02 | Filename | 0 | Mode | 0 | * WRQ ----------------------------------------------- */ uint16_t TFTP::TFTP_Transaction::waitForRequest(Socket* pServerSocket) { union { uint8_t buf[TFTP_DATA_SIZE]; uint16_t opCode; } record; size_t length = 100; ESP_LOGD(LOG_TAG, "TFTP: Waiting for a request"); pServerSocket->receiveFrom(record.buf, length, &m_partnerAddress); // Save the filename, mode and op code. m_filename = std::string((char*) (record.buf + 2)); m_mode = std::string((char*) (record.buf + 3 + m_filename.length())); m_opCode = ntohs(record.opCode); switch (m_opCode) { // Handle the Write Request command. case TFTP_OPCODE_WRQ: { m_partnerSocket.createSocket(true); m_partnerSocket.bind(0, INADDR_ANY); sendAck(0); break; } // Handle the Read request command. case TFTP_OPCODE_RRQ: { m_partnerSocket.createSocket(true); m_partnerSocket.bind(0, INADDR_ANY); break; } default: { ESP_LOGD(LOG_TAG, "Un-handled opcode: %d", m_opCode); break; } } return m_opCode; } // waitForRequest /** * @brief Send an error indication to the client. * @param [in] code Error code to send to the client. * @param [in] message Explanation message. * @return N/A. */ void TFTP::TFTP_Transaction::sendError(uint16_t code, std::string message) { /* * 2 bytes 2 bytes string 1 byte * ----------------------------------------- * | Opcode | ErrorCode | ErrMsg | 0 | * ----------------------------------------- */ int size = 2 + 2 + message.length() + 1; uint8_t* buf = (uint8_t*) malloc(size); *(uint16_t*) (&buf[0]) = htons(opcode::TFTP_OPCODE_ERROR); *(uint16_t*) (&buf[2]) = htons(code); strcpy((char*) (&buf[4]), message.c_str()); m_partnerSocket.sendTo(buf, size, &m_partnerAddress); free(buf); } // sendError
10,916
4,241
/* textdefs.c diStorm3 - Powerful disassembler for X86/AMD64 http://ragestorm.net/distorm/ distorm at gmail dot com Copyright (C) 2003-2016 Gil Dabah This library is licensed under the BSD license. See the file COPYING. */ #include <stdafx.h> #include "textdefs.h" #ifndef DISTORM_LIGHT static uint8_t Nibble2ChrTable[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; #define NIBBLE_TO_CHR Nibble2ChrTable[t] void _FASTCALL_ str_hex_b(_WString* s, unsigned int x) { /* * def prebuilt(): * s = "" * for i in xrange(256): * if ((i % 0x10) == 0): * s += "\r\n" * s += "\"%02x\", " % (i) * return s */ static int8_t TextBTable[256][3] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff" }; /* * Fixed length of 3 including null terminate character. */ memcpy(&s->p[s->length], TextBTable[x & 255], 3); s->length += 2; } void _FASTCALL_ str_code_hb(_WString* s, unsigned int x) { static int8_t TextHBTable[256][5] = { /* * def prebuilt(): * s = "" * for i in xrange(256): * if ((i % 0x10) == 0): * s += "\r\n" * s += "\"0x%x\", " % (i) * return s */ "0x0", "0x1", "0x2", "0x3", "0x4", "0x5", "0x6", "0x7", "0x8", "0x9", "0xa", "0xb", "0xc", "0xd", "0xe", "0xf", "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1a", "0x1b", "0x1c", "0x1d", "0x1e", "0x1f", "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2a", "0x2b", "0x2c", "0x2d", "0x2e", "0x2f", "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3a", "0x3b", "0x3c", "0x3d", "0x3e", "0x3f", "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4a", "0x4b", "0x4c", "0x4d", "0x4e", "0x4f", "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5a", "0x5b", "0x5c", "0x5d", "0x5e", "0x5f", "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6a", "0x6b", "0x6c", "0x6d", "0x6e", "0x6f", "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7a", "0x7b", "0x7c", "0x7d", "0x7e", "0x7f", "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8a", "0x8b", "0x8c", "0x8d", "0x8e", "0x8f", "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9a", "0x9b", "0x9c", "0x9d", "0x9e", "0x9f", "0xa0", "0xa1", "0xa2", "0xa3", "0xa4", "0xa5", "0xa6", "0xa7", "0xa8", "0xa9", "0xaa", "0xab", "0xac", "0xad", "0xae", "0xaf", "0xb0", "0xb1", "0xb2", "0xb3", "0xb4", "0xb5", "0xb6", "0xb7", "0xb8", "0xb9", "0xba", "0xbb", "0xbc", "0xbd", "0xbe", "0xbf", "0xc0", "0xc1", "0xc2", "0xc3", "0xc4", "0xc5", "0xc6", "0xc7", "0xc8", "0xc9", "0xca", "0xcb", "0xcc", "0xcd", "0xce", "0xcf", "0xd0", "0xd1", "0xd2", "0xd3", "0xd4", "0xd5", "0xd6", "0xd7", "0xd8", "0xd9", "0xda", "0xdb", "0xdc", "0xdd", "0xde", "0xdf", "0xe0", "0xe1", "0xe2", "0xe3", "0xe4", "0xe5", "0xe6", "0xe7", "0xe8", "0xe9", "0xea", "0xeb", "0xec", "0xed", "0xee", "0xef", "0xf0", "0xf1", "0xf2", "0xf3", "0xf4", "0xf5", "0xf6", "0xf7", "0xf8", "0xf9", "0xfa", "0xfb", "0xfc", "0xfd", "0xfe", "0xff" }; if (x < 0x10) { /* < 0x10 has a fixed length of 4 including null terminate. */ memcpy(&s->p[s->length], TextHBTable[x & 255], 4); s->length += 3; } else { /* >= 0x10 has a fixed length of 5 including null terminate. */ memcpy(&s->p[s->length], TextHBTable[x & 255], 5); s->length += 4; } } void _FASTCALL_ str_code_hdw(_WString* s, uint32_t x) { int8_t* buf; int i = 0, shift = 0; unsigned int t = 0; buf = (int8_t*)&s->p[s->length]; buf[0] = '0'; buf[1] = 'x'; buf += 2; for (shift = 28; shift != 0; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } t = x & 0xf; buf[i++] = NIBBLE_TO_CHR; s->length += i + 2; buf[i] = '\0'; } void _FASTCALL_ str_code_hqw(_WString* s, uint8_t src[8]) { int8_t* buf; int i = 0, shift = 0; uint32_t x = RULONG(&src[sizeof(int32_t)]); int t; buf = (int8_t*)&s->p[s->length]; buf[0] = '0'; buf[1] = 'x'; buf += 2; for (shift = 28; shift != -4; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } x = RULONG(src); for (shift = 28; shift != 0; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } t = x & 0xf; buf[i++] = NIBBLE_TO_CHR; s->length += i + 2; buf[i] = '\0'; } #ifdef SUPPORT_64BIT_OFFSET void _FASTCALL_ str_off64(_WString* s, OFFSET_INTEGER x) { int8_t* buf; int i = 0, shift = 0; OFFSET_INTEGER t = 0; buf = (int8_t*)&s->p[s->length]; buf[0] = '0'; buf[1] = 'x'; buf += 2; for (shift = 60; shift != 0; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } t = x & 0xf; buf[i++] = NIBBLE_TO_CHR; s->length += i + 2; buf[i] = '\0'; } #endif /* SUPPORT_64BIT_OFFSET */ #endif /* DISTORM_LIGHT */
6,462
4,052
// // UtcTime - shows how to use UTC time in logs. // #include <plog/Log.h> #include <plog/Init.h> #include <plog/Formatters/CsvFormatter.h> #include <plog/Formatters/TxtFormatter.h> #include <plog/Appenders/ColorConsoleAppender.h> #include <plog/Appenders/RollingFileAppender.h> int main() { static plog::ColorConsoleAppender<plog::TxtFormatterUtcTime> consoleAppender; // TxtFormatter in UTC static plog::RollingFileAppender<plog::CsvFormatterUtcTime> fileAppender("UtcTime.csv", 10000, 2); // CsvFormatter in UTC plog::init(plog::verbose, &consoleAppender).addAppender(&fileAppender); PLOG_VERBOSE << "This is a VERBOSE message"; PLOG_DEBUG << "This is a DEBUG message"; PLOG_INFO << "This is an INFO message"; PLOG_WARNING << "This is a WARNING message"; PLOG_ERROR << "This is an ERROR message"; PLOG_FATAL << "This is a FATAL message"; return 0; }
898
329
#include "bam.h" #include "sam.h" #include "stdlib.h" #include <vector> #include <string> #include <set> #include <iostream> #include <fstream> #include <map> #include <sstream> #include <numeric> #include <iomanip> using namespace std; typedef struct { int beg, end; samfile_t *in; } tmpstruct_t; int GetTLen(const bam1_t *b) { uint32_t *cigar = bam1_cigar(b); int len = b->core.n_cigar; int tlen = 0; int i; for (i = 0; i < len; i++) { int op = cigar[i] & 0xf; int oplen = cigar[i] >> 4; if (op == BAM_CMATCH or op == BAM_CDEL) { tlen += oplen; } } return tlen; } int main(int argc, char* argv[]) { int ret; bam_index_t *idx; bam_plbuf_t *buf; if (argc < 4) { cout << "usage: bamc out.bed [-in <filename> -in <filename> ... ] ... [options ]" << endl; cout << " Prints coverage by base." << endl; cout << " Options: " << endl; cout << " -q q min mapping quality (30)" << endl; cout << " -b b bin size . " << endl; exit(1); } string outFileName; outFileName = argv[1]; int argi = 2; int minQuality = 30; int bin = 50; vector<string> bamFileNames; while ( argi < argc ) { if (strcmp(argv[argi], "-q") == 0) { ++argi; minQuality = atoi(argv[argi]); ++argi; } if (strcmp(argv[argi], "-b") == 0) { ++argi; bin = atoi(argv[argi]); ++argi; } if (strcmp(argv[argi], "-in") == 0) { ++argi; bamFileNames.push_back(argv[argi]); ++argi; } } ofstream outFile(outFileName.c_str()); int i; int bamI = 0; vector<vector<int> > coverage; bam_header_t *header; int readIndex =0 ; long totalNumBases = 0; cout << "Found " << bamFileNames.size() << " BAM files\n"; for (bamI = 0; bamI < bamFileNames.size(); bamI++) { bamFile in; in = bam_open(bamFileNames[bamI].c_str(), "rb"); cout << "Processing " << bamFileNames[bamI].c_str() << "\n"; header = bam_header_read(in); if (bamI == 0) { coverage.resize(header->n_targets); for (i = 0; i < header->n_targets; i++) { coverage[i].resize(header->target_len[i]/bin + (header->target_len[i]%bin== 0? 0 : 1), 0); } } bam1_t *b = bam_init1(); cout << "Start loop\n"; while (bam_read1(in, b) >= 0) { cout << "Read: " << readIndex << "\n"; int tStart = b->core.pos; int tEnd = b->core.pos + GetTLen(b); // if (b->core.qual >= minQuality) { // vector<int>* v = &coverage[b->core.tid]; // for (i = tStart; i < tEnd; i++) { // (*v)[i/bin]+=1; // } // } ++readIndex; totalNumBases += tEnd - tStart; if (readIndex % 10000 == 0) { cerr << "processed " << readIndex << " reads " << totalNumBases / 1000000000 << "Gb" << endl; } } cout << "End loop\n"; bam_destroy1(b); // Destroy the header as long as this isn't the last BAM to be // processed. The header of the last BAM will be used to create the // output for overall coverage. if (bamI < bamFileNames.size() - 1) { bam_header_destroy(header); } bam_close(in); } cout << "Done processing BAMs\n"; for (i = 0; i < header->n_targets; i++) { int p; int lastBinIndex = header->target_len[i] / bin + (header->target_len[i] / bin == 0? 0 : 1); for (p = 0; p < lastBinIndex - 1; p++) { outFile << header->target_name[i] << "\t" << p*bin << "\t" << (p+1)*bin << "\t" << std::setw(4) << float(coverage[i][p]) / bin << endl; } int lastBinLength = header->target_len[i] - (lastBinIndex -1) * bin; if (lastBinLength > 0) { outFile << header->target_name[i] << "\t" << p *bin << "\t" << header->target_len[i] << "\t" << float(coverage[i][p]) / lastBinLength << endl; } } bam_header_destroy(header); outFile.close(); }
3,723
1,716
// Fill out your copyright notice in the Description page of Project Settings. #include "CompoundStorageComponent_Cell.h" #include "Character_SingleCelled.h" #include "Logging.h" #include "Runtime/Engine/Classes/Kismet/GameplayStatics.h" #include "Meta_CellStage.h" // Sets default values for this component's properties UCompoundStorageComponent_Cell::UCompoundStorageComponent_Cell() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // ... } // Called when the game starts void UCompoundStorageComponent_Cell::BeginPlay() { Super::BeginPlay(); SetCompounds(); StartLowCompoundCycle(); lowCompound = "Carbon"; _protein.maximum = 100; _protein.current = 25; } // Called every frame void UCompoundStorageComponent_Cell::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); // ... } /*---------------------------------------------------------------------------------------------------------------------------------------------------------------*/ ////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// PRIVATE //////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void UCompoundStorageComponent_Cell::EnforceCompoundBalance() { AddCompound(_playerCompounds._CO2.balance, ECompound::ECO2); AddCompound(_playerCompounds._O2.balance, ECompound::EO2); AddCompound(_playerCompounds._AminoAcid.balance, ECompound::EAminoAcid); AddCompound(_playerCompounds._Glucose.balance, ECompound::EGlucose); AddCompound(_playerCompounds._Lipid.balance, ECompound::ELipid); //First of all set the volume back on the player ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(this->GetOwner()); if (controller != nullptr) { controller->GetWorldTimerManager().SetTimer(consumptionTimer, this, &UCompoundStorageComponent_Cell::EnforceCompoundBalance, SURROUNDINGS_DELTA_TIME, false); } } FString UCompoundStorageComponent_Cell::GetCompoundName(ECompound compound) { return FString(); } void UCompoundStorageComponent_Cell::UpdateLowCompound() { ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0)); if (controller != nullptr) { TArray<bool> isLow = { false, //CO2 false, //oxygen false, //amino acid false, //glucose false //lipid }; //cycle through all compounds and see if the are <= than 10% of their maximum //if they are set, their value in the array to true //after this is done: //check if maybe there are no compounds that are low // in that case set lowCompound to "" //most likely that won't be the case so: //check what currently is in lowCompound //start at that value in the array and go to the next one that is low and set it // current amount / maximum <= 0.1f isLow[0] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::ECO2, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::ECO2, true)) <= 0.1f; isLow[1] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EO2, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EO2, true)) <= 0.1f; isLow[2] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EAminoAcid, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EAminoAcid, true)) <= 0.1f; isLow[3] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EGlucose, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EGlucose, true)) <= 0.1f; isLow[4] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::ELipid, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::ELipid, true)) <= 0.1f; if (!isLow[0] && !isLow[1] && !isLow[2] && !isLow[3] && !isLow[4]) { lowCompound = ""; _eLowCompound = ECompound::ENothing; } else { int start = 0; if (_eLowCompound == ECompound::ENothing) { start = 0; } else if (_eLowCompound == ECompound::ECO2) { start = 1; } else if (_eLowCompound == ECompound::EO2) { start = 2; } else if (_eLowCompound == ECompound::EAminoAcid) { start = 3; } else if (_eLowCompound == ECompound::EGlucose) { start = 4; } else if (_eLowCompound == ECompound::ELipid) { start = 0; } //6 so it can return to the starting position if there are not other compounds int position = 0; for (position; position < 6; position++) { if (isLow[(start + position) % 5]) { break; } } switch ((start + position) % 5) { case 0: lowCompound = "CO2"; _eLowCompound = ECompound::ECO2; break; case 1: lowCompound = "Oxygen"; _eLowCompound = ECompound::EO2; break; case 2: lowCompound = "Amino Acids"; _eLowCompound = ECompound::EAminoAcid; break; case 3: lowCompound = "Glucose"; _eLowCompound = ECompound::EGlucose; break; case 4: lowCompound = "Lipids"; _eLowCompound = ECompound::ELipid; break; default: _eLowCompound = ECompound::ENothing; lowCompound = "ERROR"; break; } } controller->GetWorldTimerManager().SetTimer(lowCompoundRefreshTimer, this, &UCompoundStorageComponent_Cell::UpdateLowCompound, 2.f, false); } } ////////////////////////////////////////////////////////////////////////////// //////////////////////////////// PROTECTED /////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void UCompoundStorageComponent_Cell::StartLowCompoundCycle() { //ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0)); //if (controller != nullptr) //{ // controller->GetWorldTimerManager().SetTimer(lowCompoundRefreshTimer, this, &AGameMode_Cell::UpdateLowCompound, 2.f, false); //} UpdateLowCompound(); } ////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// PUBLIC ///////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void UCompoundStorageComponent_Cell::SetCompounds() { //CO2 _playerCompounds._CO2.maximum = 10000.f; _playerCompounds._CO2.current = 1000.f; _playerCompounds._CO2.balance = -1; //Oxygen _playerCompounds._O2.maximum = 10000.f; _playerCompounds._O2.current = 1000.f; _playerCompounds._O2.balance = -1; //Amino Acid _playerCompounds._AminoAcid.maximum = 10000.f; _playerCompounds._AminoAcid.current = 1000.f; _playerCompounds._AminoAcid.balance = -1; //Glucose _playerCompounds._Glucose.maximum = 10000.f; _playerCompounds._Glucose.current = 1000.f; _playerCompounds._Glucose.balance = -1; //Lipid _playerCompounds._Lipid.maximum = 10000.f; _playerCompounds._Lipid.current = 1000.f; _playerCompounds._Lipid.balance = -1; } void UCompoundStorageComponent_Cell::AddCompound(int amount, ECompound compound) { //find the right compound to add the amount if (compound == ECompound::ECO2) { Logging::Log(_playerCompounds._CO2.current); Logging::Log(amount); //add the amount _playerCompounds._CO2.current = _playerCompounds._CO2.current + amount; //check if it's greater than the maximum or smaller than 0 and correct that if (_playerCompounds._CO2.current > _playerCompounds._CO2.maximum) { _playerCompounds._CO2.current = _playerCompounds._CO2.maximum; } else if (_playerCompounds._CO2.current < 0) { _playerCompounds._CO2.current = 0; } } else if (compound == ECompound::EO2) { Logging::Log(_playerCompounds._O2.current); Logging::Log(amount); _playerCompounds._O2.current = _playerCompounds._O2.current + amount; if (_playerCompounds._O2.current > _playerCompounds._O2.maximum) { _playerCompounds._O2.current = _playerCompounds._O2.maximum; } else if (_playerCompounds._O2.current < 0) { _playerCompounds._O2.current = 0; } } else if (compound == ECompound::EAminoAcid) { Logging::Log(_playerCompounds._AminoAcid.current); Logging::Log(amount); _playerCompounds._AminoAcid.current = _playerCompounds._AminoAcid.current + amount; if (_playerCompounds._AminoAcid.current > _playerCompounds._AminoAcid.maximum) { _playerCompounds._AminoAcid.current = _playerCompounds._AminoAcid.maximum; } else if (_playerCompounds._AminoAcid.current < 0) { _playerCompounds._AminoAcid.current = 0; } } else if (compound == ECompound::EGlucose) { Logging::Log(_playerCompounds._Glucose.current); Logging::Log(amount); _playerCompounds._Glucose.current = _playerCompounds._Glucose.current + amount; if (_playerCompounds._Glucose.current > _playerCompounds._Glucose.maximum) { _playerCompounds._Glucose.current = _playerCompounds._Glucose.maximum; } else if (_playerCompounds._Glucose.current < 0) { _playerCompounds._Glucose.current = 0; } } else if (compound == ECompound::ELipid) { Logging::Log(_playerCompounds._Lipid.current); Logging::Log(amount); _playerCompounds._Lipid.current = _playerCompounds._Lipid.current + amount; if (_playerCompounds._Lipid.current > _playerCompounds._Lipid.maximum) { _playerCompounds._Lipid.current = _playerCompounds._Lipid.maximum; } else if (_playerCompounds._Lipid.current < 0) { _playerCompounds._Lipid.current = 0; } } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at AddCompound()"), *GetCompoundName(compound)); } } int UCompoundStorageComponent_Cell::GetCompound(ECompound compound, bool bMax) { if (bMax) { if (compound == ECompound::ECO2) { return _playerCompounds._CO2.maximum; } else if (compound == ECompound::EO2) { return _playerCompounds._O2.maximum; } else if (compound == ECompound::EAminoAcid) { return _playerCompounds._AminoAcid.maximum; } else if (compound == ECompound::EGlucose) { return _playerCompounds._Glucose.maximum; } else if (compound == ECompound::ELipid) { return _playerCompounds._Lipid.maximum; } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompound()"), *GetCompoundName(compound)); return 0; } } else { if (compound == ECompound::ECO2) { return _playerCompounds._CO2.current; } else if (compound == ECompound::EO2) { return _playerCompounds._O2.current; } else if (compound == ECompound::EAminoAcid) { return _playerCompounds._AminoAcid.current; } else if (compound == ECompound::EGlucose) { return _playerCompounds._Glucose.current; } else if (compound == ECompound::ELipid) { return _playerCompounds._Lipid.current; } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompound()"), *GetCompoundName(compound)); return 0; } } } int UCompoundStorageComponent_Cell::GetCompoundBalance(ECompound compound) { if (compound == ECompound::ECO2) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._CO2.balance; } } else if (compound == ECompound::EO2) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._O2.balance; } } else if (compound == ECompound::EAminoAcid) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._AminoAcid.balance; } } else if (compound == ECompound::EGlucose) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._Glucose.balance; } } else if (compound == ECompound::ELipid) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._Lipid.balance; } } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompoundBalance()"), *GetCompoundName(compound)); return 0; } } void UCompoundStorageComponent_Cell::AddProtein(int amount) { _protein.current += amount; if (_protein.current > _protein.maximum) { _protein.current = _protein.maximum; } else if (_protein.current < 0) { _protein.current = 0; } } int UCompoundStorageComponent_Cell::GetProtein(bool bMax) { if (bMax) { return _protein.maximum; } else { return _protein.current; } } FString UCompoundStorageComponent_Cell::GetLowCompound() { return lowCompound; }
12,690
5,064
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "myriad_metrics.h" #include <algorithm> #include <vpu/utils/error.hpp> using namespace vpu::MyriadPlugin; using namespace InferenceEngine; using namespace VPUConfigParams; using namespace PluginConfigParams; //------------------------------------------------------------------------------ // Implementation of methods of class MyriadMetrics //------------------------------------------------------------------------------ MyriadMetrics::MyriadMetrics() { _supportedMetrics = { METRIC_KEY(AVAILABLE_DEVICES), METRIC_KEY(FULL_DEVICE_NAME), METRIC_KEY(SUPPORTED_METRICS), METRIC_KEY(SUPPORTED_CONFIG_KEYS), METRIC_KEY(OPTIMIZATION_CAPABILITIES), METRIC_KEY(RANGE_FOR_ASYNC_INFER_REQUESTS), METRIC_KEY(DEVICE_THERMAL), }; IE_SUPPRESS_DEPRECATED_START _supportedConfigKeys = { MYRIAD_ENABLE_HW_ACCELERATION, MYRIAD_ENABLE_RECEIVING_TENSOR_TIME, MYRIAD_CUSTOM_LAYERS, MYRIAD_ENABLE_FORCE_RESET, MYRIAD_THROUGHPUT_STREAMS, // deprecated KEY_VPU_HW_STAGES_OPTIMIZATION, KEY_VPU_PRINT_RECEIVE_TENSOR_TIME, KEY_VPU_CUSTOM_LAYERS, KEY_VPU_MYRIAD_FORCE_RESET, KEY_VPU_MYRIAD_PLATFORM, CONFIG_KEY(LOG_LEVEL), CONFIG_KEY(EXCLUSIVE_ASYNC_REQUESTS), CONFIG_KEY(PERF_COUNT), CONFIG_KEY(CONFIG_FILE), CONFIG_KEY(DEVICE_ID) }; IE_SUPPRESS_DEPRECATED_END _optimizationCapabilities = { METRIC_VALUE(FP16) }; _rangeForAsyncInferRequests = RangeType(3, 6, 1); _idToDeviceFullNameMap = { {"5", "Intel Movidius Myriad 2 VPU"}, {"8", "Intel Movidius Myriad X VPU"}, }; } std::vector<std::string> MyriadMetrics::AvailableDevicesNames( const std::shared_ptr<IMvnc> &mvnc, const std::vector<DevicePtr> &devicePool) const { std::vector<std::string> availableDevices; auto unbootedDevices = mvnc->AvailableDevicesNames(); availableDevices.insert(availableDevices.begin(), unbootedDevices.begin(), unbootedDevices.end()); for (auto & device : devicePool) { availableDevices.push_back(device->_name); } std::sort(availableDevices.begin(), availableDevices.end()); return availableDevices; } std::string MyriadMetrics::FullName(std::string deviceName) const { std::string nameDelimiter("-ma"); unsigned int indexLenght = 4; unsigned int placeOfTypeId = 2; auto indexStr = deviceName; indexStr.erase(0, indexStr.find(nameDelimiter) + nameDelimiter.length()); if (indexLenght != indexStr.length()) { return deviceName; } else { auto myriadId = std::string(1, indexStr[placeOfTypeId]); if (_idToDeviceFullNameMap.count(myriadId)) { return _idToDeviceFullNameMap.at(myriadId); } } return deviceName; } float MyriadMetrics::DevicesThermal(const DevicePtr& device) const { VPU_THROW_UNLESS(device != nullptr, "No device specified to get its thermal"); return MyriadExecutor::GetThermal(device); } const std::unordered_set<std::string>& MyriadMetrics::SupportedMetrics() const { return _supportedMetrics; } const std::unordered_set<std::string>& MyriadMetrics::SupportedConfigKeys() const { return _supportedConfigKeys; } const std::unordered_set<std::string>& MyriadMetrics::OptimizationCapabilities() const { return _optimizationCapabilities; } RangeType MyriadMetrics::RangeForAsyncInferRequests( const std::map<std::string, std::string>& config) const { auto throughput_streams_str = config.find(ie::MYRIAD_THROUGHPUT_STREAMS); if (throughput_streams_str != config.end()) { try { int throughput_streams = std::stoi(throughput_streams_str->second); if (throughput_streams > 0) { return RangeType(throughput_streams+1, throughput_streams*3, 1); } } catch(...) { THROW_IE_EXCEPTION << "Invalid config value for MYRIAD_THROUGHPUT_STREAMS, can't cast to int"; } } return _rangeForAsyncInferRequests; }
4,202
1,459
#include "enclave.h" int enclave_b_flow(oe_enclave_t* enclave, const char* input_file) { int ret = 0; const char* encrypted_file = "./out.encrypted"; const char* decrypted_file = "./out.decrypted"; // encrypt a file std::cout << "Host: decrypting file:" << decrypted_file << std::endl; ret = encrypt_file(enclave, DECRYPT_OPERATION, encrypted_file, decrypted_file); if (ret != 0) { std::cerr << "Host: processFile(DECRYPT_OPERATION) failed with " << ret << std::endl; return 1; } // Make sure the decryption is successfull. Input and decrypted files // are equal std::cout << "Host: compared file:" << decrypted_file << " to file:" << input_file << std::endl; ret = compare_2_files(input_file, decrypted_file); if (ret != 0) { std::cerr << "Host: checking failed! " << decrypted_file << "'s contents are supposed to be same as " << input_file << std::endl; return 1; } std::cout << "Host: " << decrypted_file << " is equal to " << input_file << " as expected" << std::endl; std::cout << "Host: decryption was done successfully" << std::endl; return ret; }
1,230
398
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdint.h> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include <mesos/mesos.hpp> #include <mesos/authorizer/authorizer.hpp> #include <mesos/allocator/allocator.hpp> #include <mesos/master/contender.hpp> #include <mesos/master/detector.hpp> #include <mesos/module/anonymous.hpp> #include <mesos/module/authorizer.hpp> #include <mesos/state/in_memory.hpp> #ifndef __WINDOWS__ #include <mesos/state/log.hpp> #endif // __WINDOWS__ #include <mesos/state/state.hpp> #include <mesos/state/storage.hpp> #include <mesos/zookeeper/detector.hpp> #include <process/limiter.hpp> #include <process/owned.hpp> #include <process/pid.hpp> #include <stout/check.hpp> #include <stout/duration.hpp> #include <stout/exit.hpp> #include <stout/flags.hpp> #include <stout/nothing.hpp> #include <stout/option.hpp> #include <stout/os.hpp> #include <stout/path.hpp> #include <stout/stringify.hpp> #include <stout/strings.hpp> #include <stout/try.hpp> #include <stout/version.hpp> #include "common/build.hpp" #include "common/http.hpp" #include "common/protobuf_utils.hpp" #include "hook/manager.hpp" #include "logging/flags.hpp" #include "logging/logging.hpp" #include "master/master.hpp" #include "master/registrar.hpp" #include "master/allocator/mesos/hierarchical.hpp" #include "master/detector/standalone.hpp" #include "module/manager.hpp" #include "version/version.hpp" using namespace mesos::internal; #ifndef __WINDOWS__ using namespace mesos::internal::log; #endif // __WINDOWS__ using namespace mesos::internal::master; using namespace zookeeper; using mesos::Authorizer; using mesos::MasterInfo; using mesos::Parameter; using mesos::Parameters; #ifndef __WINDOWS__ using mesos::log::Log; #endif // __WINDOWS__ using mesos::allocator::Allocator; using mesos::master::contender::MasterContender; using mesos::master::detector::MasterDetector; using mesos::master::detector::StandaloneMasterDetector; using mesos::modules::Anonymous; using mesos::modules::ModuleManager; using mesos::state::InMemoryStorage; #ifndef __WINDOWS__ using mesos::state::LogStorage; #endif // __WINDOWS__ using mesos::state::Storage; using process::Owned; using process::RateLimiter; using process::UPID; using process::firewall::DisabledEndpointsFirewallRule; using process::firewall::FirewallRule; using std::cerr; using std::cout; using std::endl; using std::move; using std::ostringstream; using std::set; using std::shared_ptr; using std::string; using std::vector; int main(int argc, char** argv) { // The order of initialization of various master components is as follows: // * Validate flags. // * Logging. // * Log build information. // * Libprocess. // * Version process. // * Firewall rules: should be initialized before initializing HTTP endpoints. // * Modules: Load module libraries and manifests before they // can be instantiated. // * Anonymous modules: Later components such as Allocators, and master // contender/detector might depend upon anonymous modules. // * Hooks. // * Allocator. // * Registry storage. // * State. // * Master contender. // * Master detector. // * Authorizer. // * Slave removal rate limiter. // * `Master` process. // // TODO(avinash): Add more comments discussing the rationale behind for this // particular component ordering. GOOGLE_PROTOBUF_VERIFY_VERSION; master::Flags flags; Try<flags::Warnings> load = flags.load("MESOS_", argc, argv); if (flags.help) { cout << flags.usage() << endl; return EXIT_SUCCESS; } if (flags.version) { cout << "mesos" << " " << MESOS_VERSION << endl; return EXIT_SUCCESS; } if (load.isError()) { cerr << flags.usage(load.error()) << endl; return EXIT_FAILURE; } logging::initialize(argv[0], true, flags); // Catch signals. // Log any flag warnings (after logging is initialized). foreach (const flags::Warning& warning, load->warnings) { LOG(WARNING) << warning.message; } // Check that master's version has the expected format (SemVer). { Try<Version> version = Version::parse(MESOS_VERSION); if (version.isError()) { EXIT(EXIT_FAILURE) << "Failed to parse Mesos version '" << MESOS_VERSION << "': " << version.error(); } } if (flags.ip_discovery_command.isSome() && flags.ip.isSome()) { EXIT(EXIT_FAILURE) << flags.usage( "Only one of `--ip` or `--ip_discovery_command` should be specified"); } if (flags.ip_discovery_command.isSome()) { Try<string> ipAddress = os::shell(flags.ip_discovery_command.get()); if (ipAddress.isError()) { EXIT(EXIT_FAILURE) << ipAddress.error(); } os::setenv("LIBPROCESS_IP", strings::trim(ipAddress.get())); } else if (flags.ip.isSome()) { os::setenv("LIBPROCESS_IP", flags.ip.get()); } os::setenv("LIBPROCESS_PORT", stringify(flags.port)); if (flags.advertise_ip.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_IP", flags.advertise_ip.get()); } if (flags.advertise_port.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_PORT", flags.advertise_port.get()); } if (flags.zk.isNone()) { if (flags.master_contender.isSome() ^ flags.master_detector.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Both --master_contender and --master_detector should " "be specified or omitted."); } } else { if (flags.master_contender.isSome() || flags.master_detector.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --zk or the " "--master_contender/--master_detector " "pair should be specified."); } } // Log build information. LOG(INFO) << "Build: " << build::DATE << " by " << build::USER; LOG(INFO) << "Version: " << MESOS_VERSION; if (build::GIT_TAG.isSome()) { LOG(INFO) << "Git tag: " << build::GIT_TAG.get(); } if (build::GIT_SHA.isSome()) { LOG(INFO) << "Git SHA: " << build::GIT_SHA.get(); } // This should be the first invocation of `process::initialize`. If it returns // `false`, then it has already been called, which means that the // authentication realm for libprocess-level HTTP endpoints was not set to the // correct value for the master. if (!process::initialize( "master", READWRITE_HTTP_AUTHENTICATION_REALM, READONLY_HTTP_AUTHENTICATION_REALM)) { EXIT(EXIT_FAILURE) << "The call to `process::initialize()` in the master's " << "`main()` was not the function's first invocation"; } spawn(new VersionProcess(), true); // Initialize firewall rules. if (flags.firewall_rules.isSome()) { vector<Owned<FirewallRule>> rules; const Firewall firewall = flags.firewall_rules.get(); if (firewall.has_disabled_endpoints()) { hashset<string> paths; foreach (const string& path, firewall.disabled_endpoints().paths()) { paths.insert(path); } rules.emplace_back(new DisabledEndpointsFirewallRule(paths)); } process::firewall::install(move(rules)); } // Initialize modules. if (flags.modules.isSome() && flags.modulesDir.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --modules or --modules_dir should be specified"); } if (flags.modulesDir.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modulesDir.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } if (flags.modules.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modules.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } // Create anonymous modules. foreach (const string& name, ModuleManager::find<Anonymous>()) { Try<Anonymous*> create = ModuleManager::create<Anonymous>(name); if (create.isError()) { EXIT(EXIT_FAILURE) << "Failed to create anonymous module named '" << name << "'"; } // We don't bother keeping around the pointer to this anonymous // module, when we exit that will effectively free its memory. // // TODO(benh): We might want to add explicit finalization (and // maybe explicit initialization too) in order to let the module // do any housekeeping necessary when the master is cleanly // terminating. } // Initialize hooks. if (flags.hooks.isSome()) { Try<Nothing> result = HookManager::initialize(flags.hooks.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error installing hooks: " << result.error(); } } // Create an instance of allocator. const string allocatorName = flags.allocator; Try<Allocator*> allocator = Allocator::create(allocatorName); if (allocator.isError()) { EXIT(EXIT_FAILURE) << "Failed to create '" << allocatorName << "' allocator: " << allocator.error(); } CHECK_NOTNULL(allocator.get()); LOG(INFO) << "Using '" << allocatorName << "' allocator"; Storage* storage = nullptr; #ifndef __WINDOWS__ Log* log = nullptr; #endif // __WINDOWS__ if (flags.registry == "in_memory") { storage = new InMemoryStorage(); #ifndef __WINDOWS__ } else if (flags.registry == "replicated_log" || flags.registry == "log_storage") { // TODO(bmahler): "log_storage" is present for backwards // compatibility, can be removed before 0.19.0. if (flags.work_dir.isNone()) { EXIT(EXIT_FAILURE) << "--work_dir needed for replicated log based registry"; } Try<Nothing> mkdir = os::mkdir(flags.work_dir.get()); if (mkdir.isError()) { EXIT(EXIT_FAILURE) << "Failed to create work directory '" << flags.work_dir.get() << "': " << mkdir.error(); } if (flags.zk.isSome()) { // Use replicated log with ZooKeeper. if (flags.quorum.isNone()) { EXIT(EXIT_FAILURE) << "Need to specify --quorum for replicated log based" << " registry when using ZooKeeper"; } Try<zookeeper::URL> url = zookeeper::URL::parse(flags.zk.get()); if (url.isError()) { EXIT(EXIT_FAILURE) << "Error parsing ZooKeeper URL: " << url.error(); } log = new Log( flags.quorum.get(), path::join(flags.work_dir.get(), "replicated_log"), url.get().servers, flags.zk_session_timeout, path::join(url.get().path, "log_replicas"), url.get().authentication, flags.log_auto_initialize, "registrar/"); } else { // Use replicated log without ZooKeeper. log = new Log( 1, path::join(flags.work_dir.get(), "replicated_log"), set<UPID>(), flags.log_auto_initialize, "registrar/"); } storage = new LogStorage(log); #endif // __WINDOWS__ } else { EXIT(EXIT_FAILURE) << "'" << flags.registry << "' is not a supported" << " option for registry persistence"; } CHECK_NOTNULL(storage); mesos::state::State* state = new mesos::state::State(storage); Registrar* registrar = new Registrar(flags, state, READONLY_HTTP_AUTHENTICATION_REALM); MasterContender* contender; MasterDetector* detector; Try<MasterContender*> contender_ = MasterContender::create( flags.zk, flags.master_contender, flags.zk_session_timeout); if (contender_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master contender: " << contender_.error(); } contender = contender_.get(); Try<MasterDetector*> detector_ = MasterDetector::create( flags.zk, flags.master_detector, flags.zk_session_timeout); if (detector_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master detector: " << detector_.error(); } detector = detector_.get(); Option<Authorizer*> authorizer_ = None(); auto authorizerNames = strings::split(flags.authorizers, ","); if (authorizerNames.empty()) { EXIT(EXIT_FAILURE) << "No authorizer specified"; } if (authorizerNames.size() > 1) { EXIT(EXIT_FAILURE) << "Multiple authorizers not supported"; } string authorizerName = authorizerNames[0]; // NOTE: The flag --authorizers overrides the flag --acls, i.e. if // a non default authorizer is requested, it will be used and // the contents of --acls will be ignored. // TODO(arojas): Consider adding support for multiple authorizers. Result<Authorizer*> authorizer((None())); if (authorizerName != master::DEFAULT_AUTHORIZER) { LOG(INFO) << "Creating '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(authorizerName); } else { // `authorizerName` is `DEFAULT_AUTHORIZER` at this point. if (flags.acls.isSome()) { LOG(INFO) << "Creating default '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(flags.acls.get()); } } if (authorizer.isError()) { EXIT(EXIT_FAILURE) << "Could not create '" << authorizerName << "' authorizer: " << authorizer.error(); } else if (authorizer.isSome()) { authorizer_ = authorizer.get(); // Set the authorization callbacks for libprocess HTTP endpoints. // Note that these callbacks capture `authorizer_.get()`, but the master // creates a copy of the authorizer during construction. Thus, if in the // future it becomes possible to dynamically set the authorizer, this would // break. process::http::authorization::setCallbacks( createAuthorizationCallbacks(authorizer_.get())); } Files files(READONLY_HTTP_AUTHENTICATION_REALM, authorizer_); Option<shared_ptr<RateLimiter>> slaveRemovalLimiter = None(); if (flags.agent_removal_rate_limit.isSome()) { // Parse the flag value. // TODO(vinod): Move this parsing logic to flags once we have a // 'Rate' abstraction in stout. vector<string> tokens = strings::tokenize(flags.agent_removal_rate_limit.get(), "/"); if (tokens.size() != 2) { EXIT(EXIT_FAILURE) << "Invalid agent_removal_rate_limit: " << flags.agent_removal_rate_limit.get() << ". Format is <Number of agents>/<Duration>"; } Try<int> permits = numify<int>(tokens[0]); if (permits.isError()) { EXIT(EXIT_FAILURE) << "Invalid agent_removal_rate_limit: " << flags.agent_removal_rate_limit.get() << ". Format is <Number of agents>/<Duration>" << ": " << permits.error(); } Try<Duration> duration = Duration::parse(tokens[1]); if (duration.isError()) { EXIT(EXIT_FAILURE) << "Invalid agent_removal_rate_limit: " << flags.agent_removal_rate_limit.get() << ". Format is <Number of agents>/<Duration>" << ": " << duration.error(); } slaveRemovalLimiter = new RateLimiter(permits.get(), duration.get()); } Master* master = new Master( allocator.get(), registrar, &files, contender, detector, authorizer_, slaveRemovalLimiter, flags); if (flags.zk.isNone() && flags.master_detector.isNone()) { // It means we are using the standalone detector so we need to // appoint this Master as the leader. dynamic_cast<StandaloneMasterDetector*>(detector)->appoint(master->info()); } process::spawn(master); process::wait(master->self()); delete master; delete allocator.get(); delete registrar; delete state; delete storage; #ifndef __WINDOWS__ delete log; #endif // __WINDOWS__ delete contender; delete detector; if (authorizer_.isSome()) { delete authorizer_.get(); } return EXIT_SUCCESS; }
16,444
5,397
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_CONFIG_H #define BOOST_FIBERS_DETAIL_CONFIG_H #include <cstddef> #include <boost/config.hpp> #include <boost/predef.h> #include <boost/detail/workaround.hpp> #ifdef BOOST_FIBERS_DECL # undef BOOST_FIBERS_DECL #endif #if (defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FIBERS_DYN_LINK) ) && ! defined(BOOST_FIBERS_STATIC_LINK) # if defined(BOOST_FIBERS_SOURCE) # define BOOST_FIBERS_DECL BOOST_SYMBOL_EXPORT # define BOOST_FIBERS_BUILD_DLL # else # define BOOST_FIBERS_DECL BOOST_SYMBOL_IMPORT # endif #endif #if ! defined(BOOST_FIBERS_DECL) # define BOOST_FIBERS_DECL #endif #if ! defined(BOOST_FIBERS_SOURCE) && ! defined(BOOST_ALL_NO_LIB) && ! defined(BOOST_FIBERS_NO_LIB) # define BOOST_LIB_NAME boost_fiber # if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FIBERS_DYN_LINK) # define BOOST_DYN_LINK # endif # include <boost/config/auto_link.hpp> #endif #if BOOST_OS_LINUX || BOOST_OS_WINDOWS # define BOOST_FIBERS_HAS_FUTEX #endif #if (!defined(BOOST_FIBERS_HAS_FUTEX) && \ (defined(BOOST_FIBERS_SPINLOCK_TTAS_FUTEX) || defined(BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_FUTEX))) # error "futex not supported on this platform" #endif #if !defined(BOOST_FIBERS_SPIN_MAX_COLLISIONS) # define BOOST_FIBERS_SPIN_MAX_COLLISIONS 16 #endif #if !defined(BOOST_FIBERS_SPIN_MAX_TESTS) # define BOOST_FIBERS_SPIN_MAX_TESTS 100 #endif // modern architectures have cachelines with 64byte length // ARM Cortex-A15 32/64byte, Cortex-A9 16/32/64bytes // MIPS 74K: 32byte, 4KEc: 16byte // ist shoudl be safe to use 64byte for all static constexpr std::size_t cache_alignment{ 64 }; static constexpr std::size_t cacheline_length{ 64 }; #endif // BOOST_FIBERS_DETAIL_CONFIG_H
1,913
860
#define FMT_HEADER_ONLY #include <fmt/format.h> int main() { fmt::print("Hello, {}!\n", 42); }
98
46
// MapGenerator // from https://github.com/Rellikiox/MapGenerator /* * LineEquation.cc * * Created on: Mar 5, 2012 * Author: rellik */ #include "LineEquation.h" equ::equ(Vec2 p1, Vec2 p2) { // Calculamos la pendiente if (p1.x != p2.x) { vertical = false; m = (p2.y - p1.y) / (p2.x - p1.x); b = p1.y - p1.y * m; } else { vertical = true; m = 0; b = p1.x; } } equ::equ(Vec2 p, double m_){ m = m_; if(m != 0){ vertical = false; b = p.y - p.x * m; }else{ vertical = true; b = p.x; } } equ::equ(const equ& e) { m = e.m; b = e.b; vertical = e.vertical; } equ & equ::operator=(const equ &e) { if (this != &e) { m = e.m; b = e.b; vertical = e.vertical; } return *this; } equ::~equ() { m = 0; b = 0; vertical = false; } double equ::operator()(const double x) { return (x * m + b); } void equ::Move(const Vec2 vec) { Vec2 p0, p1; if (vertical) { p0 = Vec2(b, 0); p1 = Vec2(b, 1); } else { p0 = Vec2(0, b); p1 = Vec2(1, m + b); } p0 += Vec2(vec.x, vec.y); p1 += Vec2(vec.x, vec.y); *this = equ(p0, p1); } Vec2 equ::Intersection(equ &e) const { double x; double y; if (this->m != e.m) { if (this->vertical) { x = this->b; y = e(x); } else if (e.vertical) { x = e.b; y = x * this->m + this->b; } else { x = (e.b - this->b) / (this->m - e.m); y = e(x); } } else { if (this->vertical == e.vertical) { x = 0; y = 0; } else { if (this->vertical) { // this es vertical, e es horizontal x = this->b; y = e.b; } else { // this es horizontal, e es vertical x = e.b; y = this->b; } } } return Vec2(x, y); } bool equ::Vertical(){ return vertical; } bool equ::Horizontal(){ return !vertical && m == 0; }
1,743
910
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include <wextestclass.h> #include "../../inc/consoletaeftemplates.hpp" #include "adaptDispatch.hpp" using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; namespace Microsoft { namespace Console { namespace VirtualTerminal { class AdapterTest; class ConAdapterTestGetSet; }; }; }; enum class CursorY { TOP, BOTTOM, YCENTER }; enum class CursorX { LEFT, RIGHT, XCENTER }; enum class CursorDirection : size_t { UP = 0, DOWN = 1, RIGHT = 2, LEFT = 3, NEXTLINE = 4, PREVLINE = 5 }; enum class AbsolutePosition : size_t { CursorHorizontal = 0, VerticalLine = 1, }; using namespace Microsoft::Console::VirtualTerminal; class TestGetSet final : public ConGetSet { public: bool GetConsoleScreenBufferInfoEx(CONSOLE_SCREEN_BUFFER_INFOEX& sbiex) const override { Log::Comment(L"GetConsoleScreenBufferInfoEx MOCK returning data..."); if (_getConsoleScreenBufferInfoExResult) { sbiex.dwSize = _bufferSize; sbiex.srWindow = _viewport; sbiex.dwCursorPosition = _cursorPos; sbiex.wAttributes = _attribute.GetLegacyAttributes(); } return _getConsoleScreenBufferInfoExResult; } bool SetConsoleScreenBufferInfoEx(const CONSOLE_SCREEN_BUFFER_INFOEX& sbiex) override { Log::Comment(L"SetConsoleScreenBufferInfoEx MOCK returning data..."); if (_setConsoleScreenBufferInfoExResult) { VERIFY_ARE_EQUAL(_expectedCursorPos, sbiex.dwCursorPosition); VERIFY_ARE_EQUAL(_expectedScreenBufferSize, sbiex.dwSize); VERIFY_ARE_EQUAL(_expectedScreenBufferViewport, sbiex.srWindow); VERIFY_ARE_EQUAL(_expectedAttribute, TextAttribute{ sbiex.wAttributes }); } return _setConsoleScreenBufferInfoExResult; } bool SetConsoleCursorPosition(const COORD position) override { Log::Comment(L"SetConsoleCursorPosition MOCK called..."); if (_setConsoleCursorPositionResult) { VERIFY_ARE_EQUAL(_expectedCursorPos, position); _cursorPos = position; } return _setConsoleCursorPositionResult; } bool SetConsoleWindowInfo(const bool absolute, const SMALL_RECT& window) override { Log::Comment(L"SetConsoleWindowInfo MOCK called..."); if (_setConsoleWindowInfoResult) { VERIFY_ARE_EQUAL(_expectedWindowAbsolute, absolute); VERIFY_ARE_EQUAL(_expectedConsoleWindow, window); _viewport = window; } return _setConsoleWindowInfoResult; } bool PrivateSetCursorKeysMode(const bool applicationMode) override { Log::Comment(L"PrivateSetCursorKeysMode MOCK called..."); if (_privateSetCursorKeysModeResult) { VERIFY_ARE_EQUAL(_cursorKeysApplicationMode, applicationMode); } return _privateSetCursorKeysModeResult; } bool PrivateSetKeypadMode(const bool applicationMode) override { Log::Comment(L"PrivateSetKeypadMode MOCK called..."); if (_privateSetKeypadModeResult) { VERIFY_ARE_EQUAL(_keypadApplicationMode, applicationMode); } return _privateSetKeypadModeResult; } bool PrivateEnableWin32InputMode(const bool /*win32InputMode*/) override { Log::Comment(L"PrivateEnableWin32InputMode MOCK called..."); return true; } bool PrivateSetAnsiMode(const bool ansiMode) override { Log::Comment(L"PrivateSetAnsiMode MOCK called..."); if (_privateSetAnsiModeResult) { VERIFY_ARE_EQUAL(_expectedAnsiMode, ansiMode); } return _privateSetAnsiModeResult; } bool PrivateSetScreenMode(const bool /*reverseMode*/) override { Log::Comment(L"PrivateSetScreenMode MOCK called..."); return true; } bool PrivateSetAutoWrapMode(const bool /*wrapAtEOL*/) override { Log::Comment(L"PrivateSetAutoWrapMode MOCK called..."); return false; } bool PrivateShowCursor(const bool show) override { Log::Comment(L"PrivateShowCursor MOCK called..."); if (_privateShowCursorResult) { VERIFY_ARE_EQUAL(_expectedShowCursor, show); } return _privateShowCursorResult; } bool PrivateAllowCursorBlinking(const bool enable) override { Log::Comment(L"PrivateAllowCursorBlinking MOCK called..."); if (_privateAllowCursorBlinkingResult) { VERIFY_ARE_EQUAL(_enable, enable); } return _privateAllowCursorBlinkingResult; } bool PrivateIsVtInputEnabled() const override { return false; } bool PrivateGetTextAttributes(TextAttribute& attrs) const { Log::Comment(L"PrivateGetTextAttributes MOCK called..."); if (_privateGetTextAttributesResult) { attrs = _attribute; } return _privateGetTextAttributesResult; } bool PrivateSetTextAttributes(const TextAttribute& attrs) { Log::Comment(L"PrivateSetTextAttributes MOCK called..."); if (_privateSetTextAttributesResult) { VERIFY_ARE_EQUAL(_expectedAttribute, attrs); _attribute = attrs; } return _privateSetTextAttributesResult; } bool PrivateSetCurrentLineRendition(const LineRendition /*lineRendition*/) { Log::Comment(L"PrivateSetCurrentLineRendition MOCK called..."); return false; } bool PrivateResetLineRenditionRange(const size_t /*startRow*/, const size_t /*endRow*/) { Log::Comment(L"PrivateResetLineRenditionRange MOCK called..."); return false; } SHORT PrivateGetLineWidth(const size_t /*row*/) const { Log::Comment(L"PrivateGetLineWidth MOCK called..."); return _bufferSize.X; } bool PrivateWriteConsoleInputW(std::deque<std::unique_ptr<IInputEvent>>& events, size_t& eventsWritten) override { Log::Comment(L"PrivateWriteConsoleInputW MOCK called..."); if (_privateWriteConsoleInputWResult) { // move all the input events we were given into local storage so we can test against them Log::Comment(NoThrowString().Format(L"Moving %zu input events into local storage...", events.size())); if (_retainInput) { std::move(events.begin(), events.end(), std::back_inserter(_events)); } else { _events.clear(); _events.swap(events); } eventsWritten = _events.size(); } return _privateWriteConsoleInputWResult; } bool PrivateWriteConsoleControlInput(_In_ KeyEvent key) override { Log::Comment(L"PrivateWriteConsoleControlInput MOCK called..."); if (_privateWriteConsoleControlInputResult) { VERIFY_ARE_EQUAL('C', key.GetVirtualKeyCode()); VERIFY_ARE_EQUAL(0x3, key.GetCharData()); VERIFY_ARE_EQUAL(true, key.IsCtrlPressed()); } return _privateWriteConsoleControlInputResult; } bool PrivateSetScrollingRegion(const SMALL_RECT& scrollMargins) override { Log::Comment(L"PrivateSetScrollingRegion MOCK called..."); if (_privateSetScrollingRegionResult) { VERIFY_ARE_EQUAL(_expectedScrollRegion, scrollMargins); } return _privateSetScrollingRegionResult; } bool PrivateWarningBell() override { Log::Comment(L"PrivateWarningBell MOCK called..."); // We made it through the adapter, woo! Return true. return TRUE; } bool PrivateGetLineFeedMode() const override { Log::Comment(L"PrivateGetLineFeedMode MOCK called..."); return _privateGetLineFeedModeResult; } bool PrivateLineFeed(const bool withReturn) override { Log::Comment(L"PrivateLineFeed MOCK called..."); if (_privateLineFeedResult) { VERIFY_ARE_EQUAL(_expectedLineFeedWithReturn, withReturn); } return _privateLineFeedResult; } bool PrivateReverseLineFeed() override { Log::Comment(L"PrivateReverseLineFeed MOCK called..."); // We made it through the adapter, woo! Return true. return TRUE; } bool SetConsoleTitleW(const std::wstring_view title) { Log::Comment(L"SetConsoleTitleW MOCK called..."); if (_setConsoleTitleWResult) { // Put into WEX strings for rich logging when they don't compare. VERIFY_ARE_EQUAL(String(_expectedWindowTitle.data(), gsl::narrow<int>(_expectedWindowTitle.size())), String(title.data(), gsl::narrow<int>(title.size()))); } return TRUE; } bool PrivateUseAlternateScreenBuffer() override { Log::Comment(L"PrivateUseAlternateScreenBuffer MOCK called..."); return true; } bool PrivateUseMainScreenBuffer() override { Log::Comment(L"PrivateUseMainScreenBuffer MOCK called..."); return true; } bool PrivateEnableVT200MouseMode(const bool enabled) override { Log::Comment(L"PrivateEnableVT200MouseMode MOCK called..."); if (_privateEnableVT200MouseModeResult) { VERIFY_ARE_EQUAL(_expectedMouseEnabled, enabled); } return _privateEnableVT200MouseModeResult; } bool PrivateEnableUTF8ExtendedMouseMode(const bool enabled) override { Log::Comment(L"PrivateEnableUTF8ExtendedMouseMode MOCK called..."); if (_privateEnableUTF8ExtendedMouseModeResult) { VERIFY_ARE_EQUAL(_expectedMouseEnabled, enabled); } return _privateEnableUTF8ExtendedMouseModeResult; } bool PrivateEnableSGRExtendedMouseMode(const bool enabled) override { Log::Comment(L"PrivateEnableSGRExtendedMouseMode MOCK called..."); if (_privateEnableSGRExtendedMouseModeResult) { VERIFY_ARE_EQUAL(_expectedMouseEnabled, enabled); } return _privateEnableSGRExtendedMouseModeResult; } bool PrivateEnableButtonEventMouseMode(const bool enabled) override { Log::Comment(L"PrivateEnableButtonEventMouseMode MOCK called..."); if (_privateEnableButtonEventMouseModeResult) { VERIFY_ARE_EQUAL(_expectedMouseEnabled, enabled); } return _privateEnableButtonEventMouseModeResult; } bool PrivateEnableAnyEventMouseMode(const bool enabled) override { Log::Comment(L"PrivateEnableAnyEventMouseMode MOCK called..."); if (_privateEnableAnyEventMouseModeResult) { VERIFY_ARE_EQUAL(_expectedMouseEnabled, enabled); } return _privateEnableAnyEventMouseModeResult; } bool PrivateEnableAlternateScroll(const bool enabled) override { Log::Comment(L"PrivateEnableAlternateScroll MOCK called..."); if (_privateEnableAlternateScrollResult) { VERIFY_ARE_EQUAL(_expectedAlternateScrollEnabled, enabled); } return _privateEnableAlternateScrollResult; } bool PrivateEraseAll() override { Log::Comment(L"PrivateEraseAll MOCK called..."); return TRUE; } bool PrivateClearBuffer() override { Log::Comment(L"PrivateClearBuffer MOCK called..."); return TRUE; } bool GetUserDefaultCursorStyle(CursorType& style) override { style = CursorType::Legacy; return true; } bool SetCursorStyle(const CursorType cursorType) override { Log::Comment(L"SetCursorStyle MOCK called..."); if (_setCursorStyleResult) { VERIFY_ARE_EQUAL(_expectedCursorStyle, cursorType); } return _setCursorStyleResult; } bool SetCursorColor(const COLORREF cursorColor) override { Log::Comment(L"SetCursorColor MOCK called..."); if (_setCursorColorResult) { VERIFY_ARE_EQUAL(_expectedCursorColor, cursorColor); } return _setCursorColorResult; } bool PrivateRefreshWindow() override { Log::Comment(L"PrivateRefreshWindow MOCK called..."); // We made it through the adapter, woo! Return true. return TRUE; } bool PrivateSuppressResizeRepaint() override { Log::Comment(L"PrivateSuppressResizeRepaint MOCK called..."); VERIFY_IS_TRUE(false, L"AdaptDispatch should never be calling this function."); return FALSE; } bool SetConsoleOutputCP(const unsigned int /*codepage*/) override { Log::Comment(L"SetConsoleOutputCP MOCK called..."); return TRUE; } bool GetConsoleOutputCP(unsigned int& codepage) override { Log::Comment(L"GetConsoleOutputCP MOCK called..."); if (_getConsoleOutputCPResult) { codepage = _expectedOutputCP; } return _getConsoleOutputCPResult; } bool IsConsolePty() const override { Log::Comment(L"IsConsolePty MOCK called..."); return _isPty; } bool DeleteLines(const size_t /*count*/) override { Log::Comment(L"DeleteLines MOCK called..."); return TRUE; } bool InsertLines(const size_t /*count*/) override { Log::Comment(L"InsertLines MOCK called..."); return TRUE; } bool MoveToBottom() const override { Log::Comment(L"MoveToBottom MOCK called..."); return _moveToBottomResult; } bool PrivateGetColorTableEntry(const size_t index, COLORREF& value) const noexcept override { Log::Comment(L"PrivateGetColorTableEntry MOCK called..."); if (_privateGetColorTableEntryResult) { VERIFY_ARE_EQUAL(_expectedColorTableIndex, index); // Simply returning the index as the color value makes it easy for // tests to confirm that they've received the color they expected. value = gsl::narrow_cast<COLORREF>(index); } return _privateGetColorTableEntryResult; } bool PrivateSetColorTableEntry(const size_t index, const COLORREF value) const noexcept override { Log::Comment(L"PrivateSetColorTableEntry MOCK called..."); if (_privateSetColorTableEntryResult) { VERIFY_ARE_EQUAL(_expectedColorTableIndex, index); VERIFY_ARE_EQUAL(_expectedColorValue, value); } return _privateSetColorTableEntryResult; } bool PrivateSetDefaultForeground(const COLORREF value) const noexcept override { Log::Comment(L"PrivateSetDefaultForeground MOCK called..."); if (_privateSetDefaultForegroundResult) { VERIFY_ARE_EQUAL(_expectedDefaultForegroundColorValue, value); } return _privateSetDefaultForegroundResult; } bool PrivateSetDefaultBackground(const COLORREF value) const noexcept override { Log::Comment(L"PrivateSetDefaultForeground MOCK called..."); if (_privateSetDefaultBackgroundResult) { VERIFY_ARE_EQUAL(_expectedDefaultBackgroundColorValue, value); } return _privateSetDefaultBackgroundResult; } bool PrivateFillRegion(const COORD /*startPosition*/, const size_t /*fillLength*/, const wchar_t /*fillChar*/, const bool /*standardFillAttrs*/) noexcept override { Log::Comment(L"PrivateFillRegion MOCK called..."); return TRUE; } bool PrivateScrollRegion(const SMALL_RECT /*scrollRect*/, const std::optional<SMALL_RECT> /*clipRect*/, const COORD /*destinationOrigin*/, const bool /*standardFillAttrs*/) noexcept override { Log::Comment(L"PrivateScrollRegion MOCK called..."); return TRUE; } bool PrivateUpdateSoftFont(const gsl::span<const uint16_t> /*bitPattern*/, const SIZE cellSize, const size_t /*centeringHint*/) noexcept override { Log::Comment(L"PrivateUpdateSoftFont MOCK called..."); Log::Comment(NoThrowString().Format(L"Cell size: %dx%d", cellSize.cx, cellSize.cy)); VERIFY_ARE_EQUAL(_expectedCellSize.cx, cellSize.cx); VERIFY_ARE_EQUAL(_expectedCellSize.cy, cellSize.cy); return TRUE; } void PrepData() { PrepData(CursorDirection::UP); // if called like this, the cursor direction doesn't matter. } void PrepData(CursorDirection dir) { switch (dir) { case CursorDirection::UP: return PrepData(CursorX::LEFT, CursorY::TOP); case CursorDirection::DOWN: return PrepData(CursorX::LEFT, CursorY::BOTTOM); case CursorDirection::LEFT: return PrepData(CursorX::LEFT, CursorY::TOP); case CursorDirection::RIGHT: return PrepData(CursorX::RIGHT, CursorY::TOP); case CursorDirection::NEXTLINE: return PrepData(CursorX::LEFT, CursorY::BOTTOM); case CursorDirection::PREVLINE: return PrepData(CursorX::LEFT, CursorY::TOP); } } void PrepData(CursorX xact, CursorY yact) { Log::Comment(L"Resetting mock data state."); // APIs succeed by default _setConsoleCursorPositionResult = TRUE; _getConsoleScreenBufferInfoExResult = TRUE; _privateGetTextAttributesResult = TRUE; _privateSetTextAttributesResult = TRUE; _privateWriteConsoleInputWResult = TRUE; _privateWriteConsoleControlInputResult = TRUE; _setConsoleWindowInfoResult = TRUE; _moveToBottomResult = true; _bufferSize.X = 100; _bufferSize.Y = 600; // Viewport sitting in the "middle" of the buffer somewhere (so all sides have excess buffer around them) _viewport.Top = 20; _viewport.Bottom = 49; _viewport.Left = 30; _viewport.Right = 59; // Call cursor positions separately PrepCursor(xact, yact); _cursorVisible = TRUE; // Attribute default is gray on black. _attribute = TextAttribute{ FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED }; _expectedAttribute = _attribute; _events.clear(); _retainInput = false; } void PrepCursor(CursorX xact, CursorY yact) { Log::Comment(L"Adjusting cursor within viewport... Expected will match actual when done."); switch (xact) { case CursorX::LEFT: Log::Comment(L"Cursor set to left edge of buffer."); _cursorPos.X = 0; break; case CursorX::RIGHT: Log::Comment(L"Cursor set to right edge of buffer."); _cursorPos.X = _bufferSize.X - 1; break; case CursorX::XCENTER: Log::Comment(L"Cursor set to centered X of buffer."); _cursorPos.X = _bufferSize.X / 2; break; } switch (yact) { case CursorY::TOP: Log::Comment(L"Cursor set to top edge of viewport."); _cursorPos.Y = _viewport.Top; break; case CursorY::BOTTOM: Log::Comment(L"Cursor set to bottom edge of viewport."); _cursorPos.Y = _viewport.Bottom - 1; break; case CursorY::YCENTER: Log::Comment(L"Cursor set to centered Y of viewport."); _cursorPos.Y = _viewport.Top + ((_viewport.Bottom - _viewport.Top) / 2); break; } _expectedCursorPos = _cursorPos; } void ValidateInputEvent(_In_ PCWSTR pwszExpectedResponse) { size_t const cchResponse = wcslen(pwszExpectedResponse); size_t const eventCount = _events.size(); VERIFY_ARE_EQUAL(cchResponse * 2, eventCount, L"We should receive TWO input records for every character in the expected string. Key down and key up."); for (size_t iInput = 0; iInput < eventCount; iInput++) { wchar_t const wch = pwszExpectedResponse[iInput / 2]; // the same portion of the string will be used twice. 0/2 = 0. 1/2 = 0. 2/2 = 1. 3/2 = 1. and so on. VERIFY_ARE_EQUAL(InputEventType::KeyEvent, _events[iInput]->EventType()); const KeyEvent* const keyEvent = static_cast<const KeyEvent* const>(_events[iInput].get()); // every even key is down. every odd key is up. DOWN = 0, UP = 1. DOWN = 2, UP = 3. and so on. VERIFY_ARE_EQUAL((bool)!(iInput % 2), keyEvent->IsKeyDown()); VERIFY_ARE_EQUAL(0u, keyEvent->GetActiveModifierKeys()); Log::Comment(NoThrowString().Format(L"Comparing '%c' with '%c'...", wch, keyEvent->GetCharData())); VERIFY_ARE_EQUAL(wch, keyEvent->GetCharData()); VERIFY_ARE_EQUAL(1u, keyEvent->GetRepeatCount()); VERIFY_ARE_EQUAL(0u, keyEvent->GetVirtualKeyCode()); VERIFY_ARE_EQUAL(0u, keyEvent->GetVirtualScanCode()); } } bool PrivateAddHyperlink(const std::wstring_view /*uri*/, const std::wstring_view /*params*/) const { Log::Comment(L"PrivateAddHyperlink MOCK called..."); return TRUE; } bool PrivateEndHyperlink() const { Log::Comment(L"PrivateEndHyperlink MOCK called..."); return TRUE; } void _SetMarginsHelper(SMALL_RECT* rect, SHORT top, SHORT bottom) { rect->Top = top; rect->Bottom = bottom; //The rectangle is going to get converted from VT space to conhost space _expectedScrollRegion.Top = (top > 0) ? rect->Top - 1 : rect->Top; _expectedScrollRegion.Bottom = (bottom > 0) ? rect->Bottom - 1 : rect->Bottom; } ~TestGetSet() { } static const WCHAR s_wchErase = (WCHAR)0x20; static const WCHAR s_wchDefault = L'Z'; static const WORD s_wAttrErase = FOREGROUND_BLUE | FOREGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY; static const WORD s_wDefaultAttribute = 0; static const WORD s_defaultFill = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED; // dark gray on black. std::deque<std::unique_ptr<IInputEvent>> _events; bool _retainInput{ false }; auto EnableInputRetentionInScope() { auto oldRetainValue{ _retainInput }; _retainInput = true; return wil::scope_exit([oldRetainValue, this] { _retainInput = oldRetainValue; }); } COORD _bufferSize = { 0, 0 }; SMALL_RECT _viewport = { 0, 0, 0, 0 }; SMALL_RECT _expectedConsoleWindow = { 0, 0, 0, 0 }; COORD _cursorPos = { 0, 0 }; SMALL_RECT _expectedScrollRegion = { 0, 0, 0, 0 }; bool _cursorVisible = false; COORD _expectedCursorPos = { 0, 0 }; TextAttribute _attribute = {}; TextAttribute _expectedAttribute = {}; unsigned int _expectedOutputCP = 0; bool _isPty = false; bool _privateShowCursorResult = false; bool _expectedShowCursor = false; bool _getConsoleScreenBufferInfoExResult = false; bool _setConsoleCursorPositionResult = false; bool _privateGetTextAttributesResult = false; bool _privateSetTextAttributesResult = false; bool _privateWriteConsoleInputWResult = false; bool _privateWriteConsoleControlInputResult = false; bool _setConsoleWindowInfoResult = false; bool _expectedWindowAbsolute = false; bool _setConsoleScreenBufferInfoExResult = false; COORD _expectedScreenBufferSize = { 0, 0 }; SMALL_RECT _expectedScreenBufferViewport{ 0, 0, 0, 0 }; bool _privateSetCursorKeysModeResult = false; bool _privateSetKeypadModeResult = false; bool _cursorKeysApplicationMode = false; bool _keypadApplicationMode = false; bool _privateSetAnsiModeResult = false; bool _expectedAnsiMode = false; bool _privateAllowCursorBlinkingResult = false; bool _enable = false; // for cursor blinking bool _privateSetScrollingRegionResult = false; bool _privateGetLineFeedModeResult = false; bool _privateLineFeedResult = false; bool _expectedLineFeedWithReturn = false; bool _privateReverseLineFeedResult = false; bool _setConsoleTitleWResult = false; std::wstring_view _expectedWindowTitle{}; bool _expectedMouseEnabled = false; bool _expectedAlternateScrollEnabled = false; bool _privateEnableVT200MouseModeResult = false; bool _privateEnableUTF8ExtendedMouseModeResult = false; bool _privateEnableSGRExtendedMouseModeResult = false; bool _privateEnableButtonEventMouseModeResult = false; bool _privateEnableAnyEventMouseModeResult = false; bool _privateEnableAlternateScrollResult = false; bool _setCursorStyleResult = false; CursorType _expectedCursorStyle; bool _setCursorColorResult = false; COLORREF _expectedCursorColor = 0; bool _getConsoleOutputCPResult = false; bool _moveToBottomResult = false; bool _privateGetColorTableEntryResult = false; bool _privateSetColorTableEntryResult = false; size_t _expectedColorTableIndex = SIZE_MAX; COLORREF _expectedColorValue = INVALID_COLOR; bool _privateSetDefaultForegroundResult = false; COLORREF _expectedDefaultForegroundColorValue = INVALID_COLOR; bool _privateSetDefaultBackgroundResult = false; COLORREF _expectedDefaultBackgroundColorValue = INVALID_COLOR; SIZE _expectedCellSize = {}; private: HANDLE _hCon; }; class DummyAdapter : public AdaptDefaults { void Print(const wchar_t /*wch*/) override { } void PrintString(const std::wstring_view /*string*/) override { } void Execute(const wchar_t /*wch*/) override { } }; class AdapterTest { public: TEST_CLASS(AdapterTest); TEST_METHOD_SETUP(SetupMethods) { bool fSuccess = true; auto api = std::make_unique<TestGetSet>(); fSuccess = api.get() != nullptr; if (fSuccess) { auto adapter = std::make_unique<DummyAdapter>(); // give AdaptDispatch ownership of _testGetSet _testGetSet = api.get(); // keep a copy for us but don't manage its lifetime anymore. _pDispatch = std::make_unique<AdaptDispatch>(std::move(api), std::move(adapter)); fSuccess = _pDispatch != nullptr; } return fSuccess; } TEST_METHOD_CLEANUP(CleanupMethods) { _pDispatch.reset(); _testGetSet = nullptr; return true; } TEST_METHOD(CursorMovementTest) { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiDirection", L"{0, 1, 2, 3, 4, 5}") // These values align with the CursorDirection enum class to try all the directions. END_TEST_METHOD_PROPERTIES() Log::Comment(L"Starting test..."); // Used to switch between the various function options. typedef bool (AdaptDispatch::*CursorMoveFunc)(size_t); CursorMoveFunc moveFunc = nullptr; // Modify variables based on directionality of this test CursorDirection direction; size_t dir; VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"uiDirection", dir)); direction = (CursorDirection)dir; switch (direction) { case CursorDirection::UP: Log::Comment(L"Testing up direction."); moveFunc = &AdaptDispatch::CursorUp; break; case CursorDirection::DOWN: Log::Comment(L"Testing down direction."); moveFunc = &AdaptDispatch::CursorDown; break; case CursorDirection::RIGHT: Log::Comment(L"Testing right direction."); moveFunc = &AdaptDispatch::CursorForward; break; case CursorDirection::LEFT: Log::Comment(L"Testing left direction."); moveFunc = &AdaptDispatch::CursorBackward; break; case CursorDirection::NEXTLINE: Log::Comment(L"Testing next line direction."); moveFunc = &AdaptDispatch::CursorNextLine; break; case CursorDirection::PREVLINE: Log::Comment(L"Testing prev line direction."); moveFunc = &AdaptDispatch::CursorPrevLine; break; } if (moveFunc == nullptr) { VERIFY_FAIL(); return; } // success cases // place cursor in top left. moving up is expected to go nowhere (it should get bounded by the viewport) Log::Comment(L"Test 1: Cursor doesn't move when placed in corner of viewport."); _testGetSet->PrepData(direction); VERIFY_IS_TRUE((_pDispatch.get()->*(moveFunc))(1)); Log::Comment(L"Test 1b: Cursor moves to left of line with next/prev line command when cursor can't move higher/lower."); bool fDoTest1b = false; switch (direction) { case CursorDirection::NEXTLINE: _testGetSet->PrepData(CursorX::RIGHT, CursorY::BOTTOM); fDoTest1b = true; break; case CursorDirection::PREVLINE: _testGetSet->PrepData(CursorX::RIGHT, CursorY::TOP); fDoTest1b = true; break; } if (fDoTest1b) { _testGetSet->_expectedCursorPos.X = 0; VERIFY_IS_TRUE((_pDispatch.get()->*(moveFunc))(1)); } else { Log::Comment(L"Test not applicable to direction selected. Skipping."); } // place cursor lower, move up 1. Log::Comment(L"Test 2: Cursor moves 1 in the correct direction from viewport."); _testGetSet->PrepData(CursorX::XCENTER, CursorY::YCENTER); switch (direction) { case CursorDirection::UP: _testGetSet->_expectedCursorPos.Y--; break; case CursorDirection::DOWN: _testGetSet->_expectedCursorPos.Y++; break; case CursorDirection::RIGHT: _testGetSet->_expectedCursorPos.X++; break; case CursorDirection::LEFT: _testGetSet->_expectedCursorPos.X--; break; case CursorDirection::NEXTLINE: _testGetSet->_expectedCursorPos.Y++; _testGetSet->_expectedCursorPos.X = 0; break; case CursorDirection::PREVLINE: _testGetSet->_expectedCursorPos.Y--; _testGetSet->_expectedCursorPos.X = 0; break; } VERIFY_IS_TRUE((_pDispatch.get()->*(moveFunc))(1)); // place cursor and move it up too far. It should get bounded by the viewport. Log::Comment(L"Test 3: Cursor moves and gets stuck at viewport when started away from edges and moved beyond edges."); _testGetSet->PrepData(CursorX::XCENTER, CursorY::YCENTER); // Bottom and right viewports are -1 because those two sides are specified to be 1 outside the viewable area. switch (direction) { case CursorDirection::UP: _testGetSet->_expectedCursorPos.Y = _testGetSet->_viewport.Top; break; case CursorDirection::DOWN: _testGetSet->_expectedCursorPos.Y = _testGetSet->_viewport.Bottom - 1; break; case CursorDirection::RIGHT: _testGetSet->_expectedCursorPos.X = _testGetSet->_bufferSize.X - 1; break; case CursorDirection::LEFT: _testGetSet->_expectedCursorPos.X = 0; break; case CursorDirection::NEXTLINE: _testGetSet->_expectedCursorPos.X = 0; _testGetSet->_expectedCursorPos.Y = _testGetSet->_viewport.Bottom - 1; break; case CursorDirection::PREVLINE: _testGetSet->_expectedCursorPos.X = 0; _testGetSet->_expectedCursorPos.Y = _testGetSet->_viewport.Top; break; } VERIFY_IS_TRUE((_pDispatch.get()->*(moveFunc))(100)); // error cases // SetConsoleCursorPosition throws failure. Parameters are otherwise normal. Log::Comment(L"Test 4: When SetConsoleCursorPosition throws a failure, call fails and cursor doesn't move."); _testGetSet->PrepData(direction); _testGetSet->_setConsoleCursorPositionResult = FALSE; VERIFY_IS_FALSE((_pDispatch.get()->*(moveFunc))(0)); VERIFY_ARE_EQUAL(_testGetSet->_expectedCursorPos, _testGetSet->_cursorPos); // GetConsoleScreenBufferInfo throws failure. Parameters are otherwise normal. Log::Comment(L"Test 5: When GetConsoleScreenBufferInfo throws a failure, call fails and cursor doesn't move."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); _testGetSet->_getConsoleScreenBufferInfoExResult = FALSE; VERIFY_IS_FALSE((_pDispatch.get()->*(moveFunc))(0)); VERIFY_ARE_EQUAL(_testGetSet->_expectedCursorPos, _testGetSet->_cursorPos); } TEST_METHOD(CursorPositionTest) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Place cursor within the viewport. Start from top left, move to middle."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); short sCol = (_testGetSet->_viewport.Right - _testGetSet->_viewport.Left) / 2; short sRow = (_testGetSet->_viewport.Bottom - _testGetSet->_viewport.Top) / 2; // The X coordinate is unaffected by the viewport. _testGetSet->_expectedCursorPos.X = sCol - 1; _testGetSet->_expectedCursorPos.Y = _testGetSet->_viewport.Top + (sRow - 1); VERIFY_IS_TRUE(_pDispatch.get()->CursorPosition(sRow, sCol)); Log::Comment(L"Test 2: Move to 0, 0 (which is 1,1 in VT speak)"); _testGetSet->PrepData(CursorX::RIGHT, CursorY::BOTTOM); // The X coordinate is unaffected by the viewport. _testGetSet->_expectedCursorPos.X = 0; _testGetSet->_expectedCursorPos.Y = _testGetSet->_viewport.Top; VERIFY_IS_TRUE(_pDispatch.get()->CursorPosition(1, 1)); Log::Comment(L"Test 3: Move beyond rectangle (down/right too far). Should be bounded back in."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); sCol = (_testGetSet->_bufferSize.X) * 2; sRow = (_testGetSet->_viewport.Bottom - _testGetSet->_viewport.Top) * 2; _testGetSet->_expectedCursorPos.X = _testGetSet->_bufferSize.X - 1; _testGetSet->_expectedCursorPos.Y = _testGetSet->_viewport.Bottom - 1; VERIFY_IS_TRUE(_pDispatch.get()->CursorPosition(sRow, sCol)); Log::Comment(L"Test 4: GetConsoleInfo API returns false. No move, return false."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); _testGetSet->_getConsoleScreenBufferInfoExResult = FALSE; VERIFY_IS_FALSE(_pDispatch.get()->CursorPosition(1, 1)); Log::Comment(L"Test 5: SetCursor API returns false. No move, return false."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); _testGetSet->_setConsoleCursorPositionResult = FALSE; VERIFY_IS_FALSE(_pDispatch.get()->CursorPosition(1, 1)); } TEST_METHOD(CursorSingleDimensionMoveTest) { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiDirection", L"{0, 1}") // These values align with the CursorDirection enum class to try all the directions. END_TEST_METHOD_PROPERTIES() Log::Comment(L"Starting test..."); //// Used to switch between the various function options. typedef bool (AdaptDispatch::*CursorMoveFunc)(size_t); CursorMoveFunc moveFunc = nullptr; SHORT sRangeEnd = 0; SHORT sRangeStart = 0; SHORT* psCursorExpected = nullptr; // Modify variables based on directionality of this test AbsolutePosition direction; size_t dir; VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"uiDirection", dir)); direction = (AbsolutePosition)dir; _testGetSet->PrepData(); switch (direction) { case AbsolutePosition::CursorHorizontal: Log::Comment(L"Testing cursor horizontal movement."); sRangeEnd = _testGetSet->_bufferSize.X; sRangeStart = 0; psCursorExpected = &_testGetSet->_expectedCursorPos.X; moveFunc = &AdaptDispatch::CursorHorizontalPositionAbsolute; break; case AbsolutePosition::VerticalLine: Log::Comment(L"Testing vertical line movement."); sRangeEnd = _testGetSet->_viewport.Bottom; sRangeStart = _testGetSet->_viewport.Top; psCursorExpected = &_testGetSet->_expectedCursorPos.Y; moveFunc = &AdaptDispatch::VerticalLinePositionAbsolute; break; } if (moveFunc == nullptr || psCursorExpected == nullptr) { VERIFY_FAIL(); return; } Log::Comment(L"Test 1: Place cursor within the viewport. Start from top left, move to middle."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); short sVal = (sRangeEnd - sRangeStart) / 2; *psCursorExpected = sRangeStart + (sVal - 1); VERIFY_IS_TRUE((_pDispatch.get()->*(moveFunc))(sVal)); Log::Comment(L"Test 2: Move to 0 (which is 1 in VT speak)"); _testGetSet->PrepData(CursorX::RIGHT, CursorY::BOTTOM); *psCursorExpected = sRangeStart; sVal = 1; VERIFY_IS_TRUE((_pDispatch.get()->*(moveFunc))(sVal)); Log::Comment(L"Test 3: Move beyond rectangle (down/right too far). Should be bounded back in."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); sVal = (sRangeEnd - sRangeStart) * 2; *psCursorExpected = sRangeEnd - 1; VERIFY_IS_TRUE((_pDispatch.get()->*(moveFunc))(sVal)); Log::Comment(L"Test 4: GetConsoleInfo API returns false. No move, return false."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); _testGetSet->_getConsoleScreenBufferInfoExResult = FALSE; sVal = 1; VERIFY_IS_FALSE((_pDispatch.get()->*(moveFunc))(sVal)); Log::Comment(L"Test 5: SetCursor API returns false. No move, return false."); _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); _testGetSet->_setConsoleCursorPositionResult = FALSE; sVal = 1; VERIFY_IS_FALSE((_pDispatch.get()->*(moveFunc))(sVal)); } TEST_METHOD(CursorSaveRestoreTest) { Log::Comment(L"Starting test..."); COORD coordExpected = { 0 }; Log::Comment(L"Test 1: Restore with no saved data should move to top-left corner, the null/default position."); // Move cursor to top left and save off expected position. _testGetSet->PrepData(CursorX::LEFT, CursorY::TOP); coordExpected = _testGetSet->_expectedCursorPos; // Then move cursor to the middle and reset the expected to the top left. _testGetSet->PrepData(CursorX::XCENTER, CursorY::YCENTER); _testGetSet->_expectedCursorPos = coordExpected; // Attributes are restored to defaults. _testGetSet->_expectedAttribute = {}; VERIFY_IS_TRUE(_pDispatch.get()->CursorRestoreState(), L"By default, restore to top left corner (0,0 offset from viewport)."); Log::Comment(L"Test 2: Place cursor in center. Save. Move cursor to corner. Restore. Should come back to center."); _testGetSet->PrepData(CursorX::XCENTER, CursorY::YCENTER); VERIFY_IS_TRUE(_pDispatch.get()->CursorSaveState(), L"Succeed at saving position."); Log::Comment(L"Backup expected cursor (in the middle). Move cursor to corner. Then re-set expected cursor to middle."); // save expected cursor position coordExpected = _testGetSet->_expectedCursorPos; // adjust cursor to corner _testGetSet->PrepData(CursorX::LEFT, CursorY::BOTTOM); // restore expected cursor position to center. _testGetSet->_expectedCursorPos = coordExpected; VERIFY_IS_TRUE(_pDispatch.get()->CursorRestoreState(), L"Restoring to corner should succeed. API call inside will test that cursor matched expected position."); } TEST_METHOD(CursorHideShowTest) { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:fStartingVis", L"{TRUE, FALSE}") TEST_METHOD_PROPERTY(L"Data:fEndingVis", L"{TRUE, FALSE}") END_TEST_METHOD_PROPERTIES() Log::Comment(L"Starting test..."); // Modify variables based on permutations of this test. bool fStart; bool fEnd; VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"fStartingVis", fStart)); VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"fEndingVis", fEnd)); Log::Comment(L"Test 1: Verify successful API call modifies visibility state."); _testGetSet->PrepData(); _testGetSet->_cursorVisible = fStart; _testGetSet->_privateShowCursorResult = true; _testGetSet->_expectedShowCursor = fEnd; VERIFY_IS_TRUE(_pDispatch.get()->CursorVisibility(fEnd)); Log::Comment(L"Test 3: When we fail to set updated cursor information, the dispatch should fail."); _testGetSet->PrepData(); _testGetSet->_privateShowCursorResult = false; VERIFY_IS_FALSE(_pDispatch.get()->CursorVisibility(fEnd)); } TEST_METHOD(GraphicsBaseTests) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Send no options."); _testGetSet->PrepData(); VTParameter rgOptions[16]; size_t cOptions = 0; VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Test 2: Gracefully fail when getting attribute data fails."); _testGetSet->PrepData(); _testGetSet->_privateGetTextAttributesResult = FALSE; VERIFY_IS_FALSE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Test 3: Gracefully fail when setting attribute data fails."); _testGetSet->PrepData(); _testGetSet->_privateSetTextAttributesResult = FALSE; // Need at least one option in order for the call to be able to fail. rgOptions[0] = (DispatchTypes::GraphicsOptions)0; cOptions = 1; VERIFY_IS_FALSE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); } TEST_METHOD(GraphicsSingleTests) { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"Data:uiGraphicsOptions", L"{0, 1, 2, 4, 7, 8, 9, 21, 22, 24, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49, 53, 55, 90, 91, 92, 93, 94, 95, 96, 97, 100, 101, 102, 103, 104, 105, 106, 107}") // corresponds to options in DispatchTypes::GraphicsOptions END_TEST_METHOD_PROPERTIES() Log::Comment(L"Starting test..."); _testGetSet->PrepData(); // Modify variables based on type of this test DispatchTypes::GraphicsOptions graphicsOption; size_t uiGraphicsOption; VERIFY_SUCCEEDED_RETURN(TestData::TryGetValue(L"uiGraphicsOptions", uiGraphicsOption)); graphicsOption = (DispatchTypes::GraphicsOptions)uiGraphicsOption; VTParameter rgOptions[16]; size_t cOptions = 1; rgOptions[0] = graphicsOption; switch (graphicsOption) { case DispatchTypes::GraphicsOptions::Off: Log::Comment(L"Testing graphics 'Off/Reset'"); _testGetSet->_attribute = TextAttribute{ (WORD)~_testGetSet->s_defaultFill }; _testGetSet->_expectedAttribute = TextAttribute{}; break; case DispatchTypes::GraphicsOptions::BoldBright: Log::Comment(L"Testing graphics 'Bold/Bright'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute.SetBold(true); break; case DispatchTypes::GraphicsOptions::RGBColorOrFaint: Log::Comment(L"Testing graphics 'Faint'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute.SetFaint(true); break; case DispatchTypes::GraphicsOptions::Underline: Log::Comment(L"Testing graphics 'Underline'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute.SetUnderlined(true); break; case DispatchTypes::GraphicsOptions::DoublyUnderlined: Log::Comment(L"Testing graphics 'Doubly Underlined'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute.SetDoublyUnderlined(true); break; case DispatchTypes::GraphicsOptions::Overline: Log::Comment(L"Testing graphics 'Overline'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ COMMON_LVB_GRID_HORIZONTAL }; break; case DispatchTypes::GraphicsOptions::Negative: Log::Comment(L"Testing graphics 'Negative'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ COMMON_LVB_REVERSE_VIDEO }; break; case DispatchTypes::GraphicsOptions::Invisible: Log::Comment(L"Testing graphics 'Invisible'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute.SetInvisible(true); break; case DispatchTypes::GraphicsOptions::CrossedOut: Log::Comment(L"Testing graphics 'Crossed Out'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute.SetCrossedOut(true); break; case DispatchTypes::GraphicsOptions::NotBoldOrFaint: Log::Comment(L"Testing graphics 'No Bold or Faint'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_attribute.SetBold(true); _testGetSet->_attribute.SetFaint(true); _testGetSet->_expectedAttribute = TextAttribute{ 0 }; break; case DispatchTypes::GraphicsOptions::NoUnderline: Log::Comment(L"Testing graphics 'No Underline'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_attribute.SetUnderlined(true); _testGetSet->_attribute.SetDoublyUnderlined(true); _testGetSet->_expectedAttribute = TextAttribute{ 0 }; break; case DispatchTypes::GraphicsOptions::NoOverline: Log::Comment(L"Testing graphics 'No Overline'"); _testGetSet->_attribute = TextAttribute{ COMMON_LVB_GRID_HORIZONTAL }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; break; case DispatchTypes::GraphicsOptions::Positive: Log::Comment(L"Testing graphics 'Positive'"); _testGetSet->_attribute = TextAttribute{ COMMON_LVB_REVERSE_VIDEO }; _testGetSet->_expectedAttribute = TextAttribute{ 0 }; break; case DispatchTypes::GraphicsOptions::Visible: Log::Comment(L"Testing graphics 'Visible'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_attribute.SetInvisible(true); _testGetSet->_expectedAttribute = TextAttribute{ 0 }; break; case DispatchTypes::GraphicsOptions::NotCrossedOut: Log::Comment(L"Testing graphics 'Not Crossed Out'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_attribute.SetCrossedOut(true); _testGetSet->_expectedAttribute = TextAttribute{ 0 }; break; case DispatchTypes::GraphicsOptions::ForegroundBlack: Log::Comment(L"Testing graphics 'Foreground Color Black'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(0); break; case DispatchTypes::GraphicsOptions::ForegroundBlue: Log::Comment(L"Testing graphics 'Foreground Color Blue'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE); break; case DispatchTypes::GraphicsOptions::ForegroundGreen: Log::Comment(L"Testing graphics 'Foreground Color Green'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); break; case DispatchTypes::GraphicsOptions::ForegroundCyan: Log::Comment(L"Testing graphics 'Foreground Color Cyan'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED | FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE | FOREGROUND_GREEN); break; case DispatchTypes::GraphicsOptions::ForegroundRed: Log::Comment(L"Testing graphics 'Foreground Color Red'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::ForegroundMagenta: Log::Comment(L"Testing graphics 'Foreground Color Magenta'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_GREEN | FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE | FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::ForegroundYellow: Log::Comment(L"Testing graphics 'Foreground Color Yellow'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_BLUE | FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN | FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::ForegroundWhite: Log::Comment(L"Testing graphics 'Foreground Color White'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::ForegroundDefault: Log::Comment(L"Testing graphics 'Foreground Color Default'"); _testGetSet->_attribute = TextAttribute{ (WORD)~_testGetSet->s_wDefaultAttribute }; // set the current attribute to the opposite of default so we can ensure all relevant bits flip. // To get expected value, take what we started with and change ONLY the background series of bits to what the Default says. _testGetSet->_expectedAttribute = _testGetSet->_attribute; // expect = starting _testGetSet->_expectedAttribute.SetDefaultForeground(); // set the foreground as default break; case DispatchTypes::GraphicsOptions::BackgroundBlack: Log::Comment(L"Testing graphics 'Background Color Black'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground(0); break; case DispatchTypes::GraphicsOptions::BackgroundBlue: Log::Comment(L"Testing graphics 'Background Color Blue'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_BLUE >> 4); break; case DispatchTypes::GraphicsOptions::BackgroundGreen: Log::Comment(L"Testing graphics 'Background Color Green'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_GREEN >> 4); break; case DispatchTypes::GraphicsOptions::BackgroundCyan: Log::Comment(L"Testing graphics 'Background Color Cyan'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED | BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_BLUE | BACKGROUND_GREEN) >> 4); break; case DispatchTypes::GraphicsOptions::BackgroundRed: Log::Comment(L"Testing graphics 'Background Color Red'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_RED >> 4); break; case DispatchTypes::GraphicsOptions::BackgroundMagenta: Log::Comment(L"Testing graphics 'Background Color Magenta'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_GREEN | BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_BLUE | BACKGROUND_RED) >> 4); break; case DispatchTypes::GraphicsOptions::BackgroundYellow: Log::Comment(L"Testing graphics 'Background Color Yellow'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_BLUE | BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_GREEN | BACKGROUND_RED) >> 4); break; case DispatchTypes::GraphicsOptions::BackgroundWhite: Log::Comment(L"Testing graphics 'Background Color White'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_INTENSITY }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED) >> 4); break; case DispatchTypes::GraphicsOptions::BackgroundDefault: Log::Comment(L"Testing graphics 'Background Color Default'"); _testGetSet->_attribute = TextAttribute{ (WORD)~_testGetSet->s_wDefaultAttribute }; // set the current attribute to the opposite of default so we can ensure all relevant bits flip. // To get expected value, take what we started with and change ONLY the background series of bits to what the Default says. _testGetSet->_expectedAttribute = _testGetSet->_attribute; // expect = starting _testGetSet->_expectedAttribute.SetDefaultBackground(); // set the background as default break; case DispatchTypes::GraphicsOptions::BrightForegroundBlack: Log::Comment(L"Testing graphics 'Bright Foreground Color Black'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY); break; case DispatchTypes::GraphicsOptions::BrightForegroundBlue: Log::Comment(L"Testing graphics 'Bright Foreground Color Blue'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED | FOREGROUND_GREEN }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY | FOREGROUND_BLUE); break; case DispatchTypes::GraphicsOptions::BrightForegroundGreen: Log::Comment(L"Testing graphics 'Bright Foreground Color Green'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED | FOREGROUND_BLUE }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY | FOREGROUND_GREEN); break; case DispatchTypes::GraphicsOptions::BrightForegroundCyan: Log::Comment(L"Testing graphics 'Bright Foreground Color Cyan'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_RED }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN); break; case DispatchTypes::GraphicsOptions::BrightForegroundRed: Log::Comment(L"Testing graphics 'Bright Foreground Color Red'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_BLUE | FOREGROUND_GREEN }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY | FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::BrightForegroundMagenta: Log::Comment(L"Testing graphics 'Bright Foreground Color Magenta'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_GREEN }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::BrightForegroundYellow: Log::Comment(L"Testing graphics 'Bright Foreground Color Yellow'"); _testGetSet->_attribute = TextAttribute{ FOREGROUND_BLUE }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::BrightForegroundWhite: Log::Comment(L"Testing graphics 'Bright Foreground Color White'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); break; case DispatchTypes::GraphicsOptions::BrightBackgroundBlack: Log::Comment(L"Testing graphics 'Bright Background Color Black'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_INTENSITY >> 4); break; case DispatchTypes::GraphicsOptions::BrightBackgroundBlue: Log::Comment(L"Testing graphics 'Bright Background Color Blue'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED | BACKGROUND_GREEN }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_INTENSITY | BACKGROUND_BLUE) >> 4); break; case DispatchTypes::GraphicsOptions::BrightBackgroundGreen: Log::Comment(L"Testing graphics 'Bright Background Color Green'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED | BACKGROUND_BLUE }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_INTENSITY | BACKGROUND_GREEN) >> 4); break; case DispatchTypes::GraphicsOptions::BrightBackgroundCyan: Log::Comment(L"Testing graphics 'Bright Background Color Cyan'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_RED }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_INTENSITY | BACKGROUND_BLUE | BACKGROUND_GREEN) >> 4); break; case DispatchTypes::GraphicsOptions::BrightBackgroundRed: Log::Comment(L"Testing graphics 'Bright Background Color Red'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_BLUE | BACKGROUND_GREEN }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_INTENSITY | BACKGROUND_RED) >> 4); break; case DispatchTypes::GraphicsOptions::BrightBackgroundMagenta: Log::Comment(L"Testing graphics 'Bright Background Color Magenta'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_GREEN }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_INTENSITY | BACKGROUND_BLUE | BACKGROUND_RED) >> 4); break; case DispatchTypes::GraphicsOptions::BrightBackgroundYellow: Log::Comment(L"Testing graphics 'Bright Background Color Yellow'"); _testGetSet->_attribute = TextAttribute{ BACKGROUND_BLUE }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_INTENSITY | BACKGROUND_GREEN | BACKGROUND_RED) >> 4); break; case DispatchTypes::GraphicsOptions::BrightBackgroundWhite: Log::Comment(L"Testing graphics 'Bright Background Color White'"); _testGetSet->_attribute = TextAttribute{ 0 }; _testGetSet->_expectedAttribute = _testGetSet->_attribute; _testGetSet->_expectedAttribute.SetIndexedBackground((BACKGROUND_INTENSITY | BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED) >> 4); break; default: VERIFY_FAIL(L"Test not implemented yet!"); break; } VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); } TEST_METHOD(GraphicsPushPopTests) { Log::Comment(L"Starting test..."); _testGetSet->PrepData(); // default color from here is gray on black, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED VTParameter rgOptions[16]; VTParameter rgStackOptions[16]; size_t cOptions = 1; Log::Comment(L"Test 1: Basic push and pop"); rgOptions[0] = DispatchTypes::GraphicsOptions::Off; _testGetSet->_expectedAttribute = {}; VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); cOptions = 0; VERIFY_IS_TRUE(_pDispatch->PushGraphicsRendition({ rgStackOptions, cOptions })); VERIFY_IS_TRUE(_pDispatch->PopGraphicsRendition()); Log::Comment(L"Test 2: Push, change color, pop"); VERIFY_IS_TRUE(_pDispatch->PushGraphicsRendition({ rgStackOptions, cOptions })); cOptions = 1; rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundCyan; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(3); _testGetSet->_expectedAttribute.SetDefaultBackground(); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); cOptions = 0; _testGetSet->_expectedAttribute = {}; VERIFY_IS_TRUE(_pDispatch->PopGraphicsRendition()); Log::Comment(L"Test 3: two pushes (nested) and pops"); // First push: VERIFY_IS_TRUE(_pDispatch->PushGraphicsRendition({ rgStackOptions, cOptions })); cOptions = 1; rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundRed; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_RED); _testGetSet->_expectedAttribute.SetDefaultBackground(); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); // Second push: cOptions = 0; VERIFY_IS_TRUE(_pDispatch->PushGraphicsRendition({ rgStackOptions, cOptions })); cOptions = 1; rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundGreen; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); _testGetSet->_expectedAttribute.SetDefaultBackground(); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); // First pop: cOptions = 0; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_RED); _testGetSet->_expectedAttribute.SetDefaultBackground(); VERIFY_IS_TRUE(_pDispatch->PopGraphicsRendition()); // Second pop: cOptions = 0; _testGetSet->_expectedAttribute = {}; VERIFY_IS_TRUE(_pDispatch->PopGraphicsRendition()); Log::Comment(L"Test 4: Save and restore partial attributes"); cOptions = 1; rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundGreen; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); _testGetSet->_expectedAttribute.SetDefaultBackground(); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); cOptions = 1; rgOptions[0] = DispatchTypes::GraphicsOptions::BoldBright; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); _testGetSet->_expectedAttribute.SetBold(true); _testGetSet->_expectedAttribute.SetDefaultBackground(); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); rgOptions[0] = DispatchTypes::GraphicsOptions::BackgroundBlue; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_BLUE >> 4); _testGetSet->_expectedAttribute.SetBold(true); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); // Push, specifying that we only want to save the background, the boldness, and double-underline-ness: cOptions = 3; rgStackOptions[0] = (size_t)DispatchTypes::SgrSaveRestoreStackOptions::Boldness; rgStackOptions[1] = (size_t)DispatchTypes::SgrSaveRestoreStackOptions::SaveBackgroundColor; rgStackOptions[2] = (size_t)DispatchTypes::SgrSaveRestoreStackOptions::DoublyUnderlined; VERIFY_IS_TRUE(_pDispatch->PushGraphicsRendition({ rgStackOptions, cOptions })); // Now change everything... cOptions = 2; rgOptions[0] = DispatchTypes::GraphicsOptions::BackgroundGreen; rgOptions[1] = DispatchTypes::GraphicsOptions::DoublyUnderlined; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_GREEN >> 4); _testGetSet->_expectedAttribute.SetBold(true); _testGetSet->_expectedAttribute.SetDoublyUnderlined(true); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); cOptions = 1; rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundRed; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_RED); _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_GREEN >> 4); _testGetSet->_expectedAttribute.SetBold(true); _testGetSet->_expectedAttribute.SetDoublyUnderlined(true); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); rgOptions[0] = DispatchTypes::GraphicsOptions::NotBoldOrFaint; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_RED); _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_GREEN >> 4); _testGetSet->_expectedAttribute.SetDoublyUnderlined(true); VERIFY_IS_TRUE(_pDispatch->SetGraphicsRendition({ rgOptions, cOptions })); // And then restore... cOptions = 0; _testGetSet->_expectedAttribute = {}; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_RED); _testGetSet->_expectedAttribute.SetIndexedBackground(BACKGROUND_BLUE >> 4); _testGetSet->_expectedAttribute.SetBold(true); VERIFY_IS_TRUE(_pDispatch->PopGraphicsRendition()); } TEST_METHOD(GraphicsPersistBrightnessTests) { Log::Comment(L"Starting test..."); _testGetSet->PrepData(); // default color from here is gray on black, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED VTParameter rgOptions[16]; size_t cOptions = 1; Log::Comment(L"Test 1: Basic brightness test"); Log::Comment(L"Resetting graphics options"); rgOptions[0] = DispatchTypes::GraphicsOptions::Off; _testGetSet->_expectedAttribute = {}; VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Testing graphics 'Foreground Color Blue'"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundBlue; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Enabling brightness"); rgOptions[0] = DispatchTypes::GraphicsOptions::BoldBright; _testGetSet->_expectedAttribute.SetBold(true); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_TRUE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Testing graphics 'Foreground Color Green, with brightness'"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundGreen; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_TRUE(WI_IsFlagSet(_testGetSet->_attribute.GetLegacyAttributes(), FOREGROUND_GREEN)); VERIFY_IS_TRUE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Test 2: Disable brightness, use a bright color, next normal call remains not bright"); Log::Comment(L"Resetting graphics options"); rgOptions[0] = DispatchTypes::GraphicsOptions::Off; _testGetSet->_expectedAttribute = {}; VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_TRUE(WI_IsFlagClear(_testGetSet->_attribute.GetLegacyAttributes(), FOREGROUND_INTENSITY)); VERIFY_IS_FALSE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Testing graphics 'Foreground Color Bright Blue'"); rgOptions[0] = DispatchTypes::GraphicsOptions::BrightForegroundBlue; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE | FOREGROUND_INTENSITY); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_FALSE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Testing graphics 'Foreground Color Blue', brightness of 9x series doesn't persist"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundBlue; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_FALSE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Test 3: Enable brightness, use a bright color, brightness persists to next normal call"); Log::Comment(L"Resetting graphics options"); rgOptions[0] = DispatchTypes::GraphicsOptions::Off; _testGetSet->_expectedAttribute = {}; VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_FALSE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Testing graphics 'Foreground Color Blue'"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundBlue; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_FALSE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Enabling brightness"); rgOptions[0] = DispatchTypes::GraphicsOptions::BoldBright; _testGetSet->_expectedAttribute.SetBold(true); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_TRUE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Testing graphics 'Foreground Color Bright Blue'"); rgOptions[0] = DispatchTypes::GraphicsOptions::BrightForegroundBlue; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE | FOREGROUND_INTENSITY); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_TRUE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Testing graphics 'Foreground Color Blue, with brightness', brightness of 9x series doesn't affect brightness"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundBlue; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_BLUE); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_TRUE(_testGetSet->_attribute.IsBold()); Log::Comment(L"Testing graphics 'Foreground Color Green, with brightness'"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundGreen; _testGetSet->_expectedAttribute.SetIndexedForeground(FOREGROUND_GREEN); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); VERIFY_IS_TRUE(_testGetSet->_attribute.IsBold()); } TEST_METHOD(DeviceStatusReportTests) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Verify failure when using bad status."); _testGetSet->PrepData(); VERIFY_IS_FALSE(_pDispatch.get()->DeviceStatusReport((DispatchTypes::AnsiStatusType)-1)); } TEST_METHOD(DeviceStatus_OperatingStatusTests) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Verify good operating condition."); _testGetSet->PrepData(); VERIFY_IS_TRUE(_pDispatch.get()->DeviceStatusReport(DispatchTypes::AnsiStatusType::OS_OperatingStatus)); _testGetSet->ValidateInputEvent(L"\x1b[0n"); } TEST_METHOD(DeviceStatus_CursorPositionReportTests) { Log::Comment(L"Starting test..."); { Log::Comment(L"Test 1: Verify normal cursor response position."); _testGetSet->PrepData(CursorX::XCENTER, CursorY::YCENTER); // start with the cursor position in the buffer. COORD coordCursorExpected = _testGetSet->_cursorPos; // to get to VT, we have to adjust it to its position relative to the viewport top. coordCursorExpected.Y -= _testGetSet->_viewport.Top; // Then note that VT is 1,1 based for the top left, so add 1. (The rest of the console uses 0,0 for array index bases.) coordCursorExpected.X++; coordCursorExpected.Y++; VERIFY_IS_TRUE(_pDispatch.get()->DeviceStatusReport(DispatchTypes::AnsiStatusType::CPR_CursorPositionReport)); wchar_t pwszBuffer[50]; swprintf_s(pwszBuffer, ARRAYSIZE(pwszBuffer), L"\x1b[%d;%dR", coordCursorExpected.Y, coordCursorExpected.X); _testGetSet->ValidateInputEvent(pwszBuffer); } { Log::Comment(L"Test 2: Verify multiple CPRs with a cursor move between them"); _testGetSet->PrepData(CursorX::XCENTER, CursorY::YCENTER); // enable retention so that the two DSR responses don't delete eachother auto retentionScope{ _testGetSet->EnableInputRetentionInScope() }; // start with the cursor position in the buffer. til::point coordCursorExpectedFirst{ _testGetSet->_cursorPos }; // to get to VT, we have to adjust it to its position relative to the viewport top. coordCursorExpectedFirst -= til::point{ 0, _testGetSet->_viewport.Top }; // Then note that VT is 1,1 based for the top left, so add 1. (The rest of the console uses 0,0 for array index bases.) coordCursorExpectedFirst += til::point{ 1, 1 }; VERIFY_IS_TRUE(_pDispatch.get()->DeviceStatusReport(DispatchTypes::AnsiStatusType::CPR_CursorPositionReport)); _testGetSet->_cursorPos.X++; _testGetSet->_cursorPos.Y++; auto coordCursorExpectedSecond{ coordCursorExpectedFirst }; coordCursorExpectedSecond += til::point{ 1, 1 }; VERIFY_IS_TRUE(_pDispatch.get()->DeviceStatusReport(DispatchTypes::AnsiStatusType::CPR_CursorPositionReport)); wchar_t pwszBuffer[50]; swprintf_s(pwszBuffer, ARRAYSIZE(pwszBuffer), L"\x1b[%d;%dR\x1b[%d;%dR", coordCursorExpectedFirst.y<int>(), coordCursorExpectedFirst.x<int>(), coordCursorExpectedSecond.y<int>(), coordCursorExpectedSecond.x<int>()); _testGetSet->ValidateInputEvent(pwszBuffer); } } TEST_METHOD(DeviceAttributesTests) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Verify normal response."); _testGetSet->PrepData(); VERIFY_IS_TRUE(_pDispatch.get()->DeviceAttributes()); PCWSTR pwszExpectedResponse = L"\x1b[?1;0c"; _testGetSet->ValidateInputEvent(pwszExpectedResponse); Log::Comment(L"Test 2: Verify failure when WriteConsoleInput doesn't work."); _testGetSet->PrepData(); _testGetSet->_privateWriteConsoleInputWResult = FALSE; VERIFY_IS_FALSE(_pDispatch.get()->DeviceAttributes()); } TEST_METHOD(SecondaryDeviceAttributesTests) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Verify normal response."); _testGetSet->PrepData(); VERIFY_IS_TRUE(_pDispatch.get()->SecondaryDeviceAttributes()); PCWSTR pwszExpectedResponse = L"\x1b[>0;10;1c"; _testGetSet->ValidateInputEvent(pwszExpectedResponse); Log::Comment(L"Test 2: Verify failure when WriteConsoleInput doesn't work."); _testGetSet->PrepData(); _testGetSet->_privateWriteConsoleInputWResult = FALSE; VERIFY_IS_FALSE(_pDispatch.get()->SecondaryDeviceAttributes()); } TEST_METHOD(TertiaryDeviceAttributesTests) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Verify normal response."); _testGetSet->PrepData(); VERIFY_IS_TRUE(_pDispatch.get()->TertiaryDeviceAttributes()); PCWSTR pwszExpectedResponse = L"\x1bP!|00000000\x1b\\"; _testGetSet->ValidateInputEvent(pwszExpectedResponse); Log::Comment(L"Test 2: Verify failure when WriteConsoleInput doesn't work."); _testGetSet->PrepData(); _testGetSet->_privateWriteConsoleInputWResult = FALSE; VERIFY_IS_FALSE(_pDispatch.get()->TertiaryDeviceAttributes()); } TEST_METHOD(RequestTerminalParametersTests) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Verify response for unsolicited permission."); _testGetSet->PrepData(); VERIFY_IS_TRUE(_pDispatch.get()->RequestTerminalParameters(DispatchTypes::ReportingPermission::Unsolicited)); _testGetSet->ValidateInputEvent(L"\x1b[2;1;1;128;128;1;0x"); Log::Comment(L"Test 2: Verify response for solicited permission."); _testGetSet->PrepData(); VERIFY_IS_TRUE(_pDispatch.get()->RequestTerminalParameters(DispatchTypes::ReportingPermission::Solicited)); _testGetSet->ValidateInputEvent(L"\x1b[3;1;1;128;128;1;0x"); Log::Comment(L"Test 3: Verify failure with invalid parameter."); _testGetSet->PrepData(); VERIFY_IS_FALSE(_pDispatch.get()->RequestTerminalParameters((DispatchTypes::ReportingPermission)2)); Log::Comment(L"Test 4: Verify failure when WriteConsoleInput doesn't work."); _testGetSet->PrepData(); _testGetSet->_privateWriteConsoleInputWResult = FALSE; VERIFY_IS_FALSE(_pDispatch.get()->RequestTerminalParameters(DispatchTypes::ReportingPermission::Unsolicited)); } TEST_METHOD(CursorKeysModeTest) { Log::Comment(L"Starting test..."); // success cases // set numeric mode = true Log::Comment(L"Test 1: application mode = false"); _testGetSet->_privateSetCursorKeysModeResult = TRUE; _testGetSet->_cursorKeysApplicationMode = false; VERIFY_IS_TRUE(_pDispatch.get()->SetCursorKeysMode(false)); // set numeric mode = false Log::Comment(L"Test 2: application mode = true"); _testGetSet->_privateSetCursorKeysModeResult = TRUE; _testGetSet->_cursorKeysApplicationMode = true; VERIFY_IS_TRUE(_pDispatch.get()->SetCursorKeysMode(true)); } TEST_METHOD(KeypadModeTest) { Log::Comment(L"Starting test..."); // success cases // set numeric mode = true Log::Comment(L"Test 1: application mode = false"); _testGetSet->_privateSetKeypadModeResult = TRUE; _testGetSet->_keypadApplicationMode = false; VERIFY_IS_TRUE(_pDispatch.get()->SetKeypadMode(false)); // set numeric mode = false Log::Comment(L"Test 2: application mode = true"); _testGetSet->_privateSetKeypadModeResult = TRUE; _testGetSet->_keypadApplicationMode = true; VERIFY_IS_TRUE(_pDispatch.get()->SetKeypadMode(true)); } TEST_METHOD(AnsiModeTest) { Log::Comment(L"Starting test..."); // success cases // set ansi mode = true Log::Comment(L"Test 1: ansi mode = true"); _testGetSet->_privateSetAnsiModeResult = true; _testGetSet->_expectedAnsiMode = true; VERIFY_IS_TRUE(_pDispatch.get()->SetAnsiMode(true)); // set ansi mode = false Log::Comment(L"Test 2: ansi mode = false."); _testGetSet->_privateSetAnsiModeResult = true; _testGetSet->_expectedAnsiMode = false; VERIFY_IS_TRUE(_pDispatch.get()->SetAnsiMode(false)); } TEST_METHOD(AllowBlinkingTest) { Log::Comment(L"Starting test..."); // success cases // set numeric mode = true Log::Comment(L"Test 1: enable blinking = true"); _testGetSet->_privateAllowCursorBlinkingResult = TRUE; _testGetSet->_enable = true; VERIFY_IS_TRUE(_pDispatch.get()->EnableCursorBlinking(true)); // set numeric mode = false Log::Comment(L"Test 2: enable blinking = false"); _testGetSet->_privateAllowCursorBlinkingResult = TRUE; _testGetSet->_enable = false; VERIFY_IS_TRUE(_pDispatch.get()->EnableCursorBlinking(false)); } TEST_METHOD(ScrollMarginsTest) { Log::Comment(L"Starting test..."); SMALL_RECT srTestMargins = { 0 }; _testGetSet->_bufferSize = { 100, 600 }; _testGetSet->_viewport.Right = 8; _testGetSet->_viewport.Bottom = 8; _testGetSet->_getConsoleScreenBufferInfoExResult = TRUE; SHORT sScreenHeight = _testGetSet->_viewport.Bottom - _testGetSet->_viewport.Top; Log::Comment(L"Test 1: Verify having both values is valid."); _testGetSet->_SetMarginsHelper(&srTestMargins, 2, 6); _testGetSet->_privateSetScrollingRegionResult = TRUE; _testGetSet->_setConsoleCursorPositionResult = true; _testGetSet->_moveToBottomResult = true; VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 2: Verify having only top is valid."); _testGetSet->_SetMarginsHelper(&srTestMargins, 7, 0); _testGetSet->_expectedScrollRegion.Bottom = _testGetSet->_viewport.Bottom - 1; // We expect the bottom to be the bottom of the viewport, exclusive. _testGetSet->_privateSetScrollingRegionResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 3: Verify having only bottom is valid."); _testGetSet->_SetMarginsHelper(&srTestMargins, 0, 7); _testGetSet->_privateSetScrollingRegionResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 4: Verify having no values is valid."); _testGetSet->_SetMarginsHelper(&srTestMargins, 0, 0); _testGetSet->_privateSetScrollingRegionResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 5: Verify having both values, but bad bounds is invalid."); _testGetSet->_SetMarginsHelper(&srTestMargins, 7, 3); _testGetSet->_privateSetScrollingRegionResult = TRUE; VERIFY_IS_FALSE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 6: Verify setting margins to (0, height) clears them"); // First set, _testGetSet->_privateSetScrollingRegionResult = TRUE; _testGetSet->_SetMarginsHelper(&srTestMargins, 2, 6); VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); // Then clear _testGetSet->_SetMarginsHelper(&srTestMargins, 0, sScreenHeight); _testGetSet->_expectedScrollRegion.Top = 0; _testGetSet->_expectedScrollRegion.Bottom = 0; VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 7: Verify setting margins to (1, height) clears them"); // First set, _testGetSet->_privateSetScrollingRegionResult = TRUE; _testGetSet->_SetMarginsHelper(&srTestMargins, 2, 6); VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); // Then clear _testGetSet->_SetMarginsHelper(&srTestMargins, 1, sScreenHeight); _testGetSet->_expectedScrollRegion.Top = 0; _testGetSet->_expectedScrollRegion.Bottom = 0; VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 8: Verify setting margins to (1, 0) clears them"); // First set, _testGetSet->_privateSetScrollingRegionResult = TRUE; _testGetSet->_SetMarginsHelper(&srTestMargins, 2, 6); VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); // Then clear _testGetSet->_SetMarginsHelper(&srTestMargins, 1, 0); _testGetSet->_expectedScrollRegion.Top = 0; _testGetSet->_expectedScrollRegion.Bottom = 0; VERIFY_IS_TRUE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 9: Verify having top and bottom margin the same is invalid."); _testGetSet->_SetMarginsHelper(&srTestMargins, 4, 4); _testGetSet->_privateSetScrollingRegionResult = TRUE; VERIFY_IS_FALSE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 10: Verify having top margin out of bounds is invalid."); _testGetSet->_SetMarginsHelper(&srTestMargins, sScreenHeight + 1, sScreenHeight + 10); _testGetSet->_privateSetScrollingRegionResult = TRUE; VERIFY_IS_FALSE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); Log::Comment(L"Test 11: Verify having bottom margin out of bounds is invalid."); _testGetSet->_SetMarginsHelper(&srTestMargins, 1, sScreenHeight + 1); _testGetSet->_privateSetScrollingRegionResult = TRUE; VERIFY_IS_FALSE(_pDispatch.get()->SetTopBottomScrollingMargins(srTestMargins.Top, srTestMargins.Bottom)); } TEST_METHOD(LineFeedTest) { Log::Comment(L"Starting test..."); // All test cases need the LineFeed call to succeed. _testGetSet->_privateLineFeedResult = TRUE; Log::Comment(L"Test 1: Line feed without carriage return."); _testGetSet->_expectedLineFeedWithReturn = false; VERIFY_IS_TRUE(_pDispatch.get()->LineFeed(DispatchTypes::LineFeedType::WithoutReturn)); Log::Comment(L"Test 2: Line feed with carriage return."); _testGetSet->_expectedLineFeedWithReturn = true; VERIFY_IS_TRUE(_pDispatch.get()->LineFeed(DispatchTypes::LineFeedType::WithReturn)); Log::Comment(L"Test 3: Line feed depends on mode, and mode reset."); _testGetSet->_privateGetLineFeedModeResult = false; _testGetSet->_expectedLineFeedWithReturn = false; VERIFY_IS_TRUE(_pDispatch.get()->LineFeed(DispatchTypes::LineFeedType::DependsOnMode)); Log::Comment(L"Test 4: Line feed depends on mode, and mode set."); _testGetSet->_privateGetLineFeedModeResult = true; _testGetSet->_expectedLineFeedWithReturn = true; VERIFY_IS_TRUE(_pDispatch.get()->LineFeed(DispatchTypes::LineFeedType::DependsOnMode)); } TEST_METHOD(SetConsoleTitleTest) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: set title to be non-null"); _testGetSet->_setConsoleTitleWResult = TRUE; _testGetSet->_expectedWindowTitle = L"Foo bar"; VERIFY_IS_TRUE(_pDispatch.get()->SetWindowTitle(_testGetSet->_expectedWindowTitle)); Log::Comment(L"Test 2: set title to be null"); _testGetSet->_setConsoleTitleWResult = FALSE; _testGetSet->_expectedWindowTitle = {}; VERIFY_IS_TRUE(_pDispatch.get()->SetWindowTitle({})); } TEST_METHOD(TestMouseModes) { Log::Comment(L"Starting test..."); Log::Comment(L"Test 1: Test Default Mouse Mode"); _testGetSet->_expectedMouseEnabled = true; _testGetSet->_privateEnableVT200MouseModeResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->EnableVT200MouseMode(true)); _testGetSet->_expectedMouseEnabled = false; VERIFY_IS_TRUE(_pDispatch.get()->EnableVT200MouseMode(false)); Log::Comment(L"Test 2: Test UTF-8 Extended Mouse Mode"); _testGetSet->_expectedMouseEnabled = true; _testGetSet->_privateEnableUTF8ExtendedMouseModeResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->EnableUTF8ExtendedMouseMode(true)); _testGetSet->_expectedMouseEnabled = false; VERIFY_IS_TRUE(_pDispatch.get()->EnableUTF8ExtendedMouseMode(false)); Log::Comment(L"Test 3: Test SGR Extended Mouse Mode"); _testGetSet->_expectedMouseEnabled = true; _testGetSet->_privateEnableSGRExtendedMouseModeResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->EnableSGRExtendedMouseMode(true)); _testGetSet->_expectedMouseEnabled = false; VERIFY_IS_TRUE(_pDispatch.get()->EnableSGRExtendedMouseMode(false)); Log::Comment(L"Test 4: Test Button-Event Mouse Mode"); _testGetSet->_expectedMouseEnabled = true; _testGetSet->_privateEnableButtonEventMouseModeResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->EnableButtonEventMouseMode(true)); _testGetSet->_expectedMouseEnabled = false; VERIFY_IS_TRUE(_pDispatch.get()->EnableButtonEventMouseMode(false)); Log::Comment(L"Test 5: Test Any-Event Mouse Mode"); _testGetSet->_expectedMouseEnabled = true; _testGetSet->_privateEnableAnyEventMouseModeResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->EnableAnyEventMouseMode(true)); _testGetSet->_expectedMouseEnabled = false; VERIFY_IS_TRUE(_pDispatch.get()->EnableAnyEventMouseMode(false)); Log::Comment(L"Test 6: Test Alt Scroll Mouse Mode"); _testGetSet->_expectedAlternateScrollEnabled = true; _testGetSet->_privateEnableAlternateScrollResult = TRUE; VERIFY_IS_TRUE(_pDispatch.get()->EnableAlternateScroll(true)); _testGetSet->_expectedAlternateScrollEnabled = false; VERIFY_IS_TRUE(_pDispatch.get()->EnableAlternateScroll(false)); } TEST_METHOD(Xterm256ColorTest) { Log::Comment(L"Starting test..."); _testGetSet->PrepData(); // default color from here is gray on black, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED VTParameter rgOptions[16]; size_t cOptions = 3; _testGetSet->_privateGetColorTableEntryResult = true; _testGetSet->_expectedAttribute = _testGetSet->_attribute; Log::Comment(L"Test 1: Change Foreground"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::BlinkOrXterm256Index; rgOptions[2] = (DispatchTypes::GraphicsOptions)2; // Green _testGetSet->_expectedAttribute.SetIndexedForeground256((BYTE)::XtermToWindowsIndex(2)); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Test 2: Change Background"); rgOptions[0] = DispatchTypes::GraphicsOptions::BackgroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::BlinkOrXterm256Index; rgOptions[2] = (DispatchTypes::GraphicsOptions)9; // Bright Red _testGetSet->_expectedAttribute.SetIndexedBackground256((BYTE)::XtermToWindowsIndex(9)); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Test 3: Change Foreground to RGB color"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::BlinkOrXterm256Index; rgOptions[2] = (DispatchTypes::GraphicsOptions)42; // Arbitrary Color _testGetSet->_expectedAttribute.SetIndexedForeground256(42); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Test 4: Change Background to RGB color"); rgOptions[0] = DispatchTypes::GraphicsOptions::BackgroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::BlinkOrXterm256Index; rgOptions[2] = (DispatchTypes::GraphicsOptions)142; // Arbitrary Color _testGetSet->_expectedAttribute.SetIndexedBackground256(142); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); Log::Comment(L"Test 5: Change Foreground to Legacy Attr while BG is RGB color"); // Unfortunately this test isn't all that good, because the adapterTest adapter isn't smart enough // to have its own color table and translate the pre-existing RGB BG into a legacy BG. // Fortunately, the ft_api:RgbColorTests IS smart enough to test that. rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::BlinkOrXterm256Index; rgOptions[2] = (DispatchTypes::GraphicsOptions)9; // Bright Red _testGetSet->_expectedAttribute.SetIndexedForeground256((BYTE)::XtermToWindowsIndex(9)); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, cOptions })); } TEST_METHOD(XtermExtendedColorDefaultParameterTest) { Log::Comment(L"Starting test..."); _testGetSet->PrepData(); // default color from here is gray on black, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED VTParameter rgOptions[16]; _testGetSet->_privateGetColorTableEntryResult = true; _testGetSet->_expectedAttribute = _testGetSet->_attribute; Log::Comment(L"Test 1: Change Indexed Foreground with missing index parameter"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::BlinkOrXterm256Index; _testGetSet->_expectedAttribute.SetIndexedForeground256(0); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, 2 })); Log::Comment(L"Test 2: Change Indexed Background with default index parameter"); rgOptions[0] = DispatchTypes::GraphicsOptions::BackgroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::BlinkOrXterm256Index; rgOptions[2] = {}; _testGetSet->_expectedAttribute.SetIndexedBackground256(0); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, 3 })); Log::Comment(L"Test 3: Change RGB Foreground with all RGB parameters missing"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::RGBColorOrFaint; _testGetSet->_expectedAttribute.SetForeground(RGB(0, 0, 0)); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, 2 })); Log::Comment(L"Test 4: Change RGB Background with some missing RGB parameters"); rgOptions[0] = DispatchTypes::GraphicsOptions::BackgroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::RGBColorOrFaint; rgOptions[2] = 123; _testGetSet->_expectedAttribute.SetBackground(RGB(123, 0, 0)); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, 3 })); Log::Comment(L"Test 5: Change RGB Foreground with some default RGB parameters"); rgOptions[0] = DispatchTypes::GraphicsOptions::ForegroundExtended; rgOptions[1] = DispatchTypes::GraphicsOptions::RGBColorOrFaint; rgOptions[2] = {}; rgOptions[3] = {}; rgOptions[4] = 123; _testGetSet->_expectedAttribute.SetForeground(RGB(0, 0, 123)); VERIFY_IS_TRUE(_pDispatch.get()->SetGraphicsRendition({ rgOptions, 5 })); } TEST_METHOD(SetColorTableValue) { _testGetSet->PrepData(); _testGetSet->_privateSetColorTableEntryResult = true; const auto testColor = RGB(1, 2, 3); _testGetSet->_expectedColorValue = testColor; for (size_t i = 0; i < 256; i++) { _testGetSet->_expectedColorTableIndex = i; VERIFY_IS_TRUE(_pDispatch.get()->SetColorTableEntry(i, testColor)); } // Test in pty mode - we should fail, but PrivateSetColorTableEntry should still be called _testGetSet->_isPty = true; _testGetSet->_expectedColorTableIndex = 15; // Windows BRIGHT_WHITE VERIFY_IS_FALSE(_pDispatch.get()->SetColorTableEntry(15, testColor)); } TEST_METHOD(SoftFontSizeDetection) { using CellMatrix = DispatchTypes::DrcsCellMatrix; using FontSet = DispatchTypes::DrcsFontSet; using FontUsage = DispatchTypes::DrcsFontUsage; const auto decdld = [=](const auto cmw, const auto cmh, const auto ss, const auto u, const std::wstring_view data = {}) { const auto ec = DispatchTypes::DrcsEraseControl::AllChars; const auto css = DispatchTypes::DrcsCharsetSize::Size94; const auto cellMatrix = static_cast<DispatchTypes::DrcsCellMatrix>(cmw); const auto stringHandler = _pDispatch.get()->DownloadDRCS(0, 0, ec, cellMatrix, ss, u, cmh, css); if (stringHandler) { stringHandler(L'B'); // Charset identifier for (auto ch : data) { stringHandler(ch); } stringHandler(L'\033'); // String terminator } return stringHandler != nullptr; }; // Matrix sizes at 80x24 should always use a 10x10 cell size (VT2xx). Log::Comment(L"Matrix 5x10 for 80x24 font set with text usage"); _testGetSet->_expectedCellSize = { 10, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size5x10, 0, FontSet::Size80x24, FontUsage::Text)); Log::Comment(L"Matrix 6x10 for 80x24 font set with text usage"); _testGetSet->_expectedCellSize = { 10, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size6x10, 0, FontSet::Size80x24, FontUsage::Text)); Log::Comment(L"Matrix 7x10 for 80x24 font set with text usage"); _testGetSet->_expectedCellSize = { 10, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size7x10, 0, FontSet::Size80x24, FontUsage::Text)); // At 132x24 the cell size is typically 6x10 (VT240), but could be 10x10 (VT220) Log::Comment(L"Matrix 5x10 for 132x24 font set with text usage"); _testGetSet->_expectedCellSize = { 6, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size5x10, 0, FontSet::Size132x24, FontUsage::Text)); Log::Comment(L"Matrix 6x10 for 132x24 font set with text usage"); _testGetSet->_expectedCellSize = { 6, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size6x10, 0, FontSet::Size132x24, FontUsage::Text)); Log::Comment(L"Matrix 7x10 for 132x24 font set with text usage (VT220 only)"); _testGetSet->_expectedCellSize = { 10, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size7x10, 0, FontSet::Size132x24, FontUsage::Text)); // Full cell usage is invalid for all matrix sizes except 6x10 at 132x24. Log::Comment(L"Matrix 5x10 for 80x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Size5x10, 0, FontSet::Size80x24, FontUsage::FullCell)); Log::Comment(L"Matrix 6x10 for 80x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Size6x10, 0, FontSet::Size80x24, FontUsage::FullCell)); Log::Comment(L"Matrix 7x10 for 80x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Size7x10, 0, FontSet::Size80x24, FontUsage::FullCell)); Log::Comment(L"Matrix 5x10 for 132x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Size5x10, 0, FontSet::Size132x24, FontUsage::FullCell)); Log::Comment(L"Matrix 6x10 for 132x24 font set with full cell usage"); _testGetSet->_expectedCellSize = { 6, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size6x10, 0, FontSet::Size132x24, FontUsage::FullCell)); Log::Comment(L"Matrix 7x10 for 132x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Size7x10, 0, FontSet::Size132x24, FontUsage::FullCell)); // Matrix size 1 is always invalid. Log::Comment(L"Matrix 1 for 80x24 font set with text usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Invalid, 0, FontSet::Size80x24, FontUsage::Text)); Log::Comment(L"Matrix 1 for 132x24 font set with text usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Invalid, 0, FontSet::Size132x24, FontUsage::Text)); Log::Comment(L"Matrix 1 for 80x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Invalid, 0, FontSet::Size80x24, FontUsage::FullCell)); Log::Comment(L"Matrix 1 for 132x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(CellMatrix::Invalid, 0, FontSet::Size132x24, FontUsage::FullCell)); // The height parameter has no effect when a matrix size is used. Log::Comment(L"Matrix 7x10 with unused height parameter"); _testGetSet->_expectedCellSize = { 10, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Size7x10, 20, FontSet::Size80x24, FontUsage::Text)); // Full cell fonts with explicit dimensions are accepted as their given cell size. Log::Comment(L"Explicit 13x17 for 80x24 font set with full cell usage"); _testGetSet->_expectedCellSize = { 13, 17 }; VERIFY_IS_TRUE(decdld(13, 17, FontSet::Size80x24, FontUsage::FullCell)); Log::Comment(L"Explicit 9x25 for 132x24 font set with full cell usage"); _testGetSet->_expectedCellSize = { 9, 25 }; VERIFY_IS_TRUE(decdld(9, 25, FontSet::Size132x24, FontUsage::FullCell)); // Cell sizes outside the maximum supported range (16x32) are invalid. Log::Comment(L"Explicit 18x38 for 80x24 font set with full cell usage (invalid)"); VERIFY_IS_FALSE(decdld(18, 38, FontSet::Size80x24, FontUsage::FullCell)); // Text fonts with explicit dimensions are interpreted as their closest matching device. Log::Comment(L"Explicit 12x12 for 80x24 font set with text usage (VT320)"); _testGetSet->_expectedCellSize = { 15, 12 }; VERIFY_IS_TRUE(decdld(12, 12, FontSet::Size80x24, FontUsage::Text)); Log::Comment(L"Explicit 9x20 for 80x24 font set with text usage (VT340)"); _testGetSet->_expectedCellSize = { 10, 20 }; VERIFY_IS_TRUE(decdld(9, 20, FontSet::Size80x24, FontUsage::Text)); Log::Comment(L"Explicit 10x30 for 80x24 font set with text usage (VT382)"); _testGetSet->_expectedCellSize = { 12, 30 }; VERIFY_IS_TRUE(decdld(10, 30, FontSet::Size80x24, FontUsage::Text)); Log::Comment(L"Explicit 8x16 for 80x24 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 10, 16 }; VERIFY_IS_TRUE(decdld(8, 16, FontSet::Size80x24, FontUsage::Text)); Log::Comment(L"Explicit 7x12 for 132x24 font set with text usage (VT320)"); _testGetSet->_expectedCellSize = { 9, 12 }; VERIFY_IS_TRUE(decdld(7, 12, FontSet::Size132x24, FontUsage::Text)); Log::Comment(L"Explicit 5x20 for 132x24 font set with text usage (VT340)"); _testGetSet->_expectedCellSize = { 6, 20 }; VERIFY_IS_TRUE(decdld(5, 20, FontSet::Size132x24, FontUsage::Text)); Log::Comment(L"Explicit 6x30 for 132x24 font set with text usage (VT382)"); _testGetSet->_expectedCellSize = { 7, 30 }; VERIFY_IS_TRUE(decdld(6, 30, FontSet::Size132x24, FontUsage::Text)); Log::Comment(L"Explicit 5x16 for 132x24 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 6, 16 }; VERIFY_IS_TRUE(decdld(5, 16, FontSet::Size132x24, FontUsage::Text)); // Font sets with more than 24 lines must be VT420/VT5xx. Log::Comment(L"80x36 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 10, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x36, FontUsage::Text)); Log::Comment(L"80x48 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 10, 8 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x48, FontUsage::Text)); Log::Comment(L"132x36 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 6, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x36, FontUsage::Text)); Log::Comment(L"132x48 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 6, 8 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x48, FontUsage::Text)); Log::Comment(L"80x36 font set with full cell usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 10, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x36, FontUsage::FullCell)); Log::Comment(L"80x48 font set with full cell usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 10, 8 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x48, FontUsage::FullCell)); Log::Comment(L"132x36 font set with full cell usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 6, 10 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x36, FontUsage::FullCell)); Log::Comment(L"132x48 font set with full cell usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 6, 8 }; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x48, FontUsage::FullCell)); // Without an explicit size, the cell size is estimated from the number of sixels // used in the character bitmaps. But note that sixel heights are always a multiple // of 6, so will often be larger than the cell size for which they were intended. Log::Comment(L"8x12 bitmap for 80x24 font set with text usage (VT2xx)"); _testGetSet->_expectedCellSize = { 10, 10 }; const auto bitmapOf8x12 = L"????????/????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::Text, bitmapOf8x12)); Log::Comment(L"12x12 bitmap for 80x24 font set with text usage (VT320)"); _testGetSet->_expectedCellSize = { 15, 12 }; const auto bitmapOf12x12 = L"????????????/????????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::Text, bitmapOf12x12)); Log::Comment(L"9x24 bitmap for 80x24 font set with text usage (VT340)"); _testGetSet->_expectedCellSize = { 10, 20 }; const auto bitmapOf9x24 = L"?????????/?????????/?????????/?????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::Text, bitmapOf9x24)); Log::Comment(L"10x30 bitmap for 80x24 font set with text usage (VT382)"); _testGetSet->_expectedCellSize = { 12, 30 }; const auto bitmapOf10x30 = L"??????????/??????????/??????????/??????????/??????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::Text, bitmapOf10x30)); Log::Comment(L"8x18 bitmap for 80x24 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 10, 16 }; const auto bitmapOf8x18 = L"????????/????????/????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::Text, bitmapOf8x18)); Log::Comment(L"5x12 bitmap for 132x24 font set with text usage (VT240)"); _testGetSet->_expectedCellSize = { 6, 10 }; const auto bitmapOf5x12 = L"?????/?????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::Text, bitmapOf5x12)); Log::Comment(L"7x12 bitmap for 132x24 font set with text usage (VT320)"); _testGetSet->_expectedCellSize = { 9, 12 }; const auto bitmapOf7x12 = L"???????/???????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::Text, bitmapOf7x12)); Log::Comment(L"5x24 bitmap for 132x24 font set with text usage (VT340)"); _testGetSet->_expectedCellSize = { 6, 20 }; const auto bitmapOf5x24 = L"?????/?????/?????/?????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::Text, bitmapOf5x24)); Log::Comment(L"6x30 bitmap for 132x24 font set with text usage (VT382)"); _testGetSet->_expectedCellSize = { 7, 30 }; const auto bitmapOf6x30 = L"??????/??????/??????/??????/??????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::Text, bitmapOf6x30)); Log::Comment(L"5x18 bitmap for 132x24 font set with text usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 6, 16 }; const auto bitmapOf5x18 = L"?????/?????/?????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::Text, bitmapOf5x18)); Log::Comment(L"15x12 bitmap for 80x24 font set with full cell usage (VT320)"); _testGetSet->_expectedCellSize = { 15, 12 }; const auto bitmapOf15x12 = L"???????????????/???????????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::FullCell, bitmapOf15x12)); Log::Comment(L"10x24 bitmap for 80x24 font set with full cell usage (VT340)"); _testGetSet->_expectedCellSize = { 10, 20 }; const auto bitmapOf10x24 = L"??????????/??????????/??????????/??????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::FullCell, bitmapOf10x24)); Log::Comment(L"12x30 bitmap for 80x24 font set with full cell usage (VT382)"); _testGetSet->_expectedCellSize = { 12, 30 }; const auto bitmapOf12x30 = L"????????????/????????????/????????????/????????????/????????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::FullCell, bitmapOf12x30)); Log::Comment(L"10x18 bitmap for 80x24 font set with full cell usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 10, 16 }; const auto bitmapOf10x18 = L"??????????/??????????/??????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size80x24, FontUsage::FullCell, bitmapOf10x18)); Log::Comment(L"6x12 bitmap for 132x24 font set with full cell usage (VT240)"); _testGetSet->_expectedCellSize = { 6, 10 }; const auto bitmapOf6x12 = L"??????/??????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::FullCell, bitmapOf6x12)); Log::Comment(L"9x12 bitmap for 132x24 font set with full cell usage (VT320)"); _testGetSet->_expectedCellSize = { 9, 12 }; const auto bitmapOf9x12 = L"?????????/?????????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::FullCell, bitmapOf9x12)); Log::Comment(L"6x24 bitmap for 132x24 font set with full cell usage (VT340)"); _testGetSet->_expectedCellSize = { 6, 20 }; const auto bitmapOf6x24 = L"??????/??????/??????/??????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::FullCell, bitmapOf6x24)); Log::Comment(L"7x30 bitmap for 132x24 font set with full cell usage (VT382)"); _testGetSet->_expectedCellSize = { 7, 30 }; const auto bitmapOf7x30 = L"???????/???????/???????/???????/???????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::FullCell, bitmapOf7x30)); Log::Comment(L"6x18 bitmap for 132x24 font set with full cell usage (VT420/VT5xx)"); _testGetSet->_expectedCellSize = { 6, 16 }; const auto bitmapOf6x18 = L"??????/??????/??????"; VERIFY_IS_TRUE(decdld(CellMatrix::Default, 0, FontSet::Size132x24, FontUsage::FullCell, bitmapOf6x18)); } private: TestGetSet* _testGetSet; // non-ownership pointer std::unique_ptr<AdaptDispatch> _pDispatch; };
118,963
37,484
/******************************************************************************* * Copyright 2014-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "mpi_transceiver.h" #include <mpi.h> #include <Python.h> void mpi_transceiver::init() { int is_mpi_initialized = 0; MPI_Initialized(&is_mpi_initialized); // protect against double-init if(!is_mpi_initialized) { MPI_Init(NULL, NULL); } transceiver_impl::init(); } void mpi_transceiver::fini() { MPI_Finalize(); } size_t mpi_transceiver::nMembers() { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); return size; } size_t mpi_transceiver::me() { int me; MPI_Comm_rank(MPI_COMM_WORLD, &me); return me; } void mpi_transceiver::send(const void* buff, size_t N, size_t recpnt, size_t tag) { MPI_Send(buff, (int)N, MPI_CHAR, recpnt, tag, MPI_COMM_WORLD); } size_t mpi_transceiver::recv(void * buff, size_t N, int sender, int tag) { MPI_Status s; MPI_Recv(buff, N, MPI_CHAR, sender, tag, MPI_COMM_WORLD, &s); int count; MPI_Get_count(&s, MPI_CHAR, &count); return count; } void * mpi_transceiver::gather(const void * ptr, size_t N, size_t root, const size_t * sizes, bool varying) { char * buff = NULL; if(varying) { // -> gatherv if(m_me == root) { int * offsets = new int[m_nMembers]; int tot_sz = sizes[0]; offsets[0] = 0; for(int i = 1; i < m_nMembers; ++i) { offsets[i] = offsets[i-1] + sizes[i-1]; tot_sz += sizes[i]; } buff = new char[tot_sz]; int * szs = new int[m_nMembers]; for(size_t i=0; i<m_nMembers; ++i) szs[i] = static_cast<int>(sizes[i]); MPI_Gatherv(ptr, N, MPI_CHAR, buff, szs, offsets, MPI_CHAR, root, MPI_COMM_WORLD); delete [] szs; delete [] offsets; } else { MPI_Gatherv(ptr, N, MPI_CHAR, NULL, NULL, NULL, MPI_CHAR, root, MPI_COMM_WORLD); } } else { if(m_me == root) buff = new char[m_nMembers*N]; // -> gather with same size on all procs MPI_Gather(ptr, N, MPI_CHAR, buff, N, MPI_CHAR, root, MPI_COMM_WORLD); } return buff; } static MPI_Datatype to_mpi(transceiver_iface::type_type T) { switch(T) { case transceiver_iface::BOOL: return MPI_C_BOOL; case transceiver_iface::INT8: return MPI_INT8_T; case transceiver_iface::UINT8: return MPI_UINT8_T; case transceiver_iface::INT32: return MPI_INT32_T; case transceiver_iface::UINT32: return MPI_INT32_T; case transceiver_iface::INT64: return MPI_INT64_T; case transceiver_iface::UINT64: return MPI_INT64_T; case transceiver_iface::FLOAT: return MPI_FLOAT; case transceiver_iface::DOUBLE: return MPI_DOUBLE; default: throw std::logic_error("unsupported data type"); } } static MPI_Op to_mpi(transceiver_iface::operation_type o) { switch(o) { case transceiver_iface::OP_MAX: return MPI_MAX; case transceiver_iface::OP_MIN: return MPI_MIN; case transceiver_iface::OP_SUM: return MPI_SUM; case transceiver_iface::OP_PROD: return MPI_PROD; case transceiver_iface::OP_LAND: return MPI_LAND; case transceiver_iface::OP_BAND: return MPI_BAND; case transceiver_iface::OP_LOR: return MPI_LOR; case transceiver_iface::OP_BOR: return MPI_BOR; case transceiver_iface::OP_LXOR: return MPI_LXOR; case transceiver_iface::OP_BXOR: return MPI_BXOR; default: throw std::logic_error("unsupported operation type"); } } void mpi_transceiver::bcast(void * ptr, size_t N, size_t root) { MPI_Bcast(ptr, N, MPI_CHAR, root, MPI_COMM_WORLD); } void mpi_transceiver::reduce_all(void * inout, transceiver_iface::type_type T, size_t N, transceiver_iface::operation_type op) { MPI_Allreduce(MPI_IN_PLACE, inout, N, to_mpi(T), to_mpi(op), MPI_COMM_WORLD); } void mpi_transceiver::reduce_exscan(void * inout, transceiver_iface::type_type T, size_t N, transceiver_iface::operation_type op) { MPI_Exscan(MPI_IN_PLACE, inout, N, to_mpi(T), to_mpi(op), MPI_COMM_WORLD); } // ************************************ // ************************************ // shared pointer, will GC transceiver when shutting down static std::shared_ptr<mpi_transceiver> s_smt; extern "C" PyMODINIT_FUNC PyInit_mpi_transceiver(void) { PyObject *m; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "mpi_transceiver", "No docs", -1, NULL, }; m = PyModule_Create(&moduledef); if (m == NULL) return NULL; s_smt.reset(new mpi_transceiver); PyObject_SetAttrString(m, "transceiver", PyLong_FromVoidPtr((void*)(&s_smt))); return m; }
5,417
2,057
//snippet-sourcedescription:[list_receipt_filters.cpp demonstrates how to list the Amazon SES IP filters for an AWS account.] //snippet-service:[ses] //snippet-keyword:[Amazon Simple Email Service] //snippet-keyword:[C++] //snippet-keyword:[Code Sample] //snippet-sourcetype:[full-example] //snippet-sourceauthor:[AWS] /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is 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/ This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <aws/core/Aws.h> #include <aws/email/SESClient.h> #include <aws/email/model/ListReceiptFiltersRequest.h> #include <aws/email/model/ListReceiptFiltersResult.h> #include <aws/email/model/ReceiptFilterPolicy.h> #include <iostream> int main(int argc, char **argv) { Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SES::SESClient ses; Aws::SES::Model::ListReceiptFiltersRequest lrf_req; auto lrf_out = ses.ListReceiptFilters(lrf_req); if (!lrf_out.IsSuccess()) { std::cout << "Error retrieving IP address filters: " << lrf_out.GetError().GetMessage() << std::endl; } else { // Output filter details std::cout << "Amazon Simple Email Service\n"; std::cout << "Email Receiving: IP Address Filters:\n\n"; auto filters = lrf_out.GetResult().GetFilters(); if (filters.empty()) { std::cout << "No filters defined" << std::endl; } else { for (auto filter : filters) { std::cout << "Name: " << filter.GetName() << "\n"; std::cout << " Policy: "; auto ip_filter = filter.GetIpFilter(); switch (ip_filter.GetPolicy()) { case Aws::SES::Model::ReceiptFilterPolicy::Block: std::cout << "Block\n"; break; case Aws::SES::Model::ReceiptFilterPolicy::Allow: std::cout << "Allow\n"; break; default: std::cout << "NOT SET\n"; break; } std::cout << " CIDR: " << ip_filter.GetCidr() << std::endl; } } } } Aws::ShutdownAPI(options); return 0; }
2,939
885
#include <common.h> #pragma hdrstop #include <OpenGlRenderMechanism.h> #include <GlContextManager.h> #include <GlWindowUtils.h> #include <DrawEnums.h> #include <State.h> #include <Framebuffer.h> namespace Gin { ////////////////////////////////////////////////////////////////////////// COpenGlRenderMechanism::COpenGlRenderMechanism( CGlContextManager& _glContextManager ) : glContextManager( _glContextManager ) { backgroundBrush = ::CreateSolidBrush( RGB( 0, 0, 0 ) ); } COpenGlRenderMechanism::~COpenGlRenderMechanism() { ::DeleteObject( backgroundBrush ); } void COpenGlRenderMechanism::AttachNewWindow( const CGlWindow& newWindow ) { assert( newWindow.IsCreated() ); targetWindow = &newWindow; OnWindowResize( newWindow.WindowSize() ); } void COpenGlRenderMechanism::ActivateWindowTarget() { glContextManager.SetContextTarget( targetWindow->GetDeviceContext() ); } void COpenGlRenderMechanism::SetBackgroundColor( CColor newValue ) { backgroundColor = newValue; ::DeleteObject( backgroundBrush ); backgroundBrush = ::CreateSolidBrush( RGB( newValue.R, newValue.G, newValue.B ) ); } void COpenGlRenderMechanism::OnWindowResize( CVector2<int> ) { } LRESULT COpenGlRenderMechanism::OnEraseBackground( HWND, WPARAM wParam, LPARAM ) { RECT bgRect{ INT_MIN, INT_MIN, INT_MAX, INT_MAX }; HDC bgDC = reinterpret_cast<HDC>( wParam ); ::FillRect( bgDC, &bgRect, backgroundBrush ); return 1; } void COpenGlRenderMechanism::OnDraw( const IState& currentState ) const { const auto windowSize = targetWindow->WindowSize(); CViewportSwitcher::SetBaseViewport( CVector2<int>{}, windowSize ); // Set the clear values. gl::ClearColor( backgroundColor.GetRed(), backgroundColor.GetGreen(), backgroundColor.GetBlue(), backgroundColor.GetAlpha() ); gl::ClearDepth( glContextManager.GetDepthZFar() ); gl::Enable( gl::DEPTH_TEST ); gl::Disable( gl::BLEND ); // Clear the buffer. gl::Clear( gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT ); currentState.Draw( COpenGlRenderParameters( *targetWindow ) ); } void COpenGlRenderMechanism::OnPostDraw() const { ::SwapBuffers( targetWindow->GetDeviceContext() ); } LRESULT COpenGlRenderMechanism::OnPaintMessage( HWND window, WPARAM wParam, LPARAM lParam, const IState& ) const { return ::DefWindowProc( window, WM_PAINT, wParam, lParam ); } CArray<BYTE> COpenGlRenderMechanism::ReadScreenBuffer( TTexelFormat format, CVector2<int>& bufferSize ) const { assert( CFramebufferSwitcher::GetReadTarget() == 0 ); const auto viewportSize = CViewportSwitcher::GetViewportSize(); const int rowSize = CeilTo( 3 * viewportSize.X(), 4 ); const int dataSize = rowSize * viewportSize.Y(); CArray<BYTE> data; data.IncreaseSizeNoInitialize( dataSize ); gl::PixelStorei( AT_Pack, 4 ); gl::ReadPixels( 0, 0, viewportSize.X(), viewportSize.Y(), format, TDT_UnsignedByte, data.Ptr() ); gl::PixelStorei( AT_Pack, 1 ); bufferSize = viewportSize; return data; } ////////////////////////////////////////////////////////////////////////// } // namespace Gin.
3,145
1,128
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE #include <CoreLib/LogSystem/EntityLogger.hpp> namespace bw { inline EntityLogger::EntityLogger(Ndk::EntityHandle entity, const Logger& logParent) : LoggerProxy(logParent), m_entity(std::move(entity)) { } inline void EntityLogger::UpdateEntity(Ndk::EntityHandle newEntity) { m_entity = newEntity; } }
472
162
//===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the MIPS implementation of the TargetRegisterInfo class. // //===----------------------------------------------------------------------===// #include "MipsRegisterInfo.h" #include "Mips.h" #include "MipsAnalyzeImmediate.h" #include "MipsInstrInfo.h" #include "MipsMachineFunction.h" #include "MipsSubtarget.h" #include "MipsTargetMachine.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/STLExtras.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/Function.h" #include "llvm/IR/Type.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; #define DEBUG_TYPE "mips-reg-info" #define GET_REGINFO_TARGET_DESC #include "MipsGenRegisterInfo.inc" MipsRegisterInfo::MipsRegisterInfo() : MipsGenRegisterInfo(Mips::RA) {} unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; } const TargetRegisterClass * MipsRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind) const { MipsABIInfo ABI = MF.getSubtarget<MipsSubtarget>().getABI(); return ABI.ArePtrs64bit() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; } unsigned MipsRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC, MachineFunction &MF) const { switch (RC->getID()) { default: return 0; case Mips::GPR32RegClassID: case Mips::GPR64RegClassID: case Mips::DSPRRegClassID: { const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); return 28 - TFI->hasFP(MF); } case Mips::FGR32RegClassID: return 32; case Mips::AFGR64RegClassID: return 16; case Mips::FGR64RegClassID: return 32; } } //===----------------------------------------------------------------------===// // Callee Saved Registers methods //===----------------------------------------------------------------------===// /// Mips Callee Saved Registers const MCPhysReg * MipsRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { const MipsSubtarget &Subtarget = MF->getSubtarget<MipsSubtarget>(); if (Subtarget.isSingleFloat()) return CSR_SingleFloatOnly_SaveList; if (Subtarget.isABI_N64()) return CSR_N64_SaveList; if (Subtarget.isABI_N32()) return CSR_N32_SaveList; if (Subtarget.isFP64bit()) return CSR_O32_FP64_SaveList; if (Subtarget.isFPXX()) return CSR_O32_FPXX_SaveList; return CSR_O32_SaveList; } const uint32_t * MipsRegisterInfo::getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const { const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>(); if (Subtarget.isSingleFloat()) return CSR_SingleFloatOnly_RegMask; if (Subtarget.isABI_N64()) return CSR_N64_RegMask; if (Subtarget.isABI_N32()) return CSR_N32_RegMask; if (Subtarget.isFP64bit()) return CSR_O32_FP64_RegMask; if (Subtarget.isFPXX()) return CSR_O32_FPXX_RegMask; return CSR_O32_RegMask; } const uint32_t *MipsRegisterInfo::getMips16RetHelperMask() { return CSR_Mips16RetHelper_RegMask; } BitVector MipsRegisterInfo:: getReservedRegs(const MachineFunction &MF) const { static const MCPhysReg ReservedGPR32[] = { Mips::ZERO, Mips::K0, Mips::K1, Mips::SP }; static const MCPhysReg ReservedGPR64[] = { Mips::ZERO_64, Mips::K0_64, Mips::K1_64, Mips::SP_64 }; BitVector Reserved(getNumRegs()); const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>(); typedef TargetRegisterClass::const_iterator RegIter; for (unsigned I = 0; I < array_lengthof(ReservedGPR32); ++I) Reserved.set(ReservedGPR32[I]); // Reserve registers for the NaCl sandbox. if (Subtarget.isTargetNaCl()) { Reserved.set(Mips::T6); // Reserved for control flow mask. Reserved.set(Mips::T7); // Reserved for memory access mask. Reserved.set(Mips::T8); // Reserved for thread pointer. } for (unsigned I = 0; I < array_lengthof(ReservedGPR64); ++I) Reserved.set(ReservedGPR64[I]); // For mno-abicalls, GP is a program invariant! if (!Subtarget.isABICalls()) { Reserved.set(Mips::GP); Reserved.set(Mips::GP_64); } if (Subtarget.isFP64bit()) { // Reserve all registers in AFGR64. for (RegIter Reg = Mips::AFGR64RegClass.begin(), EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg) Reserved.set(*Reg); } else { // Reserve all registers in FGR64. for (RegIter Reg = Mips::FGR64RegClass.begin(), EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg) Reserved.set(*Reg); } // Reserve FP if this function should have a dedicated frame pointer register. if (Subtarget.getFrameLowering()->hasFP(MF)) { if (Subtarget.inMips16Mode()) Reserved.set(Mips::S0); else { Reserved.set(Mips::FP); Reserved.set(Mips::FP_64); // Reserve the base register if we need to both realign the stack and // allocate variable-sized objects at runtime. This should test the // same conditions as MipsFrameLowering::hasBP(). if (needsStackRealignment(MF) && MF.getFrameInfo()->hasVarSizedObjects()) { Reserved.set(Mips::S7); Reserved.set(Mips::S7_64); } } } // Reserve hardware registers. Reserved.set(Mips::HWR29); // Reserve DSP control register. Reserved.set(Mips::DSPPos); Reserved.set(Mips::DSPSCount); Reserved.set(Mips::DSPCarry); Reserved.set(Mips::DSPEFI); Reserved.set(Mips::DSPOutFlag); // Reserve MSA control registers. Reserved.set(Mips::MSAIR); Reserved.set(Mips::MSACSR); Reserved.set(Mips::MSAAccess); Reserved.set(Mips::MSASave); Reserved.set(Mips::MSAModify); Reserved.set(Mips::MSARequest); Reserved.set(Mips::MSAMap); Reserved.set(Mips::MSAUnmap); // Reserve RA if in mips16 mode. if (Subtarget.inMips16Mode()) { const MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); Reserved.set(Mips::RA); Reserved.set(Mips::RA_64); Reserved.set(Mips::T0); Reserved.set(Mips::T1); if (MF.getFunction()->hasFnAttribute("saveS2") || MipsFI->hasSaveS2()) Reserved.set(Mips::S2); } // Reserve GP if small section is used. if (Subtarget.useSmallSection()) { Reserved.set(Mips::GP); Reserved.set(Mips::GP_64); } if (Subtarget.isABI_O32() && !Subtarget.useOddSPReg()) { for (const auto &Reg : Mips::OddSPRegClass) Reserved.set(Reg); } return Reserved; } bool MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const { return true; } bool MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const { return true; } // FrameIndex represent objects inside a abstract stack. // We must replace FrameIndex with an stack/frame pointer // direct reference. void MipsRegisterInfo:: eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { MachineInstr &MI = *II; MachineFunction &MF = *MI.getParent()->getParent(); DEBUG(errs() << "\nFunction : " << MF.getName() << "\n"; errs() << "<--------->\n" << MI); int FrameIndex = MI.getOperand(FIOperandNum).getIndex(); uint64_t stackSize = MF.getFrameInfo()->getStackSize(); int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex); DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n" << "spOffset : " << spOffset << "\n" << "stackSize : " << stackSize << "\n"); eliminateFI(MI, FIOperandNum, FrameIndex, stackSize, spOffset); } unsigned MipsRegisterInfo:: getFrameRegister(const MachineFunction &MF) const { const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>(); const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); bool IsN64 = static_cast<const MipsTargetMachine &>(MF.getTarget()).getABI().IsN64(); if (Subtarget.inMips16Mode()) return TFI->hasFP(MF) ? Mips::S0 : Mips::SP; else return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) : (IsN64 ? Mips::SP_64 : Mips::SP); } bool MipsRegisterInfo::canRealignStack(const MachineFunction &MF) const { const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>(); unsigned FP = Subtarget.isGP32bit() ? Mips::FP : Mips::FP_64; unsigned BP = Subtarget.isGP32bit() ? Mips::S7 : Mips::S7_64; // Support dynamic stack realignment only for targets with standard encoding. if (!Subtarget.hasStandardEncoding()) return false; // We can't perform dynamic stack realignment if we can't reserve the // frame pointer register. if (!MF.getRegInfo().canReserveReg(FP)) return false; // We can realign the stack if we know the maximum call frame size and we // don't have variable sized objects. if (Subtarget.getFrameLowering()->hasReservedCallFrame(MF)) return true; // We have to reserve the base pointer register in the presence of variable // sized objects. return MF.getRegInfo().canReserveReg(BP); } bool MipsRegisterInfo::needsStackRealignment(const MachineFunction &MF) const { const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>(); const MachineFrameInfo *MFI = MF.getFrameInfo(); bool CanRealign = canRealignStack(MF); // Avoid realigning functions that explicitly do not want to be realigned. // Normally, we should report an error when a function should be dynamically // realigned but also has the attribute no-realign-stack. Unfortunately, // with this attribute, MachineFrameInfo clamps each new object's alignment // to that of the stack's alignment as specified by the ABI. As a result, // the information of whether we have objects with larger alignment // requirement than the stack's alignment is already lost at this point. if (MF.getFunction()->hasFnAttribute("no-realign-stack")) return false; const Function *F = MF.getFunction(); if (F->hasFnAttribute(Attribute::StackAlignment)) { #ifdef DEBUG if (!CanRealign) DEBUG(dbgs() << "It's not possible to realign the stack of the function: " << F->getName() << "\n"); #endif return CanRealign; } unsigned StackAlignment = Subtarget.getFrameLowering()->getStackAlignment(); if (MFI->getMaxAlignment() > StackAlignment) { #ifdef DEBUG if (!CanRealign) DEBUG(dbgs() << "It's not possible to realign the stack of the function: " << F->getName() << "\n"); #endif return CanRealign; } return false; }
11,230
3,930
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "BehaviorTreeEditorPrivatePCH.h" #include "BehaviorTreeEditorCommands.h" #define LOCTEXT_NAMESPACE "BehaviorTreeEditorCommands" FBTCommonCommands::FBTCommonCommands() : TCommands<FBTCommonCommands>("BTEditor.Common", LOCTEXT("Common", "Common"), NAME_None, FEditorStyle::GetStyleSetName()) { } void FBTCommonCommands::RegisterCommands() { UI_COMMAND(SearchBT, "Search", "Search this Behavior Tree.", EUserInterfaceActionType::Button, FInputChord(EModifierKey::Control, EKeys::F)); UI_COMMAND(NewBlackboard, "New Blackboard", "Create a new Blackboard Data Asset", EUserInterfaceActionType::Button, FInputChord()); } FBTDebuggerCommands::FBTDebuggerCommands() : TCommands<FBTDebuggerCommands>("BTEditor.Debugger", LOCTEXT("Debugger", "Debugger"), NAME_None, FEditorStyle::GetStyleSetName()) { } void FBTDebuggerCommands::RegisterCommands() { UI_COMMAND(BackInto, "Back: Into", "Show state from previous step, can go into subtrees", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(BackOver, "Back: Over", "Show state from previous step, don't go into subtrees", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(ForwardInto, "Forward: Into", "Show state from next step, can go into subtrees", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(ForwardOver, "Forward: Over", "Show state from next step, don't go into subtrees", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(StepOut, "Step Out", "Show state from next step, leave current subtree", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(PausePlaySession, "Pause", "Pause simulation", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(ResumePlaySession, "Resume", "Resume simulation", EUserInterfaceActionType::Button, FInputChord() ); UI_COMMAND(StopPlaySession, "Stop", "Stop simulation", EUserInterfaceActionType::Button, FInputChord()); UI_COMMAND(CurrentValues, "Current", "View current values", EUserInterfaceActionType::RadioButton, FInputChord()); UI_COMMAND(SavedValues, "Saved", "View saved values", EUserInterfaceActionType::RadioButton, FInputChord()); } FBTBlackboardCommands::FBTBlackboardCommands() : TCommands<FBTBlackboardCommands>("BTEditor.Blackboard", LOCTEXT("Blackboard", "Blackboard"), NAME_None, FEditorStyle::GetStyleSetName()) { } void FBTBlackboardCommands::RegisterCommands() { UI_COMMAND(DeleteEntry, "Delete", "Delete this blackboard entry", EUserInterfaceActionType::Button, FInputChord(EKeys::Platform_Delete)); } #undef LOCTEXT_NAMESPACE
2,598
852
#include <mscorlib/System/Security/Permissions/mscorlib_System_Security_Permissions_StrongNameIdentityPermissionAttribute.h> #include <mscorlib/System/mscorlib_System_String.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Security { namespace Permissions { //Public Methods mscorlib::System::Security::IPermission StrongNameIdentityPermissionAttribute::CreatePermission() { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "CreatePermission", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::Security::IPermission(__result__); } //Get Set Properties Methods // Get/Set:Name mscorlib::System::String StrongNameIdentityPermissionAttribute::get_Name() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "get_Name", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } void StrongNameIdentityPermissionAttribute::set_Name(mscorlib::System::String value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = (MonoObject*)value; Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "set_Name", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get/Set:PublicKey mscorlib::System::String StrongNameIdentityPermissionAttribute::get_PublicKey() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "get_PublicKey", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } void StrongNameIdentityPermissionAttribute::set_PublicKey(mscorlib::System::String value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = (MonoObject*)value; Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "set_PublicKey", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get/Set:Version mscorlib::System::String StrongNameIdentityPermissionAttribute::get_Version() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "get_Version", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } void StrongNameIdentityPermissionAttribute::set_Version(mscorlib::System::String value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = (MonoObject*)value; Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "set_Version", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get/Set:Unrestricted mscorlib::System::Boolean StrongNameIdentityPermissionAttribute::get_Unrestricted() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "get_Unrestricted", __native_object__, 0, NULL, NULL, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } void StrongNameIdentityPermissionAttribute::set_Unrestricted(mscorlib::System::Boolean value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = reinterpret_cast<void*>(value); Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "set_Unrestricted", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get/Set:Action mscorlib::System::Security::Permissions::SecurityAction::__ENUM__ StrongNameIdentityPermissionAttribute::get_Action() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "get_Action", __native_object__, 0, NULL, NULL, NULL); return static_cast<mscorlib::System::Security::Permissions::SecurityAction::__ENUM__>(*(mscorlib::System::Int32*)mono_object_unbox(__result__)); } void StrongNameIdentityPermissionAttribute::set_Action(mscorlib::System::Security::Permissions::SecurityAction::__ENUM__ value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); mscorlib::System::Int32 __param_value__ = value; __parameters__[0] = &__param_value__; Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "set_Action", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get:TypeId mscorlib::System::Object StrongNameIdentityPermissionAttribute::get_TypeId() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Attribute", 0, NULL, "get_TypeId", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::Object(__result__); } } } } }
5,634
2,073
// // Created by Sebastian on 26/11/2020. // #include "Checking_Account.h" Checking_Account::Checking_Account(std::string name, double balance, double fee) : Account{name, balance}, fee{fee} { } bool Checking_Account::withdraw(double amount) { amount += fee; return Account::withdraw(amount); } std::ostream &operator<<(std::ostream &os, const Checking_Account &account) { os << "[Checking_Account: " << account.name << " : " << account.balance << ", " << account.fee << "]"; return os; }
514
177
/* * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_RUNTIME_PERFDATA_HPP #define SHARE_VM_RUNTIME_PERFDATA_HPP #include "memory/allocation.hpp" #include "runtime/perfMemory.hpp" #include "runtime/timer.hpp" template <typename T> class GrowableArray; /* jvmstat global and subsystem counter name space - enumeration value * serve as an index into the PerfDataManager::_name_space[] array * containing the corresponding name space string. Only the top level * subsystem name spaces are represented here. */ enum CounterNS { // top level name spaces JAVA_NS, COM_NS, SUN_NS, // subsystem name spaces JAVA_GC, // Garbage Collection name spaces COM_GC, SUN_GC, JAVA_CI, // Compiler name spaces COM_CI, SUN_CI, JAVA_CLS, // Class Loader name spaces COM_CLS, SUN_CLS, JAVA_RT, // Runtime name spaces COM_RT, SUN_RT, JAVA_OS, // Operating System name spaces COM_OS, SUN_OS, JAVA_THREADS, // Threads System name spaces COM_THREADS, SUN_THREADS, JAVA_PROPERTY, // Java Property name spaces COM_PROPERTY, SUN_PROPERTY, NULL_NS, COUNTERNS_LAST = NULL_NS }; /* * Classes to support access to production performance data * * The PerfData class structure is provided for creation, access, and update * of performance data (a.k.a. instrumentation) in a specific memory region * which is possibly accessible as shared memory. Although not explicitly * prevented from doing so, developers should not use the values returned * by accessor methods to make algorithmic decisions as they are potentially * extracted from a shared memory region. Although any shared memory region * created is with appropriate access restrictions, allowing read-write access * only to the principal that created the JVM, it is believed that a the * shared memory region facilitates an easier attack path than attacks * launched through mechanisms such as /proc. For this reason, it is * recommended that data returned by PerfData accessor methods be used * cautiously. * * There are three variability classifications of performance data * Constants - value is written to the PerfData memory once, on creation * Variables - value is modifiable, with no particular restrictions * Counters - value is monotonically changing (increasing or decreasing) * * The performance data items can also have various types. The class * hierarchy and the structure of the memory region are designed to * accommodate new types as they are needed. Types are specified in * terms of Java basic types, which accommodates client applications * written in the Java programming language. The class hierarchy is: * * - PerfData (Abstract) * - PerfLong (Abstract) * - PerfLongConstant (alias: PerfConstant) * - PerfLongVariant (Abstract) * - PerfLongVariable (alias: PerfVariable) * - PerfLongCounter (alias: PerfCounter) * * - PerfByteArray (Abstract) * - PerfString (Abstract) * - PerfStringVariable * - PerfStringConstant * * * As seen in the class hierarchy, the initially supported types are: * * Long - performance data holds a Java long type * ByteArray - performance data holds an array of Java bytes * used for holding C++ char arrays. * * The String type is derived from the ByteArray type. * * A PerfData subtype is not required to provide an implementation for * each variability classification. For example, the String type provides * Variable and Constant variability classifications in the PerfStringVariable * and PerfStringConstant classes, but does not provide a counter type. * * Performance data are also described by a unit of measure. Units allow * client applications to make reasonable decisions on how to treat * performance data generically, preventing the need to hard-code the * specifics of a particular data item in client applications. The current * set of units are: * * None - the data has no units of measure * Bytes - data is measured in bytes * Ticks - data is measured in clock ticks * Events - data is measured in events. For example, * the number of garbage collection events or the * number of methods compiled. * String - data is not numerical. For example, * the java command line options * Hertz - data is a frequency * * The performance counters also provide a support attribute, indicating * the stability of the counter as a programmatic interface. The support * level is also implied by the name space in which the counter is created. * The counter name space support conventions follow the Java package, class, * and property support conventions: * * java.* - stable, supported interface * com.sun.* - unstable, supported interface * sun.* - unstable, unsupported interface * * In the above context, unstable is a measure of the interface support * level, not the implementation stability level. * * Currently, instances of PerfData subtypes are considered to have * a life time equal to that of the VM and are managed by the * PerfDataManager class. All constructors for the PerfData class and * its subtypes have protected constructors. Creation of PerfData * instances is performed by invoking various create methods on the * PerfDataManager class. Users should not attempt to delete these * instances as the PerfDataManager class expects to perform deletion * operations on exit of the VM. * * Examples: * * Creating performance counter that holds a monotonically increasing * long data value with units specified in U_Bytes in the "java.gc.*" * name space. * * PerfLongCounter* foo_counter; * * foo_counter = PerfDataManager::create_long_counter(JAVA_GC, "foo", * PerfData::U_Bytes, * optionalInitialValue, * CHECK); * foo_counter->inc(); * * Creating a performance counter that holds a variably change long * data value with units specified in U_Bytes in the "com.sun.ci * name space. * * PerfLongVariable* bar_variable; * bar_variable = PerfDataManager::create_long_variable(COM_CI, "bar", .* PerfData::U_Bytes, * optionalInitialValue, * CHECK); * * bar_variable->inc(); * bar_variable->set_value(0); * * Creating a performance counter that holds a constant string value in * the "sun.cls.*" name space. * * PerfDataManager::create_string_constant(SUN_CLS, "foo", string, CHECK); * * Although the create_string_constant() factory method returns a pointer * to the PerfStringConstant object, it can safely be ignored. Developers * are not encouraged to access the string constant's value via this * pointer at this time due to security concerns. * * Creating a performance counter in an arbitrary name space that holds a * value that is sampled by the StatSampler periodic task. * * PerfDataManager::create_counter("foo.sampled", PerfData::U_Events, * &my_jlong, CHECK); * * In this example, the PerfData pointer can be ignored as the caller * is relying on the StatSampler PeriodicTask to sample the given * address at a regular interval. The interval is defined by the * PerfDataSamplingInterval global variable, and is applied on * a system wide basis, not on an per-counter basis. * * Creating a performance counter in an arbitrary name space that utilizes * a helper object to return a value to the StatSampler via the take_sample() * method. * * class MyTimeSampler : public PerfLongSampleHelper { * public: * jlong take_sample() { return os::elapsed_counter(); } * }; * * PerfDataManager::create_counter(SUN_RT, "helped", * PerfData::U_Ticks, * new MyTimeSampler(), CHECK); * * In this example, a subtype of PerfLongSampleHelper is instantiated * and its take_sample() method is overridden to perform whatever * operation is necessary to generate the data sample. This method * will be called by the StatSampler at a regular interval, defined * by the PerfDataSamplingInterval global variable. * * As before, PerfSampleHelper is an alias for PerfLongSampleHelper. * * For additional uses of PerfData subtypes, see the utility classes * PerfTraceTime and PerfTraceTimedEvent below. * * Always-on non-sampled counters can be created independent of * the UsePerfData flag. Counters will be created on the c-heap * if UsePerfData is false. * * Until further notice, all PerfData objects should be created and * manipulated within a guarded block. The guard variable is * UsePerfData, a product flag set to true by default. This flag may * be removed from the product in the future. * */ class PerfData : public CHeapObj<mtInternal> { friend class StatSampler; // for access to protected void sample() friend class PerfDataManager; // for access to protected destructor friend class VMStructs; public: // the Variability enum must be kept in synchronization with the // the com.sun.hotspot.perfdata.Variability class enum Variability { V_Constant = 1, V_Monotonic = 2, V_Variable = 3, V_last = V_Variable }; // the Units enum must be kept in synchronization with the // the com.sun.hotspot.perfdata.Units class enum Units { U_None = 1, U_Bytes = 2, U_Ticks = 3, U_Events = 4, U_String = 5, U_Hertz = 6, U_Last = U_Hertz }; // Miscellaneous flags enum Flags { F_None = 0x0, F_Supported = 0x1 // interface is supported - java.* and com.sun.* }; private: char* _name; Variability _v; Units _u; bool _on_c_heap; Flags _flags; PerfDataEntry* _pdep; protected: void *_valuep; PerfData(CounterNS ns, const char* name, Units u, Variability v); virtual ~PerfData(); // create the entry for the PerfData item in the PerfData memory region. // this region is maintained separately from the PerfData objects to // facilitate its use by external processes. void create_entry(BasicType dtype, size_t dsize, size_t dlen = 0); // sample the data item given at creation time and write its value // into the its corresponding PerfMemory location. virtual void sample() = 0; public: // returns a boolean indicating the validity of this object. // the object is valid if and only if memory in PerfMemory // region was successfully allocated. inline bool is_valid() { return _valuep != NULL; } // returns a boolean indicating whether the underlying object // was allocated in the PerfMemory region or on the C heap. inline bool is_on_c_heap() { return _on_c_heap; } // returns a pointer to a char* containing the name of the item. // The pointer returned is the pointer to a copy of the name // passed to the constructor, not the pointer to the name in the // PerfData memory region. This redundancy is maintained for // security reasons as the PerfMemory region may be in shared // memory. const char* name() { return _name; } // returns the variability classification associated with this item Variability variability() { return _v; } // returns the units associated with this item. Units units() { return _u; } // returns the flags associated with this item. Flags flags() { return _flags; } // returns the address of the data portion of the item in the // PerfData memory region. inline void* get_address() { return _valuep; } // returns the value of the data portion of the item in the // PerfData memory region formatted as a string. virtual int format(char* cp, int length) = 0; }; /* * PerfLongSampleHelper, and its alias PerfSamplerHelper, is a base class * for helper classes that rely upon the StatSampler periodic task to * invoke the take_sample() method and write the value returned to its * appropriate location in the PerfData memory region. */ class PerfLongSampleHelper : public CHeapObj<mtInternal> { public: virtual jlong take_sample() = 0; }; typedef PerfLongSampleHelper PerfSampleHelper; /* * PerfLong is the base class for the various Long PerfData subtypes. * it contains implementation details that are common among its derived * types. */ class PerfLong : public PerfData { protected: PerfLong(CounterNS ns, const char* namep, Units u, Variability v); public: int format(char* buffer, int length); // returns the value of the data portion of the item in the // PerfData memory region. inline jlong get_value() { return *(jlong*)_valuep; } }; /* * The PerfLongConstant class, and its alias PerfConstant, implement * a PerfData subtype that holds a jlong data value that is set upon * creation of an instance of this class. This class provides no * methods for changing the data value stored in PerfData memory region. */ class PerfLongConstant : public PerfLong { friend class PerfDataManager; // for access to protected constructor private: // hide sample() - no need to sample constants void sample() { } protected: PerfLongConstant(CounterNS ns, const char* namep, Units u, jlong initial_value=0) : PerfLong(ns, namep, u, V_Constant) { if (is_valid()) *(jlong*)_valuep = initial_value; } }; typedef PerfLongConstant PerfConstant; /* * The PerfLongVariant class, and its alias PerfVariant, implement * a PerfData subtype that holds a jlong data value that can be modified * in an unrestricted manner. This class provides the implementation details * for common functionality among its derived types. */ class PerfLongVariant : public PerfLong { protected: jlong* _sampled; PerfLongSampleHelper* _sample_helper; PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v, jlong initial_value=0) : PerfLong(ns, namep, u, v) { if (is_valid()) *(jlong*)_valuep = initial_value; } PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v, jlong* sampled); PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v, PerfLongSampleHelper* sample_helper); void sample(); public: inline void inc() { (*(jlong*)_valuep)++; } inline void inc(jlong val) { (*(jlong*)_valuep) += val; } inline void dec(jlong val) { inc(-val); } inline void add(jlong val) { (*(jlong*)_valuep) += val; } void clear_sample_helper() { _sample_helper = NULL; } }; /* * The PerfLongCounter class, and its alias PerfCounter, implement * a PerfData subtype that holds a jlong data value that can (should) * be modified in a monotonic manner. The inc(jlong) and add(jlong) * methods can be passed negative values to implement a monotonically * decreasing value. However, we rely upon the programmer to honor * the notion that this counter always moves in the same direction - * either increasing or decreasing. */ class PerfLongCounter : public PerfLongVariant { friend class PerfDataManager; // for access to protected constructor protected: PerfLongCounter(CounterNS ns, const char* namep, Units u, jlong initial_value=0) : PerfLongVariant(ns, namep, u, V_Monotonic, initial_value) { } PerfLongCounter(CounterNS ns, const char* namep, Units u, jlong* sampled) : PerfLongVariant(ns, namep, u, V_Monotonic, sampled) { } PerfLongCounter(CounterNS ns, const char* namep, Units u, PerfLongSampleHelper* sample_helper) : PerfLongVariant(ns, namep, u, V_Monotonic, sample_helper) { } }; typedef PerfLongCounter PerfCounter; /* * The PerfLongVariable class, and its alias PerfVariable, implement * a PerfData subtype that holds a jlong data value that can * be modified in an unrestricted manner. */ class PerfLongVariable : public PerfLongVariant { friend class PerfDataManager; // for access to protected constructor protected: PerfLongVariable(CounterNS ns, const char* namep, Units u, jlong initial_value=0) : PerfLongVariant(ns, namep, u, V_Variable, initial_value) { } PerfLongVariable(CounterNS ns, const char* namep, Units u, jlong* sampled) : PerfLongVariant(ns, namep, u, V_Variable, sampled) { } PerfLongVariable(CounterNS ns, const char* namep, Units u, PerfLongSampleHelper* sample_helper) : PerfLongVariant(ns, namep, u, V_Variable, sample_helper) { } public: inline void set_value(jlong val) { (*(jlong*)_valuep) = val; } }; typedef PerfLongVariable PerfVariable; /* * The PerfByteArray provides a PerfData subtype that allows the creation * of a contiguous region of the PerfData memory region for storing a vector * of bytes. This class is currently intended to be a base class for * the PerfString class, and cannot be instantiated directly. */ class PerfByteArray : public PerfData { protected: jint _length; PerfByteArray(CounterNS ns, const char* namep, Units u, Variability v, jint length); }; class PerfString : public PerfByteArray { protected: void set_string(const char* s2); PerfString(CounterNS ns, const char* namep, Variability v, jint length, const char* initial_value) : PerfByteArray(ns, namep, U_String, v, length) { if (is_valid()) set_string(initial_value); } public: int format(char* buffer, int length); }; /* * The PerfStringConstant class provides a PerfData sub class that * allows a null terminated string of single byte characters to be * stored in the PerfData memory region. */ class PerfStringConstant : public PerfString { friend class PerfDataManager; // for access to protected constructor private: // hide sample() - no need to sample constants void sample() { } protected: // Restrict string constant lengths to be <= PerfMaxStringConstLength. // This prevents long string constants, as can occur with very // long classpaths or java command lines, from consuming too much // PerfData memory. PerfStringConstant(CounterNS ns, const char* namep, const char* initial_value); }; /* * The PerfStringVariable class provides a PerfData sub class that * allows a null terminated string of single byte character data * to be stored in PerfData memory region. The string value can be reset * after initialization. If the string value is >= max_length, then * it will be truncated to max_length characters. The copied string * is always null terminated. */ class PerfStringVariable : public PerfString { friend class PerfDataManager; // for access to protected constructor protected: // sampling of string variables are not yet supported void sample() { } PerfStringVariable(CounterNS ns, const char* namep, jint max_length, const char* initial_value) : PerfString(ns, namep, V_Variable, max_length+1, initial_value) { } public: inline void set_value(const char* val) { set_string(val); } }; /* * The PerfDataList class is a container class for managing lists * of PerfData items. The intention of this class is to allow for * alternative implementations for management of list of PerfData * items without impacting the code that uses the lists. * * The initial implementation is based upon GrowableArray. Searches * on GrowableArray types is linear in nature and this may become * a performance issue for creation of PerfData items, particularly * from Java code where a test for existence is implemented as a * search over all existing PerfData items. * * The abstraction is not complete. A more general container class * would provide an Iterator abstraction that could be used to * traverse the lists. This implementation still relies upon integer * iterators and the at(int index) method. However, the GrowableArray * is not directly visible outside this class and can be replaced by * some other implementation, as long as that implementation provides * a mechanism to iterate over the container by index. */ class PerfDataList : public CHeapObj<mtInternal> { private: // GrowableArray implementation typedef GrowableArray<PerfData*> PerfDataArray; PerfDataArray* _set; // method to search for a instrumentation object by name static bool by_name(void* name, PerfData* pd); protected: // we expose the implementation here to facilitate the clone // method. PerfDataArray* get_impl() { return _set; } public: // create a PerfDataList with the given initial length PerfDataList(int length); // create a PerfDataList as a shallow copy of the given PerfDataList PerfDataList(PerfDataList* p); ~PerfDataList(); // return the PerfData item indicated by name, // or NULL if it doesn't exist. PerfData* find_by_name(const char* name); // return true if a PerfData item with the name specified in the // argument exists, otherwise return false. bool contains(const char* name) { return find_by_name(name) != NULL; } // return the number of PerfData items in this list inline int length(); // add a PerfData item to this list inline void append(PerfData *p); // remove the given PerfData item from this list. When called // while iterating over the list, this method will result in a // change in the length of the container. The at(int index) // method is also impacted by this method as elements with an // index greater than the index of the element removed by this // method will be shifted down by one. inline void remove(PerfData *p); // create a new PerfDataList from this list. The new list is // a shallow copy of the original list and care should be taken // with respect to delete operations on the elements of the list // as the are likely in use by another copy of the list. PerfDataList* clone(); // for backward compatibility with GrowableArray - need to implement // some form of iterator to provide a cleaner abstraction for // iteration over the container. inline PerfData* at(int index); }; /* * The PerfDataManager class is responsible for creating PerfData * subtypes via a set a factory methods and for managing lists * of the various PerfData types. */ class PerfDataManager : AllStatic { friend class StatSampler; // for access to protected PerfDataList methods private: static PerfDataList* _all; static PerfDataList* _sampled; static PerfDataList* _constants; static const char* _name_spaces[]; static volatile bool _has_PerfData; // add a PerfData item to the list(s) of know PerfData objects static void add_item(PerfData* p, bool sampled); protected: // return the list of all known PerfData items static PerfDataList* all(); static inline int count(); // return the list of all known PerfData items that are to be // sampled by the StatSampler. static PerfDataList* sampled(); static inline int sampled_count(); // return the list of all known PerfData items that have a // variability classification of type Constant static PerfDataList* constants(); static inline int constants_count(); public: // method to check for the existence of a PerfData item with // the given name. static inline bool exists(const char* name); // method to search for a instrumentation object by name static PerfData* find_by_name(const char* name); // method to map a CounterNS enumeration to a namespace string static const char* ns_to_string(CounterNS ns) { return _name_spaces[ns]; } // methods to test the interface stability of a given counter namespace // static bool is_stable_supported(CounterNS ns) { return (ns != NULL_NS) && ((ns % 3) == JAVA_NS); } static bool is_unstable_supported(CounterNS ns) { return (ns != NULL_NS) && ((ns % 3) == COM_NS); } static bool is_unstable_unsupported(CounterNS ns) { return (ns == NULL_NS) || ((ns % 3) == SUN_NS); } // methods to test the interface stability of a given counter name // static bool is_stable_supported(const char* name) { const char* javadot = "java."; return strncmp(name, javadot, strlen(javadot)) == 0; } static bool is_unstable_supported(const char* name) { const char* comdot = "com.sun."; return strncmp(name, comdot, strlen(comdot)) == 0; } static bool is_unstable_unsupported(const char* name) { return !(is_stable_supported(name) && is_unstable_supported(name)); } // method to construct counter name strings in a given name space. // The string object is allocated from the Resource Area and calls // to this method must be made within a ResourceMark. // static char* counter_name(const char* name_space, const char* name); // method to construct name space strings in a given name space. // The string object is allocated from the Resource Area and calls // to this method must be made within a ResourceMark. // static char* name_space(const char* name_space, const char* sub_space) { return counter_name(name_space, sub_space); } // same as above, but appends the instance number to the name space // static char* name_space(const char* name_space, const char* sub_space, int instance); static char* name_space(const char* name_space, int instance); // these methods provide the general interface for creating // performance data resources. The types of performance data // resources can be extended by adding additional create<type> // methods. // Constant Types static PerfStringConstant* create_string_constant(CounterNS ns, const char* name, const char *s, TRAPS); static PerfLongConstant* create_long_constant(CounterNS ns, const char* name, PerfData::Units u, jlong val, TRAPS); // Variable Types static PerfStringVariable* create_string_variable(CounterNS ns, const char* name, int max_length, const char *s, TRAPS); static PerfStringVariable* create_string_variable(CounterNS ns, const char* name, const char *s, TRAPS) { return create_string_variable(ns, name, 0, s, THREAD); }; static PerfLongVariable* create_long_variable(CounterNS ns, const char* name, PerfData::Units u, jlong ival, TRAPS); static PerfLongVariable* create_long_variable(CounterNS ns, const char* name, PerfData::Units u, TRAPS) { return create_long_variable(ns, name, u, (jlong)0, THREAD); }; static PerfLongVariable* create_long_variable(CounterNS, const char* name, PerfData::Units u, jlong* sp, TRAPS); static PerfLongVariable* create_long_variable(CounterNS ns, const char* name, PerfData::Units u, PerfLongSampleHelper* sh, TRAPS); // Counter Types static PerfLongCounter* create_long_counter(CounterNS ns, const char* name, PerfData::Units u, jlong ival, TRAPS); static PerfLongCounter* create_long_counter(CounterNS ns, const char* name, PerfData::Units u, TRAPS) { return create_long_counter(ns, name, u, (jlong)0, THREAD); }; static PerfLongCounter* create_long_counter(CounterNS ns, const char* name, PerfData::Units u, jlong* sp, TRAPS); static PerfLongCounter* create_long_counter(CounterNS ns, const char* name, PerfData::Units u, PerfLongSampleHelper* sh, TRAPS); // these creation methods are provided for ease of use. These allow // Long performance data types to be created with a shorthand syntax. static PerfConstant* create_constant(CounterNS ns, const char* name, PerfData::Units u, jlong val, TRAPS) { return create_long_constant(ns, name, u, val, THREAD); } static PerfVariable* create_variable(CounterNS ns, const char* name, PerfData::Units u, jlong ival, TRAPS) { return create_long_variable(ns, name, u, ival, THREAD); } static PerfVariable* create_variable(CounterNS ns, const char* name, PerfData::Units u, TRAPS) { return create_long_variable(ns, name, u, (jlong)0, THREAD); } static PerfVariable* create_variable(CounterNS ns, const char* name, PerfData::Units u, jlong* sp, TRAPS) { return create_long_variable(ns, name, u, sp, THREAD); } static PerfVariable* create_variable(CounterNS ns, const char* name, PerfData::Units u, PerfSampleHelper* sh, TRAPS) { return create_long_variable(ns, name, u, sh, THREAD); } static PerfCounter* create_counter(CounterNS ns, const char* name, PerfData::Units u, jlong ival, TRAPS) { return create_long_counter(ns, name, u, ival, THREAD); } static PerfCounter* create_counter(CounterNS ns, const char* name, PerfData::Units u, TRAPS) { return create_long_counter(ns, name, u, (jlong)0, THREAD); } static PerfCounter* create_counter(CounterNS ns, const char* name, PerfData::Units u, jlong* sp, TRAPS) { return create_long_counter(ns, name, u, sp, THREAD); } static PerfCounter* create_counter(CounterNS ns, const char* name, PerfData::Units u, PerfSampleHelper* sh, TRAPS) { return create_long_counter(ns, name, u, sh, THREAD); } static void destroy(); static bool has_PerfData() { return _has_PerfData; } }; // Useful macros to create the performance counters #define NEWPERFTICKCOUNTER(counter, counter_ns, counter_name) \ {counter = PerfDataManager::create_counter(counter_ns, counter_name, \ PerfData::U_Ticks,CHECK);} #define NEWPERFEVENTCOUNTER(counter, counter_ns, counter_name) \ {counter = PerfDataManager::create_counter(counter_ns, counter_name, \ PerfData::U_Events,CHECK);} #define NEWPERFBYTECOUNTER(counter, counter_ns, counter_name) \ {counter = PerfDataManager::create_counter(counter_ns, counter_name, \ PerfData::U_Bytes,CHECK);} // Utility Classes /* * this class will administer a PerfCounter used as a time accumulator * for a basic block much like the TraceTime class. * * Example: * * static PerfCounter* my_time_counter = PerfDataManager::create_counter("my.time.counter", PerfData::U_Ticks, 0LL, CHECK); * * { * PerfTraceTime ptt(my_time_counter); * // perform the operation you want to measure * } * * Note: use of this class does not need to occur within a guarded * block. The UsePerfData guard is used with the implementation * of this class. */ class PerfTraceTime : public StackObj { protected: elapsedTimer _t; PerfLongCounter* _timerp; // pointer to thread-local or global recursion counter variable int* _recursion_counter; public: inline PerfTraceTime(PerfLongCounter* timerp) : _timerp(timerp), _recursion_counter(NULL) { if (!UsePerfData) return; _t.start(); } inline PerfTraceTime(PerfLongCounter* timerp, int* recursion_counter) : _timerp(timerp), _recursion_counter(recursion_counter) { if (!UsePerfData || (_recursion_counter != NULL && (*_recursion_counter)++ > 0)) return; _t.start(); } inline void suspend() { if (!UsePerfData) return; _t.stop(); } inline void resume() { if (!UsePerfData) return; _t.start(); } ~PerfTraceTime(); }; /* The PerfTraceTimedEvent class is responsible for counting the * occurrence of some event and measuring the the elapsed time of * the event in two separate PerfCounter instances. * * Example: * * static PerfCounter* my_time_counter = PerfDataManager::create_counter("my.time.counter", PerfData::U_Ticks, CHECK); * static PerfCounter* my_event_counter = PerfDataManager::create_counter("my.event.counter", PerfData::U_Events, CHECK); * * { * PerfTraceTimedEvent ptte(my_time_counter, my_event_counter); * // perform the operation you want to count and measure * } * * Note: use of this class does not need to occur within a guarded * block. The UsePerfData guard is used with the implementation * of this class. * */ class PerfTraceTimedEvent : public PerfTraceTime { protected: PerfLongCounter* _eventp; public: inline PerfTraceTimedEvent(PerfLongCounter* timerp, PerfLongCounter* eventp): PerfTraceTime(timerp), _eventp(eventp) { if (!UsePerfData) return; _eventp->inc(); } inline PerfTraceTimedEvent(PerfLongCounter* timerp, PerfLongCounter* eventp, int* recursion_counter): PerfTraceTime(timerp, recursion_counter), _eventp(eventp) { if (!UsePerfData) return; _eventp->inc(); } }; #endif // SHARE_VM_RUNTIME_PERFDATA_HPP
36,610
10,089
#pragma once #include "../../other/template.hpp" #include "../../other/monoid.hpp" template<class M> class SlidingWindowAggregation { protected: using T = typename M::value_type; std::stack<T> lst, rst; std::stack<T> lsm, rsm; T internal_all_prod() const { assert(!empty()); if (lst.empty()) return rsm.top(); if (rst.empty()) return lsm.top(); return M::op(lsm.top(), rsm.top()); } public: SlidingWindowAggregation() = default; int size() const { return lst.size() + rst.size(); } bool empty() const { return lst.empty() && rst.empty(); } void push(const T& x) { rst.push(x); if (rsm.empty()) rsm.push(rst.top()); else rsm.push(M::op(rsm.top(), rst.top())); } template<class... Args> void emplace(Args&&... args) { rst.emplace(std::forward<Args>(args)...); if (rsm.empty()) rsm.push(rst.top()); else rsm.push(M::op(rsm.top(), rst.top())); } void pop() { assert(!empty()); if (lst.empty()) { lst.push(rst.top()); lsm.push(rst.top()); rst.pop(); rsm.pop(); while (!rst.empty()) { lst.push(rst.top()); lsm.push(M::op(rst.top(), lsm.top())); rst.pop(); rsm.pop(); } } lst.pop(); lsm.pop(); } template<bool AlwaysTrue = true, typename std::enable_if< Monoid::has_id<M>::value && AlwaysTrue>::type* = nullptr> T all_prod() const { if (empty()) return M::id(); return internal_all_prod(); } template<bool AlwaysTrue = true, typename std::enable_if<!Monoid::has_id<M>::value && AlwaysTrue>::type* = nullptr> T all_prod() const { return internal_all_prod(); } }; /** * @brief SlidingWindowAggregation(SWAG) * @docs docs/SlidingWindowAggregation.md */
1,873
655
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/power_monitor/power_monitor.h" #include "base/macros.h" #include "base/test/power_monitor_test_base.h" #include "base/test/task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { class PowerMonitorTest : public testing::Test { protected: PowerMonitorTest() = default; void TearDown() override { PowerMonitor::ShutdownForTesting(); } void PowerMonitorInitialize() { power_monitor_source_ = new PowerMonitorTestSource(); PowerMonitor::Initialize( std::unique_ptr<PowerMonitorSource>(power_monitor_source_)); } PowerMonitorTestSource* source() { return power_monitor_source_; } private: test::TaskEnvironment task_environment_; PowerMonitorTestSource* power_monitor_source_; DISALLOW_COPY_AND_ASSIGN(PowerMonitorTest); }; // PowerMonitorSource is tightly coupled with the PowerMonitor, so this test // covers both classes. TEST_F(PowerMonitorTest, PowerNotifications) { const int kObservers = 5; PowerMonitorInitialize(); PowerMonitorTestObserver observers[kObservers]; for (auto& index : observers) { PowerMonitor::AddPowerSuspendObserver(&index); PowerMonitor::AddPowerStateObserver(&index); PowerMonitor::AddPowerThermalObserver(&index); } // Sending resume when not suspended should have no effect. source()->GenerateResumeEvent(); EXPECT_EQ(observers[0].resumes(), 0); // Pretend we suspended. source()->GenerateSuspendEvent(); // Ensure all observers were notified of the event for (const auto& index : observers) EXPECT_EQ(index.suspends(), 1); // Send a second suspend notification. This should be suppressed. source()->GenerateSuspendEvent(); EXPECT_EQ(observers[0].suspends(), 1); // Pretend we were awakened. source()->GenerateResumeEvent(); EXPECT_EQ(observers[0].resumes(), 1); // Send a duplicate resume notification. This should be suppressed. source()->GenerateResumeEvent(); EXPECT_EQ(observers[0].resumes(), 1); // Pretend the device has gone on battery power source()->GeneratePowerStateEvent(true); EXPECT_EQ(observers[0].power_state_changes(), 1); EXPECT_EQ(observers[0].last_power_state(), true); // Repeated indications the device is on battery power should be suppressed. source()->GeneratePowerStateEvent(true); EXPECT_EQ(observers[0].power_state_changes(), 1); // Pretend the device has gone off battery power source()->GeneratePowerStateEvent(false); EXPECT_EQ(observers[0].power_state_changes(), 2); EXPECT_EQ(observers[0].last_power_state(), false); // Repeated indications the device is off battery power should be suppressed. source()->GeneratePowerStateEvent(false); EXPECT_EQ(observers[0].power_state_changes(), 2); EXPECT_EQ(observers[0].thermal_state_changes(), 0); // Send a power thermal change notification. source()->GenerateThermalThrottlingEvent( PowerThermalObserver::DeviceThermalState::kNominal); EXPECT_EQ(observers[0].thermal_state_changes(), 1); EXPECT_EQ(observers[0].last_thermal_state(), PowerThermalObserver::DeviceThermalState::kNominal); // Send a duplicate power thermal notification. This should be suppressed. source()->GenerateThermalThrottlingEvent( PowerThermalObserver::DeviceThermalState::kNominal); EXPECT_EQ(observers[0].thermal_state_changes(), 1); // Send a different power thermal change notification. source()->GenerateThermalThrottlingEvent( PowerThermalObserver::DeviceThermalState::kFair); EXPECT_EQ(observers[0].thermal_state_changes(), 2); EXPECT_EQ(observers[0].last_thermal_state(), PowerThermalObserver::DeviceThermalState::kFair); for (auto& index : observers) { PowerMonitor::RemovePowerSuspendObserver(&index); PowerMonitor::RemovePowerStateObserver(&index); PowerMonitor::RemovePowerThermalObserver(&index); } } TEST_F(PowerMonitorTest, ThermalThrottling) { PowerMonitorTestObserver observer; PowerMonitor::AddPowerThermalObserver(&observer); PowerMonitorInitialize(); constexpr PowerThermalObserver::DeviceThermalState kThermalStates[] = { PowerThermalObserver::DeviceThermalState::kUnknown, PowerThermalObserver::DeviceThermalState::kNominal, PowerThermalObserver::DeviceThermalState::kFair, PowerThermalObserver::DeviceThermalState::kSerious, PowerThermalObserver::DeviceThermalState::kCritical}; for (const auto state : kThermalStates) { source()->GenerateThermalThrottlingEvent(state); EXPECT_EQ(state, source()->GetCurrentThermalState()); EXPECT_EQ(observer.last_thermal_state(), state); } PowerMonitor::RemovePowerThermalObserver(&observer); } TEST_F(PowerMonitorTest, AddPowerSuspendObserverBeforeAndAfterInitialization) { PowerMonitorTestObserver observer1; PowerMonitorTestObserver observer2; // An observer is added before the PowerMonitor initialization. PowerMonitor::AddPowerSuspendObserver(&observer1); PowerMonitorInitialize(); // An observer is added after the PowerMonitor initialization. PowerMonitor::AddPowerSuspendObserver(&observer2); // Simulate suspend/resume notifications. source()->GenerateSuspendEvent(); EXPECT_EQ(observer1.suspends(), 1); EXPECT_EQ(observer2.suspends(), 1); EXPECT_EQ(observer1.resumes(), 0); EXPECT_EQ(observer2.resumes(), 0); source()->GenerateResumeEvent(); EXPECT_EQ(observer1.resumes(), 1); EXPECT_EQ(observer2.resumes(), 1); PowerMonitor::RemovePowerSuspendObserver(&observer1); PowerMonitor::RemovePowerSuspendObserver(&observer2); } TEST_F(PowerMonitorTest, AddPowerStateObserverBeforeAndAfterInitialization) { PowerMonitorTestObserver observer1; PowerMonitorTestObserver observer2; // An observer is added before the PowerMonitor initialization. PowerMonitor::AddPowerStateObserver(&observer1); PowerMonitorInitialize(); // An observer is added after the PowerMonitor initialization. PowerMonitor::AddPowerStateObserver(&observer2); // Simulate power state transitions (e.g. battery on/off). EXPECT_EQ(observer1.power_state_changes(), 0); EXPECT_EQ(observer2.power_state_changes(), 0); source()->GeneratePowerStateEvent(true); EXPECT_EQ(observer1.power_state_changes(), 1); EXPECT_EQ(observer2.power_state_changes(), 1); source()->GeneratePowerStateEvent(false); EXPECT_EQ(observer1.power_state_changes(), 2); EXPECT_EQ(observer2.power_state_changes(), 2); PowerMonitor::RemovePowerStateObserver(&observer1); PowerMonitor::RemovePowerStateObserver(&observer2); } TEST_F(PowerMonitorTest, SuspendStateReturnedFromAddObserver) { PowerMonitorTestObserver observer1; PowerMonitorTestObserver observer2; PowerMonitorInitialize(); EXPECT_FALSE( PowerMonitor::AddPowerSuspendObserverAndReturnSuspendedState(&observer1)); source()->GenerateSuspendEvent(); EXPECT_TRUE( PowerMonitor::AddPowerSuspendObserverAndReturnSuspendedState(&observer2)); EXPECT_EQ(observer1.suspends(), 1); EXPECT_EQ(observer2.suspends(), 0); EXPECT_EQ(observer1.resumes(), 0); EXPECT_EQ(observer2.resumes(), 0); PowerMonitor::RemovePowerSuspendObserver(&observer1); PowerMonitor::RemovePowerSuspendObserver(&observer2); } TEST_F(PowerMonitorTest, PowerStateReturnedFromAddObserver) { PowerMonitorTestObserver observer1; PowerMonitorTestObserver observer2; PowerMonitorInitialize(); // An observer is added before the on-battery notification. EXPECT_FALSE( PowerMonitor::AddPowerStateObserverAndReturnOnBatteryState(&observer1)); source()->GeneratePowerStateEvent(true); // An observer is added after the on-battery notification. EXPECT_TRUE( PowerMonitor::AddPowerStateObserverAndReturnOnBatteryState(&observer2)); EXPECT_EQ(observer1.power_state_changes(), 1); EXPECT_EQ(observer2.power_state_changes(), 0); PowerMonitor::RemovePowerStateObserver(&observer1); PowerMonitor::RemovePowerStateObserver(&observer2); } } // namespace base
8,107
2,700
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP #define BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP #include <cstddef> #include <boost/concept/requires.hpp> #include <boost/concept_check.hpp> #include <boost/mpl/assert.hpp> #include <boost/mpl/if.hpp> #include <boost/numeric/conversion/bounds.hpp> #include <boost/numeric/conversion/cast.hpp> #include <boost/type_traits.hpp> #include <boost/geometry/arithmetic/arithmetic.hpp> #include <boost/geometry/algorithms/append.hpp> #include <boost/geometry/algorithms/clear.hpp> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/util/for_each_coordinate.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace assign { template < typename Box, std::size_t Index, std::size_t Dimension, std::size_t DimensionCount > struct initialize { typedef typename coordinate_type<Box>::type coordinate_type; static inline void apply(Box& box, coordinate_type const& value) { geometry::set<Index, Dimension>(box, value); initialize<Box, Index, Dimension + 1, DimensionCount>::apply(box, value); } }; template <typename Box, std::size_t Index, std::size_t DimensionCount> struct initialize<Box, Index, DimensionCount, DimensionCount> { typedef typename coordinate_type<Box>::type coordinate_type; static inline void apply(Box&, coordinate_type const& ) {} }; template <typename Point> struct assign_zero_point { static inline void apply(Point& point) { geometry::assign_value(point, 0); } }; template <typename BoxOrSegment> struct assign_inverse_box_or_segment { typedef typename point_type<BoxOrSegment>::type point_type; static inline void apply(BoxOrSegment& geometry) { typedef typename coordinate_type<point_type>::type bound_type; initialize < BoxOrSegment, 0, 0, dimension<BoxOrSegment>::type::value >::apply( geometry, boost::numeric::bounds<bound_type>::highest()); initialize < BoxOrSegment, 1, 0, dimension<BoxOrSegment>::type::value >::apply( geometry, boost::numeric::bounds<bound_type>::lowest()); } }; template <typename BoxOrSegment> struct assign_zero_box_or_segment { static inline void apply(BoxOrSegment& geometry) { typedef typename coordinate_type<BoxOrSegment>::type coordinate_type; initialize < BoxOrSegment, 0, 0, dimension<BoxOrSegment>::type::value >::apply(geometry, coordinate_type()); initialize < BoxOrSegment, 1, 0, dimension<BoxOrSegment>::type::value >::apply(geometry, coordinate_type()); } }; template < std::size_t Corner1, std::size_t Corner2, typename Box, typename Point > inline void assign_box_2d_corner(Box const& box, Point& point) { // Be sure both are 2-Dimensional assert_dimension<Box, 2>(); assert_dimension<Point, 2>(); // Copy coordinates typedef typename coordinate_type<Point>::type coordinate_type; geometry::set<0>(point, boost::numeric_cast<coordinate_type>(get<Corner1, 0>(box))); geometry::set<1>(point, boost::numeric_cast<coordinate_type>(get<Corner2, 1>(box))); } template < typename Geometry, typename Point, std::size_t Index, std::size_t Dimension, std::size_t DimensionCount > struct assign_point_to_index { static inline void apply(Point const& point, Geometry& geometry) { geometry::set<Index, Dimension>(geometry, boost::numeric_cast < typename coordinate_type<Geometry>::type >(geometry::get<Dimension>(point))); assign_point_to_index < Geometry, Point, Index, Dimension + 1, DimensionCount >::apply(point, geometry); } }; template < typename Geometry, typename Point, std::size_t Index, std::size_t DimensionCount > struct assign_point_to_index < Geometry, Point, Index, DimensionCount, DimensionCount > { static inline void apply(Point const& , Geometry& ) { } }; template < typename Geometry, typename Point, std::size_t Index, std::size_t Dimension, std::size_t DimensionCount > struct assign_point_from_index { static inline void apply(Geometry const& geometry, Point& point) { geometry::set<Dimension>( point, boost::numeric_cast < typename coordinate_type<Point>::type >(geometry::get<Index, Dimension>(geometry))); assign_point_from_index < Geometry, Point, Index, Dimension + 1, DimensionCount >::apply(geometry, point); } }; template < typename Geometry, typename Point, std::size_t Index, std::size_t DimensionCount > struct assign_point_from_index < Geometry, Point, Index, DimensionCount, DimensionCount > { static inline void apply(Geometry const&, Point&) { } }; template <typename Geometry> struct assign_2d_box_or_segment { typedef typename coordinate_type<Geometry>::type coordinate_type; // Here we assign 4 coordinates to a box of segment // -> Most logical is: x1,y1,x2,y2 // In case the user reverses x1/x2 or y1/y2, for a box, we could reverse them (THAT IS NOT IMPLEMENTED) template <typename Type> static inline void apply(Geometry& geometry, Type const& x1, Type const& y1, Type const& x2, Type const& y2) { geometry::set<0, 0>(geometry, boost::numeric_cast<coordinate_type>(x1)); geometry::set<0, 1>(geometry, boost::numeric_cast<coordinate_type>(y1)); geometry::set<1, 0>(geometry, boost::numeric_cast<coordinate_type>(x2)); geometry::set<1, 1>(geometry, boost::numeric_cast<coordinate_type>(y2)); } }; }} // namespace detail::assign #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template <typename GeometryTag, typename Geometry, std::size_t DimensionCount> struct assign { BOOST_MPL_ASSERT_MSG ( false, NOT_OR_NOT_YET_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE , (types<Geometry>) ); }; template <typename Point> struct assign<point_tag, Point, 2> { typedef typename coordinate_type<Point>::type coordinate_type; template <typename T> static inline void apply(Point& point, T const& c1, T const& c2) { set<0>(point, boost::numeric_cast<coordinate_type>(c1)); set<1>(point, boost::numeric_cast<coordinate_type>(c2)); } }; template <typename Point> struct assign<point_tag, Point, 3> { typedef typename coordinate_type<Point>::type coordinate_type; template <typename T> static inline void apply(Point& point, T const& c1, T const& c2, T const& c3) { set<0>(point, boost::numeric_cast<coordinate_type>(c1)); set<1>(point, boost::numeric_cast<coordinate_type>(c2)); set<2>(point, boost::numeric_cast<coordinate_type>(c3)); } }; template <typename Box> struct assign<box_tag, Box, 2> : detail::assign::assign_2d_box_or_segment<Box> {}; template <typename Segment> struct assign<segment_tag, Segment, 2> : detail::assign::assign_2d_box_or_segment<Segment> {}; template <typename GeometryTag, typename Geometry> struct assign_zero {}; template <typename Point> struct assign_zero<point_tag, Point> : detail::assign::assign_zero_point<Point> {}; template <typename Box> struct assign_zero<box_tag, Box> : detail::assign::assign_zero_box_or_segment<Box> {}; template <typename Segment> struct assign_zero<segment_tag, Segment> : detail::assign::assign_zero_box_or_segment<Segment> {}; template <typename GeometryTag, typename Geometry> struct assign_inverse {}; template <typename Box> struct assign_inverse<box_tag, Box> : detail::assign::assign_inverse_box_or_segment<Box> {}; template <typename Segment> struct assign_inverse<segment_tag, Segment> : detail::assign::assign_inverse_box_or_segment<Segment> {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH /*! \brief Assign two coordinates to a geometry (usually a 2D point) \ingroup assign \tparam Geometry \tparam_geometry \tparam Type \tparam_numeric to specify the coordinates \param geometry \param_geometry \param c1 \param_x \param c2 \param_y \qbk{distinguish, 2 coordinate values} \qbk{ [heading Example] [assign_2d_point] [assign_2d_point_output] [heading See also] \* [link geometry.reference.algorithms.make.make_2_2_coordinate_values make] } */ template <typename Geometry, typename Type> inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2) { concept::check<Geometry>(); dispatch::assign < typename tag<Geometry>::type, Geometry, geometry::dimension<Geometry>::type::value >::apply(geometry, c1, c2); } /*! \brief Assign three values to a geometry (usually a 3D point) \ingroup assign \tparam Geometry \tparam_geometry \tparam Type \tparam_numeric to specify the coordinates \param geometry \param_geometry \param c1 \param_x \param c2 \param_y \param c3 \param_z \qbk{distinguish, 3 coordinate values} \qbk{ [heading Example] [assign_3d_point] [assign_3d_point_output] [heading See also] \* [link geometry.reference.algorithms.make.make_3_3_coordinate_values make] } */ template <typename Geometry, typename Type> inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2, Type const& c3) { concept::check<Geometry>(); dispatch::assign < typename tag<Geometry>::type, Geometry, geometry::dimension<Geometry>::type::value >::apply(geometry, c1, c2, c3); } /*! \brief Assign four values to a geometry (usually a box or segment) \ingroup assign \tparam Geometry \tparam_geometry \tparam Type \tparam_numeric to specify the coordinates \param geometry \param_geometry \param c1 First coordinate (usually x1) \param c2 Second coordinate (usually y1) \param c3 Third coordinate (usually x2) \param c4 Fourth coordinate (usually y2) \qbk{distinguish, 4 coordinate values} */ template <typename Geometry, typename Type> inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2, Type const& c3, Type const& c4) { concept::check<Geometry>(); dispatch::assign < typename tag<Geometry>::type, Geometry, geometry::dimension<Geometry>::type::value >::apply(geometry, c1, c2, c3, c4); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP
11,924
3,989
// Copyright (c) 2012-2018 fo-dicom contributors. // Licensed under the Microsoft Public License (MS-PL). #if defined(_WIN32) #define EXPORT_OpenJPEG __declspec(dllexport) extern "C"{ #include "OpenJPEG/openjpeg.h" #include "OpenJPEG/j2k.h" } #elif defined(__linux__) #define EXPORT_OpenJPEG extern extern "C"{ #include "./Linux64/OpenJPEG/openjpeg.h" #include "./Linux64/OpenJPEG/j2k.h" } #endif namespace Dicom { namespace Imaging { namespace Codec { #ifdef __cplusplus extern "C" { #endif //Encode OpenJPEG EXPORT_OpenJPEG opj_cinfo_t* Opj_create_compress(OPJ_CODEC_FORMAT format){ return opj_create_compress(format); } EXPORT_OpenJPEG opj_event_mgr_t* Opj_set_event_mgr(opj_common_ptr cinfo, opj_event_mgr_t* e, void* context){ return opj_set_event_mgr(cinfo, e, context); } EXPORT_OpenJPEG opj_image_t* Opj_image_create(int numcmpts, opj_image_cmptparm_t* cmptparms, OPJ_COLOR_SPACE clrspc){ return opj_image_create(numcmpts, cmptparms, clrspc); } EXPORT_OpenJPEG void Opj_setup_encoder(opj_cinfo_t* cinfo, opj_cparameters_t* parameters, opj_image_t* image){ opj_setup_encoder(cinfo, parameters, image); } EXPORT_OpenJPEG opj_cio_t* Opj_cio_open(opj_common_ptr cinfo , unsigned char* buffer, int length){ return opj_cio_open(cinfo, buffer, length); } EXPORT_OpenJPEG int Opj_encode(opj_cinfo_t* cinfo, opj_cio_t* cio, opj_image_t* image, char* index){ return opj_encode(cinfo, cio, image, index); } EXPORT_OpenJPEG void Opj_cio_close(opj_cio_t* cio){ opj_cio_close(cio); } EXPORT_OpenJPEG void Opj_image_destroy(opj_image_t* image){ opj_image_destroy(image); } EXPORT_OpenJPEG void Opj_destroy_compress(opj_cinfo_t* cinfo){ opj_destroy_compress(cinfo); } EXPORT_OpenJPEG int Cio_tell(opj_cio_t* cio){ return cio_tell(cio); } //Decode OpenJPEG EXPORT_OpenJPEG opj_dinfo_t* Opj_create_decompress(OPJ_CODEC_FORMAT format){ return opj_create_decompress(format); } EXPORT_OpenJPEG void Opj_setup_decoder(opj_dinfo_t* dinfo, opj_dparameters_t* parameters){ opj_setup_decoder(dinfo, parameters); } EXPORT_OpenJPEG opj_image_t* Opj_decode(opj_dinfo_t* dinfo, opj_cio_t* cio){ return opj_decode(dinfo, cio); } EXPORT_OpenJPEG void Opj_destroy_decompress(opj_dinfo_t* dinfo){ opj_destroy_decompress(dinfo); } #ifdef __cplusplus } #endif }//Codec }//Imaging }//Dicom
2,342
1,042
/* $NoKeywords: $ */ /* // // Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved. // OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert // McNeel & Associates. // // THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. // ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF // MERCHANTABILITY ARE HEREBY DISCLAIMED. // // For complete openNURBS copyright information see <http://www.opennurbs.org>. // //////////////////////////////////////////////////////////////// */ #include "opennurbs.h" // 8 July 2003 Dale Lear // changed ON_Matrix to use multiple allocations // for coefficient memory in large matrices. // ON_Matrix.m_cmem points to a struct DBLBLK struct DBLBLK { int count; double* a; struct DBLBLK *next; }; double const * const * ON_Matrix::ThisM() const { // When the "expert" constructor Create(row_count,col_count,user_memory,...) // is used, m_rowmem[] is empty and m = user_memory; // When any other constructor is used, m_rowmem[] is the 0-based // row memory. return (m_row_count == m_rowmem.Count()) ? m_rowmem.Array() : m; } double * * ON_Matrix::ThisM() { // When the "expert" constructor Create(row_count,col_count,user_memory,...) // is used, m_rowmem[] is empty and m = user_memory; // When any other constructor is used, m_rowmem[] is the 0-based // row memory. return (m_row_count == m_rowmem.Count()) ? m_rowmem.Array() : m; } double* ON_Matrix::operator[](int i) { return m[i]; } const double* ON_Matrix::operator[](int i) const { return m[i]; } ON_Matrix::ON_Matrix() : m(0) , m_row_count(0) , m_col_count(0) , m_Mmem(0) , m_row_offset(0) , m_col_offset(0) , m_cmem(0) { } ON_Matrix::ON_Matrix( int row_size, int col_size ) : m(0) , m_row_count(0) , m_col_count(0) , m_Mmem(0) , m_row_offset(0) , m_col_offset(0) , m_cmem(0) { Create(row_size,col_size); } ON_Matrix::ON_Matrix( int row0, int row1, int col0, int col1 ) : m(0) , m_row_count(0) , m_col_count(0) , m_Mmem(0) , m_row_offset(0) , m_col_offset(0) , m_cmem(0) { Create(row0,row1,col0,col1); } ON_Matrix::ON_Matrix( const ON_Xform& x ) : m(0) , m_row_count(0) , m_col_count(0) , m_Mmem(0) , m_row_offset(0) , m_col_offset(0) , m_cmem(0) { *this = x; } ON_Matrix::ON_Matrix( const ON_Matrix& src ) : m(0) , m_row_count(0) , m_col_count(0) , m_Mmem(0) , m_row_offset(0) , m_col_offset(0) , m_cmem(0) { *this = src; } ON_Matrix::ON_Matrix( int row_count, int col_count, double** M, bool bDestructorFreeM ) : m(0) , m_row_count(0) , m_col_count(0) , m_Mmem(0) , m_row_offset(0) , m_col_offset(0) , m_cmem(0) { Create(row_count,col_count,M,bDestructorFreeM); } ON_Matrix::~ON_Matrix() { if ( 0 != m_Mmem ) { onfree(m_Mmem); m_Mmem = 0; } m_row_offset = 0; m_col_offset = 0; struct DBLBLK* p = (struct DBLBLK*)m_cmem; m_cmem = 0; while(0 != p) { struct DBLBLK* next = p->next; onfree(p); p = next; } } int ON_Matrix::RowCount() const { return m_row_count; } int ON_Matrix::ColCount() const { return m_col_count; } int ON_Matrix::MinCount() const { return (m_row_count <= m_col_count) ? m_row_count : m_col_count; } int ON_Matrix::MaxCount() const { return (m_row_count >= m_col_count) ? m_row_count : m_col_count; } bool ON_Matrix::Create( int row_count, int col_count) { bool b = false; Destroy(); if ( row_count > 0 && col_count > 0 ) { m_rowmem.Reserve(row_count); if ( 0 != m_rowmem.Array() ) { m_rowmem.SetCount(row_count); // In general, allocate coefficient memory in chunks // of <= max_dblblk_size bytes. The value of max_dblblk_size // is tuned to maximize speed on calculations involving // large matrices. If all of the coefficients will fit // into a chunk of memory <= 1.1*max_dblblk_size, then // a single chunk is allocated. // In limited testing, these two values appeared to work ok. // The latter was a hair faster in solving large row reduction // problems (for reasons I do not understand). //const int max_dblblk_size = 1024*1024*8; const int max_dblblk_size = 512*1024; int rows_per_block = max_dblblk_size/(col_count*sizeof(double)); if ( rows_per_block > row_count ) rows_per_block = row_count; else if ( rows_per_block < 1 ) rows_per_block = 1; else if ( rows_per_block < row_count && 11*rows_per_block >= 10*row_count ) rows_per_block = row_count; int j, i = row_count; m = m_rowmem.Array(); double** row = m; for ( i = row_count; i > 0; i -= rows_per_block ) { if ( i < rows_per_block ) rows_per_block = i; int dblblk_count = rows_per_block*col_count; struct DBLBLK* p = (struct DBLBLK*)onmalloc(sizeof(*p) + dblblk_count*sizeof(p->a[0])); p->a = (double*)(p+1); p->count = dblblk_count; p->next = (struct DBLBLK*)m_cmem; m_cmem = p; *row = p->a; j = rows_per_block-1; while(j--) { row[1] = row[0] + col_count; row++; } row++; } m_row_count = row_count; m_col_count = col_count; b = true; } } return b; } bool ON_Matrix::Create( // E.g., Create(1,5,1,7) creates a 5x7 sized matrix that with // "top" row = m[1][1],...,m[1][7] and "bottom" row // = m[5][1],...,m[5][7]. The result of Create(0,m,0,n) is // identical to the result of Create(m+1,n+1). int ri0, // first valid row index int ri1, // last valid row index int ci0, // first valid column index int ci1 // last valid column index ) { bool b = false; if ( ri1 > ri0 && ci1 > ci0 ) { // juggle m[] pointers so that m[ri0+i][ci0+j] = m_row[i][j]; b = Create( ri1-ri0, ci1-ci0 ); if (b) { m_row_offset = ri0; // this is the only line of code where m_row_offset should be set to a non-zero value m_col_offset = ci0; // this is the only line of code where m_col_offset should be set to a non-zero value if ( ci0 != 0 ) { int i; for ( i = 0; i < m_row_count; i++ ) { m[i] -= ci0; } } if ( ri0 != 0 ) m -= ri0; } } return b; } bool ON_Matrix::Create( int row_count, int col_count, double** M, bool bDestructorFreeM ) { Destroy(); if ( row_count < 1 || col_count < 1 || 0 == M ) return false; m = M; m_row_count = row_count; m_col_count = col_count; if ( bDestructorFreeM ) m_Mmem = M; return true; } void ON_Matrix::Destroy() { m = 0; m_row_count = 0; m_col_count = 0; m_rowmem.SetCount(0); if ( 0 != m_Mmem ) { // pointer passed to Create( row_count, col_count, M, bDestructorFreeM ) // when bDestructorFreeM = true. onfree(m_Mmem); m_Mmem = 0; } m_row_offset = 0; m_col_offset = 0; struct DBLBLK* cmem = (struct DBLBLK*)m_cmem; m_cmem = 0; while( 0 != cmem ) { struct DBLBLK* next_cmem = cmem->next; onfree(cmem); cmem = next_cmem; } } void ON_Matrix::EmergencyDestroy() { // call if memory pool used matrix by becomes invalid m = 0; m_row_count = 0; m_col_count = 0; m_rowmem.EmergencyDestroy(); m_Mmem = 0; m_row_offset = 0; m_col_offset = 0; m_cmem = 0; } ON_Matrix& ON_Matrix::operator=(const ON_Matrix& src) { if ( this != &src ) { if ( src.m_row_count != m_row_count || src.m_col_count != m_col_count || 0 == m ) { Destroy(); Create( src.RowCount(), src.ColCount() ); } if (src.m_row_count == m_row_count && src.m_col_count == m_col_count && 0 != m ) { int i; // src rows may be permuted - copy row by row double** m_dest = ThisM(); double const*const* m_src = src.ThisM(); const int sizeof_row = m_col_count*sizeof(m_dest[0][0]); for ( i = 0; i < m_row_count; i++ ) { memcpy( m_dest[i], m_src[i], sizeof_row ); } m_row_offset = src.m_row_offset; m_col_offset = src.m_col_offset; } } return *this; } ON_Matrix& ON_Matrix::operator=(const ON_Xform& src) { m_row_offset = 0; m_col_offset = 0; if ( 4 != m_row_count || 4 != m_col_count || 0 == m ) { Destroy(); Create( 4, 4 ); } if ( 4 == m_row_count && 4 == m_col_count && 0 != m ) { double** this_m = ThisM(); if ( this_m ) { memcpy( this_m[0], &src.m_xform[0][0], 4*sizeof(this_m[0][0]) ); memcpy( this_m[1], &src.m_xform[1][0], 4*sizeof(this_m[0][0]) ); memcpy( this_m[2], &src.m_xform[2][0], 4*sizeof(this_m[0][0]) ); memcpy( this_m[3], &src.m_xform[3][0], 4*sizeof(this_m[0][0]) ); } } return *this; } bool ON_Matrix::Transpose() { bool rc = false; int i, j; double t; const int row_count = RowCount(); const int col_count = ColCount(); if ( row_count > 0 && col_count > 0 ) { double** this_m = ThisM(); if ( row_count == col_count ) { rc = true; for ( i = 0; i < row_count; i++ ) for ( j = i+1; j < row_count; j++ ) { t = this_m[i][j]; this_m[i][j] = this_m[j][i]; this_m[j][i] = t; } } else if ( this_m == m_rowmem.Array() ) { ON_Matrix A(*this); rc = Create(col_count,row_count) && m_row_count == A.ColCount() && m_col_count == A.RowCount(); if (rc) { double const*const* Am = A.ThisM(); this_m = ThisM(); // Create allocates new memory for ( i = 0; i < row_count; i++ ) for ( j = 0; j < col_count; j++ ) { this_m[j][i] = Am[i][j]; } m_row_offset = A.m_col_offset; m_col_offset = A.m_row_offset; } else { // attempt to put values back *this = A; } } } return rc; } bool ON_Matrix::SwapRows( int row0, int row1 ) { bool b = false; double** this_m = ThisM(); row0 -= m_row_offset; row1 -= m_row_offset; if ( this_m && 0 <= row0 && row0 < m_row_count && 0 <= row1 && row1 < m_row_count ) { if ( row0 != row1 ) { double* tmp = this_m[row0]; this_m[row0] = this_m[row1]; this_m[row1] = tmp; } b = true; } return b; } bool ON_Matrix::SwapCols( int col0, int col1 ) { bool b = false; int i; double t; double** this_m = ThisM(); col0 -= m_col_offset; col1 -= m_col_offset; if ( this_m && 0 <= col0 && col0 < m_col_count && 0 <= col1 && col1 < m_col_count ) { if ( col0 != col1 ) { for ( i = 0; i < m_row_count; i++ ) { t = this_m[i][col0]; this_m[i][col0] = this_m[i][col1]; this_m[i][col1] = t; } } b = true; } return b; } void ON_Matrix::RowScale( int dest_row, double s ) { double** this_m = ThisM(); dest_row -= m_row_offset; ON_ArrayScale( m_col_count, s, this_m[dest_row], this_m[dest_row] ); } void ON_Matrix::RowOp( int dest_row, double s, int src_row ) { double** this_m = ThisM(); dest_row -= m_row_offset; src_row -= m_row_offset; ON_Array_aA_plus_B( m_col_count, s, this_m[src_row], this_m[dest_row], this_m[dest_row] ); } void ON_Matrix::ColScale( int dest_col, double s ) { int i; double** this_m = ThisM(); dest_col -= m_col_offset; for ( i = 0; i < m_row_count; i++ ) { this_m[i][dest_col] *= s; } } void ON_Matrix::ColOp( int dest_col, double s, int src_col ) { int i; double** this_m = ThisM(); dest_col -= m_col_offset; src_col -= m_col_offset; for ( i = 0; i < m_row_count; i++ ) { this_m[i][dest_col] += s*this_m[i][src_col]; } } int ON_Matrix::RowReduce( double zero_tolerance, double& determinant, double& pivot ) { double x, piv, det; int i, k, ix, rank; double** this_m = ThisM(); piv = det = 1.0; rank = 0; const int n = m_row_count <= m_col_count ? m_row_count : m_col_count; for ( k = 0; k < n; k++ ) { ix = k; x = fabs(this_m[ix][k]); for ( i = k+1; i < m_row_count; i++ ) { if ( fabs(this_m[i][k]) > x ) { ix = i; x = fabs(this_m[ix][k]); } } if ( x < piv || k == 0 ) { piv = x; } if ( x <= zero_tolerance ) { det = 0.0; break; } rank++; if ( ix != k ) { // swap rows SwapRows( ix, k ); det = -det; } // scale row k of matrix and B det *= this_m[k][k]; x = 1.0/this_m[k][k]; this_m[k][k] = 1.0; ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] ); // zero column k for rows below this_m[k][k] for ( i = k+1; i < m_row_count; i++ ) { x = -this_m[i][k]; this_m[i][k] = 0.0; if ( fabs(x) > zero_tolerance ) { ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] ); } } } pivot = piv; determinant = det; return rank; } int ON_Matrix::RowReduce( double zero_tolerance, double* B, double* pivot ) { double t; double x, piv; int i, k, ix, rank; double** this_m = ThisM(); piv = 0.0; rank = 0; const int n = m_row_count <= m_col_count ? m_row_count : m_col_count; for ( k = 0; k < n; k++ ) { ix = k; x = fabs(this_m[ix][k]); for ( i = k+1; i < m_row_count; i++ ) { if ( fabs(this_m[i][k]) > x ) { ix = i; x = fabs(this_m[ix][k]); } } if ( x < piv || k == 0 ) { piv = x; } if ( x <= zero_tolerance ) break; rank++; if ( ix != k ) { // swap rows of matrix and B SwapRows( ix, k ); t = B[ix]; B[ix] = B[k]; B[k] = t; } // scale row k of matrix and B x = 1.0/this_m[k][k]; this_m[k][k] = 1.0; ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] ); B[k] *= x; // zero column k for rows below this_m[k][k] for ( i = k+1; i < m_row_count; i++ ) { x = -this_m[i][k]; this_m[i][k] = 0.0; if ( fabs(x) > zero_tolerance ) { ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] ); B[i] += x*B[k]; } } } if ( pivot ) *pivot = piv; return rank; } int ON_Matrix::RowReduce( double zero_tolerance, ON_3dPoint* B, double* pivot ) { ON_3dPoint t; double x, piv; int i, k, ix, rank; double** this_m = ThisM(); piv = 0.0; rank = 0; const int n = m_row_count <= m_col_count ? m_row_count : m_col_count; for ( k = 0; k < n; k++ ) { //onfree( onmalloc( 1)); // 8-06-03 lw for cancel thread responsiveness onmalloc( 0); // 9-4-03 lw changed to 0 ix = k; x = fabs(this_m[ix][k]); for ( i = k+1; i < m_row_count; i++ ) { if ( fabs(this_m[i][k]) > x ) { ix = i; x = fabs(this_m[ix][k]); } } if ( x < piv || k == 0 ) { piv = x; } if ( x <= zero_tolerance ) break; rank++; if ( ix != k ) { // swap rows of matrix and B SwapRows( ix, k ); t = B[ix]; B[ix] = B[k]; B[k] = t; } // scale row k of matrix and B x = 1.0/this_m[k][k]; this_m[k][k] = 1.0; ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] ); B[k] *= x; // zero column k for rows below this_m[k][k] for ( i = k+1; i < m_row_count; i++ ) { x = -this_m[i][k]; this_m[i][k] = 0.0; if ( fabs(x) > zero_tolerance ) { ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] ); B[i] += x*B[k]; } } } if ( pivot ) *pivot = piv; return rank; } int ON_Matrix::RowReduce( double zero_tolerance, int pt_dim, int pt_stride, double* pt, double* pivot ) { const int sizeof_pt = pt_dim*sizeof(pt[0]); double* tmp_pt = (double*)onmalloc(pt_dim*sizeof(tmp_pt[0])); double *ptA, *ptB; double x, piv; int i, k, ix, rank, pti; double** this_m = ThisM(); piv = 0.0; rank = 0; const int n = m_row_count <= m_col_count ? m_row_count : m_col_count; for ( k = 0; k < n; k++ ) { // onfree( onmalloc( 1)); // 8-06-03 lw for cancel thread responsiveness onmalloc( 0); // 9-4-03 lw changed to 0 ix = k; x = fabs(this_m[ix][k]); for ( i = k+1; i < m_row_count; i++ ) { if ( fabs(this_m[i][k]) > x ) { ix = i; x = fabs(this_m[ix][k]); } } if ( x < piv || k == 0 ) { piv = x; } if ( x <= zero_tolerance ) break; rank++; // swap rows of matrix and B if ( ix != k ) { SwapRows( ix, k ); ptA = pt + (ix*pt_stride); ptB = pt + (k*pt_stride); memcpy( tmp_pt, ptA, sizeof_pt ); memcpy( ptA, ptB, sizeof_pt ); memcpy( ptB, tmp_pt, sizeof_pt ); } // scale row k of matrix and B x = 1.0/this_m[k][k]; if ( x != 1.0 ) { this_m[k][k] = 1.0; ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] ); ptA = pt + (k*pt_stride); for ( pti = 0; pti < pt_dim; pti++ ) ptA[pti] *= x; } // zero column k for rows below this_m[k][k] ptB = pt + (k*pt_stride); for ( i = k+1; i < m_row_count; i++ ) { x = -this_m[i][k]; this_m[i][k] = 0.0; if ( fabs(x) > zero_tolerance ) { ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] ); ptA = pt + (i*pt_stride); for ( pti = 0; pti < pt_dim; pti++ ) { ptA[pti] += x*ptB[pti]; } } } } if ( pivot ) *pivot = piv; onfree(tmp_pt); return rank; } bool ON_Matrix::BackSolve( double zero_tolerance, int Bsize, const double* B, double* X ) const { int i; if ( m_col_count > m_row_count ) return false; // under determined if ( Bsize < m_col_count || Bsize > m_row_count ) return false; // under determined for ( i = m_col_count; i < Bsize; i++ ) { if ( fabs(B[i]) > zero_tolerance ) return false; // over determined } // backsolve double const*const* this_m = ThisM(); const int n = m_col_count-1; if ( X != B ) X[n] = B[n]; for ( i = n-1; i >= 0; i-- ) { X[i] = B[i] - ON_ArrayDotProduct( n-i, &this_m[i][i+1], &X[i+1] ); } return true; } bool ON_Matrix::BackSolve( double zero_tolerance, int Bsize, const ON_3dPoint* B, ON_3dPoint* X ) const { int i, j; if ( m_col_count > m_row_count ) return false; // under determined if ( Bsize < m_col_count || Bsize > m_row_count ) return false; // under determined for ( i = m_col_count; i < Bsize; i++ ) { if ( B[i].MaximumCoordinate() > zero_tolerance ) return false; // over determined } // backsolve double const*const* this_m = ThisM(); if ( X != B ) { X[m_col_count-1] = B[m_col_count-1]; for ( i = m_col_count-2; i >= 0; i-- ) { X[i] = B[i]; for ( j = i+1; j < m_col_count; j++ ) { X[i] -= this_m[i][j]*X[j]; } } } else { for ( i = m_col_count-2; i >= 0; i-- ) { for ( j = i+1; j < m_col_count; j++ ) { X[i] -= this_m[i][j]*X[j]; } } } return true; } bool ON_Matrix::BackSolve( double zero_tolerance, int pt_dim, int Bsize, int Bpt_stride, const double* Bpt, int Xpt_stride, double* Xpt ) const { const int sizeof_pt = pt_dim*sizeof(double); double mij; int i, j, k; const double* Bi; double* Xi; double* Xj; if ( m_col_count > m_row_count ) return false; // under determined if ( Bsize < m_col_count || Bsize > m_row_count ) return false; // under determined for ( i = m_col_count; i < Bsize; i++ ) { Bi = Bpt + i*Bpt_stride; for( j = 0; j < pt_dim; j++ ) { if ( fabs(Bi[j]) > zero_tolerance ) return false; // over determined } } // backsolve double const*const* this_m = ThisM(); if ( Xpt != Bpt ) { Xi = Xpt + (m_col_count-1)*Xpt_stride; Bi = Bpt + (m_col_count-1)*Bpt_stride; memcpy(Xi,Bi,sizeof_pt); for ( i = m_col_count-2; i >= 0; i-- ) { Xi = Xpt + i*Xpt_stride; Bi = Bpt + i*Bpt_stride; memcpy(Xi,Bi,sizeof_pt); for ( j = i+1; j < m_col_count; j++ ) { Xj = Xpt + j*Xpt_stride; mij = this_m[i][j]; for ( k = 0; k < pt_dim; k++ ) Xi[k] -= mij*Xj[k]; } } } else { for ( i = m_col_count-2; i >= 0; i-- ) { Xi = Xpt + i*Xpt_stride; for ( j = i+1; j < m_col_count; j++ ) { Xj = Xpt + j*Xpt_stride; mij = this_m[i][j]; for ( k = 0; k < pt_dim; k++ ) Xi[k] -= mij*Xj[k]; } } } return true; } void ON_Matrix::Zero() { struct DBLBLK* cmem = (struct DBLBLK*)m_cmem; while ( 0 != cmem ) { if ( 0 != cmem->a && cmem->count > 0 ) { memset( cmem->a, 0, cmem->count*sizeof(cmem->a[0]) ); } cmem = cmem->next; } //m_a.Zero(); } void ON_Matrix::SetDiagonal( double d) { const int n = MinCount(); int i; Zero(); double** this_m = ThisM(); for ( i = 0; i < n; i++ ) { this_m[i][i] = d; } } void ON_Matrix::SetDiagonal( const double* d ) { Zero(); if (d) { double** this_m = ThisM(); const int n = MinCount(); int i; for ( i = 0; i < n; i++ ) { this_m[i][i] = *d++; } } } void ON_Matrix::SetDiagonal( int count, const double* d ) { Create(count,count); Zero(); SetDiagonal(d); } void ON_Matrix::SetDiagonal( const ON_SimpleArray<double>& a ) { SetDiagonal( a.Count(), a.Array() ); } bool ON_Matrix::IsValid() const { if ( m_row_count < 1 || m_col_count < 1 ) return false; if ( 0 == m ) return false; return true; } int ON_Matrix::IsSquare() const { return ( m_row_count > 0 && m_col_count == m_row_count ) ? m_row_count : 0; } bool ON_Matrix::IsRowOrthoganal() const { double d0, d1, d; int i0, i1, j; double const*const* this_m = ThisM(); bool rc = ( m_row_count <= m_col_count && m_row_count > 0 ); for ( i0 = 0; i0 < m_row_count && rc; i0++ ) for ( i1 = i0+1; i1 < m_row_count && rc; i1++ ) { d0 = d1 = d = 0.0; for ( j = 0; j < m_col_count; j++ ) { d0 += fabs(this_m[i0][j]); d1 += fabs(this_m[i0][j]); d += this_m[i0][j]*this_m[i1][j]; } if ( d0 <= ON_EPSILON || d1 <= ON_EPSILON || fabs(d) >= d0*d1* ON_SQRT_EPSILON ) rc = false; } return rc; } bool ON_Matrix::IsRowOrthoNormal() const { double d; int i, j; bool rc = IsRowOrthoganal(); if ( rc ) { double const*const* this_m = ThisM(); for ( i = 0; i < m_row_count; i++ ) { d = 0.0; for ( j = 0; j < m_col_count; j++ ) { d += this_m[i][j]*this_m[i][j]; } if ( fabs(1.0-d) >= ON_SQRT_EPSILON ) rc = false; } } return rc; } bool ON_Matrix::IsColOrthoganal() const { double d0, d1, d; int i, j0, j1; bool rc = ( m_col_count <= m_row_count && m_col_count > 0 ); double const*const* this_m = ThisM(); for ( j0 = 0; j0 < m_col_count && rc; j0++ ) for ( j1 = j0+1; j1 < m_col_count && rc; j1++ ) { d0 = d1 = d = 0.0; for ( i = 0; i < m_row_count; i++ ) { d0 += fabs(this_m[i][j0]); d1 += fabs(this_m[i][j0]); d += this_m[i][j0]*this_m[i][j1]; } if ( d0 <= ON_EPSILON || d1 <= ON_EPSILON || fabs(d) > ON_SQRT_EPSILON ) rc = false; } return rc; } bool ON_Matrix::IsColOrthoNormal() const { double d; int i, j; bool rc = IsColOrthoganal(); double const*const* this_m = ThisM(); if ( rc ) { for ( j = 0; j < m_col_count; j++ ) { d = 0.0; for ( i = 0; i < m_row_count; i++ ) { d += this_m[i][j]*this_m[i][j]; } if ( fabs(1.0-d) >= ON_SQRT_EPSILON ) rc = false; } } return rc; } bool ON_Matrix::Invert( double zero_tolerance ) { ON_Workspace ws; int i, j, k, ix, jx, rank; double x; const int n = MinCount(); if ( n < 1 ) return false; ON_Matrix I(m_col_count, m_row_count); int* col = ws.GetIntMemory(n); I.SetDiagonal(1.0); rank = 0; double** this_m = ThisM(); for ( k = 0; k < n; k++ ) { // find largest value in sub matrix ix = jx = k; x = fabs(this_m[ix][jx]); for ( i = k; i < n; i++ ) { for ( j = k; j < n; j++ ) { if ( fabs(this_m[i][j]) > x ) { ix = i; jx = j; x = fabs(this_m[ix][jx]); } } } SwapRows( k, ix ); I.SwapRows( k, ix ); SwapCols( k, jx ); col[k] = jx; if ( x <= zero_tolerance ) { break; } x = 1.0/this_m[k][k]; this_m[k][k] = 1.0; ON_ArrayScale( m_col_count-k-1, x, &this_m[k][k+1], &this_m[k][k+1] ); I.RowScale( k, x ); // zero this_m[!=k][k]'s for ( i = 0; i < n; i++ ) { if ( i != k ) { x = -this_m[i][k]; this_m[i][k] = 0.0; if ( fabs(x) > zero_tolerance ) { ON_Array_aA_plus_B( m_col_count-k-1, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] ); I.RowOp( i, x, k ); } } } } // take care of column swaps for ( i = k-1; i >= 0; i-- ) { if ( i != col[i] ) I.SwapRows(i,col[i]); } *this = I; return (k == n) ? true : false; } bool ON_Matrix::Multiply( const ON_Matrix& a, const ON_Matrix& b ) { int i, j, k, mult_count; double x; if (a.ColCount() != b.RowCount() ) return false; if ( a.RowCount() < 1 || a.ColCount() < 1 || b.ColCount() < 1 ) return false; if ( this == &a ) { ON_Matrix tmp(a); return Multiply(tmp,b); } if ( this == &b ) { ON_Matrix tmp(b); return Multiply(a,tmp); } Create( a.RowCount(), b.ColCount() ); mult_count = a.ColCount(); double const*const* am = a.ThisM(); double const*const* bm = b.ThisM(); double** this_m = ThisM(); for ( i = 0; i < m_row_count; i++ ) for ( j = 0; j < m_col_count; j++ ) { x = 0.0; for (k = 0; k < mult_count; k++ ) { x += am[i][k] * bm[k][j]; } this_m[i][j] = x; } return true; } bool ON_Matrix::Add( const ON_Matrix& a, const ON_Matrix& b ) { int i, j; if (a.ColCount() != b.ColCount() ) return false; if (a.RowCount() != b.RowCount() ) return false; if ( a.RowCount() < 1 || a.ColCount() < 1 ) return false; if ( this != &a && this != &b ) { Create( a.RowCount(), b.ColCount() ); } double const*const* am = a.ThisM(); double const*const* bm = b.ThisM(); double** this_m = ThisM(); for ( i = 0; i < m_row_count; i++ ) for ( j = 0; j < m_col_count; j++ ) { this_m[i][j] = am[i][j] + bm[i][j]; } return true; } bool ON_Matrix::Scale( double s ) { bool rc = false; if ( m_row_count > 0 && m_col_count > 0 ) { struct DBLBLK* cmem = (struct DBLBLK*)m_cmem; int i; double* p; while ( 0 != cmem ) { if ( 0 != cmem->a && cmem->count > 0 ) { p = cmem->a; i = cmem->count; while(i--) *p++ *= s; } cmem = cmem->next; } rc = true; } /* int i = m_a.Capacity(); if ( m_row_count > 0 && m_col_count > 0 && m_row_count*m_col_count <= i ) { double* p = m_a.Array(); while ( i-- ) *p++ *= s; rc = true; } */ return rc; } int ON_RowReduce( int row_count, int col_count, double zero_pivot, double** A, double** B, double pivots[2] ) { // returned A is identity, B = inverse of input A const int M = row_count; const int N = col_count; const size_t sizeof_row = N*sizeof(A[0][0]); int i, j, ii; double a, p, p0, p1; const double* ptr0; double* ptr1; if ( pivots ) { pivots[0] = 0.0; pivots[1] = 0.0; } if ( zero_pivot <= 0.0 || !ON_IsValid(zero_pivot) ) zero_pivot = 0.0; for ( i = 0; i < M; i++ ) { memset(B[i],0,sizeof_row); if ( i < N ) B[i][i] = 1.0; } p0 = p1 = A[0][0]; for ( i = 0; i < M; i++ ) { p = fabs(a = A[i][i]); if ( p < p0 ) p0 = p; else if (p > p1) p1 = p; if ( 1.0 != a ) { if ( p <= zero_pivot || !ON_IsValid(a) ) { break; } a = 1.0/a; //A[i][i] = 1.0; // no need to do this // The "ptr" voodoo is faster but does the same thing as // //for ( j = i+1; j < N; j++ ) // A[i][j] *= a; // j = i+1; ptr1 = A[i] + j; j = N - j; while(j--) *ptr1++ *= a; // The "ptr" voodoo is faster but does the same thing as // //for ( j = 0; j <= i; j++ ) // B[i][j] *= a; // ptr1 = B[i]; j = i+1; while(j--) *ptr1++ *= a; } for ( ii = i+1; ii < M; ii++ ) { a = A[ii][i]; if ( 0.0 == a ) continue; a = -a; //A[ii][i] = 0.0; // no need to do this // The "ptr" voodoo is faster but does the same thing as // //for( j = i+1; j < N; j++ ) // A[ii][j] += a*A[i][j]; // j = i+1; ptr0 = A[i] + j; ptr1 = A[ii] + j; j = N - j; while(j--) *ptr1++ += a* *ptr0++; for( j = 0; j <= i; j++ ) B[ii][j] += a*B[i][j]; } } if ( pivots ) { pivots[0] = p0; pivots[1] = p1; } if ( i < M ) { return i; } // A is now upper triangular with all 1s on diagonal // (That is, if the lines that say "no need to do this" are used.) // B is lower triangular with a nonzero diagonal for ( i = M-1; i >= 0; i-- ) { for ( ii = i-1; ii >= 0; ii-- ) { a = A[ii][i]; if ( 0.0 == a ) continue; a = -a; //A[ii][i] = 0.0; // no need to do this // The "ptr" voodoo is faster but does the same thing as // //for( j = 0; j < N; j++ ) // B[ii][j] += a*B[i][j]; // ptr0 = B[i]; ptr1 = B[ii]; j = N; while(j--) *ptr1++ += a* *ptr0++; } } // At this point, A is trash. // If the input A was really nice (positive definite....) // the B = inverse of the input A. If A was not nice, // B is also trash. return M; } int ON_InvertSVDW( int count, const double* W, double*& invW ) { double w, maxw; int i; if ( 0 == W || count <= 0 ) return -1; if ( 0 == invW ) { invW = (double*)onmalloc(count*sizeof(invW[0])); } maxw = fabs(W[0]); for (i = 1; i < count; i++) { w = fabs(W[i]); if (w > maxw) maxw = w; } if (maxw == 0.0) { if ( W != invW ) memset(invW,0,count*sizeof(invW[0])); return 0; } i = 0; maxw *= ON_SQRT_EPSILON; while (count--) { if (fabs(W[count]) > maxw) { i++; invW[count] = 1.0/W[count]; } else invW[count] = 0.0; } return i; // number of nonzero terms in invW[] } bool ON_SolveSVD( int row_count, int col_count, double const * const * U, const double* invW, double const * const * V, const double* B, double*& X ) { int i, j; double *Y; const double* p0; double workY[128], x; if ( row_count < 1 || col_count < 1 || 0 == U || 0 == invW || 0 == V || 0 == B) return false; if ( 0 == X ) X = (double*)onmalloc(col_count*sizeof(X[0])); Y = (col_count > 128) ? ( (double*)onmalloc(col_count*sizeof(*Y)) ) : workY; for (i = 0; i < col_count; i++) { double y = 0.0; for (j = 0; j < row_count; j++) y += U[j][i] * *B++; B -= row_count; Y[i] = invW[i] * y; } for (i = 0; i < col_count; i++) { p0 = V[i]; j = col_count; x = 0.0; while (j--) x += *p0++ * *Y++; Y -= col_count; X[i] = x; } if (Y != workY) onfree(Y); return true; }
33,014
14,645
/* * Copyright (C) 2008, 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/core/v8/V8NodeFilterCondition.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/V8HiddenValue.h" #include "bindings/core/v8/V8Node.h" #include "core/dom/Node.h" #include "core/dom/NodeFilter.h" #include "wtf/OwnPtr.h" namespace blink { V8NodeFilterCondition::V8NodeFilterCondition(v8::Handle<v8::Value> filter, v8::Handle<v8::Object> owner, ScriptState* scriptState) : m_scriptState(scriptState) { // ..acceptNode(..) will only dispatch m_filter if m_filter->IsObject(). // We'll make sure m_filter is either usable by acceptNode or empty. // (See the fast/dom/node-filter-gc test for a case where 'empty' happens.) if (!filter.IsEmpty() && filter->IsObject()) { V8HiddenValue::setHiddenValue(scriptState->isolate(), owner, V8HiddenValue::condition(scriptState->isolate()), filter); m_filter.set(scriptState->isolate(), filter); m_filter.setWeak(this, &setWeakCallback); } } V8NodeFilterCondition::~V8NodeFilterCondition() { } short V8NodeFilterCondition::acceptNode(Node* node, ExceptionState& exceptionState) const { v8::Isolate* isolate = m_scriptState->isolate(); ASSERT(!m_scriptState->context().IsEmpty()); v8::HandleScope handleScope(isolate); v8::Handle<v8::Value> filter = m_filter.newLocal(isolate); ASSERT(filter.IsEmpty() || filter->IsObject()); if (filter.IsEmpty()) return NodeFilter::FILTER_ACCEPT; v8::TryCatch exceptionCatcher; v8::Handle<v8::Function> callback; if (filter->IsFunction()) { callback = v8::Handle<v8::Function>::Cast(filter); } else { v8::Local<v8::Value> value = filter->ToObject(isolate)->Get(v8AtomicString(isolate, "acceptNode")); if (value.IsEmpty() || !value->IsFunction()) { exceptionState.throwTypeError("NodeFilter object does not have an acceptNode function"); return NodeFilter::FILTER_REJECT; } callback = v8::Handle<v8::Function>::Cast(value); } OwnPtr<v8::Handle<v8::Value>[]> info = adoptArrayPtr(new v8::Handle<v8::Value>[1]); v8::Handle<v8::Object> context = m_scriptState->context()->Global(); info[0] = toV8(node, context, isolate); v8::Handle<v8::Value> result = ScriptController::callFunction(m_scriptState->executionContext(), callback, context, 1, info.get(), isolate); if (exceptionCatcher.HasCaught()) { exceptionState.rethrowV8Exception(exceptionCatcher.Exception()); return NodeFilter::FILTER_REJECT; } ASSERT(!result.IsEmpty()); return result->Int32Value(); } void V8NodeFilterCondition::setWeakCallback(const v8::WeakCallbackData<v8::Value, V8NodeFilterCondition>& data) { data.GetParameter()->m_filter.clear(); } } // namespace blink
4,364
1,465
// This file is generated by Ubpa::USRefl::AutoRefl #pragma once #include <USRefl/USRefl.h> template<> struct Ubpa::USRefl::TypeInfo<Ubpa::UECS::SingletonsView> : TypeInfoBase<Ubpa::UECS::SingletonsView> { #ifdef UBPA_USREFL_NOT_USE_NAMEOF static constexpr char name[27] = "Ubpa::UECS::SingletonsView"; #endif static constexpr AttrList attrs = {}; static constexpr FieldList fields = { Field {TSTR(UMeta::constructor), WrapConstructor<Type(Span<const UECS::CmptAccessPtr>)>()}, Field {TSTR("GetSingleton"), &Type::GetSingleton}, Field {TSTR("Singletons"), &Type::Singletons}, }; };
630
231
// -*- C++ -*- // Grid_i.cpp,v 1.20 2001/04/02 18:12:24 kitty Exp #include "Grid_i.h" #include "tao/corba.h" // Default constructor. Grid_i::Grid_i (void) : width_ (0), height_ (0), array_ (0) { //no-op } // Constructor. Grid_i::Grid_i (CORBA::Short x, CORBA::Short y, CORBA::Environment &ACE_TRY_ENV) : width_ (x), height_ (y) { ACE_NEW_THROW_EX (array_, CORBA::Long *[y], CORBA::NO_MEMORY ()); ACE_CHECK; // Allocate memory for the matrix. for (int ctr = 0; ctr < y; ctr++) { ACE_NEW_THROW_EX (array_[ctr], CORBA::Long[x], CORBA::NO_MEMORY ()); ACE_CHECK; } } // Default destructor. Grid_i::~Grid_i (void) { // no-op. } // Set a value in the grid. void Grid_i::set (CORBA::Short x, CORBA::Short y, CORBA::Long value, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException, Grid::RANGE_ERROR)) { if (x < 0 || y < 0 || x >= width_ || y >= height_) ACE_THROW (Grid::RANGE_ERROR ()); else array_[x][y] = value; } // Get a value from the grid. CORBA::Long Grid_i::get (CORBA::Short x, CORBA::Short y, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException, Grid::RANGE_ERROR)) { if (x < 0 || y < 0 || x >= width_ || y >= height_) ACE_THROW_RETURN (Grid::RANGE_ERROR (), -1); else return array_[x][y]; } // Access methods. CORBA::Short Grid_i::width (CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { return this->width_; } CORBA::Short Grid_i::height (CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { return this->height_; } void Grid_i::width (CORBA::Short x, CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { this->width_ = x; } void Grid_i::height (CORBA::Short y, CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { this->height_ = y; } // Destroy the grid void Grid_i::destroy (CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { // Delete the array. for (int i = 0; i < height_; i++) delete [] array_[i]; delete [] array_; ACE_DEBUG ((LM_DEBUG, "(%P|%t) %s\n", "Grid has been destroyed")); } // Set the ORB pointer. void Grid_Factory_i::orb (CORBA::ORB_ptr o) { this->orb_ = CORBA::ORB::_duplicate (o); } // Shutdown. void Grid_Factory_i::shutdown (CORBA::Environment &) ACE_THROW_SPEC ((CORBA::SystemException)) { ACE_DEBUG ((LM_DEBUG, "(%P|%t) %s\n", "Grid Factory is shutting down")); // Instruct the ORB to shutdown. this->orb_->shutdown (); } // Constructor Grid_Factory_i::Grid_Factory_i (void) { // no-op } // Copy Constructor Grid_Factory_i::Grid_Factory_i (Grid_Factory_i &grid) :POA_Grid_Factory (grid) { // no-op } // Destructor Grid_Factory_i::~Grid_Factory_i (void) { // no-op } // Make a <Grid>. Grid_ptr Grid_Factory_i::make_grid (CORBA::Short width, CORBA::Short height, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)) { Grid_i *grid_ptr = 0; ACE_DEBUG ((LM_DEBUG, "(%P|%t) Making a new Grid\n")); // Set a default value for width. if (width <= 0) width = Grid_Factory::DEFAULT_WIDTH; // Set a default value for height. if (height <= 0) height = Grid_Factory::DEFAULT_HEIGHT; // This attempts to create a new Grid_i and throws an exception and // returns a null value if it fails CORBA::Environment &env = ACE_TRY_ENV; ACE_NEW_THROW_EX (grid_ptr, Grid_i (width, height, env), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (Grid::_nil ()); // Register the Grid pointer. Grid_ptr gptr = grid_ptr->_this (ACE_TRY_ENV); ACE_CHECK_RETURN (0); return gptr; }
4,241
1,746
/* * Copyright (C) 2020 The Android Open Source Project * * 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 <mathio/ostream.h> #include <math/mat2.h> #include <math/mat3.h> #include <math/mat4.h> #include <math/vec2.h> #include <math/vec3.h> #include <math/vec4.h> #include <math/quat.h> #include <math/half.h> #include <iomanip> #include <ostream> #include <string> namespace filament { namespace math { namespace details { template<typename T> std::ostream& printVector(std::ostream& stream, const T* data, size_t count) { stream << "< "; for (size_t i = 0; i < count - 1; i++) { stream << data[i] << ", "; } stream << data[count - 1] << " >"; return stream; } template<typename T> std::ostream& printMatrix(std::ostream& stream, const T* m, size_t rows, size_t cols) { for (size_t row = 0; row < rows; ++row) { if (row != 0) { stream << std::endl; } if (row == 0) { stream << "/ "; } else if (row == rows - 1) { stream << "\\ "; } else { stream << "| "; } for (size_t col = 0; col < cols; ++col) { stream << std::setw(10) << std::to_string(m[row + col * rows]); } if (row == 0) { stream << " \\"; } else if (row == rows - 1) { stream << " /"; } else { stream << " |"; } } return stream; } template<template<typename T> class BASE, typename T> std::ostream& printQuat(std::ostream& stream, const BASE<T>& q) { return stream << "< " << q.w << " + " << q.x << "i + " << q.y << "j + " << q.z << "k >"; } } // namespace details using namespace details; template<typename T> std::ostream& operator<<(std::ostream& out, const details::TVec2<T>& v) noexcept { return printVector(out, v.v, 2); } template<typename T> std::ostream& operator<<(std::ostream& out, const details::TVec3<T>& v) noexcept { return printVector(out, v.v, 3); } template<typename T> std::ostream& operator<<(std::ostream& out, const details::TVec4<T>& v) noexcept { return printVector(out, v.v, 4); } template<typename T> std::ostream& operator<<(std::ostream& out, const details::TMat22<T>& v) noexcept { return printMatrix(out, v.asArray(), 2, 2); } template<typename T> std::ostream& operator<<(std::ostream& out, const details::TMat33<T>& v) noexcept { return printMatrix(out, v.asArray(), 3, 3); } template<typename T> std::ostream& operator<<(std::ostream& out, const details::TMat44<T>& v) noexcept { return printMatrix(out, v.asArray(), 4, 4); } template std::ostream& operator<<(std::ostream& out, const details::TVec2<double>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<float>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<half>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<uint32_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<int32_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<uint16_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<int16_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<uint8_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<int8_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec2<bool>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<double>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<float>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<half>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<uint32_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<int32_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<uint16_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<int16_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<uint8_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<int8_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec3<bool>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<double>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<float>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<half>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<uint32_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<int32_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<uint16_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<int16_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<uint8_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<int8_t>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TVec4<bool>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TMat22<double>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TMat22<float>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TMat33<double>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TMat33<float>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TMat44<double>& v) noexcept; template std::ostream& operator<<(std::ostream& out, const details::TMat44<float>& v) noexcept; } // namespace math } // namespace filament
6,639
2,215
// Copyright 2015 Patrick Putnam // // 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 DEVICE_SEQUENCE_SPACE_KERNELS_HPP_ #define DEVICE_SEQUENCE_SPACE_KERNELS_HPP_ #include "clotho/cuda/data_spaces/sequence_space/device_sequence_space_def.hpp" #include "clotho/cuda/data_spaces/sequence_space/device_sequence_space_kernel_api.hpp" template < class IntType > __device__ void _resize_space_impl( device_sequence_space< IntType > * sspace, unsigned int cols, unsigned int rows ) { // assert( blockIdx.y * gridDim.x + blockIdx.x == 0); // assert( threadIdx.y * blockDim.x + threadIdx.x == 0 ); typedef typename device_sequence_space< IntType >::int_type int_type; unsigned int N = cols * rows; if( sspace->capacity < N ) { int_type * seqs = sspace->sequences; if( seqs ) { delete seqs; } seqs = new int_type[ N ]; assert( seqs != NULL ); sspace->sequences = seqs; sspace->capacity = N; } sspace->size = N; sspace->seq_count = rows; sspace->seq_width = cols; } template < class IntType > __global__ void _resize_space( device_sequence_space< IntType > * sspace, unsigned int cols, unsigned int rows = 1 ) { assert( blockIdx.y * gridDim.x + blockIdx.x == 0 ); if( threadIdx.y * blockDim.x + threadIdx.x == 0 ) { _resize_space_impl( sspace, cols, rows ); } }; template < class IntType, class ColumnSpaceType > __global__ void _resize_space( device_sequence_space< IntType > * sspace, ColumnSpaceType * aspace, unsigned int seq_count ) { assert( blockIdx.y * gridDim.x + blockIdx.x == 0 ); if( threadIdx.y * blockDim.x + threadIdx.x == 0 ) { typedef device_sequence_space< IntType > space_type; typedef typename space_type::int_type int_type; unsigned int W = aspace->capacity; W /= space_type::OBJECTS_PER_INT; _resize_space_impl( sspace, W, seq_count ); } } template < class IntType > __global__ void _delete_space( device_sequence_space< IntType > * sspace ) { if( sspace->sequences != NULL ) { delete sspace->sequences; } } #endif // DEVICE_SEQUENCE_SPACE_KERNELS_HPP_
2,705
924
/****************************************************************************** * Copyright (c) 2017 Philipp Schubert. * All rights reserved. This program and the accompanying materials are made * available under the terms of LICENSE.txt. * * Contributors: * Philipp Schubert and others *****************************************************************************/ #include <stdexcept> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/throw_exception.hpp> #include <clang/Tooling/CommonOptionsParser.h> #include <clang/Tooling/CompilationDatabase.h> #include <clang/Tooling/Tooling.h> #include <llvm/Support/CommandLine.h> #include <phasar/Config/Configuration.h> #include <phasar/Controller/AnalysisController.h> #include <phasar/DB/ProjectIRDB.h> #include <phasar/PhasarClang/ClangController.h> #include <phasar/PhasarLLVM/ControlFlow/ICFG.h> #include <phasar/PhasarLLVM/Passes/GeneralStatisticsPass.h> #include <phasar/PhasarLLVM/Plugins/Interfaces/IfdsIde/IDETabulationProblemPlugin.h> #include <phasar/PhasarLLVM/Plugins/Interfaces/IfdsIde/IFDSTabulationProblemPlugin.h> #include <phasar/PhasarLLVM/Plugins/Interfaces/Mono/InterMonoProblemPlugin.h> #include <phasar/PhasarLLVM/Plugins/Interfaces/Mono/IntraMonoProblemPlugin.h> #include <phasar/PhasarLLVM/Utils/DataFlowAnalysisType.h> #include <phasar/Utils/EnumFlags.h> #include <phasar/Utils/Logger.h> #include <phasar/Utils/PAMMMacros.h> namespace bpo = boost::program_options; namespace bfs = boost::filesystem; using namespace std; using namespace psr; // setup programs command line options (via Clang) static llvm::cl::OptionCategory StaticAnalysisCategory("Static Analysis"); static llvm::cl::extrahelp CommonHelp( clang::tooling::CommonOptionsParser::HelpMessage); llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::Optional; static const string MORE_PHASAR_LLVM_HELP( #include "../phasar-llvm_more_help.txt" ); static const string MORE_PHASAR_CLANG_HELP(""); namespace boost { void throw_exception(std::exception const &e) {} } // namespace boost // functions for parameter validation void validateParamModule(const std::vector<std::string> &modules) { for (const auto &module : modules) { if (!(bfs::exists(module) && !bfs::is_directory(module))) { throw bpo::error_with_option_name("'" + module + "' is not a valid module"); } } } void validateParamProject(const std::string &project) { if (!(bfs::exists(project) && bfs::is_directory(project) && bfs::exists(bfs::path(project) / CompileCommandsJson))) { throw bpo::error_with_option_name("'" + project + "' is not a valid project"); } } void validateParamDataFlowAnalysis(const std::vector<std::string> &dfa) { for (const auto &analysis : dfa) { if (StringToDataFlowAnalysisType.count(analysis) == 0) { throw bpo::error_with_option_name("'" + analysis + "' is not a valid data-flow analysis"); } } } void validateParamPointerAnalysis(const std::string &pta) { if (StringToPointerAnalysisType.count(pta) == 0) { throw bpo::error_with_option_name("'" + pta + "' is not a valid pointer analysis"); } } void validateParamCallGraphAnalysis(const std::string &cga) { if (StringToCallGraphAnalysisType.count(cga) == 0) { throw bpo::error_with_option_name("'" + cga + "' is not a valid call-graph analysis"); } } void validateParamExport(const std::string &exp) { if (StringToExportType.count(exp) == 0) { throw bpo::error_with_option_name("'" + exp + "' is not a valid export parameter"); } } void validateParamAnalysisPlugin(const std::vector<std::string> &plugins) { for (const auto &plugin : plugins) { if (!bfs::exists(plugin) && !bfs::is_directory(plugin) && bfs::extension(plugin) == ".so") { throw bpo::error_with_option_name( "'" + plugin + "' is not a valid shared object library"); } } } void validateParamICFGPlugin(const std::string &plugin) { if (!bfs::exists(plugin) && !bfs::is_directory(plugin) && bfs::extension(plugin) == ".so") { throw bpo::error_with_option_name("'" + plugin + "' is not a valid shared object library"); } if (VariablesMap.count("callgraph-analysis")) { throw bpo::error_with_option_name( "Cannot choose a built-in callgraph AND " "a plug-in for callgraph construction."); } if (VariablesMap.count("wpa") && !VariablesMap["wpa"].as<bool>()) { throw bpo::error_with_option_name( "Plug-in for callgraph construction can only be used in 'wpa' mode."); } } void validateParamConfig(const std::string &cfg) { if (!(bfs::exists(cfg) && !bfs::is_directory(cfg))) { throw bpo::error_with_option_name("'" + cfg + "' does not exist"); } } void validateParamOutput(const std::string &filename) { if (bfs::exists(filename)) { if (bfs::is_directory(filename)) { throw bpo::error_with_option_name("'" + filename + "' is a directory"); } } } void validateParamGraphID(const std::string &graphID) { // TODO perform some validation } void validateParamProjectID(const std::string &projectID) { // TODO perform some validation } void validateParamMode(const std::string &mode) { if (mode != "phasarLLVM" && mode != "phasarClang") { throw bpo::error_with_option_name( "Phasar operation mode must be either 'phasarLLVM' or 'phasarClang', " "but is: '" + mode + "'"); } } template <typename T> ostream &operator<<(ostream &os, const std::vector<T> &v) { copy(v.begin(), v.end(), ostream_iterator<T>(os, " ")); return os; } int main(int argc, const char **argv) { PAMM_GET_INSTANCE; START_TIMER("Phasar Runtime", PAMM_SEVERITY_LEVEL::Core); // set-up the logger and get a reference to it initializeLogger(false); auto &lg = lg::get(); // handling the command line parameters LOG_IF_ENABLE(BOOST_LOG_SEV(lg, DEBUG) << "Set-up the command-line parameters"); // Here we start creating Phasars top level operation mode: // Based on the mode, we delegate to the further subtools and their // corresponding argument parsers. bpo::variables_map ModeMap; bpo::options_description PhasarMode("Phasar operation mode"); // clang-format off PhasarMode.add_options() ("mode", bpo::value<std::string>()->notifier(validateParamMode), "Set the operation mode: 'phasarLLVM' or 'phasarClang'"); // clang-format on bpo::options_description ModeOptions; ModeOptions.add(PhasarMode); try { // Just parse the mode options and ignore everythin else, since the other // parsers deal with it bpo::store(bpo::command_line_parser(argc, argv) .options(ModeOptions) .allow_unregistered() .run(), ModeMap); bpo::notify(ModeMap); } catch (const bpo::error &e) { std::cerr << "error: could not parse program options\n" "message: " << e.what() << ", abort\n"; return 1; } // Make sure an operation mode has been set // If it has not been set explicitly by the user, then use // phasarLLVM as default. if (!ModeMap.count("mode")) { ModeMap.insert( make_pair("mode", bpo::variable_value(string("phasarLLVM"), false))); } // Next we can check what operation mode was chosen and resume accordingly: if (ModeMap["mode"].as<std::string>() == "phasarLLVM") { // --- LLVM mode --- LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Chosen operation mode: 'phasarLLVM'"); try { std::string ConfigFile; // Declare a group of options that will be allowed only on command line bpo::options_description Generic("Command-line options"); // clang-format off Generic.add_options() ("help,h", "Print help message") ("more_help", "Print more help") ("config", bpo::value<std::string>(&ConfigFile)->notifier(validateParamConfig), "Path to the configuration file, options can be specified as 'parameter = option'") ("silent", "Suppress any non-result output"); // clang-format on // Declare a group of options that will be allowed both on command line // and in config file bpo::options_description Config("Configuration file options"); // clang-format off Config.add_options() ("swift,s", bpo::value<bool>()->default_value(0),"Swift-aware analysis mode (1 or 0)") ("function,f", bpo::value<std::string>(), "Function under analysis (a mangled function name)") ("module,m", bpo::value<std::vector<std::string>>()->multitoken()->zero_tokens()->composing()->notifier(validateParamModule), "Path to the module(s) under analysis") ("entry-points,E", bpo::value<std::vector<std::string>>()->multitoken()->zero_tokens()->composing(), "Set the entry point(s) to be used") ("output,O", bpo::value<std::string>()->notifier(validateParamOutput)->default_value("results.json"), "Filename for the results") ("data-flow-analysis,D", bpo::value<std::vector<std::string>>()->multitoken()->zero_tokens()->composing()->notifier(validateParamDataFlowAnalysis), "Set the analysis to be run") ("pointer-analysis,P", bpo::value<std::string>()->notifier(validateParamPointerAnalysis), "Set the points-to analysis to be used (CFLSteens, CFLAnders)") ("callgraph-analysis,C", bpo::value<std::string>()->notifier(validateParamCallGraphAnalysis), "Set the call-graph algorithm to be used (CHA, RTA, DTA, VTA, OTF)") ("classhierachy-analysis,H", bpo::value<bool>(), "Class-hierarchy analysis") ("vtable-analysis,V", bpo::value<bool>(), "Virtual function table analysis") ("statistical-analysis,S", bpo::value<bool>(), "Statistics") //("export,E", bpo::value<std::string>()->notifier(validateParamExport), "Export mode (TODO: yet to implement!)") ("wpa,W", bpo::value<bool>()->default_value(1), "Whole-program analysis mode (1 or 0)") ("mem2reg,M", bpo::value<bool>()->default_value(1), "Promote memory to register pass (1 or 0)") ("printedgerec,R", bpo::value<bool>()->default_value(0), "Print exploded-super-graph edge recorder (1 or 0)") #ifdef PHASAR_PLUGINS_ENABLED ("analysis-plugin", bpo::value<std::vector<std::string>>()->notifier(validateParamAnalysisPlugin), "Analysis plugin(s) (absolute path to the shared object file(s))") ("callgraph-plugin", bpo::value<std::string>()->notifier(validateParamICFGPlugin), "ICFG plugin (absolute path to the shared object file)") #endif ("project-id", bpo::value<std::string>()->default_value("myphasarproject")->notifier(validateParamProjectID), "Project Id used for the database") ("graph-id", bpo::value<std::string>()->default_value("123456")->notifier(validateParamGraphID), "Graph Id used by the visualization framework") ("pamm-out", bpo::value<std::string>()->notifier(validateParamOutput)->default_value("PAMM_data.json"), "Filename for PAMM's gathered data"); // clang-format on bpo::options_description CmdlineOptions; CmdlineOptions.add(PhasarMode).add(Generic).add(Config); bpo::options_description ConfigFileOptions; ConfigFileOptions.add(Config); bpo::options_description Visible("Allowed options"); Visible.add(Generic).add(Config); bpo::store( bpo::command_line_parser(argc, argv).options(CmdlineOptions).run(), VariablesMap); bpo::notify(VariablesMap); ifstream ifs(ConfigFile.c_str()); if (!ifs) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "No configuration file is used."); } else { LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Using configuration file: " << ConfigFile); bpo::store(bpo::parse_config_file(ifs, ConfigFileOptions), VariablesMap); bpo::notify(VariablesMap); } // Vanity header if (!VariablesMap.count("silent")) { std::cout << PhasarVersion << "\n" "A LLVM-based static analysis framework\n\n"; } // check if we have anything at all or a call for help if ((argc < 3 || VariablesMap.count("help")) && !VariablesMap.count("silent")) { std::cout << Visible << '\n'; return 0; } LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Program options have been successfully parsed."); bl::core::get()->flush(); if (!VariablesMap.count("silent")) { // Print current configuration if (VariablesMap.count("more_help")) { if (!VariablesMap.count("help")) { std::cout << Visible << '\n'; } std::cout << MORE_PHASAR_LLVM_HELP << '\n'; return 0; } std::cout << "--- Configuration ---\n"; if (VariablesMap.count("config")) { std::cout << "Configuration file: " << VariablesMap["config"].as<std::string>() << '\n'; } if (VariablesMap.count("swift")) { if (VariablesMap["swift"].as<bool>()) { psr::DefaultSourceSinkFunctionsPath = (psr::PhasarPath + "/config/swift-source-sink-function.json"); } std::cout << "Swift analysis: " << VariablesMap["swift"].as<bool>() << '\n'; std::cout << "Source/Sink JSON file: " << bfs::path(psr::DefaultSourceSinkFunctionsPath).filename() << '\n'; } if (VariablesMap.count("project-id")) { std::cout << "Project ID: " << VariablesMap["project-id"].as<std::string>() << '\n'; } if (VariablesMap.count("graph-id")) { std::cout << "Graph ID: " << VariablesMap["graph-id"].as<std::string>() << '\n'; } if (VariablesMap.count("function")) { std::cout << "Function: " << VariablesMap["function"].as<std::string>() << '\n'; } if (VariablesMap.count("module")) { std::cout << "Module(s): " << VariablesMap["module"].as<std::vector<std::string>>() << '\n'; } if (VariablesMap.count("data-flow-analysis")) { std::cout << "Data-flow analysis: " << VariablesMap["data-flow-analysis"] .as<std::vector<std::string>>() << '\n'; } if (VariablesMap.count("pointer-analysis")) { std::cout << "Pointer analysis: " << VariablesMap["pointer-analysis"].as<std::string>() << '\n'; } if (VariablesMap.count("callgraph-analysis")) { std::cout << "Callgraph analysis: " << VariablesMap["callgraph-analysis"].as<std::string>() << '\n'; } if (VariablesMap.count("entry-points")) { std::cout << "Entry points: " << VariablesMap["entry-points"].as<std::vector<std::string>>() << '\n'; } if (VariablesMap.count("classhierarchy_analysis")) { std::cout << "Classhierarchy analysis: " << VariablesMap["classhierarchy_analysis"].as<bool>() << '\n'; } if (VariablesMap.count("vtable-analysis")) { std::cout << "Vtable analysis: " << VariablesMap["vtable-analysis"].as<bool>() << '\n'; } if (VariablesMap.count("statistical-analysis")) { std::cout << "Statistical analysis: " << VariablesMap["statistical-analysis"].as<bool>() << '\n'; } if (VariablesMap.count("export")) { std::cout << "Export: " << VariablesMap["export"].as<std::string>() << '\n'; } if (VariablesMap.count("wpa")) { std::cout << "WPA: " << VariablesMap["wpa"].as<bool>() << '\n'; } if (VariablesMap.count("mem2reg")) { std::cout << "Mem2reg: " << VariablesMap["mem2reg"].as<bool>() << '\n'; } if (VariablesMap.count("printedgerec")) { std::cout << "Print edge recorder: " << VariablesMap["printedgerec"].as<bool>() << '\n'; } if (VariablesMap.count("analysis-plugin")) { std::cout << "Analysis plugin(s): \n"; for (const auto &analysis_plugin : VariablesMap["analysis-plugin"].as<std::vector<std::string>>()) { std::cout << analysis_plugin << '\n'; } } if (VariablesMap.count("output")) { std::cout << "Output: " << VariablesMap["output"].as<std::string>() << '\n'; } if (VariablesMap.count("output-pamm")) { std::cout << "Output PAMM: " << VariablesMap["output-pamm"].as<std::string>() << '\n'; } } else { setLoggerFilterLevel(INFO); } // Validation LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Check program options for logical errors."); // validate the logic of the command-line arguments if (!VariablesMap.count("module")) { std::cerr << "A module must be specified for an analysis.\n"; return 1; } // Plugin Validation if (VariablesMap.count("data-flow-analysis")) { if (find(VariablesMap["data-flow-analysis"] .as<std::vector<std::string>>() .begin(), VariablesMap["data-flow-analysis"] .as<std::vector<std::string>>() .end(), "plugin") != VariablesMap["data-flow-analysis"] .as<std::vector<std::string>>() .end() && (!VariablesMap.count("analysis-plugin"))) { std::cerr << "If an analysis plugin is chosen, the plugin itself must also " "be specified.\n"; return 1; } } } catch (const bpo::error &e) { std::cerr << "error: could not parse program options\n" "message: " << e.what() << ", abort\n"; return 1; } // Set chosen dfa std::vector<DataFlowAnalysisType> ChosenDataFlowAnalyses = { DataFlowAnalysisType::None}; if (VariablesMap.count("data-flow-analysis")) { ChosenDataFlowAnalyses.clear(); for (auto &DataFlowAnalysis : VariablesMap["data-flow-analysis"].as<std::vector<std::string>>()) { if (StringToDataFlowAnalysisType.count(DataFlowAnalysis)) { ChosenDataFlowAnalyses.push_back( StringToDataFlowAnalysisType.at(DataFlowAnalysis)); } } } #ifdef PHASAR_PLUGINS_ENABLED // Check if user has specified an analysis plugin if (!IDETabulationProblemPluginFactory.empty() || !IFDSTabulationProblemPluginFactory.empty() || !IntraMonoProblemPluginFactory.empty() || !InterMonoProblemPluginFactory.empty()) { ChosenDataFlowAnalyses.push_back(DataFlowAnalysisType::Plugin); } #endif // At this point we have set-up all the parameters and can start the actual // analyses that have been choosen. AnalysisController Controller( [&lg]() { PAMM_GET_INSTANCE; START_TIMER("IRDB Construction", PAMM_SEVERITY_LEVEL::Full); LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Set-up IR database."); IRDBOptions Opt = IRDBOptions::NONE; if (VariablesMap["wpa"].as<bool>()) { Opt |= IRDBOptions::WPA; } if (VariablesMap["mem2reg"].as<bool>()) { Opt |= IRDBOptions::MEM2REG; } ProjectIRDB IRDB( VariablesMap["module"].as<std::vector<std::string>>(), Opt); STOP_TIMER("IRDB Construction", PAMM_SEVERITY_LEVEL::Full); return IRDB; }(), ChosenDataFlowAnalyses, VariablesMap["wpa"].as<bool>(), VariablesMap["printedgerec"].as<bool>(), VariablesMap["graph-id"].as<std::string>()); LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Write results to file"); Controller.writeResults(VariablesMap["output"].as<std::string>()); } else { // -- Clang mode --- LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Chosen operation mode: 'phasarClang'"); std::string ConfigFile; // Declare a group of options that will be allowed only on command line bpo::options_description Generic("Command-line options"); // clang-format off Generic.add_options() ("help,h", "Print help message") ("config", bpo::value<std::string>(&ConfigFile)->notifier(validateParamConfig), "Path to the configuration file, options can be specified as 'parameter = option'"); // clang-format on // Declare a group of options that will be allowed both on command line and // in config file bpo::options_description Config("Configuration file options"); // clang-format off Config.add_options() ("project,p", bpo::value<std::string>()->notifier(validateParamProject), "Path to the project under analysis"); // clang-format on bpo::options_description CmdlineOptions; CmdlineOptions.add(PhasarMode).add(Generic).add(Config); bpo::options_description ConfigFileOptions; ConfigFileOptions.add(Config); bpo::options_description Visible("Allowed options"); Visible.add(Generic).add(Config); bpo::store( bpo::command_line_parser(argc, argv).options(CmdlineOptions).run(), VariablesMap); bpo::notify(VariablesMap); ifstream ifs(ConfigFile.c_str()); if (!ifs) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "No configuration file is used."); } else { LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Using configuration file: " << ConfigFile); bpo::store(bpo::parse_config_file(ifs, ConfigFileOptions), VariablesMap); bpo::notify(VariablesMap); } // check if we have anything at all or a call for help if (argc < 3 || VariablesMap.count("help")) { std::cout << Visible << '\n'; return 0; } // Print what has been parsed if (VariablesMap.count("project")) { std::cout << "Project: " << VariablesMap["project"].as<std::string>() << '\n'; } // Bring Clang source-to-source transformation to life if (VariablesMap.count("project")) { int OnlyTakeCareOfSources = 2; const char *ProjectSources = VariablesMap["project"].as<std::string>().c_str(); const char *DummyProgName = "not_important"; const char *DummyArgs[] = {DummyProgName, ProjectSources}; clang::tooling::CommonOptionsParser OptionsParser( OnlyTakeCareOfSources, DummyArgs, StaticAnalysisCategory, OccurrencesFlag); // At this point we have set-up all the parameters and can start the // actual // analyses that have been choosen. ClangController CC(OptionsParser); } } LOG_IF_ENABLE(BOOST_LOG_SEV(lg, INFO) << "Shutdown llvm and the analysis framework."); // free all resources handled by llvm llvm::llvm_shutdown(); // flush the log core at last (performs flush() on all registered sinks) bl::core::get()->flush(); STOP_TIMER("Phasar Runtime", PAMM_SEVERITY_LEVEL::Core); // PRINT_MEASURED_DATA(std::cout); EXPORT_MEASURED_DATA(VariablesMap["pamm-out"].as<std::string>()); return 0; }
23,828
7,313
// @HEADER // *********************************************************************** // // Sacado Package // Copyright (2006) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 // USA // Questions? Contact David M. Gay (dmgay@sandia.gov) or Eric T. Phipps // (etphipp@sandia.gov). // // *********************************************************************** // @HEADER #ifndef SACADO_LFAD_LOGICALSPARSE_HPP #define SACADO_LFAD_LOGICALSPARSE_HPP #include "Sacado_LFad_LogicalSparseTraits.hpp" #include "Sacado_LFad_ExpressionTraits.hpp" #include "Sacado_Fad_DynamicStorage.hpp" namespace Sacado { //! Namespace for logical forward-mode AD classes namespace LFad { //! Wrapper for a generic expression template /*! * This template class serves as a wrapper for all Fad expression * template classes. */ template <typename ExprT> class Expr {}; //! Meta-function for determining nesting with an expression /*! * This determines the level of nesting within nested Fad types. * The default implementation works for any type that isn't a Fad type * or an expression of Fad types. */ template <typename T> struct ExprLevel { static const unsigned value = 0; }; template <typename T> struct ExprLevel< Expr<T> > { static const unsigned value = ExprLevel< typename Expr<T>::value_type >::value + 1; }; //! Determine whether a given type is an expression template <typename T> struct IsFadExpr { static const bool value = false; }; template <typename T> struct IsFadExpr< Expr<T> > { static const bool value = true; }; // Forward declaration template <typename ValT, typename LogT> class LogicalSparse; /*! * \brief Implementation class for computing the logical sparsity of a * derivative using forward-mode AD. */ template <typename ValT, typename LogT> class LogicalSparseImp : public Fad::DynamicStorage<ValT,LogT> { typedef Fad::DynamicStorage<ValT,LogT> Storage; public: //! Typename of values (e.g., double) typedef ValT value_type; //! Typename of scalar's (which may be different from ValT) typedef typename ScalarType<value_type>::type scalar_type; //! Logical type (i.e., type for derivative array components (e.g., bool) typedef LogT logical_type; /*! * @name Initialization methods */ //@{ //! Default constructor LogicalSparseImp() : Storage(value_type(0)) {} //! Constructor with supplied value \c x /*! * Initializes value to \c x and derivative array is empty */ template <typename S> LogicalSparseImp(const S& x, SACADO_ENABLE_VALUE_CTOR_DECL) : Storage(x) {} //! Constructor with size \c sz and value \c x /*! * Initializes value to \c x and derivative array 0 of length \c sz */ LogicalSparseImp(const int sz, const value_type & x) : Storage(sz, x, InitDerivArray) {} //! Constructor with size \c sz, index \c i, and value \c x /*! * Initializes value to \c x and derivative array of length \c sz * as row \c i of the identity matrix, i.e., sets derivative component * \c i to 1 and all other's to zero. */ LogicalSparseImp(const int sz, const int i, const value_type & x) : Storage(sz, x, InitDerivArray) { this->fastAccessDx(i)=logical_type(1); } //! Copy constructor LogicalSparseImp(const LogicalSparseImp& x) : Storage(x) {} //! Copy constructor from any Expression object template <typename S> LogicalSparseImp(const Expr<S>& x, SACADO_ENABLE_EXPR_CTOR_DECL) : Storage(value_type(0)) { int sz = x.size(); if (sz != this->size()) this->resize(sz); if (sz) { if (x.hasFastAccess()) for(int i=0; i<sz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); else for(int i=0; i<sz; ++i) this->fastAccessDx(i) = x.dx(i); } this->val() = x.val(); } //! Destructor ~LogicalSparseImp() {} //! Set %LogicalSparseImp object as the \c ith independent variable /*! * Sets the derivative array of length \c n to the \c ith row of the * identity matrix and has the same affect as the * Implementation(const int sz, const int i, const T & x) * constructor. */ void diff(const int ith, const int n) { if (this->size() != n) this->resize(n); this->zero(); this->fastAccessDx(ith) = logical_type(1); } //! Returns whether two Fad objects have the same values template <typename S> SACADO_ENABLE_EXPR_FUNC(bool) isEqualTo(const Expr<S>& x) const { typedef IsEqual<value_type> IE; if (x.size() != this->size()) return false; bool eq = IE::eval(x.val(), this->val()); for (int i=0; i<this->size(); i++) eq = eq && IE::eval(x.dx(i), this->dx(i)); return eq; } //@} /*! * @name Derivative accessor methods */ //@{ //! Returns true if derivative array is not empty bool hasFastAccess() const { return this->size()!=0;} //! Returns true if derivative array is empty bool isPassive() const { return this->size()!=0;} //! Set whether variable is constant void setIsConstant(bool is_const) { if (is_const && this->size()!=0) this->resize(0); } //@} /*! * @name Assignment operators */ //@{ //! Assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator=(const S& v) { this->val() = v; if (this->size()) { this->zero(); this->resize(0); } return *this; } //! Assignment with Expr right-hand-side LogicalSparseImp& operator=(const LogicalSparseImp& x) { // Copy value & dx_ Storage::operator=(x); return *this; } //! Assignment operator with any expression right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator=(const Expr<S>& x) { int sz = x.size(); if (sz != this->size()) this->resize(sz); if (sz) { if (x.hasFastAccess()) for(int i=0; i<sz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); else for(int i=0; i<sz; ++i) this->fastAccessDx(i) = x.dx(i); } this->val() = x.val(); return *this; } //@} /*! * @name Unary operators */ //@{ //! Addition-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator += (const S& v) { this->val() += v; return *this; } //! Subtraction-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator -= (const S& v) { this->val() -= v; return *this; } //! Multiplication-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator *= (const S& v) { this->val() *= v; return *this; } //! Division-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator /= (const S& v) { this->val() /= v; return *this; } //! Addition-assignment operator with LogicalSparseImp right-hand-side LogicalSparseImp& operator += (const LogicalSparseImp& x) { int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); } else { this->resize(xsz); for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); } } this->val() += x.val(); return *this; } //! Subtraction-assignment operator with LogicalSparseImp right-hand-side LogicalSparseImp& operator -= (const LogicalSparseImp& x) { int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); } else { this->resize(xsz); for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); } } this->val() -= x.val(); return *this; } //! Multiplication-assignment operator with LogicalSparseImp right-hand-side LogicalSparseImp& operator *= (const LogicalSparseImp& x) { int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); } else { this->resize(xsz); for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); } } this->val() *= x.val(); return *this; } //! Division-assignment operator with LogicalSparseImp right-hand-side LogicalSparseImp& operator /= (const LogicalSparseImp& x) { int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); } else { this->resize(xsz); for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); } } this->val() /= x.val(); return *this; } //! Addition-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator += (const Expr<S>& x){ int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i); } else { this->resize(xsz); if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.dx(i); } } this->val() += x.val(); return *this; } //! Subtraction-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator -= (const Expr<S>& x){ int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i); } else { this->resize(xsz); if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.dx(i); } } this->val() -= x.val(); return *this; } //! Multiplication-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator *= (const Expr<S>& x){ int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i); } else { this->resize(xsz); if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.dx(i); } } this->val() *= x.val(); return *this; } //! Division-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator /= (const Expr<S>& x){ int xsz = x.size(), sz = this->size(); #ifdef SACADO_DEBUG if ((xsz != sz) && (xsz != 0) && (sz != 0)) throw "LFad Error: Attempt to assign with incompatible sizes"; #endif if (xsz) { if (sz) { if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i); } else { this->resize(xsz); if (x.hasFastAccess()) for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.fastAccessDx(i); else for (int i=0; i<xsz; ++i) this->fastAccessDx(i) = x.dx(i); } } this->val() /= x.val(); return *this; } //@} }; // class LogicalSparseImp //! Expression template specialization for LogicalSparse template <typename ValT, typename LogT> class Expr< LogicalSparseImp<ValT,LogT> > : public LogicalSparseImp<ValT,LogT> { public: //! Typename of values typedef typename LogicalSparseImp<ValT,LogT>::value_type value_type; //! Typename of scalar's (which may be different from value_type) typedef typename LogicalSparseImp<ValT,LogT>::scalar_type scalar_type; //! Typename of base-expressions typedef LogicalSparse<ValT,LogT> base_expr_type; //! Default constructor Expr() : LogicalSparseImp<ValT,LogT>() {} //! Constructor with supplied value \c x /*! * Initializes value to \c x and derivative array is empty */ template <typename S> Expr(const S & x, SACADO_ENABLE_VALUE_CTOR_DECL) : LogicalSparseImp<ValT,LogT>(x) {} //! Constructor with size \c sz and value \c x /*! * Initializes value to \c x and derivative array 0 of length \c sz */ Expr(const int sz, const ValT & x) : LogicalSparseImp<ValT,LogT>(sz,x) {} //! Constructor with size \c sz, index \c i, and value \c x /*! * Initializes value to \c x and derivative array of length \c sz * as row \c i of the identity matrix, i.e., sets derivative component * \c i to 1 and all other's to zero. */ Expr(const int sz, const int i, const ValT & x) : LogicalSparseImp<ValT,LogT>(sz,i,x) {} //! Copy constructor Expr(const Expr& x) : LogicalSparseImp<ValT,LogT>(x) {} //! Copy constructor from any Expression object template <typename S> Expr(const Expr<S>& x, SACADO_ENABLE_EXPR_CTOR_DECL) : LogicalSparseImp<ValT,LogT>(x) {} //! Destructor ~Expr() {} }; // class Expr<LogicalSparseImp> /*! * \brief User inteface class for computing the logical sparsity pattern * of a derivative via forward-mode AD. */ template <typename ValT, typename LogT > class LogicalSparse : public Expr< LogicalSparseImp<ValT,LogT > > { public: //! Base classes typedef LogicalSparseImp< ValT,LogT > ImplType; typedef Expr<ImplType> ExprType; //! Typename of values typedef typename ExprType::value_type value_type; //! Typename of scalar's (which may be different from value_type) typedef typename ExprType::scalar_type scalar_type; //! Turn LogicalSparse into a meta-function class usable with mpl::apply template <typename T, typename U = LogT> struct apply { typedef LogicalSparse<T,U> type; }; /*! * @name Initialization methods */ //@{ //! Default constructor. /*! * Initializes value to 0 and derivative array is empty */ LogicalSparse() : ExprType() {} //! Constructor with supplied value \c x of type ValueT /*! * Initializes value to \c x and derivative array is empty */ template <typename S> LogicalSparse(const S& x, SACADO_ENABLE_VALUE_CTOR_DECL) : ExprType(x) {} //! Constructor with size \c sz and value \c x /*! * Initializes value to \c x and derivative array 0 of length \c sz */ LogicalSparse(const int sz, const ValT& x) : ExprType(sz,x) {} //! Constructor with size \c sz, index \c i, and value \c x /*! * Initializes value to \c x and derivative array of length \c sz * as row \c i of the identity matrix, i.e., sets derivative component * \c i to 1 and all other's to zero. */ LogicalSparse(const int sz, const int i, const ValT & x) : ExprType(sz,i,x) {} //! Copy constructor LogicalSparse(const LogicalSparse& x) : ExprType(x) {} //! Copy constructor from any Expression object template <typename S> LogicalSparse(const Expr<S>& x, SACADO_ENABLE_EXPR_CTOR_DECL) : ExprType(x) {} //@} //! Destructor ~LogicalSparse() {} //! Assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator=(const S& v) { ImplType::operator=(v); return *this; } //! Assignment operator with LogicalSparse right-hand-side LogicalSparse& operator=(const LogicalSparse& x) { ImplType::operator=(static_cast<const ImplType&>(x)); return *this; } //! Assignment operator with any expression right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator=(const Expr<S>& x) { ImplType::operator=(x); return *this; } //! Addition-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator += (const S& x) { ImplType::operator+=(x); return *this; } //! Subtraction-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator -= (const S& x) { ImplType::operator-=(x); return *this; } //! Multiplication-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator *= (const S& x) { ImplType::operator*=(x); return *this; } //! Division-assignment operator with constant right-hand-side template <typename S> SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator /= (const S& x) { ImplType::operator/=(x); return *this; } //! Addition-assignment operator with LogicalSparse right-hand-side LogicalSparse& operator += (const LogicalSparse& x) { ImplType::operator+=(static_cast<const ImplType&>(x)); return *this; } //! Subtraction-assignment operator with LogicalSparse right-hand-side LogicalSparse& operator -= (const LogicalSparse& x) { ImplType::operator-=(static_cast<const ImplType&>(x)); return *this; } //! Multiplication-assignment operator with LogicalSparse right-hand-side LogicalSparse& operator *= (const LogicalSparse& x) { ImplType::operator*=(static_cast<const ImplType&>(x)); return *this; } //! Division-assignment operator with LogicalSparse right-hand-side LogicalSparse& operator /= (const LogicalSparse& x) { ImplType::operator/=(static_cast<const ImplType&>(x)); return *this; } //! Addition-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator += (const Expr<S>& x) { ImplType::operator+=(x); return *this; } //! Subtraction-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator -= (const Expr<S>& x) { ImplType::operator-=(x); return *this; } //! Multiplication-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator *= (const Expr<S>& x) { ImplType::operator*=(x); return *this; } //! Division-assignment operator with Expr right-hand-side template <typename S> SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator /= (const Expr<S>& x) { ImplType::operator/=(x); return *this; } }; // class LogicalSparse<ValT,LogT> template <typename T, typename L> struct ExprLevel< LogicalSparse<T,L> > { static const unsigned value = ExprLevel< typename LogicalSparse<T,L>::value_type >::value + 1; }; } // namespace LFad template <typename T> struct IsExpr< LFad::Expr<T> > { static const bool value = true; }; template <typename T> struct BaseExprType< LFad::Expr<T> > { typedef typename LFad::Expr<T>::base_expr_type type; }; template <typename T, typename L> struct IsExpr< LFad::LogicalSparse<T,L> > { static const bool value = true; }; template <typename T, typename L> struct BaseExprType< LFad::LogicalSparse<T,L> > { typedef typename LFad::LogicalSparse<T,L>::base_expr_type type; }; } // namespace Sacado #include "Sacado_LFad_LogicalSparseOps.hpp" #endif // SACADO_LFAD_LOGICALSPARSE_HPP
24,618
8,162
// // Created by hossein on 9/22/20. // #include "tf_publisher/tf_publisher.h" int main(int argc, char **argv){ rclcpp::init(argc, argv); std::shared_ptr<TFPublisher> tf_publisher_node = std::make_shared<TFPublisher>(); rclcpp::spin(tf_publisher_node); rclcpp::shutdown(); return 0; }
297
131
#include "clinterface/batteryarg.h" namespace rtt { namespace clinterface { BatteryArg::BatteryArg() {} BatteryArg::BatteryArg(const std::string & battery) { init(battery); } std::string BatteryArg::getName(Constants::BatteryID batteryId) { switch(batteryId) { case Constants::BatteryID::NIST_STS: return "NIST Statistical Testing Suite"; case Constants::BatteryID::DIEHARDER: return "Dieharder"; case Constants::BatteryID::TU01_SMALLCRUSH: return "TestU01 Small Crush"; case Constants::BatteryID::TU01_CRUSH: return "TestU01 Crush"; case Constants::BatteryID::TU01_BIGCRUSH: return "TestU01 Big Crush"; case Constants::BatteryID::TU01_RABBIT: return "TestU01 Rabbit"; case Constants::BatteryID::TU01_ALPHABIT: return "TestU01 Alphabit"; case Constants::BatteryID::TU01_BLOCK_ALPHABIT: return "TestU01 Block Alphabit"; default: raiseBugException("invalid battery id"); } } std::string BatteryArg::getShortName(Constants::BatteryID batteryId) { switch(batteryId) { case Constants::BatteryID::NIST_STS: return "nist_sts"; case Constants::BatteryID::DIEHARDER: return "dieharder"; case Constants::BatteryID::TU01_SMALLCRUSH: return "tu01_smallcrush"; case Constants::BatteryID::TU01_CRUSH: return "tu01_crush"; case Constants::BatteryID::TU01_BIGCRUSH: return "tu01_bigcrush"; case Constants::BatteryID::TU01_RABBIT: return "tu01_rabbit"; case Constants::BatteryID::TU01_ALPHABIT: return "tu01_alphabit"; case Constants::BatteryID::TU01_BLOCK_ALPHABIT: return "tu01_blockalphabit"; default: raiseBugException("invalid battery id"); } } uint BatteryArg::getExpectedExitCode(Constants::BatteryID batteryId) { switch(batteryId) { case Constants::BatteryID::NIST_STS: return 256; case Constants::BatteryID::DIEHARDER: case Constants::BatteryID::TU01_SMALLCRUSH: case Constants::BatteryID::TU01_CRUSH: case Constants::BatteryID::TU01_BIGCRUSH: case Constants::BatteryID::TU01_RABBIT: case Constants::BatteryID::TU01_ALPHABIT: case Constants::BatteryID::TU01_BLOCK_ALPHABIT: return 0; default: raiseBugException("invalid battery id"); } } Constants::BatteryID BatteryArg::getBatteryId() const { initCheck(); return batteryId; } std::string BatteryArg::getName() const { initCheck(); return name; } std::string BatteryArg::getShortName() const { initCheck(); return shortName; } uint BatteryArg::getExpectedExitCode() const { initCheck(); return expectedExitCode; } bool BatteryArg::isInTU01Family() const { initCheck(); switch(batteryId) { case Constants::BatteryID::NIST_STS: case Constants::BatteryID::DIEHARDER: return false; case Constants::BatteryID::TU01_SMALLCRUSH: case Constants::BatteryID::TU01_CRUSH: case Constants::BatteryID::TU01_BIGCRUSH: case Constants::BatteryID::TU01_RABBIT: case Constants::BatteryID::TU01_ALPHABIT: case Constants::BatteryID::TU01_BLOCK_ALPHABIT: return true; default: raiseBugException("invalid battery id"); } } bool BatteryArg::isInTU01CrushFamily() const { initCheck(); switch(batteryId) { case Constants::BatteryID::NIST_STS: case Constants::BatteryID::DIEHARDER: case Constants::BatteryID::TU01_RABBIT: case Constants::BatteryID::TU01_ALPHABIT: case Constants::BatteryID::TU01_BLOCK_ALPHABIT: return false; case Constants::BatteryID::TU01_SMALLCRUSH: case Constants::BatteryID::TU01_CRUSH: case Constants::BatteryID::TU01_BIGCRUSH: return true; default: raiseBugException("invalid battery id"); } } bool BatteryArg::isInTU01BitFamily() const { initCheck(); switch(batteryId) { case Constants::BatteryID::NIST_STS: case Constants::BatteryID::DIEHARDER: case Constants::BatteryID::TU01_SMALLCRUSH: case Constants::BatteryID::TU01_CRUSH: case Constants::BatteryID::TU01_BIGCRUSH: return false; case Constants::BatteryID::TU01_RABBIT: case Constants::BatteryID::TU01_ALPHABIT: case Constants::BatteryID::TU01_BLOCK_ALPHABIT: return true; default: raiseBugException("invalid battery id"); } } bool BatteryArg::isInTU01AlphabitFamily() const { initCheck(); switch(batteryId) { case Constants::BatteryID::NIST_STS: case Constants::BatteryID::DIEHARDER: case Constants::BatteryID::TU01_SMALLCRUSH: case Constants::BatteryID::TU01_CRUSH: case Constants::BatteryID::TU01_BIGCRUSH: case Constants::BatteryID::TU01_RABBIT: return false; case Constants::BatteryID::TU01_ALPHABIT: case Constants::BatteryID::TU01_BLOCK_ALPHABIT: return true; default: raiseBugException("invalid battery id"); } } Constants::BatteryID BatteryArg::getBatteryIdFromShortName(const std::string & shortName){ Constants::BatteryID batteryId; for(int i = 1; i < static_cast<int>(Constants::BatteryID::LAST_ITEM); ++i) { batteryId = static_cast<Constants::BatteryID>(i); if(shortName == getShortName(batteryId)) return batteryId; } throw std::runtime_error("unknown battery argument: " + shortName); } void BatteryArg::init(const std::string & shortName) { if(initialized) raiseBugException("BatteryArg is already initialized"); batteryId = getBatteryIdFromShortName(shortName); this->shortName = shortName; name = getName(batteryId); expectedExitCode = getExpectedExitCode(batteryId); initialized = true; } void BatteryArg::initCheck() const { if(!initialized) raiseBugException("BatteryArg is not initialized"); } } // namespace clinterface } // namespace rtt
5,896
2,257
#pragma once #include <typed-geometry/functions/basic/limits.hh> #include <typed-geometry/functions/vector/math.hh> #include <typed-geometry/types/objects/triangle.hh> #include "aabb.hh" #include "coordinates.hh" /** * Rasterization of objects * * Enumerates all integer points (tg::ipos2, tg::ipos3, ...) that are contained in the objects * (e.g. contains(obj, pos) == true for all enumerated positions) */ namespace tg { // F: (tg::ipos2 p, float a) -> void template <class ScalarT, class F> constexpr void rasterize(segment<2, ScalarT> const& l, F&& f) { // TODO add limits? // bresenham, see http://www.roguebasin.com/index.php?title=Bresenham%27s_Line_Algorithm auto x0 = iround(l.pos0.x); auto x1 = iround(l.pos1.x); auto y0 = iround(l.pos0.y); auto y1 = iround(l.pos1.y); auto delta_x = x1 - x0; // if x1 == x2, then it does not matter what we set here signed char const ix((delta_x > 0) - (delta_x < 0)); delta_x = std::abs(delta_x) << 1; auto delta_y = y1 - y0; // if y1 == y2, then it does not matter what we set here signed char const iy((delta_y > 0) - (delta_y < 0)); delta_y = std::abs(delta_y) << 1; // start f(tg::ipos2(x0, y0), ScalarT(0)); if (delta_x >= delta_y) { // done if (x0 == x1) return; // error may go below zero int error(delta_y - (delta_x >> 1)); while (x0 != x1) { // reduce error, while taking into account the corner case of error == 0 if ((error > 0) || (!error && (ix > 0))) { error -= delta_x; y0 += iy; } // else do nothing error += delta_y; x0 += ix; f(tg::ipos2(x0, y0), min(length(tg::pos2(x0, y0) - l.pos0) / length(l.pos1 - l.pos0), ScalarT(1))); } } else { // done if (y0 == y1) return; // error may go below zero int error(delta_x - (delta_y >> 1)); while (y1 != y0) { // reduce error, while taking into account the corner case of error == 0 if ((error > 0) || (!error && (iy > 0))) { error -= delta_y; x0 += ix; } // else do nothing error += delta_x; y0 += iy; f(tg::ipos2(x0, y0), min(length(tg::pos2(x0, y0) - l.pos0) / length(l.pos1 - l.pos0), ScalarT(1))); } } } // F: (tg::ipos2 p, float a, float b) -> void // offset is subpixel offset, e.g. 0.5f means sampling at pixel center template <class ScalarT, class F> constexpr void rasterize_bresenham(triangle<2, ScalarT> const& t, F&& f) { // bresenham 3 sides of a triangle, then fill contour // inspired by https://stackoverflow.com/a/11145708 auto const box = aabb_of(t); // margin so that we can safely round/clamp to integer coords auto const minPix = ifloor(box.min); auto const maxPix = iceil(box.max); // TODO no abs, correct? // auto const width = maxPix.x - minPix.x; auto const height = maxPix.y - minPix.y; // stores leftmost and rightmost pixel from bresenham auto contour = new int*[uint(height)]; for (auto r = 0; r < height; r++) { contour[r] = new int[2]; // will bresenham to find left and right bounds of row // will scanline only if row[0] <= row[1] contour[r][0] = tg::detail::limits<int>().max(); contour[r][1] = tg::detail::limits<int>().min(); } // rasterize two sides of the triangle auto lines = {tg::segment(t.pos0, t.pos1), tg::segment(t.pos1, t.pos2), tg::segment(t.pos2, t.pos0)}; // note that if the triangle is "flat" (that means one side is not slanted with respect to the pixel grid) two edges would be sufficient! // rasterize to get triangle contour for each row for (auto l : lines) tg::rasterize(l, [&](tg::ipos2 p, ScalarT a) { auto iy = p.y - minPix.y; if (iy < 0 || iy >= height) // std::cout << "bad y: " << iy << " | height is " << height << std::endl; return; // update contour if (p.x < contour[iy][0]) contour[iy][0] = p.x; if (p.x > contour[iy][1]) contour[iy][1] = p.x; // TODO interpolate line parameters for bary? (void)a; }); for (auto y = 0; y < height; ++y) { // bresenham was here for (auto x = contour[y][0]; x <= contour[y][1]; x++) { auto const pos = tg::ipos2(x, y + minPix.y); // TODO if experimental: derive bary from line parameters and x / (maxPix.x - minPix.x) instead? // TODO note that calculating barycentrics for pixels may give values outside 0..1 as pixels may be // "touched" by a triangle but e.g. their topleft corner may not actually be contained // TODO offset? auto const off = ScalarT(0.0); // subpixel offset auto bary = tg::coordinates(t, tg::pos2(pos.x + off, pos.y + off)); // TODO might be slightly outside of triangle, clamp bary[0] = tg::clamp(bary[0], 0, 1); bary[1] = tg::clamp(bary[1], 0, 1); f(pos, bary[0], bary[1]); } } } // no barycentric coords returned: // F: (tg::ipos2 p) -> void // offset is subpixel offset, e.g. 0.5f means sampling at pixel center template <class ScalarT, class F> constexpr void fast_rasterize(triangle<2, ScalarT> const& t, F&& f, tg::vec<2, ScalarT> const& offset = tg::vec<2, ScalarT>(0)) { // adaptive half-space rasterization // see https://www.uni-obuda.hu/journal/Mileff_Nehez_Dudra_63.pdf auto const fbox = aabb_of(t); auto box = tg::aabb<2, int>(tg::ipos2(ifloor(fbox.min)), tg::ipos2(iceil(fbox.max))); // edge functions and their constants ScalarT edgeConstants[3 * 3]; tg::pos<2, ScalarT> verts[3] = {t.pos0, t.pos1, t.pos2}; // edges AB, BC and CA for (auto e = 0; e < 3; e++) { auto next = (e + 1) % 3; edgeConstants[e * 3 + 0] = verts[e].y - verts[next].y; edgeConstants[e * 3 + 1] = verts[next].x - verts[e].x; edgeConstants[e * 3 + 2] = verts[e].x * verts[next].y - verts[e].y * verts[next].x; } auto edgeFunction = [edgeConstants, offset](tg::ipos2 pos, int f) { auto first = min(f * 3, 6); return edgeConstants[first + 0] * (pos.x + offset.x) + edgeConstants[first + 1] * (pos.y + offset.y) + edgeConstants[first + 2]; }; auto renderBlock = [f, edgeFunction, edgeConstants](int x, int y, int sizeX, int sizeY) { if (sizeX * sizeY <= 0) return; // compute once, increment later auto pos = tg::ipos2(x, y); auto cy1 = edgeFunction(pos, 0); auto cy2 = edgeFunction(pos, 1); auto cy3 = edgeFunction(pos, 2); auto cx1 = cy1; auto cx2 = cy2; auto cx3 = cy3; for (auto py = y; py < y + sizeY; py++) { // y has changed, clip cx to cy cx1 = cy1; cx2 = cy2; cx3 = cy3; for (auto px = x; px < x + sizeX; px++) { // allows for both ccw and cc vertex order auto in = (cx1 < 0 && cx2 < 0 && cx3 < 0) || (cx1 >= 0 && cx2 >= 0 && cx3 >= 0); if (in) { f(tg::ipos2(px, py)); } // increment cx1 += edgeConstants[3 * 0 + 0]; // I values cx2 += edgeConstants[3 * 1 + 0]; cx3 += edgeConstants[3 * 2 + 0]; } // update cy values cy1 += edgeConstants[3 * 0 + 1]; // J values cy2 += edgeConstants[3 * 1 + 1]; cy3 += edgeConstants[3 * 2 + 1]; } }; auto width = box.max.x - box.min.x; auto height = box.max.y - box.min.y; renderBlock(box.min.x, box.min.y, width, height); } // F: (tg::ipos2 p, float a, float b) -> void // offset is subpixel offset, e.g. 0.5f means sampling at pixel center template <class ScalarT, class F> constexpr void rasterize(triangle<2, ScalarT> const& t, F&& f, tg::vec<2, ScalarT> const& offset = tg::vec<2, ScalarT>(0)) { auto const box = aabb_of(t); // margin so that we can safely round/clamp to integer coords auto const minPix = ifloor(box.min); auto const maxPix = iceil(box.max); // TODO: Bresenham on two of the triangle edges, then scanline for (auto y = minPix.y; y <= maxPix.y; ++y) for (auto x = minPix.x; x <= maxPix.x; ++x) { auto const pos = tg::pos<2, ScalarT>(ScalarT(x), ScalarT(y)) + offset; auto const bary = coordinates(t, pos); auto const a = bary[0]; auto const b = bary[1]; auto const c = bary[2]; if (a >= 0 && b >= 0 && c >= 0) { // inside triangle f(ipos2(x, y), a, b); } } } } // namespace tg
9,149
3,323
/* * 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. */ /** * @file gk_test.cpp * @brief Testbench to generate randomized input data and launch on kernel. * Results are compared to a full precision model. */ #include <stdio.h> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <chrono> #include "gk_host.hpp" #include "xcl2.hpp" /// @def Controls the data type used in the kernel #define KERNEL_DT float // Temporary copy of this macro definition until new xcl2.hpp is used #define OCL_CHECK(error, call) \ call; \ if (error != CL_SUCCESS) { \ printf("%s:%d Error calling " #call ", error code is: %d\n", __FILE__, __LINE__, error); \ exit(EXIT_FAILURE); \ } static void usage(std::string exe) { std::cout << "Usage: " << exe << " ./xclbin/<kernel_name> <test data file>" << std::endl; std::cout << "Test data file line format:" << std::endl; std::cout << "s=<value>, k=<value>, r_domestic=<value>1, r_foreign=<value>1, v=<value>1, t=<value>" << std::endl; std::cout << "# comments out the line" << std::endl; } static int validate_parameters(int argc, char* argv[]) { /* check 2 arguments specified */ if (argc != 3) { usage(argv[0]); return 0; } /* check xclbin file exists */ std::ifstream ifs1(argv[1]); if (!ifs1.is_open()) { std::cout << "ERROR: cannot open " << argv[1] << std::endl; return 0; } /* check test data file exists */ std::ifstream ifs2(argv[2]); if (!ifs2.is_open()) { std::cout << "ERROR: cannot open " << argv[2] << std::endl; return 0; } return 1; } /// @brief Main entry point to test /// /// This is a command-line application to test the kernel. It supports software /// and hardware emulation as well as /// running on an Alveo target. /// /// Usage: ./gk_test ./xclbin/<kernel_name> <test data file> /// /// @param[in] argc Standard C++ argument count /// @param[in] argv Standard C++ input arguments int main(int argc, char* argv[]) { std::cout << std::endl << std::endl; std::cout << "**************************" << std::endl; std::cout << "Garman-Kohlhagen Demo v1.0" << std::endl; std::cout << "**************************" << std::endl; std::cout << std::endl; if (!validate_parameters(argc, argv)) { exit(1); } // parse the input test data file std::vector<struct parsed_params*>* vect = parse_file(argv[2]); if (vect == nullptr) { return 1; } unsigned int num = vect->size(); // kernel expects multiple of 16 input data unsigned int remainder = num % 16; unsigned int extra = 0; if (remainder != 0) { extra = 16 - remainder; } unsigned int modified_num = num + extra; // Test parameters static const unsigned int call = 1; std::string xclbin_file(argv[1]); // Vectors for parameter storage. These use an aligned allocator in order // to avoid an additional copy of the host memory into the device std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > s(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > v(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > r_domestic(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > r_foreign(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > t(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > k(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > price(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > delta(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > gamma(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > vega(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > theta(modified_num); std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > rho(modified_num); // Host results (always double precision) double* host_price = new double[modified_num]; double* host_delta = new double[modified_num]; double* host_gamma = new double[modified_num]; double* host_vega = new double[modified_num]; double* host_theta = new double[modified_num]; double* host_rho = new double[modified_num]; // write the test data to the input vectors and calculate the model results std::cout << "Generating reference results..." << std::endl; for (unsigned int i = 0; i < num; i++) { s[i] = vect->at(i)->s; v[i] = vect->at(i)->v; t[i] = vect->at(i)->t; k[i] = vect->at(i)->k; r_domestic[i] = vect->at(i)->r_domestic; r_foreign[i] = vect->at(i)->r_foreign; } for (unsigned int i = num; i < modified_num; i++) { s[i] = 0; v[i] = 0; t[i] = 0; k[i] = 0; r_domestic[i] = 0; r_foreign[i] = 0; } std::cout << "Running CPU model..." << std::endl; auto t_start = std::chrono::high_resolution_clock::now(); for (unsigned int i = 0; i < num; i++) { gk_model(s[i], v[i], r_domestic[i], t[i], k[i], r_foreign[i], call, host_price[i], host_delta[i], host_gamma[i], host_vega[i], host_theta[i], host_rho[i]); } auto cpu_duration = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - t_start) .count(); // OPENCL HOST CODE AREA START // get_xil_devices() is a utility API which will find the xilinx // platforms and will return list of devices connected to Xilinx platform std::cout << "Connecting to device and loading kernel..." << std::endl; std::vector<cl::Device> devices = xcl::get_xil_devices(); cl::Device device = devices[0]; cl_int err; OCL_CHECK(err, cl::Context context(device, NULL, NULL, NULL, &err)); OCL_CHECK(err, cl::CommandQueue cq(context, device, CL_QUEUE_PROFILING_ENABLE, &err)); // Load the binary file (using function from xcl2.cpp) cl::Program::Binaries bins = xcl::import_binary_file(xclbin_file); devices.resize(1); OCL_CHECK(err, cl::Program program(context, devices, bins, NULL, &err)); OCL_CHECK(err, cl::Kernel krnl_cfGKEngine(program, "gk_kernel", &err)); // Allocate Buffer in Global Memory // Buffers are allocated using CL_MEM_USE_HOST_PTR for efficient memory and // Device-to-host communication std::cout << "Allocating buffers..." << std::endl; OCL_CHECK(err, cl::Buffer buffer_s(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, modified_num * sizeof(KERNEL_DT), s.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_v(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, modified_num * sizeof(KERNEL_DT), v.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_r_domestic(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, modified_num * sizeof(KERNEL_DT), r_domestic.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_t(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, modified_num * sizeof(KERNEL_DT), t.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_k(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, modified_num * sizeof(KERNEL_DT), k.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_r_foreign(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, modified_num * sizeof(KERNEL_DT), r_foreign.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_price(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, modified_num * sizeof(KERNEL_DT), price.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_delta(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, modified_num * sizeof(KERNEL_DT), delta.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_gamma(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, modified_num * sizeof(KERNEL_DT), gamma.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_vega(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, modified_num * sizeof(KERNEL_DT), vega.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_theta(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, modified_num * sizeof(KERNEL_DT), theta.data(), &err)); OCL_CHECK(err, cl::Buffer buffer_rho(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, modified_num * sizeof(KERNEL_DT), rho.data(), &err)); // Set the arguments OCL_CHECK(err, err = krnl_cfGKEngine.setArg(0, buffer_s)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(1, buffer_v)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(2, buffer_r_domestic)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(3, buffer_t)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(4, buffer_k)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(5, buffer_r_foreign)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(6, call)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(7, modified_num)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(8, buffer_price)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(9, buffer_delta)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(10, buffer_gamma)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(11, buffer_vega)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(12, buffer_theta)); OCL_CHECK(err, err = krnl_cfGKEngine.setArg(13, buffer_rho)); // Copy input data to device global memory t_start = std::chrono::high_resolution_clock::now(); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_s}, 0)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_v}, 0)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_r_domestic}, 0)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_t}, 0)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_k}, 0)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_r_foreign}, 0)); // Launch the Kernel std::cout << "Launching kernel..." << std::endl; uint64_t nstimestart, nstimeend; cl::Event event; OCL_CHECK(err, err = cq.enqueueTask(krnl_cfGKEngine, NULL, &event)); OCL_CHECK(err, err = cq.finish()); OCL_CHECK(err, err = event.getProfilingInfo<uint64_t>(CL_PROFILING_COMMAND_START, &nstimestart)); OCL_CHECK(err, err = event.getProfilingInfo<uint64_t>(CL_PROFILING_COMMAND_END, &nstimeend)); auto duration_nanosec = nstimeend - nstimestart; // Copy Result from Device Global Memory to Host Local Memory OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_price}, CL_MIGRATE_MEM_OBJECT_HOST)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_delta}, CL_MIGRATE_MEM_OBJECT_HOST)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_gamma}, CL_MIGRATE_MEM_OBJECT_HOST)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_vega}, CL_MIGRATE_MEM_OBJECT_HOST)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_theta}, CL_MIGRATE_MEM_OBJECT_HOST)); OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_rho}, CL_MIGRATE_MEM_OBJECT_HOST)); cq.finish(); auto fpga_duration = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - t_start) .count(); // OPENCL HOST CODE AREA END // Check results double max_price_diff = 0.0f; double max_delta_diff = 0.0f; double max_gamma_diff = 0.0f; double max_vega_diff = 0.0f; double max_theta_diff = 0.0f; double max_rho_diff = 0.0f; for (unsigned int i = 0; i < num; i++) { double temp = 0.0f; std::cout << price[i] << " " << host_price[i] << " diff = " << price[i] - host_price[i] << std::endl; if (std::abs(temp = (price[i] - host_price[i])) > std::abs(max_price_diff)) max_price_diff = temp; if (std::abs(temp = (delta[i] - host_delta[i])) > std::abs(max_delta_diff)) max_delta_diff = temp; if (std::abs(temp = (gamma[i] - host_gamma[i])) > std::abs(max_gamma_diff)) max_gamma_diff = temp; if (std::abs(temp = (vega[i] - host_vega[i])) > std::abs(max_vega_diff)) max_vega_diff = temp; if (std::abs(temp = (theta[i] - host_theta[i])) > std::abs(max_theta_diff)) max_theta_diff = temp; if (std::abs(temp = (rho[i] - host_rho[i])) > std::abs(max_rho_diff)) max_rho_diff = temp; } std::cout << "Kernel done!" << std::endl; std::cout << "Comparing results..." << std::endl; std::cout << "Processed " << num; if (call) { std::cout << " call options:" << std::endl; } else { std::cout << " put options:" << std::endl; } std::cout << "Throughput = " << (1.0 * num) / (duration_nanosec * 1.0e-9) / 1.0e6 << " Mega options/sec" << std::endl; std::cout << std::endl; std::cout << " Largest host-kernel price difference = " << max_price_diff << std::endl; std::cout << " Largest host-kernel delta difference = " << max_delta_diff << std::endl; std::cout << " Largest host-kernel gamma difference = " << max_gamma_diff << std::endl; std::cout << " Largest host-kernel vega difference = " << max_vega_diff << std::endl; std::cout << " Largest host-kernel theta difference = " << max_theta_diff << std::endl; std::cout << " Largest host-kernel rho difference = " << max_rho_diff << std::endl; std::cout << "CPU execution time = " << cpu_duration << "us" << std::endl; std::cout << "FPGA time returned by profile API = " << (duration_nanosec * (1.0e-6)) << " ms" << std::endl; std::cout << "FPGA execution time (including mem transfer)= " << fpga_duration << "us" << std::endl; int ret = 0; if (std::abs(max_price_diff) > 6.0e-5) { std::cout << "FAIL: max_price_diff = " << max_price_diff << std::endl; ret = 1; } if (std::abs(max_delta_diff) > 4.0e-7) { std::cout << "FAIL: max_delta_diff = " << max_delta_diff << std::endl; ret = 1; } if (std::abs(max_gamma_diff) > 3.0e-7) { std::cout << "FAIL: max_gamma_diff = " << max_gamma_diff << std::endl; ret = 1; } if (std::abs(max_vega_diff) > 6.0e-7) { std::cout << "FAIL: max_vega_diff = " << max_vega_diff << std::endl; ret = 1; } if (std::abs(max_theta_diff) > 5.0e-8) { std::cout << "FAIL: max_theta_diff = " << max_theta_diff << std::endl; ret = 1; } if (std::abs(max_rho_diff) > 6.0e-7) { std::cout << "FAIL: max_rho_diff = " << max_rho_diff << std::endl; ret = 1; } if (!ret) { std::cout << "PASS" << std::endl; } return ret; }
15,862
5,808
#include "common.h" #include <sys/time.h> int main(int argc, char** argv) { int batchSize; options_description batchOption("batch_write option"); batchOption.add_options()("batch_size,b", value<int>(&batchSize)->default_value(1), "batch size"); variables_map vm = parse(argc, argv, &batchOption); int total = vm["total"].as<int>(); int valueSize = vm["size"].as<int>(); std::cout << "batch size is " << batchSize << std::endl; DB* db = opendb(); struct timeval tv; gettimeofday(&tv, 0); long start = tv.tv_sec * 1000000 + tv.tv_usec; int count = 0; std::string valuePrefix = std::string(valueSize, 'a'); while (count != total) { WriteBatch batch; for (int j = 0; j < batchSize; j++, count++) { if (count == total) break; std::string tmp = std::to_string(count); std::string key = keyPrefix + tmp; std::string value = valuePrefix + tmp; auto s = batch.Put(key, value); if (!s.ok()) std::cerr << "batch.Put():" << s.ToString() << std::endl; assert(s.ok()); } auto s = db->Write(WriteOptions(), &batch); if (!s.ok()) std::cerr << "db->Write():" << s.ToString() << std::endl; assert(s.ok()); } gettimeofday(&tv, 0); long end = tv.tv_sec * 1000000 + tv.tv_usec; std::cout << total << " records batch put in " << end - start << " usec, " << double(end - start) / total << " usec average, throughput is " << (double)total * valueSize / (end - start) << " MB/s, rps is " << (double)1000000 * total / (end - start) << std::endl; delete db; }
1,733
581
/* * Copyright (C) 2015 Samsung Electronics Co., Ltd All Rights Reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @author Lukasz Pawelczyk (l.pawelczyk@samsung.com) * @brief Headers of root FS preparation command */ #ifndef LXCPP_COMMANDS_PIVOT_AND_PREP_ROOT_HPP #define LXCPP_COMMANDS_PIVOT_AND_PREP_ROOT_HPP #include "lxcpp/commands/command.hpp" #include "lxcpp/container-config.hpp" namespace lxcpp { class PivotAndPrepRoot final: Command { public: /** * Does a pivot_root syscall and prepares the resulting root fs for its usage * * After the pivot_root previously prepared /dev and /dev/pts filesystems are mounted, * as well as a list of static mounts that are required for a fully working OS. * Things like /proc, /sys and security filesystem (if permitted). * * @param config A container config */ PivotAndPrepRoot(ContainerConfig &config); ~PivotAndPrepRoot(); void execute(); private: ContainerConfig &mConfig; const bool mIsUserNamespace; const bool mIsNetNamespace; void pivotRoot(); void cleanUpRoot(); void mountStatic(); void prepDev(); void symlinkStatic(); }; } // namespace lxcpp #endif // LXCPP_COMMANDS_PIVOT_AND_PREP_ROOT_HPP
1,925
632
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // _Stoxflt function #include "xmath.h" #include <ctype.h> #include <locale.h> #include <stdlib.h> #include <string.h> _EXTERN_C_UNLESS_PURE constexpr int _Base = 16; // hexadecimal constexpr int _Ndig = 7; // hexadecimal digits per long element constexpr int _Maxsig = 5 * _Ndig; // maximum significant digits to keep int _Stoxflt(const char* s0, const char* s, char** endptr, long lo[], int maxsig) { // convert string to array of long plus exponent char buf[_Maxsig + 1]; // worst case, with room for rounding digit int nsig = 0; // number of significant digits seen int seen = 0; // any valid field characters seen int word = 0; // current long word to fill const char* pd; static const char digits[] = "0123456789abcdefABCDEF"; static const char vals[] = {// values of hex digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 10, 11, 12, 13, 14, 15}; maxsig *= _Ndig; // convert word count to digit count if (_Maxsig < maxsig) { maxsig = _Maxsig; // protect against bad call } lo[0] = 0; // power of ten exponent lo[1] = 0; // first _Ndig-digit word of fraction while (*s == '0') { // strip leading zeros ++s; seen = 1; } while ((pd = (char*) memchr(&digits[0], *s, 22)) != 0) { if (nsig <= maxsig) { buf[nsig++] = vals[pd - digits]; // accumulate a digit } else { ++lo[0]; // too many digits, just scale exponent } ++s; seen = 1; } if (*s == localeconv()->decimal_point[0]) { ++s; } if (nsig == 0) { for (; *s == '0'; ++s, seen = 1) { --lo[0]; // strip zeros after point } } for (; (pd = (char*) memchr(&digits[0], *s, 22)) != 0; ++s, seen = 1) { if (nsig <= maxsig) { // accumulate a fraction digit buf[nsig++] = vals[pd - digits]; --lo[0]; } } if (maxsig < nsig) { // discard excess digit after rounding up if (_Base / 2 <= buf[maxsig]) { ++buf[maxsig - 1]; // okay if digit becomes _Base } nsig = maxsig; ++lo[0]; } for (; 0 < nsig && buf[nsig - 1] == '\0'; --nsig) { ++lo[0]; // discard trailing zeros } if (nsig == 0) { buf[nsig++] = '\0'; // ensure at least one digit } lo[0] <<= 2; // change hex exponent to binary exponent if (seen) { // convert digit sequence to words int bufidx = 0; // next digit in buffer int wordidx = _Ndig - nsig % _Ndig; // next digit in word (% _Ndig) word = wordidx % _Ndig == 0 ? 0 : 1; for (; bufidx < nsig; ++wordidx, ++bufidx) { if (wordidx % _Ndig == 0) { lo[++word] = buf[bufidx]; } else { lo[word] = lo[word] * _Base + buf[bufidx]; } } if (*s == 'p' || *s == 'P') { // parse exponent const char* ssav = s; const char esign = *++s == '+' || *s == '-' ? *s++ : '+'; int eseen = 0; long lexp = 0; for (; isdigit((unsigned char) *s); ++s, eseen = 1) { if (lexp < 100000000) { // else overflow lexp = lexp * 10 + (unsigned char) *s - '0'; } } if (esign == '-') { lexp = -lexp; } lo[0] += lexp; if (!eseen) { s = ssav; // roll back if incomplete exponent } } } if (!seen) { word = 0; // return zero if bad parse } if (endptr) { *endptr = (char*) (seen ? s : s0); // roll back if bad parse } return word; } _END_EXTERN_C_UNLESS_PURE
4,002
1,472
#include "VelocityComponent.h" VelocityComponent::VelocityComponent() { m_xVelocity = 0; m_yVelocity = 0; } VelocityComponent::~VelocityComponent() { } VelocityComponent::VelocityComponent(int xVelocity, int yVelocity) { } int VelocityComponent::GetXVelocity() { return 0; } int VelocityComponent::GetYVelocity() { return 0; } int VelocityComponent::SetXVelocity(int newXVelocity) { return 0; } int VelocityComponent::SetYVelocity(int newYVelocity) { return 0; } const char* VelocityComponent::GetComponentType() const { return TYPE; }
603
246
#include "EffectSetting.h" #include "../Graphics/GraphicsDevice.h" #include "../Sound/SoundDevice.h" #include "FileInterface.h" #ifdef _WIN32 #include "../Graphics/Platform/DX11/efk.GraphicsDX11.h" #endif #include "../Graphics/Platform/GL/efk.GraphicsGL.h" #include <EffekseerSoundOSMixer.h> namespace Effekseer::Tool { std::shared_ptr<EffectSetting> EffectSetting::Create(std::shared_ptr<Effekseer::Tool::GraphicsDevice> graphicsDevice, std::shared_ptr<Effekseer::Tool::SoundDevice> soundDevice) { auto ret = std::make_shared<EffectSetting>(); auto setting = Effekseer::Setting::Create(); ret->setting_ = setting; auto gd = graphicsDevice->GetGraphics()->GetGraphicsDevice(); auto fileInterface = Effekseer::MakeRefPtr<Effekseer::Tool::EffekseerFile>(); auto textureLoader = EffekseerRenderer::CreateTextureLoader( gd, fileInterface, graphicsDevice->GetIsSRGBMode() ? ::Effekseer::ColorSpaceType::Linear : ::Effekseer::ColorSpaceType::Gamma); setting->SetTextureLoader(textureLoader); auto modelLoader = EffekseerRenderer::CreateModelLoader(gd, fileInterface); setting->SetModelLoader(modelLoader); setting->SetCurveLoader(Effekseer::CurveLoaderRef(new ::Effekseer::CurveLoader(fileInterface))); if (soundDevice != nullptr) { setting->SetSoundLoader(soundDevice->GetSound()->CreateSoundLoader(fileInterface)); } if (graphicsDevice->GetDeviceType() == DeviceType::DirectX11) { #ifdef _WIN32 setting->SetMaterialLoader(EffekseerRendererDX11::CreateMaterialLoader(gd, fileInterface)); #endif } else if (graphicsDevice->GetDeviceType() == DeviceType::OpenGL) { setting->SetMaterialLoader(EffekseerRendererGL::CreateMaterialLoader(gd, fileInterface)); } return ret; return nullptr; } } // namespace Effekseer::Tool
1,758
612
//============================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2016, CHAI3D. (www.chai3d.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of CHAI3D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \author <http://www.chai3d.org> \author Francois Conti \version $MAJOR.$MINOR.$RELEASE $Rev: 2158 $ */ //============================================================================== //------------------------------------------------------------------------------ #include "tools/CHapticPoint.h" //------------------------------------------------------------------------------ #include "tools/CGenericTool.h" #include "world/CMultiMesh.h" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace chai3d { //------------------------------------------------------------------------------ //============================================================================== /*! Constructor of cHapticPoint. */ //============================================================================== cHapticPoint::cHapticPoint(cGenericTool* a_parentTool) { // set parent tool m_parentTool = a_parentTool; // initialize variables m_radiusDisplay = 0.0; m_radiusContact = 0.0; m_lastComputedGlobalForce.zero(); m_meshProxyContacts[0] = NULL; m_meshProxyContacts[1] = NULL; m_meshProxyContacts[2] = NULL; m_audioSourceImpact[0] = NULL; m_audioSourceImpact[1] = NULL; m_audioSourceImpact[2] = NULL; m_audioSourceFriction[0] = NULL; m_audioSourceFriction[1] = NULL; m_audioSourceFriction[2] = NULL; m_audioProxyContacts[0] = NULL; m_audioProxyContacts[1] = NULL; m_audioProxyContacts[2] = NULL; m_useAudioSources = false; // create finger-proxy algorithm used for modelling contacts with // cMesh objects. m_algorithmFingerProxy = new cAlgorithmFingerProxy(); // create potential field algorithm used for modelling interaction // forces with haptic effects. m_algorithmPotentialField = new cAlgorithmPotentialField(); // create sphere object used for rendering the Proxy position. m_sphereProxy = new cShapeSphere(0.0); // create sphere object used for rendering the Goal position. m_sphereGoal = new cShapeSphere(0.0); // Set default radius of proxy and goal spheres setRadius(0.01, 0.01); // define a color for the proxy sphere m_sphereProxy->m_material->setGrayDim(); // define a color for the goal sphere m_sphereGoal->m_material->setGrayLight(); // Initialize force rendering algorithms initialize(cVector3d(0.0, 0.0, 0.0)); } //============================================================================== /*! Destructor of cHapticPoint. */ //============================================================================== cHapticPoint::~cHapticPoint() { // delete force rendering algorithms delete m_algorithmFingerProxy; delete m_algorithmPotentialField; // delete graphical spheres (proxy and goal) delete m_sphereProxy; delete m_sphereGoal; // delete audio sources for impact for (int i = 0; i<3; i++) { if (m_audioSourceImpact[i] != NULL) { delete m_audioSourceImpact[i]; } } // delete audio sources for friction for (int i = 0; i<3; i++) { if (m_audioSourceFriction[i] != NULL) { delete m_audioSourceFriction[i]; } } } //============================================================================== /*! This method returns the current desired goal position of the contact point in world global coordinates. \return Goal position of haptic point. */ //============================================================================== cVector3d cHapticPoint::getGlobalPosGoal() { return(m_algorithmFingerProxy->getDeviceGlobalPosition()); } //============================================================================== /*! This method returns the current proxy position of the haptic point in world global coordinates. \return Proxy position of haptic point. */ //============================================================================== cVector3d cHapticPoint::getGlobalPosProxy() { return(m_algorithmFingerProxy->getProxyGlobalPosition()); } //============================================================================== /*! This method returns the current desired goal position of the haptic point in local tool coordinates. \return Goal position of haptic point. */ //============================================================================== cVector3d cHapticPoint::getLocalPosGoal() { cMatrix3d rot; cVector3d newpos; cVector3d toolGlobalPos = m_parentTool->getGlobalPos(); cMatrix3d toolGlobalRot = m_parentTool->getGlobalRot(); cVector3d pos = m_algorithmFingerProxy->getDeviceGlobalPosition(); toolGlobalRot.transr(rot); pos.sub(toolGlobalPos); rot.mulr(pos, newpos); return(newpos); } //============================================================================== /*! This method returns the current proxy position of the haptic point in local tool coordinates. \return Proxy position of haptic point. */ //============================================================================== cVector3d cHapticPoint::getLocalPosProxy() { cMatrix3d rot; cVector3d newpos; cVector3d toolGlobalPos = m_parentTool->getGlobalPos(); cMatrix3d toolGlobalRot = m_parentTool->getGlobalRot(); cVector3d pos = m_algorithmFingerProxy->getProxyGlobalPosition(); toolGlobalRot.transr(rot); pos.sub(toolGlobalPos); rot.mulr(pos, newpos); return(newpos); } //============================================================================== /*! This method resets the position of the proxy to be at the current desired goal position. */ //============================================================================== void cHapticPoint::initialize() { // reset finger proxy algorithm by placing the proxy and the same position // as the goal. m_algorithmFingerProxy->reset(); // update position of proxy and goal spheres in tool coordinates updateSpherePositions(); } //============================================================================== /*! This method initializes the position of the haptic point to a new desired position. The __proxy__ and the __device__ are set to the same value despite any constraints. \param a_globalPos New desired position of the haptic point. */ //============================================================================== void cHapticPoint::initialize(cVector3d a_globalPos) { // initialize proxy algorithm. m_algorithmFingerProxy->initialize(m_parentTool->getParentWorld(), a_globalPos); m_algorithmPotentialField->initialize(m_parentTool->getParentWorld(), a_globalPos); // update position of proxy and goal spheres in tool coordinates updateSpherePositions(); } //============================================================================== /*! This method sets the radius size of the haptic point. The radius affects the physical radius of the proxy and the radius of the spheres that are used to render the goal and proxy positions. \param a_radius New radius for display rendering and contact computation. */ //============================================================================== void cHapticPoint::setRadius(double a_radius) { m_radiusContact = a_radius; m_radiusDisplay = a_radius; // set the radius of the contact model of the proxy m_algorithmFingerProxy->setProxyRadius(m_radiusContact); // set radius of proxy and goal. goal radius is slightly smaller to avoid graphical // artifacts when both sphere are located at the same position. m_sphereProxy->setRadius(m_radiusDisplay); m_sphereGoal->setRadius(0.95 * m_radiusDisplay); } //============================================================================== /*! This method sets the radius size of the display spheres (goal and proxy) and physical contact sphere (proxy) used to compute the contact forces. Setting the a_radiusContact parameter to zero will generally accelerate the force rendering algorithm. For more realistic effects, settings both values to be identical is recommended \param a_radiusDisplay New radius for display of spheres (proxy and goal). \param a_radiusContact New radius for contact computation (proxy). */ //============================================================================== void cHapticPoint::setRadius(double a_radiusDisplay, double a_radiusContact) { m_radiusContact = a_radiusContact; m_radiusDisplay = a_radiusDisplay; // set the radius of the contact model of the proxy m_algorithmFingerProxy->setProxyRadius(m_radiusContact); // set radius of proxy and goal. goal radius is slightly smaller to avoid graphical // artifacts when both sphere are located at the same position. m_sphereProxy->setRadius(m_radiusDisplay); m_sphereGoal->setRadius(0.95 * m_radiusDisplay); } //============================================================================== /*! This method sets the radius size of the physical proxy. \param a_radiusContact New radius for contact computation (proxy). */ //============================================================================== void cHapticPoint::setRadiusContact(double a_radiusContact) { m_radiusContact = a_radiusContact; // set the radius of the contact model of the proxy m_algorithmFingerProxy->setProxyRadius(m_radiusContact); } //============================================================================== /*! This method sets the radius size of the sphere used to display the proxy and goal position. \param a_radiusDisplay New radius for display of spheres (proxy and goal). */ //============================================================================== void cHapticPoint::setRadiusDisplay(double a_radiusDisplay) { m_radiusDisplay = a_radiusDisplay; // set radius of proxy and goal. goal radius is slightly smaller to avoid graphical // artifacts when both sphere are located at the same position. m_sphereProxy->setRadius(m_radiusDisplay); m_sphereGoal->setRadius(0.99 * m_radiusDisplay); } //============================================================================== /*! This method sets the display options of the goal and proxy spheres. If both spheres are enabled, a small line is drawn between both spheres. \param a_showProxy If __true__, then the proxy sphere is displayed. \param a_showGoal If __true__, then the goal sphere is displayed. \param a_colorLine Color of line connecting proxy to goal spheres. */ //============================================================================== void cHapticPoint::setShow(bool a_showProxy, bool a_showGoal, cColorf a_colorLine) { // update display properties of both spheres m_sphereProxy->setShowEnabled(a_showProxy); m_sphereGoal->setShowEnabled(a_showGoal); m_colorLine = a_colorLine; } //============================================================================== /*! This method creates an audio source for this haptic point. \param a_audioDevice Audio device. */ //============================================================================== bool cHapticPoint::createAudioSource(cAudioDevice* a_audioDevice) { // sanity check if (a_audioDevice == NULL) { return (C_ERROR); } // create three audio sources for impact for (int i=0; i<3; i++) { m_audioSourceImpact[i] = new cAudioSource(); } // create three audio sources for friction for (int i=0; i<3; i++) { m_audioSourceFriction[i] = new cAudioSource(); } // audio sources have been created and are now enabled m_useAudioSources = true; // success return (C_SUCCESS); } //============================================================================== /*! This method computes all interaction forces between the tool haptic points and the virtual environment. \param a_globalPos New desired goal position. \param a_globalRot New desired goal rotation. \param a_globalLinVel Linear velocity of tool. \param a_globalAngVel Angular velocity of tool. \return Computed interaction force in world coordinates. */ //============================================================================== cVector3d cHapticPoint::computeInteractionForces(cVector3d& a_globalPos, cMatrix3d& a_globalRot, cVector3d& a_globalLinVel, cVector3d& a_globalAngVel) { /////////////////////////////////////////////////////////////////////////// // ALGORITHM FINGER PROXY /////////////////////////////////////////////////////////////////////////// // we first consider all object the proxy may have been in contact with and // mark their interaction as no longer active. for (int i=0; i<3; i++) { if (m_meshProxyContacts[i] != NULL) { m_meshProxyContacts[i]->m_interactionInside = false; cMultiMesh* multiMesh = dynamic_cast<cMultiMesh*>(m_meshProxyContacts[i]->getOwner()); if (multiMesh != NULL) { multiMesh->m_interactionInside = false; } m_meshProxyContacts[i] = NULL; } } // we now update the new position of a goal point and update the proxy position. // As a result, the force contribution from the proxy is now calculated. cVector3d force0 = m_algorithmFingerProxy->computeForces(a_globalPos, a_globalLinVel); // we now flag each mesh for which the proxy may be interacting with. This information is // necessary for haptic effects that may be associated with these mesh objects. for (int i=0; i<3; i++) { if (m_algorithmFingerProxy->m_collisionEvents[i]->m_object != NULL) { m_meshProxyContacts[i] = m_algorithmFingerProxy->m_collisionEvents[i]->m_object; cGenericObject* object = m_meshProxyContacts[i]; object->m_interactionInside = true; object->m_interactionPoint = m_algorithmFingerProxy->m_collisionEvents[i]->m_localPos; object->m_interactionNormal = m_algorithmFingerProxy->m_collisionEvents[i]->m_localNormal; cMultiMesh* multiMesh = dynamic_cast<cMultiMesh*>(m_meshProxyContacts[i]->getOwner()); if (multiMesh != NULL) { multiMesh->m_interactionInside = true; multiMesh->m_interactionPoint = cAdd(object->getLocalPos(), cMul(object->getLocalRot(),object->m_interactionPoint)); multiMesh->m_interactionNormal = cMul(object->getLocalRot(), object->m_interactionNormal); } } } /////////////////////////////////////////////////////////////////////////// // ALGORITHM POTENTIAL FIELD /////////////////////////////////////////////////////////////////////////// // compute interaction forces (haptic effects) in world coordinates between tool and all // objects for which haptic effects have been programmed cVector3d force1 = m_algorithmPotentialField->computeForces(a_globalPos, a_globalLinVel); /////////////////////////////////////////////////////////////////////////// // FINALIZATION /////////////////////////////////////////////////////////////////////////// // update position of proxy and goal spheres in tool coordinates updateSpherePositions(); // finally return the contribution from both force models. force0.addr(force1, m_lastComputedGlobalForce); /////////////////////////////////////////////////////////////////////////// // AUDIO /////////////////////////////////////////////////////////////////////////// // force magnitude double force = m_lastComputedGlobalForce.length(); // velocity of tool double velocity = m_parentTool->getDeviceGlobalLinVel().length(); // friction sound if (m_useAudioSources) { for (int i=0; i<3; i++) { /////////////////////////////////////////////////////////////////// // FRICTION SOUND /////////////////////////////////////////////////////////////////// m_audioSourceFriction[i]->setSourcePos(a_globalPos); // if tool is not in contact, or material does not exist, turn off sound. if (m_meshProxyContacts[i] == NULL) { m_audioSourceFriction[i]->setGain(0.0); } // if tool is in contact and material exist else { // check if tool is touching a new material, in which case we swap audio buffers if (m_meshProxyContacts[i]->m_material->getAudioFrictionBuffer() != NULL) { if (m_audioSourceFriction[i]->getAudioBuffer() != m_meshProxyContacts[i]->m_material->getAudioFrictionBuffer()) { m_audioSourceFriction[i]->stop(); m_audioSourceFriction[i]->setGain(0.0); m_audioSourceFriction[i]->setPitch(1.0); m_audioSourceFriction[i]->setAudioBuffer(m_meshProxyContacts[i]->m_material->getAudioFrictionBuffer()); m_audioSourceFriction[i]->setLoop(true); m_audioSourceFriction[i]->play(); } } // we compute an angle that compares the velocity of the tool with the reaction force. This friction maximizes // returns a value between o.0 and 1.0 which maximize tangential forces, versus normal forces. The higher // the tangential force, the higher the sound level. This is slightly hacky but could be improved by // taking the exact tangential component of the force. double angleFactor = 0.0; if ((force > C_SMALL) && (velocity > C_SMALL)) { angleFactor = cSqr(cSqr(sin(cAngle(m_lastComputedGlobalForce, m_parentTool->getDeviceGlobalLinVel())))) ; } // adjust audio gains according to material properties, and force and velocity of tool. m_audioSourceFriction[i]->setGain((float)(m_meshProxyContacts[i]->m_material->getAudioFrictionGain() * angleFactor * force * cSqr(velocity))); m_audioSourceFriction[i]->setPitch((float)(m_meshProxyContacts[i]->m_material->getAudioFrictionPitchOffset() + m_meshProxyContacts[i]->m_material->getAudioFrictionPitchGain() * velocity)); } /////////////////////////////////////////////////////////////////// // IMAPCT SOUND /////////////////////////////////////////////////////////////////// m_audioSourceImpact[i]->setSourcePos(a_globalPos); if ((m_audioProxyContacts[i] == NULL) && (m_meshProxyContacts[i] != NULL)) { if ((m_audioSourceImpact[i]->getAudioBuffer() != m_meshProxyContacts[i]->m_material->getAudioImpactBuffer()) && (m_meshProxyContacts[i]->m_material->getAudioImpactBuffer() != NULL)) { m_audioSourceImpact[i]->stop(); m_audioSourceImpact[i]->setAudioBuffer(m_meshProxyContacts[i]->m_material->getAudioImpactBuffer()); m_audioSourceImpact[i]->setLoop(false); } m_audioSourceImpact[i]->setGain((float)(m_meshProxyContacts[i]->m_material->getAudioImpactGain() * cSqr(velocity))); m_audioSourceImpact[i]->play(); } // update contact list m_audioProxyContacts[i] = m_meshProxyContacts[i]; } } // return result return (m_lastComputedGlobalForce); } //============================================================================== /*! This method checks if the tool is touching a particular object passed as argument. \param a_object Object to checked for possible contact. \return __true__ if the object is in contact with tool, __false__ otherwise. */ //============================================================================== bool cHapticPoint::isInContact(cGenericObject* a_object) { ///////////////////////////////////////////////////////////////////// // verify finger-proxy algorithm ///////////////////////////////////////////////////////////////////// // contact 0 if (m_algorithmFingerProxy->m_collisionEvents[0]->m_object == a_object) { return (true); } // contact 1 if ((m_algorithmFingerProxy->m_collisionEvents[0]->m_object != NULL) && (m_algorithmFingerProxy->m_collisionEvents[1]->m_object == a_object)) { return (true); } // contact 2 if ((m_algorithmFingerProxy->m_collisionEvents[0]->m_object != NULL) && (m_algorithmFingerProxy->m_collisionEvents[1]->m_object != NULL) && (m_algorithmFingerProxy->m_collisionEvents[2]->m_object == a_object)) { return (true); } ///////////////////////////////////////////////////////////////////// // verify potential-field algorithm ///////////////////////////////////////////////////////////////////// unsigned int num = (int)(m_algorithmPotentialField->m_interactionRecorder.m_interactions.size()); unsigned int i = 0; while (i < num) { // check next interaction if (m_algorithmPotentialField->m_interactionRecorder.m_interactions[i].m_object == a_object) { return (true); } // increment counter i++; } // no object in contact return (false); } //============================================================================== /*! This method renders the tool graphically using OpenGL. \param a_options Rendering options. */ //============================================================================== void cHapticPoint::render(cRenderOptions& a_options) { #ifdef C_USE_OPENGL ///////////////////////////////////////////////////////////////////////// // Render parts that are always opaque ///////////////////////////////////////////////////////////////////////// if (SECTION_RENDER_OPAQUE_PARTS_ONLY(a_options)) { // render line only if both spheres are enabled for display if (m_sphereProxy->getShowEnabled() && m_sphereGoal->getShowEnabled()) { // disable lighting glDisable(GL_LIGHTING); // points describe line extremities cVector3d posA = m_sphereProxy->getLocalPos(); cVector3d posB = m_sphereGoal->getLocalPos(); // draw line glBegin(GL_LINES); m_colorLine.render(); glVertex3dv(&posA(0) ); glVertex3dv(&posB(0) ); glEnd(); // restore lighting to default value glEnable(GL_LIGHTING); } } ///////////////////////////////////////////////////////////////////////// // Render other objects ///////////////////////////////////////////////////////////////////////// // render proxy sphere m_sphereProxy->renderSceneGraph(a_options); // render goal sphere m_sphereGoal->renderSceneGraph(a_options); // render proxy algorithm (debug purposes) //m_algorithmFingerProxy->render(a_options); #endif } //============================================================================== /*! This method updates the position of the spheres in tool coordinates. The position of the actual proxy and goal spheres need to be expressed in the tool's local coordinate system. This comes from the fact that the contact points are rendered at the same time as the tool, respectively when the OpenGL model view matrix corresponds to the one of the parent tool. */ //============================================================================== void cHapticPoint::updateSpherePositions() { // sanity check if (m_parentTool == NULL) { return; } // position and orientation of tool in world global coordinates cMatrix3d toolGlobalRot = m_parentTool->getGlobalRot(); // temp variables cVector3d pos; cMatrix3d rot; toolGlobalRot.transr(rot); // update position of proxy sphere pos = getLocalPosProxy(); m_sphereProxy->setLocalPos(pos); // update position of goal sphere pos = getLocalPosGoal(); m_sphereGoal->setLocalPos(pos); } //------------------------------------------------------------------------------ } // namespace chai3d //------------------------------------------------------------------------------
27,569
7,508
/* * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved. * * SSL viewer tool, SecureTransport / Aspen version. */ #include <Security/SecureTransport.h> #include <Security/SecureTransportPriv.h> // for SSLGetPeerSecTrust #include <Security/SecTrustPriv.h> #include "sslAppUtils.h" #include "ioSock.h" #include "utilities/fileIo.h" #include "utilities/SecCFWrappers.h" #include <Security/SecBase.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> #include <CoreFoundation/CoreFoundation.h> #include "SecurityTool/print_cert.h" #include <utilities/SecIOFormat.h> #if NO_SERVER #include <securityd/spi.h> #endif #define DEFAULT_GETMSG "GET" #define DEFAULT_PATH "/" #define DEFAULT_GET_SUFFIX "HTTP/1.0\r\n\r\n" #define DEFAULT_HOST "www.amazon.com" #define DEFAULT_PORT 443 #include <Security/SecCertificate.h> static void usageNorm(char **argv) { printf("Usage: %s [hostname|-] [path] [option ...]\n", argv[0]); printf(" %s hostname [path] [option ...]\n", argv[0]); printf("Specifying '-' for hostname, or no args, uses default of %s.\n", DEFAULT_HOST); printf("Optional path argument must start with leading '/'.\n"); printf("Options:\n"); printf(" e Allow Expired Certs\n"); printf(" E Allow Expired Roots\n"); printf(" r Allow any root cert\n"); printf(" c Display peer certs\n"); printf(" c c Display peer SecTrust\n"); printf(" d Display received data\n"); printf(" 2 SSLv2 only (default is TLSv1)\n"); printf(" 3 SSLv3 only (default is TLSv1)\n"); printf(" t TLSv1\n"); printf(" %% TLSv1.1 only\n"); printf(" ^ TLSv1.2 only\n"); printf(" L all - TLSv1.2, TLSv1.1, TLSv1.0, SSLv3, SSLv2 (default = TLSv1.2)\n"); printf(" g={prot...} Specify legal protocols; prot = any combo of" " [23t]\n"); printf(" k=keychain Contains cert and keys. Optional.\n"); printf(" l=loopCount Perform loopCount ops (default = 1)\n"); printf(" P=port Default = %d\n", DEFAULT_PORT); printf(" p Pause after each loop\n"); printf(" q Quiet/diagnostic mode (site names and errors" " only)\n"); printf(" a fileName Add fileName to list of trusted roots\n"); printf(" A fileName fileName is ONLY trusted root\n"); printf(" x Disable Cert Verification\n"); printf(" z=password Unlock client keychain with password.\n"); printf(" 8 Complete cert chains (default is out cert is a root)\n"); printf(" s Silent\n"); printf(" V Verbose\n"); printf(" h Help\n"); printf(" hv More, verbose help\n"); } static void usageVerbose(char **argv) __attribute__((noreturn)); static void usageVerbose(char **argv) { usageNorm(argv); printf("Obscure Usage:\n"); printf(" u kSSLProtocolUnknown only (TLSv1)\n"); printf(" M Manual cert verification via " "SecTrustEvaluate\n"); printf(" f fileBase Write Peer Certs to fileBase*\n"); printf(" o TLSv1, SSLv3 use kSSLProtocol__X__Only\n"); printf(" C=cipherSuite (e=40-bit d=DES D=40-bit DES 3=3DES 4=RC4 " "$=40-bit RC4\n" " 2=RC2 a=AES128 A=AES256 h=DH H=Anon DH r=DHE/RSA s=DH/DSS\n"); printf(" y=keychain Encryption-only cert and keys. Optional.\n"); printf(" K Keep connected until server disconnects\n"); printf(" n Require closure notify message in TLSv1, " "SSLv3 mode (implies K)\n"); printf(" R Disable resumable session support\n"); printf(" b Non-blocking I/O\n"); printf(" v Verify negotiated protocol equals attempted\n"); printf(" m=[23t] Max protocol supported as specified; implies " "v\n"); printf(" T=[nrsj] Verify client cert state = " "none/requested/sent/rejected\n"); printf(" H allow hostname spoofing\n"); printf(" F=vfyHost Verify certs with specified host name\n"); printf(" G=getMsg Specify entire GET, POST, etc.\n"); printf(" N Log handshake timing\n"); printf(" 7 Pause only after first loop\n"); exit(1); } static void usage(char **argv) __attribute__((noreturn)); static void usage(char **argv) { usageNorm(argv); exit(1); } /* * Arguments to top-level sslPing() */ typedef struct { SSLProtocol tryVersion; // only used if acceptedProts NULL // uses SSLSetProtocolVersion char *acceptedProts; // optional, any combo of {2,3,t} // uses SSLSetProtocolVersionEnabled const char *hostName; // e.g., "www.amazon.com" const char *vfyHostName; // use this for cert vfy if non-NULL, // else use hostName unsigned short port; const char *getMsg; // e.g., // "GET / HTTP/1.0\r\n\r\n" bool allowExpired; bool allowAnyRoot; bool allowExpiredRoot; bool disableCertVerify; bool manualCertVerify; bool dumpRxData; // display server data char cipherRestrict; // '2', 'd'. etc...; '\0' for // no restriction bool keepConnected; bool requireNotify; // require closure notify // in V3 mode bool resumableEnable; bool allowHostnameSpoof; bool nonBlocking; char *anchorFile; bool replaceAnchors; CFArrayRef clientCerts; // optional CFArrayRef encryptClientCerts; // optional bool quiet; // minimal stdout bool silent; // no stdout bool verbose; SSLProtocol negVersion; // RETURNED SSLCipherSuite negCipher; // RETURNED CFArrayRef peerCerts; // mallocd & RETURNED SecTrustRef peerTrust; // RETURNED SSLClientCertificateState certState; // RETURNED char *password; // optional to open clientCerts char **argv; Boolean sessionWasResumed; unsigned char sessionID[MAX_SESSION_ID_LENGTH]; size_t sessionIDLength; CFAbsoluteTime handshakeTimeOp; // time for this op CFAbsoluteTime handshakeTimeFirst; // time for FIRST op, not averaged CFAbsoluteTime handshakeTimeTotal; // time for all ops except first unsigned numHandshakes; } sslPingArgs; #include <signal.h> static void sigpipe(int sig) { fflush(stdin); printf("***SIGPIPE***\n"); } /* * Snag a copy of current connection's peer certs so we can * examine them later after the connection is closed. * SecureTransport actually does the create and retain for us. */ static OSStatus copyPeerCerts( SSLContext *ctx, CFArrayRef *peerCerts) // mallocd & RETURNED { OSStatus ortn = SSLCopyPeerCertificates(ctx, peerCerts); if(ortn) { printf("***Error obtaining peer certs: %s\n", sslGetSSLErrString(ortn)); } return ortn; } /* free the cert array obtained via SSLGetPeerCertificates() */ static void freePeerCerts( CFArrayRef peerCerts) { if(peerCerts) { CFRelease(peerCerts); } } /* * Manually evaluate session's SecTrustRef. */ #define SSL_SEC_TRUST 1 static OSStatus sslEvaluateTrust( SSLContext *ctx, bool verbose, bool silent, CFArrayRef *peerCerts) // fetched and retained { OSStatus ortn = errSecSuccess; #if USE_CDSA_CRYPTO SecTrustRef secTrust = NULL; #if SSL_SEC_TRUST ortn = SSLGetPeerSecTrust(ctx, &secTrust); #else ortn = errSecUnimplemented; #endif if(ortn) { printf("\n***Error obtaining peer SecTrustRef: %s\n", sslGetSSLErrString(ortn)); return ortn; } if(secTrust == NULL) { /* this is the normal case for resumed sessions, in which * no cert evaluation is performed */ if(!silent) { printf("...No SecTrust available - this is a resumed session, right?\n"); } return errSecSuccess; } SecTrustResultType secTrustResult; ortn = SecTrustEvaluate(secTrust, &secTrustResult); if(ortn) { printf("\n***Error on SecTrustEvaluate: %d\n", (int)ortn); return ortn; } if(verbose) { char *res = NULL; switch(secTrustResult) { case kSecTrustResultInvalid: res = "kSecTrustResultInvalid"; break; case kSecTrustResultProceed: res = "kSecTrustResultProceed"; break; case kSecTrustResultConfirm: res = "kSecTrustResultConfirm"; break; case kSecTrustResultDeny: res = "kSecTrustResultDeny"; break; case kSecTrustResultUnspecified: res = "kSecTrustResultUnspecified"; break; case kSecTrustResultRecoverableTrustFailure: res = "kSecTrustResultRecoverableTrustFailure"; break; case kSecTrustResultFatalTrustFailure: res = "kSecTrustResultFatalTrustFailure"; break; case kSecTrustResultOtherError: res = "kSecTrustResultOtherError"; break; default: res = "UNKNOWN"; break; } printf("\nSecTrustEvaluate(): secTrustResult %s\n", res); } switch(secTrustResult) { case kSecTrustResultUnspecified: /* cert chain valid, no special UserTrust assignments */ case kSecTrustResultProceed: /* cert chain valid AND user explicitly trusts this */ break; default: printf("\n***SecTrustEvaluate reported secTrustResult %d\n", (int)secTrustResult); ortn = errSSLXCertChainInvalid; break; } #endif *peerCerts = NULL; #ifdef USE_CDSA_CRYPTO /* one more thing - get peer certs in the form of an evidence chain */ CSSM_TP_APPLE_EVIDENCE_INFO *dummyEv; OSStatus thisRtn = SecTrustGetResult(secTrust, &secTrustResult, peerCerts, &dummyEv); if(thisRtn) { printSslErrStr("SecTrustGetResult", thisRtn); } else { /* workaround for the fact that SSLGetPeerCertificates() * leaves a retain count on each element in the returned array, * requiring us to do a release on each cert. */ CFIndex numCerts = CFArrayGetCount(*peerCerts); for(CFIndex dex=0; dex<numCerts; dex++) { CFRetain(CFArrayGetValueAtIndex(*peerCerts, dex)); } } #endif return ortn; } /* print reply received from server, safely */ static void dumpAscii( uint8_t *rcvBuf, size_t len) { char *cp = (char *)rcvBuf; uint32_t i; char c; for(i=0; i<len; i++) { c = *cp++; if(c == '\0') { break; } switch(c) { case '\n': printf("\\n"); break; case '\r': printf("\\r"); break; default: if(isprint(c) && (c != '\n')) { printf("%c", c); } else { printf("<%02X>", ((unsigned)c) & 0xff); } break; } } printf("\n"); } /* * Perform one SSL diagnostic session. Returns nonzero on error. Normally no * output to stdout except initial "connecting to" message, unless there * is a really screwed up error (i.e., something not directly related * to the SSL connection). */ #define RCV_BUF_SIZE 256 static OSStatus sslPing( sslPingArgs *pargs) { PeerSpec peerId; otSocket sock = 0; OSStatus ortn; SSLContextRef ctx = NULL; size_t length; size_t actLen; uint8_t rcvBuf[RCV_BUF_SIZE]; CFAbsoluteTime startHandshake; CFAbsoluteTime endHandshake; pargs->negVersion = kSSLProtocolUnknown; pargs->negCipher = SSL_NULL_WITH_NULL_NULL; pargs->peerCerts = NULL; /* first make sure requested server is there */ ortn = MakeServerConnection(pargs->hostName, pargs->port, pargs->nonBlocking, &sock, &peerId); if(ortn) { printf("MakeServerConnection returned %d; aborting\n", (int)ortn); return ortn; } if(pargs->verbose) { printf("...connected to server; starting SecureTransport\n"); } /* * Set up a SecureTransport session. * First the standard calls. */ ortn = SSLNewContext(false, &ctx); if(ortn) { printSslErrStr("SSLNewContext", ortn); goto cleanup; } ortn = SSLSetIOFuncs(ctx, SocketRead, SocketWrite); if(ortn) { printSslErrStr("SSLSetIOFuncs", ortn); goto cleanup; } ortn = SSLSetConnection(ctx, (SSLConnectionRef)(intptr_t)sock); if(ortn) { printSslErrStr("SSLSetConnection", ortn); goto cleanup; } SSLConnectionRef getConn; ortn = SSLGetConnection(ctx, &getConn); if(ortn) { printSslErrStr("SSLGetConnection", ortn); goto cleanup; } if(getConn != (SSLConnectionRef)(intptr_t)sock) { printf("***SSLGetConnection error\n"); ortn = errSecParam; goto cleanup; } if(!pargs->allowHostnameSpoof) { /* if this isn't set, it isn't checked by AppleX509TP */ const char *vfyHost = pargs->hostName; if(pargs->vfyHostName) { /* generally means we're expecting an error */ vfyHost = pargs->vfyHostName; } ortn = SSLSetPeerDomainName(ctx, vfyHost, strlen(vfyHost)); if(ortn) { printSslErrStr("SSLSetPeerDomainName", ortn); goto cleanup; } } /* * SecureTransport options. */ if(pargs->acceptedProts) { ortn = SSLSetProtocolVersionEnabled(ctx, kSSLProtocolAll, false); if(ortn) { printSslErrStr("SSLSetProtocolVersionEnabled(all off)", ortn); goto cleanup; } for(const char *cp = pargs->acceptedProts; *cp; cp++) { SSLProtocol prot; switch(*cp) { case '2': prot = kSSLProtocol2; break; case '3': prot = kSSLProtocol3; break; case 't': prot = kTLSProtocol12; break; default: usage(pargs->argv); } ortn = SSLSetProtocolVersionEnabled(ctx, prot, true); if(ortn) { printSslErrStr("SSLSetProtocolVersionEnabled", ortn); goto cleanup; } } } else { ortn = SSLSetProtocolVersion(ctx, pargs->tryVersion); if(ortn) { printSslErrStr("SSLSetProtocolVersion", ortn); goto cleanup; } SSLProtocol getVers; ortn = SSLGetProtocolVersion(ctx, &getVers); if(ortn) { printSslErrStr("SSLGetProtocolVersion", ortn); goto cleanup; } if(getVers != pargs->tryVersion) { printf("***SSLGetProtocolVersion screwup: try %s get %s\n", sslGetProtocolVersionString(pargs->tryVersion), sslGetProtocolVersionString(getVers)); ortn = errSecParam; goto cleanup; } } if(pargs->resumableEnable) { const void *rtnId = NULL; size_t rtnIdLen = 0; ortn = SSLSetPeerID(ctx, &peerId, sizeof(PeerSpec)); if(ortn) { printSslErrStr("SSLSetPeerID", ortn); goto cleanup; } /* quick test of the get fcn */ ortn = SSLGetPeerID(ctx, &rtnId, &rtnIdLen); if(ortn) { printSslErrStr("SSLGetPeerID", ortn); goto cleanup; } if((rtnId == NULL) || (rtnIdLen != sizeof(PeerSpec))) { printf("***SSLGetPeerID screwup\n"); } else if(memcmp(&peerId, rtnId, rtnIdLen) != 0) { printf("***SSLGetPeerID data mismatch\n"); } } if(pargs->allowExpired) { ortn = SSLSetAllowsExpiredCerts(ctx, true); if(ortn) { printSslErrStr("SSLSetAllowExpiredCerts", ortn); goto cleanup; } } if(pargs->allowExpiredRoot) { ortn = SSLSetAllowsExpiredRoots(ctx, true); if(ortn) { printSslErrStr("SSLSetAllowsExpiredRoots", ortn); goto cleanup; } } if(pargs->disableCertVerify) { ortn = SSLSetEnableCertVerify(ctx, false); if(ortn) { printSslErrStr("SSLSetEnableCertVerify", ortn); goto cleanup; } } if(pargs->allowAnyRoot) { ortn = SSLSetAllowsAnyRoot(ctx, true); if(ortn) { printSslErrStr("SSLSetAllowAnyRoot", ortn); goto cleanup; } } if(pargs->cipherRestrict != '\0') { ortn = sslSetCipherRestrictions(ctx, pargs->cipherRestrict); if(ortn) { goto cleanup; } } if(pargs->anchorFile) { ortn = sslAddTrustedRoot(ctx, pargs->anchorFile, pargs->replaceAnchors); if(ortn) { printf("***Error obtaining anchor file %s\n", pargs->anchorFile); goto cleanup; } } if(pargs->clientCerts) { CFArrayRef dummy; if(pargs->anchorFile == NULL) { /* assume this is a root we want to implicitly trust */ ortn = addIdentityAsTrustedRoot(ctx, pargs->clientCerts); if(ortn) { goto cleanup; } } ortn = SSLSetCertificate(ctx, pargs->clientCerts); if(ortn) { printSslErrStr("SSLSetCertificate", ortn); goto cleanup; } /* quickie test for this new function */ ortn = SSLGetCertificate(ctx, &dummy); if(ortn) { printSslErrStr("SSLGetCertificate", ortn); goto cleanup; } if(dummy != pargs->clientCerts) { printf("***SSLGetCertificate error\n"); ortn = errSecIO; goto cleanup; } } if(pargs->encryptClientCerts) { if(pargs->anchorFile == NULL) { ortn = addIdentityAsTrustedRoot(ctx, pargs->encryptClientCerts); if(ortn) { goto cleanup; } } ortn = SSLSetEncryptionCertificate(ctx, pargs->encryptClientCerts); if(ortn) { printSslErrStr("SSLSetEncryptionCertificate", ortn); goto cleanup; } } /*** end options ***/ if(pargs->verbose) { printf("...starting SSL handshake\n"); } startHandshake = CFAbsoluteTimeGetCurrent(); do { ortn = SSLHandshake(ctx); if((ortn == errSSLWouldBlock) && !pargs->silent) { /* keep UI responsive */ sslOutputDot(); } } while (ortn == errSSLWouldBlock); endHandshake = CFAbsoluteTimeGetCurrent(); pargs->handshakeTimeOp = endHandshake - startHandshake; if(pargs->numHandshakes == 0) { /* special case, this one is always way longer */ pargs->handshakeTimeFirst = pargs->handshakeTimeOp; } else { /* normal running total */ pargs->handshakeTimeTotal += pargs->handshakeTimeOp; } pargs->numHandshakes++; /* this works even if handshake failed due to cert chain invalid */ if(!pargs->manualCertVerify) { copyPeerCerts(ctx, &pargs->peerCerts); } else { /* else fetched via SecTrust later */ pargs->peerCerts = NULL; } ortn = SSLCopyPeerTrust(ctx, &pargs->peerTrust); if(ortn) { printf("***SSLCopyPeerTrust error %" PRIdOSStatus "\n", ortn); pargs->peerTrust = NULL; } /* ditto */ SSLGetClientCertificateState(ctx, &pargs->certState); SSLGetNegotiatedCipher(ctx, &pargs->negCipher); SSLGetNegotiatedProtocolVersion(ctx, &pargs->negVersion); pargs->sessionIDLength = MAX_SESSION_ID_LENGTH; SSLGetResumableSessionInfo(ctx, &pargs->sessionWasResumed, pargs->sessionID, &pargs->sessionIDLength); if(pargs->manualCertVerify) { OSStatus certRtn = sslEvaluateTrust(ctx, pargs->verbose, pargs->silent, &pargs->peerCerts); if(certRtn && !ortn ) { ortn = certRtn; } } if(ortn) { if(!pargs->silent) { printf("\n"); } goto cleanup; } if(pargs->verbose) { printf("...SSL handshake complete\n"); } length = strlen(pargs->getMsg); (void) SSLWrite(ctx, pargs->getMsg, length, &actLen); /* * Try to snag RCV_BUF_SIZE bytes. Exit if (!keepConnected and we get any data * at all), or (keepConnected and err != (none, wouldBlock)). */ while (1) { actLen = 0; if(pargs->dumpRxData) { size_t avail = 0; ortn = SSLGetBufferedReadSize(ctx, &avail); if(ortn) { printf("***SSLGetBufferedReadSize error\n"); break; } if(avail != 0) { printf("\n%d bytes available: ", (int)avail); } } ortn = SSLRead(ctx, rcvBuf, RCV_BUF_SIZE, &actLen); if((actLen == 0) && !pargs->silent) { sslOutputDot(); } if((actLen == 0) && (ortn == errSecSuccess)) { printf("***Radar 2984932 confirmed***\n"); } if (ortn == errSSLWouldBlock) { /* for this loop, these are identical */ ortn = errSecSuccess; } if((actLen > 0) && pargs->dumpRxData) { dumpAscii(rcvBuf, actLen); } if(ortn != errSecSuccess) { /* connection closed by server or by error */ break; } if(!pargs->keepConnected && (actLen > 0)) { /* good enough, we connected */ break; } } if(!pargs->silent) { printf("\n"); } /* snag these again in case of renegotiate */ SSLGetClientCertificateState(ctx, &pargs->certState); SSLGetNegotiatedCipher(ctx, &pargs->negCipher); SSLGetNegotiatedProtocolVersion(ctx, &pargs->negVersion); /* convert normal "shutdown" into zero err rtn */ if(ortn == errSSLClosedGraceful) { ortn = errSecSuccess; } if((ortn == errSSLClosedNoNotify) && !pargs->requireNotify) { /* relaxed disconnect rules */ ortn = errSecSuccess; } cleanup: /* * always do close, even on error - to flush outgoing write queue */ OSStatus cerr = SSLClose(ctx); if(ortn == errSecSuccess) { ortn = cerr; } if(sock) { endpointShutdown(sock); } if(ctx) { SSLDisposeContext(ctx); } return ortn; } static void add_key(const void *key, const void *value, void *context) { CFArrayAppendValue((CFMutableArrayRef)context, key); } static void showInfo(CFDictionaryRef info) { CFIndex dict_count, key_ix, key_count; CFMutableArrayRef keys = NULL; CFIndex maxWidth = 20; /* Maybe precompute this or grab from context? */ dict_count = CFDictionaryGetCount(info); keys = CFArrayCreateMutable(kCFAllocatorDefault, dict_count, &kCFTypeArrayCallBacks); CFDictionaryApplyFunction(info, add_key, keys); key_count = CFArrayGetCount(keys); CFArraySortValues(keys, CFRangeMake(0, key_count), (CFComparatorFunction)CFStringCompare, 0); for (key_ix = 0; key_ix < key_count; ++key_ix) { CFStringRef key = (CFStringRef)CFArrayGetValueAtIndex(keys, key_ix); CFTypeRef value = CFDictionaryGetValue(info, key); CFMutableStringRef line = CFStringCreateMutable(NULL, 0); CFStringAppend(line, key); CFIndex jx; for (jx = CFStringGetLength(key); jx < maxWidth; ++jx) { CFStringAppend(line, CFSTR(" ")); } CFStringAppend(line, CFSTR(" : ")); if (CFStringGetTypeID() == CFGetTypeID(value)) { CFStringAppend(line, (CFStringRef)value); } else if (CFDateGetTypeID() == CFGetTypeID(value)) { CFLocaleRef lc = CFLocaleCopyCurrent(); CFDateFormatterRef df = CFDateFormatterCreate(NULL, lc, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle); CFDateRef date = (CFDateRef)value; CFStringRef ds = CFDateFormatterCreateStringWithDate(NULL, df, date); CFStringAppend(line, ds); CFRelease(ds); CFRelease(df); CFRelease(lc); } else if (CFURLGetTypeID() == CFGetTypeID(value)) { CFURLRef url = (CFURLRef)value; CFStringAppend(line, CFSTR("<")); CFStringAppend(line, CFURLGetString(url)); CFStringAppend(line, CFSTR(">")); } else if (CFDataGetTypeID() == CFGetTypeID(value)) { CFDataRef v_d = (CFDataRef)value; CFStringRef v_s = CFStringCreateFromExternalRepresentation( kCFAllocatorDefault, v_d, kCFStringEncodingUTF8); if (v_s) { CFStringAppend(line, CFSTR("/")); CFStringAppend(line, v_s); CFStringAppend(line, CFSTR("/ ")); CFRelease(v_s); } const uint8_t *bytes = CFDataGetBytePtr(v_d); CFIndex len = CFDataGetLength(v_d); for (jx = 0; jx < len; ++jx) { CFStringAppendFormat(line, NULL, CFSTR("%.02X"), bytes[jx]); } } else { CFStringAppendFormat(line, NULL, CFSTR("%@"), value); } CFStringWriteToFileWithNewline(line, stdout); CFRelease(line); } CFRelease(keys); } static void showPeerTrust(SecTrustRef peerTrust, bool verbose) { CFIndex numCerts; CFIndex i; if(peerTrust == NULL) { return; } printf("\n=============== Peer Trust Properties ===============\n"); CFArrayRef plist = SecTrustCopyProperties(peerTrust); if (plist) { print_plist(plist); CFRelease(plist); } printf("\n================== Peer Trust Info ==================\n"); CFDictionaryRef info = SecTrustCopyInfo(peerTrust); if (info && CFDictionaryGetCount(info)) { showInfo(info); } if (info) CFRelease(info); numCerts = SecTrustGetCertificateCount(peerTrust); for(i=0; i<numCerts; i++) { plist = SecTrustCopySummaryPropertiesAtIndex(peerTrust, i); printf("\n============= Peer Trust Cert %lu Summary =============\n\n", i); print_plist(plist); if (plist) CFRelease(plist); printf("\n============= Peer Trust Cert %lu Details =============\n\n", i); plist = SecTrustCopyDetailedPropertiesAtIndex(peerTrust, i); print_plist(plist); if (plist) CFRelease(plist); printf("\n============= End of Peer Trust Cert %lu ==============\n", i); } } static void showPeerCerts( CFArrayRef peerCerts, bool verbose) { CFIndex numCerts; SecCertificateRef certRef; CFIndex i; if(peerCerts == NULL) { return; } numCerts = CFArrayGetCount(peerCerts); for(i=0; i<numCerts; i++) { certRef = (SecCertificateRef)CFArrayGetValueAtIndex(peerCerts, i); printf("\n==================== Peer Cert %lu ====================\n\n", i); print_cert(certRef, verbose); printf("\n================ End of Peer Cert %lu =================\n", i); } } static void writePeerCerts( CFArrayRef peerCerts, const char *fileBase) { CFIndex numCerts; SecCertificateRef certRef; CFIndex i; char fileName[100]; if(peerCerts == NULL) { return; } numCerts = CFArrayGetCount(peerCerts); for(i=0; i<numCerts; i++) { sprintf(fileName, "%s%02d.cer", fileBase, (int)i); certRef = (SecCertificateRef)CFArrayGetValueAtIndex(peerCerts, i); CFDataRef derCert = SecCertificateCopyData(certRef); if (derCert) { writeFile(fileName, CFDataGetBytePtr(derCert), CFDataGetLength(derCert)); CFRelease(derCert); } } printf("...wrote %lu certs to fileBase %s\n", numCerts, fileBase); } /* * Show result of an sslPing(). * Assumes the following from sslPingArgs: * * verbose * tryVersion * acceptedProts * negVersion * negCipher * peerCerts * certState * sessionWasResumed * sessionID * sessionIDLength * handshakeTime */ static void showSSLResult( const sslPingArgs &pargs, OSStatus err, int displayPeerCerts, char *fileBase) // non-NULL: write certs to file { CFIndex numPeerCerts; printf("\n"); if(pargs.acceptedProts) { printf(" Allowed SSL versions : %s\n", pargs.acceptedProts); } else { printf(" Attempted SSL version : %s\n", sslGetProtocolVersionString(pargs.tryVersion)); } printf(" Result : %s\n", sslGetSSLErrString(err)); printf(" Negotiated SSL version : %s\n", sslGetProtocolVersionString(pargs.negVersion)); printf(" Negotiated CipherSuite : %s\n", sslGetCipherSuiteString(pargs.negCipher)); if(pargs.certState != kSSLClientCertNone) { printf(" Client Cert State : %s\n", sslGetClientCertStateString(pargs.certState)); } if(pargs.verbose) { printf(" Resumed Session : "); if(pargs.sessionWasResumed) { for(unsigned dex=0; dex<pargs.sessionIDLength; dex++) { printf("%02X ", pargs.sessionID[dex]); if(((dex % 8) == 7) && (dex != (pargs.sessionIDLength - 1))) { printf("\n "); } } printf("\n"); } else { printf("NOT RESUMED\n"); } printf(" Handshake time : %f seconds\n", pargs.handshakeTimeOp); } if(pargs.peerCerts == NULL) { numPeerCerts = 0; } else { numPeerCerts = CFArrayGetCount(pargs.peerCerts); } printf(" Number of server certs : %lu\n", numPeerCerts); if(numPeerCerts != 0) { if (displayPeerCerts == 1) { showPeerCerts(pargs.peerCerts, false); } else if (displayPeerCerts == 2) { showPeerTrust(pargs.peerTrust, false); } if(fileBase != NULL) { writePeerCerts(pargs.peerCerts, fileBase); } } printf("\n"); } static int verifyProtocol( bool verifyProt, SSLProtocol maxProtocol, SSLProtocol reqProtocol, SSLProtocol negProtocol) { if(!verifyProt) { return 0; } if(reqProtocol > maxProtocol) { /* known not to support this attempt, relax */ reqProtocol = maxProtocol; } if(reqProtocol != negProtocol) { printf("***Expected protocol %s; negotiated %s\n", sslGetProtocolVersionString(reqProtocol), sslGetProtocolVersionString(negProtocol)); return 1; } else { return 0; } } static int verifyClientCertState( bool verifyCertState, SSLClientCertificateState expectState, SSLClientCertificateState gotState) { if(!verifyCertState) { return 0; } if(expectState == gotState) { return 0; } printf("***Expected clientCertState %s; got %s\n", sslGetClientCertStateString(expectState), sslGetClientCertStateString(gotState)); return 1; } static SSLProtocol charToProt( char c, // 2, 3, t char **argv) { switch(c) { case '2': return kSSLProtocol2; case '3': return kSSLProtocol3; case 't': return kTLSProtocol12; default: usage(argv); } /* NOT REACHED */ return kSSLProtocolUnknown; } int main(int argc, char **argv) { OSStatus err; int arg; char *argp; char getMsg[300]; char fullFileBase[100]; int ourRtn = 0; // exit status - sum of all errors unsigned loop; SecKeychainRef serverKc = nil; SecKeychainRef encryptKc = nil; sslPingArgs pargs; /* user-spec'd parameters */ const char *getPath = DEFAULT_PATH; char *fileBase = NULL; int displayCerts = 0; bool doSslV2 = false; bool doSslV3 = false; bool doTlsV1 = true; bool doTlsV11 = false; bool doTlsV12 = false; bool protXOnly = false; // kSSLProtocol3Only, kTLSProtocol1Only bool doProtUnknown = false; unsigned loopCount = 1; bool doPause = false; bool pauseFirstLoop = false; bool verifyProt = false; SSLProtocol maxProtocol = kTLSProtocol12; // for verifying negotiated // protocol char *acceptedProts = NULL; char *keyChainName = NULL; char *encryptKeyChainName = NULL; char *getMsgSpec = NULL; bool vfyCertState = false; SSLClientCertificateState expectCertState = kSSLClientCertNone; bool displayHandshakeTimes = false; bool completeCertChain = false; /* special case - one arg of "h" or "-h" or "hv" */ if(argc == 2) { if((strcmp(argv[1], "h") == 0) || (strcmp(argv[1], "-h") == 0)) { usage(argv); } if(strcmp(argv[1], "hv") == 0) { usageVerbose(argv); } } /* set up defaults */ memset(&pargs, 0, sizeof(sslPingArgs)); pargs.hostName = DEFAULT_HOST; pargs.port = DEFAULT_PORT; pargs.resumableEnable = true; pargs.argv = argv; for(arg=1; arg<argc; arg++) { argp = argv[arg]; if(arg == 1) { /* first arg, is always hostname; '-' means default */ if(argp[0] != '-') { pargs.hostName = argp; } continue; } if(argp[0] == '/') { /* path always starts with leading slash */ getPath = argp; continue; } /* options */ switch(argp[0]) { case 'e': pargs.allowExpired = true; break; case 'E': pargs.allowExpiredRoot = true; break; case 'x': pargs.disableCertVerify = true; break; case 'M': pargs.disableCertVerify = true; // implied pargs.manualCertVerify = true; break; case 'a': if(++arg == argc) { /* requires another arg */ usage(argv); } pargs.anchorFile = argv[arg]; break; case 'A': if(++arg == argc) { /* requires another arg */ usage(argv); } pargs.anchorFile = argv[arg]; pargs.replaceAnchors = true; break; case 'r': pargs.allowAnyRoot = true; break; case 'd': pargs.dumpRxData = true; break; case 'c': displayCerts++; break; case 'f': if(++arg == argc) { /* requires another arg */ usage(argv); } fileBase = argv[arg]; break; case 'C': pargs.cipherRestrict = argp[2]; break; case '2': doSslV3 = doTlsV1 = doTlsV11 = false; doSslV2 = true; break; case '3': doSslV2 = doTlsV1 = doTlsV11 = doTlsV12 = false; doSslV3 = true; break; case 't': doSslV2 = doSslV3 = doTlsV11 = doTlsV12 = false; doTlsV1 = true; break; case '%': doSslV2 = doSslV3 = doTlsV1 = false; doTlsV11 = true; break; case '^': doSslV2 = doSslV3 = doTlsV1 = doTlsV12 = false; doTlsV12 = true; break; case 'L': doSslV2 = doSslV3 = doTlsV1 = doTlsV11 = doTlsV12 = true; break; case 'o': protXOnly = true; break; case 'u': doSslV2 = doSslV3 = doTlsV1 = doTlsV11 = doTlsV12 = false; doProtUnknown = true; break; case 'K': pargs.keepConnected = true; break; case 'n': pargs.requireNotify = true; pargs.keepConnected = true; break; case 'R': pargs.resumableEnable = false; break; case 'b': pargs.nonBlocking = true; break; case 'v': verifyProt = true; break; case 'm': if(argp[1] != '=') { usage(argv); } verifyProt = true; // implied maxProtocol = charToProt(argp[2], argv); break; case 'g': if(argp[1] != '=') { usage(argv); } acceptedProts = &argp[2]; doSslV3 = doSslV2 = doTlsV1 = doTlsV11 = doTlsV12 = false; break; case 'l': loopCount = atoi(&argp[2]); if(loopCount == 0) { printf("***bad loopCount\n"); usage(argv); } break; case 'P': pargs.port = atoi(&argp[2]); break; case 'H': pargs.allowHostnameSpoof = true; break; case 'F': pargs.vfyHostName = &argp[2]; break; case 'k': keyChainName = &argp[2]; break; case 'y': encryptKeyChainName = &argp[2]; break; case 'G': getMsgSpec = &argp[2]; break; case 'T': if(argp[1] != '=') { usage(argv); } vfyCertState = true; switch(argp[2]) { case 'n': expectCertState = kSSLClientCertNone; break; case 'r': expectCertState = kSSLClientCertRequested; break; case 's': expectCertState = kSSLClientCertSent; break; case 'j': expectCertState = kSSLClientCertRejected; break; default: usage(argv); } break; case 'z': pargs.password = &argp[2]; break; case 'p': doPause = true; break; case '7': pauseFirstLoop = true; break; case 'q': pargs.quiet = true; break; case 'V': pargs.verbose = true; break; case 's': pargs.silent = pargs.quiet = true; break; case 'N': displayHandshakeTimes = true; break; case '8': completeCertChain = true; break; case 'h': if(pargs.verbose || (argp[1] == 'v')) { usageVerbose(argv); } else { usage(argv); } default: usage(argv); } } if(getMsgSpec) { pargs.getMsg = getMsgSpec; } else { sprintf(getMsg, "%s %s %s", DEFAULT_GETMSG, getPath, DEFAULT_GET_SUFFIX); pargs.getMsg = getMsg; } #if NO_SERVER # if DEBUG securityd_init(NULL); # endif #endif /* get client cert and optional encryption cert as CFArrayRef */ if(keyChainName) { pargs.clientCerts = getSslCerts(keyChainName, false, completeCertChain, pargs.anchorFile, &serverKc); if(pargs.clientCerts == nil) { exit(1); } #ifdef USE_CDSA_CRYPTO if(pargs.password) { OSStatus ortn = SecKeychainUnlock(serverKc, strlen(pargs.password), pargs.password, true); if(ortn) { printf("SecKeychainUnlock returned %d\n", (int)ortn); /* oh well */ } } #endif } if(encryptKeyChainName) { pargs.encryptClientCerts = getSslCerts(encryptKeyChainName, true, completeCertChain, pargs.anchorFile, &encryptKc); if(pargs.encryptClientCerts == nil) { exit(1); } } signal(SIGPIPE, sigpipe); for(loop=0; loop<loopCount; loop++) { /* * One pass for each protocol version, skipping any explicit version if * an attempt at a higher version and succeeded in doing so successfully fell * back. */ if(doTlsV12) { pargs.tryVersion = kTLSProtocol12; pargs.acceptedProts = NULL; if(!pargs.silent) { printf("Connecting to host %s with TLS V1.2...", pargs.hostName); } fflush(stdout); err = sslPing(&pargs); if(err) { ourRtn++; } if(!pargs.quiet) { if(fileBase) { sprintf(fullFileBase, "%s_v3.1", fileBase); } showSSLResult(pargs, err, displayCerts, fileBase ? fullFileBase : NULL); } freePeerCerts(pargs.peerCerts); if(!err) { /* deal with fallbacks, skipping redundant tests */ switch(pargs.negVersion) { case kTLSProtocol11: doTlsV11 =false; break; case kTLSProtocol1: doTlsV11 =false; doTlsV1 =false; break; case kSSLProtocol3: doTlsV11 =false; doTlsV1 =false; doSslV3 = false; break; case kSSLProtocol2: doTlsV11 =false; doTlsV1 =false; doSslV3 = false; doSslV2 = false; break; default: break; } ourRtn += verifyProtocol(verifyProt, maxProtocol, kTLSProtocol12, pargs.negVersion); } /* note we do this regardless since the client state might be * the cause of a failure */ ourRtn += verifyClientCertState(vfyCertState, expectCertState, pargs.certState); } if(doTlsV11) { pargs.tryVersion = kTLSProtocol11; pargs.acceptedProts = NULL; if(!pargs.silent) { printf("Connecting to host %s with TLS V1.1...", pargs.hostName); } fflush(stdout); err = sslPing(&pargs); if(err) { ourRtn++; } if(!pargs.quiet) { if(fileBase) { sprintf(fullFileBase, "%s_v3.1", fileBase); } showSSLResult(pargs, err, displayCerts, fileBase ? fullFileBase : NULL); } freePeerCerts(pargs.peerCerts); if(!err) { /* deal with fallbacks, skipping redundant tests */ switch(pargs.negVersion) { case kTLSProtocol1: doTlsV1 =false; break; case kSSLProtocol3: doTlsV1 =false; doSslV3 = false; break; case kSSLProtocol2: doTlsV1 =false; doSslV3 = false; doSslV2 = false; break; default: break; } ourRtn += verifyProtocol(verifyProt, maxProtocol, kTLSProtocol11, pargs.negVersion); } /* note we do this regardless since the client state might be * the cause of a failure */ ourRtn += verifyClientCertState(vfyCertState, expectCertState, pargs.certState); } if(doTlsV1) { pargs.tryVersion = protXOnly ? kTLSProtocol1Only : kTLSProtocol1; pargs.acceptedProts = NULL; if(!pargs.silent) { printf("Connecting to host %s with TLS V1...", pargs.hostName); } fflush(stdout); err = sslPing(&pargs); if(err) { ourRtn++; } if(!pargs.quiet) { if(fileBase) { sprintf(fullFileBase, "%s_v3.1", fileBase); } showSSLResult(pargs, err, displayCerts, fileBase ? fullFileBase : NULL); } freePeerCerts(pargs.peerCerts); if(!err) { /* deal with fallbacks, skipping redundant tests */ switch(pargs.negVersion) { case kSSLProtocol3: doSslV3 = false; break; case kSSLProtocol2: doSslV3 = false; doSslV2 = false; break; default: break; } ourRtn += verifyProtocol(verifyProt, maxProtocol, kTLSProtocol1, pargs.negVersion); } /* note we do this regardless since the client state might be * the cause of a failure */ ourRtn += verifyClientCertState(vfyCertState, expectCertState, pargs.certState); } if(doSslV3) { pargs.tryVersion = protXOnly ? kSSLProtocol3Only : kSSLProtocol3; pargs.acceptedProts = NULL; if(!pargs.silent) { printf("Connecting to host %s with SSL V3...", pargs.hostName); } fflush(stdout); err = sslPing(&pargs); if(err) { ourRtn++; } if(!pargs.quiet) { if(fileBase) { sprintf(fullFileBase, "%s_v3.0", fileBase); } showSSLResult(pargs, err, displayCerts, fileBase ? fullFileBase : NULL); } freePeerCerts(pargs.peerCerts); if(!err) { /* deal with fallbacks, skipping redundant tests */ switch(pargs.negVersion) { case kSSLProtocol2: doSslV2 = false; break; default: break; } ourRtn += verifyProtocol(verifyProt, maxProtocol, kSSLProtocol3, pargs.negVersion); } /* note we do this regardless since the client state might be * the cause of a failure */ ourRtn += verifyClientCertState(vfyCertState, expectCertState, pargs.certState); } if(doSslV2) { if(fileBase) { sprintf(fullFileBase, "%s_v2", fileBase); } if(!pargs.silent) { printf("Connecting to host %s with SSL V2...", pargs.hostName); } fflush(stdout); pargs.tryVersion = kSSLProtocol2; pargs.acceptedProts = NULL; err = sslPing(&pargs); if(err) { ourRtn++; } if(!pargs.quiet) { if(fileBase) { sprintf(fullFileBase, "%s_v2", fileBase); } showSSLResult(pargs, err, displayCerts, fileBase ? fullFileBase : NULL); } freePeerCerts(pargs.peerCerts); if(!err) { ourRtn += verifyProtocol(verifyProt, maxProtocol, kSSLProtocol2, pargs.negVersion); } /* note we do this regardless since the client state might be * the cause of a failure */ ourRtn += verifyClientCertState(vfyCertState, expectCertState, pargs.certState); } if(doProtUnknown) { if(!pargs.silent) { printf("Connecting to host %s with kSSLProtocolUnknown...", pargs.hostName); } fflush(stdout); pargs.tryVersion = kSSLProtocolUnknown; pargs.acceptedProts = NULL; err = sslPing(&pargs); if(err) { ourRtn++; } if(!pargs.quiet) { if(fileBase) { sprintf(fullFileBase, "%s_def", fileBase); } showSSLResult(pargs, err, displayCerts, fileBase ? fullFileBase : NULL); } freePeerCerts(pargs.peerCerts); } if(acceptedProts != NULL) { pargs.acceptedProts = acceptedProts; pargs.tryVersion = kSSLProtocolUnknown; // not used if(!pargs.silent) { printf("Connecting to host %s with acceptedProts %s...", pargs.hostName, pargs.acceptedProts); } fflush(stdout); err = sslPing(&pargs); if(err) { ourRtn++; } if(!pargs.quiet) { if(fileBase) { sprintf(fullFileBase, "%s_def", fileBase); } showSSLResult(pargs, err, displayCerts, fileBase ? fullFileBase : NULL); } freePeerCerts(pargs.peerCerts); } if(doPause || (pauseFirstLoop && /* pause after first, before last to grab trace */ ((loop == 0) || (loop == loopCount - 1)) ) ) { char resp; fpurge(stdin); printf("a to abort, c to continue: "); resp = getchar(); if(resp == 'a') { break; } } } /* main loop */ if(displayHandshakeTimes) { CFAbsoluteTime totalTime; unsigned numHandshakes; if(pargs.numHandshakes == 1) { /* just display the first one */ totalTime = pargs.handshakeTimeFirst; numHandshakes = 1; } else { /* skip the first one */ totalTime = pargs.handshakeTimeTotal; numHandshakes = pargs.numHandshakes - 1; } if(numHandshakes != 0) { printf(" %u handshakes in %f seconds; %f seconds per handshake\n", numHandshakes, totalTime, (totalTime / numHandshakes)); } } //printCertShutdown(); if(ourRtn) { printf("===%s exiting with %d %s for host %s\n", argv[0], ourRtn, (ourRtn > 1) ? "errors" : "error", pargs.hostName); } return ourRtn; }
43,655
18,368
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2021 Intel Corporation */ #pragma once #include <memory> #include <set> #include "../allocator.hpp" #include "../utils/utils.hpp" #include "kvdk/namespace.hpp" namespace KVDK_NAMESPACE { constexpr uint32_t kFreelistMaxClassifiedBlockSize = 255; constexpr uint32_t kSpaceMapLockGranularity = 64; class PMEMAllocator; // A byte map to record free blocks of PMem space, used for merging adjacent // free space entries in the free list class SpaceMap { public: SpaceMap(uint64_t num_blocks) : map_(num_blocks, {false, 0}), lock_granularity_(kSpaceMapLockGranularity), map_spins_(num_blocks / lock_granularity_ + 1) {} uint64_t TestAndUnset(uint64_t offset, uint64_t length); uint64_t TryMerge(uint64_t offset, uint64_t max_merge_length, uint64_t min_merge_length); void Set(uint64_t offset, uint64_t length); uint64_t Size() { return map_.size(); } private: // The highest 1 bit ot the token indicates if this is the start of a space // entry, the lower 7 bits indicate how many free blocks followed struct Token { public: Token(bool is_start, uint8_t size) : token_(size | (is_start ? (1 << 7) : 0)) {} uint8_t Size() { return token_ & INT8_MAX; } void Clear() { token_ = 0; } bool Empty() { return Size() == 0; } bool IsStart() { return token_ & (1 << 7); } void UnStart() { token_ &= INT8_MAX; } private: uint8_t token_; }; // how many blocks share a lock const uint32_t lock_granularity_; std::vector<Token> map_; // every lock_granularity_ bytes share a spin lock std::vector<SpinMutex> map_spins_; }; // free entry pool consists of three level vectors, the first level // indicates different block size, each block size consists of several free // space entry lists (the second level), and each list consists of several // free space entries (the third level). // // For a specific block size, a write thread will move a entry list from the // pool to its thread cache while no usable free space in the cache, and the // background thread will move cached entry list to the pool for merge and // balance resource // // Organization of the three level vectors: // // block size (1st level) entry list (2nd level) entries (3th level) // 1 ----------------- list1 ------------ entry1 // | |--- entry2 // |----- list2 ------------ entry1 // |--- entry2 // |--- entry3 // ... // 2 ----------------- list1 ------------ entry1 // | |--- entry2 // | |--- entry3 // |----- list2 // ... // ... // max_block_size -------- list1 // |----- list2 class SpaceEntryPool { public: SpaceEntryPool(uint32_t max_classified_b_size) : pool_(max_classified_b_size), spins_(max_classified_b_size) {} // move a list of b_size free space entries to pool, "src" will be empty // after move void MoveEntryList(std::vector<PMemOffsetType> &src, uint32_t b_size) { std::lock_guard<SpinMutex> lg(spins_[b_size]); assert(b_size < pool_.size()); pool_[b_size].emplace_back(); pool_[b_size].back().swap(src); } // try to fetch a b_size free space entries list from pool to dst bool TryFetchEntryList(std::vector<PMemOffsetType> &dst, uint32_t b_size) { if (pool_[b_size].size() != 0) { std::lock_guard<SpinMutex> lg(spins_[b_size]); if (pool_[b_size].size() != 0) { dst.swap(pool_[b_size].back()); pool_[b_size].pop_back(); return true; } } return false; } private: std::vector<std::vector<std::vector<PMemOffsetType>>> pool_; // Entry lists of a same block size share a spin lock std::vector<SpinMutex> spins_; }; class Freelist { public: Freelist(uint32_t max_classified_b_size, uint64_t num_segment_blocks, uint32_t block_size, uint32_t num_threads, uint64_t num_blocks, PMEMAllocator *allocator) : num_segment_blocks_(num_segment_blocks), block_size_(block_size), max_classified_b_size_(max_classified_b_size), active_pool_(max_classified_b_size), merged_pool_(max_classified_b_size), space_map_(num_blocks), flist_thread_cache_(num_threads, max_classified_b_size), pmem_allocator_(allocator) {} Freelist(uint64_t num_segment_blocks, uint32_t block_size, uint32_t num_threads, uint64_t num_blocks, PMEMAllocator *allocator) : Freelist(kFreelistMaxClassifiedBlockSize, num_segment_blocks, block_size, num_threads, num_blocks, allocator) {} // Add a space entry void Push(const SpaceEntry &entry); // Request a at least "size" free space entry bool Get(uint32_t size, SpaceEntry *space_entry); // Try to merge thread-cached free space entries to get a at least "size" // entry bool MergeGet(uint32_t size, SpaceEntry *space_entry); // Merge adjacent free spaces stored in the entry pool into larger one // // Fetch every free space entry lists from active_pool_, for each entry in the // list, try to merge followed free space with it. Then insert merged entries // into merged_pool_. After merging, move all entry lists from merged_pool_ to // active_pool_ for next run. Calculate the minimal timestamp of free entries // in the pool meantime // TODO: set a condition to decide if we need to do merging void MergeAndCheckTSInPool(); // Move cached free space list to space entry pool to balance usable space // of write threads // // Iterate every active entry lists of thread caches, move the list to // active_pool_, and update minimal timestamp of free entries meantime void MoveCachedListsToPool(); // Origanize free space entries, including merging adjacent space and move // thread cached space entries to pool void OrganizeFreeSpace(); private: // Each write threads cache some freed space entries in active_entry_offsets // to avoid contention. To balance free space entries among threads, if too // many entries cached by a thread, newly freed entries will be stored to // backup_entries and move to entry pool which shared by all threads. struct alignas(64) FlistThreadCache { FlistThreadCache(uint32_t max_classified_b_size) : active_entry_offsets(max_classified_b_size), spins(max_classified_b_size) {} FlistThreadCache() = delete; FlistThreadCache(FlistThreadCache &&) = delete; FlistThreadCache(const FlistThreadCache &) = delete; // Entry size stored in block unit Array<std::vector<PMemOffsetType>> active_entry_offsets; // Protect active_entry_offsets Array<SpinMutex> spins; }; class SpaceCmp { public: bool operator()(const SpaceEntry &s1, const SpaceEntry &s2) const { return s1.size > s2.size; } }; uint64_t MergeSpace(uint64_t offset, uint64_t max_size, uint64_t min_merge_size) { if (min_merge_size > max_size) { return 0; } uint64_t size = space_map_.TryMerge(offset, max_size, min_merge_size); return size; } const uint64_t num_segment_blocks_; const uint32_t block_size_; const uint32_t max_classified_b_size_; SpaceMap space_map_; Array<FlistThreadCache> flist_thread_cache_; SpaceEntryPool active_pool_; SpaceEntryPool merged_pool_; // Store all large free space entries that larger than max_classified_b_size_ std::set<SpaceEntry, SpaceCmp> large_entries_; SpinMutex large_entries_spin_; PMEMAllocator *pmem_allocator_; }; } // namespace KVDK_NAMESPACE
7,852
2,540
/* oscpack -- Open Sound Control packet manipulation library http://www.audiomulch.com/~rossb/oscpack Copyright (c) 2004-2005 Ross Bencina <rossb@audiomulch.com> 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. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. 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 "OscPrintReceivedElements.h" #include <iostream> #include <iomanip> #include <ctime> namespace osc{ std::ostream& operator<<( std::ostream & os, const ReceivedMessageArgument& arg ) { switch( arg.TypeTag() ){ case TRUE_TYPE_TAG: os << "bool:true"; break; case FALSE_TYPE_TAG: os << "bool:false"; break; case NIL_TYPE_TAG: os << "(Nil)"; break; case INFINITUM_TYPE_TAG: os << "(Infinitum)"; break; case INT32_TYPE_TAG: os << "int32:" << arg.AsInt32Unchecked(); break; case FLOAT_TYPE_TAG: os << "float32:" << arg.AsFloatUnchecked(); break; case CHAR_TYPE_TAG: { char s[2] = {0}; s[0] = arg.AsCharUnchecked(); os << "char:'" << s << "'"; } break; case RGBA_COLOR_TYPE_TAG: { uint32 color = arg.AsRgbaColorUnchecked(); os << "RGBA:0x" << std::hex << std::setfill('0') << std::setw(2) << (int)((color>>24) & 0xFF) << std::setw(2) << (int)((color>>16) & 0xFF) << std::setw(2) << (int)((color>>8) & 0xFF) << std::setw(2) << (int)(color & 0xFF) << std::setfill(' '); os.unsetf(std::ios::basefield); } break; case MIDI_MESSAGE_TYPE_TAG: { uint32 m = arg.AsMidiMessageUnchecked(); os << "midi (port, status, data1, data2):<<" << std::hex << std::setfill('0') << "0x" << std::setw(2) << (int)((m>>24) & 0xFF) << " 0x" << std::setw(2) << (int)((m>>16) & 0xFF) << " 0x" << std::setw(2) << (int)((m>>8) & 0xFF) << " 0x" << std::setw(2) << (int)(m & 0xFF) << std::setfill(' ') << ">>"; os.unsetf(std::ios::basefield); } break; case INT64_TYPE_TAG: os << "int64:" << arg.AsInt64Unchecked(); break; case TIME_TAG_TYPE_TAG: { os << "OSC-timetag:" << arg.AsTimeTagUnchecked(); std::time_t t = (unsigned long)( arg.AsTimeTagUnchecked() >> 32 ); // strip trailing newline from string returned by ctime const char *timeString = std::ctime( &t ); size_t len = strlen( timeString ); char *s = new char[ len + 1 ]; strcpy( s, timeString ); if( len ) s[ len - 1 ] = '\0'; os << " " << s; } break; case DOUBLE_TYPE_TAG: os << "double:" << arg.AsDoubleUnchecked(); break; case STRING_TYPE_TAG: os << "OSC-string:`" << arg.AsStringUnchecked() << "'"; break; case SYMBOL_TYPE_TAG: os << "OSC-string (symbol):`" << arg.AsSymbolUnchecked() << "'"; break; case BLOB_TYPE_TAG: { unsigned long size; const void *data; arg.AsBlobUnchecked( data, size ); os << "OSC-blob:<<" << std::hex << std::setfill('0'); unsigned char *p = (unsigned char*)data; for( unsigned long i = 0; i < size; ++i ){ os << "0x" << std::setw(2) << int(p[i]); if( i != size-1 ) os << ' '; } os.unsetf(std::ios::basefield); os << ">>" << std::setfill(' '); } break; default: os << "unknown"; } return os; } std::ostream& operator<<( std::ostream & os, const ReceivedMessage& m ) { os << "[" << m.AddressPattern(); bool first = true; for( ReceivedMessage::const_iterator i = m.ArgumentsBegin(); i != m.ArgumentsEnd(); ++i ){ if( first ){ os << " "; first = false; }else{ os << ", "; } os << *i; } os << "]"; return os; } std::ostream& operator<<( std::ostream & os, const ReceivedBundle& b ) { static int indent = 0; for( int j=0; j < indent; ++j ) os << " "; os << "{ ( "; if( b.TimeTag() == 1 ) os << "immediate"; else os << b.TimeTag(); os << " )\n"; ++indent; for( ReceivedBundle::const_iterator i = b.ElementsBegin(); i != b.ElementsEnd(); ++i ){ if( i->IsBundle() ){ ReceivedBundle b(*i); os << b << "\n"; }else{ ReceivedMessage m(*i); for( int j=0; j < indent; ++j ) os << " "; os << m << "\n"; } } --indent; for( int j=0; j < indent; ++j ) os << " "; os << "}"; return os; } std::ostream& operator<<( std::ostream & os, const ReceivedPacket& p ) { if( p.IsBundle() ){ ReceivedBundle b(p); os << b << "\n"; }else{ ReceivedMessage m(p); os << m << "\n"; } return os; } } // namespace osc
5,554
2,485
#include "mandelbrot.hpp" #include <FL/fl_draw.H> Mandelbrot::Mandelbrot(int max_iter, int screen_width, int screen_height, double start_x, double end_x, double start_y, double end_y, double zoom_center_x, double zoom_center_y, double zoom_coeff) : max_iter(max_iter), screen_width(screen_width), screen_height(screen_height), start_x(start_x), start_y(start_y), end_x(end_x), end_y(end_y), zoom_center_x(zoom_center_x), zoom_center_y(zoom_center_y), zoom_coeff(zoom_coeff) { } Mandelbrot::~Mandelbrot() {} void Mandelbrot::draw() { // fl_point(int x, int y) -> draws a pixel at x,y // fl_color(FL_Color|int c) -> sets the color // fl_rgb_color(uchar g) -> returns grayscale for (int i = 0; i < screen_height; i++) { for (int j = 0; j < screen_width; j++) { unsigned char color = set[i][j]; Fl_Color grayscale = fl_rgb_color(color); fl_color(grayscale); fl_point(j, i); // (j,i) and not (i,j) because i=y and j=x on screen } } } void Mandelbrot::calculate() { // init variables set = std::vector<std::vector<unsigned char>>(); double coeff = 255.0 / (double) max_iter; double step_x = (end_x - start_x) / screen_width; double step_y = (end_y - start_y) / screen_height; // unsigned char value; // loop for (double y = start_y; y < end_y; y += step_y) { std::vector<unsigned char> row; for (double x = start_x; x < end_x; x += step_x) { int num_iter = calculate_point(std::complex<double>(x, y), max_iter); value = (unsigned char) (255.0 - (((double) num_iter) * coeff)); row.push_back(value); } set.push_back(row); } } void Mandelbrot::calculate_and_draw() { // init variables double coeff = 255.0 / (double) max_iter; double step_x = (end_x - start_x) / screen_width; double step_y = (end_y - start_y) / screen_height; // unsigned char value; // loop int i = 0; for (double y = start_y; y < end_y; y += step_y) { std::vector<unsigned char> row; int j = 0; for (double x = start_x; x < end_x; x += step_x) { int num_iter = calculate_point(std::complex<double>(x, y), max_iter); value = (unsigned char) (255.0 - (((double) num_iter) * coeff)); // draw pixel Fl_Color grayscale = fl_rgb_color(value); fl_color(grayscale); fl_point(j, i); j++; } i++; } } void Mandelbrot::zoom() { // calculate distances double distance_left = zoom_center_x - start_x, distance_right = end_x - zoom_center_x, distance_top = zoom_center_y - start_y, distance_bottom = end_y - zoom_center_y; // calculate zoom distances double zoom_left = distance_left * zoom_coeff, zoom_right = distance_right * zoom_coeff, zoom_top = distance_top * zoom_coeff, zoom_bottom = distance_bottom * zoom_coeff; // apply changes start_x += zoom_left; start_y += zoom_top; end_x -= zoom_right; end_y -= zoom_bottom; } int Mandelbrot::calculate_point(std::complex<double> z, int max_iter, int threshold) { int num_iter = 0; std::complex<double> c = z; while (num_iter < max_iter && abs(z) < threshold) { z = z * z + c; num_iter++; } return num_iter; }
3,048
1,292
namespace hise { using namespace juce; //============================================================================== struct HiseJavascriptEngine::RootObject::TokenIterator { TokenIterator(const String& code, const String &externalFile) : location(code, externalFile), p(code.getCharPointer()) { skip(); } DebugableObject::Location createDebugLocation() { DebugableObject::Location loc; loc.fileName = location.externalFile; loc.charNumber = (int)(location.location - location.program.getCharPointer()); return loc; } void skip() { skipWhitespaceAndComments(); location.location = p; currentType = matchNextToken(); } void skipBlock() { match(TokenTypes::openBrace); int braceCount = 1; while (currentType != TokenTypes::eof && braceCount > 0) { if (currentType == TokenTypes::openBrace) braceCount++; else if (currentType == TokenTypes::closeBrace) braceCount--; skip(); } } void match(TokenType expected) { if (currentType != expected) location.throwError("Found " + getTokenName(currentType) + " when expecting " + getTokenName(expected)); skip(); } bool matchIf(TokenType expected) { if (currentType == expected) { skip(); return true; } return false; } bool matchesAny(TokenType t1, TokenType t2) const { return currentType == t1 || currentType == t2; } bool matchesAny(TokenType t1, TokenType t2, TokenType t3) const { return matchesAny(t1, t2) || currentType == t3; } CodeLocation location; TokenType currentType; var currentValue; void clearLastComment() { lastComment = String(); } String lastComment; void skipWhitespaceAndComments() { for (;;) { p = p.findEndOfWhitespace(); if (*p == '/') { const juce_wchar c2 = p[1]; if (c2 == '/') { p = CharacterFunctions::find(p, (juce_wchar) '\n'); continue; } if (c2 == '*') { location.location = p; lastComment = String(p).upToFirstOccurrenceOf("*/", false, false).fromFirstOccurrenceOf("/**", false, false).trim(); p = CharacterFunctions::find(p + 2, CharPointer_ASCII("*/")); if (p.isEmpty()) location.throwError("Unterminated '/*' comment"); p += 2; continue; } } break; } } private: String::CharPointerType p; static bool isIdentifierStart(const juce_wchar c) noexcept{ return CharacterFunctions::isLetter(c) || c == '_'; } static bool isIdentifierBody(const juce_wchar c) noexcept{ return CharacterFunctions::isLetterOrDigit(c) || c == '_'; } TokenType matchNextToken() { if (isIdentifierStart(*p)) { String::CharPointerType end(p); while (isIdentifierBody(*++end)) {} const size_t len = (size_t)(end - p); #define JUCE_JS_COMPARE_KEYWORD(name, str) if (len == sizeof (str) - 1 && matchToken (TokenTypes::name, len)) return TokenTypes::name; JUCE_JS_KEYWORDS(JUCE_JS_COMPARE_KEYWORD) currentValue = String(p, end); p = end; return TokenTypes::identifier; } if (p.isDigit()) { if (parseHexLiteral() || parseFloatLiteral() || parseOctalLiteral() || parseDecimalLiteral()) return TokenTypes::literal; location.throwError("Syntax error in numeric constant"); } if (parseStringLiteral(*p) || (*p == '.' && parseFloatLiteral())) return TokenTypes::literal; #define JUCE_JS_COMPARE_OPERATOR(name, str) if (matchToken (TokenTypes::name, sizeof (str) - 1)) return TokenTypes::name; JUCE_JS_OPERATORS(JUCE_JS_COMPARE_OPERATOR) if (!p.isEmpty()) location.throwError("Unexpected character '" + String::charToString(*p) + "' in source"); return TokenTypes::eof; } bool matchToken(TokenType name, const size_t len) noexcept { if (p.compareUpTo(CharPointer_ASCII(name), (int)len) != 0) return false; p += (int)len; return true; } bool parseStringLiteral(juce_wchar quoteType) { if (quoteType != '"' && quoteType != '\'') return false; Result r(JSON::parseQuotedString(p, currentValue)); if (r.failed()) location.throwError(r.getErrorMessage()); return true; } bool parseHexLiteral() { if (*p != '0' || (p[1] != 'x' && p[1] != 'X')) return false; String::CharPointerType t(++p); int64 v = CharacterFunctions::getHexDigitValue(*++t); if (v < 0) return false; for (;;) { const int digit = CharacterFunctions::getHexDigitValue(*++t); if (digit < 0) break; v = v * 16 + digit; } currentValue = v; p = t; return true; } bool parseFloatLiteral() { int numDigits = 0; String::CharPointerType t(p); while (t.isDigit()) { ++t; ++numDigits; } const bool hasPoint = (*t == '.'); if (hasPoint) while ((++t).isDigit()) ++numDigits; if (numDigits == 0) return false; juce_wchar c = *t; const bool hasExponent = (c == 'e' || c == 'E'); if (hasExponent) { c = *++t; if (c == '+' || c == '-') ++t; if (!t.isDigit()) return false; while ((++t).isDigit()) {} } if (!(hasExponent || hasPoint)) return false; currentValue = CharacterFunctions::getDoubleValue(p); p = t; return true; } bool parseOctalLiteral() { String::CharPointerType t(p); int64 v = *t - '0'; if (v != 0) return false; // first digit of octal must be 0 for (;;) { const int digit = (int)(*++t - '0'); if (isPositiveAndBelow(digit, 8)) v = v * 8 + digit; else if (isPositiveAndBelow(digit, 10)) location.throwError("Decimal digit in octal constant"); else break; } currentValue = v; p = t; return true; } bool parseDecimalLiteral() { int64 v = 0; for (;; ++p) { const int digit = (int)(*p - '0'); if (isPositiveAndBelow(digit, 10)) v = v * 10 + digit; else break; } currentValue = v; return true; } }; //============================================================================== struct HiseJavascriptEngine::RootObject::ExpressionTreeBuilder : private TokenIterator { ExpressionTreeBuilder(const String code, const String externalFile) : TokenIterator(code, externalFile) { #if ENABLE_SCRIPTING_BREAKPOINTS if (externalFile.isNotEmpty()) { fileId = Identifier("File_" + File(externalFile).getFileNameWithoutExtension()); } #endif } void setupApiData(HiseSpecialData &data, const String& codeToPreprocess) { hiseSpecialData = &data; currentNamespace = hiseSpecialData; #if 0 //ENABLE_SCRIPTING_BREAKPOINTS Identifier localId = hiseSpecialData->getBreakpointLocalIdentifier(); if (localId.isValid()) { if (hiseSpecialData->getCallback(localId) != nullptr) { currentlyParsedCallback = localId; } else if (auto obj = hiseSpecialData->getInlineFunction(localId)) { currentInlineFunction = obj; currentlyParsingInlineFunction = true; } } #endif if(codeToPreprocess.isNotEmpty()) preprocessCode(codeToPreprocess); } void preprocessCode(const String& codeToPreprocess, const String& externalFileName=""); BlockStatement* parseStatementList() { ScopedPointer<BlockStatement> b(new BlockStatement(location)); while (currentType != TokenTypes::closeBrace && currentType != TokenTypes::eof) { #if ENABLE_SCRIPTING_BREAKPOINTS const int64 charactersBeforeToken = (location.location - location.program.getCharPointer()); ScopedPointer<Statement> s = parseStatement(); const int64 charactersAfterToken = (location.location - location.program.getCharPointer()); Range<int64> r(charactersBeforeToken, charactersAfterToken); for (int i = 0; i < breakpoints.size(); i++) { const bool isOtherFile = !fileId.isNull() && breakpoints[i].snippetId != fileId; const bool isFileButOnInit = fileId.isNull() && breakpoints[i].snippetId.toString().startsWith("File"); if (isOtherFile || isFileButOnInit) continue; if (breakpoints[i].found) continue; if (r.contains(breakpoints[i].charIndex)) { if (currentInlineFunction != nullptr) { if (getCurrentNamespace() != hiseSpecialData) { const String combination = currentNamespace->id.toString() + "." + dynamic_cast<InlineFunction::Object*>(currentInlineFunction)->name.toString(); s->breakpointReference.localScopeId = Identifier(combination); } else { s->breakpointReference.localScopeId = dynamic_cast<InlineFunction::Object*>(currentInlineFunction)->name; } } else if (currentlyParsedCallback.isValid()) { s->breakpointReference.localScopeId = currentlyParsedCallback; } s->breakpointReference.index = breakpoints[i].index; breakpoints.getReference(i).found = true; break; } } #else ScopedPointer<Statement> s = parseStatement(); #endif if (LockStatement* ls = dynamic_cast<LockStatement*>(s.get())) { b->lockStatements.add(ls); s.release(); } else { b->statements.add(s.release()); } } return b.release(); } String removeUnneededNamespaces(int& counter); String uglify(); void parseFunctionParamsAndBody(FunctionObject& fo) { match(TokenTypes::openParen); while (currentType != TokenTypes::closeParen) { fo.parameters.add(currentValue.toString()); match(TokenTypes::identifier); if (currentType != TokenTypes::closeParen) match(TokenTypes::comma); } match(TokenTypes::closeParen); fo.body = parseBlock(); } #if INCLUDE_NATIVE_JIT Expression* parseNativeJITExpression(NativeJITScope* scope) { const Identifier scopeId = parseIdentifier(); jassert(scopeId == scope->getName()); match(TokenTypes::dot); static const Identifier pb("processBlock"); const Identifier id = parseIdentifier(); if (scope->isFunction(id)) { ScopedPointer<RootObject::NativeJIT::FunctionCall> f = new RootObject::NativeJIT::FunctionCall(location); f->scope = scope; f->numArgs = scope->getNumArgsForFunction(id); f->functionName = id; match(TokenTypes::openParen); while (currentType != TokenTypes::closeParen && currentType != TokenTypes::eof) { ExpPtr p = parseExpression(); matchIf(TokenTypes::comma); f->arguments.add(p.release()); } match(TokenTypes::closeParen); if (f->numArgs != f->arguments.size()) { location.throwError("Argument amount mismatch. Expected: " + String(f->numArgs) + ". Actual: " + String(f->arguments.size())); } return f.release(); } else if (scope->isGlobal(id)) { ScopedPointer<RootObject::NativeJIT::GlobalReference> r = new RootObject::NativeJIT::GlobalReference(location, scope); r->index = scope->getIndexForGlobal(id); return parseSuffixes(r.release()); } else if (id == pb) { ScopedPointer<RootObject::NativeJIT::ProcessBufferCall> c = new RootObject::NativeJIT::ProcessBufferCall(location, scope); match(TokenTypes::openParen); ExpPtr target = parseExpression(); match(TokenTypes::closeParen); c->target = target.release(); return c.release(); } else { location.throwError(id.toString() + " not found in " + scope->getName()); } } #endif Expression* parseExpression() { Identifier id = Identifier::isValidIdentifier(currentValue.toString()) ? Identifier(currentValue.toString()) : Identifier::null; bool skipConsoleCalls = false; #if !ENABLE_SCRIPTING_SAFE_CHECKS static const Identifier c("Console"); if (id == c) { skipConsoleCalls = true; } #endif ExpPtr lhs; #if INCLUDE_NATIVE_JIT if (auto s = hiseSpecialData->getNativeJITScope(id)) { lhs = parseNativeJITExpression(s); } else if (auto c = hiseSpecialData->getNativeCompiler(id)) { parseIdentifier(); match(TokenTypes::dot); parseIdentifier(); match(TokenTypes::openParen); match(TokenTypes::closeParen); ScopedPointer<NativeJITScope> s = c->compileAndReturnScope(); if (s == nullptr) { location.throwError("NativeJIT compile error: " + c->getErrorMessage()); } hiseSpecialData->jitScopes.add(s.get()); return new RootObject::NativeJIT::ScopeReference(location, s.release()); } else { lhs = parseLogicOperator(); } #else lhs = parseLogicOperator(); #endif if (matchIf(TokenTypes::in)) { ExpPtr rhs(parseExpression()); currentIterator = id; return rhs.release(); } if (matchIf(TokenTypes::question)) return parseTerneryOperator(lhs); if (matchIf(TokenTypes::assign)) { ExpPtr rhs(parseExpression()); return new Assignment(location, lhs, rhs); } if (matchIf(TokenTypes::plusEquals)) return parseInPlaceOpExpression<AdditionOp>(lhs); if (matchIf(TokenTypes::minusEquals)) return parseInPlaceOpExpression<SubtractionOp>(lhs); if (matchIf(TokenTypes::timesEquals)) return parseInPlaceOpExpression<MultiplyOp>(lhs); if (matchIf(TokenTypes::divideEquals)) return parseInPlaceOpExpression<DivideOp>(lhs); if (matchIf(TokenTypes::moduloEquals)) return parseInPlaceOpExpression<ModuloOp>(lhs); if (matchIf(TokenTypes::leftShiftEquals)) return parseInPlaceOpExpression<LeftShiftOp>(lhs); if (matchIf(TokenTypes::andEquals)) return parseInPlaceOpExpression<BitwiseAndOp>(lhs); if (matchIf(TokenTypes::orEquals)) return parseInPlaceOpExpression<BitwiseOrOp>(lhs); if (matchIf(TokenTypes::xorEquals)) return parseInPlaceOpExpression<BitwiseXorOp>(lhs); if (matchIf(TokenTypes::rightShiftEquals)) return parseInPlaceOpExpression<RightShiftOp>(lhs); if (skipConsoleCalls) { return new Expression(location); } return lhs.release(); } Array<Breakpoint> breakpoints; private: HiseSpecialData *hiseSpecialData; bool currentlyParsingInlineFunction = false; Identifier currentlyParsedCallback = Identifier::null; Identifier fileId; DynamicObject* currentInlineFunction = nullptr; JavascriptNamespace* currentNamespace = nullptr; JavascriptNamespace* getCurrentNamespace() { jassert(currentNamespace != nullptr); return currentNamespace; } void throwError(const String& err) const { location.throwError(err); } template <typename OpType> Expression* parseInPlaceOpExpression(ExpPtr& lhs) { ExpPtr rhs(parseExpression()); Expression* bareLHS = lhs; // careful - bare pointer is deliberately alised return new SelfAssignment(location, bareLHS, new OpType(location, lhs, rhs)); } BlockStatement* parseBlock() { match(TokenTypes::openBrace); ScopedPointer<BlockStatement> b(parseStatementList()); match(TokenTypes::closeBrace); return b.release(); } Statement* parseStatement() { if (matchIf(TokenTypes::include_)) return parseExternalFile(); if (matchIf(TokenTypes::inline_)) return parseInlineFunction(getCurrentNamespace()); if (currentType == TokenTypes::openBrace) return parseBlock(); if (matchIf(TokenTypes::const_)) return parseConstVar(getCurrentNamespace()); if (matchIf(TokenTypes::var)) return parseVar(); if (matchIf(TokenTypes::register_var)) return parseRegisterVar(getCurrentNamespace()); if (matchIf(TokenTypes::global_)) return parseGlobalAssignment(); if (matchIf(TokenTypes::local_)) return parseLocalAssignment(); if (matchIf(TokenTypes::namespace_)) return parseNamespace(); if (matchIf(TokenTypes::if_)) return parseIf(); if (matchIf(TokenTypes::while_)) return parseDoOrWhileLoop(false); if (matchIf(TokenTypes::do_)) return parseDoOrWhileLoop(true); if (matchIf(TokenTypes::for_)) return parseForLoop(); if (matchIf(TokenTypes::return_)) return parseReturn(); if (matchIf(TokenTypes::switch_)) return parseSwitchBlock(); if (matchIf(TokenTypes::break_)) return new BreakStatement(location); if (matchIf(TokenTypes::continue_)) return new ContinueStatement(location); if (matchIf(TokenTypes::function)) return parseFunction(); if (matchIf(TokenTypes::loadJit_)) return parseJITModule(); if (matchIf(TokenTypes::semicolon)) return new Statement(location); if (matchIf(TokenTypes::plusplus)) return parsePreIncDec<AdditionOp>(); if (matchIf(TokenTypes::minusminus)) return parsePreIncDec<SubtractionOp>(); if (matchIf(TokenTypes::rLock_)) return parseLockStatement(true); if (matchIf(TokenTypes::wLock_)) return parseLockStatement(false); if (matchesAny(TokenTypes::openParen, TokenTypes::openBracket)) return matchEndOfStatement(parseFactor()); if (matchesAny(TokenTypes::identifier, TokenTypes::literal, TokenTypes::minus)) { ExpPtr ex = parseExpression(); return matchEndOfStatement(ex.release()); } throwError("Found " + getTokenName(currentType) + " when expecting a statement"); return nullptr; } String getFileContent(const String &fileNameInScript, String &refFileName) { String cleanedFileName = fileNameInScript.removeCharacters("\"\'"); if (cleanedFileName.contains("{DEVICE}")) { cleanedFileName = cleanedFileName.replace("{DEVICE}", HiseDeviceSimulator::getDeviceName()); } #if USE_BACKEND if (File::isAbsolutePath(cleanedFileName)) refFileName = cleanedFileName; else if (cleanedFileName.contains("{GLOBAL_SCRIPT_FOLDER}")) { File globalScriptFolder = PresetHandler::getGlobalScriptFolder(dynamic_cast<Processor*>(hiseSpecialData->processor)); const String f1 = cleanedFileName.fromFirstOccurrenceOf("{GLOBAL_SCRIPT_FOLDER}", false, false); refFileName = globalScriptFolder.getChildFile(f1).getFullPathName(); } else { const String fileName = "{PROJECT_FOLDER}" + cleanedFileName; refFileName = GET_PROJECT_HANDLER(dynamic_cast<Processor*>(hiseSpecialData->processor)).getFilePath(fileName, ProjectHandler::SubDirectories::Scripts); } File f(refFileName); const String shortFileName = f.getFileName(); if (!f.existsAsFile()) throwError("File " + refFileName + " not found"); for (int i = 0; i < hiseSpecialData->includedFiles.size(); i++) { if (hiseSpecialData->includedFiles[i]->f == f) { debugToConsole(dynamic_cast<Processor*>(hiseSpecialData->processor), "File " + shortFileName + " was included multiple times"); return String(); } } return f.loadFileAsString(); #else refFileName = cleanedFileName; if (File::isAbsolutePath(refFileName)) { File f(refFileName); for (int i = 0; i < hiseSpecialData->includedFiles.size(); i++) { if (hiseSpecialData->includedFiles[i]->f == f) { DBG("File " + refFileName + " was included multiple times"); return String(); } } return f.loadFileAsString(); } else { for (int i = 0; i < hiseSpecialData->includedFiles.size(); i++) { if (hiseSpecialData->includedFiles[i]->scriptName == refFileName) { DBG("Script " + refFileName + " was included multiple times"); return String(); } } return dynamic_cast<Processor*>(hiseSpecialData->processor)->getMainController()->getExternalScriptFromCollection(fileNameInScript); } #endif }; Statement* parseExternalFile() { if (getCurrentNamespace() != hiseSpecialData) { location.throwError("Including files inside namespaces is not supported"); } match(TokenTypes::openParen); String refFileName; String fileContent = getFileContent(currentValue.toString(), refFileName); if (fileContent.isEmpty()) { match(TokenTypes::literal); match(TokenTypes::closeParen); match(TokenTypes::semicolon); return new Statement(location); } else { #if USE_BACKEND File f(refFileName); hiseSpecialData->includedFiles.add(new ExternalFileData(ExternalFileData::Type::RelativeFile, f, String())); #else if (File::isAbsolutePath(refFileName)) hiseSpecialData->includedFiles.add(new ExternalFileData(ExternalFileData::Type::AbsoluteFile, File(refFileName), String())); else hiseSpecialData->includedFiles.add(new ExternalFileData(ExternalFileData::Type::AbsoluteFile, File(), refFileName)); #endif try { ExpressionTreeBuilder ftb(fileContent, refFileName); #if ENABLE_SCRIPTING_BREAKPOINTS ftb.breakpoints.addArray(breakpoints); #endif ftb.hiseSpecialData = hiseSpecialData; ftb.currentNamespace = hiseSpecialData; //ftb.setupApiData(*hiseSpecialData, fileContent); ScopedPointer<BlockStatement> s = ftb.parseStatementList(); match(TokenTypes::literal); match(TokenTypes::closeParen); match(TokenTypes::semicolon); return s.release(); } catch (String &errorMessage) { hiseSpecialData->includedFiles.getLast()->setErrorMessage(errorMessage); throw errorMessage; } } } Expression* matchEndOfStatement(Expression* ex) { ExpPtr e(ex); if (currentType != TokenTypes::eof) match(TokenTypes::semicolon); return e.release(); } Expression* matchCloseParen(Expression* ex) { ExpPtr e(ex); match(TokenTypes::closeParen); return e.release(); } Statement* parseIf() { ScopedPointer<IfStatement> s(new IfStatement(location)); match(TokenTypes::openParen); s->condition = parseExpression(); match(TokenTypes::closeParen); s->trueBranch = parseStatement(); s->falseBranch = matchIf(TokenTypes::else_) ? parseStatement() : new Statement(location); return s.release(); } Statement *parseRegisterAssignment(const Identifier &id) { match(TokenTypes::identifier); match(TokenTypes::assign); //const int index = registerIdentifiers.indexOf(id); const int index = hiseSpecialData->varRegister.getRegisterIndex(id); RegisterAssignment *r = new RegisterAssignment(location, index, parseExpression()); match(TokenTypes::semicolon); return r; } Statement* parseReturn() { if (matchIf(TokenTypes::semicolon)) return new ReturnStatement(location, new Expression(location)); ReturnStatement* r = new ReturnStatement(location, parseExpression()); matchIf(TokenTypes::semicolon); return r; } Statement* parseVar() { #if 0 if (getCurrentNamespace() != hiseSpecialData) { location.throwError("No var definitions inside namespaces (use reg or const var instead)"); } #endif ScopedPointer<VarStatement> s(new VarStatement(location)); s->name = parseIdentifier(); hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::RootScope, s->name, location); s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location); if (matchIf(TokenTypes::comma)) { ScopedPointer<BlockStatement> block(new BlockStatement(location)); block->statements.add(s.release()); block->statements.add(parseVar()); return block.release(); } match(TokenTypes::semicolon); return s.release(); } Statement* parseConstVar(JavascriptNamespace* ns) { matchIf(TokenTypes::var); ScopedPointer<ConstVarStatement> s(new ConstVarStatement(location)); s->name = parseIdentifier(); hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::ConstVariables, s->name, location); s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location); #if INCLUDE_NATIVE_JIT if (auto sr = dynamic_cast<RootObject::NativeJIT::ScopeReference*>(s->initialiser.get())) { sr->scope->setName(s->name); } #endif if (matchIf(TokenTypes::comma)) { ScopedPointer<BlockStatement> block(new BlockStatement(location)); block->statements.add(s.release()); block->statements.add(parseVar()); return block.release(); } jassert(ns->constObjects.contains(s->name)); static const var uninitialised("uninitialised"); ns->constObjects.set(s->name, uninitialised); // Will be initialied at runtime s->ns = ns; return s.release(); } Statement *parseRegisterVar(JavascriptNamespace* ns, TokenIterator* preparser=nullptr) { if (preparser) { Identifier name = preparser->currentValue.toString(); ns->varRegister.addRegister(name, var::undefined()); ns->registerLocations.add(preparser->createDebugLocation()); if (ns->registerLocations.size() != ns->varRegister.getNumUsedRegisters()) { String s; if (!ns->id.isNull()) s << ns->id.toString() << "."; s << name << ": error at definition"; preparser->location.throwError(s); } return nullptr; } else { ScopedPointer<RegisterVarStatement> s(new RegisterVarStatement(location)); s->name = parseIdentifier(); hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::Register, s->name, location); s->varRegister = &ns->varRegister; s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location); if (matchIf(TokenTypes::comma)) { ScopedPointer<BlockStatement> block(new BlockStatement(location)); block->statements.add(s.release()); block->statements.add(parseVar()); return block.release(); } match(TokenTypes::semicolon); return s.release(); } } Statement* parseLockStatement(bool isReadLock) { ScopedPointer<LockStatement> ls = new LockStatement(location, isReadLock); match(TokenTypes::openParen); ls->lockedObj = parseFactor(); match(TokenTypes::closeParen); match(TokenTypes::semicolon); return ls.release(); } Statement* parseGlobalAssignment() { ScopedPointer<GlobalVarStatement> s(new GlobalVarStatement(location)); s->name = parseIdentifier(); if (!hiseSpecialData->globals->hasProperty(s->name)) { hiseSpecialData->globals->setProperty(s->name, var::undefined()); } s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location); if (matchIf(TokenTypes::comma)) { ScopedPointer<BlockStatement> block(new BlockStatement(location)); block->statements.add(s.release()); block->statements.add(parseVar()); return block.release(); } match(TokenTypes::semicolon); return s.release(); } Statement* parseLocalAssignment() { if (InlineFunction::Object::Ptr ifo = dynamic_cast<InlineFunction::Object*>(getCurrentInlineFunction())) { ScopedPointer<LocalVarStatement> s(new LocalVarStatement(location, ifo)); s->name = parseIdentifier(); hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::LocalScope, s->name, location); ifo->localProperties.set(s->name, var::undefined()); s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location); if (matchIf(TokenTypes::comma)) { ScopedPointer<BlockStatement> block(new BlockStatement(location)); block->statements.add(s.release()); block->statements.add(parseVar()); return block.release(); } match(TokenTypes::semicolon); return s.release(); } else if (!currentlyParsedCallback.isNull()) { Callback* callback = hiseSpecialData->getCallback(currentlyParsedCallback); ScopedPointer<CallbackLocalStatement> s(new CallbackLocalStatement(location, callback)); s->name = parseIdentifier(); hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::LocalScope, s->name, location); callback->localProperties.set(s->name, var()); s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location); if (matchIf(TokenTypes::comma)) { ScopedPointer<BlockStatement> block(new BlockStatement(location)); block->statements.add(s.release()); block->statements.add(parseVar()); return block.release(); } match(TokenTypes::semicolon); return s.release(); } throwError("Cannot define local variables outside of inline functions or callbacks."); RETURN_IF_NO_THROW(nullptr) } Statement* parseCallback() { Identifier name = parseIdentifier(); Callback *c = hiseSpecialData->getCallback(name); jassert(c != nullptr); match(TokenTypes::openParen); for (int i = 0; i < c->getNumArgs(); i++) { c->parameters[i] = parseIdentifier(); c->parameterValues[i] = var::undefined(); if (i != c->getNumArgs() - 1) match(TokenTypes::comma); } match(TokenTypes::closeParen); ScopedValueSetter<Identifier> cParser(currentlyParsedCallback, name, Identifier::null); ScopedPointer<BlockStatement> s = parseBlock(); c->setStatements(s.release()); return new Statement(location); } Statement* parseNamespace() { Identifier namespaceId = parseIdentifier(); currentNamespace = hiseSpecialData->getNamespace(namespaceId); if (currentNamespace == nullptr) { location.throwError("Error at parsing namespace"); } ScopedPointer<BlockStatement> block = parseBlock(); currentNamespace = hiseSpecialData; return block.release(); } Statement* parseFunction() { Identifier name; if (hiseSpecialData->getCallback(currentValue.toString())) { return parseCallback(); } var fn = parseFunctionDefinition(name); if (name.isNull()) throwError("Functions defined at statement-level must have a name"); ExpPtr nm(new UnqualifiedName(location, name, true)), value(new LiteralValue(location, fn)); return new Assignment(location, nm, value); } InlineFunction::Object *getInlineFunction(Identifier &id, JavascriptNamespace* ns=nullptr) { if (ns == nullptr) { for (int i = 0; i < hiseSpecialData->inlineFunctions.size(); i++) { DynamicObject *o = hiseSpecialData->inlineFunctions.getUnchecked(i); InlineFunction::Object *obj = dynamic_cast<InlineFunction::Object*>(o); jassert(obj != nullptr); if (obj->name == id) return obj; } } else { for (int i = 0; i < ns->inlineFunctions.size(); i++) { DynamicObject *o = ns->inlineFunctions.getUnchecked(i); InlineFunction::Object *obj = dynamic_cast<InlineFunction::Object*>(o); jassert(obj != nullptr); if (obj->name == id) return obj; } } return nullptr; } JavascriptNamespace* getNamespaceForStorageType(JavascriptNamespace::StorageType storageType, JavascriptNamespace* nameSpaceToLook, const Identifier &id) { switch (storageType) { case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::Register: if (nameSpaceToLook != nullptr && nameSpaceToLook->varRegister.getRegisterIndex(id) != -1) return nameSpaceToLook; if (hiseSpecialData->varRegister.getRegisterIndex(id) != -1) return hiseSpecialData; break; case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::ConstVariable: if (nameSpaceToLook != nullptr && nameSpaceToLook->constObjects.contains(id)) return nameSpaceToLook; if (hiseSpecialData->constObjects.contains(id)) return hiseSpecialData; break; case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::InlineFunction: { if (nameSpaceToLook != nullptr) { for (int i = 0; i < nameSpaceToLook->inlineFunctions.size(); i++) { if (dynamic_cast<InlineFunction::Object*>(nameSpaceToLook->inlineFunctions[i].get())->name == id) return nameSpaceToLook; } } for (int i = 0; i < hiseSpecialData->inlineFunctions.size(); i++) { if (dynamic_cast<InlineFunction::Object*>(hiseSpecialData->inlineFunctions[i].get())->name == id) return hiseSpecialData; } break; } case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::numStorageTypes: break; default: break; } return nullptr; } int getRegisterIndex(const Identifier& id, JavascriptNamespace* ns = nullptr) { if (ns == nullptr) { return hiseSpecialData->varRegister.getRegisterIndex(id); } else { return ns->varRegister.getRegisterIndex(id); } } var* getRegisterData(int index, JavascriptNamespace* ns = nullptr) { if (ns == nullptr) { return hiseSpecialData->varRegister.getVarPointer(index); } else { return ns->varRegister.getVarPointer(index); } } int getConstIndex(const Identifier& id, JavascriptNamespace* ns = nullptr) { if (ns == nullptr) { return hiseSpecialData->constObjects.indexOf(id); } else { return ns->constObjects.indexOf(id); } } var* getConstData(int index, JavascriptNamespace* ns = nullptr) { if (ns == nullptr) { return hiseSpecialData->constObjects.getVarPointerAt(index); } else { return ns->constObjects.getVarPointerAt(index); } } DynamicObject* getCurrentInlineFunction() { return currentInlineFunction; } Expression* parseInlineFunctionCall(InlineFunction::Object *obj) { ScopedPointer<InlineFunction::FunctionCall> f = new InlineFunction::FunctionCall(location, obj); parseIdentifier(); if (currentType == TokenTypes::openParen) { match(TokenTypes::openParen); while (currentType != TokenTypes::closeParen) { f->addParameter(parseExpression()); if (currentType != TokenTypes::closeParen) match(TokenTypes::comma); } if (f->numArgs != f->parameterExpressions.size()) { throwError("Inline function call " + obj->name + ": parameter amount mismatch: " + String(f->parameterExpressions.size()) + " (Expected: " + String(f->numArgs) + ")"); } return matchCloseParen(f.release()); } else { return new LiteralValue(location, var(obj)); } } Statement *parseInlineFunction(JavascriptNamespace* ns, TokenIterator *preparser=nullptr) { if (preparser != nullptr) { DebugableObject::Location loc = preparser->createDebugLocation(); preparser->match(TokenTypes::function); Identifier name = preparser->currentValue.toString(); preparser->match(TokenTypes::identifier); preparser->match(TokenTypes::openParen); Array<Identifier> inlineArguments; while (preparser->currentType != TokenTypes::closeParen) { inlineArguments.add(preparser->currentValue.toString()); preparser->match(TokenTypes::identifier); if (preparser->currentType != TokenTypes::closeParen) preparser->match(TokenTypes::comma); } preparser->match(TokenTypes::closeParen); ScopedPointer<InlineFunction::Object> o = new InlineFunction::Object(name, inlineArguments); o->location = loc; ns->inlineFunctions.add(o.release()); preparser->matchIf(TokenTypes::semicolon); return nullptr; } else { if (getCurrentInlineFunction() != nullptr) throwError("No nested inline functions allowed."); match(TokenTypes::function); Identifier name = parseIdentifier(); match(TokenTypes::openParen); while (currentType != TokenTypes::closeParen) skip(); match(TokenTypes::closeParen); InlineFunction::Object::Ptr o; for (int i = 0; i < ns->inlineFunctions.size(); i++) { if ((o = dynamic_cast<InlineFunction::Object*>(ns->inlineFunctions[i].get()))) { if (o->name == name) { break; } } } currentInlineFunction = o; if (o != nullptr) { o->commentDoc = lastComment; clearLastComment(); ScopedPointer<BlockStatement> body = parseBlock(); o->body = body.release(); currentInlineFunction = nullptr; matchIf(TokenTypes::semicolon); return new Statement(location); } else { currentInlineFunction = nullptr; location.throwError("Error at inline function parsing"); return nullptr; } } } Statement* parseJITModule() { match(TokenTypes::openParen); String refFileName; String fileContent = getFileContent(currentValue.toString(), refFileName); match(TokenTypes::literal); match(TokenTypes::closeParen); match(TokenTypes::semicolon); #if INCLUDE_NATIVE_JIT ScopedPointer<NativeJITCompiler> compiler = new NativeJITCompiler(fileContent); hiseSpecialData->jitModules.add(compiler.release()); #endif return new Statement(location); } Statement* parseCaseStatement() { const bool isNotDefaultCase = currentType == TokenTypes::case_; ScopedPointer<CaseStatement> s(new CaseStatement(location, isNotDefaultCase)); skip(); if (isNotDefaultCase) s->conditions.add(parseExpression()); match(TokenTypes::colon); if (currentType == TokenTypes::openBrace) { s->body = parseBlock(); } else if (currentType == TokenTypes::case_ || currentType == TokenTypes::default_ || currentType == TokenTypes::closeBrace) { // Empty statement (the condition will be added to the next case. s->body = nullptr; } else { s->body = new BlockStatement(location); while (currentType != TokenTypes::case_ && currentType != TokenTypes::closeBrace && currentType != TokenTypes::default_) { s->body->statements.add(parseStatement()); } } return s.release(); } Statement* parseSwitchBlock() { ScopedPointer<SwitchStatement> s(new SwitchStatement(location)); match(TokenTypes::openParen); s->condition = parseExpression(); match(TokenTypes::closeParen); match(TokenTypes::openBrace); OwnedArray<Expression> emptyCaseConditions; while (currentType == TokenTypes::case_ || currentType == TokenTypes::default_) { ScopedPointer<CaseStatement> caseStatement = dynamic_cast<CaseStatement*>(parseCaseStatement()); if (caseStatement != nullptr) { if (caseStatement->body == nullptr) { for (auto& c : caseStatement->conditions) { emptyCaseConditions.add(c.release()); } caseStatement->conditions.clear(); continue; } else { while (!emptyCaseConditions.isEmpty()) { auto c = emptyCaseConditions.removeAndReturn(0); caseStatement->conditions.add(c); } } if (caseStatement->isNotDefault) { s->cases.add(caseStatement.release()); } else { s->defaultCase = caseStatement.release(); } } } match(TokenTypes::closeBrace); return s.release(); } Statement* parseForLoop() { match(TokenTypes::openParen); const Identifier previousIteratorName = currentIterator; const bool isVarInitialiser = matchIf(TokenTypes::var); Expression *iter = parseExpression(); // Allow unqualified names in for loop initialisation for convenience if (auto assignment = dynamic_cast<Assignment*>(iter)) { if (auto un = dynamic_cast<UnqualifiedName*>(assignment->target.get())) un->allowUnqualifiedDefinition = true; } if (!isVarInitialiser && currentType == TokenTypes::closeParen) { ScopedPointer<LoopStatement> s(new LoopStatement(location, false, true)); s->currentIterator = iter; s->iterator = nullptr; s->initialiser = nullptr; s->condition = new LiteralValue(location, true); match(TokenTypes::closeParen); s->body = parseStatement(); currentIterator = previousIteratorName; return s.release(); } else { ScopedPointer<LoopStatement> s(new LoopStatement(location, false)); s->initialiser = matchEndOfStatement(iter); if (matchIf(TokenTypes::semicolon)) s->condition = new LiteralValue(location, true); else { s->condition = parseExpression(); match(TokenTypes::semicolon); } if (matchIf(TokenTypes::closeParen)) s->iterator = new Statement(location); else { s->iterator = parseExpression(); match(TokenTypes::closeParen); } s->body = parseStatement(); return s.release(); } } Statement* parseDoOrWhileLoop(bool isDoLoop) { ScopedPointer<LoopStatement> s(new LoopStatement(location, isDoLoop)); s->initialiser = new Statement(location); s->iterator = new Statement(location); if (isDoLoop) { s->body = parseBlock(); match(TokenTypes::while_); } match(TokenTypes::openParen); s->condition = parseExpression(); match(TokenTypes::closeParen); if (!isDoLoop) s->body = parseStatement(); return s.release(); } Identifier parseIdentifier() { Identifier i; if (currentType == TokenTypes::identifier) i = currentValue.toString(); match(TokenTypes::identifier); return i; } var parseFunctionDefinition(Identifier& functionName) { const String::CharPointerType functionStart(location.location); if (currentType == TokenTypes::identifier) functionName = parseIdentifier(); ScopedPointer<FunctionObject> fo(new FunctionObject()); parseFunctionParamsAndBody(*fo); fo->functionCode = String(functionStart, location.location); fo->createFunctionDefinition(functionName); fo->commentDoc = lastComment; clearLastComment(); return var(fo.release()); } Expression* parseFunctionCall(FunctionCall* call, ExpPtr& function) { ScopedPointer<FunctionCall> s(call); s->object = function; match(TokenTypes::openParen); while (currentType != TokenTypes::closeParen) { s->arguments.add(parseExpression()); if (currentType != TokenTypes::closeParen) match(TokenTypes::comma); } return matchCloseParen(s.release()); } Expression* parseApiExpression() { const Identifier apiId = parseIdentifier(); const int apiIndex = hiseSpecialData->apiIds.indexOf(apiId); ApiClass *apiClass = hiseSpecialData->apiClasses.getUnchecked(apiIndex); match(TokenTypes::dot); const Identifier memberName = parseIdentifier(); int constantIndex = apiClass->getConstantIndex(memberName); if (constantIndex != -1) { return parseApiConstant(apiClass, memberName); } else { return parseApiCall(apiClass, memberName); } } Expression* parseApiConstant(ApiClass *apiClass, const Identifier &constantName) { const int index = apiClass->getConstantIndex(constantName); const var value = apiClass->getConstantValue(index); ScopedPointer<ApiConstant> s = new ApiConstant(location); s->value = value; return s.release(); } Expression* parseApiCall(ApiClass *apiClass, const Identifier &functionName) { int functionIndex, numArgs; apiClass->getIndexAndNumArgsForFunction(functionName, functionIndex, numArgs); const String prettyName = apiClass->getObjectName() + "." + functionName.toString(); if (functionIndex < 0) throwError("Function / constant not found: " + prettyName); // Handle also missing constants here ScopedPointer<ApiCall> s = new ApiCall(location, apiClass, numArgs, functionIndex); match(TokenTypes::openParen); int numActualArguments = 0; while (currentType != TokenTypes::closeParen) { if (numActualArguments < numArgs) { s->argumentList[numActualArguments++] = parseExpression(); if (currentType != TokenTypes::closeParen) match(TokenTypes::comma); } else throwError("Too many arguments in API call " + prettyName + "(). Expected: " + String(numArgs)); } if (numArgs != numActualArguments) throwError("Call to " + prettyName + "(): argument number mismatch : " + String(numActualArguments) + " (Expected : " + String(numArgs) + ")"); return matchCloseParen(s.release()); } Expression* parseConstExpression(JavascriptNamespace* ns=nullptr) { const Identifier constId = parseIdentifier(); const int index = getConstIndex(constId, ns); #if 0 if (currentType == TokenTypes::dot) { match(TokenTypes::dot); const Identifier memberName = parseIdentifier(); return parseConstObjectApiCall(constId, memberName, ns); } #endif ns = (ns != nullptr) ? ns : hiseSpecialData; return new ConstReference(location, ns, index); } Expression* parseConstObjectApiCall(const Identifier& objectName, const Identifier& functionName, JavascriptNamespace* ns=nullptr) { const String prettyName = objectName.toString() + "." + functionName.toString(); const int index = getConstIndex(objectName, ns); var *v = getConstData(index, ns); ScopedPointer<ConstObjectApiCall> s = new ConstObjectApiCall(location, v, functionName); match(TokenTypes::openParen); int numActualArguments = 0; while (currentType != TokenTypes::closeParen) { s->argumentList[numActualArguments++] = parseExpression(); if (currentType != TokenTypes::closeParen) match(TokenTypes::comma); } return matchCloseParen(s.release()); } Expression* parseSuffixes(Expression* e) { ExpPtr input(e); if (matchIf(TokenTypes::dot)) return parseSuffixes(new DotOperator(location, input, parseIdentifier())); if (currentType == TokenTypes::openParen) return parseSuffixes(parseFunctionCall(new FunctionCall(location), input)); if (matchIf(TokenTypes::openBracket)) { ScopedPointer<ArraySubscript> s(new ArraySubscript(location)); s->object = input; s->index = parseExpression(); match(TokenTypes::closeBracket); return parseSuffixes(s.release()); } if (matchIf(TokenTypes::plusplus)) return parsePostIncDec<AdditionOp>(input); if (matchIf(TokenTypes::minusminus)) return parsePostIncDec<SubtractionOp>(input); return input.release(); } Expression* parseFactor(JavascriptNamespace* ns=nullptr) { if (currentType == TokenTypes::identifier) { Identifier id = Identifier(currentValue.toString()); // Allow direct referencing of namespaced variables within the namespace if (getCurrentNamespace() != hiseSpecialData && ns == nullptr) { ns = getCurrentNamespace(); // Allow usage of namespace prefix within namespace if (ns->id == id) { match(TokenTypes::identifier); match(TokenTypes::dot); id = currentValue.toString(); } } if (id == currentIterator) { return parseSuffixes(new LoopStatement::IteratorName(location, parseIdentifier())); } else if (currentInlineFunction != nullptr) { InlineFunction::Object* ob = dynamic_cast<InlineFunction::Object*>(currentInlineFunction); const int inlineParameterIndex = ob->parameterNames.indexOf(id); const int localParameterIndex = ob->localProperties.indexOf(id); if (inlineParameterIndex >= 0) { parseIdentifier(); return parseSuffixes(new InlineFunction::ParameterReference(location, ob, inlineParameterIndex)); } if (localParameterIndex >= 0) { parseIdentifier(); return parseSuffixes(new LocalReference(location, ob, id)); } } // Only resolve one level of namespaces JavascriptNamespace* namespaceForId = hiseSpecialData->getNamespace(id); if (namespaceForId != nullptr) { match(TokenTypes::identifier); match(TokenTypes::dot); return parseFactor(namespaceForId); } else { if (JavascriptNamespace* inlineNamespace = getNamespaceForStorageType(JavascriptNamespace::StorageType::InlineFunction, ns, id)) { InlineFunction::Object *obj = getInlineFunction(id, inlineNamespace); return parseSuffixes(parseInlineFunctionCall(obj)); } else if (JavascriptNamespace* constNamespace = getNamespaceForStorageType(JavascriptNamespace::StorageType::ConstVariable, ns, id)) { return parseSuffixes(parseConstExpression(constNamespace)); } else if (JavascriptNamespace* regNamespace = getNamespaceForStorageType(JavascriptNamespace::StorageType::Register, ns, id)) { VarRegister* rootRegister = &regNamespace->varRegister; const int registerIndex = rootRegister->getRegisterIndex(id); return parseSuffixes(new RegisterName(location, parseIdentifier(), rootRegister, registerIndex, getRegisterData(registerIndex, regNamespace))); } const int apiClassIndex = hiseSpecialData->apiIds.indexOf(id); const int globalIndex = hiseSpecialData->globals != nullptr ? hiseSpecialData->globals->getProperties().indexOf(id) : -1; if (apiClassIndex != -1) { return parseSuffixes(parseApiExpression()); } #if INCLUDE_NATIVE_JIT else if (auto compiler = hiseSpecialData->getNativeCompiler(id)) { match(TokenTypes::dot); match(TokenTypes::identifier); match(TokenTypes::openParen); match(TokenTypes::closeParen); return new RootObject::NativeJIT::ScopeReference(location, compiler->compileAndReturnScope()); } #endif else if (globalIndex != -1) { return parseSuffixes(new GlobalReference(location, hiseSpecialData->globals, parseIdentifier())); } else { if (!currentlyParsedCallback.isNull()) { Callback *c = hiseSpecialData->getCallback(currentlyParsedCallback); if (c != nullptr) { var* callbackParameter = c->getVarPointer(id); if (callbackParameter != nullptr) { parseIdentifier(); return parseSuffixes(new CallbackParameterReference(location, callbackParameter)); } var* localParameter = c->localProperties.getVarPointer(id); if (localParameter != nullptr) { auto name = parseIdentifier(); return parseSuffixes(new CallbackLocalReference(location, c, name)); } } else { jassertfalse; } } return parseSuffixes(new UnqualifiedName(location, parseIdentifier(), false)); } } } if (matchIf(TokenTypes::openParen)) return parseSuffixes(matchCloseParen(parseExpression())); if (matchIf(TokenTypes::true_)) return parseSuffixes(new LiteralValue(location, (int)1)); if (matchIf(TokenTypes::false_)) return parseSuffixes(new LiteralValue(location, (int)0)); if (matchIf(TokenTypes::null_)) return parseSuffixes(new LiteralValue(location, var())); if (matchIf(TokenTypes::undefined)) return parseSuffixes(new Expression(location)); if (currentType == TokenTypes::literal) { var v(currentValue); skip(); return parseSuffixes(new LiteralValue(location, v)); } if (matchIf(TokenTypes::openBrace)) { ScopedPointer<ObjectDeclaration> e(new ObjectDeclaration(location)); while (currentType != TokenTypes::closeBrace) { e->names.add(currentValue.toString()); match((currentType == TokenTypes::literal && currentValue.isString()) ? TokenTypes::literal : TokenTypes::identifier); match(TokenTypes::colon); e->initialisers.add(parseExpression()); if (currentType != TokenTypes::closeBrace) match(TokenTypes::comma); } match(TokenTypes::closeBrace); return parseSuffixes(e.release()); } if (matchIf(TokenTypes::openBracket)) { ScopedPointer<ArrayDeclaration> e(new ArrayDeclaration(location)); while (currentType != TokenTypes::closeBracket) { e->values.add(parseExpression()); if (currentType != TokenTypes::closeBracket) match(TokenTypes::comma); } match(TokenTypes::closeBracket); return parseSuffixes(e.release()); } if (matchIf(TokenTypes::function)) { Identifier name; var fn = parseFunctionDefinition(name); if (name.isValid()) throwError("Inline functions definitions cannot have a name"); return new LiteralValue(location, fn); } if (matchIf(TokenTypes::new_)) { return parseNewOperator(); } if (matchIf(TokenTypes::isDefined_)) { return parseIsDefined(); } throwError("Found " + getTokenName(currentType) + " when expecting an expression"); RETURN_IF_NO_THROW(nullptr); } template <typename OpType> Expression* parsePreIncDec() { Expression* e = parseFactor(); // careful - bare pointer is deliberately alised ExpPtr lhs(e), one(new LiteralValue(location, (int)1)); return new SelfAssignment(location, e, new OpType(location, lhs, one)); } template <typename OpType> Expression* parsePostIncDec(ExpPtr& lhs) { Expression* e = lhs.release(); // careful - bare pointer is deliberately alised ExpPtr lhs2(e), one(new LiteralValue(location, (int)1)); return new PostAssignment(location, e, new OpType(location, lhs2, one)); } Expression* parseTypeof() { ScopedPointer<FunctionCall> f(new FunctionCall(location)); f->object = new UnqualifiedName(location, "typeof", true); f->arguments.add(parseUnary()); return f.release(); } Expression* parseUnary() { if (matchIf(TokenTypes::minus)) { ExpPtr a(new LiteralValue(location, (int)0)), b(parseUnary()); return new SubtractionOp(location, a, b); } if (matchIf(TokenTypes::logicalNot)) { ExpPtr a(new LiteralValue(location, (int)0)), b(parseUnary()); return new EqualsOp(location, a, b); } if (matchIf(TokenTypes::plusplus)) return parsePreIncDec<AdditionOp>(); if (matchIf(TokenTypes::minusminus)) return parsePreIncDec<SubtractionOp>(); if (matchIf(TokenTypes::typeof_)) return parseTypeof(); return parseFactor(); } Expression* parseNewOperator() { location.throwError("new is not supported anymore"); return nullptr; } Expression* parseIsDefined() { match(TokenTypes::openParen); ExpPtr a(parseExpression()); match(TokenTypes::closeParen); return new IsDefinedTest(location, a.release()); } Expression* parseMultiplyDivide() { ExpPtr a(parseUnary()); for (;;) { if (matchIf(TokenTypes::times)) { ExpPtr b(parseUnary()); a = new MultiplyOp(location, a, b); } else if (matchIf(TokenTypes::divide)) { ExpPtr b(parseUnary()); a = new DivideOp(location, a, b); } else if (matchIf(TokenTypes::modulo)) { ExpPtr b(parseUnary()); a = new ModuloOp(location, a, b); } else break; } return a.release(); } Expression* parseAdditionSubtraction() { ExpPtr a(parseMultiplyDivide()); for (;;) { if (matchIf(TokenTypes::plus)) { ExpPtr b(parseMultiplyDivide()); a = new AdditionOp(location, a, b); } else if (matchIf(TokenTypes::minus)) { ExpPtr b(parseMultiplyDivide()); a = new SubtractionOp(location, a, b); } else break; } return a.release(); } Expression* parseShiftOperator() { ExpPtr a(parseAdditionSubtraction()); for (;;) { if (matchIf(TokenTypes::leftShift)) { ExpPtr b(parseExpression()); a = new LeftShiftOp(location, a, b); } else if (matchIf(TokenTypes::rightShift)) { ExpPtr b(parseExpression()); a = new RightShiftOp(location, a, b); } else if (matchIf(TokenTypes::rightShiftUnsigned)) { ExpPtr b(parseExpression()); a = new RightShiftUnsignedOp(location, a, b); } else break; } return a.release(); } Expression* parseComparator() { ExpPtr a(parseShiftOperator()); for (;;) { if (matchIf(TokenTypes::equals)) { ExpPtr b(parseShiftOperator()); a = new EqualsOp(location, a, b); } else if (matchIf(TokenTypes::notEquals)) { ExpPtr b(parseShiftOperator()); a = new NotEqualsOp(location, a, b); } else if (matchIf(TokenTypes::typeEquals)) { ExpPtr b(parseShiftOperator()); a = new TypeEqualsOp(location, a, b); } else if (matchIf(TokenTypes::typeNotEquals)) { ExpPtr b(parseShiftOperator()); a = new TypeNotEqualsOp(location, a, b); } else if (matchIf(TokenTypes::lessThan)) { ExpPtr b(parseShiftOperator()); a = new LessThanOp(location, a, b); } else if (matchIf(TokenTypes::lessThanOrEqual)) { ExpPtr b(parseShiftOperator()); a = new LessThanOrEqualOp(location, a, b); } else if (matchIf(TokenTypes::greaterThan)) { ExpPtr b(parseShiftOperator()); a = new GreaterThanOp(location, a, b); } else if (matchIf(TokenTypes::greaterThanOrEqual)) { ExpPtr b(parseShiftOperator()); a = new GreaterThanOrEqualOp(location, a, b); } else break; } return a.release(); } Expression* parseLogicOperator() { ExpPtr a(parseComparator()); for (;;) { if (matchIf(TokenTypes::logicalAnd)) { ExpPtr b(parseComparator()); a = new LogicalAndOp(location, a, b); } else if (matchIf(TokenTypes::logicalOr)) { ExpPtr b(parseComparator()); a = new LogicalOrOp(location, a, b); } else if (matchIf(TokenTypes::bitwiseAnd)) { ExpPtr b(parseComparator()); a = new BitwiseAndOp(location, a, b); } else if (matchIf(TokenTypes::bitwiseOr)) { ExpPtr b(parseComparator()); a = new BitwiseOrOp(location, a, b); } else if (matchIf(TokenTypes::bitwiseXor)) { ExpPtr b(parseComparator()); a = new BitwiseXorOp(location, a, b); } else break; } return a.release(); } Expression* parseTerneryOperator(ExpPtr& condition) { ScopedPointer<ConditionalOp> e(new ConditionalOp(location)); e->condition = condition; e->trueBranch = parseExpression(); match(TokenTypes::colon); e->falseBranch = parseExpression(); return e.release(); } Array<Identifier> registerIdentifiers; Identifier currentIterator; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ExpressionTreeBuilder) }; void HiseJavascriptEngine::RootObject::ExpressionTreeBuilder::preprocessCode(const String& codeToPreprocess, const String& externalFileName) { if (codeToPreprocess.isEmpty()) return; static const var undeclared("undeclared"); JavascriptNamespace* rootNamespace = hiseSpecialData; JavascriptNamespace* cns = rootNamespace; TokenIterator it(codeToPreprocess, externalFileName); int braceLevel = 0; while (it.currentType != TokenTypes::eof) { if (it.currentType == TokenTypes::namespace_) { if (cns != rootNamespace) { it.location.throwError("Nesting of namespaces is not allowed"); } it.match(TokenTypes::namespace_); Identifier namespaceId = Identifier(it.currentValue); if (hiseSpecialData->getNamespace(namespaceId) == nullptr) { ScopedPointer<JavascriptNamespace> newNamespace = new JavascriptNamespace(namespaceId); newNamespace->namespaceLocation = it.createDebugLocation(); cns = newNamespace; hiseSpecialData->namespaces.add(newNamespace.release()); continue; } else { it.location.throwError("Duplicate namespace " + namespaceId.toString()); } } // Skip extern "C" functions if (it.currentType == TokenTypes::extern_) { while (!(it.currentType == TokenTypes::closeBrace && braceLevel == 1) && !(it.currentType == TokenTypes::eof)) { if (it.currentType == TokenTypes::openBrace) braceLevel++; else if (it.currentType == TokenTypes::closeBrace) braceLevel--; it.skip(); } } // Search in included files if (it.currentType == TokenTypes::include_) { it.match(TokenTypes::include_); it.match(TokenTypes::openParen); String fileName = it.currentValue.toString(); String externalCode = getFileContent(it.currentValue.toString(), fileName); preprocessCode(externalCode, fileName); continue; } // Handle the brace level if (it.matchIf(TokenTypes::openBrace)) { braceLevel++; continue; } else if (it.matchIf(TokenTypes::closeBrace)) { braceLevel--; if (braceLevel == 0 && (rootNamespace != cns)) { cns = rootNamespace; } continue; } if (it.matchIf(TokenTypes::inline_)) { parseInlineFunction(cns, &it); continue; } if (it.matchIf(TokenTypes::register_var)) { parseRegisterVar(cns, &it); continue; } // Handle the keyword if (it.currentType == TokenTypes::const_) { it.match(TokenTypes::const_); it.matchIf(TokenTypes::var); const Identifier newId(it.currentValue); if ((rootNamespace == cns) && braceLevel != 0) it.location.throwError("const var declaration must be on global level"); if (newId.isNull()) it.location.throwError("Expected identifier for const var declaration"); if (cns->constObjects.contains(newId)) it.location.throwError("Duplicate const var declaration."); cns->constObjects.set(newId, undeclared); cns->constLocations.add(it.createDebugLocation()); continue; } else { it.skip(); } } if (rootNamespace != cns) { it.location.throwError("Parsing error (open namespace)"); } if (cns->constObjects.size() != cns->constLocations.size()) { jassertfalse; } } String HiseJavascriptEngine::RootObject::ExpressionTreeBuilder::removeUnneededNamespaces(int& counter) { StringArray namespaces; while (currentType != TokenTypes::eof) { if (currentType != TokenTypes::namespace_) skip(); else { auto start = location.location; match(TokenTypes::namespace_); match(TokenTypes::identifier); skipBlock(); matchIf(TokenTypes::semicolon); auto end = location.location; namespaces.add(String(start, end)); } } String returnCode = location.program; for (int i = namespaces.size() - 1; i >= 0; i--) { const String namespaceId = RegexFunctions::getFirstMatch("namespace\\s+(\\w+)", namespaces[i])[1]; const String remainingCode = returnCode.fromFirstOccurrenceOf(namespaces[i], false, false); TokenIterator it(remainingCode, ""); bool found = false; while (it.currentType != TokenTypes::eof) { if (it.currentType == TokenTypes::identifier && it.currentValue == namespaceId) { found = true; break; } it.skip(); } if (!found) { returnCode = returnCode.replace(namespaces[i], ""); counter++; } } return returnCode; } String HiseJavascriptEngine::RootObject::ExpressionTreeBuilder::uglify() { String uglyCode; int tokenCounter = 0; while (currentType != TokenTypes::eof) { if (currentType == TokenTypes::in) uglyCode << ' '; // the only keyword that needs a leading space... if (currentType == TokenTypes::identifier) { uglyCode << currentValue.toString(); } else if (currentType == TokenTypes::literal) { if (currentValue.isString()) { uglyCode << "\"" << currentValue.toString().replace("\n", "\\n") << "\""; } else { uglyCode << currentValue.toString(); } } else { uglyCode << currentType; } if (currentType == TokenTypes::namespace_ || currentType == TokenTypes::function || currentType == TokenTypes::const_ || currentType == TokenTypes::extern_ || currentType == TokenTypes::case_ || currentType == TokenTypes::const_ || currentType == TokenTypes::local_ || currentType == TokenTypes::var || currentType == TokenTypes::in || currentType == TokenTypes::inline_ || currentType == TokenTypes::return_ || currentType == TokenTypes::typeof_ || currentType == TokenTypes::register_var || currentType == TokenTypes::new_ || currentType == TokenTypes::else_ || currentType == TokenTypes::global_) { uglyCode << ' '; } tokenCounter++; if (tokenCounter % 256 == 0) uglyCode << NewLine::getDefault(); // one single line is too slow for the code editor... skip(); } return uglyCode; } var HiseJavascriptEngine::RootObject::evaluate(const String& code) { ExpressionTreeBuilder tb(code, String()); tb.setupApiData(hiseSpecialData, code); return ExpPtr(tb.parseExpression())->getResult(Scope(nullptr, this, this)); } void HiseJavascriptEngine::RootObject::execute(const String& code, bool allowConstDeclarations) { ExpressionTreeBuilder tb(code, String()); #if ENABLE_SCRIPTING_BREAKPOINTS tb.breakpoints.swapWith(breakpoints); #endif tb.setupApiData(hiseSpecialData, allowConstDeclarations ? code : String()); auto sl = ScopedPointer<BlockStatement>(tb.parseStatementList()); if(shouldUseCycleCheck) prepareCycleReferenceCheck(); sl->perform(Scope(nullptr, this, this), nullptr); } HiseJavascriptEngine::RootObject::FunctionObject::FunctionObject(const FunctionObject& other) : DynamicObject(), functionCode(other.functionCode) { ExpressionTreeBuilder tb(functionCode, String()); tb.parseFunctionParamsAndBody(*this); } } // namespace hise
62,594
22,691
#include <utility> #include <iostream> #include <tuple> #include <functional> template <typename N> void print(N v) { std::cout << v << std::endl; } template <typename N, typename... Ns> void print(N v, Ns... vs) { std::cout << v << ", "; print(vs...); } template <size_t... I> void print(std::index_sequence<I...>) { print(I...); } template <typename Func, typename Tuple, size_t... I> auto callback(Func&& func, Tuple t, std::index_sequence<I...>) { return func(std::get<I>(t)...); } template <typename Func, typename Tuple> auto callback(Func&& func, Tuple t) { return callback(std::forward<Func>(func), t, std::make_index_sequence<std::tuple_size_v<Tuple>>{}); } template <typename Func, typename... Args> auto callback(Func&& func, Args... args) { return callback(std::forward<Func>(func), std::make_tuple(args...)); } class TestClass { public: typedef std::function<int(int, int)> add_func_t; void Test() { auto generic_lambda = [this](auto&&... args) -> decltype(auto) { return this->TestClass::Hello(std::forward<decltype(args)>(args)...); }; CatchAddFunc(generic_lambda); } void CatchAddFunc(add_func_t&& func) { std::cout << "Catch func!\n"; } private: int Hello(int a, int b) { std::cout << a << " + " << b << " = " << a + b << "\n"; return a + b; } }; int main() { print(std::make_index_sequence<10>{}); print(std::make_index_sequence<6>{}); auto lambda = [](int a, double b) -> int { std::cout << a << ": " << b; return 5; }; auto lambda1 = [](int a, int b, int c) -> void { std::cout << a << " " << b << " " << c << "\nsum: " << a + b + c << std::endl; }; std::cout << " return: " << callback(lambda, 2, 6.55) << "\n"; std::cout << " return: " << callback(lambda, 8, 8454.55) << "\n"; std::cout << " return: " << callback(lambda, 999, 5424.55) << "\n"; callback(lambda1, 8, 9, 5); callback(lambda1, 84, 91, 52); TestClass testClass; testClass.Test(); }
1,938
807
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "platform/v8_inspector/V8ConsoleAgentImpl.h" #include "platform/v8_inspector/V8ConsoleMessage.h" #include "platform/v8_inspector/V8DebuggerImpl.h" #include "platform/v8_inspector/V8InspectorSessionImpl.h" #include "platform/v8_inspector/V8StackTraceImpl.h" namespace blink { namespace ConsoleAgentState { static const char consoleEnabled[] = "consoleEnabled"; } V8ConsoleAgentImpl::V8ConsoleAgentImpl(V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel, protocol::DictionaryValue* state) : m_session(session) , m_state(state) , m_frontend(frontendChannel) , m_enabled(false) { } V8ConsoleAgentImpl::~V8ConsoleAgentImpl() { } void V8ConsoleAgentImpl::enable(ErrorString* errorString) { if (m_enabled) return; m_state->setBoolean(ConsoleAgentState::consoleEnabled, true); m_enabled = true; m_session->debugger()->enableStackCapturingIfNeeded(); reportAllMessages(); m_session->client()->consoleEnabled(); } void V8ConsoleAgentImpl::disable(ErrorString* errorString) { if (!m_enabled) return; m_session->debugger()->disableStackCapturingIfNeeded(); m_state->setBoolean(ConsoleAgentState::consoleEnabled, false); m_enabled = false; } void V8ConsoleAgentImpl::clearMessages(ErrorString* errorString) { m_session->debugger()->ensureConsoleMessageStorage(m_session->contextGroupId())->clear(); } void V8ConsoleAgentImpl::restore() { if (!m_state->booleanProperty(ConsoleAgentState::consoleEnabled, false)) return; m_frontend.messagesCleared(); ErrorString ignored; enable(&ignored); } void V8ConsoleAgentImpl::messageAdded(V8ConsoleMessage* message) { if (m_enabled) reportMessage(message, true); } void V8ConsoleAgentImpl::reset() { if (m_enabled) m_frontend.messagesCleared(); } bool V8ConsoleAgentImpl::enabled() { return m_enabled; } void V8ConsoleAgentImpl::reportAllMessages() { V8ConsoleMessageStorage* storage = m_session->debugger()->ensureConsoleMessageStorage(m_session->contextGroupId()); if (storage->expiredCount()) { std::unique_ptr<protocol::Console::ConsoleMessage> expired = protocol::Console::ConsoleMessage::create() .setSource(protocol::Console::ConsoleMessage::SourceEnum::Other) .setLevel(protocol::Console::ConsoleMessage::LevelEnum::Warning) .setText(String16::number(storage->expiredCount()) + String16("console messages are not shown.")) .setTimestamp(0) .build(); expired->setType(protocol::Console::ConsoleMessage::TypeEnum::Log); expired->setLine(0); expired->setColumn(0); expired->setUrl(""); m_frontend.messageAdded(std::move(expired)); m_frontend.flush(); } for (const auto& message : storage->messages()) { if (!reportMessage(message.get(), false)) return; } } bool V8ConsoleAgentImpl::reportMessage(V8ConsoleMessage* message, bool generatePreview) { m_frontend.messageAdded(message->buildInspectorObject(m_session, generatePreview)); m_frontend.flush(); return m_session->debugger()->hasConsoleMessageStorage(m_session->contextGroupId()); } } // namespace blink
3,401
1,038
#include <stdio.h> int main(){ int v[10001], n,x,y, maior, menor; scanf("%d", &n); for(int i =0; i < n; i++){ scanf("%d %d", &x, &y); if(x > y){ maior = x; menor = y; }else{ maior = y; menor = x; } v[i]=0; for(int j = menor + 1; j < maior; j++){ if(j % 2 != 0) v[i]+=j; } } for(int i =0; i < n; i++){ printf("%d\n", v[i]); } return 0; }
486
205
// ************************************** // File: KButtonView.cpp // Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved. // Website: http://www.nuiengine.com // Description: This code is part of NUI Engine (NUI Graphics Lib) // Comments: // Rev: 2 // Created: 2017/4/11 // Last edit: 2017/4/28 // Author: Chen Zhi // E-mail: cz_666@qq.com // License: APACHE V2.0 (see license file) // *************************************** #include "KButtonView.h" #include "DataSync.h" #include "KShapeDrawable.h" /////////////////// KImgButtonView ////////////////////////// KImgButtonView::KImgButtonView() { m_e_viewtype = KVIEW_BUTTON; m_b_check_alpha = FALSE; } KImgButtonView::~KImgButtonView() { } void KImgButtonView::setState( ViewState state, kn_bool bRefresh ) { //调用基类函数设置文本状态,传入False不激活刷新 if (m_state != state) { //m_state = state; writeLock lock(m_lst_drawable_mutex); switch(state) { case BS_FOCUS: m_lst_drawable[0] = m_focus_bk_drawable; break; case BS_NORMAL: m_lst_drawable[0] = m_bk_drawable; break; case BS_PRESSED: case BS_ACTIVE: m_lst_drawable[0] = m_selected_bk_drawable; break; case BS_DISABLED: m_lst_drawable[0] = m_disable_bk_drawable; break; default: break; } lock.unlock(); KTextView::setState(state, FALSE); if (bRefresh) { InvalidateView(); } } } void KImgButtonView::setBKGImage(const kn_string& normalResPath, const kn_string& focusResPath, const kn_string& selectedResPath, const kn_string& disabledResPath) { KDrawable_PTR normal = KImageDrawable_PTR(new KImageDrawable(normalResPath)); KDrawable_PTR focus = KImageDrawable_PTR(new KImageDrawable(focusResPath)); KDrawable_PTR selected = KImageDrawable_PTR(new KImageDrawable(selectedResPath)); KDrawable_PTR disable = KImageDrawable_PTR(new KImageDrawable(disabledResPath)); setBKG(normal,focus,selected,disable); } void KImgButtonView::setBKG( KDrawable_PTR normal, KDrawable_PTR focus, KDrawable_PTR selected, KDrawable_PTR disabled) { writeLock lock(m_lst_drawable_mutex); m_bk_drawable = normal; m_focus_bk_drawable = focus; m_selected_bk_drawable = selected; m_disable_bk_drawable = disabled; m_lst_drawable[0] = m_bk_drawable; //不要忘了释放锁 lock.unlock(); showBK(TRUE); }
2,342
974
#include <iostream> #include <fstream> #include "lexer.h" #include "parser.h" using namespace kaleidoscope; int main(int argc, char **argv) { if (argc != 2) { std::cout << "Too few arguments; you need to specify the input filename.\n"; return -1; } std::fstream f(argv[1]); if (f.fail()) { std::cout << "Error reading file: " << argv[1] << "\n"; return -1; } std::cout << "Reading file: " << argv[1] << "...\n"; Lexer lexer(f); Parser parser(lexer); parser.parse(); f.close(); return 0; }
535
214
// 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 "net/url_request/url_request_context_builder.h" #include <string> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/thread_task_runner_handle.h" #include "base/threading/thread.h" #include "net/base/cache_type.h" #include "net/base/net_errors.h" #include "net/base/network_delegate.h" #include "net/cert/cert_verifier.h" #include "net/cookies/cookie_monster.h" #include "net/dns/host_resolver.h" #include "net/ftp/ftp_network_layer.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" #include "net/http/http_network_session.h" #include "net/http/http_server_properties_impl.h" #include "net/http/transport_security_persister.h" #include "net/http/transport_security_state.h" #include "net/ssl/channel_id_service.h" #include "net/ssl/default_channel_id_store.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/url_request/data_protocol_handler.h" #include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_storage.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_throttler_manager.h" #if !defined(DISABLE_FILE_SUPPORT) #include "net/url_request/file_protocol_handler.h" #endif #if !defined(DISABLE_FTP_SUPPORT) #include "net/url_request/ftp_protocol_handler.h" #endif namespace net { namespace { class BasicNetworkDelegate : public NetworkDelegate { public: BasicNetworkDelegate() {} virtual ~BasicNetworkDelegate() {} private: virtual int OnBeforeURLRequest(URLRequest* request, const CompletionCallback& callback, GURL* new_url) OVERRIDE { return OK; } virtual int OnBeforeSendHeaders(URLRequest* request, const CompletionCallback& callback, HttpRequestHeaders* headers) OVERRIDE { return OK; } virtual void OnSendHeaders(URLRequest* request, const HttpRequestHeaders& headers) OVERRIDE {} virtual int OnHeadersReceived( URLRequest* request, const CompletionCallback& callback, const HttpResponseHeaders* original_response_headers, scoped_refptr<HttpResponseHeaders>* override_response_headers, GURL* allowed_unsafe_redirect_url) OVERRIDE { return OK; } virtual void OnBeforeRedirect(URLRequest* request, const GURL& new_location) OVERRIDE {} virtual void OnResponseStarted(URLRequest* request) OVERRIDE {} virtual void OnRawBytesRead(const URLRequest& request, int bytes_read) OVERRIDE {} virtual void OnCompleted(URLRequest* request, bool started) OVERRIDE {} virtual void OnURLRequestDestroyed(URLRequest* request) OVERRIDE {} virtual void OnPACScriptError(int line_number, const base::string16& error) OVERRIDE {} virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired( URLRequest* request, const AuthChallengeInfo& auth_info, const AuthCallback& callback, AuthCredentials* credentials) OVERRIDE { return NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; } virtual bool OnCanGetCookies(const URLRequest& request, const CookieList& cookie_list) OVERRIDE { return true; } virtual bool OnCanSetCookie(const URLRequest& request, const std::string& cookie_line, CookieOptions* options) OVERRIDE { return true; } virtual bool OnCanAccessFile(const net::URLRequest& request, const base::FilePath& path) const OVERRIDE { return true; } virtual bool OnCanThrottleRequest(const URLRequest& request) const OVERRIDE { // Returning true will only enable throttling if there's also a // URLRequestThrottlerManager, which there isn't, by default. return true; } virtual int OnBeforeSocketStreamConnect( SocketStream* stream, const CompletionCallback& callback) OVERRIDE { return OK; } DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate); }; class BasicURLRequestContext : public URLRequestContext { public: BasicURLRequestContext() : storage_(this) {} URLRequestContextStorage* storage() { return &storage_; } base::Thread* GetCacheThread() { if (!cache_thread_) { cache_thread_.reset(new base::Thread("Network Cache Thread")); cache_thread_->StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); } return cache_thread_.get(); } base::Thread* GetFileThread() { if (!file_thread_) { file_thread_.reset(new base::Thread("Network File Thread")); file_thread_->StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_DEFAULT, 0)); } return file_thread_.get(); } void set_transport_security_persister( scoped_ptr<TransportSecurityPersister> transport_security_persister) { transport_security_persister = transport_security_persister.Pass(); } protected: virtual ~BasicURLRequestContext() { AssertNoURLRequests(); } private: // Threads should be torn down last. scoped_ptr<base::Thread> cache_thread_; scoped_ptr<base::Thread> file_thread_; URLRequestContextStorage storage_; scoped_ptr<TransportSecurityPersister> transport_security_persister_; DISALLOW_COPY_AND_ASSIGN(BasicURLRequestContext); }; } // namespace URLRequestContextBuilder::HttpCacheParams::HttpCacheParams() : type(IN_MEMORY), max_size(0) {} URLRequestContextBuilder::HttpCacheParams::~HttpCacheParams() {} URLRequestContextBuilder::HttpNetworkSessionParams::HttpNetworkSessionParams() : ignore_certificate_errors(false), host_mapping_rules(NULL), testing_fixed_http_port(0), testing_fixed_https_port(0), next_protos(NextProtosDefaults()), use_alternate_protocols(true), enable_quic(false) { } URLRequestContextBuilder::HttpNetworkSessionParams::~HttpNetworkSessionParams() {} URLRequestContextBuilder::SchemeFactory::SchemeFactory( const std::string& auth_scheme, net::HttpAuthHandlerFactory* auth_handler_factory) : scheme(auth_scheme), factory(auth_handler_factory) { } URLRequestContextBuilder::SchemeFactory::~SchemeFactory() { } URLRequestContextBuilder::URLRequestContextBuilder() : data_enabled_(false), #if !defined(DISABLE_FILE_SUPPORT) file_enabled_(false), #endif #if !defined(DISABLE_FTP_SUPPORT) ftp_enabled_(false), #endif http_cache_enabled_(true), throttling_enabled_(false), channel_id_enabled_(true) { } URLRequestContextBuilder::~URLRequestContextBuilder() {} void URLRequestContextBuilder::EnableHttpCache(const HttpCacheParams& params) { http_cache_enabled_ = true; http_cache_params_ = params; } void URLRequestContextBuilder::DisableHttpCache() { http_cache_enabled_ = false; http_cache_params_ = HttpCacheParams(); } void URLRequestContextBuilder::SetSpdyAndQuicEnabled(bool spdy_enabled, bool quic_enabled) { http_network_session_params_.next_protos = NextProtosWithSpdyAndQuic(spdy_enabled, quic_enabled); http_network_session_params_.enable_quic = quic_enabled; } URLRequestContext* URLRequestContextBuilder::Build() { BasicURLRequestContext* context = new BasicURLRequestContext; URLRequestContextStorage* storage = context->storage(); storage->set_http_user_agent_settings(new StaticHttpUserAgentSettings( accept_language_, user_agent_)); if (!network_delegate_) network_delegate_.reset(new BasicNetworkDelegate); NetworkDelegate* network_delegate = network_delegate_.release(); storage->set_network_delegate(network_delegate); if (net_log_) { storage->set_net_log(net_log_.release()); } else { storage->set_net_log(new net::NetLog); } if (!host_resolver_) { host_resolver_ = net::HostResolver::CreateDefaultResolver( context->net_log()); } storage->set_host_resolver(host_resolver_.Pass()); if (!proxy_service_) { // TODO(willchan): Switch to using this code when // ProxyService::CreateSystemProxyConfigService()'s signature doesn't suck. #if defined(OS_LINUX) || defined(OS_ANDROID) ProxyConfigService* proxy_config_service = proxy_config_service_.release(); #else ProxyConfigService* proxy_config_service = NULL; if (proxy_config_service_) { proxy_config_service = proxy_config_service_.release(); } else { proxy_config_service = ProxyService::CreateSystemProxyConfigService( base::ThreadTaskRunnerHandle::Get().get(), context->GetFileThread()->task_runner()); } #endif // defined(OS_LINUX) || defined(OS_ANDROID) proxy_service_.reset( ProxyService::CreateUsingSystemProxyResolver( proxy_config_service, 0, // This results in using the default value. context->net_log())); } storage->set_proxy_service(proxy_service_.release()); storage->set_ssl_config_service(new net::SSLConfigServiceDefaults); HttpAuthHandlerRegistryFactory* http_auth_handler_registry_factory = net::HttpAuthHandlerRegistryFactory::CreateDefault( context->host_resolver()); for (size_t i = 0; i < extra_http_auth_handlers_.size(); ++i) { http_auth_handler_registry_factory->RegisterSchemeFactory( extra_http_auth_handlers_[i].scheme, extra_http_auth_handlers_[i].factory); } storage->set_http_auth_handler_factory(http_auth_handler_registry_factory); storage->set_cookie_store(new CookieMonster(NULL, NULL)); if (channel_id_enabled_) { // TODO(mmenke): This always creates a file thread, even when it ends up // not being used. Consider lazily creating the thread. storage->set_channel_id_service( new ChannelIDService( new DefaultChannelIDStore(NULL), context->GetFileThread()->message_loop_proxy())); } storage->set_transport_security_state(new net::TransportSecurityState()); if (!transport_security_persister_path_.empty()) { context->set_transport_security_persister( make_scoped_ptr<TransportSecurityPersister>( new TransportSecurityPersister( context->transport_security_state(), transport_security_persister_path_, context->GetFileThread()->message_loop_proxy(), false))); } storage->set_http_server_properties( scoped_ptr<net::HttpServerProperties>( new net::HttpServerPropertiesImpl())); storage->set_cert_verifier(CertVerifier::CreateDefault()); if (throttling_enabled_) storage->set_throttler_manager(new URLRequestThrottlerManager()); net::HttpNetworkSession::Params network_session_params; network_session_params.host_resolver = context->host_resolver(); network_session_params.cert_verifier = context->cert_verifier(); network_session_params.transport_security_state = context->transport_security_state(); network_session_params.proxy_service = context->proxy_service(); network_session_params.ssl_config_service = context->ssl_config_service(); network_session_params.http_auth_handler_factory = context->http_auth_handler_factory(); network_session_params.network_delegate = network_delegate; network_session_params.http_server_properties = context->http_server_properties(); network_session_params.net_log = context->net_log(); network_session_params.ignore_certificate_errors = http_network_session_params_.ignore_certificate_errors; network_session_params.host_mapping_rules = http_network_session_params_.host_mapping_rules; network_session_params.testing_fixed_http_port = http_network_session_params_.testing_fixed_http_port; network_session_params.testing_fixed_https_port = http_network_session_params_.testing_fixed_https_port; network_session_params.use_alternate_protocols = http_network_session_params_.use_alternate_protocols; network_session_params.trusted_spdy_proxy = http_network_session_params_.trusted_spdy_proxy; network_session_params.next_protos = http_network_session_params_.next_protos; network_session_params.enable_quic = http_network_session_params_.enable_quic; HttpTransactionFactory* http_transaction_factory = NULL; if (http_cache_enabled_) { network_session_params.channel_id_service = context->channel_id_service(); HttpCache::BackendFactory* http_cache_backend = NULL; if (http_cache_params_.type == HttpCacheParams::DISK) { http_cache_backend = new HttpCache::DefaultBackend( DISK_CACHE, net::CACHE_BACKEND_DEFAULT, http_cache_params_.path, http_cache_params_.max_size, context->GetCacheThread()->task_runner()); } else { http_cache_backend = HttpCache::DefaultBackend::InMemory(http_cache_params_.max_size); } http_transaction_factory = new HttpCache( network_session_params, http_cache_backend); } else { scoped_refptr<net::HttpNetworkSession> network_session( new net::HttpNetworkSession(network_session_params)); http_transaction_factory = new HttpNetworkLayer(network_session.get()); } storage->set_http_transaction_factory(http_transaction_factory); URLRequestJobFactoryImpl* job_factory = new URLRequestJobFactoryImpl; if (data_enabled_) job_factory->SetProtocolHandler("data", new DataProtocolHandler); #if !defined(DISABLE_FILE_SUPPORT) if (file_enabled_) { job_factory->SetProtocolHandler( "file", new FileProtocolHandler(context->GetFileThread()->message_loop_proxy())); } #endif // !defined(DISABLE_FILE_SUPPORT) #if !defined(DISABLE_FTP_SUPPORT) if (ftp_enabled_) { ftp_transaction_factory_.reset( new FtpNetworkLayer(context->host_resolver())); job_factory->SetProtocolHandler("ftp", new FtpProtocolHandler(ftp_transaction_factory_.get())); } #endif // !defined(DISABLE_FTP_SUPPORT) storage->set_job_factory(job_factory); // TODO(willchan): Support sdch. return context; } } // namespace net
14,569
4,366
// Copyright (c) 2018 Parsa Amini // Copyright (c) 2018 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(PHYLANX_PRIMITIVES_SUM) #define PHYLANX_PRIMITIVES_SUM #include <phylanx/config.hpp> #include <phylanx/execution_tree/primitives/base_primitive.hpp> #include <phylanx/execution_tree/primitives/primitive_component_base.hpp> #include <hpx/lcos/future.hpp> #include <hpx/util/optional.hpp> #include <cstdint> #include <string> #include <vector> namespace phylanx { namespace execution_tree { namespace primitives { /// \brief Sums the values of the elements of a vector or a matrix or /// returns the value of the scalar that was given to it. /// \param a The scalar, vector, or matrix to perform sum over /// \param axis Optional. If provided, sum is calculated along the /// provided axis and a vector of results is returned. /// \p keep_dims is ignored if \p axis present. Must be /// nil if \p keep_dims is set /// \param keep_dims Optional. Whether the sum value has to have the same /// number of dimensions as \p a. Ignored if \p axis is /// anything except nil. class sum_operation : public primitive_component_base , public std::enable_shared_from_this<sum_operation> { protected: hpx::future<primitive_argument_type> eval( std::vector<primitive_argument_type> const& operands, std::vector<primitive_argument_type> const& args) const; using val_type = double; using arg_type = ir::node_data<val_type>; using args_type = std::vector<arg_type>; public: static match_pattern_type const match_data; sum_operation() = default; sum_operation(std::vector<primitive_argument_type>&& operands, std::string const& name, std::string const& codename); hpx::future<primitive_argument_type> eval( std::vector<primitive_argument_type> const& args) const override; private: primitive_argument_type sum0d(arg_type&& arg, hpx::util::optional<std::int64_t> axis, bool keep_dims) const; primitive_argument_type sum1d(arg_type&& arg, hpx::util::optional<std::int64_t> axis, bool keep_dims) const; primitive_argument_type sum2d(arg_type&& arg, hpx::util::optional<std::int64_t> axis, bool keep_dims) const; primitive_argument_type sum2d_flat( arg_type&& arg, bool keep_dims) const; primitive_argument_type sum2d_axis0(arg_type&& arg) const; primitive_argument_type sum2d_axis1(arg_type&& arg) const; }; PHYLANX_EXPORT primitive create_sum_operation(hpx::id_type const& locality, std::vector<primitive_argument_type>&& operands, std::string const& name = "", std::string const& codename = ""); }}} #endif
3,054
957
// // FILE NAME: CQCTreeBrws_CfgSrvBrws.cpp // // AUTHOR: Dean Roddey // // CREATED: 12/11/2015 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the remote browser derivative that handles browsing the // config server. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CQCTreeBrws_.hpp" #include "CQCTreeBrws_CfgSrvBrws_.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TCQCCfgSrvBrws,TCQCTreeBrwsIntf) // --------------------------------------------------------------------------- // CLASS: TCQCCfgSrvBrws // PREFIX: rbrws // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TCQCCfgSrvBrws: Constructors and Destructor // --------------------------------------------------------------------------- TCQCCfgSrvBrws::TCQCCfgSrvBrws() : TCQCTreeBrwsIntf ( kCQCRemBrws::strPath_Configure , kCQCRemBrws::strItem_Configure , facCQCTreeBrws().strMsg(kTBrwsMsgs::midTitle_ConfBrower) ) { } TCQCCfgSrvBrws::~TCQCCfgSrvBrws() { } // --------------------------------------------------------------------------- // TCQCCfgSrvBrws: Public, inherited methods // --------------------------------------------------------------------------- // Our browser object never accepts dropped files, so this won't get called tCIDLib::TVoid TCQCCfgSrvBrws::AcceptFiles(const TString& , const tCIDLib::TStrList& , const tCIDLib::TStrList&) { CIDAssert2(L"The config server browser should not be accepting files"); } // We never accept dropped files in this section tCIDLib::TBoolean TCQCCfgSrvBrws::bAcceptsNew(const TString&, const tCIDLib::TStrHashSet&) const { return kCIDLib::False; } // // The browser window calls us here if the user invokes a menu operation on the // tree window. // tCIDLib::TBoolean TCQCCfgSrvBrws::bDoMenuAction( const TString& strPath , TTreeBrowseInfo& wnotToSend) { // Get the area of this item, tell it to use just the text width TArea areaItem; wndBrowser().bQueryItemArea(strPath, areaItem, kCIDLib::True, kCIDLib::True); // Get the center point of it and convert to screen coordinates TPoint pntAt; wndBrowser().ToScreenCoordinates(areaItem.pntCenter(), pntAt); // Create the menu and load it up from the resource TPopupMenu menuAction(L"/Configure Action"); // Depending on the type of thing selected, we do a different menu tCIDLib::TBoolean bAtTop; const tCQCRemBrws::EDTypes eDType = ePathToDType(strPath, bAtTop); const tCIDLib::TBoolean bNoType(eDType == tCQCRemBrws::EDTypes::Count); const tCIDLib::TBoolean bScope = wndBrowser().bIsScope(strPath); tCIDLib::TCard4 c4MenuCmd = 0; menuAction.Create(facCQCTreeBrws(), kCQCTreeBrws::ridMenu_GenFile); // If an item, or not e-mail or user, then disable new if (!bScope || ((eDType != tCQCRemBrws::EDTypes::EMailAccount) && (eDType != tCQCRemBrws::EDTypes::User))) { menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_New, kCIDLib::False); } // If a scope, or not an e-mail or user, then disable delete if (bScope || ((eDType != tCQCRemBrws::EDTypes::EMailAccount) && (eDType != tCQCRemBrws::EDTypes::User))) { menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Delete, kCIDLib::False); } // If a scope, disable the Edit and Copy. If not, disable the Refresh and Paste if (bScope) { menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Copy, kCIDLib::False); menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Edit, kCIDLib::False); } else { menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Paste, kCIDLib::False); menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Refresh, kCIDLib::False); } // We only allow email accounts to be renamed if (bScope || (eDType != tCQCRemBrws::EDTypes::EMailAccount)) menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Rename, kCIDLib::False); c4MenuCmd = menuAction.c4Process(wndBrowser(), pntAt, tCIDLib::EVJustify::Bottom); // // If they made a choice, then we have to translate it to the standard action // enum that the browser window will understand. // return bProcessMenuSelection(c4MenuCmd, strPath, wnotToSend); } // We don't use a persistent connection, so we just say yes tCIDLib::TBoolean TCQCCfgSrvBrws::bIsConnected() const { return kCIDLib::True; } // // Our own bDoMenuAction calls this if a selection is made. It is also called by the // browser window if an accelerator driven command is seen. That's why it's split out // so that we can avoid duplicating this code. // tCIDLib::TBoolean TCQCCfgSrvBrws::bProcessMenuSelection( const tCIDLib::TCard4 c4CmdId , const TString& strPath , TTreeBrowseInfo& wnotToSend) { // See what the data type is, if any tCIDLib::TBoolean bAtTop = kCIDLib::False; const tCQCRemBrws::EDTypes eType = ePathToDType(strPath, bAtTop); tCIDLib::TBoolean bRet = kCIDLib::True; switch(c4CmdId) { case kCQCTreeBrws::ridMenu_GenFile_Edit : { // Just inform the containing application that the user wants to edit CIDAssert(eType != tCQCRemBrws::EDTypes::Count, L"Unknown data type for Edit"); wnotToSend = TTreeBrowseInfo ( tCQCTreeBrws::EEvents::Edit, strPath, eType, wndBrowser() ); break; } case kCQCTreeBrws::ridMenu_GenFile_New : { CIDAssert(eType != tCQCRemBrws::EDTypes::Count, L"Unknown data type for New"); bRet = bMakeNewFile(strPath, eType, wnotToSend); break; } case kCQCTreeBrws::ridMenu_GenFile_Delete : { CIDAssert(eType != tCQCRemBrws::EDTypes::Count, L"Unknown data type for Delete"); // Delete the indicated file if (bDeleteFile(strPath)) { // Let any listeners know we did this wnotToSend = TTreeBrowseInfo ( tCQCTreeBrws::EEvents::Deleted, strPath, eType, wndBrowser() ); } break; } case kCQCTreeBrws::ridMenu_GenFile_Refresh : { // We just handle this one internally UpdateScope(strPath); break; } case kCQCTreeBrws::ridMenu_GenFile_Rename : { // Call our parent's rename method which does what we want bRet = bDoRename(strPath, wnotToSend); break; } default : bRet = kCIDLib::False; break; }; return bRet; } // // For our stuff, as long as it's not our top level path or some other scope, it's fine // to report it all when double clicked. The client code will decide if it really // wants to deal with it and how. So just checking to see if it's a scope is a good // enough check. We indicate these are all edit operations. // tCIDLib::TBoolean TCQCCfgSrvBrws::bReportInvocation(const TString& strPath, tCIDLib::TBoolean& bAsEdit) const { bAsEdit = kCIDLib::True; return !wndBrowser().bIsScope(strPath); } // // We add our top level scope and all of the next level ones since it's a fixed set // that we always have. // tCIDLib::TVoid TCQCCfgSrvBrws::Initialize(const TCQCUserCtx& cuctxUser) { TParent::Initialize(cuctxUser); TTreeView& wndTar = wndBrowser(); // // Add our top level scope. It's not marked as virtual in this case, since we // preload all of the possible top level items and sub-scopes. Some of our // sub-scopes will be virtual. // wndTar.AddScope ( kCQCRemBrws::strPath_Root, kCQCRemBrws::strItem_Configure, kCIDLib::False ); // // Load our main scopes. Some are virtual and will be faulted in only if // they are accessed. Others we know the content and will go ahead and load them. // wndTar.AddScope(kCQCRemBrws::strPath_Configure, L"Accounts", kCIDLib::True); wndTar.AddScope(kCQCRemBrws::strPath_Accounts, L"EMail", kCIDLib::True); wndTar.AddScope(kCQCRemBrws::strPath_Configure, L"Ports", kCIDLib::True); wndTar.AddScope(kCQCRemBrws::strPath_Configure, L"Users", kCIDLib::True); // // These are items at the top level, not scopes. These are for known, fixed data // and cannot be removed. // wndTar.AddItem(kCQCRemBrws::strPath_Ports, L"GC-100"); wndTar.AddItem(kCQCRemBrws::strPath_Ports, L"JustAddPwr"); wndTar.AddItem(kCQCRemBrws::strPath_Configure, L"LogicSrv"); wndTar.AddItem(kCQCRemBrws::strPath_Configure, L"Location"); wndTar.AddItem(kCQCRemBrws::strPath_Configure, L"SystemCfg"); } tCIDLib::TVoid TCQCCfgSrvBrws::LoadScope(const TString& strPath) { TTreeView& wndTar = wndBrowser(); try { // // Depending on the path, let's load up the relevant info and put it into // the tree. // if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users)) LoadUsers(wndTar); else if (strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts)) LoadEMails(wndTar); // // Probably this happened, if we added any above. But, if the scope was // empty, then we need to do this just in case, to clear set the child // count info, which also turns off the virtual scope flag, so we won't // try to fault this one back in. // wndTar.UpdateChildCnt(strPath); // // At the end of an expansion, force the expanded once state on. It won't // get done if this is a lazily faulted in tree and the expanded scope // ended up being empty. That will cause lots of problems later. // wndTar.ForceExpandedOnce(strPath); } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); facCQCGKit().ShowError ( wndBrowser(), strTitle(), L"Could not expand item", errToCatch ); } } // // Some of our stuff doesn't use this, like user accounts, because they have to have a // correct name up front. For other stuff we create a default name based on the parent // scope. // tCIDLib::TVoid TCQCCfgSrvBrws::MakeDefName(const TString& strParScope , TString& strToFill , const tCIDLib::TBoolean bIsFile) const { tCIDLib::TBoolean bAtTop = kCIDLib::False; const tCQCRemBrws::EDTypes eType = ePathToDType(strParScope, bAtTop); CIDAssert(bAtTop, L"The parent scope was not the top level scope for its type"); // Build up the base name for the new guy TString strCurPath(strParScope); strCurPath.Append(kCIDLib::chForwardSlash); strCurPath.Append(tCQCRemBrws::strXlatEDTypes(eType)); // Now we add numbers to it until we get a unique name not already in this scope. const tCIDLib::TCard4 c4BaseLen = strCurPath.c4Length(); tCIDLib::TCard4 c4Num = 1; while (kCIDLib::True) { strCurPath.CapAt(c4BaseLen); strCurPath.AppendFormatted(c4Num); if (!wndBrowser().bPathExists(strCurPath)) { strToFill = tCQCRemBrws::strXlatEDTypes(eType); strToFill.AppendFormatted(c4Num); break; } // Not unique, to try another c4Num++; } } // // If the browser window gets an accelerator key translation call, he will call us // here to load up an accelerator table for him which he will process. If it causes // him to get a menu call, he will pass it on to us. // tCIDLib::TVoid TCQCCfgSrvBrws::QueryAccelTable(const TString& strPath , TAccelTable& accelToFill) const { // // Just load it up from our menu. So we just create an instance of our menu but // never show it. // TPopupMenu menuAction(L"/Configure Action"); // Depending on the type of thing selected, we do a different menu tCIDLib::TBoolean bAtTop; const tCQCRemBrws::EDTypes eDType = ePathToDType(strPath, bAtTop); if ((eDType == tCQCRemBrws::EDTypes::EMailAccount) || (eDType == tCQCRemBrws::EDTypes::User)) { menuAction.Create(facCQCTreeBrws(), kCQCTreeBrws::ridMenu_GenFile); if (!bAtTop) menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_New, kCIDLib::False); } else { // Don't have a menu for this so nothing return; } // And now set up the accel table from the menu accelToFill.Create(menuAction); } // We don't use a persistent connection, so nothing really to do here tCIDLib::TVoid TCQCCfgSrvBrws::Terminate() { } // --------------------------------------------------------------------------- // TCQCCfgSrvBrws: Protected, inherited methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TCQCCfgSrvBrws::bCanRename(const TString& strPath) const { // // The only things we currently allow to be renamed are e-mail accounts. Everything // else is all special stuff. // return ( !wndBrowser().bIsScope(strPath) && strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts) ); } tCIDLib::TBoolean TCQCCfgSrvBrws::bRenameItem(const TString& strParScope , const TString& strOldName , const TString& strNewName , const tCIDLib::TBoolean bIsScope) { try { // Depending on the parent scope, we do the appropriate thing if (strParScope.bStartsWithI(kCQCRemBrws::strPath_EMailAccts)) { TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait); tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy(); orbcInst->RenameEMailAccount(strOldName, strNewName, sectUser()); // And now tell the tree to update the display text of the item wndBrowser().UpdateItem(strParScope, strOldName, strNewName); } else { TErrBox msgbErr(strTitle(), L"This data type cannot be renamed"); msgbErr.ShowIt(wndBrowser()); } } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); facCQCGKit().ShowError ( wndBrowser(), strTitle(), L"Could not expand item", errToCatch ); return kCIDLib::False; } return kCIDLib::True; } // --------------------------------------------------------------------------- // TCQCCfgSrvBrws: Private, non-virtual methods // --------------------------------------------------------------------------- // // This is called if we get a delete command (via menu or hot key). We look at // the type and do the appropriate // tCIDLib::TBoolean TCQCCfgSrvBrws::bDeleteFile(const TString& strPath) { // Make sure that they really want to do it TYesNoBox msgbConfirm ( strTitle(), facCQCTreeBrws().strMsg(kTBrwsMsgs::midQ_DeleteItem, strPath) ); if (!msgbConfirm.bShowIt(wndBrowser())) return kCIDLib::False; tCQCRemBrws::EDTypes eType = tCQCRemBrws::EDTypes::Count; try { if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users)) { // Set this first in case of error eType = tCQCRemBrws::EDTypes::User; // // Let's try to delete the indicated user. The last part of the path is // the login name. We can get an error, even if the login name is valid, // if they try to delete the last admin account. // TString strLoginName; facCQCRemBrws().QueryNamePart(strPath, strLoginName); tCQCKit::TSecuritySrvProxy orbcSrc = facCQCKit().orbcSecuritySrvProxy(); orbcSrc->DeleteAccount(strLoginName, sectUser()); } else if (strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts)) { // Set this first in case of error eType = tCQCRemBrws::EDTypes::EMailAccount; TString strAcctName; facCQCRemBrws().QueryNamePart(strPath, strAcctName); TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait); tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy(); if (!orbcInst->bDeleteEMailAccount(strAcctName, sectUser())) { facCQCTreeBrws().LogMsg ( CID_FILE , CID_LINE , kTBrwsErrs::errcBrws_EMailDelete , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotFound , strAcctName ); } } else { // // Shouldn't happen, since we don't allow it in menus and we don't create // a delete accellerator unless it's a deletable item. But, just in case. // facCQCGKit().ShowError ( wndBrowser() , strTitle() , L"This item cannot be deleted, and you shouldn't have been able to " L" try to do so. Sorry about that. Please report this issue." ); return kCIDLib::False; } } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); TString strMsg = TString::strConcat ( L"An error occurred while deleting the ", tCQCRemBrws::strLoadEDTypes(eType) ); facCQCGKit().ShowError(wndBrowser(), strTitle(), strMsg, errToCatch); return kCIDLib::False; } // It didn't fail, so remove this item from the browser window wndBrowser().RemoveItem(strPath); return kCIDLib::True; } // // This is called when we get a New menu selection. We see if it's one of the types // of ours that we can create (it should be since the menu shouldn't have allowed // otherwise.) We try to create the new file and get it into the browser. // tCIDLib::TBoolean TCQCCfgSrvBrws::bMakeNewFile(const TString& strParHPath , const tCQCRemBrws::EDTypes eDType , TTreeBrowseInfo& wnotToSend) { // We need the browser a number of times so get a convenient ref TCQCTreeBrowser& wndTar = wndBrowser(); // // The first thing we need to do is to get a name from the user. We call // a helper on the browser window do this since it's sort of messy. If they // don't commit, we return and nothing has been done. // TString strNewName; if (!wndTar.bGetNewName(strParHPath, kCIDLib::False, eDType, strNewName, *this)) return kCIDLib::False; // Build up the new full hierarchical path TString strNewHPath(strParHPath); facCQCRemBrws().AddPathComp(strNewHPath, strNewName); // // At this point the item is in the tree. We need to make sure it gets removed // if we don't explicitly decide to keep it. // TTreeItemJan janTree(&wndTar, strNewHPath); // Get the type relative version of the parent path TString strParRelPath; facCQCRemBrws().CreateRelPath(strParHPath, eDType, strParRelPath); tCIDLib::TBoolean bRet = kCIDLib::False; try { if (eDType == tCQCRemBrws::EDTypes::EMailAccount) { bRet = bMakeNewEmailAcct(strParHPath, strParRelPath, strNewName); } else if (eDType == tCQCRemBrws::EDTypes::User) { bRet = bMakeNewUserAcct(strParHPath, strParRelPath, strNewName); } else { // Not something we can edit TErrBox msgbView ( strTitle() , facCQCTreeBrws().strMsg ( kTBrwsMsgs::midStatus_CantNew , tCQCRemBrws::strLoadEDTypes(eDType) , strNewHPath ) ); msgbView.ShowIt(wndBrowser()); return kCIDLib::False; } // It appears to have worked, so prevent the janitor from removing it janTree.Orphan(); } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); TErrBox msgbNew ( strTitle() , facCQCRemBrws().strMsg(kTBrwsMsgs::midStatus_CantCreateFile, strNewHPath) ); msgbNew.ShowIt(wndTar); return kCIDLib::False; } // Select this new guy wndTar.SelectPath(strNewHPath); // It workeed so fill in a notification to be sent to the containing app wnotToSend = TTreeBrowseInfo ( tCQCTreeBrws::EEvents::NewFile, strNewHPath, eDType, wndBrowser() ); return bRet; } // // This is called to create a e-mail account. We just generate an empty one with // a default name, save it which also adds it to the tree view, and select it. We don't // need the hierarchy path info here for this. // tCIDLib::TBoolean TCQCCfgSrvBrws::bMakeNewEmailAcct(const TString&, const TString&, const TString& strNewName) { // Set up a default account TCQCEMailAccount emacctNew; emacctNew.Set ( tCQCKit::EEMailTypes::Unused , strNewName , L"me@myisp.com" , L"HappyWeaselParty" , L"myisp.com" , L"Bubba" , 25 ); TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait); tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy(); tCIDLib::TCard4 c4SerNum = 0; // Indicate it must be a new account, if not it will throw return orbcInst->bUpdateEmailAccount(emacctNew, c4SerNum, sectUser(), kCIDLib::True); } // // Called when the user asks to create a new user account. This one is a little special. // In this case, we don't get a default name. The name has to be set up front and // cannot be changed once it's created and stored away. So in this special case we // get a login name from the user up front and use that. // tCIDLib::TBoolean TCQCCfgSrvBrws::bMakeNewUserAcct(const TString& strParHPath , const TString& strParRelPath , const TString& strNewName) { // Set up a user account with basic info TCQCUserAccount uaccNew ( tCQCKit::EUserRoles::NormalUser , L"New user account" , strNewName , L"Welcome" , L"John" , L"Smith" ); // Create the hierarchical path for display purposes TString strNewHPath(strParHPath); strNewHPath.Append(kCIDLib::chForwardSlash); strNewHPath.Append(strNewName); tCQCKit::TSecuritySrvProxy orbcSrc = facCQCKit().orbcSecuritySrvProxy(); // // In order to provide a more targeted error message for a common possible // error, we check to see if this login name already exists. We have to provide // the current user's security token to get this info. // if (orbcSrc->bLoginExists(strNewName, cuctxUser().sectUser())) { TErrBox msgbNew ( strTitle() , facCQCTreeBrws().strMsg(kTBrwsErrs::errcBrws_UAccExists, strNewName) ); msgbNew.ShowIt(wndBrowser()); return kCIDLib::False; } orbcSrc->CreateAccount(uaccNew, sectUser()); return kCIDLib::True; } // // Check the path to see if starts with the top level path for any of the types we // deal with. If not, we return the _Count value. // // We also indicate if it was the top level for that type, or is on some sub-scope of // it. // tCQCRemBrws::EDTypes TCQCCfgSrvBrws::ePathToDType(const TString& strPath, tCIDLib::TBoolean& bAtTop) const { bAtTop = kCIDLib::False; tCQCRemBrws::EDTypes eRet = tCQCRemBrws::EDTypes::Count; const TString* pstrRoot = nullptr; if (strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts)) { eRet = tCQCRemBrws::EDTypes::EMailAccount; pstrRoot = &kCQCRemBrws::strPath_EMailAccts; } else if (strPath.bStartsWithI(kCQCRemBrws::strPath_GC100Ports)) { eRet = tCQCRemBrws::EDTypes::GC100Ports; pstrRoot = &kCQCRemBrws::strPath_GC100Ports; } else if (strPath.bStartsWithI(kCQCRemBrws::strPath_JAPwrPorts)) { eRet = tCQCRemBrws::EDTypes::JAPwrPorts; pstrRoot = &kCQCRemBrws::strPath_JAPwrPorts; } else if (strPath.bStartsWithI(kCQCRemBrws::strPath_Location)) { eRet = tCQCRemBrws::EDTypes::Location; pstrRoot = &kCQCRemBrws::strPath_Location; } else if (strPath.bStartsWithI(kCQCRemBrws::strPath_LogicSrv)) { eRet = tCQCRemBrws::EDTypes::LogicSrv; pstrRoot = &kCQCRemBrws::strPath_LogicSrv; } else if (strPath.bStartsWithI(kCQCRemBrws::strPath_SystemCfg)) { eRet = tCQCRemBrws::EDTypes::SystemCfg; pstrRoot = &kCQCRemBrws::strPath_SystemCfg; } else if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users)) { eRet = tCQCRemBrws::EDTypes::User; pstrRoot = &kCQCRemBrws::strPath_Users; } if (eRet != tCQCRemBrws::EDTypes::Count) bAtTop = (strPath == *pstrRoot); return eRet; } // // Called when it's time to fault in our email accounts scope or the user asks to reload // the scope. In our case we just need to interate the config server scope that contains // the email accounts and load an entry for each one. // // We let exceptions propagate. // tCIDLib::TVoid TCQCCfgSrvBrws::LoadEMails(TTreeView& wndTar) { TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait); tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy(); tCIDLib::TStrList colList; orbcInst->bQueryEMailAccountNames(colList, sectUser()); colList.bForEach([&wndTar](const TString& strName) { wndTar.AddItem(kCQCRemBrws::strPath_EMailAccts, strName); return kCIDLib::True; }); } // // Called when it's time to fault in our users scope or the user asks to reload the // scope. // // We let exceptions propagate. // tCIDLib::TVoid TCQCCfgSrvBrws::LoadUsers(TTreeView& wndTar) { tCQCKit::TSecuritySrvProxy orbcSrc = facCQCKit().orbcSecuritySrvProxy(); // If we don't get any, then we are done TVector<TCQCUserAccount> colList; if (!orbcSrc->c4QueryAccounts(colList, sectUser())) return; // // Loop though the list and load them into the tree. The text is the login // name, which is also the key to upload changes, delete users and so forth. // TString strCurPath; const tCIDLib::TCard4 c4Count = colList.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TCQCUserAccount& uaccCur = colList[c4Index]; wndTar.AddItem(kCQCRemBrws::strPath_Users, uaccCur.strLoginName()); } } // // We query the contents of the indicated path, which must be a scope. We don't // try to be clever. We temporarily disable drawing, remove the contents of // the scope, then call our scope loader above to reload it. This also serves to // toss all of the nested scopes, so we go back to virtual scope mode on all of // them, to be subsequently reloaded as well. Not the most efficient, but the // safest. // tCIDLib::TVoid TCQCCfgSrvBrws::UpdateScope(const TString& strPath) { TTreeView& wndTar = wndBrowser(); try { // Has to be a scope CIDAssert(wndTar.bIsScope(strPath), L"Cannot update a non-scope item"); // Stop updates while we do this TWndPaintJanitor janPaint(&wndTar); wndBrowser().RemoveChildrenOf(strPath); // Now call the same private helper used to do the initial load if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users)) LoadUsers(wndTar); } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); facCQCGKit().ShowError ( wndBrowser(), strTitle(), L"Could not update scope", errToCatch ); } }
29,258
9,734
/*! \file \brief The AnnotationManager that generates ActiveStandard. \authors Michelle Strout \version $Id: ManagerActiveStandard.cpp,v 1.8 2005/06/10 02:32:02 mstrout Exp $ Copyright (c) 2002-2005, Rice University <br> Copyright (c) 2004-2005, University of Chicago <br> Copyright (c) 2006, Contributors <br> All rights reserved. <br> See ../../../Copyright.txt for details. <br> */ #include "ManagerActiveStandard.hpp" #include <Utils/Util.hpp> namespace OA { namespace Activity { static bool debug = false; /*! */ ManagerActiveStandard::ManagerActiveStandard(OA_ptr<ActivityIRInterface> _ir) : mIR(_ir) { OA_DEBUG_CTRL_MACRO("DEBUG_ManagerActiveStandard:ALL", debug); } /*! OA_ptr<ActiveStandard> ManagerActiveStandard::performAnalysis(ProcHandle proc, OA_ptr<CFG::Interface> cfg, OA_ptr<Alias::Interface> alias, OA_ptr<SideEffect::InterSideEffectInterface> interSE) { return performAnalysis(proc, cfg, alias, interSE, interSE->getUSEIterator(proc), interSE->getMODIterator(proc)); } */ /*! */ OA_ptr<ActiveStandard> ManagerActiveStandard::performAnalysis(ProcHandle proc, OA_ptr<CFG::CFGInterface> cfg, OA_ptr<Alias::Interface> alias, OA_ptr<VaryStandard> vary, OA_ptr<UsefulStandard> useful) { mAlias = alias; mActive = new ActiveStandard(proc); if (debug) { std::cout << "ManagerActiveStandard::performAnalysis: "; std::cout << "\tAnalyzing procedure " << mIR->toString(proc); std::cout << std::endl; } // first create DepStandard, VaryStandard, and UsefulStandard // Dep Analysis // OA_ptr<ManagerDepStandard> depman; // depman = new ManagerDepStandard(mIR); //mDep = depman->performAnalysis(proc, alias, cfg); // if (debug) { mDep->dump(std::cout, mIR); } // Vary // OA_ptr<ManagerVaryStandard> varyman; // varyman = new ManagerVaryStandard(mIR); // OA_ptr<VaryStandard> vary // = varyman->performAnalysis(proc, cfg, mDep, indepLocIter); // if (debug) { vary->dump(std::cout, mIR); } // Useful // OA_ptr<ManagerUsefulStandard> usefulman; // usefulman = new ManagerUsefulStandard(mIR); // OA_ptr<UsefulStandard> useful // = usefulman->performAnalysis(proc, cfg, mDep, depLocIter); // if (debug) { useful->dump(std::cout, mIR); } // initialize OutVaryIterator to iterator over independent variables OA_ptr<LocIterator> outVaryIterPtr = vary->getIndepSetIterator(); OA_ptr<LocIterator> depLocIter = useful->getDepSetIterator(); StmtHandle prevStmt = StmtHandle(0); // for each statement in the procedure OA_ptr<OA::IRStmtIterator> stmtIterPtr = mIR->getStmtIterator(proc); for ( ; stmtIterPtr->isValid(); (*stmtIterPtr)++) { OA::StmtHandle stmt = stmtIterPtr->current(); // send iterator for OutVary from previous stmt and InVary for current // stmt into a helper function that determines active locations, whether // the previous stmt was active, and which memory references in the // previous and current stmt are active calculateActive(prevStmt, outVaryIterPtr, stmt, useful->getInUsefulIterator(stmt)); // get OutVary for this stmt outVaryIterPtr = vary->getOutVaryIterator(stmt); prevStmt = stmt; } // do calculation for point after last stmt calculateActive(prevStmt, outVaryIterPtr, StmtHandle(0), depLocIter); return mActive; } /*! A helper function that determines active locations, whether the previous stmt was active, and which memory references in the previous and current stmt are active */ void ManagerActiveStandard::calculateActive( StmtHandle prevStmt, OA_ptr<LocIterator> prevOutVaryIter, StmtHandle stmt, OA_ptr<LocIterator> inUsefulIter) { if (debug) { std::cout << "\tcalculateActive ---------------------" << std::endl; } // get set of active locations prevOutVaryIter->reset(); for ( ; prevOutVaryIter->isValid(); (*prevOutVaryIter)++ ) { OA_ptr<Location> loc = prevOutVaryIter->current(); if (debug) { std::cout << "\t\tinVary loc = "; loc->dump(std::cout,mIR); } inUsefulIter->reset(); for ( ; inUsefulIter->isValid(); (*inUsefulIter)++ ) { if (debug) { std::cout << "\t\tinUseful loc = "; inUsefulIter->current()->dump(std::cout,mIR); } if (loc->mayOverlap(*(inUsefulIter->current())) ) { mActive->insertLoc(loc); mActive->insertLoc(inUsefulIter->current()); if (debug) { std::cout << "\t\tinserting active loc = "; loc->dump(std::cout,mIR); std::cout << "\t\tinserting active loc = "; inUsefulIter->current()->dump(std::cout,mIR); } } } } // get all the defines from prevStmt and if any of those memory // references have maylocs that may overlap with the active // locations then the prevStmt and the memory references are active if (prevStmt != StmtHandle(0)) { OA_ptr<MemRefHandleIterator> defIterPtr = mIR->getDefMemRefs(prevStmt); for ( ; defIterPtr->isValid(); (*defIterPtr)++ ) { MemRefHandle def = defIterPtr->current(); if (debug) { std::cout << "\t\tdef (" << def.hval() << ") = "; mIR->dump(def,std::cout); } OA_ptr<LocIterator> activeIterPtr = mActive->getActiveLocsIterator(); OA_ptr<LocIterator> locIterPtr = mAlias->getMayLocs(def); for (; locIterPtr->isValid(); ++(*locIterPtr)) { OA_ptr<Location> loc = locIterPtr->current(); activeIterPtr->reset(); for (; activeIterPtr->isValid(); (*activeIterPtr)++ ) { if (loc->mayOverlap(*(activeIterPtr->current())) ) { mActive->insertStmt(prevStmt); mActive->insertMemRef(def); } } } } } // get all the uses from stmt and if any of those memory // references have maylocs that may overlap with the active // locations then those memory references are active if (stmt != StmtHandle(0)) { OA_ptr<MemRefHandleIterator> useIterPtr = mIR->getUseMemRefs(stmt); for ( ; useIterPtr->isValid(); (*useIterPtr)++ ) { MemRefHandle use = useIterPtr->current(); if (debug) { std::cout << "\t\tuse (" << use.hval() << ") = "; mIR->dump(use,std::cout); } OA_ptr<LocIterator> locIterPtr = mAlias->getMayLocs(use); OA_ptr<LocIterator> activeIterPtr = mActive->getActiveLocsIterator(); for (; locIterPtr->isValid(); ++(*locIterPtr)) { OA_ptr<Location> loc = locIterPtr->current(); activeIterPtr->reset(); for (; activeIterPtr->isValid(); (*activeIterPtr)++ ) { if (loc->mayOverlap(*(activeIterPtr->current())) ) { mActive->insertMemRef(use); } } } } } } } // end of namespace Activity } // end of namespace OA
7,244
2,316
#include <ros/ros.h> #include <graph_core/parallel_moveit_collision_checker.h> #include <graph_replanning/trajectory.h> #include <moveit/robot_state/robot_state.h> #include <graph_replanning/replanner.h> int main(int argc, char **argv) { ros::init(argc, argv, "node_test_replanner"); ros::AsyncSpinner spinner(4); spinner.start(); ros::NodeHandle nh; // //////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string group_name = "cartesian_arm"; std::string last_link = "end_effector"; moveit::planning_interface::MoveGroupInterface move_group(group_name); robot_model_loader::RobotModelLoader robot_model_loader("robot_description"); robot_model::RobotModelPtr kinematic_model = robot_model_loader.getModel(); planning_scene::PlanningScenePtr planning_scene = std::make_shared<planning_scene::PlanningScene>(kinematic_model); const robot_state::JointModelGroup* joint_model_group = move_group.getCurrentState()->getJointModelGroup(group_name); std::vector<std::string> joint_names = joint_model_group->getActiveJointModelNames(); unsigned int dof = joint_names.size(); Eigen::VectorXd lb(dof); Eigen::VectorXd ub(dof); for (unsigned int idx = 0; idx < dof; idx++) { const robot_model::VariableBounds& bounds = kinematic_model->getVariableBounds(joint_names.at(idx)); //bounds dei joints definito in urdf e file joints limit if (bounds.position_bounded_) { lb(idx) = bounds.min_position_; ub(idx) = bounds.max_position_; } } // //////////////////////////////////////////UPDATING PLANNING SCENE//////////////////////////////////////////////////////// ros::ServiceClient ps_client=nh.serviceClient<moveit_msgs::GetPlanningScene>("/get_planning_scene"); if (!ps_client.waitForExistence(ros::Duration(10))) { ROS_ERROR("unable to connect to /get_planning_scene"); return 1; } moveit_msgs::GetPlanningScene ps_srv; if (!ps_client.call(ps_srv)) { ROS_ERROR("call to srv not ok"); return 1; } if (!planning_scene->setPlanningSceneMsg(ps_srv.response.scene)) { ROS_ERROR("unable to update planning scene"); return 0; } // //////////////////////////////////////////PATH PLAN & VISUALIZATION//////////////////////////////////////////////////////// pathplan::MetricsPtr metrics = std::make_shared<pathplan::Metrics>(); pathplan::CollisionCheckerPtr checker = std::make_shared<pathplan::ParallelMoveitCollisionChecker>(planning_scene, group_name); pathplan::DisplayPtr disp = std::make_shared<pathplan::Display>(planning_scene,group_name,last_link); disp->clearMarkers(); ros::Duration(1).sleep(); pathplan::Trajectory trajectory = pathplan::Trajectory(nh,planning_scene,group_name); std::vector<pathplan::PathPtr> path_vector; Eigen::VectorXd start_conf(3); start_conf << 0.0,0.0,0.0; Eigen::VectorXd goal_conf(3); goal_conf << 0.8,0.8,0.8; int id=100; int id_wp = 1000; for (unsigned int i =0; i<2; i++) { pathplan::SamplerPtr sampler = std::make_shared<pathplan::InformedSampler>(start_conf, goal_conf, lb, ub); pathplan::BiRRTPtr solver = std::make_shared<pathplan::BiRRT>(metrics, checker, sampler); pathplan::PathPtr solution = trajectory.computePath(start_conf, goal_conf,solver,1); path_vector.push_back(solution); std::vector<double> marker_color; if(i==0) marker_color = {0.5,0.5,0.0,1.0}; if(i==1) marker_color = {0.0f,0.0f,1.0,1.0}; disp->displayPathAndWaypoints(solution,id,id_wp,"pathplan",marker_color); id +=1; id_wp +=50; ros::Duration(0.5).sleep(); } pathplan::PathPtr current_path = path_vector.front(); std::vector<pathplan::PathPtr> other_paths = {path_vector.at(1)}; Eigen::VectorXd parent = current_path->getConnections().at(2)->getParent()->getConfiguration(); Eigen::VectorXd child = current_path->getConnections().at(2)->getChild()->getConfiguration(); Eigen::VectorXd current_configuration = parent + (child-parent)*0.5; current_path->getConnections().at(3)->setCost(std::numeric_limits<double>::infinity()); current_path->cost(); // ///////////////////////////////////////// VISUALIZATION OF CURRENT NODE /////////////////////////////////////////////////////////// std::vector<double> marker_color_sphere_actual = {1.0,0.0,1.0,1.0}; disp->displayNode(std::make_shared<pathplan::Node>(current_configuration),id,"pathplan",marker_color_sphere_actual); id++; // //////////////////////////////////////// REPLANNING & TEST //////////////////////////////////////////////////////////////// pathplan::SamplerPtr samp = std::make_shared<pathplan::InformedSampler>(start_conf, goal_conf, lb, ub); pathplan::BiRRTPtr solver = std::make_shared<pathplan::BiRRT>(metrics, checker, samp); solver->config(nh); pathplan::Replanner replanner = pathplan::Replanner(current_configuration, current_path, other_paths, solver, metrics, checker, lb, ub); double time_repl = 1.0; bool success = replanner.informedOnlineReplanning(time_repl); std::vector<double> marker_color = {1.0,1.0,0.0,1.0}; std::vector<double> marker_color_sphere_new_curr_conf = {0.0,0.0,0.0,1.0}; int id_new_curr_conf = 1678; if(success) { ROS_WARN("SUCCESS"); std::vector<double> marker_scale(3,0.01); disp->changeConnectionSize(marker_scale); disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color); } else { return 0; } int idx_replanned_path_start; pathplan::PathPtr replanned_path = replanner.getReplannedPath()->clone(); pathplan::ConnectionPtr replanned_path_conn = current_path->findConnection(replanned_path->getWaypoints().at(0),idx_replanned_path_start); pathplan::NodePtr parent_node,child_node; Eigen::VectorXd new_current_configuration; // disp->nextButton("Starting replanned path from conf1 -> press NEXT"); parent_node = replanned_path_conn->getParent(); child_node = replanned_path_conn->getChild();; new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration()); replanner.startReplannedPathFromNewCurrentConf(new_current_configuration); disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color); disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf); replanner.setReplannedPath(replanned_path->clone()); // disp->nextButton("Starting replanned path from conf2 -> press NEXT"); parent_node = current_path->getConnections().at(0)->getParent(); child_node = current_path->getConnections().at(0)->getChild(); new_current_configuration = current_path->getWaypoints().at(0)+0.3*(current_path->getWaypoints().at(1)-current_path->getWaypoints().at(0)); replanner.startReplannedPathFromNewCurrentConf(new_current_configuration); disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color); disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf); replanner.setReplannedPath(replanned_path->clone()); // disp->nextButton("Starting replanned path from conf3 -> press NEXT"); parent_node = replanned_path->getConnections().at(0)->getParent(); child_node = replanned_path->getConnections().at(0)->getChild(); new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration()); replanner.startReplannedPathFromNewCurrentConf(new_current_configuration); disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color); disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf); replanner.setReplannedPath(replanned_path->clone()); // disp->nextButton("Starting replanned path from conf4 -> press NEXT"); parent_node = replanned_path->getConnections().at(1)->getParent(); child_node = replanned_path->getConnections().at(1)->getChild(); new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration()); replanner.startReplannedPathFromNewCurrentConf(new_current_configuration); disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color); disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf); replanner.setReplannedPath(replanned_path->clone()); // disp->nextButton("Starting replanned path from conf5 -> press NEXT"); parent_node = current_path->getConnections().at(idx_replanned_path_start+1)->getParent(); child_node = current_path->getConnections().at(idx_replanned_path_start+1)->getChild(); new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration()); replanner.startReplannedPathFromNewCurrentConf(new_current_configuration); disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color); disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf); return 0; }
9,299
3,149
#include "landscapes/svo_tree.sanity.hpp" #include "landscapes/svo_tree.hpp" #include "landscapes/svo_formatters.hpp" #include "format.h" #include <iostream> #include <tuple> namespace svo{ ::std::ostream& operator<<(::std::ostream& out, const svo::svo_block_sanity_error_t& error) { if (!error.has_error) { out << "no error"; return out; } out << error.error; return out; } ::std::ostream& operator<<(::std::ostream& out, const svo::svo_slice_sanity_error_t& error) { if (!error.has_error) { out << "no error"; return out; } out << error.error; return out; } svo_slice_sanity_error_t svo_slice_sanity_minimal(const svo_slice_t* slice, svo_sanity_type_t sanity_type); svo_slice_sanity_error_t svo_slice_sanity_pos_data_to_parent(const svo_slice_t* slice); svo_slice_sanity_error_t svo_slice_sanity_channel_data_to_parent(const svo_slice_t* slice); svo_block_sanity_error_t svo_block_sanity_data(const svo_block_t* block) { assert(block); assert(block->tree); goffset_t root_shadow_cd_goffset = block->root_shadow_cd_goffset; goffset_t parent_root_cd_goffset = block->parent_root_cd_goffset; if (root_shadow_cd_goffset == 0) return svo_block_sanity_error_t("root_shadow_cd_goffset is 0", block); if (parent_root_cd_goffset == 0) return svo_block_sanity_error_t("parent_root_cd_goffset is 0", block); if (block->root_shadow_cd_goffset == invalid_goffset) return svo_block_sanity_error_t(fmt::format("root_shadow_cd_goffset is invalid") , block); if (!block->is_valid_cd_goffset(block->root_shadow_cd_goffset)) return svo_block_sanity_error_t(fmt::format("root_shadow_cd_goffset is not within the block") , block); if (!block->parent_block) { if (block->parent_root_cd_goffset != invalid_goffset) return svo_block_sanity_error_t(fmt::format("block->parent_block is blank, but parent_root_cd_goffset is pointing somewhere" ", parent_root_cd_goffset: {}" , block->parent_root_cd_goffset) , block); } if (block->parent_block) { if (!block->has_root_children_goffset()) return svo_block_sanity_error_t(fmt::format("block has parent but has no root_children_goffset ..") , block); if (block->parent_root_cd_goffset == invalid_goffset) return svo_block_sanity_error_t(fmt::format("block->parent_block is set, but parent_root_cd_goffset is invalid") , block); if (!block->parent_block->is_valid_cd_goffset(block->parent_root_cd_goffset)) return svo_block_sanity_error_t(fmt::format("parent_root_cd_goffset is not within the parent block") , block); ///gets the root shadow CD, which lies in the current block const auto* shadow_root_cd = svo_cget_cd(block->tree->address_space, block->root_shadow_cd_goffset); ///gets the root CD, which lies in the parent block const auto* parent_root_cd = svo_cget_cd(block->tree->address_space, block->parent_root_cd_goffset); ///the root CD should always have a far pointer to this block. if (!svo_get_far(parent_root_cd)) return svo_block_sanity_error_t(fmt::format("the root CD that points into this block is not using a far ptr") , block); ///the goffset to the beginning of the root children set. goffset_t shadow_root_cd_children_goffset = svo_get_child_ptr_goffset(block->tree->address_space, block->root_shadow_cd_goffset, shadow_root_cd); ///the goffset to the beginning of the root children set. goffset_t parent_root_cd_children_goffset = svo_get_child_ptr_goffset(block->tree->address_space, block->parent_root_cd_goffset, parent_root_cd); assert(block->is_valid_cd_goffset(block->root_shadow_cd_goffset)); assert(block->parent_block->is_valid_cd_goffset(block->parent_root_cd_goffset)); assert(shadow_root_cd_children_goffset == block->root_children_goffset()); if (!block->is_valid_cd_goffset(parent_root_cd_children_goffset)) return svo_block_sanity_error_t(fmt::format("the root CD that points into this block is pointing somewhere not inside this block" ", parent_root_cd_children_goffset: {}" , parent_root_cd_children_goffset) , block); if (!block->is_valid_cd_goffset(shadow_root_cd_children_goffset)) return svo_block_sanity_error_t(fmt::format("the shadow CD of this block is pointing somewhere not inside this block" ", shadow_root_cd_children_goffset: {}" , shadow_root_cd_children_goffset) , block); if (shadow_root_cd_children_goffset != parent_root_cd_children_goffset) return svo_block_sanity_error_t(fmt::format("the root CD that points into this block is not pointing to the same location as the shadow root CD" ", shadow_root_cd_children_goffset: {}, parent_root_cd_children_goffset: {}" , shadow_root_cd_children_goffset, parent_root_cd_children_goffset) , block); } if (block->root_valid_bit) { } else { //if (root_shadow_cd_goffset != invalid_goffset) // return svo_block_sanity_error_t("root is not root_valid_bit, yet has a root shadow CD", block); } if (block->root_leaf_bit) { if (!(block->root_valid_bit)) return svo_block_sanity_error_t("root_valid_bit is not set, yet root_leaf_bit is set ...", block); } else { if (root_shadow_cd_goffset == invalid_goffset) return svo_block_sanity_error_t("root is not a leaf, and has no root shadow CD", block); } std::vector< svo_block_sanity_error_t > issues; std::size_t voxel_count = 0; std::size_t leaf_count = 0; std::size_t cd_count = 0; std::set< goffset_t > found_cd_goffsets; auto visitor = [&voxel_count, &leaf_count, &cd_count, &block, &issues, &found_cd_goffsets](goffset_t pcd_goffset, goffset_t cd_goffset, ccurve_t voxel_ccurve , std::tuple<std::size_t, vcurve_t> metadata) { ++voxel_count; std::size_t level = std::get<0>(metadata); vcurve_t parent_vcurve = std::get<1>(metadata); vcurve_t voxel_vcurve = parent_vcurve*8 + voxel_ccurve; vside_t level_side = 1 << level; vcurvesize_t level_size = vcurvesize(level_side); bool is_cd = (cd_goffset != invalid_goffset); bool is_invalid_cd = is_cd && (!block->is_valid_cd_goffset(cd_goffset)); const child_descriptor_t* cd = 0; if (is_cd && !is_invalid_cd) cd = svo_cget_cd(block->tree->address_space, cd_goffset); std::size_t cd_nonleaf_count = cd ? svo_get_cd_nonleaf_count(cd) : 0; std::size_t cd_valid_count = cd ? svo_get_cd_valid_count(cd) : 0; bool is_leaf = !is_cd || (!is_invalid_cd && (cd_valid_count == 0)); bool is_bottom_leaf = !block->trunk && (level == block->height - 1); /* std::cout << "is_bottom_leaf: " << (is_bottom_leaf ? "true" : "false") << ", is_leaf: " << (is_leaf ? "true" : "false") << ", is_cd: " << (is_cd ? "true" : "false") << ", cd_nonleaf_count: " << cd_nonleaf_count << std::endl; if (cd) std::cout << ", cd: " << *cd << std::endl; */ if (is_leaf) ++leaf_count; if (is_cd) ++cd_count; if(cd_goffset != invalid_goffset) { if (cd_goffset == svo_get_ph_goffset(cd_goffset)) issues.push_back(svo_block_sanity_error_t(fmt::format("CD is located on a page header!" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}" , pcd_goffset, cd_goffset, voxel_ccurve, level, block->height) , block)); if (found_cd_goffsets.count(cd_goffset) > 0) issues.push_back(svo_block_sanity_error_t(fmt::format("Duplicate CD goffset" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}" , pcd_goffset, cd_goffset, voxel_ccurve, level, block->height) , block)); if (pcd_goffset != invalid_goffset && found_cd_goffsets.count(pcd_goffset) == 0) issues.push_back(svo_block_sanity_error_t(fmt::format("Parent CD is not in found_cd_goffsets" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}" , pcd_goffset, cd_goffset, voxel_ccurve, level, block->height) , block)); found_cd_goffsets.insert(cd_goffset); } if (!block->trunk && !(level < block->height)) { issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel level out of block bounds" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}" , pcd_goffset, cd_goffset, voxel_ccurve, level, block->height) , block)); } if (!(voxel_vcurve < level_size)) { issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel vcurve out of level bounds" ", pcd_goffset: {}, cd_goffset: {}, block->height: {}" ", level: {}, level_side: {}, level_size:{}, voxel_ccurve: {}" , pcd_goffset, cd_goffset, block->height , level, level_side, level_size, voxel_vcurve) , block)); } if (is_invalid_cd) { issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel is a CD but is not inside block" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}" , pcd_goffset, cd_goffset, voxel_ccurve, level, block->height) , block)); } if (is_bottom_leaf && !is_leaf) { issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel is at bottom leaf level, but not a leaf" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}" , pcd_goffset, cd_goffset, voxel_ccurve, level, block->height) , block)); } /* if (is_bottom_leaf && is_cd) { issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel is at bottom leaf level, but has a CD" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}" , pcd_goffset, cd_goffset, voxel_ccurve, level, block->height) , block)); }*/ if (pcd_goffset == 0) issues.push_back(svo_block_sanity_error_t(fmt::format("pcd_goffset somehow is equal to zero, zero is not an defined;" " it isn't even an invalid offset, use @c invalid_goffset instead") , block)); if (cd_goffset == 0) issues.push_back(svo_block_sanity_error_t(fmt::format("cd_goffset somehow is equal to zero, zero is not an defined;" " it isn't even an invalid offset, use @c invalid_goffset instead") , block)); if (!is_leaf && cd_goffset == pcd_goffset) issues.push_back(svo_block_sanity_error_t(fmt::format("Child ptr is zero, yet this is a non-leaf voxel .." ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" , pcd_goffset, cd_goffset, voxel_ccurve), block)); if (cd_goffset != invalid_goffset && cd_goffset != 0 && !block->is_valid_cd_goffset(cd_goffset)) issues.push_back(svo_block_sanity_error_t(fmt::format("cd_goffset is an invalid CD, not inside block bounds .." ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" , pcd_goffset, cd_goffset, voxel_ccurve), block)); if (pcd_goffset != invalid_goffset && pcd_goffset != 0 && !block->is_valid_cd_goffset(pcd_goffset)) issues.push_back(svo_block_sanity_error_t(fmt::format("pcd_goffset is an invalid CD, not inside block bounds .." ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" , pcd_goffset, cd_goffset, voxel_ccurve), block)); if (pcd_goffset != invalid_goffset && pcd_goffset != 0 && block->is_valid_cd_goffset(pcd_goffset)) { const auto* pcd = svo_cget_cd(block->tree->address_space, pcd_goffset); bool parent_valid_bit = svo_get_valid_bit(pcd, voxel_ccurve); bool parent_leaf_bit = svo_get_leaf_bit(pcd, voxel_ccurve); if (!parent_valid_bit) issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel exists, but parent says this is an invalid voxel" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" , pcd_goffset, cd_goffset, voxel_ccurve), block)); if (parent_leaf_bit && cd_goffset != invalid_goffset && cd_goffset != 0) issues.push_back(svo_block_sanity_error_t(fmt::format("Parent says voxel is a leaf, but yet we have a CD for it" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" , pcd_goffset, cd_goffset, voxel_ccurve), block)); } if (cd_goffset != pcd_goffset && cd_goffset != invalid_goffset && cd_goffset != 0) { const auto* cd = svo_cget_cd(block->tree->address_space, cd_goffset); child_mask_t valid_mask = svo_get_valid_mask(cd); child_mask_t leaf_mask = svo_get_leaf_mask(cd); child_mask_t error_bits = leaf_mask & (~valid_mask); if (error_bits) issues.push_back(svo_block_sanity_error_t(fmt::format("CD has children that are invalid, but are marked as leafs" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" ", valid_mask: {}, leaf_mask: {}, error_bits: {}" , pcd_goffset, cd_goffset, voxel_ccurve , std::bitset<8>(valid_mask) , std::bitset<8>(leaf_mask) , std::bitset<8>(error_bits)), block)); bool has_non_leaf_child = cd_nonleaf_count > 0; goffset_t child0_base_goffset = svo_get_child_ptr_goffset(block->tree->address_space, cd_goffset, cd); if (has_non_leaf_child && child0_base_goffset == invalid_goffset) issues.push_back(svo_block_sanity_error_t(fmt::format("CD's child ptr is invalid" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" ", valid_mask: {}, leaf_mask: {}, child0_base_goffset: {}" , pcd_goffset, cd_goffset, voxel_ccurve , std::bitset<8>(valid_mask) , std::bitset<8>(leaf_mask) , child0_base_goffset), block)); if (has_non_leaf_child && !block->is_valid_cd_goffset(child0_base_goffset)) { if (!block->trunk) issues.push_back(svo_block_sanity_error_t(fmt::format("CD's child ptr points outside of the block's bounds, and this is not a trunk" ", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}" ", valid_mask: {}, leaf_mask: {}, child0_base_goffset: {}" , pcd_goffset, cd_goffset, voxel_ccurve , std::bitset<8>(valid_mask) , std::bitset<8>(leaf_mask) , child0_base_goffset), block)); } } return std::make_tuple(level+1, voxel_vcurve); }; z_preorder_traverse_block_cds( block->tree->address_space , block , std::make_tuple(std::size_t(0), vcurve_t(0)) ///(level,vcurve) as metadata , visitor); if (issues.size() > 0) return issues[0]; if (cd_count != block->cd_count) return svo_block_sanity_error_t(fmt::format("CD counts do not match. block->cd_count: {}, actual CD count: {}" , block->cd_count, cd_count), block); if (leaf_count != block->leaf_count) return svo_block_sanity_error_t(fmt::format("voxel counts do not match. block->leaf_count: {}, actual leaf_count: {}" , block->leaf_count, leaf_count), block); return svo_block_sanity_error_t(); } svo_block_sanity_error_t svo_block_sanity_check(const svo_block_t* block, int recurse) { auto check_is_valid_goffset = [&block](const std::string& name, goffset_t goffset) { if (goffset == 0 || goffset == invalid_goffset) return svo_block_sanity_error_t(fmt::format("{} is is not a valid goffset: {}.", name, goffset), block); return svo_block_sanity_error_t(); }; auto check_is_range = [&block](const std::string& range_name, goffset_t begin, goffset_t end) { if (begin > end) return svo_block_sanity_error_t(fmt::format("{} is is not a valid range: [{}, {}).", range_name, begin, end), block); return svo_block_sanity_error_t(); }; auto check_in_range = [&block]( const std::string& name, goffset_t goffset, std::size_t size , const std::string& range_name, goffset_t begin, goffset_t end) { if (goffset < begin || goffset + size > end ) return svo_block_sanity_error_t(fmt::format("{} is out of bounds of {}.", name, range_name), block); return svo_block_sanity_error_t(); }; if(!block) return svo_block_sanity_error_t("block is invalid pointer", block); if(!(block->child_blocks)) return svo_block_sanity_error_t("block->child_blocks is invalid pointer", block); if(!(block->tree)) return svo_block_sanity_error_t("block->tree is invalid pointer", block); if (block->trunk) { if(block->height != 0) return svo_block_sanity_error_t("block is trunk, yet has a height", block); if(block->side != 0) return svo_block_sanity_error_t("block is trunk, yet has a side", block); } if (block->root_shadow_cd_goffset == 0) return svo_block_sanity_error_t(fmt::format("root_shadow_cd_goffset is 0, an undefined value; use @c invalid_goffset somewhere instead" ), block); if (block->root_valid_bit) { if (!block->trunk && block->height < 1) return svo_block_sanity_error_t(fmt::format("root is valid but block->height is 0" ", height: {}, side: {}, root_valid_bit: {}, root_leaf_bit: {}" , block->height, block->side, block->root_valid_bit, block->root_leaf_bit), block); vside_t expected_side = (1UL << (block->height - 1)); if (!block->trunk && block->side != expected_side) return svo_block_sanity_error_t(fmt::format("side does not match expected side based on height" ", height: {}, side: {}, expected side: {}, root_valid_bit: {}, root_leaf_bit: {}" , block->height, block->side, expected_side, block->root_valid_bit, block->root_leaf_bit) , block); if (!(block->root_leaf_bit) && block->root_shadow_cd_goffset == invalid_goffset) return svo_block_sanity_error_t(fmt::format("nonleaf root, and no shadow root cd specified"), block); } if (block->root_leaf_bit) { if (!block->trunk && !(block->root_valid_bit)) return svo_block_sanity_error_t(fmt::format("root is a leaf but is marked as invalid" ", height: {}, side: {}, root_valid_bit: {}, root_leaf_bit: {}" , block->height, block->side, block->root_valid_bit, block->root_leaf_bit), block); if (!block->trunk && block->height != 1) return svo_block_sanity_error_t(fmt::format("root is a leaf but block->height is not 1" ", height: {}, side: {}, root_valid_bit: {}, root_leaf_bit: {}" , block->height, block->side, block->root_valid_bit, block->root_leaf_bit), block); } if (block->block_start % SVO_PAGE_SIZE != 0 || block->block_end % SVO_PAGE_SIZE != 0) return svo_block_sanity_error_t(fmt::format("block is not aligned to page!" ", block->block_start: {}, misalignment: {}" ", block->block_end: {}, misalignment: {}" ", SVO_PAGE_SIZE: {}" , block->block_start, block->block_start % SVO_PAGE_SIZE , block->block_end, block->block_end % SVO_PAGE_SIZE , SVO_PAGE_SIZE) ,block); if (!!(block->slice) && block->child_blocks->size() > 0) return svo_block_sanity_error_t(fmt::format("block has a child slice, but also has child blocks ...") , block); if(block->root_shadow_cd_goffset == 0) return svo_block_sanity_error_t("block->root_shadow_cd_goffset is not initialized; this should always be pointing to a dummy root CD.", block); ///range sanities { if (auto error = check_is_valid_goffset("block_start", block->block_start)) return error; if (auto error = check_is_valid_goffset("block_end", block->block_end)) return error; if (auto error = check_is_valid_goffset("cd_start", block->cd_start)) return error; if (auto error = check_is_valid_goffset("cd_end", block->cd_end)) return error; if (auto error = check_is_valid_goffset("cdspace_end", block->cdspace_end)) return error; if (auto error = check_is_range("[block_start,block_end)", block->block_start, block->block_end)) return error; if (auto error = check_is_range("[cd_start,cd_end)", block->cd_start, block->cd_end)) return error; if (auto error = check_is_range("[cd_start,cdspace_end)", block->cd_start, block->cdspace_end)) return error; if (auto error = check_in_range("cd_start", block->cd_start, 0 , "the block", block->block_start, block->block_end)) return error; if (auto error = check_in_range("cd_end", block->cd_end, 0 , "the block", block->block_start, block->block_end)) return error; if (auto error = check_in_range("cdspace_end", block->cdspace_end, 0 , "the block", block->block_start, block->block_end)) return error; if (auto error = check_in_range("cd_end", block->cd_end, 0 , "cd space", block->cd_start, block->cdspace_end)) return error; } if (block->slice) { vside_t expected_slice_side = block->side == 0 ? 1 : block->side * 2; if (expected_slice_side != block->slice->side) return svo_block_sanity_error_t(fmt::format("slice side does not match the next expected level's side ..." " block->side: {}, slice->side: {}, expected_slice_side: {}" , block->side, block->slice->side, expected_slice_side) , block); } auto calculate_cd_level = [](const svo_block_t* block, goffset_t needle) { assert(block->is_valid_cd_goffset(needle)); std::size_t needle_level = std::size_t(-1); auto visitor = [&needle_level, needle]( goffset_t pcd_goffset, goffset_t cd_goffset, ccurve_t voxel_ccurve , std::tuple<std::size_t, vcurve_t> metadata) { std::size_t level = std::get<0>(metadata); vcurve_t parent_vcurve = std::get<1>(metadata); vcurve_t vcurve = parent_vcurve*8 + voxel_ccurve; if (cd_goffset == needle) needle_level = level; return std::make_tuple(level+1, vcurve); }; z_preorder_traverse_block_cds(block->tree->address_space , block , std::make_tuple(std::size_t(0), vcurve_t(0)) ///(level) as metadata , visitor); return needle_level; }; if (block->parent_block) { auto& parent_block = *block->parent_block; if (!parent_block.child_blocks) return svo_block_sanity_error_t("block->parent_block->child_blocks is invalid pointer", block, block->parent_block); if (std::find(parent_block.child_blocks->begin(), parent_block.child_blocks->end(), block) == parent_block.child_blocks->end()) return svo_block_sanity_error_t("block->parent_block->child_blocks does not contain block ...", block, block->parent_block); if (!(block->parent_block->is_valid_cd_goffset(block->parent_root_cd_goffset))) return svo_block_sanity_error_t("block->parent_root_cd_goffset is pointing to something, but that something is not within the parent block ..." , block); std::size_t parent_root_cd_cd_level = calculate_cd_level(block->parent_block, block->parent_root_cd_goffset); std::size_t expected_root_level = block->parent_block->root_level + parent_root_cd_cd_level; if (block->root_level != expected_root_level) return svo_block_sanity_error_t(fmt::format("block->root_level is not the expected root level" " root_level: {}, parent_root_cd_cd_level: {}, expected_root_level: {}" , block->root_level, parent_root_cd_cd_level, expected_root_level) , block); } else { if (block->parent_root_cd_goffset != invalid_goffset) return svo_block_sanity_error_t("block->parent_root_cd_goffset is pointing to something, but there is no parent block ...", block); } for (const svo_block_t* child_block : *block->child_blocks) { if (child_block->parent_block != block) return svo_block_sanity_error_t("child block does not point back to the parent ...", block, child_block); } if (auto error = svo_block_sanity_data(block)) { return error; } if (recurse) { for (const svo_block_t* child_block : *block->child_blocks) { auto result = svo_block_sanity_check(child_block, recurse-1); if (result) return result; } } return svo_block_sanity_error_t(); } svo_slice_sanity_error_t svo_slice_sanity_channel_data_to_parent(const svo_slice_t* slice) { if (auto error = svo_slice_sanity_minimal(slice, svo_sanity_type_t::minimal)) { return error; } assert(slice); assert(slice->pos_data); assert(slice->buffers); const auto& pos_data = *(slice->pos_data); const auto& buffers = *(slice->buffers); for (const auto& buffer : buffers.buffers()) { if (buffer.entries() != pos_data.size()) return svo_slice_sanity_error_t(fmt::format("different number of channel elements than position elements" " buffer.declaration: {}, buffer.entries(): {}, pos_data.size(): {}" , buffer.declaration(), buffer.entries(), pos_data.size()) , slice); } if (slice->parent_slice) { if (slice->parent_slice->buffers == nullptr) return svo_slice_sanity_error_t(fmt::format("slice->parent_slice->buffers is invalid pointer") , slice); const auto& parent_buffers = *slice->parent_slice->buffers; if (buffers.schema() != parent_buffers.schema()) return svo_slice_sanity_error_t(fmt::format("parent_slice->buffers does not match buffers" ", buffers: {}, parent_buffers: {}" , buffers.schema(), parent_buffers.schema()) , slice); } return svo_slice_sanity_error_t(); } svo_slice_sanity_error_t svo_slice_sanity_pos_data_to_parent(const svo_slice_t* slice) { if (auto error = svo_slice_sanity_minimal(slice, svo_sanity_type_t::minimal)) { return error; } assert(slice->pos_data); const auto& pos_data = *(slice->pos_data); ///check position data sanity. { vcurvesize_t max_vcurve = vcurvesize(slice->side); for (const vcurve_t voxel_vcurve : pos_data) { if (!(voxel_vcurve < max_vcurve)) return svo_slice_sanity_error_t(fmt::format("data contains a voxel that is outside of the bounds of the slice ..." " voxel_vcurve: {}, max_vcurve: {}" , voxel_vcurve, max_vcurve) , slice); } } if (!(slice->parent_slice)) return svo_slice_sanity_error_t(); assert(slice->parent_slice->pos_data); const auto& parent_pos_data = *(slice->parent_slice->pos_data); ///we will iterate through the parent data in tandem with our data. vcurve_t parent_data_index = 0; for (const vcurve_t voxel_vcurve : pos_data) { vcurve_t expected_parent_voxel_vcurve = (voxel_vcurve / 8) + slice->parent_vcurve_begin; ///move the cursor in the parent data until we are up to our expected @c parent_voxel_vcurve while (parent_data_index < parent_pos_data.size() && parent_pos_data[parent_data_index] < expected_parent_voxel_vcurve) { ++parent_data_index; } if (!(parent_data_index < parent_pos_data.size()) || expected_parent_voxel_vcurve != parent_pos_data[parent_data_index]) { return svo_slice_sanity_error_t(fmt::format("data contains a voxel that is not contained in the parent slice ..." " voxel_vcurve: {}, expected_parent_voxel_vcurve: {}" , voxel_vcurve, expected_parent_voxel_vcurve) , slice); } assert(parent_data_index < parent_pos_data.size()); if (expected_parent_voxel_vcurve == parent_pos_data[parent_data_index]) ///we found the parent voxel; it exists. continue; } return svo_slice_sanity_error_t(); } svo_slice_sanity_error_t svo_slice_sanity_minimal(const svo_slice_t* slice, svo_sanity_type_t sanity_type) { if(!slice) return svo_slice_sanity_error_t("slice is invalid pointer", slice); ///parent <=> slice sanity if (slice->parent_slice) { auto parent_slice = slice->parent_slice; if (sanity_type & svo_sanity_type_t::levels) if (parent_slice->level + 1 != slice->level) return svo_slice_sanity_error_t( fmt::format("parent->level is not one less than slice->level" ", parent->level: {}, slice->level: {}" ", parent: {}, slice: {}" , parent_slice->level, slice->level , (void*)parent_slice, (void*)slice), slice); if (!parent_slice->children) return svo_slice_sanity_error_t("parent->children is invalid pointer", slice); const auto& siblings = *parent_slice->children; auto it = std::find(siblings.begin(), siblings.end(), slice); if (it == siblings.end()) return svo_slice_sanity_error_t("slice not in parent's children", slice); } if (slice->parent_slice == nullptr) { if (slice->parent_vcurve_begin != 0) return svo_slice_sanity_error_t(fmt::format("slice has no parent, and yet has a parent_vcurve_begin: {}" , slice->parent_vcurve_begin), slice); } if (!slice->pos_data) return svo_slice_sanity_error_t("slice->data is an invalid pointer", slice); if (!slice->buffers) return svo_slice_sanity_error_t("slice->buffers is an invalid pointer", slice); const auto& pos_data = *slice->pos_data; ///parameter consistency { if (!slice->parent_slice && slice->parent_vcurve_begin != 0) return svo_slice_sanity_error_t(fmt::format("no parent slice specified, but has a non-zero parent_vcurve_begin ..." " parent_vcurve_begin: {}" , slice->parent_vcurve_begin) , slice); if (slice->side == 0) return svo_slice_sanity_error_t(fmt::format("side is zero ...") , slice); assert(slice->side != 0); if (slice->side == 1 && slice->parent_slice != nullptr) return svo_slice_sanity_error_t(fmt::format("slice has a side of 1, and yet has a parent slice") , slice->parent_slice, slice); if (slice->side > SVO_VOLUME_SIDE_LIMIT) return svo_slice_sanity_error_t(fmt::format("slice has a side of greater than SVO_MAX_VOLUME_SIDE" "side: {}, SVO_MAX_VOLUME_SIDE: {}" , slice->side, SVO_VOLUME_SIDE_LIMIT) , slice); if (slice->side > 1) { auto size_in_parent = vcurvesize(slice->side / 2); assert(size_in_parent != 0); if (slice->parent_vcurve_begin % size_in_parent != 0) return svo_slice_sanity_error_t(fmt::format("parent_vcurve_begin is not aligned to the beginning of a node of this size ..." " parent_vcurve_begin: {}, side: {}, size: {}, size in parent: {}" , slice->parent_vcurve_begin, slice->side, vcurvesize(slice->side), vcurvesize(slice->side / 2)) , slice); } } ///data/bounds check { vcurvesize_t size = vcurvesize(slice->side); vcurvesize_t last_vcurve = size; for (const auto& voxel_vcurve : pos_data) { if (!(voxel_vcurve < size)) return svo_slice_sanity_error_t(fmt::format("data contains voxel that is out of bounds of the slice ..." " side: {}, size: {}, vcurve: {}" , slice->side, size, voxel_vcurve) , slice); if (last_vcurve == size) { ///pass } else { if (voxel_vcurve == last_vcurve) return svo_slice_sanity_error_t(fmt::format("data contains a duplicate voxel ..." " voxel_vcurve: {}" , voxel_vcurve) , slice); if (!(voxel_vcurve > last_vcurve)) return svo_slice_sanity_error_t(fmt::format("data contains voxels that are out of order ..." " side: {}, size: {}, vcurve: {}, last vcurve: {}" , slice->side, size, voxel_vcurve, last_vcurve) , slice); } last_vcurve = voxel_vcurve; } } ///slice => children sanity { if (!slice->children) return svo_slice_sanity_error_t("slice->children is invalid pointer", slice); const auto& children = *slice->children; ///child space bounds check { vcurvesize_t size = vcurvesize(slice->side); vcurve_t last_parent_vcurve_end = 0; for (std::size_t child_index = 0; child_index < slice->children->size(); ++child_index) { const svo_slice_t* child = (*slice->children)[child_index]; vcurvesize_t child_size = vcurvesize(child->side); vcurvesize_t child_size_in_parent = vcurvesize(child->side / 2); vcurvesize_t child_parent_vcurve_end = child->parent_vcurve_begin + child_size_in_parent; //std::cout << "child_index: " << child_index << std::endl; //std::cout << "child->parent_vcurve_begin: " << child->parent_vcurve_begin << std::endl; //std::cout << "child_parent_vcurve_end: " << child_parent_vcurve_end << std::endl; if (!child->parent_slice) return svo_slice_sanity_error_t("child->parent_slice is invalid pointer", slice, child); if (child->parent_slice != slice) return svo_slice_sanity_error_t("child->parent_slice is not pointing the slice", slice, child, child->parent_slice); if (child->side > slice->side * 2) return svo_slice_sanity_error_t(fmt::format("child takes up more space than the parent ..." " side: {}, size: {}, child->side: {}, child size (double res): {}" ", child size (in parent space): {}" , slice->side, size, child->side, child_size, child_size_in_parent) , slice, child); if (child->side % 2 != 0) return svo_slice_sanity_error_t(fmt::format("child cube side is not divisible by 2; yet it takes up (side/2) space in the parent ..." " side: {}, size: {}, child->side: {}, child size: {}" ", child size (in parent space): {}" , slice->side, size, child->side, child_size, child_size_in_parent) , slice, child); if (child->parent_vcurve_begin < last_parent_vcurve_end) return svo_slice_sanity_error_t(fmt::format("child overlaps previous child's bounds ..." " child->parent_vcurve_begin: {}, child_parent_vcurve_end: {}" ", last_parent_vcurve_end: {}, size: {}" ", child size (double res): {}, child size (parent res): {}, child_index: {}" , child->parent_vcurve_begin, child_parent_vcurve_end , last_parent_vcurve_end, size , child_size, child_size_in_parent, child_index) , slice, child); if (!(child_parent_vcurve_end <= size)) return svo_slice_sanity_error_t(fmt::format("child overflows the bounds of the parent ..." " slice size: {}, child_parent_vcurve_end: {}" , size, child_parent_vcurve_end) , slice, child); last_parent_vcurve_end = child_parent_vcurve_end; } } } return svo_slice_sanity_error_t(); } #if 0 svo_slice_sanity_error_t svo_slice_sanity_check_parent_error(const svo_slice_t* slice, int recurse) { if (!slice) return svo_slice_sanity_error_t("slice is invalid pointer", slice); if (!slice->parent_slice) return svo_slice_sanity_error_t(); return svo_slice_sanity_check_error(slice->parent_slice, recurse); } svo_slice_sanity_error_t svo_slice_sanity_check_children_error(const svo_slice_t* slice, int recurse) { if (!slice) return svo_slice_sanity_error_t("slice is invalid pointer", slice); if (!slice->children) return svo_slice_sanity_error_t(); for (const svo_slice_t* child : *slice->children) { auto error = svo_slice_sanity_check_error(child, recurse); if (error) return error; } return svo_slice_sanity_error_t(); } svo_slice_sanity_error_t svo_slice_sanity_all(const svo_slice_t* slice) { if (auto error = svo_slice_sanity_minimal(slice)) return error; if (auto error = svo_slice_sanity_check_parent_error(slice)) return error; if (auto error = svo_slice_sanity_check_children_error(slice)) return error; if (auto error = svo_slice_sanity_pos_data(slice)) return error; if (auto error = svo_slice_sanity_channel_data(slice, 1)) return error; return svo_slice_sanity_error_t(); } #endif svo_slice_sanity_error_t svo_slice_sanity( const svo_slice_t* slice , svo_sanity_type_t sanity_type , int recurse , bool parent_recurse) { if (sanity_type) if (auto error = svo_slice_sanity_minimal(slice, sanity_type)) return error; const auto& children = *slice->children; if (sanity_type & svo_sanity_type_t::pos_data) for (const auto* child_slice : children) if (auto error = svo_slice_sanity_pos_data_to_parent(child_slice)) return error; if (sanity_type & svo_sanity_type_t::channel_data) for (const auto* child_slice : children) if (auto error = svo_slice_sanity_channel_data_to_parent(child_slice)) return error; if (sanity_type & svo_sanity_type_t::parent && slice->parent_slice && parent_recurse) if (auto error = svo_slice_sanity(slice->parent_slice, sanity_type, 0/*recurse*/, false/*parent_recurse*/)) return error; if (sanity_type & svo_sanity_type_t::children && recurse > 0) { for (const auto* child_slice : children) { if (auto error = svo_slice_sanity(child_slice, sanity_type, recurse - 1)) return error; } } return svo_slice_sanity_error_t(); } } // namespace svo
47,872
14,020
/* * Copyright (C) 2012 The Android Open Source Project * * 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 "barrier.h" #include <string> #include "atomic.h" #include "common_runtime_test.h" #include "mirror/object_array-inl.h" #include "thread_pool.h" #include "thread-inl.h" namespace art { class CheckWaitTask : public Task { public: CheckWaitTask(Barrier* barrier, AtomicInteger* count1, AtomicInteger* count2) : barrier_(barrier), count1_(count1), count2_(count2) {} void Run(Thread* self) { LOG(INFO) << "Before barrier" << *self; ++*count1_; barrier_->Wait(self); ++*count2_; LOG(INFO) << "After barrier" << *self; } virtual void Finalize() { delete this; } private: Barrier* const barrier_; AtomicInteger* const count1_; AtomicInteger* const count2_; }; class BarrierTest : public CommonRuntimeTest { public: static int32_t num_threads; }; int32_t BarrierTest::num_threads = 4; // Check that barrier wait and barrier increment work. TEST_F(BarrierTest, CheckWait) { Thread* self = Thread::Current(); ThreadPool thread_pool("Barrier test thread pool", num_threads); Barrier barrier(num_threads + 1); // One extra Wait() in main thread. Barrier timeout_barrier(0); // Only used for sleeping on timeout. AtomicInteger count1(0); AtomicInteger count2(0); for (int32_t i = 0; i < num_threads; ++i) { thread_pool.AddTask(self, new CheckWaitTask(&barrier, &count1, &count2)); } thread_pool.StartWorkers(self); while (count1.LoadRelaxed() != num_threads) { timeout_barrier.Increment(self, 1, 100); // sleep 100 msecs } // Count 2 should still be zero since no thread should have gone past the barrier. EXPECT_EQ(0, count2.LoadRelaxed()); // Perform one additional Wait(), allowing pool threads to proceed. barrier.Wait(self); // Wait for all the threads to finish. thread_pool.Wait(self, true, false); // Both counts should be equal to num_threads now. EXPECT_EQ(count1.LoadRelaxed(), num_threads); EXPECT_EQ(count2.LoadRelaxed(), num_threads); timeout_barrier.Init(self, 0); // Reset to zero for destruction. } class CheckPassTask : public Task { public: CheckPassTask(Barrier* barrier, AtomicInteger* count, size_t subtasks) : barrier_(barrier), count_(count), subtasks_(subtasks) {} void Run(Thread* self) { for (size_t i = 0; i < subtasks_; ++i) { ++*count_; // Pass through to next subtask. barrier_->Pass(self); } } void Finalize() { delete this; } private: Barrier* const barrier_; AtomicInteger* const count_; const size_t subtasks_; }; // Check that barrier pass through works. TEST_F(BarrierTest, CheckPass) { Thread* self = Thread::Current(); ThreadPool thread_pool("Barrier test thread pool", num_threads); Barrier barrier(0); AtomicInteger count(0); const int32_t num_tasks = num_threads * 4; const int32_t num_sub_tasks = 128; for (int32_t i = 0; i < num_tasks; ++i) { thread_pool.AddTask(self, new CheckPassTask(&barrier, &count, num_sub_tasks)); } thread_pool.StartWorkers(self); const int32_t expected_total_tasks = num_sub_tasks * num_tasks; // Wait for all the tasks to complete using the barrier. barrier.Increment(self, expected_total_tasks); // The total number of completed tasks should be equal to expected_total_tasks. EXPECT_EQ(count.LoadRelaxed(), expected_total_tasks); } } // namespace art
3,979
1,345
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/hhbbc/type-system.h" #include <gtest/gtest.h> #include <boost/range/join.hpp> #include <algorithm> #include <limits> #include <memory> #include <utility> #include <vector> #include "folly/Lazy.h" #include "hphp/runtime/base/complex-types.h" #include "hphp/runtime/base/array-init.h" #include "hphp/hhbbc/hhbbc.h" #include "hphp/hhbbc/misc.h" #include "hphp/hhbbc/representation.h" #include "hphp/hhbbc/parse.h" #include "hphp/hhbbc/index.h" #include "hphp/runtime/vm/as.h" #include "hphp/runtime/vm/unit-emitter.h" namespace HPHP { namespace HHBBC { namespace { ////////////////////////////////////////////////////////////////////// const StaticString s_test("test"); const StaticString s_TestClass("TestClass"); const StaticString s_Base("Base"); const StaticString s_A("A"); const StaticString s_AA("AA"); const StaticString s_AB("AB"); const StaticString s_B("B"); const StaticString s_BA("BA"); const StaticString s_BB("BB"); const StaticString s_BAA("BAA"); const StaticString s_IBase("IBase"); const StaticString s_IA("IA"); const StaticString s_IAA("IAA"); const StaticString s_IB("IB"); const StaticString s_NonUnique("NonUnique"); const StaticString s_NonUniqueA("NonUniqueA"); const StaticString s_WaitHandle("HH\\WaitHandle"); // A test program so we can actually test things involving object or // class types. std::unique_ptr<php::Unit> make_test_unit() { assert(SystemLib::s_inited); std::string const hhas = R"( .main { Int 1 RetC } # Technically this should be provided by systemlib, but it's the # only one we have to make sure the type system can see for unit # test purposes, so we can just define it here. We don't need to # give it any of its functions currently. .class [abstract unique builtin] HH\WaitHandle { } .class [interface unique] IBase { } .class [interface unique] IA implements (IBase) { } .class [interface unique] IB implements (IBase) { } .class [interface unique] IAA implements (IA) { } .class [unique] Base { .default_ctor; } .class [unique] A extends Base implements (IA) { .default_ctor; } .class [no_override unique] AA extends A implements (IAA) { .default_ctor; } .class [no_override unique] AB extends A { .default_ctor; } .class [unique] B extends Base { .default_ctor; } .class [unique] BA extends B { .default_ctor; } .class [no_override unique] BB extends B { .default_ctor; } .class [unique] BAA extends BA { .default_ctor; } # Make sure BAA doesn't get AttrNoOverride: .class [unique] BAADeriver extends BAA { .default_ctor; } .class [unique] TestClass { .default_ctor; } # Make sure TestClass doesn't get AttrNoOverride: .class [unique] TestClassDeriver extends TestClass { .default_ctor; } .class NonUnique { .default_ctor; } .class NonUnique { .default_ctor; } .class NonUniqueA extends NonUnique { .default_ctor; } .class NonUniqueA extends NonUnique { .default_ctor; } .function test() { Int 1 RetC } )"; std::unique_ptr<UnitEmitter> ue(assemble_string( hhas.c_str(), hhas.size(), "ignore.php", MD5("12345432123454321234543212345432") )); return parse_unit(*ue); } std::unique_ptr<php::Program> make_program() { auto program = folly::make_unique<php::Program>(); program->units.push_back(make_test_unit()); return program; } ////////////////////////////////////////////////////////////////////// auto const test_empty_array = folly::lazy([] { return staticEmptyArray(); }); auto const test_array_map_value = folly::lazy([] { auto ar = make_map_array( s_A.get(), s_B.get(), s_test.get(), 12 ); return ArrayData::GetScalarArray(ar.get()); }); auto const test_array_packed_value = folly::lazy([] { auto ar = make_packed_array( 42, 23, 12 ); return ArrayData::GetScalarArray(ar.get()); }); auto const test_array_packed_value2 = folly::lazy([] { auto ar = make_packed_array( 42, 23.0, 12 ); return ArrayData::GetScalarArray(ar.get()); }); auto const test_array_packed_value3 = folly::lazy([] { auto ar = make_packed_array( 1, 2, 3, 4, 5 ); return ArrayData::GetScalarArray(ar.get()); }); auto const with_data = folly::lazy([] { return std::vector<Type> { ival(2), dval(2.0), sval(s_test.get()), aval(test_array_map_value()), aval(test_array_packed_value()) }; }); // In the sense of "non-union type", not the sense of TPrim. auto const primitives = { TUninit, TInitNull, TFalse, TTrue, TInt, TDbl, TSStr, TCStr, TSArrE, TCArrE, TSArrN, TCArrN, TObj, TRes, TCls, TRef }; auto const optionals = { TOptTrue, TOptFalse, TOptBool, TOptInt, TOptDbl, TOptNum, TOptSStr, TOptCStr, TOptStr, TOptSArrE, TOptCArrE, TOptSArrN, TOptCArrN, TOptSArr, TOptCArr, TOptArr, TOptObj, TOptRes }; auto const non_opt_unions = { TInitCell, TCell, TInitGen, TGen, TNull, TBool, TNum, TStr, TArrE, TArrN, TSArr, TCArr, TArr, TInitPrim, TPrim, TInitUnc, TUnc, TTop, }; auto const all_unions = boost::join(optionals, non_opt_unions); auto const all = folly::lazy([] { std::vector<Type> ret; auto const wdata = with_data(); ret.insert(end(ret), begin(primitives), end(primitives)); ret.insert(end(ret), begin(all_unions), end(all_unions)); ret.insert(end(ret), begin(wdata), end(wdata)); return ret; }); template<class Range> std::vector<Type> wait_handles_of(const Index& index, const Range& r) { std::vector<Type> ret; for (auto& t : r) ret.push_back(wait_handle(index, t)); return ret; } std::vector<Type> all_with_waithandles(const Index& index) { auto ret = wait_handles_of(index, all()); for (auto& t : all()) ret.push_back(t); return ret; } auto const specialized_array_examples = folly::lazy([] { auto ret = std::vector<Type>{}; auto test_map_a = StructMap{}; test_map_a[s_test.get()] = ival(2); ret.emplace_back(sarr_struct(test_map_a)); auto test_map_b = StructMap{}; test_map_b[s_test.get()] = TInt; ret.emplace_back(sarr_struct(test_map_b)); auto test_map_c = StructMap{}; test_map_c[s_A.get()] = TInt; ret.emplace_back(sarr_struct(test_map_c)); auto test_map_d = StructMap{}; test_map_d[s_A.get()] = TInt; test_map_d[s_test.get()] = TDbl; ret.emplace_back(sarr_struct(test_map_d)); ret.emplace_back(arr_packedn(TInt)); ret.emplace_back(arr_mapn(TSStr, arr_mapn(TInt, TSStr))); ret.emplace_back(arr_mapn(TSStr, TArr)); ret.emplace_back(arr_mapn(TSStr, arr_packedn(TSStr))); ret.emplace_back(arr_mapn(TSStr, arr_mapn(TSStr, TSStr))); return ret; }); ////////////////////////////////////////////////////////////////////// } TEST(Type, Top) { auto const program = make_program(); Index index { borrow(program) }; // Everything is a subtype of Top, couldBe Top, and the union of Top // with anything is Top. for (auto& t : all_with_waithandles(index)) { EXPECT_TRUE(t.subtypeOf(TTop)); EXPECT_TRUE(t.couldBe(TTop)); EXPECT_TRUE(union_of(t, TTop) == TTop); EXPECT_TRUE(union_of(TTop, t) == TTop); } } TEST(Type, Bottom) { auto const program = make_program(); Index index { borrow(program) }; // Bottom is a subtype of everything, nothing couldBe Bottom, and // the union_of anything with Bottom is itself. for (auto& t : all_with_waithandles(index)) { EXPECT_TRUE(TBottom.subtypeOf(t)); EXPECT_TRUE(!TBottom.couldBe(t)); EXPECT_TRUE(union_of(t, TBottom) == t); EXPECT_TRUE(union_of(TBottom, t) == t); } } TEST(Type, Prims) { auto const program = make_program(); Index index { borrow(program) }; // All pairs of non-equivalent primitives are not related by either // subtypeOf or couldBe, including if you wrap them in wait handles. for (auto& t1 : primitives) { for (auto& t2 : primitives) { if (t1 != t2) { EXPECT_TRUE(!t1.subtypeOf(t2) && !t2.subtypeOf(t1)); EXPECT_TRUE(!t1.couldBe(t2)); EXPECT_TRUE(!t2.couldBe(t1)); auto const w1 = wait_handle(index, t1); auto const w2 = wait_handle(index, t2); EXPECT_TRUE(!w1.subtypeOf(w2) && !w2.subtypeOf(w1)); EXPECT_TRUE(!w1.couldBe(w2)); EXPECT_TRUE(!w2.couldBe(w1)); } } } } TEST(Type, Relations) { auto const program = make_program(); Index index { borrow(program) }; // couldBe is symmetric and reflexive for (auto& t1 : all_with_waithandles(index)) { for (auto& t2 : all()) { EXPECT_TRUE(t1.couldBe(t2) == t2.couldBe(t1)); } } for (auto& t1 : all_with_waithandles(index)) { EXPECT_TRUE(t1.couldBe(t1)); } // subtype is antisymmetric and reflexive for (auto& t1 : all_with_waithandles(index)) { for (auto& t2 : all_with_waithandles(index)) { if (t1 != t2) { EXPECT_TRUE(!(t1.subtypeOf(t2) && t2.subtypeOf(t1))); } } } for (auto& t1 : all_with_waithandles(index)) { EXPECT_TRUE(t1.subtypeOf(t1)); } // union_of is commutative for (auto& t1 : all_with_waithandles(index)) { for (auto& t2 : all_with_waithandles(index)) { EXPECT_TRUE(union_of(t1, t2) == union_of(t2, t1)) << " " << show(t1) << ' ' << show(t2) << "\n union_of(t1, t2): " << show(union_of(t1, t2)) << "\n union_of(t2, t1): " << show(union_of(t2, t1)); } } } TEST(Type, Prim) { auto subtype_true = std::initializer_list<std::pair<Type,Type>> { { TInt, TPrim }, { TBool, TPrim }, { TNum, TPrim }, { TInitNull, TPrim }, { TDbl, TPrim }, { dval(0.0), TPrim }, { ival(0), TPrim }, { TNull, TPrim }, { TInt, TInitPrim }, { TBool, TInitPrim }, { TNum, TInitPrim }, { TInitNull, TInitPrim }, { TDbl, TInitPrim }, { dval(0.0), TInitPrim }, { ival(0), TInitPrim }, }; auto subtype_false = std::initializer_list<std::pair<Type,Type>> { { sval(s_test.get()), TPrim }, { TSStr, TPrim }, { TSArr, TPrim }, { TNull, TInitPrim }, // TNull could be uninit { TPrim, TBool }, { TPrim, TInt }, { TPrim, TNum }, { TInitPrim, TNum }, { TUnc, TPrim }, { TUnc, TInitPrim }, { TInitUnc, TPrim }, { TSStr, TInitPrim }, { TArr, TInitPrim }, { TSArr, TPrim }, { TPrim, dval(0.0) }, }; auto couldbe_true = std::initializer_list<std::pair<Type,Type>> { { TPrim, TInt }, { TPrim, TBool }, { TPrim, TNum }, { TInitPrim, TNum }, { TInitPrim, TFalse }, { TPrim, TCell }, { TPrim, TInt }, { TPrim, TInt }, { TPrim, TOptObj }, { TPrim, TOptFalse }, }; auto couldbe_false = std::initializer_list<std::pair<Type,Type>> { { TPrim, TSStr }, { TInitPrim, TSStr }, { TInitPrim, sval(s_test.get()) }, { TPrim, sval(s_test.get()) }, { TInitPrim, TUninit }, { TPrim, TRef }, { TPrim, TObj }, }; for (auto kv : subtype_true) { EXPECT_TRUE(kv.first.subtypeOf(kv.second)) << show(kv.first) << " subtypeOf " << show(kv.second); } for (auto kv : subtype_false) { EXPECT_FALSE(kv.first.subtypeOf(kv.second)) << show(kv.first) << " !subtypeOf " << show(kv.second); } for (auto kv : couldbe_true) { EXPECT_TRUE(kv.first.couldBe(kv.second)) << show(kv.first) << " couldbe " << show(kv.second); EXPECT_TRUE(kv.second.couldBe(kv.first)) << show(kv.first) << " couldbe " << show(kv.second); } for (auto kv : couldbe_false) { EXPECT_TRUE(!kv.first.couldBe(kv.second)) << show(kv.first) << " !couldbe " << show(kv.second); EXPECT_TRUE(!kv.second.couldBe(kv.first)) << show(kv.first) << " !couldbe " << show(kv.second); } } TEST(Type, CouldBeValues) { EXPECT_FALSE(ival(2).couldBe(ival(3))); EXPECT_TRUE(ival(2).couldBe(ival(2))); EXPECT_FALSE(aval(test_array_packed_value()).couldBe( aval(test_array_map_value()))); EXPECT_TRUE(aval(test_array_packed_value()).couldBe( aval(test_array_packed_value()))); EXPECT_TRUE(dval(2.0).couldBe(dval(2.0))); EXPECT_FALSE(dval(2.0).couldBe(dval(3.0))); EXPECT_FALSE(sval(s_test.get()).couldBe(sval(s_A.get()))); EXPECT_TRUE(sval(s_test.get()).couldBe(sval(s_test.get()))); } TEST(Type, Unc) { EXPECT_TRUE(TInt.subtypeOf(TInitUnc)); EXPECT_TRUE(TInt.subtypeOf(TUnc)); EXPECT_TRUE(TDbl.subtypeOf(TInitUnc)); EXPECT_TRUE(TDbl.subtypeOf(TUnc)); EXPECT_TRUE(dval(3.0).subtypeOf(TInitUnc)); auto pairs = std::initializer_list<std::pair<Type,Type>> { { TUnc, TInitUnc }, { TUnc, TInitCell }, { TUnc, TCell }, { TInitUnc, TInt }, { TInitUnc, TOptInt }, { TInitUnc, opt(ival(2)) }, { TUnc, TInt }, { TUnc, TOptInt }, { TUnc, opt(ival(2)) }, { TNum, TUnc }, { TNum, TInitUnc }, }; for (auto kv : pairs) { EXPECT_TRUE(kv.first.couldBe(kv.second)) << show(kv.first) << " couldBe " << show(kv.second); } } TEST(Type, DblNan) { auto const qnan = std::numeric_limits<double>::quiet_NaN(); EXPECT_TRUE(dval(qnan).subtypeOf(dval(qnan))); EXPECT_TRUE(dval(qnan).couldBe(dval(qnan))); EXPECT_TRUE(dval(qnan) == dval(qnan)); } TEST(Type, Option) { auto const program = make_program(); Index index { borrow(program) }; EXPECT_TRUE(TTrue.subtypeOf(TOptTrue)); EXPECT_TRUE(TInitNull.subtypeOf(TOptTrue)); EXPECT_TRUE(!TUninit.subtypeOf(TOptTrue)); EXPECT_TRUE(TFalse.subtypeOf(TOptFalse)); EXPECT_TRUE(TInitNull.subtypeOf(TOptFalse)); EXPECT_TRUE(!TUninit.subtypeOf(TOptFalse)); EXPECT_TRUE(TFalse.subtypeOf(TOptBool)); EXPECT_TRUE(TTrue.subtypeOf(TOptBool)); EXPECT_TRUE(TInitNull.subtypeOf(TOptBool)); EXPECT_TRUE(!TUninit.subtypeOf(TOptBool)); EXPECT_TRUE(ival(3).subtypeOf(TOptInt)); EXPECT_TRUE(TInt.subtypeOf(TOptInt)); EXPECT_TRUE(TInitNull.subtypeOf(TOptInt)); EXPECT_TRUE(!TUninit.subtypeOf(TOptInt)); EXPECT_TRUE(TDbl.subtypeOf(TOptDbl)); EXPECT_TRUE(TInitNull.subtypeOf(TOptDbl)); EXPECT_TRUE(!TUninit.subtypeOf(TOptDbl)); EXPECT_TRUE(dval(3.0).subtypeOf(TOptDbl)); EXPECT_TRUE(sval(s_test.get()).subtypeOf(TOptSStr)); EXPECT_TRUE(TSStr.subtypeOf(TOptSStr)); EXPECT_TRUE(TInitNull.subtypeOf(TOptSStr)); EXPECT_TRUE(!TUninit.subtypeOf(TOptSStr)); EXPECT_TRUE(!TStr.subtypeOf(TOptSStr)); EXPECT_TRUE(TStr.couldBe(TOptSStr)); EXPECT_TRUE(TCStr.subtypeOf(TOptStr)); EXPECT_TRUE(TCArr.subtypeOf(TOptArr)); EXPECT_TRUE(TStr.subtypeOf(TOptStr)); EXPECT_TRUE(TSStr.subtypeOf(TOptStr)); EXPECT_TRUE(sval(s_test.get()).subtypeOf(TOptStr)); EXPECT_TRUE(TInitNull.subtypeOf(TOptStr)); EXPECT_TRUE(!TUninit.subtypeOf(TOptStr)); EXPECT_TRUE(TSArr.subtypeOf(TOptSArr)); EXPECT_TRUE(!TArr.subtypeOf(TOptSArr)); EXPECT_TRUE(TInitNull.subtypeOf(TOptSArr)); EXPECT_TRUE(!TUninit.subtypeOf(TOptSArr)); EXPECT_TRUE(TArr.subtypeOf(TOptArr)); EXPECT_TRUE(TInitNull.subtypeOf(TOptArr)); EXPECT_TRUE(!TUninit.subtypeOf(TOptArr)); EXPECT_TRUE(TObj.subtypeOf(TOptObj)); EXPECT_TRUE(TInitNull.subtypeOf(TOptObj)); EXPECT_TRUE(!TUninit.subtypeOf(TOptObj)); EXPECT_TRUE(TRes.subtypeOf(TOptRes)); EXPECT_TRUE(TInitNull.subtypeOf(TOptRes)); EXPECT_TRUE(!TUninit.subtypeOf(TOptRes)); for (auto& t : optionals) EXPECT_EQ(t, opt(unopt(t))); for (auto& t : optionals) EXPECT_TRUE(is_opt(t)); for (auto& t : all()) { auto const found = std::find(begin(optionals), end(optionals), t) != end(optionals); EXPECT_EQ(found, is_opt(t)); } EXPECT_TRUE(is_opt(opt(sval(s_test.get())))); EXPECT_TRUE(is_opt(opt(ival(2)))); EXPECT_TRUE(is_opt(opt(dval(2.0)))); EXPECT_FALSE(is_opt(sval(s_test.get()))); EXPECT_FALSE(is_opt(ival(2))); EXPECT_FALSE(is_opt(dval(2.0))); EXPECT_TRUE(wait_handle(index, opt(dval(2.0))).couldBe( wait_handle(index, dval(2.0)))); } TEST(Type, Num) { EXPECT_EQ(union_of(TInt, TDbl), TNum); EXPECT_EQ(union_of(ival(2), dval(1.0)), TNum); EXPECT_EQ(union_of(TInt, dval(1.0)), TNum); } TEST(Type, OptUnionOf) { EXPECT_EQ(opt(ival(2)), union_of(ival(2), TInitNull)); EXPECT_EQ(opt(dval(2.0)), union_of(TInitNull, dval(2.0))); EXPECT_EQ(opt(sval(s_test.get())), union_of(sval(s_test.get()), TInitNull)); EXPECT_EQ(opt(sval(s_test.get())), union_of(TInitNull, sval(s_test.get()))); EXPECT_EQ(TOptBool, union_of(TOptFalse, TOptTrue)); EXPECT_EQ(TOptBool, union_of(TOptTrue, TOptFalse)); EXPECT_EQ(TOptCArr, union_of(TCArr, TInitNull)); EXPECT_EQ(TOptCArr, union_of(TInitNull, TCArr)); EXPECT_EQ(TOptSArr, union_of(TInitNull, TOptSArr)); EXPECT_EQ(TOptSArr, union_of(TOptSArr, TInitNull)); EXPECT_EQ(TOptArr, union_of(TOptArr, TInitNull)); EXPECT_EQ(TOptArr, union_of(TInitNull, TOptArr)); EXPECT_EQ(TInitUnc, union_of(TOptSArr, TSStr)); EXPECT_EQ(TInitUnc, union_of(TSStr, TOptSArr)); EXPECT_EQ(TOptSStr, union_of(opt(sval(s_test.get())), opt(sval(s_TestClass.get())))); EXPECT_EQ(TOptInt, union_of(opt(ival(2)), opt(ival(3)))); EXPECT_EQ(TOptDbl, union_of(opt(dval(2.0)), opt(dval(3.0)))); EXPECT_EQ(TOptNum, union_of(TInitNull, TNum)); EXPECT_EQ(TOptNum, union_of(TInitNull, union_of(dval(1), ival(0)))); auto const program = make_program(); Index index { borrow(program) }; auto const rcls = index.builtin_class(s_WaitHandle.get()); EXPECT_TRUE(union_of(TObj, opt(objExact(rcls))) == TOptObj); } TEST(Type, OptTV) { EXPECT_TRUE(!tv(opt(ival(2)))); EXPECT_TRUE(!tv(opt(sval(s_test.get())))); EXPECT_TRUE(!tv(opt(dval(2.0)))); EXPECT_TRUE(!tv(TOptFalse)); EXPECT_TRUE(!tv(TOptTrue)); for (auto& x : optionals) { EXPECT_TRUE(!tv(x)); } } TEST(Type, OptCouldBe) { for (auto& x : optionals) EXPECT_TRUE(x.couldBe(unopt(x))); auto true_cases = std::initializer_list<std::pair<Type,Type>> { { opt(sval(s_test.get())), TStr }, { opt(sval(s_test.get())), TInitNull }, { opt(sval(s_test.get())), TSStr }, { opt(sval(s_test.get())), sval(s_test.get()) }, { opt(ival(2)), TInt }, { opt(ival(2)), TInitNull }, { opt(ival(2)), ival(2) }, { opt(dval(2.0)), TDbl }, { opt(dval(2.0)), TInitNull }, { opt(dval(2.0)), dval(2) }, { opt(TFalse), TBool }, { opt(TFalse), TFalse }, { opt(TTrue), TBool }, { opt(TTrue), TTrue }, { opt(TDbl), opt(TNum) }, { TDbl, opt(TNum) }, { TNum, opt(TDbl) }, { opt(TInt), TNum }, { TInt, opt(TNum) }, { opt(TDbl), TNum }, }; auto false_cases = std::initializer_list<std::pair<Type,Type>> { { opt(sval(s_test.get())), TCStr }, { opt(ival(2)), TDbl }, { opt(dval(2.0)), TInt }, { opt(TFalse), TTrue }, { opt(TTrue), TFalse }, { TFalse, opt(TNum) }, }; for (auto kv : true_cases) { EXPECT_TRUE(kv.first.couldBe(kv.second)) << show(kv.first) << " couldBe " << show(kv.second) << " should be true"; } for (auto kv : false_cases) { EXPECT_TRUE(!kv.first.couldBe(kv.second)) << show(kv.first) << " couldBe " << show(kv.second) << " should be false"; } for (auto kv : boost::join(true_cases, false_cases)) { EXPECT_EQ(kv.first.couldBe(kv.second), kv.second.couldBe(kv.first)) << show(kv.first) << " couldBe " << show(kv.second) << " wasn't reflexive"; } for (auto& x : optionals) { EXPECT_TRUE(x.couldBe(unopt(x))); EXPECT_TRUE(x.couldBe(TInitNull)); EXPECT_TRUE(!x.couldBe(TUninit)); for (auto& y : optionals) { EXPECT_TRUE(x.couldBe(y)); } } } TEST(Type, Ref) { EXPECT_TRUE(TRef == TRef); EXPECT_TRUE(TRef != ref_to(TInt)); EXPECT_TRUE(ref_to(TInt) == ref_to(TInt)); EXPECT_TRUE(ref_to(TInt) != ref_to(TOptInt)); EXPECT_TRUE(TRef.couldBe(ref_to(TInt))); EXPECT_TRUE(ref_to(TInt).couldBe(TRef)); EXPECT_TRUE(!ref_to(TInt).couldBe(ref_to(TObj))); EXPECT_TRUE(ref_to(TOptInt).couldBe(ref_to(TInt))); EXPECT_TRUE(!TRef.subtypeOf(ref_to(TInt))); EXPECT_TRUE(ref_to(TInt).subtypeOf(TRef)); EXPECT_TRUE(ref_to(TInt).subtypeOf(ref_to(TOptInt))); EXPECT_TRUE(!ref_to(TOptInt).subtypeOf(ref_to(TInt))); EXPECT_TRUE(!ref_to(TObj).subtypeOf(ref_to(TInt))); EXPECT_TRUE(!ref_to(TInt).subtypeOf(ref_to(TObj))); EXPECT_TRUE(union_of(TRef, ref_to(TInt)) == TRef); EXPECT_TRUE(union_of(ref_to(TInt), ref_to(TObj)) == ref_to(TInitCell)); EXPECT_TRUE(union_of(ref_to(TInitNull), ref_to(TObj)) == ref_to(TOptObj)); } TEST(Type, SpecificExamples) { // Random examples to stress option types, values, etc: EXPECT_TRUE(!TInt.subtypeOf(ival(1))); EXPECT_TRUE(TInitCell.couldBe(ival(1))); EXPECT_TRUE(TInitCell.subtypeOf(TGen)); EXPECT_TRUE(ival(2).subtypeOf(TInt)); EXPECT_TRUE(!ival(2).subtypeOf(TBool)); EXPECT_TRUE(ival(3).subtypeOf(TOptInt)); EXPECT_TRUE(TInt.subtypeOf(TOptInt)); EXPECT_TRUE(!TBool.subtypeOf(TOptInt)); EXPECT_TRUE(TInitNull.subtypeOf(TOptInt)); EXPECT_TRUE(!TNull.subtypeOf(TOptInt)); EXPECT_TRUE(TNull.couldBe(TOptInt)); EXPECT_TRUE(TNull.couldBe(TOptBool)); EXPECT_TRUE(TInitNull.subtypeOf(TInitCell)); EXPECT_TRUE(TInitNull.subtypeOf(TCell)); EXPECT_TRUE(!TUninit.subtypeOf(TInitNull)); EXPECT_TRUE(ival(3).subtypeOf(TOptInt)); EXPECT_TRUE(ival(3).subtypeOf(opt(ival(3)))); EXPECT_TRUE(ival(3).couldBe(opt(ival(3)))); EXPECT_TRUE(ival(3).couldBe(TInt)); EXPECT_TRUE(TInitNull.couldBe(opt(ival(3)))); EXPECT_TRUE(TNull.couldBe(opt(ival(3)))); EXPECT_TRUE(TInitNull.subtypeOf(opt(ival(3)))); EXPECT_TRUE(!TNull.subtypeOf(opt(ival(3)))); EXPECT_EQ(TStr, union_of(sval(s_test.get()), TCStr)); EXPECT_EQ(TStr, union_of(TCStr, sval(s_test.get()))); EXPECT_EQ(TGen, union_of(TRef, TUninit)); } TEST(Type, IndexBased) { auto const program = make_program(); auto const unit = borrow(program->units.back()); auto const func = [&]() -> borrowed_ptr<php::Func> { for (auto& f : unit->funcs) { if (f->name->isame(s_test.get())) return borrow(f); } return nullptr; }(); EXPECT_TRUE(func != nullptr); auto const ctx = Context { unit, func }; Index idx{borrow(program)}; auto const cls = idx.resolve_class(ctx, s_TestClass.get()); if (!cls) EXPECT_TRUE(false); auto const clsBase = idx.resolve_class(ctx, s_Base.get()); if (!clsBase) EXPECT_TRUE(false); auto const objExactTy = objExact(*cls); auto const subObjTy = subObj(*cls); auto const clsExactTy = clsExact(*cls); auto const subClsTy = subCls(*cls); auto const objExactBaseTy = objExact(*clsBase); auto const subObjBaseTy = subObj(*clsBase); // Basic relationship between the class types and object types. EXPECT_EQ(objcls(objExactTy), clsExactTy); EXPECT_EQ(objcls(subObjTy), subClsTy); // =TestClass <: <=TestClass, and not vice versa. EXPECT_TRUE(objExactTy.subtypeOf(subObjTy)); EXPECT_TRUE(!subObjTy.subtypeOf(objExactTy)); // =TestClass <: <=TestClass, and not vice versa. EXPECT_TRUE(clsExactTy.subtypeOf(subClsTy)); EXPECT_TRUE(!subClsTy.subtypeOf(clsExactTy)); // =TestClass couldBe <= TestClass, and vice versa. EXPECT_TRUE(objExactTy.couldBe(subObjTy)); EXPECT_TRUE(subObjTy.couldBe(objExactTy)); EXPECT_TRUE(clsExactTy.couldBe(subClsTy)); EXPECT_TRUE(subClsTy.couldBe(clsExactTy)); // Foo= and Foo<= are both subtypes of Foo, and couldBe Foo. EXPECT_TRUE(objExactTy.subtypeOf(TObj)); EXPECT_TRUE(subObjTy.subtypeOf(TObj)); EXPECT_TRUE(objExactTy.couldBe(TObj)); EXPECT_TRUE(subObjTy.couldBe(TObj)); EXPECT_TRUE(TObj.couldBe(objExactTy)); EXPECT_TRUE(TObj.couldBe(subObjTy)); EXPECT_TRUE(clsExactTy.subtypeOf(TCls)); EXPECT_TRUE(subClsTy.subtypeOf(TCls)); EXPECT_TRUE(clsExactTy.couldBe(TCls)); EXPECT_TRUE(subClsTy.couldBe(TCls)); EXPECT_TRUE(TCls.couldBe(clsExactTy)); EXPECT_TRUE(TCls.couldBe(subClsTy)); // Obj= and Obj<= both couldBe ?Obj, and vice versa. EXPECT_TRUE(objExactTy.couldBe(TOptObj)); EXPECT_TRUE(subObjTy.couldBe(TOptObj)); EXPECT_TRUE(TOptObj.couldBe(objExactTy)); EXPECT_TRUE(TOptObj.couldBe(subObjTy)); // Obj= and Obj<= are subtypes of ?Obj. EXPECT_TRUE(objExactTy.subtypeOf(TOptObj)); EXPECT_TRUE(subObjTy.subtypeOf(TOptObj)); // Obj= is a subtype of ?Obj=, and also ?Obj<=. EXPECT_TRUE(objExactTy.subtypeOf(opt(objExactTy))); EXPECT_TRUE(objExactTy.subtypeOf(opt(subObjTy))); EXPECT_TRUE(!opt(objExactTy).subtypeOf(objExactTy)); EXPECT_TRUE(!opt(subObjTy).subtypeOf(objExactTy)); // Obj= couldBe ?Obj= and ?Obj<=, and vice versa. EXPECT_TRUE(objExactTy.couldBe(opt(objExactTy))); EXPECT_TRUE(opt(objExactTy).couldBe(objExactTy)); EXPECT_TRUE(objExactTy.couldBe(opt(subObjTy))); EXPECT_TRUE(opt(subObjTy).couldBe(objExactTy)); // Obj<= is not a subtype of ?Obj=, it is overlapping but // potentially contains other types. (We might eventually check // whether objects are final as part of this, but not right now.) EXPECT_TRUE(!subObjTy.subtypeOf(opt(objExactTy))); EXPECT_TRUE(!opt(objExactTy).subtypeOf(subObjTy)); // Obj<= couldBe ?Obj= and vice versa. EXPECT_TRUE(subObjTy.couldBe(opt(objExactTy))); EXPECT_TRUE(opt(objExactTy).couldBe(subObjTy)); // ?Obj<=, ?Obj=, ?Foo<= and ?Foo= couldBe each other EXPECT_TRUE(opt(subObjTy).couldBe(opt(objExactBaseTy))); EXPECT_TRUE(opt(objExactBaseTy).couldBe(opt(subObjTy))); EXPECT_TRUE(opt(subObjTy).couldBe(opt(subObjBaseTy))); EXPECT_TRUE(opt(subObjBaseTy).couldBe(opt(subObjTy))); EXPECT_TRUE(opt(objExactTy).couldBe(opt(objExactBaseTy))); EXPECT_TRUE(opt(objExactBaseTy).couldBe(opt(objExactTy))); EXPECT_TRUE(opt(objExactTy).couldBe(opt(subObjBaseTy))); EXPECT_TRUE(opt(subObjBaseTy).couldBe(opt(objExactTy))); } TEST(Type, Hierarchies) { auto const program = make_program(); auto const unit = borrow(program->units.back()); auto const func = [&]() -> borrowed_ptr<php::Func> { for (auto& f : unit->funcs) { if (f->name->isame(s_test.get())) return borrow(f); } return nullptr; }(); EXPECT_TRUE(func != nullptr); auto const ctx = Context { unit, func }; Index idx{borrow(program)}; // load classes in hierarchy auto const clsBase = idx.resolve_class(ctx, s_Base.get()); if (!clsBase) EXPECT_TRUE(false); auto const clsA = idx.resolve_class(ctx, s_A.get()); if (!clsA) EXPECT_TRUE(false); auto const clsB = idx.resolve_class(ctx, s_B.get()); if (!clsB) EXPECT_TRUE(false); auto const clsAA = idx.resolve_class(ctx, s_AA.get()); if (!clsAA) EXPECT_TRUE(false); auto const clsAB = idx.resolve_class(ctx, s_AB.get()); if (!clsAB) EXPECT_TRUE(false); auto const clsBA = idx.resolve_class(ctx, s_BA.get()); if (!clsBA) EXPECT_TRUE(false); auto const clsBB = idx.resolve_class(ctx, s_BB.get()); if (!clsBB) EXPECT_TRUE(false); auto const clsBAA = idx.resolve_class(ctx, s_BAA.get()); if (!clsBAA) EXPECT_TRUE(false); auto const clsTestClass = idx.resolve_class(ctx, s_TestClass.get()); if (!clsTestClass) EXPECT_TRUE(false); auto const clsNonUnique = idx.resolve_class(ctx, s_NonUnique.get()); if (!clsNonUnique) EXPECT_TRUE(false); // make *exact type* and *sub type* types and objects for all loaded classes auto const objExactBaseTy = objExact(*clsBase); auto const subObjBaseTy = subObj(*clsBase); auto const clsExactBaseTy = clsExact(*clsBase); auto const subClsBaseTy = subCls(*clsBase); auto const objExactATy = objExact(*clsA); auto const subObjATy = subObj(*clsA); auto const clsExactATy = clsExact(*clsA); auto const subClsATy = subCls(*clsA); auto const objExactAATy = objExact(*clsAA); auto const subObjAATy = subObj(*clsAA); auto const clsExactAATy = clsExact(*clsAA); auto const subClsAATy = subCls(*clsAA); auto const objExactABTy = objExact(*clsAB); auto const subObjABTy = subObj(*clsAB); auto const clsExactABTy = clsExact(*clsAB); auto const subClsABTy = subCls(*clsAB); auto const objExactBTy = objExact(*clsB); auto const subObjBTy = subObj(*clsB); auto const clsExactBTy = clsExact(*clsB); auto const subClsBTy = subCls(*clsB); auto const objExactBATy = objExact(*clsBA); auto const subObjBATy = subObj(*clsBA); auto const clsExactBATy = clsExact(*clsBA); auto const subClsBATy = subCls(*clsBA); auto const objExactBBTy = objExact(*clsBB); auto const subObjBBTy = subObj(*clsBB); auto const clsExactBBTy = clsExact(*clsBB); auto const subClsBBTy = subCls(*clsBB); auto const objExactBAATy = objExact(*clsBAA); auto const subObjBAATy = subObj(*clsBAA); auto const clsExactBAATy = clsExact(*clsBAA); auto const subClsBAATy = subCls(*clsBAA); auto const objExactTestClassTy = objExact(*clsTestClass); auto const subObjTestClassTy = subObj(*clsTestClass); auto const clsExactTestClassTy = clsExact(*clsTestClass); auto const subClsTestClassTy = subCls(*clsTestClass); auto const objExactNonUniqueTy = objExact(*clsNonUnique); auto const subObjNonUniqueTy = subObj(*clsNonUnique); auto const clsExactNonUniqueTy = clsExact(*clsNonUnique); auto const subClsNonUniqueTy = subCls(*clsNonUnique); // check that type from object and type are the same (obnoxious test) EXPECT_EQ(objcls(objExactBaseTy), clsExactBaseTy); EXPECT_EQ(objcls(subObjBaseTy), subClsBaseTy); EXPECT_EQ(objcls(objExactATy), clsExactATy); EXPECT_EQ(objcls(subObjATy), subClsATy); EXPECT_EQ(objcls(objExactAATy), clsExactAATy); EXPECT_EQ(objcls(subObjAATy), subClsAATy); EXPECT_EQ(objcls(objExactABTy), clsExactABTy); EXPECT_EQ(objcls(subObjABTy), subClsABTy); EXPECT_EQ(objcls(objExactBTy), clsExactBTy); EXPECT_EQ(objcls(subObjBTy), subClsBTy); EXPECT_EQ(objcls(objExactBATy), clsExactBATy); EXPECT_EQ(objcls(subObjBATy), subClsBATy); EXPECT_EQ(objcls(objExactBBTy), clsExactBBTy); EXPECT_EQ(objcls(subObjBBTy), subClsBBTy); EXPECT_EQ(objcls(objExactBAATy), clsExactBAATy); EXPECT_EQ(objcls(subObjBAATy), subClsBAATy); // both subobj(A) and subcls(A) of no_override class A change to exact types EXPECT_EQ(objcls(objExactABTy), subClsABTy); EXPECT_EQ(objcls(subObjABTy), clsExactABTy); // a T= is a subtype of itself but not a strict subtype // also a T= is in a "could be" relationship with itself. EXPECT_TRUE(objcls(objExactBaseTy).subtypeOf(clsExactBaseTy)); EXPECT_FALSE(objcls(objExactBaseTy).strictSubtypeOf(objcls(objExactBaseTy))); EXPECT_TRUE(objcls(objExactBAATy).subtypeOf(clsExactBAATy)); EXPECT_FALSE(clsExactBAATy.strictSubtypeOf(objcls(objExactBAATy))); EXPECT_TRUE(clsExactBAATy.couldBe(clsExactBAATy)); // Given the hierarchy A <- B <- C where A is the base then: // B= is not in any subtype relationshipt with a A= or C=. // Neither they are in "could be" relationships. // Overall T= sets are always disjoint. EXPECT_FALSE(objcls(objExactBATy).subtypeOf(clsExactBaseTy)); EXPECT_FALSE(objcls(objExactBATy).subtypeOf(clsExactBTy)); EXPECT_FALSE(objcls(objExactBATy).subtypeOf(clsExactBAATy)); EXPECT_FALSE(clsExactBATy.strictSubtypeOf(objcls(objExactBaseTy))); EXPECT_FALSE(clsExactBATy.strictSubtypeOf(objcls(objExactBTy))); EXPECT_FALSE(clsExactBATy.strictSubtypeOf(objcls(objExactBAATy))); EXPECT_FALSE(clsExactBATy.couldBe(objcls(objExactBaseTy))); EXPECT_FALSE(objcls(objExactBATy).couldBe(clsExactBTy)); EXPECT_FALSE(clsExactBATy.couldBe(objcls(objExactBAATy))); // any T= is both a subtype and strict subtype of T<=. // Given the hierarchy A <- B <- C where A is the base then: // C= is a subtype and a strict subtype of B<=, ?B<=, A<= and ?A<=. // The "could be" relationship also holds. EXPECT_TRUE(objcls(objExactATy).subtypeOf(subClsATy)); EXPECT_TRUE(objcls(objExactBAATy).subtypeOf(subClsBaseTy)); EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBaseTy))); EXPECT_TRUE(objcls(objExactBAATy).subtypeOf(subClsBTy)); EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBTy))); EXPECT_TRUE(clsExactBAATy.subtypeOf(objcls(subObjBATy))); EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBATy))); EXPECT_TRUE(clsExactBAATy.subtypeOf(objcls(subObjBAATy))); EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBAATy))); EXPECT_TRUE(objcls(objExactATy).strictSubtypeOf(subClsATy)); EXPECT_TRUE(objcls(objExactBAATy).strictSubtypeOf(subClsBaseTy)); EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBaseTy))); EXPECT_TRUE(objcls(objExactBAATy).strictSubtypeOf(subClsBTy)); EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBTy))); EXPECT_TRUE(clsExactBAATy.strictSubtypeOf(objcls(subObjBATy))); EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBATy))); EXPECT_TRUE(clsExactBAATy.strictSubtypeOf(objcls(subObjBAATy))); EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBAATy))); EXPECT_TRUE(objcls(objExactATy).couldBe(subClsATy)); EXPECT_TRUE(objcls(objExactBAATy).couldBe(subClsBaseTy)); EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBaseTy))); EXPECT_TRUE(objcls(objExactBAATy).couldBe(subClsBTy)); EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBTy))); EXPECT_TRUE(clsExactBAATy.couldBe(objcls(subObjBATy))); EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBATy))); EXPECT_TRUE(clsExactBAATy.couldBe(objcls(subObjBAATy))); EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBAATy))); // a T<= is a subtype of itself but not a strict subtype // also a T<= is in a "could be" relationship with itself EXPECT_TRUE(objcls(subObjBaseTy).subtypeOf(subClsBaseTy)); EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(objcls(subObjBaseTy))); EXPECT_TRUE(objcls(subObjBAATy).subtypeOf(subClsBAATy)); EXPECT_FALSE(subClsBAATy.strictSubtypeOf(objcls(subObjBAATy))); EXPECT_TRUE(subClsBAATy.couldBe(subClsBAATy)); // a T<= type is in no subtype relationship with T=. // However a T<= is in a "could be" relationship with T=. EXPECT_FALSE(objcls(subObjATy).subtypeOf(clsExactATy)); EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(clsExactATy)); EXPECT_TRUE(clsExactATy.couldBe(objcls(subObjATy))); // Given 2 types A and B in no inheritance relationship then // A<= and B<= are in no subtype or "could be" relationship. // Same if one of the 2 types is an optional type EXPECT_FALSE(objcls(subObjATy).subtypeOf(clsExactBTy)); EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(clsExactBTy)); EXPECT_FALSE(subObjATy.subtypeOf(opt(objExactBTy))); EXPECT_FALSE(subObjATy.strictSubtypeOf(opt(objExactBTy))); EXPECT_FALSE(clsExactATy.couldBe(objcls(subObjBTy))); EXPECT_FALSE(objExactATy.couldBe(opt(subObjBTy))); EXPECT_FALSE(objcls(subObjBTy).subtypeOf(clsExactATy)); EXPECT_FALSE(subObjBTy.subtypeOf(opt(objExactATy))); EXPECT_FALSE(objcls(subObjBTy).strictSubtypeOf(clsExactATy)); EXPECT_FALSE(subObjBTy.strictSubtypeOf(opt(objExactATy))); EXPECT_FALSE(clsExactBTy.couldBe(objcls(subObjATy))); EXPECT_FALSE(objExactBTy.couldBe(opt(subObjATy))); // Given the hierarchy A <- B <- C where A is the base then: // C<= is a subtype and a strict subtype of B<=, ?B<=, A<= and ?A<=. // It is also in a "could be" relationship with all its ancestors // (including optional) EXPECT_TRUE(objcls(subObjBAATy).subtypeOf(subClsBaseTy)); EXPECT_TRUE(subObjBAATy.subtypeOf(opt(subObjBaseTy))); EXPECT_TRUE(objcls(subObjBAATy).subtypeOf(subClsBTy)); EXPECT_TRUE(subObjBAATy.subtypeOf(opt(subObjBTy))); EXPECT_TRUE(subClsBAATy.subtypeOf(objcls(subObjBATy))); EXPECT_TRUE(subObjBAATy.subtypeOf(opt(subObjBATy))); EXPECT_TRUE(objcls(subObjBAATy).strictSubtypeOf(subClsBaseTy)); EXPECT_TRUE(subObjBAATy.strictSubtypeOf(opt(subObjBaseTy))); EXPECT_TRUE(objcls(subObjBAATy).strictSubtypeOf(subClsBTy)); EXPECT_TRUE(subObjBAATy.strictSubtypeOf(opt(subObjBTy))); EXPECT_TRUE(subClsBAATy.strictSubtypeOf(objcls(subObjBATy))); EXPECT_TRUE(subObjBAATy.strictSubtypeOf(opt(subObjBATy))); EXPECT_TRUE(objcls(subObjBAATy).couldBe(subClsBaseTy)); EXPECT_TRUE(subObjBAATy.couldBe(opt(subObjBaseTy))); EXPECT_TRUE(objcls(subObjBAATy).couldBe(subClsBTy)); EXPECT_TRUE(subObjBAATy.couldBe(opt(subObjBTy))); EXPECT_TRUE(subClsBAATy.couldBe(objcls(subObjBATy))); EXPECT_TRUE(subObjBAATy.couldBe(opt(subObjBATy))); // Given the hierarchy A <- B <- C where A is the base then: // A<= is not in a subtype neither a strict subtype with B<=, ?B<=, A<= // ?A<=. However A<= is in a "could be" relationship with all its // children (including optional) EXPECT_FALSE(objcls(subObjBaseTy).subtypeOf(subClsATy)); EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjATy))); EXPECT_FALSE(objcls(subObjBaseTy).subtypeOf(subClsBTy)); EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBTy))); EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjAATy))); EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjAATy))); EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjABTy))); EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjABTy))); EXPECT_FALSE(objcls(subObjBaseTy).subtypeOf(subClsBATy)); EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBATy))); EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjBBTy))); EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBBTy))); EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjBAATy))); EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBAATy))); EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(subClsATy)); EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjATy))); EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(subClsBTy)); EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBTy))); EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjAATy))); EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjAATy))); EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjABTy))); EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjABTy))); EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(subClsBATy)); EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBATy))); EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjBBTy))); EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBBTy))); EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjBAATy))); EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBAATy))); EXPECT_TRUE(objcls(subObjBaseTy).couldBe(subClsATy)); EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjATy))); EXPECT_TRUE(objcls(subObjBaseTy).couldBe(subClsBTy)); EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBTy))); EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjAATy))); EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjAATy))); EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjABTy))); EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjABTy))); EXPECT_TRUE(objcls(subObjBaseTy).couldBe(subClsBATy)); EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBATy))); EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjBBTy))); EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBBTy))); EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjBAATy))); EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBAATy))); // check union_of and commonAncestor API EXPECT_TRUE((*(*clsA).commonAncestor(*clsB)).same(*clsBase)); EXPECT_TRUE((*(*clsB).commonAncestor(*clsA)).same(*clsBase)); EXPECT_TRUE((*(*clsAA).commonAncestor(*clsAB)).same(*clsA)); EXPECT_TRUE((*(*clsAB).commonAncestor(*clsAA)).same(*clsA)); EXPECT_TRUE((*(*clsA).commonAncestor(*clsBAA)).same(*clsBase)); EXPECT_TRUE((*(*clsBAA).commonAncestor(*clsA)).same(*clsBase)); EXPECT_TRUE((*(*clsBAA).commonAncestor(*clsB)).same(*clsB)); EXPECT_TRUE((*(*clsB).commonAncestor(*clsBAA)).same(*clsB)); EXPECT_TRUE((*(*clsBAA).commonAncestor(*clsBB)).same(*clsB)); EXPECT_TRUE((*(*clsBB).commonAncestor(*clsBAA)).same(*clsB)); EXPECT_TRUE((*(*clsAA).commonAncestor(*clsBase)).same(*clsBase)); EXPECT_TRUE((*(*clsBase).commonAncestor(*clsAA)).same(*clsBase)); EXPECT_FALSE((*clsAA).commonAncestor(*clsTestClass)); EXPECT_FALSE((*clsTestClass).commonAncestor(*clsAA)); EXPECT_FALSE((*clsBAA).commonAncestor(*clsNonUnique)); EXPECT_FALSE((*clsNonUnique).commonAncestor(*clsBAA)); // check union_of // union of subCls EXPECT_EQ(union_of(subClsATy, subClsBTy), subClsBaseTy); EXPECT_EQ(union_of(subClsAATy, subClsABTy), subClsATy); EXPECT_EQ(union_of(subClsATy, subClsBAATy), subClsBaseTy); EXPECT_EQ(union_of(subClsBAATy, subClsBTy), subClsBTy); EXPECT_EQ(union_of(subClsBAATy, subClsBBTy), subClsBTy); EXPECT_EQ(union_of(subClsAATy, subClsBaseTy), subClsBaseTy); EXPECT_EQ(union_of(subClsAATy, subClsTestClassTy), TCls); EXPECT_EQ(union_of(subClsBAATy, subClsNonUniqueTy), TCls); // union of subCls and clsExact mixed EXPECT_EQ(union_of(clsExactATy, subClsBTy), subClsBaseTy); EXPECT_EQ(union_of(subClsAATy, clsExactABTy), subClsATy); EXPECT_EQ(union_of(clsExactATy, subClsBAATy), subClsBaseTy); EXPECT_EQ(union_of(subClsBAATy, clsExactBTy), subClsBTy); EXPECT_EQ(union_of(clsExactBAATy, subClsBBTy), subClsBTy); EXPECT_EQ(union_of(subClsAATy, clsExactBaseTy), subClsBaseTy); EXPECT_EQ(union_of(clsExactAATy, subClsTestClassTy), TCls); EXPECT_EQ(union_of(subClsBAATy, clsExactNonUniqueTy), TCls); // union of clsExact EXPECT_EQ(union_of(clsExactATy, clsExactBTy), subClsBaseTy); EXPECT_EQ(union_of(clsExactAATy, clsExactABTy), subClsATy); EXPECT_EQ(union_of(clsExactATy, clsExactBAATy), subClsBaseTy); EXPECT_EQ(union_of(clsExactBAATy, clsExactBTy), subClsBTy); EXPECT_EQ(union_of(clsExactBAATy, clsExactBBTy), subClsBTy); EXPECT_EQ(union_of(clsExactAATy, clsExactBaseTy), subClsBaseTy); EXPECT_EQ(union_of(clsExactAATy, subClsTestClassTy), TCls); EXPECT_EQ(union_of(clsExactBAATy, clsExactNonUniqueTy), TCls); // union of subObj EXPECT_EQ(union_of(subObjATy, subObjBTy), subObjBaseTy); EXPECT_EQ(union_of(subObjAATy, subObjABTy), subObjATy); EXPECT_EQ(union_of(subObjATy, subObjBAATy), subObjBaseTy); EXPECT_EQ(union_of(subObjBAATy, subObjBTy), subObjBTy); EXPECT_EQ(union_of(subObjBAATy, subObjBBTy), subObjBTy); EXPECT_EQ(union_of(subObjAATy, subObjBaseTy), subObjBaseTy); EXPECT_EQ(union_of(subObjAATy, subObjTestClassTy), TObj); EXPECT_EQ(union_of(subObjBAATy, subObjNonUniqueTy), TObj); // union of subObj and objExact mixed EXPECT_EQ(union_of(objExactATy, subObjBTy), subObjBaseTy); EXPECT_EQ(union_of(subObjAATy, objExactABTy), subObjATy); EXPECT_EQ(union_of(objExactATy, subObjBAATy), subObjBaseTy); EXPECT_EQ(union_of(subObjBAATy, objExactBTy), subObjBTy); EXPECT_EQ(union_of(objExactBAATy, subObjBBTy), subObjBTy); EXPECT_EQ(union_of(subObjAATy, objExactBaseTy), subObjBaseTy); EXPECT_EQ(union_of(objExactAATy, subObjTestClassTy), TObj); EXPECT_EQ(union_of(subObjBAATy, objExactNonUniqueTy), TObj); // union of objExact EXPECT_EQ(union_of(objExactATy, objExactBTy), subObjBaseTy); EXPECT_EQ(union_of(objExactAATy, objExactABTy), subObjATy); EXPECT_EQ(union_of(objExactATy, objExactBAATy), subObjBaseTy); EXPECT_EQ(union_of(objExactBAATy, objExactBTy), subObjBTy); EXPECT_EQ(union_of(objExactBAATy, objExactBBTy), subObjBTy); EXPECT_EQ(union_of(objExactAATy, objExactBaseTy), subObjBaseTy); EXPECT_EQ(union_of(objExactAATy, objExactTestClassTy), TObj); EXPECT_EQ(union_of(objExactBAATy, objExactNonUniqueTy), TObj); // optional sub obj EXPECT_EQ(union_of(opt(subObjATy), opt(subObjBTy)), opt(subObjBaseTy)); EXPECT_EQ(union_of(subObjAATy, opt(subObjABTy)), opt(subObjATy)); EXPECT_EQ(union_of(opt(subObjATy), subObjBAATy), opt(subObjBaseTy)); EXPECT_EQ(union_of(opt(subObjBAATy), opt(subObjBTy)), opt(subObjBTy)); EXPECT_EQ(union_of(opt(subObjBAATy), subObjBBTy), opt(subObjBTy)); EXPECT_EQ(union_of(opt(subObjAATy), opt(subObjBaseTy)), opt(subObjBaseTy)); EXPECT_EQ(union_of(subObjAATy, opt(subObjTestClassTy)), opt(TObj)); EXPECT_EQ(union_of(subObjBAATy, opt(subObjNonUniqueTy)), opt(TObj)); // optional sub and exact obj mixed EXPECT_EQ(union_of(opt(objExactATy), subObjBTy), opt(subObjBaseTy)); EXPECT_EQ(union_of(subObjAATy, opt(objExactABTy)), opt(subObjATy)); EXPECT_EQ(union_of(opt(objExactATy), objExactBAATy), opt(subObjBaseTy)); EXPECT_EQ(union_of(subObjBAATy, opt(objExactBTy)), opt(subObjBTy)); EXPECT_EQ(union_of(opt(subObjBAATy), objExactBBTy), opt(subObjBTy)); EXPECT_EQ(union_of(objExactAATy, opt(objExactBaseTy)), opt(subObjBaseTy)); EXPECT_EQ(union_of(opt(subObjAATy), objExactTestClassTy), opt(TObj)); EXPECT_EQ(union_of(subObjBAATy, opt(objExactNonUniqueTy)), opt(TObj)); } TEST(Type, Interface) { auto const program = make_program(); auto const unit = borrow(program->units.back()); auto const func = [&]() -> borrowed_ptr<php::Func> { for (auto& f : unit->funcs) { if (f->name->isame(s_test.get())) return borrow(f); } return nullptr; }(); EXPECT_TRUE(func != nullptr); auto const ctx = Context { unit, func }; Index idx{borrow(program)}; // load classes in hierarchy auto const clsIA = idx.resolve_class(ctx, s_IA.get()); if (!clsIA) EXPECT_TRUE(false); auto const clsIAA = idx.resolve_class(ctx, s_IAA.get()); if (!clsIAA) EXPECT_TRUE(false); auto const clsA = idx.resolve_class(ctx, s_A.get()); if (!clsA) EXPECT_TRUE(false); auto const clsAA = idx.resolve_class(ctx, s_AA.get()); if (!clsAA) EXPECT_TRUE(false); // make sometypes and objects auto const subObjIATy = subObj(*clsIA); auto const subClsIATy = subCls(*clsIA); auto const subObjIAATy = subObj(*clsIAA); auto const subClsIAATy = subCls(*clsIAA); auto const subObjATy = subObj(*clsA); auto const clsExactATy = clsExact(*clsA); auto const subClsATy = subCls(*clsA); auto const subObjAATy = subObj(*clsAA); auto const subClsAATy = subCls(*clsAA); // we don't support interfaces quite yet so let's put few tests // that will fail once interfaces are supported // first 2 are "not precise" - should be true EXPECT_FALSE(subClsATy.subtypeOf(objcls(subObjIATy))); EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(subClsIATy)); EXPECT_TRUE(subClsATy.couldBe(objcls(subObjIATy))); // first 2 are "not precise" - should be true EXPECT_FALSE(subClsAATy.subtypeOf(objcls(subObjIAATy))); EXPECT_FALSE(objcls(subObjAATy).strictSubtypeOf(objcls(subObjIAATy))); EXPECT_TRUE(subClsAATy.couldBe(objcls(subObjIAATy))); // 3rd one is not precise - should be false EXPECT_FALSE(subClsATy.subtypeOf(objcls(subObjIAATy))); EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(objcls(subObjIAATy))); EXPECT_TRUE(clsExactATy.couldBe(objcls(subObjIAATy))); } TEST(Type, NonUnique) { auto const program = make_program(); auto const unit = borrow(program->units.back()); auto const func = [&]() -> borrowed_ptr<php::Func> { for (auto& f : unit->funcs) { if (f->name->isame(s_test.get())) return borrow(f); } return nullptr; }(); EXPECT_TRUE(func != nullptr); auto const ctx = Context { unit, func }; Index idx{borrow(program)}; auto const clsA = idx.resolve_class(ctx, s_A.get()); if (!clsA) EXPECT_TRUE(false); auto const clssNonUnique = idx.resolve_class(ctx, s_NonUnique.get()); if (!clssNonUnique) EXPECT_TRUE(false); auto const clssNonUniqueA = idx.resolve_class(ctx, s_NonUniqueA.get()); if (!clssNonUniqueA) EXPECT_TRUE(false); // non unique types are funny because we cannot really make any conclusion // about them so they resolve to "non precise" subtype relationship auto const subObjATy = subObj(*clsA); auto const subClsATy = subCls(*clsA); auto const subObjNonUniqueTy = subObj(*clssNonUnique); auto const subClsNonUniqueTy = subCls(*clssNonUnique); auto const subObjNonUniqueATy = subObj(*clssNonUniqueA); auto const subClsNonUniqueATy = subCls(*clssNonUniqueA); // all are obviously "non precise" but what can you do?.... EXPECT_FALSE(subClsNonUniqueATy.subtypeOf(objcls(subObjNonUniqueTy))); EXPECT_FALSE(objcls(subObjNonUniqueATy).strictSubtypeOf(subClsNonUniqueTy)); EXPECT_TRUE(subClsATy.couldBe(objcls(subObjNonUniqueTy))); } TEST(Type, WaitH) { auto const program = make_program(); Index index { borrow(program) }; for (auto& t : wait_handles_of(index, all())) { EXPECT_TRUE(is_specialized_wait_handle(t)); EXPECT_TRUE(t.subtypeOf(wait_handle(index, TTop))); } // union_of(WaitH<A>, WaitH<B>) == WaitH<union_of(A, B)> for (auto& t1 : all()) { for (auto& t2 : all()) { auto const u1 = union_of(t1, t2); auto const u2 = union_of(wait_handle(index, t1), wait_handle(index, t2)); EXPECT_TRUE(is_specialized_wait_handle(u2)); EXPECT_EQ(wait_handle_inner(u2), u1); EXPECT_EQ(wait_handle(index, u1), u2); } } // union_of(?WaitH<A>, ?WaitH<B>) == ?WaitH<union_of(A, B)> for (auto& t1 : all()) { for (auto& t2 : all()) { auto const w1 = opt(wait_handle(index, t1)); auto const w2 = opt(wait_handle(index, t2)); auto const u1 = union_of(w1, w2); auto const u2 = opt(wait_handle(index, union_of(t1, t2))); EXPECT_EQ(u1, u2); } } auto const rcls = index.builtin_class(s_WaitHandle.get()); auto const twhobj = subObj(rcls); EXPECT_TRUE(wait_handle(index, TTop).subtypeOf(twhobj)); // Some test cases with optional wait handles. auto const optWH = opt(wait_handle(index, ival(2))); EXPECT_TRUE(is_opt(optWH)); EXPECT_TRUE(TInitNull.subtypeOf(optWH)); EXPECT_TRUE(optWH.subtypeOf(TOptObj)); EXPECT_TRUE(optWH.subtypeOf(opt(twhobj))); EXPECT_TRUE(wait_handle(index, ival(2)).subtypeOf(optWH)); EXPECT_FALSE(optWH.subtypeOf(wait_handle(index, ival(2)))); EXPECT_TRUE(optWH.couldBe(wait_handle(index, ival(2)))); // union_of(WaitH<T>, Obj<=WaitHandle) == Obj<=WaitHandle for (auto& t : all()) { auto const u = union_of(wait_handle(index, t), twhobj); EXPECT_EQ(u, twhobj); } for (auto& t : all()) { auto const u1 = union_of(wait_handle(index, t), TInitNull); EXPECT_TRUE(is_opt(u1)); EXPECT_TRUE(is_specialized_wait_handle(u1)); auto const u2 = union_of(TInitNull, wait_handle(index, t)); EXPECT_TRUE(is_opt(u2)); EXPECT_TRUE(is_specialized_wait_handle(u2)); EXPECT_EQ(u1, u2); } // You can have WaitH<WaitH<T>>. And stuff. for (auto& w : wait_handles_of(index, all())) { auto const ww = wait_handle(index, w); auto const www = wait_handle(index, ww); EXPECT_EQ(wait_handle_inner(www), ww); EXPECT_EQ(wait_handle_inner(ww), w); // Skip the following in cases like WaitH<WaitH<Obj>>, which // actually *is* a subtype of WaitH<Obj>, since a WaitH<Obj> is // also an Obj. Similar for Top, or InitCell, etc. auto const inner = wait_handle_inner(w); if (twhobj.subtypeOf(inner)) continue; EXPECT_FALSE(w.subtypeOf(ww)); EXPECT_FALSE(ww.subtypeOf(w)); EXPECT_FALSE(w.couldBe(ww)); EXPECT_TRUE(ww.subtypeOf(twhobj)); EXPECT_TRUE(www.subtypeOf(twhobj)); EXPECT_FALSE(ww.subtypeOf(www)); EXPECT_FALSE(www.subtypeOf(ww)); EXPECT_FALSE(ww.couldBe(www)); } } TEST(Type, FromHNIConstraint) { EXPECT_EQ(from_hni_constraint(makeStaticString("?HH\\resource")), TOptRes); EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\resource")), TRes); EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\bool")), TBool); EXPECT_EQ(from_hni_constraint(makeStaticString("?HH\\bool")), TOptBool); EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\int")), TInt); EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\float")), TDbl); EXPECT_EQ(from_hni_constraint(makeStaticString("?HH\\float")), TOptDbl); EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\mixed")), TInitGen); // These are conservative, but we're testing them that way. If we // make the function better later we'll remove the tests. EXPECT_EQ(from_hni_constraint(makeStaticString("stdClass")), TGen); EXPECT_EQ(from_hni_constraint(makeStaticString("?stdClass")), TGen); EXPECT_EQ(from_hni_constraint(makeStaticString("fooooo")), TGen); EXPECT_EQ(from_hni_constraint(makeStaticString("")), TGen); } TEST(Type, ArrPacked1) { auto const a1 = arr_packed({ival(2), TSStr, TInt}); auto const a2 = arr_packed({TInt, TStr, TInitCell}); auto const s1 = sarr_packed({ival(2), TSStr, TInt}); auto const s2 = sarr_packed({TInt, TStr, TInitCell}); auto const c1 = carr_packed({ival(2), TSStr, TInt}); auto const c2 = carr_packed({TInt, TStr, TInitCell}); for (auto& a : { a1, s1, c1, a2, s2, c2 }) { EXPECT_TRUE(a.subtypeOf(TArr)); EXPECT_TRUE(a.subtypeOf(a)); EXPECT_EQ(a, a); } // Subtype stuff. EXPECT_TRUE(a1.subtypeOf(TArr)); EXPECT_FALSE(a1.subtypeOf(TSArr)); EXPECT_FALSE(a1.subtypeOf(TCArr)); EXPECT_TRUE(s1.subtypeOf(TArr)); EXPECT_TRUE(s1.subtypeOf(TSArr)); EXPECT_FALSE(s1.subtypeOf(TCArr)); EXPECT_TRUE(c1.subtypeOf(TArr)); EXPECT_TRUE(c1.subtypeOf(TCArr)); EXPECT_FALSE(c1.subtypeOf(TSArr)); EXPECT_TRUE(a1.subtypeOf(a2)); EXPECT_TRUE(s1.subtypeOf(s2)); EXPECT_TRUE(c1.subtypeOf(c2)); EXPECT_TRUE(s1.subtypeOf(a1)); EXPECT_TRUE(c1.subtypeOf(a1)); EXPECT_FALSE(a1.subtypeOf(c1)); EXPECT_FALSE(s1.subtypeOf(c1)); EXPECT_FALSE(c1.subtypeOf(s1)); EXPECT_FALSE(a1.subtypeOf(c1)); // Could be stuff. EXPECT_TRUE(c1.couldBe(a1)); EXPECT_TRUE(c2.couldBe(a2)); EXPECT_TRUE(s1.couldBe(a1)); EXPECT_TRUE(s2.couldBe(a2)); EXPECT_TRUE(a1.couldBe(a2)); EXPECT_TRUE(a2.couldBe(a1)); EXPECT_TRUE(s1.couldBe(a2)); EXPECT_TRUE(s2.couldBe(a1)); EXPECT_TRUE(c1.couldBe(a2)); EXPECT_TRUE(c2.couldBe(a1)); EXPECT_TRUE(s1.couldBe(s2)); EXPECT_TRUE(s2.couldBe(s1)); EXPECT_TRUE(c1.couldBe(c2)); EXPECT_TRUE(c2.couldBe(c1)); EXPECT_FALSE(c1.couldBe(s1)); EXPECT_FALSE(c2.couldBe(s1)); EXPECT_FALSE(c1.couldBe(s2)); EXPECT_FALSE(c2.couldBe(s2)); EXPECT_FALSE(s1.couldBe(c1)); EXPECT_FALSE(s2.couldBe(c1)); EXPECT_FALSE(s1.couldBe(c2)); EXPECT_FALSE(s2.couldBe(c2)); } TEST(Type, OptArrPacked1) { auto const a1 = opt(arr_packed({ival(2), TSStr, TInt})); auto const a2 = opt(arr_packed({TInt, TStr, TInitCell})); auto const s1 = opt(sarr_packed({ival(2), TSStr, TInt})); auto const s2 = opt(sarr_packed({TInt, TStr, TInitCell})); auto const c1 = opt(carr_packed({ival(2), TSStr, TInt})); auto const c2 = opt(carr_packed({TInt, TStr, TInitCell})); for (auto& a : { a1, s1, c1, a2, s2, c2 }) { EXPECT_TRUE(a.subtypeOf(TOptArr)); EXPECT_TRUE(a.subtypeOf(a)); EXPECT_EQ(a, a); } // Subtype stuff. EXPECT_TRUE(a1.subtypeOf(TOptArr)); EXPECT_FALSE(a1.subtypeOf(TOptSArr)); EXPECT_FALSE(a1.subtypeOf(TOptCArr)); EXPECT_TRUE(s1.subtypeOf(TOptArr)); EXPECT_TRUE(s1.subtypeOf(TOptSArr)); EXPECT_FALSE(s1.subtypeOf(TOptCArr)); EXPECT_TRUE(c1.subtypeOf(TOptArr)); EXPECT_TRUE(c1.subtypeOf(TOptCArr)); EXPECT_FALSE(c1.subtypeOf(TOptSArr)); EXPECT_TRUE(a1.subtypeOf(a2)); EXPECT_TRUE(s1.subtypeOf(s2)); EXPECT_TRUE(c1.subtypeOf(c2)); EXPECT_TRUE(s1.subtypeOf(a1)); EXPECT_TRUE(c1.subtypeOf(a1)); EXPECT_FALSE(a1.subtypeOf(c1)); EXPECT_FALSE(s1.subtypeOf(c1)); EXPECT_FALSE(c1.subtypeOf(s1)); EXPECT_FALSE(a1.subtypeOf(c1)); // Could be stuff. EXPECT_TRUE(c1.couldBe(a1)); EXPECT_TRUE(c2.couldBe(a2)); EXPECT_TRUE(s1.couldBe(a1)); EXPECT_TRUE(s2.couldBe(a2)); EXPECT_TRUE(a1.couldBe(a2)); EXPECT_TRUE(a2.couldBe(a1)); EXPECT_TRUE(s1.couldBe(a2)); EXPECT_TRUE(s2.couldBe(a1)); EXPECT_TRUE(c1.couldBe(a2)); EXPECT_TRUE(c2.couldBe(a1)); EXPECT_TRUE(s1.couldBe(s2)); EXPECT_TRUE(s2.couldBe(s1)); EXPECT_TRUE(c1.couldBe(c2)); EXPECT_TRUE(c2.couldBe(c1)); EXPECT_TRUE(c1.couldBe(s1)); EXPECT_TRUE(c2.couldBe(s1)); EXPECT_TRUE(c1.couldBe(s2)); EXPECT_TRUE(c2.couldBe(s2)); EXPECT_TRUE(s1.couldBe(c1)); EXPECT_TRUE(s2.couldBe(c1)); EXPECT_TRUE(s1.couldBe(c2)); EXPECT_TRUE(s2.couldBe(c2)); } TEST(Type, ArrPacked2) { { auto const a1 = arr_packed({TInt, TInt, TDbl}); auto const a2 = arr_packed({TInt, TInt}); EXPECT_FALSE(a1.subtypeOf(a2)); EXPECT_FALSE(a1.couldBe(a2)); } { auto const a1 = arr_packed({TInitCell, TInt}); auto const a2 = arr_packed({TInt, TInt}); EXPECT_TRUE(a1.couldBe(a2)); EXPECT_TRUE(a2.subtypeOf(a1)); } { auto const a1 = arr_packed({TInt, TInt, TInt}); auto const s1 = sarr_packed({TInt, TInt, TInt}); auto const c1 = carr_packed({TInt, TInt, TInt}); auto const s2 = aval(test_array_packed_value()); EXPECT_TRUE(s2.subtypeOf(a1)); EXPECT_TRUE(s2.subtypeOf(s1)); EXPECT_FALSE(s2.subtypeOf(c1)); EXPECT_TRUE(s2.couldBe(a1)); EXPECT_TRUE(s2.couldBe(s1)); EXPECT_FALSE(s2.couldBe(c1)); } { auto const s1 = sarr_packed({ival(42), ival(23), ival(12)}); auto const s2 = aval(test_array_packed_value()); auto const s3 = sarr_packed({TInt}); auto const a4 = sarr_packed({TInt}); auto const a5 = arr_packed({ival(42), ival(23), ival(12)}); auto const c6 = carr_packed({ival(42), ival(23), ival(12)}); EXPECT_TRUE(s1.subtypeOf(s2)); EXPECT_EQ(s1, s2); EXPECT_FALSE(s2.subtypeOf(s3)); EXPECT_FALSE(s2.couldBe(s3)); EXPECT_FALSE(s2.subtypeOf(s3)); EXPECT_FALSE(s2.couldBe(s3)); EXPECT_TRUE(s2.couldBe(s1)); EXPECT_TRUE(s2.couldBe(a5)); EXPECT_TRUE(s2.subtypeOf(a5)); EXPECT_FALSE(a5.subtypeOf(s2)); EXPECT_FALSE(s2.subtypeOf(c6)); EXPECT_FALSE(c6.subtypeOf(s2)); } } TEST(Type, ArrPackedUnion) { { auto const a1 = arr_packed({TInt, TDbl}); auto const a2 = arr_packed({TDbl, TInt}); EXPECT_EQ(union_of(a1, a2), arr_packed({TNum, TNum})); } { auto const s1 = sarr_packed({TInt, TDbl}); auto const s2 = sarr_packed({TDbl, TInt}); auto const c2 = carr_packed({TDbl, TInt}); EXPECT_EQ(union_of(s1, c2), arr_packed({TNum, TNum})); EXPECT_EQ(union_of(s1, s1), s1); EXPECT_EQ(union_of(s1, s2), sarr_packed({TNum, TNum})); } { auto const s1 = sarr_packed({TInt}); auto const s2 = sarr_packed({TDbl, TDbl}); EXPECT_EQ(union_of(s1, s2), sarr_packedn(TNum)); } { auto const s1 = aval(test_array_packed_value()); auto const s2 = sarr_packed({TInt, TInt, TInt}); auto const s3 = sarr_packed({TInt, TNum, TInt}); auto const s4 = carr_packed({TInt, TObj, TInt}); EXPECT_EQ(union_of(s1, s2), s2); EXPECT_EQ(union_of(s1, s3), s3); EXPECT_EQ(union_of(s1, s4), arr_packed({TInt, TInitCell, TInt})); } { auto const s1 = sarr_packed({TInt}); auto const os1 = opt(s1); EXPECT_EQ(union_of(s1, TInitNull), os1); EXPECT_EQ(union_of(os1, s1), os1); EXPECT_EQ(union_of(TInitNull, s1), os1); EXPECT_EQ(union_of(os1, os1), os1); } { auto const s1 = sarr_packed({TInt}); EXPECT_EQ(union_of(s1, TObj), TInitCell); EXPECT_EQ(union_of(s1, TCArr), TArr); } { auto const s1 = aval(test_array_packed_value()); auto const s2 = aval(test_array_packed_value2()); EXPECT_EQ(union_of(s1, s2), sarr_packed({ival(42), TNum, ival(12)})); } } TEST(Type, ArrPackedN) { auto const s1 = aval(test_array_packed_value()); auto const s2 = sarr_packed({TInt, TInt}); EXPECT_EQ(union_of(s1, s2), sarr_packedn(TInt)); EXPECT_TRUE(s2.subtypeOf(sarr_packedn(TInt))); EXPECT_FALSE(s2.subtypeOf(sarr_packedn(TDbl))); EXPECT_TRUE(s2.subtypeOf(sarr_packedn(TNum))); EXPECT_TRUE(s2.subtypeOf(arr_packedn(TInt))); EXPECT_TRUE(s2.subtypeOf(opt(arr_packedn(TInt)))); EXPECT_TRUE(s2.couldBe(arr_packedn(TInt))); EXPECT_TRUE(s2.couldBe(arr_packedn(TInitGen))); auto const sn1 = sarr_packedn(TInt); auto const sn2 = sarr_packedn(TInitNull); EXPECT_EQ(union_of(sn1, sn2), sarr_packedn(TOptInt)); EXPECT_EQ(union_of(sn1, TInitNull), opt(sn1)); EXPECT_EQ(union_of(TInitNull, sn1), opt(sn1)); EXPECT_FALSE(sn2.couldBe(sn1)); EXPECT_FALSE(sn1.couldBe(sn2)); auto const sn3 = sarr_packedn(TInitCell); EXPECT_TRUE(sn1.couldBe(sn3)); EXPECT_TRUE(sn2.couldBe(sn3)); EXPECT_TRUE(sn3.couldBe(sn1)); EXPECT_TRUE(sn3.couldBe(sn2)); EXPECT_TRUE(s2.couldBe(sn3)); EXPECT_TRUE(s2.couldBe(sn1)); EXPECT_FALSE(s2.couldBe(sn2)); EXPECT_EQ(union_of(carr_packedn(TInt), sarr_packedn(TInt)), arr_packedn(TInt)); } TEST(Type, ArrStruct) { auto test_map_a = StructMap{}; test_map_a[s_test.get()] = ival(2); auto test_map_b = StructMap{}; test_map_b[s_test.get()] = TInt; auto test_map_c = StructMap{}; test_map_c[s_test.get()] = ival(2); test_map_c[s_A.get()] = TInt; test_map_c[s_B.get()] = TDbl; auto const ta = arr_struct(test_map_a); auto const tb = arr_struct(test_map_b); auto const tc = arr_struct(test_map_c); EXPECT_FALSE(ta.subtypeOf(tc)); EXPECT_FALSE(tc.subtypeOf(ta)); EXPECT_TRUE(ta.subtypeOf(tb)); EXPECT_FALSE(tb.subtypeOf(ta)); EXPECT_TRUE(ta.couldBe(tb)); EXPECT_TRUE(tb.couldBe(ta)); EXPECT_FALSE(tc.couldBe(ta)); EXPECT_FALSE(tc.couldBe(tb)); EXPECT_TRUE(ta.subtypeOf(TArr)); EXPECT_TRUE(tb.subtypeOf(TArr)); EXPECT_TRUE(tc.subtypeOf(TArr)); auto const sa = sarr_struct(test_map_a); auto const sb = sarr_struct(test_map_b); auto const sc = sarr_struct(test_map_c); EXPECT_FALSE(sa.subtypeOf(sc)); EXPECT_FALSE(sc.subtypeOf(sa)); EXPECT_TRUE(sa.subtypeOf(sb)); EXPECT_FALSE(sb.subtypeOf(sa)); EXPECT_TRUE(sa.couldBe(sb)); EXPECT_TRUE(sb.couldBe(sa)); EXPECT_FALSE(sc.couldBe(sa)); EXPECT_FALSE(sc.couldBe(sb)); EXPECT_TRUE(sa.subtypeOf(TSArr)); EXPECT_TRUE(sb.subtypeOf(TSArr)); EXPECT_TRUE(sc.subtypeOf(TSArr)); auto test_map_d = StructMap{}; test_map_d[s_A.get()] = sval(s_B.get()); test_map_d[s_test.get()] = ival(12); auto const sd = sarr_struct(test_map_d); EXPECT_EQ(sd, aval(test_array_map_value())); auto test_map_e = StructMap{}; test_map_e[s_A.get()] = TSStr; test_map_e[s_test.get()] = TNum; auto const se = sarr_struct(test_map_e); EXPECT_TRUE(aval(test_array_map_value()).subtypeOf(se)); EXPECT_TRUE(se.couldBe(aval(test_array_map_value()))); } TEST(Type, ArrMapN) { auto const test_map = aval(test_array_map_value()); EXPECT_TRUE(test_map != arr_mapn(TSStr, TInitUnc)); EXPECT_TRUE(test_map.subtypeOf(arr_mapn(TSStr, TInitUnc))); EXPECT_TRUE(test_map.subtypeOf(sarr_mapn(TSStr, TInitUnc))); EXPECT_TRUE(!test_map.subtypeOf(carr_mapn(TSStr, TInitUnc))); EXPECT_TRUE(sarr_packedn({TInt}).subtypeOf(arr_mapn(TInt, TInt))); EXPECT_TRUE(sarr_packed({TInt}).subtypeOf(arr_mapn(TInt, TInt))); auto test_map_a = StructMap{}; test_map_a[s_test.get()] = ival(2); auto const tstruct = sarr_struct(test_map_a); EXPECT_TRUE(tstruct.subtypeOf(arr_mapn(TSStr, ival(2)))); EXPECT_TRUE(tstruct.subtypeOf(arr_mapn(TSStr, TInt))); EXPECT_TRUE(tstruct.subtypeOf(sarr_mapn(TSStr, TInt))); EXPECT_TRUE(tstruct.subtypeOf(arr_mapn(TStr, TInt))); EXPECT_TRUE(!tstruct.subtypeOf(carr_mapn(TStr, TInt))); EXPECT_TRUE(test_map.couldBe(arr_mapn(TSStr, TInitCell))); EXPECT_FALSE(test_map.couldBe(arr_mapn(TSStr, TCStr))); EXPECT_FALSE(test_map.couldBe(arr_mapn(TSStr, TObj))); EXPECT_FALSE(test_map.couldBe(aval(test_empty_array()))); EXPECT_FALSE(arr_mapn(TSStr, TInt).couldBe(aval(test_empty_array()))); EXPECT_TRUE(sarr_packedn(TInt).couldBe(sarr_mapn(TInt, TInt))); EXPECT_FALSE(sarr_packedn(TInt).couldBe(sarr_mapn(TInt, TObj))); EXPECT_TRUE(tstruct.couldBe(sarr_mapn(TSStr, TInt))); EXPECT_FALSE(tstruct.couldBe(sarr_mapn(TSStr, TObj))); EXPECT_FALSE(tstruct.couldBe(carr_mapn(TSStr, TObj))); EXPECT_FALSE(tstruct.couldBe(carr_mapn(TSStr, TInt))); } TEST(Type, ArrEquivalentRepresentations) { { auto const simple = aval(test_array_packed_value()); auto const bulky = sarr_packed({ival(42), ival(23), ival(12)}); EXPECT_EQ(simple, bulky); } { auto const simple = aval(test_array_map_value()); auto map = StructMap{}; map[s_A.get()] = sval(s_B.get()); map[s_test.get()] = ival(12); auto const bulky = sarr_struct(map); EXPECT_EQ(simple, bulky); } } TEST(Type, ArrUnions) { auto test_map_a = StructMap{}; test_map_a[s_test.get()] = ival(2); auto const tstruct = sarr_struct(test_map_a); auto test_map_b = StructMap{}; test_map_b[s_test.get()] = TInt; auto const tstruct2 = sarr_struct(test_map_b); auto test_map_c = StructMap{}; test_map_c[s_A.get()] = TInt; auto const tstruct3 = sarr_struct(test_map_c); auto test_map_d = StructMap{}; test_map_d[s_A.get()] = TInt; test_map_d[s_test.get()] = TDbl; auto const tstruct4 = sarr_struct(test_map_d); auto const packed_int = arr_packedn(TInt); EXPECT_EQ(union_of(tstruct, packed_int), arr_mapn(union_of(TSStr, TInt), TInt)); EXPECT_EQ(union_of(tstruct, tstruct2), tstruct2); EXPECT_EQ(union_of(tstruct, tstruct3), sarr_mapn(TSStr, TInt)); EXPECT_EQ(union_of(tstruct, tstruct4), sarr_mapn(TSStr, TNum)); EXPECT_EQ(union_of(sarr_packed({TInt, TDbl, TDbl}), sarr_packedn(TDbl)), sarr_packedn(TNum)); EXPECT_EQ(union_of(sarr_packed({TInt, TDbl}), tstruct), sarr_mapn(union_of(TSStr, TInt), TNum)); EXPECT_EQ(union_of(arr_mapn(TInt, TTrue), arr_mapn(TDbl, TFalse)), arr_mapn(TNum, TBool)); auto const aval1 = aval(test_array_packed_value()); auto const aval2 = aval(test_array_packed_value3()); EXPECT_EQ(union_of(aval1, aval2), sarr_packedn(TInt)); } TEST(Type, ArrOfArr) { auto const t1 = arr_mapn(TSStr, arr_mapn(TInt, TSStr)); auto const t2 = arr_mapn(TSStr, TArr); auto const t3 = arr_mapn(TSStr, arr_packedn(TSStr)); auto const t4 = arr_mapn(TSStr, arr_mapn(TSStr, TSStr)); EXPECT_TRUE(t1.subtypeOf(t2)); EXPECT_TRUE(t1.couldBe(t3)); EXPECT_FALSE(t1.subtypeOf(t3)); EXPECT_TRUE(t3.subtypeOf(t1)); EXPECT_TRUE(t3.subtypeOf(t2)); EXPECT_FALSE(t1.couldBe(t4)); EXPECT_FALSE(t4.couldBe(t3)); EXPECT_TRUE(t4.subtypeOf(t2)); } TEST(Type, WideningAlreadyStable) { // A widening union on types that are already stable should not move // the type anywhere. for (auto& t : all()) { EXPECT_EQ(widening_union(t, t), t); } for (auto& t : specialized_array_examples()) { EXPECT_EQ(widening_union(t, t), t); } } TEST(Type, EmptyArray) { { auto const possible_e = union_of(arr_packedn(TInt), aempty()); EXPECT_TRUE(possible_e.couldBe(aempty())); EXPECT_TRUE(possible_e.couldBe(arr_packedn(TInt))); EXPECT_EQ(array_elem(possible_e, ival(0)), opt(TInt)); } { auto const possible_e = union_of(arr_packed({TInt, TInt}), aempty()); EXPECT_TRUE(possible_e.couldBe(aempty())); EXPECT_TRUE(possible_e.couldBe(arr_packed({TInt, TInt}))); EXPECT_FALSE(possible_e.couldBe(arr_packed({TInt, TInt, TInt}))); EXPECT_FALSE(possible_e.subtypeOf(arr_packedn(TInt))); EXPECT_EQ(array_elem(possible_e, ival(0)), opt(TInt)); EXPECT_EQ(array_elem(possible_e, ival(1)), opt(TInt)); } { auto const estat = union_of(sarr_packedn(TInt), aempty()); EXPECT_TRUE(estat.couldBe(aempty())); EXPECT_TRUE(estat.couldBe(sarr_packedn(TInt))); EXPECT_FALSE(estat.subtypeOf(sarr_packedn(TInt))); EXPECT_FALSE(estat.subtypeOf(TCArr)); EXPECT_FALSE(estat.couldBe(TCArr)); EXPECT_FALSE(estat.subtypeOf(TSArrE)); EXPECT_TRUE(estat.couldBe(TSArrE)); } EXPECT_EQ(array_newelem(aempty(), ival(142)), arr_packed({ival(142)})); } TEST(Type, BasicArrays) { EXPECT_TRUE(TSArr.subtypeOf(TArr)); EXPECT_TRUE(TCArr.subtypeOf(TArr)); EXPECT_TRUE(TArrE.subtypeOf(TArr)); EXPECT_TRUE(TArrN.subtypeOf(TArr)); EXPECT_TRUE(TSArrE.subtypeOf(TArr)); EXPECT_TRUE(TSArrN.subtypeOf(TArr)); EXPECT_TRUE(TCArrE.subtypeOf(TArr)); EXPECT_TRUE(TCArrN.subtypeOf(TArr)); EXPECT_EQ(union_of(TSArr, TCArr), TArr); EXPECT_EQ(union_of(TSArrE, TCArrE), TArrE); EXPECT_EQ(union_of(TSArrN, TCArrN), TArrN); EXPECT_EQ(union_of(TArrN, TArrE), TArr); EXPECT_EQ(union_of(TSArrN, TCArrE), TArr); EXPECT_EQ(union_of(TSArrE, TCArrN), TArr); EXPECT_EQ(union_of(TOptCArrN, TSArrE), TOptArr); EXPECT_EQ(union_of(TOptSArr, TCArr), TOptArr); EXPECT_EQ(union_of(TOptSArrE, TCArrE), TOptArrE); EXPECT_EQ(union_of(TOptSArrN, TCArrN), TOptArrN); EXPECT_EQ(union_of(TOptArrN, TArrE), TOptArr); EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr); EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr); EXPECT_EQ(union_of(TOptSArr, TOptCArr), TOptArr); EXPECT_EQ(union_of(TOptSArrE, TOptCArrE), TOptArrE); EXPECT_EQ(union_of(TOptSArrN, TOptCArrN), TOptArrN); EXPECT_EQ(union_of(TOptArrN, TOptArrE), TOptArr); EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr); EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr); EXPECT_EQ(union_of(TSArr, TInitNull), TOptSArr); EXPECT_EQ(union_of(TSArrE, TInitNull), TOptSArrE); EXPECT_EQ(union_of(TSArrN, TInitNull), TOptSArrN); EXPECT_EQ(union_of(TCArr, TInitNull), TOptCArr); EXPECT_EQ(union_of(TCArrE, TInitNull), TOptCArrE); EXPECT_EQ(union_of(TCArrN, TInitNull), TOptCArrN); EXPECT_EQ(union_of(TArr, TInitNull), TOptArr); EXPECT_EQ(union_of(TArrE, TInitNull), TOptArrE); EXPECT_EQ(union_of(TArrN, TInitNull), TOptArrN); } /* * These are tests for some unrepresentable bit combos. If we ever * add predefined bits for things like TSArrE|TCArrN these will fail * and need to be revisted. */ TEST(Type, ArrBitCombos) { auto const u1 = union_of(sarr_packedn(TInt), TCArrE); EXPECT_TRUE(u1.couldBe(TArrE)); EXPECT_TRUE(u1.couldBe(TSArrE)); EXPECT_TRUE(u1.couldBe(TCArrE)); EXPECT_TRUE(u1.couldBe(sarr_packedn(TInt))); EXPECT_EQ(array_elem(u1, ival(0)), TOptInt); auto const u2 = union_of(TSArrE, carr_packedn(TInt)); EXPECT_TRUE(u2.couldBe(TArrE)); EXPECT_TRUE(u2.couldBe(TSArrE)); EXPECT_TRUE(u2.couldBe(TCArrE)); EXPECT_TRUE(u2.couldBe(arr_packedn(TInt))); EXPECT_EQ(array_elem(u2, ival(0)), TOptInt); } ////////////////////////////////////////////////////////////////////// }}
70,741
30,470