text
stringlengths
1
1.05M
; A014206: a(n) = n^2 + n + 2. ; 2,4,8,14,22,32,44,58,74,92,112,134,158,184,212,242,274,308,344,382,422,464,508,554,602,652,704,758,814,872,932,994,1058,1124,1192,1262,1334,1408,1484,1562,1642,1724,1808,1894,1982,2072,2164,2258,2354,2452,2552,2654,2758,2864,2972,3082,3194,3308,3424,3542,3662,3784,3908,4034,4162,4292,4424,4558,4694,4832,4972,5114,5258,5404,5552,5702,5854,6008,6164,6322,6482,6644,6808,6974,7142,7312,7484,7658,7834,8012,8192,8374,8558,8744,8932,9122,9314,9508,9704,9902,10102,10304,10508,10714,10922,11132,11344,11558,11774,11992,12212,12434,12658,12884,13112,13342,13574,13808,14044,14282,14522,14764,15008,15254,15502,15752,16004,16258,16514,16772,17032,17294,17558,17824,18092,18362,18634,18908,19184,19462,19742,20024,20308,20594,20882,21172,21464,21758,22054,22352,22652,22954,23258,23564,23872,24182,24494,24808,25124,25442,25762,26084,26408,26734,27062,27392,27724,28058,28394,28732,29072,29414,29758,30104,30452,30802,31154,31508,31864,32222,32582,32944,33308,33674,34042,34412,34784,35158,35534,35912,36292,36674,37058,37444,37832,38222,38614,39008,39404,39802,40202,40604,41008,41414,41822,42232,42644,43058,43474,43892,44312,44734,45158,45584,46012,46442,46874,47308,47744,48182,48622,49064,49508,49954,50402,50852,51304,51758,52214,52672,53132,53594,54058,54524,54992,55462,55934,56408,56884,57362,57842,58324,58808,59294,59782,60272,60764,61258,61754,62252 mov $1,$0 mul $1,$0 add $1,$0 add $1,2
SFX_Cry13_2_Ch5: duty_cycle_pattern 0, 3, 0, 3 square_note 15, 15, 6, 1472 square_note 8, 14, 3, 1468 square_note 6, 13, 2, 1488 square_note 6, 11, 2, 1504 square_note 6, 12, 2, 1520 square_note 8, 11, 1, 1536 sound_ret SFX_Cry13_2_Ch6: duty_cycle_pattern 2, 1, 2, 1 square_note 14, 12, 6, 1201 square_note 7, 12, 3, 1197 square_note 5, 11, 2, 1217 square_note 8, 9, 2, 1233 square_note 6, 10, 2, 1249 square_note 8, 9, 1, 1265 sound_ret SFX_Cry13_2_Ch8: noise_note 10, 14, 6, 92 noise_note 10, 13, 6, 108 noise_note 4, 12, 2, 76 noise_note 6, 13, 3, 92 noise_note 8, 11, 3, 76 noise_note 8, 10, 1, 92 sound_ret
; A089792: a(n) = n-(exponent of highest power of 3 dividing n!). ; 0,1,2,2,3,4,4,5,6,5,6,7,7,8,9,9,10,11,10,11,12,12,13,14,14,15,16,14,15,16,16,17,18,18,19,20,19,20,21,21,22,23,23,24,25,24,25,26,26,27,28,28,29,30,28,29,30,30,31,32,32,33,34,33 mov $1,$0 lpb $1,1 div $0,3 sub $1,$0 lpe
/*========================================================================= Program: Visualization Toolkit Module: vtkTemporalDataSetCache.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTemporalDataSetCache.h" #include "vtkCompositeDataIterator.h" #include "vtkCompositeDataPipeline.h" #include "vtkCompositeDataSet.h" #include "vtkFeatures.h" // for VTK_USE_MEMKIND #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" #include "vtkStreamingDemandDrivenPipeline.h" #include <algorithm> #include <vector> // A helper class to to turn on memkind, if enabled, while ensuring it always is restored class vtkTDSCMemkindRAII { #ifdef VTK_USE_MEMKIND bool OriginalValue = false; #endif public: vtkTDSCMemkindRAII(vtkTemporalDataSetCache* owner) { #ifdef VTK_USE_MEMKIND this->OriginalValue = vtkObjectBase::GetUsingMemkind(); if (owner->GetCacheInMemkind()) { vtkObjectBase::SetUsingMemkind(true); } #else (void)owner; #endif } #ifdef VTK_USE_MEMKIND ~vtkTDSCMemkindRAII() { vtkObjectBase::SetUsingMemkind(this->OriginalValue); } #else ~vtkTDSCMemkindRAII() = default; #endif vtkTDSCMemkindRAII(vtkTDSCMemkindRAII const&) = default; }; //------------------------------------------------------------------------------ vtkStandardNewMacro(vtkTemporalDataSetCache); //------------------------------------------------------------------------------ vtkTemporalDataSetCache::vtkTemporalDataSetCache() { this->CacheSize = 10; this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); this->CacheInMemkind = false; this->IsASource = false; this->Ejected = nullptr; } //------------------------------------------------------------------------------ vtkTemporalDataSetCache::~vtkTemporalDataSetCache() { CacheType::iterator pos = this->Cache.begin(); for (; pos != this->Cache.end();) { pos->second.second->UnRegister(this); this->Cache.erase(pos++); } this->SetEjected(nullptr); } //------------------------------------------------------------------------------ vtkTypeBool vtkTemporalDataSetCache::ProcessRequest( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // create the output if (request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT())) { return this->RequestDataObject(request, inputVector, outputVector); } // generate the data if (request->Has(vtkCompositeDataPipeline::REQUEST_DATA())) { int retVal = this->RequestData(request, inputVector, outputVector); return retVal; } // set update extent if (request->Has(vtkCompositeDataPipeline::REQUEST_UPDATE_EXTENT())) { return this->RequestUpdateExtent(request, inputVector, outputVector); } // when acting as a source, provide extents if (request->Has(vtkCompositeDataPipeline::REQUEST_INFORMATION())) { if (this->IsASource) { return this->RequestInformation(request, inputVector, outputVector); } } return this->Superclass::ProcessRequest(request, inputVector, outputVector); } //------------------------------------------------------------------------------ int vtkTemporalDataSetCache::FillInputPortInformation(int port, vtkInformation* info) { // port 0 must be temporal data, but port 1 can be any dataset if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject"); } return 1; } int vtkTemporalDataSetCache::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataObject"); return 1; } //------------------------------------------------------------------------------ void vtkTemporalDataSetCache::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "CacheSize: " << this->CacheSize << endl; } //------------------------------------------------------------------------------ void vtkTemporalDataSetCache::SetCacheSize(int size) { if (size < 1) { vtkErrorMacro("Attempt to set cache size to less than 1"); return; } // if growing the cache, there is no need to do anything this->CacheSize = size; if (this->Cache.size() <= static_cast<unsigned long>(size)) { return; } // skrinking, have to get rid of some old data, to be easy just chuck the // first entries int i = static_cast<int>(this->Cache.size()) - size; CacheType::iterator pos = this->Cache.begin(); for (; i > 0; --i) { pos->second.second->UnRegister(this); this->Cache.erase(pos++); } } //------------------------------------------------------------------------------ int vtkTemporalDataSetCache::RequestInformation( vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkDataObject* dobj = inInfo->Get(vtkDataObject::DATA_OBJECT()); bool hasInTime = false; double inTime = 0.0; if (dobj) { if (dobj->GetInformation()->Has(vtkDataObject::DATA_TIME_STEP())) { inTime = dobj->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP()); hasInTime = true; } } this->TimeStepValues.clear(); size_t numTimeStepValues = this->Cache.size(); if (numTimeStepValues <= 0) { return 1; } CacheType::iterator pos = this->Cache.begin(); double min = pos->first; double max = pos->first; for (; pos != this->Cache.end();) { this->TimeStepValues.push_back(pos->first); if (pos->first < min) { min = pos->first; } if (pos->first > max) { max = pos->first; } if (hasInTime && pos->first == inTime) { hasInTime = false; } pos++; } if (hasInTime) { // cache doesn't contain our input, but it will when we are asked later // so announce it's time too if (inTime < min) { min = inTime; } if (inTime > max) { max = inTime; } this->TimeStepValues.push_back(inTime); } std::sort(this->TimeStepValues.begin(), this->TimeStepValues.end()); vtkInformation* info = outputVector->GetInformationObject(0); // tell the caller that I can provide time varying data and // tell it what range of times I can deal with double tRange[2]; tRange[0] = this->TimeStepValues[0]; tRange[1] = this->TimeStepValues[this->TimeStepValues.size() - 1]; info->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), tRange, 2); // tell the caller what the specific values are info->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &this->TimeStepValues[0], static_cast<int>(this->TimeStepValues.size())); // if we are caching structured data, we need to provide topological extents pos = this->Cache.begin(); if (pos != this->Cache.end()) { vtkImageData* id = vtkImageData::SafeDownCast(pos->second.second); if (id) { // as an ID double* origin = id->GetOrigin(); int* extent = id->GetExtent(); double* spacing = id->GetSpacing(); info->Set(vtkDataObject::ORIGIN(), origin, 3); info->Set(vtkDataObject::SPACING(), spacing, 3); info->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent, 6); } } return 1; } //------------------------------------------------------------------------------ int vtkTemporalDataSetCache::RequestDataObject( vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if (this->GetNumberOfInputPorts() == 0 || this->GetNumberOfOutputPorts() == 0) { return 1; } vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); if (!inInfo) { return 0; } vtkDataObject* input = inInfo->Get(vtkDataObject::DATA_OBJECT()); if (input) { // for each output for (int i = 0; i < this->GetNumberOfOutputPorts(); ++i) { vtkInformation* info = outputVector->GetInformationObject(i); vtkDataObject* output = info->Get(vtkDataObject::DATA_OBJECT()); if (!output || !output->IsA(input->GetClassName())) { vtkTDSCMemkindRAII(this); vtkDataObject* newOutput = input->NewInstance(); info->Set(vtkDataObject::DATA_OBJECT(), newOutput); newOutput->Delete(); } } return 1; } return 0; } //------------------------------------------------------------------------------ int vtkTemporalDataSetCache ::RequestUpdateExtent(vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // get the info objects vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); // First look through the cached data to see if it is still valid. CacheType::iterator pos; vtkDemandDrivenPipeline* ddp = vtkDemandDrivenPipeline::SafeDownCast(this->GetExecutive()); if (!ddp) { return 1; } if (!this->IsASource) { vtkMTimeType pmt = ddp->GetPipelineMTime(); for (pos = this->Cache.begin(); pos != this->Cache.end();) { if (pos->second.first < pmt) { pos->second.second->Delete(); this->Cache.erase(pos++); } else { ++pos; } } } // are there any times that we are missing from the request? e.g. times // that are not cached? std::vector<double> reqTimeSteps; if (!outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) { // no time steps were passed in the update request, so just request // something to keep the pipeline happy. if (inInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS())) { int NumberOfInputTimeSteps = inInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); // // Get list of input time step values std::vector<double> InputTimeValues; InputTimeValues.resize(NumberOfInputTimeSteps); inInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &InputTimeValues[0]); // this should be the same, just checking for debug purposes reqTimeSteps.push_back(InputTimeValues[0]); } else return 0; } if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) { double upTime = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); // do we have this time step? pos = this->Cache.find(upTime); if (pos == this->Cache.end()) { reqTimeSteps.push_back(upTime); } // if we need any data if (!reqTimeSteps.empty()) { inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(), reqTimeSteps[0]); } // otherwise leave the input with what it already has else { vtkDataObject* dobj = inInfo->Get(vtkDataObject::DATA_OBJECT()); if (dobj) { double it = dobj->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP()); if (dobj->GetInformation()->Has(vtkDataObject::DATA_TIME_STEP())) { inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(), it); } } } } return 1; } //------------------------------------------------------------------------------ // This method simply copies by reference the input data to the output. int vtkTemporalDataSetCache::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkMTimeType outputUpdateTime = outInfo->Get(vtkDataObject::DATA_OBJECT())->GetUpdateTime(); vtkDataObject* input = inInfo->Get(vtkDataObject::DATA_OBJECT()); // get some time informationX double upTime = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); double inTime = input->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP()); vtkSmartPointer<vtkDataObject> output; // a time should either be in the Cache or in the input CacheType::iterator pos = this->Cache.find(upTime); if (pos != this->Cache.end()) { vtkTDSCMemkindRAII(this); vtkDataObject* cachedData = pos->second.second; output.TakeReference(cachedData->NewInstance()); output->ShallowCopy(cachedData); // update the m time in the cache pos->second.first = outputUpdateTime; } // otherwise it better be in the input else { if (input->GetInformation()->Has(vtkDataObject::DATA_TIME_STEP())) { if (inTime == upTime) { vtkTDSCMemkindRAII(this); output.TakeReference(input->NewInstance()); output->ShallowCopy(input); } else { output = this->GetEjected()->NewInstance(); output->ShallowCopy(this->GetEjected()); } } else { // just shallow copy input to output output.TakeReference(input->NewInstance()); output->ShallowCopy(input); } } // set the data times outInfo->Set(vtkDataObject::DATA_OBJECT(), output); output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(), upTime); // now we need to update the cache, based on the new data and the cache // size add the requested data to the cache first if (input->GetInformation()->Has(vtkDataObject::DATA_TIME_STEP())) { // nothing to do if the input time is already in the cache CacheType::iterator pos1 = this->Cache.find(inTime); if (pos1 == this->Cache.end()) { // if we have room in the Cache then just add the new data if (this->Cache.size() < static_cast<unsigned long>(this->CacheSize)) { this->ReplaceCacheItem(input, inTime, outputUpdateTime); } // if there is no room in the cache, we need to get rid of something else { // get rid of the oldest data in the cache CacheType::iterator pos2 = this->Cache.begin(); CacheType::iterator oldestpos = this->Cache.begin(); for (; pos2 != this->Cache.end(); ++pos2) { if (pos2->second.first < oldestpos->second.first) { oldestpos = pos2; } } // was there old data? if (oldestpos->second.first < outputUpdateTime) { this->SetEjected(oldestpos->second.second); oldestpos->second.second->UnRegister(this); this->Cache.erase(oldestpos); this->ReplaceCacheItem(input, inTime, outputUpdateTime); } else { // if no old data and no room then we are done } } } } return 1; } //------------------------------------------------------------------------------ void vtkTemporalDataSetCache::ReplaceCacheItem( vtkDataObject* input, double inTime, vtkMTimeType outputUpdateTime) { vtkTDSCMemkindRAII(this); vtkDataObject* cachedData = input->NewInstance(); if (input->GetUsingMemkind() && !this->IsASource) { cachedData->ShallowCopy(input); } else { if (this->GetCacheInMemkind()) { cachedData->DeepCopy(input); } else { cachedData->ShallowCopy(input); } } this->Cache[inTime] = std::pair<unsigned long, vtkDataObject*>(outputUpdateTime, cachedData); } //------------------------------------------------------------------------------ void vtkTemporalDataSetCache::SetEjected(vtkDataObject* victim) { if (this->Ejected != victim) { vtkDataObject* tmp = this->Ejected; this->Ejected = victim; if (this->Ejected != nullptr) { this->Ejected->Register(this); } if (tmp != nullptr) { tmp->UnRegister(this); } // this->Modified(); //this is only thing we are changing from the macro } }
#note: r40 (the exception handler) and r46 (the start of usermode code) must #be specified in hex (0xwhatever) #I just don't see any reason not to, and it makes programming the script #much nicer to deal with... #load exception handler lc r40, 0x80000050 leh r40 #enable exceptions cle #load TLB entries #virtual page 0 is for instructions #virtual page 1 is for data lc r46, 0x0000005c #usermode start address lc r47, 1 #interrupts off lc r48, 1 #in user mode lc r42, 0x00000000 #denotes VPN 0 lc r43, 0x0000000d #denotes VPN 0 maps to physical page 0 #and is fetchable, readable, and valid tlbse r0, r42 #load into entry 0 lc r42, 0x00001000 #denotes VPN 1 lc r43, 0x0000101e #denotes VPN 1 maps to physical page 1 #and is readable, writable, valid, and dirty #(dirty to prevent taking a #read-only exception) tlbse r48, r42 #load into entry 1 #this last tlb entry is designed to produce a bus error lc r44, 2 #load into TLB entry 2 lc r42, 0x3fffe000 #denotes VPN 0x3fffe lc r43, 0x3fffe01f #map VPN 0x3fffe to page 0x3fffe #and is readable, writable, valid, and dirty #(dirty to prevent taking a #read-only exception) tlbse r44, r42 #warp to user mode rfe r46, r47, r48 #handle exceptions lc r49, 0xdeadbeef halt #or rather don't =) lc r30, 1 jez e2, r30, r30 trap #@expected values #e3 = 0x000000a0 #mode = S #interrupts = off #exceptions = off #r40 = 0x80000050 #r46 = 0x0000005c #r47 = 1 #r48 = 1 #r42 = 0x3fffe000 #r43 = 0x3fffe01f #r44 = 2 #r49 = 0xdeadbeef #pc = 0x8000005c #e0 = 0x00000060 #e2 = 0x00000060 #e1 = 0x00000001 #tlb 0: # vpn = 0x00000 # os = 0x000 # ppn = 0x00000 # at = 0x00d #tlb 1: # vpn = 0x00001 # os = 0x000 # ppn = 0x00001 # at = 0x01e #tlb 2: # vpn = 0x3fffe # os = 0x000 # ppn = 0x3fffe # at = 0x01f
; Z88 Small C+ Run time Library ; l_gint variant to be used sometimes by the peephole optimizer ; SECTION code_crt0_sccz80 PUBLIC l_gintspsp .l_gintspsp add hl,sp inc hl inc hl ld a,(hl) inc hl ld h,(hl) ld l,a ex (sp),hl jp (hl)
#include "copier.h" // static mutex initialization; will replace with a more elegant solution eventually std::mutex Copier::copy_lock{}; // default constructor Copier::Copier() { currentException = nullptr; status = false; } // destructor Copier::~Copier() { } // get source filename std::string Copier::GetSource() { return source; } // set source filename void Copier::SetSource(const std::string& filename) { source = filename; } // get destination filename std::string Copier::GetDestination() { return destination; } // set destination filename void Copier::SetDestination(const std::string& filename) { destination = filename; } bool Copier::isFinished() { return status; } std::exception_ptr Copier::GetException() { return currentException; } // the function that this whole app exists to call bool Copier::CreateCopy() { // try block so it can fail gracefully try { // instantiate a lock_guard with the static mutex to avoid data races; heavy-handed solution std::lock_guard<std::mutex> lock(copy_lock); // instantiate input and output files and a string variable to transfer the data std::ifstream inFile{}; std::ofstream outFile{}; std::string line{}; // use input file as a resource handle for the opensource file inFile.open(source); // use output file as a resource handle for the open destination file outFile.open(destination); // while std::getline successfully reads a line from the source file, store it in the variable line while(std::getline(inFile, line)) { // write what is in the line variable to the destination file and append an endline character outFile << line << "\n"; } // close files via resource handles, just to be explicit (sorry, RAII) inFile.close(); outFile.close(); // return true if successfully completed status = true; } catch(std::exception& e) { currentException = std::current_exception(); } // return false, because function execution won't reach this point if it completed successfully return status; }
; A010139: Continued fraction for sqrt(53). ; 7,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3,14,3,1,1,3 seq $0,10186 ; Continued fraction for sqrt(125). sub $0,1 mul $0,2 add $2,$0 lpb $2 sub $0,1 div $2,6 lpe div $0,3 add $0,1
palette: db 0x00, 0x00, 0x00 db 0x02, 0x00, 0x00 db 0x03, 0x00, 0x00 db 0x05, 0x00, 0x00 db 0x06, 0x00, 0x00 db 0x08, 0x01, 0x00 db 0x0A, 0x01, 0x00 db 0x0B, 0x01, 0x00 db 0x0D, 0x01, 0x00 db 0x0E, 0x02, 0x00 db 0x10, 0x02, 0x00 db 0x12, 0x02, 0x00 db 0x13, 0x03, 0x00 db 0x15, 0x03, 0x00 db 0x16, 0x04, 0x00 db 0x18, 0x05, 0x00 db 0x1A, 0x05, 0x00 db 0x1B, 0x06, 0x00 db 0x1D, 0x07, 0x00 db 0x1E, 0x07, 0x00 db 0x20, 0x08, 0x00 db 0x21, 0x09, 0x00 db 0x23, 0x0A, 0x00 db 0x25, 0x0B, 0x00 db 0x26, 0x0C, 0x00 db 0x28, 0x0D, 0x00 db 0x29, 0x0E, 0x00 db 0x2B, 0x0F, 0x00 db 0x2D, 0x10, 0x00 db 0x2E, 0x11, 0x00 db 0x30, 0x12, 0x00 db 0x31, 0x13, 0x00 db 0x33, 0x15, 0x00 db 0x35, 0x16, 0x00 db 0x36, 0x17, 0x00 db 0x38, 0x19, 0x00 db 0x39, 0x1A, 0x00 db 0x3B, 0x1C, 0x00 db 0x3D, 0x1D, 0x00 db 0x3E, 0x1F, 0x00 db 0x3F, 0x20, 0x01 db 0x3F, 0x22, 0x02 db 0x3F, 0x23, 0x04 db 0x3F, 0x25, 0x06 db 0x3F, 0x26, 0x07 db 0x3F, 0x28, 0x09 db 0x3F, 0x29, 0x0A db 0x3F, 0x2A, 0x0C db 0x3F, 0x2C, 0x0E db 0x3F, 0x2D, 0x0F db 0x3F, 0x2E, 0x11 db 0x3F, 0x2F, 0x12 db 0x3F, 0x30, 0x14 db 0x3F, 0x31, 0x16 db 0x3F, 0x32, 0x17 db 0x3F, 0x33, 0x19 db 0x3F, 0x34, 0x1A db 0x3F, 0x35, 0x1C db 0x3F, 0x36, 0x1E db 0x3F, 0x37, 0x1F db 0x3F, 0x38, 0x21 db 0x3F, 0x38, 0x22 db 0x3F, 0x39, 0x24 db 0x3F, 0x3A, 0x25 db 0x3F, 0x3A, 0x27 db 0x3F, 0x3B, 0x29 db 0x3F, 0x3C, 0x2A db 0x3F, 0x3C, 0x2C db 0x3F, 0x3D, 0x2D db 0x3F, 0x3D, 0x2F db 0x3F, 0x3D, 0x31 db 0x3F, 0x3E, 0x32 db 0x3F, 0x3E, 0x34 db 0x3F, 0x3E, 0x35 db 0x3F, 0x3E, 0x37 db 0x3F, 0x3F, 0x39 db 0x3F, 0x3F, 0x3A db 0x3F, 0x3F, 0x3C db 0x3F, 0x3F, 0x3D db 0x3F, 0x3F, 0x3F
; Object Mappings Subtype Frame Arttile dbglistobj Obj_Ring, Map_Ring, 0, 0, make_art_tile($6BC,1,1) dbglistobj Obj_Monitor, Map_Monitor, 6, 0, make_art_tile($4C4,0,0) dbglistobj Obj_PathSwap, Map_PathSwap, 9, 1, make_art_tile($6BC,1,0) dbglistobj Obj_PathSwap, Map_PathSwap, $D, 5, make_art_tile($6BC,1,0) dbglistobj Obj_Spring, Map_Spring, $81, 0, make_art_tile($4A4,0,0) dbglistobj Obj_Spring, Map_Spring, $90, 3, make_art_tile($4B4,0,0) dbglistobj Obj_Spring, Map_Spring, $A0, 6, make_art_tile($4A4,0,0) dbglistobj Obj_Spikes, Map_Spikes, 3, 0, make_art_tile($200,0,0) dbglistobj Obj_Blaster, Map_Blaster, $80, 0, make_art_tile($506,1,0) dbglistobj Obj_TechnoSqueek, Map_TechnoSqueek, 0, 0, make_art_tile($52E,1,0) dbglistobj Obj_TechnoSqueek, Map_TechnoSqueek, 2, 0, make_art_tile($52E,1,0) dbglistobj Obj_TechnoSqueek, Map_TechnoSqueek, 4, 0, make_art_tile($52E,1,0) dbglistobj Obj_FBZSpringPlunger, Map_FBZEggCapsule, 0, 5, make_art_tile($000,0,0) dbglistobj Obj_FBZEggPrison, Map_FBZEggCapsule, 0, 0, make_art_tile($000,0,0) dbglistobj Obj_FBZEggPrison, Map_FBZEggCapsule, 1, 0, make_art_tile($000,0,0) dbglistobj Obj_FBZEggPrison, Map_FBZEggCapsule, 2, 0, make_art_tile($000,0,0) dbglistobj Obj_FBZFloatingPlatform, Map_FBZFloatingPlatform, $10, 0, make_art_tile($383,1,0) dbglistobj Obj_FBZFloatingPlatform, Map_FBZFloatingPlatform, $30, 0, make_art_tile($383,1,0) dbglistobj Obj_FBZFloatingPlatform, Map_FBZFloatingPlatform, $40, 0, make_art_tile($383,1,0) dbglistobj Obj_FBZ_ChainLink, Map_FBZChainLink, $1A, 0, make_art_tile($379,2,0) dbglistobj Obj_StillSprite, Map_StillSprites, $27, $27, make_art_tile($379,2,0) dbglistobj Obj_StillSprite, Map_StillSprites, $28, $28, make_art_tile($379,2,0) dbglistobj Obj_StillSprite, Map_StillSprites, $29, $29, make_art_tile($379,2,0) dbglistobj Obj_StillSprite, Map_StillSprites, $2A, $2A, make_art_tile($379,2,0) dbglistobj Obj_StillSprite, Map_StillSprites, $2B, $2B, make_art_tile($443,1,0) dbglistobj Obj_FBZMagneticSpikeBall, Map_FBZMagneticSpikeBall, 0, 0, make_art_tile($443,1,0) dbglistobj Obj_FBZMagneticSpikeBall, Map_FBZMagneticSpikeBall, $80, 1, make_art_tile($443,1,1) dbglistobj Obj_FBZMagneticSpikeBall, Map_FBZMagneticSpikeBall, $81, 5, make_art_tile($442,1,1) dbglistobj Obj_FBZMagneticPlatform, Map_FBZMagneticPlatform, $10, 4, make_art_tile($443,1,0) dbglistobj Obj_CorkFloor, Map_FBZCorkFloor, 1, 0, make_art_tile($43A,1,0) dbglistobj Obj_FBZBentPipe, Map_FBZBentPipe, 0, 0, make_art_tile($46B,1,0) dbglistobj Obj_FBZBentPipe, Map_FBZBentPipe, 1, 1, make_art_tile($46B,1,0) dbglistobj Obj_FBZBentPipe, Map_FBZBentPipe, 2, 2, make_art_tile($46B,1,0) dbglistobj Obj_FBZRotatingPlatform, Map_FBZRotatingPlatform, 0, 0, make_art_tile($46B,1,0) dbglistobj Obj_FBZDEZPlayerLauncher, Map_FBZDEZPlayerLauncher, 0, 0, make_art_tile($3B5,1,0) dbglistobj Obj_FBZDisappearingPlatform, Map_FBZDisappearingPlatform, 0, 0, make_art_tile($3BA,1,0) dbglistobj Obj_FBZScrewDoor, Map_FBZScrewDoor, 0, 0, make_art_tile($3D2,1,0) dbglistobj Obj_FBZScrewDoor, Map_FBZScrewDoor, $20, 4, make_art_tile($3D2,1,0) dbglistobj Obj_FBZScrewDoor, Map_FBZScrewDoor, $40, 8, make_art_tile($3D2,1,0) dbglistobj Obj_Button, Map_Button, 0, 2, make_art_tile($500,0,0) dbglistobj Obj_FBZPropeller, Map_FBZPropeller, 0, 0, make_art_tile($2E5,1,0) dbglistobj Obj_FBZPiston, Map_FBZPiston, $34, 0, make_art_tile($31B,1,0) dbglistobj Obj_FBZPlatformBlocks, Map_FBZPlatformBlocks, $14, 1, make_art_tile($40D,2,0) dbglistobj Obj_FBZMissileLauncher, Map_FBZMissileLauncher, 2, 0, make_art_tile($32B,1,1) dbglistobj Obj_FBZWallMissile, Map_FBZMissileLauncher, $10, 4, make_art_tile($32B,1,0) dbglistobj Obj_CollapsingBridge, Map_FBZCollapsingBridge, 8, 0, make_art_tile($001,2,0) dbglistobj Obj_FBZMine, Map_FBZMine, 0, 0, make_art_tile($40A,0,0) dbglistobj Obj_FBZFlamethrower, Map_FBZFlameThrower, 0, 1, make_art_tile($41D,0,0) dbglistobj Obj_FBZFlamethrower, Map_FBZFlameThrower, $C0, 3, make_art_tile($41D,0,0)
; A024702: a(n) = (prime(n)^2 - 1)/24. ; 1,2,5,7,12,15,22,35,40,57,70,77,92,117,145,155,187,210,222,260,287,330,392,425,442,477,495,532,672,715,782,805,925,950,1027,1107,1162,1247,1335,1365,1520,1552,1617,1650,1855,2072,2147,2185,2262,2380,2420,2625,2752,2882,3015,3060,3197,3290,3337,3577,3927,4030,4082,4187,4565,4732,5017,5075,5192,5370,5612,5797,5985,6112,6305,6567,6700,6970,7315,7385,7740,7812,8030,8177,8400,8702,8855,8932,9087,9560,9882,10045,10375,10542,10795,11310,11397,12195,12467,12927 add $0,1 seq $0,98090 ; Numbers k such that 2k-3 is prime. sub $0,1 bin $0,2 div $0,3
; void adt_HeapSiftUp(uint start, void **array, void *compare) ; 03.2003, 08.2005 aralbrec SECTION code_clib PUBLIC ADTHeapSiftUp EXTERN l_jpix ; enter: DE = start index * 2 (offset into array in bytes) ; HL = &array[start] = bc + de ; BC = array address ; IX = compare(DE=&array[child], HL=&array[parent]) ; set carry if child < parent (min heap) -- MUST PRESERVE BC,DE,HL,IX ; uses : AF,DE,HL,AF' .ADTHeapSiftUp ld a,e and $fc or d ret z ; if start <= 2 we have reached root so return srl d rr e res 0,e push de ; stack = parent(child=start) index ex de,hl ; de = &array[child=start] add hl,bc ; hl = &array[parent] call l_jpix ; compare(child, parent) jr nc, done ; if child >= parent, we are done ld a,(de) ; swap(child, parent) ex af,af ld a,(hl) ld (de),a ex af,af ld (hl),a inc hl inc de ld a,(de) ex af,af ld a,(hl) ld (de),a ex af,af ld (hl),a dec hl ; hl = &array[parent] pop de ; de = parent index jp ADTHeapSiftUp ; parent becomes child .done pop de ret
fact: addi $sp,$sp-8 sw $ra,4($sp) sw $a0,0($sp) slti $t0,$a0,1 beq $t0,$zero,L1 addi $v0,$zero,1 addi $sp,$sp,8 jr $ra L1: addi $a0,$a0,-1 jal fact lw $a0,0($sp) lw $ra,4($sp) mul $v0,$v0,$a0 addi $sp,$sp,8 jr $ra
// Copyright (c) 2021 LibreSprite Authors (cf. AUTHORS.md) // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #include <cmd/Command.hpp> #include <common/Messages.hpp> #include <common/PubSub.hpp> #include <common/System.hpp> #include <doc/Cell.hpp> #include <gui/Controller.hpp> #include <gui/Events.hpp> #include <gui/Node.hpp> #include <tools/Tool.hpp> class Canvas : public ui::Controller { public: PubSub<msg::ModifyCell, msg::ActivateCell, msg::ActivateTool> pub{this}; inject<Cell> cell; std::shared_ptr<Tool> activeTool; Tool::Path points; void attach() override { node()->addEventListener<ui::MouseMove, ui::MouseDown, ui::MouseUp, ui::MouseWheel, ui::MouseLeave>(this); setup(); } void on(msg::ActivateTool&) { end(); } void on(msg::ModifyCell& event) { if (event.cell.get() == cell) setup(); } void on(msg::ActivateCell& event) { node()->set("inputEnabled", event.cell.get() == cell); } void setup() { auto surface = cell->getComposite()->shared_from_this(); if (!surface) { logI("Empty cell"); } node()->load({ {"surface", surface}, {"alpha", cell->getAlpha()} }); } void eventHandler(const ui::MouseDown& event) { paint(event.targetX(), event.targetY(), event.buttons); } void eventHandler(const ui::MouseUp& event) { end(); } void eventHandler(const ui::MouseLeave&) { system->setMouseCursorVisible(true); end(); } inject<System> system; U32 prevButtons = ~U32{}; void eventHandler(const ui::MouseMove& event) { paint(event.targetX(), event.targetY(), event.buttons); Tool::Preview* preview = nullptr; if (activeTool) preview = activeTool->getPreview(); system->setMouseCursorVisible(!preview || !preview->hideCursor); } void eventHandler(const ui::MouseWheel& event) { inject<Command> zoom{"zoom"}; zoom->set("level", "*" + tostring(1 + 0.2 * event.wheelY)); zoom->run(); } void end() { prevButtons = ~U32{}; if (points.empty()) return; if (activeTool) activeTool->end(cell->getComposite(), points); points.clear(); } void paint(S32 tx, S32 ty, U32 buttons) { if (prevButtons != buttons) end(); prevButtons = buttons; auto rect = node()->globalRect; if (!rect.width || !rect.height) return; auto surface = cell->getComposite(); S32 x = (tx * surface->width()) / rect.width; S32 y = (ty * surface->height()) / rect.height; bool begin = points.empty(); if (!begin && x == points.back().x && y == points.back().y) return; points.push_back({x, y}); if (begin) { do { activeTool = Tool::active.lock(); if (!activeTool) return; activeTool->begin(surface, points, buttons); } while (Tool::active.lock() != activeTool); } else if (activeTool) { activeTool->update(surface, points); } } }; static ui::Controller::Shared<Canvas> canvas{"canvas"};
bits 16 ; glb intptr_t : int ; glb uintptr_t : unsigned ; glb intmax_t : int ; glb uintmax_t : unsigned ; glb int8_t : signed char ; glb int_least8_t : signed char ; glb int_fast8_t : signed char ; glb uint8_t : unsigned char ; glb uint_least8_t : unsigned char ; glb uint_fast8_t : unsigned char ; glb int16_t : short ; glb int_least16_t : short ; glb int_fast16_t : short ; glb uint16_t : unsigned short ; glb uint_least16_t : unsigned short ; glb uint_fast16_t : unsigned short ; glb int32_t : int ; glb int_least32_t : int ; glb int_fast32_t : int ; glb uint32_t : unsigned ; glb uint_least32_t : unsigned ; glb uint_fast32_t : unsigned ; glb imaxdiv_t : struct <something> ; glb bool_t : int ; glb pointer_t : * unsigned char ; glb funcion_t : * ( ; prm <something> : * void ; ) * void ; glb manejador_t : * (void) void ; glb rti_t : * (void) void ; glb isr_t : * (void) void ; glb handler_t : * (void) void ; glb retardarThread_t : * (void) int ; glb ptrTVI_t : * * (void) void ; glb modoSO1_t : int ; glb lh_t : struct <something> ; glb address_t : struct <something> ; glb uPtrAdr_t : union <something> ; glb pid_t : int ; glb tid_t : int ; glb uid_t : int ; glb gid_t : int ; glb pindx_t : int ; glb tindx_t : int ; glb df_t : int ; glb dfs_t : int ; glb rindx_t : int ; glb inportb : ( ; prm port : unsigned short ; ) unsigned char ; glb inport : ( ; prm port : unsigned short ; ) unsigned short ; glb outport : ( ; prm port : unsigned short ; prm val : unsigned short ; ) void ; glb outportb : ( ; prm port : unsigned short ; prm val : unsigned char ; ) void ; glb inportb_r : ( ; prm port : unsigned char ; ) unsigned char ; glb outportb_r : ( ; prm port : unsigned char ; prm val : unsigned char ; ) void ; glb contadorTimer0 : (void) unsigned short ; glb ptrTVI : * * (void) void ; glb valorIMR : (void) unsigned short ; glb establecerIMR : ( ; prm nuevoIMR : unsigned short ; ) void ; glb mask_pic1 : ( ; prm irq : unsigned char ; ) void ; glb mask_pic2 : ( ; prm irq : unsigned char ; ) void ; glb unmask_pic1 : ( ; prm irq : unsigned char ; ) void ; glb unmask_pic2 : ( ; prm irq : unsigned char ; ) void ; glb get_pic1_isr : (void) unsigned char ; glb get_pic2_isr : (void) unsigned char ; glb set_pics : ( ; prm irq0 : unsigned char ; prm irq8 : unsigned char ; ) void ; glb pic_setup : (void) void ; glb enable_hwirq : ( ; prm hwirq : int ; prm rti : * (void) void ; ) void ; glb startBin : (void) void ; glb modoSO1 : (void) int ; glb unidadBIOS : (void) unsigned char ; glb CS_SO1H : unsigned short ; glb RO_SO1H : unsigned short ; glb DS_SO1H : unsigned short ; glb BSS_SO1H : unsigned short ; glb SS_SO1H : unsigned short ; glb SS_Kernel : unsigned short ; glb IMRInicial : unsigned short ; glb obtenerMapa : (void) void ; glb modoAp_t : unsigned short ; glb tramaDWords_t : struct <something> ; glb tramaWords_t : struct <something> ; RPN'ized expression: "2 " ; Expanded expression: "2 " ; Expression value: 2 ; RPN'ized expression: "2 " ; Expanded expression: "2 " ; Expression value: 2 ; RPN'ized expression: "2 " ; Expanded expression: "2 " ; Expression value: 2 ; RPN'ized expression: "2 " ; Expanded expression: "2 " ; Expression value: 2 ; glb tramaBytes_t : struct <something> ; glb trama_t : union <something> ; RPN'ized expression: "8 " ; Expanded expression: "8 " ; Expression value: 8 ; glb bloque_t : struct <something> ; glb ptrBloque_t : * struct <something> ; glb dobleEnlace_t : struct <something> ; glb c2c_t : struct <something> ; glb posicionC2c : ( ; prm i : int ; prm c2c : struct <something> ; ) int ; glb eliminarC2c : ( ; prm i : int ; prm c2c : struct <something> ; ) void ; glb apilarC2c : ( ; prm i : int ; prm c2c : struct <something> ; ) void ; glb encolarC2c : ( ; prm i : int ; prm c2c : struct <something> ; ) void ; glb desencolarC2c : ( ; prm c2c : struct <something> ; ) int ; glb inicializarC2c : ( ; prm c2c : * struct <something> ; prm e : * struct <something> ; prm cabecera : int ; prm compartida : int ; ) void ; glb ptrC2c_t : * struct <something> ; glb posicionPC2c : ( ; prm i : int ; prm c2c : * struct <something> ; ) int ; glb eliminarPC2c : ( ; prm i : int ; prm ptrC2c : * struct <something> ; ) void ; glb apilarPC2c : ( ; prm i : int ; prm ptrC2c : * struct <something> ; ) void ; glb encolarPC2c : ( ; prm i : int ; prm ptrC2c : * struct <something> ; ) void ; glb desencolarPC2c : ( ; prm ptrC2c : * struct <something> ; ) int ; glb inicializarPC2c : ( ; prm ptrC2c : * struct <something> ; prm e : * struct <something> ; prm cabecera : int ; prm compartida : int ; ) void ; glb callBack_t : * ( ; prm arg : * void ; ) int ; RPN'ized expression: "10 " ; Expanded expression: "10 " ; Expression value: 10 ; glb descCcb_t : struct <something> ; glb ccb_t : * struct <something> ; glb inicCcb : ( ; prm ccb : * struct <something> ; prm max : unsigned short ; ) int ; glb encolarCcb : ( ; prm cb : * ( ; prm arg : * void ; ) int ; prm ccb : * struct <something> ; ) int ; glb desencolarCcb : ( ; prm ccb : * struct <something> ; ) * ( ; prm arg : * void ; ) int ; glb eliminarCcb : ( ; prm cb : * ( ; prm arg : * void ; ) int ; prm ccb : * struct <something> ; ) int ; glb eliminarSegCcb : ( ; prm segmento : unsigned short ; prm ccb : * struct <something> ; ) int ; glb vaciarCcb : ( ; prm ccb : * struct <something> ; ) int ; glb atenderCcb : ( ; prm ccb : * struct <something> ; ) int ; glb estado_t : int ; glb dfa_t : struct <something> ; RPN'ized expression: "12 " ; Expanded expression: "12 " ; Expression value: 12 ; RPN'ized expression: "80 " ; Expanded expression: "80 " ; Expression value: 80 ; RPN'ized expression: "10 " ; Expanded expression: "10 " ; Expression value: 10 ; glb descProceso_t : struct <something> ; glb descThread_t : struct <something> ; glb tipoFichero_t : int ; RPN'ized expression: "9 " ; Expanded expression: "9 " ; Expression value: 9 ; glb descFichero_t : struct <something> ; glb tipoRecurso_t : int ; glb open_t : * ( ; prm dfs : int ; prm modo : unsigned short ; ) int ; glb release_t : * ( ; prm dfs : int ; ) int ; glb read_t : * ( ; prm dfs : int ; prm dir : * unsigned char ; prm nbytes : unsigned short ; ) int ; glb aio_read_t : * ( ; prm dfs : int ; prm dir : * unsigned char ; prm nbytes : unsigned short ; ) int ; glb write_t : * ( ; prm dfs : int ; prm dir : * unsigned char ; prm nbytes : unsigned short ; ) int ; glb aio_write_t : * ( ; prm dfs : int ; prm dir : * unsigned char ; prm nbytes : unsigned short ; ) int ; glb lseek_t : * ( ; prm dfs : int ; prm pos : int ; prm whence : unsigned short ; ) int ; glb fcntl_t : * ( ; prm dfs : int ; prm cmd : unsigned short ; prm arg : unsigned short ; ) int ; glb ioctl_t : * ( ; prm dfs : int ; prm request : unsigned short ; prm arg : unsigned short ; ) int ; glb eliminar_t : * ( ; prm pindx : int ; ) int ; RPN'ized expression: "12 " ; Expanded expression: "12 " ; Expression value: 12 ; RPN'ized expression: "2 " ; Expanded expression: "2 " ; Expression value: 2 ; RPN'ized expression: "2 " ; Expanded expression: "2 " ; Expression value: 2 ; RPN'ized expression: "2 " ; Expanded expression: "2 " ; Expression value: 2 ; glb descRecurso_t : struct <something> ; glb info_t : struct <something> ; glb cabecera_t : struct <something> ; RPN'ized expression: "16 1 + " ; Expanded expression: "17 " ; Expression value: 17 ; RPN'ized expression: "16 2 + " ; Expanded expression: "18 " ; Expression value: 18 ; RPN'ized expression: "2010 1 + " ; Expanded expression: "2011 " ; Expression value: 2011 ; RPN'ized expression: "2010 2 + " ; Expanded expression: "2012 " ; Expression value: 2012 ; RPN'ized expression: "20 1 + " ; Expanded expression: "21 " ; Expression value: 21 ; RPN'ized expression: "20 2 + " ; Expanded expression: "22 " ; Expression value: 22 ; RPN'ized expression: "14 1 + " ; Expanded expression: "15 " ; Expression value: 15 ; RPN'ized expression: "14 2 + " ; Expanded expression: "16 " ; Expression value: 16 ; RPN'ized expression: "16 16 + " ; Expanded expression: "32 " ; Expression value: 32 ; RPN'ized expression: "2010 16 + " ; Expanded expression: "2026 " ; Expression value: 2026 ; RPN'ized expression: "2010 1 + " ; Expanded expression: "2011 " ; Expression value: 2011 ; RPN'ized expression: "2010 1 + " ; Expanded expression: "2011 " ; Expression value: 2011 ; RPN'ized expression: "16 1 + " ; Expanded expression: "17 " ; Expression value: 17 ; RPN'ized expression: "2010 1 + " ; Expanded expression: "2011 " ; Expression value: 2011 ; RPN'ized expression: "20 14 + " ; Expanded expression: "34 " ; Expression value: 34 ; glb e2PFR_t : struct <something> ; glb cPFR_t : int ; glb sigThread_t : * () int ; glb activarThread_t : * ( ; prm tindx : int ; ) void ; glb buscarNuevoThreadActual_t : * (void) void ; glb bloquearThreadActual_t : * ( ; prm rindx : int ; ) void ; glb descSO1H_t : struct <something> ; RPN'ized expression: "12 " ; Expanded expression: "12 " ; Expression value: 12 ; RPN'ized expression: "80 " ; Expanded expression: "80 " ; Expression value: 80 ; RPN'ized expression: "10 " ; Expanded expression: "10 " ; Expression value: 10 ; glb descProcesoExt_t : struct <something> ; glb descThreadExt_t : struct <something> ; RPN'ized expression: "16 " ; Expanded expression: "16 " ; Expression value: 16 ; glb descProceso : [16u] struct <something> ; RPN'ized expression: "2010 " ; Expanded expression: "2010 " ; Expression value: 2010 ; glb descThread : [2010u] struct <something> ; RPN'ized expression: "20 " ; Expanded expression: "20 " ; Expression value: 20 ; glb descFichero : [20u] struct <something> ; RPN'ized expression: "14 " ; Expanded expression: "14 " ; Expression value: 14 ; glb descRecurso : [14u] struct <something> ; RPN'ized expression: "numColasPFR " ; Expanded expression: "12 " ; Expression value: 12 ; glb c2cPFR : [12u] struct <something> ; glb e2PFR : struct <something> ; glb descCcbAlEpilogo : struct <something> ; glb ccbAlEpilogo : * struct <something> ; glb tramaThread : * union <something> ; glb tramaTarea : * union <something> ; glb indThreadActual : int ; glb indProcesoActual : int ; glb indThreadDeSuperficie : int ; glb contRodajas : unsigned ; glb contTicsRodaja : int ; glb contadorTimer00 : unsigned short ; glb contOcioso : int ; glb nuevoPid : (void) int ; glb nuevoTid : (void) int ; glb indice : ( ; prm tid : int ; ) int ; glb sigThread : (void) int ; glb activarThread : ( ; prm tindx : int ; ) int ; glb registrarEnPOrdenados : ( ; prm pindx : int ; ) void ; glb crearThread : ( ; prm funcion : * ( ; prm <something> : * void ; ) * void ; prm SP0 : unsigned short ; prm arg : * void ; prm pindx : int ; ) int ; glb crearProceso : ( ; prm segmento : unsigned short ; prm tam : unsigned short ; prm tamFich : unsigned ; prm programa : * char ; prm comando : * char ; prm pindx : int ; ) int ; glb inicProcesos : (void) void ; glb resetPids : (void) void ; glb resetTids : (void) void ; glb terminarThreadIndx : ( ; prm tindx : int ; ) int ; glb eliminarThreadIndx : ( ; prm tindx : int ; ) int ; glb terminarProcIndx : ( ; prm pindx : int ; ) int ; glb eliminarProcIndx : ( ; prm pindx : int ; ) int ; glb matarThreadIndx : ( ; prm tindx : int ; ) int ; glb matarProcIndx : ( ; prm pindx : int ; ) int ; glb link_procs : (void) void ; glb SS_Thread : unsigned short ; glb SP_Thread : unsigned short ; glb SS_Tarea : unsigned short ; glb SP_Tarea : unsigned short ; glb nivelActivacionSO1H : int ; glb nVIntActual : int ; glb enHalt : int ; glb activarAlEpilogo1 : int ; glb hayTic : int ; glb setKernelStack : (void) void ; glb setThreadStack : ( ; prm SS_Thread : unsigned short ; prm SP_Thread : unsigned short ; ) void ; glb reg_DL : (void) unsigned ; glb prepararDesbloqueadosUrgentes : (void) void ; glb buscarNuevoThreadActual : (void) void ; glb bloquearThreadActual : ( ; prm rindx : int ; ) void ; glb printCarVideo : ( ; prm car : char ; ) int ; glb printLnVideo : (void) int ; glb printStrVideo : ( ; prm str : * char ; ) int ; glb printStrHastaVideo : ( ; prm str : * char ; prm n : unsigned short ; prm lleno : int ; ) int ; glb printDecVideo : ( ; prm num : unsigned short ; prm l : unsigned short ; ) int ; glb printLDecVideo : ( ; prm num : unsigned ; prm l : unsigned short ; ) int ; glb printIntVideo : ( ; prm num : int ; prm l : unsigned short ; ) int ; glb printLIntVideo : ( ; prm num : int ; prm l : unsigned short ; ) int ; glb printHexVideo : ( ; prm num : unsigned short ; prm l : unsigned short ; ) int ; glb printLHexVideo : ( ; prm num : unsigned ; prm l : unsigned short ; ) int ; glb printBinVideo : ( ; prm num : unsigned short ; prm l : unsigned short ; ) int ; glb printLBinVideo : ( ; prm num : unsigned ; prm l : unsigned short ; ) int ; glb printPtrVideo : ( ; prm ptr : * unsigned char ; ) int ; glb printByteVideo : ( ; prm b : unsigned char ; ) int ; glb printWordVideo : ( ; prm w : unsigned short ; ) int ; glb printCadVideo : ( ; prm cad : * char ; ) int ; glb isr_SO1H : (void) void ; glb link_llamadas : (void) void %define NUM_MATRICULA 0x0123 section .text global _link_llamadas _link_llamadas: ; glb so1_manejador_00 : (void) void ; glb so1_manejador_01 : (void) void ; glb so1_manejador_02 : (void) void ; glb so1_manejador_03 : (void) void ; glb so1_manejador_0b : (void) void ; glb so1_manejador_Nulo : (void) void section .text global _so1_manejador_Nulo _so1_manejador_Nulo: push ebp movzx ebp, sp ;sub sp, 0 L1: db 0x66 leave retf L3: section .fxnsz noalloc dd L3 - _so1_manejador_Nulo ; glb manejador : [0u] * (void) void section .data align 4 global _manejador _manejador: ; = ; RPN'ized expression: "so1_manejador_00 " ; Expanded expression: "so1_manejador_00 " section .relod dd L4 section .data L4: dd _so1_manejador_00 ; RPN'ized expression: "so1_manejador_01 " ; Expanded expression: "so1_manejador_01 " section .relod dd L5 section .data L5: dd _so1_manejador_01 ; RPN'ized expression: "so1_manejador_02 " ; Expanded expression: "so1_manejador_02 " section .relod dd L6 section .data L6: dd _so1_manejador_02 ; RPN'ized expression: "so1_manejador_03 " ; Expanded expression: "so1_manejador_03 " section .relod dd L7 section .data L7: dd _so1_manejador_03 ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L8 section .data L8: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L9 section .data L9: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L10 section .data L10: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L11 section .data L11: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L12 section .data L12: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L13 section .data L13: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L14 section .data L14: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_0b " ; Expanded expression: "so1_manejador_0b " section .relod dd L15 section .data L15: dd _so1_manejador_0b ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L16 section .data L16: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L17 section .data L17: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L18 section .data L18: dd _so1_manejador_Nulo ; RPN'ized expression: "so1_manejador_Nulo " ; Expanded expression: "so1_manejador_Nulo " section .relod dd L19 section .data L19: dd _so1_manejador_Nulo ; glb isr_SO1H : (void) void section .text global _isr_SO1H _isr_SO1H: push ebp movzx ebp, sp ;sub sp, 0 ; if ; RPN'ized expression: "nivelActivacionSO1H 1 > " ; Expanded expression: "nivelActivacionSO1H *(4) 1 > " ; Fused expression: "nivelActivacionSO1H > *ax 1 IF! " section .relod dd L24 section .text db 0x66, 0xB8 L24: dd _nivelActivacionSO1H mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov eax, [si] cmp eax, 1 jle L22 ; { section .rodata L25: db 10," llamada al sistema desde el nivel " times 1 db 0 section .text ; RPN'ized expression: "( L25 printStrVideo ) " ; Expanded expression: " L25 printStrVideo ()4 " ; Fused expression: "( L25 , printStrVideo )4 " section .relod dd L26 section .text db 0x66, 0x68 L26: dd L25 db 0x9A section .relot dd L27 section .text L27: dd _printStrVideo sub sp, -4 ; RPN'ized expression: "( 1 , nivelActivacionSO1H 1 - printDecVideo ) " ; Expanded expression: " 1 nivelActivacionSO1H *(4) 1 - printDecVideo ()8 " ; Fused expression: "( 1 , nivelActivacionSO1H - *ax 1 , printDecVideo )8 " push dword 1 section .relod dd L28 section .text db 0x66, 0xB8 L28: dd _nivelActivacionSO1H mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov eax, [si] dec eax push eax db 0x9A section .relot dd L29 section .text L29: dd _printDecVideo sub sp, -8 section .rodata L30: db " (0: usuario, 1: tarea) pindx = " times 1 db 0 section .text ; RPN'ized expression: "( L30 printStrVideo ) " ; Expanded expression: " L30 printStrVideo ()4 " ; Fused expression: "( L30 , printStrVideo )4 " section .relod dd L31 section .text db 0x66, 0x68 L31: dd L30 db 0x9A section .relot dd L32 section .text L32: dd _printStrVideo sub sp, -4 ; RPN'ized expression: "( 1 , indProcesoActual printIntVideo ) " ; Expanded expression: " 1 indProcesoActual *(4) printIntVideo ()8 " ; Fused expression: "( 1 , indProcesoActual *(4) ax , printIntVideo )8 " push dword 1 section .relod dd L33 section .text db 0x66, 0xB8 L33: dd _indProcesoActual mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 push dword [si] db 0x9A section .relot dd L34 section .text L34: dd _printIntVideo sub sp, -8 section .rodata L35: db " tid = " times 1 db 0 section .text ; RPN'ized expression: "( L35 printStrVideo ) " ; Expanded expression: " L35 printStrVideo ()4 " ; Fused expression: "( L35 , printStrVideo )4 " section .relod dd L36 section .text db 0x66, 0x68 L36: dd L35 db 0x9A section .relot dd L37 section .text L37: dd _printStrVideo sub sp, -4 ; RPN'ized expression: "( 1 , indThreadActual printIntVideo ) " ; Expanded expression: " 1 indThreadActual *(4) printIntVideo ()8 " ; Fused expression: "( 1 , indThreadActual *(4) ax , printIntVideo )8 " push dword 1 section .relod dd L38 section .text db 0x66, 0xB8 L38: dd _indThreadActual mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 push dword [si] db 0x9A section .relot dd L39 section .text L39: dd _printIntVideo sub sp, -8 section .rodata L40: db " AX = " times 1 db 0 section .text ; RPN'ized expression: "( L40 printStrVideo ) " ; Expanded expression: " L40 printStrVideo ()4 " ; Fused expression: "( L40 , printStrVideo )4 " section .relod dd L41 section .text db 0x66, 0x68 L41: dd L40 db 0x9A section .relot dd L42 section .text L42: dd _printStrVideo sub sp, -4 ; RPN'ized expression: "( 4 , tramaThread tw -> *u &u AX -> *u printHexVideo ) " ; Expanded expression: " 4 tramaThread *(4) 0 + 32 + *(2) printHexVideo ()8 " ; Fused expression: "( 4 , tramaThread + *ax 0 + ax 32 *(2) ax , printHexVideo )8 " push dword 4 section .relod dd L43 section .text db 0x66, 0xB8 L43: dd _tramaThread mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov eax, [si] add eax, 32 mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov ax, [si] movzx eax, ax push eax db 0x9A section .relot dd L44 section .text L44: dd _printHexVideo sub sp, -8 cli hlt ; } L22: ; loc <something> : * union <something> ; loc <something> : unsigned ; loc <something> : unsigned ; RPN'ized expression: "tramaThread SS_Thread (something46) 4 << SP_Thread (something47) + (something45) = " ; Expanded expression: "tramaThread SS_Thread *(2) 4 << SP_Thread *(2) + =(4) " ; Fused expression: "tramaThread push-ax SS_Thread << *ax 4 push-ax SP_Thread + *sp *ax =(204) **sp ax " section .relod dd L48 section .text db 0x66, 0xB8 L48: dd _tramaThread push eax section .relod dd L49 section .text db 0x66, 0xB8 L49: dd _SS_Thread mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov ax, [si] movzx eax, ax shl eax, 4 push eax section .relod dd L50 section .text db 0x66, 0xB8 L50: dd _SP_Thread mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 movzx ecx, word [si] pop eax add eax, ecx pop ebx mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov [si], eax ; loc 51 : unsigned char section .bss L51: resb 1 section .text ; RPN'ized expression: "codOp tramaThread tb -> *u &u AH -> *u = " ; Expanded expression: "L51 tramaThread *(4) 0 + 33 + *(1) =(1) " ; Fused expression: "L51 push-ax tramaThread + *ax 0 + ax 33 =(153) **sp *ax " section .relod dd L52 section .text db 0x66, 0xB8 L52: dd L51 push eax section .relod dd L53 section .text db 0x66, 0xB8 L53: dd _tramaThread mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov eax, [si] add eax, 33 mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov al, [si] movzx eax, al pop ebx mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov [si], al movzx eax, al ; if ; loc <something> : * (void) void ; RPN'ized expression: "codOp manejador sizeof <something56> sizeof / < " ; Expanded expression: "L51 *(1) 16u <u " ; Fused expression: "L51 <u *ax 16u IF! " section .relod dd L57 section .text db 0x66, 0xB8 L57: dd L51 mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov al, [si] movzx eax, al cmp eax, 16 jae L54 ; RPN'ized expression: "( manejador codOp + *u ) " ; Expanded expression: " manejador L51 *(1) 4 * + *(4) ()0 " ; Fused expression: "( manejador push-ax L51 * *ax 4 + *sp ax *(4) ax )0 " section .relod dd L58 section .text db 0x66, 0xB8 L58: dd _manejador push eax section .relod dd L59 section .text db 0x66, 0xB8 L59: dd L51 mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov al, [si] movzx eax, al imul eax, eax, 4 mov ecx, eax pop eax add eax, ecx mov ebx, eax mov esi, ebx ror esi, 4 mov ds, si shr esi, 28 mov eax, [si] db 0x9A section .relot dd L60 section .text L60: dd L61 L61: mov si, sp add word [ss:si], L62 - L61 shl eax, 12 rol ax, 4 push eax retf L62: L54: L20: db 0x66 leave retf L63: section .fxnsz dd L63 - _isr_SO1H extern _so1_manejador_00 extern _so1_manejador_01 extern _so1_manejador_02 extern _so1_manejador_03 extern _so1_manejador_0b extern _nivelActivacionSO1H extern _printStrVideo extern _printDecVideo extern _indProcesoActual extern _printIntVideo extern _indThreadActual extern _tramaThread extern _printHexVideo extern _SS_Thread extern _SP_Thread ; Syntax/declaration table/stack: ; Bytes used: 11710/40960 ; Macro table: ; Macro __SMALLER_C__ = `0x0100` ; Macro __SMALLER_C_32__ = `` ; Macro __HUGE__ = `` ; Macro __SMALLER_C_SCHAR__ = `` ; Bytes used: 74/5120 ; Identifier table: ; Ident __floatsisf ; Ident __floatunsisf ; Ident __fixsfsi ; Ident __fixunssfsi ; Ident __addsf3 ; Ident __subsf3 ; Ident __negsf2 ; Ident __mulsf3 ; Ident __divsf3 ; Ident __lesf2 ; Ident __gesf2 ; Ident intptr_t ; Ident uintptr_t ; Ident intmax_t ; Ident uintmax_t ; Ident int8_t ; Ident int_least8_t ; Ident int_fast8_t ; Ident uint8_t ; Ident uint_least8_t ; Ident uint_fast8_t ; Ident int16_t ; Ident int_least16_t ; Ident int_fast16_t ; Ident uint16_t ; Ident uint_least16_t ; Ident uint_fast16_t ; Ident int32_t ; Ident int_least32_t ; Ident int_fast32_t ; Ident uint32_t ; Ident uint_least32_t ; Ident uint_fast32_t ; Ident <something> ; Ident quot ; Ident rem ; Ident imaxdiv_t ; Ident FALSE ; Ident TRUE ; Ident bool_t ; Ident pointer_t ; Ident funcion_t ; Ident manejador_t ; Ident rti_t ; Ident isr_t ; Ident handler_t ; Ident retardarThread_t ; Ident ptrTVI_t ; Ident modoSO1_Bin ; Ident modoSO1_Exe ; Ident modoSO1_Bs ; Ident modoSO1_t ; Ident lo ; Ident hi ; Ident lh_t ; Ident offset ; Ident segment ; Ident address_t ; Ident ptr ; Ident adr ; Ident uPtrAdr_t ; Ident pid_t ; Ident tid_t ; Ident uid_t ; Ident gid_t ; Ident pindx_t ; Ident tindx_t ; Ident df_t ; Ident dfs_t ; Ident rindx_t ; Ident inportb ; Ident port ; Ident inport ; Ident outport ; Ident val ; Ident outportb ; Ident inportb_r ; Ident outportb_r ; Ident contadorTimer0 ; Ident ptrTVI ; Ident valorIMR ; Ident establecerIMR ; Ident nuevoIMR ; Ident mask_pic1 ; Ident irq ; Ident mask_pic2 ; Ident unmask_pic1 ; Ident unmask_pic2 ; Ident get_pic1_isr ; Ident get_pic2_isr ; Ident set_pics ; Ident irq0 ; Ident irq8 ; Ident pic_setup ; Ident enable_hwirq ; Ident hwirq ; Ident rti ; Ident startBin ; Ident modoSO1 ; Ident unidadBIOS ; Ident CS_SO1H ; Ident RO_SO1H ; Ident DS_SO1H ; Ident BSS_SO1H ; Ident SS_SO1H ; Ident SS_Kernel ; Ident IMRInicial ; Ident obtenerMapa ; Ident modoAp_t ; Ident DS ; Ident ES ; Ident EDI ; Ident ESI ; Ident EBP ; Ident ESP ; Ident EBX ; Ident EDX ; Ident ECX ; Ident EAX ; Ident IP ; Ident CS ; Ident Flags ; Ident tramaDWords_t ; Ident DI ; Ident rDI ; Ident SI ; Ident rSI ; Ident BP ; Ident rBP ; Ident SP ; Ident rSP ; Ident BX ; Ident rBX ; Ident DX ; Ident rDX ; Ident CX ; Ident rCX ; Ident AX ; Ident rAX ; Ident tramaWords_t ; Ident BL ; Ident BH ; Ident rB ; Ident DL ; Ident DH ; Ident rD ; Ident CL ; Ident CH ; Ident rC ; Ident AL ; Ident AH ; Ident rA ; Ident tramaBytes_t ; Ident td ; Ident tw ; Ident tb ; Ident trama_t ; Ident tam ; Ident sig ; Ident ant ; Ident aux ; Ident relleno ; Ident bloque_t ; Ident ptrBloque_t ; Ident cab ; Ident dobleEnlace_t ; Ident numElem ; Ident primero ; Ident cabecera ; Ident e ; Ident c2c_t ; Ident posicionC2c ; Ident i ; Ident c2c ; Ident eliminarC2c ; Ident apilarC2c ; Ident encolarC2c ; Ident desencolarC2c ; Ident inicializarC2c ; Ident compartida ; Ident ptrC2c_t ; Ident posicionPC2c ; Ident eliminarPC2c ; Ident ptrC2c ; Ident apilarPC2c ; Ident encolarPC2c ; Ident desencolarPC2c ; Ident inicializarPC2c ; Ident callBack_t ; Ident arg ; Ident num ; Ident in ; Ident out ; Ident max ; Ident callBack ; Ident descCcb_t ; Ident ccb_t ; Ident inicCcb ; Ident ccb ; Ident encolarCcb ; Ident cb ; Ident desencolarCcb ; Ident eliminarCcb ; Ident eliminarSegCcb ; Ident segmento ; Ident vaciarCcb ; Ident atenderCcb ; Ident libre ; Ident preparado ; Ident ejecutandose ; Ident bloqueado ; Ident estado_t ; Ident modoAp ; Ident dfs ; Ident pos ; Ident dfa_t ; Ident pid ; Ident noStatus ; Ident status ; Ident ppindx ; Ident hpindx ; Ident c2cHijos ; Ident c2cThreads ; Ident CSProc ; Ident tamCodigo ; Ident desplBSS ; Ident desplPila ; Ident tamFichero ; Ident programa ; Ident comando ; Ident nfa ; Ident tfa ; Ident uid ; Ident gid ; Ident descProceso_t ; Ident tid ; Ident estado ; Ident esperandoPor ; Ident trama ; Ident ptindx ; Ident htindx ; Ident pindx ; Ident SSThread ; Ident SP0 ; Ident descThread_t ; Ident flibre ; Ident fRegular ; Ident fedBloques ; Ident fedCaracteres ; Ident tuberia ; Ident tipoFichero_t ; Ident tipo ; Ident nombre ; Ident rindx ; Ident menor ; Ident shareMode ; Ident contAp_L ; Ident contAp_E ; Ident descFichero_t ; Ident rLibre ; Ident rDCaracteres ; Ident rDBloques ; Ident rTuberia ; Ident rGP ; Ident rGM ; Ident rSF ; Ident rOtro ; Ident tipoRecurso_t ; Ident open_t ; Ident modo ; Ident release_t ; Ident read_t ; Ident dir ; Ident nbytes ; Ident aio_read_t ; Ident write_t ; Ident aio_write_t ; Ident lseek_t ; Ident whence ; Ident fcntl_t ; Ident cmd ; Ident ioctl_t ; Ident request ; Ident eliminar_t ; Ident tindx ; Ident c2cFichRec ; Ident numVI ; Ident nVInt ; Ident isr ; Ident open ; Ident release ; Ident read ; Ident aio_read ; Ident write ; Ident aio_write ; Ident lseek ; Ident fcntl ; Ident ioctl ; Ident eliminar ; Ident descRecurso_t ; Ident SP0_So1 ; Ident IMR ; Ident ptrDebugWord ; Ident info_t ; Ident signatura ; Ident bytesUltSector ; Ident sectores ; Ident numDirReub ; Ident numParCabecera ; Ident minAlloc ; Ident maxAlloc ; Ident SS0 ; Ident checkSum ; Ident IP0 ; Ident CS0 ; Ident offTablaReub ; Ident numOverlay ; Ident cabecera_t ; Ident Libres ; Ident Ocupados ; Ident e2DescProceso ; Ident e2DescThread ; Ident e2DescFichero ; Ident e2DescRecurso ; Ident e2Hijos ; Ident e2Threads ; Ident e2Preparados ; Ident e2Urgentes ; Ident e2POrdenados ; Ident e2TDormidos ; Ident e2FichRec ; Ident e2PFR_t ; Ident DPLibres ; Ident DPOcupados ; Ident DTLibres ; Ident DTOcupados ; Ident TPreparados ; Ident TUrgentes ; Ident POrdenados ; Ident TDormidos ; Ident DFLibres ; Ident DFOcupados ; Ident DRLibres ; Ident DROcupados ; Ident numColasPFR ; Ident cPFR_t ; Ident sigThread_t ; Ident activarThread_t ; Ident buscarNuevoThreadActual_t ; Ident bloquearThreadActual_t ; Ident ptrIndProcesoActual ; Ident ptrIndThreadActual ; Ident ptrTramaThread ; Ident ptrActivarAlEpilogo ; Ident ptrDescProceso ; Ident tamDescProceso ; Ident ptrDescThread ; Ident tamDescThread ; Ident ptrDescFichero ; Ident ptrDescRecurso ; Ident ptrC2cPFR ; Ident ptrE2PFR ; Ident ptrNivelActivacionSO1H ; Ident ptrEnHalt ; Ident ptrHayTic ; Ident ptrCcbAlEpilogo ; Ident ptrSS_Thread ; Ident ptrSP_Thread ; Ident ptrSS_Kernel ; Ident ptrSP0_Kernel ; Ident SP0_SO1H ; Ident ptrContRodajas ; Ident ptrContTicsRodaja ; Ident ptrVIOrg ; Ident sigThread ; Ident activarThread ; Ident buscarNuevoThreadActual ; Ident bloquearThreadActual ; Ident ptrListaLibres ; Ident ptrTamBloqueMax ; Ident descSO1H_t ; Ident descProcesoExt_t ; Ident descThreadExt_t ; Ident descProceso ; Ident descThread ; Ident descFichero ; Ident descRecurso ; Ident c2cPFR ; Ident e2PFR ; Ident descCcbAlEpilogo ; Ident ccbAlEpilogo ; Ident tramaThread ; Ident tramaTarea ; Ident indThreadActual ; Ident indProcesoActual ; Ident indThreadDeSuperficie ; Ident contRodajas ; Ident contTicsRodaja ; Ident contadorTimer00 ; Ident contOcioso ; Ident nuevoPid ; Ident nuevoTid ; Ident indice ; Ident registrarEnPOrdenados ; Ident crearThread ; Ident funcion ; Ident crearProceso ; Ident tamFich ; Ident inicProcesos ; Ident resetPids ; Ident resetTids ; Ident terminarThreadIndx ; Ident eliminarThreadIndx ; Ident terminarProcIndx ; Ident eliminarProcIndx ; Ident matarThreadIndx ; Ident matarProcIndx ; Ident link_procs ; Ident SS_Thread ; Ident SP_Thread ; Ident SS_Tarea ; Ident SP_Tarea ; Ident nivelActivacionSO1H ; Ident nVIntActual ; Ident enHalt ; Ident activarAlEpilogo1 ; Ident hayTic ; Ident setKernelStack ; Ident setThreadStack ; Ident reg_DL ; Ident prepararDesbloqueadosUrgentes ; Ident printCarVideo ; Ident car ; Ident printLnVideo ; Ident printStrVideo ; Ident str ; Ident printStrHastaVideo ; Ident n ; Ident lleno ; Ident printDecVideo ; Ident l ; Ident printLDecVideo ; Ident printIntVideo ; Ident printLIntVideo ; Ident printHexVideo ; Ident printLHexVideo ; Ident printBinVideo ; Ident printLBinVideo ; Ident printPtrVideo ; Ident printByteVideo ; Ident b ; Ident printWordVideo ; Ident w ; Ident printCadVideo ; Ident cad ; Ident isr_SO1H ; Ident link_llamadas ; Ident so1_manejador_00 ; Ident so1_manejador_01 ; Ident so1_manejador_02 ; Ident so1_manejador_03 ; Ident so1_manejador_0b ; Ident so1_manejador_Nulo ; Ident manejador ; Bytes used: 4885/16384 ; Next label number: 64 ; Compilation succeeded.
db DEX_OMANYTE ; pokedex id db 35, 40, 100, 35, 90 ; hp atk def spd spc db ROCK, WATER ; type db 45 ; catch rate db 120 ; base exp INCBIN "gfx/pokemon/front/omanyte.pic", 0, 1 ; sprite dimensions dw OmanytePicFront, OmanytePicBack db BUBBLE, HARDEN, NO_MOVE, NO_MOVE ; level 1 learnset db GROWTH_MEDIUM_FAST ; growth rate ; tm/hm learnset tmhm TOXIC, BODY_SLAM, TAKE_DOWN, DOUBLE_EDGE, BUBBLEBEAM, \ WATER_GUN, ICE_BEAM, BLIZZARD, RAGE, MIMIC, \ DOUBLE_TEAM, REFLECT, BIDE, REST, SUBSTITUTE, \ SURF ; end db 0 ; padding
#include "calc_fstr.h" #include "compare_documents.h" #include "feature_str.h" #include "shap_values.h" #include "shap_interaction_values.h" #include "util.h" #include <catboost/private/libs/algo/apply.h> #include <catboost/private/libs/algo/plot.h> #include <catboost/private/libs/algo/yetirank_helpers.h> #include <catboost/private/libs/algo/tree_print.h> #include <catboost/libs/data/features_layout_helpers.h> #include <catboost/libs/data/model_dataset_compatibility.h> #include <catboost/libs/helpers/exception.h> #include <catboost/libs/helpers/mem_usage.h> #include <catboost/libs/helpers/query_info_helper.h> #include <catboost/libs/logging/logging.h> #include <catboost/libs/logging/profile_info.h> #include <catboost/libs/loggers/logger.h> #include <catboost/private/libs/options/enum_helpers.h> #include <catboost/private/libs/options/json_helper.h> #include <catboost/private/libs/options/restrictions.h> #include <catboost/private/libs/target/data_providers.h> #include <util/generic/algorithm.h> #include <util/generic/cast.h> #include <util/generic/hash.h> #include <util/generic/xrange.h> #include <util/string/builder.h> #include <util/string/cast.h> #include <util/system/compiler.h> #include <util/system/info.h> #include <cmath> #include <functional> using namespace NCB; TCombinationClassFeatures GetCombinationClassFeatures(const TFullModel& model) { NCB::TFeaturesLayout layout = MakeFeaturesLayout(model); TVector<std::pair<TVector<int>, TFeature>> featuresCombinations; const TModelTrees& forest = *model.ModelTrees; for (const TFloatFeature& floatFeature : forest.GetFloatFeatures()) { if (!floatFeature.UsedInModel()) { continue; } featuresCombinations.emplace_back(); featuresCombinations.back().first = { floatFeature.Position.FlatIndex }; featuresCombinations.back().second = TFeature(floatFeature); } for (const TOneHotFeature& oneHotFeature: forest.GetOneHotFeatures()) { featuresCombinations.emplace_back(); featuresCombinations.back().first = { (int)layout.GetExternalFeatureIdx(oneHotFeature.CatFeatureIndex, EFeatureType::Categorical) }; featuresCombinations.back().second = TFeature(oneHotFeature); } for (const TCtrFeature& ctrFeature : forest.GetCtrFeatures()) { const TFeatureCombination& combination = ctrFeature.Ctr.Base.Projection; featuresCombinations.emplace_back(); for (int catFeatureIdx : combination.CatFeatures) { featuresCombinations.back().first.push_back( layout.GetExternalFeatureIdx(catFeatureIdx, EFeatureType::Categorical) ); } featuresCombinations.back().second = TFeature(ctrFeature); } for (const TEstimatedFeature& estimatedFeature: forest.GetEstimatedFeatures()) { featuresCombinations.emplace_back(); featuresCombinations.back().first = { (int)layout.GetExternalFeatureIdx( estimatedFeature.ModelEstimatedFeature.SourceFeatureId, EstimatedSourceFeatureTypeToFeatureType( estimatedFeature.ModelEstimatedFeature.SourceFeatureType ) ) }; featuresCombinations.back().second = TFeature( estimatedFeature.ModelEstimatedFeature, model.TextProcessingCollection->GetCalcer(estimatedFeature.ModelEstimatedFeature.CalcerId)->Type() ); } TVector<int> sortedBinFeatures(featuresCombinations.size()); Iota(sortedBinFeatures.begin(), sortedBinFeatures.end(), 0); Sort( sortedBinFeatures.begin(), sortedBinFeatures.end(), [featuresCombinations](int feature1, int feature2) { return featuresCombinations[feature1].first < featuresCombinations[feature2].first; } ); TCombinationClassFeatures combinationClassFeatures; for (ui32 featureIdx = 0; featureIdx < featuresCombinations.size(); ++featureIdx) { int currentFeature = sortedBinFeatures[featureIdx]; int previousFeature = featureIdx == 0 ? -1 : sortedBinFeatures[featureIdx - 1]; if (featureIdx == 0 || featuresCombinations[currentFeature].first != featuresCombinations[previousFeature].first) { combinationClassFeatures.push_back(featuresCombinations[currentFeature].second); } } return combinationClassFeatures; } static TVector<TMxTree> BuildTrees( const THashMap<TFeature, int, TFeatureHash>& featureToIdx, const TFullModel& model) { CB_ENSURE_INTERNAL(model.IsOblivious(), "BuildTrees are supported only for symmetric trees"); TVector<TMxTree> trees(model.GetTreeCount()); const auto binFeatures = model.ModelTrees->GetBinFeatures(); for (int treeIdx = 0; treeIdx < trees.ysize(); ++treeIdx) { auto& tree = trees[treeIdx]; const int leafCount = (1uLL << model.ModelTrees->GetModelTreeData()->GetTreeSizes()[treeIdx]); tree.Leaves.resize(leafCount); for (int leafIdx = 0; leafIdx < leafCount; ++leafIdx) { tree.Leaves[leafIdx].Vals.resize(model.ModelTrees->GetDimensionsCount()); } auto firstTreeLeafPtr = model.ModelTrees->GetFirstLeafPtrForTree(treeIdx); for (int leafIdx = 0; leafIdx < leafCount; ++leafIdx) { for (int dim = 0; dim < (int)model.ModelTrees->GetDimensionsCount(); ++dim) { tree.Leaves[leafIdx].Vals[dim] = firstTreeLeafPtr[leafIdx * model.ModelTrees->GetDimensionsCount() + dim]; } } auto treeSplitsStart = model.ModelTrees->GetModelTreeData()->GetTreeStartOffsets()[treeIdx]; auto treeSplitsStop = treeSplitsStart + model.ModelTrees->GetModelTreeData()->GetTreeSizes()[treeIdx]; for (auto splitIdx = treeSplitsStart; splitIdx < treeSplitsStop; ++splitIdx) { auto feature = GetFeature( model, binFeatures[model.ModelTrees->GetModelTreeData()->GetTreeSplits()[splitIdx]] ); tree.SrcFeatures.push_back(featureToIdx.at(feature)); } } return trees; } static THashMap<TFeature, int, TFeatureHash> GetFeatureToIdxMap( const TFullModel& model, TVector<TFeature>* features) { THashMap<TFeature, int, TFeatureHash> featureToIdx; const auto& modelBinFeatures = model.ModelTrees->GetBinFeatures(); for (auto binSplit : model.ModelTrees->GetModelTreeData()->GetTreeSplits()) { TFeature feature = GetFeature(model, modelBinFeatures[binSplit]); if (featureToIdx.contains(feature)) { continue; } int featureIdx = featureToIdx.ysize(); featureToIdx[feature] = featureIdx; features->push_back(feature); } return featureToIdx; } i64 GetMaxObjectCountForFstrCalc(i64 objectCount, i32 featureCount) { return Min(objectCount, Max(i64(2e5), i64(2e9 / featureCount))); } const TDataProviderPtr GetSubsetForFstrCalc( const TDataProviderPtr dataset, NPar::ILocalExecutor* localExecutor) { ui32 totalDocumentCount = dataset->ObjectsData->GetObjectCount(); ui32 maxDocumentCount = SafeIntegerCast<ui32>( GetMaxObjectCountForFstrCalc( totalDocumentCount, SafeIntegerCast<i64>(dataset->ObjectsData->GetFeaturesLayout()->GetExternalFeatureCount()) ) ); if (totalDocumentCount > maxDocumentCount) { ui32 foldCount = totalDocumentCount / maxDocumentCount; TVector<NCB::TArraySubsetIndexing<ui32>> testSubsets; testSubsets = NCB::Split(*dataset->ObjectsGrouping, foldCount, /*oldCvStyleSplit*/ true); auto subset = dataset->GetSubset( GetSubset( dataset->ObjectsGrouping, std::move(testSubsets[0]), NCB::EObjectsOrder::Ordered ), NSystemInfo::TotalMemorySize(), localExecutor ); return subset; } else { return dataset; } } TVector<std::pair<double, TFeature>> CalcFeatureEffectAverageChange( const TFullModel& model, TConstArrayRef<double> weights) { if (model.GetTreeCount() == 0) { return TVector<std::pair<double, TFeature>>(); } TVector<double> effect; TVector<TFeature> features; THashMap<TFeature, int, TFeatureHash> featureToIdx = GetFeatureToIdxMap(model, &features); if (model.IsOblivious()) { TVector<TMxTree> trees = BuildTrees(featureToIdx, model); TVector<TConstArrayRef<double>> mxTreeWeightsPresentation; auto applyData = model.ModelTrees->GetApplyData(); auto leafOffsetPtr = applyData->TreeFirstLeafOffsets.data(); const auto leafSizes = model.ModelTrees->GetModelTreeData()->GetTreeSizes(); const int approxDimension = model.ModelTrees->GetDimensionsCount(); for (size_t treeIdx = 0; treeIdx < model.GetTreeCount(); ++treeIdx) { mxTreeWeightsPresentation.push_back( TConstArrayRef<double>( weights.data() + leafOffsetPtr[treeIdx] / approxDimension, (1ull << leafSizes[treeIdx]) ) ); } effect = CalcEffect( trees, mxTreeWeightsPresentation ); } else { effect = CalcEffectForNonObliviousModel( model, featureToIdx, weights ); } TVector<std::pair<double, int>> effectWithFeature; for (int i = 0; i < effect.ysize(); ++i) { effectWithFeature.emplace_back(effect[i], i); } Sort(effectWithFeature.begin(), effectWithFeature.end(), std::greater<std::pair<double, int>>()); TVector<std::pair<double, TFeature>> result; for (int i = 0; i < effectWithFeature.ysize(); ++i) { result.emplace_back(effectWithFeature[i].first, features[effectWithFeature[i].second]); } return result; } static TVector<std::pair<double, TFeature>> CalcFeatureEffectAverageChange( const TFullModel& model, const TDataProviderPtr dataset, NPar::ILocalExecutor* localExecutor) { TVector<double> leavesStatistics; TConstArrayRef<double> weights; if (dataset) { CB_ENSURE(dataset->GetObjectCount() != 0, "no docs in pool"); CB_ENSURE(dataset->MetaInfo.GetFeatureCount() > 0, "no features in pool"); CATBOOST_INFO_LOG << "Used dataset leave statistics for fstr calculation" << Endl; leavesStatistics = CollectLeavesStatistics(*dataset, model, localExecutor); weights = leavesStatistics; } else { CB_ENSURE( !model.ModelTrees->GetModelTreeData()->GetLeafWeights().empty(), "CalcFeatureEffect requires either non-empty LeafWeights in model or provided dataset" ); weights = model.ModelTrees->GetModelTreeData()->GetLeafWeights(); } return CalcFeatureEffectAverageChange(model, weights); } void CreateMetricAndLossDescriptionForLossChange( const TFullModel& model, NCatboostOptions::TLossDescription* metricDescription, NCatboostOptions::TLossDescription* lossDescription, bool* needYetiRankPairs, THolder<IMetric>* metric) { CB_ENSURE( TryGetObjectiveMetric(model, metricDescription), "Cannot calculate LossFunctionChange feature importances without metric, need model with params" ); CATBOOST_INFO_LOG << "Used " << *metricDescription << " metric for fstr calculation" << Endl; CB_ENSURE(TryGetLossDescription(model, lossDescription), "No loss_function in model params"); // NDCG and PFound metrics are possible for YetiRank // PFound replace with PairLogit (with YetiRank generated pairs) due to quality // NDCG used for labels not in [0., 1.] and don't use YetiRank pairs *needYetiRankPairs = (IsYetiRankLossFunction(lossDescription->GetLossFunction()) && metricDescription->LossFunction != ELossFunction::NDCG); if (*needYetiRankPairs) { *metricDescription = NCatboostOptions::ParseLossDescription("PairLogit"); } *metric = std::move( CreateMetricFromDescription(*metricDescription, model.ModelTrees->GetDimensionsCount())[0] ); CB_ENSURE((*metric)->IsAdditiveMetric(), "LossFunctionChange support only additive metric"); } TVector<TMetricHolder> CalcFeatureEffectLossChangeMetricStats( const TFullModel& model, const int featuresCount, const TShapPreparedTrees& preparedTrees, const TDataProviderPtr dataset, ECalcTypeShapValues calcType, NPar::ILocalExecutor* localExecutor) { NCatboostOptions::TLossDescription metricDescription; NCatboostOptions::TLossDescription lossDescription; bool needYetiRankPairs = false; THolder<IMetric> metric; CreateMetricAndLossDescriptionForLossChange( model, &metricDescription, &lossDescription, &needYetiRankPairs, &metric ); TRestorableFastRng64 rand(0); auto targetData = CreateModelCompatibleProcessedDataProvider( *dataset.Get(), { metricDescription }, model, GetMonopolisticFreeCpuRam(), &rand, localExecutor ).TargetData; CB_ENSURE(targetData->GetTargetDimension() <= 1, "Multi-dimensional target fstr is unimplemented yet"); ui32 documentCount = dataset->ObjectsData->GetObjectCount(); const TObjectsDataProvider& objectsData = *dataset->ObjectsData; TVector<TMetricHolder> scores(featuresCount + 1); TConstArrayRef<TQueryInfo> targetQueriesInfo = targetData->GetGroupInfo().GetOrElse(TConstArrayRef<TQueryInfo>()); TVector<TVector<double>> approx = ApplyModelMulti( model, objectsData, EPredictionType::RawFormulaVal, /*begin*/ 0, /*end*/ 0, localExecutor ); TVector<TQueryInfo> queriesInfo(targetQueriesInfo.begin(), targetQueriesInfo.end()); ui32 blockCount = queriesInfo.empty() ? documentCount : queriesInfo.size(); ui32 blockSize = Min(ui32(10000), ui32(1e6) / (featuresCount * approx.ysize())); // shapValues[blockSize][featuresCount][dim] double if (needYetiRankPairs) { ui32 maxQuerySize = 0; for (const auto& query : queriesInfo) { maxQuerySize = Max(maxQuerySize, query.GetSize()); } blockSize = Min(blockSize, ui32(ceil(20000. / maxQuerySize))); } int approxDimension = model.ModelTrees->GetDimensionsCount(); TProfileInfo profile(documentCount); TImportanceLogger importanceLogger( documentCount, "Process documents", "Started LossFunctionChange calculation", 1 ); for (ui32 queryBegin = 0; queryBegin < blockCount; queryBegin += blockSize) { profile.StartIterationBlock(); ui32 queryEnd = Min(blockCount, queryBegin + blockSize); ui32 begin, end; if (queriesInfo.empty()) { begin = queryBegin; end = queryEnd; } else { begin = queriesInfo[queryBegin].Begin; end = queriesInfo[queryEnd - 1].End; } if (needYetiRankPairs) { UpdatePairsForYetiRank( approx[0], *targetData->GetOneDimensionalTarget(), lossDescription, /*randomSeed*/ 0, queryBegin, queryEnd, &queriesInfo, localExecutor ); } scores.back().Add( metric->Eval( approx, targetData->GetOneDimensionalTarget().GetOrElse(TConstArrayRef<float>()), GetWeights(*targetData), queriesInfo, queryBegin, queryEnd, *localExecutor ) ); TVector<TVector<TVector<double>>> shapValues; CalcShapValuesInternalForFeature( preparedTrees, model, 0, begin, end, featuresCount, objectsData, &shapValues, localExecutor, calcType ); for (int featureIdx = 0; featureIdx < featuresCount; ++featureIdx) { NPar::ILocalExecutor::TExecRangeParams blockParams(begin, end); blockParams.SetBlockCountToThreadCount(); localExecutor->ExecRange([&](ui32 docIdx) { for (int dimensionIdx = 0; dimensionIdx < approxDimension; ++dimensionIdx) { approx[dimensionIdx][docIdx] -= shapValues[docIdx - begin][featureIdx][dimensionIdx]; } }, blockParams, NPar::TLocalExecutor::WAIT_COMPLETE); scores[featureIdx].Add( metric->Eval( approx, targetData->GetOneDimensionalTarget().GetOrElse(TConstArrayRef<float>()), GetWeights(*targetData), queriesInfo, queryBegin, queryEnd, *localExecutor ) ); localExecutor->ExecRange([&](ui32 docIdx) { for (int dimensionIdx = 0; dimensionIdx < approxDimension; ++dimensionIdx) { approx[dimensionIdx][docIdx] += shapValues[docIdx - begin][featureIdx][dimensionIdx]; } }, blockParams, NPar::TLocalExecutor::WAIT_COMPLETE); } if (needYetiRankPairs) { for (ui32 queryIndex = queryBegin; queryIndex < queryEnd; ++queryIndex) { queriesInfo[queryIndex].Competitors.clear(); queriesInfo[queryIndex].Competitors.shrink_to_fit(); } } profile.FinishIterationBlock(end - begin); importanceLogger.Log(profile.GetProfileResults()); } return scores; } TVector<std::pair<double, TFeature>> CalcFeatureEffectLossChangeFromScores( const TCombinationClassFeatures& combinationClassFeatures, const IMetric& metric, const TVector<TMetricHolder>& scores) { int featuresCount = combinationClassFeatures.size(); if (featuresCount == 0) { TVector<std::pair<double, TFeature>> result; return result; } TVector<std::pair<double, int>> featureScore(featuresCount); EMetricBestValue valueType; float bestValue; metric.GetBestValue(&valueType, &bestValue); for (int idx = 0; idx < featuresCount; ++idx) { double score = metric.GetFinalError(scores[idx]) - metric.GetFinalError(scores.back()); switch(valueType) { case EMetricBestValue::Min: break; case EMetricBestValue::Max: score = -score; break; case EMetricBestValue::FixedValue: score = abs(metric.GetFinalError(scores[idx]) - bestValue) - abs(metric.GetFinalError(scores.back()) - bestValue); break; default: ythrow TCatBoostException() << "unsupported bestValue metric type"; } featureScore[idx].first = score; featureScore[idx].second = idx; } Sort(featureScore.begin(), featureScore.end(), std::greater<std::pair<double, int>>()); TVector<std::pair<double, TFeature>> result; for (const auto& score: featureScore) { result.emplace_back(); result.back().first = score.first; result.back().second = combinationClassFeatures[score.second]; } return result; } static TVector<std::pair<double, TFeature>> CalcFeatureEffectLossChange( const TFullModel& model, const TDataProviderPtr dataProvider, NPar::ILocalExecutor* localExecutor, ECalcTypeShapValues calcType) { NCatboostOptions::TLossDescription metricDescription; NCatboostOptions::TLossDescription lossDescription; bool needYetiRankPairs = false; THolder<IMetric> metric; CreateMetricAndLossDescriptionForLossChange( model, &metricDescription, &lossDescription, &needYetiRankPairs, &metric ); const auto dataset = GetSubsetForFstrCalc(dataProvider, localExecutor); ui32 documentCount = dataset->ObjectsData->GetObjectCount(); CATBOOST_INFO_LOG << "Selected " << documentCount << " documents from " << dataProvider->GetObjectCount() << " for LossFunctionChange calculation." << Endl; TShapPreparedTrees preparedTrees = PrepareTrees( model, dataset.Get(), /*referenceDataset*/ nullptr, EPreCalcShapValues::Auto, localExecutor, /*calcInternalValues*/ true, calcType ); CalcShapValuesByLeaf( model, /*fixedFeatureParams*/ Nothing(), /*logPeriod*/ 0, preparedTrees.CalcInternalValues, localExecutor, &preparedTrees, calcType ); auto combinationClassFeatures = GetCombinationClassFeatures(model); int featuresCount = combinationClassFeatures.size(); auto scores = CalcFeatureEffectLossChangeMetricStats( model, featuresCount, preparedTrees, dataset, calcType, localExecutor ); return CalcFeatureEffectLossChangeFromScores(combinationClassFeatures, *metric, scores); } TVector<std::pair<double, TFeature>> CalcFeatureEffect( const TFullModel& model, const TDataProviderPtr dataset, EFstrType type, NPar::ILocalExecutor* localExecutor, ECalcTypeShapValues calcType) { type = AdjustFeatureImportanceType(type, model.GetLossFunctionName()); if (type != EFstrType::PredictionValuesChange) { CB_ENSURE_SCALE_IDENTITY(model.GetScaleAndBias(), "feature effect"); } if (type == EFstrType::LossFunctionChange) { CB_ENSURE( dataset, "Dataset is not provided for " << EFstrType::LossFunctionChange << ", choose " << EFstrType::PredictionValuesChange << " fstr type explicitly or provide dataset."); return CalcFeatureEffectLossChange(model, dataset, localExecutor, calcType); } else { CB_ENSURE_INTERNAL( type == EFstrType::PredictionValuesChange || type == EFstrType::InternalFeatureImportance, "Inappropriate fstr type " << type); return CalcFeatureEffectAverageChange(model, dataset, localExecutor); } } TVector<TFeatureEffect> CalcRegularFeatureEffect( const TVector<std::pair<double, TFeature>>& internalEffect, const TFullModel& model) { int catFeaturesCount = model.GetNumCatFeatures(); int floatFeaturesCount = model.GetNumFloatFeatures(); int textFeaturesCount = model.GetNumTextFeatures(); int embeddingFeaturesCount = model.GetNumEmbeddingFeatures(); TVector<double> catFeatureEffect(catFeaturesCount); TVector<double> floatFeatureEffect(floatFeaturesCount); TVector<double> textFeatureEffect(textFeaturesCount); TVector<double> embeddingFeatureEffect(embeddingFeaturesCount); for (const auto& effectWithSplit : internalEffect) { TFeature feature = effectWithSplit.second; switch (feature.Type) { case ESplitType::FloatFeature: floatFeatureEffect[feature.FeatureIdx] += effectWithSplit.first; break; case ESplitType::OneHotFeature: catFeatureEffect[feature.FeatureIdx] += effectWithSplit.first; break; case ESplitType::OnlineCtr: { auto& proj = feature.Ctr.Base.Projection; int featuresInSplit = proj.BinFeatures.ysize() + proj.CatFeatures.ysize() + proj.OneHotFeatures.ysize(); double addEffect = effectWithSplit.first / featuresInSplit; for (const auto& binFeature : proj.BinFeatures) { floatFeatureEffect[binFeature.FloatFeature] += addEffect; } for (auto catIndex : proj.CatFeatures) { catFeatureEffect[catIndex] += addEffect; } for (auto oneHotFeature : proj.OneHotFeatures) { catFeatureEffect[oneHotFeature.CatFeatureIdx] += addEffect; } break; } case ESplitType::EstimatedFeature: { if (feature.EstimatedFeature.SourceFeatureType == EEstimatedSourceFeatureType::Text) { textFeatureEffect[feature.EstimatedFeature.SourceFeatureId] += effectWithSplit.first; } else { CB_ENSURE( feature.EstimatedFeature.SourceFeatureType == EEstimatedSourceFeatureType::Embedding ); embeddingFeatureEffect[feature.EstimatedFeature.SourceFeatureId] += effectWithSplit.first; } break; } } } TVector<TFeatureEffect> regularFeatureEffect; for (int i = 0; i < catFeatureEffect.ysize(); ++i) { regularFeatureEffect.push_back( TFeatureEffect(catFeatureEffect[i], EFeatureType::Categorical, i) ); } for (int i = 0; i < floatFeatureEffect.ysize(); ++i) { regularFeatureEffect.push_back( TFeatureEffect(floatFeatureEffect[i], EFeatureType::Float, i) ); } for (int i = 0; i < textFeatureEffect.ysize(); ++i) { regularFeatureEffect.push_back( TFeatureEffect(textFeatureEffect[i], EFeatureType::Text, i) ); } for (int i = 0; i < embeddingFeatureEffect.ysize(); ++i) { regularFeatureEffect.push_back( TFeatureEffect(embeddingFeatureEffect[i], EFeatureType::Embedding, i) ); } Sort( regularFeatureEffect.rbegin(), regularFeatureEffect.rend(), [](const TFeatureEffect& left, const TFeatureEffect& right) { return left.Score < right.Score || (left.Score == right.Score && left.Feature.Index > right.Feature.Index); } ); return regularFeatureEffect; } TVector<double> GetFeatureEffectForLinearIndices( const TVector<std::pair<double, TFeature>>& featureEffect, const TFullModel& model) { TVector<TFeatureEffect> regularEffect = CalcRegularFeatureEffect(featureEffect, model); const NCB::TFeaturesLayout layout = MakeFeaturesLayout(model); TVector<double> effect(layout.GetExternalFeatureCount()); for (const auto& featureEffect : regularEffect) { int externalFeatureIdx = layout.GetExternalFeatureIdx( featureEffect.Feature.Index, featureEffect.Feature.Type ); effect[externalFeatureIdx] = featureEffect.Score; } return effect; } TVector<double> CalcRegularFeatureEffect( const TFullModel& model, const TDataProviderPtr dataset, EFstrType type, NPar::ILocalExecutor* localExecutor, ECalcTypeShapValues calcType) { return GetFeatureEffectForLinearIndices( CalcFeatureEffect(model, dataset, type, localExecutor, calcType), model ); } TVector<TInternalFeatureInteraction> CalcInternalFeatureInteraction(const TFullModel& model) { if (model.GetTreeCount() == 0) { return TVector<TInternalFeatureInteraction>(); } CB_ENSURE_SCALE_IDENTITY(model.GetScaleAndBias(), "feature interaction"); TVector<TFeature> features; THashMap<TFeature, int, TFeatureHash> featureToIdx = GetFeatureToIdxMap(model, &features); TVector<TFeaturePairInteractionInfo> pairwiseEffect; if (model.IsOblivious()) { TVector<TMxTree> trees = BuildTrees(featureToIdx, model); pairwiseEffect = CalcMostInteractingFeatures(trees); } else { pairwiseEffect = CalcMostInteractingFeatures( model, featureToIdx ); } TVector<TInternalFeatureInteraction> result; result.reserve(pairwiseEffect.size()); for (const auto& efffect : pairwiseEffect) { result.emplace_back(efffect.Score, features[efffect.Feature1], features[efffect.Feature2]); } return result; } TVector<TFeatureInteraction> CalcFeatureInteraction( const TVector<TInternalFeatureInteraction>& internalFeatureInteraction, const NCB::TFeaturesLayout& layout) { THashMap<std::pair<int, int>, double> sumInteraction; double totalEffect = 0; for (const auto& effectWithFeaturePair : internalFeatureInteraction) { TVector<TFeature> features{effectWithFeaturePair.FirstFeature, effectWithFeaturePair.SecondFeature}; TVector<TVector<int>> internalToRegular; for (const auto& internalFeature : features) { TVector<int> regularFeatures; if (internalFeature.Type == ESplitType::FloatFeature) { regularFeatures.push_back( layout.GetExternalFeatureIdx(internalFeature.FeatureIdx, EFeatureType::Float) ); } else { auto proj = internalFeature.Ctr.Base.Projection; for (auto& binFeature : proj.BinFeatures) { regularFeatures.push_back( layout.GetExternalFeatureIdx(binFeature.FloatFeature, EFeatureType::Float) ); } for (auto catFeature : proj.CatFeatures) { regularFeatures.push_back( layout.GetExternalFeatureIdx(catFeature, EFeatureType::Categorical) ); } } internalToRegular.push_back(regularFeatures); } double effect = effectWithFeaturePair.Score; for (int f0 : internalToRegular[0]) { for (int f1 : internalToRegular[1]) { if (f0 == f1) { continue; } if (f1 < f0) { DoSwap(f0, f1); } sumInteraction[std::make_pair(f0, f1)] += effect / (internalToRegular[0].ysize() * internalToRegular[1].ysize()); } } totalEffect += effect; } TVector<TFeatureInteraction> regularFeatureEffect; for (const auto& pairInteraction : sumInteraction) { int f0 = pairInteraction.first.first; int f1 = pairInteraction.first.second; regularFeatureEffect.push_back( TFeatureInteraction( sumInteraction[pairInteraction.first] / totalEffect * 100, layout.GetExternalFeatureType(f0), layout.GetInternalFeatureIdx(f0), layout.GetExternalFeatureType(f1), layout.GetInternalFeatureIdx(f1)) ); } Sort( regularFeatureEffect.rbegin(), regularFeatureEffect.rend(), [](const TFeatureInteraction& left, const TFeatureInteraction& right) { return left.Score < right.Score; } ); return regularFeatureEffect; } static TVector<TVector<double>> CalcFstr( const TFullModel& model, const TDataProviderPtr dataset, EFstrType type, NPar::ILocalExecutor* localExecutor, ECalcTypeShapValues calcType) { CB_ENSURE( !model.ModelTrees->GetModelTreeData()->GetLeafWeights().empty() || (dataset != nullptr), "CalcFstr requires either non-empty LeafWeights in model or provided dataset" ); TVector<double> regularEffect = CalcRegularFeatureEffect(model, dataset, type, localExecutor, calcType); TVector<TVector<double>> result; for (const auto& value : regularEffect){ TVector<double> vec = {value}; result.push_back(vec); } return result; } TVector<TVector<double>> CalcInteraction(const TFullModel& model) { const TFeaturesLayout layout = MakeFeaturesLayout(model); TVector<TInternalFeatureInteraction> internalInteraction = CalcInternalFeatureInteraction(model); TVector<TFeatureInteraction> interaction = CalcFeatureInteraction(internalInteraction, layout); TVector<TVector<double>> result; for (const auto& value : interaction){ int featureIdxFirst = layout.GetExternalFeatureIdx(value.FirstFeature.Index, value.FirstFeature.Type); int featureIdxSecond = layout.GetExternalFeatureIdx( value.SecondFeature.Index, value.SecondFeature.Type ); TVector<double> vec = { static_cast<double>(featureIdxFirst), static_cast<double>(featureIdxSecond), value.Score }; result.push_back(vec); } return result; } static bool AllFeatureIdsEmpty(TConstArrayRef<TFeatureMetaInfo> featuresMetaInfo) { return AllOf( featuresMetaInfo.begin(), featuresMetaInfo.end(), [](const auto& featureMetaInfo) { return featureMetaInfo.Name.empty(); } ); } TVector<TVector<double>> GetFeatureImportances( const EFstrType fstrType, const TFullModel& model, const TDataProviderPtr dataset, // can be nullptr const TDataProviderPtr referenceDataset, // can be nullptr int threadCount, EPreCalcShapValues mode, int logPeriod, ECalcTypeShapValues calcType, EExplainableModelOutput modelOutputType) { TSetLoggingVerboseOrSilent inThisScope(logPeriod); CB_ENSURE(model.GetTreeCount(), "Model is not trained"); if (dataset) { CheckModelAndDatasetCompatibility(model, *dataset->ObjectsData.Get()); } if (fstrType != EFstrType::PredictionValuesChange) { CB_ENSURE_SCALE_IDENTITY(model.GetScaleAndBias(), "feature importance"); } switch (fstrType) { case EFstrType::PredictionValuesChange: case EFstrType::LossFunctionChange: case EFstrType::FeatureImportance: { NPar::TLocalExecutor localExecutor; localExecutor.RunAdditionalThreads(threadCount - 1); return CalcFstr(model, dataset, fstrType, &localExecutor, calcType); } case EFstrType::Interaction: if (dataset) { CATBOOST_NOTICE_LOG << "Dataset is provided, but not used, because importance values are" " cached in the model." << Endl; } return CalcInteraction(model); case EFstrType::ShapValues: { CB_ENSURE(dataset, "Dataset is not provided"); NPar::TLocalExecutor localExecutor; localExecutor.RunAdditionalThreads(threadCount - 1); return CalcShapValues( model, *dataset, referenceDataset, /*fixedFeatureParams*/ Nothing(), logPeriod, mode, &localExecutor, calcType, modelOutputType ); } case EFstrType::PredictionDiff: { NPar::TLocalExecutor localExecutor; localExecutor.RunAdditionalThreads(threadCount - 1); CB_ENSURE(dataset, "Documents for comparison are not provided"); return GetPredictionDiff(model, *dataset, &localExecutor); } default: Y_UNREACHABLE(); } } TVector<TVector<TVector<double>>> GetFeatureImportancesMulti( const EFstrType fstrType, const TFullModel& model, const TDataProviderPtr dataset, const TDataProviderPtr referenceDataset, // can be nullptr int threadCount, EPreCalcShapValues mode, int logPeriod, ECalcTypeShapValues calcType, EExplainableModelOutput modelOutputType) { TSetLoggingVerboseOrSilent inThisScope(logPeriod); CB_ENSURE(model.GetTreeCount(), "Model is not trained"); CB_ENSURE(fstrType == EFstrType::ShapValues, "Only shap values can provide multi approxes."); CB_ENSURE(dataset, "Dataset is not provided"); CheckModelAndDatasetCompatibility(model, *dataset->ObjectsData.Get()); NPar::TLocalExecutor localExecutor; localExecutor.RunAdditionalThreads(threadCount - 1); return CalcShapValuesMulti( model, *dataset, referenceDataset, /*fixedFeatureParams*/ Nothing(), logPeriod, mode, &localExecutor, calcType, modelOutputType ); } TVector<TVector<TVector<TVector<double>>>> CalcShapFeatureInteractionMulti( const EFstrType fstrType, const TFullModel& model, const NCB::TDataProviderPtr dataset, const TMaybe<std::pair<int, int>>& pairOfFeatures, int threadCount, EPreCalcShapValues mode, int logPeriod, ECalcTypeShapValues calcType) { ValidateFeatureInteractionParams(fstrType, model, dataset, calcType); if (pairOfFeatures.Defined()) { const int flatFeatureCount = SafeIntegerCast<int>(dataset->MetaInfo.GetFeatureCount()); ValidateFeaturePair(flatFeatureCount, pairOfFeatures.GetRef()); } NPar::TLocalExecutor localExecutor; localExecutor.RunAdditionalThreads(threadCount - 1); return CalcShapInteractionValuesMulti( model, *dataset, pairOfFeatures, logPeriod, mode, &localExecutor, calcType ); } TVector<TString> GetMaybeGeneratedModelFeatureIds( const TFullModel& model, const TFeaturesLayoutPtr datasetFeaturesLayout) { const NCB::TFeaturesLayout modelFeaturesLayout = MakeFeaturesLayout(model); TVector<TString> modelFeatureIds(modelFeaturesLayout.GetExternalFeatureCount()); if (AllFeatureIdsEmpty(modelFeaturesLayout.GetExternalFeaturesMetaInfo())) { if (datasetFeaturesLayout) { THashMap<ui32, ui32> columnIndexesReorderMap; // unused CheckModelAndDatasetCompatibility(model, *datasetFeaturesLayout, &columnIndexesReorderMap); const auto datasetFeaturesMetaInfo = datasetFeaturesLayout->GetExternalFeaturesMetaInfo(); if (!AllFeatureIdsEmpty(datasetFeaturesMetaInfo)) { CB_ENSURE( datasetFeaturesMetaInfo.size() >= modelFeatureIds.size(), "Dataset has less features than the model" ); for (auto i : xrange(modelFeatureIds.size())) { modelFeatureIds[i] = datasetFeaturesMetaInfo[i].Name; } } } } else { modelFeatureIds = modelFeaturesLayout.GetExternalFeatureIds(); } for (size_t i = 0; i < modelFeatureIds.size(); ++i) { if (modelFeatureIds[i].empty()) { modelFeatureIds[i] = ToString(i); } } return modelFeatureIds; } TVector<TString> GetMaybeGeneratedModelFeatureIds(const TFullModel& model, const TDataProviderPtr dataset) { TFeaturesLayoutPtr datasetFeaturesLayout; if (dataset) { datasetFeaturesLayout = dataset->MetaInfo.FeaturesLayout; } return GetMaybeGeneratedModelFeatureIds(model, std::move(datasetFeaturesLayout)); }
; A002203: Companion Pell numbers: a(n) = 2*a(n-1) + a(n-2), a(0) = a(1) = 2. ; 2,2,6,14,34,82,198,478,1154,2786,6726,16238,39202,94642,228486,551614,1331714,3215042,7761798,18738638,45239074,109216786,263672646,636562078,1536796802,3710155682,8957108166,21624372014,52205852194,126036076402,304278004998,734592086398,1773462177794,4281516441986,10336495061766,24954506565518,60245508192802,145445522951122,351136554095046,847718631141214,2046573816377474,4940866263896162,11928306344169798,28797478952235758,69523264248641314,167844007449518386,405211279147678086,978266565744874558,2361744410637427202,5701755387019728962,13765255184676885126,33232265756373499214,80229786697423883554,193691839151221266322,467613464999866416198,1128918769150954098718,2725451003301774613634,6579820775754503325986,15885092554810781265606,38350005885376065857198,92585104325562912980002,223520214536501891817202,539625533398566696614406,1302771281333635285046014,3145168096065837266706434,7593107473465309818458882,18331383042996456903624198,44255873559458223625707278,106843130161912904155038754,257942133883284031935784786,622727397928480968026608326,1503396929740245967989001438,3629521257408972904004611202,8762439444558191775998223842,21154400146525356456001058886,51071239737608904688000341614,123296879621743165832001742114,297664998981095236352003825842,718626877583933638536009393798,1734918754148962513424022613438,4188464385881858665384054620674,10111847525912679844192131854786,24412159437707218353768318330246,58936166401327116551728768515278,142284492240361451457225855360802,343505150882050019466180479236882,829294794004461490389586813834566,2002094738890973000245354106906014,4833484271786407490880295027646594,11669063282463787982005944162199202,28171610836713983454892183352044998,68012284955891754891790310866289198,164196180748497493238472805084623394,396404646452886741368735921035535986,957005473654270975975944647155695366 mov $1,2 lpb $0 sub $0,1 mov $3,$1 add $1,$2 mul $3,2 add $2,$3 lpe mov $0,$1
;; ;; Copyright (c) 2020-2022, 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 USE_GFNI 1 %define ZUC_CIPHER_4 asm_ZucCipher_4_gfni_sse %define ZUC128_INIT_4 asm_ZucInitialization_4_gfni_sse %define ZUC256_INIT_4 asm_Zuc256Initialization_4_gfni_sse %define ZUC_KEYGEN16B_4 asm_ZucGenKeystream16B_4_gfni_sse %define ZUC_KEYGEN8B_4 asm_ZucGenKeystream8B_4_gfni_sse %define ZUC_KEYGEN4B_4 asm_ZucGenKeystream4B_4_gfni_sse %define ZUC_EIA3ROUND16B asm_Eia3Round16B_gfni_sse %define ZUC_EIA3REMAINDER asm_Eia3Remainder_gfni_sse %include "sse/zuc_x4_sse.asm"
DATA SEGMENT A DB 1,8,2,1,12,2,14,1 NA DB 8 B DB 7,1,1,7,8,10,7,7,1,1 NB DB 10 C DB 18 DUP (?) NC DB 0 DATA ENDS sseg segment stack dw 100h dup(?) sseg ends cseg segment assume ds:DATA,cs:cseg,ss:sseg sort proc L5: mov al,C[di] cmp al,C[di+1] jbe L4 xchg al,C[di+1] mov C[di],al mov ah,1 ;promotion of array C L4: inc di loop L5 ret sort endp start: mov ax,DATA mov ds,ax ;initialization for A mov ax,0 mov si,0 mov cx,0 mov cl,NA ;transfer of the array A to the array C L1: mov al,A[si] mov C[si],al inc si inc NC loop L1 ;initialization for B mov di,0 mov cl,NB ;transfer of the array B to the array C L2: mov al,B[di] mov C[si],al inc si inc di inc NC loop L2 ;sorting of the array C L3: mov ax,0 mov di,0 mov cl,NC call sort cmp ah,0 jne L3 ;delete duplicate xor si,si mov cl,NC dec cl jz SOF L8: mov al,C[si] cmp al,C[si+1] jne L6 ;duplicate mov di,si inc di mov ah,cl dec ah L7: mov al,C[di+1] mov C[di],al inc di dec ah jnz L7 mov C[di],0 dec NC loop L8 jmp SOF ;not duplicate L6: inc si loop L8 SOF: mov ah,4ch int 21h cseg ends end start
############################################################################### # Copyright 2018 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 6, 0x90 .globl k0_cpAddMulDgt_BNU .type k0_cpAddMulDgt_BNU, @function k0_cpAddMulDgt_BNU: push %rbx push %r12 mov %edx, %edx movq (%rsi), %rax cmp $(1), %rdx jnz .Lgeneral_casegas_1 mul %rcx addq %rax, (%rdi) adc $(0), %rdx mov %rdx, %rax vzeroupper pop %r12 pop %rbx ret .Lgeneral_casegas_1: lea (-40)(%rsi,%rdx,8), %rsi lea (-40)(%rdi,%rdx,8), %rdi mov $(5), %rbx sub %rdx, %rbx mul %rcx mov %rax, %r8 movq (8)(%rsi,%rbx,8), %rax mov %rdx, %r9 cmp $(0), %rbx jge .Lskip_muladd_loop4gas_1 .p2align 6, 0x90 .Lmuladd_loop4gas_1: mul %rcx xor %r10, %r10 addq %r8, (%rdi,%rbx,8) adc %rax, %r9 movq (16)(%rsi,%rbx,8), %rax adc %rdx, %r10 mul %rcx xor %r11, %r11 addq %r9, (8)(%rdi,%rbx,8) adc %rax, %r10 movq (24)(%rsi,%rbx,8), %rax adc %rdx, %r11 mul %rcx xor %r8, %r8 addq %r10, (16)(%rdi,%rbx,8) adc %rax, %r11 movq (32)(%rsi,%rbx,8), %rax adc %rdx, %r8 mul %rcx xor %r9, %r9 addq %r11, (24)(%rdi,%rbx,8) adc %rax, %r8 movq (40)(%rsi,%rbx,8), %rax adc %rdx, %r9 add $(4), %rbx jnc .Lmuladd_loop4gas_1 .Lskip_muladd_loop4gas_1: mul %rcx xor %r10, %r10 addq %r8, (%rdi,%rbx,8) adc %rax, %r9 adc %rdx, %r10 cmp $(2), %rbx ja .Lfin_mul1x4n_2gas_1 jz .Lfin_mul1x4n_3gas_1 jp .Lfin_mul1x4n_4gas_1 .Lfin_mul1x4n_1gas_1: movq (16)(%rsi,%rbx,8), %rax mul %rcx xor %r11, %r11 addq %r9, (8)(%rdi,%rbx,8) adc %rax, %r10 movq (24)(%rsi,%rbx,8), %rax adc %rdx, %r11 mul %rcx xor %r8, %r8 addq %r10, (16)(%rdi,%rbx,8) adc %rax, %r11 movq (32)(%rsi,%rbx,8), %rax adc %rdx, %r8 mul %rcx xor %r9, %r9 addq %r11, (24)(%rdi,%rbx,8) adc %rax, %r8 adc $(0), %rdx addq %r8, (32)(%rdi,%rbx,8) adc $(0), %rdx mov %rdx, %rax jmp .Lexitgas_1 .Lfin_mul1x4n_4gas_1: movq (16)(%rsi,%rbx,8), %rax mul %rcx xor %r11, %r11 addq %r9, (8)(%rdi,%rbx,8) adc %rax, %r10 movq (24)(%rsi,%rbx,8), %rax adc %rdx, %r11 mul %rcx xor %r8, %r8 addq %r10, (16)(%rdi,%rbx,8) adc %rax, %r11 adc $(0), %rdx addq %r11, (24)(%rdi,%rbx,8) adc $(0), %rdx mov %rdx, %rax jmp .Lexitgas_1 .Lfin_mul1x4n_3gas_1: movq (16)(%rsi,%rbx,8), %rax mul %rcx xor %r11, %r11 addq %r9, (8)(%rdi,%rbx,8) adc %rax, %r10 adc $(0), %rdx addq %r10, (16)(%rdi,%rbx,8) adc $(0), %rdx mov %rdx, %rax jmp .Lexitgas_1 .Lfin_mul1x4n_2gas_1: addq %r9, (8)(%rdi,%rbx,8) adc $(0), %r10 mov %r10, %rax .Lexitgas_1: vzeroupper pop %r12 pop %rbx ret .Lfe1: .size k0_cpAddMulDgt_BNU, .Lfe1-(k0_cpAddMulDgt_BNU)
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * About Marlin * * This firmware is a mashup between Sprinter and grbl. * - https://github.com/kliment/Sprinter * - https://github.com/grbl/grbl */ #include "MarlinCore.h" #if ENABLED(MARLIN_DEV_MODE) #warning "WARNING! Disable MARLIN_DEV_MODE for the final build!" #endif #include "HAL/shared/Delay.h" #include "HAL/shared/esp_wifi.h" #ifdef ARDUINO #include <pins_arduino.h> #endif #include <math.h> #include "core/utility.h" #include "module/motion.h" #include "module/planner.h" #include "module/endstops.h" #include "module/temperature.h" #include "module/settings.h" #include "module/printcounter.h" // PrintCounter or Stopwatch #include "module/stepper.h" #include "module/stepper/indirection.h" #include "gcode/gcode.h" #include "gcode/parser.h" #include "gcode/queue.h" #include "sd/cardreader.h" #include "lcd/ultralcd.h" #if HAS_TOUCH_XPT2046 #include "lcd/touch/touch_buttons.h" #endif #if HAS_TFT_LVGL_UI #include "lcd/extui/lib/mks_ui/tft_lvgl_configuration.h" #include "lcd/extui/lib/mks_ui/draw_ui.h" #include "lcd/extui/lib/mks_ui/mks_hardware_test.h" #include <lvgl.h> #endif #if ENABLED(DWIN_CREALITY_LCD) #include "lcd/dwin/e3v2/dwin.h" #include "lcd/dwin/dwin_lcd.h" #include "lcd/dwin/e3v2/rotary_encoder.h" #endif #if ENABLED(IIC_BL24CXX_EEPROM) #include "libs/BL24CXX.h" #endif #if ENABLED(DIRECT_STEPPING) #include "feature/direct_stepping.h" #endif #if ENABLED(HOST_ACTION_COMMANDS) #include "feature/host_actions.h" #endif #if USE_BEEPER #include "libs/buzzer.h" #endif #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER) #include "feature/closedloop.h" #endif #if HAS_MOTOR_CURRENT_I2C #include "feature/digipot/digipot.h" #endif #if ENABLED(MIXING_EXTRUDER) #include "feature/mixing.h" #endif #if ENABLED(MAX7219_DEBUG) #include "feature/max7219.h" #endif #if HAS_COLOR_LEDS #include "feature/leds/leds.h" #endif #if ENABLED(BLTOUCH) #include "feature/bltouch.h" #endif #if ENABLED(POLL_JOG) #include "feature/joystick.h" #endif #if HAS_SERVOS #include "module/servo.h" #endif #if ENABLED(HAS_MOTOR_CURRENT_DAC) #include "feature/dac/stepper_dac.h" #endif #if ENABLED(EXPERIMENTAL_I2CBUS) #include "feature/twibus.h" TWIBus i2c; #endif #if ENABLED(I2C_POSITION_ENCODERS) #include "feature/encoder_i2c.h" #endif #if HAS_TRINAMIC_CONFIG && DISABLED(PSU_DEFAULT_OFF) #include "feature/tmc_util.h" #endif #if HAS_CUTTER #include "feature/spindle_laser.h" #endif #if ENABLED(SDSUPPORT) CardReader card; #endif #if ENABLED(G38_PROBE_TARGET) uint8_t G38_move; // = 0 bool G38_did_trigger; // = false #endif #if ENABLED(DELTA) #include "module/delta.h" #elif IS_SCARA #include "module/scara.h" #endif #if HAS_LEVELING #include "feature/bedlevel/bedlevel.h" #endif #if BOTH(ADVANCED_PAUSE_FEATURE, PAUSE_PARK_NO_STEPPER_TIMEOUT) #include "feature/pause.h" #endif #if ENABLED(POWER_LOSS_RECOVERY) #include "feature/powerloss.h" #endif #if ENABLED(CANCEL_OBJECTS) #include "feature/cancel_object.h" #endif #if HAS_FILAMENT_SENSOR #include "feature/runout.h" #endif #if HAS_Z_SERVO_PROBE #include "module/probe.h" #endif #if ENABLED(HOTEND_IDLE_TIMEOUT) #include "feature/hotend_idle.h" #endif #if ENABLED(TEMP_STAT_LEDS) #include "feature/leds/tempstat.h" #endif #if ENABLED(CASE_LIGHT_ENABLE) #include "feature/caselight.h" #endif #if HAS_FANMUX #include "feature/fanmux.h" #endif #if DO_SWITCH_EXTRUDER || ANY(SWITCHING_NOZZLE, PARKING_EXTRUDER, MAGNETIC_PARKING_EXTRUDER, ELECTROMAGNETIC_SWITCHING_TOOLHEAD, SWITCHING_TOOLHEAD) #include "module/tool_change.h" #endif #if ENABLED(USE_CONTROLLER_FAN) #include "feature/controllerfan.h" #endif #if ENABLED(PRUSA_MMU2) #include "feature/mmu2/mmu2.h" #endif #if HAS_L64XX #include "libs/L64XX/L64XX_Marlin.h" #endif #if ENABLED(PASSWORD_FEATURE) #include "feature/password/password.h" #endif PGMSTR(NUL_STR, ""); PGMSTR(M112_KILL_STR, "M112 Shutdown"); PGMSTR(G28_STR, "G28"); PGMSTR(M21_STR, "M21"); PGMSTR(M23_STR, "M23 %s"); PGMSTR(M24_STR, "M24"); PGMSTR(SP_P_STR, " P"); PGMSTR(SP_T_STR, " T"); PGMSTR(X_STR, "X"); PGMSTR(Y_STR, "Y"); PGMSTR(Z_STR, "Z"); PGMSTR(E_STR, "E"); PGMSTR(X_LBL, "X:"); PGMSTR(Y_LBL, "Y:"); PGMSTR(Z_LBL, "Z:"); PGMSTR(E_LBL, "E:"); PGMSTR(SP_A_STR, " A"); PGMSTR(SP_B_STR, " B"); PGMSTR(SP_C_STR, " C"); PGMSTR(SP_X_STR, " X"); PGMSTR(SP_Y_STR, " Y"); PGMSTR(SP_Z_STR, " Z"); PGMSTR(SP_E_STR, " E"); PGMSTR(SP_X_LBL, " X:"); PGMSTR(SP_Y_LBL, " Y:"); PGMSTR(SP_Z_LBL, " Z:"); PGMSTR(SP_E_LBL, " E:"); MarlinState marlin_state = MF_INITIALIZING; // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop bool wait_for_heatup = true; // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop #if HAS_RESUME_CONTINUE bool wait_for_user; // = false; void wait_for_user_response(millis_t ms/*=0*/, const bool no_sleep/*=false*/) { TERN(ADVANCED_PAUSE_FEATURE,,UNUSED(no_sleep)); KEEPALIVE_STATE(PAUSED_FOR_USER); wait_for_user = true; if (ms) ms += millis(); // expire time while (wait_for_user && !(ms && ELAPSED(millis(), ms))) idle(TERN_(ADVANCED_PAUSE_FEATURE, no_sleep)); wait_for_user = false; } #endif #if PIN_EXISTS(CHDK) extern millis_t chdk_timeout; #endif #if ENABLED(I2C_POSITION_ENCODERS) I2CPositionEncodersMgr I2CPEM; #endif /** * *************************************************************************** * ******************************** FUNCTIONS ******************************** * *************************************************************************** */ void setup_killpin() { #if HAS_KILL #if KILL_PIN_STATE SET_INPUT_PULLDOWN(KILL_PIN); #else SET_INPUT_PULLUP(KILL_PIN); #endif #endif } void setup_powerhold() { #if HAS_SUICIDE OUT_WRITE(SUICIDE_PIN, !SUICIDE_PIN_INVERTING); #endif #if ENABLED(PSU_CONTROL) powersupply_on = ENABLED(PSU_DEFAULT_OFF); if (ENABLED(PSU_DEFAULT_OFF)) PSU_OFF(); else PSU_ON(); #endif } /** * Stepper Reset (RigidBoard, et.al.) */ #if HAS_STEPPER_RESET void disableStepperDrivers() { OUT_WRITE(STEPPER_RESET_PIN, LOW); } // Drive down to keep motor driver chips in reset void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // Set to input, allowing pullups to pull the pin high #endif #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0 void i2c_on_receive(int bytes) { // just echo all bytes received to serial i2c.receive(bytes); } void i2c_on_request() { // just send dummy data for now i2c.reply("Hello World!\n"); } #endif /** * Sensitive pin test for M42, M226 */ #include "pins/sensitive_pins.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wnarrowing" bool pin_is_protected(const pin_t pin) { static const pin_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; LOOP_L_N(i, COUNT(sensitive_pins)) { pin_t sensitive_pin; memcpy_P(&sensitive_pin, &sensitive_pins[i], sizeof(pin_t)); if (pin == sensitive_pin) return true; } return false; } #pragma GCC diagnostic pop void protected_pin_err() { SERIAL_ERROR_MSG(STR_ERR_PROTECTED_PIN); } void quickstop_stepper() { planner.quick_stop(); planner.synchronize(); set_current_from_steppers_for_axis(ALL_AXES); sync_plan_position(); } void enable_e_steppers() { #define _ENA_E(N) ENABLE_AXIS_E##N(); REPEAT(E_STEPPERS, _ENA_E) } void enable_all_steppers() { TERN_(AUTO_POWER_CONTROL, powerManager.power_on()); ENABLE_AXIS_X(); ENABLE_AXIS_Y(); ENABLE_AXIS_Z(); enable_e_steppers(); } void disable_e_steppers() { #define _DIS_E(N) DISABLE_AXIS_E##N(); REPEAT(E_STEPPERS, _DIS_E) } void disable_e_stepper(const uint8_t e) { #define _CASE_DIS_E(N) case N: DISABLE_AXIS_E##N(); break; switch (e) { REPEAT(EXTRUDERS, _CASE_DIS_E) } } void disable_all_steppers() { DISABLE_AXIS_X(); DISABLE_AXIS_Y(); DISABLE_AXIS_Z(); disable_e_steppers(); } #if ENABLED(G29_RETRY_AND_RECOVER) void event_probe_failure() { #ifdef ACTION_ON_G29_FAILURE host_action(PSTR(ACTION_ON_G29_FAILURE)); #endif #ifdef G29_FAILURE_COMMANDS gcode.process_subcommands_now_P(PSTR(G29_FAILURE_COMMANDS)); #endif #if ENABLED(G29_HALT_ON_FAILURE) #ifdef ACTION_ON_CANCEL host_action_cancel(); #endif kill(GET_TEXT(MSG_LCD_PROBING_FAILED)); #endif } void event_probe_recover() { TERN_(HOST_PROMPT_SUPPORT, host_prompt_do(PROMPT_INFO, PSTR("G29 Retrying"), DISMISS_STR)); #ifdef ACTION_ON_G29_RECOVER host_action(PSTR(ACTION_ON_G29_RECOVER)); #endif #ifdef G29_RECOVER_COMMANDS gcode.process_subcommands_now_P(PSTR(G29_RECOVER_COMMANDS)); #endif } #endif #if ENABLED(ADVANCED_PAUSE_FEATURE) #include "feature/pause.h" #else constexpr bool did_pause_print = false; #endif /** * A Print Job exists when the timer is running or SD printing */ bool printJobOngoing() { return print_job_timer.isRunning() || IS_SD_PRINTING(); } /** * Printing is active when the print job timer is running */ bool printingIsActive() { return !did_pause_print && (print_job_timer.isRunning() || IS_SD_PRINTING()); } /** * Printing is paused according to SD or host indicators */ bool printingIsPaused() { return did_pause_print || print_job_timer.isPaused() || IS_SD_PAUSED(); } void startOrResumeJob() { if (!printingIsPaused()) { TERN_(CANCEL_OBJECTS, cancelable.reset()); TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator = 0); #if BOTH(LCD_SET_PROGRESS_MANUALLY, USE_M73_REMAINING_TIME) ui.reset_remaining_time(); #endif } print_job_timer.start(); } #if ENABLED(SDSUPPORT) inline void abortSDPrinting() { card.endFilePrint(TERN_(SD_RESORT, true)); queue.clear(); quickstop_stepper(); print_job_timer.stop(); #if DISABLED(SD_ABORT_NO_COOLDOWN) thermalManager.disable_all_heaters(); #endif #if !HAS_CUTTER thermalManager.zero_fan_speeds(); #else cutter.kill(); // Full cutter shutdown including ISR control #endif wait_for_heatup = false; TERN_(POWER_LOSS_RECOVERY, recovery.purge()); #ifdef EVENT_GCODE_SD_ABORT queue.inject_P(PSTR(EVENT_GCODE_SD_ABORT)); #endif TERN_(PASSWORD_AFTER_SD_PRINT_ABORT, password.lock_machine()); } inline void finishSDPrinting() { if (queue.enqueue_one_P(PSTR("M1001"))) { marlin_state = MF_RUNNING; TERN_(PASSWORD_AFTER_SD_PRINT_END, password.lock_machine()); } } #endif // SDSUPPORT /** * Minimal management of Marlin's core activities: * - Keep the command buffer full * - Check for maximum inactive time between commands * - Check for maximum inactive time between stepper commands * - Check if CHDK_PIN needs to go LOW * - Check for KILL button held down * - Check for HOME button held down * - Check if cooling fan needs to be switched on * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT) * - Pulse FET_SAFETY_PIN if it exists */ inline void manage_inactivity(const bool ignore_stepper_queue=false) { if (queue.length < BUFSIZE) queue.get_available_commands(); const millis_t ms = millis(); // Prevent steppers timing-out in the middle of M600 // unless PAUSE_PARK_NO_STEPPER_TIMEOUT is disabled const bool parked_or_ignoring = ignore_stepper_queue || (BOTH(ADVANCED_PAUSE_FEATURE, PAUSE_PARK_NO_STEPPER_TIMEOUT) && did_pause_print); // Reset both the M18/M84 activity timeout and the M85 max 'kill' timeout if (parked_or_ignoring) gcode.reset_stepper_timeout(ms); if (gcode.stepper_max_timed_out(ms)) { SERIAL_ERROR_START(); SERIAL_ECHOLNPAIR(STR_KILL_INACTIVE_TIME, parser.command_ptr); kill(); } // M18 / M94 : Handle steppers inactive time timeout if (gcode.stepper_inactive_time) { static bool already_shutdown_steppers; // = false // Any moves in the planner? Resets both the M18/M84 // activity timeout and the M85 max 'kill' timeout if (planner.has_blocks_queued()) gcode.reset_stepper_timeout(ms); else if (!parked_or_ignoring && gcode.stepper_inactive_timeout()) { if (!already_shutdown_steppers) { already_shutdown_steppers = true; // L6470 SPI will consume 99% of free time without this // Individual axes will be disabled if configured if (ENABLED(DISABLE_INACTIVE_X)) DISABLE_AXIS_X(); if (ENABLED(DISABLE_INACTIVE_Y)) DISABLE_AXIS_Y(); if (ENABLED(DISABLE_INACTIVE_Z)) DISABLE_AXIS_Z(); if (ENABLED(DISABLE_INACTIVE_E)) disable_e_steppers(); TERN_(AUTO_BED_LEVELING_UBL, ubl.steppers_were_disabled()); } } else already_shutdown_steppers = false; } #if PIN_EXISTS(CHDK) // Check if pin should be set to LOW (after M240 set it HIGH) if (chdk_timeout && ELAPSED(ms, chdk_timeout)) { chdk_timeout = 0; WRITE(CHDK_PIN, LOW); } #endif #if HAS_KILL // Check if the kill button was pressed and wait just in case it was an accidental // key kill key press // ------------------------------------------------------------------------------- static int killCount = 0; // make the inactivity button a bit less responsive const int KILL_DELAY = 750; if (kill_state()) killCount++; else if (killCount > 0) killCount--; // Exceeded threshold and we can confirm that it was not accidental // KILL the machine // ---------------------------------------------------------------- if (killCount >= KILL_DELAY) { SERIAL_ERROR_MSG(STR_KILL_BUTTON); kill(); } #endif #if HAS_HOME // Handle a standalone HOME button constexpr millis_t HOME_DEBOUNCE_DELAY = 1000UL; static millis_t next_home_key_ms; // = 0 if (!IS_SD_PRINTING() && !READ(HOME_PIN)) { // HOME_PIN goes LOW when pressed const millis_t ms = millis(); if (ELAPSED(ms, next_home_key_ms)) { next_home_key_ms = ms + HOME_DEBOUNCE_DELAY; LCD_MESSAGEPGM(MSG_AUTO_HOME); queue.enqueue_now_P(G28_STR); } } #endif TERN_(USE_CONTROLLER_FAN, controllerFan.update()); // Check if fan should be turned on to cool stepper drivers down TERN_(AUTO_POWER_CONTROL, powerManager.check()); TERN_(HOTEND_IDLE_TIMEOUT, hotend_idle.check()); #if ENABLED(EXTRUDER_RUNOUT_PREVENT) if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP && ELAPSED(ms, gcode.previous_move_ms + SEC_TO_MS(EXTRUDER_RUNOUT_SECONDS)) && !planner.has_blocks_queued() ) { #if ENABLED(SWITCHING_EXTRUDER) bool oldstatus; switch (active_extruder) { default: oldstatus = E0_ENABLE_READ(); ENABLE_AXIS_E0(); break; #if E_STEPPERS > 1 case 2: case 3: oldstatus = E1_ENABLE_READ(); ENABLE_AXIS_E1(); break; #if E_STEPPERS > 2 case 4: case 5: oldstatus = E2_ENABLE_READ(); ENABLE_AXIS_E2(); break; #if E_STEPPERS > 3 case 6: case 7: oldstatus = E3_ENABLE_READ(); ENABLE_AXIS_E3(); break; #endif // E_STEPPERS > 3 #endif // E_STEPPERS > 2 #endif // E_STEPPERS > 1 } #else // !SWITCHING_EXTRUDER bool oldstatus; switch (active_extruder) { default: #define _CASE_EN(N) case N: oldstatus = E##N##_ENABLE_READ(); ENABLE_AXIS_E##N(); break; REPEAT(E_STEPPERS, _CASE_EN); } #endif const float olde = current_position.e; current_position.e += EXTRUDER_RUNOUT_EXTRUDE; line_to_current_position(MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED)); current_position.e = olde; planner.set_e_position_mm(olde); planner.synchronize(); #if ENABLED(SWITCHING_EXTRUDER) switch (active_extruder) { default: oldstatus = E0_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 1 case 2: case 3: oldstatus = E1_ENABLE_WRITE(oldstatus); break; #if E_STEPPERS > 2 case 4: case 5: oldstatus = E2_ENABLE_WRITE(oldstatus); break; #endif // E_STEPPERS > 2 #endif // E_STEPPERS > 1 } #else // !SWITCHING_EXTRUDER switch (active_extruder) { #define _CASE_RESTORE(N) case N: E##N##_ENABLE_WRITE(oldstatus); break; REPEAT(E_STEPPERS, _CASE_RESTORE); } #endif // !SWITCHING_EXTRUDER gcode.reset_stepper_timeout(ms); } #endif // EXTRUDER_RUNOUT_PREVENT #if ENABLED(DUAL_X_CARRIAGE) // handle delayed move timeout if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) { // travel moves have been received so enact them delayed_move_time = 0xFFFFFFFFUL; // force moves to be done destination = current_position; prepare_line_to_destination(); } #endif TERN_(TEMP_STAT_LEDS, handle_status_leds()); TERN_(MONITOR_DRIVER_STATUS, monitor_tmc_drivers()); TERN_(MONITOR_L6470_DRIVER_STATUS, L64xxManager.monitor_driver()); // Limit check_axes_activity frequency to 10Hz static millis_t next_check_axes_ms = 0; if (ELAPSED(ms, next_check_axes_ms)) { planner.check_axes_activity(); next_check_axes_ms = ms + 100UL; } #if PIN_EXISTS(FET_SAFETY) static millis_t FET_next; if (ELAPSED(ms, FET_next)) { FET_next = ms + FET_SAFETY_DELAY; // 2µs pulse every FET_SAFETY_DELAY mS OUT_WRITE(FET_SAFETY_PIN, !FET_SAFETY_INVERTED); DELAY_US(2); WRITE(FET_SAFETY_PIN, FET_SAFETY_INVERTED); } #endif } /** * Standard idle routine keeps the machine alive: * - Core Marlin activities * - Manage heaters (and Watchdog) * - Max7219 heartbeat, animation, etc. * * Only after setup() is complete: * - Handle filament runout sensors * - Run HAL idle tasks * - Handle Power-Loss Recovery * - Run StallGuard endstop checks * - Handle SD Card insert / remove * - Handle USB Flash Drive insert / remove * - Announce Host Keepalive state (if any) * - Update the Print Job Timer state * - Update the Beeper queue * - Read Buttons and Update the LCD * - Run i2c Position Encoders * - Auto-report Temperatures / SD Status * - Update the Průša MMU2 * - Handle Joystick jogging */ void idle(TERN_(ADVANCED_PAUSE_FEATURE, bool no_stepper_sleep/*=false*/)) { // Core Marlin activities manage_inactivity(TERN_(ADVANCED_PAUSE_FEATURE, no_stepper_sleep)); // Manage Heaters (and Watchdog) thermalManager.manage_heater(); // Max7219 heartbeat, animation, etc TERN_(MAX7219_DEBUG, max7219.idle_tasks()); // Return if setup() isn't completed if (marlin_state == MF_INITIALIZING) return; // Handle filament runout sensors TERN_(HAS_FILAMENT_SENSOR, runout.run()); // Run HAL idle tasks #ifdef HAL_IDLETASK HAL_idletask(); #endif // Handle Power-Loss Recovery #if ENABLED(POWER_LOSS_RECOVERY) && PIN_EXISTS(POWER_LOSS) if (printJobOngoing()) recovery.outage(); #endif // Run StallGuard endstop checks #if ENABLED(SPI_ENDSTOPS) if (endstops.tmc_spi_homing.any && TERN1(IMPROVE_HOMING_RELIABILITY, ELAPSED(millis(), sg_guard_period)) ) LOOP_L_N(i, 4) // Read SGT 4 times per idle loop if (endstops.tmc_spi_homing_check()) break; #endif // Handle SD Card insert / remove TERN_(SDSUPPORT, card.manage_media()); // Handle USB Flash Drive insert / remove TERN_(USB_FLASH_DRIVE_SUPPORT, Sd2Card::idle()); // Announce Host Keepalive state (if any) TERN_(HOST_KEEPALIVE_FEATURE, gcode.host_keepalive()); // Update the Print Job Timer state TERN_(PRINTCOUNTER, print_job_timer.tick()); // Update the Beeper queue TERN_(USE_BEEPER, buzzer.tick()); // Handle UI input / draw events TERN(DWIN_CREALITY_LCD, DWIN_Update(), ui.update()); // Run i2c Position Encoders #if ENABLED(I2C_POSITION_ENCODERS) static millis_t i2cpem_next_update_ms; if (planner.has_blocks_queued()) { const millis_t ms = millis(); if (ELAPSED(ms, i2cpem_next_update_ms)) { I2CPEM.update(); i2cpem_next_update_ms = ms + I2CPE_MIN_UPD_TIME_MS; } } #endif // Auto-report Temperatures / SD Status #if HAS_AUTO_REPORTING if (!gcode.autoreport_paused) { TERN_(AUTO_REPORT_TEMPERATURES, thermalManager.auto_report_temperatures()); TERN_(AUTO_REPORT_SD_STATUS, card.auto_report_sd_status()); } #endif // Update the Průša MMU2 TERN_(PRUSA_MMU2, mmu2.mmu_loop()); // Handle Joystick jogging TERN_(POLL_JOG, joystick.inject_jog_moves()); // Direct Stepping TERN_(DIRECT_STEPPING, page_manager.write_responses()); #if HAS_TFT_LVGL_UI LV_TASK_HANDLER(); #endif } /** * Kill all activity and lock the machine. * After this the machine will need to be reset. */ void kill(PGM_P const lcd_error/*=nullptr*/, PGM_P const lcd_component/*=nullptr*/, const bool steppers_off/*=false*/) { thermalManager.disable_all_heaters(); TERN_(HAS_CUTTER, cutter.kill()); // Full cutter shutdown including ISR control SERIAL_ERROR_MSG(STR_ERR_KILLED); #if HAS_DISPLAY ui.kill_screen(lcd_error ?: GET_TEXT(MSG_KILLED), lcd_component ?: NUL_STR); #else UNUSED(lcd_error); UNUSED(lcd_component); #endif #if HAS_TFT_LVGL_UI lv_draw_error_message(lcd_error); #endif #ifdef ACTION_ON_KILL host_action_kill(); #endif minkill(steppers_off); } void minkill(const bool steppers_off/*=false*/) { // Wait a short time (allows messages to get out before shutting down. for (int i = 1000; i--;) DELAY_US(600); cli(); // Stop interrupts // Wait to ensure all interrupts stopped for (int i = 1000; i--;) DELAY_US(250); // Reiterate heaters off thermalManager.disable_all_heaters(); TERN_(HAS_CUTTER, cutter.kill()); // Reiterate cutter shutdown // Power off all steppers (for M112) or just the E steppers steppers_off ? disable_all_steppers() : disable_e_steppers(); TERN_(PSU_CONTROL, PSU_OFF()); TERN_(HAS_SUICIDE, suicide()); #if HAS_KILL // Wait for kill to be released while (kill_state()) watchdog_refresh(); // Wait for kill to be pressed while (!kill_state()) watchdog_refresh(); void (*resetFunc)() = 0; // Declare resetFunc() at address 0 resetFunc(); // Jump to address 0 #else for (;;) watchdog_refresh(); // Wait for reset #endif } /** * Turn off heaters and stop the print in progress * After a stop the machine may be resumed with M999 */ void stop() { thermalManager.disable_all_heaters(); // 'unpause' taken care of in here print_job_timer.stop(); #if ENABLED(PROBING_FANS_OFF) if (thermalManager.fans_paused) thermalManager.set_fans_paused(false); // put things back the way they were #endif if (IsRunning()) { SERIAL_ERROR_MSG(STR_ERR_STOPPED); LCD_MESSAGEPGM(MSG_STOPPED); safe_delay(350); // allow enough time for messages to get out before stopping marlin_state = MF_STOPPED; } } inline void tmc_standby_setup() { #if PIN_EXISTS(X_STDBY) SET_INPUT_PULLDOWN(X_STDBY_PIN); #endif #if PIN_EXISTS(X2_STDBY) SET_INPUT_PULLDOWN(X2_STDBY_PIN); #endif #if PIN_EXISTS(Y_STDBY) SET_INPUT_PULLDOWN(Y_STDBY_PIN); #endif #if PIN_EXISTS(Y2_STDBY) SET_INPUT_PULLDOWN(Y2_STDBY_PIN); #endif #if PIN_EXISTS(Z_STDBY) SET_INPUT_PULLDOWN(Z_STDBY_PIN); #endif #if PIN_EXISTS(Z2_STDBY) SET_INPUT_PULLDOWN(Z2_STDBY_PIN); #endif #if PIN_EXISTS(Z3_STDBY) SET_INPUT_PULLDOWN(Z3_STDBY_PIN); #endif #if PIN_EXISTS(Z4_STDBY) SET_INPUT_PULLDOWN(Z4_STDBY_PIN); #endif #if PIN_EXISTS(E0_STDBY) SET_INPUT_PULLDOWN(E0_STDBY_PIN); #endif #if PIN_EXISTS(E1_STDBY) SET_INPUT_PULLDOWN(E1_STDBY_PIN); #endif #if PIN_EXISTS(E2_STDBY) SET_INPUT_PULLDOWN(E2_STDBY_PIN); #endif #if PIN_EXISTS(E3_STDBY) SET_INPUT_PULLDOWN(E3_STDBY_PIN); #endif #if PIN_EXISTS(E4_STDBY) SET_INPUT_PULLDOWN(E4_STDBY_PIN); #endif #if PIN_EXISTS(E5_STDBY) SET_INPUT_PULLDOWN(E5_STDBY_PIN); #endif #if PIN_EXISTS(E6_STDBY) SET_INPUT_PULLDOWN(E6_STDBY_PIN); #endif #if PIN_EXISTS(E7_STDBY) SET_INPUT_PULLDOWN(E7_STDBY_PIN); #endif } /** * Marlin entry-point: Set up before the program loop * - Set up the kill pin, filament runout, power hold * - Start the serial port * - Print startup messages and diagnostics * - Get EEPROM or default settings * - Initialize managers for: * • temperature * • planner * • watchdog * • stepper * • photo pin * • servos * • LCD controller * • Digipot I2C * • Z probe sled * • status LEDs * • Max7219 */ void setup() { tmc_standby_setup(); // TMC Low Power Standby pins must be set early or they're not usable #if ENABLED(MARLIN_DEV_MODE) auto log_current_ms = [&](PGM_P const msg) { SERIAL_ECHO_START(); SERIAL_CHAR('['); SERIAL_ECHO(millis()); SERIAL_ECHOPGM("] "); serialprintPGM(msg); SERIAL_EOL(); }; #define SETUP_LOG(M) log_current_ms(PSTR(M)) #else #define SETUP_LOG(...) NOOP #endif #define SETUP_RUN(C) do{ SETUP_LOG(STRINGIFY(C)); C; }while(0) #if EITHER(DISABLE_DEBUG, DISABLE_JTAG) // Disable any hardware debug to free up pins for IO #if ENABLED(DISABLE_DEBUG) && defined(JTAGSWD_DISABLE) JTAGSWD_DISABLE(); #elif defined(JTAG_DISABLE) JTAG_DISABLE(); #else #error "DISABLE_(DEBUG|JTAG) is not supported for the selected MCU/Board." #endif #endif MYSERIAL0.begin(BAUDRATE); uint32_t serial_connect_timeout = millis() + 1000UL; while (!MYSERIAL0 && PENDING(millis(), serial_connect_timeout)) { /*nada*/ } #if HAS_MULTI_SERIAL MYSERIAL1.begin(BAUDRATE); serial_connect_timeout = millis() + 1000UL; while (!MYSERIAL1 && PENDING(millis(), serial_connect_timeout)) { /*nada*/ } #endif SERIAL_ECHOLNPGM("start"); #if BOTH(HAS_TFT_LVGL_UI, USE_WIFI_FUNCTION) mks_esp_wifi_init(); WIFISERIAL.begin(WIFI_BAUDRATE); serial_connect_timeout = millis() + 1000UL; while (/*!WIFISERIAL && */PENDING(millis(), serial_connect_timeout)) { /*nada*/ } #endif SETUP_RUN(HAL_init()); #if HAS_L64XX SETUP_RUN(L64xxManager.init()); // Set up SPI, init drivers #endif #if ENABLED(DUET_SMART_EFFECTOR) && PIN_EXISTS(SMART_EFFECTOR_MOD) OUT_WRITE(SMART_EFFECTOR_MOD_PIN, LOW); // Put Smart Effector into NORMAL mode #endif #if HAS_FILAMENT_SENSOR SETUP_RUN(runout.setup()); #endif #if ENABLED(POWER_LOSS_RECOVERY) SETUP_RUN(recovery.setup()); #endif SETUP_RUN(setup_killpin()); #if HAS_TMC220x SETUP_RUN(tmc_serial_begin()); #endif SETUP_RUN(setup_powerhold()); #if HAS_STEPPER_RESET SETUP_RUN(disableStepperDrivers()); #endif #if HAS_TMC_SPI #if DISABLED(TMC_USE_SW_SPI) SETUP_RUN(SPI.begin()); #endif SETUP_RUN(tmc_init_cs_pins()); #endif #ifdef BOARD_INIT SETUP_LOG("BOARD_INIT"); BOARD_INIT(); #endif SETUP_RUN(esp_wifi_init()); // Check startup - does nothing if bootloader sets MCUSR to 0 const byte mcu = HAL_get_reset_source(); if (mcu & RST_POWER_ON) SERIAL_ECHOLNPGM(STR_POWERUP); if (mcu & RST_EXTERNAL) SERIAL_ECHOLNPGM(STR_EXTERNAL_RESET); if (mcu & RST_BROWN_OUT) SERIAL_ECHOLNPGM(STR_BROWNOUT_RESET); if (mcu & RST_WATCHDOG) SERIAL_ECHOLNPGM(STR_WATCHDOG_RESET); if (mcu & RST_SOFTWARE) SERIAL_ECHOLNPGM(STR_SOFTWARE_RESET); HAL_clear_reset_source(); serialprintPGM(GET_TEXT(MSG_MARLIN)); SERIAL_CHAR(' '); SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION); SERIAL_EOL(); #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR) SERIAL_ECHO_MSG( " Last Updated: " STRING_DISTRIBUTION_DATE " | Author: " STRING_CONFIG_H_AUTHOR ); #endif SERIAL_ECHO_MSG("Compiled: " __DATE__); SERIAL_ECHO_MSG(STR_FREE_MEMORY, freeMemory(), STR_PLANNER_BUFFER_BYTES, (int)sizeof(block_t) * (BLOCK_BUFFER_SIZE)); // Init buzzer pin(s) #if USE_BEEPER SETUP_RUN(buzzer.init()); #endif // Set up LEDs early #if HAS_COLOR_LEDS SETUP_RUN(leds.setup()); #endif #if ENABLED(NEOPIXEL2_SEPARATE) SETUP_RUN(leds2.setup()); #endif #if ENABLED(USE_CONTROLLER_FAN) // Set up fan controller to initialize also the default configurations. SETUP_RUN(controllerFan.setup()); #endif // UI must be initialized before EEPROM // (because EEPROM code calls the UI). #if ENABLED(DWIN_CREALITY_LCD) delay(800); // Required delay (since boot?) SERIAL_ECHOPGM("\nDWIN handshake "); if (DWIN_Handshake()) SERIAL_ECHOLNPGM("ok."); else SERIAL_ECHOLNPGM("error."); DWIN_Frame_SetDir(1); // Orientation 90° DWIN_UpdateLCD(); // Show bootscreen (first image) #else SETUP_RUN(ui.init()); #if HAS_WIRED_LCD && ENABLED(SHOW_BOOTSCREEN) SETUP_RUN(ui.show_bootscreen()); #endif SETUP_RUN(ui.reset_status()); // Load welcome message early. (Retained if no errors exist.) #endif #if BOTH(SDSUPPORT, SDCARD_EEPROM_EMULATION) SETUP_RUN(card.mount()); // Mount media with settings before first_load #endif SETUP_RUN(settings.first_load()); // Load data from EEPROM if available (or use defaults) // This also updates variables in the planner, elsewhere #if HAS_TOUCH_XPT2046 SETUP_RUN(touch.init()); #endif TERN_(HAS_M206_COMMAND, current_position += home_offset); // Init current position based on home_offset sync_plan_position(); // Vital to init stepper/planner equivalent for current_position SETUP_RUN(thermalManager.init()); // Initialize temperature loop SETUP_RUN(print_job_timer.init()); // Initial setup of print job timer SETUP_RUN(endstops.init()); // Init endstops and pullups SETUP_RUN(stepper.init()); // Init stepper. This enables interrupts! #if HAS_SERVOS SETUP_RUN(servo_init()); #endif #if HAS_Z_SERVO_PROBE SETUP_RUN(probe.servo_probe_init()); #endif #if HAS_PHOTOGRAPH OUT_WRITE(PHOTOGRAPH_PIN, LOW); #endif #if HAS_CUTTER SETUP_RUN(cutter.init()); #endif #if ENABLED(COOLANT_MIST) OUT_WRITE(COOLANT_MIST_PIN, COOLANT_MIST_INVERT); // Init Mist Coolant OFF #endif #if ENABLED(COOLANT_FLOOD) OUT_WRITE(COOLANT_FLOOD_PIN, COOLANT_FLOOD_INVERT); // Init Flood Coolant OFF #endif #if HAS_BED_PROBE SETUP_RUN(endstops.enable_z_probe(false)); #endif #if HAS_STEPPER_RESET SETUP_RUN(enableStepperDrivers()); #endif #if HAS_MOTOR_CURRENT_I2C SETUP_RUN(digipot_i2c.init()); #endif #if ENABLED(HAS_MOTOR_CURRENT_DAC) SETUP_RUN(stepper_dac.init()); #endif #if EITHER(Z_PROBE_SLED, SOLENOID_PROBE) && HAS_SOLENOID_1 OUT_WRITE(SOL1_PIN, LOW); // OFF #endif #if HAS_HOME SET_INPUT_PULLUP(HOME_PIN); #endif #if PIN_EXISTS(STAT_LED_RED) OUT_WRITE(STAT_LED_RED_PIN, LOW); // OFF #endif #if PIN_EXISTS(STAT_LED_BLUE) OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // OFF #endif #if ENABLED(CASE_LIGHT_ENABLE) #if DISABLED(CASE_LIGHT_USE_NEOPIXEL) if (PWM_PIN(CASE_LIGHT_PIN)) SET_PWM(CASE_LIGHT_PIN); else SET_OUTPUT(CASE_LIGHT_PIN); #endif SETUP_RUN(caselight.update_brightness()); #endif #if ENABLED(MK2_MULTIPLEXER) SETUP_LOG("MK2_MULTIPLEXER"); SET_OUTPUT(E_MUX0_PIN); SET_OUTPUT(E_MUX1_PIN); SET_OUTPUT(E_MUX2_PIN); #endif #if HAS_FANMUX SETUP_RUN(fanmux_init()); #endif #if ENABLED(MIXING_EXTRUDER) SETUP_RUN(mixer.init()); #endif #if ENABLED(BLTOUCH) SETUP_RUN(bltouch.init(/*set_voltage=*/true)); #endif #if ENABLED(I2C_POSITION_ENCODERS) SETUP_RUN(I2CPEM.init()); #endif #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0 SETUP_LOG("i2c..."); i2c.onReceive(i2c_on_receive); i2c.onRequest(i2c_on_request); #endif #if DO_SWITCH_EXTRUDER SETUP_RUN(move_extruder_servo(0)); // Initialize extruder servo #endif #if ENABLED(SWITCHING_NOZZLE) SETUP_LOG("SWITCHING_NOZZLE"); // Initialize nozzle servo(s) #if SWITCHING_NOZZLE_TWO_SERVOS lower_nozzle(0); raise_nozzle(1); #else move_nozzle_servo(0); #endif #endif #if ENABLED(MAGNETIC_PARKING_EXTRUDER) SETUP_RUN(mpe_settings_init()); #endif #if ENABLED(PARKING_EXTRUDER) SETUP_RUN(pe_solenoid_init()); #endif #if ENABLED(SWITCHING_TOOLHEAD) SETUP_RUN(swt_init()); #endif #if ENABLED(ELECTROMAGNETIC_SWITCHING_TOOLHEAD) SETUP_RUN(est_init()); #endif #if ENABLED(USE_WATCHDOG) SETUP_RUN(watchdog_init()); // Reinit watchdog after HAL_get_reset_source call #endif #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER) SETUP_RUN(closedloop.init()); #endif #ifdef STARTUP_COMMANDS SETUP_LOG("STARTUP_COMMANDS"); queue.inject_P(PSTR(STARTUP_COMMANDS)); #endif #if ENABLED(HOST_PROMPT_SUPPORT) SETUP_RUN(host_action_prompt_end()); #endif #if HAS_TRINAMIC_CONFIG && DISABLED(PSU_DEFAULT_OFF) SETUP_RUN(test_tmc_connection(true, true, true, true)); #endif #if ENABLED(PRUSA_MMU2) SETUP_RUN(mmu2.init()); #endif #if ENABLED(IIC_BL24CXX_EEPROM) BL24CXX::init(); const uint8_t err = BL24CXX::check(); SERIAL_ECHO_TERNARY(err, "BL24CXX Check ", "failed", "succeeded", "!\n"); #endif #if ENABLED(DWIN_CREALITY_LCD) Encoder_Configuration(); HMI_Init(); HMI_StartFrame(true); #endif #if HAS_SERVICE_INTERVALS && DISABLED(DWIN_CREALITY_LCD) ui.reset_status(true); // Show service messages or keep current status #endif #if ENABLED(MAX7219_DEBUG) SETUP_RUN(max7219.init()); #endif #if ENABLED(DIRECT_STEPPING) SETUP_RUN(page_manager.init()); #endif #if HAS_TFT_LVGL_UI #if ENABLED(SDSUPPORT) if (!card.isMounted()) SETUP_RUN(card.mount()); // Mount SD to load graphics and fonts #endif SETUP_RUN(tft_lvgl_init()); #endif #if ENABLED(PASSWORD_ON_STARTUP) SETUP_RUN(password.lock_machine()); // Will not proceed until correct password provided #endif marlin_state = MF_RUNNING; SETUP_LOG("setup() completed."); } /** * The main Marlin program loop * * - Call idle() to handle all tasks between G-code commands * Note that no G-codes from the queue can be executed during idle() * but many G-codes can be called directly anytime like macros. * - Check whether SD card auto-start is needed now. * - Check whether SD print finishing is needed now. * - Run one G-code command from the immediate or main command queue * and open up one space. Commands in the main queue may come from sd * card, host, or by direct injection. The queue will continue to fill * as long as idle() or manage_inactivity() are being called. */ void loop() { do { idle(); #if ENABLED(SDSUPPORT) card.checkautostart(); if (card.flag.abort_sd_printing) abortSDPrinting(); if (marlin_state == MF_SD_COMPLETE) finishSDPrinting(); #endif queue.advance(); endstops.event_handler(); TERN_(HAS_TFT_LVGL_UI, printer_state_polling()); } while (ENABLED(__AVR__)); // Loop forever on slower (AVR) boards }
;@Author MEHRAN JAVID ;@Copyright Copyright (C) 2021 [org 100h] jmp start ;------------------------------global variables-------------------------------------------------------------- character db 'a' row: db 0 col: db 0 boolNewline: db 0 ;-----------------------------Starting of Program----------------------------------------------------------------- start: call clearScreen push cs ; value to be displayed is in codesegment pop es mov bp, character ; address of character mov dl, [col] ; col mov dh, [row] ; row mov ah,2 int 10h ;--------------------------Main Execution starts here----------------------------------------------------- ResetCol: mov dl, [col] ; col mov dh, [row] ; row mov bh, 0 ; page 0, means first page mov bl, 0x70 ; set attribute bit 1 of AL is zero mov cx, 1 ; message size mov al,[boolNewline] ;Boolean value being used to display character on new line cmp al, 0 je Start2 mov al, 0 mov [boolNewline], al mov al, [character] call Print Start2: mov ah, 0 int 16h ; wait for any key.... cmp ah, 0x48 ; if key is 'up'. je moveUp cmp ah, 0x50 ; if key is 'down'. je moveDown cmp ah, 0x4B ; if key is 'left'. je moveLeft cmp ah, 0x4D ; if key is 'right'. je moveRight cmp ah, 0x0E ; if key is 'BackSpace'. je moveBack cmp al, 27 ; if key is 'esc' then exit. je stop cmp al, 0xD ; if key is 'Enter' then Newline. je Newline cmp dl, 79 je CheckNewline call Print SkipPrint: jmp Start2 ;------------------------------------Ends Here--------------------------------------------------- stop: mov ax,0x4c00 int 21h ;------------------------------------------------------------------------------------------------ ;------------------------------All Functions Are Below------------------------------------------- moveUp: ;------------------------------Function 1------------------------------------------ mov bh, 0 mov ah, 03h INT 10h ; gets cursor position cmp dh, 0 je skipUp sub dh, 1 ; decrements row mov [row], dh mov [col], dl mov ah,2 int 10h ; sets new cursor position skipUp: jmp ResetCol moveDown:;------------------------------Function 2------------------------------------------ mov bh, 0 mov ah, 03h INT 10h ; gets cursor position cmp dh, 24 jge skipDown add dh, 1 ; increments row mov [row], dh mov [col], dl mov ah,2 int 10h ; sets new cursor position skipDown: jmp ResetCol moveLeft:;------------------------------Function 3------------------------------------------ mov bh, 0 mov ah, 03h INT 10h ; gets cursor position cmp dl, 0 je skipLeft sub dl, 1 ; decrements col mov [col], dl mov dh, [row] mov ah,2 int 10h ; sets new cursor position skipLeft: jmp ResetCol moveRight:;------------------------------Function 4------------------------------------------ mov bh, 0 mov ah, 03h INT 10h ; gets cursor position cmp dl, 79 jge skipRight add dl, 1 ; increments col mov [col], dl mov dh, [row] mov ah,2 int 10h ; sets new cursor position skipRight: jmp ResetCol Newline:;------------------------------Function 5------------------------------------------ mov bh, 0 mov ah, 03h INT 10h ; gets cursor position add dh, 1 ; increments row mov [row], dh mov dl, 0 mov [col], dl mov ah,2 int 10h ; sets new cursor position jmp ResetCol Print:;------------------------------Function 6------------------------------------------ mov [character], al mov al, 17; ; set attribute mov ah, 13h int 10h inc dl ret CheckNewline:;------------------------------Function 7------------------------------------------ cmp dh, 24 jge ResetCol mov bh, 1 mov [boolNewline], bh mov [character], al jmp Newline moveBack:;------------------------------Function 8------------------------------------------ mov bh, 0 mov ah, 03h INT 10h ; gets cursor position cmp dl, 0 je skipBack sub dl, 1 ; decrements col mov al, ' ' mov [character], al mov bh, 0 ; page 0, means first page mov bl, 0x70 ; set attribute bit 1 of AL is zero mov cx, 1 call Print sub dl, 1 ; decrements col mov [col], dl mov dh, [row] mov ah,2 int 10h ; sets new cursor position skipBack: jmp ResetCol clearScreen:;------------------------------Function 9------------------------------------------ pusha push 0xb800 pop es mov ah, 0x70 mov al, ' ' mov si, 2000 mov di, 0 loopClearScreen: STOSW sub si, 1 cmp si, 0 jne loopClearScreen popa ret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r13 push %r14 push %r15 push %rcx push %rdi push %rsi lea addresses_WC_ht+0xc885, %rsi lea addresses_WT_ht+0xaa65, %rdi nop nop sub $57973, %r10 mov $53, %rcx rep movsb nop nop nop nop nop inc %r15 lea addresses_WT_ht+0x1a865, %rsi lea addresses_UC_ht+0x18e5, %rdi sub $25639, %r13 mov $82, %rcx rep movsw nop sub $45610, %r15 lea addresses_A_ht+0x1b465, %rsi lea addresses_D_ht+0xd1a4, %rdi nop nop nop nop add $28493, %r13 mov $127, %rcx rep movsl nop nop nop nop nop and $13423, %rsi lea addresses_WC_ht+0x12751, %r10 nop nop nop nop inc %r11 movb $0x61, (%r10) nop nop nop nop and $24614, %r10 lea addresses_A_ht+0xd965, %rsi lea addresses_A_ht+0x1cde5, %rdi nop cmp $11420, %r14 mov $120, %rcx rep movsq nop add $35167, %r15 lea addresses_normal_ht+0x32e5, %rsi lea addresses_D_ht+0x19731, %rdi sub %r13, %r13 mov $102, %rcx rep movsq xor $60923, %r11 lea addresses_WC_ht+0x6d65, %r13 nop nop nop xor %r11, %r11 movw $0x6162, (%r13) and $30097, %r15 pop %rsi pop %rdi pop %rcx pop %r15 pop %r14 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r8 push %rbx push %rcx push %rdx // Faulty Load lea addresses_PSE+0x1d865, %r12 nop nop nop nop nop xor %rbx, %rbx mov (%r12), %r10 lea oracles, %rdx and $0xff, %r10 shlq $12, %r10 mov (%rdx,%r10,1), %r10 pop %rdx pop %rcx pop %rbx pop %r8 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'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 */
cpu 80196 include reg96 ax equ 20h al equ ax ah equ ax+1 eax equ ax bx equ 24h bl equ bx bh equ bx+1 ebx equ bx cx equ 28h cl equ cx ch equ cx+1 ecx equ cx dx equ 2ch dl equ dx dh equ dx+1 edx equ dx CLRC CLRVT DI EI NOP POPF PUSHF RET RSC SETC TRAP PUSHA POPA EPTS DPTS targ: JC targ JE targ JGE targ JGT targ JH targ JLE targ JLT targ JNC targ JNE targ JNH targ JNST targ JNV targ JNVT targ JST targ JV targ JVT targ bmov eax,cx bmovi eax,cx add ax,bx add ax,2000h add ax,[bx] add ax,[bx]+ add ax,2[bx] add ax,-15[bx] add ax,700[bx] add ax,-300[bx] add ax,#1234h add ax,cx,bx add ax,cx,2000h add ax,cx,[bx] add ax,cx,[bx]+ add ax,cx,2[bx] add ax,cx,-15[bx] add ax,cx,700[bx] add ax,cx,-300[bx] add ax,cx,#1234h addb al,bl addb al,2000h addb al,[bx] addb al,[bx]+ addb al,2[bx] addb al,-15[bx] addb al,700[bx] addb al,-300[bx] addb al,#12h addb al,cl,bl addb al,cl,2000h addb al,cl,[bx] addb al,cl,[bx]+ addb al,cl,2[bx] addb al,cl,-15[bx] addb al,cl,700[bx] addb al,cl,-300[bx] addb al,cl,#12h and dx,300h mulu eax,bx,cx mulb ax,cl,ch subb cl,#5 addc ax,bx addcb al,[bx] cmp ax,[bx]+ cmpb al,2[bx] cmpl ecx,edx div eax,-15[bx] divb ax,200[bx] divu eax,-300[bx] divub ax,200 ld ax,#2345h ldb al,#16 st ax,bx stb al,[bx] subc ax,[bx]+ subcb al,2[bx] xor ax,-15[bx] xorb al,200[bx] push ax push [bx] push #1234h pop 2000h pop 10[cx] xch ax,bx xch ax,[bx] xch ax,10[bx] xch ax,-150[bx] xch ax,[bx]+ xch ax,2000h xchb bl,al xchb [bx],al xchb 10[bx],al xchb -150[bx],al xchb [bx]+,al xchb 2000h,al clr ax clrb al dec bx decb bh ext eax extb ax inc cx incb cl neg dx negb dh not ax notb al scall targ lcall targ call targ sjmp targ ljmp targ br targ br [dx] djnz cl,$ djnzw cx,$ jbc dh,3,$ jbs al,1,$ tijmp bx,ax,#127 ldbse ax,#-1 ldbze cx,[bx]+ norml eax,cl shl ax,#5 shl ax,cl shlb al,#6 shlb al,cl shll eax,#7 shll eax,cl shr ax,#5 shr ax,cl shrb al,#6 shrb al,cl shrl eax,#7 shrl eax,cl shra ax,#5 shra ax,cl shrab al,#6 shrab al,cl shral eax,#7 shral eax,cl skip dl idlpd #2 ldb al,100h ; lang ldb al,0c0h ; kurz ldb al,000h ; kurz ldb al,140h ; lang ldb al,[0c0h] ldb al,[000h] assume wsr:24h ; =100h..13fh auf 0c0h..0ffh ldb al,100h ; jetzt kurz ldb al,0c0h ; jetzt lang ldb al,000h ; immmer noch kurz ldb al,140h ; immer noch lang ldb al,[100h] ldb al,[000h] bne 2000h bc 2000h
dnl ****************************************************************************** dnl Copyright 2009 Paul Zimmermann and Alexander Kruppa. dnl dnl This file is part of the ECM Library. dnl dnl The ECM Library is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Lesser General Public License as published by dnl the Free Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl The ECM Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public dnl License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public License dnl along with the ECM Library; see the file COPYING.LIB. If not, write to dnl the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, dnl MA 02110-1301, USA. dnl ****************************************************************************** define(C, ` dnl') C mp_limb_t mulredc10(mp_limb_t * z, const mp_limb_t * x, const mp_limb_t * y, C const mp_limb_t *m, mp_limb_t inv_m); C C arguments: C r3 = ptr to result z least significant limb C r4 = ptr to input x least significant limb C r5 = ptr to input y least significant limb C r6 = ptr to modulus m least significant limb C r7 = -1/m mod 2^64 C C final carry returned in r3 include(`config.m4') GLOBL GSYM_PREFIX`'mulredc10 GLOBL .GSYM_PREFIX`'mulredc10 .section ".opd", "aw" .align 3 GSYM_PREFIX`'mulredc10: .quad .GSYM_PREFIX`'mulredc10, .TOC.@tocbase, 0 .size GSYM_PREFIX`'mulredc10, 24 C Implements multiplication and REDC for two input numbers of 10 words C The algorithm: C (Notation: a:b:c == a * 2^128 + b * 2^64 + c) C C T1:T0 = x[i]*y[0] ; C u = (T0*invm) % 2^64 ; C cy:T1 = (m[0]*u + T1:T0) / 2^64 ; /* cy:T1 <= 2*2^64 - 4 (see note 1) */ C for (j = 1; j < len; j++) C { C cy:T1:T0 = x[i]*y[j] + m[j]*u + cy:T1 ; C /* for all j result cy:T1 <= 2*2^64 - 3 (see note 2) */ C tmp[j-1] = T0; C } C tmp[len-1] = T1 ; C tmp[len] = cy ; /* cy <= 1 (see note 2) */ C for (i = 1; i < len; i++) C { C cy:T1:T0 = x[i]*y[0] + tmp[1]:tmp[0] ; C u = (T0*invm) % 2^64 ; C cy:T1 = (m[0]*u + cy:T1:T0) / 2^64 ; /* cy:T1 <= 3*2^64 - 4 (see note 3) */ C for (j = 1; j < len; j++) C { C cy:T1:T0 = x[i]*y[j] + m[j]*u + (tmp[j+1] + cy):T1 ; C /* for all j < (len-1), result cy:T1 <= 3*2^64 - 3 C for j = (len-1), result cy:T1 <= 2*2^64 - 1 (see note 4) */ C tmp[j-1] = T0; C } C tmp[len-1] = T1 ; C tmp[len] = cy ; /* cy <= 1 for all i (see note 4) */ C } C z[0 ... len-1] = tmp[0 ... len-1] ; C return (tmp[len]) ; C C notes: C C 1: m[0]*u + T1:T0 <= 2*(2^64 - 1)^2 <= 2*2^128 - 4*2^64 + 2, C so cy:T1 <= 2*2^64 - 4. C 2: For j = 1, x[i]*y[j] + m[j]*u + cy:T1 <= 2*(2^64 - 1)^2 + 2*2^64 - 4 C <= 2*2^128 - 2*2^64 - 2 = 1:(2^64-3):(2^64-2), C so cy:T1 <= 2*2^64 - 3. For j > 1, C x[i]*y[j] + m[j]*u + cy:T1 <= 2*2^128 - 2*2^64 - 1 = 1:(2^64-3):(2^64-1), C so cy:T1 <= 2*2^64 - 3 = 1:(2^64-3) holds for all j. C 3: m[0]*u + cy:T1:T0 <= 2*(2^64 - 1)^2 + 2^128 - 1 = 3*2^128 - 4*2^64 + 1, C so cy:T1 <= 3*2^64 - 4 = 2:(2^64-4) C 4: For j = 1, x[i]*y[j] + m[j]*u + (tmp[j+1] + cy):T1 C <= 2*(2^64 - 1)^2 + (3*2^64 - 4) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 2 = 2:(2^64-3):(2^64-2), C so cy:T1 <= 3*2^64 - 3. For j > 1, C x[i]*y[j] + m[j]*u + (tmp[j+1] + cy):T1 <= 2:(2^64-3):(2^64-1), C so cy:T1 <= 3*2^64 - 3 = 2:(2^64-3) holds for all j < len - 1. C For j = len - 1, we know from note 2 that tmp(len) <= 1 for i = 0. C Assume this is true for index i-1, Then C x[i]*y[len-1] + m[len-1]*u + (tmp[len] + cy):T1 C <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + 2^64 C <= 2*2^128 - 1 = 1:(2^64-1):(2^64-1), C so cy:T1 <= 1:(2^64-1) and tmp[len] <= 1 for all i by induction. C C Register vars: T0 = r13, T1 = r14, CY = r10, XI = r12, U = r11 C YP = r5, MP = r6, TP = r1 (stack ptr) C C local variables: tmp[0 ... 10] array, having 10+1 8-byte words C The tmp array needs 10+1 entries, but tmp[10] is stored in C r15, so only 10 entries are used in the stack. TEXT .align 5 C powerPC 32 byte alignment .GSYM_PREFIX`'mulredc10: C ######################################################################## C # i = 0 pass C ######################################################################### C Pass for j = 0. We need to fetch x[i] from memory and compute the new u ld r12, 0(r4) C XI = x[0] ld r0, 0(r5) C y[0] stdu r13, -8(r1) C save r13 mulld r8, r0, r12 C x[0]*y[0] low half stdu r14, -8(r1) C save r14 mulhdu r9, r0, r12 C x[0]*y[0] high half ld r0, 0(r6) C m[0] mulld r11, r7, r8 C U = T0*invm mod 2^64 stdu r15, -8(r1) C save r15 mulld r13, r0, r11 C T0 = U*m[0] low stdu r16, -8(r1) C save r16 li r16, 0 C set r16 to zero for carry propagation subi r1, r1, 80 C set tmp stack space mulhdu r14, r0, r11 C T1 = U*m[0] high ld r0, 8(r5) C y[1] addc r8, r8, r13 C adde r13, r9, r14 C T0 = initial tmp(0) addze r10, r16 C carry to CY C CY:T1:T0 <= 2*(2^64-1)^2 <= 2^2*128 - 4*2^64 + 2, hence C CY:T1 <= 2*2^64 - 4 C Pass for j = 1 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 8(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 16(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 0(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 2 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 16(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 24(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 8(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 3 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 24(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 32(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 16(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 4 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 32(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 40(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 24(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 5 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 40(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 48(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 32(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 6 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 48(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 56(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 40(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 7 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 56(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 64(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 48(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 8 mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 64(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 72(r5) C y[j+1] adde r13, r9, r14 C add high word with carry to T1 addze r10, r16 C carry to CY std r8, 56(r1) C store tmp[j-1] C CY:T1:T0 <= 2^128 - 2 + 2^128 - 2*2^64 + 1 <= C 2 * 2^128 - 2*2^64 - 1 ==> CY:T1 <= 2 * 2^64 - 3 C Pass for j = 9. Don't fetch new data from y[j+1]. mulld r8, r0, r12 C x[i]*y[j] low half mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 72(r6) C m[j] addc r13, r8, r13 C add low word to T0 adde r14, r9, r10 C add high word with carry + CY to T1 C T1:T0 <= 2^128 - 2*2^64 + 1 + 2*2^64 - 3 <= 2^128 - 2, no carry! mulld r8, r0, r11 C U*m[j] low mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word adde r13, r9, r14 C add high word with carry to T1 std r8, 64(r1) C store tmp[len-2] addze r15, r16 C put carry in r15 (tmp[len] <= 1) std r13, 72(r1) C store tmp[len-1] C ######################################################################### C # i > 0 passes C ######################################################################### li r9, 9 C outer loop count mtctr r9 1: C Pass for j = 0. We need to fetch x[i], tmp[i] and tmp[i+1] from memory C and compute the new u ldu r12, 8(r4) C x[i] ld r0, 0(r5) C y[0] ld r13, 0(r1) C tmp[0] mulld r8, r0, r12 C x[i]*y[0] low half ld r14, 8(r1) C tmp[1] mulhdu r9, r0, r12 C x[i]*y[0] high half addc r13, r8, r13 C T0 ld r0, 0(r6) C m[0] mulld r11, r7, r13 C U = T0*invm mod 2^64 adde r14, r9, r14 C T1 mulld r8, r0, r11 C U*m[0] low addze r10, r16 C CY mulhdu r9, r0, r11 C U*m[0] high ld r0, 8(r5) C y[1] addc r8, r8, r13 C result = 0 adde r13, r9, r14 C T0, carry pending C cy:T1:T0 <= 2*(2^64 - 1)^2 + 2^128 - 1 = 3*2^128 - 4*2^64 + 1, C so cy:T1 <= 3*2^64 - 4 C Pass for j = 1 ld r14, 16(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 8(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 16(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 0(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 2 ld r14, 24(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 16(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 24(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 8(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 3 ld r14, 32(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 24(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 32(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 16(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 4 ld r14, 40(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 32(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 40(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 24(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 5 ld r14, 48(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 40(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 48(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 32(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 6 ld r14, 56(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 48(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 56(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 40(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 7 ld r14, 64(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 56(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 64(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 48(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 8 ld r14, 72(r1) C tmp[j+1] mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r14, r10 C tmp[j+1] + CY + pending carry addze r10, r16 C carry to CY mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 64(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r10 C add carry to CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word ld r0, 72(r5) C y[j+1] adde r13, r9, r14 C T1, carry pending std r8, 56(r1) C store tmp[j-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + (2^64-1)*2^64 C <= 3*2^128 - 2*2^64 - 1 ==> CY:T1 <= 3*2^64 - 3 C Pass for j = 9. Don't fetch new data from y[j+1]. mulld r8, r0, r12 C x[i]*y[j] low half adde r14, r15, r10 C T1 = tmp[len] + CY + pending carry C since tmp[len] <= 1, T1 <= 3 and carry is zero mulhdu r9, r0, r12 C x[i]*y[j] high half ld r0, 72(r6) C m[j] addc r13, r8, r13 C add low word to T0 mulld r8, r0, r11 C U*m[j] low adde r14, r9, r14 C add high to T1 addze r10, r16 C CY mulhdu r9, r0, r11 C U*m[j] high addc r8, r8, r13 C add T0 and low word adde r13, r9, r14 C T1, carry pending std r8, 64(r1) C store tmp[len-2] addze r15, r10 C store tmp[len] <= 1 std r13, 72(r1) C store tmp[len-1] C CY:T1:T0 <= 2*(2^64 - 1)^2 + (3*2^64 - 3) + 2^64 C <= 2*2^128 - 1 ==> CY:T1 <= 2*2^64 - 1 = 1:(2^64-1) bdnz 1b C Copy result from tmp memory to z ld r8, 0(r1) ldu r9, 8(r1) std r8, 0(r3) stdu r9, 8(r3) ldu r8, 8(r1) ldu r9, 8(r1) stdu r8, 8(r3) stdu r9, 8(r3) ldu r8, 8(r1) ldu r9, 8(r1) stdu r8, 8(r3) stdu r9, 8(r3) ldu r8, 8(r1) ldu r9, 8(r1) stdu r8, 8(r3) stdu r9, 8(r3) ldu r8, 8(r1) ldu r9, 8(r1) stdu r8, 8(r3) stdu r9, 8(r3) mr r3, r15 C return tmp(len) ldu r16, 8(r1) ldu r15, 8(r1) ldu r14, 8(r1) ldu r13, 8(r1) addi r1, r1, 8 blr .size .GSYM_PREFIX`'mulredc10, .-.GSYM_PREFIX`'mulredc10
mov r1, 121 mov r2, 10 @y out r1 out r2 jmp %y
// Copyright (c) 2009-2017 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 <core_io.h> #include <base58.h> #include <consensus/consensus.h> #include <consensus/validation.h> #include <script/script.h> #include <script/standard.h> #include <serialize.h> #include <streams.h> #include <univalue.h> #include <util.h> #include <utilmoneystr.h> #include <utilstrencodings.h> UniValue ValueFromAmount(const CAmount& amount) { bool sign = amount < 0; int64_t n_abs = (sign ? -amount : amount); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; return UniValue(UniValue::VNUM, strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); // Maza: Updated num decimals } std::string FormatScript(const CScript& script) { std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; std::vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_NOP10) { std::string str(GetOpName(op)); if (str.substr(0, 3) == std::string("OP_")) { ret += str.substr(3, std::string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x ", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } const std::map<unsigned char, std::string> mapSigHashTypes = { {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")}, {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")}, {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")}, {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")}, // {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_FORKID), std::string("ALL|FORKID")},Maza: Replay attack protection {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")}, // {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_FORKID), std::string("NONE|FORKID")}, Maza: Replay attack protection {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")}, // {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_FORKID), std::string("SINGLE|FORKID")},Maza: Replay attack protection {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")}, // {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_FORKID|SIGHASH_ANYONECANPAY), std::string("ALL|FORKID|ANYONECANPAY")},Maza: Replay attack protection {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")}, // {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_FORKID|SIGHASH_ANYONECANPAY), std::string("NONE|FORKID|ANYONECANPAY")},Maza: Replay attack protection {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")}, // {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_FORKID|SIGHASH_ANYONECANPAY), std::string("SINGLE|FORKID|ANYONECANPAY")},Maza: Replay attack protection }; /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string representation. * @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format * of a signature. Only pass true for scripts you believe could contain signatures. For example, * pass false, or omit the this argument (defaults to false), for scriptPubKeys. */ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode) { std::string str; opcodetype opcode; std::vector<unsigned char> vch; CScript::const_iterator pc = script.begin(); while (pc < script.end()) { if (!str.empty()) { str += " "; } if (!script.GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) { str += strprintf("%d", CScriptNum(vch, false).getint()); } else { // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature if (fAttemptSighashDecode && !script.IsUnspendable()) { std::string strSigHashDecode; // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig. // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // checks in CheckSignatureEncoding. auto flags = SCRIPT_VERIFY_STRICTENC; //| SCRIPT_ENABLE_SIGHASH_FORKID; // Maza: use SCRIPT_ENABLE_SIGHASH_FORKID if (CheckSignatureEncoding(vch, flags, nullptr)) { const unsigned char chSigHashType = vch.back(); if (mapSigHashTypes.count(chSigHashType)) { strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode. } } str += HexStr(vch) + strSigHashDecode; } else { str += HexStr(vch); } } } else { str += GetOpName(opcode); } } return str; } std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); for (const CTxDestination& addr : addresses) { a.push_back(EncodeDestination(addr)); } out.pushKV("addresses", a); } void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags) { entry.pushKV("txid", tx.GetHash().GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)); entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxIn& txin = tx.vin[i]; UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { in.pushKV("txid", txin.prevout.hash.GetHex()); in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true)); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); if (!tx.vin[i].scriptWitness.IsNull()) { UniValue txinwitness(UniValue::VARR); for (const auto& item : tx.vin[i].scriptWitness.stack) { txinwitness.push_back(HexStr(item.begin(), item.end())); } in.pushKV("txinwitness", txinwitness); } } in.pushKV("sequence", (int64_t)txin.nSequence); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); out.pushKV("value", ValueFromAmount(txout.nValue)); out.pushKV("n", (int64_t)i); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } entry.pushKV("vout", vout); if (!hashBlock.IsNull()) entry.pushKV("blockhash", hashBlock.GetHex()); if (include_hex) { entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". } }
#ifndef color_cmy_convert_cmy #define color_cmy_convert_cmy #include "../category.hpp" #include "../../_internal/convert.hpp" #include "../place/place.hpp" #include "../trait/container.hpp" #include "../../_internal/reformat.hpp" namespace color { namespace _internal { template< typename tag_left_name, typename tag_right_name > struct convert < ::color::category::cmy< tag_left_name > ,::color::category::cmy< tag_right_name> > { public: typedef ::color::category::cmy< tag_left_name > category_left_type; typedef ::color::category::cmy< tag_right_name> category_right_type; typedef ::color::trait::container<category_left_type> container_left_trait_type; typedef ::color::trait::container<category_right_type> container_right_trait_type; typedef ::color::_internal::reformat< category_left_type, category_right_type > reformat_type; typedef typename container_left_trait_type::input_type container_left_input_type; typedef typename container_right_trait_type::model_type container_right_const_input_type; enum { cl_p = ::color::place::_internal::cyan<category_left_type>::position_enum ,ml_p = ::color::place::_internal::magenta<category_left_type>::position_enum ,yl_p = ::color::place::_internal::yellow<category_left_type>::position_enum }; enum { cr_p = ::color::place::_internal::cyan<category_right_type>::position_enum ,mr_p = ::color::place::_internal::magenta<category_right_type>::position_enum ,yr_p = ::color::place::_internal::yellow<category_right_type>::position_enum }; static void process ( container_left_input_type left ,container_right_const_input_type right ) { container_left_trait_type::template set<cl_p>( left, reformat_type::template process<cl_p,cr_p>( container_right_trait_type::template get<cr_p>( right ) ) ); container_left_trait_type::template set<ml_p>( left, reformat_type::template process<ml_p,mr_p>( container_right_trait_type::template get<mr_p>( right ) ) ); container_left_trait_type::template set<yl_p>( left, reformat_type::template process<yl_p,yr_p>( container_right_trait_type::template get<yr_p>( right ) ) ); } }; } } #endif
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r15 push %r8 push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x946f, %rbp nop nop cmp $57462, %r8 mov (%rbp), %rbx nop nop nop nop add %rdx, %rdx lea addresses_WT_ht+0x532f, %r15 nop nop nop cmp $55168, %rsi mov $0x6162636465666768, %r12 movq %r12, (%r15) nop nop nop nop cmp $21737, %r12 lea addresses_WC_ht+0x1582f, %rsi lea addresses_UC_ht+0x90af, %rdi nop nop nop nop nop and %rbx, %rbx mov $67, %rcx rep movsb nop nop nop nop nop and $20861, %rbx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r8 pop %r15 pop %r12 ret .global s_faulty_load s_faulty_load: push %r14 push %r15 push %r8 push %rcx push %rdi push %rdx push %rsi // REPMOV lea addresses_A+0x189af, %rsi lea addresses_normal+0x128af, %rdi clflush (%rdi) nop nop nop nop sub $23553, %rdx mov $4, %rcx rep movsw nop nop nop nop add %rdx, %rdx // REPMOV lea addresses_WT+0x178e3, %rsi lea addresses_PSE+0x14f2f, %rdi nop nop nop nop nop sub $6999, %r8 mov $50, %rcx rep movsw nop and $38929, %r14 // Load lea addresses_D+0x14faf, %r14 and %rdx, %rdx vmovups (%r14), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $0, %xmm0, %rsi inc %rdx // Faulty Load lea addresses_D+0x14faf, %rdx nop nop nop nop and %rcx, %rcx movb (%rdx), %r14b lea oracles, %r14 and $0xff, %r14 shlq $12, %r14 mov (%r14,%r14,1), %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %r8 pop %r15 pop %r14 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal', 'congruent': 5, 'same': False}} {'src': {'type': 'addresses_WT', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_PSE', 'congruent': 6, 'same': False}} {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 32, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 7}} {'src': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}} {'15': 1} 15 */
; A037573: Base 8 digits are, in order, the first n terms of the periodic sequence with initial period 2,1,2. ; Submitted by Jamie Morken(s1) ; 2,17,138,1106,8849,70794,566354,4530833,36246666,289973330,2319786641,18558293130,148466345042,1187730760337,9501846082698,76014768661586,608118149292689,4864945194341514 mov $3,1 lpb $0 sub $0,1 add $3,1 mov $1,$3 mul $1,7 add $2,$1 add $3,$2 sub $2,3 mod $2,2 lpe mov $0,$3 add $0,1
; DV3 Q40 IDE Write Sector V3.00  1998 Tony Tebby ; if LBA FAT32 access : byteswap V3.01  W. Lenerz 2017 Nov 21 section dv3 xdef id_wdirect ; write sector xdef id_wsint ; write sector internal xdef id_wsecs ; write with special key xref id_diradd ; address for direct sector xref id_cmdw xref id_statw xref.s ideo.data xref.s ideo.stat include 'dev8_keys_err' include 'dev8_dv3_keys' include 'dev8_dv3_hd_keys' include 'dev8_dv3_hd_ide_keys' include 'dev8_mac_assert' include 'dev8_keys_q40' drv_led equ hdl_freq+1 ; use led as drive activity indicator? ;+++ ; This routine writes sectors to an IDE disk for direct sector IO ; ; d0 cr sector number / error code ; d2 c p number of sectors ; d7 c p drive ID / number ; a1 c p address to write from ; a3 c p linkage block ; a4 c p drive definition ; ; status return 0, ERR.NC or ERR.MCHK ; ;--- id_wdirect assert ddf.drct-1 tst.b ddf_ftype(a4) ; real direct access? bge.s id_wsint ; ... no jsr id_diradd ; scrumple address for direct sector bne.s idw_rts ;+++ ; This routine writes sectors to an IDE disk at an even address ; ; d0 cr sector number / error code ; d2 c p number of sectors ; d7 c p drive ID / number ; a1 c p address to write from ; a3 c p linkage block ; a4 c p drive definition ; ; status return 0, ERR.NC or ERR.MCHK ; ;--- id_wsint idw.reg reg d1 move.l d1,-(sp) move.l d0,d1 assert hdl.hold,-1 subq.b #hdl.acss,hdl_acss(a3) ; hold poll bsr.s idw_do ; write ble.s idw_done bsr.s idw_retry ; try again ble.s idw_done bsr.s idw_retry ; try again idw_done beq.s idw_exrp idw_mchk moveq #err.mchk,d0 idw_exrp addq.b #hdl.acss,hdl_acss(a3) ; restore poll move.l (sp)+,d1 tst.l d0 idw_rts rts ;****************** idw_retry idw_do moveq #ide.write,d0 ;+++ ; This routine writes sectors to an IDE disk (special key) ; ; d0 cr command / error code ; d1 c p sector address ; d2 c p number of sectors ; d7 c p drive ID / number ; a1 c p address to write from ; a3 c p linkage block ; a4 c p drive definition ; ; status return 0, ERR.NC or ERR.MCHK ; ;--- id_wsecs idws.reg reg a1/d2/d3/d4/a5 movem.l idws.reg,-(sp) tst.b ddf_lba(a4) bne.s idw_cmd add.l ddf_dtop-4(a4),d1 idw_cmd jsr id_cmdw ; write sector(s) bne.s idws_exit ; command not accepted idws_sector move.l hdl_1sec(a3),d3 lsl.l #2,d3 ; allow for run-up idws_wait btst #ide..drq,ideo.stat(a5) ; wait for data request bne.s idws_copy subq.l #1,d3 bgt.s idws_wait moveq #err.mchk,d0 bra.s idws_stat idws_copy move.w #255,d3 tst.b ddf_lba(a4) ; byte switch needed? bne.s idws_cloop ; no idws_lba ; yes move.w (a1)+,d4 rol.w #8,d4 move.w d4,ideo.data(a5) ; copy data dbra d3,idws_lba idws_cpok subq.b #1,d2 bne.s idws_sector idws_stat jsr id_statw ; wait for completion idws_exit movem.l (sp)+,idws.reg tst.l d0 rts ; copy bytes when no byte switch needed idws_cloop move.w (a1)+,ideo.data(a5) ; copy data dbra d3,idws_cloop bra.s idws_cpok end
; A210645: Area A of the triangles such that A, the sides and one of the altitudes are four consecutive integers of an arithmetic progression d. ; 84,336,756,1344,2100,3024,4116,5376,6804,8400,10164,12096,14196,16464,18900,21504,24276,27216,30324,33600,37044,40656,44436,48384,52500,56784,61236,65856,70644,75600,80724,86016,91476,97104,102900,108864,114996,121296 add $0,1 mov $1,$0 pow $1,2 mul $1,84
############################################################################### # 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 5, 0x90 .globl l9_cpAESCMAC_Update_AES_NI .type l9_cpAESCMAC_Update_AES_NI, @function l9_cpAESCMAC_Update_AES_NI: movslq %edx, %rdx movdqu (%rdi), %xmm0 .p2align 5, 0x90 .Lblks_loopgas_1: movdqu (%rsi), %xmm1 movdqa (%r8), %xmm4 mov %r8, %r9 pxor %xmm1, %xmm0 pxor %xmm4, %xmm0 movdqa (16)(%r9), %xmm4 add $(16), %r9 mov %rcx, %r10 sub $(1), %r10 .p2align 5, 0x90 .Lcipher_loopgas_1: aesenc %xmm4, %xmm0 movdqa (16)(%r9), %xmm4 add $(16), %r9 dec %r10 jnz .Lcipher_loopgas_1 aesenclast %xmm4, %xmm0 add $(16), %rsi sub $(16), %rdx jnz .Lblks_loopgas_1 pxor %xmm4, %xmm4 movdqu %xmm0, (%rdi) vzeroupper ret .Lfe1: .size l9_cpAESCMAC_Update_AES_NI, .Lfe1-(l9_cpAESCMAC_Update_AES_NI)
; A176708: Partial sums of A094820. ; Submitted by Jon Maiga ; 1,3,6,11,17,25,34,45,58,73,89,108,128,150,174,201,229,260,292,327,364,403,443,487,533,581,631,684,738,796,855,917,981,1047,1115,1188,1262,1338,1416,1498,1581,1668,1756,1847,1941,2037,2134,2236,2340,2447,2556 mov $2,$0 mov $3,$0 lpb $2 mov $0,$3 sub $2,1 sub $0,$2 seq $0,94820 ; Partial sums of A038548. add $4,$0 lpe mov $0,$4 add $0,1
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft import six %> <%docstring>setresuid32(vararg_0, vararg_1, vararg_2, vararg_3, vararg_4) -> str Invokes the syscall setresuid32. See 'man 2 setresuid32' for more information. Arguments: vararg(int): vararg Returns: long </%docstring> <%page args="vararg_0=None, vararg_1=None, vararg_2=None, vararg_3=None, vararg_4=None"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = [] can_pushstr_array = [] argument_names = ['vararg_0', 'vararg_1', 'vararg_2', 'vararg_3', 'vararg_4'] argument_values = [vararg_0, vararg_1, vararg_2, vararg_3, vararg_4] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False))) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)): if isinstance(arg, six.text_type): arg = arg.encode('utf-8') string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_setresuid32']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* setresuid32(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld c, 41 ld b, 03 lbegin_waitm3: ldff a, (c) and a, b cmp a, b jrnz lbegin_waitm3 ld a, 20 ldff(c), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei ld c, 0f .text@1000 lstatint: nop .text@1065 xor a, a ldff(41), a ldff a, (c) and a, b jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %rax push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x19c0d, %rsi lea addresses_WC_ht+0x87, %rdi nop nop nop nop nop inc %rdx mov $109, %rcx rep movsl nop nop nop xor $41382, %rax lea addresses_WC_ht+0x1dc45, %rbx clflush (%rbx) nop nop nop cmp $65420, %rcx mov (%rbx), %di nop nop nop nop sub $62139, %rcx lea addresses_A_ht+0x1cbc5, %rdi clflush (%rdi) nop nop nop nop nop inc %r12 mov (%rdi), %eax nop nop cmp $28816, %rcx lea addresses_WC_ht+0xc7c5, %rdx nop xor $14325, %rcx mov $0x6162636465666768, %rdi movq %rdi, %xmm0 vmovups %ymm0, (%rdx) nop nop nop add $15552, %rax lea addresses_WC_ht+0x5fc5, %rdx nop nop nop cmp %rax, %rax movl $0x61626364, (%rdx) nop nop nop nop and %rcx, %rcx lea addresses_normal_ht+0x8fc5, %rsi lea addresses_A_ht+0x14e45, %rdi xor %r14, %r14 mov $93, %rcx rep movsw nop nop nop nop dec %rdx lea addresses_WT_ht+0xa7f9, %rcx nop nop dec %rsi mov $0x6162636465666768, %rbx movq %rbx, (%rcx) nop nop cmp %r14, %r14 lea addresses_WC_ht+0x55c5, %r12 nop nop nop cmp %rbx, %rbx movb $0x61, (%r12) nop cmp $2582, %r12 lea addresses_UC_ht+0x18b5, %rdx nop nop cmp $39463, %rcx mov $0x6162636465666768, %r14 movq %r14, %xmm2 movups %xmm2, (%rdx) nop nop nop add %rbx, %rbx lea addresses_WT_ht+0x192c5, %rsi nop nop xor %rbx, %rbx movups (%rsi), %xmm5 vpextrq $0, %xmm5, %rcx nop nop nop nop sub %rax, %rax lea addresses_WC_ht+0x11945, %rax nop nop nop xor $5147, %rsi mov $0x6162636465666768, %r14 movq %r14, %xmm4 movups %xmm4, (%rax) nop nop nop cmp $33564, %rdx lea addresses_WT_ht+0x14dc5, %rsi lea addresses_WC_ht+0x19027, %rdi nop nop xor $39625, %rax mov $89, %rcx rep movsb nop nop nop nop inc %rax lea addresses_WT_ht+0x64a5, %rbx nop nop nop nop cmp $8817, %r12 movb (%rbx), %r14b nop nop nop nop sub %rdx, %rdx lea addresses_D_ht+0x16705, %rsi lea addresses_UC_ht+0x187c5, %rdi nop nop nop dec %rax mov $85, %rcx rep movsw nop nop inc %r12 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rax pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %rax push %rcx push %rdi push %rdx // Faulty Load lea addresses_A+0xb7c5, %rdi nop nop nop cmp $53427, %r14 mov (%rdi), %cx lea oracles, %rdi and $0xff, %rcx shlq $12, %rcx mov (%rdi,%rcx,1), %rcx pop %rdx pop %rdi pop %rcx pop %rax pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 1, 'NT': True, 'type': 'addresses_A'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 3, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 6, 'AVXalign': True, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': True, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 11, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': True, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_UC_ht'}} {'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 */
; A135678: Floor(n^(4/3)+n). ; 2,4,7,10,13,16,20,24,27,31,35,39,43,47,51,56,60,65,69,74,78,83,88,93,98,103,108,113,118,123,128,133,138,144,149,154,160,165,171,176,182,187,193,199,205,210,216,222,228,234,240,246,252,258,264,270,276,282,288,294,301,307,313,320,326,332,339,345,352,358,364,371,378,384,391,397,404,411,417,424,431,438,445,451,458,465,472,479,486,493,500,507,514,521,528,535,542,549,556,564 mov $1,$0 add $0,1 pow $0,2 seq $0,77113 ; Number of integer cubes <= n^2. add $0,$1
// ================================================================================================ // // This file is part of the CAMPVis Software Framework. // // If not explicitly stated otherwise: Copyright (C) 2012-2015, all rights reserved, // Christian Schulte zu Berge <christian.szb@in.tum.de> // Chair for Computer Aided Medical Procedures // Technische Universitaet Muenchen // Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany // // For a full list of authors and contributors, please refer to the file "AUTHORS.txt". // // 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 "tfgeometry1d.h" #include "cgt/assert.h" #include "cgt/texture.h" #include "cgt/cgt_math.h" #include "core/datastructures/facegeometry.h" #include <algorithm> namespace campvis { bool operator< (const TFGeometry1D::KeyPoint& left, const TFGeometry1D::KeyPoint& right) { return left._position < right._position; } TFGeometry1D::TFGeometry1D(const std::vector<KeyPoint>& keyPoints) : _keyPoints(keyPoints) , _tfRenderFace(nullptr) , _tfEditorFace(nullptr) { std::sort(_keyPoints.begin(), _keyPoints.end()); } TFGeometry1D::~TFGeometry1D() { } TFGeometry1D* TFGeometry1D::clone() const { return new TFGeometry1D(_keyPoints); } std::vector<TFGeometry1D::KeyPoint>& TFGeometry1D::getKeyPoints() { return _keyPoints; } void TFGeometry1D::renderIntoEditor() const { // TODO: get rid of intermediade mode? if (_keyPoints.size() < 2) return; glBegin(GL_QUADS); std::vector<KeyPoint>::const_iterator a = _keyPoints.begin(); std::vector<KeyPoint>::const_iterator b = _keyPoints.begin()+1; for (/* already inited */; b != _keyPoints.end(); ++a, ++b) { glColor4ub(a->_color.r, a->_color.g, a->_color.b, 144); float y = static_cast<float>(a->_color.a) / 255.f; glVertex2f(a->_position, 0.f); glVertex2f(a->_position, y); glColor4ub(b->_color.r, b->_color.g, b->_color.b, 144); y = static_cast<float>(b->_color.a) / 255.f; glVertex2f(b->_position, y); glVertex2f(b->_position, 0.f); } glEnd(); } void TFGeometry1D::render() const { if (_keyPoints.size() < 2) return; // TODO: regenerating these buffers each time is slow as hell std::vector<cgt::vec3> vertices; std::vector<cgt::vec4> colors; for (std::vector<KeyPoint>::const_iterator a = _keyPoints.begin(); a != _keyPoints.end(); ++a) { vertices.push_back(cgt::vec3(a->_position, 0.f, 0.f)); vertices.push_back(cgt::vec3(a->_position, 1.f, 0.f)); colors.push_back(cgt::vec4(a->_color) / 255.f); colors.push_back(cgt::vec4(a->_color) / 255.f); } FaceGeometry fg(vertices, std::vector<cgt::vec3>(), colors); fg.render(GL_TRIANGLE_STRIP); } TFGeometry1D* TFGeometry1D::createQuad(const cgt::vec2& interval, const cgt::col4& leftColor, const cgt::col4& rightColor) { cgtAssert(interval.x >= 0.f && interval.y <= 1.f, "Interval out of bounds"); std::vector<KeyPoint> keyPoints; keyPoints.push_back(KeyPoint(interval.x, leftColor)); keyPoints.push_back(KeyPoint(interval.y, rightColor)); return new TFGeometry1D(keyPoints); } TFGeometry1D* TFGeometry1D::crateRamp(const cgt::vec2& interval, const cgt::col4& color) { return createQuad(interval, cgt::col4(color.xyz(), 0), cgt::col4(color.xyz(), 255)); } TFGeometry1D* TFGeometry1D::createDivergingColorMap(const cgt::vec2& interval, const cgt::col4& leftColor, const cgt::col4& rightColor, float bias /*= 0.5f*/) { cgtAssert(interval.x >= 0.f && interval.y <= 1.f, "Interval out of bounds, must be in [0, 1]."); cgtAssert(bias > 0.f && bias < 1.f, "Bias out of bounds, must be in (0, 1)."); std::vector<KeyPoint> keyPoints; keyPoints.push_back(KeyPoint(interval.x, leftColor)); keyPoints.push_back(KeyPoint(interval.x + (interval.y - interval.x) * bias, cgt::col4(255, 255, 255, 255))); keyPoints.push_back(KeyPoint(interval.y, rightColor)); return new TFGeometry1D(keyPoints); } TFGeometry1D* TFGeometry1D::createColdHotColorMap(const cgt::vec2& interval /*= cgt::vec2(0.f, 1.f)*/) { return createDivergingColorMap(interval, cgt::col4(0, 0, 255, 255), cgt::col4(255, 0, 0, 255), 0.5f); } TFGeometry1D* TFGeometry1D::createHeatedBodyColorMap(const cgt::vec2& interval /*= cgt::vec2(0.f, 1.f)*/) { cgtAssert(interval.x >= 0.f && interval.y <= 1.f, "Interval out of bounds, must be in [0, 1]."); std::vector<KeyPoint> keyPoints; keyPoints.push_back(KeyPoint(interval.x, cgt::col4(0, 0, 0, 255))); keyPoints.push_back(KeyPoint(interval.x + (interval.y - interval.x) * 0.35f, cgt::col4(224, 0, 0, 255))); keyPoints.push_back(KeyPoint(interval.x + (interval.y - interval.x) * 0.85f, cgt::col4(255, 255, 0, 255))); keyPoints.push_back(KeyPoint(interval.y, cgt::col4(255, 255, 255, 255))); return new TFGeometry1D(keyPoints); } void TFGeometry1D::addKeyPoint( float position, float alpha) { TFGeometry1D::KeyPoint kp(position, cgt::col4(255)); cgt::col4 color(255); std::vector<TFGeometry1D::KeyPoint>::iterator lb = std::upper_bound(_keyPoints.begin(), _keyPoints.end(), kp); if (lb != _keyPoints.end()) { color = lb->_color; } else { color = _keyPoints.back()._color; } color.a = static_cast<uint8_t>(alpha * 255.f); addKeyPoint(position, color); } void TFGeometry1D::addKeyPoint( float position, const cgt::col4& color ) { TFGeometry1D::KeyPoint kp(position, color); std::vector<TFGeometry1D::KeyPoint>::iterator lb = std::upper_bound(_keyPoints.begin(), _keyPoints.end(), kp); _keyPoints.insert(lb, kp); } cgt::vec2 TFGeometry1D::getIntensityDomain() const { return cgt::vec2(_keyPoints.front()._position, _keyPoints.back()._position); } }
_wc: file format elf32-i386 Disassembly of section .text: 00000000 <wc>: char buf[512]; void wc(int fd, char *name) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 ec 28 sub $0x28,%esp int i, n; int l, w, c, inword; l = w = c = 0; 6: c7 45 e8 00 00 00 00 movl $0x0,-0x18(%ebp) d: 8b 45 e8 mov -0x18(%ebp),%eax 10: 89 45 ec mov %eax,-0x14(%ebp) 13: 8b 45 ec mov -0x14(%ebp),%eax 16: 89 45 f0 mov %eax,-0x10(%ebp) inword = 0; 19: c7 45 e4 00 00 00 00 movl $0x0,-0x1c(%ebp) while((n = read(fd, buf, sizeof(buf))) > 0){ 20: eb 69 jmp 8b <wc+0x8b> for(i=0; i<n; i++){ 22: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 29: eb 58 jmp 83 <wc+0x83> c++; 2b: 83 45 e8 01 addl $0x1,-0x18(%ebp) if(buf[i] == '\n') 2f: 8b 45 f4 mov -0xc(%ebp),%eax 32: 05 40 0d 00 00 add $0xd40,%eax 37: 0f b6 00 movzbl (%eax),%eax 3a: 3c 0a cmp $0xa,%al 3c: 75 04 jne 42 <wc+0x42> l++; 3e: 83 45 f0 01 addl $0x1,-0x10(%ebp) if(strchr(" \r\t\n\v", buf[i])) 42: 8b 45 f4 mov -0xc(%ebp),%eax 45: 05 40 0d 00 00 add $0xd40,%eax 4a: 0f b6 00 movzbl (%eax),%eax 4d: 0f be c0 movsbl %al,%eax 50: 83 ec 08 sub $0x8,%esp 53: 50 push %eax 54: 68 2f 0a 00 00 push $0xa2f 59: e8 35 02 00 00 call 293 <strchr> 5e: 83 c4 10 add $0x10,%esp 61: 85 c0 test %eax,%eax 63: 74 09 je 6e <wc+0x6e> inword = 0; 65: c7 45 e4 00 00 00 00 movl $0x0,-0x1c(%ebp) 6c: eb 11 jmp 7f <wc+0x7f> else if(!inword){ 6e: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp) 72: 75 0b jne 7f <wc+0x7f> w++; 74: 83 45 ec 01 addl $0x1,-0x14(%ebp) inword = 1; 78: c7 45 e4 01 00 00 00 movl $0x1,-0x1c(%ebp) int l, w, c, inword; l = w = c = 0; inword = 0; while((n = read(fd, buf, sizeof(buf))) > 0){ for(i=0; i<n; i++){ 7f: 83 45 f4 01 addl $0x1,-0xc(%ebp) 83: 8b 45 f4 mov -0xc(%ebp),%eax 86: 3b 45 e0 cmp -0x20(%ebp),%eax 89: 7c a0 jl 2b <wc+0x2b> int i, n; int l, w, c, inword; l = w = c = 0; inword = 0; while((n = read(fd, buf, sizeof(buf))) > 0){ 8b: 83 ec 04 sub $0x4,%esp 8e: 68 00 02 00 00 push $0x200 93: 68 40 0d 00 00 push $0xd40 98: ff 75 08 pushl 0x8(%ebp) 9b: e8 1a 04 00 00 call 4ba <read> a0: 83 c4 10 add $0x10,%esp a3: 89 45 e0 mov %eax,-0x20(%ebp) a6: 83 7d e0 00 cmpl $0x0,-0x20(%ebp) aa: 0f 8f 72 ff ff ff jg 22 <wc+0x22> w++; inword = 1; } } } if(n < 0){ b0: 83 7d e0 00 cmpl $0x0,-0x20(%ebp) b4: 79 17 jns cd <wc+0xcd> printf(1, "wc: read error\n"); b6: 83 ec 08 sub $0x8,%esp b9: 68 35 0a 00 00 push $0xa35 be: 6a 01 push $0x1 c0: e8 b4 05 00 00 call 679 <printf> c5: 83 c4 10 add $0x10,%esp exit(); c8: e8 d5 03 00 00 call 4a2 <exit> } printf(1, "%d %d %d %s\n", l, w, c, name); cd: 83 ec 08 sub $0x8,%esp d0: ff 75 0c pushl 0xc(%ebp) d3: ff 75 e8 pushl -0x18(%ebp) d6: ff 75 ec pushl -0x14(%ebp) d9: ff 75 f0 pushl -0x10(%ebp) dc: 68 45 0a 00 00 push $0xa45 e1: 6a 01 push $0x1 e3: e8 91 05 00 00 call 679 <printf> e8: 83 c4 20 add $0x20,%esp } eb: 90 nop ec: c9 leave ed: c3 ret 000000ee <main>: int main(int argc, char *argv[]) { ee: 8d 4c 24 04 lea 0x4(%esp),%ecx f2: 83 e4 f0 and $0xfffffff0,%esp f5: ff 71 fc pushl -0x4(%ecx) f8: 55 push %ebp f9: 89 e5 mov %esp,%ebp fb: 53 push %ebx fc: 51 push %ecx fd: 83 ec 10 sub $0x10,%esp 100: 89 cb mov %ecx,%ebx int fd, i; if(argc <= 1){ 102: 83 3b 01 cmpl $0x1,(%ebx) 105: 7f 17 jg 11e <main+0x30> wc(0, ""); 107: 83 ec 08 sub $0x8,%esp 10a: 68 52 0a 00 00 push $0xa52 10f: 6a 00 push $0x0 111: e8 ea fe ff ff call 0 <wc> 116: 83 c4 10 add $0x10,%esp exit(); 119: e8 84 03 00 00 call 4a2 <exit> } for(i = 1; i < argc; i++){ 11e: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%ebp) 125: e9 83 00 00 00 jmp 1ad <main+0xbf> if((fd = open(argv[i], 0)) < 0){ 12a: 8b 45 f4 mov -0xc(%ebp),%eax 12d: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 134: 8b 43 04 mov 0x4(%ebx),%eax 137: 01 d0 add %edx,%eax 139: 8b 00 mov (%eax),%eax 13b: 83 ec 08 sub $0x8,%esp 13e: 6a 00 push $0x0 140: 50 push %eax 141: e8 9c 03 00 00 call 4e2 <open> 146: 83 c4 10 add $0x10,%esp 149: 89 45 f0 mov %eax,-0x10(%ebp) 14c: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 150: 79 29 jns 17b <main+0x8d> printf(1, "wc: cannot open %s\n", argv[i]); 152: 8b 45 f4 mov -0xc(%ebp),%eax 155: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 15c: 8b 43 04 mov 0x4(%ebx),%eax 15f: 01 d0 add %edx,%eax 161: 8b 00 mov (%eax),%eax 163: 83 ec 04 sub $0x4,%esp 166: 50 push %eax 167: 68 53 0a 00 00 push $0xa53 16c: 6a 01 push $0x1 16e: e8 06 05 00 00 call 679 <printf> 173: 83 c4 10 add $0x10,%esp exit(); 176: e8 27 03 00 00 call 4a2 <exit> } wc(fd, argv[i]); 17b: 8b 45 f4 mov -0xc(%ebp),%eax 17e: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 185: 8b 43 04 mov 0x4(%ebx),%eax 188: 01 d0 add %edx,%eax 18a: 8b 00 mov (%eax),%eax 18c: 83 ec 08 sub $0x8,%esp 18f: 50 push %eax 190: ff 75 f0 pushl -0x10(%ebp) 193: e8 68 fe ff ff call 0 <wc> 198: 83 c4 10 add $0x10,%esp close(fd); 19b: 83 ec 0c sub $0xc,%esp 19e: ff 75 f0 pushl -0x10(%ebp) 1a1: e8 24 03 00 00 call 4ca <close> 1a6: 83 c4 10 add $0x10,%esp if(argc <= 1){ wc(0, ""); exit(); } for(i = 1; i < argc; i++){ 1a9: 83 45 f4 01 addl $0x1,-0xc(%ebp) 1ad: 8b 45 f4 mov -0xc(%ebp),%eax 1b0: 3b 03 cmp (%ebx),%eax 1b2: 0f 8c 72 ff ff ff jl 12a <main+0x3c> exit(); } wc(fd, argv[i]); close(fd); } exit(); 1b8: e8 e5 02 00 00 call 4a2 <exit> 000001bd <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 1bd: 55 push %ebp 1be: 89 e5 mov %esp,%ebp 1c0: 57 push %edi 1c1: 53 push %ebx asm volatile("cld; rep stosb" : 1c2: 8b 4d 08 mov 0x8(%ebp),%ecx 1c5: 8b 55 10 mov 0x10(%ebp),%edx 1c8: 8b 45 0c mov 0xc(%ebp),%eax 1cb: 89 cb mov %ecx,%ebx 1cd: 89 df mov %ebx,%edi 1cf: 89 d1 mov %edx,%ecx 1d1: fc cld 1d2: f3 aa rep stos %al,%es:(%edi) 1d4: 89 ca mov %ecx,%edx 1d6: 89 fb mov %edi,%ebx 1d8: 89 5d 08 mov %ebx,0x8(%ebp) 1db: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 1de: 90 nop 1df: 5b pop %ebx 1e0: 5f pop %edi 1e1: 5d pop %ebp 1e2: c3 ret 000001e3 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 1e3: 55 push %ebp 1e4: 89 e5 mov %esp,%ebp 1e6: 83 ec 10 sub $0x10,%esp char *os; os = s; 1e9: 8b 45 08 mov 0x8(%ebp),%eax 1ec: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 1ef: 90 nop 1f0: 8b 45 08 mov 0x8(%ebp),%eax 1f3: 8d 50 01 lea 0x1(%eax),%edx 1f6: 89 55 08 mov %edx,0x8(%ebp) 1f9: 8b 55 0c mov 0xc(%ebp),%edx 1fc: 8d 4a 01 lea 0x1(%edx),%ecx 1ff: 89 4d 0c mov %ecx,0xc(%ebp) 202: 0f b6 12 movzbl (%edx),%edx 205: 88 10 mov %dl,(%eax) 207: 0f b6 00 movzbl (%eax),%eax 20a: 84 c0 test %al,%al 20c: 75 e2 jne 1f0 <strcpy+0xd> ; return os; 20e: 8b 45 fc mov -0x4(%ebp),%eax } 211: c9 leave 212: c3 ret 00000213 <strcmp>: int strcmp(const char *p, const char *q) { 213: 55 push %ebp 214: 89 e5 mov %esp,%ebp while(*p && *p == *q) 216: eb 08 jmp 220 <strcmp+0xd> p++, q++; 218: 83 45 08 01 addl $0x1,0x8(%ebp) 21c: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 220: 8b 45 08 mov 0x8(%ebp),%eax 223: 0f b6 00 movzbl (%eax),%eax 226: 84 c0 test %al,%al 228: 74 10 je 23a <strcmp+0x27> 22a: 8b 45 08 mov 0x8(%ebp),%eax 22d: 0f b6 10 movzbl (%eax),%edx 230: 8b 45 0c mov 0xc(%ebp),%eax 233: 0f b6 00 movzbl (%eax),%eax 236: 38 c2 cmp %al,%dl 238: 74 de je 218 <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; 23a: 8b 45 08 mov 0x8(%ebp),%eax 23d: 0f b6 00 movzbl (%eax),%eax 240: 0f b6 d0 movzbl %al,%edx 243: 8b 45 0c mov 0xc(%ebp),%eax 246: 0f b6 00 movzbl (%eax),%eax 249: 0f b6 c0 movzbl %al,%eax 24c: 29 c2 sub %eax,%edx 24e: 89 d0 mov %edx,%eax } 250: 5d pop %ebp 251: c3 ret 00000252 <strlen>: uint strlen(char *s) { 252: 55 push %ebp 253: 89 e5 mov %esp,%ebp 255: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 258: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 25f: eb 04 jmp 265 <strlen+0x13> 261: 83 45 fc 01 addl $0x1,-0x4(%ebp) 265: 8b 55 fc mov -0x4(%ebp),%edx 268: 8b 45 08 mov 0x8(%ebp),%eax 26b: 01 d0 add %edx,%eax 26d: 0f b6 00 movzbl (%eax),%eax 270: 84 c0 test %al,%al 272: 75 ed jne 261 <strlen+0xf> ; return n; 274: 8b 45 fc mov -0x4(%ebp),%eax } 277: c9 leave 278: c3 ret 00000279 <memset>: void* memset(void *dst, int c, uint n) { 279: 55 push %ebp 27a: 89 e5 mov %esp,%ebp stosb(dst, c, n); 27c: 8b 45 10 mov 0x10(%ebp),%eax 27f: 50 push %eax 280: ff 75 0c pushl 0xc(%ebp) 283: ff 75 08 pushl 0x8(%ebp) 286: e8 32 ff ff ff call 1bd <stosb> 28b: 83 c4 0c add $0xc,%esp return dst; 28e: 8b 45 08 mov 0x8(%ebp),%eax } 291: c9 leave 292: c3 ret 00000293 <strchr>: char* strchr(const char *s, char c) { 293: 55 push %ebp 294: 89 e5 mov %esp,%ebp 296: 83 ec 04 sub $0x4,%esp 299: 8b 45 0c mov 0xc(%ebp),%eax 29c: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 29f: eb 14 jmp 2b5 <strchr+0x22> if(*s == c) 2a1: 8b 45 08 mov 0x8(%ebp),%eax 2a4: 0f b6 00 movzbl (%eax),%eax 2a7: 3a 45 fc cmp -0x4(%ebp),%al 2aa: 75 05 jne 2b1 <strchr+0x1e> return (char*)s; 2ac: 8b 45 08 mov 0x8(%ebp),%eax 2af: eb 13 jmp 2c4 <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 2b1: 83 45 08 01 addl $0x1,0x8(%ebp) 2b5: 8b 45 08 mov 0x8(%ebp),%eax 2b8: 0f b6 00 movzbl (%eax),%eax 2bb: 84 c0 test %al,%al 2bd: 75 e2 jne 2a1 <strchr+0xe> if(*s == c) return (char*)s; return 0; 2bf: b8 00 00 00 00 mov $0x0,%eax } 2c4: c9 leave 2c5: c3 ret 000002c6 <gets>: char* gets(char *buf, int max) { 2c6: 55 push %ebp 2c7: 89 e5 mov %esp,%ebp 2c9: 83 ec 18 sub $0x18,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 2cc: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 2d3: eb 42 jmp 317 <gets+0x51> cc = read(0, &c, 1); 2d5: 83 ec 04 sub $0x4,%esp 2d8: 6a 01 push $0x1 2da: 8d 45 ef lea -0x11(%ebp),%eax 2dd: 50 push %eax 2de: 6a 00 push $0x0 2e0: e8 d5 01 00 00 call 4ba <read> 2e5: 83 c4 10 add $0x10,%esp 2e8: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 2eb: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 2ef: 7e 33 jle 324 <gets+0x5e> break; buf[i++] = c; 2f1: 8b 45 f4 mov -0xc(%ebp),%eax 2f4: 8d 50 01 lea 0x1(%eax),%edx 2f7: 89 55 f4 mov %edx,-0xc(%ebp) 2fa: 89 c2 mov %eax,%edx 2fc: 8b 45 08 mov 0x8(%ebp),%eax 2ff: 01 c2 add %eax,%edx 301: 0f b6 45 ef movzbl -0x11(%ebp),%eax 305: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 307: 0f b6 45 ef movzbl -0x11(%ebp),%eax 30b: 3c 0a cmp $0xa,%al 30d: 74 16 je 325 <gets+0x5f> 30f: 0f b6 45 ef movzbl -0x11(%ebp),%eax 313: 3c 0d cmp $0xd,%al 315: 74 0e je 325 <gets+0x5f> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 317: 8b 45 f4 mov -0xc(%ebp),%eax 31a: 83 c0 01 add $0x1,%eax 31d: 3b 45 0c cmp 0xc(%ebp),%eax 320: 7c b3 jl 2d5 <gets+0xf> 322: eb 01 jmp 325 <gets+0x5f> cc = read(0, &c, 1); if(cc < 1) break; 324: 90 nop buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 325: 8b 55 f4 mov -0xc(%ebp),%edx 328: 8b 45 08 mov 0x8(%ebp),%eax 32b: 01 d0 add %edx,%eax 32d: c6 00 00 movb $0x0,(%eax) return buf; 330: 8b 45 08 mov 0x8(%ebp),%eax } 333: c9 leave 334: c3 ret 00000335 <stat>: int stat(char *n, struct stat *st) { 335: 55 push %ebp 336: 89 e5 mov %esp,%ebp 338: 83 ec 18 sub $0x18,%esp int fd; int r; fd = open(n, O_RDONLY); 33b: 83 ec 08 sub $0x8,%esp 33e: 6a 00 push $0x0 340: ff 75 08 pushl 0x8(%ebp) 343: e8 9a 01 00 00 call 4e2 <open> 348: 83 c4 10 add $0x10,%esp 34b: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 34e: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 352: 79 07 jns 35b <stat+0x26> return -1; 354: b8 ff ff ff ff mov $0xffffffff,%eax 359: eb 25 jmp 380 <stat+0x4b> r = fstat(fd, st); 35b: 83 ec 08 sub $0x8,%esp 35e: ff 75 0c pushl 0xc(%ebp) 361: ff 75 f4 pushl -0xc(%ebp) 364: e8 91 01 00 00 call 4fa <fstat> 369: 83 c4 10 add $0x10,%esp 36c: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 36f: 83 ec 0c sub $0xc,%esp 372: ff 75 f4 pushl -0xc(%ebp) 375: e8 50 01 00 00 call 4ca <close> 37a: 83 c4 10 add $0x10,%esp return r; 37d: 8b 45 f0 mov -0x10(%ebp),%eax } 380: c9 leave 381: c3 ret 00000382 <atoi>: int atoi(const char *s) { 382: 55 push %ebp 383: 89 e5 mov %esp,%ebp 385: 83 ec 10 sub $0x10,%esp int n; n = 0; 388: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 38f: eb 25 jmp 3b6 <atoi+0x34> n = n*10 + *s++ - '0'; 391: 8b 55 fc mov -0x4(%ebp),%edx 394: 89 d0 mov %edx,%eax 396: c1 e0 02 shl $0x2,%eax 399: 01 d0 add %edx,%eax 39b: 01 c0 add %eax,%eax 39d: 89 c1 mov %eax,%ecx 39f: 8b 45 08 mov 0x8(%ebp),%eax 3a2: 8d 50 01 lea 0x1(%eax),%edx 3a5: 89 55 08 mov %edx,0x8(%ebp) 3a8: 0f b6 00 movzbl (%eax),%eax 3ab: 0f be c0 movsbl %al,%eax 3ae: 01 c8 add %ecx,%eax 3b0: 83 e8 30 sub $0x30,%eax 3b3: 89 45 fc mov %eax,-0x4(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 3b6: 8b 45 08 mov 0x8(%ebp),%eax 3b9: 0f b6 00 movzbl (%eax),%eax 3bc: 3c 2f cmp $0x2f,%al 3be: 7e 0a jle 3ca <atoi+0x48> 3c0: 8b 45 08 mov 0x8(%ebp),%eax 3c3: 0f b6 00 movzbl (%eax),%eax 3c6: 3c 39 cmp $0x39,%al 3c8: 7e c7 jle 391 <atoi+0xf> n = n*10 + *s++ - '0'; return n; 3ca: 8b 45 fc mov -0x4(%ebp),%eax } 3cd: c9 leave 3ce: c3 ret 000003cf <atoo>: int atoo(const char *s) { 3cf: 55 push %ebp 3d0: 89 e5 mov %esp,%ebp 3d2: 83 ec 10 sub $0x10,%esp int n, sign; n = 0; 3d5: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while (*s == ' ') 3dc: eb 04 jmp 3e2 <atoo+0x13> s++; 3de: 83 45 08 01 addl $0x1,0x8(%ebp) int atoo(const char *s) { int n, sign; n = 0; while (*s == ' ') 3e2: 8b 45 08 mov 0x8(%ebp),%eax 3e5: 0f b6 00 movzbl (%eax),%eax 3e8: 3c 20 cmp $0x20,%al 3ea: 74 f2 je 3de <atoo+0xf> s++; sign = (*s == '-') ? -1 : 1; 3ec: 8b 45 08 mov 0x8(%ebp),%eax 3ef: 0f b6 00 movzbl (%eax),%eax 3f2: 3c 2d cmp $0x2d,%al 3f4: 75 07 jne 3fd <atoo+0x2e> 3f6: b8 ff ff ff ff mov $0xffffffff,%eax 3fb: eb 05 jmp 402 <atoo+0x33> 3fd: b8 01 00 00 00 mov $0x1,%eax 402: 89 45 f8 mov %eax,-0x8(%ebp) if (*s == '+' || *s == '-') 405: 8b 45 08 mov 0x8(%ebp),%eax 408: 0f b6 00 movzbl (%eax),%eax 40b: 3c 2b cmp $0x2b,%al 40d: 74 0a je 419 <atoo+0x4a> 40f: 8b 45 08 mov 0x8(%ebp),%eax 412: 0f b6 00 movzbl (%eax),%eax 415: 3c 2d cmp $0x2d,%al 417: 75 27 jne 440 <atoo+0x71> s++; 419: 83 45 08 01 addl $0x1,0x8(%ebp) while ('0' <= *s && *s <= '7') 41d: eb 21 jmp 440 <atoo+0x71> n = n*8 + *s++ - '0'; 41f: 8b 45 fc mov -0x4(%ebp),%eax 422: 8d 0c c5 00 00 00 00 lea 0x0(,%eax,8),%ecx 429: 8b 45 08 mov 0x8(%ebp),%eax 42c: 8d 50 01 lea 0x1(%eax),%edx 42f: 89 55 08 mov %edx,0x8(%ebp) 432: 0f b6 00 movzbl (%eax),%eax 435: 0f be c0 movsbl %al,%eax 438: 01 c8 add %ecx,%eax 43a: 83 e8 30 sub $0x30,%eax 43d: 89 45 fc mov %eax,-0x4(%ebp) while (*s == ' ') s++; sign = (*s == '-') ? -1 : 1; if (*s == '+' || *s == '-') s++; while ('0' <= *s && *s <= '7') 440: 8b 45 08 mov 0x8(%ebp),%eax 443: 0f b6 00 movzbl (%eax),%eax 446: 3c 2f cmp $0x2f,%al 448: 7e 0a jle 454 <atoo+0x85> 44a: 8b 45 08 mov 0x8(%ebp),%eax 44d: 0f b6 00 movzbl (%eax),%eax 450: 3c 37 cmp $0x37,%al 452: 7e cb jle 41f <atoo+0x50> n = n*8 + *s++ - '0'; return sign*n; 454: 8b 45 f8 mov -0x8(%ebp),%eax 457: 0f af 45 fc imul -0x4(%ebp),%eax } 45b: c9 leave 45c: c3 ret 0000045d <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 45d: 55 push %ebp 45e: 89 e5 mov %esp,%ebp 460: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 463: 8b 45 08 mov 0x8(%ebp),%eax 466: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 469: 8b 45 0c mov 0xc(%ebp),%eax 46c: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 46f: eb 17 jmp 488 <memmove+0x2b> *dst++ = *src++; 471: 8b 45 fc mov -0x4(%ebp),%eax 474: 8d 50 01 lea 0x1(%eax),%edx 477: 89 55 fc mov %edx,-0x4(%ebp) 47a: 8b 55 f8 mov -0x8(%ebp),%edx 47d: 8d 4a 01 lea 0x1(%edx),%ecx 480: 89 4d f8 mov %ecx,-0x8(%ebp) 483: 0f b6 12 movzbl (%edx),%edx 486: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 488: 8b 45 10 mov 0x10(%ebp),%eax 48b: 8d 50 ff lea -0x1(%eax),%edx 48e: 89 55 10 mov %edx,0x10(%ebp) 491: 85 c0 test %eax,%eax 493: 7f dc jg 471 <memmove+0x14> *dst++ = *src++; return vdst; 495: 8b 45 08 mov 0x8(%ebp),%eax } 498: c9 leave 499: c3 ret 0000049a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 49a: b8 01 00 00 00 mov $0x1,%eax 49f: cd 40 int $0x40 4a1: c3 ret 000004a2 <exit>: SYSCALL(exit) 4a2: b8 02 00 00 00 mov $0x2,%eax 4a7: cd 40 int $0x40 4a9: c3 ret 000004aa <wait>: SYSCALL(wait) 4aa: b8 03 00 00 00 mov $0x3,%eax 4af: cd 40 int $0x40 4b1: c3 ret 000004b2 <pipe>: SYSCALL(pipe) 4b2: b8 04 00 00 00 mov $0x4,%eax 4b7: cd 40 int $0x40 4b9: c3 ret 000004ba <read>: SYSCALL(read) 4ba: b8 05 00 00 00 mov $0x5,%eax 4bf: cd 40 int $0x40 4c1: c3 ret 000004c2 <write>: SYSCALL(write) 4c2: b8 10 00 00 00 mov $0x10,%eax 4c7: cd 40 int $0x40 4c9: c3 ret 000004ca <close>: SYSCALL(close) 4ca: b8 15 00 00 00 mov $0x15,%eax 4cf: cd 40 int $0x40 4d1: c3 ret 000004d2 <kill>: SYSCALL(kill) 4d2: b8 06 00 00 00 mov $0x6,%eax 4d7: cd 40 int $0x40 4d9: c3 ret 000004da <exec>: SYSCALL(exec) 4da: b8 07 00 00 00 mov $0x7,%eax 4df: cd 40 int $0x40 4e1: c3 ret 000004e2 <open>: SYSCALL(open) 4e2: b8 0f 00 00 00 mov $0xf,%eax 4e7: cd 40 int $0x40 4e9: c3 ret 000004ea <mknod>: SYSCALL(mknod) 4ea: b8 11 00 00 00 mov $0x11,%eax 4ef: cd 40 int $0x40 4f1: c3 ret 000004f2 <unlink>: SYSCALL(unlink) 4f2: b8 12 00 00 00 mov $0x12,%eax 4f7: cd 40 int $0x40 4f9: c3 ret 000004fa <fstat>: SYSCALL(fstat) 4fa: b8 08 00 00 00 mov $0x8,%eax 4ff: cd 40 int $0x40 501: c3 ret 00000502 <link>: SYSCALL(link) 502: b8 13 00 00 00 mov $0x13,%eax 507: cd 40 int $0x40 509: c3 ret 0000050a <mkdir>: SYSCALL(mkdir) 50a: b8 14 00 00 00 mov $0x14,%eax 50f: cd 40 int $0x40 511: c3 ret 00000512 <chdir>: SYSCALL(chdir) 512: b8 09 00 00 00 mov $0x9,%eax 517: cd 40 int $0x40 519: c3 ret 0000051a <dup>: SYSCALL(dup) 51a: b8 0a 00 00 00 mov $0xa,%eax 51f: cd 40 int $0x40 521: c3 ret 00000522 <getpid>: SYSCALL(getpid) 522: b8 0b 00 00 00 mov $0xb,%eax 527: cd 40 int $0x40 529: c3 ret 0000052a <sbrk>: SYSCALL(sbrk) 52a: b8 0c 00 00 00 mov $0xc,%eax 52f: cd 40 int $0x40 531: c3 ret 00000532 <sleep>: SYSCALL(sleep) 532: b8 0d 00 00 00 mov $0xd,%eax 537: cd 40 int $0x40 539: c3 ret 0000053a <uptime>: SYSCALL(uptime) 53a: b8 0e 00 00 00 mov $0xe,%eax 53f: cd 40 int $0x40 541: c3 ret 00000542 <halt>: SYSCALL(halt) 542: b8 16 00 00 00 mov $0x16,%eax 547: cd 40 int $0x40 549: c3 ret 0000054a <date>: SYSCALL(date) 54a: b8 17 00 00 00 mov $0x17,%eax 54f: cd 40 int $0x40 551: c3 ret 00000552 <getuid>: SYSCALL(getuid) 552: b8 18 00 00 00 mov $0x18,%eax 557: cd 40 int $0x40 559: c3 ret 0000055a <getgid>: SYSCALL(getgid) 55a: b8 19 00 00 00 mov $0x19,%eax 55f: cd 40 int $0x40 561: c3 ret 00000562 <getppid>: SYSCALL(getppid) 562: b8 1a 00 00 00 mov $0x1a,%eax 567: cd 40 int $0x40 569: c3 ret 0000056a <setuid>: SYSCALL(setuid) 56a: b8 1b 00 00 00 mov $0x1b,%eax 56f: cd 40 int $0x40 571: c3 ret 00000572 <setgid>: SYSCALL(setgid) 572: b8 1c 00 00 00 mov $0x1c,%eax 577: cd 40 int $0x40 579: c3 ret 0000057a <getprocs>: SYSCALL(getprocs) 57a: b8 1d 00 00 00 mov $0x1d,%eax 57f: cd 40 int $0x40 581: c3 ret 00000582 <setpriority>: SYSCALL(setpriority) 582: b8 1e 00 00 00 mov $0x1e,%eax 587: cd 40 int $0x40 589: c3 ret 0000058a <chmod>: SYSCALL(chmod) 58a: b8 1f 00 00 00 mov $0x1f,%eax 58f: cd 40 int $0x40 591: c3 ret 00000592 <chown>: SYSCALL(chown) 592: b8 20 00 00 00 mov $0x20,%eax 597: cd 40 int $0x40 599: c3 ret 0000059a <chgrp>: SYSCALL(chgrp) 59a: b8 21 00 00 00 mov $0x21,%eax 59f: cd 40 int $0x40 5a1: c3 ret 000005a2 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 5a2: 55 push %ebp 5a3: 89 e5 mov %esp,%ebp 5a5: 83 ec 18 sub $0x18,%esp 5a8: 8b 45 0c mov 0xc(%ebp),%eax 5ab: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 5ae: 83 ec 04 sub $0x4,%esp 5b1: 6a 01 push $0x1 5b3: 8d 45 f4 lea -0xc(%ebp),%eax 5b6: 50 push %eax 5b7: ff 75 08 pushl 0x8(%ebp) 5ba: e8 03 ff ff ff call 4c2 <write> 5bf: 83 c4 10 add $0x10,%esp } 5c2: 90 nop 5c3: c9 leave 5c4: c3 ret 000005c5 <printint>: static void printint(int fd, int xx, int base, int sgn) { 5c5: 55 push %ebp 5c6: 89 e5 mov %esp,%ebp 5c8: 53 push %ebx 5c9: 83 ec 24 sub $0x24,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 5cc: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 5d3: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 5d7: 74 17 je 5f0 <printint+0x2b> 5d9: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 5dd: 79 11 jns 5f0 <printint+0x2b> neg = 1; 5df: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 5e6: 8b 45 0c mov 0xc(%ebp),%eax 5e9: f7 d8 neg %eax 5eb: 89 45 ec mov %eax,-0x14(%ebp) 5ee: eb 06 jmp 5f6 <printint+0x31> } else { x = xx; 5f0: 8b 45 0c mov 0xc(%ebp),%eax 5f3: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 5f6: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 5fd: 8b 4d f4 mov -0xc(%ebp),%ecx 600: 8d 41 01 lea 0x1(%ecx),%eax 603: 89 45 f4 mov %eax,-0xc(%ebp) 606: 8b 5d 10 mov 0x10(%ebp),%ebx 609: 8b 45 ec mov -0x14(%ebp),%eax 60c: ba 00 00 00 00 mov $0x0,%edx 611: f7 f3 div %ebx 613: 89 d0 mov %edx,%eax 615: 0f b6 80 fc 0c 00 00 movzbl 0xcfc(%eax),%eax 61c: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) }while((x /= base) != 0); 620: 8b 5d 10 mov 0x10(%ebp),%ebx 623: 8b 45 ec mov -0x14(%ebp),%eax 626: ba 00 00 00 00 mov $0x0,%edx 62b: f7 f3 div %ebx 62d: 89 45 ec mov %eax,-0x14(%ebp) 630: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 634: 75 c7 jne 5fd <printint+0x38> if(neg) 636: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 63a: 74 2d je 669 <printint+0xa4> buf[i++] = '-'; 63c: 8b 45 f4 mov -0xc(%ebp),%eax 63f: 8d 50 01 lea 0x1(%eax),%edx 642: 89 55 f4 mov %edx,-0xc(%ebp) 645: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 64a: eb 1d jmp 669 <printint+0xa4> putc(fd, buf[i]); 64c: 8d 55 dc lea -0x24(%ebp),%edx 64f: 8b 45 f4 mov -0xc(%ebp),%eax 652: 01 d0 add %edx,%eax 654: 0f b6 00 movzbl (%eax),%eax 657: 0f be c0 movsbl %al,%eax 65a: 83 ec 08 sub $0x8,%esp 65d: 50 push %eax 65e: ff 75 08 pushl 0x8(%ebp) 661: e8 3c ff ff ff call 5a2 <putc> 666: 83 c4 10 add $0x10,%esp buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 669: 83 6d f4 01 subl $0x1,-0xc(%ebp) 66d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 671: 79 d9 jns 64c <printint+0x87> putc(fd, buf[i]); } 673: 90 nop 674: 8b 5d fc mov -0x4(%ebp),%ebx 677: c9 leave 678: c3 ret 00000679 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 679: 55 push %ebp 67a: 89 e5 mov %esp,%ebp 67c: 83 ec 28 sub $0x28,%esp char *s; int c, i, state; uint *ap; state = 0; 67f: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 686: 8d 45 0c lea 0xc(%ebp),%eax 689: 83 c0 04 add $0x4,%eax 68c: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 68f: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 696: e9 59 01 00 00 jmp 7f4 <printf+0x17b> c = fmt[i] & 0xff; 69b: 8b 55 0c mov 0xc(%ebp),%edx 69e: 8b 45 f0 mov -0x10(%ebp),%eax 6a1: 01 d0 add %edx,%eax 6a3: 0f b6 00 movzbl (%eax),%eax 6a6: 0f be c0 movsbl %al,%eax 6a9: 25 ff 00 00 00 and $0xff,%eax 6ae: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 6b1: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 6b5: 75 2c jne 6e3 <printf+0x6a> if(c == '%'){ 6b7: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 6bb: 75 0c jne 6c9 <printf+0x50> state = '%'; 6bd: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 6c4: e9 27 01 00 00 jmp 7f0 <printf+0x177> } else { putc(fd, c); 6c9: 8b 45 e4 mov -0x1c(%ebp),%eax 6cc: 0f be c0 movsbl %al,%eax 6cf: 83 ec 08 sub $0x8,%esp 6d2: 50 push %eax 6d3: ff 75 08 pushl 0x8(%ebp) 6d6: e8 c7 fe ff ff call 5a2 <putc> 6db: 83 c4 10 add $0x10,%esp 6de: e9 0d 01 00 00 jmp 7f0 <printf+0x177> } } else if(state == '%'){ 6e3: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 6e7: 0f 85 03 01 00 00 jne 7f0 <printf+0x177> if(c == 'd'){ 6ed: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 6f1: 75 1e jne 711 <printf+0x98> printint(fd, *ap, 10, 1); 6f3: 8b 45 e8 mov -0x18(%ebp),%eax 6f6: 8b 00 mov (%eax),%eax 6f8: 6a 01 push $0x1 6fa: 6a 0a push $0xa 6fc: 50 push %eax 6fd: ff 75 08 pushl 0x8(%ebp) 700: e8 c0 fe ff ff call 5c5 <printint> 705: 83 c4 10 add $0x10,%esp ap++; 708: 83 45 e8 04 addl $0x4,-0x18(%ebp) 70c: e9 d8 00 00 00 jmp 7e9 <printf+0x170> } else if(c == 'x' || c == 'p'){ 711: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 715: 74 06 je 71d <printf+0xa4> 717: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 71b: 75 1e jne 73b <printf+0xc2> printint(fd, *ap, 16, 0); 71d: 8b 45 e8 mov -0x18(%ebp),%eax 720: 8b 00 mov (%eax),%eax 722: 6a 00 push $0x0 724: 6a 10 push $0x10 726: 50 push %eax 727: ff 75 08 pushl 0x8(%ebp) 72a: e8 96 fe ff ff call 5c5 <printint> 72f: 83 c4 10 add $0x10,%esp ap++; 732: 83 45 e8 04 addl $0x4,-0x18(%ebp) 736: e9 ae 00 00 00 jmp 7e9 <printf+0x170> } else if(c == 's'){ 73b: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 73f: 75 43 jne 784 <printf+0x10b> s = (char*)*ap; 741: 8b 45 e8 mov -0x18(%ebp),%eax 744: 8b 00 mov (%eax),%eax 746: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 749: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 74d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 751: 75 25 jne 778 <printf+0xff> s = "(null)"; 753: c7 45 f4 67 0a 00 00 movl $0xa67,-0xc(%ebp) while(*s != 0){ 75a: eb 1c jmp 778 <printf+0xff> putc(fd, *s); 75c: 8b 45 f4 mov -0xc(%ebp),%eax 75f: 0f b6 00 movzbl (%eax),%eax 762: 0f be c0 movsbl %al,%eax 765: 83 ec 08 sub $0x8,%esp 768: 50 push %eax 769: ff 75 08 pushl 0x8(%ebp) 76c: e8 31 fe ff ff call 5a2 <putc> 771: 83 c4 10 add $0x10,%esp s++; 774: 83 45 f4 01 addl $0x1,-0xc(%ebp) } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 778: 8b 45 f4 mov -0xc(%ebp),%eax 77b: 0f b6 00 movzbl (%eax),%eax 77e: 84 c0 test %al,%al 780: 75 da jne 75c <printf+0xe3> 782: eb 65 jmp 7e9 <printf+0x170> putc(fd, *s); s++; } } else if(c == 'c'){ 784: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 788: 75 1d jne 7a7 <printf+0x12e> putc(fd, *ap); 78a: 8b 45 e8 mov -0x18(%ebp),%eax 78d: 8b 00 mov (%eax),%eax 78f: 0f be c0 movsbl %al,%eax 792: 83 ec 08 sub $0x8,%esp 795: 50 push %eax 796: ff 75 08 pushl 0x8(%ebp) 799: e8 04 fe ff ff call 5a2 <putc> 79e: 83 c4 10 add $0x10,%esp ap++; 7a1: 83 45 e8 04 addl $0x4,-0x18(%ebp) 7a5: eb 42 jmp 7e9 <printf+0x170> } else if(c == '%'){ 7a7: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 7ab: 75 17 jne 7c4 <printf+0x14b> putc(fd, c); 7ad: 8b 45 e4 mov -0x1c(%ebp),%eax 7b0: 0f be c0 movsbl %al,%eax 7b3: 83 ec 08 sub $0x8,%esp 7b6: 50 push %eax 7b7: ff 75 08 pushl 0x8(%ebp) 7ba: e8 e3 fd ff ff call 5a2 <putc> 7bf: 83 c4 10 add $0x10,%esp 7c2: eb 25 jmp 7e9 <printf+0x170> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 7c4: 83 ec 08 sub $0x8,%esp 7c7: 6a 25 push $0x25 7c9: ff 75 08 pushl 0x8(%ebp) 7cc: e8 d1 fd ff ff call 5a2 <putc> 7d1: 83 c4 10 add $0x10,%esp putc(fd, c); 7d4: 8b 45 e4 mov -0x1c(%ebp),%eax 7d7: 0f be c0 movsbl %al,%eax 7da: 83 ec 08 sub $0x8,%esp 7dd: 50 push %eax 7de: ff 75 08 pushl 0x8(%ebp) 7e1: e8 bc fd ff ff call 5a2 <putc> 7e6: 83 c4 10 add $0x10,%esp } state = 0; 7e9: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 7f0: 83 45 f0 01 addl $0x1,-0x10(%ebp) 7f4: 8b 55 0c mov 0xc(%ebp),%edx 7f7: 8b 45 f0 mov -0x10(%ebp),%eax 7fa: 01 d0 add %edx,%eax 7fc: 0f b6 00 movzbl (%eax),%eax 7ff: 84 c0 test %al,%al 801: 0f 85 94 fe ff ff jne 69b <printf+0x22> putc(fd, c); } state = 0; } } } 807: 90 nop 808: c9 leave 809: c3 ret 0000080a <free>: static Header base; static Header *freep; void free(void *ap) { 80a: 55 push %ebp 80b: 89 e5 mov %esp,%ebp 80d: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 810: 8b 45 08 mov 0x8(%ebp),%eax 813: 83 e8 08 sub $0x8,%eax 816: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 819: a1 28 0d 00 00 mov 0xd28,%eax 81e: 89 45 fc mov %eax,-0x4(%ebp) 821: eb 24 jmp 847 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 823: 8b 45 fc mov -0x4(%ebp),%eax 826: 8b 00 mov (%eax),%eax 828: 3b 45 fc cmp -0x4(%ebp),%eax 82b: 77 12 ja 83f <free+0x35> 82d: 8b 45 f8 mov -0x8(%ebp),%eax 830: 3b 45 fc cmp -0x4(%ebp),%eax 833: 77 24 ja 859 <free+0x4f> 835: 8b 45 fc mov -0x4(%ebp),%eax 838: 8b 00 mov (%eax),%eax 83a: 3b 45 f8 cmp -0x8(%ebp),%eax 83d: 77 1a ja 859 <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 83f: 8b 45 fc mov -0x4(%ebp),%eax 842: 8b 00 mov (%eax),%eax 844: 89 45 fc mov %eax,-0x4(%ebp) 847: 8b 45 f8 mov -0x8(%ebp),%eax 84a: 3b 45 fc cmp -0x4(%ebp),%eax 84d: 76 d4 jbe 823 <free+0x19> 84f: 8b 45 fc mov -0x4(%ebp),%eax 852: 8b 00 mov (%eax),%eax 854: 3b 45 f8 cmp -0x8(%ebp),%eax 857: 76 ca jbe 823 <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 859: 8b 45 f8 mov -0x8(%ebp),%eax 85c: 8b 40 04 mov 0x4(%eax),%eax 85f: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 866: 8b 45 f8 mov -0x8(%ebp),%eax 869: 01 c2 add %eax,%edx 86b: 8b 45 fc mov -0x4(%ebp),%eax 86e: 8b 00 mov (%eax),%eax 870: 39 c2 cmp %eax,%edx 872: 75 24 jne 898 <free+0x8e> bp->s.size += p->s.ptr->s.size; 874: 8b 45 f8 mov -0x8(%ebp),%eax 877: 8b 50 04 mov 0x4(%eax),%edx 87a: 8b 45 fc mov -0x4(%ebp),%eax 87d: 8b 00 mov (%eax),%eax 87f: 8b 40 04 mov 0x4(%eax),%eax 882: 01 c2 add %eax,%edx 884: 8b 45 f8 mov -0x8(%ebp),%eax 887: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 88a: 8b 45 fc mov -0x4(%ebp),%eax 88d: 8b 00 mov (%eax),%eax 88f: 8b 10 mov (%eax),%edx 891: 8b 45 f8 mov -0x8(%ebp),%eax 894: 89 10 mov %edx,(%eax) 896: eb 0a jmp 8a2 <free+0x98> } else bp->s.ptr = p->s.ptr; 898: 8b 45 fc mov -0x4(%ebp),%eax 89b: 8b 10 mov (%eax),%edx 89d: 8b 45 f8 mov -0x8(%ebp),%eax 8a0: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 8a2: 8b 45 fc mov -0x4(%ebp),%eax 8a5: 8b 40 04 mov 0x4(%eax),%eax 8a8: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 8af: 8b 45 fc mov -0x4(%ebp),%eax 8b2: 01 d0 add %edx,%eax 8b4: 3b 45 f8 cmp -0x8(%ebp),%eax 8b7: 75 20 jne 8d9 <free+0xcf> p->s.size += bp->s.size; 8b9: 8b 45 fc mov -0x4(%ebp),%eax 8bc: 8b 50 04 mov 0x4(%eax),%edx 8bf: 8b 45 f8 mov -0x8(%ebp),%eax 8c2: 8b 40 04 mov 0x4(%eax),%eax 8c5: 01 c2 add %eax,%edx 8c7: 8b 45 fc mov -0x4(%ebp),%eax 8ca: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 8cd: 8b 45 f8 mov -0x8(%ebp),%eax 8d0: 8b 10 mov (%eax),%edx 8d2: 8b 45 fc mov -0x4(%ebp),%eax 8d5: 89 10 mov %edx,(%eax) 8d7: eb 08 jmp 8e1 <free+0xd7> } else p->s.ptr = bp; 8d9: 8b 45 fc mov -0x4(%ebp),%eax 8dc: 8b 55 f8 mov -0x8(%ebp),%edx 8df: 89 10 mov %edx,(%eax) freep = p; 8e1: 8b 45 fc mov -0x4(%ebp),%eax 8e4: a3 28 0d 00 00 mov %eax,0xd28 } 8e9: 90 nop 8ea: c9 leave 8eb: c3 ret 000008ec <morecore>: static Header* morecore(uint nu) { 8ec: 55 push %ebp 8ed: 89 e5 mov %esp,%ebp 8ef: 83 ec 18 sub $0x18,%esp char *p; Header *hp; if(nu < 4096) 8f2: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 8f9: 77 07 ja 902 <morecore+0x16> nu = 4096; 8fb: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 902: 8b 45 08 mov 0x8(%ebp),%eax 905: c1 e0 03 shl $0x3,%eax 908: 83 ec 0c sub $0xc,%esp 90b: 50 push %eax 90c: e8 19 fc ff ff call 52a <sbrk> 911: 83 c4 10 add $0x10,%esp 914: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 917: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 91b: 75 07 jne 924 <morecore+0x38> return 0; 91d: b8 00 00 00 00 mov $0x0,%eax 922: eb 26 jmp 94a <morecore+0x5e> hp = (Header*)p; 924: 8b 45 f4 mov -0xc(%ebp),%eax 927: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 92a: 8b 45 f0 mov -0x10(%ebp),%eax 92d: 8b 55 08 mov 0x8(%ebp),%edx 930: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 933: 8b 45 f0 mov -0x10(%ebp),%eax 936: 83 c0 08 add $0x8,%eax 939: 83 ec 0c sub $0xc,%esp 93c: 50 push %eax 93d: e8 c8 fe ff ff call 80a <free> 942: 83 c4 10 add $0x10,%esp return freep; 945: a1 28 0d 00 00 mov 0xd28,%eax } 94a: c9 leave 94b: c3 ret 0000094c <malloc>: void* malloc(uint nbytes) { 94c: 55 push %ebp 94d: 89 e5 mov %esp,%ebp 94f: 83 ec 18 sub $0x18,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 952: 8b 45 08 mov 0x8(%ebp),%eax 955: 83 c0 07 add $0x7,%eax 958: c1 e8 03 shr $0x3,%eax 95b: 83 c0 01 add $0x1,%eax 95e: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 961: a1 28 0d 00 00 mov 0xd28,%eax 966: 89 45 f0 mov %eax,-0x10(%ebp) 969: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 96d: 75 23 jne 992 <malloc+0x46> base.s.ptr = freep = prevp = &base; 96f: c7 45 f0 20 0d 00 00 movl $0xd20,-0x10(%ebp) 976: 8b 45 f0 mov -0x10(%ebp),%eax 979: a3 28 0d 00 00 mov %eax,0xd28 97e: a1 28 0d 00 00 mov 0xd28,%eax 983: a3 20 0d 00 00 mov %eax,0xd20 base.s.size = 0; 988: c7 05 24 0d 00 00 00 movl $0x0,0xd24 98f: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 992: 8b 45 f0 mov -0x10(%ebp),%eax 995: 8b 00 mov (%eax),%eax 997: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 99a: 8b 45 f4 mov -0xc(%ebp),%eax 99d: 8b 40 04 mov 0x4(%eax),%eax 9a0: 3b 45 ec cmp -0x14(%ebp),%eax 9a3: 72 4d jb 9f2 <malloc+0xa6> if(p->s.size == nunits) 9a5: 8b 45 f4 mov -0xc(%ebp),%eax 9a8: 8b 40 04 mov 0x4(%eax),%eax 9ab: 3b 45 ec cmp -0x14(%ebp),%eax 9ae: 75 0c jne 9bc <malloc+0x70> prevp->s.ptr = p->s.ptr; 9b0: 8b 45 f4 mov -0xc(%ebp),%eax 9b3: 8b 10 mov (%eax),%edx 9b5: 8b 45 f0 mov -0x10(%ebp),%eax 9b8: 89 10 mov %edx,(%eax) 9ba: eb 26 jmp 9e2 <malloc+0x96> else { p->s.size -= nunits; 9bc: 8b 45 f4 mov -0xc(%ebp),%eax 9bf: 8b 40 04 mov 0x4(%eax),%eax 9c2: 2b 45 ec sub -0x14(%ebp),%eax 9c5: 89 c2 mov %eax,%edx 9c7: 8b 45 f4 mov -0xc(%ebp),%eax 9ca: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 9cd: 8b 45 f4 mov -0xc(%ebp),%eax 9d0: 8b 40 04 mov 0x4(%eax),%eax 9d3: c1 e0 03 shl $0x3,%eax 9d6: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 9d9: 8b 45 f4 mov -0xc(%ebp),%eax 9dc: 8b 55 ec mov -0x14(%ebp),%edx 9df: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 9e2: 8b 45 f0 mov -0x10(%ebp),%eax 9e5: a3 28 0d 00 00 mov %eax,0xd28 return (void*)(p + 1); 9ea: 8b 45 f4 mov -0xc(%ebp),%eax 9ed: 83 c0 08 add $0x8,%eax 9f0: eb 3b jmp a2d <malloc+0xe1> } if(p == freep) 9f2: a1 28 0d 00 00 mov 0xd28,%eax 9f7: 39 45 f4 cmp %eax,-0xc(%ebp) 9fa: 75 1e jne a1a <malloc+0xce> if((p = morecore(nunits)) == 0) 9fc: 83 ec 0c sub $0xc,%esp 9ff: ff 75 ec pushl -0x14(%ebp) a02: e8 e5 fe ff ff call 8ec <morecore> a07: 83 c4 10 add $0x10,%esp a0a: 89 45 f4 mov %eax,-0xc(%ebp) a0d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) a11: 75 07 jne a1a <malloc+0xce> return 0; a13: b8 00 00 00 00 mov $0x0,%eax a18: eb 13 jmp a2d <malloc+0xe1> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ a1a: 8b 45 f4 mov -0xc(%ebp),%eax a1d: 89 45 f0 mov %eax,-0x10(%ebp) a20: 8b 45 f4 mov -0xc(%ebp),%eax a23: 8b 00 mov (%eax),%eax a25: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } a28: e9 6d ff ff ff jmp 99a <malloc+0x4e> } a2d: c9 leave a2e: c3 ret
PUBLIC pixeladdress EXTERN base_graphics ; ; $Id: pixladdr.asm,v 1.2 2015/01/19 01:32:51 pauloscustodio Exp $ ; ; ****************************************************************** ; ; Get absolute pixel address in map of virtual (x,y) coordinate. ; ; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995 ; ; ****************************************************************** ; ; VZ200/300 version By Stefano Bodrato ; ; The VZ screen size is 128x64 ; We draw blue dots over green display (UGH!) ; ; .pixeladdress push hl ld a,h push af rra rra and @00111111 ld b,l ld hl,(base_graphics) ; pointer to base of graphics area ld l,a ld de,32 .adder add hl,de djnz adder ld d,h ld e,l pop af pop hl rla and @00000110 ; a = x mod 8 xor @00000111 ; a = 7 - a ret
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r8 push %r9 push %rbp push %rcx push %rdi push %rsi lea addresses_normal_ht+0xdae8, %rsi lea addresses_UC_ht+0x1c028, %rdi nop nop nop nop nop lfence mov $29, %rcx rep movsq nop nop nop and %r9, %r9 lea addresses_A_ht+0xa828, %r14 nop nop nop xor $62298, %rbp mov (%r14), %r8w nop nop and $33139, %rbp lea addresses_UC_ht+0x73c0, %r9 nop and %r14, %r14 mov $0x6162636465666768, %rcx movq %rcx, %xmm1 movups %xmm1, (%r9) dec %r14 lea addresses_WT_ht+0xefa8, %r14 nop nop nop nop nop cmp $55158, %rdi mov $0x6162636465666768, %rsi movq %rsi, (%r14) nop nop nop add %r9, %r9 pop %rsi pop %rdi pop %rcx pop %rbp pop %r9 pop %r8 pop %r14 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r15 push %rbp push %rbx push %rcx // Faulty Load lea addresses_D+0x18c28, %r11 nop sub %r15, %r15 mov (%r11), %r10w lea oracles, %rbp and $0xff, %r10 shlq $12, %r10 mov (%rbp,%r10,1), %r10 pop %rcx pop %rbx pop %rbp pop %r15 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 2, 'AVXalign': True, 'NT': True, 'congruent': 10, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'36': 1434} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
; ; Small C z88 File functions ; Written by Dominic Morris <djm@jb.man.ac.uk> ; 22 August 1998 ** UNTESTED ** ; ; *** THIS IS A Z88 SPECIFIC ROUTINE!!! *** ; ; 11/3/99 Visited to fix, jp nz,feof_abort was jp z,feof_abort ; if we enter in with a std* stream then we exit with error ; INCLUDE "fileio.def" XLIB fdfeof LIB fhand_ck ;*feof(fp) ;int fp ;on stack ;return address,fp ;fp file handle to query if at end of file .fdfeof ld hl,2 add hl,sp ld e,(hl) inc hl ld d,(hl) call fhand_ck jr nz,feof1 .feof_abort ld hl,-1 ;error! ret .feof1 push de pop ix ld a,fa_eof call_oz(os_frm) jp nz,feof_abort jp c,feof_abort ld hl,0 ret
; Find date V2.00  1989 Tony Tebby QJUMP section iou xdef iou_date include 'dev8_keys_qdos_sms' ;+++ ; Find date ; ; d1 r (long) date ; ; status return arbitrary ;--- iou_date reg.date reg d2/a0 movem.l reg.date,-(sp) moveq #sms.rrtc,d0 trap #do.sms2 movem.l (sp)+,reg.date rts end
; A081288: a(n) is the minimal i such that A000108(i) > n. ; 0,2,3,3,3,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6 mov $3,$0 mov $0,4 mov $1,10 mov $5,$3 lpb $0,1 add $0,3 div $0,2 mul $1,$5 mul $1,4 sub $1,$5 add $1,3 add $4,$1 add $1,$4 clr $2,4 lpe mul $1,2 gcd $5,3 log $1,$5 sub $1,2
MODULE _printk SECTION code_clib PUBLIC _printk PUBLIC _cprintf EXTERN asm_printf EXTERN printk_outc ;sdcc version _printk: _cprintf: ld hl,4 add hl,sp ;points to first argument pop bc ;ret address pop de ;fmt push de push bc IF !__CPU_INTEL__ push ix ;save ix ENDIF push bc ;fp (we don't care about it) ld bc,printk_outc push bc ld bc,0 ;flag push bc push de ;fmt push hl ;argument call asm_printf pop bc pop bc pop bc pop bc pop bc IF !__CPU_INTEL__ pop ix ;restore ix ENDIF ret
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. 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 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 INTEL OR ITS 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. END_LEGAL */ // Encapsulating all floating point operations within the Pintool // replacement function inside "fxsave; emms" and "fxrstor" causes // a seg fault. // // Robert reproduced this problem on vs-lin64-3. The problem is // that the stack pointer is not properly aligned in the replacement // routine and you get a segv trying to save an xmm to memory. // // (gdb) x/i$pc // 0x2a96429676: movaps XMMWORD PTR [rax-0x7f],xmm0 // (gdb) p/x $rax-0x7f // $2 = 0x2a9816b8b8 // // At the entry point, it should be 8 mod 16, but it is 0 mod 16. #include <iostream> #include <stdio.h> #include "pin.H" void my_print(int x) { #if defined(TARGET_IA32) || defined(TARGET_IA32E) static char buffer[2048]; static char* aligned_bufp =reinterpret_cast<char*> (((reinterpret_cast<ADDRINT>(buffer) + 16) >> 4)<<4); #if defined(PIN_GNU_COMPATIBLE) cerr << "Pin GNU compatible" << endl; asm volatile ("fxsave %0\n\t" "emms" : "=m"(*aligned_bufp)); #else __asm { push eax mov eax, aligned_bufp fxsave [eax] pop eax } #endif #endif cerr << "my_print: " << x << endl; double y = x * 0.33445; cerr << "Done initializing y" << endl; cerr << y << endl; cerr << "Done with my_print" << endl; #if defined(TARGET_IA32) || defined(TARGET_IA32E) #if defined(PIN_GNU_COMPATIBLE) asm volatile ("fxrstor %0" :: "m"(*aligned_bufp)); #else __asm { push eax mov eax, aligned_bufp fxrstor [eax] pop eax } #endif #endif } VOID ImageLoad(IMG img, VOID * v) { RTN rtn; rtn = RTN_FindByName(img, "print"); if (RTN_Valid(rtn)) { PROTO proto = PROTO_Allocate(PIN_PARG(void), CALLINGSTD_DEFAULT, "print", PIN_PARG(int), PIN_PARG_END()); RTN_ReplaceSignature(rtn, (AFUNPTR)my_print, IARG_PROTOTYPE, proto, IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END); } } int main(int argc, char *argv[]) { PIN_InitSymbols(); PIN_Init(argc, argv); IMG_AddInstrumentFunction(ImageLoad, 0); PIN_StartProgram(); return 0; }
;*********************************************************** ; Version 2.40.00 ;*********************************************************** ; Function: log_2 ; Description: Calculate log base 2 of 16-bit Q15 number ; ; Copyright Texas instruments Inc, 2000 ;******************************************************************************** .mmregs ; assign Memory-Mapped Register names as global symbols .def _log_2 .asg #04000h, CST_4000 .asg #0DC56h, LB6 .asg #54adh, LB5 .asg #9e8ah, LB4 .asg #50d5h, LB3 .asg #0c056h, LB2 .asg #3ffdh, LB1 .asg #062dh, LB0 .asg #1h, CST_1 .asg #58B9h, CST_ln2 .asg #0D8B9h, NCST_ln2 .text ; begin assembling into .text section _log_2: PSH mmap(ST1_55) AADD #-15, SP NOP ;initialization for Logarithm calculation MOV XSP, XAR2 MOV CST_4000, *AR2+ MOV LB6, *AR2+ MOV LB5, *AR2+ MOV LB4, *AR2+ MOV LB3, *AR2+ MOV LB2, *AR2+ MOV LB1, *AR2+ MOV LB0, *AR2+ MOV CST_1, *AR2+ MOV CST_ln2, *AR2 MOV T0, AC0 SUB #1, AC0 MOV AC0, mmap(BRC0) RPTB loop1 - 1 ************** * Normalize x ************** MOV SP, AR2 MOV *AR0+ << #16, AC0 ;A = x << 16 EXP AC0, T0 ;T = number of leading bits BCLR FRCT SFTS AC0, T0, AC1 *************************** * Polynomial approximation *************************** SFTS AC1, #-15, AC0 ;A <- 2*M SUB *AR2+ << #1, AC0 ;A <- (2*M-1) Q15 MOV AC0, T1 ;U <- (2*M-1) Q15 (between 0.0 and 1.0) MOV *AR2+ << #16, AC0 ;B6 load MOV *AR2+ << #16, AC1 ;B5 load MOV *AR2+ << #16, AC1 ;B4 load ||MACR AC0, T1, AC1, AC0 ;A(32-16) <- B6*U + B5 ;Q34 + Q18 << 16 = Q34 MOV *AR2+ << #16, AC1 ;B3 load ||MACR AC0, T1, AC1, AC0 ;A <- (B6*U + B5)*U + B4 ;Q33 + Q17 << 16 = Q33 MOV *AR2+ << #16, AC1 ;B2 load ||MACR AC0, T1, AC1, AC0 ;A <- ((B6*U+B5)*U+B4)*U+B3 ;Q32 + Q16 << 16 = Q32 MOV *AR2+ << #16, AC1 ;B1 load ||MACR AC0, T1, AC1, AC0 ;A <- (((B6*U+B5)*U+B4)*U+B3)*U+B2 ;Q31 + Q15 << 16 = Q31 MOV *AR2 << #16, AC1 ;B0 load ||MACR AC0, T1, AC1, AC0 ;A <- ((((B6*U+B5)*U+B4)*U+B3)*U+B2)*U+B1 ;Q30 + Q14 << 16 = Q30 SFTSC AC0, #1 MPY T1, AC0 ADD *AR2+, AC0 ; A <- (((((B6*U + B5)*U + B4)*U + B3)*U + B2)*U ; + B1)*U + B0 ;Q30 + Q30 = Q30 ******************* * Process exponent ******************* NEG T0, AC1 ;AC1 <- number of leading bits SUB *AR2+, AC1 ;AC1 <- P-1 MOV AC1, T0 SFTS AC0, #-15 MPYM *AR2, T0, AC1 ;AC1 <- ln2 * (P-1) ************************* * Add both contributions ************************* ADD AC1, AC0 ; AC0 = <- f(2*M(x)-1) + (P(x)-1)*ln(2) MOV AC0, AC1 ;store AC0 temporarily MOV #038AAh, T1 ;0.4427 in hex BSET FRCT ||SFTSC AC0, #1 ;shift for 17 mpy MPY T1, AC0 SFTSC AC0, #-1 ;Hi word in AC0 ADD AC1, AC0 AND #7FFFh, AC1 ;take out low word from old AC0 SFTSC AC1, #16 ;process low word MPY T1, AC1 SFTSC AC1, #-16 ;Lo word in AC1 ADD AC1, AC0 ;add words together MOV AC0, dbl(*AR1+) endlog loop1: ************************ * Return overflow flag ************************ AADD #15, SP POP mmap(ST1_55) MOV #0, T0 XCC check, overflow(AC0) MOV #1, T0 check: RET ;end of file. please do not remove. it is left here to ensure that no lines of code are removed by any editor
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %r14 push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x14901, %r12 nop nop nop nop inc %rsi movw $0x6162, (%r12) nop nop nop nop add $38115, %r14 lea addresses_A_ht+0x17f92, %rsi lea addresses_normal_ht+0x151d9, %rdi clflush (%rsi) nop nop nop nop and $50732, %r11 mov $57, %rcx rep movsb nop nop nop nop inc %r12 lea addresses_UC_ht+0xefd5, %rsi lea addresses_A_ht+0x3537, %rdi clflush (%rdi) nop nop nop nop dec %r14 mov $116, %rcx rep movsq nop sub %rcx, %rcx lea addresses_D_ht+0x1c789, %rsi nop nop and %r14, %r14 movups (%rsi), %xmm0 vpextrq $0, %xmm0, %r11 nop sub $32640, %rdi lea addresses_UC_ht+0x18b29, %rsi clflush (%rsi) nop cmp $27599, %rcx mov $0x6162636465666768, %r14 movq %r14, (%rsi) nop dec %r14 lea addresses_A_ht+0x17b49, %rsi lea addresses_WT_ht+0xd129, %rdi nop nop and $46425, %r10 mov $79, %rcx rep movsb nop nop and $46780, %r11 lea addresses_D_ht+0x1e789, %rdi and $9240, %r10 movw $0x6162, (%rdi) nop nop nop nop nop sub $55592, %rdi lea addresses_WC_ht+0x105d8, %rsi lea addresses_UC_ht+0xce30, %rdi nop nop nop cmp %rdx, %rdx mov $114, %rcx rep movsq inc %rdi lea addresses_D_ht+0x2c89, %rsi nop nop nop lfence movups (%rsi), %xmm4 vpextrq $0, %xmm4, %r11 nop nop nop nop nop dec %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %r14 pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r8 push %r9 push %rcx push %rdi push %rsi // Store lea addresses_normal+0xd261, %r11 add $36385, %r8 mov $0x5152535455565758, %r13 movq %r13, (%r11) nop sub $16932, %r11 // REPMOV lea addresses_D+0x1f146, %rsi lea addresses_WT+0x1a321, %rdi clflush (%rsi) dec %r11 mov $51, %rcx rep movsl nop nop nop nop inc %rcx // Store lea addresses_PSE+0x1b15a, %r12 nop nop nop nop add $56699, %r13 mov $0x5152535455565758, %r11 movq %r11, %xmm3 movups %xmm3, (%r12) nop nop nop nop add $29988, %rsi // Faulty Load lea addresses_WC+0x12c89, %r9 nop nop nop nop cmp %rsi, %rsi mov (%r9), %r11 lea oracles, %r13 and $0xff, %r11 shlq $12, %r11 mov (%r13,%r11,1), %r11 pop %rsi pop %rdi pop %rcx pop %r9 pop %r8 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 8, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_WT', 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'38': 6253} 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 */
; A027382: a(n) = n^4 - 6*n^3 + 12*n^2 - 4*n + 1. ; 1,4,9,16,49,156,409,904,1761,3124,5161,8064,12049,17356,24249,33016,43969,57444,73801,93424,116721,144124,176089,213096,255649,304276,359529,421984,492241,570924,658681 mov $3,$0 mov $6,$0 lpb $0 sub $3,3 mul $3,$0 mov $0,$5 lpe mov $1,1 add $1,$3 pow $1,2 mov $2,$6 mul $2,2 add $1,$2 mov $4,$6 mul $4,$6 add $1,$4
// dear imgui: standalone example application for Glfw + Vulkan // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering back-end in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_vulkan.h" #include <stdio.h> // printf, fprintf #include <stdlib.h> // abort #define GLFW_INCLUDE_NONE #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include <vulkan/vulkan.h> // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers. // To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma. // Your own project should not be affected, as you are likely to link with a newer binary of GLFW that is adequate for your version of Visual Studio. #if defined(_MSC_VER) && (_MSC_VER >= 1900) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) #pragma comment(lib, "legacy_stdio_definitions") #endif //#define IMGUI_UNLIMITED_FRAME_RATE #ifdef _DEBUG #define IMGUI_VULKAN_DEBUG_REPORT #endif static VkAllocationCallbacks* g_Allocator = NULL; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; static VkDevice g_Device = VK_NULL_HANDLE; static uint32_t g_QueueFamily = (uint32_t)-1; static VkQueue g_Queue = VK_NULL_HANDLE; static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static int g_MinImageCount = 2; static bool g_SwapChainRebuild = false; static int g_SwapChainResizeWidth = 0; static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { if (err == 0) return; fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) abort(); } #ifdef IMGUI_VULKAN_DEBUG_REPORT static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } #endif // IMGUI_VULKAN_DEBUG_REPORT static void SetupVulkan(const char** extensions, uint32_t extensions_count) { VkResult err; // Create Vulkan Instance { VkInstanceCreateInfo create_info = {}; create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; create_info.enabledExtensionCount = extensions_count; create_info.ppEnabledExtensionNames = extensions; #ifdef IMGUI_VULKAN_DEBUG_REPORT // Enabling multiple validation layers grouped as LunarG standard validation const char* layers[] = { "VK_LAYER_LUNARG_standard_validation" }; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = layers; // Enable debug report extension (we need additional storage, so we duplicate the user array to add our new extension to it) const char** extensions_ext = (const char**)malloc(sizeof(const char*) * (extensions_count + 1)); memcpy(extensions_ext, extensions, extensions_count * sizeof(const char*)); extensions_ext[extensions_count] = "VK_EXT_debug_report"; create_info.enabledExtensionCount = extensions_count + 1; create_info.ppEnabledExtensionNames = extensions_ext; // Create Vulkan Instance err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); check_vk_result(err); free(extensions_ext); // Get the function pointer (required for any extensions) auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); IM_ASSERT(vkCreateDebugReportCallbackEXT != NULL); // Setup the debug report callback VkDebugReportCallbackCreateInfoEXT debug_report_ci = {}; debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; debug_report_ci.pfnCallback = debug_report; debug_report_ci.pUserData = NULL; err = vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); check_vk_result(err); #else // Create Vulkan Instance without any debug feature err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); check_vk_result(err); IM_UNUSED(g_DebugReport); #endif } // Select GPU { uint32_t gpu_count; err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, NULL); check_vk_result(err); IM_ASSERT(gpu_count > 0); VkPhysicalDevice* gpus = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * gpu_count); err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus); check_vk_result(err); // If a number >1 of GPUs got reported, you should find the best fit GPU for your purpose // e.g. VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU if available, or with the greatest memory available, etc. // for sake of simplicity we'll just take the first one, assuming it has a graphics queue family. g_PhysicalDevice = gpus[0]; free(gpus); } // Select graphics queue family { uint32_t count; vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, NULL); VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); for (uint32_t i = 0; i < count; i++) if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { g_QueueFamily = i; break; } free(queues); IM_ASSERT(g_QueueFamily != (uint32_t)-1); } // Create Logical Device (with 1 queue) { int device_extension_count = 1; const char* device_extensions[] = { "VK_KHR_swapchain" }; const float queue_priority[] = { 1.0f }; VkDeviceQueueCreateInfo queue_info[1] = {}; queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_info[0].queueFamilyIndex = g_QueueFamily; queue_info[0].queueCount = 1; queue_info[0].pQueuePriorities = queue_priority; VkDeviceCreateInfo create_info = {}; create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; create_info.queueCreateInfoCount = sizeof(queue_info) / sizeof(queue_info[0]); create_info.pQueueCreateInfos = queue_info; create_info.enabledExtensionCount = device_extension_count; create_info.ppEnabledExtensionNames = device_extensions; err = vkCreateDevice(g_PhysicalDevice, &create_info, g_Allocator, &g_Device); check_vk_result(err); vkGetDeviceQueue(g_Device, g_QueueFamily, 0, &g_Queue); } // Create Descriptor Pool { VkDescriptorPoolSize pool_sizes[] = { { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 }, { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 }, { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 }, { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 }, { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 }, { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 }, { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 }, { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 }, { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 }, { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 }, { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 } }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; pool_info.maxSets = 1000 * IM_ARRAYSIZE(pool_sizes); pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); check_vk_result(err); } } // All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo. // Your real engine/app may not use them. static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; // Check for WSI support VkBool32 res; vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res); if (res != VK_TRUE) { fprintf(stderr, "Error no WSI support on physical device 0\n"); exit(-1); } // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode #ifdef IMGUI_UNLIMITED_FRAME_RATE VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; #endif wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes)); //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } static void CleanupVulkan() { vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); #ifdef IMGUI_VULKAN_DEBUG_REPORT // Remove the debug report callback auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT"); vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator); #endif // IMGUI_VULKAN_DEBUG_REPORT vkDestroyDevice(g_Device, g_Allocator); vkDestroyInstance(g_Instance, g_Allocator); } static void CleanupVulkanWindow() { ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { VkResult err; VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking check_vk_result(err); err = vkResetFences(g_Device, 1, &fd->Fence); check_vk_result(err); } { err = vkResetCommandPool(g_Device, fd->CommandPool, 0); check_vk_result(err); VkCommandBufferBeginInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; err = vkBeginCommandBuffer(fd->CommandBuffer, &info); check_vk_result(err); } { VkRenderPassBeginInfo info = {}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; info.renderPass = wd->RenderPass; info.framebuffer = fd->Framebuffer; info.renderArea.extent.width = wd->Width; info.renderArea.extent.height = wd->Height; info.clearValueCount = 1; info.pClearValues = &wd->ClearValue; vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); } // Record dear imgui primitives into command buffer ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); { VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; VkSubmitInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; info.waitSemaphoreCount = 1; info.pWaitSemaphores = &image_acquired_semaphore; info.pWaitDstStageMask = &wait_stage; info.commandBufferCount = 1; info.pCommandBuffers = &fd->CommandBuffer; info.signalSemaphoreCount = 1; info.pSignalSemaphores = &render_complete_semaphore; err = vkEndCommandBuffer(fd->CommandBuffer); check_vk_result(err); err = vkQueueSubmit(g_Queue, 1, &info, fd->Fence); check_vk_result(err); } } static void FramePresent(ImGui_ImplVulkanH_Window* wd, GLFWwindow* window) { VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; info.pWaitSemaphores = &render_complete_semaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); if (err == VK_ERROR_OUT_OF_DATE_KHR) { glfwGetFramebufferSize(window, &g_SwapChainResizeWidth, &g_SwapChainResizeHeight); g_SwapChainRebuild = true; return; } check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } static void glfw_error_callback(int error, const char* description) { fprintf(stderr, "Glfw Error %d: %s\n", error, description); } int main(int, char**) { // Setup GLFW window glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return 1; glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Vulkan example", NULL, NULL); // Setup Vulkan if (!glfwVulkanSupported()) { printf("GLFW: Vulkan Not Supported\n"); return 1; } uint32_t extensions_count = 0; const char** extensions = glfwGetRequiredInstanceExtensions(&extensions_count); SetupVulkan(extensions, extensions_count); // Create Window Surface VkSurfaceKHR surface; VkResult err = glfwCreateWindowSurface(g_Instance, window, g_Allocator, &surface); check_vk_result(err); // Create Framebuffers int w, h; glfwGetFramebufferSize(window, &w, &h); ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows //io.ConfigViewportsNoAutoMerge = true; //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. ImGuiStyle& style = ImGui::GetStyle(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { style.WindowRounding = 0.0f; style.Colors[ImGuiCol_WindowBg].w = 1.0f; } // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForVulkan(window, true); ImGui_ImplVulkan_InitInfo init_info = {}; init_info.Instance = g_Instance; init_info.PhysicalDevice = g_PhysicalDevice; init_info.Device = g_Device; init_info.QueueFamily = g_QueueFamily; init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd->ImageCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); // Upload Fonts { // Use any command queue VkCommandPool command_pool = wd->Frames[wd->FrameIndex].CommandPool; VkCommandBuffer command_buffer = wd->Frames[wd->FrameIndex].CommandBuffer; err = vkResetCommandPool(g_Device, command_pool, 0); check_vk_result(err); VkCommandBufferBeginInfo begin_info = {}; begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; err = vkBeginCommandBuffer(command_buffer, &begin_info); check_vk_result(err); ImGui_ImplVulkan_CreateFontsTexture(command_buffer); VkSubmitInfo end_info = {}; end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; end_info.commandBufferCount = 1; end_info.pCommandBuffers = &command_buffer; err = vkEndCommandBuffer(command_buffer); check_vk_result(err); err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE); check_vk_result(err); err = vkDeviceWaitIdle(g_Device); check_vk_result(err); ImGui_ImplVulkan_DestroyFontUploadObjects(); } // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Main loop while (!glfwWindowShouldClose(window)) { // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); // Resize swap chain? if (g_SwapChainRebuild && g_SwapChainResizeWidth > 0 && g_SwapChainResizeHeight > 0) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); g_MainWindowData.FrameIndex = 0; } // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. { static float f = 0.0f; static int counter = 0; ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) counter++; ImGui::SameLine(); ImGui::Text("counter = %d", counter); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); } // 3. Show another simple window. if (show_another_window) { ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) show_another_window = false; ImGui::End(); } // Rendering ImGui::Render(); ImDrawData* main_draw_data = ImGui::GetDrawData(); const bool main_is_minimized = (main_draw_data->DisplaySize.x <= 0.0f || main_draw_data->DisplaySize.y <= 0.0f); memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); if (!main_is_minimized) FrameRender(wd, main_draw_data); // Update and Render additional Platform Windows if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); } // Present Main Platform Window if (!main_is_minimized) FramePresent(wd); } // Cleanup err = vkDeviceWaitIdle(g_Device); check_vk_result(err); ImGui_ImplVulkan_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); CleanupVulkanWindow(); CleanupVulkan(); glfwDestroyWindow(window); glfwTerminate(); return 0; }
; A170765: Expansion of g.f.: (1+x)/(1-45*x). ; Submitted by Jon Maiga ; 1,46,2070,93150,4191750,188628750,8488293750,381973218750,17188794843750,773495767968750,34807309558593750,1566328930136718750,70484801856152343750,3171816083526855468750,142731723758708496093750,6422927569141882324218750,289031740611384704589843750,13006428327512311706542968750,585289274738054026794433593750,26338017363212431205749511718750,1185210781344559404258728027343750,53334485160505173191642761230468750,2400051832222732793623924255371093750,108002332450022975713076591491699218750 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,45 lpe mov $0,$2 div $0,45
; --------------------------------------------------------------------------- ; Sprite mappings - purple rock (GHZ) ; --------------------------------------------------------------------------- dc.w byte_D110-Map_obj3B byte_D110: dc.b 2 dc.b $F0, $B, 0, 0, $E8 dc.b $F0, $B, 0, $C, 0 even
; void __CALLEE__ sp1_PrintAtInv_callee(uchar row, uchar col, uint tile) ; 01.2008 aralbrec, Sprite Pack v3.0 ; ts2068 hi-res version SECTION code_sprite_sp1 PUBLIC sp1_PrintAtInv_callee PUBLIC ASMDISP_SP1_PRINTATINV_CALLEE EXTERN sp1_GetUpdateStruct_callee, sp1_PrintAt_callee EXTERN ASMDISP_SP1_GETUPDATESTRUCT_CALLEE, ASMDISP_SP1_PRINTAT_CALLEE EXTERN SP1V_UPDATELISTT .sp1_PrintAtInv_callee pop af pop bc pop de pop hl ld d,l push af .asmentry ; Print tile and colour to given coordinate and invalidate ; the tile so that it is redrawn in the next update. ; ; enter : d = row coord ; e = col coord ; bc = tile code ; uses : af, bc, de, hl .SP1PrintAtInv call sp1_GetUpdateStruct_callee + ASMDISP_SP1_GETUPDATESTRUCT_CALLEE ld a,(hl) xor $80 jp p, sp1_PrintAt_callee + ASMDISP_SP1_PRINTAT_CALLEE + 3 ; if already marked for invalidation just do PrintAt ld (hl),a ; mark struct_sp1_update as invalidated ld e,l ld d,h ; de = & struct sp1_update inc hl ld (hl),c ; write tile inc hl ld (hl),b inc hl inc hl inc hl ld (hl),0 ; mark no struct sp1_update following in invalidated list ld hl,(SP1V_UPDATELISTT) ; current last sp1_update in invalidated list ld bc,5 add hl,bc ld (hl),d ; store this new sp1_update into current tail inc hl ld (hl),e ld (SP1V_UPDATELISTT),de ; this new struct sp1_update is now the tail in invalidated list ret DEFC ASMDISP_SP1_PRINTATINV_CALLEE = asmentry - sp1_PrintAtInv_callee
copyright zengfr site:http://github.com/zengfr/romhack 0252F8 ble $25312 [enemy+33] 0252FE jsr $1426.w [enemy+33] 0255F4 move.b ($33,A0), D0 [enemy+32] 0255F8 beq $25606 [enemy+33] 026AE4 move.b ($33,A0), D0 [enemy+32] 026AE8 beq $26af6 [enemy+33] 02940A move.b ($33,A0), D0 [enemy+32] 02940E beq $2941c [enemy+33] 02A7D8 move.b ($33,A0), D0 [enemy+32] 02A7DC beq $2a7ea [enemy+33] 02B9F8 move.b ($33,A0), D0 [enemy+32] 02B9FC beq $2ba0a [enemy+33] 032BA6 move.b ($33,A0), D0 [enemy+7A] 032BAA beq $32bb8 [enemy+33] 033140 beq $33152 [enemy+33] 0369B0 beq $369be [enemy+33] 036C32 beq $36c68 [enemy+33] 036C4E bra $36c68 [enemy+33] 036C68 tst.w ($68,A0) [enemy+33] 036E12 beq $36e22 [enemy+33] 036F28 beq $36f5e [enemy+33] 046B24 move.b ($33,A0), D0 [enemy+7A] 046B28 beq $46b42 [enemy+33] 04D3E2 beq $4d420 [enemy+33] copyright zengfr site:http://github.com/zengfr/romhack
; This is free and unencumbered software released into the public domain. ; Anyone is free to copy, modify, publish, use, compile, sell, or ; distribute this software, either in source code form or as a compiled ; binary, for any purpose, commercial or non-commercial, and by any ; means. ; In jurisdictions that recognize copyright laws, the author or authors ; of this software dedicate any and all copyright interest in the ; software to the public domain. We make this dedication for the benefit ; of the public at large and to the detriment of our heirs and ; successors. We intend this dedication to be an overt act of ; relinquishment in perpetuity of all present and future rights to this ; software under copyright law. ; 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 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. ; For more information, please refer to <https://unlicense.org> section .multiboot_header header_start: ; magic number dd 0xe85250d6 ; multiboot2 ; architecture dd 0 ; protected mode i386 ; header length dd header_end - header_start ; checksum dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start)) ; end tag dw 0 dw 0 dd 8 header_end:
SECTION code_stdio PUBLIC __stdio_unlock_file_list EXTERN __stdio_file_list_lock EXTERN asm_mtx_unlock __stdio_unlock_file_list: ; unlock stdio's FILE lists ; ; enter : none ; ; exit : none ; ; uses : af, bc, de, hl ld hl,__stdio_file_list_lock jp asm_mtx_unlock
; L1512.asm Crouton Homeworld 4 ; Generated 04.19.2001 by mlevel ; Modified 04.19.2001 by Abe Pralle INCLUDE "Source/Defs.inc" INCLUDE "Source/Levels.inc" VFENCE_INDEX EQU 19 VAR_BGKILLED EQU 15 ;--------------------------------------------------------------------- SECTION "Level1512Section",ROMX ;--------------------------------------------------------------------- L1512_Contents:: DW L1512_Load DW L1512_Init DW L1512_Check DW L1512_Map ;--------------------------------------------------------------------- ; Load ;--------------------------------------------------------------------- L1512_Load: DW ((L1512_LoadFinished - L1512_Load2)) ;size L1512_Load2: call ParseMap ret L1512_LoadFinished: ;--------------------------------------------------------------------- ; Map ;--------------------------------------------------------------------- L1512_Map: INCBIN "Data/Levels/L1512_crouton_hw4.lvl" ;--------------------------------------------------------------------- ; Init ;--------------------------------------------------------------------- L1512_Init: DW ((L1512_InitFinished - L1512_Init2)) ;size L1512_Init2: xor a ld [levelVars+VAR_BGKILLED],a ret L1512_InitFinished: ;--------------------------------------------------------------------- ; Check ;--------------------------------------------------------------------- L1512_Check: DW ((L1512_CheckFinished - L1512_Check2)) ;size L1512_Check2: call ((.animateFence-L1512_Check2)+levelCheckRAM) call ((.checkBlowGenerators-L1512_Check2)+levelCheckRAM) ret .checkBlowGenerators ld a,[levelVars+VAR_BGKILLED] or a ret z ld a,[hero0_index] or a jr z,.checkHero1 ;change hero 0 to actor & walk to teleport ld c,a call GetFirst ld hl,$d0e4 call SetActorDestLoc call GetClassMethodTable ld b,h ld c,l ld de,classActor call ChangeClass .checkHero1 ld a,[hero1_index] or a jr z,.startExplosions ;change hero 1 to actor & walk to teleport ld c,a call GetFirst ld hl,$d104 call SetActorDestLoc call GetClassMethodTable ld b,h ld c,l ld de,classActor call ChangeClass .startExplosions ld hl,$d0cb call ((.explodeGenerator-L1512_Check2)+levelCheckRAM) call ((.animateDelay-L1512_Check2)+levelCheckRAM) ld hl,$d0ce call ((.explodeGenerator-L1512_Check2)+levelCheckRAM) call ((.animateDelay-L1512_Check2)+levelCheckRAM) ld hl,$d0d1 call ((.explodeGenerator-L1512_Check2)+levelCheckRAM) ld hl,$d12e call ((.explodeGenerator-L1512_Check2)+levelCheckRAM) call ((.animateDelay-L1512_Check2)+levelCheckRAM) ld hl,$d0d4 call ((.explodeGenerator-L1512_Check2)+levelCheckRAM) ld hl,$d131 call ((.explodeGenerator-L1512_Check2)+levelCheckRAM) call ((.animateDelay-L1512_Check2)+levelCheckRAM) ld a,EXIT_U ld [hero0_enterLevelFacing],a ld [hero1_enterLevelFacing],a ld hl,$0612 ld a,l ld [curLevelIndex],a ld a,h ld [curLevelIndex+1],a ld a,EXIT_U call YankRemotePlayer ld a,1 ld [timeToChangeLevel],a ret .explodeGenerator xor a ld [bulletColor],a ld bc,$0303 ld de,$1407 push hl call CreateBigExplosion ld hl,bigExplosionSound call PlaySound ld a,15 ldio [jiggleDuration],a pop hl ;remove generator from map ld a,MAPBANK ldio [$ff70],a ld d,0 ld a,[mapPitch] ld e,a xor a ld [hl+],a ld [hl+],a ld [hl],a add hl,de ld [hl-],a ld [hl-],a ld [hl],a add hl,de ld [hl+],a ld [hl+],a ld [hl],a ret .animateDelay ld a,30 .animateDelayLoop push af ld a,1 call Delay call ((.animateFence-L1512_Check2)+levelCheckRAM) pop af dec a jr nz,.animateDelayLoop ret .animateFence ldio a,[updateTimer] rrca and 3 ld b,a ld hl,bgTileMap+VFENCE_INDEX ld d,VFENCE_INDEX call ((.animateFourFrames-L1512_Check2)+levelCheckRAM) ret .animateFourFrames ld c,4 .animateFourFrames_loop ld a,b add c and 3 add d ld [hl+],a dec c jr nz,.animateFourFrames_loop ret L1512_CheckFinished: PRINT "1512 Script Sizes (Load/Init/Check) (of $500): " PRINT (L1512_LoadFinished - L1512_Load2) PRINT " / " PRINT (L1512_InitFinished - L1512_Init2) PRINT " / " PRINT (L1512_CheckFinished - L1512_Check2) PRINT "\n"
; A169034: Number of reduced words of length n in Coxeter group on 21 generators S_i with relations (S_i)^2 = (S_i S_j)^24 = I. ; 1,21,420,8400,168000,3360000,67200000,1344000000,26880000000,537600000000,10752000000000,215040000000000,4300800000000000,86016000000000000,1720320000000000000,34406400000000000000 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,20 lpe mov $0,$2 div $0,20
# Intel P5 mpn_lshift -- mpn left shift. # # P5: 1.75 cycles/limb. # Copyright (C) 2000 Free Software Foundation, Inc. # # This file is part of the GNU MP Library. # # The GNU MP Library is free software; you can redistribute it and/or modify # it under the terms of the GNU Library General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # The GNU MP Library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public # License for more details. # # You should have received a copy of the GNU Library General Public License # along with the GNU MP Library; see the file COPYING.LIB. If not, write to # the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, # MA 02111-1307, USA. include(`../config.m4') # mp_limb_t mpn_lshift (mp_ptr dst, mp_srcptr src, mp_size_t size, # unsigned shift); # # Shift src,size left by shift many bits and store the result in dst,size. # Zeros are shifted in at the right. Return the bits shifted out at the # left. # # The comments in mpn_rshift apply here too. defframe(PARAM_SHIFT,16) defframe(PARAM_SIZE, 12) defframe(PARAM_SRC, 8) defframe(PARAM_DST, 4) deflit(`FRAME',0) dnl minimum 5, because the unrolled loop can't handle less deflit(UNROLL_THRESHOLD, 5) .text ALIGN(8) PROLOGUE(mpn_lshift) pushl %ebx pushl %edi deflit(`FRAME',8) movl PARAM_SIZE, %eax movl PARAM_DST, %edx movl PARAM_SRC, %ebx movl PARAM_SHIFT, %ecx cmp $UNROLL_THRESHOLD, %eax jae L(unroll) movl -4(%ebx,%eax,4), %edi # src high limb decl %eax jnz L(simple) shldl( %cl, %edi, %eax) # eax was decremented to zero shll %cl, %edi movl %edi, (%edx) # dst low limb popl %edi # risk of data cache bank clash popl %ebx ret #------------------------------------------------------------------------------ L(simple): # eax size-1 # ebx src # ecx shift # edx dst # esi # edi # ebp deflit(`FRAME',8) movd (%ebx,%eax,4), %mm5 # src high limb movd %ecx, %mm6 # lshift negl %ecx psllq %mm6, %mm5 addl $32, %ecx movd %ecx, %mm7 psrlq $32, %mm5 # retval L(simple_top): # eax counter, limbs, negative # ebx src # ecx # edx dst # esi # edi # # mm0 scratch # mm5 return value # mm6 shift # mm7 32-shift movq -4(%ebx,%eax,4), %mm0 decl %eax psrlq %mm7, %mm0 # movd %mm0, 4(%edx,%eax,4) jnz L(simple_top) movd (%ebx), %mm0 movd %mm5, %eax psllq %mm6, %mm0 popl %edi popl %ebx movd %mm0, (%edx) emms ret #------------------------------------------------------------------------------ ALIGN(8) L(unroll): # eax size # ebx src # ecx shift # edx dst # esi # edi # ebp deflit(`FRAME',8) movd -4(%ebx,%eax,4), %mm5 # src high limb leal (%ebx,%eax,4), %edi movd %ecx, %mm6 # lshift andl $4, %edi psllq %mm6, %mm5 jz L(start_src_aligned) # src isn't aligned, process high limb separately (marked xxx) to # make it so. # # source -8(ebx,%eax,4) # | # +-------+-------+-------+-- # | | # +-------+-------+-------+-- # 0mod8 4mod8 0mod8 # # dest # -4(edx,%eax,4) # | # +-------+-------+-- # | xxx | | # +-------+-------+-- movq -8(%ebx,%eax,4), %mm0 # unaligned load psllq %mm6, %mm0 decl %eax psrlq $32, %mm0 # movd %mm0, (%edx,%eax,4) L(start_src_aligned): movq -8(%ebx,%eax,4), %mm1 # src high qword leal (%edx,%eax,4), %edi andl $4, %edi psrlq $32, %mm5 # return value movq -16(%ebx,%eax,4), %mm3 # src second highest qword jz L(start_dst_aligned) # dst isn't aligned, subtract 4 to make it so, and pretend the shift # is 32 bits extra. High limb of dst (marked xxx) handled here # separately. # # source -8(ebx,%eax,4) # | # +-------+-------+-- # | mm1 | # +-------+-------+-- # 0mod8 4mod8 # # dest # -4(edx,%eax,4) # | # +-------+-------+-------+-- # | xxx | | # +-------+-------+-------+-- # 0mod8 4mod8 0mod8 movq %mm1, %mm0 addl $32, %ecx # new shift psllq %mm6, %mm0 movd %ecx, %mm6 psrlq $32, %mm0 # wasted cycle here waiting for %mm0 movd %mm0, -4(%edx,%eax,4) subl $4, %edx L(start_dst_aligned): psllq %mm6, %mm1 negl %ecx # -shift addl $64, %ecx # 64-shift movq %mm3, %mm2 movd %ecx, %mm7 subl $8, %eax # size-8 psrlq %mm7, %mm3 por %mm1, %mm3 # mm3 ready to store jc L(finish) # The comments in mpn_rshift apply here too. ALIGN(8) L(unroll_loop): # eax counter, limbs # ebx src # ecx # edx dst # esi # edi # # mm0 # mm1 # mm2 src qword from 48(%ebx,%eax,4) # mm3 dst qword ready to store to 56(%edx,%eax,4) # # mm5 return value # mm6 lshift # mm7 rshift movq 8(%ebx,%eax,4), %mm0 psllq %mm6, %mm2 movq %mm0, %mm1 psrlq %mm7, %mm0 movq %mm3, 24(%edx,%eax,4) # prev por %mm2, %mm0 movq (%ebx,%eax,4), %mm3 # psllq %mm6, %mm1 # movq %mm0, 16(%edx,%eax,4) movq %mm3, %mm2 # psrlq %mm7, %mm3 # subl $4, %eax por %mm1, %mm3 # jnc L(unroll_loop) L(finish): # eax -4 to -1 representing respectively 0 to 3 limbs remaining testb $2, %al jz L(finish_no_two) movq 8(%ebx,%eax,4), %mm0 psllq %mm6, %mm2 movq %mm0, %mm1 psrlq %mm7, %mm0 movq %mm3, 24(%edx,%eax,4) # prev por %mm2, %mm0 movq %mm1, %mm2 movq %mm0, %mm3 subl $2, %eax L(finish_no_two): # eax -4 or -3 representing respectively 0 or 1 limbs remaining # # mm2 src prev qword, from 48(%ebx,%eax,4) # mm3 dst qword, for 56(%edx,%eax,4) testb $1, %al movd %mm5, %eax # retval popl %edi jz L(finish_zero) # One extra src limb, destination was aligned. # # source ebx # --+---------------+-------+ # | mm2 | | # --+---------------+-------+ # # dest edx+12 edx+4 edx # --+---------------+---------------+-------+ # | mm3 | | | # --+---------------+---------------+-------+ # # mm6 = shift # mm7 = ecx = 64-shift # One extra src limb, destination was unaligned. # # source ebx # --+---------------+-------+ # | mm2 | | # --+---------------+-------+ # # dest edx+12 edx+4 # --+---------------+---------------+ # | mm3 | | # --+---------------+---------------+ # # mm6 = shift+32 # mm7 = ecx = 64-(shift+32) # In both cases there's one extra limb of src to fetch and combine # with mm2 to make a qword at 4(%edx), and in the aligned case # there's an extra limb of dst to be formed from that extra src limb # left shifted. movd (%ebx), %mm0 psllq %mm6, %mm2 movq %mm3, 12(%edx) psllq $32, %mm0 movq %mm0, %mm1 psrlq %mm7, %mm0 por %mm2, %mm0 psllq %mm6, %mm1 movq %mm0, 4(%edx) psrlq $32, %mm1 andl $32, %ecx popl %ebx jz L(finish_one_unaligned) movd %mm1, (%edx) L(finish_one_unaligned): emms ret L(finish_zero): # No extra src limbs, destination was aligned. # # source ebx # --+---------------+ # | mm2 | # --+---------------+ # # dest edx+8 edx # --+---------------+---------------+ # | mm3 | | # --+---------------+---------------+ # # mm6 = shift # mm7 = ecx = 64-shift # No extra src limbs, destination was unaligned. # # source ebx # --+---------------+ # | mm2 | # --+---------------+ # # dest edx+8 edx+4 # --+---------------+-------+ # | mm3 | | # --+---------------+-------+ # # mm6 = shift+32 # mm7 = ecx = 64-(shift+32) # The movd for the unaligned case writes the same data to 4(%edx) # that the movq does for the aligned case. movq %mm3, 8(%edx) andl $32, %ecx psllq %mm6, %mm2 jz L(finish_zero_unaligned) movq %mm2, (%edx) L(finish_zero_unaligned): psrlq $32, %mm2 popl %ebx movd %mm5, %eax # retval movd %mm2, 4(%edx) emms ret EPILOGUE()
and $6,$3,$3 sh $6,8($0) or $3,$1,$3 sltiu $1,$3,21212 slt $0,$5,$3 sra $1,$5,25 sllv $6,$5,$3 sltu $4,$3,$3 sll $3,$3,11 sll $5,$1,13 or $3,$4,$3 andi $3,$4,4015 ori $5,$3,21755 srlv $3,$5,$3 addiu $4,$6,27414 sltu $3,$3,$3 xor $3,$5,$3 lh $5,12($0) sllv $3,$1,$3 lbu $3,8($0) and $3,$3,$3 srlv $0,$0,$3 lw $1,0($0) lw $3,16($0) lh $3,0($0) srl $6,$5,28 srl $4,$4,7 xori $3,$3,14663 addiu $5,$1,29555 andi $4,$5,15434 or $5,$6,$3 xori $6,$3,24494 sll $1,$3,26 subu $5,$4,$3 srlv $6,$4,$3 lb $4,10($0) sltu $5,$4,$3 slt $3,$1,$3 subu $4,$4,$3 srlv $4,$3,$3 andi $5,$3,6395 or $1,$4,$3 lh $4,8($0) ori $3,$3,46465 sra $3,$3,12 srav $3,$5,$3 addiu $6,$6,5674 srav $5,$5,$3 or $4,$4,$3 addu $3,$3,$3 sllv $3,$3,$3 xori $6,$6,41035 slti $3,$3,-25780 lhu $5,8($0) addu $3,$3,$3 addiu $5,$0,-21325 sra $1,$3,28 lh $4,10($0) lhu $6,2($0) lh $3,10($0) lw $4,8($0) ori $3,$4,41833 srlv $3,$3,$3 and $0,$3,$3 sltu $5,$5,$3 lh $3,12($0) sw $3,8($0) lbu $6,5($0) sltiu $1,$1,16777 xori $5,$3,33726 sllv $5,$4,$3 sb $5,13($0) lb $4,1($0) sllv $3,$1,$3 addiu $1,$1,1886 xor $3,$3,$3 addiu $1,$4,-31942 sra $6,$6,9 xor $4,$4,$3 srav $3,$3,$3 sh $1,0($0) lb $4,9($0) subu $3,$5,$3 sltiu $2,$2,-455 sllv $1,$0,$3 andi $3,$6,3446 ori $3,$5,51133 lw $1,8($0) lhu $5,0($0) lbu $0,14($0) addiu $5,$4,11831 addiu $3,$4,8232 xori $5,$6,9182 sh $4,14($0) subu $1,$1,$3 sllv $5,$3,$3 sra $3,$3,28 lw $6,0($0) lb $1,5($0) nor $5,$4,$3 andi $6,$3,31886 xori $0,$5,17721 sll $3,$4,22 subu $1,$5,$3 lbu $3,10($0) sb $6,14($0) sh $0,6($0) xori $3,$3,12030 xori $4,$3,27954 lhu $6,16($0) andi $3,$0,41087 sra $5,$3,26 addu $3,$5,$3 sw $4,0($0) sltiu $3,$0,-6781 andi $3,$1,10375 sltu $4,$3,$3 or $1,$1,$3 srl $1,$3,5 sw $5,4($0) addiu $5,$5,-20191 addu $4,$4,$3 sra $5,$3,24 subu $4,$3,$3 or $5,$5,$3 xori $3,$1,842 addu $4,$3,$3 lbu $4,15($0) sb $3,1($0) xor $1,$3,$3 xor $6,$4,$3 addiu $5,$3,-29636 subu $5,$5,$3 lbu $1,12($0) sw $3,0($0) addiu $3,$4,12304 subu $5,$0,$3 lh $3,10($0) addiu $6,$4,-32094 sra $6,$5,18 lhu $0,0($0) slt $5,$4,$3 slti $3,$3,-19006 xori $4,$3,58176 sb $4,16($0) addu $3,$3,$3 addu $3,$4,$3 sllv $3,$3,$3 sltu $5,$5,$3 slt $3,$3,$3 srlv $3,$6,$3 sll $5,$4,9 or $3,$3,$3 sltiu $4,$3,-6523 or $3,$4,$3 slti $3,$3,-2064 sh $6,8($0) addu $3,$3,$3 sh $6,2($0) sb $3,10($0) lbu $3,6($0) ori $6,$5,36469 srl $5,$3,22 andi $1,$1,20358 sltu $1,$1,$3 lbu $3,7($0) or $3,$3,$3 lhu $3,16($0) srav $3,$3,$3 sllv $3,$3,$3 xori $3,$2,19635 sb $4,2($0) subu $4,$3,$3 addiu $1,$3,1664 slt $3,$5,$3 sra $3,$3,24 andi $5,$5,10656 addu $5,$1,$3 sra $4,$4,11 ori $3,$1,43129 srav $4,$3,$3 xori $4,$4,9867 ori $5,$6,61104 xor $6,$3,$3 and $4,$1,$3 lb $1,4($0) ori $6,$6,60495 lb $4,16($0) lbu $3,8($0) lh $3,14($0) ori $4,$5,53340 sltu $1,$6,$3 slt $3,$5,$3 addu $5,$1,$3 addu $4,$3,$3 and $5,$4,$3 addu $1,$1,$3 andi $3,$3,1218 sh $3,2($0) xori $4,$3,56074 slt $1,$4,$3 lbu $1,13($0) sw $3,12($0) lb $4,14($0) lb $4,14($0) sltiu $4,$4,28745 lw $3,0($0) slt $6,$1,$3 sltiu $3,$3,9135 lw $1,8($0) srav $4,$4,$3 lw $4,0($0) lb $1,12($0) sltu $3,$0,$3 sllv $0,$3,$3 xor $4,$1,$3 subu $1,$1,$3 lbu $4,3($0) andi $1,$1,64171 sltiu $0,$1,-13024 sb $5,7($0) addu $3,$5,$3 sw $3,0($0) sb $5,13($0) nor $4,$3,$3 sh $4,16($0) ori $4,$1,14401 sra $1,$4,12 addiu $4,$6,-23932 srl $5,$4,25 lbu $3,9($0) sltu $4,$3,$3 lh $5,10($0) slt $3,$3,$3 nor $4,$4,$3 slti $1,$4,-10358 xori $3,$5,11896 subu $3,$4,$3 srl $4,$4,14 sllv $4,$6,$3 xor $3,$2,$3 lbu $4,2($0) srl $3,$6,26 slt $5,$3,$3 lhu $6,8($0) nor $3,$3,$3 addiu $0,$1,5102 or $4,$5,$3 sltiu $3,$6,-14966 lh $4,6($0) sra $4,$4,26 sltu $4,$5,$3 sra $3,$6,10 ori $5,$5,19314 lh $3,2($0) srav $0,$1,$3 addiu $0,$3,18444 sll $4,$4,22 lbu $4,4($0) and $4,$4,$3 slti $6,$3,-18614 addu $4,$0,$3 sw $0,8($0) sw $5,0($0) sra $5,$3,29 and $4,$3,$3 nor $4,$2,$3 sh $3,6($0) subu $3,$3,$3 lbu $0,3($0) addiu $4,$0,16416 subu $5,$4,$3 or $3,$6,$3 and $6,$3,$3 addu $4,$1,$3 lbu $6,6($0) addu $4,$4,$3 srav $3,$4,$3 addiu $3,$1,10230 lh $5,12($0) addu $6,$1,$3 slti $1,$4,18183 sra $3,$4,12 sra $4,$5,23 lbu $1,14($0) andi $4,$3,11978 lb $1,4($0) lh $4,4($0) slti $3,$1,28429 lbu $0,7($0) xori $5,$3,59776 srav $3,$3,$3 lh $3,12($0) and $1,$2,$3 subu $1,$1,$3 lw $4,4($0) sll $4,$4,7 nor $5,$3,$3 srl $1,$1,23 addu $1,$4,$3 subu $3,$5,$3 lb $3,8($0) xori $4,$4,45731 subu $1,$3,$3 nor $6,$3,$3 sw $4,0($0) addiu $3,$3,29983 xor $3,$0,$3 subu $6,$4,$3 addu $1,$6,$3 sltiu $4,$3,30337 srlv $3,$4,$3 addiu $1,$4,21509 sltu $5,$5,$3 sh $4,12($0) slti $0,$0,6648 lbu $0,10($0) addu $6,$6,$3 sh $1,12($0) srav $0,$3,$3 xori $4,$4,41370 slti $1,$3,-13196 sll $3,$4,24 sltu $4,$1,$3 sltu $4,$5,$3 addiu $5,$5,5889 lbu $1,3($0) addu $1,$3,$3 sh $4,4($0) xori $4,$3,41224 sllv $4,$3,$3 subu $3,$4,$3 nor $5,$4,$3 srlv $1,$3,$3 sb $3,13($0) srlv $6,$5,$3 sltu $3,$3,$3 addiu $4,$1,-1531 lw $3,16($0) sllv $5,$5,$3 lh $1,12($0) srav $3,$4,$3 or $3,$6,$3 sw $0,16($0) ori $3,$4,5544 sh $4,2($0) sra $6,$4,9 addu $1,$1,$3 and $1,$5,$3 or $4,$4,$3 srl $5,$3,1 sw $5,8($0) lbu $5,0($0) nor $4,$3,$3 sltu $6,$4,$3 srlv $3,$4,$3 addiu $3,$1,26556 addu $0,$0,$3 sra $3,$1,5 lbu $4,4($0) lb $3,1($0) subu $0,$3,$3 sra $3,$1,12 lb $5,13($0) sh $3,10($0) srlv $3,$3,$3 sh $4,0($0) subu $6,$6,$3 sll $0,$3,27 lhu $1,10($0) ori $0,$6,9678 or $3,$4,$3 sra $5,$1,13 srlv $1,$1,$3 subu $4,$4,$3 ori $0,$1,18743 addu $1,$6,$3 lh $4,6($0) nor $0,$5,$3 ori $5,$3,10355 addu $4,$0,$3 sltu $4,$4,$3 slti $3,$1,-31757 sra $1,$3,25 andi $5,$5,27184 sltu $1,$3,$3 or $3,$3,$3 slt $5,$3,$3 lbu $6,1($0) xori $3,$3,55897 andi $3,$3,8302 subu $3,$1,$3 and $3,$4,$3 or $5,$3,$3 sb $3,12($0) xor $2,$2,$3 lhu $3,16($0) xor $5,$5,$3 lb $5,0($0) lbu $1,3($0) slt $1,$1,$3 sll $0,$1,16 subu $3,$0,$3 andi $0,$4,24857 or $3,$1,$3 addiu $3,$5,10845 srlv $4,$0,$3 srav $0,$1,$3 lbu $1,10($0) lbu $1,10($0) srav $3,$3,$3 xori $6,$3,34150 and $1,$4,$3 addiu $4,$6,-91 addiu $3,$4,31953 andi $3,$1,40953 sra $6,$1,11 lw $2,8($0) xori $0,$0,33576 addiu $4,$4,-16826 nor $5,$3,$3 lbu $6,9($0) or $1,$5,$3 subu $3,$5,$3 sb $5,1($0) sh $1,12($0) andi $4,$4,16246 lh $5,2($0) sllv $1,$3,$3 lbu $3,14($0) sh $3,16($0) lhu $1,4($0) srl $4,$1,30 lb $1,7($0) sll $1,$1,28 subu $6,$4,$3 lhu $3,10($0) sll $6,$3,11 slti $1,$0,-24010 sw $3,16($0) sltiu $5,$6,-27092 nor $5,$1,$3 sltiu $3,$3,19625 xor $0,$4,$3 lbu $1,3($0) xori $6,$0,8206 srav $5,$5,$3 lhu $3,14($0) xor $0,$5,$3 sltiu $4,$3,-21355 subu $3,$4,$3 srlv $0,$4,$3 or $1,$3,$3 sltu $5,$3,$3 srlv $5,$4,$3 sw $5,16($0) andi $3,$3,27624 lh $5,12($0) sll $6,$4,5 sltiu $4,$6,-19637 srl $4,$1,14 lw $6,4($0) subu $1,$5,$3 lb $3,13($0) sltu $3,$3,$3 or $1,$1,$3 sra $3,$5,1 sh $3,10($0) sll $5,$3,26 or $3,$5,$3 lh $3,14($0) sllv $4,$5,$3 and $3,$4,$3 sll $4,$6,23 and $3,$5,$3 lbu $4,1($0) subu $4,$4,$3 slti $1,$4,-9582 and $1,$1,$3 and $1,$3,$3 sltu $0,$0,$3 sra $3,$3,23 lw $3,8($0) sllv $0,$1,$3 andi $4,$4,39562 lb $1,11($0) sra $6,$4,21 sll $5,$4,24 srlv $3,$6,$3 sh $4,8($0) sh $2,14($0) and $4,$5,$3 slti $3,$4,14775 srlv $3,$1,$3 and $4,$3,$3 addu $5,$3,$3 srl $2,$2,13 sw $3,0($0) subu $6,$3,$3 or $3,$3,$3 xor $3,$6,$3 addiu $4,$4,-9161 sra $3,$3,26 slt $5,$3,$3 srav $3,$3,$3 srl $1,$3,18 and $4,$4,$3 sltu $3,$3,$3 ori $4,$5,24933 xori $0,$3,45779 addiu $3,$5,3031 sll $5,$5,24 sltiu $0,$6,17084 subu $5,$1,$3 subu $4,$3,$3 lbu $1,1($0) sh $4,16($0) sra $3,$4,5 srav $4,$4,$3 sllv $5,$1,$3 or $4,$0,$3 addu $3,$0,$3 addiu $1,$4,-23804 sllv $3,$5,$3 nor $4,$3,$3 srl $1,$3,17 subu $5,$4,$3 sw $1,0($0) srav $4,$4,$3 nor $5,$3,$3 nor $4,$3,$3 srav $4,$4,$3 xor $3,$3,$3 ori $4,$4,28751 xori $4,$4,45563 subu $5,$5,$3 addiu $5,$3,-7632 srl $3,$3,0 sh $3,6($0) sll $6,$3,23 sh $6,8($0) sll $4,$4,6 addu $4,$2,$3 addiu $1,$4,-5171 lw $3,0($0) andi $6,$5,36631 lb $0,16($0) lbu $4,13($0) or $3,$5,$3 lhu $3,0($0) sb $3,13($0) andi $4,$3,59580 nor $5,$6,$3 subu $4,$6,$3 sltiu $3,$0,23491 sltiu $6,$3,-23169 or $4,$4,$3 lhu $3,4($0) srav $3,$5,$3 sb $1,15($0) addiu $4,$3,-14407 sllv $5,$4,$3 sra $1,$3,25 subu $4,$0,$3 ori $3,$3,47596 srav $3,$4,$3 addiu $4,$1,-12679 sb $5,12($0) sh $5,10($0) sra $1,$3,31 sh $5,10($0) sll $1,$3,22 sh $1,10($0) xori $1,$1,41462 slt $3,$5,$3 or $5,$3,$3 lw $3,0($0) srl $4,$5,1 srl $3,$5,20 slti $4,$3,5624 slt $4,$5,$3 sw $4,16($0) sll $5,$4,17 subu $1,$6,$3 sh $1,8($0) subu $3,$3,$3 xori $6,$3,57726 sll $1,$3,14 andi $6,$1,23836 lh $5,14($0) and $4,$4,$3 lh $1,8($0) slti $5,$4,19818 sb $4,0($0) ori $1,$1,1994 subu $1,$1,$3 and $3,$3,$3 lbu $1,1($0) lhu $3,14($0) sltu $1,$6,$3 lb $3,12($0) xor $3,$3,$3 slti $4,$3,895 addu $5,$4,$3 lbu $0,14($0) sw $3,4($0) sltiu $4,$0,-13979 and $5,$3,$3 lhu $6,4($0) lw $3,8($0) addiu $4,$4,24441 sh $6,4($0) srav $4,$3,$3 and $4,$3,$3 or $3,$4,$3 lw $1,8($0) lbu $3,5($0) lb $5,4($0) subu $3,$4,$3 srl $4,$3,0 addiu $4,$4,-17614 addiu $4,$4,11574 sllv $0,$4,$3 sllv $3,$5,$3 lh $0,6($0) xori $1,$4,56182 sw $3,4($0) lb $5,8($0) lbu $3,14($0) sltu $4,$4,$3 nor $5,$4,$3 slt $3,$3,$3 addu $4,$5,$3 sll $1,$0,8 sh $3,12($0) lh $6,2($0) lh $3,0($0) lb $3,4($0) lw $4,16($0) lbu $4,7($0) lh $1,6($0) sb $4,15($0) subu $1,$4,$3 sra $4,$3,3 lw $3,16($0) addu $5,$4,$3 sllv $3,$1,$3 lhu $4,14($0) sra $3,$5,8 and $3,$1,$3 slti $5,$3,11322 lbu $3,9($0) lhu $5,8($0) srl $4,$5,24 lb $3,13($0) and $1,$3,$3 addu $5,$5,$3 nor $3,$3,$3 lb $3,7($0) sra $1,$3,3 srl $1,$1,20 lh $5,4($0) addu $3,$4,$3 slt $0,$1,$3 sb $6,4($0) lb $3,9($0) lb $2,13($0) xori $4,$4,12206 addiu $1,$3,18788 and $4,$4,$3 srav $4,$4,$3 or $3,$3,$3 srl $4,$1,28 xor $6,$3,$3 slti $4,$0,-8261 slt $6,$4,$3 addiu $3,$0,-26221 lh $5,10($0) addiu $3,$4,-14732 addiu $3,$6,27199 subu $3,$3,$3 sll $3,$3,10 addu $3,$1,$3 ori $0,$3,32531 sll $3,$1,27 slt $4,$4,$3 srav $3,$1,$3 addu $3,$3,$3 andi $3,$3,19218 lw $4,8($0) addu $4,$4,$3 and $4,$3,$3 subu $1,$1,$3 xor $1,$0,$3 subu $6,$5,$3 srl $1,$3,24 srav $1,$4,$3 lw $4,12($0) lhu $5,8($0) sllv $6,$4,$3 sb $4,6($0) and $5,$4,$3 sll $3,$0,29 addu $4,$2,$3 srl $1,$4,17 sb $3,15($0) xori $3,$3,44958 addiu $3,$1,-10810 xori $4,$1,29264 lhu $4,8($0) srav $5,$1,$3 lbu $4,7($0) andi $1,$3,27702 lbu $1,14($0) lw $4,4($0) sw $4,12($0) subu $1,$1,$3 addiu $1,$2,-2603 lh $3,2($0) lbu $3,11($0) or $6,$3,$3 lw $1,12($0) addu $5,$6,$3 sra $6,$1,9 slt $3,$3,$3 lw $4,12($0) nor $4,$2,$3 addu $4,$2,$3 srlv $4,$1,$3 lhu $6,14($0) subu $2,$2,$3 xori $3,$5,28800 lhu $3,14($0) xori $3,$0,977 and $4,$3,$3 subu $4,$5,$3 sltu $1,$5,$3 xor $3,$5,$3 lw $4,16($0) slt $3,$3,$3 sra $1,$1,17 addu $5,$0,$3 srl $3,$1,17 addu $6,$5,$3 slt $4,$5,$3 slt $6,$0,$3 srlv $3,$3,$3 lb $4,1($0) sb $3,13($0) subu $3,$1,$3 addu $3,$3,$3 lb $5,7($0) lbu $4,15($0) sra $3,$3,23 lb $1,5($0) sltu $5,$0,$3 xor $0,$2,$3 lw $1,12($0) addiu $1,$6,22659 or $3,$3,$3 sb $3,0($0) sh $0,6($0) sltu $1,$1,$3 nor $4,$1,$3 sh $5,14($0) lhu $1,2($0) addiu $3,$5,-17606 sltiu $4,$4,2398 sw $3,4($0) addiu $3,$5,-29528 addu $3,$3,$3 lh $1,12($0) srl $6,$0,9 srl $4,$5,21 srlv $3,$1,$3 slti $3,$3,-3192 slt $4,$3,$3 sll $3,$5,6 addu $4,$3,$3 addu $5,$5,$3 sra $5,$6,16 sll $3,$3,13 sh $6,14($0) slti $2,$2,10948 srav $1,$3,$3 sra $3,$4,13 addu $5,$0,$3 sw $1,12($0) xor $3,$4,$3 subu $3,$6,$3 sltu $3,$3,$3 addiu $0,$4,16970 lbu $3,4($0) sra $3,$0,20 addu $5,$3,$3 nor $5,$3,$3 and $3,$2,$3 lb $5,2($0) subu $3,$4,$3 subu $4,$4,$3 srl $3,$0,2 and $6,$6,$3 srl $1,$4,24 slt $4,$1,$3 nor $1,$1,$3 or $0,$2,$3 ori $4,$1,30920 xor $3,$3,$3 sw $5,16($0) slt $3,$5,$3 sh $6,2($0) srl $3,$3,23 sra $4,$3,7 sb $6,9($0) lw $1,8($0) andi $6,$4,20855 addu $0,$5,$3 lh $0,4($0) lh $4,8($0) srav $3,$0,$3 sh $1,14($0) ori $1,$3,8814 xor $3,$3,$3 srlv $6,$1,$3 sllv $3,$3,$3 lhu $3,4($0) addu $1,$1,$3 sh $5,0($0) xori $0,$5,58281 addu $6,$3,$3 sltu $4,$3,$3 addu $3,$0,$3 sb $5,8($0) lb $3,12($0) lb $3,6($0) sh $4,12($0) sltu $2,$2,$3 lw $4,16($0) sb $4,14($0) sh $2,0($0) ori $3,$4,59976 sh $3,16($0) andi $5,$0,17471 lbu $4,9($0) sll $4,$5,24 subu $3,$4,$3 srav $0,$1,$3 sh $6,8($0) sw $4,4($0) srlv $3,$4,$3 slt $3,$0,$3 sw $5,12($0) sb $0,9($0) sra $1,$3,26 sh $3,12($0) subu $3,$1,$3 slti $3,$3,28918 srav $4,$5,$3 sra $3,$3,15 andi $5,$6,25626 xor $3,$4,$3 subu $3,$4,$3 subu $4,$3,$3 andi $4,$5,6932 srl $1,$3,8 srlv $6,$6,$3 lh $1,6($0) xori $3,$5,59044 slti $4,$1,31783 subu $3,$3,$3 sltiu $3,$1,12413 sltiu $3,$1,2350 sltiu $3,$6,-25235 subu $5,$5,$3 sb $5,7($0) subu $6,$1,$3 slt $6,$3,$3 ori $6,$3,55645 addiu $0,$3,19531 andi $1,$5,59082 addu $3,$4,$3 sw $6,0($0) addiu $1,$0,-13433 sltu $3,$3,$3 sltu $6,$1,$3 sllv $0,$2,$3 lw $1,8($0) addiu $3,$1,-32723
; A098558: Expansion of e.g.f. (1+x)/(1-x). ; 1,2,4,12,48,240,1440,10080,80640,725760,7257600,79833600,958003200,12454041600,174356582400,2615348736000,41845579776000,711374856192000,12804747411456000 mov $1,$0 pow $3,$0 fac $1 mov $2,$3 mul $1,2 sub $1,$2
; ********************************************************************************* ; ********************************************************************************* ; ; File: graphics.asm ; Purpose: General screen I/O routines ; Date : 12th March 2019 ; Author: paul@robsons.org.uk ; ; ********************************************************************************* ; ********************************************************************************* ; ********************************************************************************* ; ; Set Graphics Mode to L ; ; ********************************************************************************* GFXMode: push bc push de push hl ld a,l ; save new mode. ld (SIScreenMode),a dec l ; L = 1 mode layer2 jr z,__GFXLayer2 dec l jr z,__GFXLowRes ; L = 2 mode lowres call GFXInitialise48k ; L = 0 or anything else, 48k mode. jr __GFXConfigure __GFXLayer2: call GFXInitialiseLayer2 jr __GFXConfigure __GFXLowRes: call GFXInitialiseLowRes __GFXConfigure: ld a,l ; save screen size ld (SIScreenWidth),a ld a,h ld (SIScreenHeight),a ex de,hl ; save driver ld (SIScreenDriver),hl ld l,d ; put sizes in HL DE ld h,0 ld d,0 call MULTMultiply16 ; multiply to get size and store. ld (SIScreenSize),hl pop hl pop de pop bc ret ; ********************************************************************************* ; ; Write character D (colour) E (character) to position HL. ; ; ********************************************************************************* GFXWriteCharacter: push af push bc push de push hl ld bc,__GFXWCExit push bc ld bc,(SIScreenDriver) push bc ret __GFXWCExit: pop hl pop de pop bc pop af ret ; ********************************************************************************* ; ; Write hex word DE at position HL ; ; ********************************************************************************* GFXWriteHexWord: ld a,5 GFXWriteHexWordA: push bc push de push hl ld c,a ld a,d push de call __GFXWHByte pop de ld a,e call __GFXWHByte pop hl pop de pop bc ret __GFXWHByte: push af rrc a rrc a rrc a rrc a call __GFXWHNibble pop af __GFXWHNibble: ld d,c and 15 cp 10 jr c,__GFXWHDigit add a,7 __GFXWHDigit: add a,48 ld e,a call GFXWriteCharacter inc hl ret
CGROUP group code code segment dword 'CODE' assume cs:CGROUP,ds:CGROUP public pj_bcontrast ;pj_bcontrast(UBYTE *s1, UBYTE *s2, unsigned count) pj_bcontrast PROC near push esi push edi push ecx mov esi,[esp+16] mov edi,[esp+20] mov ecx,[esp+24] repne cmpsb inc ecx mov eax,[esp+24] sub eax,ecx pop ecx pop edi pop esi ret pj_bcontrast ENDP code ends end
// Runs an infinite loop that listens to the keyboard input. // When a key is pressed (any key), the program blackens the screen, // i.e. writes "black" in every pixel; // the screen should remain fully black as long as the key is pressed. // When no key is pressed, the program clears the screen, i.e. writes // "white" in every pixel; // the screen should remain fully clear as long as no key is pressed. // 24576为键盘的地址 16384-24575 刚好8K 为屏幕的地址 @24575 D = A // R0存储屏幕最大地址 @0 M = D // R1存储屏幕当前地址 @SCREEN D = A @1 M = D (LOOP) @KBD D = M @FILL D;JGT @CLEAR 0;JMP (FILL) // 判断屏幕是否为满 @0 D = M @1 D = D - M @LOOP D;JLT @1 // 缓存当前地址 D = M // 将当前地址推入A A = M // 将地址对应的屏幕位置变黑 M = -1 // 当前地址+1 @1 M = D + 1 @LOOP 0;JMP (CLEAR) // 判断屏幕是否为空 @SCREEN D = A @1 D = D - M @LOOP D;JGT @1 // 缓存当前地址 D = M // 将当前地址推入A A = M // 将地址对应的屏幕位置变白 M = 0 // 当前地址-1 @1 M = D - 1 @LOOP 0;JMP
.nolist #include "includes\ti84pce.inc" #include "includes\defines.inc" #include "includes\macros.inc" .list .org Usermem-2 .db tExtTok,tAsm84CeCmp PROGRAM_HEADER: jp PROGRAM_START .db 1 ; Signifies a Cesium program .db 16,16 ; Width, Height of sprite .db 255,255,255,163,255,255,163,255,255,163,255,255,163,255,255,255 .db 255,107,107,162,107,107,162,107,107,162,107,107,162,107,107,255 .db 255,107,255,129,255,255,129,255,255,129,255,255,129,255,107,255 .db 255,107,255,097,181,255,097,181,255,097,181,255,097,181,107,255 .db 255,107,255,255,255,255,255,255,255,255,255,255,255,255,107,255 .db 255,107,255,182,182,182,182,182,182,182,182,255,255,255,107,255 .db 255,107,255,255,255,255,255,255,255,255,255,255,255,255,107,255 .db 255,107,255,182,182,182,182,182,182,182,182,182,182,255,107,255 .db 255,107,255,255,255,255,255,255,255,255,255,255,255,255,107,255 .db 255,107,255,182,182,182,182,182,182,182,255,255,255,255,107,255 .db 255,107,255,255,255,255,255,255,255,255,255,255,255,255,107,255 .db 255,107,255,182,182,182,182,182,182,182,182,182,255,255,107,255 .db 255,107,255,255,255,255,255,255,255,255,255,255,255,255,107,255 .db 255,107,255,182,182,182,182,182,255,255,255,255,255,255,107,255 .db 255,107,255,255,255,255,255,255,255,255,255,255,255,255,107,255 .db 255,107,107,107,107,107,107,107,107,107,107,107,107,107,107,255 .db "Text Editor ",VersionMajor+'0','.',VersionMinor+'0',0 PROGRAM_START: PGRM_BEGIN: call Initialize jp Redraw ; Draw the stuff and the files ;------------------------------------------------------------------ ; FullExit ; Fixes up everything and exits ;------------------------------------------------------------------ FullExit: call ClearScreens ld a,lcdBpp16 ld (mpLcdCtrl),a call _DrawStatusBar call _HomeUp set graphDraw,(iy+graphFlags) res onInterrupt,(iy+onFlags) ret #include "routines\initialization.asm" #include "routines\keyboard.asm" #include "routines\mainscrn.asm" #include "routines\editing.asm" #include "routines\appvar.asm" #include "routines\other.asm" #include "routines\text.asm" ; External includes #include "routines\LCD.asm" CODE_END: DATA_START: #include "data\ImageData.asm" #include "data\TextData.asm" DATA_END: PGRM_END: .echo "Code Base Size:\t",CODE_END-PGRM_BEGIN," bytes" .echo "Data Size:\t",DATA_END-DATA_START," bytes" .echo "Total Size:\t",PGRM_END-PGRM_BEGIN," bytes"
[CPU 486] [BITS 32] GLOBAL api_putchar GLOBAL api_end GLOBAL api_putstr0 GLOBAL api_openwin GLOBAL api_putstrwin GLOBAL api_boxfilwin GLOBAL api_initmalloc, api_malloc, api_free GLOBAL api_point GLOBAL api_refreshwin GLOBAL api_linewin GLOBAL api_closewin GLOBAL api_getkey GLOBAL api_alloctimer, api_inittimer, api_settimer, api_freetimer GLOBAL api_beep section .text api_putchar: ; void api_putchar(int c) MOV EDX, 1 MOV AL, [ESP + 4] ; c INT 0x40 RET api_end: ; void api_end(void) MOV EDX, 4 INT 0x40 api_putstr0: ; void api_putstr0(char *s) PUSH EBX MOV EDX, 2 MOV EBX, [ESP + 8] ; s INT 0x40 POP EBX RET api_openwin: ; int api_openwin(char *buf, int xsiz, int ysiz, int col_inv, char *title) PUSH EDI PUSH ESI PUSH EBX MOV EDX, 5 MOV EBX, [ESP + 16] ; buf MOV ESI, [ESP + 20] ; xsiz MOV EDI, [ESP + 24] ; ysiz MOV EAX, [ESP + 28] ; col_inv MOV ECX, [ESP + 32] ; title INT 0x40 POP EBX POP ESI POP EDI RET api_putstrwin: ; void api_putstrwin(int win, int x, int y, int col, int len, char *str) PUSH EDI PUSH ESI PUSH EBP PUSH EBX MOV EDX, 6 MOV EBX, [ESP + 20] ; win MOV ESI, [ESP + 24] ; x MOV EDI, [ESP + 28] ; y MOV EAX, [ESP + 32] ; col MOV ECX, [ESP + 36] ; len MOV EBP, [ESP + 40] ; str INT 0x40 POP EBX POP EBP POP ESI POP EDI RET api_boxfilwin: ; void api_boxfilwin(int win, int x0, int y0, int x1, int y1, int col) PUSH EDI PUSH ESI PUSH EBP PUSH EBX MOV EDX, 7 MOV EBX, [ESP + 20] ; win MOV EAX, [ESP + 24] ; x0 MOV ECX, [ESP + 28] ; y0 MOV ESI, [ESP + 32] ; x1 MOV EDI, [ESP + 36] ; y1 MOV EBP, [ESP + 40] ; str INT 0x40 POP EBX POP EBP POP ESI POP EDI RET api_initmalloc: ; void api_initmalloc(void); PUSH EBX MOV EDX, 8 MOV EBX, [CS:0x0020] ; malloc領域の番地 MOV EAX, EBX ADD EAX, 32 * 1024 ; 32KBを足す MOV ECX, [CS:0x0000] ; データセグメントの大きさ SUB ECX, EAX INT 0x40 POP EBX RET api_malloc: ; char *api_malloc(int size); PUSH EBX MOV EDX, 9 MOV EBX, [CS:0x0020] MOV ECX, [ESP + 8] ; size INT 0x40 POP EBX RET api_free: ; void api_free(char *addr, int size); PUSH EBX MOV EDX, 10 MOV EBX, [CS:0x0020] MOV EAX, [ESP + 8] ; addr MOV ECX, [ESP + 12] ; size INT 0x40 POP EBX RET api_point: ; void api_point(int win, int x, int y, int col); PUSH EDI PUSH ESI PUSH EBX MOV EDX, 11 MOV EBX, [ESP + 16] ; win MOV ESI, [ESP + 20] ; x MOV EDI, [ESP + 24] ; y MOV EAX, [ESP + 28] ; col INT 0x40 POP EBX POP ESI POP EDI RET api_refreshwin: ; void api_refreshwin(int win, int x0, int y0, int x1, int y1); PUSH EDI PUSH ESI PUSH EBX MOV EDX, 12 MOV EBX, [ESP + 16] ; win MOV EAX, [ESP + 20] ; x0 MOV ECX, [ESP + 24] ; y0 MOV ESI, [ESP + 28] ; x1 MOV EDI, [ESP + 32] ; y1 INT 0x40 POP EBX POP ESI POP EDI RET api_linewin: ; void api_linewin(sht, eax, ecx, esi, edi, ebp); PUSH EDI PUSH ESI PUSH EBP PUSH EBX MOV EDX, 13 MOV EBX, [ESP + 20] ; win MOV EAX, [ESP + 24] ; x0 MOV ECX, [ESP + 28] ; y0 MOV ESI, [ESP + 32] ; x1 MOV EDI, [ESP + 36] ; y1 MOV EBP, [ESP + 40] ; col INT 0x40 POP EBX POP EBP POP ESI POP EDI RET api_closewin: ; void api_linewin(sht, eax, ecx, esi, edi, ebp); PUSH EBX MOV EDX, 14 MOV EBX, [ESP + 8] ; winl INT 0x40 POP EBX RET api_getkey: ; int api_getkey(int mode); MOV EDX, 15 MOV EAX, [ESP + 4] ; mode INT 0x40 RET api_alloctimer: ; int api_alloctimer(void); MOV EDX, 16 INT 0x40 RET api_inittimer: ; void api_inittimer(int timer, int data); PUSH EBX MOV EDX, 17 MOV EBX, [ESP + 8] ; timer MOV EAX, [ESP + 12] ; data INT 0x40 POP EBX RET api_settimer: ; void api_settimer(int timer, int time); PUSH EBX MOV EDX, 18 MOV EBX, [ESP + 8] ; timer MOV EAX, [ESP + 12] ; time INT 0x40 POP EBX RET api_freetimer: ; void api_freetimer(int timer); PUSH EBX MOV EDX, 19 MOV EBX, [ESP + 8] ; timer INT 0x40 POP EBX RET api_beep: ; void api_beep(int tone); MOV EDX, 20 MOV EAX, [ESP + 4] ; tone INT 0x40 RET
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * @file text-label-example.cpp * @brief Usage of TextLabel control with style application. */ // EXTERNAL INCLUDES #include <dali-toolkit/dali-toolkit.h> #include <dali-toolkit/devel-api/controls/text-controls/text-label-devel.h> #include <dali-toolkit/devel-api/text/text-enumerations-devel.h> #include <dali/devel-api/actors/actor-devel.h> #include <dali/devel-api/object/handle-devel.h> #include <iostream> // INTERNAL INCLUDES #include "expanding-buttons.h" #include "shared/multi-language-strings.h" #include "shared/view.h" using namespace Dali; using namespace Dali::Toolkit; using namespace MultiLanguageStrings; namespace { const char* const BACKGROUND_IMAGE = DEMO_IMAGE_DIR "grab-handle.png"; const char* const STYLE_SELECTED_IMAGE = DEMO_IMAGE_DIR "FontStyleButton_OK_03.png"; const char* BUTTON_IMAGES[] = { DEMO_IMAGE_DIR "FontStyleButton_Colour.png", DEMO_IMAGE_DIR "FontStyleButton_Outline.png", DEMO_IMAGE_DIR "FontStyleButton_Shadow.png", DEMO_IMAGE_DIR "FontStyleButton_Background.png"}; const unsigned int KEY_ZERO = 10; const unsigned int KEY_ONE = 11; const unsigned int KEY_A = 38; const unsigned int KEY_F = 41; const unsigned int KEY_H = 43; const unsigned int KEY_U = 30; const unsigned int KEY_V = 55; const unsigned int KEY_M = 58; const unsigned int KEY_L = 46; const unsigned int KEY_S = 39; const unsigned int KEY_PLUS = 21; const unsigned int KEY_MINUS = 20; const char* H_ALIGNMENT_STRING_TABLE[] = { "BEGIN", "CENTER", "END"}; const unsigned int H_ALIGNMENT_STRING_COUNT = sizeof(H_ALIGNMENT_STRING_TABLE) / sizeof(H_ALIGNMENT_STRING_TABLE[0u]); const char* V_ALIGNMENT_STRING_TABLE[] = { "TOP", "CENTER", "BOTTOM"}; const unsigned int V_ALIGNMENT_STRING_COUNT = sizeof(V_ALIGNMENT_STRING_TABLE) / sizeof(V_ALIGNMENT_STRING_TABLE[0u]); enum StyleType { TEXT_COLOR = 0, OUTLINE, SHADOW, BACKGROUND, NUMBER_OF_STYLES }; const Vector4 AVAILABLE_COLORS[] = { Color::GREEN, Color::BLUE, Color::RED, Color::CYAN, Color::WHITE // Used as clear }; const unsigned int NUMBER_OF_COLORS = sizeof(AVAILABLE_COLORS) / sizeof(AVAILABLE_COLORS[0u]); int ConvertToEven(int value) { return (value % 2 == 0) ? value : (value + 1); } struct HSVColorConstraint { HSVColorConstraint(float hue, float saturation, float value) : hue(hue), saturation(saturation), value(value) { } void operator()(Vector3& current, const PropertyInputContainer& inputs) { current = hsv2rgb(Vector3(inputs[0]->GetFloat(), saturation, value)); } Vector3 hsv2rgb(Vector3 colorHSV) { float r = colorHSV.z * (1 + colorHSV.y * (cos(colorHSV.x) - 1)); float g = colorHSV.z * (1 + colorHSV.y * (cos(colorHSV.x - 2.09439) - 1)); float b = colorHSV.z * (1 + colorHSV.y * (cos(colorHSV.x + 2.09439) - 1)); return Vector3(r, g, b); } float hue; float saturation; float value; }; const float STYLE_BUTTON_POSTION_RELATIVE_TO_WINDOW = 0.9f; const float BUTTON_SIZE_RATIO_TO_WINDOW = 0.1f; const float OUTLINE_WIDTH = 2.0f; const Vector2 SHADOW_OFFSET = Vector2(2.0f, 2.0f); const int GAP_BETWEEN_BUTTONS = 3; } // anonymous namespace /** * @brief The main class of the demo. */ class TextLabelExample : public ConnectionTracker { public: TextLabelExample(Application& application) : mApplication(application), mLabel(), mSelectedColor(AVAILABLE_COLORS[0]), mStyleActivatedForColor(NUMBER_OF_STYLES), mContainer(), mGrabCorner(), mBorder(), mPanGestureDetector(), mLayoutSize(), mLanguageId(0u), mAlignment(0u), mHueAngleIndex(Property::INVALID_INDEX), mOverrideMixColorIndex(Property::INVALID_INDEX), mColorButtonsHidden(true), mCollapseColorsAndStyles(false) { // Connect to the Application's Init signal mApplication.InitSignal().Connect(this, &TextLabelExample::Create); // Set Style flags to inactive for(unsigned int i = TEXT_COLOR; i < NUMBER_OF_STYLES; i++) { mStyleActiveState[i] = false; mCurrentStyleColor[i] = AVAILABLE_COLORS[NUMBER_OF_COLORS - 1]; } } ~TextLabelExample() { // Nothing to do here. } // Clicking the expanding button shows the registered style buttons. void SetUpExpandingStyleButtons(Vector2 position) { mExpandingButtons = Demo::ExpandingButtons::New(); mExpandingButtons.SetProperty(Actor::Property::POSITION, Vector2(mButtonSize.width, mWindowSize.height * STYLE_BUTTON_POSTION_RELATIVE_TO_WINDOW)); mExpandingButtons.CollapsingSignal().Connect(this, &TextLabelExample::OnExpandingButtonCollapsing); mExpandingButtons.SetProperty(Actor::Property::SIZE, mButtonSize); // Creates the buttons to be expanded CreateStyleButtons(); // Register the created buttons with the ExpandingButtons. for(unsigned int index = 0; index < NUMBER_OF_STYLES; index++) { mExpandingButtons.RegisterButton(mStyleButtons[index]); } } /** * One-time setup in response to Application InitSignal. */ void Create(Application& application) { Window window = application.GetWindow(); window.KeyEventSignal().Connect(this, &TextLabelExample::OnKeyEvent); mWindowSize = window.GetSize(); mButtonSize = Size(mWindowSize.height * 0.1, mWindowSize.height * 0.1); // Button size 1/10 of window height mContainer = Control::New(); mContainer.SetProperty(Dali::Actor::Property::NAME, "Container"); mContainer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); mLayoutSize = Vector2(mWindowSize.width * 0.6f, mWindowSize.width * 0.6f); mContainer.SetProperty(Actor::Property::SIZE, mLayoutSize); window.Add(mContainer); // Resize the center layout when the corner is grabbed mGrabCorner = ImageView::New(BACKGROUND_IMAGE); mGrabCorner.SetProperty(Dali::Actor::Property::NAME, "GrabCorner"); mGrabCorner.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER); mGrabCorner.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_RIGHT); mGrabCorner.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS); mContainer.Add(mGrabCorner); mPanGestureDetector = PanGestureDetector::New(); mPanGestureDetector.Attach(mGrabCorner); mPanGestureDetector.DetectedSignal().Connect(this, &TextLabelExample::OnPan); mLabel = TextLabel::New("\xF0\x9F\x98\x89 A Quick Brown Fox Jumps Over The Lazy Dog"); mLabel.SetProperty(Dali::Actor::Property::NAME, "TextLabel"); mLabel.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); mLabel.SetProperty(Actor::Property::SIZE, mLayoutSize); mLabel.SetProperty(TextLabel::Property::MULTI_LINE, true); mLabel.SetProperty(TextLabel::Property::TEXT_COLOR, Color::GREEN); mLabel.SetBackgroundColor(Color::WHITE); mContainer.Add(mLabel); // Clicking ExpandingButton shows the Registered Style buttons, clicking again hides them. Vector2 expandingButtonPosition(mButtonSize.width, mWindowSize.height * STYLE_BUTTON_POSTION_RELATIVE_TO_WINDOW); SetUpExpandingStyleButtons(expandingButtonPosition); window.Add(mExpandingButtons); // Add a border for the container so you can see the container is being resized while grabbing the handle. mBorder = Control::New(); mBorder.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); mBorder.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH); mBorder.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT); Dali::Property::Map border; border.Insert(Toolkit::Visual::Property::TYPE, Visual::BORDER); border.Insert(BorderVisual::Property::COLOR, Color::WHITE); border.Insert(BorderVisual::Property::SIZE, 3.f); mBorder.SetProperty(Control::Property::BACKGROUND, border); mContainer.Add(mBorder); mBorder.SetProperty(Actor::Property::VISIBLE, false); mGrabCorner.RaiseToTop(); mHueAngleIndex = mLabel.RegisterProperty("hue", 0.0f); Renderer bgRenderer = mLabel.GetRendererAt(0); mOverrideMixColorIndex = bgRenderer.GetPropertyIndex(ColorVisual::Property::MIX_COLOR); Constraint constraint = Constraint::New<Vector3>(bgRenderer, mOverrideMixColorIndex, HSVColorConstraint(0.0f, 0.5f, 0.8f)); constraint.AddSource(Source(mLabel, mHueAngleIndex)); constraint.SetRemoveAction(Constraint::DISCARD); constraint.Apply(); Animation anim = Animation::New(50.0f); anim.AnimateTo(Property(mLabel, mHueAngleIndex), 6.28318f); anim.SetLooping(true); anim.Play(); mContainer.RaiseToTop(); mGrabCorner.RaiseToTop(); Property::Value labelText = mLabel.GetProperty(TextLabel::Property::TEXT); std::cout << "Displaying text: \"" << labelText.Get<std::string>() << "\"" << std::endl; } // If the styling buttons should colapse (hide) then the color buttons should also hide. bool OnExpandingButtonCollapsing(Demo::ExpandingButtons button) { mCollapseColorsAndStyles = true; HideColorButtons(); return true; } // Get the style type from the given button StyleType GetStyleTypeFromButton(Toolkit::Button button) { StyleType style = StyleType::TEXT_COLOR; if(button == mStyleButtons[StyleType::OUTLINE]) { style = StyleType::OUTLINE; } else if(button == mStyleButtons[StyleType::SHADOW]) { style = StyleType::SHADOW; } else if(button == mStyleButtons[StyleType::BACKGROUND]) { style = StyleType::BACKGROUND; } return style; } // Style selected, show color buttons bool OnStyleButtonClicked(Toolkit::Button button) { StyleType selectedStyle = GetStyleTypeFromButton(button); if(mStyleActivatedForColor == selectedStyle) { HideColorButtons(); } else { ResetColorButtons(mColorButtons, NUMBER_OF_COLORS); ShowColorButtons(selectedStyle); } return true; } // Set style to selected color bool OnColorSelected(Toolkit::Button button) { for(unsigned int index = 0; index < NUMBER_OF_COLORS; index++) { if(mColorButtons[index] == button) { mSelectedColor = AVAILABLE_COLORS[index]; } } switch(mStyleActivatedForColor) { case TEXT_COLOR: { Animation animation = Animation::New(1.f); animation.AnimateTo(Property(mLabel, TextLabel::Property::TEXT_COLOR), mSelectedColor, AlphaFunction::LINEAR); mCurrentStyleColor[TEXT_COLOR] = mSelectedColor; animation.Play(); break; } case OUTLINE: { Property::Map outlineMap; float outlineWidth = OUTLINE_WIDTH; if(mStyleActiveState[OUTLINE]) { outlineWidth = (Color::WHITE == mSelectedColor) ? 0.0f : OUTLINE_WIDTH; // toggles outline on/off } mStyleActiveState[OUTLINE] = (outlineWidth > 0.0f) ? true : false; outlineMap["color"] = mSelectedColor; outlineMap["width"] = outlineWidth; mCurrentStyleColor[OUTLINE] = mSelectedColor; mLabel.SetProperty(TextLabel::Property::OUTLINE, outlineMap); break; } case SHADOW: { Vector2 shadowOffset(SHADOW_OFFSET); // Will be set to zeros if color already set Property::Value value = mLabel.GetProperty(TextLabel::Property::SHADOW); Vector4 currentShadowColor; value.Get(currentShadowColor); if(mStyleActiveState[SHADOW]) { // toggle shadow off ( zero offset ) if color is already set shadowOffset = (Color::WHITE == mSelectedColor) ? Vector2::ZERO : Vector2(SHADOW_OFFSET); } mStyleActiveState[SHADOW] = (shadowOffset == Vector2::ZERO) ? false : true; mCurrentStyleColor[SHADOW] = mSelectedColor; Property::Map shadowMap; shadowMap.Insert("offset", shadowOffset); shadowMap.Insert("color", mSelectedColor); mLabel.SetProperty(TextLabel::Property::SHADOW, shadowMap); break; } case BACKGROUND: { Property::Map backgroundMap; auto backgroundEnabled(true); if(mStyleActiveState[BACKGROUND]) { backgroundEnabled = (Color::WHITE != mSelectedColor); // toggles background on/off } mStyleActiveState[BACKGROUND] = backgroundEnabled; backgroundMap["color"] = mSelectedColor; backgroundMap["enable"] = backgroundEnabled; mCurrentStyleColor[BACKGROUND] = mSelectedColor; mLabel.SetProperty(DevelTextLabel::Property::BACKGROUND, backgroundMap); break; } default: break; } return true; } // Set the inital color button that should be be selected. // If the style already has a color set then that should be used void SetInitialSelectedColorButton(StyleType styleButtonIndex) { Vector4 selectedColor = mCurrentStyleColor[styleButtonIndex]; for(unsigned int i = 0; i < NUMBER_OF_COLORS; i++) { if(AVAILABLE_COLORS[i] == selectedColor) { if(mColorButtons[i]) { mColorButtons[i].SetProperty(Toolkit::Button::Property::SELECTED, true); } break; } } } // Create a bar of color buttons that the user can select. void ShowColorButtons(StyleType styleButtonIndex) { mCollapseColorsAndStyles = false; // Request to show colors so reset flag mStyleActivatedForColor = styleButtonIndex; for(unsigned int index = 0; index < NUMBER_OF_COLORS; index++) { if(!mColorButtonsAnimation) { mColorButtonsAnimation = Animation::New(0.15f); mColorButtonsAnimation.FinishedSignal().Connect(this, &TextLabelExample::OnColorButtonAnimationFinished); } // Create a color button if(!mColorButtons[index]) { mColorButtons[index] = RadioButton::New(); mColorButtons[index].SetProperty(Actor::Property::SIZE, mButtonSize); mColorButtons[index].ClickedSignal().Connect(this, &TextLabelExample::OnColorSelected); mColorButtons[index].SetProperty(Button::Property::TOGGLABLE, true); Property::Map propertyMap; propertyMap.Insert(Visual::Property::TYPE, Visual::COLOR); propertyMap.Insert(ColorVisual::Property::MIX_COLOR, AVAILABLE_COLORS[index]); mColorButtons[index].SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, propertyMap); mColorButtons[index].SetProperty(Toolkit::Button::Property::UNSELECTED_VISUAL, propertyMap); mColorButtons[index].SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER); mColorButtons[index].SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER); propertyMap.Insert(Visual::Property::TYPE, Visual::COLOR); propertyMap.Insert(ColorVisual::Property::MIX_COLOR, AVAILABLE_COLORS[index]); mColorButtons[index].SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, propertyMap); mColorButtons[index].SetProperty(Toolkit::Button::Property::SELECTED_VISUAL, Property::Map().Add(Visual::Property::TYPE, Visual::BORDER).Add(BorderVisual::Property::COLOR, Color::WHITE).Add(BorderVisual::Property::SIZE, 4.0f).Add(BorderVisual::Property::ANTI_ALIASING, true)); // Use a white button with 50% transparency as a clear color button if(Color::WHITE == AVAILABLE_COLORS[index] && styleButtonIndex != StyleType::TEXT_COLOR) { mColorButtons[index].SetProperty(Actor::Property::OPACITY, 0.5f); mColorButtons[index].SetProperty(Toolkit::Button::Property::LABEL, Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT).Add(Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, HorizontalAlignment::CENTER).Add(Toolkit::TextVisual::Property::TEXT, "off")); } } SetInitialSelectedColorButton(mStyleActivatedForColor); mColorButtons[index].Unparent(); mStyleButtons[styleButtonIndex].Add(mColorButtons[index]); mColorButtons[index].Lower(); // Position button using nice animation mColorButtons[index].SetProperty(Actor::Property::POSITION_Y, -GAP_BETWEEN_BUTTONS); float desiredPosition = -(mButtonSize.height + GAP_BETWEEN_BUTTONS) * (index); AlphaFunction focusedAlphaFunction = AlphaFunction(Vector2(0.32f, 0.08f), Vector2(0.38f, 1.72f)); mColorButtonsAnimation.AnimateBy(Property(mColorButtons[index], Actor::Property::POSITION_Y), desiredPosition, focusedAlphaFunction); } mColorButtonsHidden = false; mColorButtonsAnimation.Play(); } // Remove the color buttons when not being shown. void ResetColorButtons(Button buttons[], unsigned int numberOfButtons) { for(unsigned int index = 0; index < numberOfButtons; index++) { UnparentAndReset(buttons[index]); } } void OnColorButtonAnimationFinished(Animation& animation) { animation.Clear(); if(mColorButtonsHidden) { ResetColorButtons(mColorButtons, NUMBER_OF_COLORS); animation.Reset(); // Handle reset if(mCollapseColorsAndStyles) { mExpandingButtons.Collapse(); } } } // Create the style buttons that will expand from the expanding button. void CreateStyleButtons() { for(unsigned int index = 0; index < NUMBER_OF_STYLES; index++) { if(!mStyleButtons[index]) { mStyleButtons[index] = PushButton::New(); mStyleButtons[index].SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, BUTTON_IMAGES[index]); mStyleButtons[index].SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, STYLE_SELECTED_IMAGE); mStyleButtons[index].SetProperty(Dali::Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); mStyleButtons[index].SetProperty(Actor::Property::SIZE, mButtonSize); mStyleButtons[index].ClickedSignal().Connect(this, &TextLabelExample::OnStyleButtonClicked); } } } // Animate away the color bar. void HideColorButtons() { if(!mColorButtonsHidden) { for(unsigned int index = 0; index < NUMBER_OF_COLORS; index++) { mColorButtonsAnimation.AnimateTo(Property(mColorButtons[index], Actor::Property::POSITION_Y), 0.0f); } mColorButtonsHidden = true; mColorButtonsAnimation.Play(); } mStyleActivatedForColor = NUMBER_OF_STYLES; } // Request the expanding button to collapse. void HideStyleAndColorButtons() { mCollapseColorsAndStyles = true; if(mColorButtonsHidden) { mExpandingButtons.Collapse(); } else { HideColorButtons(); } } // Resize the text-label with pan gesture void OnPan(Actor actor, const PanGesture& gesture) { // Reset mLayoutSize when the pan starts GestureState state = gesture.GetState(); if(state == GestureState::STARTED) { if(mLayoutSize.x < 2.0f) { mLayoutSize.x = 2.0f; } if(mLayoutSize.y < 2.0f) { mLayoutSize.y = 2.0f; } // Only show the border during the panning mBorder.SetProperty(Actor::Property::VISIBLE, true); HideStyleAndColorButtons(); } const Vector2& displacement = gesture.GetDisplacement(); mLayoutSize.x += displacement.x * 2.0f; mLayoutSize.y += displacement.y * 2.0f; if(mLayoutSize.x >= 2.0f || mLayoutSize.y >= 2.0f) { mLayoutSize.x = std::min(mLayoutSize.x, mWindowSize.width); mLayoutSize.y = std::min(mLayoutSize.y, mWindowSize.height * .9f); // Avoid pixel mis-alignment issue Vector2 clampedSize = Vector2(std::max(ConvertToEven(static_cast<int>(mLayoutSize.x)), 2), std::max(ConvertToEven(static_cast<int>(mLayoutSize.y)), 2)); mContainer.SetProperty(Actor::Property::SIZE, clampedSize); } if(state == GestureState::CANCELLED || state == GestureState::FINISHED) { // Resize the text label to match the container size when panning is finished mLabel.SetProperty(Actor::Property::SIZE, mLayoutSize); mBorder.SetProperty(Actor::Property::VISIBLE, false); } } /** * Main key event handler */ void OnKeyEvent(const KeyEvent& event) { if(event.GetState() == KeyEvent::DOWN) { if(IsKey(event, DALI_KEY_ESCAPE) || IsKey(event, DALI_KEY_BACK)) { mApplication.Quit(); } else if(event.IsCtrlModifier()) { switch(event.GetKeyCode()) { // Select rendering back-end case KEY_ZERO: // fall through case KEY_ONE: { mLabel.SetProperty(DevelTextLabel::Property::RENDERING_BACKEND, event.GetKeyCode() - 10); break; } case KEY_A: // Animate text colour { Animation animation = Animation::New(2.f); animation.AnimateTo(Property(mLabel, TextLabel::Property::TEXT_COLOR), Color::RED, AlphaFunction::SIN); animation.SetLoopCount(3); animation.Play(); break; } case KEY_F: // Fill vertically { if(ResizePolicy::DIMENSION_DEPENDENCY == mLabel.GetResizePolicy(Dimension::HEIGHT)) { mLabel.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT); } else { mLabel.SetResizePolicy(ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT); } break; } case KEY_H: // Horizontal alignment { if(++mAlignment >= H_ALIGNMENT_STRING_COUNT) { mAlignment = 0u; } mLabel.SetProperty(TextLabel::Property::HORIZONTAL_ALIGNMENT, H_ALIGNMENT_STRING_TABLE[mAlignment]); break; } case KEY_V: // Vertical alignment { if(++mAlignment >= V_ALIGNMENT_STRING_COUNT) { mAlignment = 0u; } mLabel.SetProperty(TextLabel::Property::VERTICAL_ALIGNMENT, V_ALIGNMENT_STRING_TABLE[mAlignment]); break; } case KEY_M: // Multi-line { bool multiLine = mLabel.GetProperty<bool>(TextLabel::Property::MULTI_LINE); mLabel.SetProperty(TextLabel::Property::MULTI_LINE, !multiLine); break; } case KEY_L: // Language { const Language& language = LANGUAGES[mLanguageId]; mLabel.SetProperty(TextLabel::Property::TEXT, language.text); if(++mLanguageId >= NUMBER_OF_LANGUAGES) { mLanguageId = 0u; } break; } case KEY_S: // Shadow color { Property::Value value = mLabel.GetProperty(TextLabel::Property::SHADOW); Vector4 shadowColor; value.Get(shadowColor); Property::Map shadowMap; if(Color::BLACK == shadowColor) { shadowMap.Insert("color", Color::RED); mLabel.SetProperty(TextLabel::Property::SHADOW, shadowMap); } else { shadowMap.Insert("color", Color::BLACK); mLabel.SetProperty(TextLabel::Property::SHADOW, shadowMap); } break; } case KEY_U: // Markup { mLabel.SetProperty(TextLabel::Property::ENABLE_MARKUP, true); mLabel.SetProperty(TextLabel::Property::TEXT, "<font family='DejaVuSerif' size='18'>H<color value='blue'>ello</color> <font weight='bold'>world</font> demo</font>"); break; } case KEY_PLUS: // Increase shadow offset { Property::Value value = mLabel.GetProperty(TextLabel::Property::SHADOW); Vector2 shadowOffset; value.Get(shadowOffset); shadowOffset += Vector2(1.0f, 1.0f); Property::Map shadowMap; shadowMap.Insert("offset", shadowOffset); mLabel.SetProperty(TextLabel::Property::SHADOW, shadowMap); break; } case KEY_MINUS: // Decrease shadow offset { Property::Value value = mLabel.GetProperty(TextLabel::Property::SHADOW); Vector2 shadowOffset; value.Get(shadowOffset); shadowOffset -= Vector2(1.0f, 1.0f); Property::Map shadowMap; shadowMap.Insert("offset", shadowOffset); mLabel.SetProperty(TextLabel::Property::SHADOW, shadowMap); break; } } } } } private: Application& mApplication; TextLabel mLabel; Demo::ExpandingButtons mExpandingButtons; PushButton mStyleButtons[NUMBER_OF_STYLES]; bool mStyleActiveState[NUMBER_OF_STYLES]; Vector4 mCurrentStyleColor[NUMBER_OF_STYLES]; Vector4 mSelectedColor; Button mColorButtons[NUMBER_OF_COLORS]; StyleType mStyleActivatedForColor; // The style that the color bar is connected to Control mContainer; Control mGrabCorner; Control mBorder; PanGestureDetector mPanGestureDetector; Vector2 mLayoutSize; Animation mColorButtonsAnimation; Size mWindowSize; Size mButtonSize; unsigned int mLanguageId; unsigned int mAlignment; Property::Index mHueAngleIndex; Property::Index mOverrideMixColorIndex; bool mColorButtonsHidden; bool mCollapseColorsAndStyles; }; int DALI_EXPORT_API main(int argc, char** argv) { Application application = Application::New(&argc, &argv, DEMO_THEME_PATH); TextLabelExample test(application); application.MainLoop(); return 0; }
; A154115: Numbers n such that n + 3 is prime. ; 0,2,4,8,10,14,16,20,26,28,34,38,40,44,50,56,58,64,68,70,76,80,86,94,98,100,104,106,110,124,128,134,136,146,148,154,160,164,170,176,178,188,190,194,196,208,220,224,226,230,236,238,248,254,260,266,268,274,278,280,290,304,308,310,314,328,334,344,346,350,356,364,370,376,380,386,394,398,406,416,418,428,430,436,440,446,454,458,460,464,476,484,488,496,500,506,518,520,538,544 seq $0,98090 ; Numbers k such that 2k-3 is prime. sub $0,3 mul $0,2
ori $1, $0, 12 ori $2, $0, 14 ori $3, $0, 14 ori $4, $0, 2 sw $2, 0($0) sw $4, 4($0) sw $2, 8($0) sw $4, 12($0) sw $4, 16($0) sw $2, 20($0) sw $1, 24($0) sw $4, 28($0) sw $4, 32($0) sw $2, 36($0) sw $4, 40($0) sw $4, 44($0) sw $3, 48($0) sw $1, 52($0) sw $2, 56($0) sw $3, 60($0) sw $1, 64($0) sw $1, 68($0) sw $3, 72($0) sw $3, 76($0) sw $3, 80($0) sw $4, 84($0) sw $1, 88($0) sw $4, 92($0) sw $3, 96($0) sw $4, 100($0) sw $4, 104($0) sw $1, 108($0) sw $1, 112($0) sw $2, 116($0) sw $2, 120($0) sw $3, 124($0) lb $1, 0($2) slti $4, $2, 5 multu $2, $1 blez $2, TAG1 TAG1: lb $4, 0($4) lui $4, 5 sll $0, $0, 0 lui $4, 11 TAG2: sll $0, $0, 0 or $2, $4, $4 sllv $1, $2, $4 lui $4, 2 TAG3: mtlo $4 mfhi $1 beq $4, $4, TAG4 sll $0, $0, 0 TAG4: multu $1, $1 sra $4, $1, 6 bgtz $4, TAG5 slti $1, $4, 14 TAG5: lui $2, 7 bgtz $1, TAG6 sll $0, $0, 0 bgez $2, TAG6 TAG6: div $2, $2 mtlo $2 bne $2, $2, TAG7 mult $2, $2 TAG7: mflo $2 sw $2, 0($2) mtlo $2 lh $3, 0($2) TAG8: mult $3, $3 subu $1, $3, $3 or $3, $1, $3 bne $3, $1, TAG9 TAG9: lui $4, 2 lhu $3, 0($3) or $1, $3, $4 mfhi $1 TAG10: beq $1, $1, TAG11 lh $4, 0($1) sh $4, 0($4) bltz $1, TAG11 TAG11: multu $4, $4 sh $4, 0($4) addiu $2, $4, 14 sb $4, 0($2) TAG12: sh $2, 0($2) bltz $2, TAG13 mthi $2 bgtz $2, TAG13 TAG13: srav $4, $2, $2 bgez $4, TAG14 sw $2, 0($4) lui $2, 14 TAG14: lbu $2, 0($2) addu $2, $2, $2 div $2, $2 srlv $1, $2, $2 TAG15: lh $4, 0($1) sh $1, 0($4) mfhi $4 sllv $1, $4, $1 TAG16: sltiu $4, $1, 1 mult $1, $1 bgtz $4, TAG17 xori $1, $4, 4 TAG17: subu $3, $1, $1 beq $1, $3, TAG18 lh $1, 0($3) multu $1, $3 TAG18: subu $4, $1, $1 lui $4, 4 lui $2, 5 bgtz $4, TAG19 TAG19: lui $4, 0 mthi $2 mtlo $4 lui $2, 5 TAG20: bgtz $2, TAG21 sll $0, $0, 0 mflo $4 mtlo $2 TAG21: lui $2, 4 addi $2, $4, 0 sllv $2, $2, $4 mthi $4 TAG22: bltz $2, TAG23 lb $3, 0($2) sb $2, 0($3) mtlo $3 TAG23: bltz $3, TAG24 lui $4, 8 mfhi $1 sh $4, 0($3) TAG24: mult $1, $1 mthi $1 sw $1, 0($1) multu $1, $1 TAG25: blez $1, TAG26 subu $1, $1, $1 sllv $3, $1, $1 addiu $3, $1, 2 TAG26: multu $3, $3 nor $3, $3, $3 mthi $3 sw $3, 15($3) TAG27: sll $0, $0, 0 lbu $3, 15($3) mthi $3 bne $3, $3, TAG28 TAG28: lui $2, 3 mtlo $2 mflo $2 sll $0, $0, 0 TAG29: mtlo $1 lb $2, 0($1) lui $2, 11 sll $0, $0, 0 TAG30: div $2, $2 xori $4, $2, 12 sll $0, $0, 0 div $4, $4 TAG31: mflo $4 bne $4, $4, TAG32 divu $4, $4 sltiu $4, $4, 4 TAG32: lui $3, 1 lbu $1, 0($4) multu $4, $1 lui $2, 14 TAG33: divu $2, $2 sll $0, $0, 0 or $2, $1, $1 bne $1, $1, TAG34 TAG34: divu $2, $2 lui $4, 8 subu $3, $4, $2 sll $0, $0, 0 TAG35: mult $1, $1 sra $1, $1, 11 mflo $1 mthi $1 TAG36: lui $2, 5 sll $0, $0, 0 bne $1, $2, TAG37 lui $2, 13 TAG37: sll $0, $0, 0 bne $2, $2, TAG38 mfhi $1 blez $1, TAG38 TAG38: sltu $1, $1, $1 lui $3, 3 lui $1, 15 mthi $1 TAG39: lui $4, 12 sll $0, $0, 0 div $1, $1 beq $4, $1, TAG40 TAG40: sll $0, $0, 0 xori $3, $4, 14 xori $1, $3, 5 lui $2, 14 TAG41: sll $2, $2, 7 sll $0, $0, 0 mthi $2 sltiu $2, $2, 11 TAG42: subu $2, $2, $2 andi $4, $2, 5 addi $3, $2, 11 mthi $4 TAG43: mtlo $3 sb $3, 0($3) sb $3, 0($3) bne $3, $3, TAG44 TAG44: lui $3, 13 sll $0, $0, 0 bne $3, $3, TAG45 multu $3, $3 TAG45: mflo $4 sll $0, $0, 0 mthi $4 srlv $4, $3, $3 TAG46: sll $0, $0, 0 or $4, $4, $4 mthi $4 beq $4, $4, TAG47 TAG47: multu $4, $4 slti $1, $4, 4 sra $4, $1, 14 bne $1, $4, TAG48 TAG48: multu $4, $4 blez $4, TAG49 slt $4, $4, $4 bne $4, $4, TAG49 TAG49: slt $4, $4, $4 sb $4, 0($4) lui $2, 5 bne $4, $4, TAG50 TAG50: sll $0, $0, 0 mfhi $4 mflo $1 mfhi $2 TAG51: sw $2, 0($2) mthi $2 sw $2, 0($2) bne $2, $2, TAG52 TAG52: andi $2, $2, 4 lh $3, 0($2) lui $2, 14 slti $2, $2, 5 TAG53: sh $2, 0($2) mult $2, $2 addiu $2, $2, 1 blez $2, TAG54 TAG54: mfhi $4 sb $2, 0($4) bltz $2, TAG55 srl $3, $2, 0 TAG55: mflo $1 mflo $2 bne $1, $1, TAG56 sb $1, 0($3) TAG56: beq $2, $2, TAG57 sh $2, 0($2) mfhi $2 divu $2, $2 TAG57: sh $2, 0($2) or $1, $2, $2 mthi $1 multu $1, $2 TAG58: lui $1, 15 sltu $3, $1, $1 lui $4, 15 sb $1, 0($3) TAG59: addu $4, $4, $4 or $4, $4, $4 blez $4, TAG60 sll $0, $0, 0 TAG60: slt $2, $4, $4 sw $2, 0($2) lui $1, 7 mult $2, $4 TAG61: lui $3, 12 mtlo $3 bgez $1, TAG62 addiu $3, $3, 12 TAG62: mtlo $3 beq $3, $3, TAG63 mtlo $3 lb $1, 0($3) TAG63: mfhi $1 mult $1, $1 sw $1, 0($1) mthi $1 TAG64: lui $4, 12 mult $1, $1 sll $0, $0, 0 ori $2, $4, 1 TAG65: sll $0, $0, 0 subu $3, $2, $2 sll $0, $0, 0 lhu $1, 0($3) TAG66: srl $1, $1, 13 mult $1, $1 sll $3, $1, 9 lui $1, 11 TAG67: beq $1, $1, TAG68 div $1, $1 slt $4, $1, $1 bne $4, $4, TAG68 TAG68: mfhi $1 mtlo $1 mtlo $4 sllv $2, $4, $1 TAG69: divu $2, $2 blez $2, TAG70 sll $0, $0, 0 mtlo $2 TAG70: blez $2, TAG71 divu $2, $2 addiu $4, $2, 9 mfhi $3 TAG71: blez $3, TAG72 lh $1, 0($3) beq $1, $1, TAG72 lui $4, 13 TAG72: sltu $1, $4, $4 xori $3, $1, 9 bltz $3, TAG73 sb $3, 0($1) TAG73: mtlo $3 multu $3, $3 divu $3, $3 lui $4, 10 TAG74: lui $3, 12 mflo $3 lbu $4, 0($3) bgtz $4, TAG75 TAG75: lbu $1, 0($4) lui $3, 8 mthi $1 lb $1, 0($1) TAG76: lui $3, 15 andi $1, $1, 11 or $3, $1, $3 subu $4, $1, $3 TAG77: beq $4, $4, TAG78 mfhi $4 slti $1, $4, 13 addu $3, $4, $4 TAG78: addiu $1, $3, 5 mflo $3 bgez $3, TAG79 mtlo $3 TAG79: mfhi $1 andi $2, $3, 15 mflo $4 lbu $4, 0($4) TAG80: mfhi $1 beq $1, $4, TAG81 lb $3, 0($1) lw $4, 0($4) TAG81: bgez $4, TAG82 sb $4, 0($4) sh $4, 0($4) sh $4, 0($4) TAG82: lui $1, 1 mthi $1 bltz $1, TAG83 addu $4, $4, $4 TAG83: addiu $2, $4, 10 addiu $1, $4, 5 multu $4, $1 srlv $4, $4, $1 TAG84: sllv $4, $4, $4 lb $3, 0($4) lb $3, 0($3) mult $3, $3 TAG85: subu $2, $3, $3 divu $3, $3 sb $2, 0($3) lh $4, 0($2) TAG86: srlv $3, $4, $4 beq $4, $4, TAG87 sb $3, 0($4) mtlo $4 TAG87: lbu $4, 0($3) lbu $3, 0($3) mthi $4 sb $3, 0($4) TAG88: mthi $3 andi $1, $3, 2 addiu $3, $3, 6 sb $3, 0($3) TAG89: sb $3, 0($3) lui $4, 12 sll $0, $0, 0 sb $3, 0($3) TAG90: mtlo $3 lui $3, 2 xori $3, $3, 3 blez $3, TAG91 TAG91: sll $0, $0, 0 lui $1, 6 sll $3, $3, 14 div $1, $3 TAG92: beq $3, $3, TAG93 subu $3, $3, $3 mtlo $3 sllv $1, $3, $3 TAG93: sll $0, $0, 0 addu $1, $1, $1 bne $1, $1, TAG94 mtlo $2 TAG94: sll $0, $0, 0 subu $1, $1, $1 bltz $1, TAG95 mflo $4 TAG95: sw $4, 0($4) mfhi $2 ori $2, $2, 1 lb $3, 0($4) TAG96: mtlo $3 sw $3, 0($3) bgtz $3, TAG97 lui $3, 9 TAG97: lui $2, 7 mthi $3 or $1, $2, $2 multu $1, $3 TAG98: beq $1, $1, TAG99 mthi $1 mtlo $1 mtlo $1 TAG99: sll $0, $0, 0 and $3, $1, $1 mthi $1 bgtz $1, TAG100 TAG100: sltiu $1, $3, 12 lui $3, 13 bne $3, $3, TAG101 sb $1, 0($1) TAG101: mthi $3 sll $0, $0, 0 sll $0, $0, 0 sw $3, 0($1) TAG102: mult $1, $1 lw $4, 0($1) nor $2, $4, $4 sb $4, 0($1) TAG103: addu $2, $2, $2 bltz $2, TAG104 lui $4, 3 nor $4, $4, $2 TAG104: mfhi $2 mult $4, $4 bltz $4, TAG105 multu $4, $4 TAG105: bgtz $2, TAG106 lui $4, 4 mtlo $2 mtlo $4 TAG106: div $4, $4 mfhi $1 divu $1, $4 mult $4, $4 TAG107: beq $1, $1, TAG108 sra $4, $1, 1 mflo $4 sub $2, $1, $4 TAG108: srav $4, $2, $2 mtlo $2 mflo $2 sh $4, 0($2) TAG109: bltz $2, TAG110 mthi $2 lhu $4, 0($2) multu $4, $2 TAG110: sra $1, $4, 1 mfhi $4 srl $2, $1, 11 beq $2, $4, TAG111 TAG111: mflo $4 sra $3, $4, 12 sb $4, 0($3) lh $3, 0($4) TAG112: bgez $3, TAG113 lui $3, 10 sh $3, 0($3) bltz $3, TAG113 TAG113: addu $3, $3, $3 bgez $3, TAG114 multu $3, $3 beq $3, $3, TAG114 TAG114: mfhi $1 mfhi $1 bgez $3, TAG115 lui $3, 15 TAG115: div $3, $3 bltz $3, TAG116 addu $2, $3, $3 bgez $2, TAG116 TAG116: mtlo $2 divu $2, $2 sll $0, $0, 0 slt $4, $2, $2 TAG117: sw $4, 0($4) mthi $4 beq $4, $4, TAG118 lhu $2, 0($4) TAG118: add $3, $2, $2 lhu $2, 0($2) slt $4, $3, $3 lb $1, 0($4) TAG119: mfhi $1 mflo $4 andi $2, $1, 11 bltz $4, TAG120 TAG120: mfhi $3 mtlo $2 sltu $1, $3, $3 sw $2, 0($3) TAG121: mtlo $1 bgtz $1, TAG122 sw $1, 0($1) ori $2, $1, 7 TAG122: lb $4, 0($2) srl $4, $2, 9 beq $4, $4, TAG123 mtlo $2 TAG123: lhu $2, 0($4) lb $1, 0($2) lui $3, 8 bltz $3, TAG124 TAG124: divu $3, $3 sll $0, $0, 0 mtlo $3 sll $0, $0, 0 TAG125: mult $4, $4 blez $4, TAG126 lui $2, 7 sb $2, 0($2) TAG126: sll $0, $0, 0 beq $2, $3, TAG127 addu $3, $2, $3 sll $0, $0, 0 TAG127: divu $3, $3 mfhi $3 lui $3, 7 mflo $3 TAG128: lui $3, 9 sra $1, $3, 0 mfhi $4 div $3, $1 TAG129: lui $3, 8 sll $0, $0, 0 lui $1, 0 bgez $3, TAG130 TAG130: addiu $2, $1, 12 bltz $2, TAG131 mfhi $4 lb $2, 0($4) TAG131: bgtz $2, TAG132 slt $2, $2, $2 lb $4, 0($2) srl $3, $4, 15 TAG132: lb $1, 0($3) lhu $1, 0($3) sh $1, 0($3) lui $4, 11 TAG133: bgez $4, TAG134 divu $4, $4 addu $2, $4, $4 mtlo $4 TAG134: bgez $2, TAG135 lui $3, 10 mfhi $4 mtlo $3 TAG135: blez $4, TAG136 mflo $1 lui $2, 3 mfhi $1 TAG136: sw $1, 0($1) beq $1, $1, TAG137 sh $1, 0($1) slt $2, $1, $1 TAG137: sll $0, $0, 0 sll $0, $0, 0 mtlo $1 lui $2, 15 TAG138: addu $2, $2, $2 mult $2, $2 addiu $3, $2, 6 sll $0, $0, 0 TAG139: bltz $3, TAG140 mult $3, $3 lui $3, 9 sll $0, $0, 0 TAG140: sb $1, 0($1) bgez $1, TAG141 mfhi $4 sw $1, 0($4) TAG141: mflo $4 mult $4, $4 slt $2, $4, $4 srav $1, $2, $4 TAG142: beq $1, $1, TAG143 addi $2, $1, 0 addu $3, $2, $1 lb $4, 0($3) TAG143: sll $0, $0, 0 beq $1, $4, TAG144 xori $2, $4, 2 mtlo $1 TAG144: sllv $3, $2, $2 sll $0, $0, 0 bgez $2, TAG145 sll $0, $0, 0 TAG145: srav $1, $2, $2 xor $4, $2, $1 mfhi $1 mtlo $1 TAG146: mult $1, $1 div $1, $1 sll $0, $0, 0 beq $1, $1, TAG147 TAG147: mfhi $1 subu $1, $1, $1 lui $3, 0 mfhi $2 TAG148: mthi $2 mflo $3 bne $2, $2, TAG149 multu $2, $2 TAG149: mthi $3 mthi $3 lb $4, 0($3) mtlo $3 TAG150: slt $1, $4, $4 lui $1, 6 bgez $1, TAG151 lui $2, 2 TAG151: sra $3, $2, 2 mflo $1 and $4, $2, $2 mfhi $4 TAG152: blez $4, TAG153 lui $2, 5 mflo $4 multu $2, $4 TAG153: bne $4, $4, TAG154 sltiu $3, $4, 0 subu $3, $4, $4 multu $3, $4 TAG154: lbu $2, 0($3) multu $2, $3 sw $3, 0($3) mthi $3 TAG155: sw $2, 0($2) bgez $2, TAG156 mfhi $1 ori $4, $1, 13 TAG156: sb $4, 0($4) lb $3, 0($4) sb $4, 0($4) lui $3, 12 TAG157: sltiu $4, $3, 14 sb $3, 0($4) sw $3, 0($4) mtlo $4 TAG158: bgez $4, TAG159 lbu $2, 0($4) sra $2, $2, 9 beq $2, $2, TAG159 TAG159: nor $3, $2, $2 lui $1, 13 lui $4, 2 bgtz $1, TAG160 TAG160: mthi $4 sll $0, $0, 0 bgtz $4, TAG161 sll $0, $0, 0 TAG161: nor $3, $4, $4 beq $3, $4, TAG162 mthi $4 mfhi $4 TAG162: sll $0, $0, 0 sll $0, $0, 0 mflo $2 beq $3, $4, TAG163 TAG163: lh $1, 0($2) blez $1, TAG164 sb $1, 0($2) mthi $1 TAG164: sw $1, 0($1) lbu $3, 0($1) mflo $2 addi $2, $3, 13 TAG165: mflo $3 sw $2, 0($3) bltz $3, TAG166 sb $3, 0($2) TAG166: mfhi $1 mthi $3 srl $3, $3, 11 mthi $3 TAG167: mtlo $3 lui $1, 0 mthi $1 beq $1, $3, TAG168 TAG168: xori $4, $1, 0 bne $1, $1, TAG169 mthi $4 lui $4, 3 TAG169: beq $4, $4, TAG170 addiu $2, $4, 5 mult $4, $4 mthi $4 TAG170: lui $2, 11 divu $2, $2 mtlo $2 sll $0, $0, 0 TAG171: mtlo $2 sll $0, $0, 0 bgtz $2, TAG172 sll $0, $0, 0 TAG172: mthi $2 lui $1, 4 sll $0, $0, 0 andi $2, $1, 12 TAG173: mfhi $1 bgtz $1, TAG174 lui $4, 5 blez $2, TAG174 TAG174: sll $0, $0, 0 sll $0, $0, 0 beq $4, $4, TAG175 andi $3, $4, 5 TAG175: lh $4, 0($3) srlv $4, $4, $4 lbu $1, 0($3) multu $4, $1 TAG176: sra $4, $1, 14 sb $4, 0($1) mthi $1 mult $4, $4 TAG177: multu $4, $4 sh $4, 0($4) bgez $4, TAG178 mtlo $4 TAG178: sub $4, $4, $4 multu $4, $4 sltiu $4, $4, 4 mthi $4 TAG179: lbu $4, 0($4) bgtz $4, TAG180 sw $4, 0($4) lhu $2, 0($4) TAG180: sw $2, 0($2) bltz $2, TAG181 mult $2, $2 sw $2, 0($2) TAG181: lui $4, 12 lw $2, 0($2) sb $2, 0($2) lbu $1, 0($2) TAG182: sh $1, 0($1) mfhi $3 mthi $3 mflo $1 TAG183: lui $3, 11 lui $3, 11 bgez $3, TAG184 mthi $3 TAG184: blez $3, TAG185 sll $0, $0, 0 mtlo $3 addu $3, $3, $3 TAG185: sll $0, $0, 0 mtlo $3 beq $3, $3, TAG186 mfhi $2 TAG186: sltiu $1, $2, 5 bgez $2, TAG187 div $2, $2 mthi $1 TAG187: mflo $2 bltz $1, TAG188 divu $1, $2 sw $2, 0($1) TAG188: mtlo $2 mfhi $2 sh $2, 0($2) lui $2, 1 TAG189: mfhi $1 nor $4, $2, $2 sw $1, 0($1) bne $2, $2, TAG190 TAG190: sll $0, $0, 0 bne $4, $4, TAG191 multu $4, $4 sll $0, $0, 0 TAG191: bne $4, $4, TAG192 multu $4, $4 bltz $4, TAG192 mflo $3 TAG192: sll $0, $0, 0 mthi $4 sll $0, $0, 0 mthi $4 TAG193: multu $4, $4 srlv $2, $4, $4 lb $4, 0($2) sw $4, 0($4) TAG194: mult $4, $4 blez $4, TAG195 srl $3, $4, 1 beq $4, $4, TAG195 TAG195: mult $3, $3 lui $2, 3 lb $4, 0($3) bltz $2, TAG196 TAG196: lb $4, 0($4) lw $1, 0($4) lui $1, 0 mtlo $4 TAG197: srl $2, $1, 11 lui $1, 10 mult $1, $2 sll $0, $0, 0 TAG198: mflo $3 multu $2, $3 mult $2, $3 mtlo $2 TAG199: lui $4, 7 sra $1, $3, 4 mfhi $4 sllv $1, $3, $4 TAG200: mthi $1 lbu $4, 0($1) lb $2, 0($1) sw $4, 0($2) TAG201: bgez $2, TAG202 sb $2, 0($2) subu $3, $2, $2 bne $2, $3, TAG202 TAG202: lui $3, 6 blez $3, TAG203 lui $4, 3 sll $0, $0, 0 TAG203: beq $2, $2, TAG204 andi $1, $2, 10 lui $4, 8 bne $1, $1, TAG204 TAG204: mflo $4 bltz $4, TAG205 mtlo $4 srav $3, $4, $4 TAG205: mtlo $3 mfhi $2 mfhi $2 lh $4, 0($2) TAG206: mult $4, $4 sh $4, 0($4) slt $2, $4, $4 lw $1, 0($2) TAG207: beq $1, $1, TAG208 nor $1, $1, $1 lh $4, 0($1) lbu $4, 0($4) TAG208: sw $4, 0($4) blez $4, TAG209 mtlo $4 mfhi $3 TAG209: lui $2, 1 beq $2, $2, TAG210 lhu $1, 0($3) lui $2, 14 TAG210: mflo $1 xor $1, $1, $2 lui $1, 13 sll $0, $0, 0 TAG211: mfhi $4 lui $3, 10 lui $1, 5 lb $1, 0($4) TAG212: blez $1, TAG213 sb $1, 0($1) lui $3, 15 mtlo $1 TAG213: subu $4, $3, $3 mfhi $4 mflo $1 xor $1, $1, $1 TAG214: lh $3, 0($1) lui $1, 14 mflo $2 bne $3, $1, TAG215 TAG215: subu $2, $2, $2 mthi $2 sltiu $3, $2, 0 lui $2, 14 TAG216: sll $0, $0, 0 mfhi $3 mthi $2 mult $4, $4 TAG217: lhu $1, 0($3) mfhi $4 bne $3, $1, TAG218 mfhi $3 TAG218: sw $3, 0($3) lw $1, 0($3) or $1, $1, $3 mtlo $1 TAG219: mflo $1 multu $1, $1 xor $3, $1, $1 slti $3, $1, 3 TAG220: beq $3, $3, TAG221 xori $4, $3, 2 mflo $2 andi $2, $3, 13 TAG221: sll $0, $0, 0 mthi $2 mflo $3 mflo $3 TAG222: lh $2, 0($3) addu $3, $3, $3 bgtz $3, TAG223 lui $2, 6 TAG223: addiu $4, $2, 14 div $2, $2 divu $2, $2 sll $0, $0, 0 TAG224: sll $0, $0, 0 sltu $2, $4, $4 mult $4, $2 beq $4, $2, TAG225 TAG225: mtlo $2 sh $2, 0($2) mflo $3 nor $2, $3, $2 TAG226: sll $4, $2, 14 xori $2, $4, 6 bne $2, $4, TAG227 srav $2, $4, $2 TAG227: mthi $2 multu $2, $2 sll $2, $2, 10 divu $2, $2 TAG228: multu $2, $2 slt $4, $2, $2 bne $2, $2, TAG229 sll $2, $2, 14 TAG229: mtlo $2 multu $2, $2 sw $2, 0($2) mtlo $2 TAG230: lhu $3, 0($2) lb $1, 0($3) bne $1, $2, TAG231 mult $2, $2 TAG231: sh $1, 0($1) mthi $1 sb $1, 0($1) mult $1, $1 TAG232: mthi $1 lh $4, 0($1) xor $1, $4, $1 and $4, $1, $4 TAG233: lh $3, 0($4) and $3, $4, $4 bgez $3, TAG234 lui $2, 5 TAG234: sll $0, $0, 0 blez $2, TAG235 sw $3, 0($3) lui $2, 9 TAG235: sll $0, $0, 0 andi $4, $2, 12 mult $4, $4 bgez $2, TAG236 TAG236: lui $2, 1 sh $4, 0($4) mthi $2 mult $4, $4 TAG237: addiu $1, $2, 9 sll $0, $0, 0 sll $0, $0, 0 multu $2, $1 TAG238: sb $4, 0($4) mflo $3 mflo $4 sll $0, $0, 0 TAG239: sll $0, $0, 0 sll $0, $0, 0 or $2, $4, $4 lui $4, 10 TAG240: lui $1, 1 sll $0, $0, 0 lui $3, 14 subu $2, $3, $1 TAG241: bltz $2, TAG242 sltu $3, $2, $2 mflo $4 lui $4, 12 TAG242: srl $1, $4, 13 mtlo $1 lui $1, 2 lui $2, 7 TAG243: lui $1, 7 lui $1, 1 sll $0, $0, 0 sll $0, $0, 0 TAG244: sltiu $4, $3, 15 srlv $1, $3, $3 srlv $2, $1, $1 srlv $1, $1, $1 TAG245: beq $1, $1, TAG246 sltiu $3, $1, 1 lui $1, 7 lb $1, 0($3) TAG246: slt $4, $1, $1 sh $1, 0($4) lw $3, 0($4) blez $4, TAG247 TAG247: multu $3, $3 beq $3, $3, TAG248 sll $4, $3, 15 xori $1, $3, 11 TAG248: bne $1, $1, TAG249 mflo $3 bgez $3, TAG249 mthi $1 TAG249: lhu $3, 0($3) lui $2, 9 slti $4, $2, 8 srl $4, $4, 13 TAG250: lhu $2, 0($4) addiu $1, $2, 11 multu $2, $4 bgtz $1, TAG251 TAG251: lb $4, 0($1) xor $4, $1, $4 bgtz $4, TAG252 sb $1, 0($4) TAG252: mflo $4 mthi $4 sll $2, $4, 15 xor $1, $4, $4 TAG253: lui $2, 0 ori $2, $2, 12 mtlo $2 xor $4, $1, $1 TAG254: blez $4, TAG255 sh $4, 0($4) mfhi $4 mfhi $1 TAG255: bgez $1, TAG256 lh $4, 0($1) srav $4, $1, $1 sw $4, 0($4) TAG256: bltz $4, TAG257 mtlo $4 sh $4, 0($4) slt $4, $4, $4 TAG257: sll $3, $4, 1 mult $4, $4 multu $3, $4 blez $3, TAG258 TAG258: addiu $4, $3, 15 lb $3, 0($3) sw $4, 0($3) mthi $3 TAG259: mflo $2 lhu $2, 0($3) sll $2, $2, 4 lhu $4, 0($3) TAG260: ori $2, $4, 12 sb $2, 0($2) addiu $3, $2, 9 divu $3, $3 TAG261: lui $4, 8 slti $3, $4, 12 mfhi $3 bgtz $3, TAG262 TAG262: sll $1, $3, 8 xori $3, $1, 7 sh $3, 0($1) sb $1, 0($1) TAG263: lbu $1, 0($3) sb $1, 0($3) bne $3, $1, TAG264 mtlo $1 TAG264: mthi $1 lui $1, 2 lui $2, 1 mfhi $4 TAG265: sw $4, 0($4) mtlo $4 mflo $2 mult $4, $2 TAG266: and $2, $2, $2 beq $2, $2, TAG267 addiu $1, $2, 14 lw $4, 0($2) TAG267: beq $4, $4, TAG268 mthi $4 multu $4, $4 bgez $4, TAG268 TAG268: mflo $2 mtlo $2 sw $2, 0($2) bltz $4, TAG269 TAG269: sb $2, 0($2) and $4, $2, $2 mult $2, $2 bgtz $2, TAG270 TAG270: mult $4, $4 mflo $3 bltz $4, TAG271 multu $4, $3 TAG271: mult $3, $3 lui $2, 0 multu $3, $2 lui $3, 9 TAG272: mtlo $3 sll $0, $0, 0 mflo $1 sll $0, $0, 0 TAG273: lui $3, 7 lui $2, 13 div $2, $2 bgtz $2, TAG274 TAG274: sll $0, $0, 0 mfhi $4 sll $0, $0, 0 subu $3, $2, $3 TAG275: sll $0, $0, 0 addu $2, $3, $3 srav $3, $2, $3 mthi $2 TAG276: div $3, $3 div $3, $3 mfhi $3 mflo $4 TAG277: beq $4, $4, TAG278 sb $4, 0($4) mtlo $4 lw $4, 0($4) TAG278: srl $4, $4, 4 lui $4, 14 addiu $1, $4, 8 sll $0, $0, 0 TAG279: sll $0, $0, 0 mthi $3 sll $0, $0, 0 lui $2, 6 TAG280: mtlo $2 sll $0, $0, 0 beq $3, $2, TAG281 sb $2, 0($3) TAG281: blez $3, TAG282 mflo $1 lui $3, 13 sb $1, 0($3) TAG282: bgtz $3, TAG283 lw $2, 0($3) beq $3, $3, TAG283 sltiu $3, $3, 14 TAG283: mult $3, $3 mthi $3 bne $3, $3, TAG284 mfhi $4 TAG284: blez $4, TAG285 sll $4, $4, 1 beq $4, $4, TAG285 lh $2, 0($4) TAG285: lhu $2, 0($2) mtlo $2 bne $2, $2, TAG286 lui $1, 1 TAG286: bgez $1, TAG287 mtlo $1 srav $2, $1, $1 mfhi $3 TAG287: lbu $1, 0($3) beq $3, $3, TAG288 mfhi $1 lb $1, 0($1) TAG288: sb $1, 0($1) and $4, $1, $1 mult $4, $1 mult $4, $1 TAG289: mfhi $2 mthi $4 mfhi $3 lbu $3, 0($3) TAG290: lbu $1, 0($3) slti $1, $1, 8 lbu $1, 0($3) bltz $1, TAG291 TAG291: divu $1, $1 mfhi $4 sb $1, 0($4) lui $2, 12 TAG292: sll $0, $0, 0 lui $2, 6 mflo $4 mthi $2 TAG293: xor $4, $4, $4 mthi $4 subu $1, $4, $4 addu $4, $4, $1 TAG294: mult $4, $4 lb $3, 0($4) lui $2, 0 sb $2, 0($2) TAG295: beq $2, $2, TAG296 mthi $2 mfhi $2 lui $1, 10 TAG296: sltu $1, $1, $1 lui $3, 12 lui $2, 8 blez $3, TAG297 TAG297: multu $2, $2 sll $0, $0, 0 mtlo $2 divu $2, $2 TAG298: slti $4, $2, 4 mthi $4 sllv $2, $2, $4 andi $1, $2, 9 TAG299: lb $2, 0($1) sllv $2, $1, $2 lui $2, 1 bne $2, $2, TAG300 TAG300: slti $3, $2, 2 bgez $2, TAG301 mtlo $2 sra $2, $3, 0 TAG301: mthi $2 sll $0, $0, 0 sll $0, $0, 0 multu $2, $3 TAG302: multu $3, $3 multu $3, $3 mfhi $2 sw $3, 0($3) TAG303: lb $4, 0($2) mult $4, $2 bgez $2, TAG304 mult $2, $4 TAG304: mthi $4 lui $1, 12 beq $1, $4, TAG305 sll $0, $0, 0 TAG305: xori $3, $1, 10 sll $0, $0, 0 multu $1, $1 mfhi $1 TAG306: mtlo $1 lw $2, -144($1) lui $4, 10 sll $0, $0, 0 TAG307: mthi $2 sll $4, $2, 5 multu $2, $2 lhu $2, 0($4) TAG308: bne $2, $2, TAG309 nor $1, $2, $2 bgez $2, TAG309 lui $4, 1 TAG309: lui $1, 13 mthi $4 mthi $1 sll $0, $0, 0 TAG310: sll $0, $0, 0 beq $3, $3, TAG311 mtlo $3 mult $3, $3 TAG311: mthi $3 bne $3, $3, TAG312 addiu $3, $3, 10 multu $3, $3 TAG312: lui $4, 15 mthi $3 mfhi $1 sll $0, $0, 0 TAG313: lui $2, 6 sll $0, $0, 0 mtlo $2 mult $2, $2 TAG314: beq $2, $2, TAG315 mthi $2 sll $3, $2, 0 xori $4, $3, 9 TAG315: div $4, $4 beq $4, $4, TAG316 mtlo $4 sll $2, $4, 9 TAG316: srl $2, $2, 7 bgez $2, TAG317 lhu $3, -3072($2) mflo $1 TAG317: mthi $1 sll $0, $0, 0 lui $2, 3 xori $4, $3, 8 TAG318: div $4, $4 sb $4, 0($4) mfhi $4 beq $4, $4, TAG319 TAG319: nor $4, $4, $4 beq $4, $4, TAG320 mflo $2 lw $4, 0($4) TAG320: bgez $4, TAG321 lui $4, 7 blez $4, TAG321 sh $4, 0($4) TAG321: mthi $4 mthi $4 multu $4, $4 sra $3, $4, 4 TAG322: mult $3, $3 beq $3, $3, TAG323 and $3, $3, $3 ori $3, $3, 2 TAG323: mfhi $2 lui $1, 3 sll $0, $0, 0 mfhi $1 TAG324: or $1, $1, $1 blez $1, TAG325 andi $1, $1, 14 divu $1, $1 TAG325: lui $3, 5 beq $3, $3, TAG326 sll $0, $0, 0 mfhi $4 TAG326: sll $0, $0, 0 subu $2, $4, $4 bne $2, $2, TAG327 sll $0, $0, 0 TAG327: sll $0, $0, 0 multu $4, $4 mfhi $2 beq $4, $2, TAG328 TAG328: sltu $2, $2, $2 blez $2, TAG329 mtlo $2 sw $2, 0($2) TAG329: blez $2, TAG330 mthi $2 sh $2, 0($2) mtlo $2 TAG330: mflo $1 mthi $2 mthi $2 lhu $3, 0($1) TAG331: sh $3, 0($3) lw $2, 0($3) bltz $3, TAG332 lui $3, 0 TAG332: sh $3, 0($3) mtlo $3 lui $1, 3 divu $3, $1 TAG333: sll $0, $0, 0 divu $1, $1 sll $0, $0, 0 mthi $1 TAG334: bgez $3, TAG335 mtlo $3 bne $3, $3, TAG335 and $4, $3, $3 TAG335: sltiu $1, $4, 10 bgez $1, TAG336 andi $4, $4, 15 bne $1, $4, TAG336 TAG336: lui $4, 3 mthi $4 sllv $2, $4, $4 mult $4, $2 TAG337: blez $2, TAG338 lui $4, 6 mult $2, $4 sll $0, $0, 0 TAG338: mfhi $3 blez $3, TAG339 mfhi $4 mthi $2 TAG339: mfhi $4 sll $0, $0, 0 mflo $1 mflo $3 TAG340: sb $3, 0($3) mfhi $3 sll $0, $0, 0 mtlo $3 TAG341: sll $0, $0, 0 bgtz $4, TAG342 mfhi $1 mfhi $4 TAG342: xor $3, $4, $4 div $3, $4 slti $1, $4, 9 lui $4, 3 TAG343: mthi $4 xori $4, $4, 10 mflo $1 or $1, $4, $1 TAG344: sll $0, $0, 0 srav $1, $1, $1 bne $1, $1, TAG345 lhu $1, -192($1) TAG345: mthi $1 mflo $1 mult $1, $1 sw $1, 0($1) TAG346: nor $4, $1, $1 blez $1, TAG347 srlv $4, $4, $4 mflo $3 TAG347: sh $3, 0($3) sw $3, 0($3) bne $3, $3, TAG348 mult $3, $3 TAG348: and $1, $3, $3 lui $2, 10 lui $3, 12 sra $3, $1, 12 TAG349: addi $1, $3, 5 andi $4, $3, 0 multu $3, $4 lbu $4, 0($1) TAG350: addi $1, $4, 8 lui $1, 0 sw $1, 0($4) lui $2, 5 TAG351: beq $2, $2, TAG352 mfhi $3 bltz $2, TAG352 lbu $2, 0($3) TAG352: sll $0, $0, 0 xor $2, $2, $2 mtlo $2 sh $2, 0($2) TAG353: mfhi $1 multu $1, $1 sh $2, 0($1) sh $1, 0($2) TAG354: and $2, $1, $1 lui $4, 11 sltu $1, $1, $2 beq $1, $4, TAG355 TAG355: lui $4, 1 lui $4, 5 srav $1, $4, $1 sll $0, $0, 0 TAG356: mfhi $2 mtlo $2 mthi $2 mthi $2 TAG357: lhu $2, 0($2) mtlo $2 mtlo $2 lh $3, 0($2) TAG358: sltu $3, $3, $3 sub $2, $3, $3 mflo $2 mthi $2 TAG359: mult $2, $2 lui $4, 12 sll $0, $0, 0 sll $0, $0, 0 TAG360: bne $3, $3, TAG361 sb $3, 0($3) multu $3, $3 mfhi $2 TAG361: subu $3, $2, $2 lb $4, 0($3) mtlo $4 bgtz $2, TAG362 TAG362: add $2, $4, $4 blez $4, TAG363 mtlo $4 lui $4, 11 TAG363: lui $1, 5 lui $1, 1 mthi $1 lui $3, 9 TAG364: bne $3, $3, TAG365 mult $3, $3 mthi $3 lui $1, 6 TAG365: sll $0, $0, 0 bne $1, $1, TAG366 subu $1, $3, $1 multu $3, $1 TAG366: and $4, $1, $1 srl $4, $4, 7 mflo $3 sb $4, 0($3) TAG367: blez $3, TAG368 and $4, $3, $3 lhu $2, 0($3) sw $2, 0($4) TAG368: andi $2, $2, 3 blez $2, TAG369 sb $2, 0($2) srav $4, $2, $2 TAG369: mflo $1 bltz $4, TAG370 multu $4, $4 sltiu $1, $1, 0 TAG370: mflo $3 sw $3, 0($3) lui $1, 4 bne $1, $1, TAG371 TAG371: mtlo $1 subu $3, $1, $1 bne $1, $1, TAG372 sw $3, 0($3) TAG372: multu $3, $3 mfhi $3 lw $1, 0($3) bgez $3, TAG373 TAG373: mtlo $1 lh $2, 0($1) mult $2, $2 beq $2, $2, TAG374 TAG374: lui $2, 13 mthi $2 bgtz $2, TAG375 srlv $4, $2, $2 TAG375: mthi $4 sll $0, $0, 0 xori $1, $4, 3 lui $3, 3 TAG376: bgez $3, TAG377 xori $2, $3, 9 multu $3, $3 sltu $4, $2, $3 TAG377: mult $4, $4 beq $4, $4, TAG378 sll $0, $0, 0 mfhi $4 TAG378: mult $4, $4 sll $0, $0, 0 sll $0, $0, 0 addu $3, $4, $4 TAG379: lui $4, 11 divu $4, $4 bgtz $3, TAG380 sll $0, $0, 0 TAG380: bgtz $4, TAG381 mult $4, $4 mtlo $4 slti $4, $4, 3 TAG381: mult $4, $4 lui $1, 2 sll $0, $0, 0 beq $1, $2, TAG382 TAG382: srl $2, $2, 9 subu $4, $2, $2 bgez $4, TAG383 sb $4, 0($4) TAG383: mtlo $4 sub $3, $4, $4 mthi $4 mult $4, $4 TAG384: mtlo $3 xor $3, $3, $3 mflo $3 mfhi $3 TAG385: lui $2, 10 sw $3, 0($3) addu $3, $2, $3 srlv $4, $2, $3 TAG386: mfhi $4 mflo $1 sllv $4, $1, $4 beq $4, $4, TAG387 TAG387: mfhi $4 multu $4, $4 beq $4, $4, TAG388 lbu $2, 0($4) TAG388: mult $2, $2 sll $4, $2, 1 mthi $2 lui $1, 14 TAG389: mult $1, $1 sll $0, $0, 0 sll $0, $0, 0 sll $0, $0, 0 TAG390: multu $2, $2 mthi $2 slti $3, $2, 13 sb $2, 0($3) TAG391: blez $3, TAG392 divu $3, $3 bne $3, $3, TAG392 mfhi $3 TAG392: bgtz $3, TAG393 add $3, $3, $3 blez $3, TAG393 lui $3, 15 TAG393: sll $0, $0, 0 bltz $3, TAG394 sra $4, $1, 4 bgez $4, TAG394 TAG394: subu $4, $4, $4 sll $2, $4, 8 sw $4, 0($4) lb $4, 0($2) TAG395: mtlo $4 lhu $4, 0($4) bgtz $4, TAG396 sb $4, 0($4) TAG396: lui $3, 15 sllv $2, $3, $3 beq $2, $2, TAG397 sh $3, 0($4) TAG397: sll $0, $0, 0 sll $0, $0, 0 multu $2, $4 multu $4, $4 TAG398: srl $3, $4, 1 beq $4, $3, TAG399 sll $1, $4, 1 lui $3, 6 TAG399: mthi $3 mfhi $3 bne $3, $3, TAG400 mfhi $4 TAG400: lui $1, 3 bltz $4, TAG401 sltiu $4, $4, 8 sll $0, $0, 0 TAG401: sll $0, $0, 0 sll $0, $0, 0 multu $1, $1 sll $0, $0, 0 TAG402: subu $4, $3, $3 sra $4, $4, 1 bltz $4, TAG403 sltiu $1, $3, 11 TAG403: xori $2, $1, 4 bltz $2, TAG404 slt $1, $2, $2 lui $2, 2 TAG404: sll $4, $2, 6 lui $3, 15 lui $4, 3 bne $2, $3, TAG405 TAG405: mult $4, $4 bne $4, $4, TAG406 sll $0, $0, 0 sll $0, $0, 0 TAG406: mflo $2 sll $0, $0, 0 mult $2, $2 slti $1, $2, 12 TAG407: subu $1, $1, $1 mtlo $1 lui $4, 7 beq $1, $1, TAG408 TAG408: sll $0, $0, 0 bgez $2, TAG409 div $2, $4 mthi $2 TAG409: slt $3, $2, $2 bne $3, $3, TAG410 mthi $2 mflo $1 TAG410: mthi $1 mult $1, $1 bne $1, $1, TAG411 subu $2, $1, $1 TAG411: mthi $2 mfhi $2 lui $2, 3 mtlo $2 TAG412: and $3, $2, $2 nor $4, $3, $2 sll $0, $0, 0 mtlo $4 TAG413: lui $1, 13 bne $2, $1, TAG414 srav $1, $1, $2 addi $3, $1, 11 TAG414: divu $3, $3 mfhi $2 bltz $2, TAG415 sll $0, $0, 0 TAG415: mtlo $3 mflo $3 mthi $3 lui $4, 5 TAG416: divu $4, $4 blez $4, TAG417 sll $0, $0, 0 sll $0, $0, 0 TAG417: sll $0, $0, 0 multu $1, $4 mthi $4 mfhi $4 TAG418: mtlo $4 sll $0, $0, 0 mult $4, $2 addu $2, $2, $2 TAG419: addiu $4, $2, 8 mflo $2 lui $3, 12 sb $2, 0($2) TAG420: bne $3, $3, TAG421 sra $3, $3, 14 mfhi $1 lui $1, 11 TAG421: lui $2, 2 mfhi $4 ori $2, $1, 13 sll $0, $0, 0 TAG422: sb $3, 0($3) blez $3, TAG423 multu $3, $3 lui $3, 0 TAG423: beq $3, $3, TAG424 multu $3, $3 sll $3, $3, 13 lh $3, 0($3) TAG424: mtlo $3 mthi $3 bne $3, $3, TAG425 mthi $3 TAG425: slt $3, $3, $3 lhu $1, 0($3) sra $1, $3, 3 lui $1, 13 TAG426: beq $1, $1, TAG427 sll $0, $0, 0 beq $1, $2, TAG427 sllv $1, $2, $1 TAG427: lui $3, 0 mflo $1 beq $3, $3, TAG428 ori $2, $1, 8 TAG428: mthi $2 slt $2, $2, $2 mflo $3 lh $1, 0($3) TAG429: lui $2, 15 sll $2, $2, 9 sll $0, $0, 0 mflo $3 TAG430: sra $3, $3, 3 ori $1, $3, 0 sltiu $4, $1, 7 lui $4, 5 TAG431: or $2, $4, $4 mult $2, $4 bne $4, $2, TAG432 sllv $1, $2, $4 TAG432: divu $1, $1 mthi $1 addiu $1, $1, 2 sllv $3, $1, $1 TAG433: sll $0, $0, 0 bltz $3, TAG434 lui $4, 12 divu $4, $4 TAG434: sll $0, $0, 0 sll $0, $0, 0 mthi $4 sltu $4, $4, $4 TAG435: mthi $4 mult $4, $4 mflo $2 bne $4, $2, TAG436 TAG436: mtlo $2 lb $2, 0($2) sh $2, 0($2) mflo $2 TAG437: bgtz $2, TAG438 and $1, $2, $2 lui $3, 9 sb $1, 0($2) TAG438: sll $0, $0, 0 subu $2, $3, $1 mtlo $3 multu $2, $1 TAG439: bgtz $2, TAG440 and $4, $2, $2 bne $2, $2, TAG440 sll $4, $4, 12 TAG440: mfhi $4 mthi $4 mtlo $4 bltz $4, TAG441 TAG441: xori $4, $4, 8 slt $2, $4, $4 lw $4, 0($4) bne $4, $4, TAG442 TAG442: sll $0, $0, 0 slti $2, $4, 3 addiu $3, $2, 14 sltiu $1, $2, 9 TAG443: mflo $1 bne $1, $1, TAG444 subu $4, $1, $1 or $3, $1, $4 TAG444: mult $3, $3 mflo $2 srav $3, $2, $3 mfhi $4 TAG445: mthi $4 add $1, $4, $4 lui $1, 3 lui $2, 12 TAG446: xori $3, $2, 11 sll $0, $0, 0 mthi $3 and $2, $2, $3 TAG447: lui $1, 2 sll $0, $0, 0 div $2, $2 div $2, $2 TAG448: mflo $4 sllv $4, $4, $4 andi $1, $4, 15 lui $4, 6 TAG449: multu $4, $4 blez $4, TAG450 sll $0, $0, 0 beq $4, $4, TAG450 TAG450: mflo $4 sll $2, $1, 13 lui $1, 11 bgtz $4, TAG451 TAG451: mfhi $3 addiu $1, $1, 8 divu $3, $1 sll $0, $0, 0 TAG452: mthi $3 divu $3, $3 lui $1, 11 lh $4, 0($3) TAG453: bgtz $4, TAG454 addu $3, $4, $4 bne $4, $3, TAG454 slt $3, $3, $4 TAG454: mfhi $3 and $4, $3, $3 mthi $3 mthi $3 TAG455: sw $4, 0($4) sb $4, 0($4) sllv $3, $4, $4 mtlo $4 TAG456: sw $3, 0($3) sb $3, 0($3) sltu $1, $3, $3 bgtz $3, TAG457 TAG457: mfhi $1 lbu $4, 0($1) multu $4, $1 mtlo $4 TAG458: bne $4, $4, TAG459 srlv $4, $4, $4 bne $4, $4, TAG459 mult $4, $4 TAG459: multu $4, $4 lui $2, 12 lui $3, 8 mflo $1 TAG460: mflo $1 lui $4, 2 sll $0, $0, 0 div $4, $4 TAG461: mult $3, $3 srl $2, $3, 5 lui $3, 11 sll $0, $0, 0 TAG462: lui $1, 5 mtlo $3 lui $4, 10 sll $0, $0, 0 TAG463: lui $4, 13 or $1, $4, $4 mtlo $1 mthi $4 TAG464: lui $3, 2 srav $2, $1, $1 bltz $1, TAG465 subu $4, $2, $2 TAG465: xori $2, $4, 0 sw $2, 0($2) addiu $4, $4, 14 sh $4, 0($4) TAG466: mfhi $3 bgez $4, TAG467 lui $4, 9 mthi $3 TAG467: mtlo $4 beq $4, $4, TAG468 lui $1, 8 mult $1, $4 TAG468: addu $3, $1, $1 srl $4, $3, 5 sll $0, $0, 0 sll $0, $0, 0 TAG469: mflo $3 sll $0, $0, 0 multu $3, $3 bgez $3, TAG470 TAG470: mthi $3 mflo $3 mflo $3 sb $3, 0($3) TAG471: sw $3, 0($3) lui $3, 6 bgtz $3, TAG472 ori $3, $3, 7 TAG472: bltz $3, TAG473 sll $0, $0, 0 mthi $3 slti $1, $3, 5 TAG473: sb $1, 0($1) lui $2, 10 multu $2, $1 mflo $2 TAG474: sh $2, 0($2) mthi $2 mtlo $2 add $2, $2, $2 TAG475: xori $1, $2, 7 mflo $4 sb $1, 0($4) mult $2, $2 TAG476: sb $4, 0($4) mtlo $4 mflo $2 bgtz $4, TAG477 TAG477: multu $2, $2 beq $2, $2, TAG478 sh $2, 0($2) beq $2, $2, TAG478 TAG478: addu $3, $2, $2 xori $1, $2, 9 lui $4, 0 sh $2, 0($3) TAG479: bltz $4, TAG480 lw $4, 0($4) addu $3, $4, $4 addu $2, $4, $3 TAG480: bne $2, $2, TAG481 lui $1, 7 lhu $4, 0($2) lui $1, 8 TAG481: mthi $1 sltu $4, $1, $1 addu $4, $4, $1 blez $1, TAG482 TAG482: lui $3, 15 sll $0, $0, 0 bltz $3, TAG483 mtlo $3 TAG483: mult $3, $3 addu $1, $3, $3 bne $1, $1, TAG484 mfhi $2 TAG484: and $3, $2, $2 lui $1, 1 blez $2, TAG485 addu $2, $1, $3 TAG485: lui $4, 15 beq $2, $2, TAG486 sll $0, $0, 0 sra $3, $2, 1 TAG486: beq $3, $3, TAG487 multu $3, $3 multu $3, $3 nor $3, $3, $3 TAG487: blez $3, TAG488 lbu $2, -225($3) sw $3, -225($3) lb $3, 0($2) TAG488: lui $3, 9 xori $4, $3, 15 bgtz $4, TAG489 mfhi $1 TAG489: sh $1, 0($1) sllv $1, $1, $1 beq $1, $1, TAG490 sh $1, 0($1) TAG490: mthi $1 lui $1, 4 addiu $1, $1, 0 mfhi $1 TAG491: bgtz $1, TAG492 sw $1, 0($1) sw $1, 0($1) multu $1, $1 TAG492: sw $1, 0($1) mult $1, $1 lui $4, 13 sltiu $4, $1, 5 TAG493: lui $4, 3 and $1, $4, $4 mtlo $1 div $1, $1 TAG494: xori $2, $1, 12 sra $2, $2, 14 lui $3, 6 mtlo $2 TAG495: bgez $3, TAG496 mthi $3 mfhi $1 sb $1, 0($1) TAG496: mtlo $1 beq $1, $1, TAG497 mfhi $4 bgez $4, TAG497 TAG497: sll $3, $4, 2 mtlo $4 sll $0, $0, 0 bgez $4, TAG498 TAG498: addu $1, $3, $3 xori $2, $1, 12 bgez $3, TAG499 sll $0, $0, 0 TAG499: beq $2, $2, TAG500 addiu $1, $2, 13 beq $1, $1, TAG500 slti $4, $2, 9 TAG500: blez $4, TAG501 sll $0, $0, 0 beq $2, $4, TAG501 mflo $1 TAG501: lui $2, 1 sll $0, $0, 0 ori $3, $2, 1 lui $2, 14 TAG502: subu $3, $2, $2 bne $3, $3, TAG503 mthi $2 slti $2, $3, 15 TAG503: lui $2, 15 mult $2, $2 lui $2, 6 sll $0, $0, 0 TAG504: bltz $2, TAG505 sll $0, $0, 0 bgez $2, TAG505 mfhi $4 TAG505: sll $0, $0, 0 beq $2, $2, TAG506 lui $3, 9 addiu $1, $4, 0 TAG506: slti $1, $1, 14 lbu $1, 0($1) mult $1, $1 slti $1, $1, 14 TAG507: sltu $2, $1, $1 bne $2, $2, TAG508 sb $1, 0($1) mthi $2 TAG508: srl $1, $2, 12 lui $4, 2 sra $2, $2, 4 mfhi $3 TAG509: blez $3, TAG510 lhu $1, 0($3) mtlo $1 xor $3, $3, $1 TAG510: bgez $3, TAG511 multu $3, $3 multu $3, $3 nor $4, $3, $3 TAG511: sltiu $1, $4, 14 div $1, $4 sb $1, 0($1) lbu $3, 0($1) TAG512: mtlo $3 bgtz $3, TAG513 lbu $1, 0($3) slt $2, $3, $3 TAG513: bltz $2, TAG514 sll $4, $2, 1 mtlo $2 or $3, $2, $2 TAG514: multu $3, $3 addi $2, $3, 6 lui $2, 12 sll $0, $0, 0 TAG515: sll $0, $0, 0 beq $2, $2, TAG516 multu $2, $2 bgez $2, TAG516 TAG516: lui $1, 12 lui $1, 14 mtlo $1 bne $2, $1, TAG517 TAG517: mflo $4 mflo $3 bne $1, $1, TAG518 sll $0, $0, 0 TAG518: mflo $4 sll $0, $0, 0 sll $0, $0, 0 mthi $2 TAG519: srlv $1, $1, $1 sll $0, $0, 0 sll $0, $0, 0 lui $2, 8 TAG520: mtlo $2 sll $4, $2, 1 addu $4, $2, $2 mfhi $2 TAG521: srav $1, $2, $2 sll $0, $0, 0 andi $4, $2, 0 bne $4, $1, TAG522 TAG522: mthi $4 mult $4, $4 blez $4, TAG523 sb $4, 0($4) TAG523: sh $4, 0($4) sw $4, 0($4) lh $4, 0($4) mult $4, $4 TAG524: lui $2, 8 andi $1, $4, 1 mflo $2 ori $3, $2, 5 TAG525: beq $3, $3, TAG526 andi $3, $3, 5 sw $3, 0($3) beq $3, $3, TAG526 TAG526: lb $1, 0($3) mult $3, $3 ori $3, $3, 3 xori $4, $3, 15 TAG527: bgez $4, TAG528 lui $3, 4 mfhi $2 mthi $3 TAG528: mtlo $2 sb $2, 0($2) lbu $3, 0($2) multu $2, $3 TAG529: add $1, $3, $3 bne $3, $1, TAG530 mthi $1 bne $1, $3, TAG530 TAG530: mflo $2 mtlo $2 bne $2, $2, TAG531 xori $3, $1, 5 TAG531: mthi $3 mfhi $2 bltz $3, TAG532 or $4, $3, $2 TAG532: blez $4, TAG533 addu $4, $4, $4 lhu $2, 0($4) sb $4, 0($4) TAG533: lui $3, 0 div $2, $2 nor $4, $3, $2 sh $4, 0($3) TAG534: srlv $2, $4, $4 bltz $4, TAG535 andi $4, $4, 0 addu $2, $4, $4 TAG535: addu $1, $2, $2 bne $2, $2, TAG536 divu $1, $2 slti $1, $1, 9 TAG536: lbu $4, 0($1) sra $2, $1, 7 lui $3, 11 mthi $3 TAG537: subu $2, $3, $3 mthi $3 mthi $2 sll $0, $0, 0 TAG538: mtlo $2 mthi $2 multu $2, $2 mtlo $2 TAG539: bgez $2, TAG540 sb $2, 0($2) sw $2, 0($2) div $2, $2 TAG540: srav $2, $2, $2 lb $1, 0($2) srl $1, $2, 13 lui $1, 4 TAG541: mult $1, $1 bltz $1, TAG542 sltiu $3, $1, 9 lh $3, 0($3) TAG542: lui $3, 5 lui $4, 1 sll $0, $0, 0 div $3, $3 TAG543: mtlo $3 and $3, $3, $3 sll $0, $0, 0 sll $0, $0, 0 TAG544: beq $3, $3, TAG545 srlv $1, $3, $3 lw $2, 0($1) div $1, $1 TAG545: lbu $1, 0($2) sh $2, 0($2) blez $1, TAG546 lb $1, 0($2) TAG546: blez $1, TAG547 lw $4, 0($1) mflo $4 mfhi $1 TAG547: multu $1, $1 mtlo $1 lui $4, 8 mfhi $1 TAG548: beq $1, $1, TAG549 lhu $3, 0($1) divu $1, $1 divu $3, $1 TAG549: mtlo $3 sw $3, 0($3) bgez $3, TAG550 xori $3, $3, 15 TAG550: subu $1, $3, $3 or $2, $3, $1 mfhi $3 lhu $3, 0($3) TAG551: mfhi $4 mult $4, $4 mfhi $4 mthi $4 TAG552: multu $4, $4 sb $4, 0($4) mtlo $4 bltz $4, TAG553 TAG553: xori $4, $4, 5 addu $2, $4, $4 mfhi $4 sb $2, 0($2) TAG554: sb $4, 0($4) ori $4, $4, 9 slt $3, $4, $4 multu $4, $3 TAG555: sh $3, 0($3) xori $1, $3, 9 mflo $1 lui $3, 8 TAG556: lui $4, 14 sll $0, $0, 0 lui $1, 12 mtlo $4 TAG557: mflo $4 multu $4, $4 mtlo $1 div $1, $1 TAG558: bne $4, $4, TAG559 mfhi $1 lui $2, 11 sltu $2, $2, $4 TAG559: mfhi $2 sh $2, 0($2) mfhi $3 bne $2, $2, TAG560 TAG560: mflo $4 mthi $3 mflo $1 mthi $1 TAG561: bgez $1, TAG562 lui $4, 3 mtlo $1 mtlo $1 TAG562: bne $4, $4, TAG563 mfhi $2 mult $2, $4 srlv $4, $2, $2 TAG563: bne $4, $4, TAG564 mfhi $3 sb $3, 0($4) lui $2, 12 TAG564: bgtz $2, TAG565 sll $0, $0, 0 lui $3, 12 bne $2, $3, TAG565 TAG565: srlv $2, $3, $3 mult $2, $3 mthi $2 addi $4, $3, 12 TAG566: sh $4, 0($4) andi $4, $4, 3 lui $4, 10 sll $0, $0, 0 TAG567: bne $4, $4, TAG568 srav $1, $4, $4 mthi $1 bltz $4, TAG568 TAG568: lui $1, 5 sll $0, $0, 0 div $1, $1 bne $1, $1, TAG569 TAG569: mflo $4 bgez $1, TAG570 srav $3, $4, $1 sllv $4, $4, $4 TAG570: mfhi $2 mthi $2 andi $3, $2, 0 lh $2, 0($3) TAG571: sb $2, 0($2) mtlo $2 sb $2, 0($2) mthi $2 TAG572: sw $2, 0($2) mflo $1 lhu $3, 0($1) sw $3, 0($2) TAG573: sh $3, 0($3) mfhi $4 bne $3, $4, TAG574 lui $4, 10 TAG574: beq $4, $4, TAG575 lui $1, 3 bne $4, $4, TAG575 lui $4, 7 TAG575: sll $0, $0, 0 bne $4, $4, TAG576 mtlo $4 sll $0, $0, 0 TAG576: mfhi $2 lh $1, 0($2) mtlo $4 multu $4, $1 TAG577: multu $1, $1 nor $3, $1, $1 lhu $2, 0($1) nor $3, $1, $3 TAG578: bgtz $3, TAG579 lw $4, 0($3) bne $4, $3, TAG579 xori $4, $3, 14 TAG579: bgez $4, TAG580 multu $4, $4 xor $4, $4, $4 or $4, $4, $4 TAG580: lui $3, 2 divu $3, $4 nor $3, $3, $4 bltz $3, TAG581 TAG581: mtlo $3 mthi $3 addu $1, $3, $3 or $1, $3, $1 TAG582: lui $1, 4 lui $2, 12 beq $1, $1, TAG583 lui $2, 15 TAG583: sll $0, $0, 0 lui $2, 5 xor $2, $3, $2 lui $2, 4 TAG584: addiu $1, $2, 6 mthi $2 sll $0, $0, 0 sra $4, $2, 9 TAG585: addiu $4, $4, 3 lui $1, 5 sh $1, -515($4) blez $4, TAG586 TAG586: xori $1, $1, 8 bgtz $1, TAG587 sll $0, $0, 0 bne $1, $1, TAG587 TAG587: sll $0, $0, 0 sll $0, $0, 0 beq $1, $1, TAG588 mfhi $3 TAG588: sll $1, $3, 13 bgtz $3, TAG589 sll $0, $0, 0 beq $3, $3, TAG589 TAG589: mflo $3 mthi $3 sll $0, $0, 0 bltz $1, TAG590 TAG590: mfhi $4 beq $4, $4, TAG591 slt $2, $3, $4 sh $2, 0($2) TAG591: mflo $2 blez $2, TAG592 mflo $2 lw $4, 0($2) TAG592: subu $3, $4, $4 andi $4, $4, 10 multu $4, $4 mflo $2 TAG593: bgez $2, TAG594 mfhi $4 lh $1, 0($2) div $4, $2 TAG594: mtlo $1 lui $1, 13 sra $1, $1, 8 beq $1, $1, TAG595 TAG595: mflo $4 lb $2, -3328($1) mult $2, $2 addiu $4, $2, 3 TAG596: sb $4, 0($4) slt $1, $4, $4 sw $4, 0($1) mtlo $4 TAG597: bgtz $1, TAG598 lui $3, 13 beq $3, $3, TAG598 divu $3, $3 TAG598: beq $3, $3, TAG599 or $1, $3, $3 lui $1, 13 lui $4, 11 TAG599: beq $4, $4, TAG600 mthi $4 mtlo $4 and $4, $4, $4 TAG600: lui $4, 13 mfhi $2 mfhi $4 lui $2, 12 TAG601: sll $0, $0, 0 addiu $1, $2, 0 bgez $2, TAG602 div $2, $1 TAG602: sll $4, $1, 9 sll $0, $0, 0 sll $0, $0, 0 div $1, $4 TAG603: divu $4, $4 lui $1, 5 sll $0, $0, 0 sll $0, $0, 0 TAG604: blez $1, TAG605 sll $0, $0, 0 sll $0, $0, 0 sra $1, $1, 3 TAG605: sra $1, $1, 11 addu $2, $1, $1 mflo $3 lui $2, 1 TAG606: sll $0, $0, 0 lui $1, 14 divu $1, $4 bltz $4, TAG607 TAG607: addiu $2, $1, 13 sll $0, $0, 0 mthi $1 mfhi $2 TAG608: ori $2, $2, 6 addu $1, $2, $2 xori $2, $2, 12 lui $4, 6 TAG609: divu $4, $4 nor $2, $4, $4 xori $4, $2, 6 beq $4, $4, TAG610 TAG610: sll $2, $4, 13 srl $3, $2, 11 addu $1, $4, $4 sll $0, $0, 0 TAG611: mthi $4 divu $4, $4 mflo $2 xori $3, $4, 12 TAG612: sll $0, $0, 0 sll $0, $0, 0 sltiu $1, $3, 9 lui $2, 14 TAG613: srlv $3, $2, $2 bltz $3, TAG614 mtlo $3 blez $2, TAG614 TAG614: divu $3, $3 sll $0, $0, 0 sra $1, $3, 0 bne $1, $3, TAG615 TAG615: mult $1, $1 mflo $3 mult $3, $3 blez $1, TAG616 TAG616: or $1, $3, $3 sb $3, 0($1) or $1, $3, $3 mtlo $1 TAG617: bne $1, $1, TAG618 addu $2, $1, $1 mthi $2 sh $1, 0($2) TAG618: lui $1, 15 sll $0, $0, 0 mthi $1 sll $0, $0, 0 TAG619: sll $0, $0, 0 subu $1, $1, $1 bltz $4, TAG620 mult $4, $1 TAG620: multu $1, $1 lb $2, 0($1) lui $3, 9 srav $1, $3, $3 TAG621: sll $0, $0, 0 mtlo $1 subu $1, $1, $4 bgez $1, TAG622 TAG622: mtlo $1 blez $1, TAG623 sll $0, $0, 0 mthi $1 TAG623: blez $4, TAG624 slti $4, $4, 3 mult $4, $4 lui $4, 12 TAG624: mthi $4 slti $1, $4, 6 lui $3, 8 mthi $1 TAG625: bltz $3, TAG626 lui $4, 0 beq $3, $4, TAG626 xor $3, $4, $4 TAG626: mthi $3 addu $3, $3, $3 blez $3, TAG627 andi $2, $3, 4 TAG627: lh $2, 0($2) bne $2, $2, TAG628 lui $1, 6 or $2, $1, $1 TAG628: multu $2, $2 sll $0, $0, 0 sll $0, $0, 0 sll $0, $0, 0 TAG629: lui $4, 12 sll $0, $0, 0 mtlo $4 ori $2, $4, 10 TAG630: mtlo $2 mthi $2 sll $0, $0, 0 mtlo $2 TAG631: sll $0, $0, 0 srl $2, $3, 15 beq $2, $3, TAG632 lui $2, 4 TAG632: lui $1, 11 sll $0, $0, 0 sll $0, $0, 0 sll $0, $0, 0 TAG633: blez $2, TAG634 mthi $2 bltz $2, TAG634 mthi $2 TAG634: sll $0, $0, 0 addiu $4, $2, 5 bltz $4, TAG635 lui $4, 9 TAG635: bltz $4, TAG636 sll $0, $0, 0 sll $0, $0, 0 sll $0, $0, 0 TAG636: blez $2, TAG637 multu $2, $2 beq $2, $2, TAG637 or $1, $2, $2 TAG637: beq $1, $1, TAG638 srav $4, $1, $1 lui $1, 12 sh $1, 0($4) TAG638: sll $0, $0, 0 lui $1, 14 blez $1, TAG639 lui $2, 2 TAG639: sll $0, $0, 0 blez $2, TAG640 addu $2, $2, $2 sllv $1, $2, $2 TAG640: bne $1, $1, TAG641 sra $4, $1, 8 beq $4, $4, TAG641 slti $1, $1, 1 TAG641: and $2, $1, $1 and $3, $1, $2 mthi $3 mfhi $3 TAG642: lui $4, 0 bne $3, $3, TAG643 srl $2, $4, 1 mfhi $2 TAG643: bltz $2, TAG644 mflo $2 bne $2, $2, TAG644 xori $4, $2, 1 TAG644: or $2, $4, $4 lbu $3, 0($2) sltu $1, $2, $4 mthi $2 TAG645: mthi $1 or $4, $1, $1 mthi $4 bgez $1, TAG646 TAG646: mult $4, $4 mflo $1 ori $4, $1, 0 sw $4, 0($4) TAG647: lb $4, 0($4) multu $4, $4 beq $4, $4, TAG648 mfhi $1 TAG648: mfhi $4 blez $1, TAG649 mthi $4 multu $4, $1 TAG649: mflo $2 lw $4, 0($2) blez $4, TAG650 lui $4, 10 TAG650: bgtz $4, TAG651 sltu $4, $4, $4 xori $3, $4, 2 bltz $4, TAG651 TAG651: mthi $3 xor $1, $3, $3 bgtz $1, TAG652 mult $1, $3 TAG652: mult $1, $1 nor $4, $1, $1 beq $4, $4, TAG653 mtlo $1 TAG653: sll $1, $4, 3 multu $1, $4 sllv $2, $4, $4 bgez $4, TAG654 TAG654: mflo $1 sll $0, $0, 0 bgez $1, TAG655 sll $0, $0, 0 TAG655: lui $2, 7 ori $4, $4, 11 sll $2, $4, 2 bne $2, $4, TAG656 TAG656: mfhi $1 lui $3, 15 mthi $1 bgez $1, TAG657 TAG657: sll $0, $0, 0 lui $1, 3 bgtz $3, TAG658 mfhi $2 TAG658: blez $2, TAG659 sh $2, 9($2) sll $1, $2, 10 ori $4, $2, 5 TAG659: addu $2, $4, $4 mfhi $4 lui $2, 6 sh $4, 9($4) TAG660: mflo $4 mult $2, $4 mfhi $1 mtlo $1 TAG661: lb $1, 0($1) lui $2, 8 bgtz $2, TAG662 lbu $1, 9($1) TAG662: lui $2, 7 mthi $1 mtlo $1 lui $4, 12 TAG663: sll $0, $0, 0 sll $0, $0, 0 lui $1, 15 bne $1, $1, TAG664 TAG664: mthi $1 lui $2, 9 sltu $3, $2, $2 bne $2, $2, TAG665 TAG665: lui $1, 6 bne $1, $3, TAG666 srlv $3, $3, $3 sb $3, 0($3) TAG666: sb $3, 0($3) lh $4, 0($3) mflo $1 mtlo $3 TAG667: mtlo $1 lui $3, 2 sll $0, $0, 0 slti $1, $1, 13 TAG668: sltiu $4, $1, 4 bgez $1, TAG669 lui $1, 14 mflo $4 TAG669: lbu $4, 0($4) mfhi $2 blez $4, TAG670 addiu $1, $4, 13 TAG670: lui $2, 11 bne $2, $2, TAG671 multu $1, $2 sll $0, $0, 0 TAG671: lui $4, 13 sll $0, $0, 0 sll $0, $0, 0 bgtz $1, TAG672 TAG672: sh $1, -268($1) beq $1, $1, TAG673 ori $3, $1, 10 bne $1, $3, TAG673 TAG673: sw $3, -270($3) mtlo $3 srl $4, $3, 7 beq $4, $3, TAG674 TAG674: div $4, $4 bgtz $4, TAG675 mfhi $2 lui $3, 11 TAG675: mthi $3 lbu $4, -270($3) sh $4, -270($3) srlv $2, $3, $4 TAG676: lui $3, 10 sll $0, $0, 0 sub $3, $2, $2 beq $3, $3, TAG677 TAG677: sw $3, 0($3) bne $3, $3, TAG678 lui $2, 14 lui $3, 11 TAG678: addiu $3, $3, 6 srl $4, $3, 4 mthi $4 sll $0, $0, 0 TAG679: mflo $1 sll $0, $0, 0 bltz $4, TAG680 subu $2, $1, $4 TAG680: sll $0, $0, 0 beq $1, $1, TAG681 lui $3, 7 mfhi $3 TAG681: mfhi $4 mthi $4 lui $1, 10 sra $2, $3, 13 TAG682: bltz $2, TAG683 mfhi $2 sll $0, $0, 0 mthi $2 TAG683: srlv $3, $2, $2 mflo $1 mtlo $3 subu $2, $3, $3 TAG684: mfhi $1 srav $1, $1, $2 addiu $1, $2, 1 beq $1, $1, TAG685 TAG685: subu $4, $1, $1 sltu $4, $1, $1 multu $4, $1 and $2, $4, $1 TAG686: sh $2, 0($2) multu $2, $2 bgez $2, TAG687 andi $1, $2, 13 TAG687: blez $1, TAG688 mfhi $1 lui $1, 4 bne $1, $1, TAG688 TAG688: nor $4, $1, $1 mtlo $1 bne $4, $1, TAG689 mthi $1 TAG689: andi $2, $4, 9 bltz $2, TAG690 sb $4, 1($4) sb $4, 0($2) TAG690: xor $4, $2, $2 lb $4, 0($2) ori $3, $2, 2 xor $3, $4, $4 TAG691: beq $3, $3, TAG692 mfhi $4 lh $1, 0($3) lui $1, 4 TAG692: beq $1, $1, TAG693 sh $1, 0($1) lui $4, 13 sb $1, 0($4) TAG693: sllv $4, $4, $4 sw $4, 0($4) beq $4, $4, TAG694 lui $3, 14 TAG694: sra $4, $3, 2 lui $3, 8 sll $0, $0, 0 mtlo $3 TAG695: sll $0, $0, 0 divu $3, $3 mthi $3 mfhi $3 TAG696: mult $3, $3 bgtz $3, TAG697 subu $1, $3, $3 mfhi $4 TAG697: lui $4, 9 sll $0, $0, 0 blez $4, TAG698 xori $1, $4, 15 TAG698: multu $1, $1 bgtz $1, TAG699 div $1, $1 mflo $3 TAG699: bltz $3, TAG700 sll $0, $0, 0 mfhi $3 mfhi $3 TAG700: mflo $3 mfhi $4 sub $2, $3, $4 mtlo $3 TAG701: divu $2, $2 sb $2, 0($2) bgtz $2, TAG702 subu $3, $2, $2 TAG702: blez $3, TAG703 mthi $3 addiu $3, $3, 4 slt $4, $3, $3 TAG703: lui $3, 2 add $3, $4, $4 subu $2, $4, $4 sw $3, 0($3) TAG704: mult $2, $2 nor $3, $2, $2 mfhi $2 multu $2, $3 TAG705: lw $2, 0($2) multu $2, $2 bgez $2, TAG706 lui $4, 0 TAG706: mtlo $4 sub $2, $4, $4 ori $2, $2, 9 bgez $4, TAG707 TAG707: mtlo $2 beq $2, $2, TAG708 lbu $3, 0($2) mult $2, $2 TAG708: mtlo $3 mflo $2 mthi $2 nor $3, $3, $2 TAG709: ori $2, $3, 11 mtlo $2 slt $1, $2, $3 mflo $2 TAG710: sll $0, $0, 0 bne $2, $4, TAG711 mfhi $3 blez $3, TAG711 TAG711: sra $3, $3, 2 addu $4, $3, $3 mthi $4 divu $3, $4 TAG712: slt $3, $4, $4 bgtz $4, TAG713 mult $4, $3 bne $3, $3, TAG713 TAG713: lw $4, 0($3) lhu $1, 0($4) mult $1, $4 and $1, $3, $1 TAG714: lhu $2, 0($1) addu $2, $1, $2 mult $2, $2 beq $1, $2, TAG715 TAG715: lui $3, 13 mfhi $4 lui $4, 10 beq $3, $4, TAG716 TAG716: sll $0, $0, 0 sra $2, $4, 3 sll $0, $0, 0 mfhi $4 TAG717: bgtz $4, TAG718 nor $1, $4, $4 blez $1, TAG718 xor $2, $1, $1 TAG718: srav $4, $2, $2 addiu $2, $4, 1 mult $2, $4 bne $2, $2, TAG719 TAG719: xor $3, $2, $2 addiu $2, $2, 10 srl $4, $3, 9 lui $3, 6 TAG720: multu $3, $3 mflo $1 mthi $1 multu $3, $1 TAG721: mtlo $1 addi $4, $1, 4 or $3, $1, $1 lb $2, 0($4) TAG722: mthi $2 and $2, $2, $2 lui $2, 3 bne $2, $2, TAG723 TAG723: mfhi $4 mthi $4 lui $4, 15 sll $0, $0, 0 TAG724: mtlo $2 sll $0, $0, 0 slti $3, $2, 2 mthi $2 TAG725: bltz $3, TAG726 addiu $4, $3, 0 bgez $3, TAG726 lui $3, 6 TAG726: sll $0, $0, 0 mthi $3 sw $1, 0($1) srav $3, $1, $3 TAG727: mtlo $3 multu $3, $3 mult $3, $3 mult $3, $3 TAG728: bgtz $3, TAG729 mthi $3 mtlo $3 mfhi $4 TAG729: nor $2, $4, $4 multu $2, $4 multu $4, $4 sltu $2, $2, $2 TAG730: lbu $2, 0($2) sra $2, $2, 3 sltiu $1, $2, 15 bne $2, $1, TAG731 TAG731: mfhi $4 bgez $4, TAG732 mfhi $2 sh $4, 0($2) TAG732: lb $4, 0($2) mflo $2 mfhi $2 xor $1, $2, $2 TAG733: sll $3, $1, 14 mflo $2 andi $4, $1, 9 mtlo $4 TAG734: lui $4, 10 slti $4, $4, 1 srlv $3, $4, $4 multu $4, $3 TAG735: slt $2, $3, $3 beq $2, $3, TAG736 lui $1, 9 div $2, $3 TAG736: lui $4, 9 sltiu $3, $1, 8 mtlo $3 bgez $4, TAG737 TAG737: sllv $3, $3, $3 addi $1, $3, 9 sw $3, 0($3) slti $2, $3, 1 TAG738: lui $2, 0 sb $2, 0($2) mflo $2 lh $2, 0($2) TAG739: mthi $2 lui $4, 8 bgez $4, TAG740 div $2, $4 TAG740: sltiu $3, $4, 1 mflo $1 sll $0, $0, 0 mtlo $1 TAG741: lh $3, 0($1) mfhi $4 mult $1, $1 lui $3, 12 TAG742: beq $3, $3, TAG743 sll $0, $0, 0 bltz $3, TAG743 ori $1, $3, 14 TAG743: mflo $3 mfhi $1 sb $1, 0($1) lui $4, 11 TAG744: mthi $4 or $2, $4, $4 mtlo $2 sll $0, $0, 0 TAG745: sll $0, $0, 0 or $4, $2, $4 addiu $4, $4, 2 mflo $4 TAG746: sll $0, $0, 0 mflo $1 bgez $4, TAG747 mflo $3 TAG747: mfhi $4 beq $4, $4, TAG748 sll $0, $0, 0 blez $3, TAG748 TAG748: div $4, $4 xori $2, $4, 10 bgtz $2, TAG749 srl $4, $4, 15 TAG749: divu $4, $4 sh $4, 0($4) slti $3, $4, 14 beq $3, $4, TAG750 TAG750: nop nop test_end: beq $0, $0, test_end nop
dnl PowerPC-64 mpn_sec_tabselect. dnl Contributed to the GNU project by Torbjörn Granlund. dnl Copyright 2011-2013 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C cycles/limb C POWER3/PPC630 1.75 C POWER4/PPC970 2.0 C POWER5 ? C POWER6 5.0 C POWER7 1.75 define(`rp', `r3') define(`tp', `r4') define(`n', `r5') define(`nents', `r6') define(`which', `r7') define(`i', `r8') define(`j', `r9') define(`stride', `r12') define(`mask', `r11') ASM_START() PROLOGUE(mpn_sec_tabselect) addic. j, n, -4 C outer loop induction variable std r31, -8(r1) std r30, -16(r1) std r29, -24(r1) std r28, -32(r1) std r27, -40(r1) sldi stride, n, 3 blt cr0, L(outer_end) L(outer_top): mtctr nents mr r10, tp li r28, 0 li r29, 0 li r30, 0 li r31, 0 addic. j, j, -4 C outer loop induction variable mr i, which ALIGN(16) L(top): addic i, i, -1 C set carry iff i != 0 subfe mask, mask, mask ld r0, 0(tp) ld r27, 8(tp) and r0, r0, mask and r27, r27, mask or r28, r28, r0 or r29, r29, r27 ld r0, 16(tp) ld r27, 24(tp) and r0, r0, mask and r27, r27, mask or r30, r30, r0 or r31, r31, r27 add tp, tp, stride bdnz L(top) std r28, 0(rp) std r29, 8(rp) std r30, 16(rp) std r31, 24(rp) addi tp, r10, 32 addi rp, rp, 32 bge cr0, L(outer_top) L(outer_end): rldicl. r0, n, 63, 63 beq cr0, L(b0x) L(b1x): mtctr nents mr r10, tp li r28, 0 li r29, 0 mr i, which ALIGN(16) L(tp2): addic i, i, -1 subfe mask, mask, mask ld r0, 0(tp) ld r27, 8(tp) and r0, r0, mask and r27, r27, mask or r28, r28, r0 or r29, r29, r27 add tp, tp, stride bdnz L(tp2) std r28, 0(rp) std r29, 8(rp) addi tp, r10, 16 addi rp, rp, 16 L(b0x): rldicl. r0, n, 0, 63 beq cr0, L(b00) L(b01): mtctr nents mr r10, tp li r28, 0 mr i, which ALIGN(16) L(tp1): addic i, i, -1 subfe mask, mask, mask ld r0, 0(tp) and r0, r0, mask or r28, r28, r0 add tp, tp, stride bdnz L(tp1) std r28, 0(rp) L(b00): ld r31, -8(r1) ld r30, -16(r1) ld r29, -24(r1) ld r28, -32(r1) ld r27, -40(r1) blr EPILOGUE()
#define PROBLEM "https://judge.yosupo.jp/problem/point_add_rectangle_sum" #include "../../template/template.hpp" #include "../../data-structure-2d/fenwick-tree-on-range-tree.hpp" #include "../../misc/compress.hpp" #include "../../misc/fastio.hpp" using namespace Nyaan; void Nyaan::solve() { FenwickRangeTree<int, ll> bit; int N, Q; rd(N, Q); vector<int> X(N), Y(N), W(N), c(Q), s(Q), t(Q), u(Q), v(Q); rep(i, N) { rd(X[i], Y[i], W[i]); bit.add_point(X[i], Y[i]); } rep(i, Q) { rd(c[i], s[i], t[i], u[i]); if (c[i]) rd(v[i]); else bit.add_point(s[i], t[i]); } bit.build(); rep(i, N) { bit.add(X[i], Y[i], W[i]); } rep(i, Q) { if (c[i]) { out(bit.sum(s[i], t[i], u[i], v[i])); } else bit.add(s[i], t[i], u[i]); } }
; Copyright © 2021, VideoLAN and dav1d authors ; Copyright © 2021, Two Orioles, LLC ; Copyright (c) 2017-2021, The rav1e contributors ; Copyright (c) 2021, Nathan Egge ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; ; 1. Redistributions of source code must retain the above copyright notice, this ; list of conditions and the following disclaimer. ; ; 2. Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and/or other materials provided with the distribution. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ; ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %include "config.asm" %include "ext/x86/x86inc.asm" SECTION_RODATA %macro DUP8 1-* %rep %0 times 8 dw %1 %rotate 1 %endrep %endmacro pri_taps: DUP8 4, 2, 3, 3 dir_table: db 1 * 32 + 0, 2 * 32 + 0 db 1 * 32 + 0, 2 * 32 - 2 db -1 * 32 + 2, -2 * 32 + 4 db 0 * 32 + 2, -1 * 32 + 4 db 0 * 32 + 2, 0 * 32 + 4 db 0 * 32 + 2, 1 * 32 + 4 db 1 * 32 + 2, 2 * 32 + 4 db 1 * 32 + 0, 2 * 32 + 2 db 1 * 32 + 0, 2 * 32 + 0 db 1 * 32 + 0, 2 * 32 - 2 db -1 * 32 + 2, -2 * 32 + 4 db 0 * 32 + 2, -1 * 32 + 4 dir_shift: times 4 dw 0x4000 times 4 dw 0x1000 pw_128: times 4 dw 128 pw_2048: times 8 dw 2048 pw_m16384: times 8 dw -16384 cextern cdef_dir_8bpc_ssse3.main cextern cdef_dir_8bpc_sse4.main cextern shufw_6543210x SECTION .text %macro REPX 2-* %xdefine %%f(x) %1 %rep %0 - 1 %rotate 1 %%f(%1) %endrep %endmacro %if ARCH_X86_32 DECLARE_REG_TMP 5, 3 %elif WIN64 DECLARE_REG_TMP 7, 4 %else DECLARE_REG_TMP 7, 8 %endif %macro CDEF_FILTER 2 ; w, h %if ARCH_X86_64 DEFINE_ARGS dst, stride, tmp, pridmp, pri, sec, dir mova m8, [base+pw_2048] %else DEFINE_ARGS dst, pridmp, tmp, sec, pri, _, dir %define m8 [base+pw_2048] %define m9 [rsp+16*1+gprsize] %define m10 [rsp+16*2+gprsize] %endif movifnidn prid, r4m movifnidn secd, r5m test prid, prid jz .sec_only movd m6, r4m %if ARCH_X86_32 mov [rsp+24], pridmpd %endif bsr pridmpd, prid lea tmpd, [priq*4] cmp dword r9m, 0x3ff ; if (bpc == 10) cmove prid, tmpd ; pri <<= 2 mov tmpd, r7m ; damping mov dird, r6m and prid, 16 pshufb m6, m7 ; splat lea dirq, [base+dir_table+dirq*2] lea priq, [base+pri_taps+priq*2] test secd, secd jz .pri_only mova [rsp], m6 movd m6, secd tzcnt secd, secd sub pridmpd, tmpd sub tmpd, secd pshufb m6, m7 xor secd, secd neg pridmpd cmovs pridmpd, secd %if ARCH_X86_32 mov [pri_shift+4], secd mov [sec_shift+4], secd %endif mov [pri_shift+0], pridmpq mov [sec_shift+0], tmpq lea tmpq, [px] %if WIN64 movaps r4m, m9 movaps r6m, m10 %elif ARCH_X86_32 mov pridmpd, [rsp+24] %endif %rep %1*%2/8 call mangle(private_prefix %+ _cdef_filter_%1x%1_16bpc %+ SUFFIX).pri_sec %endrep %if WIN64 movaps m9, r4m movaps m10, r6m %endif jmp .end .pri_only: sub tmpd, pridmpd cmovs tmpd, secd %if ARCH_X86_32 mov pridmpd, [rsp+24] mov [pri_shift+4], secd %endif mov [pri_shift+0], tmpq lea tmpq, [px] %rep %1*%2/8 call mangle(private_prefix %+ _cdef_filter_%1x%1_16bpc %+ SUFFIX).pri %endrep .end: RET .sec_only: mov tmpd, r7m ; damping movd m6, r5m tzcnt secd, secd mov dird, r6m pshufb m6, m7 sub tmpd, secd lea dirq, [base+dir_table+dirq*2] %if ARCH_X86_32 mov [sec_shift+4], prid %endif mov [sec_shift+0], tmpq lea tmpq, [px] %rep %1*%2/8 call mangle(private_prefix %+ _cdef_filter_%1x%1_16bpc %+ SUFFIX).sec %endrep jmp .end %if %1 == %2 DEFINE_ARGS dst, stride, tmp, off, pri, _, dir ALIGN function_align .pri: movsx offq, byte [dirq+4] ; off_k0 %if %1 == 4 movq m1, [dstq+strideq*0] movhps m1, [dstq+strideq*1] movq m2, [tmpq+offq+32*0] ; k0p0 movhps m2, [tmpq+offq+32*1] neg offq movq m3, [tmpq+offq+32*0] ; k0p1 movhps m3, [tmpq+offq+32*1] %else mova m1, [dstq] movu m2, [tmpq+offq] neg offq movu m3, [tmpq+offq] %endif movsx offq, byte [dirq+5] ; off_k1 psubw m2, m1 ; diff_k0p0 psubw m3, m1 ; diff_k0p1 pabsw m4, m2 ; adiff_k0p0 psrlw m5, m4, [pri_shift+gprsize] psubusw m0, m6, m5 pabsw m5, m3 ; adiff_k0p1 pminsw m0, m4 psrlw m4, m5, [pri_shift+gprsize] psignw m0, m2 ; constrain(diff_k0p0) psubusw m2, m6, m4 pminsw m2, m5 %if %1 == 4 movq m4, [tmpq+offq+32*0] ; k1p0 movhps m4, [tmpq+offq+32*1] neg offq movq m5, [tmpq+offq+32*0] ; k1p1 movhps m5, [tmpq+offq+32*1] %else movu m4, [tmpq+offq] neg offq movu m5, [tmpq+offq] %endif psubw m4, m1 ; diff_k1p0 psubw m5, m1 ; diff_k1p1 psignw m2, m3 ; constrain(diff_k0p1) pabsw m3, m4 ; adiff_k1p0 paddw m0, m2 ; constrain(diff_k0) psrlw m2, m3, [pri_shift+gprsize] psubusw m7, m6, m2 pabsw m2, m5 ; adiff_k1p1 pminsw m7, m3 psrlw m3, m2, [pri_shift+gprsize] psignw m7, m4 ; constrain(diff_k1p0) psubusw m4, m6, m3 pminsw m4, m2 psignw m4, m5 ; constrain(diff_k1p1) paddw m7, m4 ; constrain(diff_k1) pmullw m0, [priq+16*0] ; pri_tap_k0 pmullw m7, [priq+16*1] ; pri_tap_k1 paddw m0, m7 ; sum psraw m2, m0, 15 paddw m0, m2 pmulhrsw m0, m8 paddw m0, m1 %if %1 == 4 add tmpq, 32*2 movq [dstq+strideq*0], m0 movhps [dstq+strideq*1], m0 lea dstq, [dstq+strideq*2] %else add tmpq, 32 mova [dstq], m0 add dstq, strideq %endif ret ALIGN function_align .sec: movsx offq, byte [dirq+8] ; off1_k0 %if %1 == 4 movq m1, [dstq+strideq*0] movhps m1, [dstq+strideq*1] movq m2, [tmpq+offq+32*0] ; k0s0 movhps m2, [tmpq+offq+32*1] neg offq movq m3, [tmpq+offq+32*0] ; k0s1 movhps m3, [tmpq+offq+32*1] %else mova m1, [dstq] movu m2, [tmpq+offq] neg offq movu m3, [tmpq+offq] %endif movsx offq, byte [dirq+0] ; off2_k0 psubw m2, m1 ; diff_k0s0 psubw m3, m1 ; diff_k0s1 pabsw m4, m2 ; adiff_k0s0 psrlw m5, m4, [sec_shift+gprsize] psubusw m0, m6, m5 pabsw m5, m3 ; adiff_k0s1 pminsw m0, m4 psrlw m4, m5, [sec_shift+gprsize] psignw m0, m2 ; constrain(diff_k0s0) psubusw m2, m6, m4 pminsw m2, m5 %if %1 == 4 movq m4, [tmpq+offq+32*0] ; k0s2 movhps m4, [tmpq+offq+32*1] neg offq movq m5, [tmpq+offq+32*0] ; k0s3 movhps m5, [tmpq+offq+32*1] %else movu m4, [tmpq+offq] neg offq movu m5, [tmpq+offq] %endif movsx offq, byte [dirq+9] ; off1_k1 psubw m4, m1 ; diff_k0s2 psubw m5, m1 ; diff_k0s3 psignw m2, m3 ; constrain(diff_k0s1) pabsw m3, m4 ; adiff_k0s2 paddw m0, m2 psrlw m2, m3, [sec_shift+gprsize] psubusw m7, m6, m2 pabsw m2, m5 ; adiff_k0s3 pminsw m7, m3 psrlw m3, m2, [sec_shift+gprsize] psignw m7, m4 ; constrain(diff_k0s2) psubusw m4, m6, m3 pminsw m4, m2 %if %1 == 4 movq m2, [tmpq+offq+32*0] ; k1s0 movhps m2, [tmpq+offq+32*1] neg offq movq m3, [tmpq+offq+32*0] ; k1s1 movhps m3, [tmpq+offq+32*1] %else movu m2, [tmpq+offq] neg offq movu m3, [tmpq+offq] %endif movsx offq, byte [dirq+1] ; off2_k1 paddw m0, m7 psignw m4, m5 ; constrain(diff_k0s3) paddw m0, m4 ; constrain(diff_k0) psubw m2, m1 ; diff_k1s0 psubw m3, m1 ; diff_k1s1 paddw m0, m0 ; sec_tap_k0 pabsw m4, m2 ; adiff_k1s0 psrlw m5, m4, [sec_shift+gprsize] psubusw m7, m6, m5 pabsw m5, m3 ; adiff_k1s1 pminsw m7, m4 psrlw m4, m5, [sec_shift+gprsize] psignw m7, m2 ; constrain(diff_k1s0) psubusw m2, m6, m4 pminsw m2, m5 %if %1 == 4 movq m4, [tmpq+offq+32*0] ; k1s2 movhps m4, [tmpq+offq+32*1] neg offq movq m5, [tmpq+offq+32*0] ; k1s3 movhps m5, [tmpq+offq+32*1] %else movu m4, [tmpq+offq] neg offq movu m5, [tmpq+offq] %endif paddw m0, m7 psubw m4, m1 ; diff_k1s2 psubw m5, m1 ; diff_k1s3 psignw m2, m3 ; constrain(diff_k1s1) pabsw m3, m4 ; adiff_k1s2 paddw m0, m2 psrlw m2, m3, [sec_shift+gprsize] psubusw m7, m6, m2 pabsw m2, m5 ; adiff_k1s3 pminsw m7, m3 psrlw m3, m2, [sec_shift+gprsize] psignw m7, m4 ; constrain(diff_k1s2) psubusw m4, m6, m3 pminsw m4, m2 paddw m0, m7 psignw m4, m5 ; constrain(diff_k1s3) paddw m0, m4 ; sum psraw m2, m0, 15 paddw m0, m2 pmulhrsw m0, m8 paddw m0, m1 %if %1 == 4 add tmpq, 32*2 movq [dstq+strideq*0], m0 movhps [dstq+strideq*1], m0 lea dstq, [dstq+strideq*2] %else add tmpq, 32 mova [dstq], m0 add dstq, strideq %endif ret ALIGN function_align .pri_sec: movsx offq, byte [dirq+8] ; off2_k0 %if %1 == 4 movq m1, [dstq+strideq*0] movhps m1, [dstq+strideq*1] movq m2, [tmpq+offq+32*0] ; k0s0 movhps m2, [tmpq+offq+32*1] neg offq movq m3, [tmpq+offq+32*0] ; k0s1 movhps m3, [tmpq+offq+32*1] %else mova m1, [dstq] movu m2, [tmpq+offq] neg offq movu m3, [tmpq+offq] %endif movsx offq, byte [dirq+0] ; off3_k0 pabsw m4, m2 %if ARCH_X86_64 pabsw m10, m3 pmaxsw m9, m2, m3 pminsw m10, m4 %else pabsw m7, m3 pmaxsw m5, m2, m3 pminsw m4, m7 mova m9, m5 mova m10, m4 %endif psubw m2, m1 ; diff_k0s0 psubw m3, m1 ; diff_k0s1 pabsw m4, m2 ; adiff_k0s0 psrlw m5, m4, [sec_shift+gprsize] psubusw m0, m6, m5 pabsw m5, m3 ; adiff_k0s1 pminsw m0, m4 psrlw m4, m5, [sec_shift+gprsize] psignw m0, m2 ; constrain(diff_k0s0) psubusw m2, m6, m4 pminsw m2, m5 %if %1 == 4 movq m4, [tmpq+offq+32*0] ; k0s2 movhps m4, [tmpq+offq+32*1] neg offq movq m5, [tmpq+offq+32*0] ; k0s3 movhps m5, [tmpq+offq+32*1] %else movu m4, [tmpq+offq] neg offq movu m5, [tmpq+offq] %endif movsx offq, byte [dirq+9] ; off2_k1 pabsw m7, m4 psignw m2, m3 pabsw m3, m5 ; constrain(diff_k0s1) %if ARCH_X86_64 pmaxsw m9, m4 pminsw m10, m7 pmaxsw m9, m5 pminsw m10, m3 %else pminsw m7, m10 pminsw m7, m3 pmaxsw m3, m9, m4 pmaxsw m3, m5 mova m10, m7 mova m9, m3 %endif psubw m4, m1 ; diff_k0s2 psubw m5, m1 ; diff_k0s3 paddw m0, m2 pabsw m3, m4 ; adiff_k0s2 psrlw m2, m3, [sec_shift+gprsize] psubusw m7, m6, m2 pabsw m2, m5 ; adiff_k0s3 pminsw m7, m3 psrlw m3, m2, [sec_shift+gprsize] psignw m7, m4 ; constrain(diff_k0s2) psubusw m4, m6, m3 pminsw m4, m2 %if %1 == 4 movq m2, [tmpq+offq+32*0] ; k1s0 movhps m2, [tmpq+offq+32*1] neg offq movq m3, [tmpq+offq+32*0] ; k1s1 movhps m3, [tmpq+offq+32*1] %else movu m2, [tmpq+offq] neg offq movu m3, [tmpq+offq] %endif movsx offq, byte [dirq+1] ; off3_k1 paddw m0, m7 pabsw m7, m2 psignw m4, m5 ; constrain(diff_k0s3) pabsw m5, m3 %if ARCH_X86_64 pmaxsw m9, m2 pminsw m10, m7 pmaxsw m9, m3 pminsw m10, m5 %else pminsw m7, m10 pminsw m7, m5 pmaxsw m5, m9, m2 pmaxsw m5, m3 mova m10, m7 mova m9, m5 %endif paddw m0, m4 ; constrain(diff_k0) psubw m2, m1 ; diff_k1s0 psubw m3, m1 ; diff_k1s1 paddw m0, m0 ; sec_tap_k0 pabsw m4, m2 ; adiff_k1s0 psrlw m5, m4, [sec_shift+gprsize] psubusw m7, m6, m5 pabsw m5, m3 ; adiff_k1s1 pminsw m7, m4 psrlw m4, m5, [sec_shift+gprsize] psignw m7, m2 ; constrain(diff_k1s0) psubusw m2, m6, m4 pminsw m2, m5 %if %1 == 4 movq m4, [tmpq+offq+32*0] ; k1s2 movhps m4, [tmpq+offq+32*1] neg offq movq m5, [tmpq+offq+32*0] ; k1s3 movhps m5, [tmpq+offq+32*1] %else movu m4, [tmpq+offq] neg offq movu m5, [tmpq+offq] %endif movsx offq, byte [dirq+4] ; off1_k0 paddw m0, m7 pabsw m7, m4 psignw m2, m3 ; constrain(diff_k1s1) pabsw m3, m5 %if ARCH_X86_64 pmaxsw m9, m4 pminsw m10, m7 pmaxsw m9, m5 pminsw m10, m3 %else pminsw m7, m10 pminsw m7, m3 pmaxsw m3, m9, m4 pmaxsw m3, m5 mova m10, m7 mova m9, m3 %endif psubw m4, m1 ; diff_k1s2 psubw m5, m1 ; diff_k1s3 pabsw m3, m4 ; adiff_k1s2 paddw m0, m2 psrlw m2, m3, [sec_shift+gprsize] psubusw m7, m6, m2 pabsw m2, m5 ; adiff_k1s3 pminsw m7, m3 psrlw m3, m2, [sec_shift+gprsize] psignw m7, m4 ; constrain(diff_k1s2) psubusw m4, m6, m3 pminsw m4, m2 paddw m0, m7 %if %1 == 4 movq m2, [tmpq+offq+32*0] ; k0p0 movhps m2, [tmpq+offq+32*1] neg offq movq m3, [tmpq+offq+32*0] ; k0p1 movhps m3, [tmpq+offq+32*1] %else movu m2, [tmpq+offq] neg offq movu m3, [tmpq+offq] %endif movsx offq, byte [dirq+5] ; off1_k1 pabsw m7, m2 psignw m4, m5 ; constrain(diff_k1s3) pabsw m5, m3 %if ARCH_X86_64 pmaxsw m9, m2 pminsw m10, m7 pmaxsw m9, m3 pminsw m10, m5 %else pminsw m7, m10 pminsw m7, m5 pmaxsw m5, m9, m2 pmaxsw m5, m3 mova m10, m7 mova m9, m5 %endif psubw m2, m1 ; diff_k0p0 psubw m3, m1 ; diff_k0p1 paddw m0, m4 pabsw m4, m2 ; adiff_k0p0 psrlw m5, m4, [pri_shift+gprsize] psubusw m7, [rsp+gprsize], m5 pabsw m5, m3 ; adiff_k0p1 pminsw m7, m4 psrlw m4, m5, [pri_shift+gprsize] psignw m7, m2 ; constrain(diff_k0p0) psubusw m2, [rsp+gprsize], m4 pminsw m2, m5 %if %1 == 4 movq m4, [tmpq+offq+32*0] ; k1p0 movhps m4, [tmpq+offq+32*1] neg offq movq m5, [tmpq+offq+32*0] ; k1p1 movhps m5, [tmpq+offq+32*1] %else movu m4, [tmpq+offq] neg offq movu m5, [tmpq+offq] %endif psignw m2, m3 ; constrain(diff_k0p1) pabsw m3, m4 paddw m7, m2 ; constrain(diff_k0) pabsw m2, m5 %if ARCH_X86_64 pmaxsw m9, m4 pminsw m10, m3 pmaxsw m9, m5 pminsw m10, m2 %else pminsw m3, m10 pminsw m3, m2 pmaxsw m2, m9, m4 pmaxsw m2, m5 mova m10, m3 mova m9, m2 %endif psubw m4, m1 ; diff_k1p0 psubw m5, m1 ; diff_k1p1 pabsw m3, m4 ; adiff_k1p0 pmullw m7, [priq+16*0] ; pri_tap_k0 paddw m0, m7 psrlw m2, m3, [pri_shift+gprsize] psubusw m7, [rsp+16*0+gprsize], m2 pabsw m2, m5 ; adiff_k1p1 pminsw m7, m3 psrlw m3, m2, [pri_shift+gprsize] psignw m7, m4 ; constrain(diff_k1p0) psubusw m4, [rsp+16*0+gprsize], m3 pminsw m4, m2 psignw m4, m5 ; constrain(diff_k1p1) paddw m7, m4 ; constrain(diff_k1) pmullw m7, [priq+16*1] ; pri_tap_k1 paddw m0, m7 ; sum psraw m2, m0, 15 paddw m0, m2 pmulhrsw m0, m8 paddw m0, m1 %if ARCH_X86_64 pmaxsw m9, m1 pminsw m0, m9 %else pmaxsw m2, m9, m1 pminsw m0, m2 %endif pminsw m1, m10 pmaxsw m0, m1 %if %1 == 4 add tmpq, 32*2 movq [dstq+strideq*0], m0 movhps [dstq+strideq*1], m0 lea dstq, [dstq+strideq*2] %else add tmpq, 32 mova [dstq], m0 add dstq, strideq %endif ret %endif %endmacro INIT_XMM ssse3 %if ARCH_X86_64 cglobal cdef_filter_4x4_16bpc, 4, 8, 9, 32*10, dst, stride, left, top, pri, sec, edge %define px rsp+32*4 %else cglobal cdef_filter_4x4_16bpc, 2, 7, 8, -32*11, dst, stride, edge, top, left %define px rsp+32*5 %endif %define base t0-dir_table %define pri_shift px-16*6 %define sec_shift px-16*5 mov edged, r8m LEA t0, dir_table movu m0, [dstq+strideq*0] movu m1, [dstq+strideq*1] lea t1, [dstq+strideq*2] movu m2, [t1 +strideq*0] movu m3, [t1 +strideq*1] movddup m7, [base+pw_m16384] mova [px+32*0+0], m0 mova [px+32*1+0], m1 mova [px+32*2+0], m2 mova [px+32*3+0], m3 test edgeb, 4 ; HAVE_TOP jz .no_top movifnidn topq, topmp movu m0, [topq+strideq*0] movu m1, [topq+strideq*1] mova [px-32*2+0], m0 mova [px-32*1+0], m1 test edgeb, 1 ; HAVE_LEFT jz .top_no_left movd m0, [topq+strideq*0-4] movd m1, [topq+strideq*1-4] movd [px-32*2-4], m0 movd [px-32*1-4], m1 jmp .top_done .no_top: mova [px-32*2+0], m7 mova [px-32*1+0], m7 .top_no_left: movd [px-32*2-4], m7 movd [px-32*1-4], m7 .top_done: test edgeb, 8 ; HAVE_BOTTOM jz .no_bottom lea r3, [dstq+strideq*4] movu m0, [r3+strideq*0] movu m1, [r3+strideq*1] mova [px+32*4+0], m0 mova [px+32*5+0], m1 test edgeb, 1 ; HAVE_LEFT jz .bottom_no_left movd m0, [r3+strideq*0-4] movd m1, [r3+strideq*1-4] movd [px+32*4-4], m0 movd [px+32*5-4], m1 jmp .bottom_done .no_bottom: mova [px+32*4+0], m7 mova [px+32*5+0], m7 .bottom_no_left: movd [px+32*4-4], m7 movd [px+32*5-4], m7 .bottom_done: test edgeb, 1 ; HAVE_LEFT jz .no_left movifnidn leftq, r2mp movd m0, [leftq+4*0] movd m1, [leftq+4*1] movd m2, [leftq+4*2] movd m3, [leftq+4*3] movd [px+32*0-4], m0 movd [px+32*1-4], m1 movd [px+32*2-4], m2 movd [px+32*3-4], m3 jmp .left_done .no_left: REPX {movd [px+32*x-4], m7}, 0, 1, 2, 3 .left_done: test edgeb, 2 ; HAVE_RIGHT jnz .padding_done REPX {movd [px+32*x+8], m7}, -2, -1, 0, 1, 2, 3, 4, 5 .padding_done: CDEF_FILTER 4, 4 %if ARCH_X86_64 cglobal cdef_filter_4x8_16bpc, 4, 8, 9, 32*14, dst, stride, left, top, pri, sec, edge %else cglobal cdef_filter_4x8_16bpc, 2, 7, 8, -32*15, dst, stride, edge, top, left %endif mov edged, r8m LEA t0, dir_table movu m0, [dstq+strideq*0] movu m1, [dstq+strideq*1] lea t1, [dstq+strideq*2] movu m2, [t1 +strideq*0] movu m3, [t1 +strideq*1] lea t1, [t1 +strideq*2] movu m4, [t1 +strideq*0] movu m5, [t1 +strideq*1] lea t1, [t1 +strideq*2] movu m6, [t1 +strideq*0] movu m7, [t1 +strideq*1] mova [px+32*0+0], m0 mova [px+32*1+0], m1 mova [px+32*2+0], m2 mova [px+32*3+0], m3 mova [px+32*4+0], m4 mova [px+32*5+0], m5 mova [px+32*6+0], m6 mova [px+32*7+0], m7 movddup m7, [base+pw_m16384] test edgeb, 4 ; HAVE_TOP jz .no_top movifnidn topq, topmp movu m0, [topq+strideq*0] movu m1, [topq+strideq*1] mova [px-32*2+0], m0 mova [px-32*1+0], m1 test edgeb, 1 ; HAVE_LEFT jz .top_no_left movd m0, [topq+strideq*0-4] movd m1, [topq+strideq*1-4] movd [px-32*2-4], m0 movd [px-32*1-4], m1 jmp .top_done .no_top: mova [px-32*2+0], m7 mova [px-32*1+0], m7 .top_no_left: movd [px-32*2-4], m7 movd [px-32*1-4], m7 .top_done: test edgeb, 8 ; HAVE_BOTTOM jz .no_bottom lea r3, [dstq+strideq*8] movu m0, [r3+strideq*0] movu m1, [r3+strideq*1] mova [px+32*8+0], m0 mova [px+32*9+0], m1 test edgeb, 1 ; HAVE_LEFT jz .bottom_no_left movd m0, [r3+strideq*0-4] movd m1, [r3+strideq*1-4] movd [px+32*8-4], m0 movd [px+32*9-4], m1 jmp .bottom_done .no_bottom: mova [px+32*8+0], m7 mova [px+32*9+0], m7 .bottom_no_left: movd [px+32*8-4], m7 movd [px+32*9-4], m7 .bottom_done: test edgeb, 1 ; HAVE_LEFT jz .no_left movifnidn leftq, r2mp movd m0, [leftq+4*0] movd m1, [leftq+4*1] movd m2, [leftq+4*2] movd m3, [leftq+4*3] movd [px+32*0-4], m0 movd [px+32*1-4], m1 movd [px+32*2-4], m2 movd [px+32*3-4], m3 movd m0, [leftq+4*4] movd m1, [leftq+4*5] movd m2, [leftq+4*6] movd m3, [leftq+4*7] movd [px+32*4-4], m0 movd [px+32*5-4], m1 movd [px+32*6-4], m2 movd [px+32*7-4], m3 jmp .left_done .no_left: REPX {movd [px+32*x-4], m7}, 0, 1, 2, 3, 4, 5, 6, 7 .left_done: test edgeb, 2 ; HAVE_RIGHT jnz .padding_done REPX {movd [px+32*x+8], m7}, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 .padding_done: CDEF_FILTER 4, 8 %if ARCH_X86_64 cglobal cdef_filter_8x8_16bpc, 4, 8, 9, 32*14, dst, stride, left, top, pri, sec, edge %else cglobal cdef_filter_8x8_16bpc, 2, 7, 8, -32*15, dst, stride, edge, top, left %endif mov edged, r8m LEA t0, dir_table mova m0, [dstq+strideq*0+ 0] movd m1, [dstq+strideq*0+16] mova m2, [dstq+strideq*1+ 0] movd m3, [dstq+strideq*1+16] lea t1, [dstq+strideq*2] mova m4, [t1 +strideq*0+ 0] movd m5, [t1 +strideq*0+16] mova m6, [t1 +strideq*1+ 0] movd m7, [t1 +strideq*1+16] lea t1, [t1 +strideq*2] mova [px+32*0+ 0], m0 movd [px+32*0+16], m1 mova [px+32*1+ 0], m2 movd [px+32*1+16], m3 mova [px+32*2+ 0], m4 movd [px+32*2+16], m5 mova [px+32*3+ 0], m6 movd [px+32*3+16], m7 mova m0, [t1 +strideq*0+ 0] movd m1, [t1 +strideq*0+16] mova m2, [t1 +strideq*1+ 0] movd m3, [t1 +strideq*1+16] lea t1, [t1 +strideq*2] mova m4, [t1 +strideq*0+ 0] movd m5, [t1 +strideq*0+16] mova m6, [t1 +strideq*1+ 0] movd m7, [t1 +strideq*1+16] mova [px+32*4+ 0], m0 movd [px+32*4+16], m1 mova [px+32*5+ 0], m2 movd [px+32*5+16], m3 mova [px+32*6+ 0], m4 movd [px+32*6+16], m5 mova [px+32*7+ 0], m6 movd [px+32*7+16], m7 movddup m7, [base+pw_m16384] test edgeb, 4 ; HAVE_TOP jz .no_top movifnidn topq, topmp mova m0, [topq+strideq*0+ 0] mova m1, [topq+strideq*0+16] mova m2, [topq+strideq*1+ 0] mova m3, [topq+strideq*1+16] mova [px-32*2+ 0], m0 movd [px-32*2+16], m1 mova [px-32*1+ 0], m2 movd [px-32*1+16], m3 test edgeb, 1 ; HAVE_LEFT jz .top_no_left movd m0, [topq+strideq*0-4] movd m1, [topq+strideq*1-4] movd [px-32*2-4], m0 movd [px-32*1-4], m1 jmp .top_done .no_top: mova [px-32*2+ 0], m7 movd [px-32*2+16], m7 mova [px-32*1+ 0], m7 movd [px-32*1+16], m7 .top_no_left: movd [px-32*2- 4], m7 movd [px-32*1- 4], m7 .top_done: test edgeb, 8 ; HAVE_BOTTOM jz .no_bottom lea r3, [dstq+strideq*8] mova m0, [r3+strideq*0+ 0] movd m1, [r3+strideq*0+16] mova m2, [r3+strideq*1+ 0] movd m3, [r3+strideq*1+16] mova [px+32*8+ 0], m0 movd [px+32*8+16], m1 mova [px+32*9+ 0], m2 movd [px+32*9+16], m3 test edgeb, 1 ; HAVE_LEFT jz .bottom_no_left movd m0, [r3+strideq*0-4] movd m1, [r3+strideq*1-4] movd [px+32*8- 4], m0 movd [px+32*9- 4], m1 jmp .bottom_done .no_bottom: mova [px+32*8+ 0], m7 movd [px+32*8+16], m7 mova [px+32*9+ 0], m7 movd [px+32*9+16], m7 .bottom_no_left: movd [px+32*8- 4], m7 movd [px+32*9- 4], m7 .bottom_done: test edgeb, 1 ; HAVE_LEFT jz .no_left movifnidn leftq, r2mp movd m0, [leftq+4*0] movd m1, [leftq+4*1] movd m2, [leftq+4*2] movd m3, [leftq+4*3] movd [px+32*0- 4], m0 movd [px+32*1- 4], m1 movd [px+32*2- 4], m2 movd [px+32*3- 4], m3 movd m0, [leftq+4*4] movd m1, [leftq+4*5] movd m2, [leftq+4*6] movd m3, [leftq+4*7] movd [px+32*4- 4], m0 movd [px+32*5- 4], m1 movd [px+32*6- 4], m2 movd [px+32*7- 4], m3 jmp .left_done .no_left: REPX {movd [px+32*x- 4], m7}, 0, 1, 2, 3, 4, 5, 6, 7 .left_done: test edgeb, 2 ; HAVE_RIGHT jnz .padding_done REPX {movd [px+32*x+16], m7}, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 .padding_done: CDEF_FILTER 8, 8 %macro CDEF_DIR 0 %if ARCH_X86_64 cglobal cdef_dir_16bpc, 4, 7, 16, src, stride, var, bdmax lea r6, [dir_shift] shr bdmaxd, 11 ; 0 for 10bpc, 1 for 12bpc movddup m7, [r6+bdmaxq*8] lea r6, [strideq*3] mova m0, [srcq+strideq*0] mova m1, [srcq+strideq*1] mova m2, [srcq+strideq*2] mova m3, [srcq+r6 ] lea srcq, [srcq+strideq*4] mova m4, [srcq+strideq*0] mova m5, [srcq+strideq*1] mova m6, [srcq+strideq*2] REPX {pmulhuw x, m7}, m0, m1, m2, m3, m4, m5, m6 pmulhuw m7, [srcq+r6 ] pxor m8, m8 packuswb m9, m0, m1 packuswb m10, m2, m3 packuswb m11, m4, m5 packuswb m12, m6, m7 REPX {psadbw x, m8}, m9, m10, m11, m12 packssdw m9, m10 packssdw m11, m12 packssdw m9, m11 jmp mangle(private_prefix %+ _cdef_dir_8bpc %+ SUFFIX).main %else cglobal cdef_dir_16bpc, 2, 4, 8, 96, src, stride, var, bdmax mov bdmaxd, bdmaxm LEA r2, dir_shift shr bdmaxd, 11 movddup m7, [r2+bdmaxq*8] lea r3, [strideq*3] pmulhuw m3, m7, [srcq+strideq*0] pmulhuw m4, m7, [srcq+strideq*1] pmulhuw m5, m7, [srcq+strideq*2] pmulhuw m6, m7, [srcq+r3 ] movddup m1, [r2-dir_shift+pw_128] lea srcq, [srcq+strideq*4] pxor m0, m0 packuswb m2, m3, m4 psubw m3, m1 psubw m4, m1 mova [esp+0x00], m3 mova [esp+0x10], m4 packuswb m3, m5, m6 psadbw m2, m0 psadbw m3, m0 psubw m5, m1 psubw m6, m1 packssdw m2, m3 mova [esp+0x20], m5 mova [esp+0x50], m6 pmulhuw m4, m7, [srcq+strideq*0] pmulhuw m5, m7, [srcq+strideq*1] pmulhuw m6, m7, [srcq+strideq*2] pmulhuw m7, [srcq+r3 ] packuswb m3, m4, m5 packuswb m1, m6, m7 psadbw m3, m0 psadbw m1, m0 packssdw m3, m1 movddup m1, [r2-dir_shift+pw_128] LEA r2, shufw_6543210x jmp mangle(private_prefix %+ _cdef_dir_8bpc %+ SUFFIX).main %endif %endmacro INIT_XMM ssse3 CDEF_DIR INIT_XMM sse4 CDEF_DIR
frame 0, 04 frame 2, 24 setrepeat 3 frame 0, 06 frame 1, 06 dorepeat 3 endanim
.global s_prepare_buffers s_prepare_buffers: push %r12 push %rbx push %rsi lea addresses_WC_ht+0x8dc9, %rbx nop nop nop nop sub %r12, %r12 mov (%rbx), %esi nop nop nop cmp %r12, %r12 pop %rsi pop %rbx pop %r12 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r14 push %r8 push %rbp push %rbx push %rcx // Load lea addresses_WT+0x15e09, %rcx clflush (%rcx) nop and $64015, %r8 mov (%rcx), %r14w nop nop nop nop nop and $23591, %r11 // Store mov $0xa50, %r8 clflush (%r8) cmp %r13, %r13 mov $0x5152535455565758, %rcx movq %rcx, %xmm4 movaps %xmm4, (%r8) cmp $11089, %r14 // Store lea addresses_WC+0x5e09, %rbp nop nop cmp $54190, %r11 movb $0x51, (%rbp) nop nop cmp %r8, %r8 // Store mov $0xa09, %rbx nop cmp %r11, %r11 movl $0x51525354, (%rbx) nop nop nop nop nop and $8544, %r8 // Store lea addresses_WT+0xeddb, %r14 nop cmp %rbp, %rbp movb $0x51, (%r14) nop nop nop nop nop inc %r11 // Store lea addresses_RW+0x1be59, %rcx nop nop nop nop nop add $29100, %r13 movw $0x5152, (%rcx) nop xor $32257, %r14 // Store lea addresses_normal+0x2609, %r14 nop nop add %rbp, %rbp mov $0x5152535455565758, %r11 movq %r11, %xmm2 movups %xmm2, (%r14) add $7805, %r13 // Faulty Load lea addresses_RW+0x16e09, %r14 nop nop nop nop nop xor $25715, %rbx mov (%r14), %r8w lea oracles, %rcx and $0xff, %r8 shlq $12, %r8 mov (%rcx,%r8,1), %r8 pop %rcx pop %rbx pop %rbp pop %r8 pop %r14 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 10}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 11}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 4}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 5}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 6}} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
/*************************************************************************** vidhrdw.c Functions to emulate the video hardware of the machine. ***************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" unsigned char *bankp_videoram2; unsigned char *bankp_colorram2; static unsigned char *dirtybuffer2; static struct osd_bitmap *tmpbitmap2; static int scroll_x; static int flipscreen; static int priority; /*************************************************************************** Convert the color PROMs into a more useable format. Bank Panic has a 32x8 palette PROM (I'm not sure whether the second 16 bytes are used - they contain the same colors as the first 16 with only one different) and two 256x4 lookup table PROMs (one for charset #1, one for charset #2 - only the first 128 nibbles seem to be used). I don't know for sure how the palette PROM is connected to the RGB output, but it's probably the usual: bit 7 -- 220 ohm resistor -- BLUE -- 470 ohm resistor -- BLUE -- 220 ohm resistor -- GREEN -- 470 ohm resistor -- GREEN -- 1 kohm resistor -- GREEN -- 220 ohm resistor -- RED -- 470 ohm resistor -- RED bit 0 -- 1 kohm resistor -- RED ***************************************************************************/ void bankp_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom) { int i; #define TOTAL_COLORS(gfxn) (Machine->gfx[gfxn]->total_colors * Machine->gfx[gfxn]->color_granularity) #define COLOR(gfxn,offs) (colortable[Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + offs]) for (i = 0;i < Machine->drv->total_colors;i++) { int bit0,bit1,bit2; /* red component */ bit0 = (*color_prom >> 0) & 0x01; bit1 = (*color_prom >> 1) & 0x01; bit2 = (*color_prom >> 2) & 0x01; *(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; /* green component */ bit0 = (*color_prom >> 3) & 0x01; bit1 = (*color_prom >> 4) & 0x01; bit2 = (*color_prom >> 5) & 0x01; *(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; /* blue component */ bit0 = 0; bit1 = (*color_prom >> 6) & 0x01; bit2 = (*color_prom >> 7) & 0x01; *(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; color_prom++; } /* color_prom now points to the beginning of the lookup table */ /* charset #1 lookup table */ for (i = 0;i < TOTAL_COLORS(0);i++) COLOR(0,i) = *(color_prom++) & 0x0f; color_prom += 128; /* skip the bottom half of the PROM - seems to be not used */ /* charset #2 lookup table */ for (i = 0;i < TOTAL_COLORS(1);i++) COLOR(1,i) = *(color_prom++) & 0x0f; /* the bottom half of the PROM seems to be not used */ } /*************************************************************************** Start the video hardware emulation. ***************************************************************************/ int bankp_vh_start(void) { if (generic_vh_start() != 0) return 1; if ((dirtybuffer2 = (unsigned char *)gp2x_malloc(videoram_size)) == 0) { generic_vh_stop(); return 1; } fast_memset(dirtybuffer2,1,videoram_size); if ((tmpbitmap2 = osd_create_bitmap(Machine->drv->screen_width,Machine->drv->screen_height)) == 0) { gp2x_free(dirtybuffer2); generic_vh_stop(); return 1; } return 0; } void bankp_scroll_w(int offset,int data) { scroll_x = data; } /*************************************************************************** Stop the video hardware emulation. ***************************************************************************/ void bankp_vh_stop(void) { gp2x_free(dirtybuffer2); osd_free_bitmap(tmpbitmap2); generic_vh_stop(); } void bankp_videoram2_w(int offset,int data) { if (bankp_videoram2[offset] != data) { dirtybuffer2[offset] = 1; bankp_videoram2[offset] = data; } } void bankp_colorram2_w(int offset,int data) { if (bankp_colorram2[offset] != data) { dirtybuffer2[offset] = 1; bankp_colorram2[offset] = data; } } void bankp_out_w(int offset,int data) { /* I'm not sure how, but bits 0/1 control playfield priority */ priority = data & 0x03; /* bit 4 controls NMI */ if (data & 0x10) interrupt_enable_w(0,1); else interrupt_enable_w(0,0); /* bit 5 controls screen flip */ if ((data & 0x20) != flipscreen) { flipscreen = data & 0x20; fast_memset(dirtybuffer,1,videoram_size); fast_memset(dirtybuffer2,1,videoram_size); } } /*************************************************************************** Draw the game screen in the given osd_bitmap. Do NOT call osd_update_display() from this function, it will be called by the main emulation engine. ***************************************************************************/ void bankp_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { int offs; /* for every character in the Video RAM, check if it has been modified */ /* since last time and update it accordingly. */ for (offs = videoram_size - 1;offs >= 0;offs--) { if (dirtybuffer[offs]) { int sx,sy,flipx; dirtybuffer[offs] = 0; sx = offs % 32; sy = offs / 32; flipx = colorram[offs] & 0x04; if (flipscreen) { sx = 31 - sx; sy = 31 - sy; flipx = !flipx; } drawgfx(tmpbitmap,Machine->gfx[0], videoram[offs] + 256 * ((colorram[offs] & 3) >> 0), colorram[offs] >> 3, flipx,flipscreen, 8*sx,8*sy, 0,TRANSPARENCY_NONE,0); } if (dirtybuffer2[offs]) { int sx,sy,flipx; dirtybuffer2[offs] = 0; sx = offs % 32; sy = offs / 32; flipx = bankp_colorram2[offs] & 0x08; if (flipscreen) { sx = 31 - sx; sy = 31 - sy; flipx = !flipx; } drawgfx(tmpbitmap2,Machine->gfx[1], bankp_videoram2[offs] + 256 * (bankp_colorram2[offs] & 0x07), bankp_colorram2[offs] >> 4, flipx,flipscreen, 8*sx,8*sy, &Machine->drv->visible_area,TRANSPARENCY_NONE,0); } } /* copy the temporary bitmaps to the screen */ { int scroll; scroll = -scroll_x; if (priority == 2) { copyscrollbitmap(bitmap,tmpbitmap,1,&scroll,0,0,&Machine->drv->visible_area,TRANSPARENCY_NONE,0); copybitmap(bitmap,tmpbitmap2,0,0,0,0,&Machine->drv->visible_area,TRANSPARENCY_COLOR,0); } else { copybitmap(bitmap,tmpbitmap2,0,0,0,0,&Machine->drv->visible_area,TRANSPARENCY_NONE,0); copyscrollbitmap(bitmap,tmpbitmap,1,&scroll,0,0,&Machine->drv->visible_area,TRANSPARENCY_COLOR,0); } } }
#include <core/objects/timing/RoundRobin.h> #include <hal/simd.h> #include <od/config.h> #include <sstream> #include <cstring> namespace od { RoundRobin::RoundRobin(int n) { addInput(mNext); addInput(mInput); addOption(mProcessingRate); addOption(mActiveOutput); mNumOutputs = n; mBuffers = new float *[n]; for (int i = 0; i < n; i++) { std::ostringstream ss; ss << "Out" << i + 1; Outlet *port = new Outlet(ss.str()); port->mName = ss.str(); addOutputFromHeap(port); mBuffers[i] = port->buffer(); } } RoundRobin::~RoundRobin() { delete[] mBuffers; } void RoundRobin::next() { int i = mActiveOutput.value() + 1; if (i == mNumOutputs) { mActiveOutput.set(0); } else { mActiveOutput.set(i); } } void RoundRobin::reset() { mActiveOutput.set(0); } void RoundRobin::process() { float *in = mInput.buffer(); float *trigger = mNext.buffer(); if (mProcessingRate.value() == PER_SAMPLE) { float *tmp = mBuffers[mActiveOutput.value()]; for (int i = 0; i < FRAMELENGTH; i++) { if (trigger[i] > 0.0f) { next(); } tmp[i] = in[i]; } } else if (simd_any_positive(trigger, FRAMELENGTH)) { next(); float *tmp = mBuffers[mActiveOutput.value()]; for (int i = 0; i < FRAMELENGTH; i++) { tmp[i] = in[i]; } } } } /* namespace od */
SeafoamIslands5Script: call EnableAutoTextBoxDrawing ld a, [wSeafoamIslands5CurScript] ld hl, SeafoamIslands5ScriptPointers jp JumpTable SeafoamIslands5Script_467a5: xor a ld [wJoyIgnore], a ld [wSeafoamIslands5CurScript], a ld [wCurMapScript], a ret SeafoamIslands5ScriptPointers: dw SeafoamIslands5Script0 dw SeafoamIslands5Script1 dw SeafoamIslands5Script2 dw SeafoamIslands5Script3 dw SeafoamIslands5Script4 SeafoamIslands5Script4: ld a, [wIsInBattle] cp $ff jr z, SeafoamIslands5Script_467a5 call EndTrainerBattle ld a, $0 ld [wSeafoamIslands5CurScript], a ret SeafoamIslands5Script0: CheckBothEventsSet EVENT_SEAFOAM3_BOULDER1_DOWN_HOLE, EVENT_SEAFOAM3_BOULDER2_DOWN_HOLE ret z ld hl, .Coords call ArePlayerCoordsInArray ret nc ld a, [wCoordIndex] cp $3 jr nc, .asm_467e6 ld a, NPC_MOVEMENT_UP ld [wSimulatedJoypadStatesEnd + 1], a ld a, 2 jr .asm_467e8 .asm_467e6 ld a, 1 .asm_467e8 ld [wSimulatedJoypadStatesIndex], a ld a, D_UP ld [wSimulatedJoypadStatesEnd], a call StartSimulatingJoypadStates ld hl, wFlags_D733 res 2, [hl] ld a, $1 ld [wSeafoamIslands5CurScript], a ret .Coords db $11,$14 db $11,$15 db $10,$14 db $10,$15 db $FF SeafoamIslands5Script1: ld a, [wSimulatedJoypadStatesIndex] and a ret nz xor a ld [wJoyIgnore], a ld a, $0 ld [wSeafoamIslands5CurScript], a ret SeafoamIslands5Script2: CheckBothEventsSet EVENT_SEAFOAM4_BOULDER1_DOWN_HOLE, EVENT_SEAFOAM4_BOULDER2_DOWN_HOLE ld a, $0 jr z, .asm_46849 ld hl, .Coords call ArePlayerCoordsInArray ld a, $0 jr nc, .asm_46849 ld a, [wCoordIndex] cp $1 jr nz, .asm_46837 ld de, RLEMovementData_46859 jr .asm_4683a .asm_46837 ld de, RLEMovementData_46852 .asm_4683a ld hl, wSimulatedJoypadStatesEnd call DecodeRLEList dec a ld [wSimulatedJoypadStatesIndex], a call StartSimulatingJoypadStates ld a, $3 .asm_46849 ld [wSeafoamIslands5CurScript], a ret .Coords db $0E,$04 db $0E,$05 db $FF RLEMovementData_46852: db D_UP,$03 db D_RIGHT,$02 db D_UP,$01 db $FF RLEMovementData_46859: db D_UP,$03 db D_RIGHT,$03 db D_UP,$01 db $FF SeafoamIslands5Script3: ld a, [wSimulatedJoypadStatesIndex] ld b, a cp $1 call z, SeaFoamIslands5Script_46872 ld a, b and a ret nz ld a, $0 ld [wSeafoamIslands5CurScript], a ret SeaFoamIslands5Script_46872: xor a ld [wWalkBikeSurfState], a ld [wWalkBikeSurfStateCopy], a jp ForceBikeOrSurf SeafoamIslands5TextPointers: dw BoulderText dw BoulderText dw ArticunoText dw SeafoamIslands5Text4 dw SeafoamIslands5Text5 ArticunoTrainerHeader: dbEventFlagBit EVENT_BEAT_ARTICUNO db ($0 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_ARTICUNO dw ArticunoBattleText ; TextBeforeBattle dw ArticunoBattleText ; TextAfterBattle dw ArticunoBattleText ; TextEndBattle dw ArticunoBattleText ; TextEndBattle db $ff ArticunoText: TX_ASM ld hl, ArticunoTrainerHeader call TalkToTrainer ld a, $4 ld [wSeafoamIslands5CurScript], a jp TextScriptEnd ArticunoBattleText: TX_FAR _ArticunoBattleText TX_ASM ld a, ARTICUNO call PlayCry call WaitForSoundToFinish jp TextScriptEnd SeafoamIslands5Text4: TX_FAR _SeafoamIslands5Text4 db "@" SeafoamIslands5Text5: TX_FAR _SeafoamIslands5Text5 db "@"
/** *Licensed to the Apache Software Foundation (ASF) under one *or more contributor license agreements. See the NOTICE file *distributed with this work for additional information *regarding copyright ownership. The ASF licenses this file *to you under the Apache License, Version 2.0 (the *"License"); you may not use this file except in compliance *with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ #include <sstream> #include <arpa/inet.h> #include <iostream> #include <pubsub_wire_protocol_common.h> #include "gtest/gtest.h" #include "pubsub_wire_v2_protocol_impl.h" #include "celix_byteswap.h" #include <cstring> class WireProtocolV2Test : public ::testing::Test { public: WireProtocolV2Test() = default; ~WireProtocolV2Test() override = default; }; TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeHeader_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); pubsub_protocol_message_t message; message.header.msgId = 1; message.header.seqNr = 4; message.header.msgMajorVersion = 0; message.header.msgMinorVersion = 0; message.header.payloadSize = 2; message.header.metadataSize = 3; message.header.payloadPartSize = 4; message.header.payloadOffset = 2; message.header.isLastSegment = 1; message.header.convertEndianess = 1; void *headerData = nullptr; size_t headerLength = 0; celix_status_t status = pubsubProtocol_wire_v2_encodeHeader(nullptr, &message, &headerData, &headerLength); unsigned char exp[40]; uint32_t s = bswap_32(0xABBADEAF); memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x02000000; //envelope version memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; //msg id memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x04000000; //seqnr memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); uint32_t pps = 0x04000000; memcpy(exp+28, &pps, sizeof(uint32_t)); uint32_t ppo = 0x02000000; memcpy(exp+32, &ppo, sizeof(uint32_t)); uint32_t ils = 0x01000000; memcpy(exp+36, &ils, sizeof(uint32_t)); ASSERT_EQ(status, CELIX_SUCCESS); ASSERT_EQ(40, headerLength); for (int i = 0; i < 40; i++) { ASSERT_EQ(((unsigned char*) headerData)[i], exp[i]); } pubsubProtocol_wire_v2_destroy(wireprotocol); free(headerData); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = bswap_32(0xABBADEAF); //sync memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x02000000; //envelope version memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; //msg id memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; //seqnr memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); uint32_t pps = 0x04000000; memcpy(exp+28, &pps, sizeof(uint32_t)); uint32_t ppo = 0x02000000; memcpy(exp+32, &ppo, sizeof(uint32_t)); uint32_t ils = 0x01000000; memcpy(exp+36, &ils, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_SUCCESS, status); ASSERT_EQ(1, message.header.msgId); ASSERT_EQ(8, message.header.seqNr); ASSERT_EQ(0, message.header.msgMajorVersion); ASSERT_EQ(0, message.header.msgMinorVersion); ASSERT_EQ(2, message.header.payloadSize); ASSERT_EQ(3, message.header.metadataSize); ASSERT_EQ(4, message.header.payloadPartSize); ASSERT_EQ(2, message.header.payloadOffset); ASSERT_EQ(1, message.header.isLastSegment); ASSERT_EQ(1, message.header.convertEndianess); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectSync_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = 0xBAABABBA; memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x01000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectVersion_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[40]; uint32_t s = 0xABBADEAF; memcpy(exp, &s, sizeof(uint32_t)); uint32_t e = 0x02000000; memcpy(exp+4, &e, sizeof(uint32_t)); uint32_t m = 0x01000000; memcpy(exp+8, &m, sizeof(uint32_t)); uint32_t seq = 0x08000000; memcpy(exp+12, &seq, sizeof(uint32_t)); uint32_t v = 0x00000000; memcpy(exp+16, &v, sizeof(uint32_t)); uint32_t ps = 0x02000000; memcpy(exp+20, &ps, sizeof(uint32_t)); uint32_t ms = 0x03000000; memcpy(exp+24, &ms, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeFooter_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); pubsub_protocol_message_t message; message.header.convertEndianess = 0; void *footerData = nullptr; size_t footerLength = 0; celix_status_t status = pubsubProtocol_wire_v2_encodeFooter(nullptr, &message, &footerData, &footerLength); unsigned char exp[4]; uint32_t s = 0xDEAFABBA; memcpy(exp, &s, sizeof(uint32_t)); ASSERT_EQ(status, CELIX_SUCCESS); ASSERT_EQ(4, footerLength); for (int i = 0; i < 4; i++) { if (((unsigned char*) footerData)[i] != exp[i]) { std::cerr << "error at index " << std::to_string(i) << std::endl; } ASSERT_EQ(((unsigned char*) footerData)[i], exp[i]); } pubsubProtocol_wire_v2_destroy(wireprotocol); free(footerData); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[4]; uint32_t s = 0xDEAFABBA; memcpy(exp, &s, sizeof(uint32_t)); pubsub_protocol_message_t message; message.header.convertEndianess = 0; celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message); ASSERT_EQ(CELIX_SUCCESS, status); pubsubProtocol_wire_v2_destroy(wireprotocol); } TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_IncorrectSync_Test) { // NOLINT(cert-err58-cpp) pubsub_protocol_wire_v2_t *wireprotocol; pubsubProtocol_wire_v2_create(&wireprotocol); unsigned char exp[4]; uint32_t s = 0xABBABAAB; memcpy(exp, &s, sizeof(uint32_t)); pubsub_protocol_message_t message; celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message); ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status); pubsubProtocol_wire_v2_destroy(wireprotocol); }
; A094793: a(n) = (1/n!)*A001688(n). ; 9,53,181,465,1001,1909,3333,5441,8425,12501,17909,24913,33801,44885,58501,75009,94793,118261,145845,178001,215209,257973,306821,362305,425001,495509,574453,662481,760265,868501,987909,1119233,1263241 add $0,1 lpb $0 add $3,$0 sub $0,1 add $2,3 add $2,$3 add $3,$0 add $2,$3 add $1,$2 sub $1,1 add $2,1 lpe add $1,1 mul $1,2 sub $1,1
ENTRYPOINT_LOADINGSCREEN = $2800 ENTRYPOINT_STARTSCREEN = $6000 ENTRYPOINT_LEVELSTART = $6800 - $10
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voe_base_impl.h" #include "audio_coding_module.h" #include "audio_processing.h" #include "channel.h" #include "critical_section_wrapper.h" #include "file_wrapper.h" #include "modules/audio_device/audio_device_impl.h" #include "output_mixer.h" #include "signal_processing_library.h" #include "trace.h" #include "transmit_mixer.h" #include "utility.h" #include "voe_errors.h" #include "voice_engine_impl.h" #if (defined(_WIN32) && defined(_DLL) && (_MSC_VER == 1400)) // Fix for VS 2005 MD/MDd link problem #include <stdio.h> extern "C" { FILE _iob[3] = { __iob_func()[0], __iob_func()[1], __iob_func()[2]}; } #endif namespace webrtc { VoEBase* VoEBase::GetInterface(VoiceEngine* voiceEngine) { if (NULL == voiceEngine) { return NULL; } VoiceEngineImpl* s = reinterpret_cast<VoiceEngineImpl*>(voiceEngine); s->AddRef(); return s; } VoEBaseImpl::VoEBaseImpl(voe::SharedData* shared) : _voiceEngineObserverPtr(NULL), _callbackCritSect(*CriticalSectionWrapper::CreateCriticalSection()), _voiceEngineObserver(false), _oldVoEMicLevel(0), _oldMicLevel(0), _shared(shared) { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl() - ctor"); } VoEBaseImpl::~VoEBaseImpl() { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "~VoEBaseImpl() - dtor"); TerminateInternal(); delete &_callbackCritSect; } void VoEBaseImpl::OnErrorIsReported(const ErrorCode error) { CriticalSectionScoped cs(&_callbackCritSect); if (_voiceEngineObserver) { if (_voiceEngineObserverPtr) { int errCode(0); if (error == AudioDeviceObserver::kRecordingError) { errCode = VE_RUNTIME_REC_ERROR; WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::OnErrorIsReported() => VE_RUNTIME_REC_ERROR"); } else if (error == AudioDeviceObserver::kPlayoutError) { errCode = VE_RUNTIME_PLAY_ERROR; WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::OnErrorIsReported() => " "VE_RUNTIME_PLAY_ERROR"); } // Deliver callback (-1 <=> no channel dependency) _voiceEngineObserverPtr->CallbackOnError(-1, errCode); } } } void VoEBaseImpl::OnWarningIsReported(const WarningCode warning) { CriticalSectionScoped cs(&_callbackCritSect); if (_voiceEngineObserver) { if (_voiceEngineObserverPtr) { int warningCode(0); if (warning == AudioDeviceObserver::kRecordingWarning) { warningCode = VE_RUNTIME_REC_WARNING; WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::OnErrorIsReported() => " "VE_RUNTIME_REC_WARNING"); } else if (warning == AudioDeviceObserver::kPlayoutWarning) { warningCode = VE_RUNTIME_PLAY_WARNING; WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::OnErrorIsReported() => " "VE_RUNTIME_PLAY_WARNING"); } // Deliver callback (-1 <=> no channel dependency) _voiceEngineObserverPtr->CallbackOnError(-1, warningCode); } } } WebRtc_Word32 VoEBaseImpl::RecordedDataIsAvailable( const void* audioSamples, const WebRtc_UWord32 nSamples, const WebRtc_UWord8 nBytesPerSample, const WebRtc_UWord8 nChannels, const WebRtc_UWord32 samplesPerSec, const WebRtc_UWord32 totalDelayMS, const WebRtc_Word32 clockDrift, const WebRtc_UWord32 currentMicLevel, WebRtc_UWord32& newMicLevel) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::RecordedDataIsAvailable(nSamples=%u, " "nBytesPerSample=%u, nChannels=%u, samplesPerSec=%u, " "totalDelayMS=%u, clockDrift=%d, currentMicLevel=%u)", nSamples, nBytesPerSample, nChannels, samplesPerSec, totalDelayMS, clockDrift, currentMicLevel); assert(_shared->transmit_mixer() != NULL); assert(_shared->audio_device() != NULL); bool isAnalogAGC(false); WebRtc_UWord32 maxVolume(0); WebRtc_UWord16 currentVoEMicLevel(0); WebRtc_UWord32 newVoEMicLevel(0); if (_shared->audio_processing() && (_shared->audio_processing()->gain_control()->mode() == GainControl::kAdaptiveAnalog)) { isAnalogAGC = true; } // Will only deal with the volume in adaptive analog mode if (isAnalogAGC) { // Scale from ADM to VoE level range if (_shared->audio_device()->MaxMicrophoneVolume(&maxVolume) == 0) { if (0 != maxVolume) { currentVoEMicLevel = (WebRtc_UWord16) ((currentMicLevel * kMaxVolumeLevel + (int) (maxVolume / 2)) / (maxVolume)); } } // We learned that on certain systems (e.g Linux) the currentVoEMicLevel // can be greater than the maxVolumeLevel therefore // we are going to cap the currentVoEMicLevel to the maxVolumeLevel // and change the maxVolume to currentMicLevel if it turns out that // the currentVoEMicLevel is indeed greater than the maxVolumeLevel. if (currentVoEMicLevel > kMaxVolumeLevel) { currentVoEMicLevel = kMaxVolumeLevel; maxVolume = currentMicLevel; } } // Keep track if the MicLevel has been changed by the AGC, if not, // use the old value AGC returns to let AGC continue its trend, // so eventually the AGC is able to change the mic level. This handles // issues with truncation introduced by the scaling. if (_oldMicLevel == currentMicLevel) { currentVoEMicLevel = (WebRtc_UWord16) _oldVoEMicLevel; } // Perform channel-independent operations // (APM, mix with file, record to file, mute, etc.) _shared->transmit_mixer()->PrepareDemux(audioSamples, nSamples, nChannels, samplesPerSec, static_cast<WebRtc_UWord16>(totalDelayMS), clockDrift, currentVoEMicLevel); // Copy the audio frame to each sending channel and perform // channel-dependent operations (file mixing, mute, etc.) to prepare // for encoding. _shared->transmit_mixer()->DemuxAndMix(); // Do the encoding and packetize+transmit the RTP packet when encoding // is done. _shared->transmit_mixer()->EncodeAndSend(); // Will only deal with the volume in adaptive analog mode if (isAnalogAGC) { // Scale from VoE to ADM level range newVoEMicLevel = _shared->transmit_mixer()->CaptureLevel(); if (newVoEMicLevel != currentVoEMicLevel) { // Add (kMaxVolumeLevel/2) to round the value newMicLevel = (WebRtc_UWord32) ((newVoEMicLevel * maxVolume + (int) (kMaxVolumeLevel / 2)) / (kMaxVolumeLevel)); } else { // Pass zero if the level is unchanged newMicLevel = 0; } // Keep track of the value AGC returns _oldVoEMicLevel = newVoEMicLevel; _oldMicLevel = currentMicLevel; } return 0; } WebRtc_Word32 VoEBaseImpl::NeedMorePlayData( const WebRtc_UWord32 nSamples, const WebRtc_UWord8 nBytesPerSample, const WebRtc_UWord8 nChannels, const WebRtc_UWord32 samplesPerSec, void* audioSamples, WebRtc_UWord32& nSamplesOut) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::NeedMorePlayData(nSamples=%u, " "nBytesPerSample=%d, nChannels=%d, samplesPerSec=%u)", nSamples, nBytesPerSample, nChannels, samplesPerSec); assert(_shared->output_mixer() != NULL); // TODO(andrew): if the device is running in mono, we should tell the mixer // here so that it will only request mono from AudioCodingModule. // Perform mixing of all active participants (channel-based mixing) _shared->output_mixer()->MixActiveChannels(); // Additional operations on the combined signal _shared->output_mixer()->DoOperationsOnCombinedSignal(); // Retrieve the final output mix (resampled to match the ADM) _shared->output_mixer()->GetMixedAudio(samplesPerSec, nChannels, &_audioFrame); assert(static_cast<int>(nSamples) == _audioFrame.samples_per_channel_); assert(samplesPerSec == static_cast<WebRtc_UWord32>(_audioFrame.sample_rate_hz_)); // Deliver audio (PCM) samples to the ADM memcpy( (WebRtc_Word16*) audioSamples, (const WebRtc_Word16*) _audioFrame.data_, sizeof(WebRtc_Word16) * (_audioFrame.samples_per_channel_ * _audioFrame.num_channels_)); nSamplesOut = _audioFrame.samples_per_channel_; return 0; } int VoEBaseImpl::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "RegisterVoiceEngineObserver(observer=0x%d)", &observer); CriticalSectionScoped cs(&_callbackCritSect); if (_voiceEngineObserverPtr) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "RegisterVoiceEngineObserver() observer already enabled"); return -1; } // Register the observer in all active channels voe::ScopedChannel sc(_shared->channel_manager()); void* iterator(NULL); voe::Channel* channelPtr = sc.GetFirstChannel(iterator); while (channelPtr != NULL) { channelPtr->RegisterVoiceEngineObserver(observer); channelPtr = sc.GetNextChannel(iterator); } _shared->transmit_mixer()->RegisterVoiceEngineObserver(observer); _voiceEngineObserverPtr = &observer; _voiceEngineObserver = true; return 0; } int VoEBaseImpl::DeRegisterVoiceEngineObserver() { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeRegisterVoiceEngineObserver()"); CriticalSectionScoped cs(&_callbackCritSect); if (!_voiceEngineObserverPtr) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "DeRegisterVoiceEngineObserver() observer already disabled"); return 0; } _voiceEngineObserver = false; _voiceEngineObserverPtr = NULL; // Deregister the observer in all active channels voe::ScopedChannel sc(_shared->channel_manager()); void* iterator(NULL); voe::Channel* channelPtr = sc.GetFirstChannel(iterator); while (channelPtr != NULL) { channelPtr->DeRegisterVoiceEngineObserver(); channelPtr = sc.GetNextChannel(iterator); } return 0; } int VoEBaseImpl::Init(AudioDeviceModule* external_adm) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "Init(external_adm=0x%p)", external_adm); CriticalSectionScoped cs(_shared->crit_sec()); WebRtcSpl_Init(); if (_shared->statistics().Initialized()) { return 0; } if (_shared->process_thread()) { if (_shared->process_thread()->Start() != 0) { _shared->SetLastError(VE_THREAD_ERROR, kTraceError, "Init() failed to start module process thread"); return -1; } } // Create an internal ADM if the user has not added an external // ADM implementation as input to Init(). if (external_adm == NULL) { // Create the internal ADM implementation. _shared->set_audio_device(AudioDeviceModuleImpl::Create( VoEId(_shared->instance_id(), -1), _shared->audio_device_layer())); if (_shared->audio_device() == NULL) { _shared->SetLastError(VE_NO_MEMORY, kTraceCritical, "Init() failed to create the ADM"); return -1; } } else { // Use the already existing external ADM implementation. _shared->set_audio_device(external_adm); WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "An external ADM implementation will be used in VoiceEngine"); } // Register the ADM to the process thread, which will drive the error // callback mechanism if (_shared->process_thread() && _shared->process_thread()->RegisterModule(_shared->audio_device()) != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceError, "Init() failed to register the ADM"); return -1; } bool available(false); // -------------------- // Reinitialize the ADM // Register the AudioObserver implementation if (_shared->audio_device()->RegisterEventObserver(this) != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceWarning, "Init() failed to register event observer for the ADM"); } // Register the AudioTransport implementation if (_shared->audio_device()->RegisterAudioCallback(this) != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceWarning, "Init() failed to register audio callback for the ADM"); } // ADM initialization if (_shared->audio_device()->Init() != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceError, "Init() failed to initialize the ADM"); return -1; } // Initialize the default speaker if (_shared->audio_device()->SetPlayoutDevice( WEBRTC_VOICE_ENGINE_DEFAULT_DEVICE) != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceInfo, "Init() failed to set the default output device"); } if (_shared->audio_device()->SpeakerIsAvailable(&available) != 0) { _shared->SetLastError(VE_CANNOT_ACCESS_SPEAKER_VOL, kTraceInfo, "Init() failed to check speaker availability, trying to " "initialize speaker anyway"); } else if (!available) { _shared->SetLastError(VE_CANNOT_ACCESS_SPEAKER_VOL, kTraceInfo, "Init() speaker not available, trying to initialize speaker " "anyway"); } if (_shared->audio_device()->InitSpeaker() != 0) { _shared->SetLastError(VE_CANNOT_ACCESS_SPEAKER_VOL, kTraceInfo, "Init() failed to initialize the speaker"); } // Initialize the default microphone if (_shared->audio_device()->SetRecordingDevice( WEBRTC_VOICE_ENGINE_DEFAULT_DEVICE) != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceInfo, "Init() failed to set the default input device"); } if (_shared->audio_device()->MicrophoneIsAvailable(&available) != 0) { _shared->SetLastError(VE_CANNOT_ACCESS_MIC_VOL, kTraceInfo, "Init() failed to check microphone availability, trying to " "initialize microphone anyway"); } else if (!available) { _shared->SetLastError(VE_CANNOT_ACCESS_MIC_VOL, kTraceInfo, "Init() microphone not available, trying to initialize " "microphone anyway"); } if (_shared->audio_device()->InitMicrophone() != 0) { _shared->SetLastError(VE_CANNOT_ACCESS_MIC_VOL, kTraceInfo, "Init() failed to initialize the microphone"); } // Set number of channels if (_shared->audio_device()->StereoPlayoutIsAvailable(&available) != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceWarning, "Init() failed to query stereo playout mode"); } if (_shared->audio_device()->SetStereoPlayout(available) != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceWarning, "Init() failed to set mono/stereo playout mode"); } // TODO(andrew): These functions don't tell us whether stereo recording // is truly available. We simply set the AudioProcessing input to stereo // here, because we have to wait until receiving the first frame to // determine the actual number of channels anyway. // // These functions may be changed; tracked here: // http://code.google.com/p/webrtc/issues/detail?id=204 _shared->audio_device()->StereoRecordingIsAvailable(&available); if (_shared->audio_device()->SetStereoRecording(available) != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceWarning, "Init() failed to set mono/stereo recording mode"); } // APM initialization done after sound card since we need // to know if we support stereo recording or not. // Create the AudioProcessing Module if it does not exist. if (_shared->audio_processing() == NULL) { _shared->set_audio_processing(AudioProcessing::Create( VoEId(_shared->instance_id(), -1))); if (_shared->audio_processing() == NULL) { _shared->SetLastError(VE_NO_MEMORY, kTraceCritical, "Init() failed to create the AP module"); return -1; } // Ensure that mixers in both directions has access to the created APM _shared->transmit_mixer()->SetAudioProcessingModule( _shared->audio_processing()); _shared->output_mixer()->SetAudioProcessingModule( _shared->audio_processing()); if (_shared->audio_processing()->echo_cancellation()-> set_device_sample_rate_hz( kVoiceEngineAudioProcessingDeviceSampleRateHz)) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set the device sample rate to 48K for AP " " module"); return -1; } // Using 8 kHz as inital Fs. Might be changed already at first call. if (_shared->audio_processing()->set_sample_rate_hz(8000)) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set the sample rate to 8K for AP module"); return -1; } // Assume mono until the audio frames are received from the capture // device, at which point this can be updated. if (_shared->audio_processing()->set_num_channels(1, 1) != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceError, "Init() failed to set channels for the primary audio stream"); return -1; } if (_shared->audio_processing()->set_num_reverse_channels(1) != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceError, "Init() failed to set channels for the primary audio stream"); return -1; } // high-pass filter if (_shared->audio_processing()->high_pass_filter()->Enable( WEBRTC_VOICE_ENGINE_HP_DEFAULT_STATE) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set the high-pass filter for AP module"); return -1; } // Echo Cancellation if (_shared->audio_processing()->echo_cancellation()-> enable_drift_compensation(false) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set drift compensation for AP module"); return -1; } if (_shared->audio_processing()->echo_cancellation()->Enable( WEBRTC_VOICE_ENGINE_EC_DEFAULT_STATE)) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set echo cancellation state for AP module"); return -1; } // Noise Reduction if (_shared->audio_processing()->noise_suppression()->set_level( (NoiseSuppression::Level) WEBRTC_VOICE_ENGINE_NS_DEFAULT_MODE) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set noise reduction level for AP module"); return -1; } if (_shared->audio_processing()->noise_suppression()->Enable( WEBRTC_VOICE_ENGINE_NS_DEFAULT_STATE) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set noise reduction state for AP module"); return -1; } // Automatic Gain control if (_shared->audio_processing()->gain_control()-> set_analog_level_limits(kMinVolumeLevel,kMaxVolumeLevel) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set AGC analog level for AP module"); return -1; } if (_shared->audio_processing()->gain_control()->set_mode( (GainControl::Mode) WEBRTC_VOICE_ENGINE_AGC_DEFAULT_MODE) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set AGC mode for AP module"); return -1; } if (_shared->audio_processing()->gain_control()->Enable( WEBRTC_VOICE_ENGINE_AGC_DEFAULT_STATE) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set AGC state for AP module"); return -1; } // VAD if (_shared->audio_processing()->voice_detection()->Enable( WEBRTC_VOICE_ENGINE_VAD_DEFAULT_STATE) != 0) { _shared->SetLastError(VE_APM_ERROR, kTraceError, "Init() failed to set VAD state for AP module"); return -1; } } // Set default AGC mode for the ADM #ifdef WEBRTC_VOICE_ENGINE_AGC bool enable(false); if (_shared->audio_processing()->gain_control()->mode() != GainControl::kFixedDigital) { enable = _shared->audio_processing()->gain_control()->is_enabled(); // Only set the AGC mode for the ADM when Adaptive AGC mode is selected if (_shared->audio_device()->SetAGC(enable) != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceError, "Init() failed to set default AGC mode in ADM 0"); } } #endif return _shared->statistics().SetInitialized(); } int VoEBaseImpl::Terminate() { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "Terminate()"); CriticalSectionScoped cs(_shared->crit_sec()); return TerminateInternal(); } int VoEBaseImpl::MaxNumOfChannels() { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "MaxNumOfChannels()"); WebRtc_Word32 maxNumOfChannels = _shared->channel_manager().MaxNumOfChannels(); WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "MaxNumOfChannels() => %d", maxNumOfChannels); return (maxNumOfChannels); } int VoEBaseImpl::CreateChannel() { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "CreateChannel()"); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } WebRtc_Word32 channelId = -1; if (!_shared->channel_manager().CreateChannel(channelId)) { _shared->SetLastError(VE_CHANNEL_NOT_CREATED, kTraceError, "CreateChannel() failed to allocate memory for channel"); return -1; } bool destroyChannel(false); { voe::ScopedChannel sc(_shared->channel_manager(), channelId); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_CREATED, kTraceError, "CreateChannel() failed to allocate memory for channel"); return -1; } else if (channelPtr->SetEngineInformation(_shared->statistics(), *_shared->output_mixer(), *_shared->transmit_mixer(), *_shared->process_thread(), *_shared->audio_device(), _voiceEngineObserverPtr, &_callbackCritSect) != 0) { destroyChannel = true; _shared->SetLastError(VE_CHANNEL_NOT_CREATED, kTraceError, "CreateChannel() failed to associate engine and channel." " Destroying channel."); } else if (channelPtr->Init() != 0) { destroyChannel = true; _shared->SetLastError(VE_CHANNEL_NOT_CREATED, kTraceError, "CreateChannel() failed to initialize channel. Destroying" " channel."); } } if (destroyChannel) { _shared->channel_manager().DestroyChannel(channelId); return -1; } WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "CreateChannel() => %d", channelId); return channelId; } int VoEBaseImpl::DeleteChannel(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeleteChannel(channel=%d)", channel); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } { voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeleteChannel() failed to locate channel"); return -1; } } if (_shared->channel_manager().DestroyChannel(channel) != 0) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeleteChannel() failed to destroy channel"); return -1; } if (StopSend() != 0) { return -1; } if (StopPlayout() != 0) { return -1; } return 0; } int VoEBaseImpl::SetLocalReceiver(int channel, int port, int RTCPport, const char ipAddr[64], const char multiCastAddr[64]) { // Inititialize local receive sockets (RTP and RTCP). // // The sockets are always first closed and then created again by this // function call. The created sockets are by default also used for // transmission (unless source port is set in SetSendDestination). // // Note that, sockets can also be created automatically if a user calls // SetSendDestination and StartSend without having called SetLocalReceiver // first. The sockets are then created at the first packet transmission. CriticalSectionScoped cs(_shared->crit_sec()); if (ipAddr == NULL && multiCastAddr == NULL) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetLocalReceiver(channel=%d, port=%d, RTCPport=%d)", channel, port, RTCPport); } else if (ipAddr != NULL && multiCastAddr == NULL) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetLocalReceiver(channel=%d, port=%d, RTCPport=%d, ipAddr=%s)", channel, port, RTCPport, ipAddr); } else if (ipAddr == NULL && multiCastAddr != NULL) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetLocalReceiver(channel=%d, port=%d, RTCPport=%d, " "multiCastAddr=%s)", channel, port, RTCPport, multiCastAddr); } else { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetLocalReceiver(channel=%d, port=%d, RTCPport=%d, " "ipAddr=%s, multiCastAddr=%s)", channel, port, RTCPport, ipAddr, multiCastAddr); } #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if ((port < 0) || (port > 65535)) { _shared->SetLastError(VE_INVALID_PORT_NMBR, kTraceError, "SetLocalReceiver() invalid RTP port"); return -1; } if (((RTCPport != kVoEDefault) && (RTCPport < 0)) || ((RTCPport != kVoEDefault) && (RTCPport > 65535))) { _shared->SetLastError(VE_INVALID_PORT_NMBR, kTraceError, "SetLocalReceiver() invalid RTCP port"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetLocalReceiver() failed to locate channel"); return -1; } // Cast RTCP port. In the RTP module 0 corresponds to RTP port + 1 in // the module, which is the default. WebRtc_UWord16 rtcpPortUW16(0); if (RTCPport != kVoEDefault) { rtcpPortUW16 = static_cast<WebRtc_UWord16> (RTCPport); } return channelPtr->SetLocalReceiver(port, rtcpPortUW16, ipAddr, multiCastAddr); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "SetLocalReceiver() VoE is built for external " "transport"); return -1; #endif } int VoEBaseImpl::GetLocalReceiver(int channel, int& port, int& RTCPport, char ipAddr[64]) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetLocalReceiver(channel=%d, ipAddr[]=?)", channel); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetLocalReceiver() failed to locate channel"); return -1; } WebRtc_Word32 ret = channelPtr->GetLocalReceiver(port, RTCPport, ipAddr); if (ipAddr != NULL) { WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetLocalReceiver() => port=%d, RTCPport=%d, ipAddr=%s", port, RTCPport, ipAddr); } else { WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetLocalReceiver() => port=%d, RTCPport=%d", port, RTCPport); } return ret; #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "SetLocalReceiver() VoE is built for external transport"); return -1; #endif } int VoEBaseImpl::SetSendDestination(int channel, int port, const char* ipaddr, int sourcePort, int RTCPport) { WEBRTC_TRACE( kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetSendDestination(channel=%d, port=%d, ipaddr=%s," "sourcePort=%d, RTCPport=%d)", channel, port, ipaddr, sourcePort, RTCPport); CriticalSectionScoped cs(_shared->crit_sec()); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetSendDestination() failed to locate channel"); return -1; } if ((port < 0) || (port > 65535)) { _shared->SetLastError(VE_INVALID_PORT_NMBR, kTraceError, "SetSendDestination() invalid RTP port"); return -1; } if (((RTCPport != kVoEDefault) && (RTCPport < 0)) || ((RTCPport != kVoEDefault) && (RTCPport > 65535))) { _shared->SetLastError(VE_INVALID_PORT_NMBR, kTraceError, "SetSendDestination() invalid RTCP port"); return -1; } if (((sourcePort != kVoEDefault) && (sourcePort < 0)) || ((sourcePort != kVoEDefault) && (sourcePort > 65535))) { _shared->SetLastError(VE_INVALID_PORT_NMBR, kTraceError, "SetSendDestination() invalid source port"); return -1; } // Cast RTCP port. In the RTP module 0 corresponds to RTP port + 1 in the // module, which is the default. WebRtc_UWord16 rtcpPortUW16(0); if (RTCPport != kVoEDefault) { rtcpPortUW16 = static_cast<WebRtc_UWord16> (RTCPport); WEBRTC_TRACE( kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), channel), "SetSendDestination() non default RTCP port %u will be " "utilized", rtcpPortUW16); } return channelPtr->SetSendDestination(port, ipaddr, sourcePort, rtcpPortUW16); #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "SetSendDestination() VoE is built for external transport"); return -1; #endif } int VoEBaseImpl::GetSendDestination(int channel, int& port, char ipAddr[64], int& sourcePort, int& RTCPport) { WEBRTC_TRACE( kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetSendDestination(channel=%d, ipAddr[]=?, sourcePort=?," "RTCPport=?)", channel); #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetSendDestination() failed to locate channel"); return -1; } WebRtc_Word32 ret = channelPtr->GetSendDestination(port, ipAddr, sourcePort, RTCPport); if (ipAddr != NULL) { WEBRTC_TRACE( kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetSendDestination() => port=%d, RTCPport=%d, ipAddr=%s, " "sourcePort=%d, RTCPport=%d", port, RTCPport, ipAddr, sourcePort, RTCPport); } else { WEBRTC_TRACE( kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetSendDestination() => port=%d, RTCPport=%d, " "sourcePort=%d, RTCPport=%d", port, RTCPport, sourcePort, RTCPport); } return ret; #else _shared->SetLastError(VE_EXTERNAL_TRANSPORT_ENABLED, kTraceWarning, "GetSendDestination() VoE is built for external transport"); return -1; #endif } int VoEBaseImpl::StartReceive(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "StartReceive(channel=%d)", channel); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "StartReceive() failed to locate channel"); return -1; } return channelPtr->StartReceiving(); } int VoEBaseImpl::StopReceive(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "StopListen(channel=%d)", channel); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetLocalReceiver() failed to locate channel"); return -1; } return channelPtr->StopReceiving(); } int VoEBaseImpl::StartPlayout(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "StartPlayout(channel=%d)", channel); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "StartPlayout() failed to locate channel"); return -1; } if (channelPtr->Playing()) { return 0; } if (StartPlayout() != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceError, "StartPlayout() failed to start playout"); return -1; } return channelPtr->StartPlayout(); } int VoEBaseImpl::StopPlayout(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "StopPlayout(channel=%d)", channel); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "StopPlayout() failed to locate channel"); return -1; } if (channelPtr->StopPlayout() != 0) { WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_shared->instance_id(), -1), "StopPlayout() failed to stop playout for channel %d", channel); } return StopPlayout(); } int VoEBaseImpl::StartSend(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "StartSend(channel=%d)", channel); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "StartSend() failed to locate channel"); return -1; } if (channelPtr->Sending()) { return 0; } #ifndef WEBRTC_EXTERNAL_TRANSPORT if (!channelPtr->ExternalTransport() && !channelPtr->SendSocketsInitialized()) { _shared->SetLastError(VE_DESTINATION_NOT_INITED, kTraceError, "StartSend() must set send destination first"); return -1; } #endif if (StartSend() != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceError, "StartSend() failed to start recording"); return -1; } return channelPtr->StartSend(); } int VoEBaseImpl::StopSend(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "StopSend(channel=%d)", channel); CriticalSectionScoped cs(_shared->crit_sec()); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "StopSend() failed to locate channel"); return -1; } if (channelPtr->StopSend() != 0) { WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_shared->instance_id(), -1), "StopSend() failed to stop sending for channel %d", channel); } return StopSend(); } #ifdef WEBRTC_VOE_EXTERNAL_REC_AND_PLAYOUT WebRtc_Word32 VoEBaseImpl::AddExternalRecAndPlayoutBuild(char* str) const { return sprintf(str, "External recording and playout build\n"); } #endif int VoEBaseImpl::GetVersion(char version[1024]) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetVersion(version=?)"); assert(kVoiceEngineVersionMaxMessageSize == 1024); if (version == NULL) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError); return (-1); } char versionBuf[kVoiceEngineVersionMaxMessageSize]; char* versionPtr = versionBuf; WebRtc_Word32 len = 0; WebRtc_Word32 accLen = 0; len = AddVoEVersion(versionPtr); if (len == -1) { return -1; } versionPtr += len; accLen += len; assert(accLen < kVoiceEngineVersionMaxMessageSize); len = AddBuildInfo(versionPtr); if (len == -1) { return -1; } versionPtr += len; accLen += len; assert(accLen < kVoiceEngineVersionMaxMessageSize); #ifdef WEBRTC_EXTERNAL_TRANSPORT len = AddExternalTransportBuild(versionPtr); if (len == -1) { return -1; } versionPtr += len; accLen += len; assert(accLen < kVoiceEngineVersionMaxMessageSize); #endif #ifdef WEBRTC_VOE_EXTERNAL_REC_AND_PLAYOUT len = AddExternalRecAndPlayoutBuild(versionPtr); if (len == -1) { return -1; } versionPtr += len; accLen += len; assert(accLen < kVoiceEngineVersionMaxMessageSize); #endif memcpy(version, versionBuf, accLen); version[accLen] = '\0'; // to avoid the truncation in the trace, split the string into parts char partOfVersion[256]; WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetVersion() =>"); for (int partStart = 0; partStart < accLen;) { memset(partOfVersion, 0, sizeof(partOfVersion)); int partEnd = partStart + 180; while (version[partEnd] != '\n' && version[partEnd] != '\0') { partEnd--; } if (partEnd < accLen) { memcpy(partOfVersion, &version[partStart], partEnd - partStart); } else { memcpy(partOfVersion, &version[partStart], accLen - partStart); } partStart = partEnd; WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "%s", partOfVersion); } return 0; } WebRtc_Word32 VoEBaseImpl::AddBuildInfo(char* str) const { return sprintf(str, "Build: svn:%s\n", BUILDINFO); } WebRtc_Word32 VoEBaseImpl::AddVoEVersion(char* str) const { return sprintf(str, "VoiceEngine 4.1.0\n"); } #ifdef WEBRTC_EXTERNAL_TRANSPORT WebRtc_Word32 VoEBaseImpl::AddExternalTransportBuild(char* str) const { return sprintf(str, "External transport build\n"); } #endif int VoEBaseImpl::LastError() { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "LastError()"); return (_shared->statistics().LastError()); } int VoEBaseImpl::SetNetEQPlayoutMode(int channel, NetEqModes mode) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetNetEQPlayoutMode(channel=%i, mode=%i)", channel, mode); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetNetEQPlayoutMode() failed to locate channel"); return -1; } return channelPtr->SetNetEQPlayoutMode(mode); } int VoEBaseImpl::GetNetEQPlayoutMode(int channel, NetEqModes& mode) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetNetEQPlayoutMode(channel=%i, mode=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetNetEQPlayoutMode() failed to locate channel"); return -1; } return channelPtr->GetNetEQPlayoutMode(mode); } int VoEBaseImpl::SetNetEQBGNMode(int channel, NetEqBgnModes mode) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetNetEQBGNMode(channel=%i, mode=%i)", channel, mode); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetNetEQBGNMode() failed to locate channel"); return -1; } return channelPtr->SetNetEQBGNMode(mode); } int VoEBaseImpl::GetNetEQBGNMode(int channel, NetEqBgnModes& mode) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetNetEQBGNMode(channel=%i, mode=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetNetEQBGNMode() failed to locate channel"); return -1; } return channelPtr->GetNetEQBGNMode(mode); } int VoEBaseImpl::SetOnHoldStatus(int channel, bool enable, OnHoldModes mode) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetOnHoldStatus(channel=%d, enable=%d, mode=%d)", channel, enable, mode); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetOnHoldStatus() failed to locate channel"); return -1; } return channelPtr->SetOnHoldStatus(enable, mode); } int VoEBaseImpl::GetOnHoldStatus(int channel, bool& enabled, OnHoldModes& mode) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetOnHoldStatus(channel=%d, enabled=?, mode=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetOnHoldStatus() failed to locate channel"); return -1; } return channelPtr->GetOnHoldStatus(enabled, mode); } WebRtc_Word32 VoEBaseImpl::StartPlayout() { WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::StartPlayout()"); if (_shared->audio_device()->Playing()) { return 0; } if (!_shared->ext_playout()) { if (_shared->audio_device()->InitPlayout() != 0) { WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_shared->instance_id(), -1), "StartPlayout() failed to initialize playout"); return -1; } if (_shared->audio_device()->StartPlayout() != 0) { WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_shared->instance_id(), -1), "StartPlayout() failed to start playout"); return -1; } } return 0; } WebRtc_Word32 VoEBaseImpl::StopPlayout() { WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::StopPlayout()"); WebRtc_Word32 numOfChannels = _shared->channel_manager().NumOfChannels(); if (numOfChannels <= 0) { return 0; } WebRtc_UWord16 nChannelsPlaying(0); WebRtc_Word32* channelsArray = new WebRtc_Word32[numOfChannels]; // Get number of playing channels _shared->channel_manager().GetChannelIds(channelsArray, numOfChannels); for (int i = 0; i < numOfChannels; i++) { voe::ScopedChannel sc(_shared->channel_manager(), channelsArray[i]); voe::Channel* chPtr = sc.ChannelPtr(); if (chPtr) { if (chPtr->Playing()) { nChannelsPlaying++; } } } delete[] channelsArray; // Stop audio-device playing if no channel is playing out if (nChannelsPlaying == 0) { if (_shared->audio_device()->StopPlayout() != 0) { _shared->SetLastError(VE_CANNOT_STOP_PLAYOUT, kTraceError, "StopPlayout() failed to stop playout"); return -1; } } return 0; } WebRtc_Word32 VoEBaseImpl::StartSend() { WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::StartSend()"); if (_shared->audio_device()->Recording()) { return 0; } if (!_shared->ext_recording()) { if (_shared->audio_device()->InitRecording() != 0) { WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_shared->instance_id(), -1), "StartSend() failed to initialize recording"); return -1; } if (_shared->audio_device()->StartRecording() != 0) { WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_shared->instance_id(), -1), "StartSend() failed to start recording"); return -1; } } return 0; } WebRtc_Word32 VoEBaseImpl::StopSend() { WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::StopSend()"); if (_shared->NumOfSendingChannels() == 0 && !_shared->transmit_mixer()->IsRecordingMic()) { // Stop audio-device recording if no channel is recording if (_shared->audio_device()->StopRecording() != 0) { _shared->SetLastError(VE_CANNOT_STOP_RECORDING, kTraceError, "StopSend() failed to stop recording"); return -1; } _shared->transmit_mixer()->StopSend(); } return 0; } WebRtc_Word32 VoEBaseImpl::TerminateInternal() { WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoEBaseImpl::TerminateInternal()"); // Delete any remaining channel objects WebRtc_Word32 numOfChannels = _shared->channel_manager().NumOfChannels(); if (numOfChannels > 0) { WebRtc_Word32* channelsArray = new WebRtc_Word32[numOfChannels]; _shared->channel_manager().GetChannelIds(channelsArray, numOfChannels); for (int i = 0; i < numOfChannels; i++) { DeleteChannel(channelsArray[i]); } delete[] channelsArray; } if (_shared->process_thread()) { if (_shared->audio_device()) { if (_shared->process_thread()-> DeRegisterModule(_shared->audio_device()) != 0) { _shared->SetLastError(VE_THREAD_ERROR, kTraceError, "TerminateInternal() failed to deregister ADM"); } } if (_shared->process_thread()->Stop() != 0) { _shared->SetLastError(VE_THREAD_ERROR, kTraceError, "TerminateInternal() failed to stop module process thread"); } } // Audio Device Module if (_shared->audio_device() != NULL) { if (_shared->audio_device()->StopPlayout() != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceWarning, "TerminateInternal() failed to stop playout"); } if (_shared->audio_device()->StopRecording() != 0) { _shared->SetLastError(VE_SOUNDCARD_ERROR, kTraceWarning, "TerminateInternal() failed to stop recording"); } if (_shared->audio_device()->RegisterEventObserver(NULL) != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceWarning, "TerminateInternal() failed to de-register event observer " "for the ADM"); } if (_shared->audio_device()->RegisterAudioCallback(NULL) != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceWarning, "TerminateInternal() failed to de-register audio callback " "for the ADM"); } if (_shared->audio_device()->Terminate() != 0) { _shared->SetLastError(VE_AUDIO_DEVICE_MODULE_ERROR, kTraceError, "TerminateInternal() failed to terminate the ADM"); } _shared->set_audio_device(NULL); } // AP module if (_shared->audio_processing() != NULL) { _shared->transmit_mixer()->SetAudioProcessingModule(NULL); _shared->set_audio_processing(NULL); } return _shared->statistics().SetUnInitialized(); } } // namespace webrtc
; A156894: a(n) = Sum_{k=0..n} binomial(n,k)*binomial(2*n+k-1,k). ; Submitted by Simon Strandgaard ; 1,3,19,138,1059,8378,67582,552576,4563235,37972290,317894394,2674398268,22590697614,191475925332,1627653567916,13870754053388,118464647799075,1013709715774130,8689197042438274,74594573994750972,641252293546113434,5519339268476249676,47558930664216470628,410223801143351443568,3541733105816766128014,30604410007943425664628,264664847197180564798852,2290481204378617035843096,19835921465506306354705212,171890778759671214997185016,1490420420349514966580489832,12930171894390234413046221988 mov $1,1 mov $2,1 mov $3,$0 mul $0,2 sub $0,1 mov $4,2 lpb $3 add $0,1 mul $1,$3 mul $1,$0 sub $3,1 sub $5,1 add $5,$4 div $1,$5 add $2,$1 add $4,2 lpe mov $0,$2
; A065234: Fill a triangular array by rows by writing numbers 1 up to b(0), 1 up to b(1), etc., where b(n) are the decagonal numbers. The first elements of the rows form a(n). ; 1,1,3,6,10,5,11,18,26,8,18,29,41,2,16,31,47,64,82,16,36,57,79,102,126,25,51,78,106,135,165,21,53,86,120,155,191,228,34,73,113,154,196,239,283,31,77,124,172,221,271,322,4,57,111,166,222,279,337,396,5,66,128 lpb $0 add $2,$0 sub $0,1 lpe mov $1,1 lpb $2 add $3,$1 add $1,8 sub $2,$3 lpe mov $0,$2 add $0,1
; A268527: a(n) = r*a(ceiling(n/2))+s*a(floor(n/2)) with a(1)=1 and (r,s)=(4,1). ; 1,5,21,25,89,105,121,125,381,445,509,525,589,605,621,625,1649,1905,2161,2225,2481,2545,2609,2625,2881,2945,3009,3025,3089,3105,3121,3125,7221,8245,9269,9525,10549,10805,11061,11125,12149,12405,12661,12725,12981,13045,13109,13125,14149,14405 mov $7,$0 add $7,1 lpb $7 clr $0,5 sub $7,1 sub $0,$7 mul $0,2 cal $0,309074 ; a(0) = 1; a(2*n) = 4*a(n), a(2*n+1) = a(n). add $0,1 add $3,2 mul $3,10 add $2,$3 add $0,$2 mov $1,$0 sub $1,22 div $1,3 mul $1,3 add $1,1 add $6,$1 lpe mov $1,$6
; A036234: Number of primes <= n, if 1 is counted as a prime. ; 1,2,3,3,4,4,5,5,5,5,6,6,7,7,7,7,8,8,9,9,9,9,10,10,10,10,10,10,11,11,12,12,12,12,12,12,13,13,13,13,14,14,15,15,15,15,16,16,16,16,16,16,17,17,17,17,17,17,18,18,19,19,19,19,19,19,20,20,20,20,21,21,22,22,22,22,22,22,23,23,23,23,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26 mov $1,$0 seq $1,62298 ; Number of nonprimes <= n. sub $1,2 sub $0,$1
/* Copyright 2019 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "legion.h" #include "legion/runtime.h" #include "legion/legion_ops.h" #include "legion/legion_tasks.h" #include "legion/legion_context.h" #include "legion/legion_profiling.h" #include "legion/legion_allocation.h" namespace Legion { #ifndef DISABLE_PARTITION_SHIM namespace PartitionShim { template<int COLOR_DIM> /*static*/ TaskID ColorPoints<COLOR_DIM>::TASK_ID; template<int COLOR_DIM, int RANGE_DIM> /*static*/ TaskID ColorRects<COLOR_DIM,RANGE_DIM>::TASK_ID; //-------------------------------------------------------------------------- template<int CDIM> ColorPoints<CDIM>::ColorPoints(const Coloring &coloring, LogicalRegion region, FieldID color_field, FieldID pointer_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, pointer_field); // Serialize the coloring into the argument buffer assert(CDIM == 1); rez.serialize<size_t>(coloring.size()); for (Coloring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = DomainPoint(cit->first); rez.serialize(color); rez.serialize<size_t>(cit->second.points.size()); for (std::set<ptr_t>::const_iterator it = cit->second.points.begin(); it != cit->second.points.end(); it++) { const Point<1,coord_t> point = it->value; rez.serialize(point); } // No need to do ranges since we know that they are all empty } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM> ColorPoints<CDIM>::ColorPoints(const PointColoring &coloring, LogicalRegion region, FieldID color_field, FieldID pointer_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, pointer_field); // Serialize the coloring into the argument buffer rez.serialize<size_t>(coloring.size()); for (PointColoring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = cit->first; rez.serialize(color); rez.serialize<size_t>(cit->second.points.size()); for (std::set<ptr_t>::const_iterator it = cit->second.points.begin(); it != cit->second.points.end(); it++) { const Point<1,coord_t> point = it->value; rez.serialize(point); } // No need to do any ranges since we know they are all empty } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM> /*static*/ void ColorPoints<CDIM>::register_task(void) //-------------------------------------------------------------------------- { TASK_ID = Legion::Runtime::generate_static_task_id(); char variant_name[128]; snprintf(variant_name,128,"Color Points <%d>", CDIM); TaskVariantRegistrar registrar(TASK_ID, variant_name); registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); registrar.set_leaf(); Legion::Runtime::preregister_task_variant< ColorPoints<CDIM>::cpu_variant>(registrar, variant_name); } //-------------------------------------------------------------------------- template<int CDIM> /*static*/ void ColorPoints<CDIM>::cpu_variant(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) //-------------------------------------------------------------------------- { const FieldAccessor<WRITE_DISCARD,Point<CDIM,coord_t>,1,coord_t> fa_color(regions[0], task->regions[0].instance_fields[0]); const FieldAccessor<WRITE_DISCARD,Point<1,coord_t>,1,coord_t> fa_point(regions[0], task->regions[0].instance_fields[1]); Deserializer derez(task->args, task->arglen); size_t num_colors; derez.deserialize(num_colors); coord_t next_entry = 0; for (unsigned cidx = 0; cidx < num_colors; cidx++) { Point<CDIM,coord_t> color; derez.deserialize(color); size_t num_points; derez.deserialize(num_points); for (unsigned idx = 0; idx < num_points; idx++, next_entry++) { Point<1,coord_t> point; derez.deserialize(point); fa_color.write(next_entry, color); fa_point.write(next_entry, point); } } } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> ColorRects<CDIM,RDIM>::ColorRects(const DomainColoring &coloring, LogicalRegion region, FieldID color_field, FieldID range_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, range_field); // Serialize the coloring into the argument buffer assert(CDIM == 1); rez.serialize<size_t>(coloring.size()); for (DomainColoring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = DomainPoint(cit->first); rez.serialize(color); rez.serialize<size_t>(1); // number of rects const Rect<RDIM,coord_t> rect = cit->second; rez.serialize(rect); } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> ColorRects<CDIM,RDIM>::ColorRects(const MultiDomainColoring &coloring, LogicalRegion region, FieldID color_field, FieldID range_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, range_field); // Serialize the coloring into the argument buffer assert(CDIM == 1); rez.serialize<size_t>(coloring.size()); for (MultiDomainColoring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = DomainPoint(cit->first); rez.serialize(color); rez.serialize<size_t>(cit->second.size()); for (std::set<Domain>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) { const Rect<RDIM,coord_t> rect = *it; rez.serialize(rect); } } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> ColorRects<CDIM,RDIM>::ColorRects(const DomainPointColoring &coloring, LogicalRegion region, FieldID color_field, FieldID range_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, range_field); // Serialize the coloring into the argument buffer rez.serialize<size_t>(coloring.size()); for (DomainPointColoring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = cit->first; rez.serialize(color); rez.serialize<size_t>(1); // number of rects const Rect<RDIM,coord_t> rect = cit->second; rez.serialize(rect); } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> ColorRects<CDIM,RDIM>::ColorRects(const MultiDomainPointColoring &coloring, LogicalRegion region, FieldID color_field, FieldID range_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, range_field); // Serialize the coloring into the argument buffer rez.serialize<size_t>(coloring.size()); for (MultiDomainPointColoring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = cit->first; rez.serialize(color); rez.serialize<size_t>(cit->second.size()); for (std::set<Domain>::const_iterator it = cit->second.begin(); it != cit->second.end(); it++) { const Rect<RDIM,coord_t> rect = *it; rez.serialize(rect); } } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> ColorRects<CDIM,RDIM>::ColorRects(const Coloring &coloring, LogicalRegion region, FieldID color_field, FieldID range_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, range_field); rez.serialize<size_t>(coloring.size()); for (Coloring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = DomainPoint(cit->first); rez.serialize(color); // Count how many rectangles there will be size_t total_rects = cit->second.points.size(); for (std::set<std::pair<ptr_t,ptr_t> >::const_iterator it = cit->second.ranges.begin(); it != cit->second.ranges.end(); it++) { // Skip empty ranges if (it->first.value > it->second.value) continue; total_rects++; } rez.serialize(total_rects); for (std::set<ptr_t>::const_iterator it = cit->second.points.begin(); it != cit->second.points.end(); it++) { const Point<1,coord_t> point(*it); const Rect<1,coord_t> rect(point, point); rez.serialize(rect); } for (std::set<std::pair<ptr_t,ptr_t> >::const_iterator it = cit->second.ranges.begin(); it != cit->second.ranges.end(); it++) { // Skip empty ranges if (it->first.value > it->second.value) continue; const Point<1,coord_t> lo(it->first.value); const Point<1,coord_t> hi(it->second.value); const Rect<1,coord_t> rect(lo, hi); rez.serialize(rect); } } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> ColorRects<CDIM,RDIM>::ColorRects(const PointColoring &coloring, LogicalRegion region, FieldID color_field, FieldID range_field) : TaskLauncher(TASK_ID, TaskArgument(), Predicate::TRUE_PRED, PARTITION_SHIM_MAPPER_ID) //-------------------------------------------------------------------------- { add_region_requirement( RegionRequirement(region, WRITE_DISCARD, EXCLUSIVE, region)); add_field(0/*index*/, color_field); add_field(0/*index*/, range_field); rez.serialize<size_t>(coloring.size()); for (PointColoring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { const Point<CDIM,coord_t> color = cit->first; rez.serialize(color); // Count how many rectangles there will be size_t total_rects = cit->second.points.size(); for (std::set<std::pair<ptr_t,ptr_t> >::const_iterator it = cit->second.ranges.begin(); it != cit->second.ranges.end(); it++) { // Skip empty ranges if (it->first.value > it->second.value) continue; total_rects++; } rez.serialize(total_rects); for (std::set<ptr_t>::const_iterator it = cit->second.points.begin(); it != cit->second.points.end(); it++) { const Point<1,coord_t> point(*it); const Rect<1,coord_t> rect(point, point); rez.serialize(rect); } for (std::set<std::pair<ptr_t,ptr_t> >::const_iterator it = cit->second.ranges.begin(); it != cit->second.ranges.end(); it++) { // Skip empty ranges if (it->first.value > it->second.value) continue; const Point<1,coord_t> lo(it->first.value); const Point<1,coord_t> hi(it->second.value); const Rect<1,coord_t> rect(lo, hi); rez.serialize(rect); } } argument = TaskArgument(rez.get_buffer(), rez.get_used_bytes()); } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> /*static*/ void ColorRects<CDIM,RDIM>::register_task(void) //-------------------------------------------------------------------------- { TASK_ID = Legion::Runtime::generate_static_task_id(); char variant_name[128]; snprintf(variant_name,128,"Color Rects <%d,%d>", CDIM, RDIM); TaskVariantRegistrar registrar(TASK_ID, variant_name); registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); registrar.set_leaf(); Legion::Runtime::preregister_task_variant< ColorRects<CDIM,RDIM>::cpu_variant>(registrar, variant_name); } //-------------------------------------------------------------------------- template<int CDIM, int RDIM> /*static*/ void ColorRects<CDIM,RDIM>::cpu_variant(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) //-------------------------------------------------------------------------- { const FieldAccessor<WRITE_DISCARD,Point<CDIM,coord_t>,1,coord_t> fa_color(regions[0], task->regions[0].instance_fields[0]); const FieldAccessor<WRITE_DISCARD,Rect<RDIM,coord_t>,1,coord_t> fa_range(regions[0], task->regions[0].instance_fields[1]); Deserializer derez(task->args, task->arglen); size_t num_colors; derez.deserialize(num_colors); coord_t next_entry = 0; for (unsigned cidx = 0; cidx < num_colors; cidx++) { Point<CDIM,coord_t> color; derez.deserialize(color); size_t num_ranges; derez.deserialize(num_ranges); for (unsigned idx = 0; idx < num_ranges; idx++, next_entry++) { Rect<RDIM,coord_t> range; derez.deserialize(range); fa_color.write(next_entry, color); fa_range.write(next_entry, range); } } } // Do the explicit instantiation #define DIMFUNC(DIM) \ template class ColorPoints<DIM>; LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC #define DIMFUNC(D1,D2) \ template class ColorRects<D1,D2>; LEGION_FOREACH_NN(DIMFUNC) #undef DIMFUNC }; #endif // DISABLE_PARTITION_SHIM namespace Internal { LEGION_EXTERN_LOGGER_DECLARATIONS }; const LogicalRegion LogicalRegion::NO_REGION = LogicalRegion(); const LogicalPartition LogicalPartition::NO_PART = LogicalPartition(); const Domain Domain::NO_DOMAIN = Domain(); // Cache static type tags so we don't need to recompute them all the time #define DIMFUNC(DIM) \ static const TypeTag TYPE_TAG_##DIM##D = \ Internal::NT_TemplateHelper::encode_tag<DIM,coord_t>(); LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC ///////////////////////////////////////////////////////////// // Mappable ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Mappable::Mappable(void) : map_id(0), tag(0), mapper_data(NULL), mapper_data_size(0) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Task ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Task::Task(void) : Mappable(), args(NULL), arglen(0), local_args(NULL), local_arglen(0), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Copy ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Copy::Copy(void) : Mappable(), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Inline Mapping ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InlineMapping::InlineMapping(void) : Mappable(), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Acquire ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Acquire::Acquire(void) : Mappable(), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Release ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Release::Release(void) : Mappable(), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Close ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Close::Close(void) : Mappable(), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Fill ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Fill::Fill(void) : Mappable(), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Partition ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Partition::Partition(void) : Mappable(), parent_task(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // IndexSpace ///////////////////////////////////////////////////////////// /*static*/ const IndexSpace IndexSpace::NO_SPACE = IndexSpace(); //-------------------------------------------------------------------------- IndexSpace::IndexSpace(IndexSpaceID _id, IndexTreeID _tid, TypeTag _tag) : id(_id), tid(_tid), type_tag(_tag) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexSpace::IndexSpace(void) : id(0), tid(0), type_tag(0) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexSpace::IndexSpace(const IndexSpace &rhs) : id(rhs.id), tid(rhs.tid), type_tag(rhs.type_tag) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // IndexPartition ///////////////////////////////////////////////////////////// /*static*/ const IndexPartition IndexPartition::NO_PART = IndexPartition(); //-------------------------------------------------------------------------- IndexPartition::IndexPartition(IndexPartitionID _id, IndexTreeID _tid, TypeTag _tag) : id(_id), tid(_tid), type_tag(_tag) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexPartition::IndexPartition(void) : id(0), tid(0), type_tag(0) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexPartition::IndexPartition(const IndexPartition &rhs) : id(rhs.id), tid(rhs.tid), type_tag(rhs.type_tag) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // FieldSpace ///////////////////////////////////////////////////////////// /*static*/ const FieldSpace FieldSpace::NO_SPACE = FieldSpace(0); //-------------------------------------------------------------------------- FieldSpace::FieldSpace(unsigned _id) : id(_id) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FieldSpace::FieldSpace(void) : id(0) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FieldSpace::FieldSpace(const FieldSpace &rhs) : id(rhs.id) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Logical Region ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalRegion::LogicalRegion(RegionTreeID tid, IndexSpace index, FieldSpace field) : tree_id(tid), index_space(index), field_space(field) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalRegion::LogicalRegion(void) : tree_id(0), index_space(IndexSpace::NO_SPACE), field_space(FieldSpace::NO_SPACE) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalRegion::LogicalRegion(const LogicalRegion &rhs) : tree_id(rhs.tree_id), index_space(rhs.index_space), field_space(rhs.field_space) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Logical Partition ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LogicalPartition::LogicalPartition(RegionTreeID tid, IndexPartition pid, FieldSpace field) : tree_id(tid), index_partition(pid), field_space(field) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalPartition::LogicalPartition(void) : tree_id(0), index_partition(IndexPartition::NO_PART), field_space(FieldSpace::NO_SPACE) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LogicalPartition::LogicalPartition(const LogicalPartition &rhs) : tree_id(rhs.tree_id), index_partition(rhs.index_partition), field_space(rhs.field_space) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Argument Map ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ArgumentMap::ArgumentMap(void) //-------------------------------------------------------------------------- { impl = new Internal::ArgumentMapImpl(); #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->add_reference(); } //-------------------------------------------------------------------------- ArgumentMap::ArgumentMap(const FutureMap &rhs) //-------------------------------------------------------------------------- { impl = new Internal::ArgumentMapImpl(rhs); #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->add_reference(); } //-------------------------------------------------------------------------- ArgumentMap::ArgumentMap(const ArgumentMap &rhs) : impl(rhs.impl) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- ArgumentMap::ArgumentMap(Internal::ArgumentMapImpl *i) : impl(i) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- ArgumentMap::~ArgumentMap(void) //-------------------------------------------------------------------------- { if (impl != NULL) { // Remove our reference and if we were the // last reference holder, then delete it if (impl->remove_reference()) { delete impl; } impl = NULL; } } //-------------------------------------------------------------------------- ArgumentMap& ArgumentMap::operator=(const FutureMap &rhs) //-------------------------------------------------------------------------- { // Check to see if our current impl is not NULL, // if so remove our reference if (impl != NULL) { if (impl->remove_reference()) { delete impl; } } impl = new Internal::ArgumentMapImpl(rhs); impl->add_reference(); return *this; } //-------------------------------------------------------------------------- ArgumentMap& ArgumentMap::operator=(const ArgumentMap &rhs) //-------------------------------------------------------------------------- { // Check to see if our current impl is not NULL, // if so remove our reference if (impl != NULL) { if (impl->remove_reference()) { delete impl; } } impl = rhs.impl; // Add our reference to the new impl if (impl != NULL) { impl->add_reference(); } return *this; } //-------------------------------------------------------------------------- bool ArgumentMap::has_point(const DomainPoint &point) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->has_point(point); } //-------------------------------------------------------------------------- void ArgumentMap::set_point(const DomainPoint &point, const TaskArgument &arg, bool replace/*= true*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->set_point(point, arg, replace); } //-------------------------------------------------------------------------- void ArgumentMap::set_point(const DomainPoint &point, const Future &f, bool replace/*= true*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->set_point(point, f, replace); } //-------------------------------------------------------------------------- bool ArgumentMap::remove_point(const DomainPoint &point) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->remove_point(point); } //-------------------------------------------------------------------------- TaskArgument ArgumentMap::get_point(const DomainPoint &point) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->get_point(point); } ///////////////////////////////////////////////////////////// // Predicate ///////////////////////////////////////////////////////////// const Predicate Predicate::TRUE_PRED = Predicate(true); const Predicate Predicate::FALSE_PRED = Predicate(false); //-------------------------------------------------------------------------- Predicate::Predicate(void) : impl(NULL), const_value(true) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- Predicate::Predicate(const Predicate &p) //-------------------------------------------------------------------------- { const_value = p.const_value; impl = p.impl; if (impl != NULL) impl->add_predicate_reference(); } //-------------------------------------------------------------------------- Predicate::Predicate(bool value) : impl(NULL), const_value(value) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- Predicate::Predicate(Internal::PredicateImpl *i) : impl(i) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_predicate_reference(); } //-------------------------------------------------------------------------- Predicate::~Predicate(void) //-------------------------------------------------------------------------- { if (impl != NULL) { impl->remove_predicate_reference(); impl = NULL; } } //-------------------------------------------------------------------------- Predicate& Predicate::operator=(const Predicate &rhs) //-------------------------------------------------------------------------- { if (impl != NULL) impl->remove_predicate_reference(); const_value = rhs.const_value; impl = rhs.impl; if (impl != NULL) impl->add_predicate_reference(); return *this; } ///////////////////////////////////////////////////////////// // Lock ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Lock::Lock(void) : reservation_lock(Reservation::NO_RESERVATION) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- Lock::Lock(Reservation r) : reservation_lock(r) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- bool Lock::operator<(const Lock &rhs) const //-------------------------------------------------------------------------- { return (reservation_lock < rhs.reservation_lock); } //-------------------------------------------------------------------------- bool Lock::operator==(const Lock &rhs) const //-------------------------------------------------------------------------- { return (reservation_lock == rhs.reservation_lock); } //-------------------------------------------------------------------------- void Lock::acquire(unsigned mode /*=0*/, bool exclusive /*=true*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(reservation_lock.exists()); #endif Internal::ApEvent lock_event(reservation_lock.acquire(mode,exclusive)); lock_event.wait(); } //-------------------------------------------------------------------------- void Lock::release(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(reservation_lock.exists()); #endif reservation_lock.release(); } ///////////////////////////////////////////////////////////// // Lock Request ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LockRequest::LockRequest(Lock l, unsigned m, bool excl) : lock(l), mode(m), exclusive(excl) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // Grant ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Grant::Grant(void) : impl(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- Grant::Grant(Internal::GrantImpl *i) : impl(i) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- Grant::Grant(const Grant &rhs) : impl(rhs.impl) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- Grant::~Grant(void) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_reference()) delete impl; impl = NULL; } } //-------------------------------------------------------------------------- Grant& Grant::operator=(const Grant &rhs) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_reference()) delete impl; } impl = rhs.impl; if (impl != NULL) impl->add_reference(); return *this; } ///////////////////////////////////////////////////////////// // Phase Barrier ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PhaseBarrier::PhaseBarrier(void) : phase_barrier(Internal::ApBarrier::NO_AP_BARRIER) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhaseBarrier::PhaseBarrier(Internal::ApBarrier b) : phase_barrier(b) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- bool PhaseBarrier::operator<(const PhaseBarrier &rhs) const //-------------------------------------------------------------------------- { return (phase_barrier < rhs.phase_barrier); } //-------------------------------------------------------------------------- bool PhaseBarrier::operator==(const PhaseBarrier &rhs) const //-------------------------------------------------------------------------- { return (phase_barrier == rhs.phase_barrier); } //-------------------------------------------------------------------------- bool PhaseBarrier::operator!=(const PhaseBarrier &rhs) const //-------------------------------------------------------------------------- { return (phase_barrier != rhs.phase_barrier); } //-------------------------------------------------------------------------- void PhaseBarrier::arrive(unsigned count /*=1*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(phase_barrier.exists()); #endif Internal::Runtime::phase_barrier_arrive(*this, count); } //-------------------------------------------------------------------------- void PhaseBarrier::wait(void) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(phase_barrier.exists()); #endif Internal::ApEvent e = Internal::Runtime::get_previous_phase(*this); e.wait(); } //-------------------------------------------------------------------------- void PhaseBarrier::alter_arrival_count(int delta) //-------------------------------------------------------------------------- { Internal::Runtime::alter_arrival_count(*this, delta); } //-------------------------------------------------------------------------- bool PhaseBarrier::exists(void) const //-------------------------------------------------------------------------- { return phase_barrier.exists(); } ///////////////////////////////////////////////////////////// // Dynamic Collective ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- DynamicCollective::DynamicCollective(void) : PhaseBarrier(), redop(0) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- DynamicCollective::DynamicCollective(Internal::ApBarrier b, ReductionOpID r) : PhaseBarrier(b), redop(r) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- void DynamicCollective::arrive(const void *value, size_t size, unsigned count /*=1*/) //-------------------------------------------------------------------------- { Internal::Runtime::phase_barrier_arrive(*this, count, Internal::ApEvent::NO_AP_EVENT, value, size); } ///////////////////////////////////////////////////////////// // Region Requirement ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(void) : region(LogicalRegion::NO_REGION), partition(LogicalPartition::NO_PART), privilege(NO_ACCESS), prop(EXCLUSIVE), parent(LogicalRegion::NO_REGION), redop(0), tag(0), flags(NO_FLAG), handle_type(SINGULAR), projection(0), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, const std::set<FieldID> &priv_fields, const std::vector<FieldID> &inst_fields, PrivilegeMode _priv, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(_priv), prop(_prop), parent(_parent), redop(0), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(SINGULAR), projection(0), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { privilege_fields = priv_fields; instance_fields = inst_fields; // For backwards compatibility with the old encoding if (privilege == WRITE_PRIV) privilege = WRITE_DISCARD; #ifdef DEBUG_LEGION if (IS_REDUCE(*this)) // Shouldn't use this constructor for reductions REPORT_LEGION_ERROR(ERROR_USE_REDUCTION_REGION_REQ, "Use different RegionRequirement " "constructor for reductions"); #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalPartition pid, ProjectionID _proj, const std::set<FieldID> &priv_fields, const std::vector<FieldID> &inst_fields, PrivilegeMode _priv, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : partition(pid), privilege(_priv), prop(_prop), parent(_parent), redop(0), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(PART_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { privilege_fields = priv_fields; instance_fields = inst_fields; // For backwards compatibility with the old encoding if (privilege == WRITE_PRIV) privilege = WRITE_DISCARD; #ifdef DEBUG_LEGION if (IS_REDUCE(*this)) REPORT_LEGION_ERROR(ERROR_USE_REDUCTION_REGION_REQ, "Use different RegionRequirement " "constructor for reductions"); #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, ProjectionID _proj, const std::set<FieldID> &priv_fields, const std::vector<FieldID> &inst_fields, PrivilegeMode _priv, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(_priv), prop(_prop), parent(_parent), redop(0), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(REG_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { privilege_fields = priv_fields; instance_fields = inst_fields; // For backwards compatibility with the old encoding if (privilege == WRITE_PRIV) privilege = WRITE_DISCARD; #ifdef DEBUG_LEGION if (IS_REDUCE(*this)) REPORT_LEGION_ERROR(ERROR_USE_REDUCTION_REGION_REQ, "Use different RegionRequirement " "constructor for reductions") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, const std::set<FieldID> &priv_fields, const std::vector<FieldID> &inst_fields, ReductionOpID op, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(REDUCE), prop(_prop), parent(_parent), redop(op), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(SINGULAR), projection(0), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { privilege_fields = priv_fields; instance_fields = inst_fields; #ifdef DEBUG_LEGION if (redop == 0) REPORT_LEGION_ERROR(ERROR_RESERVED_REDOP_ID, "Zero is not a valid ReductionOpID") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalPartition pid, ProjectionID _proj, const std::set<FieldID> &priv_fields, const std::vector<FieldID> &inst_fields, ReductionOpID op, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : partition(pid), privilege(REDUCE), prop(_prop), parent(_parent), redop(op), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(PART_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { privilege_fields = priv_fields; instance_fields = inst_fields; #ifdef DEBUG_LEGION if (redop == 0) REPORT_LEGION_ERROR(ERROR_RESERVED_REDOP_ID, "Zero is not a valid ReductionOpID") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, ProjectionID _proj, const std::set<FieldID> &priv_fields, const std::vector<FieldID> &inst_fields, ReductionOpID op, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(REDUCE), prop(_prop), parent(_parent), redop(op), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(REG_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { privilege_fields = priv_fields; instance_fields = inst_fields; #ifdef DEBUG_LEGION if (redop == 0) REPORT_LEGION_ERROR(ERROR_RESERVED_REDOP_ID, "Zero is not a valid ReductionOpID") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, PrivilegeMode _priv, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(_priv), prop(_prop), parent(_parent), redop(0), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(SINGULAR), projection(), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { // For backwards compatibility with the old encoding if (privilege == WRITE_PRIV) privilege = WRITE_DISCARD; #ifdef DEBUG_LEGION if (IS_REDUCE(*this)) // Shouldn't use this constructor for reductions REPORT_LEGION_ERROR(ERROR_USE_REDUCTION_REGION_REQ, "Use different RegionRequirement " "constructor for reductions") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalPartition pid, ProjectionID _proj, PrivilegeMode _priv, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : partition(pid), privilege(_priv), prop(_prop), parent(_parent), redop(0), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(PART_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { // For backwards compatibility with the old encoding if (privilege == WRITE_PRIV) privilege = WRITE_DISCARD; #ifdef DEBUG_LEGION if (IS_REDUCE(*this)) REPORT_LEGION_ERROR(ERROR_USE_REDUCTION_REGION_REQ, "Use different RegionRequirement " "constructor for reductions") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, ProjectionID _proj, PrivilegeMode _priv, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(_priv), prop(_prop), parent(_parent), redop(0), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(REG_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { // For backwards compatibility with the old encoding if (privilege == WRITE_PRIV) privilege = WRITE_DISCARD; #ifdef DEBUG_LEGION if (IS_REDUCE(*this)) REPORT_LEGION_ERROR(ERROR_USE_REDUCTION_REGION_REQ, "Use different RegionRequirement " "constructor for reductions") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, ReductionOpID op, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(REDUCE), prop(_prop), parent(_parent), redop(op), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(SINGULAR), projection(0), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION if (redop == 0) REPORT_LEGION_ERROR(ERROR_RESERVED_REDOP_ID, "Zero is not a valid ReductionOpID") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalPartition pid, ProjectionID _proj, ReductionOpID op, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : partition(pid), privilege(REDUCE), prop(_prop), parent(_parent), redop(op), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(PART_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION if (redop == 0) REPORT_LEGION_ERROR(ERROR_RESERVED_REDOP_ID, "Zero is not a valid ReductionOpID") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(LogicalRegion _handle, ProjectionID _proj, ReductionOpID op, CoherenceProperty _prop, LogicalRegion _parent, MappingTagID _tag, bool _verified) : region(_handle), privilege(REDUCE), prop(_prop), parent(_parent), redop(op), tag(_tag), flags(_verified ? VERIFIED_FLAG : NO_FLAG), handle_type(REG_PROJECTION), projection(_proj), projection_args(NULL), projection_args_size(0) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION if (redop == 0) REPORT_LEGION_ERROR(ERROR_RESERVED_REDOP_ID, "Zero is not a valid ReductionOpID") #endif } //-------------------------------------------------------------------------- RegionRequirement::RegionRequirement(const RegionRequirement &rhs) : region(rhs.region), partition(rhs.partition), privilege_fields(rhs.privilege_fields), instance_fields(rhs.instance_fields), privilege(rhs.privilege), prop(rhs.prop), parent(rhs.parent), redop(rhs.redop), tag(rhs.tag), flags(rhs.flags), handle_type(rhs.handle_type), projection(rhs.projection), projection_args(NULL), projection_args_size(rhs.projection_args_size) //-------------------------------------------------------------------------- { if (projection_args_size > 0) { projection_args = malloc(projection_args_size); memcpy(projection_args, rhs.projection_args, projection_args_size); } } //-------------------------------------------------------------------------- RegionRequirement::~RegionRequirement(void) //-------------------------------------------------------------------------- { if (projection_args_size > 0) free(projection_args); } //-------------------------------------------------------------------------- RegionRequirement& RegionRequirement::operator=( const RegionRequirement &rhs) //-------------------------------------------------------------------------- { region = rhs.region; partition = rhs.partition; privilege_fields = rhs.privilege_fields; instance_fields = rhs.instance_fields; privilege = rhs.privilege; prop = rhs.prop; parent = rhs.parent; redop = rhs.redop; tag = rhs.tag; flags = rhs.flags; handle_type = rhs.handle_type; projection = rhs.projection; projection_args_size = rhs.projection_args_size; if (projection_args != NULL) { free(projection_args); projection_args = NULL; } if (projection_args_size > 0) { projection_args = malloc(projection_args_size); memcpy(projection_args, rhs.projection_args, projection_args_size); } return *this; } //-------------------------------------------------------------------------- bool RegionRequirement::operator==(const RegionRequirement &rhs) const //-------------------------------------------------------------------------- { if ((handle_type == rhs.handle_type) && (privilege == rhs.privilege) && (prop == rhs.prop) && (parent == rhs.parent) && (redop == rhs.redop) && (tag == rhs.tag) && (flags == rhs.flags)) { if (((handle_type == SINGULAR) && (region == rhs.region)) || ((handle_type == PART_PROJECTION) && (partition == rhs.partition) && (projection == rhs.projection)) || ((handle_type == REG_PROJECTION) && (region == rhs.region))) { if ((privilege_fields.size() == rhs.privilege_fields.size()) && (instance_fields.size() == rhs.instance_fields.size())) { if (projection_args_size == rhs.projection_args_size) { if ((projection_args_size == 0) || (memcmp(projection_args, rhs.projection_args, projection_args_size) == 0)) { return ((privilege_fields == rhs.privilege_fields) && (instance_fields == rhs.instance_fields)); } } } } } return false; } //-------------------------------------------------------------------------- bool RegionRequirement::operator<(const RegionRequirement &rhs) const //-------------------------------------------------------------------------- { if (handle_type < rhs.handle_type) return true; else if (handle_type > rhs.handle_type) return false; else { if (privilege < rhs.privilege) return true; else if (privilege > rhs.privilege) return false; else { if (prop < rhs.prop) return true; else if (prop > rhs.prop) return false; else { if (parent < rhs.parent) return true; else if (!(parent == rhs.parent)) // therefore greater than return false; else { if (redop < rhs.redop) return true; else if (redop > rhs.redop) return false; else { if (tag < rhs.tag) return true; else if (tag > rhs.tag) return false; else { if (flags < rhs.flags) return true; else if (flags > rhs.flags) return false; else { if (privilege_fields < rhs.privilege_fields) return true; else if (privilege_fields > rhs.privilege_fields) return false; else { if (instance_fields < rhs.instance_fields) return true; else if (instance_fields > rhs.instance_fields) return false; else { if (handle_type == SINGULAR) return (region < rhs.region); else if (projection_args_size < rhs.projection_args_size) return true; else if (projection_args_size > rhs.projection_args_size) return false; else if ((projection_args_size > 0) && (memcmp(projection_args, rhs.projection_args, projection_args_size) < 0)) return true; else if ((projection_args_size > 0) && (memcmp(projection_args, rhs.projection_args, projection_args_size) > 0)) return false; else if (handle_type == PART_PROJECTION) { if (partition < rhs.partition) return true; // therefore greater than else if (partition != rhs.partition) return false; else return (projection < rhs.projection); } else { if (region < rhs.region) return true; else if (region != rhs.region) return false; else return (projection < rhs.projection); } } } } } } } } } } } #ifdef PRIVILEGE_CHECKS //-------------------------------------------------------------------------- unsigned RegionRequirement::get_accessor_privilege(void) const //-------------------------------------------------------------------------- { switch (privilege) { case NO_ACCESS: return LegionRuntime::ACCESSOR_NONE; case READ_ONLY: return LegionRuntime::ACCESSOR_READ; case READ_WRITE: case WRITE_DISCARD: return LegionRuntime::ACCESSOR_ALL; case REDUCE: return LegionRuntime::ACCESSOR_REDUCE; default: assert(false); } return LegionRuntime::ACCESSOR_NONE; } #endif //-------------------------------------------------------------------------- bool RegionRequirement::has_field_privilege(FieldID fid) const //-------------------------------------------------------------------------- { return (privilege_fields.find(fid) != privilege_fields.end()); } //-------------------------------------------------------------------------- const void* RegionRequirement::get_projection_args(size_t *size) const //-------------------------------------------------------------------------- { if (size != NULL) *size = projection_args_size; return projection_args; } //-------------------------------------------------------------------------- void RegionRequirement::set_projection_args(const void *args, size_t size, bool own) //-------------------------------------------------------------------------- { if (projection_args_size > 0) { free(projection_args); projection_args = NULL; } projection_args_size = size; if (projection_args_size > 0) { if (!own) { projection_args = malloc(projection_args_size); memcpy(projection_args, args, projection_args_size); } else projection_args = const_cast<void*>(args); } } ///////////////////////////////////////////////////////////// // Index Space Requirement ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- IndexSpaceRequirement::IndexSpaceRequirement(void) : handle(IndexSpace::NO_SPACE), privilege(NO_MEMORY), parent(IndexSpace::NO_SPACE), verified(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexSpaceRequirement::IndexSpaceRequirement(IndexSpace _handle, AllocateMode _priv, IndexSpace _parent, bool _verified /*=false*/) : handle(_handle), privilege(_priv), parent(_parent), verified(_verified) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- bool IndexSpaceRequirement::operator<( const IndexSpaceRequirement &rhs) const //-------------------------------------------------------------------------- { if (handle < rhs.handle) return true; else if (handle != rhs.handle) // therefore greater than return false; else { if (privilege < rhs.privilege) return true; else if (privilege > rhs.privilege) return false; else { if (parent < rhs.parent) return true; else if (parent != rhs.parent) // therefore greater than return false; else return verified < rhs.verified; } } } //-------------------------------------------------------------------------- bool IndexSpaceRequirement::operator==( const IndexSpaceRequirement &rhs) const //-------------------------------------------------------------------------- { return (handle == rhs.handle) && (privilege == rhs.privilege) && (parent == rhs.parent) && (verified == rhs.verified); } ///////////////////////////////////////////////////////////// // Field Space Requirement ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FieldSpaceRequirement::FieldSpaceRequirement(void) : handle(FieldSpace::NO_SPACE), privilege(NO_MEMORY), verified(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FieldSpaceRequirement::FieldSpaceRequirement(FieldSpace _handle, AllocateMode _priv, bool _verified /*=false*/) : handle(_handle), privilege(_priv), verified(_verified) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- bool FieldSpaceRequirement::operator<( const FieldSpaceRequirement &rhs) const //-------------------------------------------------------------------------- { if (handle < rhs.handle) return true; else if (!(handle == rhs.handle)) // therefore greater than return false; else { if (privilege < rhs.privilege) return true; else if (privilege > rhs.privilege) return false; else return verified < rhs.verified; } } //-------------------------------------------------------------------------- bool FieldSpaceRequirement::operator==( const FieldSpaceRequirement &rhs) const //-------------------------------------------------------------------------- { return (handle == rhs.handle) && (privilege == rhs.privilege) && (verified == rhs.verified); } ///////////////////////////////////////////////////////////// // StaticDependence ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- StaticDependence::StaticDependence(void) : previous_offset(0), previous_req_index(0), current_req_index(0), dependence_type(NO_DEPENDENCE), validates(false), shard_only(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- StaticDependence::StaticDependence(unsigned prev, unsigned prev_req, unsigned current_req, DependenceType dtype, bool val, bool shard) : previous_offset(prev), previous_req_index(prev_req), current_req_index(current_req), dependence_type(dtype), validates(val), shard_only(shard) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // TaskLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- TaskLauncher::TaskLauncher(void) : task_id(0), argument(TaskArgument()), predicate(Predicate::TRUE_PRED), map_id(0), tag(0), point(DomainPoint()), static_dependences(NULL), enable_inlining(false), independent_requirements(false), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- TaskLauncher::TaskLauncher(TaskID tid, TaskArgument arg, Predicate pred /*= Predicate::TRUE_PRED*/, MapperID mid /*=0*/, MappingTagID t /*=0*/) : task_id(tid), argument(arg), predicate(pred), map_id(mid), tag(t), point(DomainPoint()), static_dependences(NULL), enable_inlining(false), independent_requirements(false), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // IndexTaskLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- IndexTaskLauncher::IndexTaskLauncher(void) : task_id(0), launch_domain(Domain::NO_DOMAIN), launch_space(IndexSpace::NO_SPACE), global_arg(TaskArgument()), argument_map(ArgumentMap()), predicate(Predicate::TRUE_PRED), must_parallelism(false), map_id(0), tag(0), static_dependences(NULL), enable_inlining(false), independent_requirements(false), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexTaskLauncher::IndexTaskLauncher(TaskID tid, Domain dom, TaskArgument global, ArgumentMap map, Predicate pred /*= Predicate::TRUE_PRED*/, bool must /*=false*/, MapperID mid /*=0*/, MappingTagID t /*=0*/) : task_id(tid), launch_domain(dom), launch_space(IndexSpace::NO_SPACE), global_arg(global), argument_map(map), predicate(pred), must_parallelism(must), map_id(mid), tag(t), static_dependences(NULL), enable_inlining(false), independent_requirements(false), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexTaskLauncher::IndexTaskLauncher(TaskID tid, IndexSpace space, TaskArgument global, ArgumentMap map, Predicate pred /*= Predicate::TRUE_PRED*/, bool must /*=false*/, MapperID mid /*=0*/, MappingTagID t /*=0*/) : task_id(tid), launch_domain(Domain::NO_DOMAIN), launch_space(space), global_arg(global), argument_map(map), predicate(pred), must_parallelism(must), map_id(mid), tag(t), static_dependences(NULL), enable_inlining(false), independent_requirements(false), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // InlineLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- InlineLauncher::InlineLauncher(void) : map_id(0), tag(0), layout_constraint_id(0), static_dependences(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- InlineLauncher::InlineLauncher(const RegionRequirement &req, MapperID mid /*=0*/, MappingTagID t /*=0*/, LayoutConstraintID lay_id /*=0*/) : requirement(req), map_id(mid), tag(t), layout_constraint_id(lay_id), static_dependences(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // CopyLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- CopyLauncher::CopyLauncher(Predicate pred /*= Predicate::TRUE_PRED*/, MapperID mid /*=0*/, MappingTagID t /*=0*/) : predicate(pred), map_id(mid), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // IndexCopyLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- IndexCopyLauncher::IndexCopyLauncher(void) : launch_domain(Domain::NO_DOMAIN), launch_space(IndexSpace::NO_SPACE), predicate(Predicate::TRUE_PRED), map_id(0), tag(0), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexCopyLauncher::IndexCopyLauncher(Domain dom, Predicate pred /*= Predicate::TRUE_PRED*/, MapperID mid /*=0*/, MappingTagID t /*=0*/) : launch_domain(dom), launch_space(IndexSpace::NO_SPACE), predicate(pred), map_id(mid),tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexCopyLauncher::IndexCopyLauncher(IndexSpace space, Predicate pred /*= Predicate::TRUE_PRED*/, MapperID mid /*=0*/, MappingTagID t /*=0*/) : launch_domain(Domain::NO_DOMAIN), launch_space(space), predicate(pred), map_id(mid), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // AcquireLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- AcquireLauncher::AcquireLauncher(LogicalRegion reg, LogicalRegion par, PhysicalRegion phy, Predicate pred /*= Predicate::TRUE_PRED*/, MapperID id /*=0*/, MappingTagID t /*=0*/) : logical_region(reg), parent_region(par), physical_region(phy), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // ReleaseLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ReleaseLauncher::ReleaseLauncher(LogicalRegion reg, LogicalRegion par, PhysicalRegion phy, Predicate pred /*= Predicate::TRUE_PRED*/, MapperID id /*=0*/, MappingTagID t /*=0*/) : logical_region(reg), parent_region(par), physical_region(phy), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // FillLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FillLauncher::FillLauncher(void) : handle(LogicalRegion::NO_REGION), parent(LogicalRegion::NO_REGION), map_id(0), tag(0), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FillLauncher::FillLauncher(LogicalRegion h, LogicalRegion p, TaskArgument arg, Predicate pred /*= Predicate::TRUE_PRED*/, MapperID id /*=0*/, MappingTagID t /*=0*/) : handle(h), parent(p), argument(arg), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FillLauncher::FillLauncher(LogicalRegion h, LogicalRegion p, Future f, Predicate pred /*= Predicate::TRUE_PRED*/, MapperID id /*=0*/, MappingTagID t /*=0*/) : handle(h), parent(p), future(f), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // IndexFillLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(void) : launch_domain(Domain::NO_DOMAIN), launch_space(IndexSpace::NO_SPACE), region(LogicalRegion::NO_REGION), partition(LogicalPartition::NO_PART), projection(0), map_id(0), tag(0), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(Domain dom, LogicalRegion h, LogicalRegion p, TaskArgument arg, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(dom), launch_space(IndexSpace::NO_SPACE), region(h), partition(LogicalPartition::NO_PART), parent(p), projection(proj), argument(arg), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(Domain dom, LogicalRegion h, LogicalRegion p, Future f, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(dom), launch_space(IndexSpace::NO_SPACE), region(h), partition(LogicalPartition::NO_PART), parent(p), projection(proj), future(f), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(IndexSpace space, LogicalRegion h, LogicalRegion p, TaskArgument arg, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(Domain::NO_DOMAIN), launch_space(space), region(h), partition(LogicalPartition::NO_PART), parent(p), projection(proj), argument(arg), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(IndexSpace space, LogicalRegion h, LogicalRegion p, Future f, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(Domain::NO_DOMAIN), launch_space(space), region(h), partition(LogicalPartition::NO_PART), parent(p), projection(proj), future(f), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(Domain dom, LogicalPartition h, LogicalRegion p, TaskArgument arg, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(dom), launch_space(IndexSpace::NO_SPACE), region(LogicalRegion::NO_REGION), partition(h), parent(p), projection(proj), argument(arg), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(Domain dom, LogicalPartition h, LogicalRegion p, Future f, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(dom), launch_space(IndexSpace::NO_SPACE), region(LogicalRegion::NO_REGION), partition(h), parent(p), projection(proj), future(f), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(IndexSpace space, LogicalPartition h, LogicalRegion p, TaskArgument arg, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(Domain::NO_DOMAIN), launch_space(space), region(LogicalRegion::NO_REGION), partition(h), parent(p), projection(proj), argument(arg), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexFillLauncher::IndexFillLauncher(IndexSpace space, LogicalPartition h, LogicalRegion p, Future f, ProjectionID proj, Predicate pred, MapperID id /*=0*/, MappingTagID t /*=0*/) : launch_domain(Domain::NO_DOMAIN), launch_space(space), region(LogicalRegion::NO_REGION), partition(h), parent(p), projection(proj), future(f), predicate(pred), map_id(id), tag(t), static_dependences(NULL), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // AttachLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- AttachLauncher::AttachLauncher(ExternalResource r, LogicalRegion h, LogicalRegion p, const bool restr/*= true*/, const bool map/*= true*/) : resource(r), handle(h), parent(p), restricted(restr), mapped(map), file_name(NULL), mode(LEGION_FILE_READ_ONLY), footprint(0), static_dependences(NULL) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // PredicateLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PredicateLauncher::PredicateLauncher(bool and_) : and_op(and_) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // TimingLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- TimingLauncher::TimingLauncher(TimingMeasurement m) : measurement(m) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // MustEpochLauncher ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- MustEpochLauncher::MustEpochLauncher(MapperID id /*= 0*/, MappingTagID tag/*= 0*/) : map_id(id), mapping_tag(tag), silence_warnings(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // LayoutConstraintRegistrar ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- LayoutConstraintRegistrar::LayoutConstraintRegistrar(void) : handle(FieldSpace::NO_SPACE), layout_name(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LayoutConstraintRegistrar::LayoutConstraintRegistrar(FieldSpace h, const char *layout/*= NULL*/) : handle(h), layout_name(layout) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // TaskVariantRegistrar ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- TaskVariantRegistrar::TaskVariantRegistrar(void) : task_id(0), global_registration(true), task_variant_name(NULL), leaf_variant(false), inner_variant(false), idempotent_variant(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- TaskVariantRegistrar::TaskVariantRegistrar(TaskID task_id, bool global, const char *variant_name) : task_id(task_id), global_registration(global), task_variant_name(variant_name), leaf_variant(false), inner_variant(false), idempotent_variant(false) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- TaskVariantRegistrar::TaskVariantRegistrar(TaskID task_id, const char *variant_name, bool global/*=true*/) : task_id(task_id), global_registration(global), task_variant_name(variant_name), leaf_variant(false), inner_variant(false), idempotent_variant(false) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // MPILegionHandshake ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- MPILegionHandshake::MPILegionHandshake(void) : impl(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- MPILegionHandshake::MPILegionHandshake(const MPILegionHandshake &rhs) : impl(rhs.impl) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- MPILegionHandshake::~MPILegionHandshake(void) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_reference()) delete impl; impl = NULL; } } //-------------------------------------------------------------------------- MPILegionHandshake::MPILegionHandshake(Internal::MPILegionHandshakeImpl *i) : impl(i) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- MPILegionHandshake& MPILegionHandshake::operator=( const MPILegionHandshake &rhs) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_reference()) delete impl; } impl = rhs.impl; if (impl != NULL) impl->add_reference(); return *this; } //-------------------------------------------------------------------------- void MPILegionHandshake::mpi_handoff_to_legion(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->mpi_handoff_to_legion(); } //-------------------------------------------------------------------------- void MPILegionHandshake::mpi_wait_on_legion(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->mpi_wait_on_legion(); } //-------------------------------------------------------------------------- void MPILegionHandshake::legion_handoff_to_mpi(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->legion_handoff_to_mpi(); } //-------------------------------------------------------------------------- void MPILegionHandshake::legion_wait_on_mpi(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->legion_wait_on_mpi(); } //-------------------------------------------------------------------------- PhaseBarrier MPILegionHandshake::get_legion_wait_phase_barrier(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->get_legion_wait_phase_barrier(); } //-------------------------------------------------------------------------- PhaseBarrier MPILegionHandshake::get_legion_arrive_phase_barrier(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->get_legion_arrive_phase_barrier(); } //-------------------------------------------------------------------------- void MPILegionHandshake::advance_legion_handshake(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->advance_legion_handshake(); } ///////////////////////////////////////////////////////////// // Future ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Future::Future(void) : impl(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- Future::Future(const Future &rhs) : impl(rhs.impl) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_base_gc_ref(Internal::FUTURE_HANDLE_REF); } //-------------------------------------------------------------------------- Future::~Future(void) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_base_gc_ref(Internal::FUTURE_HANDLE_REF)) delete impl; impl = NULL; } } //-------------------------------------------------------------------------- Future::Future(Internal::FutureImpl *i, bool need_reference) : impl(i) //-------------------------------------------------------------------------- { if ((impl != NULL) && need_reference) impl->add_base_gc_ref(Internal::FUTURE_HANDLE_REF); } //-------------------------------------------------------------------------- Future& Future::operator=(const Future &rhs) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_base_gc_ref(Internal::FUTURE_HANDLE_REF)) delete impl; } impl = rhs.impl; if (impl != NULL) impl->add_base_gc_ref(Internal::FUTURE_HANDLE_REF); return *this; } //-------------------------------------------------------------------------- void Future::get_void_result(bool silence_warnings, const char *warning_string) const //-------------------------------------------------------------------------- { if (impl != NULL) impl->wait(silence_warnings, warning_string); } //-------------------------------------------------------------------------- bool Future::is_empty(bool block /*= true*/, bool silence_warnings/*=false*/, const char *warning_string /*=NULL*/) const //-------------------------------------------------------------------------- { if (impl != NULL) return impl->is_empty(block, silence_warnings, warning_string); return true; } //-------------------------------------------------------------------------- bool Future::is_ready(bool subscribe) const //-------------------------------------------------------------------------- { if (impl != NULL) { const Internal::ApEvent ready = subscribe ? impl->subscribe() : impl->get_ready_event(); // Always subscribe to the Realm event to know when it triggers ready.subscribe(); return ready.has_triggered(); } return true; // Empty futures are always ready } //-------------------------------------------------------------------------- void* Future::get_untyped_result(bool silence_warnings, const char *warning_string, bool check_size, size_t future_size) const //-------------------------------------------------------------------------- { if (impl == NULL) REPORT_LEGION_ERROR(ERROR_REQUEST_FOR_EMPTY_FUTURE, "Illegal request for future value from empty future") return impl->get_untyped_result(silence_warnings, warning_string, false/*internal*/, check_size, future_size); } //-------------------------------------------------------------------------- size_t Future::get_untyped_size(void) const //-------------------------------------------------------------------------- { if (impl == NULL) REPORT_LEGION_ERROR(ERROR_REQUEST_FOR_EMPTY_FUTURE, "Illegal request for future size from empty future"); return impl->get_untyped_size(); } ///////////////////////////////////////////////////////////// // Future Map ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FutureMap::FutureMap(void) : impl(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FutureMap::FutureMap(const FutureMap &map) : impl(map.impl) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_base_gc_ref(Internal::FUTURE_HANDLE_REF); } //-------------------------------------------------------------------------- FutureMap::FutureMap(Internal::FutureMapImpl *i, bool need_reference) : impl(i) //-------------------------------------------------------------------------- { if ((impl != NULL) && need_reference) impl->add_base_gc_ref(Internal::FUTURE_HANDLE_REF); } //-------------------------------------------------------------------------- FutureMap::~FutureMap(void) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_base_gc_ref(Internal::FUTURE_HANDLE_REF)) delete impl; impl = NULL; } } //-------------------------------------------------------------------------- FutureMap& FutureMap::operator=(const FutureMap &rhs) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_base_gc_ref(Internal::FUTURE_HANDLE_REF)) delete impl; } impl = rhs.impl; if (impl != NULL) impl->add_base_gc_ref(Internal::FUTURE_HANDLE_REF); return *this; } //-------------------------------------------------------------------------- Future FutureMap::get_future(const DomainPoint &point) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->get_future(point); } //-------------------------------------------------------------------------- void FutureMap::get_void_result(const DomainPoint &point, bool silence_warnings, const char *warning_string) //-------------------------------------------------------------------------- { if (impl != NULL) impl->get_void_result(point, silence_warnings, warning_string); } //-------------------------------------------------------------------------- void FutureMap::wait_all_results(bool silence_warnings, const char *warning_string) //-------------------------------------------------------------------------- { if (impl != NULL) impl->wait_all_results(silence_warnings, warning_string); } ///////////////////////////////////////////////////////////// // Physical Region ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- PhysicalRegion::PhysicalRegion(void) : impl(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- PhysicalRegion::PhysicalRegion(const PhysicalRegion &rhs) : impl(rhs.impl) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- PhysicalRegion::PhysicalRegion(Internal::PhysicalRegionImpl *i) : impl(i) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- PhysicalRegion::~PhysicalRegion(void) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_reference()) delete impl; impl = NULL; } } //-------------------------------------------------------------------------- PhysicalRegion& PhysicalRegion::operator=(const PhysicalRegion &rhs) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_reference()) delete impl; } impl = rhs.impl; if (impl != NULL) impl->add_reference(); return *this; } //-------------------------------------------------------------------------- bool PhysicalRegion::is_mapped(void) const //-------------------------------------------------------------------------- { if (impl == NULL) return false; return impl->is_mapped(); } //-------------------------------------------------------------------------- void PhysicalRegion::wait_until_valid(bool silence_warnings, const char *warning_string) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->wait_until_valid(silence_warnings, warning_string); } //-------------------------------------------------------------------------- bool PhysicalRegion::is_valid(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->is_valid(); } //-------------------------------------------------------------------------- LogicalRegion PhysicalRegion::get_logical_region(void) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->get_logical_region(); } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> PhysicalRegion::get_accessor(bool silence_warnings) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->get_accessor(silence_warnings); } //-------------------------------------------------------------------------- LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> PhysicalRegion::get_field_accessor(FieldID fid, bool silence_warnings) const //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->get_field_accessor(fid, silence_warnings); } //-------------------------------------------------------------------------- void PhysicalRegion::get_memories(std::set<Memory>& memories) const //-------------------------------------------------------------------------- { impl->get_memories(memories); } //-------------------------------------------------------------------------- void PhysicalRegion::get_fields(std::vector<FieldID>& fields) const //-------------------------------------------------------------------------- { impl->get_fields(fields); } //-------------------------------------------------------------------------- void PhysicalRegion::get_bounds(void *realm_is, TypeTag type_tag) const //-------------------------------------------------------------------------- { impl->get_bounds(realm_is, type_tag); } //-------------------------------------------------------------------------- Realm::RegionInstance PhysicalRegion::get_instance_info(PrivilegeMode mode, FieldID fid, size_t field_size, void *realm_is, TypeTag type_tag, const char *warning_string, bool silence_warnings, bool generic_accessor, bool check_field_size, ReductionOpID redop) const //-------------------------------------------------------------------------- { if (impl == NULL) REPORT_LEGION_ERROR(ERROR_PHYSICAL_REGION_UNMAPPED, "Illegal request to create an accessor for uninitialized physical " "region in task %s (UID %lld)", Internal::implicit_context->get_task_name(), Internal::implicit_context->get_unique_id()) return impl->get_instance_info(mode, fid, field_size, realm_is, type_tag, warning_string, silence_warnings, generic_accessor, check_field_size, redop); } //-------------------------------------------------------------------------- void PhysicalRegion::fail_bounds_check(DomainPoint p, FieldID fid, PrivilegeMode mode) const //-------------------------------------------------------------------------- { impl->fail_bounds_check(p, fid, mode); } //-------------------------------------------------------------------------- void PhysicalRegion::fail_bounds_check(Domain d, FieldID fid, PrivilegeMode mode) const //-------------------------------------------------------------------------- { impl->fail_bounds_check(d, fid, mode); } //-------------------------------------------------------------------------- void PhysicalRegion::report_incompatible_accessor(const char *accessor_kind, Realm::RegionInstance instance, FieldID fid) const //-------------------------------------------------------------------------- { impl->report_incompatible_accessor(accessor_kind, instance, fid); } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif ///////////////////////////////////////////////////////////// // Index Iterator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- IndexIterator::IndexIterator(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexIterator::IndexIterator(const Domain &dom, ptr_t start) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(dom.get_dim() == 1); #endif const DomainT<1,coord_t> is = dom; is_iterator = Realm::IndexSpaceIterator<1,coord_t>(is); } //-------------------------------------------------------------------------- IndexIterator::IndexIterator(Runtime *rt, Context ctx, IndexSpace space, ptr_t start) //-------------------------------------------------------------------------- { Domain dom = rt->get_index_space_domain(ctx, space); #ifdef DEBUG_LEGION assert(dom.get_dim() == 1); #endif const DomainT<1,coord_t> is = dom; is_iterator = Realm::IndexSpaceIterator<1,coord_t>(is); } //-------------------------------------------------------------------------- IndexIterator::IndexIterator(Runtime *rt, Context ctx, LogicalRegion handle, ptr_t start) //-------------------------------------------------------------------------- { Domain dom = rt->get_index_space_domain(ctx, handle.get_index_space()); #ifdef DEBUG_LEGION assert(dom.get_dim() == 1); #endif const DomainT<1,coord_t> is = dom; is_iterator = Realm::IndexSpaceIterator<1,coord_t>(is); } //-------------------------------------------------------------------------- IndexIterator::IndexIterator(Runtime *rt, IndexSpace space, ptr_t start) //-------------------------------------------------------------------------- { Domain dom = rt->get_index_space_domain(space); #ifdef DEBUG_LEGION assert(dom.get_dim() == 1); #endif const DomainT<1,coord_t> is = dom; is_iterator = Realm::IndexSpaceIterator<1,coord_t>(is); } //-------------------------------------------------------------------------- IndexIterator::IndexIterator(const IndexIterator &rhs) : is_iterator(rhs.is_iterator), rect_iterator(rhs.rect_iterator) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexIterator::~IndexIterator(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexIterator& IndexIterator::operator=(const IndexIterator &rhs) //-------------------------------------------------------------------------- { is_iterator = rhs.is_iterator; rect_iterator = rhs.rect_iterator; return *this; } ///////////////////////////////////////////////////////////// // IndexAllocator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- IndexAllocator::IndexAllocator(void) : index_space(IndexSpace::NO_SPACE) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexAllocator::IndexAllocator(const IndexAllocator &rhs) : index_space(rhs.index_space), iterator(rhs.iterator) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexAllocator::IndexAllocator(IndexSpace is, IndexIterator itr) : index_space(is), iterator(itr) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexAllocator::~IndexAllocator(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexAllocator& IndexAllocator::operator=(const IndexAllocator &rhs) //-------------------------------------------------------------------------- { index_space = rhs.index_space; iterator = rhs.iterator; return *this; } //-------------------------------------------------------------------------- ptr_t IndexAllocator::alloc(unsigned num_elements) //-------------------------------------------------------------------------- { size_t allocated = 0; ptr_t result = iterator.next_span(allocated, num_elements); if (allocated == num_elements) return result; else return ptr_t::nil(); } //-------------------------------------------------------------------------- void IndexAllocator::free(ptr_t ptr, unsigned num_elements) //-------------------------------------------------------------------------- { Internal::log_run.error("Dynamic free of index space points is " "no longer supported"); assert(false); } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic pop #endif ///////////////////////////////////////////////////////////// // Field Allocator ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- FieldAllocator::FieldAllocator(void) : impl(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- FieldAllocator::FieldAllocator(const FieldAllocator &rhs) : impl(rhs.impl) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- FieldAllocator::~FieldAllocator(void) //-------------------------------------------------------------------------- { if (impl != NULL) { if (impl->remove_reference()) delete impl; impl = NULL; } } //-------------------------------------------------------------------------- FieldAllocator::FieldAllocator(Internal::FieldAllocatorImpl *i) : impl(i) //-------------------------------------------------------------------------- { if (impl != NULL) impl->add_reference(); } //-------------------------------------------------------------------------- FieldAllocator& FieldAllocator::operator=(const FieldAllocator &rhs) //-------------------------------------------------------------------------- { if ((impl != NULL) && impl->remove_reference()) delete impl; impl = rhs.impl; if (impl != NULL) impl->add_reference(); return *this; } //-------------------------------------------------------------------------- FieldID FieldAllocator::allocate_field(size_t field_size, FieldID desired_fieldid, CustomSerdezID serdez_id, bool local) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->allocate_field(field_size, desired_fieldid, serdez_id,local); } //-------------------------------------------------------------------------- void FieldAllocator::free_field(FieldID fid, const bool unordered) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->free_field(fid, unordered); } //-------------------------------------------------------------------------- FieldID FieldAllocator::allocate_local_field(size_t field_size, FieldID desired_fieldid, CustomSerdezID serdez_id) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif return impl->allocate_field(field_size, desired_fieldid, serdez_id, true/*local*/); } //-------------------------------------------------------------------------- void FieldAllocator::allocate_fields(const std::vector<size_t> &field_sizes, std::vector<FieldID> &resulting_fields, CustomSerdezID serdez_id, bool local) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->allocate_fields(field_sizes, resulting_fields, serdez_id, local); } //-------------------------------------------------------------------------- void FieldAllocator::free_fields(const std::set<FieldID> &to_free, const bool unordered) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->free_fields(to_free, unordered); } //-------------------------------------------------------------------------- void FieldAllocator::allocate_local_fields( const std::vector<size_t> &field_sizes, std::vector<FieldID> &resulting_fields, CustomSerdezID serdez_id) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(impl != NULL); #endif impl->allocate_fields(field_sizes, resulting_fields, serdez_id, true/*local*/); } //-------------------------------------------------------------------------- FieldSpace FieldAllocator::get_field_space(void) const //-------------------------------------------------------------------------- { if (impl == NULL) return FieldSpace::NO_SPACE; else return impl->get_field_space(); } ///////////////////////////////////////////////////////////// // Task Config Options ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- TaskConfigOptions::TaskConfigOptions(bool l /*=false*/, bool in /*=false*/, bool idem /*=false*/) : leaf(l), inner(in), idempotent(idem) //-------------------------------------------------------------------------- { } ///////////////////////////////////////////////////////////// // ProjectionFunctor ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ProjectionFunctor::ProjectionFunctor(void) : runtime(NULL) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ProjectionFunctor::ProjectionFunctor(Runtime *rt) : runtime(rt) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- ProjectionFunctor::~ProjectionFunctor(void) //-------------------------------------------------------------------------- { } // FIXME: This exists for backwards compatibility but it is tripping // over our own deprecation warnings. Turn those off inside this method. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" //-------------------------------------------------------------------------- LogicalRegion ProjectionFunctor::project(const Mappable *mappable, unsigned index, LogicalRegion upper_bound, const DomainPoint &point) //-------------------------------------------------------------------------- { if (is_functional()) { switch (mappable->get_mappable_type()) { case TASK_MAPPABLE: { const Task *task = mappable->as_task(); return project(upper_bound, point, task->index_domain); } case COPY_MAPPABLE: { const Copy *copy = mappable->as_copy(); return project(upper_bound, point, copy->index_domain); } case INLINE_MAPPABLE: case ACQUIRE_MAPPABLE: case RELEASE_MAPPABLE: case CLOSE_MAPPABLE: case DYNAMIC_COLLECTIVE_MAPPABLE: { const Domain launch_domain(point, point); return project(upper_bound, point, launch_domain); } case FILL_MAPPABLE: { const Fill *fill = mappable->as_fill(); return project(upper_bound, point, fill->index_domain); } case PARTITION_MAPPABLE: { const Partition *part = mappable->as_partition(); return project(upper_bound, point, part->index_domain); } case MUST_EPOCH_MAPPABLE: { const MustEpoch *must = mappable->as_must_epoch(); return project(upper_bound, point, must->launch_domain); } default: REPORT_LEGION_ERROR(ERROR_UNKNOWN_MAPPABLE, "Unknown mappable type passed to projection " "functor! You must override the default " "implementations of the non-deprecated " "'project' methods!"); } } else { #ifdef DEBUG_LEGION REPORT_LEGION_WARNING(LEGION_WARNING_NEW_PROJECTION_FUNCTORS, "THERE ARE NEW METHODS FOR PROJECTION FUNCTORS " "THAT MUST BE OVERRIDEN! CALLING DEPRECATED " "METHODS FOR NOW!"); #endif switch (mappable->get_mappable_type()) { case TASK_MAPPABLE: return project(0/*dummy ctx*/, const_cast<Task*>(mappable->as_task()), index, upper_bound, point); default: REPORT_LEGION_ERROR(ERROR_UNKNOWN_MAPPABLE, "Unknown mappable type passed to projection " "functor! You must override the default " "implementations of the non-deprecated " "'project' methods!"); } } return LogicalRegion::NO_REGION; } #pragma GCC diagnostic pop // FIXME: This exists for backwards compatibility but it is tripping // over our own deprecation warnings. Turn those off inside this method. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" //-------------------------------------------------------------------------- LogicalRegion ProjectionFunctor::project(const Mappable *mappable, unsigned index, LogicalPartition upper_bound, const DomainPoint &point) //-------------------------------------------------------------------------- { if (is_functional()) { switch (mappable->get_mappable_type()) { case TASK_MAPPABLE: { const Task *task = mappable->as_task(); return project(upper_bound, point, task->index_domain); } case COPY_MAPPABLE: { const Copy *copy = mappable->as_copy(); return project(upper_bound, point, copy->index_domain); } case INLINE_MAPPABLE: case ACQUIRE_MAPPABLE: case RELEASE_MAPPABLE: case CLOSE_MAPPABLE: case DYNAMIC_COLLECTIVE_MAPPABLE: { const Domain launch_domain(point, point); return project(upper_bound, point, launch_domain); } case FILL_MAPPABLE: { const Fill *fill = mappable->as_fill(); return project(upper_bound, point, fill->index_domain); } case PARTITION_MAPPABLE: { const Partition *part = mappable->as_partition(); return project(upper_bound, point, part->index_domain); } case MUST_EPOCH_MAPPABLE: { const MustEpoch *must = mappable->as_must_epoch(); return project(upper_bound, point, must->launch_domain); } default: REPORT_LEGION_ERROR(ERROR_UNKNOWN_MAPPABLE, "Unknown mappable type passed to projection " "functor! You must override the default " "implementations of the non-deprecated " "'project' methods!"); } } else { #ifdef DEBUG_LEGION REPORT_LEGION_WARNING(LEGION_WARNING_NEW_PROJECTION_FUNCTORS, "THERE ARE NEW METHODS FOR PROJECTION FUNCTORS " "THAT MUST BE OVERRIDEN! CALLING DEPRECATED " "METHODS FOR NOW!"); #endif switch (mappable->get_mappable_type()) { case TASK_MAPPABLE: return project(0/*dummy ctx*/, const_cast<Task*>(mappable->as_task()), index, upper_bound, point); default: REPORT_LEGION_ERROR(ERROR_UNKNOWN_MAPPABLE, "Unknown mappable type passed to projection " "functor! You must override the default " "implementations of the non-deprecated " "'project' methods!"); assert(false); } } return LogicalRegion::NO_REGION; } #pragma GCC diagnostic pop //-------------------------------------------------------------------------- LogicalRegion ProjectionFunctor::project(LogicalRegion upper_bound, const DomainPoint &point, const Domain &launch_domain) //-------------------------------------------------------------------------- { REPORT_LEGION_ERROR(ERROR_DEPRECATED_PROJECTION, "INVOCATION OF DEPRECATED PROJECTION " "FUNCTOR METHOD WITHOUT AN OVERRIDE!"); return LogicalRegion::NO_REGION; } //-------------------------------------------------------------------------- LogicalRegion ProjectionFunctor::project(LogicalPartition upper_bound, const DomainPoint &point, const Domain &launch_domain) //-------------------------------------------------------------------------- { REPORT_LEGION_ERROR(ERROR_DEPRECATED_PROJECTION, "INVOCATION OF DEPRECATED PROJECTION " "FUNCTOR METHOD WITHOUT AN OVERRIDE!"); return LogicalRegion::NO_REGION; } //-------------------------------------------------------------------------- LogicalRegion ProjectionFunctor::project(Context ctx, Task *task, unsigned index, LogicalRegion upper_bound, const DomainPoint &point) //-------------------------------------------------------------------------- { REPORT_LEGION_ERROR(ERROR_DEPRECATED_PROJECTION, "INVOCATION OF DEPRECATED PROJECTION " "FUNCTOR METHOD WITHOUT AN OVERRIDE!"); return LogicalRegion::NO_REGION; } //-------------------------------------------------------------------------- LogicalRegion ProjectionFunctor::project(Context ctx, Task *task, unsigned index, LogicalPartition upper_bound, const DomainPoint &point) //-------------------------------------------------------------------------- { REPORT_LEGION_ERROR(ERROR_DEPRECATED_PROJECTION, "INVOCATION OF DEPRECATED PROJECTION " "FUNCTOR METHOD WITHOUT AN OVERRIDE!"); return LogicalRegion::NO_REGION; } //-------------------------------------------------------------------------- void ProjectionFunctor::invert(LogicalRegion region, LogicalRegion upper, const Domain &launch_domain, std::vector<DomainPoint> &ordered_points) //-------------------------------------------------------------------------- { // Must be override by derived classes assert(false); } //-------------------------------------------------------------------------- void ProjectionFunctor::invert(LogicalRegion region, LogicalPartition upper, const Domain &launch_domain, std::vector<DomainPoint> &ordered_points) //-------------------------------------------------------------------------- { // Must be override by derived classes assert(false); } ///////////////////////////////////////////////////////////// // Coloring Serializer ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- ColoringSerializer::ColoringSerializer(const Coloring &c) : coloring(c) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- size_t ColoringSerializer::legion_buffer_size(void) const //-------------------------------------------------------------------------- { size_t result = sizeof(size_t); // number of elements for (Coloring::const_iterator it = coloring.begin(); it != coloring.end(); it++) { result += sizeof(Color); result += 2*sizeof(size_t); // number of each kind of pointer result += (it->second.points.size() * sizeof(ptr_t)); result += (it->second.ranges.size() * 2 * sizeof(ptr_t)); } return result; } //-------------------------------------------------------------------------- size_t ColoringSerializer::legion_serialize(void *buffer) const //-------------------------------------------------------------------------- { char *target = (char*)buffer; *((size_t*)target) = coloring.size(); target += sizeof(size_t); for (Coloring::const_iterator it = coloring.begin(); it != coloring.end(); it++) { *((Color*)target) = it->first; target += sizeof(it->first); *((size_t*)target) = it->second.points.size(); target += sizeof(size_t); for (std::set<ptr_t>::const_iterator ptr_it = it->second.points.begin(); ptr_it != it->second.points.end(); ptr_it++) { *((ptr_t*)target) = *ptr_it; target += sizeof(ptr_t); } *((size_t*)target) = it->second.ranges.size(); target += sizeof(size_t); for (std::set<std::pair<ptr_t,ptr_t> >::const_iterator range_it = it->second.ranges.begin(); range_it != it->second.ranges.end(); range_it++) { *((ptr_t*)target) = range_it->first; target += sizeof(range_it->first); *((ptr_t*)target) = range_it->second; target += sizeof(range_it->second); } } return (size_t(target) - size_t(buffer)); } //-------------------------------------------------------------------------- size_t ColoringSerializer::legion_deserialize(const void *buffer) //-------------------------------------------------------------------------- { const char *source = (const char*)buffer; size_t num_colors = *((const size_t*)source); source += sizeof(num_colors); for (unsigned idx = 0; idx < num_colors; idx++) { Color c = *((const Color*)source); source += sizeof(c); coloring[c]; // Force coloring to exist even if empty. size_t num_points = *((const size_t*)source); source += sizeof(num_points); for (unsigned p = 0; p < num_points; p++) { ptr_t ptr = *((const ptr_t*)source); source += sizeof(ptr); coloring[c].points.insert(ptr); } size_t num_ranges = *((const size_t*)source); source += sizeof(num_ranges); for (unsigned r = 0; r < num_ranges; r++) { ptr_t start = *((const ptr_t*)source); source += sizeof(start); ptr_t stop = *((const ptr_t*)source); source += sizeof(stop); coloring[c].ranges.insert(std::pair<ptr_t,ptr_t>(start,stop)); } } // Return the number of bytes consumed return (size_t(source) - size_t(buffer)); } ///////////////////////////////////////////////////////////// // Domain Coloring Serializer ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- DomainColoringSerializer::DomainColoringSerializer(const DomainColoring &d) : coloring(d) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- size_t DomainColoringSerializer::legion_buffer_size(void) const //-------------------------------------------------------------------------- { size_t result = sizeof(size_t); // number of elements result += (coloring.size() * (sizeof(Color) + sizeof(Domain))); return result; } //-------------------------------------------------------------------------- size_t DomainColoringSerializer::legion_serialize(void *buffer) const //-------------------------------------------------------------------------- { char *target = (char*)buffer; *((size_t*)target) = coloring.size(); target += sizeof(size_t); for (DomainColoring::const_iterator it = coloring.begin(); it != coloring.end(); it++) { *((Color*)target) = it->first; target += sizeof(it->first); *((Domain*)target) = it->second; target += sizeof(it->second); } return (size_t(target) - size_t(buffer)); } //-------------------------------------------------------------------------- size_t DomainColoringSerializer::legion_deserialize(const void *buffer) //-------------------------------------------------------------------------- { const char *source = (const char*)buffer; size_t num_elements = *((const size_t*)source); source += sizeof(size_t); for (unsigned idx = 0; idx < num_elements; idx++) { Color c = *((const Color*)source); source += sizeof(c); Domain d = *((const Domain*)source); source += sizeof(d); coloring[c] = d; } // Return the number of bytes consumed return (size_t(source) - size_t(buffer)); } ///////////////////////////////////////////////////////////// // Legion Runtime ///////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- Runtime::Runtime(Internal::Runtime *rt) : runtime(rt) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space(Context ctx, size_t max_num_elmts) //-------------------------------------------------------------------------- { Rect<1,coord_t> bounds((Point<1,coord_t>(0)), (Point<1,coord_t>(max_num_elmts-1))); DomainT<1,coord_t> realm_index_space(bounds); return create_index_space_internal(ctx, &realm_index_space, TYPE_TAG_1D); } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space(Context ctx, Domain domain) //-------------------------------------------------------------------------- { switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM,coord_t> bounds = domain; \ DomainT<DIM,coord_t> realm_is(bounds); \ return create_index_space_internal(ctx, &realm_is, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space(Context ctx, const std::set<Domain> &domains) //-------------------------------------------------------------------------- { std::vector<Domain> rects(domains.begin(), domains.end()); return create_index_space(ctx, rects); } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space(Context ctx, const std::vector<DomainPoint> &points) //-------------------------------------------------------------------------- { switch (points[0].get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ std::vector<Realm::Point<DIM,coord_t> > realm_points(points.size()); \ for (unsigned idx = 0; idx < points.size(); idx++) \ realm_points[idx] = Point<DIM,coord_t>(points[idx]); \ DomainT<DIM,coord_t> realm_is( \ (Realm::IndexSpace<DIM,coord_t>(realm_points))); \ return runtime->create_index_space(ctx, &realm_is, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space(Context ctx, const std::vector<Domain> &rects) //-------------------------------------------------------------------------- { switch (rects[0].get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ std::vector<Realm::Rect<DIM,coord_t> > realm_rects(rects.size()); \ for (unsigned idx = 0; idx < rects.size(); idx++) \ realm_rects[idx] = Rect<DIM,coord_t>(rects[idx]); \ DomainT<DIM,coord_t> realm_is( \ (Realm::IndexSpace<DIM,coord_t>(realm_rects))); \ return runtime->create_index_space(ctx, &realm_is, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_internal(Context ctx, const void *realm_is, TypeTag type_tag) //-------------------------------------------------------------------------- { return runtime->create_index_space(ctx, realm_is, type_tag); } //-------------------------------------------------------------------------- IndexSpace Runtime::union_index_spaces(Context ctx, const std::vector<IndexSpace> &spaces) //-------------------------------------------------------------------------- { return runtime->union_index_spaces(ctx, spaces); } //-------------------------------------------------------------------------- IndexSpace Runtime::intersect_index_spaces(Context ctx, const std::vector<IndexSpace> &spaces) //-------------------------------------------------------------------------- { return runtime->intersect_index_spaces(ctx, spaces); } //-------------------------------------------------------------------------- IndexSpace Runtime::subtract_index_spaces(Context ctx, IndexSpace left, IndexSpace right) //-------------------------------------------------------------------------- { return runtime->subtract_index_spaces(ctx, left, right); } //-------------------------------------------------------------------------- void Runtime::destroy_index_space(Context ctx, IndexSpace handle, const bool unordered) //-------------------------------------------------------------------------- { runtime->destroy_index_space(ctx, handle, unordered); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_index_partition(Context ctx, IndexSpace parent, const Domain &color_space, const PointColoring &coloring, PartitionKind part_kind, Color color, bool allocable) //-------------------------------------------------------------------------- { #ifndef DISABLE_PARTITION_SHIM if (allocable) Internal::log_run.warning("WARNING: allocable index partitions are " "no longer supported"); // Count how many entries there are in the coloring coord_t num_entries = 0; bool do_ranges = false; for (PointColoring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { #ifdef DEBUG_LEGION assert(cit->first.get_dim() == color_space.get_dim()); #endif num_entries += cit->second.points.size(); for (std::set<std::pair<ptr_t,ptr_t> >::const_iterator it = cit->second.ranges.begin(); it != cit->second.ranges.end(); it++) { // Skip empty ranges if (it->first.value > it->second.value) continue; num_entries++; do_ranges = true; } } // Now make a temporary logical region with two fields to handle // the colors and points Rect<1,coord_t> bounds(Point<1,coord_t>(0), Point<1,coord_t>(num_entries-1)); IndexSpaceT<1,coord_t> temp_is = create_index_space(ctx, bounds); FieldSpace temp_fs = create_field_space(ctx); const FieldID color_fid = 1; const FieldID pointer_fid = 2; { FieldAllocator allocator = create_field_allocator(ctx,temp_fs); switch (color_space.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ allocator.allocate_field( \ sizeof(Point<DIM,coord_t>), color_fid); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } if (do_ranges) allocator.allocate_field(sizeof(Rect<1,coord_t>), pointer_fid); else allocator.allocate_field(sizeof(Point<1,coord_t>), pointer_fid); } LogicalRegionT<1,coord_t> temp_lr = create_logical_region(ctx, temp_is, temp_fs, true); // Fill in the logical region with the data // Do this with a task launch to maintain deferred execution switch (color_space.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ if (do_ranges) \ { \ PartitionShim::ColorRects<DIM,1> launcher(coloring, temp_lr, \ color_fid, pointer_fid); \ runtime->execute_task(ctx, launcher); \ } \ else \ { \ PartitionShim::ColorPoints<DIM> launcher(coloring, temp_lr, \ color_fid, pointer_fid); \ runtime->execute_task(ctx, launcher); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } // Make an index space for the color space IndexSpace index_color_space = create_index_space(ctx, color_space); // Partition the logical region by the color field IndexPartition temp_ip = create_partition_by_field(ctx, temp_lr, temp_lr, color_fid, index_color_space, AUTO_GENERATE_ID, PARTITION_SHIM_MAPPER_ID); // Then project the partition image through the pointer field LogicalPartition temp_lp = get_logical_partition(temp_lr, temp_ip); IndexPartition result; if (do_ranges) result = create_partition_by_image_range(ctx, parent, temp_lp, temp_lr, pointer_fid, index_color_space, part_kind, color, PARTITION_SHIM_MAPPER_ID); else result = create_partition_by_image(ctx, parent, temp_lp, temp_lr, pointer_fid, index_color_space, part_kind, color, PARTITION_SHIM_MAPPER_ID); // Clean everything up destroy_logical_region(ctx, temp_lr); destroy_field_space(ctx, temp_fs); destroy_index_space(ctx, temp_is); return result; #else // DISABLE_PARTITION_SHIM log_run.error("THE PARTITION SHIM HAS BEEN DISABLED!"); assert(false); return IndexPartition::NO_PART; #endif } //-------------------------------------------------------------------------- IndexPartition Runtime::create_index_partition( Context ctx, IndexSpace parent, const Coloring &coloring, bool disjoint, Color part_color) //-------------------------------------------------------------------------- { #ifndef DISABLE_PARTITION_SHIM // Count how many entries there are in the coloring coord_t num_entries = 0; bool do_ranges = false; Color lower_bound = UINT_MAX, upper_bound = 0; for (Coloring::const_iterator cit = coloring.begin(); cit != coloring.end(); cit++) { if (cit->first < lower_bound) lower_bound = cit->first; if (cit->first > upper_bound) upper_bound = cit->first; num_entries += cit->second.points.size(); for (std::set<std::pair<ptr_t,ptr_t> >::const_iterator it = cit->second.ranges.begin(); it != cit->second.ranges.end(); it++) { // Skip empty ranges if (it->first.value > it->second.value) continue; num_entries++; do_ranges = true; } } #ifdef DEBUG_LEGION assert(lower_bound <= upper_bound); #endif // Make the color space Rect<1,coord_t> color_space((Point<1,coord_t>(lower_bound)), (Point<1,coord_t>(upper_bound))); // Now make a temporary logical region with two fields to handle // the colors and points Rect<1,coord_t> bounds(Point<1,coord_t>(0), Point<1,coord_t>(num_entries-1)); IndexSpaceT<1,coord_t> temp_is = create_index_space(ctx, bounds); FieldSpace temp_fs = create_field_space(ctx); const FieldID color_fid = 1; const FieldID pointer_fid = 2; { FieldAllocator allocator = create_field_allocator(ctx,temp_fs); allocator.allocate_field(sizeof(Point<1,coord_t>), color_fid); if (do_ranges) allocator.allocate_field(sizeof(Rect<1,coord_t>), pointer_fid); else allocator.allocate_field(sizeof(Point<1,coord_t>), pointer_fid); } LogicalRegionT<1,coord_t> temp_lr = create_logical_region(ctx, temp_is, temp_fs, true); // Fill in the logical region with the data // Do this with a task launch to maintain deferred execution if (do_ranges) { PartitionShim::ColorRects<1,1> launcher(coloring, temp_lr, color_fid, pointer_fid); runtime->execute_task(ctx, launcher); } else { PartitionShim::ColorPoints<1> launcher(coloring, temp_lr, color_fid, pointer_fid); runtime->execute_task(ctx, launcher); } // Make an index space for the color space IndexSpaceT<1,coord_t> index_color_space = create_index_space(ctx, color_space); // Partition the logical region by the color field IndexPartitionT<1,coord_t> temp_ip = create_partition_by_field(ctx, temp_lr, temp_lr, color_fid, index_color_space, AUTO_GENERATE_ID, PARTITION_SHIM_MAPPER_ID); // Then project the partition image through the pointer field LogicalPartitionT<1,coord_t> temp_lp = get_logical_partition(temp_lr, temp_ip); IndexPartitionT<1,coord_t> result; if (do_ranges) result = create_partition_by_image_range(ctx, IndexSpaceT<1,coord_t>(parent), temp_lp, temp_lr, pointer_fid, index_color_space, (disjoint ? DISJOINT_KIND : ALIASED_KIND), part_color, PARTITION_SHIM_MAPPER_ID); else result = create_partition_by_image(ctx, IndexSpaceT<1,coord_t>(parent), temp_lp, temp_lr, pointer_fid, index_color_space, (disjoint ? DISJOINT_KIND : ALIASED_KIND), part_color, PARTITION_SHIM_MAPPER_ID); // Clean everything up destroy_logical_region(ctx, temp_lr); destroy_field_space(ctx, temp_fs); destroy_index_space(ctx, temp_is); return result; #else // DISABLE_PARTITION_SHIM log_run.error("THE PARTITION SHIM HAS BEEN DISABLED!"); assert(false); return IndexPartition::NO_PART; #endif } //-------------------------------------------------------------------------- IndexPartition Runtime::create_index_partition(Context ctx, IndexSpace parent, const Domain &color_space, const DomainPointColoring &coloring, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { #ifndef DISABLE_PARTITION_SHIM // Count how many entries there are in the coloring const coord_t num_entries = coloring.size(); // Now make a temporary logical region with two fields to handle // the colors and points Rect<1,coord_t> bounds(Point<1,coord_t>(0), Point<1,coord_t>(num_entries-1)); IndexSpaceT<1,coord_t> temp_is = create_index_space(ctx, bounds); FieldSpace temp_fs = create_field_space(ctx); const FieldID color_fid = 1; const FieldID range_fid = 2; const int color_dim = color_space.get_dim(); const int range_dim = coloring.begin()->second.get_dim(); { FieldAllocator allocator = create_field_allocator(ctx,temp_fs); switch (color_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ allocator.allocate_field( \ sizeof(Point<DIM,coord_t>), color_fid); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } switch (range_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ allocator.allocate_field( \ sizeof(Rect<DIM,coord_t>), range_fid); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } } LogicalRegionT<1,coord_t> temp_lr = create_logical_region(ctx, temp_is, temp_fs, true); // Fill in the logical region with the data // Do this with a task launch to maintain deferred execution switch ((color_dim-1) * LEGION_MAX_DIM + (range_dim-1)) { #define DIMFUNC(D1,D2) \ case ((D1-1)*LEGION_MAX_DIM+(D2-1)): \ { \ PartitionShim::ColorRects<D1,D2> launcher(coloring, \ temp_lr, color_fid, range_fid); \ runtime->execute_task(ctx, launcher); \ break; \ } LEGION_FOREACH_NN(DIMFUNC) #undef DIMFUNC } // Make an index space for the color space IndexSpace index_color_space = create_index_space(ctx, color_space); // Partition the logical region by the color field IndexPartition temp_ip = create_partition_by_field(ctx, temp_lr, temp_lr, color_fid, index_color_space, AUTO_GENERATE_ID, PARTITION_SHIM_MAPPER_ID); // Then project the partition image through the range field LogicalPartition temp_lp = get_logical_partition(temp_lr, temp_ip); IndexPartition result = create_partition_by_image_range(ctx, parent, temp_lp, temp_lr, range_fid, index_color_space, part_kind, color, PARTITION_SHIM_MAPPER_ID); // Clean everything up destroy_logical_region(ctx, temp_lr); destroy_field_space(ctx, temp_fs); destroy_index_space(ctx, temp_is); return result; #else // DISABLE_PARTITION_SHIM log_run.error("THE PARTITION SHIM HAS BEEN DISABLED!"); assert(false); return IndexPartition::NO_PART; #endif } //-------------------------------------------------------------------------- IndexPartition Runtime::create_index_partition( Context ctx, IndexSpace parent, Domain color_space, const DomainColoring &coloring, bool disjoint, Color part_color) //-------------------------------------------------------------------------- { #ifndef DISABLE_PARTITION_SHIM // Count how many entries there are in the coloring const coord_t num_entries = coloring.size(); // Now make a temporary logical region with two fields to handle // the colors and points Rect<1,coord_t> bounds(Point<1,coord_t>(0), Point<1,coord_t>(num_entries-1)); IndexSpaceT<1,coord_t> temp_is = create_index_space(ctx, bounds); FieldSpace temp_fs = create_field_space(ctx); const FieldID color_fid = 1; const FieldID range_fid = 2; const int range_dim = coloring.begin()->second.get_dim(); { FieldAllocator allocator = create_field_allocator(ctx,temp_fs); allocator.allocate_field(sizeof(Point<1,coord_t>), color_fid); switch (range_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ allocator.allocate_field( \ sizeof(Rect<DIM,coord_t>), range_fid); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } } LogicalRegionT<1,coord_t> temp_lr = create_logical_region(ctx, temp_is, temp_fs, true); // Fill in the logical region with the data // Do this with a task launch to maintain deferred execution switch (range_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ PartitionShim::ColorRects<1,DIM> launcher(coloring, \ temp_lr, color_fid, range_fid); \ runtime->execute_task(ctx, launcher); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexSpaceT<1,coord_t> index_color_space = create_index_space<1,coord_t>(ctx, color_space); // Partition the logical region by the color field IndexPartition temp_ip = create_partition_by_field(ctx, temp_lr, temp_lr, color_fid, index_color_space, AUTO_GENERATE_ID, PARTITION_SHIM_MAPPER_ID); // Then project the partition image through the pointer field LogicalPartition temp_lp = get_logical_partition(temp_lr, temp_ip); IndexPartition result = create_partition_by_image_range(ctx, parent, temp_lp, temp_lr, range_fid, index_color_space, (disjoint ? DISJOINT_KIND : ALIASED_KIND), part_color, PARTITION_SHIM_MAPPER_ID); // Clean everything up destroy_logical_region(ctx, temp_lr); destroy_field_space(ctx, temp_fs); destroy_index_space(ctx, temp_is); return result; #else // DISABLE_PARTITION_SHIM log_run.error("THE PARTITION SHIM HAS BEEN DISABLED!"); assert(false); return IndexPartition::NO_PART; #endif } //-------------------------------------------------------------------------- IndexPartition Runtime::create_index_partition(Context ctx, IndexSpace parent, const Domain &color_space, const MultiDomainPointColoring &coloring, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { #ifndef DISABLE_PARTITION_SHIM // Count how many entries there are in the coloring coord_t num_entries = 0; for (MultiDomainPointColoring::const_iterator it = coloring.begin(); it != coloring.end(); it++) num_entries += it->second.size(); // Now make a temporary logical region with two fields to handle // the colors and points Rect<1,coord_t> bounds(Point<1,coord_t>(0), Point<1,coord_t>(num_entries-1)); IndexSpaceT<1,coord_t> temp_is = create_index_space(ctx, bounds); FieldSpace temp_fs = create_field_space(ctx); const FieldID color_fid = 1; const FieldID range_fid = 2; const int color_dim = color_space.get_dim(); const int range_dim = coloring.begin()->second.begin()->get_dim(); { FieldAllocator allocator = create_field_allocator(ctx,temp_fs); switch (color_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ allocator.allocate_field( \ sizeof(Point<DIM,coord_t>), color_fid); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } switch (range_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ allocator.allocate_field( \ sizeof(Rect<DIM,coord_t>), range_fid); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } } LogicalRegionT<1,coord_t> temp_lr = create_logical_region(ctx, temp_is, temp_fs, true); // Fill in the logical region with the data // Do this with a task launch to maintain deferred execution switch ((color_dim-1) * LEGION_MAX_DIM + (range_dim-1)) { #define DIMFUNC(D1,D2) \ case ((D1-1)*LEGION_MAX_DIM+(D2-1)): \ { \ PartitionShim::ColorRects<D1,D2> launcher(coloring, \ temp_lr, color_fid, range_fid); \ runtime->execute_task(ctx, launcher); \ break; \ } LEGION_FOREACH_NN(DIMFUNC) #undef DIMFUNC } // Make an index space for the color space IndexSpace index_color_space = create_index_space(ctx, color_space); // Partition the logical region by the color field IndexPartition temp_ip = create_partition_by_field(ctx, temp_lr, temp_lr, color_fid, index_color_space, AUTO_GENERATE_ID, PARTITION_SHIM_MAPPER_ID); // Then project the partition image through the range field LogicalPartition temp_lp = get_logical_partition(temp_lr, temp_ip); IndexPartition result = create_partition_by_image_range(ctx, parent, temp_lp, temp_lr, range_fid, index_color_space, part_kind, color, PARTITION_SHIM_MAPPER_ID); // Clean everything up destroy_logical_region(ctx, temp_lr); destroy_field_space(ctx, temp_fs); destroy_index_space(ctx, temp_is); return result; #else // DISABLE_PARTITION_SHIM log_run.error("THE PARTITION SHIM HAS BEEN DISABLED!"); assert(false); return IndexPartition::NO_PART; #endif } //-------------------------------------------------------------------------- IndexPartition Runtime::create_index_partition( Context ctx, IndexSpace parent, Domain color_space, const MultiDomainColoring &coloring, bool disjoint, Color part_color) //-------------------------------------------------------------------------- { #ifndef DISABLE_PARTITION_SHIM // Count how many entries there are in the coloring coord_t num_entries = 0; for (MultiDomainColoring::const_iterator it = coloring.begin(); it != coloring.end(); it++) num_entries += it->second.size(); // Now make a temporary logical region with two fields to handle // the colors and points Rect<1,coord_t> bounds(Point<1,coord_t>(0), Point<1,coord_t>(num_entries-1)); IndexSpaceT<1,coord_t> temp_is = create_index_space(ctx, bounds); FieldSpace temp_fs = create_field_space(ctx); const FieldID color_fid = 1; const FieldID range_fid = 2; const int range_dim = coloring.begin()->second.begin()->get_dim(); { FieldAllocator allocator = create_field_allocator(ctx,temp_fs); allocator.allocate_field(sizeof(Point<1,coord_t>), color_fid); switch (range_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ allocator.allocate_field( \ sizeof(Rect<DIM,coord_t>), range_fid); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } } LogicalRegionT<1,coord_t> temp_lr = create_logical_region(ctx, temp_is, temp_fs, true); // Fill in the logical region with the data // Do this with a task launch to maintain deferred execution switch (range_dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ PartitionShim::ColorRects<1,DIM> launcher(coloring, \ temp_lr, color_fid, range_fid); \ runtime->execute_task(ctx, launcher); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexSpaceT<1,coord_t> index_color_space = create_index_space<1,coord_t>(ctx, color_space); // Partition the logical region by the color field IndexPartition temp_ip = create_partition_by_field(ctx, temp_lr, temp_lr, color_fid, index_color_space, AUTO_GENERATE_ID, PARTITION_SHIM_MAPPER_ID); // Then project the partition image through the pointer field LogicalPartition temp_lp = get_logical_partition(temp_lr, temp_ip); IndexPartition result = create_partition_by_image_range(ctx, parent, temp_lp, temp_lr, range_fid, index_color_space, (disjoint ? DISJOINT_KIND : ALIASED_KIND), part_color, PARTITION_SHIM_MAPPER_ID); // Clean everything up destroy_logical_region(ctx, temp_lr); destroy_field_space(ctx, temp_fs); destroy_index_space(ctx, temp_is); return result; #else // DISABLE_PARTITION_SHIM log_run.error("THE PARTITION SHIM HAS BEEN DISABLED!"); assert(false); return IndexPartition::NO_PART; #endif } //-------------------------------------------------------------------------- IndexPartition Runtime::create_index_partition( Context ctx, IndexSpace parent, LegionRuntime::Accessor::RegionAccessor< LegionRuntime::Accessor::AccessorType::Generic> field_accessor, Color part_color) //-------------------------------------------------------------------------- { Internal::log_run.error("Call to deprecated 'create_index_partition' " "method with an accessor in task %s (UID %lld) should be " "replaced with a call to create_partition_by_field.", ctx->get_task_name(), ctx->get_unique_id()); assert(false); return IndexPartition::NO_PART; } //-------------------------------------------------------------------------- void Runtime::destroy_index_partition(Context ctx, IndexPartition handle, const bool unordered) //-------------------------------------------------------------------------- { runtime->destroy_index_partition(ctx, handle, unordered); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_equal_partition(Context ctx, IndexSpace parent, IndexSpace color_space, size_t granularity, Color color) //-------------------------------------------------------------------------- { return runtime->create_equal_partition(ctx, parent, color_space, granularity, color); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_union(Context ctx, IndexSpace parent, IndexPartition handle1, IndexPartition handle2, IndexSpace color_space, PartitionKind kind, Color color) //-------------------------------------------------------------------------- { return runtime->create_partition_by_union(ctx, parent, handle1, handle2, color_space, kind, color); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_intersection( Context ctx, IndexSpace parent, IndexPartition handle1, IndexPartition handle2, IndexSpace color_space, PartitionKind kind, Color color) //-------------------------------------------------------------------------- { return runtime->create_partition_by_intersection(ctx, parent, handle1, handle2, color_space, kind, color); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_intersection(Context ctx, IndexSpace parent, IndexPartition partition, PartitionKind part_kind, Color color, bool dominates) //-------------------------------------------------------------------------- { return runtime->create_partition_by_intersection(ctx, parent, partition, part_kind, color, dominates); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_difference( Context ctx, IndexSpace parent, IndexPartition handle1, IndexPartition handle2, IndexSpace color_space, PartitionKind kind, Color color) //-------------------------------------------------------------------------- { return runtime->create_partition_by_difference(ctx, parent, handle1, handle2, color_space, kind, color); } //-------------------------------------------------------------------------- Color Runtime::create_cross_product_partitions(Context ctx, IndexPartition handle1, IndexPartition handle2, std::map<IndexSpace,IndexPartition> &handles, PartitionKind kind, Color color) //-------------------------------------------------------------------------- { return runtime->create_cross_product_partitions(ctx, handle1, handle2, handles, kind, color); } //-------------------------------------------------------------------------- void Runtime::create_association(Context ctx, LogicalRegion domain, LogicalRegion domain_parent, FieldID domain_fid, IndexSpace range, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { runtime->create_association(ctx, domain, domain_parent, domain_fid, range, id, tag); } //-------------------------------------------------------------------------- void Runtime::create_bidirectional_association(Context ctx, LogicalRegion domain, LogicalRegion domain_parent, FieldID domain_fid, LogicalRegion range, LogicalRegion range_parent, FieldID range_fid, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { // Realm guarantees that creating association in either direction // will produce the same result, so we can do these separately create_association(ctx, domain, domain_parent, domain_fid, range.get_index_space(), id, tag); create_association(ctx, range, range_parent, range_fid, domain.get_index_space(), id, tag); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_restriction(Context ctx, IndexSpace par, IndexSpace cs, DomainTransform tran, Domain ext, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { switch ((ext.get_dim()-1) * LEGION_MAX_DIM + (tran.n-1)) { #define DIMFUNC(D1,D2) \ case (D1-1)*LEGION_MAX_DIM+(D2-1): \ { \ const IndexSpaceT<D1,coord_t> parent(par); \ const Rect<D1,coord_t> extent(ext); \ const Transform<D1,D2> transform(tran); \ const IndexSpaceT<D2,coord_t> color_space(cs); \ return create_partition_by_restriction<D1,D2,coord_t>(ctx, \ parent, color_space, transform, extent, part_kind, color); \ } LEGION_FOREACH_NN(DIMFUNC) #undef DIMFUNC } return IndexPartition::NO_PART; } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_blockify(Context ctx, IndexSpace par, DomainPoint bf, Color color) //-------------------------------------------------------------------------- { switch (bf.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ const IndexSpaceT<DIM,coord_t> parent(par); \ const Point<DIM,coord_t> blocking_factor(bf); \ return create_partition_by_blockify<DIM,coord_t>(ctx, parent, \ blocking_factor, color); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexPartition::NO_PART; } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_blockify(Context ctx, IndexSpace par, DomainPoint bf, DomainPoint orig, Color color) //-------------------------------------------------------------------------- { switch (bf.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ const IndexSpaceT<DIM,coord_t> parent(par); \ const Point<DIM,coord_t> blocking_factor(bf); \ const Point<DIM,coord_t> origin(orig); \ return create_partition_by_blockify<DIM,coord_t>(ctx, parent, \ blocking_factor, origin, color); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexPartition::NO_PART; } //-------------------------------------------------------------------------- IndexPartition Runtime::create_restricted_partition(Context ctx, IndexSpace parent, IndexSpace color_space, const void *transform, size_t transform_size, const void *extent, size_t extent_size, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return runtime->create_restricted_partition(ctx, parent, color_space, transform, transform_size, extent, extent_size, part_kind, color); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_field(Context ctx, LogicalRegion handle, LogicalRegion parent, FieldID fid, IndexSpace color_space, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return runtime->create_partition_by_field(ctx, handle, parent, fid, color_space, color, id, tag); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_image(Context ctx, IndexSpace handle, LogicalPartition projection, LogicalRegion parent, FieldID fid, IndexSpace color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return runtime->create_partition_by_image(ctx, handle, projection, parent, fid, color_space, part_kind, color, id, tag); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_image_range(Context ctx, IndexSpace handle, LogicalPartition projection, LogicalRegion parent, FieldID fid, IndexSpace color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return runtime->create_partition_by_image_range(ctx, handle, projection, parent, fid, color_space, part_kind, color, id,tag); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_preimage(Context ctx, IndexPartition projection, LogicalRegion handle, LogicalRegion parent, FieldID fid, IndexSpace color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return runtime->create_partition_by_preimage(ctx, projection, handle, parent, fid, color_space, part_kind, color, id, tag); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_partition_by_preimage_range(Context ctx, IndexPartition projection, LogicalRegion handle, LogicalRegion parent, FieldID fid, IndexSpace color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return runtime->create_partition_by_preimage_range(ctx, projection,handle, parent, fid, color_space, part_kind, color,id,tag); } //-------------------------------------------------------------------------- IndexPartition Runtime::create_pending_partition(Context ctx, IndexSpace parent, IndexSpace color_space, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return runtime->create_pending_partition(ctx, parent, color_space, part_kind, color); } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_union(Context ctx, IndexPartition parent, const DomainPoint &color, const std::vector<IndexSpace> &handles) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->create_index_space_union(ctx, parent, &point, \ TYPE_TAG_##DIM##D, handles); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_union_internal(Context ctx, IndexPartition parent, const void *color, TypeTag type_tag, const std::vector<IndexSpace> &handles) //-------------------------------------------------------------------------- { return runtime->create_index_space_union(ctx, parent, color, type_tag, handles); } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_union(Context ctx, IndexPartition parent, const DomainPoint &color, IndexPartition handle) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->create_index_space_union(ctx, parent, &point, \ TYPE_TAG_##DIM##D, handle); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_union_internal(Context ctx, IndexPartition parent, const void *realm_color, TypeTag type_tag, IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->create_index_space_union(ctx, parent, realm_color, type_tag, handle); } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_intersection(Context ctx, IndexPartition parent, const DomainPoint &color, const std::vector<IndexSpace> &handles) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->create_index_space_intersection(ctx, parent, &point, \ TYPE_TAG_##DIM##D, handles); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_intersection_internal(Context ctx, IndexPartition parent, const void *color, TypeTag type_tag, const std::vector<IndexSpace> &handles) //-------------------------------------------------------------------------- { return runtime->create_index_space_intersection(ctx, parent, color, type_tag, handles); } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_intersection(Context ctx, IndexPartition parent, const DomainPoint &color, IndexPartition handle) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->create_index_space_intersection(ctx, parent, &point, \ TYPE_TAG_##DIM##D, handle); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_intersection_internal(Context ctx, IndexPartition parent, const void *realm_color, TypeTag type_tag, IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->create_index_space_intersection(ctx, parent, realm_color, type_tag, handle); } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_difference(Context ctx, IndexPartition parent, const DomainPoint &color, IndexSpace initial, const std::vector<IndexSpace> &handles) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->create_index_space_difference(ctx, parent, &point, \ TYPE_TAG_##DIM##D, initial, handles); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::create_index_space_difference_internal(Context ctx, IndexPartition parent, const void *realm_color, TypeTag type_tag, IndexSpace initial, const std::vector<IndexSpace> &handles) //-------------------------------------------------------------------------- { return runtime->create_index_space_difference(ctx, parent, realm_color, type_tag, initial, handles); } //-------------------------------------------------------------------------- IndexPartition Runtime::get_index_partition(Context ctx, IndexSpace parent, Color color) //-------------------------------------------------------------------------- { return runtime->get_index_partition(ctx, parent, color); } //-------------------------------------------------------------------------- IndexPartition Runtime::get_index_partition(Context ctx, IndexSpace parent, const DomainPoint &color) //-------------------------------------------------------------------------- { return get_index_partition(ctx, parent, color.get_color()); } //-------------------------------------------------------------------------- IndexPartition Runtime::get_index_partition(IndexSpace parent, Color color) //-------------------------------------------------------------------------- { return runtime->get_index_partition(parent, color); } //-------------------------------------------------------------------------- IndexPartition Runtime::get_index_partition(IndexSpace parent, const DomainPoint &color) //-------------------------------------------------------------------------- { return get_index_partition(parent, color.get_color()); } //-------------------------------------------------------------------------- bool Runtime::has_index_partition(Context ctx, IndexSpace parent, Color c) //-------------------------------------------------------------------------- { return runtime->has_index_partition(ctx, parent, c); } //-------------------------------------------------------------------------- bool Runtime::has_index_partition(Context ctx, IndexSpace parent, const DomainPoint &color) //-------------------------------------------------------------------------- { return runtime->has_index_partition(ctx, parent, color.get_color()); } //-------------------------------------------------------------------------- bool Runtime::has_index_partition(IndexSpace parent, Color c) //-------------------------------------------------------------------------- { return runtime->has_index_partition(parent, c); } //-------------------------------------------------------------------------- bool Runtime::has_index_partition(IndexSpace parent, const DomainPoint &color) //-------------------------------------------------------------------------- { return runtime->has_index_partition(parent, color.get_color()); } //-------------------------------------------------------------------------- IndexSpace Runtime::get_index_subspace(Context ctx, IndexPartition p, Color color) //-------------------------------------------------------------------------- { Point<1,coord_t> point = color; return runtime->get_index_subspace(ctx, p, &point, TYPE_TAG_1D); } //-------------------------------------------------------------------------- IndexSpace Runtime::get_index_subspace(Context ctx, IndexPartition p, const DomainPoint &color) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->get_index_subspace(ctx, p, &point, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::get_index_subspace(IndexPartition p, Color color) //-------------------------------------------------------------------------- { Point<1,coord_t> point = color; return runtime->get_index_subspace(p, &point, TYPE_TAG_1D); } //-------------------------------------------------------------------------- IndexSpace Runtime::get_index_subspace(IndexPartition p, const DomainPoint &color) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->get_index_subspace(p, &point, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return IndexSpace::NO_SPACE; } //-------------------------------------------------------------------------- IndexSpace Runtime::get_index_subspace_internal(IndexPartition p, const void *realm_color, TypeTag type_tag) //-------------------------------------------------------------------------- { return runtime->get_index_subspace(p, realm_color, type_tag); } //-------------------------------------------------------------------------- bool Runtime::has_index_subspace(Context ctx, IndexPartition p, const DomainPoint &color) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->has_index_subspace(ctx, p, &point, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return false; } //-------------------------------------------------------------------------- bool Runtime::has_index_subspace(IndexPartition p, const DomainPoint &color) //-------------------------------------------------------------------------- { switch (color.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point = color; \ return runtime->has_index_subspace(p, &point, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return false; } //-------------------------------------------------------------------------- bool Runtime::has_index_subspace_internal(IndexPartition p, const void *realm_color, TypeTag type_tag) //-------------------------------------------------------------------------- { return runtime->has_index_subspace(p, realm_color, type_tag); } //-------------------------------------------------------------------------- bool Runtime::has_multiple_domains(Context ctx, IndexSpace handle) //-------------------------------------------------------------------------- { // Multiple domains supported implicitly return false; } //-------------------------------------------------------------------------- bool Runtime::has_multiple_domains(IndexSpace handle) //-------------------------------------------------------------------------- { // Multiple domains supported implicitly return false; } //-------------------------------------------------------------------------- Domain Runtime::get_index_space_domain(Context ctx, IndexSpace handle) //-------------------------------------------------------------------------- { const TypeTag type_tag = handle.get_type_tag(); switch (Internal::NT_TemplateHelper::get_dim(type_tag)) { #define DIMFUNC(DIM) \ case DIM: \ { \ DomainT<DIM,coord_t> realm_is; \ runtime->get_index_space_domain(ctx, handle, &realm_is, type_tag); \ return Domain(realm_is); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return Domain::NO_DOMAIN; } //-------------------------------------------------------------------------- Domain Runtime::get_index_space_domain(IndexSpace handle) //-------------------------------------------------------------------------- { const TypeTag type_tag = handle.get_type_tag(); switch (Internal::NT_TemplateHelper::get_dim(type_tag)) { #define DIMFUNC(DIM) \ case DIM: \ { \ DomainT<DIM,coord_t> realm_is; \ runtime->get_index_space_domain(handle, &realm_is, type_tag); \ return Domain(realm_is); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return Domain::NO_DOMAIN; } //-------------------------------------------------------------------------- void Runtime::get_index_space_domain_internal(IndexSpace handle, void *realm_is, TypeTag type_tag) //-------------------------------------------------------------------------- { runtime->get_index_space_domain(handle, realm_is, type_tag); } //-------------------------------------------------------------------------- void Runtime::get_index_space_domains(Context ctx, IndexSpace handle, std::vector<Domain> &domains) //-------------------------------------------------------------------------- { domains.push_back(get_index_space_domain(ctx, handle)); } //-------------------------------------------------------------------------- void Runtime::get_index_space_domains(IndexSpace handle, std::vector<Domain> &domains) //-------------------------------------------------------------------------- { domains.push_back(get_index_space_domain(handle)); } //-------------------------------------------------------------------------- Domain Runtime::get_index_partition_color_space(Context ctx, IndexPartition p) //-------------------------------------------------------------------------- { return runtime->get_index_partition_color_space(ctx, p); } //-------------------------------------------------------------------------- Domain Runtime::get_index_partition_color_space(IndexPartition p) //-------------------------------------------------------------------------- { return runtime->get_index_partition_color_space(p); } //-------------------------------------------------------------------------- void Runtime::get_index_partition_color_space_internal(IndexPartition p, void *realm_is, TypeTag type_tag) //-------------------------------------------------------------------------- { runtime->get_index_partition_color_space(p, realm_is, type_tag); } //-------------------------------------------------------------------------- IndexSpace Runtime::get_index_partition_color_space_name(Context ctx, IndexPartition p) //-------------------------------------------------------------------------- { return runtime->get_index_partition_color_space_name(ctx, p); } //-------------------------------------------------------------------------- IndexSpace Runtime::get_index_partition_color_space_name(IndexPartition p) //-------------------------------------------------------------------------- { return runtime->get_index_partition_color_space_name(p); } //-------------------------------------------------------------------------- void Runtime::get_index_space_partition_colors(Context ctx, IndexSpace sp, std::set<Color> &colors) //-------------------------------------------------------------------------- { runtime->get_index_space_partition_colors(ctx, sp, colors); } //-------------------------------------------------------------------------- void Runtime::get_index_space_partition_colors(Context ctx, IndexSpace sp, std::set<DomainPoint> &colors) //-------------------------------------------------------------------------- { std::set<Color> temp_colors; runtime->get_index_space_partition_colors(ctx, sp, temp_colors); for (std::set<Color>::const_iterator it = temp_colors.begin(); it != temp_colors.end(); it++) colors.insert(DomainPoint(*it)); } //-------------------------------------------------------------------------- void Runtime::get_index_space_partition_colors(IndexSpace sp, std::set<Color> &colors) //-------------------------------------------------------------------------- { runtime->get_index_space_partition_colors(sp, colors); } //-------------------------------------------------------------------------- void Runtime::get_index_space_partition_colors(IndexSpace sp, std::set<DomainPoint> &colors) //-------------------------------------------------------------------------- { std::set<Color> temp_colors; runtime->get_index_space_partition_colors(sp, temp_colors); for (std::set<Color>::const_iterator it = temp_colors.begin(); it != temp_colors.end(); it++) colors.insert(DomainPoint(*it)); } //-------------------------------------------------------------------------- bool Runtime::is_index_partition_disjoint(Context ctx, IndexPartition p) //-------------------------------------------------------------------------- { return runtime->is_index_partition_disjoint(ctx, p); } //-------------------------------------------------------------------------- bool Runtime::is_index_partition_disjoint(IndexPartition p) //-------------------------------------------------------------------------- { return runtime->is_index_partition_disjoint(p); } //-------------------------------------------------------------------------- bool Runtime::is_index_partition_complete(Context ctx, IndexPartition p) //-------------------------------------------------------------------------- { return runtime->is_index_partition_complete(ctx, p); } //-------------------------------------------------------------------------- bool Runtime::is_index_partition_complete(IndexPartition p) //-------------------------------------------------------------------------- { return runtime->is_index_partition_complete(p); } //-------------------------------------------------------------------------- Color Runtime::get_index_space_color(Context ctx, IndexSpace handle) //-------------------------------------------------------------------------- { Point<1,coord_t> point; runtime->get_index_space_color_point(ctx, handle, &point, TYPE_TAG_1D); return point[0]; } //-------------------------------------------------------------------------- Color Runtime::get_index_space_color(IndexSpace handle) //-------------------------------------------------------------------------- { Point<1,coord_t> point; runtime->get_index_space_color_point(handle, &point, TYPE_TAG_1D); return point[0]; } //-------------------------------------------------------------------------- DomainPoint Runtime::get_index_space_color_point(Context ctx, IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_index_space_color_point(ctx, handle); } //-------------------------------------------------------------------------- DomainPoint Runtime::get_index_space_color_point(IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_index_space_color_point(handle); } //-------------------------------------------------------------------------- void Runtime::get_index_space_color_internal(IndexSpace handle, void *realm_color, TypeTag type_tag) //-------------------------------------------------------------------------- { runtime->get_index_space_color_point(handle, realm_color, type_tag); } //-------------------------------------------------------------------------- Color Runtime::get_index_partition_color(Context ctx, IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_index_partition_color(ctx, handle); } //-------------------------------------------------------------------------- Color Runtime::get_index_partition_color(IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_index_partition_color(handle); } //-------------------------------------------------------------------------- DomainPoint Runtime::get_index_partition_color_point(Context ctx, IndexPartition handle) //-------------------------------------------------------------------------- { return DomainPoint(runtime->get_index_partition_color(ctx, handle)); } //-------------------------------------------------------------------------- DomainPoint Runtime::get_index_partition_color_point(IndexPartition handle) //-------------------------------------------------------------------------- { return DomainPoint(runtime->get_index_partition_color(handle)); } //-------------------------------------------------------------------------- IndexSpace Runtime::get_parent_index_space(Context ctx, IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_parent_index_space(ctx, handle); } //-------------------------------------------------------------------------- IndexSpace Runtime::get_parent_index_space(IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_parent_index_space(handle); } //-------------------------------------------------------------------------- bool Runtime::has_parent_index_partition(Context ctx, IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->has_parent_index_partition(ctx, handle); } //-------------------------------------------------------------------------- bool Runtime::has_parent_index_partition(IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->has_parent_index_partition(handle); } //-------------------------------------------------------------------------- IndexPartition Runtime::get_parent_index_partition(Context ctx, IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_parent_index_partition(ctx, handle); } //-------------------------------------------------------------------------- IndexPartition Runtime::get_parent_index_partition(IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_parent_index_partition(handle); } //-------------------------------------------------------------------------- unsigned Runtime::get_index_space_depth(Context ctx, IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_index_space_depth(ctx, handle); } //-------------------------------------------------------------------------- unsigned Runtime::get_index_space_depth(IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_index_space_depth(handle); } //-------------------------------------------------------------------------- unsigned Runtime::get_index_partition_depth(Context ctx, IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_index_partition_depth(ctx, handle); } //-------------------------------------------------------------------------- unsigned Runtime::get_index_partition_depth(IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_index_partition_depth(handle); } //-------------------------------------------------------------------------- ptr_t Runtime::safe_cast(Context ctx, ptr_t pointer, LogicalRegion region) //-------------------------------------------------------------------------- { if (pointer.is_null()) return pointer; Point<1,coord_t> p(pointer.value); if (runtime->safe_cast(ctx, region, &p, TYPE_TAG_1D)) return pointer; return ptr_t::nil(); } //-------------------------------------------------------------------------- DomainPoint Runtime::safe_cast(Context ctx, DomainPoint point, LogicalRegion region) //-------------------------------------------------------------------------- { switch (point.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> p(point); \ if (runtime->safe_cast(ctx, region, &p, TYPE_TAG_##DIM##D)) \ return point; \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return DomainPoint::nil(); } //-------------------------------------------------------------------------- bool Runtime::safe_cast_internal(Context ctx, LogicalRegion region, const void *realm_point, TypeTag type_tag) //-------------------------------------------------------------------------- { return runtime->safe_cast(ctx, region, realm_point, type_tag); } //-------------------------------------------------------------------------- FieldSpace Runtime::create_field_space(Context ctx) //-------------------------------------------------------------------------- { return runtime->create_field_space(ctx); } //-------------------------------------------------------------------------- void Runtime::destroy_field_space(Context ctx, FieldSpace handle, const bool unordered) //-------------------------------------------------------------------------- { runtime->destroy_field_space(ctx, handle, unordered); } //-------------------------------------------------------------------------- size_t Runtime::get_field_size(Context ctx, FieldSpace handle, FieldID fid) //-------------------------------------------------------------------------- { return runtime->get_field_size(ctx, handle, fid); } //-------------------------------------------------------------------------- size_t Runtime::get_field_size(FieldSpace handle, FieldID fid) //-------------------------------------------------------------------------- { return runtime->get_field_size(handle, fid); } //-------------------------------------------------------------------------- void Runtime::get_field_space_fields(Context ctx, FieldSpace handle, std::vector<FieldID> &fields) //-------------------------------------------------------------------------- { runtime->get_field_space_fields(ctx, handle, fields); } //-------------------------------------------------------------------------- void Runtime::get_field_space_fields(FieldSpace handle, std::vector<FieldID> &fields) //-------------------------------------------------------------------------- { runtime->get_field_space_fields(handle, fields); } //-------------------------------------------------------------------------- void Runtime::get_field_space_fields(Context ctx, FieldSpace handle, std::set<FieldID> &fields) //-------------------------------------------------------------------------- { std::vector<FieldID> local; runtime->get_field_space_fields(ctx, handle, local); fields.insert(local.begin(), local.end()); } //-------------------------------------------------------------------------- void Runtime::get_field_space_fields(FieldSpace handle, std::set<FieldID> &fields) //-------------------------------------------------------------------------- { std::vector<FieldID> local; runtime->get_field_space_fields(handle, local); fields.insert(local.begin(), local.end()); } //-------------------------------------------------------------------------- LogicalRegion Runtime::create_logical_region(Context ctx, IndexSpace index, FieldSpace fields, bool task_local) //-------------------------------------------------------------------------- { return runtime->create_logical_region(ctx, index, fields, task_local); } //-------------------------------------------------------------------------- void Runtime::destroy_logical_region(Context ctx, LogicalRegion handle, const bool unordered) //-------------------------------------------------------------------------- { runtime->destroy_logical_region(ctx, handle, unordered); } //-------------------------------------------------------------------------- void Runtime::destroy_logical_partition(Context ctx,LogicalPartition handle, const bool unordered) //-------------------------------------------------------------------------- { runtime->destroy_logical_partition(ctx, handle, unordered); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition(Context ctx, LogicalRegion parent, IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_logical_partition(ctx, parent, handle); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition(LogicalRegion parent, IndexPartition handle) //-------------------------------------------------------------------------- { return runtime->get_logical_partition(parent, handle); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition_by_color( Context ctx, LogicalRegion parent, Color c) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_by_color(ctx, parent, c); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition_by_color( Context ctx, LogicalRegion parent, const DomainPoint &c) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_by_color(ctx, parent,c.get_color()); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition_by_color( LogicalRegion parent, Color c) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_by_color(parent, c); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition_by_color( LogicalRegion parent, const DomainPoint &c) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_by_color(parent, c.get_color()); } //-------------------------------------------------------------------------- bool Runtime::has_logical_partition_by_color(Context ctx, LogicalRegion parent, const DomainPoint &c) //-------------------------------------------------------------------------- { return runtime->has_logical_partition_by_color(ctx, parent,c.get_color()); } //-------------------------------------------------------------------------- bool Runtime::has_logical_partition_by_color(LogicalRegion parent, const DomainPoint &c) //-------------------------------------------------------------------------- { return runtime->has_logical_partition_by_color(parent, c.get_color()); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition_by_tree( Context ctx, IndexPartition handle, FieldSpace fspace, RegionTreeID tid) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_by_tree(ctx, handle, fspace, tid); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_logical_partition_by_tree( IndexPartition handle, FieldSpace fspace, RegionTreeID tid) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_by_tree(handle, fspace, tid); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion(Context ctx, LogicalPartition parent, IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_logical_subregion(ctx, parent, handle); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion(LogicalPartition parent, IndexSpace handle) //-------------------------------------------------------------------------- { return runtime->get_logical_subregion(parent, handle); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion_by_color(Context ctx, LogicalPartition parent, Color c) //-------------------------------------------------------------------------- { Point<1,coord_t> point(c); return runtime->get_logical_subregion_by_color(ctx, parent, &point, TYPE_TAG_1D); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion_by_color(Context ctx, LogicalPartition parent, const DomainPoint &c) //-------------------------------------------------------------------------- { switch (c.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point(c); \ return runtime->get_logical_subregion_by_color(ctx, parent, \ &point, TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return LogicalRegion::NO_REGION; } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion_by_color( LogicalPartition parent, Color c) //-------------------------------------------------------------------------- { Point<1,coord_t> point(c); return runtime->get_logical_subregion_by_color(parent,&point,TYPE_TAG_1D); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion_by_color( LogicalPartition parent, const DomainPoint &c) //-------------------------------------------------------------------------- { switch (c.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point(c); \ return runtime->get_logical_subregion_by_color(parent, &point, \ TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return LogicalRegion::NO_REGION; } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion_by_color_internal( LogicalPartition parent, const void *realm_color, TypeTag type_tag) //-------------------------------------------------------------------------- { return runtime->get_logical_subregion_by_color(parent, realm_color, type_tag); } //-------------------------------------------------------------------------- bool Runtime::has_logical_subregion_by_color(Context ctx, LogicalPartition parent, const DomainPoint &c) //-------------------------------------------------------------------------- { switch (c.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point(c); \ return runtime->has_logical_subregion_by_color(ctx, parent, &point, \ TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return false; } //-------------------------------------------------------------------------- bool Runtime::has_logical_subregion_by_color(LogicalPartition parent, const DomainPoint &c) //-------------------------------------------------------------------------- { switch (c.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Point<DIM,coord_t> point(c); \ return runtime->has_logical_subregion_by_color(parent, &point, \ TYPE_TAG_##DIM##D); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return false; } //-------------------------------------------------------------------------- bool Runtime::has_logical_subregion_by_color_internal( LogicalPartition parent, const void *realm_color, TypeTag type_tag) //-------------------------------------------------------------------------- { return runtime->has_logical_subregion_by_color(parent, realm_color, type_tag); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion_by_tree(Context ctx, IndexSpace handle, FieldSpace fspace, RegionTreeID tid) //-------------------------------------------------------------------------- { return runtime->get_logical_subregion_by_tree(ctx, handle, fspace, tid); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_logical_subregion_by_tree(IndexSpace handle, FieldSpace fspace, RegionTreeID tid) //-------------------------------------------------------------------------- { return runtime->get_logical_subregion_by_tree(handle, fspace, tid); } //-------------------------------------------------------------------------- Color Runtime::get_logical_region_color(Context ctx, LogicalRegion handle) //-------------------------------------------------------------------------- { Point<1,coord_t> point; runtime->get_logical_region_color(ctx, handle, &point, TYPE_TAG_1D); return point[0]; } //-------------------------------------------------------------------------- DomainPoint Runtime::get_logical_region_color_point(Context ctx, LogicalRegion handle) //-------------------------------------------------------------------------- { return runtime->get_logical_region_color_point(ctx, handle); } //-------------------------------------------------------------------------- Color Runtime::get_logical_region_color(LogicalRegion handle) //-------------------------------------------------------------------------- { Point<1,coord_t> point; runtime->get_logical_region_color(handle, &point, TYPE_TAG_1D); return point[0]; } //-------------------------------------------------------------------------- DomainPoint Runtime::get_logical_region_color_point(LogicalRegion handle) //-------------------------------------------------------------------------- { return runtime->get_logical_region_color_point(handle); } //-------------------------------------------------------------------------- Color Runtime::get_logical_partition_color(Context ctx, LogicalPartition handle) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_color(ctx, handle); } //-------------------------------------------------------------------------- DomainPoint Runtime::get_logical_partition_color_point(Context ctx, LogicalPartition handle) //-------------------------------------------------------------------------- { return DomainPoint(runtime->get_logical_partition_color(ctx, handle)); } //-------------------------------------------------------------------------- Color Runtime::get_logical_partition_color(LogicalPartition handle) //-------------------------------------------------------------------------- { return runtime->get_logical_partition_color(handle); } //-------------------------------------------------------------------------- DomainPoint Runtime::get_logical_partition_color_point( LogicalPartition handle) //-------------------------------------------------------------------------- { return DomainPoint(runtime->get_logical_partition_color(handle)); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_parent_logical_region(Context ctx, LogicalPartition handle) //-------------------------------------------------------------------------- { return runtime->get_parent_logical_region(ctx, handle); } //-------------------------------------------------------------------------- LogicalRegion Runtime::get_parent_logical_region(LogicalPartition handle) //-------------------------------------------------------------------------- { return runtime->get_parent_logical_region(handle); } //-------------------------------------------------------------------------- bool Runtime::has_parent_logical_partition(Context ctx, LogicalRegion handle) //-------------------------------------------------------------------------- { return runtime->has_parent_logical_partition(ctx, handle); } //-------------------------------------------------------------------------- bool Runtime::has_parent_logical_partition(LogicalRegion handle) //-------------------------------------------------------------------------- { return runtime->has_parent_logical_partition(handle); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_parent_logical_partition(Context ctx, LogicalRegion handle) //-------------------------------------------------------------------------- { return runtime->get_parent_logical_partition(ctx, handle); } //-------------------------------------------------------------------------- LogicalPartition Runtime::get_parent_logical_partition(LogicalRegion handle) //-------------------------------------------------------------------------- { return runtime->get_parent_logical_partition(handle); } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif //-------------------------------------------------------------------------- IndexAllocator Runtime::create_index_allocator(Context ctx, IndexSpace is) //-------------------------------------------------------------------------- { Internal::log_run.warning("Dynamic index space allocation is no longer " "supported. You can only make one allocator " "per index space and it must always be in the " "same task that created the index space."); return IndexAllocator(is, IndexIterator(this, ctx, is)); } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic pop #endif //-------------------------------------------------------------------------- FieldAllocator Runtime::create_field_allocator(Context ctx, FieldSpace handle) //-------------------------------------------------------------------------- { return runtime->create_field_allocator(ctx, handle); } //-------------------------------------------------------------------------- ArgumentMap Runtime::create_argument_map(Context ctx) //-------------------------------------------------------------------------- { return runtime->create_argument_map(); } //-------------------------------------------------------------------------- Future Runtime::execute_task(Context ctx, const TaskLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->execute_task(ctx, launcher); } //-------------------------------------------------------------------------- FutureMap Runtime::execute_index_space(Context ctx, const IndexTaskLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->execute_index_space(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::execute_index_space(Context ctx, const IndexTaskLauncher &launcher, ReductionOpID redop, bool deterministic) //-------------------------------------------------------------------------- { return runtime->execute_index_space(ctx, launcher, redop, deterministic); } //-------------------------------------------------------------------------- Future Runtime::execute_task(Context ctx, TaskID task_id, const std::vector<IndexSpaceRequirement> &indexes, const std::vector<FieldSpaceRequirement> &fields, const std::vector<RegionRequirement> &regions, const TaskArgument &arg, const Predicate &predicate, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { TaskLauncher launcher(task_id, arg, predicate, id, tag); launcher.index_requirements = indexes; launcher.region_requirements = regions; return runtime->execute_task(ctx, launcher); } //-------------------------------------------------------------------------- FutureMap Runtime::execute_index_space(Context ctx, TaskID task_id, const Domain domain, const std::vector<IndexSpaceRequirement> &indexes, const std::vector<FieldSpaceRequirement> &fields, const std::vector<RegionRequirement> &regions, const TaskArgument &global_arg, const ArgumentMap &arg_map, const Predicate &predicate, bool must_parallelism, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { IndexTaskLauncher launcher(task_id, domain, global_arg, arg_map, predicate, must_parallelism, id, tag); launcher.index_requirements = indexes; launcher.region_requirements = regions; return runtime->execute_index_space(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::execute_index_space(Context ctx, TaskID task_id, const Domain domain, const std::vector<IndexSpaceRequirement> &indexes, const std::vector<FieldSpaceRequirement> &fields, const std::vector<RegionRequirement> &regions, const TaskArgument &global_arg, const ArgumentMap &arg_map, ReductionOpID reduction, const TaskArgument &initial_value, const Predicate &predicate, bool must_parallelism, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { IndexTaskLauncher launcher(task_id, domain, global_arg, arg_map, predicate, must_parallelism, id, tag); launcher.index_requirements = indexes; launcher.region_requirements = regions; return runtime->execute_index_space(ctx, launcher, reduction, false); } //-------------------------------------------------------------------------- PhysicalRegion Runtime::map_region(Context ctx, const InlineLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->map_region(ctx, launcher); } //-------------------------------------------------------------------------- PhysicalRegion Runtime::map_region(Context ctx, const RegionRequirement &req, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { InlineLauncher launcher(req, id, tag); return runtime->map_region(ctx, launcher); } //-------------------------------------------------------------------------- PhysicalRegion Runtime::map_region(Context ctx, unsigned idx, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return runtime->map_region(ctx, idx, id, tag); } //-------------------------------------------------------------------------- void Runtime::remap_region(Context ctx, PhysicalRegion region) //-------------------------------------------------------------------------- { runtime->remap_region(ctx, region); } //-------------------------------------------------------------------------- void Runtime::unmap_region(Context ctx, PhysicalRegion region) //-------------------------------------------------------------------------- { runtime->unmap_region(ctx, region); } //-------------------------------------------------------------------------- void Runtime::unmap_all_regions(Context ctx) //-------------------------------------------------------------------------- { runtime->unmap_all_regions(ctx); } //-------------------------------------------------------------------------- void Runtime::fill_field(Context ctx, LogicalRegion handle, LogicalRegion parent, FieldID fid, const void *value, size_t size, Predicate pred) //-------------------------------------------------------------------------- { FillLauncher launcher(handle, parent, TaskArgument(value, size), pred); launcher.add_field(fid); runtime->fill_fields(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::fill_field(Context ctx, LogicalRegion handle, LogicalRegion parent, FieldID fid, Future f, Predicate pred) //-------------------------------------------------------------------------- { FillLauncher launcher(handle, parent, TaskArgument(), pred); launcher.set_future(f); launcher.add_field(fid); runtime->fill_fields(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::fill_fields(Context ctx, LogicalRegion handle, LogicalRegion parent, const std::set<FieldID> &fields, const void *value, size_t size, Predicate pred) //-------------------------------------------------------------------------- { FillLauncher launcher(handle, parent, TaskArgument(value, size), pred); launcher.fields = fields; runtime->fill_fields(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::fill_fields(Context ctx, LogicalRegion handle, LogicalRegion parent, const std::set<FieldID> &fields, Future f, Predicate pred) //-------------------------------------------------------------------------- { FillLauncher launcher(handle, parent, TaskArgument(), pred); launcher.set_future(f); launcher.fields = fields; runtime->fill_fields(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::fill_fields(Context ctx, const FillLauncher &launcher) //-------------------------------------------------------------------------- { runtime->fill_fields(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::fill_fields(Context ctx, const IndexFillLauncher &launcher) //-------------------------------------------------------------------------- { runtime->fill_fields(ctx, launcher); } //-------------------------------------------------------------------------- PhysicalRegion Runtime::attach_external_resource(Context ctx, const AttachLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->attach_external_resource(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::detach_external_resource(Context ctx, PhysicalRegion region, const bool flush /*= true*/, const bool unordered/*= false*/) //-------------------------------------------------------------------------- { return runtime->detach_external_resource(ctx, region, flush, unordered); } //-------------------------------------------------------------------------- void Runtime::progress_unordered_operations(Context ctx) //-------------------------------------------------------------------------- { runtime->progress_unordered_operations(ctx); } //-------------------------------------------------------------------------- PhysicalRegion Runtime::attach_hdf5(Context ctx, const char *file_name, LogicalRegion handle, LogicalRegion parent, const std::map<FieldID,const char*> &field_map, LegionFileMode mode) //-------------------------------------------------------------------------- { AttachLauncher launcher(EXTERNAL_HDF5_FILE, handle, parent); launcher.attach_hdf5(file_name, field_map, mode); return runtime->attach_external_resource(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::detach_hdf5(Context ctx, PhysicalRegion region) //-------------------------------------------------------------------------- { runtime->detach_external_resource(ctx, region, true/*flush*/, false/*unordered*/); } //-------------------------------------------------------------------------- PhysicalRegion Runtime::attach_file(Context ctx, const char *file_name, LogicalRegion handle, LogicalRegion parent, const std::vector<FieldID> &field_vec, LegionFileMode mode) //-------------------------------------------------------------------------- { AttachLauncher launcher(EXTERNAL_POSIX_FILE, handle, parent); launcher.attach_file(file_name, field_vec, mode); return runtime->attach_external_resource(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::detach_file(Context ctx, PhysicalRegion region) //-------------------------------------------------------------------------- { runtime->detach_external_resource(ctx, region, true/*flush*/, false/*unordered*/); } //-------------------------------------------------------------------------- void Runtime::issue_copy_operation(Context ctx,const CopyLauncher &launcher) //-------------------------------------------------------------------------- { runtime->issue_copy_operation(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::issue_copy_operation(Context ctx, const IndexCopyLauncher &launcher) //-------------------------------------------------------------------------- { runtime->issue_copy_operation(ctx, launcher); } //-------------------------------------------------------------------------- Predicate Runtime::create_predicate(Context ctx, const Future &f) //-------------------------------------------------------------------------- { return runtime->create_predicate(ctx, f); } //-------------------------------------------------------------------------- Predicate Runtime::predicate_not(Context ctx, const Predicate &p) //-------------------------------------------------------------------------- { return runtime->predicate_not(ctx, p); } //-------------------------------------------------------------------------- Predicate Runtime::predicate_and(Context ctx, const Predicate &p1, const Predicate &p2) //-------------------------------------------------------------------------- { PredicateLauncher launcher(true/*and*/); launcher.add_predicate(p1); launcher.add_predicate(p2); return runtime->create_predicate(ctx, launcher); } //-------------------------------------------------------------------------- Predicate Runtime::predicate_or(Context ctx, const Predicate &p1, const Predicate &p2) //-------------------------------------------------------------------------- { PredicateLauncher launcher(false/*and*/); launcher.add_predicate(p1); launcher.add_predicate(p2); return runtime->create_predicate(ctx, launcher); } //-------------------------------------------------------------------------- Predicate Runtime::create_predicate(Context ctx, const PredicateLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->create_predicate(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::get_predicate_future(Context ctx, const Predicate &p) //-------------------------------------------------------------------------- { return runtime->get_predicate_future(ctx, p); } //-------------------------------------------------------------------------- Lock Runtime::create_lock(Context ctx) //-------------------------------------------------------------------------- { return runtime->create_lock(ctx); } //-------------------------------------------------------------------------- void Runtime::destroy_lock(Context ctx, Lock l) //-------------------------------------------------------------------------- { runtime->destroy_lock(ctx, l); } //-------------------------------------------------------------------------- Grant Runtime::acquire_grant(Context ctx, const std::vector<LockRequest> &requests) //-------------------------------------------------------------------------- { return runtime->acquire_grant(ctx, requests); } //-------------------------------------------------------------------------- void Runtime::release_grant(Context ctx, Grant grant) //-------------------------------------------------------------------------- { runtime->release_grant(ctx, grant); } //-------------------------------------------------------------------------- PhaseBarrier Runtime::create_phase_barrier(Context ctx, unsigned arrivals) //-------------------------------------------------------------------------- { return runtime->create_phase_barrier(ctx, arrivals); } //-------------------------------------------------------------------------- void Runtime::destroy_phase_barrier(Context ctx, PhaseBarrier pb) //-------------------------------------------------------------------------- { runtime->destroy_phase_barrier(ctx, pb); } //-------------------------------------------------------------------------- PhaseBarrier Runtime::advance_phase_barrier(Context ctx, PhaseBarrier pb) //-------------------------------------------------------------------------- { return runtime->advance_phase_barrier(ctx, pb); } //-------------------------------------------------------------------------- DynamicCollective Runtime::create_dynamic_collective(Context ctx, unsigned arrivals, ReductionOpID redop, const void *init_value, size_t init_size) //-------------------------------------------------------------------------- { return runtime->create_dynamic_collective(ctx, arrivals, redop, init_value, init_size); } //-------------------------------------------------------------------------- void Runtime::destroy_dynamic_collective(Context ctx, DynamicCollective dc) //-------------------------------------------------------------------------- { runtime->destroy_dynamic_collective(ctx, dc); } //-------------------------------------------------------------------------- void Runtime::arrive_dynamic_collective(Context ctx, DynamicCollective dc, const void *buffer, size_t size, unsigned count) //-------------------------------------------------------------------------- { runtime->arrive_dynamic_collective(ctx, dc, buffer, size, count); } //-------------------------------------------------------------------------- void Runtime::defer_dynamic_collective_arrival(Context ctx, DynamicCollective dc, const Future &f, unsigned count) //-------------------------------------------------------------------------- { runtime->defer_dynamic_collective_arrival(ctx, dc, f, count); } //-------------------------------------------------------------------------- Future Runtime::get_dynamic_collective_result(Context ctx, DynamicCollective dc) //-------------------------------------------------------------------------- { return runtime->get_dynamic_collective_result(ctx, dc); } //-------------------------------------------------------------------------- DynamicCollective Runtime::advance_dynamic_collective(Context ctx, DynamicCollective dc) //-------------------------------------------------------------------------- { return runtime->advance_dynamic_collective(ctx, dc); } //-------------------------------------------------------------------------- void Runtime::issue_acquire(Context ctx, const AcquireLauncher &launcher) //-------------------------------------------------------------------------- { runtime->issue_acquire(ctx, launcher); } //-------------------------------------------------------------------------- void Runtime::issue_release(Context ctx, const ReleaseLauncher &launcher) //-------------------------------------------------------------------------- { runtime->issue_release(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::issue_mapping_fence(Context ctx) //-------------------------------------------------------------------------- { return runtime->issue_mapping_fence(ctx); } //-------------------------------------------------------------------------- Future Runtime::issue_execution_fence(Context ctx) //-------------------------------------------------------------------------- { return runtime->issue_execution_fence(ctx); } //-------------------------------------------------------------------------- void Runtime::begin_trace( Context ctx, TraceID tid, bool logical_only /*= false*/) //-------------------------------------------------------------------------- { runtime->begin_trace(ctx, tid, logical_only); } //-------------------------------------------------------------------------- void Runtime::end_trace(Context ctx, TraceID tid) //-------------------------------------------------------------------------- { runtime->end_trace(ctx, tid); } //-------------------------------------------------------------------------- void Runtime::begin_static_trace(Context ctx, const std::set<RegionTreeID> *managed) //-------------------------------------------------------------------------- { runtime->begin_static_trace(ctx, managed); } //-------------------------------------------------------------------------- void Runtime::end_static_trace(Context ctx) //-------------------------------------------------------------------------- { runtime->end_static_trace(ctx); } //-------------------------------------------------------------------------- TraceID Runtime::generate_dynamic_trace_id(void) //-------------------------------------------------------------------------- { return runtime->generate_dynamic_trace_id(); } //-------------------------------------------------------------------------- TraceID Runtime::generate_library_trace_ids(const char *name, size_t count) //-------------------------------------------------------------------------- { return runtime->generate_library_trace_ids(name, count); } //-------------------------------------------------------------------------- /*static*/ TraceID Runtime::generate_static_trace_id(void) //-------------------------------------------------------------------------- { return Internal::Runtime::generate_static_trace_id(); } //-------------------------------------------------------------------------- void Runtime::complete_frame(Context ctx) //-------------------------------------------------------------------------- { runtime->complete_frame(ctx); } //-------------------------------------------------------------------------- FutureMap Runtime::execute_must_epoch(Context ctx, const MustEpochLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->execute_must_epoch(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::select_tunable_value(Context ctx, TunableID tid, MapperID mid, MappingTagID tag, const void *args, size_t argsize) //-------------------------------------------------------------------------- { return runtime->select_tunable_value(ctx, tid, mid, tag, args, argsize); } //-------------------------------------------------------------------------- int Runtime::get_tunable_value(Context ctx, TunableID tid, MapperID mid, MappingTagID tag) //-------------------------------------------------------------------------- { return runtime->get_tunable_value(ctx, tid, mid, tag); } //-------------------------------------------------------------------------- const Task* Runtime::get_local_task(Context ctx) //-------------------------------------------------------------------------- { return ctx->get_task(); } //-------------------------------------------------------------------------- void* Runtime::get_local_task_variable_untyped(Context ctx, LocalVariableID id) //-------------------------------------------------------------------------- { return runtime->get_local_task_variable(ctx, id); } //-------------------------------------------------------------------------- void Runtime::set_local_task_variable_untyped(Context ctx, LocalVariableID id, const void* value, void (*destructor)(void*)) //-------------------------------------------------------------------------- { runtime->set_local_task_variable(ctx, id, value, destructor); } //-------------------------------------------------------------------------- Future Runtime::get_current_time(Context ctx, Future precondition) //-------------------------------------------------------------------------- { TimingLauncher launcher(MEASURE_SECONDS); launcher.add_precondition(precondition); return runtime->issue_timing_measurement(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::get_current_time_in_microseconds(Context ctx, Future pre) //-------------------------------------------------------------------------- { TimingLauncher launcher(MEASURE_MICRO_SECONDS); launcher.add_precondition(pre); return runtime->issue_timing_measurement(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::get_current_time_in_nanoseconds(Context ctx, Future pre) //-------------------------------------------------------------------------- { TimingLauncher launcher(MEASURE_NANO_SECONDS); launcher.add_precondition(pre); return runtime->issue_timing_measurement(ctx, launcher); } //-------------------------------------------------------------------------- Future Runtime::issue_timing_measurement(Context ctx, const TimingLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->issue_timing_measurement(ctx, launcher); } //-------------------------------------------------------------------------- /*static*/ long long Runtime::get_zero_time(void) //-------------------------------------------------------------------------- { return Realm::Clock::get_zero_time(); } //-------------------------------------------------------------------------- Mapping::Mapper* Runtime::get_mapper(Context ctx, MapperID id, Processor target) //-------------------------------------------------------------------------- { return runtime->get_mapper(ctx, id, target); } //-------------------------------------------------------------------------- Processor Runtime::get_executing_processor(Context ctx) //-------------------------------------------------------------------------- { return runtime->get_executing_processor(ctx); } //-------------------------------------------------------------------------- const Task* Runtime::get_current_task(Context ctx) //-------------------------------------------------------------------------- { if (ctx == DUMMY_CONTEXT) return NULL; return ctx->get_task(); } //-------------------------------------------------------------------------- void Runtime::raise_region_exception(Context ctx, PhysicalRegion region, bool nuclear) //-------------------------------------------------------------------------- { runtime->raise_region_exception(ctx, region, nuclear); } //-------------------------------------------------------------------------- void Runtime::yield(Context ctx) //-------------------------------------------------------------------------- { runtime->yield(ctx); } //-------------------------------------------------------------------------- const std::map<int,AddressSpace>& Runtime::find_forward_MPI_mapping(void) //-------------------------------------------------------------------------- { return runtime->find_forward_MPI_mapping(); } //-------------------------------------------------------------------------- const std::map<AddressSpace,int>& Runtime::find_reverse_MPI_mapping(void) //-------------------------------------------------------------------------- { return runtime->find_reverse_MPI_mapping(); } //-------------------------------------------------------------------------- int Runtime::find_local_MPI_rank(void) //-------------------------------------------------------------------------- { return runtime->find_local_MPI_rank(); } //-------------------------------------------------------------------------- bool Runtime::is_MPI_interop_configured(void) //-------------------------------------------------------------------------- { return runtime->is_MPI_interop_configured(); } //-------------------------------------------------------------------------- Mapping::MapperRuntime* Runtime::get_mapper_runtime(void) //-------------------------------------------------------------------------- { return runtime->get_mapper_runtime(); } //-------------------------------------------------------------------------- MapperID Runtime::generate_dynamic_mapper_id(void) //-------------------------------------------------------------------------- { return runtime->generate_dynamic_mapper_id(); } //-------------------------------------------------------------------------- MapperID Runtime::generate_library_mapper_ids(const char *name, size_t cnt) //-------------------------------------------------------------------------- { return runtime->generate_library_mapper_ids(name, cnt); } //-------------------------------------------------------------------------- /*static*/ MapperID Runtime::generate_static_mapper_id(void) //-------------------------------------------------------------------------- { return Internal::Runtime::generate_static_mapper_id(); } //-------------------------------------------------------------------------- void Runtime::add_mapper(MapperID map_id, Mapping::Mapper *mapper, Processor proc) //-------------------------------------------------------------------------- { runtime->add_mapper(map_id, mapper, proc); } //-------------------------------------------------------------------------- void Runtime::replace_default_mapper(Mapping::Mapper *mapper,Processor proc) //-------------------------------------------------------------------------- { runtime->replace_default_mapper(mapper, proc); } //-------------------------------------------------------------------------- ProjectionID Runtime::generate_dynamic_projection_id(void) //-------------------------------------------------------------------------- { return runtime->generate_dynamic_projection_id(); } //-------------------------------------------------------------------------- ProjectionID Runtime::generate_library_projection_ids(const char *name, size_t count) //-------------------------------------------------------------------------- { return runtime->generate_library_projection_ids(name, count); } //-------------------------------------------------------------------------- /*static*/ ProjectionID Runtime::generate_static_projection_id(void) //-------------------------------------------------------------------------- { return Internal::Runtime::generate_static_projection_id(); } //-------------------------------------------------------------------------- void Runtime::register_projection_functor(ProjectionID pid, ProjectionFunctor *func, bool silence_warnings, const char *warning_string) //-------------------------------------------------------------------------- { runtime->register_projection_functor(pid, func, true/*need zero check*/, silence_warnings, warning_string); } //-------------------------------------------------------------------------- /*static*/ void Runtime::preregister_projection_functor(ProjectionID pid, ProjectionFunctor *func) //-------------------------------------------------------------------------- { Internal::Runtime::preregister_projection_functor(pid, func); } //-------------------------------------------------------------------------- ShardingID Runtime::generate_dynamic_sharding_id(void) //-------------------------------------------------------------------------- { // Not implemented until control replication return 0; } //-------------------------------------------------------------------------- ShardingID Runtime::generate_library_sharding_ids( const char *name, size_t count) //-------------------------------------------------------------------------- { // Not implemented until control replication return 0; } //-------------------------------------------------------------------------- ShardingID Runtime::generate_static_sharding_id(void) //-------------------------------------------------------------------------- { // Not implemented until control replication return 0; } //-------------------------------------------------------------------------- void Runtime::register_sharding_functor(ShardingID sid, ShardingFunctor *functor, bool silence_warnings, const char *warning_string) //-------------------------------------------------------------------------- { // Not implemented until control replication } //-------------------------------------------------------------------------- /*static*/ void Runtime::preregister_sharding_functor(ShardingID sid, ShardingFunctor *functor) //-------------------------------------------------------------------------- { // Not implemented until control replication } //-------------------------------------------------------------------------- void Runtime::attach_semantic_information(TaskID task_id, SemanticTag tag, const void *buffer, size_t size, bool is_mut, bool local) //-------------------------------------------------------------------------- { runtime->attach_semantic_information(task_id, tag, buffer, size, is_mut, !local); } //-------------------------------------------------------------------------- void Runtime::attach_semantic_information(IndexSpace handle, SemanticTag tag, const void *buffer, size_t size, bool is_mut) //-------------------------------------------------------------------------- { runtime->attach_semantic_information(handle, tag, buffer, size, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_semantic_information(IndexPartition handle, SemanticTag tag, const void *buffer, size_t size, bool is_mut) //-------------------------------------------------------------------------- { runtime->attach_semantic_information(handle, tag, buffer, size, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_semantic_information(FieldSpace handle, SemanticTag tag, const void *buffer, size_t size, bool is_mut) //-------------------------------------------------------------------------- { runtime->attach_semantic_information(handle, tag, buffer, size, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_semantic_information(FieldSpace handle, FieldID fid, SemanticTag tag, const void *buffer, size_t size, bool is_mut) //-------------------------------------------------------------------------- { runtime->attach_semantic_information(handle, fid, tag, buffer, size, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_semantic_information(LogicalRegion handle, SemanticTag tag, const void *buffer, size_t size, bool is_mut) //-------------------------------------------------------------------------- { runtime->attach_semantic_information(handle, tag, buffer, size, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_semantic_information(LogicalPartition handle, SemanticTag tag, const void *buffer, size_t size, bool is_mut) //-------------------------------------------------------------------------- { runtime->attach_semantic_information(handle, tag, buffer, size, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_name(TaskID task_id, const char *name, bool is_mutable, bool local_only) //-------------------------------------------------------------------------- { Runtime::attach_semantic_information(task_id, NAME_SEMANTIC_TAG, name, strlen(name) + 1, is_mutable, local_only); } //-------------------------------------------------------------------------- void Runtime::attach_name(IndexSpace handle, const char *name, bool is_mut) //-------------------------------------------------------------------------- { Runtime::attach_semantic_information(handle, NAME_SEMANTIC_TAG, name, strlen(name) + 1, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_name(IndexPartition handle, const char *name, bool ism) //-------------------------------------------------------------------------- { Runtime::attach_semantic_information(handle, NAME_SEMANTIC_TAG, name, strlen(name) + 1, ism); } //-------------------------------------------------------------------------- void Runtime::attach_name(FieldSpace handle, const char *name, bool is_mut) //-------------------------------------------------------------------------- { Runtime::attach_semantic_information(handle, NAME_SEMANTIC_TAG, name, strlen(name) + 1, is_mut); } //-------------------------------------------------------------------------- void Runtime::attach_name(FieldSpace handle, FieldID fid, const char *name, bool is_mutable) //-------------------------------------------------------------------------- { Runtime::attach_semantic_information(handle, fid, NAME_SEMANTIC_TAG, name, strlen(name) + 1, is_mutable); } //-------------------------------------------------------------------------- void Runtime::attach_name(LogicalRegion handle, const char *name, bool ism) //-------------------------------------------------------------------------- { Runtime::attach_semantic_information(handle, NAME_SEMANTIC_TAG, name, strlen(name) + 1, ism); } //-------------------------------------------------------------------------- void Runtime::attach_name(LogicalPartition handle, const char *name, bool m) //-------------------------------------------------------------------------- { Runtime::attach_semantic_information(handle, NAME_SEMANTIC_TAG, name, strlen(name) + 1, m); } //-------------------------------------------------------------------------- bool Runtime::retrieve_semantic_information(TaskID task_id, SemanticTag tag, const void *&result, size_t &size, bool can_fail, bool wait_until) //-------------------------------------------------------------------------- { return runtime->retrieve_semantic_information(task_id, tag, result, size, can_fail, wait_until); } //-------------------------------------------------------------------------- bool Runtime::retrieve_semantic_information(IndexSpace handle, SemanticTag tag, const void *&result, size_t &size, bool can_fail, bool wait_until) //-------------------------------------------------------------------------- { return runtime->retrieve_semantic_information(handle, tag, result, size, can_fail, wait_until); } //-------------------------------------------------------------------------- bool Runtime::retrieve_semantic_information(IndexPartition handle, SemanticTag tag, const void *&result, size_t &size, bool can_fail, bool wait_until) //-------------------------------------------------------------------------- { return runtime->retrieve_semantic_information(handle, tag, result, size, can_fail, wait_until); } //-------------------------------------------------------------------------- bool Runtime::retrieve_semantic_information(FieldSpace handle, SemanticTag tag, const void *&result, size_t &size, bool can_fail, bool wait_until) //-------------------------------------------------------------------------- { return runtime->retrieve_semantic_information(handle, tag, result, size, can_fail, wait_until); } //-------------------------------------------------------------------------- bool Runtime::retrieve_semantic_information(FieldSpace handle, FieldID fid, SemanticTag tag, const void *&result, size_t &size, bool can_fail, bool wait_until) //-------------------------------------------------------------------------- { return runtime->retrieve_semantic_information(handle, fid, tag, result, size, can_fail, wait_until); } //-------------------------------------------------------------------------- bool Runtime::retrieve_semantic_information(LogicalRegion handle, SemanticTag tag, const void *&result, size_t &size, bool can_fail, bool wait_until) //-------------------------------------------------------------------------- { return runtime->retrieve_semantic_information(handle, tag, result, size, can_fail, wait_until); } //-------------------------------------------------------------------------- bool Runtime::retrieve_semantic_information(LogicalPartition part, SemanticTag tag, const void *&result, size_t &size, bool can_fail, bool wait_until) //-------------------------------------------------------------------------- { return runtime->retrieve_semantic_information(part, tag, result, size, can_fail, wait_until); } //-------------------------------------------------------------------------- void Runtime::retrieve_name(TaskID task_id, const char *&result) //-------------------------------------------------------------------------- { const void* dummy_ptr; size_t dummy_size; Runtime::retrieve_semantic_information(task_id, NAME_SEMANTIC_TAG, dummy_ptr, dummy_size, false, false); result = reinterpret_cast<const char*>(dummy_ptr); } //-------------------------------------------------------------------------- void Runtime::retrieve_name(IndexSpace handle, const char *&result) //-------------------------------------------------------------------------- { const void* dummy_ptr; size_t dummy_size; Runtime::retrieve_semantic_information(handle, NAME_SEMANTIC_TAG, dummy_ptr, dummy_size, false, false); result = reinterpret_cast<const char*>(dummy_ptr); } //-------------------------------------------------------------------------- void Runtime::retrieve_name(IndexPartition handle, const char *&result) //-------------------------------------------------------------------------- { const void* dummy_ptr; size_t dummy_size; Runtime::retrieve_semantic_information(handle, NAME_SEMANTIC_TAG, dummy_ptr, dummy_size, false, false); result = reinterpret_cast<const char*>(dummy_ptr); } //-------------------------------------------------------------------------- void Runtime::retrieve_name(FieldSpace handle, const char *&result) //-------------------------------------------------------------------------- { const void* dummy_ptr; size_t dummy_size; Runtime::retrieve_semantic_information(handle, NAME_SEMANTIC_TAG, dummy_ptr, dummy_size, false, false); result = reinterpret_cast<const char*>(dummy_ptr); } //-------------------------------------------------------------------------- void Runtime::retrieve_name(FieldSpace handle, FieldID fid, const char *&result) //-------------------------------------------------------------------------- { const void* dummy_ptr; size_t dummy_size; Runtime::retrieve_semantic_information(handle, fid, NAME_SEMANTIC_TAG, dummy_ptr, dummy_size, false, false); result = reinterpret_cast<const char*>(dummy_ptr); } //-------------------------------------------------------------------------- void Runtime::retrieve_name(LogicalRegion handle, const char *&result) //-------------------------------------------------------------------------- { const void* dummy_ptr; size_t dummy_size; Runtime::retrieve_semantic_information(handle, NAME_SEMANTIC_TAG, dummy_ptr, dummy_size, false, false); result = reinterpret_cast<const char*>(dummy_ptr); } //-------------------------------------------------------------------------- void Runtime::retrieve_name(LogicalPartition part, const char *&result) //-------------------------------------------------------------------------- { const void* dummy_ptr; size_t dummy_size; Runtime::retrieve_semantic_information(part, NAME_SEMANTIC_TAG, dummy_ptr, dummy_size, false, false); result = reinterpret_cast<const char*>(dummy_ptr); } //-------------------------------------------------------------------------- void Runtime::print_once(Context ctx, FILE *f, const char *message) //-------------------------------------------------------------------------- { fprintf(f, "%s", message); } //-------------------------------------------------------------------------- void Runtime::log_once(Context ctx, Realm::LoggerMessage &message) //-------------------------------------------------------------------------- { // Do nothing, just don't deactivate it } //-------------------------------------------------------------------------- Future Runtime::from_value(const void *value, size_t value_size, bool owned) //-------------------------------------------------------------------------- { Future result = runtime->help_create_future(Internal::ApEvent::NO_AP_EVENT); // Set the future result result.impl->set_result(value, value_size, owned); return result; } //-------------------------------------------------------------------------- /*static*/ int Runtime::start(int argc, char **argv, bool background) //-------------------------------------------------------------------------- { return Internal::Runtime::start(argc, argv, background); } //-------------------------------------------------------------------------- /*static*/ void Runtime::initialize(int *argc, char ***argv) //-------------------------------------------------------------------------- { Internal::Runtime::initialize(argc, argv); } //-------------------------------------------------------------------------- /*static*/ int Runtime::wait_for_shutdown(void) //-------------------------------------------------------------------------- { return Internal::Runtime::wait_for_shutdown(); } //-------------------------------------------------------------------------- Future Runtime::launch_top_level_task(const TaskLauncher &launcher) //-------------------------------------------------------------------------- { return runtime->launch_top_level_task(launcher); } //-------------------------------------------------------------------------- Context Runtime::begin_implicit_task(TaskID top_task_id, MapperID top_mapper_id, Processor::Kind proc_kind, const char *task_name, bool control_replicable, unsigned shard_per_address_space, int shard_id) //-------------------------------------------------------------------------- { return runtime->begin_implicit_task(top_task_id, top_mapper_id, proc_kind, task_name, control_replicable, shard_per_address_space, shard_id); } //-------------------------------------------------------------------------- void Runtime::finish_implicit_task(Context ctx) //-------------------------------------------------------------------------- { runtime->finish_implicit_task(ctx); } //-------------------------------------------------------------------------- /*static*/ void Runtime::set_top_level_task_id(TaskID top_id) //-------------------------------------------------------------------------- { Internal::Runtime::set_top_level_task_id(top_id); } //-------------------------------------------------------------------------- /*static*/ void Runtime::set_top_level_task_mapper_id(MapperID mapper_id) //-------------------------------------------------------------------------- { Internal::Runtime::set_top_level_task_mapper_id(mapper_id); } //-------------------------------------------------------------------------- /*static*/ size_t Runtime::get_maximum_dimension(void) //-------------------------------------------------------------------------- { return LEGION_MAX_DIM; } //-------------------------------------------------------------------------- /*static*/ void Runtime::configure_MPI_interoperability(int rank) //-------------------------------------------------------------------------- { Internal::Runtime::configure_MPI_interoperability(rank); } //-------------------------------------------------------------------------- /*static*/ MPILegionHandshake Runtime::create_handshake(bool init_in_MPI, int mpi_participants, int legion_participants) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(mpi_participants > 0); assert(legion_participants > 0); #endif MPILegionHandshake result( new Internal::MPILegionHandshakeImpl(init_in_MPI, mpi_participants, legion_participants)); Internal::Runtime::register_handshake(result); return result; } //-------------------------------------------------------------------------- /*static*/ void Runtime::register_reduction_op(ReductionOpID redop_id, ReductionOp *redop, SerdezInitFnptr init_fnptr, SerdezFoldFnptr fold_fnptr, bool permit_duplicates) //-------------------------------------------------------------------------- { Internal::Runtime::register_reduction_op(redop_id, redop, init_fnptr, fold_fnptr, permit_duplicates); } //-------------------------------------------------------------------------- /*static*/ const ReductionOp* Runtime::get_reduction_op( ReductionOpID redop_id) //-------------------------------------------------------------------------- { return Internal::Runtime::get_reduction_op(redop_id); } //-------------------------------------------------------------------------- /*static*/ void Runtime::register_custom_serdez_op(CustomSerdezID serdez_id, SerdezOp *serdez_op, bool permit_duplicates) //-------------------------------------------------------------------------- { Internal::Runtime::register_serdez_op(serdez_id, serdez_op, permit_duplicates); } //-------------------------------------------------------------------------- /*static*/ const SerdezOp* Runtime::get_serdez_op(CustomSerdezID serdez_id) //-------------------------------------------------------------------------- { return Internal::Runtime::get_serdez_op(serdez_id); } //-------------------------------------------------------------------------- /*static*/ void Runtime::add_registration_callback( RegistrationCallbackFnptr callback) //-------------------------------------------------------------------------- { Internal::Runtime::add_registration_callback(callback); } //-------------------------------------------------------------------------- /*static*/ void Runtime::set_registration_callback( RegistrationCallbackFnptr callback) //-------------------------------------------------------------------------- { Internal::Runtime::add_registration_callback(callback); } //-------------------------------------------------------------------------- /*static*/ const InputArgs& Runtime::get_input_args(void) //-------------------------------------------------------------------------- { if (!Internal::Runtime::runtime_started) REPORT_LEGION_ERROR(ERROR_DYNAMIC_CALL_PRE_RUNTIME_START, "Illegal call to 'get_input_args' before the runtime is started") if (Internal::implicit_runtime != NULL) return Internal::implicit_runtime->input_args; // Otherwise this is not from a Legion task, so fallback to the_runtime return Internal::Runtime::the_runtime->input_args; } //-------------------------------------------------------------------------- /*static*/ Runtime* Runtime::get_runtime(Processor p) //-------------------------------------------------------------------------- { if (!Internal::Runtime::runtime_started) REPORT_LEGION_ERROR(ERROR_DYNAMIC_CALL_PRE_RUNTIME_START, "Illegal call to 'get_runtime' before the runtime is started") // If we have an implicit runtime we use that if (Internal::implicit_runtime != NULL) return Internal::implicit_runtime->external; // Otherwise this is not from a Legion task, so fallback to the_runtime return Internal::Runtime::the_runtime->external; } //-------------------------------------------------------------------------- /*static*/ Context Runtime::get_context(void) //-------------------------------------------------------------------------- { return Internal::implicit_context; } //-------------------------------------------------------------------------- TaskID Runtime::generate_dynamic_task_id(void) //-------------------------------------------------------------------------- { return runtime->generate_dynamic_task_id(); } //-------------------------------------------------------------------------- TaskID Runtime::generate_library_task_ids(const char *name, size_t count) //-------------------------------------------------------------------------- { return runtime->generate_library_task_ids(name, count); } //-------------------------------------------------------------------------- /*static*/ TaskID Runtime::generate_static_task_id(void) //-------------------------------------------------------------------------- { return Internal::Runtime::generate_static_task_id(); } //-------------------------------------------------------------------------- ReductionOpID Runtime::generate_dynamic_reduction_id(void) //-------------------------------------------------------------------------- { return runtime->generate_dynamic_reduction_id(); } //-------------------------------------------------------------------------- ReductionOpID Runtime::generate_library_reduction_ids(const char *name, size_t count) //-------------------------------------------------------------------------- { return runtime->generate_library_reduction_ids(name, count); } //-------------------------------------------------------------------------- /*static*/ ReductionOpID Runtime::generate_static_reduction_id(void) //-------------------------------------------------------------------------- { return Internal::Runtime::generate_static_reduction_id(); } //-------------------------------------------------------------------------- CustomSerdezID Runtime::generate_dynamic_serdez_id(void) //-------------------------------------------------------------------------- { return runtime->generate_dynamic_serdez_id(); } //-------------------------------------------------------------------------- CustomSerdezID Runtime::generate_library_serdez_ids(const char *name, size_t count) //-------------------------------------------------------------------------- { return runtime->generate_library_serdez_ids(name, count); } //-------------------------------------------------------------------------- /*static*/ CustomSerdezID Runtime::generate_static_serdez_id(void) //-------------------------------------------------------------------------- { return Internal::Runtime::generate_static_serdez_id(); } //-------------------------------------------------------------------------- VariantID Runtime::register_task_variant( const TaskVariantRegistrar &registrar, const CodeDescriptor &codedesc, const void *user_data /*= NULL*/, size_t user_len /*= 0*/, bool has_return_type /*= false*/, VariantID vid /*= AUTO_GENERATE_ID*/) //-------------------------------------------------------------------------- { // Make a copy of the descriptor here CodeDescriptor *realm_desc = new CodeDescriptor(codedesc); return runtime->register_variant(registrar, user_data, user_len, realm_desc, has_return_type, vid); } //-------------------------------------------------------------------------- /*static*/ VariantID Runtime::preregister_task_variant( const TaskVariantRegistrar &registrar, const CodeDescriptor &codedesc, const void *user_data /*= NULL*/, size_t user_len /*= 0*/, const char *task_name /*= NULL*/, VariantID vid /*=AUTO_GENERATE_ID*/, bool has_return_type/*=false*/, bool check_task_id/*=true*/) //-------------------------------------------------------------------------- { // Make a copy of the descriptor here CodeDescriptor *realm_desc = new CodeDescriptor(codedesc); return Internal::Runtime::preregister_variant(registrar, user_data, user_len, realm_desc, has_return_type, task_name, vid, check_task_id); } //-------------------------------------------------------------------------- /*static*/ void Runtime::legion_task_preamble( const void *data, size_t datalen, Processor p, const Task *& task, const std::vector<PhysicalRegion> *& reg, Context& ctx, Runtime *& runtime) //-------------------------------------------------------------------------- { // Read the context out of the buffer #ifdef DEBUG_LEGION assert(datalen == sizeof(Context)); #endif ctx = *((const Context*)data); task = ctx->get_task(); reg = &ctx->begin_task(runtime); } //-------------------------------------------------------------------------- /*static*/ void Runtime::legion_task_postamble(Runtime *runtime,Context ctx, const void *retvalptr, size_t retvalsize) //-------------------------------------------------------------------------- { ctx->end_task(retvalptr, retvalsize, false/*owned*/); } //-------------------------------------------------------------------------- /*static*/ void Runtime::enable_profiling(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- /*static*/ void Runtime::disable_profiling(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- /*static*/ void Runtime::dump_profiling(void) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- LayoutConstraintID Runtime::register_layout( const LayoutConstraintRegistrar &registrar) //-------------------------------------------------------------------------- { return runtime->register_layout(registrar, AUTO_GENERATE_ID); } //-------------------------------------------------------------------------- void Runtime::release_layout(LayoutConstraintID layout_id) //-------------------------------------------------------------------------- { runtime->release_layout(layout_id); } //-------------------------------------------------------------------------- /*static*/ LayoutConstraintID Runtime::preregister_layout( const LayoutConstraintRegistrar &registrar, LayoutConstraintID layout_id) //-------------------------------------------------------------------------- { return Internal::Runtime::preregister_layout(registrar, layout_id); } //-------------------------------------------------------------------------- FieldSpace Runtime::get_layout_constraint_field_space( LayoutConstraintID layout_id) //-------------------------------------------------------------------------- { return runtime->get_layout_constraint_field_space(layout_id); } //-------------------------------------------------------------------------- void Runtime::get_layout_constraints(LayoutConstraintID layout_id, LayoutConstraintSet &layout_constraints) //-------------------------------------------------------------------------- { runtime->get_layout_constraints(layout_id, layout_constraints); } //-------------------------------------------------------------------------- const char* Runtime::get_layout_constraints_name(LayoutConstraintID id) //-------------------------------------------------------------------------- { return runtime->get_layout_constraints_name(id); } }; // namespace Legion // EOF
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Rogue Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/standard.h" #include "pubkey.h" #include "script/script.h" #include "util.h" #include "utilstrencodings.h" typedef std::vector<unsigned char> valtype; bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_NULL_DATA: return "nulldata"; case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash"; case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash"; } return nullptr; } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet) { // Templates static std::multimap<txnouttype, CScript> mTemplates; if (mTemplates.empty()) { // Standard tx, sender provides pubkey, receiver adds signature mTemplates.insert(std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG)); // Rogue address tx, sender provides hash of pubkey, receiver provides signature and pubkey mTemplates.insert(std::make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG)); // Sender provides N pubkeys, receivers provides M signatures mTemplates.insert(std::make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG)); } vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } int witnessversion; std::vector<unsigned char> witnessprogram; if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { if (witnessversion == 0 && witnessprogram.size() == 20) { typeRet = TX_WITNESS_V0_KEYHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion == 0 && witnessprogram.size() == 32) { typeRet = TX_WITNESS_V0_SCRIPTHASH; vSolutionsRet.push_back(witnessprogram); return true; } return false; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } // Scan templates const CScript& script1 = scriptPubKey; for (const std::pair<txnouttype, CScript>& tplate : mTemplates) { const CScript& script2 = tplate.second; vSolutionsRet.clear(); opcodetype opcode1, opcode2; std::vector<unsigned char> vch1, vch2; // Compare CScript::const_iterator pc1 = script1.begin(); CScript::const_iterator pc2 = script2.begin(); while (true) { if (pc1 == script1.end() && pc2 == script2.end()) { // Found a match typeRet = tplate.first; if (typeRet == TX_MULTISIG) { // Additional checks for TX_MULTISIG: unsigned char m = vSolutionsRet.front()[0]; unsigned char n = vSolutionsRet.back()[0]; if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n) return false; } return true; } if (!script1.GetOp(pc1, opcode1, vch1)) break; if (!script2.GetOp(pc2, opcode2, vch2)) break; // Template matching opcodes: if (opcode2 == OP_PUBKEYS) { while (vch1.size() >= 33 && vch1.size() <= 65) { vSolutionsRet.push_back(vch1); if (!script1.GetOp(pc1, opcode1, vch1)) break; } if (!script2.GetOp(pc2, opcode2, vch2)) break; // Normal situation is to fall through // to other if/else statements } if (opcode2 == OP_PUBKEY) { if (vch1.size() < 33 || vch1.size() > 65) break; vSolutionsRet.push_back(vch1); } else if (opcode2 == OP_PUBKEYHASH) { if (vch1.size() != sizeof(uint160)) break; vSolutionsRet.push_back(vch1); } else if (opcode2 == OP_SMALLINTEGER) { // Single-byte small integer pushed onto vSolutions if (opcode1 == OP_0 || (opcode1 >= OP_1 && opcode1 <= OP_16)) { char n = (char)CScript::DecodeOP_N(opcode1); vSolutionsRet.push_back(valtype(1, n)); } else break; } else if (opcode1 != opcode2 || vch1 != vch2) { // Others must match exactly break; } } } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } // namespace CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { unsigned char h160[20]; CHash160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160); ret << OP_0 << std::vector<unsigned char>(&h160[0], &h160[20]); return ret; } else if (typ == TX_PUBKEYHASH) { ret << OP_0 << vSolutions[0]; return ret; } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); ret << OP_0 << ToByteVector(hash); return ret; }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r8 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x11f25, %r10 nop add $60906, %r13 mov $0x6162636465666768, %rbp movq %rbp, %xmm4 movups %xmm4, (%r10) nop nop xor %r8, %r8 lea addresses_WC_ht+0x1e73, %rbx nop nop add $3106, %rbp mov $0x6162636465666768, %rax movq %rax, (%rbx) nop nop nop sub $57682, %r8 lea addresses_WC_ht+0x724f, %rsi lea addresses_D_ht+0xe9f, %rdi nop nop nop nop nop cmp %rax, %rax mov $62, %rcx rep movsl nop nop nop nop nop cmp %rcx, %rcx lea addresses_WT_ht+0x4def, %rbp and %r8, %r8 mov $0x6162636465666768, %rsi movq %rsi, %xmm3 movups %xmm3, (%rbp) sub $23301, %rdi lea addresses_D_ht+0x189c5, %r10 nop nop sub $18531, %r13 movb $0x61, (%r10) nop nop nop nop nop sub %rdi, %rdi lea addresses_WC_ht+0x13fc3, %rcx sub $34674, %rbx mov $0x6162636465666768, %rax movq %rax, %xmm0 movups %xmm0, (%rcx) nop sub $62199, %r8 lea addresses_UC_ht+0x1ae6f, %rsi lea addresses_WC_ht+0xd82f, %rdi nop dec %r8 mov $105, %rcx rep movsq nop nop cmp %rsi, %rsi lea addresses_WC_ht+0x14ea7, %r8 nop nop nop xor $20350, %rax mov $0x6162636465666768, %rbx movq %rbx, (%r8) add %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r8 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r14 push %r9 push %rax push %rbx push %rcx push %rsi // Store mov $0x7a9efa000000016f, %r12 nop nop nop xor $51422, %rbx mov $0x5152535455565758, %r9 movq %r9, %xmm2 vmovaps %ymm2, (%r12) nop sub $7011, %rbx // Store lea addresses_UC+0x78ef, %r9 nop nop nop nop nop cmp %rsi, %rsi movl $0x51525354, (%r9) nop nop xor $29084, %r14 // Load lea addresses_A+0xf607, %r12 nop nop cmp %rsi, %rsi mov (%r12), %ebx nop nop nop nop and $56170, %rsi // Faulty Load lea addresses_US+0x1316f, %r14 clflush (%r14) cmp $53729, %r9 mov (%r14), %ebx lea oracles, %rsi and $0xff, %rbx shlq $12, %rbx mov (%rsi,%rbx,1), %rbx pop %rsi pop %rcx pop %rbx pop %rax pop %r9 pop %r14 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'size': 32, 'AVXalign': True, 'NT': True, 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 8, 'AVXalign': False, 'NT': True, 'congruent': 1, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'58': 8} 58 58 58 58 58 58 58 58 */
/** * pugixml parser - version 1.8 * -------------------------------------------------------- * Copyright (C) 2006-2017, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) * Report bugs and download new versions at http://pugixml.org/ * * This library is distributed under the MIT License. See notice at the end * of this file. * * This work is based on the pugxml parser, which is: * Copyright (C) 2003, by Kristen Wegner (kristen@tima.net) */ #ifndef SOURCE_PUGIXML_CPP #define SOURCE_PUGIXML_CPP #include "pugixml.hpp" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <limits.h> #ifdef PUGIXML_WCHAR_MODE # include <wchar.h> #endif #ifndef PUGIXML_NO_XPATH # include <math.h> # include <float.h> # ifdef PUGIXML_NO_EXCEPTIONS # include <setjmp.h> # endif #endif #ifndef PUGIXML_NO_STL # include <istream> # include <ostream> # include <string> #endif // For placement new #include <new> #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4127) // conditional expression is constant # pragma warning(disable: 4324) // structure was padded due to __declspec(align()) # pragma warning(disable: 4611) // interaction between '_setjmp' and C++ object destruction is non-portable # pragma warning(disable: 4702) // unreachable code # pragma warning(disable: 4996) // this function or variable may be unsafe # pragma warning(disable: 4793) // function compiled as native: presence of '_setjmp' makes a function unmanaged #endif #ifdef __INTEL_COMPILER # pragma warning(disable: 177) // function was declared but never referenced # pragma warning(disable: 279) // controlling expression is constant # pragma warning(disable: 1478 1786) // function was declared "deprecated" # pragma warning(disable: 1684) // conversion from pointer to same-sized integral type #endif #if defined(__BORLANDC__) && defined(PUGIXML_HEADER_ONLY) # pragma warn -8080 // symbol is declared but never used; disabling this inside push/pop bracket does not make the warning go away #endif #ifdef __BORLANDC__ # pragma option push # pragma warn -8008 // condition is always false # pragma warn -8066 // unreachable code #endif #ifdef __SNC__ // Using diag_push/diag_pop does not disable the warnings inside templates due to a compiler bug # pragma diag_suppress=178 // function was declared but never referenced # pragma diag_suppress=237 // controlling expression is constant #endif // Inlining controls #if defined(_MSC_VER) && _MSC_VER >= 1300 # define PUGI__NO_INLINE __declspec(noinline) #elif defined(__GNUC__) # define PUGI__NO_INLINE __attribute__((noinline)) #else # define PUGI__NO_INLINE #endif // Branch weight controls #if defined(__GNUC__) # define PUGI__UNLIKELY(cond) __builtin_expect(cond, 0) #else # define PUGI__UNLIKELY(cond) (cond) #endif // Simple static assertion #define PUGI__STATIC_ASSERT(cond) { static const char condition_failed[(cond) ? 1 : -1] = {0}; (void)condition_failed[0]; } // Digital Mars C++ bug workaround for passing char loaded from memory via stack #ifdef __DMC__ # define PUGI__DMC_VOLATILE volatile #else # define PUGI__DMC_VOLATILE #endif // Borland C++ bug workaround for not defining ::memcpy depending on header include order (can't always use std::memcpy because some compilers don't have it at all) #if defined(__BORLANDC__) && !defined(__MEM_H_USING_LIST) using std::memcpy; using std::memmove; using std::memset; #endif // Some MinGW versions have headers that erroneously omit LLONG_MIN/LLONG_MAX/ULLONG_MAX definitions in strict ANSI mode #if defined(PUGIXML_HAS_LONG_LONG) && defined(__MINGW32__) && defined(__STRICT_ANSI__) && !defined(LLONG_MAX) && !defined(LLONG_MIN) && !defined(ULLONG_MAX) # define LLONG_MAX 9223372036854775807LL # define LLONG_MIN (-LLONG_MAX-1) # define ULLONG_MAX (2ULL*LLONG_MAX+1) #endif // In some environments MSVC is a compiler but the CRT lacks certain MSVC-specific features #if defined(_MSC_VER) && !defined(__S3E__) # define PUGI__MSVC_CRT_VERSION _MSC_VER #endif #ifdef PUGIXML_HEADER_ONLY # define PUGI__NS_BEGIN namespace pugi { namespace impl { # define PUGI__NS_END } } # define PUGI__FN inline # define PUGI__FN_NO_INLINE inline #else # if defined(_MSC_VER) && _MSC_VER < 1300 // MSVC6 seems to have an amusing bug with anonymous namespaces inside namespaces # define PUGI__NS_BEGIN namespace pugi { namespace impl { # define PUGI__NS_END } } # else # define PUGI__NS_BEGIN namespace pugi { namespace impl { namespace { # define PUGI__NS_END } } } # endif # define PUGI__FN # define PUGI__FN_NO_INLINE PUGI__NO_INLINE #endif // uintptr_t #if (defined(_MSC_VER) && _MSC_VER < 1600) || (defined(__BORLANDC__) && __BORLANDC__ < 0x561) namespace pugi { # ifndef _UINTPTR_T_DEFINED typedef size_t uintptr_t; # endif typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; } #else # include <stdint.h> #endif // Memory allocation PUGI__NS_BEGIN PUGI__FN void* default_allocate(size_t size) { return malloc(size); } PUGI__FN void default_deallocate(void* ptr) { free(ptr); } template <typename T> struct xml_memory_management_function_storage { static allocation_function allocate; static deallocation_function deallocate; }; // Global allocation functions are stored in class statics so that in header mode linker deduplicates them // Without a template<> we'll get multiple definitions of the same static template <typename T> allocation_function xml_memory_management_function_storage<T>::allocate = default_allocate; template <typename T> deallocation_function xml_memory_management_function_storage<T>::deallocate = default_deallocate; typedef xml_memory_management_function_storage<int> xml_memory; PUGI__NS_END // String utilities PUGI__NS_BEGIN // Get string length PUGI__FN size_t strlength(const char_t* s) { assert(s); #ifdef PUGIXML_WCHAR_MODE return wcslen(s); #else return strlen(s); #endif } // Compare two strings PUGI__FN bool strequal(const char_t* src, const char_t* dst) { assert(src && dst); #ifdef PUGIXML_WCHAR_MODE return wcscmp(src, dst) == 0; #else return strcmp(src, dst) == 0; #endif } // Compare lhs with [rhs_begin, rhs_end) PUGI__FN bool strequalrange(const char_t* lhs, const char_t* rhs, size_t count) { for (size_t i = 0; i < count; ++i) if (lhs[i] != rhs[i]) return false; return lhs[count] == 0; } // Get length of wide string, even if CRT lacks wide character support PUGI__FN size_t strlength_wide(const wchar_t* s) { assert(s); #ifdef PUGIXML_WCHAR_MODE return wcslen(s); #else const wchar_t* end = s; while (*end) end++; return static_cast<size_t>(end - s); #endif } PUGI__NS_END // auto_ptr-like object for exception recovery PUGI__NS_BEGIN template <typename T> struct auto_deleter { typedef void (*D)(T*); T* data; D deleter; auto_deleter(T* data_, D deleter_): data(data_), deleter(deleter_) { } ~auto_deleter() { if (data) deleter(data); } T* release() { T* result = data; data = 0; return result; } }; PUGI__NS_END #ifdef PUGIXML_COMPACT PUGI__NS_BEGIN class compact_hash_table { public: compact_hash_table(): _items(0), _capacity(0), _count(0) { } void clear() { if (_items) { xml_memory::deallocate(_items); _items = 0; _capacity = 0; _count = 0; } } void** find(const void* key) { assert(key); if (_capacity == 0) return 0; size_t hashmod = _capacity - 1; size_t bucket = hash(key) & hashmod; for (size_t probe = 0; probe <= hashmod; ++probe) { item_t& probe_item = _items[bucket]; if (probe_item.key == key) return &probe_item.value; if (probe_item.key == 0) return 0; // hash collision, quadratic probing bucket = (bucket + probe + 1) & hashmod; } assert(false && "Hash table is full"); return 0; } void** insert(const void* key) { assert(key); assert(_capacity != 0 && _count < _capacity - _capacity / 4); size_t hashmod = _capacity - 1; size_t bucket = hash(key) & hashmod; for (size_t probe = 0; probe <= hashmod; ++probe) { item_t& probe_item = _items[bucket]; if (probe_item.key == 0) { probe_item.key = key; _count++; return &probe_item.value; } if (probe_item.key == key) return &probe_item.value; // hash collision, quadratic probing bucket = (bucket + probe + 1) & hashmod; } assert(false && "Hash table is full"); return 0; } bool reserve() { if (_count + 16 >= _capacity - _capacity / 4) return rehash(); return true; } private: struct item_t { const void* key; void* value; }; item_t* _items; size_t _capacity; size_t _count; bool rehash(); static unsigned int hash(const void* key) { unsigned int h = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(key)); // MurmurHash3 32-bit finalizer h ^= h >> 16; h *= 0x85ebca6bu; h ^= h >> 13; h *= 0xc2b2ae35u; h ^= h >> 16; return h; } }; PUGI__FN_NO_INLINE bool compact_hash_table::rehash() { compact_hash_table rt; rt._capacity = (_capacity == 0) ? 32 : _capacity * 2; rt._items = static_cast<item_t*>(xml_memory::allocate(sizeof(item_t) * rt._capacity)); if (!rt._items) return false; memset(rt._items, 0, sizeof(item_t) * rt._capacity); for (size_t i = 0; i < _capacity; ++i) if (_items[i].key) *rt.insert(_items[i].key) = _items[i].value; if (_items) xml_memory::deallocate(_items); _capacity = rt._capacity; _items = rt._items; assert(_count == rt._count); return true; } PUGI__NS_END #endif PUGI__NS_BEGIN #ifdef PUGIXML_COMPACT static const uintptr_t xml_memory_block_alignment = 4; #else static const uintptr_t xml_memory_block_alignment = sizeof(void*); #endif // extra metadata bits static const uintptr_t xml_memory_page_contents_shared_mask = 64; static const uintptr_t xml_memory_page_name_allocated_mask = 32; static const uintptr_t xml_memory_page_value_allocated_mask = 16; static const uintptr_t xml_memory_page_type_mask = 15; // combined masks for string uniqueness static const uintptr_t xml_memory_page_name_allocated_or_shared_mask = xml_memory_page_name_allocated_mask | xml_memory_page_contents_shared_mask; static const uintptr_t xml_memory_page_value_allocated_or_shared_mask = xml_memory_page_value_allocated_mask | xml_memory_page_contents_shared_mask; #ifdef PUGIXML_COMPACT #define PUGI__GETHEADER_IMPL(object, page, flags) // unused #define PUGI__GETPAGE_IMPL(header) (header).get_page() #else #define PUGI__GETHEADER_IMPL(object, page, flags) (((reinterpret_cast<char*>(object) - reinterpret_cast<char*>(page)) << 8) | (flags)) // this macro casts pointers through void* to avoid 'cast increases required alignment of target type' warnings #define PUGI__GETPAGE_IMPL(header) static_cast<impl::xml_memory_page*>(const_cast<void*>(static_cast<const void*>(reinterpret_cast<const char*>(&header) - (header >> 8)))) #endif #define PUGI__GETPAGE(n) PUGI__GETPAGE_IMPL((n)->header) #define PUGI__NODETYPE(n) static_cast<xml_node_type>((n)->header & impl::xml_memory_page_type_mask) struct xml_allocator; struct xml_memory_page { static xml_memory_page* construct(void* memory) { xml_memory_page* result = static_cast<xml_memory_page*>(memory); result->allocator = 0; result->prev = 0; result->next = 0; result->busy_size = 0; result->freed_size = 0; #ifdef PUGIXML_COMPACT result->compact_string_base = 0; result->compact_shared_parent = 0; result->compact_page_marker = 0; #endif return result; } xml_allocator* allocator; xml_memory_page* prev; xml_memory_page* next; size_t busy_size; size_t freed_size; #ifdef PUGIXML_COMPACT char_t* compact_string_base; void* compact_shared_parent; uint32_t* compact_page_marker; #endif }; static const size_t xml_memory_page_size = #ifdef PUGIXML_MEMORY_PAGE_SIZE (PUGIXML_MEMORY_PAGE_SIZE) #else 32768 #endif - sizeof(xml_memory_page); struct xml_memory_string_header { uint16_t page_offset; // offset from page->data uint16_t full_size; // 0 if string occupies whole page }; struct xml_allocator { xml_allocator(xml_memory_page* root): _root(root), _busy_size(root->busy_size) { #ifdef PUGIXML_COMPACT _hash = 0; #endif } xml_memory_page* allocate_page(size_t data_size) { size_t size = sizeof(xml_memory_page) + data_size; // allocate block with some alignment, leaving memory for worst-case padding void* memory = xml_memory::allocate(size); if (!memory) return 0; // prepare page structure xml_memory_page* page = xml_memory_page::construct(memory); assert(page); page->allocator = _root->allocator; return page; } static void deallocate_page(xml_memory_page* page) { xml_memory::deallocate(page); } void* allocate_memory_oob(size_t size, xml_memory_page*& out_page); void* allocate_memory(size_t size, xml_memory_page*& out_page) { if (PUGI__UNLIKELY(_busy_size + size > xml_memory_page_size)) return allocate_memory_oob(size, out_page); void* buf = reinterpret_cast<char*>(_root) + sizeof(xml_memory_page) + _busy_size; _busy_size += size; out_page = _root; return buf; } #ifdef PUGIXML_COMPACT void* allocate_object(size_t size, xml_memory_page*& out_page) { void* result = allocate_memory(size + sizeof(uint32_t), out_page); if (!result) return 0; // adjust for marker ptrdiff_t offset = static_cast<char*>(result) - reinterpret_cast<char*>(out_page->compact_page_marker); if (PUGI__UNLIKELY(static_cast<uintptr_t>(offset) >= 256 * xml_memory_block_alignment)) { // insert new marker uint32_t* marker = static_cast<uint32_t*>(result); *marker = static_cast<uint32_t>(reinterpret_cast<char*>(marker) - reinterpret_cast<char*>(out_page)); out_page->compact_page_marker = marker; // since we don't reuse the page space until we reallocate it, we can just pretend that we freed the marker block // this will make sure deallocate_memory correctly tracks the size out_page->freed_size += sizeof(uint32_t); return marker + 1; } else { // roll back uint32_t part _busy_size -= sizeof(uint32_t); return result; } } #else void* allocate_object(size_t size, xml_memory_page*& out_page) { return allocate_memory(size, out_page); } #endif void deallocate_memory(void* ptr, size_t size, xml_memory_page* page) { if (page == _root) page->busy_size = _busy_size; assert(ptr >= reinterpret_cast<char*>(page) + sizeof(xml_memory_page) && ptr < reinterpret_cast<char*>(page) + sizeof(xml_memory_page) + page->busy_size); (void)!ptr; page->freed_size += size; assert(page->freed_size <= page->busy_size); if (page->freed_size == page->busy_size) { if (page->next == 0) { assert(_root == page); // top page freed, just reset sizes page->busy_size = 0; page->freed_size = 0; #ifdef PUGIXML_COMPACT // reset compact state to maximize efficiency page->compact_string_base = 0; page->compact_shared_parent = 0; page->compact_page_marker = 0; #endif _busy_size = 0; } else { assert(_root != page); assert(page->prev); // remove from the list page->prev->next = page->next; page->next->prev = page->prev; // deallocate deallocate_page(page); } } } char_t* allocate_string(size_t length) { static const size_t max_encoded_offset = (1 << 16) * xml_memory_block_alignment; PUGI__STATIC_ASSERT(xml_memory_page_size <= max_encoded_offset); // allocate memory for string and header block size_t size = sizeof(xml_memory_string_header) + length * sizeof(char_t); // round size up to block alignment boundary size_t full_size = (size + (xml_memory_block_alignment - 1)) & ~(xml_memory_block_alignment - 1); xml_memory_page* page; xml_memory_string_header* header = static_cast<xml_memory_string_header*>(allocate_memory(full_size, page)); if (!header) return 0; // setup header ptrdiff_t page_offset = reinterpret_cast<char*>(header) - reinterpret_cast<char*>(page) - sizeof(xml_memory_page); assert(page_offset % xml_memory_block_alignment == 0); assert(page_offset >= 0 && static_cast<size_t>(page_offset) < max_encoded_offset); header->page_offset = static_cast<uint16_t>(static_cast<size_t>(page_offset) / xml_memory_block_alignment); // full_size == 0 for large strings that occupy the whole page assert(full_size % xml_memory_block_alignment == 0); assert(full_size < max_encoded_offset || (page->busy_size == full_size && page_offset == 0)); header->full_size = static_cast<uint16_t>(full_size < max_encoded_offset ? full_size / xml_memory_block_alignment : 0); // round-trip through void* to avoid 'cast increases required alignment of target type' warning // header is guaranteed a pointer-sized alignment, which should be enough for char_t return static_cast<char_t*>(static_cast<void*>(header + 1)); } void deallocate_string(char_t* string) { // this function casts pointers through void* to avoid 'cast increases required alignment of target type' warnings // we're guaranteed the proper (pointer-sized) alignment on the input string if it was allocated via allocate_string // get header xml_memory_string_header* header = static_cast<xml_memory_string_header*>(static_cast<void*>(string)) - 1; assert(header); // deallocate size_t page_offset = sizeof(xml_memory_page) + header->page_offset * xml_memory_block_alignment; xml_memory_page* page = reinterpret_cast<xml_memory_page*>(static_cast<void*>(reinterpret_cast<char*>(header) - page_offset)); // if full_size == 0 then this string occupies the whole page size_t full_size = header->full_size == 0 ? page->busy_size : header->full_size * xml_memory_block_alignment; deallocate_memory(header, full_size, page); } bool reserve() { #ifdef PUGIXML_COMPACT return _hash->reserve(); #else return true; #endif } xml_memory_page* _root; size_t _busy_size; #ifdef PUGIXML_COMPACT compact_hash_table* _hash; #endif }; PUGI__FN_NO_INLINE void* xml_allocator::allocate_memory_oob(size_t size, xml_memory_page*& out_page) { const size_t large_allocation_threshold = xml_memory_page_size / 4; xml_memory_page* page = allocate_page(size <= large_allocation_threshold ? xml_memory_page_size : size); out_page = page; if (!page) return 0; if (size <= large_allocation_threshold) { _root->busy_size = _busy_size; // insert page at the end of linked list page->prev = _root; _root->next = page; _root = page; _busy_size = size; } else { // insert page before the end of linked list, so that it is deleted as soon as possible // the last page is not deleted even if it's empty (see deallocate_memory) assert(_root->prev); page->prev = _root->prev; page->next = _root; _root->prev->next = page; _root->prev = page; page->busy_size = size; } return reinterpret_cast<char*>(page) + sizeof(xml_memory_page); } PUGI__NS_END #ifdef PUGIXML_COMPACT PUGI__NS_BEGIN static const uintptr_t compact_alignment_log2 = 2; static const uintptr_t compact_alignment = 1 << compact_alignment_log2; class compact_header { public: compact_header(xml_memory_page* page, unsigned int flags) { PUGI__STATIC_ASSERT(xml_memory_block_alignment == compact_alignment); ptrdiff_t offset = (reinterpret_cast<char*>(this) - reinterpret_cast<char*>(page->compact_page_marker)); assert(offset % compact_alignment == 0 && static_cast<uintptr_t>(offset) < 256 * compact_alignment); _page = static_cast<unsigned char>(offset >> compact_alignment_log2); _flags = static_cast<unsigned char>(flags); } void operator&=(uintptr_t mod) { _flags &= static_cast<unsigned char>(mod); } void operator|=(uintptr_t mod) { _flags |= static_cast<unsigned char>(mod); } uintptr_t operator&(uintptr_t mod) const { return _flags & mod; } xml_memory_page* get_page() const { // round-trip through void* to silence 'cast increases required alignment of target type' warnings const char* page_marker = reinterpret_cast<const char*>(this) - (_page << compact_alignment_log2); const char* page = page_marker - *reinterpret_cast<const uint32_t*>(static_cast<const void*>(page_marker)); return const_cast<xml_memory_page*>(reinterpret_cast<const xml_memory_page*>(static_cast<const void*>(page))); } private: unsigned char _page; unsigned char _flags; }; PUGI__FN xml_memory_page* compact_get_page(const void* object, int header_offset) { const compact_header* header = reinterpret_cast<const compact_header*>(static_cast<const char*>(object) - header_offset); return header->get_page(); } template <int header_offset, typename T> PUGI__FN_NO_INLINE T* compact_get_value(const void* object) { return static_cast<T*>(*compact_get_page(object, header_offset)->allocator->_hash->find(object)); } template <int header_offset, typename T> PUGI__FN_NO_INLINE void compact_set_value(const void* object, T* value) { *compact_get_page(object, header_offset)->allocator->_hash->insert(object) = value; } template <typename T, int header_offset, int start = -126> class compact_pointer { public: compact_pointer(): _data(0) { } void operator=(const compact_pointer& rhs) { *this = rhs + 0; } void operator=(T* value) { if (value) { // value is guaranteed to be compact-aligned; 'this' is not // our decoding is based on 'this' aligned to compact alignment downwards (see operator T*) // so for negative offsets (e.g. -3) we need to adjust the diff by compact_alignment - 1 to // compensate for arithmetic shift rounding for negative values ptrdiff_t diff = reinterpret_cast<char*>(value) - reinterpret_cast<char*>(this); ptrdiff_t offset = ((diff + int(compact_alignment - 1)) >> compact_alignment_log2) - start; if (static_cast<uintptr_t>(offset) <= 253) _data = static_cast<unsigned char>(offset + 1); else { compact_set_value<header_offset>(this, value); _data = 255; } } else _data = 0; } operator T*() const { if (_data) { if (_data < 255) { uintptr_t base = reinterpret_cast<uintptr_t>(this) & ~(compact_alignment - 1); return reinterpret_cast<T*>(base + ((_data - 1 + start) << compact_alignment_log2)); } else return compact_get_value<header_offset, T>(this); } else return 0; } T* operator->() const { return *this; } private: unsigned char _data; }; template <typename T, int header_offset> class compact_pointer_parent { public: compact_pointer_parent(): _data(0) { } void operator=(const compact_pointer_parent& rhs) { *this = rhs + 0; } void operator=(T* value) { if (value) { // value is guaranteed to be compact-aligned; 'this' is not // our decoding is based on 'this' aligned to compact alignment downwards (see operator T*) // so for negative offsets (e.g. -3) we need to adjust the diff by compact_alignment - 1 to // compensate for arithmetic shift behavior for negative values ptrdiff_t diff = reinterpret_cast<char*>(value) - reinterpret_cast<char*>(this); ptrdiff_t offset = ((diff + int(compact_alignment - 1)) >> compact_alignment_log2) + 65533; if (static_cast<uintptr_t>(offset) <= 65533) { _data = static_cast<unsigned short>(offset + 1); } else { xml_memory_page* page = compact_get_page(this, header_offset); if (PUGI__UNLIKELY(page->compact_shared_parent == 0)) page->compact_shared_parent = value; if (page->compact_shared_parent == value) { _data = 65534; } else { compact_set_value<header_offset>(this, value); _data = 65535; } } } else { _data = 0; } } operator T*() const { if (_data) { if (_data < 65534) { uintptr_t base = reinterpret_cast<uintptr_t>(this) & ~(compact_alignment - 1); return reinterpret_cast<T*>(base + ((_data - 1 - 65533) << compact_alignment_log2)); } else if (_data == 65534) return static_cast<T*>(compact_get_page(this, header_offset)->compact_shared_parent); else return compact_get_value<header_offset, T>(this); } else return 0; } T* operator->() const { return *this; } private: uint16_t _data; }; template <int header_offset, int base_offset> class compact_string { public: compact_string(): _data(0) { } void operator=(const compact_string& rhs) { *this = rhs + 0; } void operator=(char_t* value) { if (value) { xml_memory_page* page = compact_get_page(this, header_offset); if (PUGI__UNLIKELY(page->compact_string_base == 0)) page->compact_string_base = value; ptrdiff_t offset = value - page->compact_string_base; if (static_cast<uintptr_t>(offset) < (65535 << 7)) { // round-trip through void* to silence 'cast increases required alignment of target type' warnings uint16_t* base = reinterpret_cast<uint16_t*>(static_cast<void*>(reinterpret_cast<char*>(this) - base_offset)); if (*base == 0) { *base = static_cast<uint16_t>((offset >> 7) + 1); _data = static_cast<unsigned char>((offset & 127) + 1); } else { ptrdiff_t remainder = offset - ((*base - 1) << 7); if (static_cast<uintptr_t>(remainder) <= 253) { _data = static_cast<unsigned char>(remainder + 1); } else { compact_set_value<header_offset>(this, value); _data = 255; } } } else { compact_set_value<header_offset>(this, value); _data = 255; } } else { _data = 0; } } operator char_t*() const { if (_data) { if (_data < 255) { xml_memory_page* page = compact_get_page(this, header_offset); // round-trip through void* to silence 'cast increases required alignment of target type' warnings const uint16_t* base = reinterpret_cast<const uint16_t*>(static_cast<const void*>(reinterpret_cast<const char*>(this) - base_offset)); assert(*base); ptrdiff_t offset = ((*base - 1) << 7) + (_data - 1); return page->compact_string_base + offset; } else { return compact_get_value<header_offset, char_t>(this); } } else return 0; } private: unsigned char _data; }; PUGI__NS_END #endif #ifdef PUGIXML_COMPACT namespace pugi { struct xml_attribute_struct { xml_attribute_struct(impl::xml_memory_page* page): header(page, 0), namevalue_base(0) { PUGI__STATIC_ASSERT(sizeof(xml_attribute_struct) == 8); } impl::compact_header header; uint16_t namevalue_base; impl::compact_string<4, 2> name; impl::compact_string<5, 3> value; impl::compact_pointer<xml_attribute_struct, 6> prev_attribute_c; impl::compact_pointer<xml_attribute_struct, 7, 0> next_attribute; }; struct xml_node_struct { xml_node_struct(impl::xml_memory_page* page, xml_node_type type): header(page, type), namevalue_base(0) { PUGI__STATIC_ASSERT(sizeof(xml_node_struct) == 12); } impl::compact_header header; uint16_t namevalue_base; impl::compact_string<4, 2> name; impl::compact_string<5, 3> value; impl::compact_pointer_parent<xml_node_struct, 6> parent; impl::compact_pointer<xml_node_struct, 8, 0> first_child; impl::compact_pointer<xml_node_struct, 9> prev_sibling_c; impl::compact_pointer<xml_node_struct, 10, 0> next_sibling; impl::compact_pointer<xml_attribute_struct, 11, 0> first_attribute; }; } #else namespace pugi { struct xml_attribute_struct { xml_attribute_struct(impl::xml_memory_page* page): name(0), value(0), prev_attribute_c(0), next_attribute(0) { header = PUGI__GETHEADER_IMPL(this, page, 0); } uintptr_t header; char_t* name; char_t* value; xml_attribute_struct* prev_attribute_c; xml_attribute_struct* next_attribute; }; struct xml_node_struct { xml_node_struct(impl::xml_memory_page* page, xml_node_type type): name(0), value(0), parent(0), first_child(0), prev_sibling_c(0), next_sibling(0), first_attribute(0) { header = PUGI__GETHEADER_IMPL(this, page, type); } uintptr_t header; char_t* name; char_t* value; xml_node_struct* parent; xml_node_struct* first_child; xml_node_struct* prev_sibling_c; xml_node_struct* next_sibling; xml_attribute_struct* first_attribute; }; } #endif PUGI__NS_BEGIN struct xml_extra_buffer { char_t* buffer; xml_extra_buffer* next; }; struct xml_document_struct: public xml_node_struct, public xml_allocator { xml_document_struct(xml_memory_page* page): xml_node_struct(page, node_document), xml_allocator(page), buffer(0), extra_buffers(0) { } const char_t* buffer; xml_extra_buffer* extra_buffers; #ifdef PUGIXML_COMPACT compact_hash_table hash; #endif }; template <typename Object> inline xml_allocator& get_allocator(const Object* object) { assert(object); return *PUGI__GETPAGE(object)->allocator; } template <typename Object> inline xml_document_struct& get_document(const Object* object) { assert(object); return *static_cast<xml_document_struct*>(PUGI__GETPAGE(object)->allocator); } PUGI__NS_END // Low-level DOM operations PUGI__NS_BEGIN inline xml_attribute_struct* allocate_attribute(xml_allocator& alloc) { xml_memory_page* page; void* memory = alloc.allocate_object(sizeof(xml_attribute_struct), page); if (!memory) return 0; return new (memory) xml_attribute_struct(page); } inline xml_node_struct* allocate_node(xml_allocator& alloc, xml_node_type type) { xml_memory_page* page; void* memory = alloc.allocate_object(sizeof(xml_node_struct), page); if (!memory) return 0; return new (memory) xml_node_struct(page, type); } inline void destroy_attribute(xml_attribute_struct* a, xml_allocator& alloc) { if (a->header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(a->name); if (a->header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(a->value); alloc.deallocate_memory(a, sizeof(xml_attribute_struct), PUGI__GETPAGE(a)); } inline void destroy_node(xml_node_struct* n, xml_allocator& alloc) { if (n->header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(n->name); if (n->header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(n->value); for (xml_attribute_struct* attr = n->first_attribute; attr; ) { xml_attribute_struct* next = attr->next_attribute; destroy_attribute(attr, alloc); attr = next; } for (xml_node_struct* child = n->first_child; child; ) { xml_node_struct* next = child->next_sibling; destroy_node(child, alloc); child = next; } alloc.deallocate_memory(n, sizeof(xml_node_struct), PUGI__GETPAGE(n)); } inline void append_node(xml_node_struct* child, xml_node_struct* node) { child->parent = node; xml_node_struct* head = node->first_child; if (head) { xml_node_struct* tail = head->prev_sibling_c; tail->next_sibling = child; child->prev_sibling_c = tail; head->prev_sibling_c = child; } else { node->first_child = child; child->prev_sibling_c = child; } } inline void prepend_node(xml_node_struct* child, xml_node_struct* node) { child->parent = node; xml_node_struct* head = node->first_child; if (head) { child->prev_sibling_c = head->prev_sibling_c; head->prev_sibling_c = child; } else child->prev_sibling_c = child; child->next_sibling = head; node->first_child = child; } inline void insert_node_after(xml_node_struct* child, xml_node_struct* node) { xml_node_struct* parent = node->parent; child->parent = parent; if (node->next_sibling) node->next_sibling->prev_sibling_c = child; else parent->first_child->prev_sibling_c = child; child->next_sibling = node->next_sibling; child->prev_sibling_c = node; node->next_sibling = child; } inline void insert_node_before(xml_node_struct* child, xml_node_struct* node) { xml_node_struct* parent = node->parent; child->parent = parent; if (node->prev_sibling_c->next_sibling) node->prev_sibling_c->next_sibling = child; else parent->first_child = child; child->prev_sibling_c = node->prev_sibling_c; child->next_sibling = node; node->prev_sibling_c = child; } inline void remove_node(xml_node_struct* node) { xml_node_struct* parent = node->parent; if (node->next_sibling) node->next_sibling->prev_sibling_c = node->prev_sibling_c; else parent->first_child->prev_sibling_c = node->prev_sibling_c; if (node->prev_sibling_c->next_sibling) node->prev_sibling_c->next_sibling = node->next_sibling; else parent->first_child = node->next_sibling; node->parent = 0; node->prev_sibling_c = 0; node->next_sibling = 0; } inline void append_attribute(xml_attribute_struct* attr, xml_node_struct* node) { xml_attribute_struct* head = node->first_attribute; if (head) { xml_attribute_struct* tail = head->prev_attribute_c; tail->next_attribute = attr; attr->prev_attribute_c = tail; head->prev_attribute_c = attr; } else { node->first_attribute = attr; attr->prev_attribute_c = attr; } } inline void prepend_attribute(xml_attribute_struct* attr, xml_node_struct* node) { xml_attribute_struct* head = node->first_attribute; if (head) { attr->prev_attribute_c = head->prev_attribute_c; head->prev_attribute_c = attr; } else attr->prev_attribute_c = attr; attr->next_attribute = head; node->first_attribute = attr; } inline void insert_attribute_after(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node) { if (place->next_attribute) place->next_attribute->prev_attribute_c = attr; else node->first_attribute->prev_attribute_c = attr; attr->next_attribute = place->next_attribute; attr->prev_attribute_c = place; place->next_attribute = attr; } inline void insert_attribute_before(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node) { if (place->prev_attribute_c->next_attribute) place->prev_attribute_c->next_attribute = attr; else node->first_attribute = attr; attr->prev_attribute_c = place->prev_attribute_c; attr->next_attribute = place; place->prev_attribute_c = attr; } inline void remove_attribute(xml_attribute_struct* attr, xml_node_struct* node) { if (attr->next_attribute) attr->next_attribute->prev_attribute_c = attr->prev_attribute_c; else node->first_attribute->prev_attribute_c = attr->prev_attribute_c; if (attr->prev_attribute_c->next_attribute) attr->prev_attribute_c->next_attribute = attr->next_attribute; else node->first_attribute = attr->next_attribute; attr->prev_attribute_c = 0; attr->next_attribute = 0; } PUGI__FN_NO_INLINE xml_node_struct* append_new_node(xml_node_struct* node, xml_allocator& alloc, xml_node_type type = node_element) { if (!alloc.reserve()) return 0; xml_node_struct* child = allocate_node(alloc, type); if (!child) return 0; append_node(child, node); return child; } PUGI__FN_NO_INLINE xml_attribute_struct* append_new_attribute(xml_node_struct* node, xml_allocator& alloc) { if (!alloc.reserve()) return 0; xml_attribute_struct* attr = allocate_attribute(alloc); if (!attr) return 0; append_attribute(attr, node); return attr; } PUGI__NS_END // Helper classes for code generation PUGI__NS_BEGIN struct opt_false { enum { value = 0 }; }; struct opt_true { enum { value = 1 }; }; PUGI__NS_END // Unicode utilities PUGI__NS_BEGIN inline uint16_t endian_swap(uint16_t value) { return static_cast<uint16_t>(((value & 0xff) << 8) | (value >> 8)); } inline uint32_t endian_swap(uint32_t value) { return ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value & 0xff0000) >> 8) | (value >> 24); } struct utf8_counter { typedef size_t value_type; static value_type low(value_type result, uint32_t ch) { // U+0000..U+007F if (ch < 0x80) return result + 1; // U+0080..U+07FF else if (ch < 0x800) return result + 2; // U+0800..U+FFFF else return result + 3; } static value_type high(value_type result, uint32_t) { // U+10000..U+10FFFF return result + 4; } }; struct utf8_writer { typedef uint8_t* value_type; static value_type low(value_type result, uint32_t ch) { // U+0000..U+007F if (ch < 0x80) { *result = static_cast<uint8_t>(ch); return result + 1; } // U+0080..U+07FF else if (ch < 0x800) { result[0] = static_cast<uint8_t>(0xC0 | (ch >> 6)); result[1] = static_cast<uint8_t>(0x80 | (ch & 0x3F)); return result + 2; } // U+0800..U+FFFF else { result[0] = static_cast<uint8_t>(0xE0 | (ch >> 12)); result[1] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F)); result[2] = static_cast<uint8_t>(0x80 | (ch & 0x3F)); return result + 3; } } static value_type high(value_type result, uint32_t ch) { // U+10000..U+10FFFF result[0] = static_cast<uint8_t>(0xF0 | (ch >> 18)); result[1] = static_cast<uint8_t>(0x80 | ((ch >> 12) & 0x3F)); result[2] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F)); result[3] = static_cast<uint8_t>(0x80 | (ch & 0x3F)); return result + 4; } static value_type any(value_type result, uint32_t ch) { return (ch < 0x10000) ? low(result, ch) : high(result, ch); } }; struct utf16_counter { typedef size_t value_type; static value_type low(value_type result, uint32_t) { return result + 1; } static value_type high(value_type result, uint32_t) { return result + 2; } }; struct utf16_writer { typedef uint16_t* value_type; static value_type low(value_type result, uint32_t ch) { *result = static_cast<uint16_t>(ch); return result + 1; } static value_type high(value_type result, uint32_t ch) { uint32_t msh = static_cast<uint32_t>(ch - 0x10000) >> 10; uint32_t lsh = static_cast<uint32_t>(ch - 0x10000) & 0x3ff; result[0] = static_cast<uint16_t>(0xD800 + msh); result[1] = static_cast<uint16_t>(0xDC00 + lsh); return result + 2; } static value_type any(value_type result, uint32_t ch) { return (ch < 0x10000) ? low(result, ch) : high(result, ch); } }; struct utf32_counter { typedef size_t value_type; static value_type low(value_type result, uint32_t) { return result + 1; } static value_type high(value_type result, uint32_t) { return result + 1; } }; struct utf32_writer { typedef uint32_t* value_type; static value_type low(value_type result, uint32_t ch) { *result = ch; return result + 1; } static value_type high(value_type result, uint32_t ch) { *result = ch; return result + 1; } static value_type any(value_type result, uint32_t ch) { *result = ch; return result + 1; } }; struct latin1_writer { typedef uint8_t* value_type; static value_type low(value_type result, uint32_t ch) { *result = static_cast<uint8_t>(ch > 255 ? '?' : ch); return result + 1; } static value_type high(value_type result, uint32_t ch) { (void)ch; *result = '?'; return result + 1; } }; struct utf8_decoder { typedef uint8_t type; template <typename Traits> static inline typename Traits::value_type process(const uint8_t* data, size_t size, typename Traits::value_type result, Traits) { const uint8_t utf8_byte_mask = 0x3f; while (size) { uint8_t lead = *data; // 0xxxxxxx -> U+0000..U+007F if (lead < 0x80) { result = Traits::low(result, lead); data += 1; size -= 1; // process aligned single-byte (ascii) blocks if ((reinterpret_cast<uintptr_t>(data) & 3) == 0) { // round-trip through void* to silence 'cast increases required alignment of target type' warnings while (size >= 4 && (*static_cast<const uint32_t*>(static_cast<const void*>(data)) & 0x80808080) == 0) { result = Traits::low(result, data[0]); result = Traits::low(result, data[1]); result = Traits::low(result, data[2]); result = Traits::low(result, data[3]); data += 4; size -= 4; } } } // 110xxxxx -> U+0080..U+07FF else if (static_cast<unsigned int>(lead - 0xC0) < 0x20 && size >= 2 && (data[1] & 0xc0) == 0x80) { result = Traits::low(result, ((lead & ~0xC0) << 6) | (data[1] & utf8_byte_mask)); data += 2; size -= 2; } // 1110xxxx -> U+0800-U+FFFF else if (static_cast<unsigned int>(lead - 0xE0) < 0x10 && size >= 3 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80) { result = Traits::low(result, ((lead & ~0xE0) << 12) | ((data[1] & utf8_byte_mask) << 6) | (data[2] & utf8_byte_mask)); data += 3; size -= 3; } // 11110xxx -> U+10000..U+10FFFF else if (static_cast<unsigned int>(lead - 0xF0) < 0x08 && size >= 4 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80 && (data[3] & 0xc0) == 0x80) { result = Traits::high(result, ((lead & ~0xF0) << 18) | ((data[1] & utf8_byte_mask) << 12) | ((data[2] & utf8_byte_mask) << 6) | (data[3] & utf8_byte_mask)); data += 4; size -= 4; } // 10xxxxxx or 11111xxx -> invalid else { data += 1; size -= 1; } } return result; } }; template <typename opt_swap> struct utf16_decoder { typedef uint16_t type; template <typename Traits> static inline typename Traits::value_type process(const uint16_t* data, size_t size, typename Traits::value_type result, Traits) { while (size) { uint16_t lead = opt_swap::value ? endian_swap(*data) : *data; // U+0000..U+D7FF if (lead < 0xD800) { result = Traits::low(result, lead); data += 1; size -= 1; } // U+E000..U+FFFF else if (static_cast<unsigned int>(lead - 0xE000) < 0x2000) { result = Traits::low(result, lead); data += 1; size -= 1; } // surrogate pair lead else if (static_cast<unsigned int>(lead - 0xD800) < 0x400 && size >= 2) { uint16_t next = opt_swap::value ? endian_swap(data[1]) : data[1]; if (static_cast<unsigned int>(next - 0xDC00) < 0x400) { result = Traits::high(result, 0x10000 + ((lead & 0x3ff) << 10) + (next & 0x3ff)); data += 2; size -= 2; } else { data += 1; size -= 1; } } else { data += 1; size -= 1; } } return result; } }; template <typename opt_swap> struct utf32_decoder { typedef uint32_t type; template <typename Traits> static inline typename Traits::value_type process(const uint32_t* data, size_t size, typename Traits::value_type result, Traits) { while (size) { uint32_t lead = opt_swap::value ? endian_swap(*data) : *data; // U+0000..U+FFFF if (lead < 0x10000) { result = Traits::low(result, lead); data += 1; size -= 1; } // U+10000..U+10FFFF else { result = Traits::high(result, lead); data += 1; size -= 1; } } return result; } }; struct latin1_decoder { typedef uint8_t type; template <typename Traits> static inline typename Traits::value_type process(const uint8_t* data, size_t size, typename Traits::value_type result, Traits) { while (size) { result = Traits::low(result, *data); data += 1; size -= 1; } return result; } }; template <size_t size> struct wchar_selector; template <> struct wchar_selector<2> { typedef uint16_t type; typedef utf16_counter counter; typedef utf16_writer writer; typedef utf16_decoder<opt_false> decoder; }; template <> struct wchar_selector<4> { typedef uint32_t type; typedef utf32_counter counter; typedef utf32_writer writer; typedef utf32_decoder<opt_false> decoder; }; typedef wchar_selector<sizeof(wchar_t)>::counter wchar_counter; typedef wchar_selector<sizeof(wchar_t)>::writer wchar_writer; struct wchar_decoder { typedef wchar_t type; template <typename Traits> static inline typename Traits::value_type process(const wchar_t* data, size_t size, typename Traits::value_type result, Traits traits) { typedef wchar_selector<sizeof(wchar_t)>::decoder decoder; return decoder::process(reinterpret_cast<const typename decoder::type*>(data), size, result, traits); } }; #ifdef PUGIXML_WCHAR_MODE PUGI__FN void convert_wchar_endian_swap(wchar_t* result, const wchar_t* data, size_t length) { for (size_t i = 0; i < length; ++i) result[i] = static_cast<wchar_t>(endian_swap(static_cast<wchar_selector<sizeof(wchar_t)>::type>(data[i]))); } #endif PUGI__NS_END PUGI__NS_BEGIN enum chartype_t { ct_parse_pcdata = 1, // \0, &, \r, < ct_parse_attr = 2, // \0, &, \r, ', " ct_parse_attr_ws = 4, // \0, &, \r, ', ", \n, tab ct_space = 8, // \r, \n, space, tab ct_parse_cdata = 16, // \0, ], >, \r ct_parse_comment = 32, // \0, -, >, \r ct_symbol = 64, // Any symbol > 127, a-z, A-Z, 0-9, _, :, -, . ct_start_symbol = 128 // Any symbol > 127, a-z, A-Z, _, : }; static const unsigned char chartype_table[256] = { 55, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 0, 0, 63, 0, 0, // 0-15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31 8, 0, 6, 0, 0, 0, 7, 6, 0, 0, 0, 0, 0, 96, 64, 0, // 32-47 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 192, 0, 1, 0, 48, 0, // 48-63 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 64-79 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 16, 0, 192, // 80-95 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 96-111 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 0, // 112-127 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 128+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192 }; enum chartypex_t { ctx_special_pcdata = 1, // Any symbol >= 0 and < 32 (except \t, \r, \n), &, <, > ctx_special_attr = 2, // Any symbol >= 0 and < 32 (except \t), &, <, >, " ctx_start_symbol = 4, // Any symbol > 127, a-z, A-Z, _ ctx_digit = 8, // 0-9 ctx_symbol = 16 // Any symbol > 127, a-z, A-Z, 0-9, _, -, . }; static const unsigned char chartypex_table[256] = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 2, 3, 3, 2, 3, 3, // 0-15 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 16-31 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 16, 16, 0, // 32-47 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 3, 0, 3, 0, // 48-63 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 64-79 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 20, // 80-95 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 96-111 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, // 112-127 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 128+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 }; #ifdef PUGIXML_WCHAR_MODE #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) ((static_cast<unsigned int>(c) < 128 ? table[static_cast<unsigned int>(c)] : table[128]) & (ct)) #else #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) (table[static_cast<unsigned char>(c)] & (ct)) #endif #define PUGI__IS_CHARTYPE(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartype_table) #define PUGI__IS_CHARTYPEX(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartypex_table) PUGI__FN bool is_little_endian() { unsigned int ui = 1; return *reinterpret_cast<unsigned char*>(&ui) == 1; } PUGI__FN xml_encoding get_wchar_encoding() { PUGI__STATIC_ASSERT(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4); if (sizeof(wchar_t) == 2) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be; else return is_little_endian() ? encoding_utf32_le : encoding_utf32_be; } PUGI__FN bool parse_declaration_encoding(const uint8_t* data, size_t size, const uint8_t*& out_encoding, size_t& out_length) { #define PUGI__SCANCHAR(ch) { if (offset >= size || data[offset] != ch) return false; offset++; } #define PUGI__SCANCHARTYPE(ct) { while (offset < size && PUGI__IS_CHARTYPE(data[offset], ct)) offset++; } // check if we have a non-empty XML declaration if (size < 6 || !((data[0] == '<') & (data[1] == '?') & (data[2] == 'x') & (data[3] == 'm') & (data[4] == 'l') && PUGI__IS_CHARTYPE(data[5], ct_space))) return false; // scan XML declaration until the encoding field for (size_t i = 6; i + 1 < size; ++i) { // declaration can not contain ? in quoted values if (data[i] == '?') return false; if (data[i] == 'e' && data[i + 1] == 'n') { size_t offset = i; // encoding follows the version field which can't contain 'en' so this has to be the encoding if XML is well formed PUGI__SCANCHAR('e'); PUGI__SCANCHAR('n'); PUGI__SCANCHAR('c'); PUGI__SCANCHAR('o'); PUGI__SCANCHAR('d'); PUGI__SCANCHAR('i'); PUGI__SCANCHAR('n'); PUGI__SCANCHAR('g'); // S? = S? PUGI__SCANCHARTYPE(ct_space); PUGI__SCANCHAR('='); PUGI__SCANCHARTYPE(ct_space); // the only two valid delimiters are ' and " uint8_t delimiter = (offset < size && data[offset] == '"') ? '"' : '\''; PUGI__SCANCHAR(delimiter); size_t start = offset; out_encoding = data + offset; PUGI__SCANCHARTYPE(ct_symbol); out_length = offset - start; PUGI__SCANCHAR(delimiter); return true; } } return false; #undef PUGI__SCANCHAR #undef PUGI__SCANCHARTYPE } PUGI__FN xml_encoding guess_buffer_encoding(const uint8_t* data, size_t size) { // skip encoding autodetection if input buffer is too small if (size < 4) return encoding_utf8; uint8_t d0 = data[0], d1 = data[1], d2 = data[2], d3 = data[3]; // look for BOM in first few bytes if (d0 == 0 && d1 == 0 && d2 == 0xfe && d3 == 0xff) return encoding_utf32_be; if (d0 == 0xff && d1 == 0xfe && d2 == 0 && d3 == 0) return encoding_utf32_le; if (d0 == 0xfe && d1 == 0xff) return encoding_utf16_be; if (d0 == 0xff && d1 == 0xfe) return encoding_utf16_le; if (d0 == 0xef && d1 == 0xbb && d2 == 0xbf) return encoding_utf8; // look for <, <? or <?xm in various encodings if (d0 == 0 && d1 == 0 && d2 == 0 && d3 == 0x3c) return encoding_utf32_be; if (d0 == 0x3c && d1 == 0 && d2 == 0 && d3 == 0) return encoding_utf32_le; if (d0 == 0 && d1 == 0x3c && d2 == 0 && d3 == 0x3f) return encoding_utf16_be; if (d0 == 0x3c && d1 == 0 && d2 == 0x3f && d3 == 0) return encoding_utf16_le; // look for utf16 < followed by node name (this may fail, but is better than utf8 since it's zero terminated so early) if (d0 == 0 && d1 == 0x3c) return encoding_utf16_be; if (d0 == 0x3c && d1 == 0) return encoding_utf16_le; // no known BOM detected; parse declaration const uint8_t* enc = 0; size_t enc_length = 0; if (d0 == 0x3c && d1 == 0x3f && d2 == 0x78 && d3 == 0x6d && parse_declaration_encoding(data, size, enc, enc_length)) { // iso-8859-1 (case-insensitive) if (enc_length == 10 && (enc[0] | ' ') == 'i' && (enc[1] | ' ') == 's' && (enc[2] | ' ') == 'o' && enc[3] == '-' && enc[4] == '8' && enc[5] == '8' && enc[6] == '5' && enc[7] == '9' && enc[8] == '-' && enc[9] == '1') return encoding_latin1; // latin1 (case-insensitive) if (enc_length == 6 && (enc[0] | ' ') == 'l' && (enc[1] | ' ') == 'a' && (enc[2] | ' ') == 't' && (enc[3] | ' ') == 'i' && (enc[4] | ' ') == 'n' && enc[5] == '1') return encoding_latin1; } return encoding_utf8; } PUGI__FN xml_encoding get_buffer_encoding(xml_encoding encoding, const void* contents, size_t size) { // replace wchar encoding with utf implementation if (encoding == encoding_wchar) return get_wchar_encoding(); // replace utf16 encoding with utf16 with specific endianness if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be; // replace utf32 encoding with utf32 with specific endianness if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be; // only do autodetection if no explicit encoding is requested if (encoding != encoding_auto) return encoding; // try to guess encoding (based on XML specification, Appendix F.1) const uint8_t* data = static_cast<const uint8_t*>(contents); return guess_buffer_encoding(data, size); } PUGI__FN bool get_mutable_buffer(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable) { size_t length = size / sizeof(char_t); if (is_mutable) { out_buffer = static_cast<char_t*>(const_cast<void*>(contents)); out_length = length; } else { char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t))); if (!buffer) return false; if (contents) memcpy(buffer, contents, length * sizeof(char_t)); else assert(length == 0); buffer[length] = 0; out_buffer = buffer; out_length = length + 1; } return true; } #ifdef PUGIXML_WCHAR_MODE PUGI__FN bool need_endian_swap_utf(xml_encoding le, xml_encoding re) { return (le == encoding_utf16_be && re == encoding_utf16_le) || (le == encoding_utf16_le && re == encoding_utf16_be) || (le == encoding_utf32_be && re == encoding_utf32_le) || (le == encoding_utf32_le && re == encoding_utf32_be); } PUGI__FN bool convert_buffer_endian_swap(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable) { const char_t* data = static_cast<const char_t*>(contents); size_t length = size / sizeof(char_t); if (is_mutable) { char_t* buffer = const_cast<char_t*>(data); convert_wchar_endian_swap(buffer, data, length); out_buffer = buffer; out_length = length; } else { char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t))); if (!buffer) return false; convert_wchar_endian_swap(buffer, data, length); buffer[length] = 0; out_buffer = buffer; out_length = length + 1; } return true; } template <typename D> PUGI__FN bool convert_buffer_generic(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, D) { const typename D::type* data = static_cast<const typename D::type*>(contents); size_t data_length = size / sizeof(typename D::type); // first pass: get length in wchar_t units size_t length = D::process(data, data_length, 0, wchar_counter()); // allocate buffer of suitable length char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t))); if (!buffer) return false; // second pass: convert utf16 input to wchar_t wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer); wchar_writer::value_type oend = D::process(data, data_length, obegin, wchar_writer()); assert(oend == obegin + length); *oend = 0; out_buffer = buffer; out_length = length + 1; return true; } PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable) { // get native encoding xml_encoding wchar_encoding = get_wchar_encoding(); // fast path: no conversion required if (encoding == wchar_encoding) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable); // only endian-swapping is required if (need_endian_swap_utf(encoding, wchar_encoding)) return convert_buffer_endian_swap(out_buffer, out_length, contents, size, is_mutable); // source encoding is utf8 if (encoding == encoding_utf8) return convert_buffer_generic(out_buffer, out_length, contents, size, utf8_decoder()); // source encoding is utf16 if (encoding == encoding_utf16_be || encoding == encoding_utf16_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be; return (native_encoding == encoding) ? convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_false>()) : convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_true>()); } // source encoding is utf32 if (encoding == encoding_utf32_be || encoding == encoding_utf32_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be; return (native_encoding == encoding) ? convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_false>()) : convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_true>()); } // source encoding is latin1 if (encoding == encoding_latin1) return convert_buffer_generic(out_buffer, out_length, contents, size, latin1_decoder()); assert(false && "Invalid encoding"); return false; } #else template <typename D> PUGI__FN bool convert_buffer_generic(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, D) { const typename D::type* data = static_cast<const typename D::type*>(contents); size_t data_length = size / sizeof(typename D::type); // first pass: get length in utf8 units size_t length = D::process(data, data_length, 0, utf8_counter()); // allocate buffer of suitable length char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t))); if (!buffer) return false; // second pass: convert utf16 input to utf8 uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer); uint8_t* oend = D::process(data, data_length, obegin, utf8_writer()); assert(oend == obegin + length); *oend = 0; out_buffer = buffer; out_length = length + 1; return true; } PUGI__FN size_t get_latin1_7bit_prefix_length(const uint8_t* data, size_t size) { for (size_t i = 0; i < size; ++i) if (data[i] > 127) return i; return size; } PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable) { const uint8_t* data = static_cast<const uint8_t*>(contents); size_t data_length = size; // get size of prefix that does not need utf8 conversion size_t prefix_length = get_latin1_7bit_prefix_length(data, data_length); assert(prefix_length <= data_length); const uint8_t* postfix = data + prefix_length; size_t postfix_length = data_length - prefix_length; // if no conversion is needed, just return the original buffer if (postfix_length == 0) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable); // first pass: get length in utf8 units size_t length = prefix_length + latin1_decoder::process(postfix, postfix_length, 0, utf8_counter()); // allocate buffer of suitable length char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t))); if (!buffer) return false; // second pass: convert latin1 input to utf8 memcpy(buffer, data, prefix_length); uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer); uint8_t* oend = latin1_decoder::process(postfix, postfix_length, obegin + prefix_length, utf8_writer()); assert(oend == obegin + length); *oend = 0; out_buffer = buffer; out_length = length + 1; return true; } PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable) { // fast path: no conversion required if (encoding == encoding_utf8) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable); // source encoding is utf16 if (encoding == encoding_utf16_be || encoding == encoding_utf16_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be; return (native_encoding == encoding) ? convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_false>()) : convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_true>()); } // source encoding is utf32 if (encoding == encoding_utf32_be || encoding == encoding_utf32_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be; return (native_encoding == encoding) ? convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_false>()) : convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_true>()); } // source encoding is latin1 if (encoding == encoding_latin1) return convert_buffer_latin1(out_buffer, out_length, contents, size, is_mutable); assert(false && "Invalid encoding"); return false; } #endif PUGI__FN size_t as_utf8_begin(const wchar_t* str, size_t length) { // get length in utf8 characters return wchar_decoder::process(str, length, 0, utf8_counter()); } PUGI__FN void as_utf8_end(char* buffer, size_t size, const wchar_t* str, size_t length) { // convert to utf8 uint8_t* begin = reinterpret_cast<uint8_t*>(buffer); uint8_t* end = wchar_decoder::process(str, length, begin, utf8_writer()); assert(begin + size == end); (void)!end; (void)!size; } #ifndef PUGIXML_NO_STL PUGI__FN std::string as_utf8_impl(const wchar_t* str, size_t length) { // first pass: get length in utf8 characters size_t size = as_utf8_begin(str, length); // allocate resulting string std::string result; result.resize(size); // second pass: convert to utf8 if (size > 0) as_utf8_end(&result[0], size, str, length); return result; } PUGI__FN std::basic_string<wchar_t> as_wide_impl(const char* str, size_t size) { const uint8_t* data = reinterpret_cast<const uint8_t*>(str); // first pass: get length in wchar_t units size_t length = utf8_decoder::process(data, size, 0, wchar_counter()); // allocate resulting string std::basic_string<wchar_t> result; result.resize(length); // second pass: convert to wchar_t if (length > 0) { wchar_writer::value_type begin = reinterpret_cast<wchar_writer::value_type>(&result[0]); wchar_writer::value_type end = utf8_decoder::process(data, size, begin, wchar_writer()); assert(begin + length == end); (void)!end; } return result; } #endif template <typename Header> inline bool strcpy_insitu_allow(size_t length, const Header& header, uintptr_t header_mask, char_t* target) { // never reuse shared memory if (header & xml_memory_page_contents_shared_mask) return false; size_t target_length = strlength(target); // always reuse document buffer memory if possible if ((header & header_mask) == 0) return target_length >= length; // reuse heap memory if waste is not too great const size_t reuse_threshold = 32; return target_length >= length && (target_length < reuse_threshold || target_length - length < target_length / 2); } template <typename String, typename Header> PUGI__FN bool strcpy_insitu(String& dest, Header& header, uintptr_t header_mask, const char_t* source, size_t source_length) { if (source_length == 0) { // empty string and null pointer are equivalent, so just deallocate old memory xml_allocator* alloc = PUGI__GETPAGE_IMPL(header)->allocator; if (header & header_mask) alloc->deallocate_string(dest); // mark the string as not allocated dest = 0; header &= ~header_mask; return true; } else if (dest && strcpy_insitu_allow(source_length, header, header_mask, dest)) { // we can reuse old buffer, so just copy the new data (including zero terminator) memcpy(dest, source, source_length * sizeof(char_t)); dest[source_length] = 0; return true; } else { xml_allocator* alloc = PUGI__GETPAGE_IMPL(header)->allocator; if (!alloc->reserve()) return false; // allocate new buffer char_t* buf = alloc->allocate_string(source_length + 1); if (!buf) return false; // copy the string (including zero terminator) memcpy(buf, source, source_length * sizeof(char_t)); buf[source_length] = 0; // deallocate old buffer (*after* the above to protect against overlapping memory and/or allocation failures) if (header & header_mask) alloc->deallocate_string(dest); // the string is now allocated, so set the flag dest = buf; header |= header_mask; return true; } } struct gap { char_t* end; size_t size; gap(): end(0), size(0) { } // Push new gap, move s count bytes further (skipping the gap). // Collapse previous gap. void push(char_t*& s, size_t count) { if (end) // there was a gap already; collapse it { // Move [old_gap_end, new_gap_start) to [old_gap_start, ...) assert(s >= end); memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end)); } s += count; // end of current gap // "merge" two gaps end = s; size += count; } // Collapse all gaps, return past-the-end pointer char_t* flush(char_t* s) { if (end) { // Move [old_gap_end, current_pos) to [old_gap_start, ...) assert(s >= end); memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end)); return s - size; } else return s; } }; PUGI__FN char_t* strconv_escape(char_t* s, gap& g) { char_t* stre = s + 1; switch (*stre) { case '#': // &#... { unsigned int ucsc = 0; if (stre[1] == 'x') // &#x... (hex code) { stre += 2; char_t ch = *stre; if (ch == ';') return stre; for (;;) { if (static_cast<unsigned int>(ch - '0') <= 9) ucsc = 16 * ucsc + (ch - '0'); else if (static_cast<unsigned int>((ch | ' ') - 'a') <= 5) ucsc = 16 * ucsc + ((ch | ' ') - 'a' + 10); else if (ch == ';') break; else // cancel return stre; ch = *++stre; } ++stre; } else // &#... (dec code) { char_t ch = *++stre; if (ch == ';') return stre; for (;;) { if (static_cast<unsigned int>(static_cast<unsigned int>(ch) - '0') <= 9) ucsc = 10 * ucsc + (ch - '0'); else if (ch == ';') break; else // cancel return stre; ch = *++stre; } ++stre; } #ifdef PUGIXML_WCHAR_MODE s = reinterpret_cast<char_t*>(wchar_writer::any(reinterpret_cast<wchar_writer::value_type>(s), ucsc)); #else s = reinterpret_cast<char_t*>(utf8_writer::any(reinterpret_cast<uint8_t*>(s), ucsc)); #endif g.push(s, stre - s); return stre; } case 'a': // &a { ++stre; if (*stre == 'm') // &am { if (*++stre == 'p' && *++stre == ';') // &amp; { *s++ = '&'; ++stre; g.push(s, stre - s); return stre; } } else if (*stre == 'p') // &ap { if (*++stre == 'o' && *++stre == 's' && *++stre == ';') // &apos; { *s++ = '\''; ++stre; g.push(s, stre - s); return stre; } } break; } case 'g': // &g { if (*++stre == 't' && *++stre == ';') // &gt; { *s++ = '>'; ++stre; g.push(s, stre - s); return stre; } break; } case 'l': // &l { if (*++stre == 't' && *++stre == ';') // &lt; { *s++ = '<'; ++stre; g.push(s, stre - s); return stre; } break; } case 'q': // &q { if (*++stre == 'u' && *++stre == 'o' && *++stre == 't' && *++stre == ';') // &quot; { *s++ = '"'; ++stre; g.push(s, stre - s); return stre; } break; } default: break; } return stre; } // Parser utilities #define PUGI__ENDSWITH(c, e) ((c) == (e) || ((c) == 0 && endch == (e))) #define PUGI__SKIPWS() { while (PUGI__IS_CHARTYPE(*s, ct_space)) ++s; } #define PUGI__OPTSET(OPT) ( optmsk & (OPT) ) #define PUGI__PUSHNODE(TYPE) { cursor = append_new_node(cursor, *alloc, TYPE); if (!cursor) PUGI__THROW_ERROR(status_out_of_memory, s); } #define PUGI__POPNODE() { cursor = cursor->parent; } #define PUGI__SCANFOR(X) { while (*s != 0 && !(X)) ++s; } #define PUGI__SCANWHILE(X) { while (X) ++s; } #define PUGI__SCANWHILE_UNROLL(X) { for (;;) { char_t ss = s[0]; if (PUGI__UNLIKELY(!(X))) { break; } ss = s[1]; if (PUGI__UNLIKELY(!(X))) { s += 1; break; } ss = s[2]; if (PUGI__UNLIKELY(!(X))) { s += 2; break; } ss = s[3]; if (PUGI__UNLIKELY(!(X))) { s += 3; break; } s += 4; } } #define PUGI__ENDSEG() { ch = *s; *s = 0; ++s; } #define PUGI__THROW_ERROR(err, m) return error_offset = m, error_status = err, static_cast<char_t*>(0) #define PUGI__CHECK_ERROR(err, m) { if (*s == 0) PUGI__THROW_ERROR(err, m); } PUGI__FN char_t* strconv_comment(char_t* s, char_t endch) { gap g; while (true) { PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_comment)); if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair { *s++ = '\n'; // replace first one with 0x0a if (*s == '\n') g.push(s, 1); } else if (s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>')) // comment ends here { *g.flush(s) = 0; return s + (s[2] == '>' ? 3 : 2); } else if (*s == 0) { return 0; } else ++s; } } PUGI__FN char_t* strconv_cdata(char_t* s, char_t endch) { gap g; while (true) { PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_cdata)); if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair { *s++ = '\n'; // replace first one with 0x0a if (*s == '\n') g.push(s, 1); } else if (s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>')) // CDATA ends here { *g.flush(s) = 0; return s + 1; } else if (*s == 0) { return 0; } else ++s; } } typedef char_t* (*strconv_pcdata_t)(char_t*); template <typename opt_trim, typename opt_eol, typename opt_escape> struct strconv_pcdata_impl { static char_t* parse(char_t* s) { gap g; char_t* begin = s; while (true) { PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_pcdata)); if (*s == '<') // PCDATA ends here { char_t* end = g.flush(s); if (opt_trim::value) while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space)) --end; *end = 0; return s + 1; } else if (opt_eol::value && *s == '\r') // Either a single 0x0d or 0x0d 0x0a pair { *s++ = '\n'; // replace first one with 0x0a if (*s == '\n') g.push(s, 1); } else if (opt_escape::value && *s == '&') { s = strconv_escape(s, g); } else if (*s == 0) { char_t* end = g.flush(s); if (opt_trim::value) while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space)) --end; *end = 0; return s; } else ++s; } } }; PUGI__FN strconv_pcdata_t get_strconv_pcdata(unsigned int optmask) { PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_trim_pcdata == 0x0800); switch (((optmask >> 4) & 3) | ((optmask >> 9) & 4)) // get bitmask for flags (eol escapes trim) { case 0: return strconv_pcdata_impl<opt_false, opt_false, opt_false>::parse; case 1: return strconv_pcdata_impl<opt_false, opt_false, opt_true>::parse; case 2: return strconv_pcdata_impl<opt_false, opt_true, opt_false>::parse; case 3: return strconv_pcdata_impl<opt_false, opt_true, opt_true>::parse; case 4: return strconv_pcdata_impl<opt_true, opt_false, opt_false>::parse; case 5: return strconv_pcdata_impl<opt_true, opt_false, opt_true>::parse; case 6: return strconv_pcdata_impl<opt_true, opt_true, opt_false>::parse; case 7: return strconv_pcdata_impl<opt_true, opt_true, opt_true>::parse; default: assert(false); return 0; // should not get here } } typedef char_t* (*strconv_attribute_t)(char_t*, char_t); template <typename opt_escape> struct strconv_attribute_impl { static char_t* parse_wnorm(char_t* s, char_t end_quote) { gap g; // trim leading whitespaces if (PUGI__IS_CHARTYPE(*s, ct_space)) { char_t* str = s; do ++str; while (PUGI__IS_CHARTYPE(*str, ct_space)); g.push(s, str - s); } while (true) { PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws | ct_space)); if (*s == end_quote) { char_t* str = g.flush(s); do *str-- = 0; while (PUGI__IS_CHARTYPE(*str, ct_space)); return s + 1; } else if (PUGI__IS_CHARTYPE(*s, ct_space)) { *s++ = ' '; if (PUGI__IS_CHARTYPE(*s, ct_space)) { char_t* str = s + 1; while (PUGI__IS_CHARTYPE(*str, ct_space)) ++str; g.push(s, str - s); } } else if (opt_escape::value && *s == '&') { s = strconv_escape(s, g); } else if (!*s) { return 0; } else ++s; } } static char_t* parse_wconv(char_t* s, char_t end_quote) { gap g; while (true) { PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws)); if (*s == end_quote) { *g.flush(s) = 0; return s + 1; } else if (PUGI__IS_CHARTYPE(*s, ct_space)) { if (*s == '\r') { *s++ = ' '; if (*s == '\n') g.push(s, 1); } else *s++ = ' '; } else if (opt_escape::value && *s == '&') { s = strconv_escape(s, g); } else if (!*s) { return 0; } else ++s; } } static char_t* parse_eol(char_t* s, char_t end_quote) { gap g; while (true) { PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr)); if (*s == end_quote) { *g.flush(s) = 0; return s + 1; } else if (*s == '\r') { *s++ = '\n'; if (*s == '\n') g.push(s, 1); } else if (opt_escape::value && *s == '&') { s = strconv_escape(s, g); } else if (!*s) { return 0; } else ++s; } } static char_t* parse_simple(char_t* s, char_t end_quote) { gap g; while (true) { PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr)); if (*s == end_quote) { *g.flush(s) = 0; return s + 1; } else if (opt_escape::value && *s == '&') { s = strconv_escape(s, g); } else if (!*s) { return 0; } else ++s; } } }; PUGI__FN strconv_attribute_t get_strconv_attribute(unsigned int optmask) { PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_wconv_attribute == 0x40 && parse_wnorm_attribute == 0x80); switch ((optmask >> 4) & 15) // get bitmask for flags (wconv wnorm eol escapes) { case 0: return strconv_attribute_impl<opt_false>::parse_simple; case 1: return strconv_attribute_impl<opt_true>::parse_simple; case 2: return strconv_attribute_impl<opt_false>::parse_eol; case 3: return strconv_attribute_impl<opt_true>::parse_eol; case 4: return strconv_attribute_impl<opt_false>::parse_wconv; case 5: return strconv_attribute_impl<opt_true>::parse_wconv; case 6: return strconv_attribute_impl<opt_false>::parse_wconv; case 7: return strconv_attribute_impl<opt_true>::parse_wconv; case 8: return strconv_attribute_impl<opt_false>::parse_wnorm; case 9: return strconv_attribute_impl<opt_true>::parse_wnorm; case 10: return strconv_attribute_impl<opt_false>::parse_wnorm; case 11: return strconv_attribute_impl<opt_true>::parse_wnorm; case 12: return strconv_attribute_impl<opt_false>::parse_wnorm; case 13: return strconv_attribute_impl<opt_true>::parse_wnorm; case 14: return strconv_attribute_impl<opt_false>::parse_wnorm; case 15: return strconv_attribute_impl<opt_true>::parse_wnorm; default: assert(false); return 0; // should not get here } } inline xml_parse_result make_parse_result(xml_parse_status status, ptrdiff_t offset = 0) { xml_parse_result result; result.status = status; result.offset = offset; return result; } struct xml_parser { xml_allocator* alloc; char_t* error_offset; xml_parse_status error_status; xml_parser(xml_allocator* alloc_): alloc(alloc_), error_offset(0), error_status(status_ok) { } // DOCTYPE consists of nested sections of the following possible types: // <!-- ... -->, <? ... ?>, "...", '...' // <![...]]> // <!...> // First group can not contain nested groups // Second group can contain nested groups of the same type // Third group can contain all other groups char_t* parse_doctype_primitive(char_t* s) { if (*s == '"' || *s == '\'') { // quoted string char_t ch = *s++; PUGI__SCANFOR(*s == ch); if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s); s++; } else if (s[0] == '<' && s[1] == '?') { // <? ... ?> s += 2; PUGI__SCANFOR(s[0] == '?' && s[1] == '>'); // no need for ENDSWITH because ?> can't terminate proper doctype if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s); s += 2; } else if (s[0] == '<' && s[1] == '!' && s[2] == '-' && s[3] == '-') { s += 4; PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && s[2] == '>'); // no need for ENDSWITH because --> can't terminate proper doctype if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s); s += 3; } else PUGI__THROW_ERROR(status_bad_doctype, s); return s; } char_t* parse_doctype_ignore(char_t* s) { size_t depth = 0; assert(s[0] == '<' && s[1] == '!' && s[2] == '['); s += 3; while (*s) { if (s[0] == '<' && s[1] == '!' && s[2] == '[') { // nested ignore section s += 3; depth++; } else if (s[0] == ']' && s[1] == ']' && s[2] == '>') { // ignore section end s += 3; if (depth == 0) return s; depth--; } else s++; } PUGI__THROW_ERROR(status_bad_doctype, s); } char_t* parse_doctype_group(char_t* s, char_t endch) { size_t depth = 0; assert((s[0] == '<' || s[0] == 0) && s[1] == '!'); s += 2; while (*s) { if (s[0] == '<' && s[1] == '!' && s[2] != '-') { if (s[2] == '[') { // ignore s = parse_doctype_ignore(s); if (!s) return s; } else { // some control group s += 2; depth++; } } else if (s[0] == '<' || s[0] == '"' || s[0] == '\'') { // unknown tag (forbidden), or some primitive group s = parse_doctype_primitive(s); if (!s) return s; } else if (*s == '>') { if (depth == 0) return s; depth--; s++; } else s++; } if (depth != 0 || endch != '>') PUGI__THROW_ERROR(status_bad_doctype, s); return s; } char_t* parse_exclamation(char_t* s, xml_node_struct* cursor, unsigned int optmsk, char_t endch) { // parse node contents, starting with exclamation mark ++s; if (*s == '-') // '<!-...' { ++s; if (*s == '-') // '<!--...' { ++s; if (PUGI__OPTSET(parse_comments)) { PUGI__PUSHNODE(node_comment); // Append a new node on the tree. cursor->value = s; // Save the offset. } if (PUGI__OPTSET(parse_eol) && PUGI__OPTSET(parse_comments)) { s = strconv_comment(s, endch); if (!s) PUGI__THROW_ERROR(status_bad_comment, cursor->value); } else { // Scan for terminating '-->'. PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>')); PUGI__CHECK_ERROR(status_bad_comment, s); if (PUGI__OPTSET(parse_comments)) *s = 0; // Zero-terminate this segment at the first terminating '-'. s += (s[2] == '>' ? 3 : 2); // Step over the '\0->'. } } else PUGI__THROW_ERROR(status_bad_comment, s); } else if (*s == '[') { // '<![CDATA[...' if (*++s=='C' && *++s=='D' && *++s=='A' && *++s=='T' && *++s=='A' && *++s == '[') { ++s; if (PUGI__OPTSET(parse_cdata)) { PUGI__PUSHNODE(node_cdata); // Append a new node on the tree. cursor->value = s; // Save the offset. if (PUGI__OPTSET(parse_eol)) { s = strconv_cdata(s, endch); if (!s) PUGI__THROW_ERROR(status_bad_cdata, cursor->value); } else { // Scan for terminating ']]>'. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>')); PUGI__CHECK_ERROR(status_bad_cdata, s); *s++ = 0; // Zero-terminate this segment. } } else // Flagged for discard, but we still have to scan for the terminator. { // Scan for terminating ']]>'. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>')); PUGI__CHECK_ERROR(status_bad_cdata, s); ++s; } s += (s[1] == '>' ? 2 : 1); // Step over the last ']>'. } else PUGI__THROW_ERROR(status_bad_cdata, s); } else if (s[0] == 'D' && s[1] == 'O' && s[2] == 'C' && s[3] == 'T' && s[4] == 'Y' && s[5] == 'P' && PUGI__ENDSWITH(s[6], 'E')) { s -= 2; if (cursor->parent) PUGI__THROW_ERROR(status_bad_doctype, s); char_t* mark = s + 9; s = parse_doctype_group(s, endch); if (!s) return s; assert((*s == 0 && endch == '>') || *s == '>'); if (*s) *s++ = 0; if (PUGI__OPTSET(parse_doctype)) { while (PUGI__IS_CHARTYPE(*mark, ct_space)) ++mark; PUGI__PUSHNODE(node_doctype); cursor->value = mark; } } else if (*s == 0 && endch == '-') PUGI__THROW_ERROR(status_bad_comment, s); else if (*s == 0 && endch == '[') PUGI__THROW_ERROR(status_bad_cdata, s); else PUGI__THROW_ERROR(status_unrecognized_tag, s); return s; } char_t* parse_question(char_t* s, xml_node_struct*& ref_cursor, unsigned int optmsk, char_t endch) { // load into registers xml_node_struct* cursor = ref_cursor; char_t ch = 0; // parse node contents, starting with question mark ++s; // read PI target char_t* target = s; if (!PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_pi, s); PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol)); PUGI__CHECK_ERROR(status_bad_pi, s); // determine node type; stricmp / strcasecmp is not portable bool declaration = (target[0] | ' ') == 'x' && (target[1] | ' ') == 'm' && (target[2] | ' ') == 'l' && target + 3 == s; if (declaration ? PUGI__OPTSET(parse_declaration) : PUGI__OPTSET(parse_pi)) { if (declaration) { // disallow non top-level declarations if (cursor->parent) PUGI__THROW_ERROR(status_bad_pi, s); PUGI__PUSHNODE(node_declaration); } else { PUGI__PUSHNODE(node_pi); } cursor->name = target; PUGI__ENDSEG(); // parse value/attributes if (ch == '?') { // empty node if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_pi, s); s += (*s == '>'); PUGI__POPNODE(); } else if (PUGI__IS_CHARTYPE(ch, ct_space)) { PUGI__SKIPWS(); // scan for tag end char_t* value = s; PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>')); PUGI__CHECK_ERROR(status_bad_pi, s); if (declaration) { // replace ending ? with / so that 'element' terminates properly *s = '/'; // we exit from this function with cursor at node_declaration, which is a signal to parse() to go to LOC_ATTRIBUTES s = value; } else { // store value and step over > cursor->value = value; PUGI__POPNODE(); PUGI__ENDSEG(); s += (*s == '>'); } } else PUGI__THROW_ERROR(status_bad_pi, s); } else { // scan for tag end PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>')); PUGI__CHECK_ERROR(status_bad_pi, s); s += (s[1] == '>' ? 2 : 1); } // store from registers ref_cursor = cursor; return s; } char_t* parse_tree(char_t* s, xml_node_struct* root, unsigned int optmsk, char_t endch) { strconv_attribute_t strconv_attribute = get_strconv_attribute(optmsk); strconv_pcdata_t strconv_pcdata = get_strconv_pcdata(optmsk); char_t ch = 0; xml_node_struct* cursor = root; char_t* mark = s; while (*s != 0) { if (*s == '<') { ++s; LOC_TAG: if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // '<#...' { PUGI__PUSHNODE(node_element); // Append a new node to the tree. cursor->name = s; PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over. if (ch == '>') { // end of tag } else if (PUGI__IS_CHARTYPE(ch, ct_space)) { LOC_ATTRIBUTES: while (true) { PUGI__SKIPWS(); // Eat any whitespace. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // <... #... { xml_attribute_struct* a = append_new_attribute(cursor, *alloc); // Make space for this attribute. if (!a) PUGI__THROW_ERROR(status_out_of_memory, s); a->name = s; // Save the offset. PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over. if (PUGI__IS_CHARTYPE(ch, ct_space)) { PUGI__SKIPWS(); // Eat any whitespace. ch = *s; ++s; } if (ch == '=') // '<... #=...' { PUGI__SKIPWS(); // Eat any whitespace. if (*s == '"' || *s == '\'') // '<... #="...' { ch = *s; // Save quote char to avoid breaking on "''" -or- '""'. ++s; // Step over the quote. a->value = s; // Save the offset. s = strconv_attribute(s, ch); if (!s) PUGI__THROW_ERROR(status_bad_attribute, a->value); // After this line the loop continues from the start; // Whitespaces, / and > are ok, symbols and EOF are wrong, // everything else will be detected if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_attribute, s); } else PUGI__THROW_ERROR(status_bad_attribute, s); } else PUGI__THROW_ERROR(status_bad_attribute, s); } else if (*s == '/') { ++s; if (*s == '>') { PUGI__POPNODE(); s++; break; } else if (*s == 0 && endch == '>') { PUGI__POPNODE(); break; } else PUGI__THROW_ERROR(status_bad_start_element, s); } else if (*s == '>') { ++s; break; } else if (*s == 0 && endch == '>') { break; } else PUGI__THROW_ERROR(status_bad_start_element, s); } // !!! } else if (ch == '/') // '<#.../' { if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_start_element, s); PUGI__POPNODE(); // Pop. s += (*s == '>'); } else if (ch == 0) { // we stepped over null terminator, backtrack & handle closing tag --s; if (endch != '>') PUGI__THROW_ERROR(status_bad_start_element, s); } else PUGI__THROW_ERROR(status_bad_start_element, s); } else if (*s == '/') { ++s; mark = s; char_t* name = cursor->name; if (!name) PUGI__THROW_ERROR(status_end_element_mismatch, mark); while (PUGI__IS_CHARTYPE(*s, ct_symbol)) { if (*s++ != *name++) PUGI__THROW_ERROR(status_end_element_mismatch, mark); } if (*name) { if (*s == 0 && name[0] == endch && name[1] == 0) PUGI__THROW_ERROR(status_bad_end_element, s); else PUGI__THROW_ERROR(status_end_element_mismatch, mark); } PUGI__POPNODE(); // Pop. PUGI__SKIPWS(); if (*s == 0) { if (endch != '>') PUGI__THROW_ERROR(status_bad_end_element, s); } else { if (*s != '>') PUGI__THROW_ERROR(status_bad_end_element, s); ++s; } } else if (*s == '?') // '<?...' { s = parse_question(s, cursor, optmsk, endch); if (!s) return s; assert(cursor); if (PUGI__NODETYPE(cursor) == node_declaration) goto LOC_ATTRIBUTES; } else if (*s == '!') // '<!...' { s = parse_exclamation(s, cursor, optmsk, endch); if (!s) return s; } else if (*s == 0 && endch == '?') PUGI__THROW_ERROR(status_bad_pi, s); else PUGI__THROW_ERROR(status_unrecognized_tag, s); } else { mark = s; // Save this offset while searching for a terminator. PUGI__SKIPWS(); // Eat whitespace if no genuine PCDATA here. if (*s == '<' || !*s) { // We skipped some whitespace characters because otherwise we would take the tag branch instead of PCDATA one assert(mark != s); if (!PUGI__OPTSET(parse_ws_pcdata | parse_ws_pcdata_single) || PUGI__OPTSET(parse_trim_pcdata)) { continue; } else if (PUGI__OPTSET(parse_ws_pcdata_single)) { if (s[0] != '<' || s[1] != '/' || cursor->first_child) continue; } } if (!PUGI__OPTSET(parse_trim_pcdata)) s = mark; if (cursor->parent || PUGI__OPTSET(parse_fragment)) { if (PUGI__OPTSET(parse_embed_pcdata) && cursor->parent && !cursor->first_child && !cursor->value) { cursor->value = s; // Save the offset. } else { PUGI__PUSHNODE(node_pcdata); // Append a new node on the tree. cursor->value = s; // Save the offset. PUGI__POPNODE(); // Pop since this is a standalone. } s = strconv_pcdata(s); if (!*s) break; } else { PUGI__SCANFOR(*s == '<'); // '...<' if (!*s) break; ++s; } // We're after '<' goto LOC_TAG; } } // check that last tag is closed if (cursor != root) PUGI__THROW_ERROR(status_end_element_mismatch, s); return s; } #ifdef PUGIXML_WCHAR_MODE static char_t* parse_skip_bom(char_t* s) { unsigned int bom = 0xfeff; return (s[0] == static_cast<wchar_t>(bom)) ? s + 1 : s; } #else static char_t* parse_skip_bom(char_t* s) { return (s[0] == '\xef' && s[1] == '\xbb' && s[2] == '\xbf') ? s + 3 : s; } #endif static bool has_element_node_siblings(xml_node_struct* node) { while (node) { if (PUGI__NODETYPE(node) == node_element) return true; node = node->next_sibling; } return false; } static xml_parse_result parse(char_t* buffer, size_t length, xml_document_struct* xmldoc, xml_node_struct* root, unsigned int optmsk) { // early-out for empty documents if (length == 0) return make_parse_result(PUGI__OPTSET(parse_fragment) ? status_ok : status_no_document_element); // get last child of the root before parsing xml_node_struct* last_root_child = root->first_child ? root->first_child->prev_sibling_c + 0 : 0; // create parser on stack xml_parser parser(static_cast<xml_allocator*>(xmldoc)); // save last character and make buffer zero-terminated (speeds up parsing) char_t endch = buffer[length - 1]; buffer[length - 1] = 0; // skip BOM to make sure it does not end up as part of parse output char_t* buffer_data = parse_skip_bom(buffer); // perform actual parsing parser.parse_tree(buffer_data, root, optmsk, endch); xml_parse_result result = make_parse_result(parser.error_status, parser.error_offset ? parser.error_offset - buffer : 0); assert(result.offset >= 0 && static_cast<size_t>(result.offset) <= length); if (result) { // since we removed last character, we have to handle the only possible false positive (stray <) if (endch == '<') return make_parse_result(status_unrecognized_tag, length - 1); // check if there are any element nodes parsed xml_node_struct* first_root_child_parsed = last_root_child ? last_root_child->next_sibling + 0 : root->first_child+ 0; if (!PUGI__OPTSET(parse_fragment) && !has_element_node_siblings(first_root_child_parsed)) return make_parse_result(status_no_document_element, length - 1); } else { // roll back offset if it occurs on a null terminator in the source buffer if (result.offset > 0 && static_cast<size_t>(result.offset) == length - 1 && endch == 0) result.offset--; } return result; } }; // Output facilities PUGI__FN xml_encoding get_write_native_encoding() { #ifdef PUGIXML_WCHAR_MODE return get_wchar_encoding(); #else return encoding_utf8; #endif } PUGI__FN xml_encoding get_write_encoding(xml_encoding encoding) { // replace wchar encoding with utf implementation if (encoding == encoding_wchar) return get_wchar_encoding(); // replace utf16 encoding with utf16 with specific endianness if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be; // replace utf32 encoding with utf32 with specific endianness if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be; // only do autodetection if no explicit encoding is requested if (encoding != encoding_auto) return encoding; // assume utf8 encoding return encoding_utf8; } template <typename D, typename T> PUGI__FN size_t convert_buffer_output_generic(typename T::value_type dest, const char_t* data, size_t length, D, T) { PUGI__STATIC_ASSERT(sizeof(char_t) == sizeof(typename D::type)); typename T::value_type end = D::process(reinterpret_cast<const typename D::type*>(data), length, dest, T()); return static_cast<size_t>(end - dest) * sizeof(*dest); } template <typename D, typename T> PUGI__FN size_t convert_buffer_output_generic(typename T::value_type dest, const char_t* data, size_t length, D, T, bool opt_swap) { PUGI__STATIC_ASSERT(sizeof(char_t) == sizeof(typename D::type)); typename T::value_type end = D::process(reinterpret_cast<const typename D::type*>(data), length, dest, T()); if (opt_swap) { for (typename T::value_type i = dest; i != end; ++i) *i = endian_swap(*i); } return static_cast<size_t>(end - dest) * sizeof(*dest); } #ifdef PUGIXML_WCHAR_MODE PUGI__FN size_t get_valid_length(const char_t* data, size_t length) { if (length < 1) return 0; // discard last character if it's the lead of a surrogate pair return (sizeof(wchar_t) == 2 && static_cast<unsigned int>(static_cast<uint16_t>(data[length - 1]) - 0xD800) < 0x400) ? length - 1 : length; } PUGI__FN size_t convert_buffer_output(char_t* r_char, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding) { // only endian-swapping is required if (need_endian_swap_utf(encoding, get_wchar_encoding())) { convert_wchar_endian_swap(r_char, data, length); return length * sizeof(char_t); } // convert to utf8 if (encoding == encoding_utf8) return convert_buffer_output_generic(r_u8, data, length, wchar_decoder(), utf8_writer()); // convert to utf16 if (encoding == encoding_utf16_be || encoding == encoding_utf16_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be; return convert_buffer_output_generic(r_u16, data, length, wchar_decoder(), utf16_writer(), native_encoding != encoding); } // convert to utf32 if (encoding == encoding_utf32_be || encoding == encoding_utf32_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be; return convert_buffer_output_generic(r_u32, data, length, wchar_decoder(), utf32_writer(), native_encoding != encoding); } // convert to latin1 if (encoding == encoding_latin1) return convert_buffer_output_generic(r_u8, data, length, wchar_decoder(), latin1_writer()); assert(false && "Invalid encoding"); return 0; } #else PUGI__FN size_t get_valid_length(const char_t* data, size_t length) { if (length < 5) return 0; for (size_t i = 1; i <= 4; ++i) { uint8_t ch = static_cast<uint8_t>(data[length - i]); // either a standalone character or a leading one if ((ch & 0xc0) != 0x80) return length - i; } // there are four non-leading characters at the end, sequence tail is broken so might as well process the whole chunk return length; } PUGI__FN size_t convert_buffer_output(char_t* /* r_char */, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding) { if (encoding == encoding_utf16_be || encoding == encoding_utf16_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be; return convert_buffer_output_generic(r_u16, data, length, utf8_decoder(), utf16_writer(), native_encoding != encoding); } if (encoding == encoding_utf32_be || encoding == encoding_utf32_le) { xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be; return convert_buffer_output_generic(r_u32, data, length, utf8_decoder(), utf32_writer(), native_encoding != encoding); } if (encoding == encoding_latin1) return convert_buffer_output_generic(r_u8, data, length, utf8_decoder(), latin1_writer()); assert(false && "Invalid encoding"); return 0; } #endif class xml_buffered_writer { xml_buffered_writer(const xml_buffered_writer&); xml_buffered_writer& operator=(const xml_buffered_writer&); public: xml_buffered_writer(xml_writer& writer_, xml_encoding user_encoding): writer(writer_), bufsize(0), encoding(get_write_encoding(user_encoding)) { PUGI__STATIC_ASSERT(bufcapacity >= 8); } size_t flush() { flush(buffer, bufsize); bufsize = 0; return 0; } void flush(const char_t* data, size_t size) { if (size == 0) return; // fast path, just write data if (encoding == get_write_native_encoding()) writer.write(data, size * sizeof(char_t)); else { // convert chunk size_t result = convert_buffer_output(scratch.data_char, scratch.data_u8, scratch.data_u16, scratch.data_u32, data, size, encoding); assert(result <= sizeof(scratch)); // write data writer.write(scratch.data_u8, result); } } void write_direct(const char_t* data, size_t length) { // flush the remaining buffer contents flush(); // handle large chunks if (length > bufcapacity) { if (encoding == get_write_native_encoding()) { // fast path, can just write data chunk writer.write(data, length * sizeof(char_t)); return; } // need to convert in suitable chunks while (length > bufcapacity) { // get chunk size by selecting such number of characters that are guaranteed to fit into scratch buffer // and form a complete codepoint sequence (i.e. discard start of last codepoint if necessary) size_t chunk_size = get_valid_length(data, bufcapacity); assert(chunk_size); // convert chunk and write flush(data, chunk_size); // iterate data += chunk_size; length -= chunk_size; } // small tail is copied below bufsize = 0; } memcpy(buffer + bufsize, data, length * sizeof(char_t)); bufsize += length; } void write_buffer(const char_t* data, size_t length) { size_t offset = bufsize; if (offset + length <= bufcapacity) { memcpy(buffer + offset, data, length * sizeof(char_t)); bufsize = offset + length; } else { write_direct(data, length); } } void write_string(const char_t* data) { // write the part of the string that fits in the buffer size_t offset = bufsize; while (*data && offset < bufcapacity) buffer[offset++] = *data++; // write the rest if (offset < bufcapacity) { bufsize = offset; } else { // backtrack a bit if we have split the codepoint size_t length = offset - bufsize; size_t extra = length - get_valid_length(data - length, length); bufsize = offset - extra; write_direct(data - extra, strlength(data) + extra); } } void write(char_t d0) { size_t offset = bufsize; if (offset > bufcapacity - 1) offset = flush(); buffer[offset + 0] = d0; bufsize = offset + 1; } void write(char_t d0, char_t d1) { size_t offset = bufsize; if (offset > bufcapacity - 2) offset = flush(); buffer[offset + 0] = d0; buffer[offset + 1] = d1; bufsize = offset + 2; } void write(char_t d0, char_t d1, char_t d2) { size_t offset = bufsize; if (offset > bufcapacity - 3) offset = flush(); buffer[offset + 0] = d0; buffer[offset + 1] = d1; buffer[offset + 2] = d2; bufsize = offset + 3; } void write(char_t d0, char_t d1, char_t d2, char_t d3) { size_t offset = bufsize; if (offset > bufcapacity - 4) offset = flush(); buffer[offset + 0] = d0; buffer[offset + 1] = d1; buffer[offset + 2] = d2; buffer[offset + 3] = d3; bufsize = offset + 4; } void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4) { size_t offset = bufsize; if (offset > bufcapacity - 5) offset = flush(); buffer[offset + 0] = d0; buffer[offset + 1] = d1; buffer[offset + 2] = d2; buffer[offset + 3] = d3; buffer[offset + 4] = d4; bufsize = offset + 5; } void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4, char_t d5) { size_t offset = bufsize; if (offset > bufcapacity - 6) offset = flush(); buffer[offset + 0] = d0; buffer[offset + 1] = d1; buffer[offset + 2] = d2; buffer[offset + 3] = d3; buffer[offset + 4] = d4; buffer[offset + 5] = d5; bufsize = offset + 6; } // utf8 maximum expansion: x4 (-> utf32) // utf16 maximum expansion: x2 (-> utf32) // utf32 maximum expansion: x1 enum { bufcapacitybytes = #ifdef PUGIXML_MEMORY_OUTPUT_STACK PUGIXML_MEMORY_OUTPUT_STACK #else 10240 #endif , bufcapacity = bufcapacitybytes / (sizeof(char_t) + 4) }; char_t buffer[bufcapacity]; union { uint8_t data_u8[4 * bufcapacity]; uint16_t data_u16[2 * bufcapacity]; uint32_t data_u32[bufcapacity]; char_t data_char[bufcapacity]; } scratch; xml_writer& writer; size_t bufsize; xml_encoding encoding; }; PUGI__FN void text_output_escaped(xml_buffered_writer& writer, const char_t* s, chartypex_t type) { while (*s) { const char_t* prev = s; // While *s is a usual symbol PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPEX(ss, type)); writer.write_buffer(prev, static_cast<size_t>(s - prev)); switch (*s) { case 0: break; case '&': writer.write('&', 'a', 'm', 'p', ';'); ++s; break; case '<': writer.write('&', 'l', 't', ';'); ++s; break; case '>': writer.write('&', 'g', 't', ';'); ++s; break; case '"': writer.write('&', 'q', 'u', 'o', 't', ';'); ++s; break; default: // s is not a usual symbol { unsigned int ch = static_cast<unsigned int>(*s++); assert(ch < 32); writer.write('&', '#', static_cast<char_t>((ch / 10) + '0'), static_cast<char_t>((ch % 10) + '0'), ';'); } } } } PUGI__FN void text_output(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags) { if (flags & format_no_escapes) writer.write_string(s); else text_output_escaped(writer, s, type); } PUGI__FN void text_output_cdata(xml_buffered_writer& writer, const char_t* s) { do { writer.write('<', '!', '[', 'C', 'D'); writer.write('A', 'T', 'A', '['); const char_t* prev = s; // look for ]]> sequence - we can't output it as is since it terminates CDATA while (*s && !(s[0] == ']' && s[1] == ']' && s[2] == '>')) ++s; // skip ]] if we stopped at ]]>, > will go to the next CDATA section if (*s) s += 2; writer.write_buffer(prev, static_cast<size_t>(s - prev)); writer.write(']', ']', '>'); } while (*s); } PUGI__FN void text_output_indent(xml_buffered_writer& writer, const char_t* indent, size_t indent_length, unsigned int depth) { switch (indent_length) { case 1: { for (unsigned int i = 0; i < depth; ++i) writer.write(indent[0]); break; } case 2: { for (unsigned int i = 0; i < depth; ++i) writer.write(indent[0], indent[1]); break; } case 3: { for (unsigned int i = 0; i < depth; ++i) writer.write(indent[0], indent[1], indent[2]); break; } case 4: { for (unsigned int i = 0; i < depth; ++i) writer.write(indent[0], indent[1], indent[2], indent[3]); break; } default: { for (unsigned int i = 0; i < depth; ++i) writer.write_buffer(indent, indent_length); } } } PUGI__FN void node_output_comment(xml_buffered_writer& writer, const char_t* s) { writer.write('<', '!', '-', '-'); while (*s) { const char_t* prev = s; // look for -\0 or -- sequence - we can't output it since -- is illegal in comment body while (*s && !(s[0] == '-' && (s[1] == '-' || s[1] == 0))) ++s; writer.write_buffer(prev, static_cast<size_t>(s - prev)); if (*s) { assert(*s == '-'); writer.write('-', ' '); ++s; } } writer.write('-', '-', '>'); } PUGI__FN void node_output_pi_value(xml_buffered_writer& writer, const char_t* s) { while (*s) { const char_t* prev = s; // look for ?> sequence - we can't output it since ?> terminates PI while (*s && !(s[0] == '?' && s[1] == '>')) ++s; writer.write_buffer(prev, static_cast<size_t>(s - prev)); if (*s) { assert(s[0] == '?' && s[1] == '>'); writer.write('?', ' ', '>'); s += 2; } } } PUGI__FN void node_output_attributes(xml_buffered_writer& writer, xml_node_struct* node, const char_t* indent, size_t indent_length, unsigned int flags, unsigned int depth) { const char_t* default_name = PUGIXML_TEXT(":anonymous"); for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute) { if ((flags & (format_indent_attributes | format_raw)) == format_indent_attributes) { writer.write('\n'); text_output_indent(writer, indent, indent_length, depth + 1); } else { writer.write(' '); } writer.write_string(a->name ? a->name + 0 : default_name); writer.write('=', '"'); if (a->value) text_output(writer, a->value, ctx_special_attr, flags); writer.write('"'); } } PUGI__FN bool node_output_start(xml_buffered_writer& writer, xml_node_struct* node, const char_t* indent, size_t indent_length, unsigned int flags, unsigned int depth) { const char_t* default_name = PUGIXML_TEXT(":anonymous"); const char_t* name = node->name ? node->name + 0 : default_name; writer.write('<'); writer.write_string(name); if (node->first_attribute) node_output_attributes(writer, node, indent, indent_length, flags, depth); // element nodes can have value if parse_embed_pcdata was used if (!node->value) { if (!node->first_child) { if (flags & format_no_empty_element_tags) { writer.write('>', '<', '/'); writer.write_string(name); writer.write('>'); return false; } else { if ((flags & format_raw) == 0) writer.write(' '); writer.write('/', '>'); return false; } } else { writer.write('>'); return true; } } else { writer.write('>'); text_output(writer, node->value, ctx_special_pcdata, flags); if (!node->first_child) { writer.write('<', '/'); writer.write_string(name); writer.write('>'); return false; } else { return true; } } } PUGI__FN void node_output_end(xml_buffered_writer& writer, xml_node_struct* node) { const char_t* default_name = PUGIXML_TEXT(":anonymous"); const char_t* name = node->name ? node->name + 0 : default_name; writer.write('<', '/'); writer.write_string(name); writer.write('>'); } PUGI__FN void node_output_simple(xml_buffered_writer& writer, xml_node_struct* node, unsigned int flags) { const char_t* default_name = PUGIXML_TEXT(":anonymous"); switch (PUGI__NODETYPE(node)) { case node_pcdata: text_output(writer, node->value ? node->value + 0 : PUGIXML_TEXT(""), ctx_special_pcdata, flags); break; case node_cdata: text_output_cdata(writer, node->value ? node->value + 0 : PUGIXML_TEXT("")); break; case node_comment: node_output_comment(writer, node->value ? node->value + 0 : PUGIXML_TEXT("")); break; case node_pi: writer.write('<', '?'); writer.write_string(node->name ? node->name + 0 : default_name); if (node->value) { writer.write(' '); node_output_pi_value(writer, node->value); } writer.write('?', '>'); break; case node_declaration: writer.write('<', '?'); writer.write_string(node->name ? node->name + 0 : default_name); node_output_attributes(writer, node, PUGIXML_TEXT(""), 0, flags | format_raw, 0); writer.write('?', '>'); break; case node_doctype: writer.write('<', '!', 'D', 'O', 'C'); writer.write('T', 'Y', 'P', 'E'); if (node->value) { writer.write(' '); writer.write_string(node->value); } writer.write('>'); break; default: assert(false && "Invalid node type"); } } enum indent_flags_t { indent_newline = 1, indent_indent = 2 }; PUGI__FN void node_output(xml_buffered_writer& writer, xml_node_struct* root, const char_t* indent, unsigned int flags, unsigned int depth) { size_t indent_length = ((flags & (format_indent | format_indent_attributes)) && (flags & format_raw) == 0) ? strlength(indent) : 0; unsigned int indent_flags = indent_indent; xml_node_struct* node = root; do { assert(node); // begin writing current node if (PUGI__NODETYPE(node) == node_pcdata || PUGI__NODETYPE(node) == node_cdata) { node_output_simple(writer, node, flags); indent_flags = 0; } else { if ((indent_flags & indent_newline) && (flags & format_raw) == 0) writer.write('\n'); if ((indent_flags & indent_indent) && indent_length) text_output_indent(writer, indent, indent_length, depth); if (PUGI__NODETYPE(node) == node_element) { indent_flags = indent_newline | indent_indent; if (node_output_start(writer, node, indent, indent_length, flags, depth)) { // element nodes can have value if parse_embed_pcdata was used if (node->value) indent_flags = 0; node = node->first_child; depth++; continue; } } else if (PUGI__NODETYPE(node) == node_document) { indent_flags = indent_indent; if (node->first_child) { node = node->first_child; continue; } } else { node_output_simple(writer, node, flags); indent_flags = indent_newline | indent_indent; } } // continue to the next node while (node != root) { if (node->next_sibling) { node = node->next_sibling; break; } node = node->parent; // write closing node if (PUGI__NODETYPE(node) == node_element) { depth--; if ((indent_flags & indent_newline) && (flags & format_raw) == 0) writer.write('\n'); if ((indent_flags & indent_indent) && indent_length) text_output_indent(writer, indent, indent_length, depth); node_output_end(writer, node); indent_flags = indent_newline | indent_indent; } } } while (node != root); if ((indent_flags & indent_newline) && (flags & format_raw) == 0) writer.write('\n'); } PUGI__FN bool has_declaration(xml_node_struct* node) { for (xml_node_struct* child = node->first_child; child; child = child->next_sibling) { xml_node_type type = PUGI__NODETYPE(child); if (type == node_declaration) return true; if (type == node_element) return false; } return false; } PUGI__FN bool is_attribute_of(xml_attribute_struct* attr, xml_node_struct* node) { for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute) if (a == attr) return true; return false; } PUGI__FN bool allow_insert_attribute(xml_node_type parent) { return parent == node_element || parent == node_declaration; } PUGI__FN bool allow_insert_child(xml_node_type parent, xml_node_type child) { if (parent != node_document && parent != node_element) return false; if (child == node_document || child == node_null) return false; if (parent != node_document && (child == node_declaration || child == node_doctype)) return false; return true; } PUGI__FN bool allow_move(xml_node parent, xml_node child) { // check that child can be a child of parent if (!allow_insert_child(parent.type(), child.type())) return false; // check that node is not moved between documents if (parent.root() != child.root()) return false; // check that new parent is not in the child subtree xml_node cur = parent; while (cur) { if (cur == child) return false; cur = cur.parent(); } return true; } template <typename String, typename Header> PUGI__FN void node_copy_string(String& dest, Header& header, uintptr_t header_mask, char_t* source, Header& source_header, xml_allocator* alloc) { assert(!dest && (header & header_mask) == 0); if (source) { if (alloc && (source_header & header_mask) == 0) { dest = source; // since strcpy_insitu can reuse document buffer memory we need to mark both source and dest as shared header |= xml_memory_page_contents_shared_mask; source_header |= xml_memory_page_contents_shared_mask; } else strcpy_insitu(dest, header, header_mask, source, strlength(source)); } } PUGI__FN void node_copy_contents(xml_node_struct* dn, xml_node_struct* sn, xml_allocator* shared_alloc) { node_copy_string(dn->name, dn->header, xml_memory_page_name_allocated_mask, sn->name, sn->header, shared_alloc); node_copy_string(dn->value, dn->header, xml_memory_page_value_allocated_mask, sn->value, sn->header, shared_alloc); for (xml_attribute_struct* sa = sn->first_attribute; sa; sa = sa->next_attribute) { xml_attribute_struct* da = append_new_attribute(dn, get_allocator(dn)); if (da) { node_copy_string(da->name, da->header, xml_memory_page_name_allocated_mask, sa->name, sa->header, shared_alloc); node_copy_string(da->value, da->header, xml_memory_page_value_allocated_mask, sa->value, sa->header, shared_alloc); } } } PUGI__FN void node_copy_tree(xml_node_struct* dn, xml_node_struct* sn) { xml_allocator& alloc = get_allocator(dn); xml_allocator* shared_alloc = (&alloc == &get_allocator(sn)) ? &alloc : 0; node_copy_contents(dn, sn, shared_alloc); xml_node_struct* dit = dn; xml_node_struct* sit = sn->first_child; while (sit && sit != sn) { if (sit != dn) { xml_node_struct* copy = append_new_node(dit, alloc, PUGI__NODETYPE(sit)); if (copy) { node_copy_contents(copy, sit, shared_alloc); if (sit->first_child) { dit = copy; sit = sit->first_child; continue; } } } // continue to the next node do { if (sit->next_sibling) { sit = sit->next_sibling; break; } sit = sit->parent; dit = dit->parent; } while (sit != sn); } } PUGI__FN void node_copy_attribute(xml_attribute_struct* da, xml_attribute_struct* sa) { xml_allocator& alloc = get_allocator(da); xml_allocator* shared_alloc = (&alloc == &get_allocator(sa)) ? &alloc : 0; node_copy_string(da->name, da->header, xml_memory_page_name_allocated_mask, sa->name, sa->header, shared_alloc); node_copy_string(da->value, da->header, xml_memory_page_value_allocated_mask, sa->value, sa->header, shared_alloc); } inline bool is_text_node(xml_node_struct* node) { xml_node_type type = PUGI__NODETYPE(node); return type == node_pcdata || type == node_cdata; } // get value with conversion functions template <typename U> U string_to_integer(const char_t* value, U minneg, U maxpos) { U result = 0; const char_t* s = value; while (PUGI__IS_CHARTYPE(*s, ct_space)) s++; bool negative = (*s == '-'); s += (*s == '+' || *s == '-'); bool overflow = false; if (s[0] == '0' && (s[1] | ' ') == 'x') { s += 2; // since overflow detection relies on length of the sequence skip leading zeros while (*s == '0') s++; const char_t* start = s; for (;;) { if (static_cast<unsigned>(*s - '0') < 10) result = result * 16 + (*s - '0'); else if (static_cast<unsigned>((*s | ' ') - 'a') < 6) result = result * 16 + ((*s | ' ') - 'a' + 10); else break; s++; } size_t digits = static_cast<size_t>(s - start); overflow = digits > sizeof(U) * 2; } else { // since overflow detection relies on length of the sequence skip leading zeros while (*s == '0') s++; const char_t* start = s; for (;;) { if (static_cast<unsigned>(*s - '0') < 10) result = result * 10 + (*s - '0'); else break; s++; } size_t digits = static_cast<size_t>(s - start); PUGI__STATIC_ASSERT(sizeof(U) == 8 || sizeof(U) == 4 || sizeof(U) == 2); const size_t max_digits10 = sizeof(U) == 8 ? 20 : sizeof(U) == 4 ? 10 : 5; const char_t max_lead = sizeof(U) == 8 ? '1' : sizeof(U) == 4 ? '4' : '6'; const size_t high_bit = sizeof(U) * 8 - 1; overflow = digits >= max_digits10 && !(digits == max_digits10 && (*start < max_lead || (*start == max_lead && result >> high_bit))); } if (negative) { // Workaround for crayc++ CC-3059: Expected no overflow in routine. #ifdef _CRAYC return (overflow || result > minneg) ? ~minneg + 1 : ~result + 1; #else return (overflow || result > minneg) ? 0 - minneg : 0 - result; #endif } else return (overflow || result > maxpos) ? maxpos : result; } PUGI__FN int get_value_int(const char_t* value) { return string_to_integer<unsigned int>(value, 0 - static_cast<unsigned int>(INT_MIN), INT_MAX); } PUGI__FN unsigned int get_value_uint(const char_t* value) { return string_to_integer<unsigned int>(value, 0, UINT_MAX); } PUGI__FN double get_value_double(const char_t* value) { #ifdef PUGIXML_WCHAR_MODE return wcstod(value, 0); #else return strtod(value, 0); #endif } PUGI__FN float get_value_float(const char_t* value) { #ifdef PUGIXML_WCHAR_MODE return static_cast<float>(wcstod(value, 0)); #else return static_cast<float>(strtod(value, 0)); #endif } PUGI__FN bool get_value_bool(const char_t* value) { // only look at first char char_t first = *value; // 1*, t* (true), T* (True), y* (yes), Y* (YES) return (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y'); } #ifdef PUGIXML_HAS_LONG_LONG PUGI__FN long long get_value_llong(const char_t* value) { return string_to_integer<unsigned long long>(value, 0 - static_cast<unsigned long long>(LLONG_MIN), LLONG_MAX); } PUGI__FN unsigned long long get_value_ullong(const char_t* value) { return string_to_integer<unsigned long long>(value, 0, ULLONG_MAX); } #endif template <typename U> PUGI__FN char_t* integer_to_string(char_t* begin, char_t* end, U value, bool negative) { char_t* result = end - 1; U rest = negative ? 0 - value : value; do { *result-- = static_cast<char_t>('0' + (rest % 10)); rest /= 10; } while (rest); assert(result >= begin); (void)begin; *result = '-'; return result + !negative; } // set value with conversion functions template <typename String, typename Header> PUGI__FN bool set_value_ascii(String& dest, Header& header, uintptr_t header_mask, char* buf) { #ifdef PUGIXML_WCHAR_MODE char_t wbuf[128]; assert(strlen(buf) < sizeof(wbuf) / sizeof(wbuf[0])); size_t offset = 0; for (; buf[offset]; ++offset) wbuf[offset] = buf[offset]; return strcpy_insitu(dest, header, header_mask, wbuf, offset); #else return strcpy_insitu(dest, header, header_mask, buf, strlen(buf)); #endif } template <typename U, typename String, typename Header> PUGI__FN bool set_value_integer(String& dest, Header& header, uintptr_t header_mask, U value, bool negative) { char_t buf[64]; char_t* end = buf + sizeof(buf) / sizeof(buf[0]); char_t* begin = integer_to_string(buf, end, value, negative); return strcpy_insitu(dest, header, header_mask, begin, end - begin); } template <typename String, typename Header> PUGI__FN bool set_value_convert(String& dest, Header& header, uintptr_t header_mask, float value) { char buf[128]; sprintf(buf, "%.9g", value); return set_value_ascii(dest, header, header_mask, buf); } template <typename String, typename Header> PUGI__FN bool set_value_convert(String& dest, Header& header, uintptr_t header_mask, double value) { char buf[128]; sprintf(buf, "%.17g", value); return set_value_ascii(dest, header, header_mask, buf); } template <typename String, typename Header> PUGI__FN bool set_value_bool(String& dest, Header& header, uintptr_t header_mask, bool value) { return strcpy_insitu(dest, header, header_mask, value ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"), value ? 4 : 5); } PUGI__FN xml_parse_result load_buffer_impl(xml_document_struct* doc, xml_node_struct* root, void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own, char_t** out_buffer) { // check input buffer if (!contents && size) return make_parse_result(status_io_error); // get actual encoding xml_encoding buffer_encoding = impl::get_buffer_encoding(encoding, contents, size); // get private buffer char_t* buffer = 0; size_t length = 0; if (!impl::convert_buffer(buffer, length, buffer_encoding, contents, size, is_mutable)) return impl::make_parse_result(status_out_of_memory); // delete original buffer if we performed a conversion if (own && buffer != contents && contents) impl::xml_memory::deallocate(contents); // grab onto buffer if it's our buffer, user is responsible for deallocating contents himself if (own || buffer != contents) *out_buffer = buffer; // store buffer for offset_debug doc->buffer = buffer; // parse xml_parse_result res = impl::xml_parser::parse(buffer, length, doc, root, options); // remember encoding res.encoding = buffer_encoding; return res; } // we need to get length of entire file to load it in memory; the only (relatively) sane way to do it is via seek/tell trick PUGI__FN xml_parse_status get_file_size(FILE* file, size_t& out_result) { #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE) // there are 64-bit versions of fseek/ftell, let's use them typedef __int64 length_type; _fseeki64(file, 0, SEEK_END); length_type length = _ftelli64(file); _fseeki64(file, 0, SEEK_SET); #elif defined(__MINGW32__) && !defined(__NO_MINGW_LFS) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR)) // there are 64-bit versions of fseek/ftell, let's use them typedef off64_t length_type; fseeko64(file, 0, SEEK_END); length_type length = ftello64(file); fseeko64(file, 0, SEEK_SET); #else // if this is a 32-bit OS, long is enough; if this is a unix system, long is 64-bit, which is enough; otherwise we can't do anything anyway. typedef long length_type; fseek(file, 0, SEEK_END); length_type length = ftell(file); fseek(file, 0, SEEK_SET); #endif // check for I/O errors if (length < 0) return status_io_error; // check for overflow size_t result = static_cast<size_t>(length); if (static_cast<length_type>(result) != length) return status_out_of_memory; // finalize out_result = result; return status_ok; } // This function assumes that buffer has extra sizeof(char_t) writable bytes after size PUGI__FN size_t zero_terminate_buffer(void* buffer, size_t size, xml_encoding encoding) { // We only need to zero-terminate if encoding conversion does not do it for us #ifdef PUGIXML_WCHAR_MODE xml_encoding wchar_encoding = get_wchar_encoding(); if (encoding == wchar_encoding || need_endian_swap_utf(encoding, wchar_encoding)) { size_t length = size / sizeof(char_t); static_cast<char_t*>(buffer)[length] = 0; return (length + 1) * sizeof(char_t); } #else if (encoding == encoding_utf8) { static_cast<char*>(buffer)[size] = 0; return size + 1; } #endif return size; } PUGI__FN xml_parse_result load_file_impl(xml_document_struct* doc, FILE* file, unsigned int options, xml_encoding encoding, char_t** out_buffer) { if (!file) return make_parse_result(status_file_not_found); // get file size (can result in I/O errors) size_t size = 0; xml_parse_status size_status = get_file_size(file, size); if (size_status != status_ok) return make_parse_result(size_status); size_t max_suffix_size = sizeof(char_t); // allocate buffer for the whole file char* contents = static_cast<char*>(xml_memory::allocate(size + max_suffix_size)); if (!contents) return make_parse_result(status_out_of_memory); // read file in memory size_t read_size = fread(contents, 1, size, file); if (read_size != size) { xml_memory::deallocate(contents); return make_parse_result(status_io_error); } xml_encoding real_encoding = get_buffer_encoding(encoding, contents, size); return load_buffer_impl(doc, doc, contents, zero_terminate_buffer(contents, size, real_encoding), options, real_encoding, true, true, out_buffer); } PUGI__FN void close_file(FILE* file) { fclose(file); } #ifndef PUGIXML_NO_STL template <typename T> struct xml_stream_chunk { static xml_stream_chunk* create() { void* memory = xml_memory::allocate(sizeof(xml_stream_chunk)); if (!memory) return 0; return new (memory) xml_stream_chunk(); } static void destroy(xml_stream_chunk* chunk) { // free chunk chain while (chunk) { xml_stream_chunk* next_ = chunk->next; xml_memory::deallocate(chunk); chunk = next_; } } xml_stream_chunk(): next(0), size(0) { } xml_stream_chunk* next; size_t size; T data[xml_memory_page_size / sizeof(T)]; }; template <typename T> PUGI__FN xml_parse_status load_stream_data_noseek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size) { auto_deleter<xml_stream_chunk<T> > chunks(0, xml_stream_chunk<T>::destroy); // read file to a chunk list size_t total = 0; xml_stream_chunk<T>* last = 0; while (!stream.eof()) { // allocate new chunk xml_stream_chunk<T>* chunk = xml_stream_chunk<T>::create(); if (!chunk) return status_out_of_memory; // append chunk to list if (last) last = last->next = chunk; else chunks.data = last = chunk; // read data to chunk stream.read(chunk->data, static_cast<std::streamsize>(sizeof(chunk->data) / sizeof(T))); chunk->size = static_cast<size_t>(stream.gcount()) * sizeof(T); // read may set failbit | eofbit in case gcount() is less than read length, so check for other I/O errors if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error; // guard against huge files (chunk size is small enough to make this overflow check work) if (total + chunk->size < total) return status_out_of_memory; total += chunk->size; } size_t max_suffix_size = sizeof(char_t); // copy chunk list to a contiguous buffer char* buffer = static_cast<char*>(xml_memory::allocate(total + max_suffix_size)); if (!buffer) return status_out_of_memory; char* write = buffer; for (xml_stream_chunk<T>* chunk = chunks.data; chunk; chunk = chunk->next) { assert(write + chunk->size <= buffer + total); memcpy(write, chunk->data, chunk->size); write += chunk->size; } assert(write == buffer + total); // return buffer *out_buffer = buffer; *out_size = total; return status_ok; } template <typename T> PUGI__FN xml_parse_status load_stream_data_seek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size) { // get length of remaining data in stream typename std::basic_istream<T>::pos_type pos = stream.tellg(); stream.seekg(0, std::ios::end); std::streamoff length = stream.tellg() - pos; stream.seekg(pos); if (stream.fail() || pos < 0) return status_io_error; // guard against huge files size_t read_length = static_cast<size_t>(length); if (static_cast<std::streamsize>(read_length) != length || length < 0) return status_out_of_memory; size_t max_suffix_size = sizeof(char_t); // read stream data into memory (guard against stream exceptions with buffer holder) auto_deleter<void> buffer(xml_memory::allocate(read_length * sizeof(T) + max_suffix_size), xml_memory::deallocate); if (!buffer.data) return status_out_of_memory; stream.read(static_cast<T*>(buffer.data), static_cast<std::streamsize>(read_length)); // read may set failbit | eofbit in case gcount() is less than read_length (i.e. line ending conversion), so check for other I/O errors if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error; // return buffer size_t actual_length = static_cast<size_t>(stream.gcount()); assert(actual_length <= read_length); *out_buffer = buffer.release(); *out_size = actual_length * sizeof(T); return status_ok; } template <typename T> PUGI__FN xml_parse_result load_stream_impl(xml_document_struct* doc, std::basic_istream<T>& stream, unsigned int options, xml_encoding encoding, char_t** out_buffer) { void* buffer = 0; size_t size = 0; xml_parse_status status = status_ok; // if stream has an error bit set, bail out (otherwise tellg() can fail and we'll clear error bits) if (stream.fail()) return make_parse_result(status_io_error); // load stream to memory (using seek-based implementation if possible, since it's faster and takes less memory) if (stream.tellg() < 0) { stream.clear(); // clear error flags that could be set by a failing tellg status = load_stream_data_noseek(stream, &buffer, &size); } else status = load_stream_data_seek(stream, &buffer, &size); if (status != status_ok) return make_parse_result(status); xml_encoding real_encoding = get_buffer_encoding(encoding, buffer, size); return load_buffer_impl(doc, doc, buffer, zero_terminate_buffer(buffer, size, real_encoding), options, real_encoding, true, true, out_buffer); } #endif #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) || (defined(__MINGW32__) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR))) PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode) { return _wfopen(path, mode); } #else PUGI__FN char* convert_path_heap(const wchar_t* str) { assert(str); // first pass: get length in utf8 characters size_t length = strlength_wide(str); size_t size = as_utf8_begin(str, length); // allocate resulting string char* result = static_cast<char*>(xml_memory::allocate(size + 1)); if (!result) return 0; // second pass: convert to utf8 as_utf8_end(result, size, str, length); // zero-terminate result[size] = 0; return result; } PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode) { // there is no standard function to open wide paths, so our best bet is to try utf8 path char* path_utf8 = convert_path_heap(path); if (!path_utf8) return 0; // convert mode to ASCII (we mirror _wfopen interface) char mode_ascii[4] = {0}; for (size_t i = 0; mode[i]; ++i) mode_ascii[i] = static_cast<char>(mode[i]); // try to open the utf8 path FILE* result = fopen(path_utf8, mode_ascii); // free dummy buffer xml_memory::deallocate(path_utf8); return result; } #endif PUGI__FN bool save_file_impl(const xml_document& doc, FILE* file, const char_t* indent, unsigned int flags, xml_encoding encoding) { if (!file) return false; xml_writer_file writer(file); doc.save(writer, indent, flags, encoding); return ferror(file) == 0; } struct name_null_sentry { xml_node_struct* node; char_t* name; name_null_sentry(xml_node_struct* node_): node(node_), name(node_->name) { node->name = 0; } ~name_null_sentry() { node->name = name; } }; PUGI__NS_END namespace pugi { PUGI__FN xml_writer_file::xml_writer_file(void* file_): file(file_) { } PUGI__FN void xml_writer_file::write(const void* data, size_t size) { size_t result = fwrite(data, 1, size, static_cast<FILE*>(file)); (void)!result; // unfortunately we can't do proper error handling here } #ifndef PUGIXML_NO_STL PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream): narrow_stream(&stream), wide_stream(0) { } PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream): narrow_stream(0), wide_stream(&stream) { } PUGI__FN void xml_writer_stream::write(const void* data, size_t size) { if (narrow_stream) { assert(!wide_stream); narrow_stream->write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size)); } else { assert(wide_stream); assert(size % sizeof(wchar_t) == 0); wide_stream->write(reinterpret_cast<const wchar_t*>(data), static_cast<std::streamsize>(size / sizeof(wchar_t))); } } #endif PUGI__FN xml_tree_walker::xml_tree_walker(): _depth(0) { } PUGI__FN xml_tree_walker::~xml_tree_walker() { } PUGI__FN int xml_tree_walker::depth() const { return _depth; } PUGI__FN bool xml_tree_walker::begin(xml_node&) { return true; } PUGI__FN bool xml_tree_walker::end(xml_node&) { return true; } PUGI__FN xml_attribute::xml_attribute(): _attr(0) { } PUGI__FN xml_attribute::xml_attribute(xml_attribute_struct* attr): _attr(attr) { } PUGI__FN static void unspecified_bool_xml_attribute(xml_attribute***) { } PUGI__FN xml_attribute::operator xml_attribute::unspecified_bool_type() const { return _attr ? unspecified_bool_xml_attribute : 0; } PUGI__FN bool xml_attribute::operator!() const { return !_attr; } PUGI__FN bool xml_attribute::operator==(const xml_attribute& r) const { return (_attr == r._attr); } PUGI__FN bool xml_attribute::operator!=(const xml_attribute& r) const { return (_attr != r._attr); } PUGI__FN bool xml_attribute::operator<(const xml_attribute& r) const { return (_attr < r._attr); } PUGI__FN bool xml_attribute::operator>(const xml_attribute& r) const { return (_attr > r._attr); } PUGI__FN bool xml_attribute::operator<=(const xml_attribute& r) const { return (_attr <= r._attr); } PUGI__FN bool xml_attribute::operator>=(const xml_attribute& r) const { return (_attr >= r._attr); } PUGI__FN xml_attribute xml_attribute::next_attribute() const { return _attr ? xml_attribute(_attr->next_attribute) : xml_attribute(); } PUGI__FN xml_attribute xml_attribute::previous_attribute() const { return _attr && _attr->prev_attribute_c->next_attribute ? xml_attribute(_attr->prev_attribute_c) : xml_attribute(); } PUGI__FN const char_t* xml_attribute::as_string(const char_t* def) const { return (_attr && _attr->value) ? _attr->value + 0 : def; } PUGI__FN int xml_attribute::as_int(int def) const { return (_attr && _attr->value) ? impl::get_value_int(_attr->value) : def; } PUGI__FN unsigned int xml_attribute::as_uint(unsigned int def) const { return (_attr && _attr->value) ? impl::get_value_uint(_attr->value) : def; } PUGI__FN double xml_attribute::as_double(double def) const { return (_attr && _attr->value) ? impl::get_value_double(_attr->value) : def; } PUGI__FN float xml_attribute::as_float(float def) const { return (_attr && _attr->value) ? impl::get_value_float(_attr->value) : def; } PUGI__FN bool xml_attribute::as_bool(bool def) const { return (_attr && _attr->value) ? impl::get_value_bool(_attr->value) : def; } #ifdef PUGIXML_HAS_LONG_LONG PUGI__FN long long xml_attribute::as_llong(long long def) const { return (_attr && _attr->value) ? impl::get_value_llong(_attr->value) : def; } PUGI__FN unsigned long long xml_attribute::as_ullong(unsigned long long def) const { return (_attr && _attr->value) ? impl::get_value_ullong(_attr->value) : def; } #endif PUGI__FN bool xml_attribute::empty() const { return !_attr; } PUGI__FN const char_t* xml_attribute::name() const { return (_attr && _attr->name) ? _attr->name + 0 : PUGIXML_TEXT(""); } PUGI__FN const char_t* xml_attribute::value() const { return (_attr && _attr->value) ? _attr->value + 0 : PUGIXML_TEXT(""); } PUGI__FN size_t xml_attribute::hash_value() const { return static_cast<size_t>(reinterpret_cast<uintptr_t>(_attr) / sizeof(xml_attribute_struct)); } PUGI__FN xml_attribute_struct* xml_attribute::internal_object() const { return _attr; } PUGI__FN xml_attribute& xml_attribute::operator=(const char_t* rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(int rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(unsigned int rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(long rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(double rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(float rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(bool rhs) { set_value(rhs); return *this; } #ifdef PUGIXML_HAS_LONG_LONG PUGI__FN xml_attribute& xml_attribute::operator=(long long rhs) { set_value(rhs); return *this; } PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long long rhs) { set_value(rhs); return *this; } #endif PUGI__FN bool xml_attribute::set_name(const char_t* rhs) { if (!_attr) return false; return impl::strcpy_insitu(_attr->name, _attr->header, impl::xml_memory_page_name_allocated_mask, rhs, impl::strlength(rhs)); } PUGI__FN bool xml_attribute::set_value(const char_t* rhs) { if (!_attr) return false; return impl::strcpy_insitu(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs)); } PUGI__FN bool xml_attribute::set_value(int rhs) { if (!_attr) return false; return impl::set_value_integer<unsigned int>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0); } PUGI__FN bool xml_attribute::set_value(unsigned int rhs) { if (!_attr) return false; return impl::set_value_integer<unsigned int>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false); } PUGI__FN bool xml_attribute::set_value(long rhs) { if (!_attr) return false; return impl::set_value_integer<unsigned long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0); } PUGI__FN bool xml_attribute::set_value(unsigned long rhs) { if (!_attr) return false; return impl::set_value_integer<unsigned long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false); } PUGI__FN bool xml_attribute::set_value(double rhs) { if (!_attr) return false; return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs); } PUGI__FN bool xml_attribute::set_value(float rhs) { if (!_attr) return false; return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs); } PUGI__FN bool xml_attribute::set_value(bool rhs) { if (!_attr) return false; return impl::set_value_bool(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs); } #ifdef PUGIXML_HAS_LONG_LONG PUGI__FN bool xml_attribute::set_value(long long rhs) { if (!_attr) return false; return impl::set_value_integer<unsigned long long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0); } PUGI__FN bool xml_attribute::set_value(unsigned long long rhs) { if (!_attr) return false; return impl::set_value_integer<unsigned long long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false); } #endif #ifdef __BORLANDC__ PUGI__FN bool operator&&(const xml_attribute& lhs, bool rhs) { return (bool)lhs && rhs; } PUGI__FN bool operator||(const xml_attribute& lhs, bool rhs) { return (bool)lhs || rhs; } #endif PUGI__FN xml_node::xml_node(): _root(0) { } PUGI__FN xml_node::xml_node(xml_node_struct* p): _root(p) { } PUGI__FN static void unspecified_bool_xml_node(xml_node***) { } PUGI__FN xml_node::operator xml_node::unspecified_bool_type() const { return _root ? unspecified_bool_xml_node : 0; } PUGI__FN bool xml_node::operator!() const { return !_root; } PUGI__FN xml_node::iterator xml_node::begin() const { return iterator(_root ? _root->first_child + 0 : 0, _root); } PUGI__FN xml_node::iterator xml_node::end() const { return iterator(0, _root); } PUGI__FN xml_node::attribute_iterator xml_node::attributes_begin() const { return attribute_iterator(_root ? _root->first_attribute + 0 : 0, _root); } PUGI__FN xml_node::attribute_iterator xml_node::attributes_end() const { return attribute_iterator(0, _root); } PUGI__FN xml_object_range<xml_node_iterator> xml_node::children() const { return xml_object_range<xml_node_iterator>(begin(), end()); } PUGI__FN xml_object_range<xml_named_node_iterator> xml_node::children(const char_t* name_) const { return xml_object_range<xml_named_node_iterator>(xml_named_node_iterator(child(name_)._root, _root, name_), xml_named_node_iterator(0, _root, name_)); } PUGI__FN xml_object_range<xml_attribute_iterator> xml_node::attributes() const { return xml_object_range<xml_attribute_iterator>(attributes_begin(), attributes_end()); } PUGI__FN bool xml_node::operator==(const xml_node& r) const { return (_root == r._root); } PUGI__FN bool xml_node::operator!=(const xml_node& r) const { return (_root != r._root); } PUGI__FN bool xml_node::operator<(const xml_node& r) const { return (_root < r._root); } PUGI__FN bool xml_node::operator>(const xml_node& r) const { return (_root > r._root); } PUGI__FN bool xml_node::operator<=(const xml_node& r) const { return (_root <= r._root); } PUGI__FN bool xml_node::operator>=(const xml_node& r) const { return (_root >= r._root); } PUGI__FN bool xml_node::empty() const { return !_root; } PUGI__FN const char_t* xml_node::name() const { return (_root && _root->name) ? _root->name + 0 : PUGIXML_TEXT(""); } PUGI__FN xml_node_type xml_node::type() const { return _root ? PUGI__NODETYPE(_root) : node_null; } PUGI__FN const char_t* xml_node::value() const { return (_root && _root->value) ? _root->value + 0 : PUGIXML_TEXT(""); } PUGI__FN xml_node xml_node::child(const char_t* name_) const { if (!_root) return xml_node(); for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling) if (i->name && impl::strequal(name_, i->name)) return xml_node(i); return xml_node(); } PUGI__FN xml_attribute xml_node::attribute(const char_t* name_) const { if (!_root) return xml_attribute(); for (xml_attribute_struct* i = _root->first_attribute; i; i = i->next_attribute) if (i->name && impl::strequal(name_, i->name)) return xml_attribute(i); return xml_attribute(); } PUGI__FN xml_node xml_node::next_sibling(const char_t* name_) const { if (!_root) return xml_node(); for (xml_node_struct* i = _root->next_sibling; i; i = i->next_sibling) if (i->name && impl::strequal(name_, i->name)) return xml_node(i); return xml_node(); } PUGI__FN xml_node xml_node::next_sibling() const { return _root ? xml_node(_root->next_sibling) : xml_node(); } PUGI__FN xml_node xml_node::previous_sibling(const char_t* name_) const { if (!_root) return xml_node(); for (xml_node_struct* i = _root->prev_sibling_c; i->next_sibling; i = i->prev_sibling_c) if (i->name && impl::strequal(name_, i->name)) return xml_node(i); return xml_node(); } PUGI__FN xml_attribute xml_node::attribute(const char_t* name_, xml_attribute& hint_) const { xml_attribute_struct* hint = hint_._attr; // if hint is not an attribute of node, behavior is not defined assert(!hint || (_root && impl::is_attribute_of(hint, _root))); if (!_root) return xml_attribute(); // optimistically search from hint up until the end for (xml_attribute_struct* i = hint; i; i = i->next_attribute) if (i->name && impl::strequal(name_, i->name)) { // update hint to maximize efficiency of searching for consecutive attributes hint_._attr = i->next_attribute; return xml_attribute(i); } // wrap around and search from the first attribute until the hint // 'j' null pointer check is technically redundant, but it prevents a crash in case the assertion above fails for (xml_attribute_struct* j = _root->first_attribute; j && j != hint; j = j->next_attribute) if (j->name && impl::strequal(name_, j->name)) { // update hint to maximize efficiency of searching for consecutive attributes hint_._attr = j->next_attribute; return xml_attribute(j); } return xml_attribute(); } PUGI__FN xml_node xml_node::previous_sibling() const { if (!_root) return xml_node(); if (_root->prev_sibling_c->next_sibling) return xml_node(_root->prev_sibling_c); else return xml_node(); } PUGI__FN xml_node xml_node::parent() const { return _root ? xml_node(_root->parent) : xml_node(); } PUGI__FN xml_node xml_node::root() const { return _root ? xml_node(&impl::get_document(_root)) : xml_node(); } PUGI__FN xml_text xml_node::text() const { return xml_text(_root); } PUGI__FN const char_t* xml_node::child_value() const { if (!_root) return PUGIXML_TEXT(""); // element nodes can have value if parse_embed_pcdata was used if (PUGI__NODETYPE(_root) == node_element && _root->value) return _root->value; for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling) if (impl::is_text_node(i) && i->value) return i->value; return PUGIXML_TEXT(""); } PUGI__FN const char_t* xml_node::child_value(const char_t* name_) const { return child(name_).child_value(); } PUGI__FN xml_attribute xml_node::first_attribute() const { return _root ? xml_attribute(_root->first_attribute) : xml_attribute(); } PUGI__FN xml_attribute xml_node::last_attribute() const { return _root && _root->first_attribute ? xml_attribute(_root->first_attribute->prev_attribute_c) : xml_attribute(); } PUGI__FN xml_node xml_node::first_child() const { return _root ? xml_node(_root->first_child) : xml_node(); } PUGI__FN xml_node xml_node::last_child() const { return _root && _root->first_child ? xml_node(_root->first_child->prev_sibling_c) : xml_node(); } PUGI__FN bool xml_node::set_name(const char_t* rhs) { xml_node_type type_ = _root ? PUGI__NODETYPE(_root) : node_null; if (type_ != node_element && type_ != node_pi && type_ != node_declaration) return false; return impl::strcpy_insitu(_root->name, _root->header, impl::xml_memory_page_name_allocated_mask, rhs, impl::strlength(rhs)); } PUGI__FN bool xml_node::set_value(const char_t* rhs) { xml_node_type type_ = _root ? PUGI__NODETYPE(_root) : node_null; if (type_ != node_pcdata && type_ != node_cdata && type_ != node_comment && type_ != node_pi && type_ != node_doctype) return false; return impl::strcpy_insitu(_root->value, _root->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs)); } PUGI__FN xml_attribute xml_node::append_attribute(const char_t* name_) { if (!impl::allow_insert_attribute(type())) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::append_attribute(a._attr, _root); a.set_name(name_); return a; } PUGI__FN xml_attribute xml_node::prepend_attribute(const char_t* name_) { if (!impl::allow_insert_attribute(type())) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::prepend_attribute(a._attr, _root); a.set_name(name_); return a; } PUGI__FN xml_attribute xml_node::insert_attribute_after(const char_t* name_, const xml_attribute& attr) { if (!impl::allow_insert_attribute(type())) return xml_attribute(); if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::insert_attribute_after(a._attr, attr._attr, _root); a.set_name(name_); return a; } PUGI__FN xml_attribute xml_node::insert_attribute_before(const char_t* name_, const xml_attribute& attr) { if (!impl::allow_insert_attribute(type())) return xml_attribute(); if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::insert_attribute_before(a._attr, attr._attr, _root); a.set_name(name_); return a; } PUGI__FN xml_attribute xml_node::append_copy(const xml_attribute& proto) { if (!proto) return xml_attribute(); if (!impl::allow_insert_attribute(type())) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::append_attribute(a._attr, _root); impl::node_copy_attribute(a._attr, proto._attr); return a; } PUGI__FN xml_attribute xml_node::prepend_copy(const xml_attribute& proto) { if (!proto) return xml_attribute(); if (!impl::allow_insert_attribute(type())) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::prepend_attribute(a._attr, _root); impl::node_copy_attribute(a._attr, proto._attr); return a; } PUGI__FN xml_attribute xml_node::insert_copy_after(const xml_attribute& proto, const xml_attribute& attr) { if (!proto) return xml_attribute(); if (!impl::allow_insert_attribute(type())) return xml_attribute(); if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::insert_attribute_after(a._attr, attr._attr, _root); impl::node_copy_attribute(a._attr, proto._attr); return a; } PUGI__FN xml_attribute xml_node::insert_copy_before(const xml_attribute& proto, const xml_attribute& attr) { if (!proto) return xml_attribute(); if (!impl::allow_insert_attribute(type())) return xml_attribute(); if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_attribute(); xml_attribute a(impl::allocate_attribute(alloc)); if (!a) return xml_attribute(); impl::insert_attribute_before(a._attr, attr._attr, _root); impl::node_copy_attribute(a._attr, proto._attr); return a; } PUGI__FN xml_node xml_node::append_child(xml_node_type type_) { if (!impl::allow_insert_child(type(), type_)) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::append_node(n._root, _root); if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml")); return n; } PUGI__FN xml_node xml_node::prepend_child(xml_node_type type_) { if (!impl::allow_insert_child(type(), type_)) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::prepend_node(n._root, _root); if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml")); return n; } PUGI__FN xml_node xml_node::insert_child_before(xml_node_type type_, const xml_node& node) { if (!impl::allow_insert_child(type(), type_)) return xml_node(); if (!node._root || node._root->parent != _root) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::insert_node_before(n._root, node._root); if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml")); return n; } PUGI__FN xml_node xml_node::insert_child_after(xml_node_type type_, const xml_node& node) { if (!impl::allow_insert_child(type(), type_)) return xml_node(); if (!node._root || node._root->parent != _root) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::insert_node_after(n._root, node._root); if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml")); return n; } PUGI__FN xml_node xml_node::append_child(const char_t* name_) { xml_node result = append_child(node_element); result.set_name(name_); return result; } PUGI__FN xml_node xml_node::prepend_child(const char_t* name_) { xml_node result = prepend_child(node_element); result.set_name(name_); return result; } PUGI__FN xml_node xml_node::insert_child_after(const char_t* name_, const xml_node& node) { xml_node result = insert_child_after(node_element, node); result.set_name(name_); return result; } PUGI__FN xml_node xml_node::insert_child_before(const char_t* name_, const xml_node& node) { xml_node result = insert_child_before(node_element, node); result.set_name(name_); return result; } PUGI__FN xml_node xml_node::append_copy(const xml_node& proto) { xml_node_type type_ = proto.type(); if (!impl::allow_insert_child(type(), type_)) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::append_node(n._root, _root); impl::node_copy_tree(n._root, proto._root); return n; } PUGI__FN xml_node xml_node::prepend_copy(const xml_node& proto) { xml_node_type type_ = proto.type(); if (!impl::allow_insert_child(type(), type_)) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::prepend_node(n._root, _root); impl::node_copy_tree(n._root, proto._root); return n; } PUGI__FN xml_node xml_node::insert_copy_after(const xml_node& proto, const xml_node& node) { xml_node_type type_ = proto.type(); if (!impl::allow_insert_child(type(), type_)) return xml_node(); if (!node._root || node._root->parent != _root) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::insert_node_after(n._root, node._root); impl::node_copy_tree(n._root, proto._root); return n; } PUGI__FN xml_node xml_node::insert_copy_before(const xml_node& proto, const xml_node& node) { xml_node_type type_ = proto.type(); if (!impl::allow_insert_child(type(), type_)) return xml_node(); if (!node._root || node._root->parent != _root) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); xml_node n(impl::allocate_node(alloc, type_)); if (!n) return xml_node(); impl::insert_node_before(n._root, node._root); impl::node_copy_tree(n._root, proto._root); return n; } PUGI__FN xml_node xml_node::append_move(const xml_node& moved) { if (!impl::allow_move(*this, moved)) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask; impl::remove_node(moved._root); impl::append_node(moved._root, _root); return moved; } PUGI__FN xml_node xml_node::prepend_move(const xml_node& moved) { if (!impl::allow_move(*this, moved)) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask; impl::remove_node(moved._root); impl::prepend_node(moved._root, _root); return moved; } PUGI__FN xml_node xml_node::insert_move_after(const xml_node& moved, const xml_node& node) { if (!impl::allow_move(*this, moved)) return xml_node(); if (!node._root || node._root->parent != _root) return xml_node(); if (moved._root == node._root) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask; impl::remove_node(moved._root); impl::insert_node_after(moved._root, node._root); return moved; } PUGI__FN xml_node xml_node::insert_move_before(const xml_node& moved, const xml_node& node) { if (!impl::allow_move(*this, moved)) return xml_node(); if (!node._root || node._root->parent != _root) return xml_node(); if (moved._root == node._root) return xml_node(); impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return xml_node(); // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask; impl::remove_node(moved._root); impl::insert_node_before(moved._root, node._root); return moved; } PUGI__FN bool xml_node::remove_attribute(const char_t* name_) { return remove_attribute(attribute(name_)); } PUGI__FN bool xml_node::remove_attribute(const xml_attribute& a) { if (!_root || !a._attr) return false; if (!impl::is_attribute_of(a._attr, _root)) return false; impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return false; impl::remove_attribute(a._attr, _root); impl::destroy_attribute(a._attr, alloc); return true; } PUGI__FN bool xml_node::remove_child(const char_t* name_) { return remove_child(child(name_)); } PUGI__FN bool xml_node::remove_child(const xml_node& n) { if (!_root || !n._root || n._root->parent != _root) return false; impl::xml_allocator& alloc = impl::get_allocator(_root); if (!alloc.reserve()) return false; impl::remove_node(n._root); impl::destroy_node(n._root, alloc); return true; } PUGI__FN xml_parse_result xml_node::append_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding) { // append_buffer is only valid for elements/documents if (!impl::allow_insert_child(type(), node_element)) return impl::make_parse_result(status_append_invalid_root); // get document node impl::xml_document_struct* doc = &impl::get_document(_root); // disable document_buffer_order optimization since in a document with multiple buffers comparing buffer pointers does not make sense doc->header |= impl::xml_memory_page_contents_shared_mask; // get extra buffer element (we'll store the document fragment buffer there so that we can deallocate it later) impl::xml_memory_page* page = 0; impl::xml_extra_buffer* extra = static_cast<impl::xml_extra_buffer*>(doc->allocate_memory(sizeof(impl::xml_extra_buffer), page)); (void)page; if (!extra) return impl::make_parse_result(status_out_of_memory); // add extra buffer to the list extra->buffer = 0; extra->next = doc->extra_buffers; doc->extra_buffers = extra; // name of the root has to be NULL before parsing - otherwise closing node mismatches will not be detected at the top level impl::name_null_sentry sentry(_root); return impl::load_buffer_impl(doc, _root, const_cast<void*>(contents), size, options, encoding, false, false, &extra->buffer); } PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* name_, const char_t* attr_name, const char_t* attr_value) const { if (!_root) return xml_node(); for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling) if (i->name && impl::strequal(name_, i->name)) { for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute) if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value + 0 : PUGIXML_TEXT(""))) return xml_node(i); } return xml_node(); } PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const { if (!_root) return xml_node(); for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling) for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute) if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value + 0 : PUGIXML_TEXT(""))) return xml_node(i); return xml_node(); } #ifndef PUGIXML_NO_STL PUGI__FN string_t xml_node::path(char_t delimiter) const { if (!_root) return string_t(); size_t offset = 0; for (xml_node_struct* i = _root; i; i = i->parent) { offset += (i != _root); offset += i->name ? impl::strlength(i->name) : 0; } string_t result; result.resize(offset); for (xml_node_struct* j = _root; j; j = j->parent) { if (j != _root) result[--offset] = delimiter; if (j->name && *j->name) { size_t length = impl::strlength(j->name); offset -= length; memcpy(&result[offset], j->name, length * sizeof(char_t)); } } assert(offset == 0); return result; } #endif PUGI__FN xml_node xml_node::first_element_by_path(const char_t* path_, char_t delimiter) const { xml_node found = *this; // Current search context. if (!_root || !path_ || !path_[0]) return found; if (path_[0] == delimiter) { // Absolute path; e.g. '/foo/bar' found = found.root(); ++path_; } const char_t* path_segment = path_; while (*path_segment == delimiter) ++path_segment; const char_t* path_segment_end = path_segment; while (*path_segment_end && *path_segment_end != delimiter) ++path_segment_end; if (path_segment == path_segment_end) return found; const char_t* next_segment = path_segment_end; while (*next_segment == delimiter) ++next_segment; if (*path_segment == '.' && path_segment + 1 == path_segment_end) return found.first_element_by_path(next_segment, delimiter); else if (*path_segment == '.' && *(path_segment+1) == '.' && path_segment + 2 == path_segment_end) return found.parent().first_element_by_path(next_segment, delimiter); else { for (xml_node_struct* j = found._root->first_child; j; j = j->next_sibling) { if (j->name && impl::strequalrange(j->name, path_segment, static_cast<size_t>(path_segment_end - path_segment))) { xml_node subsearch = xml_node(j).first_element_by_path(next_segment, delimiter); if (subsearch) return subsearch; } } return xml_node(); } } PUGI__FN bool xml_node::traverse(xml_tree_walker& walker) { walker._depth = -1; xml_node arg_begin = *this; if (!walker.begin(arg_begin)) return false; xml_node cur = first_child(); if (cur) { ++walker._depth; do { xml_node arg_for_each = cur; if (!walker.for_each(arg_for_each)) return false; if (cur.first_child()) { ++walker._depth; cur = cur.first_child(); } else if (cur.next_sibling()) cur = cur.next_sibling(); else { // Borland C++ workaround while (!cur.next_sibling() && cur != *this && !cur.parent().empty()) { --walker._depth; cur = cur.parent(); } if (cur != *this) cur = cur.next_sibling(); } } while (cur && cur != *this); } assert(walker._depth == -1); xml_node arg_end = *this; return walker.end(arg_end); } PUGI__FN size_t xml_node::hash_value() const { return static_cast<size_t>(reinterpret_cast<uintptr_t>(_root) / sizeof(xml_node_struct)); } PUGI__FN xml_node_struct* xml_node::internal_object() const { return _root; } PUGI__FN void xml_node::print(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const { if (!_root) return; impl::xml_buffered_writer buffered_writer(writer, encoding); impl::node_output(buffered_writer, _root, indent, flags, depth); buffered_writer.flush(); } #ifndef PUGIXML_NO_STL PUGI__FN void xml_node::print(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const { xml_writer_stream writer(stream); print(writer, indent, flags, encoding, depth); } PUGI__FN void xml_node::print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags, unsigned int depth) const { xml_writer_stream writer(stream); print(writer, indent, flags, encoding_wchar, depth); } #endif PUGI__FN ptrdiff_t xml_node::offset_debug() const { if (!_root) return -1; impl::xml_document_struct& doc = impl::get_document(_root); // we can determine the offset reliably only if there is exactly once parse buffer if (!doc.buffer || doc.extra_buffers) return -1; switch (type()) { case node_document: return 0; case node_element: case node_declaration: case node_pi: return _root->name && (_root->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0 ? _root->name - doc.buffer : -1; case node_pcdata: case node_cdata: case node_comment: case node_doctype: return _root->value && (_root->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0 ? _root->value - doc.buffer : -1; default: return -1; } } #ifdef __BORLANDC__ PUGI__FN bool operator&&(const xml_node& lhs, bool rhs) { return (bool)lhs && rhs; } PUGI__FN bool operator||(const xml_node& lhs, bool rhs) { return (bool)lhs || rhs; } #endif PUGI__FN xml_text::xml_text(xml_node_struct* root): _root(root) { } PUGI__FN xml_node_struct* xml_text::_data() const { if (!_root || impl::is_text_node(_root)) return _root; // element nodes can have value if parse_embed_pcdata was used if (PUGI__NODETYPE(_root) == node_element && _root->value) return _root; for (xml_node_struct* node = _root->first_child; node; node = node->next_sibling) if (impl::is_text_node(node)) return node; return 0; } PUGI__FN xml_node_struct* xml_text::_data_new() { xml_node_struct* d = _data(); if (d) return d; return xml_node(_root).append_child(node_pcdata).internal_object(); } PUGI__FN xml_text::xml_text(): _root(0) { } PUGI__FN static void unspecified_bool_xml_text(xml_text***) { } PUGI__FN xml_text::operator xml_text::unspecified_bool_type() const { return _data() ? unspecified_bool_xml_text : 0; } PUGI__FN bool xml_text::operator!() const { return !_data(); } PUGI__FN bool xml_text::empty() const { return _data() == 0; } PUGI__FN const char_t* xml_text::get() const { xml_node_struct* d = _data(); return (d && d->value) ? d->value + 0 : PUGIXML_TEXT(""); } PUGI__FN const char_t* xml_text::as_string(const char_t* def) const { xml_node_struct* d = _data(); return (d && d->value) ? d->value + 0 : def; } PUGI__FN int xml_text::as_int(int def) const { xml_node_struct* d = _data(); return (d && d->value) ? impl::get_value_int(d->value) : def; } PUGI__FN unsigned int xml_text::as_uint(unsigned int def) const { xml_node_struct* d = _data(); return (d && d->value) ? impl::get_value_uint(d->value) : def; } PUGI__FN double xml_text::as_double(double def) const { xml_node_struct* d = _data(); return (d && d->value) ? impl::get_value_double(d->value) : def; } PUGI__FN float xml_text::as_float(float def) const { xml_node_struct* d = _data(); return (d && d->value) ? impl::get_value_float(d->value) : def; } PUGI__FN bool xml_text::as_bool(bool def) const { xml_node_struct* d = _data(); return (d && d->value) ? impl::get_value_bool(d->value) : def; } #ifdef PUGIXML_HAS_LONG_LONG PUGI__FN long long xml_text::as_llong(long long def) const { xml_node_struct* d = _data(); return (d && d->value) ? impl::get_value_llong(d->value) : def; } PUGI__FN unsigned long long xml_text::as_ullong(unsigned long long def) const { xml_node_struct* d = _data(); return (d && d->value) ? impl::get_value_ullong(d->value) : def; } #endif PUGI__FN bool xml_text::set(const char_t* rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::strcpy_insitu(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs)) : false; } PUGI__FN bool xml_text::set(int rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_integer<unsigned int>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false; } PUGI__FN bool xml_text::set(unsigned int rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_integer<unsigned int>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false; } PUGI__FN bool xml_text::set(long rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_integer<unsigned long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false; } PUGI__FN bool xml_text::set(unsigned long rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_integer<unsigned long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false; } PUGI__FN bool xml_text::set(float rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false; } PUGI__FN bool xml_text::set(double rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false; } PUGI__FN bool xml_text::set(bool rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_bool(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false; } #ifdef PUGIXML_HAS_LONG_LONG PUGI__FN bool xml_text::set(long long rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_integer<unsigned long long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false; } PUGI__FN bool xml_text::set(unsigned long long rhs) { xml_node_struct* dn = _data_new(); return dn ? impl::set_value_integer<unsigned long long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false; } #endif PUGI__FN xml_text& xml_text::operator=(const char_t* rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(int rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(unsigned int rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(long rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(unsigned long rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(double rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(float rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(bool rhs) { set(rhs); return *this; } #ifdef PUGIXML_HAS_LONG_LONG PUGI__FN xml_text& xml_text::operator=(long long rhs) { set(rhs); return *this; } PUGI__FN xml_text& xml_text::operator=(unsigned long long rhs) { set(rhs); return *this; } #endif PUGI__FN xml_node xml_text::data() const { return xml_node(_data()); } #ifdef __BORLANDC__ PUGI__FN bool operator&&(const xml_text& lhs, bool rhs) { return (bool)lhs && rhs; } PUGI__FN bool operator||(const xml_text& lhs, bool rhs) { return (bool)lhs || rhs; } #endif PUGI__FN xml_node_iterator::xml_node_iterator() { } PUGI__FN xml_node_iterator::xml_node_iterator(const xml_node& node): _wrap(node), _parent(node.parent()) { } PUGI__FN xml_node_iterator::xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent) { } PUGI__FN bool xml_node_iterator::operator==(const xml_node_iterator& rhs) const { return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root; } PUGI__FN bool xml_node_iterator::operator!=(const xml_node_iterator& rhs) const { return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root; } PUGI__FN xml_node& xml_node_iterator::operator*() const { assert(_wrap._root); return _wrap; } PUGI__FN xml_node* xml_node_iterator::operator->() const { assert(_wrap._root); return const_cast<xml_node*>(&_wrap); // BCC5 workaround } PUGI__FN const xml_node_iterator& xml_node_iterator::operator++() { assert(_wrap._root); _wrap._root = _wrap._root->next_sibling; return *this; } PUGI__FN xml_node_iterator xml_node_iterator::operator++(int) { xml_node_iterator temp = *this; ++*this; return temp; } PUGI__FN const xml_node_iterator& xml_node_iterator::operator--() { _wrap = _wrap._root ? _wrap.previous_sibling() : _parent.last_child(); return *this; } PUGI__FN xml_node_iterator xml_node_iterator::operator--(int) { xml_node_iterator temp = *this; --*this; return temp; } PUGI__FN xml_attribute_iterator::xml_attribute_iterator() { } PUGI__FN xml_attribute_iterator::xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent): _wrap(attr), _parent(parent) { } PUGI__FN xml_attribute_iterator::xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent) { } PUGI__FN bool xml_attribute_iterator::operator==(const xml_attribute_iterator& rhs) const { return _wrap._attr == rhs._wrap._attr && _parent._root == rhs._parent._root; } PUGI__FN bool xml_attribute_iterator::operator!=(const xml_attribute_iterator& rhs) const { return _wrap._attr != rhs._wrap._attr || _parent._root != rhs._parent._root; } PUGI__FN xml_attribute& xml_attribute_iterator::operator*() const { assert(_wrap._attr); return _wrap; } PUGI__FN xml_attribute* xml_attribute_iterator::operator->() const { assert(_wrap._attr); return const_cast<xml_attribute*>(&_wrap); // BCC5 workaround } PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator++() { assert(_wrap._attr); _wrap._attr = _wrap._attr->next_attribute; return *this; } PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator++(int) { xml_attribute_iterator temp = *this; ++*this; return temp; } PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator--() { _wrap = _wrap._attr ? _wrap.previous_attribute() : _parent.last_attribute(); return *this; } PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator--(int) { xml_attribute_iterator temp = *this; --*this; return temp; } PUGI__FN xml_named_node_iterator::xml_named_node_iterator(): _name(0) { } PUGI__FN xml_named_node_iterator::xml_named_node_iterator(const xml_node& node, const char_t* name): _wrap(node), _parent(node.parent()), _name(name) { } PUGI__FN xml_named_node_iterator::xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name): _wrap(ref), _parent(parent), _name(name) { } PUGI__FN bool xml_named_node_iterator::operator==(const xml_named_node_iterator& rhs) const { return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root; } PUGI__FN bool xml_named_node_iterator::operator!=(const xml_named_node_iterator& rhs) const { return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root; } PUGI__FN xml_node& xml_named_node_iterator::operator*() const { assert(_wrap._root); return _wrap; } PUGI__FN xml_node* xml_named_node_iterator::operator->() const { assert(_wrap._root); return const_cast<xml_node*>(&_wrap); // BCC5 workaround } PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator++() { assert(_wrap._root); _wrap = _wrap.next_sibling(_name); return *this; } PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator++(int) { xml_named_node_iterator temp = *this; ++*this; return temp; } PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator--() { if (_wrap._root) _wrap = _wrap.previous_sibling(_name); else { _wrap = _parent.last_child(); if (!impl::strequal(_wrap.name(), _name)) _wrap = _wrap.previous_sibling(_name); } return *this; } PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator--(int) { xml_named_node_iterator temp = *this; --*this; return temp; } PUGI__FN xml_parse_result::xml_parse_result(): status(status_internal_error), offset(0), encoding(encoding_auto) { } PUGI__FN xml_parse_result::operator bool() const { return status == status_ok; } PUGI__FN const char* xml_parse_result::description() const { switch (status) { case status_ok: return "No error"; case status_file_not_found: return "File was not found"; case status_io_error: return "Error reading from file/stream"; case status_out_of_memory: return "Could not allocate memory"; case status_internal_error: return "Internal error occurred"; case status_unrecognized_tag: return "Could not determine tag type"; case status_bad_pi: return "Error parsing document declaration/processing instruction"; case status_bad_comment: return "Error parsing comment"; case status_bad_cdata: return "Error parsing CDATA section"; case status_bad_doctype: return "Error parsing document type declaration"; case status_bad_pcdata: return "Error parsing PCDATA section"; case status_bad_start_element: return "Error parsing start element tag"; case status_bad_attribute: return "Error parsing element attribute"; case status_bad_end_element: return "Error parsing end element tag"; case status_end_element_mismatch: return "Start-end tags mismatch"; case status_append_invalid_root: return "Unable to append nodes: root is not an element or document"; case status_no_document_element: return "No document element found"; default: return "Unknown error"; } } PUGI__FN xml_document::xml_document(): _buffer(0) { _create(); } PUGI__FN xml_document::~xml_document() { _destroy(); } PUGI__FN void xml_document::reset() { _destroy(); _create(); } PUGI__FN void xml_document::reset(const xml_document& proto) { reset(); for (xml_node cur = proto.first_child(); cur; cur = cur.next_sibling()) append_copy(cur); } PUGI__FN void xml_document::_create() { assert(!_root); #ifdef PUGIXML_COMPACT const size_t page_offset = sizeof(uint32_t); #else const size_t page_offset = 0; #endif // initialize sentinel page PUGI__STATIC_ASSERT(sizeof(impl::xml_memory_page) + sizeof(impl::xml_document_struct) + page_offset <= sizeof(_memory)); // prepare page structure impl::xml_memory_page* page = impl::xml_memory_page::construct(_memory); assert(page); page->busy_size = impl::xml_memory_page_size; // setup first page marker #ifdef PUGIXML_COMPACT // round-trip through void* to avoid 'cast increases required alignment of target type' warning page->compact_page_marker = reinterpret_cast<uint32_t*>(static_cast<void*>(reinterpret_cast<char*>(page) + sizeof(impl::xml_memory_page))); *page->compact_page_marker = sizeof(impl::xml_memory_page); #endif // allocate new root _root = new (reinterpret_cast<char*>(page) + sizeof(impl::xml_memory_page) + page_offset) impl::xml_document_struct(page); _root->prev_sibling_c = _root; // setup sentinel page page->allocator = static_cast<impl::xml_document_struct*>(_root); // setup hash table pointer in allocator #ifdef PUGIXML_COMPACT page->allocator->_hash = &static_cast<impl::xml_document_struct*>(_root)->hash; #endif // verify the document allocation assert(reinterpret_cast<char*>(_root) + sizeof(impl::xml_document_struct) <= _memory + sizeof(_memory)); } PUGI__FN void xml_document::_destroy() { assert(_root); // destroy static storage if (_buffer) { impl::xml_memory::deallocate(_buffer); _buffer = 0; } // destroy extra buffers (note: no need to destroy linked list nodes, they're allocated using document allocator) for (impl::xml_extra_buffer* extra = static_cast<impl::xml_document_struct*>(_root)->extra_buffers; extra; extra = extra->next) { if (extra->buffer) impl::xml_memory::deallocate(extra->buffer); } // destroy dynamic storage, leave sentinel page (it's in static memory) impl::xml_memory_page* root_page = PUGI__GETPAGE(_root); assert(root_page && !root_page->prev); assert(reinterpret_cast<char*>(root_page) >= _memory && reinterpret_cast<char*>(root_page) < _memory + sizeof(_memory)); for (impl::xml_memory_page* page = root_page->next; page; ) { impl::xml_memory_page* next = page->next; impl::xml_allocator::deallocate_page(page); page = next; } #ifdef PUGIXML_COMPACT // destroy hash table static_cast<impl::xml_document_struct*>(_root)->hash.clear(); #endif _root = 0; } #ifndef PUGIXML_NO_STL PUGI__FN xml_parse_result xml_document::load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options, xml_encoding encoding) { reset(); return impl::load_stream_impl(static_cast<impl::xml_document_struct*>(_root), stream, options, encoding, &_buffer); } PUGI__FN xml_parse_result xml_document::load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options) { reset(); return impl::load_stream_impl(static_cast<impl::xml_document_struct*>(_root), stream, options, encoding_wchar, &_buffer); } #endif PUGI__FN xml_parse_result xml_document::load_string(const char_t* contents, unsigned int options) { // Force native encoding (skip autodetection) #ifdef PUGIXML_WCHAR_MODE xml_encoding encoding = encoding_wchar; #else xml_encoding encoding = encoding_utf8; #endif return load_buffer(contents, impl::strlength(contents) * sizeof(char_t), options, encoding); } PUGI__FN xml_parse_result xml_document::load(const char_t* contents, unsigned int options) { return load_string(contents, options); } PUGI__FN xml_parse_result xml_document::load_file(const char* path_, unsigned int options, xml_encoding encoding) { reset(); using impl::auto_deleter; // MSVC7 workaround auto_deleter<FILE> file(fopen(path_, "rb"), impl::close_file); return impl::load_file_impl(static_cast<impl::xml_document_struct*>(_root), file.data, options, encoding, &_buffer); } PUGI__FN xml_parse_result xml_document::load_file(const wchar_t* path_, unsigned int options, xml_encoding encoding) { reset(); using impl::auto_deleter; // MSVC7 workaround auto_deleter<FILE> file(impl::open_file_wide(path_, L"rb"), impl::close_file); return impl::load_file_impl(static_cast<impl::xml_document_struct*>(_root), file.data, options, encoding, &_buffer); } PUGI__FN xml_parse_result xml_document::load_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding) { reset(); return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, const_cast<void*>(contents), size, options, encoding, false, false, &_buffer); } PUGI__FN xml_parse_result xml_document::load_buffer_inplace(void* contents, size_t size, unsigned int options, xml_encoding encoding) { reset(); return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, false, &_buffer); } PUGI__FN xml_parse_result xml_document::load_buffer_inplace_own(void* contents, size_t size, unsigned int options, xml_encoding encoding) { reset(); return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, true, &_buffer); } PUGI__FN void xml_document::save(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding) const { impl::xml_buffered_writer buffered_writer(writer, encoding); if ((flags & format_write_bom) && encoding != encoding_latin1) { // BOM always represents the codepoint U+FEFF, so just write it in native encoding #ifdef PUGIXML_WCHAR_MODE unsigned int bom = 0xfeff; buffered_writer.write(static_cast<wchar_t>(bom)); #else buffered_writer.write('\xef', '\xbb', '\xbf'); #endif } if (!(flags & format_no_declaration) && !impl::has_declaration(_root)) { buffered_writer.write_string(PUGIXML_TEXT("<?xml version=\"1.0\"")); if (encoding == encoding_latin1) buffered_writer.write_string(PUGIXML_TEXT(" encoding=\"ISO-8859-1\"")); buffered_writer.write('?', '>'); if (!(flags & format_raw)) buffered_writer.write('\n'); } impl::node_output(buffered_writer, _root, indent, flags, 0); buffered_writer.flush(); } #ifndef PUGIXML_NO_STL PUGI__FN void xml_document::save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding) const { xml_writer_stream writer(stream); save(writer, indent, flags, encoding); } PUGI__FN void xml_document::save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags) const { xml_writer_stream writer(stream); save(writer, indent, flags, encoding_wchar); } #endif PUGI__FN bool xml_document::save_file(const char* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const { using impl::auto_deleter; // MSVC7 workaround auto_deleter<FILE> file(fopen(path_, (flags & format_save_file_text) ? "w" : "wb"), impl::close_file); return impl::save_file_impl(*this, file.data, indent, flags, encoding); } PUGI__FN bool xml_document::save_file(const wchar_t* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const { using impl::auto_deleter; // MSVC7 workaround auto_deleter<FILE> file(impl::open_file_wide(path_, (flags & format_save_file_text) ? L"w" : L"wb"), impl::close_file); return impl::save_file_impl(*this, file.data, indent, flags, encoding); } PUGI__FN xml_node xml_document::document_element() const { assert(_root); for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling) if (PUGI__NODETYPE(i) == node_element) return xml_node(i); return xml_node(); } #ifndef PUGIXML_NO_STL PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const wchar_t* str) { assert(str); return impl::as_utf8_impl(str, impl::strlength_wide(str)); } PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t>& str) { return impl::as_utf8_impl(str.c_str(), str.size()); } PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const char* str) { assert(str); return impl::as_wide_impl(str, strlen(str)); } PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const std::string& str) { return impl::as_wide_impl(str.c_str(), str.size()); } #endif PUGI__FN void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate) { impl::xml_memory::allocate = allocate; impl::xml_memory::deallocate = deallocate; } PUGI__FN allocation_function PUGIXML_FUNCTION get_memory_allocation_function() { return impl::xml_memory::allocate; } PUGI__FN deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function() { return impl::xml_memory::deallocate; } } #if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC)) namespace std { // Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier) PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_node_iterator&) { return std::bidirectional_iterator_tag(); } PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_attribute_iterator&) { return std::bidirectional_iterator_tag(); } PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_named_node_iterator&) { return std::bidirectional_iterator_tag(); } } #endif #if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC) namespace std { // Workarounds for (non-standard) iterator category detection PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_node_iterator&) { return std::bidirectional_iterator_tag(); } PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_attribute_iterator&) { return std::bidirectional_iterator_tag(); } PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_named_node_iterator&) { return std::bidirectional_iterator_tag(); } } #endif #ifndef PUGIXML_NO_XPATH // STL replacements PUGI__NS_BEGIN struct equal_to { template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs == rhs; } }; struct not_equal_to { template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs != rhs; } }; struct less { template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs < rhs; } }; struct less_equal { template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs <= rhs; } }; template <typename T> void swap(T& lhs, T& rhs) { T temp = lhs; lhs = rhs; rhs = temp; } template <typename I, typename Pred> I min_element(I begin, I end, const Pred& pred) { I result = begin; for (I it = begin + 1; it != end; ++it) if (pred(*it, *result)) result = it; return result; } template <typename I> void reverse(I begin, I end) { while (end - begin > 1) swap(*begin++, *--end); } template <typename I> I unique(I begin, I end) { // fast skip head while (end - begin > 1 && *begin != *(begin + 1)) begin++; if (begin == end) return begin; // last written element I write = begin++; // merge unique elements while (begin != end) { if (*begin != *write) *++write = *begin++; else begin++; } // past-the-end (write points to live element) return write + 1; } template <typename I> void copy_backwards(I begin, I end, I target) { while (begin != end) *--target = *--end; } template <typename I, typename Pred, typename T> void insertion_sort(I begin, I end, const Pred& pred, T*) { assert(begin != end); for (I it = begin + 1; it != end; ++it) { T val = *it; if (pred(val, *begin)) { // move to front copy_backwards(begin, it, it + 1); *begin = val; } else { I hole = it; // move hole backwards while (pred(val, *(hole - 1))) { *hole = *(hole - 1); hole--; } // fill hole with element *hole = val; } } } // std variant for elements with == template <typename I, typename Pred> void partition(I begin, I middle, I end, const Pred& pred, I* out_eqbeg, I* out_eqend) { I eqbeg = middle, eqend = middle + 1; // expand equal range while (eqbeg != begin && *(eqbeg - 1) == *eqbeg) --eqbeg; while (eqend != end && *eqend == *eqbeg) ++eqend; // process outer elements I ltend = eqbeg, gtbeg = eqend; for (;;) { // find the element from the right side that belongs to the left one for (; gtbeg != end; ++gtbeg) if (!pred(*eqbeg, *gtbeg)) { if (*gtbeg == *eqbeg) swap(*gtbeg, *eqend++); else break; } // find the element from the left side that belongs to the right one for (; ltend != begin; --ltend) if (!pred(*(ltend - 1), *eqbeg)) { if (*eqbeg == *(ltend - 1)) swap(*(ltend - 1), *--eqbeg); else break; } // scanned all elements if (gtbeg == end && ltend == begin) { *out_eqbeg = eqbeg; *out_eqend = eqend; return; } // make room for elements by moving equal area if (gtbeg == end) { if (--ltend != --eqbeg) swap(*ltend, *eqbeg); swap(*eqbeg, *--eqend); } else if (ltend == begin) { if (eqend != gtbeg) swap(*eqbeg, *eqend); ++eqend; swap(*gtbeg++, *eqbeg++); } else swap(*gtbeg++, *--ltend); } } template <typename I, typename Pred> void median3(I first, I middle, I last, const Pred& pred) { if (pred(*middle, *first)) swap(*middle, *first); if (pred(*last, *middle)) swap(*last, *middle); if (pred(*middle, *first)) swap(*middle, *first); } template <typename I, typename Pred> void median(I first, I middle, I last, const Pred& pred) { if (last - first <= 40) { // median of three for small chunks median3(first, middle, last, pred); } else { // median of nine size_t step = (last - first + 1) / 8; median3(first, first + step, first + 2 * step, pred); median3(middle - step, middle, middle + step, pred); median3(last - 2 * step, last - step, last, pred); median3(first + step, middle, last - step, pred); } } template <typename I, typename Pred> void sort(I begin, I end, const Pred& pred) { // sort large chunks while (end - begin > 32) { // find median element I middle = begin + (end - begin) / 2; median(begin, middle, end - 1, pred); // partition in three chunks (< = >) I eqbeg, eqend; partition(begin, middle, end, pred, &eqbeg, &eqend); // loop on larger half if (eqbeg - begin > end - eqend) { sort(eqend, end, pred); end = eqbeg; } else { sort(begin, eqbeg, pred); begin = eqend; } } // insertion sort small chunk if (begin != end) insertion_sort(begin, end, pred, &*begin); } PUGI__NS_END // Allocator used for AST and evaluation stacks PUGI__NS_BEGIN static const size_t xpath_memory_page_size = #ifdef PUGIXML_MEMORY_XPATH_PAGE_SIZE PUGIXML_MEMORY_XPATH_PAGE_SIZE #else 4096 #endif ; static const uintptr_t xpath_memory_block_alignment = sizeof(double) > sizeof(void*) ? sizeof(double) : sizeof(void*); struct xpath_memory_block { xpath_memory_block* next; size_t capacity; union { char data[xpath_memory_page_size]; double alignment; }; }; class xpath_allocator { xpath_memory_block* _root; size_t _root_size; public: #ifdef PUGIXML_NO_EXCEPTIONS jmp_buf* error_handler; #endif xpath_allocator(xpath_memory_block* root, size_t root_size = 0): _root(root), _root_size(root_size) { #ifdef PUGIXML_NO_EXCEPTIONS error_handler = 0; #endif } void* allocate_nothrow(size_t size) { // round size up to block alignment boundary size = (size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1); if (_root_size + size <= _root->capacity) { void* buf = &_root->data[0] + _root_size; _root_size += size; return buf; } else { // make sure we have at least 1/4th of the page free after allocation to satisfy subsequent allocation requests size_t block_capacity_base = sizeof(_root->data); size_t block_capacity_req = size + block_capacity_base / 4; size_t block_capacity = (block_capacity_base > block_capacity_req) ? block_capacity_base : block_capacity_req; size_t block_size = block_capacity + offsetof(xpath_memory_block, data); xpath_memory_block* block = static_cast<xpath_memory_block*>(xml_memory::allocate(block_size)); if (!block) return 0; block->next = _root; block->capacity = block_capacity; _root = block; _root_size = size; return block->data; } } void* allocate(size_t size) { void* result = allocate_nothrow(size); if (!result) { #ifdef PUGIXML_NO_EXCEPTIONS assert(error_handler); longjmp(*error_handler, 1); #else throw std::bad_alloc(); #endif } return result; } void* reallocate(void* ptr, size_t old_size, size_t new_size) { // round size up to block alignment boundary old_size = (old_size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1); new_size = (new_size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1); // we can only reallocate the last object assert(ptr == 0 || static_cast<char*>(ptr) + old_size == &_root->data[0] + _root_size); // adjust root size so that we have not allocated the object at all bool only_object = (_root_size == old_size); if (ptr) _root_size -= old_size; // allocate a new version (this will obviously reuse the memory if possible) void* result = allocate(new_size); assert(result); // we have a new block if (result != ptr && ptr) { // copy old data assert(new_size >= old_size); memcpy(result, ptr, old_size); // free the previous page if it had no other objects if (only_object) { assert(_root->data == result); assert(_root->next); xpath_memory_block* next = _root->next->next; if (next) { // deallocate the whole page, unless it was the first one xml_memory::deallocate(_root->next); _root->next = next; } } } return result; } void revert(const xpath_allocator& state) { // free all new pages xpath_memory_block* cur = _root; while (cur != state._root) { xpath_memory_block* next = cur->next; xml_memory::deallocate(cur); cur = next; } // restore state _root = state._root; _root_size = state._root_size; } void release() { xpath_memory_block* cur = _root; assert(cur); while (cur->next) { xpath_memory_block* next = cur->next; xml_memory::deallocate(cur); cur = next; } } }; struct xpath_allocator_capture { xpath_allocator_capture(xpath_allocator* alloc): _target(alloc), _state(*alloc) { } ~xpath_allocator_capture() { _target->revert(_state); } xpath_allocator* _target; xpath_allocator _state; }; struct xpath_stack { xpath_allocator* result; xpath_allocator* temp; }; struct xpath_stack_data { xpath_memory_block blocks[2]; xpath_allocator result; xpath_allocator temp; xpath_stack stack; #ifdef PUGIXML_NO_EXCEPTIONS jmp_buf error_handler; #endif xpath_stack_data(): result(blocks + 0), temp(blocks + 1) { blocks[0].next = blocks[1].next = 0; blocks[0].capacity = blocks[1].capacity = sizeof(blocks[0].data); stack.result = &result; stack.temp = &temp; #ifdef PUGIXML_NO_EXCEPTIONS result.error_handler = temp.error_handler = &error_handler; #endif } ~xpath_stack_data() { result.release(); temp.release(); } }; PUGI__NS_END // String class PUGI__NS_BEGIN class xpath_string { const char_t* _buffer; bool _uses_heap; size_t _length_heap; static char_t* duplicate_string(const char_t* string, size_t length, xpath_allocator* alloc) { char_t* result = static_cast<char_t*>(alloc->allocate((length + 1) * sizeof(char_t))); assert(result); memcpy(result, string, length * sizeof(char_t)); result[length] = 0; return result; } xpath_string(const char_t* buffer, bool uses_heap_, size_t length_heap): _buffer(buffer), _uses_heap(uses_heap_), _length_heap(length_heap) { } public: static xpath_string from_const(const char_t* str) { return xpath_string(str, false, 0); } static xpath_string from_heap_preallocated(const char_t* begin, const char_t* end) { assert(begin <= end && *end == 0); return xpath_string(begin, true, static_cast<size_t>(end - begin)); } static xpath_string from_heap(const char_t* begin, const char_t* end, xpath_allocator* alloc) { assert(begin <= end); size_t length = static_cast<size_t>(end - begin); return length == 0 ? xpath_string() : xpath_string(duplicate_string(begin, length, alloc), true, length); } xpath_string(): _buffer(PUGIXML_TEXT("")), _uses_heap(false), _length_heap(0) { } void append(const xpath_string& o, xpath_allocator* alloc) { // skip empty sources if (!*o._buffer) return; // fast append for constant empty target and constant source if (!*_buffer && !_uses_heap && !o._uses_heap) { _buffer = o._buffer; } else { // need to make heap copy size_t target_length = length(); size_t source_length = o.length(); size_t result_length = target_length + source_length; // allocate new buffer char_t* result = static_cast<char_t*>(alloc->reallocate(_uses_heap ? const_cast<char_t*>(_buffer) : 0, (target_length + 1) * sizeof(char_t), (result_length + 1) * sizeof(char_t))); assert(result); // append first string to the new buffer in case there was no reallocation if (!_uses_heap) memcpy(result, _buffer, target_length * sizeof(char_t)); // append second string to the new buffer memcpy(result + target_length, o._buffer, source_length * sizeof(char_t)); result[result_length] = 0; // finalize _buffer = result; _uses_heap = true; _length_heap = result_length; } } const char_t* c_str() const { return _buffer; } size_t length() const { return _uses_heap ? _length_heap : strlength(_buffer); } char_t* data(xpath_allocator* alloc) { // make private heap copy if (!_uses_heap) { size_t length_ = strlength(_buffer); _buffer = duplicate_string(_buffer, length_, alloc); _uses_heap = true; _length_heap = length_; } return const_cast<char_t*>(_buffer); } bool empty() const { return *_buffer == 0; } bool operator==(const xpath_string& o) const { return strequal(_buffer, o._buffer); } bool operator!=(const xpath_string& o) const { return !strequal(_buffer, o._buffer); } bool uses_heap() const { return _uses_heap; } }; PUGI__NS_END PUGI__NS_BEGIN PUGI__FN bool starts_with(const char_t* string, const char_t* pattern) { while (*pattern && *string == *pattern) { string++; pattern++; } return *pattern == 0; } PUGI__FN const char_t* find_char(const char_t* s, char_t c) { #ifdef PUGIXML_WCHAR_MODE return wcschr(s, c); #else return strchr(s, c); #endif } PUGI__FN const char_t* find_substring(const char_t* s, const char_t* p) { #ifdef PUGIXML_WCHAR_MODE // MSVC6 wcsstr bug workaround (if s is empty it always returns 0) return (*p == 0) ? s : wcsstr(s, p); #else return strstr(s, p); #endif } // Converts symbol to lower case, if it is an ASCII one PUGI__FN char_t tolower_ascii(char_t ch) { return static_cast<unsigned int>(ch - 'A') < 26 ? static_cast<char_t>(ch | ' ') : ch; } PUGI__FN xpath_string string_value(const xpath_node& na, xpath_allocator* alloc) { if (na.attribute()) return xpath_string::from_const(na.attribute().value()); else { xml_node n = na.node(); switch (n.type()) { case node_pcdata: case node_cdata: case node_comment: case node_pi: return xpath_string::from_const(n.value()); case node_document: case node_element: { xpath_string result; // element nodes can have value if parse_embed_pcdata was used if (n.value()[0]) result.append(xpath_string::from_const(n.value()), alloc); xml_node cur = n.first_child(); while (cur && cur != n) { if (cur.type() == node_pcdata || cur.type() == node_cdata) result.append(xpath_string::from_const(cur.value()), alloc); if (cur.first_child()) cur = cur.first_child(); else if (cur.next_sibling()) cur = cur.next_sibling(); else { while (!cur.next_sibling() && cur != n) cur = cur.parent(); if (cur != n) cur = cur.next_sibling(); } } return result; } default: return xpath_string(); } } } PUGI__FN bool node_is_before_sibling(xml_node_struct* ln, xml_node_struct* rn) { assert(ln->parent == rn->parent); // there is no common ancestor (the shared parent is null), nodes are from different documents if (!ln->parent) return ln < rn; // determine sibling order xml_node_struct* ls = ln; xml_node_struct* rs = rn; while (ls && rs) { if (ls == rn) return true; if (rs == ln) return false; ls = ls->next_sibling; rs = rs->next_sibling; } // if rn sibling chain ended ln must be before rn return !rs; } PUGI__FN bool node_is_before(xml_node_struct* ln, xml_node_struct* rn) { // find common ancestor at the same depth, if any xml_node_struct* lp = ln; xml_node_struct* rp = rn; while (lp && rp && lp->parent != rp->parent) { lp = lp->parent; rp = rp->parent; } // parents are the same! if (lp && rp) return node_is_before_sibling(lp, rp); // nodes are at different depths, need to normalize heights bool left_higher = !lp; while (lp) { lp = lp->parent; ln = ln->parent; } while (rp) { rp = rp->parent; rn = rn->parent; } // one node is the ancestor of the other if (ln == rn) return left_higher; // find common ancestor... again while (ln->parent != rn->parent) { ln = ln->parent; rn = rn->parent; } return node_is_before_sibling(ln, rn); } PUGI__FN bool node_is_ancestor(xml_node_struct* parent, xml_node_struct* node) { while (node && node != parent) node = node->parent; return parent && node == parent; } PUGI__FN const void* document_buffer_order(const xpath_node& xnode) { xml_node_struct* node = xnode.node().internal_object(); if (node) { if ((get_document(node).header & xml_memory_page_contents_shared_mask) == 0) { if (node->name && (node->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return node->name; if (node->value && (node->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return node->value; } return 0; } xml_attribute_struct* attr = xnode.attribute().internal_object(); if (attr) { if ((get_document(attr).header & xml_memory_page_contents_shared_mask) == 0) { if ((attr->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return attr->name; if ((attr->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return attr->value; } return 0; } return 0; } struct document_order_comparator { bool operator()(const xpath_node& lhs, const xpath_node& rhs) const { // optimized document order based check const void* lo = document_buffer_order(lhs); const void* ro = document_buffer_order(rhs); if (lo && ro) return lo < ro; // slow comparison xml_node ln = lhs.node(), rn = rhs.node(); // compare attributes if (lhs.attribute() && rhs.attribute()) { // shared parent if (lhs.parent() == rhs.parent()) { // determine sibling order for (xml_attribute a = lhs.attribute(); a; a = a.next_attribute()) if (a == rhs.attribute()) return true; return false; } // compare attribute parents ln = lhs.parent(); rn = rhs.parent(); } else if (lhs.attribute()) { // attributes go after the parent element if (lhs.parent() == rhs.node()) return false; ln = lhs.parent(); } else if (rhs.attribute()) { // attributes go after the parent element if (rhs.parent() == lhs.node()) return true; rn = rhs.parent(); } if (ln == rn) return false; if (!ln || !rn) return ln < rn; return node_is_before(ln.internal_object(), rn.internal_object()); } }; struct duplicate_comparator { bool operator()(const xpath_node& lhs, const xpath_node& rhs) const { if (lhs.attribute()) return rhs.attribute() ? lhs.attribute() < rhs.attribute() : true; else return rhs.attribute() ? false : lhs.node() < rhs.node(); } }; PUGI__FN double gen_nan() { #if defined(__STDC_IEC_559__) || ((FLT_RADIX - 0 == 2) && (FLT_MAX_EXP - 0 == 128) && (FLT_MANT_DIG - 0 == 24)) PUGI__STATIC_ASSERT(sizeof(float) == sizeof(uint32_t)); typedef uint32_t UI; // BCC5 workaround union { float f; UI i; } u; u.i = 0x7fc00000; return u.f; #else // fallback const volatile double zero = 0.0; return zero / zero; #endif } PUGI__FN bool is_nan(double value) { #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) return !!_isnan(value); #elif defined(fpclassify) && defined(FP_NAN) return fpclassify(value) == FP_NAN; #else // fallback const volatile double v = value; return v != v; #endif } PUGI__FN const char_t* convert_number_to_string_special(double value) { #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) if (_finite(value)) return (value == 0) ? PUGIXML_TEXT("0") : 0; if (_isnan(value)) return PUGIXML_TEXT("NaN"); return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity"); #elif defined(fpclassify) && defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO) switch (fpclassify(value)) { case FP_NAN: return PUGIXML_TEXT("NaN"); case FP_INFINITE: return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity"); case FP_ZERO: return PUGIXML_TEXT("0"); default: return 0; } #else // fallback const volatile double v = value; if (v == 0) return PUGIXML_TEXT("0"); if (v != v) return PUGIXML_TEXT("NaN"); if (v * 2 == v) return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity"); return 0; #endif } PUGI__FN bool convert_number_to_boolean(double value) { return (value != 0 && !is_nan(value)); } PUGI__FN void truncate_zeros(char* begin, char* end) { while (begin != end && end[-1] == '0') end--; *end = 0; } // gets mantissa digits in the form of 0.xxxxx with 0. implied and the exponent #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE) PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent) { // get base values int sign, exponent; _ecvt_s(buffer, buffer_size, value, DBL_DIG + 1, &exponent, &sign); // truncate redundant zeros truncate_zeros(buffer, buffer + strlen(buffer)); // fill results *out_mantissa = buffer; *out_exponent = exponent; } #else PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent) { // get a scientific notation value with IEEE DBL_DIG decimals sprintf(buffer, "%.*e", DBL_DIG, value); assert(strlen(buffer) < buffer_size); (void)!buffer_size; // get the exponent (possibly negative) char* exponent_string = strchr(buffer, 'e'); assert(exponent_string); int exponent = atoi(exponent_string + 1); // extract mantissa string: skip sign char* mantissa = buffer[0] == '-' ? buffer + 1 : buffer; assert(mantissa[0] != '0' && mantissa[1] == '.'); // divide mantissa by 10 to eliminate integer part mantissa[1] = mantissa[0]; mantissa++; exponent++; // remove extra mantissa digits and zero-terminate mantissa truncate_zeros(mantissa, exponent_string); // fill results *out_mantissa = mantissa; *out_exponent = exponent; } #endif PUGI__FN xpath_string convert_number_to_string(double value, xpath_allocator* alloc) { // try special number conversion const char_t* special = convert_number_to_string_special(value); if (special) return xpath_string::from_const(special); // get mantissa + exponent form char mantissa_buffer[32]; char* mantissa; int exponent; convert_number_to_mantissa_exponent(value, mantissa_buffer, sizeof(mantissa_buffer), &mantissa, &exponent); // allocate a buffer of suitable length for the number size_t result_size = strlen(mantissa_buffer) + (exponent > 0 ? exponent : -exponent) + 4; char_t* result = static_cast<char_t*>(alloc->allocate(sizeof(char_t) * result_size)); assert(result); // make the number! char_t* s = result; // sign if (value < 0) *s++ = '-'; // integer part if (exponent <= 0) { *s++ = '0'; } else { while (exponent > 0) { assert(*mantissa == 0 || static_cast<unsigned int>(static_cast<unsigned int>(*mantissa) - '0') <= 9); *s++ = *mantissa ? *mantissa++ : '0'; exponent--; } } // fractional part if (*mantissa) { // decimal point *s++ = '.'; // extra zeroes from negative exponent while (exponent < 0) { *s++ = '0'; exponent++; } // extra mantissa digits while (*mantissa) { assert(static_cast<unsigned int>(*mantissa - '0') <= 9); *s++ = *mantissa++; } } // zero-terminate assert(s < result + result_size); *s = 0; return xpath_string::from_heap_preallocated(result, s); } PUGI__FN bool check_string_to_number_format(const char_t* string) { // parse leading whitespace while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string; // parse sign if (*string == '-') ++string; if (!*string) return false; // if there is no integer part, there should be a decimal part with at least one digit if (!PUGI__IS_CHARTYPEX(string[0], ctx_digit) && (string[0] != '.' || !PUGI__IS_CHARTYPEX(string[1], ctx_digit))) return false; // parse integer part while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string; // parse decimal part if (*string == '.') { ++string; while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string; } // parse trailing whitespace while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string; return *string == 0; } PUGI__FN double convert_string_to_number(const char_t* string) { // check string format if (!check_string_to_number_format(string)) return gen_nan(); // parse string #ifdef PUGIXML_WCHAR_MODE return wcstod(string, 0); #else return strtod(string, 0); #endif } PUGI__FN bool convert_string_to_number_scratch(char_t (&buffer)[32], const char_t* begin, const char_t* end, double* out_result) { size_t length = static_cast<size_t>(end - begin); char_t* scratch = buffer; if (length >= sizeof(buffer) / sizeof(buffer[0])) { // need to make dummy on-heap copy scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t))); if (!scratch) return false; } // copy string to zero-terminated buffer and perform conversion memcpy(scratch, begin, length * sizeof(char_t)); scratch[length] = 0; *out_result = convert_string_to_number(scratch); // free dummy buffer if (scratch != buffer) xml_memory::deallocate(scratch); return true; } PUGI__FN double round_nearest(double value) { return floor(value + 0.5); } PUGI__FN double round_nearest_nzero(double value) { // same as round_nearest, but returns -0 for [-0.5, -0] // ceil is used to differentiate between +0 and -0 (we return -0 for [-0.5, -0] and +0 for +0) return (value >= -0.5 && value <= 0) ? ceil(value) : floor(value + 0.5); } PUGI__FN const char_t* qualified_name(const xpath_node& node) { return node.attribute() ? node.attribute().name() : node.node().name(); } PUGI__FN const char_t* local_name(const xpath_node& node) { const char_t* name = qualified_name(node); const char_t* p = find_char(name, ':'); return p ? p + 1 : name; } struct namespace_uri_predicate { const char_t* prefix; size_t prefix_length; namespace_uri_predicate(const char_t* name) { const char_t* pos = find_char(name, ':'); prefix = pos ? name : 0; prefix_length = pos ? static_cast<size_t>(pos - name) : 0; } bool operator()(xml_attribute a) const { const char_t* name = a.name(); if (!starts_with(name, PUGIXML_TEXT("xmlns"))) return false; return prefix ? name[5] == ':' && strequalrange(name + 6, prefix, prefix_length) : name[5] == 0; } }; PUGI__FN const char_t* namespace_uri(xml_node node) { namespace_uri_predicate pred = node.name(); xml_node p = node; while (p) { xml_attribute a = p.find_attribute(pred); if (a) return a.value(); p = p.parent(); } return PUGIXML_TEXT(""); } PUGI__FN const char_t* namespace_uri(xml_attribute attr, xml_node parent) { namespace_uri_predicate pred = attr.name(); // Default namespace does not apply to attributes if (!pred.prefix) return PUGIXML_TEXT(""); xml_node p = parent; while (p) { xml_attribute a = p.find_attribute(pred); if (a) return a.value(); p = p.parent(); } return PUGIXML_TEXT(""); } PUGI__FN const char_t* namespace_uri(const xpath_node& node) { return node.attribute() ? namespace_uri(node.attribute(), node.parent()) : namespace_uri(node.node()); } PUGI__FN char_t* normalize_space(char_t* buffer) { char_t* write = buffer; for (char_t* it = buffer; *it; ) { char_t ch = *it++; if (PUGI__IS_CHARTYPE(ch, ct_space)) { // replace whitespace sequence with single space while (PUGI__IS_CHARTYPE(*it, ct_space)) it++; // avoid leading spaces if (write != buffer) *write++ = ' '; } else *write++ = ch; } // remove trailing space if (write != buffer && PUGI__IS_CHARTYPE(write[-1], ct_space)) write--; // zero-terminate *write = 0; return write; } PUGI__FN char_t* translate(char_t* buffer, const char_t* from, const char_t* to, size_t to_length) { char_t* write = buffer; while (*buffer) { PUGI__DMC_VOLATILE char_t ch = *buffer++; const char_t* pos = find_char(from, ch); if (!pos) *write++ = ch; // do not process else if (static_cast<size_t>(pos - from) < to_length) *write++ = to[pos - from]; // replace } // zero-terminate *write = 0; return write; } PUGI__FN unsigned char* translate_table_generate(xpath_allocator* alloc, const char_t* from, const char_t* to) { unsigned char table[128] = {0}; while (*from) { unsigned int fc = static_cast<unsigned int>(*from); unsigned int tc = static_cast<unsigned int>(*to); if (fc >= 128 || tc >= 128) return 0; // code=128 means "skip character" if (!table[fc]) table[fc] = static_cast<unsigned char>(tc ? tc : 128); from++; if (tc) to++; } for (int i = 0; i < 128; ++i) if (!table[i]) table[i] = static_cast<unsigned char>(i); void* result = alloc->allocate_nothrow(sizeof(table)); if (result) { memcpy(result, table, sizeof(table)); } return static_cast<unsigned char*>(result); } PUGI__FN char_t* translate_table(char_t* buffer, const unsigned char* table) { char_t* write = buffer; while (*buffer) { char_t ch = *buffer++; unsigned int index = static_cast<unsigned int>(ch); if (index < 128) { unsigned char code = table[index]; // code=128 means "skip character" (table size is 128 so 128 can be a special value) // this code skips these characters without extra branches *write = static_cast<char_t>(code); write += 1 - (code >> 7); } else { *write++ = ch; } } // zero-terminate *write = 0; return write; } inline bool is_xpath_attribute(const char_t* name) { return !(starts_with(name, PUGIXML_TEXT("xmlns")) && (name[5] == 0 || name[5] == ':')); } struct xpath_variable_boolean: xpath_variable { xpath_variable_boolean(): xpath_variable(xpath_type_boolean), value(false) { } bool value; char_t name[1]; }; struct xpath_variable_number: xpath_variable { xpath_variable_number(): xpath_variable(xpath_type_number), value(0) { } double value; char_t name[1]; }; struct xpath_variable_string: xpath_variable { xpath_variable_string(): xpath_variable(xpath_type_string), value(0) { } ~xpath_variable_string() { if (value) xml_memory::deallocate(value); } char_t* value; char_t name[1]; }; struct xpath_variable_node_set: xpath_variable { xpath_variable_node_set(): xpath_variable(xpath_type_node_set) { } xpath_node_set value; char_t name[1]; }; static const xpath_node_set dummy_node_set; PUGI__FN unsigned int hash_string(const char_t* str) { // Jenkins one-at-a-time hash (http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time) unsigned int result = 0; while (*str) { result += static_cast<unsigned int>(*str++); result += result << 10; result ^= result >> 6; } result += result << 3; result ^= result >> 11; result += result << 15; return result; } template <typename T> PUGI__FN T* new_xpath_variable(const char_t* name) { size_t length = strlength(name); if (length == 0) return 0; // empty variable names are invalid // $$ we can't use offsetof(T, name) because T is non-POD, so we just allocate additional length characters void* memory = xml_memory::allocate(sizeof(T) + length * sizeof(char_t)); if (!memory) return 0; T* result = new (memory) T(); memcpy(result->name, name, (length + 1) * sizeof(char_t)); return result; } PUGI__FN xpath_variable* new_xpath_variable(xpath_value_type type, const char_t* name) { switch (type) { case xpath_type_node_set: return new_xpath_variable<xpath_variable_node_set>(name); case xpath_type_number: return new_xpath_variable<xpath_variable_number>(name); case xpath_type_string: return new_xpath_variable<xpath_variable_string>(name); case xpath_type_boolean: return new_xpath_variable<xpath_variable_boolean>(name); default: return 0; } } template <typename T> PUGI__FN void delete_xpath_variable(T* var) { var->~T(); xml_memory::deallocate(var); } PUGI__FN void delete_xpath_variable(xpath_value_type type, xpath_variable* var) { switch (type) { case xpath_type_node_set: delete_xpath_variable(static_cast<xpath_variable_node_set*>(var)); break; case xpath_type_number: delete_xpath_variable(static_cast<xpath_variable_number*>(var)); break; case xpath_type_string: delete_xpath_variable(static_cast<xpath_variable_string*>(var)); break; case xpath_type_boolean: delete_xpath_variable(static_cast<xpath_variable_boolean*>(var)); break; default: assert(false && "Invalid variable type"); } } PUGI__FN bool copy_xpath_variable(xpath_variable* lhs, const xpath_variable* rhs) { switch (rhs->type()) { case xpath_type_node_set: return lhs->set(static_cast<const xpath_variable_node_set*>(rhs)->value); case xpath_type_number: return lhs->set(static_cast<const xpath_variable_number*>(rhs)->value); case xpath_type_string: return lhs->set(static_cast<const xpath_variable_string*>(rhs)->value); case xpath_type_boolean: return lhs->set(static_cast<const xpath_variable_boolean*>(rhs)->value); default: assert(false && "Invalid variable type"); return false; } } PUGI__FN bool get_variable_scratch(char_t (&buffer)[32], xpath_variable_set* set, const char_t* begin, const char_t* end, xpath_variable** out_result) { size_t length = static_cast<size_t>(end - begin); char_t* scratch = buffer; if (length >= sizeof(buffer) / sizeof(buffer[0])) { // need to make dummy on-heap copy scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t))); if (!scratch) return false; } // copy string to zero-terminated buffer and perform lookup memcpy(scratch, begin, length * sizeof(char_t)); scratch[length] = 0; *out_result = set->get(scratch); // free dummy buffer if (scratch != buffer) xml_memory::deallocate(scratch); return true; } PUGI__NS_END // Internal node set class PUGI__NS_BEGIN PUGI__FN xpath_node_set::type_t xpath_get_order(const xpath_node* begin, const xpath_node* end) { if (end - begin < 2) return xpath_node_set::type_sorted; document_order_comparator cmp; bool first = cmp(begin[0], begin[1]); for (const xpath_node* it = begin + 1; it + 1 < end; ++it) if (cmp(it[0], it[1]) != first) return xpath_node_set::type_unsorted; return first ? xpath_node_set::type_sorted : xpath_node_set::type_sorted_reverse; } PUGI__FN xpath_node_set::type_t xpath_sort(xpath_node* begin, xpath_node* end, xpath_node_set::type_t type, bool rev) { xpath_node_set::type_t order = rev ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted; if (type == xpath_node_set::type_unsorted) { xpath_node_set::type_t sorted = xpath_get_order(begin, end); if (sorted == xpath_node_set::type_unsorted) { sort(begin, end, document_order_comparator()); type = xpath_node_set::type_sorted; } else type = sorted; } if (type != order) reverse(begin, end); return order; } PUGI__FN xpath_node xpath_first(const xpath_node* begin, const xpath_node* end, xpath_node_set::type_t type) { if (begin == end) return xpath_node(); switch (type) { case xpath_node_set::type_sorted: return *begin; case xpath_node_set::type_sorted_reverse: return *(end - 1); case xpath_node_set::type_unsorted: return *min_element(begin, end, document_order_comparator()); default: assert(false && "Invalid node set type"); return xpath_node(); } } class xpath_node_set_raw { xpath_node_set::type_t _type; xpath_node* _begin; xpath_node* _end; xpath_node* _eos; public: xpath_node_set_raw(): _type(xpath_node_set::type_unsorted), _begin(0), _end(0), _eos(0) { } xpath_node* begin() const { return _begin; } xpath_node* end() const { return _end; } bool empty() const { return _begin == _end; } size_t size() const { return static_cast<size_t>(_end - _begin); } xpath_node first() const { return xpath_first(_begin, _end, _type); } void push_back_grow(const xpath_node& node, xpath_allocator* alloc); void push_back(const xpath_node& node, xpath_allocator* alloc) { if (_end != _eos) *_end++ = node; else push_back_grow(node, alloc); } void append(const xpath_node* begin_, const xpath_node* end_, xpath_allocator* alloc) { if (begin_ == end_) return; size_t size_ = static_cast<size_t>(_end - _begin); size_t capacity = static_cast<size_t>(_eos - _begin); size_t count = static_cast<size_t>(end_ - begin_); if (size_ + count > capacity) { // reallocate the old array or allocate a new one xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), (size_ + count) * sizeof(xpath_node))); assert(data); // finalize _begin = data; _end = data + size_; _eos = data + size_ + count; } memcpy(_end, begin_, count * sizeof(xpath_node)); _end += count; } void sort_do() { _type = xpath_sort(_begin, _end, _type, false); } void truncate(xpath_node* pos) { assert(_begin <= pos && pos <= _end); _end = pos; } void remove_duplicates() { if (_type == xpath_node_set::type_unsorted) sort(_begin, _end, duplicate_comparator()); _end = unique(_begin, _end); } xpath_node_set::type_t type() const { return _type; } void set_type(xpath_node_set::type_t value) { _type = value; } }; PUGI__FN_NO_INLINE void xpath_node_set_raw::push_back_grow(const xpath_node& node, xpath_allocator* alloc) { size_t capacity = static_cast<size_t>(_eos - _begin); // get new capacity (1.5x rule) size_t new_capacity = capacity + capacity / 2 + 1; // reallocate the old array or allocate a new one xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), new_capacity * sizeof(xpath_node))); assert(data); // finalize _begin = data; _end = data + capacity; _eos = data + new_capacity; // push *_end++ = node; } PUGI__NS_END PUGI__NS_BEGIN struct xpath_context { xpath_node n; size_t position, size; xpath_context(const xpath_node& n_, size_t position_, size_t size_): n(n_), position(position_), size(size_) { } }; enum lexeme_t { lex_none = 0, lex_equal, lex_not_equal, lex_less, lex_greater, lex_less_or_equal, lex_greater_or_equal, lex_plus, lex_minus, lex_multiply, lex_union, lex_var_ref, lex_open_brace, lex_close_brace, lex_quoted_string, lex_number, lex_slash, lex_double_slash, lex_open_square_brace, lex_close_square_brace, lex_string, lex_comma, lex_axis_attribute, lex_dot, lex_double_dot, lex_double_colon, lex_eof }; struct xpath_lexer_string { const char_t* begin; const char_t* end; xpath_lexer_string(): begin(0), end(0) { } bool operator==(const char_t* other) const { size_t length = static_cast<size_t>(end - begin); return strequalrange(other, begin, length); } }; class xpath_lexer { const char_t* _cur; const char_t* _cur_lexeme_pos; xpath_lexer_string _cur_lexeme_contents; lexeme_t _cur_lexeme; public: explicit xpath_lexer(const char_t* query): _cur(query) { next(); } const char_t* state() const { return _cur; } void next() { const char_t* cur = _cur; while (PUGI__IS_CHARTYPE(*cur, ct_space)) ++cur; // save lexeme position for error reporting _cur_lexeme_pos = cur; switch (*cur) { case 0: _cur_lexeme = lex_eof; break; case '>': if (*(cur+1) == '=') { cur += 2; _cur_lexeme = lex_greater_or_equal; } else { cur += 1; _cur_lexeme = lex_greater; } break; case '<': if (*(cur+1) == '=') { cur += 2; _cur_lexeme = lex_less_or_equal; } else { cur += 1; _cur_lexeme = lex_less; } break; case '!': if (*(cur+1) == '=') { cur += 2; _cur_lexeme = lex_not_equal; } else { _cur_lexeme = lex_none; } break; case '=': cur += 1; _cur_lexeme = lex_equal; break; case '+': cur += 1; _cur_lexeme = lex_plus; break; case '-': cur += 1; _cur_lexeme = lex_minus; break; case '*': cur += 1; _cur_lexeme = lex_multiply; break; case '|': cur += 1; _cur_lexeme = lex_union; break; case '$': cur += 1; if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol)) { _cur_lexeme_contents.begin = cur; while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++; if (cur[0] == ':' && PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // qname { cur++; // : while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++; } _cur_lexeme_contents.end = cur; _cur_lexeme = lex_var_ref; } else { _cur_lexeme = lex_none; } break; case '(': cur += 1; _cur_lexeme = lex_open_brace; break; case ')': cur += 1; _cur_lexeme = lex_close_brace; break; case '[': cur += 1; _cur_lexeme = lex_open_square_brace; break; case ']': cur += 1; _cur_lexeme = lex_close_square_brace; break; case ',': cur += 1; _cur_lexeme = lex_comma; break; case '/': if (*(cur+1) == '/') { cur += 2; _cur_lexeme = lex_double_slash; } else { cur += 1; _cur_lexeme = lex_slash; } break; case '.': if (*(cur+1) == '.') { cur += 2; _cur_lexeme = lex_double_dot; } else if (PUGI__IS_CHARTYPEX(*(cur+1), ctx_digit)) { _cur_lexeme_contents.begin = cur; // . ++cur; while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++; _cur_lexeme_contents.end = cur; _cur_lexeme = lex_number; } else { cur += 1; _cur_lexeme = lex_dot; } break; case '@': cur += 1; _cur_lexeme = lex_axis_attribute; break; case '"': case '\'': { char_t terminator = *cur; ++cur; _cur_lexeme_contents.begin = cur; while (*cur && *cur != terminator) cur++; _cur_lexeme_contents.end = cur; if (!*cur) _cur_lexeme = lex_none; else { cur += 1; _cur_lexeme = lex_quoted_string; } break; } case ':': if (*(cur+1) == ':') { cur += 2; _cur_lexeme = lex_double_colon; } else { _cur_lexeme = lex_none; } break; default: if (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) { _cur_lexeme_contents.begin = cur; while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++; if (*cur == '.') { cur++; while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++; } _cur_lexeme_contents.end = cur; _cur_lexeme = lex_number; } else if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol)) { _cur_lexeme_contents.begin = cur; while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++; if (cur[0] == ':') { if (cur[1] == '*') // namespace test ncname:* { cur += 2; // :* } else if (PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // namespace test qname { cur++; // : while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++; } } _cur_lexeme_contents.end = cur; _cur_lexeme = lex_string; } else { _cur_lexeme = lex_none; } } _cur = cur; } lexeme_t current() const { return _cur_lexeme; } const char_t* current_pos() const { return _cur_lexeme_pos; } const xpath_lexer_string& contents() const { assert(_cur_lexeme == lex_var_ref || _cur_lexeme == lex_number || _cur_lexeme == lex_string || _cur_lexeme == lex_quoted_string); return _cur_lexeme_contents; } }; enum ast_type_t { ast_unknown, ast_op_or, // left or right ast_op_and, // left and right ast_op_equal, // left = right ast_op_not_equal, // left != right ast_op_less, // left < right ast_op_greater, // left > right ast_op_less_or_equal, // left <= right ast_op_greater_or_equal, // left >= right ast_op_add, // left + right ast_op_subtract, // left - right ast_op_multiply, // left * right ast_op_divide, // left / right ast_op_mod, // left % right ast_op_negate, // left - right ast_op_union, // left | right ast_predicate, // apply predicate to set; next points to next predicate ast_filter, // select * from left where right ast_string_constant, // string constant ast_number_constant, // number constant ast_variable, // variable ast_func_last, // last() ast_func_position, // position() ast_func_count, // count(left) ast_func_id, // id(left) ast_func_local_name_0, // local-name() ast_func_local_name_1, // local-name(left) ast_func_namespace_uri_0, // namespace-uri() ast_func_namespace_uri_1, // namespace-uri(left) ast_func_name_0, // name() ast_func_name_1, // name(left) ast_func_string_0, // string() ast_func_string_1, // string(left) ast_func_concat, // concat(left, right, siblings) ast_func_starts_with, // starts_with(left, right) ast_func_contains, // contains(left, right) ast_func_substring_before, // substring-before(left, right) ast_func_substring_after, // substring-after(left, right) ast_func_substring_2, // substring(left, right) ast_func_substring_3, // substring(left, right, third) ast_func_string_length_0, // string-length() ast_func_string_length_1, // string-length(left) ast_func_normalize_space_0, // normalize-space() ast_func_normalize_space_1, // normalize-space(left) ast_func_translate, // translate(left, right, third) ast_func_boolean, // boolean(left) ast_func_not, // not(left) ast_func_true, // true() ast_func_false, // false() ast_func_lang, // lang(left) ast_func_number_0, // number() ast_func_number_1, // number(left) ast_func_sum, // sum(left) ast_func_floor, // floor(left) ast_func_ceiling, // ceiling(left) ast_func_round, // round(left) ast_step, // process set left with step ast_step_root, // select root node ast_opt_translate_table, // translate(left, right, third) where right/third are constants ast_opt_compare_attribute // @name = 'string' }; enum axis_t { axis_ancestor, axis_ancestor_or_self, axis_attribute, axis_child, axis_descendant, axis_descendant_or_self, axis_following, axis_following_sibling, axis_namespace, axis_parent, axis_preceding, axis_preceding_sibling, axis_self }; enum nodetest_t { nodetest_none, nodetest_name, nodetest_type_node, nodetest_type_comment, nodetest_type_pi, nodetest_type_text, nodetest_pi, nodetest_all, nodetest_all_in_namespace }; enum predicate_t { predicate_default, predicate_posinv, predicate_constant, predicate_constant_one }; enum nodeset_eval_t { nodeset_eval_all, nodeset_eval_any, nodeset_eval_first }; template <axis_t N> struct axis_to_type { static const axis_t axis; }; template <axis_t N> const axis_t axis_to_type<N>::axis = N; class xpath_ast_node { private: // node type char _type; char _rettype; // for ast_step char _axis; // for ast_step/ast_predicate/ast_filter char _test; // tree node structure xpath_ast_node* _left; xpath_ast_node* _right; xpath_ast_node* _next; union { // value for ast_string_constant const char_t* string; // value for ast_number_constant double number; // variable for ast_variable xpath_variable* variable; // node test for ast_step (node name/namespace/node type/pi target) const char_t* nodetest; // table for ast_opt_translate_table const unsigned char* table; } _data; xpath_ast_node(const xpath_ast_node&); xpath_ast_node& operator=(const xpath_ast_node&); template <class Comp> static bool compare_eq(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp) { xpath_value_type lt = lhs->rettype(), rt = rhs->rettype(); if (lt != xpath_type_node_set && rt != xpath_type_node_set) { if (lt == xpath_type_boolean || rt == xpath_type_boolean) return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack)); else if (lt == xpath_type_number || rt == xpath_type_number) return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack)); else if (lt == xpath_type_string || rt == xpath_type_string) { xpath_allocator_capture cr(stack.result); xpath_string ls = lhs->eval_string(c, stack); xpath_string rs = rhs->eval_string(c, stack); return comp(ls, rs); } } else if (lt == xpath_type_node_set && rt == xpath_type_node_set) { xpath_allocator_capture cr(stack.result); xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all); xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all); for (const xpath_node* li = ls.begin(); li != ls.end(); ++li) for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri) { xpath_allocator_capture cri(stack.result); if (comp(string_value(*li, stack.result), string_value(*ri, stack.result))) return true; } return false; } else { if (lt == xpath_type_node_set) { swap(lhs, rhs); swap(lt, rt); } if (lt == xpath_type_boolean) return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack)); else if (lt == xpath_type_number) { xpath_allocator_capture cr(stack.result); double l = lhs->eval_number(c, stack); xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all); for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri) { xpath_allocator_capture cri(stack.result); if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str()))) return true; } return false; } else if (lt == xpath_type_string) { xpath_allocator_capture cr(stack.result); xpath_string l = lhs->eval_string(c, stack); xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all); for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri) { xpath_allocator_capture cri(stack.result); if (comp(l, string_value(*ri, stack.result))) return true; } return false; } } assert(false && "Wrong types"); return false; } static bool eval_once(xpath_node_set::type_t type, nodeset_eval_t eval) { return type == xpath_node_set::type_sorted ? eval != nodeset_eval_all : eval == nodeset_eval_any; } template <class Comp> static bool compare_rel(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp) { xpath_value_type lt = lhs->rettype(), rt = rhs->rettype(); if (lt != xpath_type_node_set && rt != xpath_type_node_set) return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack)); else if (lt == xpath_type_node_set && rt == xpath_type_node_set) { xpath_allocator_capture cr(stack.result); xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all); xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all); for (const xpath_node* li = ls.begin(); li != ls.end(); ++li) { xpath_allocator_capture cri(stack.result); double l = convert_string_to_number(string_value(*li, stack.result).c_str()); for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri) { xpath_allocator_capture crii(stack.result); if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str()))) return true; } } return false; } else if (lt != xpath_type_node_set && rt == xpath_type_node_set) { xpath_allocator_capture cr(stack.result); double l = lhs->eval_number(c, stack); xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all); for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri) { xpath_allocator_capture cri(stack.result); if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str()))) return true; } return false; } else if (lt == xpath_type_node_set && rt != xpath_type_node_set) { xpath_allocator_capture cr(stack.result); xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all); double r = rhs->eval_number(c, stack); for (const xpath_node* li = ls.begin(); li != ls.end(); ++li) { xpath_allocator_capture cri(stack.result); if (comp(convert_string_to_number(string_value(*li, stack.result).c_str()), r)) return true; } return false; } else { assert(false && "Wrong types"); return false; } } static void apply_predicate_boolean(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once) { assert(ns.size() >= first); assert(expr->rettype() != xpath_type_number); size_t i = 1; size_t size = ns.size() - first; xpath_node* last = ns.begin() + first; // remove_if... or well, sort of for (xpath_node* it = last; it != ns.end(); ++it, ++i) { xpath_context c(*it, i, size); if (expr->eval_boolean(c, stack)) { *last++ = *it; if (once) break; } } ns.truncate(last); } static void apply_predicate_number(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once) { assert(ns.size() >= first); assert(expr->rettype() == xpath_type_number); size_t i = 1; size_t size = ns.size() - first; xpath_node* last = ns.begin() + first; // remove_if... or well, sort of for (xpath_node* it = last; it != ns.end(); ++it, ++i) { xpath_context c(*it, i, size); if (expr->eval_number(c, stack) == i) { *last++ = *it; if (once) break; } } ns.truncate(last); } static void apply_predicate_number_const(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack) { assert(ns.size() >= first); assert(expr->rettype() == xpath_type_number); size_t size = ns.size() - first; xpath_node* last = ns.begin() + first; xpath_context c(xpath_node(), 1, size); double er = expr->eval_number(c, stack); if (er >= 1.0 && er <= size) { size_t eri = static_cast<size_t>(er); if (er == eri) { xpath_node r = last[eri - 1]; *last++ = r; } } ns.truncate(last); } void apply_predicate(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, bool once) { if (ns.size() == first) return; assert(_type == ast_filter || _type == ast_predicate); if (_test == predicate_constant || _test == predicate_constant_one) apply_predicate_number_const(ns, first, _right, stack); else if (_right->rettype() == xpath_type_number) apply_predicate_number(ns, first, _right, stack, once); else apply_predicate_boolean(ns, first, _right, stack, once); } void apply_predicates(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, nodeset_eval_t eval) { if (ns.size() == first) return; bool last_once = eval_once(ns.type(), eval); for (xpath_ast_node* pred = _right; pred; pred = pred->_next) pred->apply_predicate(ns, first, stack, !pred->_next && last_once); } bool step_push(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* parent, xpath_allocator* alloc) { assert(a); const char_t* name = a->name ? a->name + 0 : PUGIXML_TEXT(""); switch (_test) { case nodetest_name: if (strequal(name, _data.nodetest) && is_xpath_attribute(name)) { ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc); return true; } break; case nodetest_type_node: case nodetest_all: if (is_xpath_attribute(name)) { ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc); return true; } break; case nodetest_all_in_namespace: if (starts_with(name, _data.nodetest) && is_xpath_attribute(name)) { ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc); return true; } break; default: ; } return false; } bool step_push(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc) { assert(n); xml_node_type type = PUGI__NODETYPE(n); switch (_test) { case nodetest_name: if (type == node_element && n->name && strequal(n->name, _data.nodetest)) { ns.push_back(xml_node(n), alloc); return true; } break; case nodetest_type_node: ns.push_back(xml_node(n), alloc); return true; case nodetest_type_comment: if (type == node_comment) { ns.push_back(xml_node(n), alloc); return true; } break; case nodetest_type_text: if (type == node_pcdata || type == node_cdata) { ns.push_back(xml_node(n), alloc); return true; } break; case nodetest_type_pi: if (type == node_pi) { ns.push_back(xml_node(n), alloc); return true; } break; case nodetest_pi: if (type == node_pi && n->name && strequal(n->name, _data.nodetest)) { ns.push_back(xml_node(n), alloc); return true; } break; case nodetest_all: if (type == node_element) { ns.push_back(xml_node(n), alloc); return true; } break; case nodetest_all_in_namespace: if (type == node_element && n->name && starts_with(n->name, _data.nodetest)) { ns.push_back(xml_node(n), alloc); return true; } break; default: assert(false && "Unknown axis"); } return false; } template <class T> void step_fill(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc, bool once, T) { const axis_t axis = T::axis; switch (axis) { case axis_attribute: { for (xml_attribute_struct* a = n->first_attribute; a; a = a->next_attribute) if (step_push(ns, a, n, alloc) & once) return; break; } case axis_child: { for (xml_node_struct* c = n->first_child; c; c = c->next_sibling) if (step_push(ns, c, alloc) & once) return; break; } case axis_descendant: case axis_descendant_or_self: { if (axis == axis_descendant_or_self) if (step_push(ns, n, alloc) & once) return; xml_node_struct* cur = n->first_child; while (cur) { if (step_push(ns, cur, alloc) & once) return; if (cur->first_child) cur = cur->first_child; else { while (!cur->next_sibling) { cur = cur->parent; if (cur == n) return; } cur = cur->next_sibling; } } break; } case axis_following_sibling: { for (xml_node_struct* c = n->next_sibling; c; c = c->next_sibling) if (step_push(ns, c, alloc) & once) return; break; } case axis_preceding_sibling: { for (xml_node_struct* c = n->prev_sibling_c; c->next_sibling; c = c->prev_sibling_c) if (step_push(ns, c, alloc) & once) return; break; } case axis_following: { xml_node_struct* cur = n; // exit from this node so that we don't include descendants while (!cur->next_sibling) { cur = cur->parent; if (!cur) return; } cur = cur->next_sibling; while (cur) { if (step_push(ns, cur, alloc) & once) return; if (cur->first_child) cur = cur->first_child; else { while (!cur->next_sibling) { cur = cur->parent; if (!cur) return; } cur = cur->next_sibling; } } break; } case axis_preceding: { xml_node_struct* cur = n; // exit from this node so that we don't include descendants while (!cur->prev_sibling_c->next_sibling) { cur = cur->parent; if (!cur) return; } cur = cur->prev_sibling_c; while (cur) { if (cur->first_child) cur = cur->first_child->prev_sibling_c; else { // leaf node, can't be ancestor if (step_push(ns, cur, alloc) & once) return; while (!cur->prev_sibling_c->next_sibling) { cur = cur->parent; if (!cur) return; if (!node_is_ancestor(cur, n)) if (step_push(ns, cur, alloc) & once) return; } cur = cur->prev_sibling_c; } } break; } case axis_ancestor: case axis_ancestor_or_self: { if (axis == axis_ancestor_or_self) if (step_push(ns, n, alloc) & once) return; xml_node_struct* cur = n->parent; while (cur) { if (step_push(ns, cur, alloc) & once) return; cur = cur->parent; } break; } case axis_self: { step_push(ns, n, alloc); break; } case axis_parent: { if (n->parent) step_push(ns, n->parent, alloc); break; } default: assert(false && "Unimplemented axis"); } } template <class T> void step_fill(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* p, xpath_allocator* alloc, bool once, T v) { const axis_t axis = T::axis; switch (axis) { case axis_ancestor: case axis_ancestor_or_self: { if (axis == axis_ancestor_or_self && _test == nodetest_type_node) // reject attributes based on principal node type test if (step_push(ns, a, p, alloc) & once) return; xml_node_struct* cur = p; while (cur) { if (step_push(ns, cur, alloc) & once) return; cur = cur->parent; } break; } case axis_descendant_or_self: case axis_self: { if (_test == nodetest_type_node) // reject attributes based on principal node type test step_push(ns, a, p, alloc); break; } case axis_following: { xml_node_struct* cur = p; while (cur) { if (cur->first_child) cur = cur->first_child; else { while (!cur->next_sibling) { cur = cur->parent; if (!cur) return; } cur = cur->next_sibling; } if (step_push(ns, cur, alloc) & once) return; } break; } case axis_parent: { step_push(ns, p, alloc); break; } case axis_preceding: { // preceding:: axis does not include attribute nodes and attribute ancestors (they are the same as parent's ancestors), so we can reuse node preceding step_fill(ns, p, alloc, once, v); break; } default: assert(false && "Unimplemented axis"); } } template <class T> void step_fill(xpath_node_set_raw& ns, const xpath_node& xn, xpath_allocator* alloc, bool once, T v) { const axis_t axis = T::axis; const bool axis_has_attributes = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_descendant_or_self || axis == axis_following || axis == axis_parent || axis == axis_preceding || axis == axis_self); if (xn.node()) step_fill(ns, xn.node().internal_object(), alloc, once, v); else if (axis_has_attributes && xn.attribute() && xn.parent()) step_fill(ns, xn.attribute().internal_object(), xn.parent().internal_object(), alloc, once, v); } template <class T> xpath_node_set_raw step_do(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval, T v) { const axis_t axis = T::axis; const bool axis_reverse = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_preceding || axis == axis_preceding_sibling); const xpath_node_set::type_t axis_type = axis_reverse ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted; bool once = (axis == axis_attribute && _test == nodetest_name) || (!_right && eval_once(axis_type, eval)) || (_right && !_right->_next && _right->_test == predicate_constant_one); xpath_node_set_raw ns; ns.set_type(axis_type); if (_left) { xpath_node_set_raw s = _left->eval_node_set(c, stack, nodeset_eval_all); // self axis preserves the original order if (axis == axis_self) ns.set_type(s.type()); for (const xpath_node* it = s.begin(); it != s.end(); ++it) { size_t size = ns.size(); // in general, all axes generate elements in a particular order, but there is no order guarantee if axis is applied to two nodes if (axis != axis_self && size != 0) ns.set_type(xpath_node_set::type_unsorted); step_fill(ns, *it, stack.result, once, v); if (_right) apply_predicates(ns, size, stack, eval); } } else { step_fill(ns, c.n, stack.result, once, v); if (_right) apply_predicates(ns, 0, stack, eval); } // child, attribute and self axes always generate unique set of nodes // for other axis, if the set stayed sorted, it stayed unique because the traversal algorithms do not visit the same node twice if (axis != axis_child && axis != axis_attribute && axis != axis_self && ns.type() == xpath_node_set::type_unsorted) ns.remove_duplicates(); return ns; } public: xpath_ast_node(ast_type_t type, xpath_value_type rettype_, const char_t* value): _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0) { assert(type == ast_string_constant); _data.string = value; } xpath_ast_node(ast_type_t type, xpath_value_type rettype_, double value): _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0) { assert(type == ast_number_constant); _data.number = value; } xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_variable* value): _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0) { assert(type == ast_variable); _data.variable = value; } xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_ast_node* left = 0, xpath_ast_node* right = 0): _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(left), _right(right), _next(0) { } xpath_ast_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents): _type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(static_cast<char>(axis)), _test(static_cast<char>(test)), _left(left), _right(0), _next(0) { assert(type == ast_step); _data.nodetest = contents; } xpath_ast_node(ast_type_t type, xpath_ast_node* left, xpath_ast_node* right, predicate_t test): _type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(0), _test(static_cast<char>(test)), _left(left), _right(right), _next(0) { assert(type == ast_filter || type == ast_predicate); } void set_next(xpath_ast_node* value) { _next = value; } void set_right(xpath_ast_node* value) { _right = value; } bool eval_boolean(const xpath_context& c, const xpath_stack& stack) { switch (_type) { case ast_op_or: return _left->eval_boolean(c, stack) || _right->eval_boolean(c, stack); case ast_op_and: return _left->eval_boolean(c, stack) && _right->eval_boolean(c, stack); case ast_op_equal: return compare_eq(_left, _right, c, stack, equal_to()); case ast_op_not_equal: return compare_eq(_left, _right, c, stack, not_equal_to()); case ast_op_less: return compare_rel(_left, _right, c, stack, less()); case ast_op_greater: return compare_rel(_right, _left, c, stack, less()); case ast_op_less_or_equal: return compare_rel(_left, _right, c, stack, less_equal()); case ast_op_greater_or_equal: return compare_rel(_right, _left, c, stack, less_equal()); case ast_func_starts_with: { xpath_allocator_capture cr(stack.result); xpath_string lr = _left->eval_string(c, stack); xpath_string rr = _right->eval_string(c, stack); return starts_with(lr.c_str(), rr.c_str()); } case ast_func_contains: { xpath_allocator_capture cr(stack.result); xpath_string lr = _left->eval_string(c, stack); xpath_string rr = _right->eval_string(c, stack); return find_substring(lr.c_str(), rr.c_str()) != 0; } case ast_func_boolean: return _left->eval_boolean(c, stack); case ast_func_not: return !_left->eval_boolean(c, stack); case ast_func_true: return true; case ast_func_false: return false; case ast_func_lang: { if (c.n.attribute()) return false; xpath_allocator_capture cr(stack.result); xpath_string lang = _left->eval_string(c, stack); for (xml_node n = c.n.node(); n; n = n.parent()) { xml_attribute a = n.attribute(PUGIXML_TEXT("xml:lang")); if (a) { const char_t* value = a.value(); // strnicmp / strncasecmp is not portable for (const char_t* lit = lang.c_str(); *lit; ++lit) { if (tolower_ascii(*lit) != tolower_ascii(*value)) return false; ++value; } return *value == 0 || *value == '-'; } } return false; } case ast_opt_compare_attribute: { const char_t* value = (_right->_type == ast_string_constant) ? _right->_data.string : _right->_data.variable->get_string(); xml_attribute attr = c.n.node().attribute(_left->_data.nodetest); return attr && strequal(attr.value(), value) && is_xpath_attribute(attr.name()); } case ast_variable: { assert(_rettype == _data.variable->type()); if (_rettype == xpath_type_boolean) return _data.variable->get_boolean(); // fallthrough to type conversion } default: { switch (_rettype) { case xpath_type_number: return convert_number_to_boolean(eval_number(c, stack)); case xpath_type_string: { xpath_allocator_capture cr(stack.result); return !eval_string(c, stack).empty(); } case xpath_type_node_set: { xpath_allocator_capture cr(stack.result); return !eval_node_set(c, stack, nodeset_eval_any).empty(); } default: assert(false && "Wrong expression for return type boolean"); return false; } } } } double eval_number(const xpath_context& c, const xpath_stack& stack) { switch (_type) { case ast_op_add: return _left->eval_number(c, stack) + _right->eval_number(c, stack); case ast_op_subtract: return _left->eval_number(c, stack) - _right->eval_number(c, stack); case ast_op_multiply: return _left->eval_number(c, stack) * _right->eval_number(c, stack); case ast_op_divide: return _left->eval_number(c, stack) / _right->eval_number(c, stack); case ast_op_mod: return fmod(_left->eval_number(c, stack), _right->eval_number(c, stack)); case ast_op_negate: return -_left->eval_number(c, stack); case ast_number_constant: return _data.number; case ast_func_last: return static_cast<double>(c.size); case ast_func_position: return static_cast<double>(c.position); case ast_func_count: { xpath_allocator_capture cr(stack.result); return static_cast<double>(_left->eval_node_set(c, stack, nodeset_eval_all).size()); } case ast_func_string_length_0: { xpath_allocator_capture cr(stack.result); return static_cast<double>(string_value(c.n, stack.result).length()); } case ast_func_string_length_1: { xpath_allocator_capture cr(stack.result); return static_cast<double>(_left->eval_string(c, stack).length()); } case ast_func_number_0: { xpath_allocator_capture cr(stack.result); return convert_string_to_number(string_value(c.n, stack.result).c_str()); } case ast_func_number_1: return _left->eval_number(c, stack); case ast_func_sum: { xpath_allocator_capture cr(stack.result); double r = 0; xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_all); for (const xpath_node* it = ns.begin(); it != ns.end(); ++it) { xpath_allocator_capture cri(stack.result); r += convert_string_to_number(string_value(*it, stack.result).c_str()); } return r; } case ast_func_floor: { double r = _left->eval_number(c, stack); return r == r ? floor(r) : r; } case ast_func_ceiling: { double r = _left->eval_number(c, stack); return r == r ? ceil(r) : r; } case ast_func_round: return round_nearest_nzero(_left->eval_number(c, stack)); case ast_variable: { assert(_rettype == _data.variable->type()); if (_rettype == xpath_type_number) return _data.variable->get_number(); // fallthrough to type conversion } default: { switch (_rettype) { case xpath_type_boolean: return eval_boolean(c, stack) ? 1 : 0; case xpath_type_string: { xpath_allocator_capture cr(stack.result); return convert_string_to_number(eval_string(c, stack).c_str()); } case xpath_type_node_set: { xpath_allocator_capture cr(stack.result); return convert_string_to_number(eval_string(c, stack).c_str()); } default: assert(false && "Wrong expression for return type number"); return 0; } } } } xpath_string eval_string_concat(const xpath_context& c, const xpath_stack& stack) { assert(_type == ast_func_concat); xpath_allocator_capture ct(stack.temp); // count the string number size_t count = 1; for (xpath_ast_node* nc = _right; nc; nc = nc->_next) count++; // gather all strings xpath_string static_buffer[4]; xpath_string* buffer = static_buffer; // allocate on-heap for large concats if (count > sizeof(static_buffer) / sizeof(static_buffer[0])) { buffer = static_cast<xpath_string*>(stack.temp->allocate(count * sizeof(xpath_string))); assert(buffer); } // evaluate all strings to temporary stack xpath_stack swapped_stack = {stack.temp, stack.result}; buffer[0] = _left->eval_string(c, swapped_stack); size_t pos = 1; for (xpath_ast_node* n = _right; n; n = n->_next, ++pos) buffer[pos] = n->eval_string(c, swapped_stack); assert(pos == count); // get total length size_t length = 0; for (size_t i = 0; i < count; ++i) length += buffer[i].length(); // create final string char_t* result = static_cast<char_t*>(stack.result->allocate((length + 1) * sizeof(char_t))); assert(result); char_t* ri = result; for (size_t j = 0; j < count; ++j) for (const char_t* bi = buffer[j].c_str(); *bi; ++bi) *ri++ = *bi; *ri = 0; return xpath_string::from_heap_preallocated(result, ri); } xpath_string eval_string(const xpath_context& c, const xpath_stack& stack) { switch (_type) { case ast_string_constant: return xpath_string::from_const(_data.string); case ast_func_local_name_0: { xpath_node na = c.n; return xpath_string::from_const(local_name(na)); } case ast_func_local_name_1: { xpath_allocator_capture cr(stack.result); xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first); xpath_node na = ns.first(); return xpath_string::from_const(local_name(na)); } case ast_func_name_0: { xpath_node na = c.n; return xpath_string::from_const(qualified_name(na)); } case ast_func_name_1: { xpath_allocator_capture cr(stack.result); xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first); xpath_node na = ns.first(); return xpath_string::from_const(qualified_name(na)); } case ast_func_namespace_uri_0: { xpath_node na = c.n; return xpath_string::from_const(namespace_uri(na)); } case ast_func_namespace_uri_1: { xpath_allocator_capture cr(stack.result); xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first); xpath_node na = ns.first(); return xpath_string::from_const(namespace_uri(na)); } case ast_func_string_0: return string_value(c.n, stack.result); case ast_func_string_1: return _left->eval_string(c, stack); case ast_func_concat: return eval_string_concat(c, stack); case ast_func_substring_before: { xpath_allocator_capture cr(stack.temp); xpath_stack swapped_stack = {stack.temp, stack.result}; xpath_string s = _left->eval_string(c, swapped_stack); xpath_string p = _right->eval_string(c, swapped_stack); const char_t* pos = find_substring(s.c_str(), p.c_str()); return pos ? xpath_string::from_heap(s.c_str(), pos, stack.result) : xpath_string(); } case ast_func_substring_after: { xpath_allocator_capture cr(stack.temp); xpath_stack swapped_stack = {stack.temp, stack.result}; xpath_string s = _left->eval_string(c, swapped_stack); xpath_string p = _right->eval_string(c, swapped_stack); const char_t* pos = find_substring(s.c_str(), p.c_str()); if (!pos) return xpath_string(); const char_t* rbegin = pos + p.length(); const char_t* rend = s.c_str() + s.length(); return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin); } case ast_func_substring_2: { xpath_allocator_capture cr(stack.temp); xpath_stack swapped_stack = {stack.temp, stack.result}; xpath_string s = _left->eval_string(c, swapped_stack); size_t s_length = s.length(); double first = round_nearest(_right->eval_number(c, stack)); if (is_nan(first)) return xpath_string(); // NaN else if (first >= s_length + 1) return xpath_string(); size_t pos = first < 1 ? 1 : static_cast<size_t>(first); assert(1 <= pos && pos <= s_length + 1); const char_t* rbegin = s.c_str() + (pos - 1); const char_t* rend = s.c_str() + s.length(); return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin); } case ast_func_substring_3: { xpath_allocator_capture cr(stack.temp); xpath_stack swapped_stack = {stack.temp, stack.result}; xpath_string s = _left->eval_string(c, swapped_stack); size_t s_length = s.length(); double first = round_nearest(_right->eval_number(c, stack)); double last = first + round_nearest(_right->_next->eval_number(c, stack)); if (is_nan(first) || is_nan(last)) return xpath_string(); else if (first >= s_length + 1) return xpath_string(); else if (first >= last) return xpath_string(); else if (last < 1) return xpath_string(); size_t pos = first < 1 ? 1 : static_cast<size_t>(first); size_t end = last >= s_length + 1 ? s_length + 1 : static_cast<size_t>(last); assert(1 <= pos && pos <= end && end <= s_length + 1); const char_t* rbegin = s.c_str() + (pos - 1); const char_t* rend = s.c_str() + (end - 1); return (end == s_length + 1 && !s.uses_heap()) ? xpath_string::from_const(rbegin) : xpath_string::from_heap(rbegin, rend, stack.result); } case ast_func_normalize_space_0: { xpath_string s = string_value(c.n, stack.result); char_t* begin = s.data(stack.result); char_t* end = normalize_space(begin); return xpath_string::from_heap_preallocated(begin, end); } case ast_func_normalize_space_1: { xpath_string s = _left->eval_string(c, stack); char_t* begin = s.data(stack.result); char_t* end = normalize_space(begin); return xpath_string::from_heap_preallocated(begin, end); } case ast_func_translate: { xpath_allocator_capture cr(stack.temp); xpath_stack swapped_stack = {stack.temp, stack.result}; xpath_string s = _left->eval_string(c, stack); xpath_string from = _right->eval_string(c, swapped_stack); xpath_string to = _right->_next->eval_string(c, swapped_stack); char_t* begin = s.data(stack.result); char_t* end = translate(begin, from.c_str(), to.c_str(), to.length()); return xpath_string::from_heap_preallocated(begin, end); } case ast_opt_translate_table: { xpath_string s = _left->eval_string(c, stack); char_t* begin = s.data(stack.result); char_t* end = translate_table(begin, _data.table); return xpath_string::from_heap_preallocated(begin, end); } case ast_variable: { assert(_rettype == _data.variable->type()); if (_rettype == xpath_type_string) return xpath_string::from_const(_data.variable->get_string()); // fallthrough to type conversion } default: { switch (_rettype) { case xpath_type_boolean: return xpath_string::from_const(eval_boolean(c, stack) ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false")); case xpath_type_number: return convert_number_to_string(eval_number(c, stack), stack.result); case xpath_type_node_set: { xpath_allocator_capture cr(stack.temp); xpath_stack swapped_stack = {stack.temp, stack.result}; xpath_node_set_raw ns = eval_node_set(c, swapped_stack, nodeset_eval_first); return ns.empty() ? xpath_string() : string_value(ns.first(), stack.result); } default: assert(false && "Wrong expression for return type string"); return xpath_string(); } } } } xpath_node_set_raw eval_node_set(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval) { switch (_type) { case ast_op_union: { xpath_allocator_capture cr(stack.temp); xpath_stack swapped_stack = {stack.temp, stack.result}; xpath_node_set_raw ls = _left->eval_node_set(c, swapped_stack, eval); xpath_node_set_raw rs = _right->eval_node_set(c, stack, eval); // we can optimize merging two sorted sets, but this is a very rare operation, so don't bother rs.set_type(xpath_node_set::type_unsorted); rs.append(ls.begin(), ls.end(), stack.result); rs.remove_duplicates(); return rs; } case ast_filter: { xpath_node_set_raw set = _left->eval_node_set(c, stack, _test == predicate_constant_one ? nodeset_eval_first : nodeset_eval_all); // either expression is a number or it contains position() call; sort by document order if (_test != predicate_posinv) set.sort_do(); bool once = eval_once(set.type(), eval); apply_predicate(set, 0, stack, once); return set; } case ast_func_id: return xpath_node_set_raw(); case ast_step: { switch (_axis) { case axis_ancestor: return step_do(c, stack, eval, axis_to_type<axis_ancestor>()); case axis_ancestor_or_self: return step_do(c, stack, eval, axis_to_type<axis_ancestor_or_self>()); case axis_attribute: return step_do(c, stack, eval, axis_to_type<axis_attribute>()); case axis_child: return step_do(c, stack, eval, axis_to_type<axis_child>()); case axis_descendant: return step_do(c, stack, eval, axis_to_type<axis_descendant>()); case axis_descendant_or_self: return step_do(c, stack, eval, axis_to_type<axis_descendant_or_self>()); case axis_following: return step_do(c, stack, eval, axis_to_type<axis_following>()); case axis_following_sibling: return step_do(c, stack, eval, axis_to_type<axis_following_sibling>()); case axis_namespace: // namespaced axis is not supported return xpath_node_set_raw(); case axis_parent: return step_do(c, stack, eval, axis_to_type<axis_parent>()); case axis_preceding: return step_do(c, stack, eval, axis_to_type<axis_preceding>()); case axis_preceding_sibling: return step_do(c, stack, eval, axis_to_type<axis_preceding_sibling>()); case axis_self: return step_do(c, stack, eval, axis_to_type<axis_self>()); default: assert(false && "Unknown axis"); return xpath_node_set_raw(); } } case ast_step_root: { assert(!_right); // root step can't have any predicates xpath_node_set_raw ns; ns.set_type(xpath_node_set::type_sorted); if (c.n.node()) ns.push_back(c.n.node().root(), stack.result); else if (c.n.attribute()) ns.push_back(c.n.parent().root(), stack.result); return ns; } case ast_variable: { assert(_rettype == _data.variable->type()); if (_rettype == xpath_type_node_set) { const xpath_node_set& s = _data.variable->get_node_set(); xpath_node_set_raw ns; ns.set_type(s.type()); ns.append(s.begin(), s.end(), stack.result); return ns; } // fallthrough to type conversion } default: assert(false && "Wrong expression for return type node set"); return xpath_node_set_raw(); } } void optimize(xpath_allocator* alloc) { if (_left) _left->optimize(alloc); if (_right) _right->optimize(alloc); if (_next) _next->optimize(alloc); optimize_self(alloc); } void optimize_self(xpath_allocator* alloc) { // Rewrite [position()=expr] with [expr] // Note that this step has to go before classification to recognize [position()=1] if ((_type == ast_filter || _type == ast_predicate) && _right->_type == ast_op_equal && _right->_left->_type == ast_func_position && _right->_right->_rettype == xpath_type_number) { _right = _right->_right; } // Classify filter/predicate ops to perform various optimizations during evaluation if (_type == ast_filter || _type == ast_predicate) { assert(_test == predicate_default); if (_right->_type == ast_number_constant && _right->_data.number == 1.0) _test = predicate_constant_one; else if (_right->_rettype == xpath_type_number && (_right->_type == ast_number_constant || _right->_type == ast_variable || _right->_type == ast_func_last)) _test = predicate_constant; else if (_right->_rettype != xpath_type_number && _right->is_posinv_expr()) _test = predicate_posinv; } // Rewrite descendant-or-self::node()/child::foo with descendant::foo // The former is a full form of //foo, the latter is much faster since it executes the node test immediately // Do a similar kind of rewrite for self/descendant/descendant-or-self axes // Note that we only rewrite positionally invariant steps (//foo[1] != /descendant::foo[1]) if (_type == ast_step && (_axis == axis_child || _axis == axis_self || _axis == axis_descendant || _axis == axis_descendant_or_self) && _left && _left->_type == ast_step && _left->_axis == axis_descendant_or_self && _left->_test == nodetest_type_node && !_left->_right && is_posinv_step()) { if (_axis == axis_child || _axis == axis_descendant) _axis = axis_descendant; else _axis = axis_descendant_or_self; _left = _left->_left; } // Use optimized lookup table implementation for translate() with constant arguments if (_type == ast_func_translate && _right->_type == ast_string_constant && _right->_next->_type == ast_string_constant) { unsigned char* table = translate_table_generate(alloc, _right->_data.string, _right->_next->_data.string); if (table) { _type = ast_opt_translate_table; _data.table = table; } } // Use optimized path for @attr = 'value' or @attr = $value if (_type == ast_op_equal && _left->_type == ast_step && _left->_axis == axis_attribute && _left->_test == nodetest_name && !_left->_left && !_left->_right && (_right->_type == ast_string_constant || (_right->_type == ast_variable && _right->_rettype == xpath_type_string))) { _type = ast_opt_compare_attribute; } } bool is_posinv_expr() const { switch (_type) { case ast_func_position: case ast_func_last: return false; case ast_string_constant: case ast_number_constant: case ast_variable: return true; case ast_step: case ast_step_root: return true; case ast_predicate: case ast_filter: return true; default: if (_left && !_left->is_posinv_expr()) return false; for (xpath_ast_node* n = _right; n; n = n->_next) if (!n->is_posinv_expr()) return false; return true; } } bool is_posinv_step() const { assert(_type == ast_step); for (xpath_ast_node* n = _right; n; n = n->_next) { assert(n->_type == ast_predicate); if (n->_test != predicate_posinv) return false; } return true; } xpath_value_type rettype() const { return static_cast<xpath_value_type>(_rettype); } }; struct xpath_parser { xpath_allocator* _alloc; xpath_lexer _lexer; const char_t* _query; xpath_variable_set* _variables; xpath_parse_result* _result; char_t _scratch[32]; #ifdef PUGIXML_NO_EXCEPTIONS jmp_buf _error_handler; #endif void throw_error(const char* message) { _result->error = message; _result->offset = _lexer.current_pos() - _query; #ifdef PUGIXML_NO_EXCEPTIONS longjmp(_error_handler, 1); #else throw xpath_exception(*_result); #endif } void throw_error_oom() { #ifdef PUGIXML_NO_EXCEPTIONS throw_error("Out of memory"); #else throw std::bad_alloc(); #endif } void* alloc_node() { void* result = _alloc->allocate_nothrow(sizeof(xpath_ast_node)); if (!result) throw_error_oom(); return result; } const char_t* alloc_string(const xpath_lexer_string& value) { if (value.begin) { size_t length = static_cast<size_t>(value.end - value.begin); char_t* c = static_cast<char_t*>(_alloc->allocate_nothrow((length + 1) * sizeof(char_t))); if (!c) throw_error_oom(); assert(c); // workaround for clang static analysis memcpy(c, value.begin, length * sizeof(char_t)); c[length] = 0; return c; } else return 0; } xpath_ast_node* parse_function_helper(ast_type_t type0, ast_type_t type1, size_t argc, xpath_ast_node* args[2]) { assert(argc <= 1); if (argc == 1 && args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set"); return new (alloc_node()) xpath_ast_node(argc == 0 ? type0 : type1, xpath_type_string, args[0]); } xpath_ast_node* parse_function(const xpath_lexer_string& name, size_t argc, xpath_ast_node* args[2]) { switch (name.begin[0]) { case 'b': if (name == PUGIXML_TEXT("boolean") && argc == 1) return new (alloc_node()) xpath_ast_node(ast_func_boolean, xpath_type_boolean, args[0]); break; case 'c': if (name == PUGIXML_TEXT("count") && argc == 1) { if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set"); return new (alloc_node()) xpath_ast_node(ast_func_count, xpath_type_number, args[0]); } else if (name == PUGIXML_TEXT("contains") && argc == 2) return new (alloc_node()) xpath_ast_node(ast_func_contains, xpath_type_boolean, args[0], args[1]); else if (name == PUGIXML_TEXT("concat") && argc >= 2) return new (alloc_node()) xpath_ast_node(ast_func_concat, xpath_type_string, args[0], args[1]); else if (name == PUGIXML_TEXT("ceiling") && argc == 1) return new (alloc_node()) xpath_ast_node(ast_func_ceiling, xpath_type_number, args[0]); break; case 'f': if (name == PUGIXML_TEXT("false") && argc == 0) return new (alloc_node()) xpath_ast_node(ast_func_false, xpath_type_boolean); else if (name == PUGIXML_TEXT("floor") && argc == 1) return new (alloc_node()) xpath_ast_node(ast_func_floor, xpath_type_number, args[0]); break; case 'i': if (name == PUGIXML_TEXT("id") && argc == 1) return new (alloc_node()) xpath_ast_node(ast_func_id, xpath_type_node_set, args[0]); break; case 'l': if (name == PUGIXML_TEXT("last") && argc == 0) return new (alloc_node()) xpath_ast_node(ast_func_last, xpath_type_number); else if (name == PUGIXML_TEXT("lang") && argc == 1) return new (alloc_node()) xpath_ast_node(ast_func_lang, xpath_type_boolean, args[0]); else if (name == PUGIXML_TEXT("local-name") && argc <= 1) return parse_function_helper(ast_func_local_name_0, ast_func_local_name_1, argc, args); break; case 'n': if (name == PUGIXML_TEXT("name") && argc <= 1) return parse_function_helper(ast_func_name_0, ast_func_name_1, argc, args); else if (name == PUGIXML_TEXT("namespace-uri") && argc <= 1) return parse_function_helper(ast_func_namespace_uri_0, ast_func_namespace_uri_1, argc, args); else if (name == PUGIXML_TEXT("normalize-space") && argc <= 1) return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_normalize_space_0 : ast_func_normalize_space_1, xpath_type_string, args[0], args[1]); else if (name == PUGIXML_TEXT("not") && argc == 1) return new (alloc_node()) xpath_ast_node(ast_func_not, xpath_type_boolean, args[0]); else if (name == PUGIXML_TEXT("number") && argc <= 1) return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_number_0 : ast_func_number_1, xpath_type_number, args[0]); break; case 'p': if (name == PUGIXML_TEXT("position") && argc == 0) return new (alloc_node()) xpath_ast_node(ast_func_position, xpath_type_number); break; case 'r': if (name == PUGIXML_TEXT("round") && argc == 1) return new (alloc_node()) xpath_ast_node(ast_func_round, xpath_type_number, args[0]); break; case 's': if (name == PUGIXML_TEXT("string") && argc <= 1) return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_0 : ast_func_string_1, xpath_type_string, args[0]); else if (name == PUGIXML_TEXT("string-length") && argc <= 1) return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_length_0 : ast_func_string_length_1, xpath_type_number, args[0]); else if (name == PUGIXML_TEXT("starts-with") && argc == 2) return new (alloc_node()) xpath_ast_node(ast_func_starts_with, xpath_type_boolean, args[0], args[1]); else if (name == PUGIXML_TEXT("substring-before") && argc == 2) return new (alloc_node()) xpath_ast_node(ast_func_substring_before, xpath_type_string, args[0], args[1]); else if (name == PUGIXML_TEXT("substring-after") && argc == 2) return new (alloc_node()) xpath_ast_node(ast_func_substring_after, xpath_type_string, args[0], args[1]); else if (name == PUGIXML_TEXT("substring") && (argc == 2 || argc == 3)) return new (alloc_node()) xpath_ast_node(argc == 2 ? ast_func_substring_2 : ast_func_substring_3, xpath_type_string, args[0], args[1]); else if (name == PUGIXML_TEXT("sum") && argc == 1) { if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set"); return new (alloc_node()) xpath_ast_node(ast_func_sum, xpath_type_number, args[0]); } break; case 't': if (name == PUGIXML_TEXT("translate") && argc == 3) return new (alloc_node()) xpath_ast_node(ast_func_translate, xpath_type_string, args[0], args[1]); else if (name == PUGIXML_TEXT("true") && argc == 0) return new (alloc_node()) xpath_ast_node(ast_func_true, xpath_type_boolean); break; default: break; } throw_error("Unrecognized function or wrong parameter count"); return 0; } axis_t parse_axis_name(const xpath_lexer_string& name, bool& specified) { specified = true; switch (name.begin[0]) { case 'a': if (name == PUGIXML_TEXT("ancestor")) return axis_ancestor; else if (name == PUGIXML_TEXT("ancestor-or-self")) return axis_ancestor_or_self; else if (name == PUGIXML_TEXT("attribute")) return axis_attribute; break; case 'c': if (name == PUGIXML_TEXT("child")) return axis_child; break; case 'd': if (name == PUGIXML_TEXT("descendant")) return axis_descendant; else if (name == PUGIXML_TEXT("descendant-or-self")) return axis_descendant_or_self; break; case 'f': if (name == PUGIXML_TEXT("following")) return axis_following; else if (name == PUGIXML_TEXT("following-sibling")) return axis_following_sibling; break; case 'n': if (name == PUGIXML_TEXT("namespace")) return axis_namespace; break; case 'p': if (name == PUGIXML_TEXT("parent")) return axis_parent; else if (name == PUGIXML_TEXT("preceding")) return axis_preceding; else if (name == PUGIXML_TEXT("preceding-sibling")) return axis_preceding_sibling; break; case 's': if (name == PUGIXML_TEXT("self")) return axis_self; break; default: break; } specified = false; return axis_child; } nodetest_t parse_node_test_type(const xpath_lexer_string& name) { switch (name.begin[0]) { case 'c': if (name == PUGIXML_TEXT("comment")) return nodetest_type_comment; break; case 'n': if (name == PUGIXML_TEXT("node")) return nodetest_type_node; break; case 'p': if (name == PUGIXML_TEXT("processing-instruction")) return nodetest_type_pi; break; case 't': if (name == PUGIXML_TEXT("text")) return nodetest_type_text; break; default: break; } return nodetest_none; } // PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall xpath_ast_node* parse_primary_expression() { switch (_lexer.current()) { case lex_var_ref: { xpath_lexer_string name = _lexer.contents(); if (!_variables) throw_error("Unknown variable: variable set is not provided"); xpath_variable* var = 0; if (!get_variable_scratch(_scratch, _variables, name.begin, name.end, &var)) throw_error_oom(); if (!var) throw_error("Unknown variable: variable set does not contain the given name"); _lexer.next(); return new (alloc_node()) xpath_ast_node(ast_variable, var->type(), var); } case lex_open_brace: { _lexer.next(); xpath_ast_node* n = parse_expression(); if (_lexer.current() != lex_close_brace) throw_error("Unmatched braces"); _lexer.next(); return n; } case lex_quoted_string: { const char_t* value = alloc_string(_lexer.contents()); xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_string_constant, xpath_type_string, value); _lexer.next(); return n; } case lex_number: { double value = 0; if (!convert_string_to_number_scratch(_scratch, _lexer.contents().begin, _lexer.contents().end, &value)) throw_error_oom(); xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_number_constant, xpath_type_number, value); _lexer.next(); return n; } case lex_string: { xpath_ast_node* args[2] = {0}; size_t argc = 0; xpath_lexer_string function = _lexer.contents(); _lexer.next(); xpath_ast_node* last_arg = 0; if (_lexer.current() != lex_open_brace) throw_error("Unrecognized function call"); _lexer.next(); if (_lexer.current() != lex_close_brace) args[argc++] = parse_expression(); while (_lexer.current() != lex_close_brace) { if (_lexer.current() != lex_comma) throw_error("No comma between function arguments"); _lexer.next(); xpath_ast_node* n = parse_expression(); if (argc < 2) args[argc] = n; else last_arg->set_next(n); argc++; last_arg = n; } _lexer.next(); return parse_function(function, argc, args); } default: throw_error("Unrecognizable primary expression"); return 0; } } // FilterExpr ::= PrimaryExpr | FilterExpr Predicate // Predicate ::= '[' PredicateExpr ']' // PredicateExpr ::= Expr xpath_ast_node* parse_filter_expression() { xpath_ast_node* n = parse_primary_expression(); while (_lexer.current() == lex_open_square_brace) { _lexer.next(); xpath_ast_node* expr = parse_expression(); if (n->rettype() != xpath_type_node_set) throw_error("Predicate has to be applied to node set"); n = new (alloc_node()) xpath_ast_node(ast_filter, n, expr, predicate_default); if (_lexer.current() != lex_close_square_brace) throw_error("Unmatched square brace"); _lexer.next(); } return n; } // Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep // AxisSpecifier ::= AxisName '::' | '@'? // NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')' // NameTest ::= '*' | NCName ':' '*' | QName // AbbreviatedStep ::= '.' | '..' xpath_ast_node* parse_step(xpath_ast_node* set) { if (set && set->rettype() != xpath_type_node_set) throw_error("Step has to be applied to node set"); bool axis_specified = false; axis_t axis = axis_child; // implied child axis if (_lexer.current() == lex_axis_attribute) { axis = axis_attribute; axis_specified = true; _lexer.next(); } else if (_lexer.current() == lex_dot) { _lexer.next(); return new (alloc_node()) xpath_ast_node(ast_step, set, axis_self, nodetest_type_node, 0); } else if (_lexer.current() == lex_double_dot) { _lexer.next(); return new (alloc_node()) xpath_ast_node(ast_step, set, axis_parent, nodetest_type_node, 0); } nodetest_t nt_type = nodetest_none; xpath_lexer_string nt_name; if (_lexer.current() == lex_string) { // node name test nt_name = _lexer.contents(); _lexer.next(); // was it an axis name? if (_lexer.current() == lex_double_colon) { // parse axis name if (axis_specified) throw_error("Two axis specifiers in one step"); axis = parse_axis_name(nt_name, axis_specified); if (!axis_specified) throw_error("Unknown axis"); // read actual node test _lexer.next(); if (_lexer.current() == lex_multiply) { nt_type = nodetest_all; nt_name = xpath_lexer_string(); _lexer.next(); } else if (_lexer.current() == lex_string) { nt_name = _lexer.contents(); _lexer.next(); } else throw_error("Unrecognized node test"); } if (nt_type == nodetest_none) { // node type test or processing-instruction if (_lexer.current() == lex_open_brace) { _lexer.next(); if (_lexer.current() == lex_close_brace) { _lexer.next(); nt_type = parse_node_test_type(nt_name); if (nt_type == nodetest_none) throw_error("Unrecognized node type"); nt_name = xpath_lexer_string(); } else if (nt_name == PUGIXML_TEXT("processing-instruction")) { if (_lexer.current() != lex_quoted_string) throw_error("Only literals are allowed as arguments to processing-instruction()"); nt_type = nodetest_pi; nt_name = _lexer.contents(); _lexer.next(); if (_lexer.current() != lex_close_brace) throw_error("Unmatched brace near processing-instruction()"); _lexer.next(); } else { throw_error("Unmatched brace near node type test"); } } // QName or NCName:* else { if (nt_name.end - nt_name.begin > 2 && nt_name.end[-2] == ':' && nt_name.end[-1] == '*') // NCName:* { nt_name.end--; // erase * nt_type = nodetest_all_in_namespace; } else { nt_type = nodetest_name; } } } } else if (_lexer.current() == lex_multiply) { nt_type = nodetest_all; _lexer.next(); } else { throw_error("Unrecognized node test"); } const char_t* nt_name_copy = alloc_string(nt_name); xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step, set, axis, nt_type, nt_name_copy); xpath_ast_node* last = 0; while (_lexer.current() == lex_open_square_brace) { _lexer.next(); xpath_ast_node* expr = parse_expression(); xpath_ast_node* pred = new (alloc_node()) xpath_ast_node(ast_predicate, 0, expr, predicate_default); if (_lexer.current() != lex_close_square_brace) throw_error("Unmatched square brace"); _lexer.next(); if (last) last->set_next(pred); else n->set_right(pred); last = pred; } return n; } // RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step xpath_ast_node* parse_relative_location_path(xpath_ast_node* set) { xpath_ast_node* n = parse_step(set); while (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash) { lexeme_t l = _lexer.current(); _lexer.next(); if (l == lex_double_slash) n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0); n = parse_step(n); } return n; } // LocationPath ::= RelativeLocationPath | AbsoluteLocationPath // AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath xpath_ast_node* parse_location_path() { if (_lexer.current() == lex_slash) { _lexer.next(); xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set); // relative location path can start from axis_attribute, dot, double_dot, multiply and string lexemes; any other lexeme means standalone root path lexeme_t l = _lexer.current(); if (l == lex_string || l == lex_axis_attribute || l == lex_dot || l == lex_double_dot || l == lex_multiply) return parse_relative_location_path(n); else return n; } else if (_lexer.current() == lex_double_slash) { _lexer.next(); xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set); n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0); return parse_relative_location_path(n); } // else clause moved outside of if because of bogus warning 'control may reach end of non-void function being inlined' in gcc 4.0.1 return parse_relative_location_path(0); } // PathExpr ::= LocationPath // | FilterExpr // | FilterExpr '/' RelativeLocationPath // | FilterExpr '//' RelativeLocationPath // UnionExpr ::= PathExpr | UnionExpr '|' PathExpr // UnaryExpr ::= UnionExpr | '-' UnaryExpr xpath_ast_node* parse_path_or_unary_expression() { // Clarification. // PathExpr begins with either LocationPath or FilterExpr. // FilterExpr begins with PrimaryExpr // PrimaryExpr begins with '$' in case of it being a variable reference, // '(' in case of it being an expression, string literal, number constant or // function call. if (_lexer.current() == lex_var_ref || _lexer.current() == lex_open_brace || _lexer.current() == lex_quoted_string || _lexer.current() == lex_number || _lexer.current() == lex_string) { if (_lexer.current() == lex_string) { // This is either a function call, or not - if not, we shall proceed with location path const char_t* state = _lexer.state(); while (PUGI__IS_CHARTYPE(*state, ct_space)) ++state; if (*state != '(') return parse_location_path(); // This looks like a function call; however this still can be a node-test. Check it. if (parse_node_test_type(_lexer.contents()) != nodetest_none) return parse_location_path(); } xpath_ast_node* n = parse_filter_expression(); if (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash) { lexeme_t l = _lexer.current(); _lexer.next(); if (l == lex_double_slash) { if (n->rettype() != xpath_type_node_set) throw_error("Step has to be applied to node set"); n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0); } // select from location path return parse_relative_location_path(n); } return n; } else if (_lexer.current() == lex_minus) { _lexer.next(); // precedence 7+ - only parses union expressions xpath_ast_node* expr = parse_expression_rec(parse_path_or_unary_expression(), 7); return new (alloc_node()) xpath_ast_node(ast_op_negate, xpath_type_number, expr); } else { return parse_location_path(); } } struct binary_op_t { ast_type_t asttype; xpath_value_type rettype; int precedence; binary_op_t(): asttype(ast_unknown), rettype(xpath_type_none), precedence(0) { } binary_op_t(ast_type_t asttype_, xpath_value_type rettype_, int precedence_): asttype(asttype_), rettype(rettype_), precedence(precedence_) { } static binary_op_t parse(xpath_lexer& lexer) { switch (lexer.current()) { case lex_string: if (lexer.contents() == PUGIXML_TEXT("or")) return binary_op_t(ast_op_or, xpath_type_boolean, 1); else if (lexer.contents() == PUGIXML_TEXT("and")) return binary_op_t(ast_op_and, xpath_type_boolean, 2); else if (lexer.contents() == PUGIXML_TEXT("div")) return binary_op_t(ast_op_divide, xpath_type_number, 6); else if (lexer.contents() == PUGIXML_TEXT("mod")) return binary_op_t(ast_op_mod, xpath_type_number, 6); else return binary_op_t(); case lex_equal: return binary_op_t(ast_op_equal, xpath_type_boolean, 3); case lex_not_equal: return binary_op_t(ast_op_not_equal, xpath_type_boolean, 3); case lex_less: return binary_op_t(ast_op_less, xpath_type_boolean, 4); case lex_greater: return binary_op_t(ast_op_greater, xpath_type_boolean, 4); case lex_less_or_equal: return binary_op_t(ast_op_less_or_equal, xpath_type_boolean, 4); case lex_greater_or_equal: return binary_op_t(ast_op_greater_or_equal, xpath_type_boolean, 4); case lex_plus: return binary_op_t(ast_op_add, xpath_type_number, 5); case lex_minus: return binary_op_t(ast_op_subtract, xpath_type_number, 5); case lex_multiply: return binary_op_t(ast_op_multiply, xpath_type_number, 6); case lex_union: return binary_op_t(ast_op_union, xpath_type_node_set, 7); default: return binary_op_t(); } } }; xpath_ast_node* parse_expression_rec(xpath_ast_node* lhs, int limit) { binary_op_t op = binary_op_t::parse(_lexer); while (op.asttype != ast_unknown && op.precedence >= limit) { _lexer.next(); xpath_ast_node* rhs = parse_path_or_unary_expression(); binary_op_t nextop = binary_op_t::parse(_lexer); while (nextop.asttype != ast_unknown && nextop.precedence > op.precedence) { rhs = parse_expression_rec(rhs, nextop.precedence); nextop = binary_op_t::parse(_lexer); } if (op.asttype == ast_op_union && (lhs->rettype() != xpath_type_node_set || rhs->rettype() != xpath_type_node_set)) throw_error("Union operator has to be applied to node sets"); lhs = new (alloc_node()) xpath_ast_node(op.asttype, op.rettype, lhs, rhs); op = binary_op_t::parse(_lexer); } return lhs; } // Expr ::= OrExpr // OrExpr ::= AndExpr | OrExpr 'or' AndExpr // AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr // EqualityExpr ::= RelationalExpr // | EqualityExpr '=' RelationalExpr // | EqualityExpr '!=' RelationalExpr // RelationalExpr ::= AdditiveExpr // | RelationalExpr '<' AdditiveExpr // | RelationalExpr '>' AdditiveExpr // | RelationalExpr '<=' AdditiveExpr // | RelationalExpr '>=' AdditiveExpr // AdditiveExpr ::= MultiplicativeExpr // | AdditiveExpr '+' MultiplicativeExpr // | AdditiveExpr '-' MultiplicativeExpr // MultiplicativeExpr ::= UnaryExpr // | MultiplicativeExpr '*' UnaryExpr // | MultiplicativeExpr 'div' UnaryExpr // | MultiplicativeExpr 'mod' UnaryExpr xpath_ast_node* parse_expression() { return parse_expression_rec(parse_path_or_unary_expression(), 0); } xpath_parser(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result): _alloc(alloc), _lexer(query), _query(query), _variables(variables), _result(result) { } xpath_ast_node* parse() { xpath_ast_node* result = parse_expression(); // check if there are unparsed tokens left if (_lexer.current() != lex_eof) throw_error("Incorrect query"); return result; } static xpath_ast_node* parse(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result) { xpath_parser parser(query, variables, alloc, result); #ifdef PUGIXML_NO_EXCEPTIONS int error = setjmp(parser._error_handler); return (error == 0) ? parser.parse() : 0; #else return parser.parse(); #endif } }; struct xpath_query_impl { static xpath_query_impl* create() { void* memory = xml_memory::allocate(sizeof(xpath_query_impl)); if (!memory) return 0; return new (memory) xpath_query_impl(); } static void destroy(xpath_query_impl* impl) { // free all allocated pages impl->alloc.release(); // free allocator memory (with the first page) xml_memory::deallocate(impl); } xpath_query_impl(): root(0), alloc(&block) { block.next = 0; block.capacity = sizeof(block.data); } xpath_ast_node* root; xpath_allocator alloc; xpath_memory_block block; }; PUGI__FN xpath_string evaluate_string_impl(xpath_query_impl* impl, const xpath_node& n, xpath_stack_data& sd) { if (!impl) return xpath_string(); #ifdef PUGIXML_NO_EXCEPTIONS if (setjmp(sd.error_handler)) return xpath_string(); #endif xpath_context c(n, 1, 1); return impl->root->eval_string(c, sd.stack); } PUGI__FN impl::xpath_ast_node* evaluate_node_set_prepare(xpath_query_impl* impl) { if (!impl) return 0; if (impl->root->rettype() != xpath_type_node_set) { #ifdef PUGIXML_NO_EXCEPTIONS return 0; #else xpath_parse_result res; res.error = "Expression does not evaluate to node set"; throw xpath_exception(res); #endif } return impl->root; } PUGI__NS_END namespace pugi { #ifndef PUGIXML_NO_EXCEPTIONS PUGI__FN xpath_exception::xpath_exception(const xpath_parse_result& result_): _result(result_) { assert(_result.error); } PUGI__FN const char* xpath_exception::what() const throw() { return _result.error; } PUGI__FN const xpath_parse_result& xpath_exception::result() const { return _result; } #endif PUGI__FN xpath_node::xpath_node() { } PUGI__FN xpath_node::xpath_node(const xml_node& node_): _node(node_) { } PUGI__FN xpath_node::xpath_node(const xml_attribute& attribute_, const xml_node& parent_): _node(attribute_ ? parent_ : xml_node()), _attribute(attribute_) { } PUGI__FN xml_node xpath_node::node() const { return _attribute ? xml_node() : _node; } PUGI__FN xml_attribute xpath_node::attribute() const { return _attribute; } PUGI__FN xml_node xpath_node::parent() const { return _attribute ? _node : _node.parent(); } PUGI__FN static void unspecified_bool_xpath_node(xpath_node***) { } PUGI__FN xpath_node::operator xpath_node::unspecified_bool_type() const { return (_node || _attribute) ? unspecified_bool_xpath_node : 0; } PUGI__FN bool xpath_node::operator!() const { return !(_node || _attribute); } PUGI__FN bool xpath_node::operator==(const xpath_node& n) const { return _node == n._node && _attribute == n._attribute; } PUGI__FN bool xpath_node::operator!=(const xpath_node& n) const { return _node != n._node || _attribute != n._attribute; } #ifdef __BORLANDC__ PUGI__FN bool operator&&(const xpath_node& lhs, bool rhs) { return (bool)lhs && rhs; } PUGI__FN bool operator||(const xpath_node& lhs, bool rhs) { return (bool)lhs || rhs; } #endif PUGI__FN void xpath_node_set::_assign(const_iterator begin_, const_iterator end_, type_t type_) { assert(begin_ <= end_); size_t size_ = static_cast<size_t>(end_ - begin_); if (size_ <= 1) { // deallocate old buffer if (_begin != &_storage) impl::xml_memory::deallocate(_begin); // use internal buffer if (begin_ != end_) _storage = *begin_; _begin = &_storage; _end = &_storage + size_; _type = type_; } else { // make heap copy xpath_node* storage = static_cast<xpath_node*>(impl::xml_memory::allocate(size_ * sizeof(xpath_node))); if (!storage) { #ifdef PUGIXML_NO_EXCEPTIONS return; #else throw std::bad_alloc(); #endif } memcpy(storage, begin_, size_ * sizeof(xpath_node)); // deallocate old buffer if (_begin != &_storage) impl::xml_memory::deallocate(_begin); // finalize _begin = storage; _end = storage + size_; _type = type_; } } #ifdef PUGIXML_HAS_MOVE PUGI__FN void xpath_node_set::_move(xpath_node_set& rhs) { _type = rhs._type; _storage = rhs._storage; _begin = (rhs._begin == &rhs._storage) ? &_storage : rhs._begin; _end = _begin + (rhs._end - rhs._begin); rhs._type = type_unsorted; rhs._begin = &rhs._storage; rhs._end = rhs._begin; } #endif PUGI__FN xpath_node_set::xpath_node_set(): _type(type_unsorted), _begin(&_storage), _end(&_storage) { } PUGI__FN xpath_node_set::xpath_node_set(const_iterator begin_, const_iterator end_, type_t type_): _type(type_unsorted), _begin(&_storage), _end(&_storage) { _assign(begin_, end_, type_); } PUGI__FN xpath_node_set::~xpath_node_set() { if (_begin != &_storage) impl::xml_memory::deallocate(_begin); } PUGI__FN xpath_node_set::xpath_node_set(const xpath_node_set& ns): _type(type_unsorted), _begin(&_storage), _end(&_storage) { _assign(ns._begin, ns._end, ns._type); } PUGI__FN xpath_node_set& xpath_node_set::operator=(const xpath_node_set& ns) { if (this == &ns) return *this; _assign(ns._begin, ns._end, ns._type); return *this; } #ifdef PUGIXML_HAS_MOVE PUGI__FN xpath_node_set::xpath_node_set(xpath_node_set&& rhs): _type(type_unsorted), _begin(&_storage), _end(&_storage) { _move(rhs); } PUGI__FN xpath_node_set& xpath_node_set::operator=(xpath_node_set&& rhs) { if (this == &rhs) return *this; if (_begin != &_storage) impl::xml_memory::deallocate(_begin); _move(rhs); return *this; } #endif PUGI__FN xpath_node_set::type_t xpath_node_set::type() const { return _type; } PUGI__FN size_t xpath_node_set::size() const { return _end - _begin; } PUGI__FN bool xpath_node_set::empty() const { return _begin == _end; } PUGI__FN const xpath_node& xpath_node_set::operator[](size_t index) const { assert(index < size()); return _begin[index]; } PUGI__FN xpath_node_set::const_iterator xpath_node_set::begin() const { return _begin; } PUGI__FN xpath_node_set::const_iterator xpath_node_set::end() const { return _end; } PUGI__FN void xpath_node_set::sort(bool reverse) { _type = impl::xpath_sort(_begin, _end, _type, reverse); } PUGI__FN xpath_node xpath_node_set::first() const { return impl::xpath_first(_begin, _end, _type); } PUGI__FN xpath_parse_result::xpath_parse_result(): error("Internal error"), offset(0) { } PUGI__FN xpath_parse_result::operator bool() const { return error == 0; } PUGI__FN const char* xpath_parse_result::description() const { return error ? error : "No error"; } PUGI__FN xpath_variable::xpath_variable(xpath_value_type type_): _type(type_), _next(0) { } PUGI__FN const char_t* xpath_variable::name() const { switch (_type) { case xpath_type_node_set: return static_cast<const impl::xpath_variable_node_set*>(this)->name; case xpath_type_number: return static_cast<const impl::xpath_variable_number*>(this)->name; case xpath_type_string: return static_cast<const impl::xpath_variable_string*>(this)->name; case xpath_type_boolean: return static_cast<const impl::xpath_variable_boolean*>(this)->name; default: assert(false && "Invalid variable type"); return 0; } } PUGI__FN xpath_value_type xpath_variable::type() const { return _type; } PUGI__FN bool xpath_variable::get_boolean() const { return (_type == xpath_type_boolean) ? static_cast<const impl::xpath_variable_boolean*>(this)->value : false; } PUGI__FN double xpath_variable::get_number() const { return (_type == xpath_type_number) ? static_cast<const impl::xpath_variable_number*>(this)->value : impl::gen_nan(); } PUGI__FN const char_t* xpath_variable::get_string() const { const char_t* value = (_type == xpath_type_string) ? static_cast<const impl::xpath_variable_string*>(this)->value : 0; return value ? value : PUGIXML_TEXT(""); } PUGI__FN const xpath_node_set& xpath_variable::get_node_set() const { return (_type == xpath_type_node_set) ? static_cast<const impl::xpath_variable_node_set*>(this)->value : impl::dummy_node_set; } PUGI__FN bool xpath_variable::set(bool value) { if (_type != xpath_type_boolean) return false; static_cast<impl::xpath_variable_boolean*>(this)->value = value; return true; } PUGI__FN bool xpath_variable::set(double value) { if (_type != xpath_type_number) return false; static_cast<impl::xpath_variable_number*>(this)->value = value; return true; } PUGI__FN bool xpath_variable::set(const char_t* value) { if (_type != xpath_type_string) return false; impl::xpath_variable_string* var = static_cast<impl::xpath_variable_string*>(this); // duplicate string size_t size = (impl::strlength(value) + 1) * sizeof(char_t); char_t* copy = static_cast<char_t*>(impl::xml_memory::allocate(size)); if (!copy) return false; memcpy(copy, value, size); // replace old string if (var->value) impl::xml_memory::deallocate(var->value); var->value = copy; return true; } PUGI__FN bool xpath_variable::set(const xpath_node_set& value) { if (_type != xpath_type_node_set) return false; static_cast<impl::xpath_variable_node_set*>(this)->value = value; return true; } PUGI__FN xpath_variable_set::xpath_variable_set() { for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) _data[i] = 0; } PUGI__FN xpath_variable_set::~xpath_variable_set() { for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) _destroy(_data[i]); } PUGI__FN xpath_variable_set::xpath_variable_set(const xpath_variable_set& rhs) { for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) _data[i] = 0; _assign(rhs); } PUGI__FN xpath_variable_set& xpath_variable_set::operator=(const xpath_variable_set& rhs) { if (this == &rhs) return *this; _assign(rhs); return *this; } #ifdef PUGIXML_HAS_MOVE PUGI__FN xpath_variable_set::xpath_variable_set(xpath_variable_set&& rhs) { for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) { _data[i] = rhs._data[i]; rhs._data[i] = 0; } } PUGI__FN xpath_variable_set& xpath_variable_set::operator=(xpath_variable_set&& rhs) { for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) { _destroy(_data[i]); _data[i] = rhs._data[i]; rhs._data[i] = 0; } return *this; } #endif PUGI__FN void xpath_variable_set::_assign(const xpath_variable_set& rhs) { xpath_variable_set temp; for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) if (rhs._data[i] && !_clone(rhs._data[i], &temp._data[i])) return; _swap(temp); } PUGI__FN void xpath_variable_set::_swap(xpath_variable_set& rhs) { for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) { xpath_variable* chain = _data[i]; _data[i] = rhs._data[i]; rhs._data[i] = chain; } } PUGI__FN xpath_variable* xpath_variable_set::_find(const char_t* name) const { const size_t hash_size = sizeof(_data) / sizeof(_data[0]); size_t hash = impl::hash_string(name) % hash_size; // look for existing variable for (xpath_variable* var = _data[hash]; var; var = var->_next) if (impl::strequal(var->name(), name)) return var; return 0; } PUGI__FN bool xpath_variable_set::_clone(xpath_variable* var, xpath_variable** out_result) { xpath_variable* last = 0; while (var) { // allocate storage for new variable xpath_variable* nvar = impl::new_xpath_variable(var->_type, var->name()); if (!nvar) return false; // link the variable to the result immediately to handle failures gracefully if (last) last->_next = nvar; else *out_result = nvar; last = nvar; // copy the value; this can fail due to out-of-memory conditions if (!impl::copy_xpath_variable(nvar, var)) return false; var = var->_next; } return true; } PUGI__FN void xpath_variable_set::_destroy(xpath_variable* var) { while (var) { xpath_variable* next = var->_next; impl::delete_xpath_variable(var->_type, var); var = next; } } PUGI__FN xpath_variable* xpath_variable_set::add(const char_t* name, xpath_value_type type) { const size_t hash_size = sizeof(_data) / sizeof(_data[0]); size_t hash = impl::hash_string(name) % hash_size; // look for existing variable for (xpath_variable* var = _data[hash]; var; var = var->_next) if (impl::strequal(var->name(), name)) return var->type() == type ? var : 0; // add new variable xpath_variable* result = impl::new_xpath_variable(type, name); if (result) { result->_next = _data[hash]; _data[hash] = result; } return result; } PUGI__FN bool xpath_variable_set::set(const char_t* name, bool value) { xpath_variable* var = add(name, xpath_type_boolean); return var ? var->set(value) : false; } PUGI__FN bool xpath_variable_set::set(const char_t* name, double value) { xpath_variable* var = add(name, xpath_type_number); return var ? var->set(value) : false; } PUGI__FN bool xpath_variable_set::set(const char_t* name, const char_t* value) { xpath_variable* var = add(name, xpath_type_string); return var ? var->set(value) : false; } PUGI__FN bool xpath_variable_set::set(const char_t* name, const xpath_node_set& value) { xpath_variable* var = add(name, xpath_type_node_set); return var ? var->set(value) : false; } PUGI__FN xpath_variable* xpath_variable_set::get(const char_t* name) { return _find(name); } PUGI__FN const xpath_variable* xpath_variable_set::get(const char_t* name) const { return _find(name); } PUGI__FN xpath_query::xpath_query(const char_t* query, xpath_variable_set* variables): _impl(0) { impl::xpath_query_impl* qimpl = impl::xpath_query_impl::create(); if (!qimpl) { #ifdef PUGIXML_NO_EXCEPTIONS _result.error = "Out of memory"; #else throw std::bad_alloc(); #endif } else { using impl::auto_deleter; // MSVC7 workaround auto_deleter<impl::xpath_query_impl> impl(qimpl, impl::xpath_query_impl::destroy); qimpl->root = impl::xpath_parser::parse(query, variables, &qimpl->alloc, &_result); if (qimpl->root) { qimpl->root->optimize(&qimpl->alloc); _impl = impl.release(); _result.error = 0; } } } PUGI__FN xpath_query::xpath_query(): _impl(0) { } PUGI__FN xpath_query::~xpath_query() { if (_impl) impl::xpath_query_impl::destroy(static_cast<impl::xpath_query_impl*>(_impl)); } #ifdef PUGIXML_HAS_MOVE PUGI__FN xpath_query::xpath_query(xpath_query&& rhs) { _impl = rhs._impl; _result = rhs._result; rhs._impl = 0; rhs._result = xpath_parse_result(); } PUGI__FN xpath_query& xpath_query::operator=(xpath_query&& rhs) { if (this == &rhs) return *this; if (_impl) impl::xpath_query_impl::destroy(static_cast<impl::xpath_query_impl*>(_impl)); _impl = rhs._impl; _result = rhs._result; rhs._impl = 0; rhs._result = xpath_parse_result(); return *this; } #endif PUGI__FN xpath_value_type xpath_query::return_type() const { if (!_impl) return xpath_type_none; return static_cast<impl::xpath_query_impl*>(_impl)->root->rettype(); } PUGI__FN bool xpath_query::evaluate_boolean(const xpath_node& n) const { if (!_impl) return false; impl::xpath_context c(n, 1, 1); impl::xpath_stack_data sd; #ifdef PUGIXML_NO_EXCEPTIONS if (setjmp(sd.error_handler)) return false; #endif return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_boolean(c, sd.stack); } PUGI__FN double xpath_query::evaluate_number(const xpath_node& n) const { if (!_impl) return impl::gen_nan(); impl::xpath_context c(n, 1, 1); impl::xpath_stack_data sd; #ifdef PUGIXML_NO_EXCEPTIONS if (setjmp(sd.error_handler)) return impl::gen_nan(); #endif return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_number(c, sd.stack); } #ifndef PUGIXML_NO_STL PUGI__FN string_t xpath_query::evaluate_string(const xpath_node& n) const { impl::xpath_stack_data sd; impl::xpath_string r = impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd); return string_t(r.c_str(), r.length()); } #endif PUGI__FN size_t xpath_query::evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const { impl::xpath_stack_data sd; impl::xpath_string r = impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd); size_t full_size = r.length() + 1; if (capacity > 0) { size_t size = (full_size < capacity) ? full_size : capacity; assert(size > 0); memcpy(buffer, r.c_str(), (size - 1) * sizeof(char_t)); buffer[size - 1] = 0; } return full_size; } PUGI__FN xpath_node_set xpath_query::evaluate_node_set(const xpath_node& n) const { impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl)); if (!root) return xpath_node_set(); impl::xpath_context c(n, 1, 1); impl::xpath_stack_data sd; #ifdef PUGIXML_NO_EXCEPTIONS if (setjmp(sd.error_handler)) return xpath_node_set(); #endif impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_all); return xpath_node_set(r.begin(), r.end(), r.type()); } PUGI__FN xpath_node xpath_query::evaluate_node(const xpath_node& n) const { impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl)); if (!root) return xpath_node(); impl::xpath_context c(n, 1, 1); impl::xpath_stack_data sd; #ifdef PUGIXML_NO_EXCEPTIONS if (setjmp(sd.error_handler)) return xpath_node(); #endif impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_first); return r.first(); } PUGI__FN const xpath_parse_result& xpath_query::result() const { return _result; } PUGI__FN static void unspecified_bool_xpath_query(xpath_query***) { } PUGI__FN xpath_query::operator xpath_query::unspecified_bool_type() const { return _impl ? unspecified_bool_xpath_query : 0; } PUGI__FN bool xpath_query::operator!() const { return !_impl; } PUGI__FN xpath_node xml_node::select_node(const char_t* query, xpath_variable_set* variables) const { xpath_query q(query, variables); return select_node(q); } PUGI__FN xpath_node xml_node::select_node(const xpath_query& query) const { return query.evaluate_node(*this); } PUGI__FN xpath_node_set xml_node::select_nodes(const char_t* query, xpath_variable_set* variables) const { xpath_query q(query, variables); return select_nodes(q); } PUGI__FN xpath_node_set xml_node::select_nodes(const xpath_query& query) const { return query.evaluate_node_set(*this); } PUGI__FN xpath_node xml_node::select_single_node(const char_t* query, xpath_variable_set* variables) const { xpath_query q(query, variables); return select_single_node(q); } PUGI__FN xpath_node xml_node::select_single_node(const xpath_query& query) const { return query.evaluate_node(*this); } } #endif #ifdef __BORLANDC__ # pragma option pop #endif // Intel C++ does not properly keep warning state for function templates, // so popping warning state at the end of translation unit leads to warnings in the middle. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) # pragma warning(pop) #endif // Undefine all local macros (makes sure we're not leaking macros in header-only mode) #undef PUGI__NO_INLINE #undef PUGI__UNLIKELY #undef PUGI__STATIC_ASSERT #undef PUGI__DMC_VOLATILE #undef PUGI__MSVC_CRT_VERSION #undef PUGI__NS_BEGIN #undef PUGI__NS_END #undef PUGI__FN #undef PUGI__FN_NO_INLINE #undef PUGI__GETHEADER_IMPL #undef PUGI__GETPAGE_IMPL #undef PUGI__GETPAGE #undef PUGI__NODETYPE #undef PUGI__IS_CHARTYPE_IMPL #undef PUGI__IS_CHARTYPE #undef PUGI__IS_CHARTYPEX #undef PUGI__ENDSWITH #undef PUGI__SKIPWS #undef PUGI__OPTSET #undef PUGI__PUSHNODE #undef PUGI__POPNODE #undef PUGI__SCANFOR #undef PUGI__SCANWHILE #undef PUGI__SCANWHILE_UNROLL #undef PUGI__ENDSEG #undef PUGI__THROW_ERROR #undef PUGI__CHECK_ERROR #endif /** * Copyright (c) 2006-2017 Arseny Kapoulkine * * 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. */
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %rbp push %rcx push %rdx push %rsi lea addresses_WT_ht+0x73ee, %rcx nop nop nop nop nop xor $30767, %rdx mov (%rcx), %r11 nop xor $10509, %r13 lea addresses_WT_ht+0xea49, %rbp nop nop cmp $24935, %r15 mov $0x6162636465666768, %rsi movq %rsi, %xmm1 vmovups %ymm1, (%rbp) nop nop sub $21076, %r11 lea addresses_D_ht+0x1516e, %rcx clflush (%rcx) nop nop nop and $55049, %rsi movw $0x6162, (%rcx) nop nop nop nop add %rdx, %rdx pop %rsi pop %rdx pop %rcx pop %rbp pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r8 push %r9 push %rbp push %rdi push %rdx // Store lea addresses_WC+0x103ee, %r10 nop nop nop xor %r9, %r9 mov $0x5152535455565758, %r13 movq %r13, (%r10) nop nop nop nop nop and %r13, %r13 // Store lea addresses_normal+0xb41a, %rdx nop nop sub $60215, %r8 mov $0x5152535455565758, %r9 movq %r9, %xmm4 vmovups %ymm4, (%rdx) nop nop add %rdi, %rdi // Store lea addresses_A+0x7e46, %r13 nop nop nop and %rdi, %rdi movl $0x51525354, (%r13) nop nop sub %rbp, %rbp // Faulty Load lea addresses_D+0x96ee, %rdi nop cmp %r13, %r13 vmovups (%rdi), %ymm5 vextracti128 $0, %ymm5, %xmm5 vpextrq $1, %xmm5, %r8 lea oracles, %rbp and $0xff, %r8 shlq $12, %r8 mov (%rbp,%r8,1), %r8 pop %rdx pop %rdi pop %rbp pop %r9 pop %r8 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'AVXalign': True, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 8}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 1}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 3}} [Faulty Load] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 32, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 7}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
; A047329: Numbers that are congruent to {1, 3, 5, 6} mod 7. ; 1,3,5,6,8,10,12,13,15,17,19,20,22,24,26,27,29,31,33,34,36,38,40,41,43,45,47,48,50,52,54,55,57,59,61,62,64,66,68,69,71,73,75,76,78,80,82,83,85,87,89,90,92,94,96,97,99,101,103,104,106,108,110,111 mov $1,$0 mul $1,7 add $1,6 div $1,4
/*============================================================================= Copyright (c) 2010-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprig 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 SPRIG_TYPE_TRAITS_IS_CONVERTIBLE_TO_RR_HPP #define SPRIG_TYPE_TRAITS_IS_CONVERTIBLE_TO_RR_HPP #include <sprig/config/config.hpp> #ifdef SPRIG_USING_PRAGMA_ONCE # pragma once #endif // #ifdef SPRIG_USING_PRAGMA_ONCE #include <sprig/type_traits/is_convertible_to_ZZ.hpp> namespace sprig { // // to_RR_convertion_traits // struct to_RR_convertion_traits : public to_ZZ_convertion_traits {}; // // is_convertible_to_RR // template<typename T/*, typename Enable = void*/> struct is_convertible_to_RR : public is_convertible_to_ZZ<T> {}; } // namespace sprig #endif // #ifndef SPRIG_TYPE_TRAITS_IS_CONVERTIBLE_TO_RR_HPP
<% from pwnlib.shellcraft.thumb.linux import getppid, kill from pwnlib.constants import SIGKILL from pwnlib.shellcraft.common import label %> <%docstring> Kills its parent process until whatever the parent is (probably init) cannot be killed any longer. </%docstring> <% killparent_loop = label('killparent') %> ${killparent_loop}: ${getppid()} ${kill('eax', SIGKILL)} test eax, eax jz ${killparent_loop}
#pragma once #include <math.h> #include "constants.hpp" namespace PantaRay { struct Vector { float x, y, z; Vector(float _x = 0, float _y = 0, float _z = 0) : x(_x), y(_y), z(_z) {} void MakeZero() { x = y = z = 0; } bool IsZero(float eps = Constants::eps) { return Length() < eps; } float LengthSqr() const { return x * x + y * y + z * z; } float Length() const { return sqrtf(LengthSqr()); } Vector& Scale(float factor) { x *= factor; y *= factor; z *= factor; return *this; } Vector& ScaleTo(float factor) { Normalize(); return Scale(factor); } Vector& Add(const Vector& vector) { x += vector.x; y += vector.y; z += vector.z; return *this; } Vector& Subtract(const Vector& vector) { x -= vector.x; y -= vector.y; z -= vector.z; return *this; } Vector& Invert() { x = -x; y = -y; z = -z; return *this; } Vector& Cross(const Vector& vector) { auto _x = y * vector.z - z * vector.y; auto _y = z * vector.x - x * vector.z; auto _z = x * vector.y - y * vector.x; x = _x; y = _y; z = _z; return *this; } Vector& Reflect(const Vector& normal) { Subtract(normal.Copy().Scale(normal.Dot(*this) * 2)); return *this; } float Dot(const Vector& vector) const { return x * vector.x + y * vector.y + z * vector.z; } Vector& Normalize() { float length = Length(); x /= length; y /= length; z /= length; return *this; } Vector Copy() const { return Vector(x, y, z); } }; }
; A343543: a(n) = n*Lucas(2*n). ; Submitted by Jon Maiga ; 0,3,14,54,188,615,1932,5901,17656,52002,151270,435633,1244184,3528759,9949058,27907470,77933552,216784731,600935076,1660672257,4576522540,12580566138,34504747354,94440719589,257998970928,703593828075,1915713858422,5208304147686 mov $1,$0 mul $1,2 mov $2,$0 mov $0,$1 lpb $0 sub $0,2 add $1,$2 add $2,$1 lpe mov $0,$1
; ; Copyright (C) 2008-2020 Advanced Micro Devices, Inc. All rights reserved. ; ; Redistribution and use in source and binary forms, with or without modification, ; are permitted provided that the following conditions are met: ; 1. Redistributions of source code must retain the above copyright notice, ; this list of conditions and the following disclaimer. ; 2. Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and/or other materials provided with the distribution. ; 3. Neither the name of the copyright holder nor the names of its contributors ; may be used to endorse or promote products derived from this software without ; specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ; IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ; BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ; OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; include fm.inc include trig_func.inc FN_PROTOTYPE_FMA3 sinf fname_special TEXTEQU <_sinf_special> ;Define name and any external functions being called EXTERN fname_special : PROC text SEGMENT EXECUTE PUBLIC fname fname PROC FRAME StackAllocate stack_size .ENDPROLOG sinf_early_exit_s: MOVD eax,xmm0 MOV r8d,L__inf_mask_32 AND eax,r8d CMP eax, r8d JZ sinf_naninf VCVTSS2SD xmm5,xmm0,xmm0 VMOVQ r9,xmm5 AND r9,L__sign_mask ;clear sign sinf_early_exit_s_1: CMP r9,L_mask_3fe JG range_reduce CMP r9,L_mask_3f8 JGE compute_sinf_pyby_4 CMP r9,L_mask_3f2 JGE compute_x_xxx_0_1666 JMP return_sinf_c compute_x_xxx_0_1666: VMULSD xmm1,xmm5,xmm5 ; VMULSD xmm0,xmm1,xmm5 ; xmm1 x3 VFNMADD132SD xmm0 ,xmm5,L_point_166 ; x - x*x*x*0.166666666666666666; JMP return_sinf_s compute_sinf_pyby_4: VMOVSD xmm0,xmm5,xmm5 sin_piby4_sf_fma3 JMP return_sinf_s range_reduce: VMOVQ xmm0,r9 ; r9 x with the sign cleared cmp r9,L_e_5 JGE sinf_remainder_piby2 ;sinf_range_e_5_s: range_e_5_sf_fma3 JMP sinf_exit_s sinf_remainder_piby2: call_remainder_piby2_f sinf_exit_s: VMOVQ rax,xmm4 and rax,01h cmp rax,01h JZ cos_piby4_compute sin_piby4_compute: sin_piby4_sf_fma3 JMP sinf_exit_s_1 cos_piby4_compute: cos_piby4_sf_fma3 sinf_exit_s_1: VPCMPEQQ xmm2,xmm4,XMMWORD PTR L_int_two VPCMPEQQ xmm3,xmm4,XMMWORD PTR L_int_three VORPD xmm3,xmm2,xmm3 VANDNPD xmm3,xmm3,L_signbit VXORPD xmm0,xmm0,xmm3 VANDNPD xmm1,xmm5,L_signbit VXORPD xmm0,xmm1,xmm0 return_sinf_s: VCVTSD2SS xmm0,xmm0,xmm0 StackDeallocate stack_size ret return_sinf_c: StackDeallocate stack_size ret sinf_naninf: call fname_special StackDeallocate stack_size ret fname endp TEXT ENDS END
/* * Copyright (C) 2020-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/gmm_helper/gmm.h" #include "shared/test/common/os_interface/windows/wddm_fixture.h" #include "test.h" namespace NEO { using WddmTests = WddmTestWithMockGdiDll; TEST_F(WddmTests, whenCreatingAllocation64kThenDoNotCreateResource) { init(); D3DKMT_HANDLE handle; Gmm gmm(executionEnvironment->rootDeviceEnvironments[0]->getGmmClientContext(), nullptr, 20, 0, false, true, true, {}); EXPECT_TRUE(wddm->createAllocation(&gmm, handle)); auto gdiParam = getMockAllocationFcn(); EXPECT_EQ(FALSE, gdiParam->Flags.CreateResource); } TEST_F(WddmTests, whenInitializingWddmThenSetMinAddressToCorrectValue) { constexpr static uintptr_t mockedInternalGpuVaRange = 0x9876u; auto gmmMemory = new MockGmmMemoryBase(wddm->rootDeviceEnvironment.getGmmClientContext()); gmmMemory->overrideInternalGpuVaRangeLimit(mockedInternalGpuVaRange); wddm->gmmMemory.reset(gmmMemory); ASSERT_EQ(0u, wddm->getWddmMinAddress()); wddm->init(); const bool obtainFromGmm = defaultHwInfo->platform.eRenderCoreFamily == IGFX_GEN12LP_CORE; const auto expectedMinAddress = obtainFromGmm ? mockedInternalGpuVaRange : windowsMinAddress; ASSERT_EQ(expectedMinAddress, wddm->getWddmMinAddress()); } TEST_F(WddmTests, whenInitializingWddmThenSetTimestampFrequencyToCorrectValue) { EXPECT_EQ(0u, wddm->timestampFrequency); init(); EXPECT_EQ(1u, wddm->timestampFrequency); } TEST_F(WddmTests, givenWddmWhenPassesCorrectHandleToVerifySharedHandleThenReturnTrue) { init(); D3DKMT_HANDLE handle = 1u; EXPECT_TRUE(wddm->verifySharedHandle(handle)); } TEST_F(WddmTests, givenWddmWhenPassesIncorrectHandleToVerifySharedHandleThenReturnFalse) { init(); D3DKMT_HANDLE handle = 0u; EXPECT_FALSE(wddm->verifySharedHandle(handle)); } TEST_F(WddmTests, givenWddmWhenPassesCorrectHandleToVerifyNTHandleThenReturnTrue) { init(); uint32_t temp = 0; HANDLE handle = &temp; EXPECT_TRUE(wddm->verifyNTHandle(handle)); } TEST_F(WddmTests, givenWddmWhenPassesIncorrectHandleToVerifyNTHandleThenReturnFalse) { init(); HANDLE handle = nullptr; EXPECT_FALSE(wddm->verifyNTHandle(handle)); } } // namespace NEO
[bits 16] ;STEP DA SEGUIRE: ; bloccare gli interrutori della BIOS ( inutili per la PM ) ; caricare la GDT ; settare il registro della CPU CR0 ; flushing del pipelining della CPU tramite un trucchetto ; inizializzare PM SWITCH_TO_PM: cli ; IMPORTANTE: dobbiamo svuotare la IVT perchè ; la IVT inziale settata dalla bios runna su 16BIT ; che non è compatibile con la PM quindi porterebbe al crash lgdt [ GDT_DESCRIPTOR ] ; cr0 non può essere settato direttamente MOV EAX, CR0 OR EAX, 0x1 MOV CR0, EAX ; flushing pipelining JMP CODE_SEG: START_PM [bits 32] ;STEPS: inizializzare i registri e preparare la stack START_PM: MOV AX, DATA_SEG MOV DS, AX MOV SS, AX MOV ES, AX MOV FS, AX MOV GS, AX ; Aggiorniamo la posizione della stack MOV EBP, 0x90000 MOV ESP, EBP CALL BEGIN_PM